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 DateTime from "effect/DateTime";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Ref from "effect/Ref";
20import * as SqlClient from "effect/unstable/sql/SqlClient";
21import * as TestClock from "effect/testing/TestClock";
22
23import * as GitWorkflow from "../git/GitWorkflowService.ts";
24import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
25import { ProjectionProjectRepository } from "../persistence/Services/ProjectionProjects.ts";
26import * as ProjectService from "../project/ProjectService.ts";
27import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
28import { makeProviderRegistryLayer } from "../provider/testUtils/providerRegistryMock.ts";
29import * as ServerSettings from "../serverSettings.ts";
30import * as TextGeneration from "../textGeneration/TextGeneration.ts";
31import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
32import * as CommandReceiptStore from "./CommandReceiptStore.ts";
33import * as EffectOutbox from "./EffectOutbox.ts";
34import * as IdAllocator from "./IdAllocator.ts";
35import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
36import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
37import * as ThreadLaunch from "./ThreadLaunchService.ts";
38import * as ThreadManagement from "./ThreadManagementService.ts";
39import * as ThreadTitleRegeneration from "./ThreadTitleRegenerationService.ts";
40import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts";
41
42const projectId = ProjectId.make("project:launch-test");
43const modelSelection = {
44 instanceId: ProviderInstanceId.make("codex"),
45 model: "gpt-5.1-codex",
46} as const;
47const project = {
48 id: projectId,
49 title: "Project",
50 workspaceRoot: "/repo",
51 repositoryIdentity: null,
52 faviconPath: null,
53 defaultModelSelection: modelSelection,
54 scripts: [],
55 createdAt: "2026-06-20T00:00:00.000Z",
56 updatedAt: "2026-06-20T00:00:00.000Z",
57 deletedAt: null,
58} as const;
59
60const adapter = {
61 instanceId: modelSelection.instanceId,
62 driver: ProviderDriverKind.make("codex"),
63 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
64 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
65 openSession: () => Effect.die("provider execution is disabled in launch tests"),
66} as ProviderAdapterV2Shape;
67
68interface HarnessOptions {
69 readonly createWorktree?: GitWorkflow.GitWorkflowService["Service"]["createWorktree"];
70 readonly renameBranch?: GitWorkflow.GitWorkflowService["Service"]["renameBranch"];
71 readonly runSetup?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"];
72 readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"];
73 readonly generateBranchName?: TextGeneration.TextGeneration["Service"]["generateBranchName"];
74 readonly serverSettings?: Parameters<typeof ServerSettings.layerTest>[0];
75 readonly providers?: ReadonlyArray<ServerProvider>;
76}
77
78function makeHarness(options: HarnessOptions = {}) {
79 const database = SqlitePersistenceMemory;
80 const registry = ProviderAdapterRegistry.makeLayer([adapter]);
81 const orchestrator = makeOrchestratorV2ReplayLayerWithRegistry(
82 { name: "thread-launch" },
83 registry,
84 { databaseLayer: database, runEffectWorker: false },
85 );
86 const threadManagement = ThreadManagement.layer.pipe(Layer.provide(orchestrator));
87 const receipts = CommandReceiptStore.layer.pipe(Layer.provide(database));
88 const outbox = EffectOutbox.layer.pipe(Layer.provide(database));
89 const createWorktree = vi.fn(
90 options.createWorktree ??
91 ((input) =>
92 Effect.succeed({
93 worktree: { path: "/repo-worktrees/feature", refName: input.newRefName, headSha: "abc" },
94 } as never)),
95 );
96 const renameBranch = vi.fn(
97 options.renameBranch ?? ((input) => Effect.succeed({ branch: input.newBranch })),
98 );
99 const runSetup = vi.fn(
100 options.runSetup ?? (() => Effect.succeed({ status: "no-script" as const })),
101 );
102 const generateBranchName = vi.fn(
103 options.generateBranchName ?? (() => Effect.succeed({ branch: "generated-branch" })),
104 );
105 const generateThreadTitle = vi.fn(
106 options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })),
107 );
108 const externalServices = Layer.mergeAll(
109 Layer.succeed(ProjectService.ProjectService, {
110 create: () => Effect.die("unused"),
111 bootstrap: () => Effect.die("unused"),
112 update: () => Effect.die("unused"),
113 delete: () => Effect.die("unused"),
114 getById: (id) => Effect.succeed(id === projectId ? Option.some(project) : Option.none()),
115 getByWorkspaceRoot: () => Effect.succeed(Option.some(project)),
116 snapshot: Effect.die("unused"),
117 }),
118 Layer.mock(GitWorkflow.GitWorkflowService)({
119 createWorktree,
120 renameBranch,
121 fetchRemote: () => Effect.void,
122 removeWorktree: () => Effect.void,
123 resolveRemoteTrackingCommit: () =>
124 Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" }),
125 }),
126 Layer.succeed(ProjectSetupScriptRunner.ProjectSetupScriptRunner, {
127 runForThread: runSetup,
128 }),
129 Layer.mock(TextGeneration.TextGeneration)({
130 generateThreadTitle,
131 generateBranchName,
132 }),
133 ServerSettings.layerTest(options.serverSettings),
134 makeProviderRegistryLayer(options.providers),
135 );
136 const launch = ThreadLaunch.layer.pipe(
137 Layer.provide(Layer.mergeAll(externalServices, threadManagement, receipts, IdAllocator.layer)),
138 );
139 const projectedProjects = Layer.mock(ProjectionProjectRepository)({
140 getById: ({ projectId: requestedProjectId }) =>
141 Effect.succeed(
142 requestedProjectId === projectId
143 ? Option.some({
144 projectId,
145 title: project.title,
146 workspaceRoot: project.workspaceRoot,
147 defaultModelSelection: project.defaultModelSelection,
148 scripts: project.scripts,
149 createdAt: project.createdAt,
150 updatedAt: project.updatedAt,
151 deletedAt: project.deletedAt,
152 })
153 : Option.none(),
154 ),
155 });
156 const titleRegeneration = ThreadTitleRegeneration.layer.pipe(
157 Layer.provide(Layer.mergeAll(threadManagement, projectedProjects, externalServices)),
158 );
159 return {
160 layer: Layer.mergeAll(launch, threadManagement, titleRegeneration, outbox, database),
161 createWorktree,
162 renameBranch,
163 generateBranchName,
164 generateThreadTitle,
165 runSetup,
166 };
167}
168
169function launchInput(input: {
170 readonly command: string;
171 readonly thread: string;
172 readonly message?: string;
173 readonly workspace?: ThreadLaunch.ThreadLaunchWorkspaceStrategy;
174}) {
175 return {
176 commandId: CommandId.make(input.command),
177 threadId: ThreadId.make(input.thread),
178 projectId,
179 title: "New thread",
180 modelSelection,
181 runtimeMode: "full-access" as const,
182 interactionMode: "default" as const,
183 workspaceStrategy: input.workspace ?? { type: "root" as const },
184 ...(input.message === undefined
185 ? {}
186 : {
187 initialMessage: {
188 messageId: MessageId.make(`${input.message}:id`),
189 text: input.message,
190 attachments: [],
191 },
192 }),
193 createdBy: "user" as const,
194 creationSource: "web" as const,
195 };
196}
197
198function waitUntil<E, R>(predicate: () => Effect.Effect<boolean, E, R>): Effect.Effect<void, E, R> {
199 return Effect.gen(function* () {
200 for (let attempt = 0; attempt < 200; attempt += 1) {
201 if (yield* predicate()) return;
202 yield* Effect.promise(
203 () =>
204 new Promise<void>((resolve) => {
205 setImmediate(resolve);
206 }),
207 );
208 }
209 assert.fail("Condition was not reached before timeout.");
210 });
211}
212
213it.effect("returns a visible preparing message while provisioning is still blocked", () =>
214 Effect.gen(function* () {
215 const worktreeEntered = yield* Deferred.make<void>();
216 const allowWorktree = yield* Deferred.make<void>();
217 const setupEntered = yield* Deferred.make<void>();
218 const allowSetup = yield* Deferred.make<void>();
219 const harness = makeHarness({
220 createWorktree: () =>
221 Deferred.succeed(worktreeEntered, undefined).pipe(
222 Effect.andThen(Deferred.await(allowWorktree)),
223 Effect.as({
224 worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" },
225 } as never),
226 ),
227 runSetup: () =>
228 Deferred.succeed(setupEntered, undefined).pipe(
229 Effect.andThen(Deferred.await(allowSetup)),
230 Effect.as({ status: "no-script" as const }),
231 ),
232 });
233 yield* Effect.gen(function* () {
234 const launches = yield* ThreadLaunch.ThreadLaunchService;
235 const outbox = yield* EffectOutbox.EffectOutboxV2;
236 const threads = yield* ThreadManagement.ThreadManagementService;
237 const input = launchInput({
238 command: "command:launch:blocked",
239 thread: "thread:launch:blocked",
240 message: "Build the feature",
241 workspace: { type: "worktree", baseRef: "main" },
242 });
243 const launched = yield* launches.launch(input);
244 assert.equal(launched.projection.messages[0]?.text, "Build the feature");
245 assert.equal(launched.projection.runs[0]?.status, "preparing");
246 assert.equal(
247 launched.projection.turnItems.find((item) => item.type === "command_execution")?.status,
248 "running",
249 );
250 yield* Deferred.await(worktreeEntered);
251 let current = yield* threads.getThreadProjection(launched.threadId);
252 assert.equal(
253 current.turnItems.find((item) => item.type === "command_execution")?.title,
254 "Preparing worktree",
255 );
256 yield* Deferred.succeed(allowWorktree, undefined);
257 const entered = yield* Deferred.await(setupEntered).pipe(
258 Effect.timeoutOption(Duration.seconds(2)),
259 );
260 if (Option.isNone(entered)) {
261 current = yield* threads.getThreadProjection(launched.threadId);
262 assert.fail(
263 `Setup was not reached; run=${current.runs[0]?.status ?? "missing"}, worklog=${current.turnItems.find((item) => item.type === "command_execution")?.title ?? "missing"}.`,
264 );
265 }
266 current = yield* threads.getThreadProjection(launched.threadId);
267 assert.equal(
268 current.turnItems.find((item) => item.type === "command_execution")?.title,
269 "Starting setup script",
270 );
271 const prematureEffects = yield* outbox.listByCommandId(
272 CommandId.make("command:launch:blocked:initial-message"),
273 );
274 assert.isEmpty(prematureEffects);
275 yield* Deferred.succeed(allowSetup, undefined);
276 }).pipe(Effect.provide(harness.layer));
277 }),
278);
279
280it.effect("provisions independent launches concurrently instead of behind a global semaphore", () =>
281 Effect.gen(function* () {
282 const setupCount = yield* Ref.make(0);
283 const bothEntered = yield* Deferred.make<void>();
284 const allowSetup = yield* Deferred.make<void>();
285 const harness = makeHarness({
286 runSetup: () =>
287 Ref.updateAndGet(setupCount, (count) => count + 1).pipe(
288 Effect.tap((count) =>
289 count === 2 ? Deferred.succeed(bothEntered, undefined) : Effect.void,
290 ),
291 Effect.andThen(Deferred.await(allowSetup)),
292 Effect.as({ status: "no-script" as const }),
293 ),
294 });
295 yield* Effect.gen(function* () {
296 const launches = yield* ThreadLaunch.ThreadLaunchService;
297 const results = yield* Effect.all(
298 [
299 launches.launch(
300 launchInput({
301 command: "command:launch:concurrent-a",
302 thread: "thread:launch:concurrent-a",
303 message: "First",
304 }),
305 ),
306 launches.launch(
307 launchInput({
308 command: "command:launch:concurrent-b",
309 thread: "thread:launch:concurrent-b",
310 message: "Second",
311 }),
312 ),
313 ],
314 { concurrency: "unbounded" },
315 );
316 assert.deepEqual(
317 results.map((result) => result.projection.runs[0]?.status),
318 ["preparing", "preparing"],
319 );
320 yield* Deferred.await(bothEntered);
321 assert.equal(yield* Ref.get(setupCount), 2);
322 yield* Deferred.succeed(allowSetup, undefined);
323 }).pipe(Effect.provide(harness.layer));
324 }),
325);
326
327it.effect("enqueues provider work only after setup has been initiated", () =>
328 Effect.gen(function* () {
329 const setupEntered = yield* Deferred.make<void>();
330 const allowSetup = yield* Deferred.make<void>();
331 const harness = makeHarness({
332 runSetup: () =>
333 Deferred.succeed(setupEntered, undefined).pipe(
334 Effect.andThen(Deferred.await(allowSetup)),
335 Effect.as({
336 status: "started" as const,
337 scriptId: "setup",
338 scriptName: "Setup",
339 terminalId: "setup",
340 cwd: "/repo",
341 }),
342 ),
343 });
344 yield* Effect.gen(function* () {
345 const launches = yield* ThreadLaunch.ThreadLaunchService;
346 const outbox = yield* EffectOutbox.EffectOutboxV2;
347 const threads = yield* ThreadManagement.ThreadManagementService;
348 const input = launchInput({
349 command: "command:launch:release",
350 thread: "thread:launch:release",
351 message: "Start after setup",
352 workspace: { type: "worktree", baseRef: "main" },
353 });
354 const launched = yield* launches.launch(input);
355 yield* Deferred.await(setupEntered);
356 assert.isEmpty(
357 yield* outbox.listByCommandId(CommandId.make("command:launch:release:release")),
358 );
359 yield* Deferred.succeed(allowSetup, undefined);
360 yield* waitUntil(() =>
361 outbox
362 .listByCommandId(CommandId.make("command:launch:release:release"))
363 .pipe(Effect.map((effects) => effects.length === 1)),
364 );
365 const projection = yield* threads.getThreadProjection(launched.threadId);
366 assert.equal(projection.runs[0]?.status, "starting");
367 assert.equal(projection.checkpointScopes[0]?.cwd, "/repo-worktrees/feature");
368 assert.equal(
369 projection.turnItems.find((item) => item.type === "command_execution")?.status,
370 "completed",
371 );
372 }).pipe(Effect.provide(harness.layer));
373 }),
374);
375
376it.effect(
377 "queues follow-up messages behind preparation and checkpoints them in the final workspace",
378 () =>
379 Effect.gen(function* () {
380 const setupEntered = yield* Deferred.make<void>();
381 const failSetup = yield* Deferred.make<void>();
382 const harness = makeHarness({
383 runSetup: () =>
384 Deferred.succeed(setupEntered, undefined).pipe(
385 Effect.andThen(Deferred.await(failSetup)),
386 Effect.andThen(Effect.fail(new Error("setup failed") as never)),
387 ),
388 });
389 yield* Effect.gen(function* () {
390 const launches = yield* ThreadLaunch.ThreadLaunchService;
391 const threads = yield* ThreadManagement.ThreadManagementService;
392 const launched = yield* launches.launch(
393 launchInput({
394 command: "command:launch:queued-during-preparation",
395 thread: "thread:launch:queued-during-preparation",
396 message: "Prepare the workspace",
397 workspace: { type: "worktree", baseRef: "main" },
398 }),
399 );
400 yield* Deferred.await(setupEntered);
401
402 const followUp = yield* threads.sendToThread({
403 projectId,
404 commandId: CommandId.make("command:launch:queued-follow-up"),
405 threadId: launched.threadId,
406 messageId: MessageId.make("message:launch:queued-follow-up"),
407 text: "Run after preparation",
408 attachments: [],
409 mode: "auto",
410 createdBy: "user",
411 creationSource: "web",
412 });
413 assert.equal(followUp.delivery, "queued");
414 assert.equal(followUp.run.status, "queued");
415 assert.equal(
416 followUp.projection.nodes.find(
417 (node) => node.runId === followUp.run.id && node.kind === "root_turn",
418 )?.checkpointScopeId,
419 null,
420 );
421
422 yield* Deferred.succeed(failSetup, undefined);
423 yield* waitUntil(() =>
424 threads
425 .getThreadProjection(launched.threadId)
426 .pipe(
427 Effect.map(
428 (projection) =>
429 projection.runs.find((run) => run.id === followUp.run.id)?.status === "starting",
430 ),
431 ),
432 );
433
434 const projection = yield* threads.getThreadProjection(launched.threadId);
435 const rootNode = projection.nodes.find(
436 (node) => node.runId === followUp.run.id && node.kind === "root_turn",
437 );
438 assert.isNotNull(rootNode?.checkpointScopeId);
439 assert.equal(
440 projection.checkpointScopes.find((scope) => scope.id === rootNode?.checkpointScopeId)
441 ?.cwd,
442 "/repo-worktrees/feature",
443 );
444 }).pipe(Effect.provide(harness.layer));
445 }),
446);
447
448it.effect("arms durable title generation after accepting the first message", () =>
449 Effect.gen(function* () {
450 const harness = makeHarness({
451 generateTitle: (input) =>
452 Effect.succeed({
453 title: input.previousTitle === undefined ? "Generated title" : "Regenerated title",
454 }),
455 });
456 yield* Effect.gen(function* () {
457 const launches = yield* ThreadLaunch.ThreadLaunchService;
458 const threads = yield* ThreadManagement.ThreadManagementService;
459 const outbox = yield* EffectOutbox.EffectOutboxV2;
460 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
461 const input = {
462 ...launchInput({
463 command: "command:launch:title-generation",
464 thread: "thread:launch:title-generation",
465 message: "Generate my title",
466 }),
467 title: "Generate my title",
468 generateTitle: true,
469 };
470 const launched = yield* launches.launch(input);
471 const generationCommandId = CommandId.make("command:launch:title-generation:initial-message");
472
473 const projection = yield* threads.getThreadProjection(launched.threadId);
474 assert.equal(projection.thread.title, "Generate my title");
475 assert.equal(projection.thread.titleRegeneration?.requestId, generationCommandId);
476 assert.deepEqual(
477 (yield* outbox.listByCommandId(generationCommandId)).map((effect) => effect.request),
478 [
479 {
480 type: "thread-title.generate",
481 kind: { type: "initial", messageId: MessageId.make("Generate my title:id") },
482 },
483 ],
484 );
485 yield* titleRegeneration.execute({
486 threadId: launched.threadId,
487 requestId: generationCommandId,
488 kind: { type: "initial", messageId: MessageId.make("Generate my title:id") },
489 });
490 const generated = yield* threads.getThreadProjection(launched.threadId);
491 assert.equal(generated.thread.title, "Generated title");
492 assert.deepEqual(
493 harness.generateThreadTitle.mock.calls[0]?.[0].modelSelection,
494 DEFAULT_SERVER_SETTINGS.textGenerationModelSelection,
495 );
496
497 const manualRequestId = CommandId.make("command:title-generation:manual");
498 yield* threads.dispatch({
499 type: "thread.metadata.update",
500 commandId: manualRequestId,
501 threadId: launched.threadId,
502 regenerateTitle: true,
503 });
504 assert.deepEqual(
505 (yield* outbox.listByCommandId(manualRequestId)).map((effect) => effect.request),
506 [{ type: "thread-title.generate", kind: { type: "regenerate" } }],
507 );
508 yield* titleRegeneration.execute({
509 threadId: launched.threadId,
510 requestId: manualRequestId,
511 kind: { type: "regenerate" },
512 });
513 const regenerated = yield* threads.getThreadProjection(launched.threadId);
514 assert.equal(regenerated.thread.title, "Regenerated title");
515 assert.equal(harness.generateThreadTitle.mock.calls[1]?.[0].previousTitle, "Generated title");
516
517 yield* threads.dispatch({
518 type: "thread.metadata.update",
519 commandId: CommandId.make("command:title-generation:user-rename"),
520 threadId: launched.threadId,
521 title: "Keep my title",
522 });
523 const renamed = yield* threads.getThreadProjection(launched.threadId);
524 yield* TestClock.adjust(Duration.seconds(1));
525 yield* threads.dispatch({
526 type: "thread.title.regeneration.complete",
527 commandId: CommandId.make("command:title-generation:stale-completion"),
528 threadId: launched.threadId,
529 requestId: generationCommandId,
530 title: "Stale generated title",
531 });
532 const afterStaleCompletion = yield* threads.getThreadProjection(launched.threadId);
533 assert.equal(afterStaleCompletion.thread.title, "Keep my title");
534 assert.equal(
535 DateTime.toEpochMillis(afterStaleCompletion.thread.updatedAt),
536 DateTime.toEpochMillis(renamed.thread.updatedAt),
537 );
538 }).pipe(Effect.provide(harness.layer));
539 }),
540);
541
542it.effect("does not update a reused thread title when the initial message is rejected", () =>
543 Effect.gen(function* () {
544 const harness = makeHarness();
545 yield* Effect.gen(function* () {
546 const launches = yield* ThreadLaunch.ThreadLaunchService;
547 const threads = yield* ThreadManagement.ThreadManagementService;
548 const outbox = yield* EffectOutbox.EffectOutboxV2;
549 const threadId = ThreadId.make("thread:launch:reused-title-failure");
550 yield* threads.dispatch({
551 type: "thread.create",
552 commandId: CommandId.make("command:launch:reused-title-failure:create"),
553 threadId,
554 projectId,
555 title: "Original title",
556 modelSelection,
557 runtimeMode: "full-access",
558 interactionMode: "default",
559 branch: null,
560 worktreePath: null,
561 createdBy: "user",
562 creationSource: "web",
563 });
564
565 const commandId = CommandId.make("command:launch:reused-title-failure");
566 const failed = yield* launches
567 .launch({
568 ...launchInput({
569 command: commandId,
570 thread: threadId,
571 message: "Generate a provisional title",
572 }),
573 reuseExistingThread: true,
574 title: "Generate a provisional title",
575 generateTitle: true,
576 modelSelection: {
577 instanceId: ProviderInstanceId.make("missing-provider"),
578 model: "missing-model",
579 },
580 })
581 .pipe(Effect.exit);
582
583 assert.isTrue(Exit.isFailure(failed));
584 const projection = yield* threads.getThreadProjection(threadId);
585 assert.equal(projection.thread.title, "Original title");
586 assert.isUndefined(projection.thread.titleRegeneration);
587 assert.isEmpty(projection.messages);
588 assert.isEmpty(yield* outbox.listByCommandId(CommandId.make(`${commandId}:initial-message`)));
589 }).pipe(Effect.provide(harness.layer));
590 }),
591);
592
593it.effect("generates an initial title for an attachment-only message", () =>
594 Effect.gen(function* () {
595 const harness = makeHarness();
596 yield* Effect.gen(function* () {
597 const launches = yield* ThreadLaunch.ThreadLaunchService;
598 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
599 const messageId = MessageId.make("message:image-only");
600 const input = {
601 ...launchInput({
602 command: "command:launch:image-only",
603 thread: "thread:launch:image-only",
604 }),
605 title: "Image: screenshot.png",
606 generateTitle: true,
607 initialMessage: {
608 messageId,
609 text: "",
610 attachments: [
611 {
612 type: "image" as const,
613 id: "attachment-image-only",
614 name: "screenshot.png",
615 mimeType: "image/png",
616 sizeBytes: 128,
617 },
618 ],
619 },
620 };
621
622 const launched = yield* launches.launch(input);
623 yield* titleRegeneration.execute({
624 threadId: launched.threadId,
625 requestId: CommandId.make("command:launch:image-only:initial-message"),
626 kind: { type: "initial", messageId },
627 });
628
629 assert.equal(harness.generateThreadTitle.mock.calls[0]?.[0].message, "");
630 assert.equal(
631 harness.generateThreadTitle.mock.calls[0]?.[0].attachments?.[0]?.name,
632 "screenshot.png",
633 );
634 }).pipe(Effect.provide(harness.layer));
635 }),
636);
637
638it.effect("uses the available source control writer for generated worktree branches", () =>
639 Effect.gen(function* () {
640 const writerInstanceId = ProviderInstanceId.make("source-control-writer");
641 const writerModelSelection = {
642 instanceId: writerInstanceId,
643 model: "branch-writer-model",
644 } as const;
645 const harness = makeHarness({
646 serverSettings: {
647 providerInstances: {
648 [writerInstanceId]: {
649 driver: ProviderDriverKind.make("codex"),
650 config: {},
651 },
652 },
653 sourceControlWriterModelSelection: writerModelSelection,
654 },
655 providers: [
656 {
657 instanceId: writerInstanceId,
658 driver: ProviderDriverKind.make("codex"),
659 enabled: true,
660 installed: true,
661 version: null,
662 status: "ready",
663 auth: { status: "authenticated" },
664 checkedAt: "2026-07-28T00:00:00.000Z",
665 availability: "available",
666 models: [],
667 slashCommands: [],
668 skills: [],
669 },
670 ],
671 });
672
673 yield* Effect.gen(function* () {
674 const launches = yield* ThreadLaunch.ThreadLaunchService;
675 yield* launches.launch(
676 launchInput({
677 command: "command:launch:source-control-writer",
678 thread: "thread:launch:source-control-writer",
679 message: "Generate a branch with the configured writer",
680 workspace: { type: "worktree", baseRef: "main" },
681 }),
682 );
683 yield* waitUntil(() => Effect.sync(() => harness.generateBranchName.mock.calls.length === 1));
684 assert.deepEqual(
685 harness.generateBranchName.mock.calls[0]?.[0].modelSelection,
686 writerModelSelection,
687 );
688 }).pipe(Effect.provide(harness.layer));
689 }),
690);
691
692it.effect("falls back when the source control writer is unavailable", () =>
693 Effect.gen(function* () {
694 const writerInstanceId = ProviderInstanceId.make("missing-source-control-writer");
695 const harness = makeHarness({
696 serverSettings: {
697 providerInstances: {
698 [writerInstanceId]: {
699 driver: ProviderDriverKind.make("missing-driver"),
700 config: {},
701 },
702 },
703 sourceControlWriterModelSelection: {
704 instanceId: writerInstanceId,
705 model: "missing-branch-writer-model",
706 },
707 },
708 providers: [],
709 });
710
711 yield* Effect.gen(function* () {
712 const launches = yield* ThreadLaunch.ThreadLaunchService;
713 yield* launches.launch(
714 launchInput({
715 command: "command:launch:source-control-writer-fallback",
716 thread: "thread:launch:source-control-writer-fallback",
717 message: "Generate a branch with the available writer",
718 workspace: { type: "worktree", baseRef: "main" },
719 }),
720 );
721 yield* waitUntil(() => Effect.sync(() => harness.generateBranchName.mock.calls.length === 1));
722 assert.deepEqual(
723 harness.generateBranchName.mock.calls[0]?.[0].modelSelection,
724 DEFAULT_SERVER_SETTINGS.textGenerationModelSelection,
725 );
726 }).pipe(Effect.provide(harness.layer));
727 }),
728);
729
730it.effect("names the worktree itself when the client provides no branch", () =>
731 Effect.gen(function* () {
732 const harness = makeHarness();
733 yield* Effect.gen(function* () {
734 const launches = yield* ThreadLaunch.ThreadLaunchService;
735 const threads = yield* ThreadManagement.ThreadManagementService;
736 const launched = yield* launches.launch(
737 launchInput({
738 command: "command:launch:server-named-branch",
739 thread: "thread:launch:server-named-branch",
740 message: "Build the feature",
741 workspace: { type: "worktree", baseRef: "main" },
742 }),
743 );
744 yield* waitUntil(() => Effect.sync(() => harness.createWorktree.mock.calls.length === 1));
745 assert.match(
746 harness.createWorktree.mock.calls[0]?.[0].newRefName ?? "",
747 /^t3code\/[0-9a-f]{8}$/u,
748 );
749 yield* waitUntil(() =>
750 threads
751 .getThreadProjection(launched.threadId)
752 .pipe(Effect.map((projection) => projection.thread.branch === "generated-branch")),
753 );
754 }).pipe(Effect.provide(harness.layer));
755 }),
756);
757
758it.effect("renames a temporary t3code/<hash> branch off the provisioning critical path", () =>
759 Effect.gen(function* () {
760 const branchNameStarted = yield* Deferred.make<void>();
761 const allowBranchName = yield* Deferred.make<void>();
762 const harness = makeHarness({
763 createWorktree: (input) =>
764 Effect.succeed({
765 worktree: { path: "/repo-worktrees/temp", refName: input.newRefName, headSha: "abc" },
766 } as never),
767 generateBranchName: () =>
768 Deferred.succeed(branchNameStarted, undefined).pipe(
769 Effect.andThen(Deferred.await(allowBranchName)),
770 Effect.as({ branch: "generated-branch" }),
771 ),
772 });
773 yield* Effect.gen(function* () {
774 const launches = yield* ThreadLaunch.ThreadLaunchService;
775 const threads = yield* ThreadManagement.ThreadManagementService;
776 const launched = yield* launches.launch(
777 launchInput({
778 command: "command:launch:temp-branch",
779 thread: "thread:launch:temp-branch",
780 message: "Build the feature",
781 workspace: { type: "worktree", baseRef: "main", branch: "t3code/abcd1234" },
782 }),
783 );
784 yield* Deferred.await(branchNameStarted);
785 assert.equal(harness.createWorktree.mock.calls[0]?.[0].newRefName, "t3code/abcd1234");
786 yield* waitUntil(() =>
787 threads
788 .getThreadProjection(launched.threadId)
789 .pipe(Effect.map((projection) => projection.runs[0]?.status === "starting")),
790 );
791 assert.equal(
792 (yield* threads.getThreadProjection(launched.threadId)).thread.branch,
793 "t3code/abcd1234",
794 );
795 yield* Deferred.succeed(allowBranchName, undefined);
796 yield* waitUntil(() =>
797 threads
798 .getThreadProjection(launched.threadId)
799 .pipe(Effect.map((projection) => projection.thread.branch === "generated-branch")),
800 );
801 assert.deepEqual(harness.renameBranch.mock.calls[0]?.[0], {
802 cwd: "/repo-worktrees/temp",
803 oldBranch: "t3code/abcd1234",
804 newBranch: "generated-branch",
805 });
806 }).pipe(Effect.provide(harness.layer));
807 }),
808);
809
810it.effect("keeps an explicit branch name instead of generating one", () =>
811 Effect.gen(function* () {
812 const harness = makeHarness();
813 yield* Effect.gen(function* () {
814 const launches = yield* ThreadLaunch.ThreadLaunchService;
815 yield* launches.launch(
816 launchInput({
817 command: "command:launch:explicit-branch",
818 thread: "thread:launch:explicit-branch",
819 message: "Build the feature",
820 workspace: { type: "worktree", baseRef: "main", branch: "my-feature" },
821 }),
822 );
823 yield* waitUntil(() => Effect.sync(() => harness.createWorktree.mock.calls.length === 1));
824 assert.equal(harness.generateBranchName.mock.calls.length, 0);
825 assert.equal(harness.createWorktree.mock.calls[0]?.[0].newRefName, "my-feature");
826 }).pipe(Effect.provide(harness.layer));
827 }),
828);
829
830it.effect("keeps the temporary branch when branch generation fails", () =>
831 Effect.gen(function* () {
832 const harness = makeHarness({
833 createWorktree: (input) =>
834 Effect.succeed({
835 worktree: { path: "/repo-worktrees/temp", refName: input.newRefName, headSha: "abc" },
836 } as never),
837 generateBranchName: () => Effect.die("branch generation is down"),
838 });
839 yield* Effect.gen(function* () {
840 const launches = yield* ThreadLaunch.ThreadLaunchService;
841 const threads = yield* ThreadManagement.ThreadManagementService;
842 const launched = yield* launches.launch(
843 launchInput({
844 command: "command:launch:branch-fallback",
845 thread: "thread:launch:branch-fallback",
846 message: "Build the feature",
847 workspace: { type: "worktree", baseRef: "main", branch: "t3code/abcd1234" },
848 }),
849 );
850 yield* waitUntil(() => Effect.sync(() => harness.generateBranchName.mock.calls.length === 1));
851 assert.equal(harness.createWorktree.mock.calls[0]?.[0].newRefName, "t3code/abcd1234");
852 yield* waitUntil(() =>
853 threads
854 .getThreadProjection(launched.threadId)
855 .pipe(Effect.map((projection) => projection.runs[0]?.status === "starting")),
856 );
857 assert.equal(harness.renameBranch.mock.calls.length, 0);
858 assert.equal(
859 (yield* threads.getThreadProjection(launched.threadId)).thread.branch,
860 "t3code/abcd1234",
861 );
862 }).pipe(Effect.provide(harness.layer));
863 }),
864);
865
866it.effect("renames a temporary branch on an existing worktree to a generated name", () =>
867 Effect.gen(function* () {
868 const harness = makeHarness();
869 yield* Effect.gen(function* () {
870 const launches = yield* ThreadLaunch.ThreadLaunchService;
871 const threads = yield* ThreadManagement.ThreadManagementService;
872 const launched = yield* launches.launch(
873 launchInput({
874 command: "command:launch:existing-worktree-rename",
875 thread: "thread:launch:existing-worktree-rename",
876 message: "Build the feature",
877 workspace: {
878 type: "existing_worktree",
879 worktreePath: "/repo-worktrees/t3code-abcd1234",
880 branch: "t3code/abcd1234",
881 },
882 }),
883 );
884 yield* waitUntil(() =>
885 threads
886 .getThreadProjection(launched.threadId)
887 .pipe(Effect.map((projection) => projection.thread.branch === "generated-branch")),
888 );
889 assert.deepEqual(harness.renameBranch.mock.calls[0]?.[0], {
890 cwd: "/repo-worktrees/t3code-abcd1234",
891 oldBranch: "t3code/abcd1234",
892 newBranch: "generated-branch",
893 });
894 }).pipe(Effect.provide(harness.layer));
895 }),
896);
897
898for (const failurePoint of ["worktree", "setup"] as const) {
899 it.effect(
900 `${failurePoint} failure keeps the thread and message visible and emits failure items`,
901 () =>
902 Effect.gen(function* () {
903 const failure = new Error(`${failurePoint} failed`);
904 const harness = makeHarness(
905 failurePoint === "worktree"
906 ? { createWorktree: () => Effect.fail(failure as never) }
907 : { runSetup: () => Effect.fail(failure as never) },
908 );
909 yield* Effect.gen(function* () {
910 const launches = yield* ThreadLaunch.ThreadLaunchService;
911 const threads = yield* ThreadManagement.ThreadManagementService;
912 const input = launchInput({
913 command: `command:launch:${failurePoint}-failure`,
914 thread: `thread:launch:${failurePoint}-failure`,
915 message: `Fail during ${failurePoint}`,
916 workspace: { type: "worktree", baseRef: "main" },
917 });
918 const launched = yield* launches.launch(input);
919 yield* waitUntil(() =>
920 threads
921 .getThreadProjection(launched.threadId)
922 .pipe(Effect.map((projection) => projection.runs[0]?.status === "failed")),
923 );
924 const projection = yield* threads.getThreadProjection(launched.threadId);
925 assert.equal(projection.messages[0]?.text, `Fail during ${failurePoint}`);
926 assert.equal(projection.runs[0]?.status, "failed");
927 assert.equal(
928 projection.turnItems.find((item) => item.type === "command_execution")?.status,
929 "failed",
930 );
931 assert.match(
932 projection.turnItems.find((item) => item.type === "error")?.failure.message ?? "",
933 new RegExp(`${failurePoint} failed`, "u"),
934 );
935 }).pipe(Effect.provide(harness.layer));
936 }),
937 );
938}
939
940it.effect("deduplicates retried launch side effects in-process", () =>
941 Effect.gen(function* () {
942 const setupEntered = yield* Deferred.make<void>();
943 const allowSetup = yield* Deferred.make<void>();
944 const harness = makeHarness({
945 runSetup: () =>
946 Deferred.succeed(setupEntered, undefined).pipe(
947 Effect.andThen(Deferred.await(allowSetup)),
948 Effect.as({ status: "no-script" as const }),
949 ),
950 });
951 yield* Effect.gen(function* () {
952 const launches = yield* ThreadLaunch.ThreadLaunchService;
953 const input = launchInput({
954 command: "command:launch:retry",
955 thread: "thread:launch:retry",
956 message: "Only once",
957 });
958 const [first, retry] = yield* Effect.all([launches.launch(input), launches.launch(input)], {
959 concurrency: "unbounded",
960 });
961 yield* Deferred.await(setupEntered);
962 assert.equal(first.threadId, retry.threadId);
963 assert.isFalse(first.resumed);
964 assert.isTrue(retry.resumed);
965 assert.equal(harness.runSetup.mock.calls.length, 1);
966 yield* Deferred.succeed(allowSetup, undefined);
967 }).pipe(Effect.provide(harness.layer));
968 }),
969);
970
971it.effect("does not let a failing same-command caller strand a concurrent durable launch", () =>
972 Effect.gen(function* () {
973 const setupEntered = yield* Deferred.make<void>();
974 const allowSetup = yield* Deferred.make<void>();
975 const harness = makeHarness({
976 runSetup: () =>
977 Deferred.succeed(setupEntered, undefined).pipe(
978 Effect.andThen(Deferred.await(allowSetup)),
979 Effect.as({ status: "no-script" as const }),
980 ),
981 });
982 yield* Effect.gen(function* () {
983 const launches = yield* ThreadLaunch.ThreadLaunchService;
984 const command = "command:launch:failed-owner-race";
985 const [failed, launched] = yield* Effect.all(
986 [
987 launches
988 .launch({
989 ...launchInput({
990 command,
991 thread: "thread:launch:failed-owner-race",
992 message: "This invalid reuse fails",
993 }),
994 reuseExistingThread: true,
995 })
996 .pipe(Effect.exit),
997 launches.launch(
998 launchInput({
999 command,
1000 thread: "thread:launch:successful-peer",
1001 message: "This peer persists",
1002 }),
1003 ),
1004 ],
1005 { concurrency: "unbounded" },
1006 );
1007 assert.isTrue(Exit.isFailure(failed));
1008 assert.equal(launched.projection.runs[0]?.status, "preparing");
1009 const entered = yield* Deferred.await(setupEntered).pipe(
1010 Effect.timeoutOption(Duration.seconds(2)),
1011 );
1012 assert.isTrue(Option.isSome(entered));
1013 assert.equal(harness.runSetup.mock.calls.length, 1);
1014 yield* Deferred.succeed(allowSetup, undefined);
1015 }).pipe(Effect.provide(harness.layer));
1016 }),
1017);
1018
1019it.effect("schedules an accepted preparing message exactly once across concurrent retries", () =>
1020 Effect.gen(function* () {
1021 const setupEntered = yield* Deferred.make<void>();
1022 const allowSetup = yield* Deferred.make<void>();
1023 const harness = makeHarness({
1024 runSetup: () =>
1025 Deferred.succeed(setupEntered, undefined).pipe(
1026 Effect.andThen(Deferred.await(allowSetup)),
1027 Effect.as({ status: "no-script" as const }),
1028 ),
1029 });
1030 yield* Effect.gen(function* () {
1031 const launches = yield* ThreadLaunch.ThreadLaunchService;
1032 const threads = yield* ThreadManagement.ThreadManagementService;
1033 const input = launchInput({
1034 command: "command:launch:accepted-before-fork",
1035 thread: "thread:launch:accepted-before-fork",
1036 message: "Resume preparation",
1037 });
1038 const messageId = MessageId.make("message:launch:accepted-before-fork");
1039
1040 yield* threads.dispatch({
1041 type: "thread.create",
1042 commandId: input.commandId,
1043 threadId: input.threadId,
1044 projectId: input.projectId,
1045 title: input.title,
1046 modelSelection: input.modelSelection,
1047 runtimeMode: input.runtimeMode,
1048 interactionMode: input.interactionMode,
1049 branch: null,
1050 worktreePath: null,
1051 createdBy: input.createdBy,
1052 creationSource: input.creationSource,
1053 });
1054 yield* threads.dispatch({
1055 type: "message.dispatch",
1056 commandId: CommandId.make(`${input.commandId}:initial-message`),
1057 threadId: input.threadId,
1058 messageId,
1059 text: "Resume preparation",
1060 attachments: [],
1061 modelSelection: input.modelSelection,
1062 dispatchMode: { type: "defer_start" },
1063 createdBy: input.createdBy,
1064 creationSource: input.creationSource,
1065 });
1066 const preparing = yield* threads.getThreadProjection(input.threadId);
1067 assert.equal(preparing.runs[0]?.status, "preparing");
1068
1069 const [first, second] = yield* Effect.all([launches.launch(input), launches.launch(input)], {
1070 concurrency: "unbounded",
1071 });
1072 yield* Deferred.await(setupEntered);
1073 assert.isTrue(first.resumed);
1074 assert.isTrue(second.resumed);
1075 assert.equal(harness.runSetup.mock.calls.length, 1);
1076 yield* Deferred.succeed(allowSetup, undefined);
1077 }).pipe(Effect.provide(harness.layer));
1078 }),
1079);
1080
1081it.effect("does not depend on the legacy launch workflow table", () => {
1082 const harness = makeHarness();
1083 return Effect.gen(function* () {
1084 const sql = yield* SqlClient.SqlClient;
1085 const launches = yield* ThreadLaunch.ThreadLaunchService;
1086 yield* sql`DROP TABLE orchestration_v2_thread_launch_workflows`;
1087 const launched = yield* launches.launch(
1088 launchInput({
1089 command: "command:launch:no-workflow-table",
1090 thread: "thread:launch:no-workflow-table",
1091 message: "No private workflow state",
1092 }),
1093 );
1094 assert.equal(launched.projection.messages[0]?.text, "No private workflow state");
1095 }).pipe(Effect.provide(harness.layer));
1096});