Open History to see the last commit
1import { assert, it, vi } from "@effect/vitest";
2import {
3 CommandId,
4 DEFAULT_SERVER_SETTINGS,
5 MessageId,
6 ProjectId,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 type ServerProvider,
10 ThreadId,
11} from "@t3tools/contracts";
12import * as Deferred from "effect/Deferred";
13import * as Duration from "effect/Duration";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Ref from "effect/Ref";
19import * as SqlClient from "effect/unstable/sql/SqlClient";
20
21import * as GitWorkflow from "../git/GitWorkflowService.ts";
22import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
23import * as ProjectService from "../project/ProjectService.ts";
24import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
25import { makeProviderRegistryLayer } from "../provider/testUtils/providerRegistryMock.ts";
26import * as ServerSettings from "../serverSettings.ts";
27import * as TextGeneration from "../textGeneration/TextGeneration.ts";
28import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
29import * as CommandReceiptStore from "./CommandReceiptStore.ts";
30import * as EffectOutbox from "./EffectOutbox.ts";
31import * as IdAllocator from "./IdAllocator.ts";
32import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
33import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
34import * as ThreadLaunch from "./ThreadLaunchService.ts";
35import * as ThreadManagement from "./ThreadManagementService.ts";
36import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts";
37
38const projectId = ProjectId.make("project:launch-test");
39const modelSelection = {
40 instanceId: ProviderInstanceId.make("codex"),
41 model: "gpt-5.1-codex",
42} as const;
43const project = {
44 id: projectId,
45 title: "Project",
46 workspaceRoot: "/repo",
47 repositoryIdentity: null,
48 faviconPath: null,
49 defaultModelSelection: modelSelection,
50 scripts: [],
51 createdAt: "2026-06-20T00:00:00.000Z",
52 updatedAt: "2026-06-20T00:00:00.000Z",
53 deletedAt: null,
54} as const;
55
56const adapter = {
57 instanceId: modelSelection.instanceId,
58 driver: ProviderDriverKind.make("codex"),
59 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
60 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
61 openSession: () => Effect.die("provider execution is disabled in launch tests"),
62} as ProviderAdapterV2Shape;
63
64interface HarnessOptions {
65 readonly createWorktree?: GitWorkflow.GitWorkflowService["Service"]["createWorktree"];
66 readonly runSetup?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"];
67 readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"];
68 readonly generateBranchName?: TextGeneration.TextGeneration["Service"]["generateBranchName"];
69 readonly serverSettings?: Parameters<typeof ServerSettings.layerTest>[0];
70 readonly providers?: ReadonlyArray<ServerProvider>;
71}
72
73function makeHarness(options: HarnessOptions = {}) {
74 const database = SqlitePersistenceMemory;
75 const registry = ProviderAdapterRegistry.makeLayer([adapter]);
76 const orchestrator = makeOrchestratorV2ReplayLayerWithRegistry(
77 { name: "thread-launch" },
78 registry,
79 { databaseLayer: database, runEffectWorker: false },
80 );
81 const threadManagement = ThreadManagement.layer.pipe(Layer.provide(orchestrator));
82 const receipts = CommandReceiptStore.layer.pipe(Layer.provide(database));
83 const outbox = EffectOutbox.layer.pipe(Layer.provide(database));
84 const createWorktree = vi.fn(
85 options.createWorktree ??
86 (() =>
87 Effect.succeed({
88 worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" },
89 } as never)),
90 );
91 const runSetup = vi.fn(
92 options.runSetup ?? (() => Effect.succeed({ status: "no-script" as const })),
93 );
94 const generateBranchName = vi.fn(
95 options.generateBranchName ?? (() => Effect.succeed({ branch: "generated-branch" })),
96 );
97 const externalServices = Layer.mergeAll(
98 Layer.succeed(ProjectService.ProjectService, {
99 create: () => Effect.die("unused"),
100 bootstrap: () => Effect.die("unused"),
101 update: () => Effect.die("unused"),
102 delete: () => Effect.die("unused"),
103 getById: (id) => Effect.succeed(id === projectId ? Option.some(project) : Option.none()),
104 getByWorkspaceRoot: () => Effect.succeed(Option.some(project)),
105 snapshot: Effect.die("unused"),
106 }),
107 Layer.mock(GitWorkflow.GitWorkflowService)({
108 createWorktree,
109 fetchRemote: () => Effect.void,
110 removeWorktree: () => Effect.void,
111 resolveRemoteTrackingCommit: () =>
112 Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" }),
113 }),
114 Layer.succeed(ProjectSetupScriptRunner.ProjectSetupScriptRunner, {
115 runForThread: runSetup,
116 }),
117 Layer.mock(TextGeneration.TextGeneration)({
118 generateThreadTitle:
119 options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })),
120 generateBranchName,
121 }),
122 ServerSettings.layerTest(options.serverSettings),
123 makeProviderRegistryLayer(options.providers),
124 );
125 const launch = ThreadLaunch.layer.pipe(
126 Layer.provide(Layer.mergeAll(externalServices, threadManagement, receipts, IdAllocator.layer)),
127 );
128 return {
129 layer: Layer.mergeAll(launch, threadManagement, outbox, database),
130 createWorktree,
131 generateBranchName,
132 runSetup,
133 };
134}
135
136function launchInput(input: {
137 readonly command: string;
138 readonly thread: string;
139 readonly message?: string;
140 readonly workspace?: ThreadLaunch.ThreadLaunchWorkspaceStrategy;
141}) {
142 return {
143 commandId: CommandId.make(input.command),
144 threadId: ThreadId.make(input.thread),
145 projectId,
146 title: "New thread",
147 modelSelection,
148 runtimeMode: "full-access" as const,
149 interactionMode: "default" as const,
150 workspaceStrategy: input.workspace ?? { type: "root" as const },
151 ...(input.message === undefined
152 ? {}
153 : {
154 initialMessage: {
155 messageId: MessageId.make(`${input.message}:id`),
156 text: input.message,
157 attachments: [],
158 },
159 }),
160 createdBy: "user" as const,
161 creationSource: "web" as const,
162 };
163}
164
165function waitUntil<E, R>(predicate: () => Effect.Effect<boolean, E, R>): Effect.Effect<void, E, R> {
166 return Effect.gen(function* () {
167 for (let attempt = 0; attempt < 200; attempt += 1) {
168 if (yield* predicate()) return;
169 yield* Effect.promise(
170 () =>
171 new Promise<void>((resolve) => {
172 setImmediate(resolve);
173 }),
174 );
175 }
176 assert.fail("Condition was not reached before timeout.");
177 });
178}
179
180it.effect("returns a visible preparing message while provisioning is still blocked", () =>
181 Effect.gen(function* () {
182 const worktreeEntered = yield* Deferred.make<void>();
183 const allowWorktree = yield* Deferred.make<void>();
184 const setupEntered = yield* Deferred.make<void>();
185 const allowSetup = yield* Deferred.make<void>();
186 const harness = makeHarness({
187 createWorktree: () =>
188 Deferred.succeed(worktreeEntered, undefined).pipe(
189 Effect.andThen(Deferred.await(allowWorktree)),
190 Effect.as({
191 worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" },
192 } as never),
193 ),
194 runSetup: () =>
195 Deferred.succeed(setupEntered, undefined).pipe(
196 Effect.andThen(Deferred.await(allowSetup)),
197 Effect.as({ status: "no-script" as const }),
198 ),
199 });
200 yield* Effect.gen(function* () {
201 const launches = yield* ThreadLaunch.ThreadLaunchService;
202 const outbox = yield* EffectOutbox.EffectOutboxV2;
203 const threads = yield* ThreadManagement.ThreadManagementService;
204 const input = launchInput({
205 command: "command:launch:blocked",
206 thread: "thread:launch:blocked",
207 message: "Build the feature",
208 workspace: { type: "worktree", baseRef: "main" },
209 });
210 const launched = yield* launches.launch(input);
211 assert.equal(launched.projection.messages[0]?.text, "Build the feature");
212 assert.equal(launched.projection.runs[0]?.status, "preparing");
213 assert.equal(
214 launched.projection.turnItems.find((item) => item.type === "command_execution")?.status,
215 "running",
216 );
217 yield* Deferred.await(worktreeEntered);
218 let current = yield* threads.getThreadProjection(launched.threadId);
219 assert.equal(
220 current.turnItems.find((item) => item.type === "command_execution")?.title,
221 "Preparing worktree",
222 );
223 yield* Deferred.succeed(allowWorktree, undefined);
224 const entered = yield* Deferred.await(setupEntered).pipe(
225 Effect.timeoutOption(Duration.seconds(2)),
226 );
227 if (Option.isNone(entered)) {
228 current = yield* threads.getThreadProjection(launched.threadId);
229 assert.fail(
230 `Setup was not reached; run=${current.runs[0]?.status ?? "missing"}, worklog=${current.turnItems.find((item) => item.type === "command_execution")?.title ?? "missing"}.`,
231 );
232 }
233 current = yield* threads.getThreadProjection(launched.threadId);
234 assert.equal(
235 current.turnItems.find((item) => item.type === "command_execution")?.title,
236 "Starting setup script",
237 );
238 const prematureEffects = yield* outbox.listByCommandId(
239 CommandId.make("command:launch:blocked:initial-message"),
240 );
241 assert.isEmpty(prematureEffects);
242 yield* Deferred.succeed(allowSetup, undefined);
243 }).pipe(Effect.provide(harness.layer));
244 }),
245);
246
247it.effect("provisions independent launches concurrently instead of behind a global semaphore", () =>
248 Effect.gen(function* () {
249 const setupCount = yield* Ref.make(0);
250 const bothEntered = yield* Deferred.make<void>();
251 const allowSetup = yield* Deferred.make<void>();
252 const harness = makeHarness({
253 runSetup: () =>
254 Ref.updateAndGet(setupCount, (count) => count + 1).pipe(
255 Effect.tap((count) =>
256 count === 2 ? Deferred.succeed(bothEntered, undefined) : Effect.void,
257 ),
258 Effect.andThen(Deferred.await(allowSetup)),
259 Effect.as({ status: "no-script" as const }),
260 ),
261 });
262 yield* Effect.gen(function* () {
263 const launches = yield* ThreadLaunch.ThreadLaunchService;
264 const results = yield* Effect.all(
265 [
266 launches.launch(
267 launchInput({
268 command: "command:launch:concurrent-a",
269 thread: "thread:launch:concurrent-a",
270 message: "First",
271 }),
272 ),
273 launches.launch(
274 launchInput({
275 command: "command:launch:concurrent-b",
276 thread: "thread:launch:concurrent-b",
277 message: "Second",
278 }),
279 ),
280 ],
281 { concurrency: "unbounded" },
282 );
283 assert.deepEqual(
284 results.map((result) => result.projection.runs[0]?.status),
285 ["preparing", "preparing"],
286 );
287 yield* Deferred.await(bothEntered);
288 assert.equal(yield* Ref.get(setupCount), 2);
289 yield* Deferred.succeed(allowSetup, undefined);
290 }).pipe(Effect.provide(harness.layer));
291 }),
292);
293
294it.effect("enqueues provider work only after setup has been initiated", () =>
295 Effect.gen(function* () {
296 const setupEntered = yield* Deferred.make<void>();
297 const allowSetup = yield* Deferred.make<void>();
298 const harness = makeHarness({
299 runSetup: () =>
300 Deferred.succeed(setupEntered, undefined).pipe(
301 Effect.andThen(Deferred.await(allowSetup)),
302 Effect.as({
303 status: "started" as const,
304 scriptId: "setup",
305 scriptName: "Setup",
306 terminalId: "setup",
307 cwd: "/repo",
308 }),
309 ),
310 });
311 yield* Effect.gen(function* () {
312 const launches = yield* ThreadLaunch.ThreadLaunchService;
313 const outbox = yield* EffectOutbox.EffectOutboxV2;
314 const threads = yield* ThreadManagement.ThreadManagementService;
315 const input = launchInput({
316 command: "command:launch:release",
317 thread: "thread:launch:release",
318 message: "Start after setup",
319 workspace: { type: "worktree", baseRef: "main" },
320 });
321 const launched = yield* launches.launch(input);
322 yield* Deferred.await(setupEntered);
323 assert.isEmpty(
324 yield* outbox.listByCommandId(CommandId.make("command:launch:release:release")),
325 );
326 yield* Deferred.succeed(allowSetup, undefined);
327 yield* waitUntil(() =>
328 outbox
329 .listByCommandId(CommandId.make("command:launch:release:release"))
330 .pipe(Effect.map((effects) => effects.length === 1)),
331 );
332 const projection = yield* threads.getThreadProjection(launched.threadId);
333 assert.equal(projection.runs[0]?.status, "starting");
334 assert.equal(projection.checkpointScopes[0]?.cwd, "/repo-worktrees/feature");
335 assert.equal(
336 projection.turnItems.find((item) => item.type === "command_execution")?.status,
337 "completed",
338 );
339 }).pipe(Effect.provide(harness.layer));
340 }),
341);
342
343it.effect(
344 "queues follow-up messages behind preparation and checkpoints them in the final workspace",
345 () =>
346 Effect.gen(function* () {
347 const setupEntered = yield* Deferred.make<void>();
348 const failSetup = yield* Deferred.make<void>();
349 const harness = makeHarness({
350 runSetup: () =>
351 Deferred.succeed(setupEntered, undefined).pipe(
352 Effect.andThen(Deferred.await(failSetup)),
353 Effect.andThen(Effect.fail(new Error("setup failed") as never)),
354 ),
355 });
356 yield* Effect.gen(function* () {
357 const launches = yield* ThreadLaunch.ThreadLaunchService;
358 const threads = yield* ThreadManagement.ThreadManagementService;
359 const launched = yield* launches.launch(
360 launchInput({
361 command: "command:launch:queued-during-preparation",
362 thread: "thread:launch:queued-during-preparation",
363 message: "Prepare the workspace",
364 workspace: { type: "worktree", baseRef: "main" },
365 }),
366 );
367 yield* Deferred.await(setupEntered);
368
369 const followUp = yield* threads.sendToThread({
370 projectId,
371 commandId: CommandId.make("command:launch:queued-follow-up"),
372 threadId: launched.threadId,
373 messageId: MessageId.make("message:launch:queued-follow-up"),
374 text: "Run after preparation",
375 attachments: [],
376 mode: "auto",
377 createdBy: "user",
378 creationSource: "web",
379 });
380 assert.equal(followUp.delivery, "queued");
381 assert.equal(followUp.run.status, "queued");
382 assert.equal(
383 followUp.projection.nodes.find(
384 (node) => node.runId === followUp.run.id && node.kind === "root_turn",
385 )?.checkpointScopeId,
386 null,
387 );
388
389 yield* Deferred.succeed(failSetup, undefined);
390 yield* waitUntil(() =>
391 threads
392 .getThreadProjection(launched.threadId)
393 .pipe(
394 Effect.map(
395 (projection) =>
396 projection.runs.find((run) => run.id === followUp.run.id)?.status === "starting",
397 ),
398 ),
399 );
400
401 const projection = yield* threads.getThreadProjection(launched.threadId);
402 const rootNode = projection.nodes.find(
403 (node) => node.runId === followUp.run.id && node.kind === "root_turn",
404 );
405 assert.isNotNull(rootNode?.checkpointScopeId);
406 assert.equal(
407 projection.checkpointScopes.find((scope) => scope.id === rootNode?.checkpointScopeId)
408 ?.cwd,
409 "/repo-worktrees/feature",
410 );
411 }).pipe(Effect.provide(harness.layer));
412 }),
413);
414
415it.effect("does not put optional title generation on the provisioning critical path", () =>
416 Effect.gen(function* () {
417 const titleStarted = yield* Deferred.make<void>();
418 const allowTitle = yield* Deferred.make<void>();
419 const setupEntered = yield* Deferred.make<void>();
420 const harness = makeHarness({
421 generateTitle: () =>
422 Deferred.succeed(titleStarted, undefined).pipe(
423 Effect.andThen(Deferred.await(allowTitle)),
424 Effect.as({ title: "Generated later" }),
425 ),
426 runSetup: () =>
427 Deferred.succeed(setupEntered, undefined).pipe(Effect.as({ status: "no-script" as const })),
428 });
429 yield* Effect.gen(function* () {
430 const launches = yield* ThreadLaunch.ThreadLaunchService;
431 const threads = yield* ThreadManagement.ThreadManagementService;
432 const input = launchInput({
433 command: "command:launch:title-independent",
434 thread: "thread:launch:title-independent",
435 message: "Generate my title slowly",
436 });
437 const launched = yield* launches.launch(input);
438 yield* Deferred.await(titleStarted);
439 yield* Deferred.await(setupEntered);
440 yield* waitUntil(() =>
441 threads
442 .getThreadProjection(launched.threadId)
443 .pipe(Effect.map((projection) => projection.runs[0]?.status === "starting")),
444 );
445 assert.equal(
446 (yield* threads.getThreadProjection(launched.threadId)).thread.title,
447 "New thread",
448 );
449 yield* Deferred.succeed(allowTitle, undefined);
450 yield* waitUntil(() =>
451 threads
452 .getThreadProjection(launched.threadId)
453 .pipe(Effect.map((projection) => projection.thread.title === "Generated later")),
454 );
455 }).pipe(Effect.provide(harness.layer));
456 }),
457);
458
459it.effect("uses the available source control writer for generated worktree branches", () =>
460 Effect.gen(function* () {
461 const writerInstanceId = ProviderInstanceId.make("source-control-writer");
462 const writerModelSelection = {
463 instanceId: writerInstanceId,
464 model: "branch-writer-model",
465 } as const;
466 const harness = makeHarness({
467 serverSettings: {
468 providerInstances: {
469 [writerInstanceId]: {
470 driver: ProviderDriverKind.make("codex"),
471 config: {},
472 },
473 },
474 sourceControlWriterModelSelection: writerModelSelection,
475 },
476 providers: [
477 {
478 instanceId: writerInstanceId,
479 driver: ProviderDriverKind.make("codex"),
480 enabled: true,
481 installed: true,
482 version: null,
483 status: "ready",
484 auth: { status: "authenticated" },
485 checkedAt: "2026-07-28T00:00:00.000Z",
486 availability: "available",
487 models: [],
488 slashCommands: [],
489 skills: [],
490 },
491 ],
492 });
493
494 yield* Effect.gen(function* () {
495 const launches = yield* ThreadLaunch.ThreadLaunchService;
496 yield* launches.launch(
497 launchInput({
498 command: "command:launch:source-control-writer",
499 thread: "thread:launch:source-control-writer",
500 message: "Generate a branch with the configured writer",
501 workspace: { type: "worktree", baseRef: "main" },
502 }),
503 );
504 yield* waitUntil(() => Effect.sync(() => harness.generateBranchName.mock.calls.length === 1));
505 assert.deepEqual(
506 harness.generateBranchName.mock.calls[0]?.[0].modelSelection,
507 writerModelSelection,
508 );
509 }).pipe(Effect.provide(harness.layer));
510 }),
511);
512
513it.effect("falls back when the source control writer is unavailable", () =>
514 Effect.gen(function* () {
515 const writerInstanceId = ProviderInstanceId.make("missing-source-control-writer");
516 const harness = makeHarness({
517 serverSettings: {
518 providerInstances: {
519 [writerInstanceId]: {
520 driver: ProviderDriverKind.make("missing-driver"),
521 config: {},
522 },
523 },
524 sourceControlWriterModelSelection: {
525 instanceId: writerInstanceId,
526 model: "missing-branch-writer-model",
527 },
528 },
529 providers: [],
530 });
531
532 yield* Effect.gen(function* () {
533 const launches = yield* ThreadLaunch.ThreadLaunchService;
534 yield* launches.launch(
535 launchInput({
536 command: "command:launch:source-control-writer-fallback",
537 thread: "thread:launch:source-control-writer-fallback",
538 message: "Generate a branch with the available writer",
539 workspace: { type: "worktree", baseRef: "main" },
540 }),
541 );
542 yield* waitUntil(() => Effect.sync(() => harness.generateBranchName.mock.calls.length === 1));
543 assert.deepEqual(
544 harness.generateBranchName.mock.calls[0]?.[0].modelSelection,
545 DEFAULT_SERVER_SETTINGS.textGenerationModelSelection,
546 );
547 }).pipe(Effect.provide(harness.layer));
548 }),
549);
550
551for (const failurePoint of ["worktree", "setup"] as const) {
552 it.effect(
553 `${failurePoint} failure keeps the thread and message visible and emits failure items`,
554 () =>
555 Effect.gen(function* () {
556 const failure = new Error(`${failurePoint} failed`);
557 const harness = makeHarness(
558 failurePoint === "worktree"
559 ? { createWorktree: () => Effect.fail(failure as never) }
560 : { runSetup: () => Effect.fail(failure as never) },
561 );
562 yield* Effect.gen(function* () {
563 const launches = yield* ThreadLaunch.ThreadLaunchService;
564 const threads = yield* ThreadManagement.ThreadManagementService;
565 const input = launchInput({
566 command: `command:launch:${failurePoint}-failure`,
567 thread: `thread:launch:${failurePoint}-failure`,
568 message: `Fail during ${failurePoint}`,
569 workspace: { type: "worktree", baseRef: "main" },
570 });
571 const launched = yield* launches.launch(input);
572 yield* waitUntil(() =>
573 threads
574 .getThreadProjection(launched.threadId)
575 .pipe(Effect.map((projection) => projection.runs[0]?.status === "failed")),
576 );
577 const projection = yield* threads.getThreadProjection(launched.threadId);
578 assert.equal(projection.messages[0]?.text, `Fail during ${failurePoint}`);
579 assert.equal(projection.runs[0]?.status, "failed");
580 assert.equal(
581 projection.turnItems.find((item) => item.type === "command_execution")?.status,
582 "failed",
583 );
584 assert.match(
585 projection.turnItems.find((item) => item.type === "error")?.failure.message ?? "",
586 new RegExp(`${failurePoint} failed`, "u"),
587 );
588 }).pipe(Effect.provide(harness.layer));
589 }),
590 );
591}
592
593it.effect("deduplicates retried launch side effects in-process", () =>
594 Effect.gen(function* () {
595 const setupEntered = yield* Deferred.make<void>();
596 const allowSetup = yield* Deferred.make<void>();
597 const harness = makeHarness({
598 runSetup: () =>
599 Deferred.succeed(setupEntered, undefined).pipe(
600 Effect.andThen(Deferred.await(allowSetup)),
601 Effect.as({ status: "no-script" as const }),
602 ),
603 });
604 yield* Effect.gen(function* () {
605 const launches = yield* ThreadLaunch.ThreadLaunchService;
606 const input = launchInput({
607 command: "command:launch:retry",
608 thread: "thread:launch:retry",
609 message: "Only once",
610 });
611 const [first, retry] = yield* Effect.all([launches.launch(input), launches.launch(input)], {
612 concurrency: "unbounded",
613 });
614 yield* Deferred.await(setupEntered);
615 assert.equal(first.threadId, retry.threadId);
616 assert.isFalse(first.resumed);
617 assert.isTrue(retry.resumed);
618 assert.equal(harness.runSetup.mock.calls.length, 1);
619 yield* Deferred.succeed(allowSetup, undefined);
620 }).pipe(Effect.provide(harness.layer));
621 }),
622);
623
624it.effect("does not let a failing same-command caller strand a concurrent durable launch", () =>
625 Effect.gen(function* () {
626 const setupEntered = yield* Deferred.make<void>();
627 const allowSetup = yield* Deferred.make<void>();
628 const harness = makeHarness({
629 runSetup: () =>
630 Deferred.succeed(setupEntered, undefined).pipe(
631 Effect.andThen(Deferred.await(allowSetup)),
632 Effect.as({ status: "no-script" as const }),
633 ),
634 });
635 yield* Effect.gen(function* () {
636 const launches = yield* ThreadLaunch.ThreadLaunchService;
637 const command = "command:launch:failed-owner-race";
638 const [failed, launched] = yield* Effect.all(
639 [
640 launches
641 .launch({
642 ...launchInput({
643 command,
644 thread: "thread:launch:failed-owner-race",
645 message: "This invalid reuse fails",
646 }),
647 reuseExistingThread: true,
648 })
649 .pipe(Effect.exit),
650 launches.launch(
651 launchInput({
652 command,
653 thread: "thread:launch:successful-peer",
654 message: "This peer persists",
655 }),
656 ),
657 ],
658 { concurrency: "unbounded" },
659 );
660 assert.isTrue(Exit.isFailure(failed));
661 assert.equal(launched.projection.runs[0]?.status, "preparing");
662 const entered = yield* Deferred.await(setupEntered).pipe(
663 Effect.timeoutOption(Duration.seconds(2)),
664 );
665 assert.isTrue(Option.isSome(entered));
666 assert.equal(harness.runSetup.mock.calls.length, 1);
667 yield* Deferred.succeed(allowSetup, undefined);
668 }).pipe(Effect.provide(harness.layer));
669 }),
670);
671
672it.effect("schedules an accepted preparing message exactly once across concurrent retries", () =>
673 Effect.gen(function* () {
674 const setupEntered = yield* Deferred.make<void>();
675 const allowSetup = yield* Deferred.make<void>();
676 const harness = makeHarness({
677 runSetup: () =>
678 Deferred.succeed(setupEntered, undefined).pipe(
679 Effect.andThen(Deferred.await(allowSetup)),
680 Effect.as({ status: "no-script" as const }),
681 ),
682 });
683 yield* Effect.gen(function* () {
684 const launches = yield* ThreadLaunch.ThreadLaunchService;
685 const threads = yield* ThreadManagement.ThreadManagementService;
686 const input = launchInput({
687 command: "command:launch:accepted-before-fork",
688 thread: "thread:launch:accepted-before-fork",
689 message: "Resume preparation",
690 });
691 const messageId = MessageId.make("message:launch:accepted-before-fork");
692
693 yield* threads.dispatch({
694 type: "thread.create",
695 commandId: input.commandId,
696 threadId: input.threadId,
697 projectId: input.projectId,
698 title: input.title,
699 modelSelection: input.modelSelection,
700 runtimeMode: input.runtimeMode,
701 interactionMode: input.interactionMode,
702 branch: null,
703 worktreePath: null,
704 createdBy: input.createdBy,
705 creationSource: input.creationSource,
706 });
707 yield* threads.dispatch({
708 type: "message.dispatch",
709 commandId: CommandId.make(`${input.commandId}:initial-message`),
710 threadId: input.threadId,
711 messageId,
712 text: "Resume preparation",
713 attachments: [],
714 modelSelection: input.modelSelection,
715 dispatchMode: { type: "defer_start" },
716 createdBy: input.createdBy,
717 creationSource: input.creationSource,
718 });
719 const preparing = yield* threads.getThreadProjection(input.threadId);
720 assert.equal(preparing.runs[0]?.status, "preparing");
721
722 const [first, second] = yield* Effect.all([launches.launch(input), launches.launch(input)], {
723 concurrency: "unbounded",
724 });
725 yield* Deferred.await(setupEntered);
726 assert.isTrue(first.resumed);
727 assert.isTrue(second.resumed);
728 assert.equal(harness.runSetup.mock.calls.length, 1);
729 yield* Deferred.succeed(allowSetup, undefined);
730 }).pipe(Effect.provide(harness.layer));
731 }),
732);
733
734it.effect("does not depend on the legacy launch workflow table", () => {
735 const harness = makeHarness();
736 return Effect.gen(function* () {
737 const sql = yield* SqlClient.SqlClient;
738 const launches = yield* ThreadLaunch.ThreadLaunchService;
739 yield* sql`DROP TABLE orchestration_v2_thread_launch_workflows`;
740 const launched = yield* launches.launch(
741 launchInput({
742 command: "command:launch:no-workflow-table",
743 thread: "thread:launch:no-workflow-table",
744 message: "No private workflow state",
745 }),
746 );
747 assert.equal(launched.projection.messages[0]?.text, "No private workflow state");
748 }).pipe(Effect.provide(harness.layer));
749});