Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadLaunchService.test.ts

1,098 lines41.8 KB

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