Open History to see the last commit
1import * as WorktreeSetupTracker from "../project/WorktreeSetupTracker.ts";
2import * as ProjectCloneTracker from "../project/ProjectCloneTracker.ts";
3import * as TerminalManager from "../terminal/Manager.ts";
4import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
5import {
6 CommandId,
7 type ChatAttachment,
8 type MessageId,
9 type ModelSelection,
10 type OrchestrationV2Actor,
11 type OrchestrationV2CreationSource,
12 type OrchestrationV2ProviderThreadNativeMetadata,
13 type OrchestrationV2ThreadProjection,
14 type ProviderDriverKind,
15 type ProviderInteractionMode,
16 ProjectId,
17 type RunId,
18 type RuntimeMode,
19 type ScheduledTaskId,
20 ThreadId,
21} from "@t3tools/contracts";
22import * as Cause from "effect/Cause";
23import * as Context from "effect/Context";
24import * as Effect from "effect/Effect";
25import * as Exit from "effect/Exit";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Ref from "effect/Ref";
29import * as Schema from "effect/Schema";
30import * as Scope from "effect/Scope";
31import * as Stream from "effect/Stream";
32import {
33 buildTemporaryWorktreeBranchName,
34 flattenTemporaryWorktreeBranchName,
35 isTemporaryWorktreeBranch,
36 WORKTREE_BRANCH_PREFIX,
37} from "@t3tools/shared/git";
38
39import * as GitWorkflow from "../git/GitWorkflowService.ts";
40import * as ProjectService from "../project/ProjectService.ts";
41import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
42import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
43import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
44import * as ServerSettings from "../serverSettings.ts";
45import * as TextGeneration from "../textGeneration/TextGeneration.ts";
46import * as CommandReceiptStore from "./CommandReceiptStore.ts";
47import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
48import type * as Orchestrator from "./Orchestrator.ts";
49import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
50import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
51import * as ThreadManagement from "./ThreadManagementService.ts";
52
53export type ThreadLaunchWorkspaceStrategy =
54 | { readonly type: "root"; readonly branch?: string | undefined }
55 | {
56 readonly type: "existing_worktree";
57 readonly worktreePath: string;
58 readonly branch?: string | undefined;
59 }
60 | {
61 readonly type: "worktree";
62 readonly baseRef: string;
63 readonly branch?: string | undefined;
64 readonly startFromOrigin?: boolean | undefined;
65 };
66
67export interface ThreadLaunchInitialMessage {
68 readonly messageId?: MessageId;
69 readonly scheduledTaskId?: ScheduledTaskId;
70 readonly senderThreadId?: ThreadId;
71 readonly text: string;
72 readonly attachments: ReadonlyArray<ChatAttachment>;
73 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
74}
75
76export interface ThreadLaunchInput {
77 readonly commandId: CommandId;
78 readonly threadId?: ThreadId;
79 readonly reuseExistingThread?: boolean;
80 readonly projectId: ProjectId;
81 readonly title: string;
82 readonly generateTitle?: boolean;
83 readonly modelSelection: ModelSelection;
84 readonly runtimeMode: RuntimeMode;
85 readonly interactionMode: ProviderInteractionMode;
86 readonly workspaceStrategy: ThreadLaunchWorkspaceStrategy;
87 readonly initialMessage?: ThreadLaunchInitialMessage;
88 readonly importedNativeThread?: {
89 readonly ref: {
90 readonly driver: ProviderDriverKind;
91 readonly nativeId: string;
92 readonly strength: "strong";
93 };
94 readonly metadata?: OrchestrationV2ProviderThreadNativeMetadata;
95 };
96 readonly createdBy: OrchestrationV2Actor;
97 readonly creationSource: OrchestrationV2CreationSource;
98}
99
100/** What workspace preparation reads from a launch; a retry rebuilds it from the run. */
101type PreparationInput = Pick<
102 ThreadLaunchInput,
103 "commandId" | "projectId" | "workspaceStrategy" | "initialMessage"
104> & {
105 /**
106 * Set when a retry reuses the worktree its failed attempt created and
107 * recorded. Its setup is tracked like a new one, but the thread already
108 * records the workspace, and a branch rename may still be running.
109 */
110 readonly reusedWorktree?: { readonly baseRef: string };
111};
112
113export interface ThreadLaunchPreparationInput {
114 readonly commandId: CommandId;
115 readonly threadId: ThreadId;
116 readonly runId: RunId;
117}
118
119export interface ThreadLaunchResult {
120 readonly threadId: ThreadId;
121 readonly projection: OrchestrationV2ThreadProjection;
122 readonly resumed: boolean;
123}
124
125export class ThreadLaunchError extends Schema.TaggedError<ThreadLaunchError>()(
126 "ThreadLaunchError",
127 {
128 operation: Schema.Literals([
129 "resolve-project",
130 "read-receipt",
131 "generate-metadata",
132 "provision-worktree",
133 "run-setup-script",
134 "create-thread",
135 "update-thread",
136 "dispatch-message",
137 "release-run",
138 "fail-run",
139 ]),
140 commandId: CommandId,
141 projectId: ProjectId,
142 threadId: Schema.optional(ThreadId),
143 cause: Schema.Defect(),
144 },
145) {
146 override get message(): string {
147 return `Thread launch ${this.commandId} failed during ${this.operation}.`;
148 }
149}
150
151/** A new worktree was asked to start from a ref that gives it no commit. */
152export class ThreadLaunchBaseRefError extends Schema.TaggedError<ThreadLaunchBaseRefError>()(
153 "ThreadLaunchBaseRefError",
154 {
155 projectId: ProjectId,
156 projectTitle: Schema.String,
157 workspaceRoot: Schema.String,
158 baseRef: Schema.String,
159 },
160) {
161 override get message(): string {
162 return `Base ref "${this.baseRef}" does not resolve to a commit in project "${this.projectTitle}" (${this.workspaceRoot}).`;
163 }
164}
165
166export class ThreadLaunchService extends Context.Service<
167 ThreadLaunchService,
168 {
169 readonly launch: (
170 input: ThreadLaunchInput,
171 ) => Effect.Effect<
172 ThreadLaunchResult,
173 ThreadLaunchError | ThreadManagement.ThreadManagementProviderInstanceDisabledError
174 >;
175 /**
176 * Fails when a new worktree's base ref cannot give provisioning a commit.
177 * `launch` accepts such a launch and reports the failure inside the
178 * thread; a caller that needs it before a thread exists checks first.
179 */
180 readonly checkWorktreeBase: (
181 input: Pick<ThreadLaunchInput, "projectId" | "workspaceStrategy">,
182 ) => Effect.Effect<void, ThreadLaunchBaseRefError>;
183 /** Dispatches prepared-run.retry and prepares the run's workspace again. */
184 readonly retryPreparation: (input: ThreadLaunchPreparationInput) => Effect.Effect<
185 Orchestrator.OrchestratorV2DispatchResult,
186 // Dispatches prepared-run.retry, a command the enablement chokepoint
187 // never gates; the type stays accurate anyway.
188 | Orchestrator.OrchestratorV2Error
189 | ThreadManagement.ThreadManagementProviderInstanceDisabledError
190 >;
191 readonly prepareRun: (input: ThreadLaunchPreparationInput) => Effect.Effect<void>;
192 }
193>()("t3/orchestration-v2/ThreadLaunchService") {}
194
195const isThreadLaunchError = Schema.is(ThreadLaunchError);
196
197function failureDetail(error: unknown): string {
198 if (isThreadLaunchError(error)) {
199 const cause = error.cause;
200 const detail = cause instanceof Error ? cause.message : String(cause);
201 return `Workspace preparation failed during ${error.operation.replaceAll("-", " ")}: ${detail}`;
202 }
203 return `Workspace preparation failed: ${error instanceof Error ? error.message : String(error)}`;
204}
205
206const make = Effect.gen(function* () {
207 const projects = yield* ProjectService.ProjectService;
208 const setupTracker = yield* WorktreeSetupTracker.WorktreeSetupTracker;
209 const cloneTracker = yield* ProjectCloneTracker.ProjectCloneTracker;
210 const terminals = yield* TerminalManager.TerminalManager;
211 const git = yield* GitWorkflow.GitWorkflowService;
212 const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
213 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
214 const serverSettings = yield* ServerSettings.ServerSettingsService;
215 const textGeneration = yield* TextGeneration.TextGeneration;
216 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
217 const ids = yield* IdAllocator.IdAllocatorV2;
218 const threads = yield* ThreadManagement.ThreadManagementService;
219 const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;
220 const preparationScope = yield* Scope.make("sequential");
221 const scheduledLaunches = yield* Ref.make<ReadonlySet<CommandId>>(new Set());
222 yield* Effect.addFinalizer(() => Scope.close(preparationScope, Exit.void));
223
224 const mapError =
225 (input: PreparationInput, operation: ThreadLaunchError["operation"], threadId?: ThreadId) =>
226 (cause: unknown) =>
227 new ThreadLaunchError({
228 operation,
229 commandId: input.commandId,
230 projectId: input.projectId,
231 ...(threadId === undefined ? {} : { threadId }),
232 cause,
233 });
234
235 const readReceipt = (input: ThreadLaunchInput, commandId: CommandId) =>
236 receipts
237 .getByCommandId(commandId)
238 .pipe(Effect.mapError(mapError(input, "read-receipt", input.threadId)));
239
240 const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")(function* (
241 input: ThreadLaunchInput,
242 threadId: ThreadId,
243 ) {
244 const projection = yield* threads
245 .getThreadRecords(threadId, ["runs"])
246 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
247 if (
248 projection.thread.projectId !== input.projectId ||
249 projection.thread.archivedAt !== null ||
250 projection.thread.deletedAt !== null ||
251 (yield* threads
252 .getMessageCount(threadId)
253 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)))) > 0 ||
254 projection.runs.length > 0
255 ) {
256 return yield* mapError(
257 input,
258 "update-thread",
259 threadId,
260 )("Only an empty active thread in the target project can change workspace during launch.");
261 }
262 });
263
264 const checkWorktreeBase: ThreadLaunchService["Service"]["checkWorktreeBase"] = Effect.fn(
265 "ThreadLaunchService.checkWorktreeBase",
266 )(function* (input) {
267 const strategy = input.workspaceStrategy;
268 // `:/text` is a commit search, which cannot be asked for a commit type.
269 if (strategy.type !== "worktree" || strategy.baseRef.startsWith(":")) return;
270 const { baseRef } = strategy;
271 // Anything this cannot establish is left for the launch to report: a
272 // missing project, a folder that is not a repository, a failing Git.
273 const unresolved = yield* Effect.gen(function* () {
274 const project = Option.getOrUndefined(yield* projects.getById(input.projectId));
275 if (project === undefined) return undefined;
276 const cwd = project.workspaceRoot;
277 // `git worktree add` reads `-` as the previous checkout.
278 if (yield* git.hasCommit({ cwd, refName: baseRef === "-" ? "@{-1}" : baseRef }))
279 return undefined;
280 // Provisioning fetches the base from origin when it can, and runs a
281 // repository with no commits yet without a worktree.
282 if (
283 strategy.startFromOrigin === true &&
284 (yield* git.remoteExists({ cwd, remoteName: "origin" }))
285 )
286 return undefined;
287 // `git worktree add` also starts from a remote-tracking branch of that
288 // name; any ref carrying it is reason enough to let Git decide.
289 if (yield* git.hasRefNamed({ cwd, refName: baseRef })) return undefined;
290 return (yield* git.hasCommit({ cwd, refName: "HEAD" })) ? project : undefined;
291 }).pipe(Effect.orElseSucceed(() => undefined));
292 if (unresolved !== undefined)
293 return yield* new ThreadLaunchBaseRefError({
294 projectId: unresolved.id,
295 projectTitle: unresolved.title,
296 workspaceRoot: unresolved.workspaceRoot,
297 baseRef,
298 });
299 });
300
301 const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* (
302 input: PreparationInput,
303 threadId: ThreadId,
304 runId: RunId | null,
305 ) {
306 const project = yield* projects.getById(input.projectId).pipe(
307 Effect.mapError(mapError(input, "resolve-project", threadId)),
308 Effect.flatMap(
309 Option.match({
310 onNone: () =>
311 Effect.fail(mapError(input, "resolve-project", threadId)("Project no longer exists.")),
312 onSome: Effect.succeed,
313 }),
314 ),
315 );
316
317 const reused = input.reusedWorktree;
318 const tracked = input.workspaceStrategy.type === "worktree" || reused !== undefined;
319 let createdWorktreePath: string | null = null;
320 let setupTerminalId: string | null = null;
321 let workspaceRecorded = false;
322 let runReleased = false;
323 if (input.workspaceStrategy.type === "worktree") {
324 yield* setupTracker.begin({
325 threadId,
326 branch: input.workspaceStrategy.branch ?? null,
327 baseRef: input.workspaceStrategy.baseRef,
328 stages: ["fetch", "checkout", "setup-script", "agent"],
329 fiber: yield* Effect.fiber,
330 });
331 } else if (reused !== undefined) {
332 yield* setupTracker.begin({
333 threadId,
334 branch: input.workspaceStrategy.branch ?? null,
335 baseRef: reused.baseRef,
336 stages: ["setup-script", "agent"],
337 fiber: yield* Effect.fiber,
338 });
339 }
340 yield* Effect.gen(function* () {
341 const initialMessage = input.initialMessage;
342 const generateBranchNameFor = (cwd: string, message: ThreadLaunchInitialMessage) =>
343 Effect.gen(function* () {
344 const settings = resolveProjectSettings(
345 yield* serverSettings.getSettings,
346 input.projectId,
347 ).settings;
348 const modelSelection =
349 settings.sourceControlWriterModelSelection === null
350 ? settings.textGenerationModelSelection
351 : ServerSettings.resolveSourceControlWriterModelSelection(
352 settings,
353 yield* providerRegistry.getProviders,
354 input.projectId,
355 );
356 return yield* textGeneration
357 .generateBranchName({
358 naming: {
359 mode: settings.branchNamingMode,
360 prefix: settings.branchNamePrefix,
361 instructions: settings.branchNameInstructions,
362 },
363 cwd,
364 message: message.text,
365 attachments: message.attachments,
366 ...(message.context ? { context: message.context } : {}),
367 modelSelection,
368 })
369 .pipe(
370 Effect.map((result) => ({
371 branch: result.branch,
372 exactName: settings.branchNamingMode === "custom",
373 })),
374 );
375 });
376
377 // The server owns worktree naming: without an explicit branch, provision
378 // under a temporary `t3/<hash>` name so the worktree never waits on
379 // name generation, then rename in the background below.
380 const requestedBranch = input.workspaceStrategy.branch;
381 let branch: string | null;
382 if (input.workspaceStrategy.type === "worktree" && requestedBranch === undefined) {
383 const uuid = yield* randomUuidV4;
384 branch = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
385 } else {
386 branch = requestedBranch ?? null;
387 }
388 let worktreePath =
389 input.workspaceStrategy.type === "existing_worktree"
390 ? input.workspaceStrategy.worktreePath
391 : null;
392 if (input.workspaceStrategy.type === "worktree") {
393 if (runId !== null) {
394 yield* threads
395 .dispatch({
396 type: "prepared-run.progress",
397 commandId: CommandId.make(`${input.commandId}:progress:worktree`),
398 threadId,
399 runId,
400 phase: "worktree",
401 })
402 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
403 }
404 let startRef = input.workspaceStrategy.baseRef;
405 // "Start from origin" is a stored default; repos without the requested
406 // remote branch fall back to the local base branch.
407 const startFromOrigin =
408 input.workspaceStrategy.startFromOrigin === true &&
409 (yield* git
410 .remoteExists({ cwd: project.workspaceRoot, remoteName: "origin" })
411 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))));
412 yield* setupTracker.stageStatus(threadId, "fetch", startFromOrigin ? "running" : "skipped");
413 if (startFromOrigin) {
414 yield* git
415 .fetchRemote({
416 cwd: project.workspaceRoot,
417 remoteName: "origin",
418 refName: input.workspaceStrategy.baseRef,
419 })
420 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
421 const remoteBaseExists = yield* git
422 .remoteBranchExists({
423 cwd: project.workspaceRoot,
424 refName: input.workspaceStrategy.baseRef,
425 remoteName: "origin",
426 })
427 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
428 if (remoteBaseExists) {
429 startRef = yield* git
430 .resolveRemoteTrackingCommit({
431 cwd: project.workspaceRoot,
432 refName: input.workspaceStrategy.baseRef,
433 fallbackRemoteName: "origin",
434 })
435 .pipe(
436 Effect.map((resolved) => resolved.commitSha),
437 Effect.mapError(mapError(input, "provision-worktree", threadId)),
438 );
439 }
440 }
441 if (startFromOrigin) yield* setupTracker.stageStatus(threadId, "fetch", "done");
442 if (
443 branch !== null &&
444 isTemporaryWorktreeBranch(branch) &&
445 (yield* git
446 .hasCommit({
447 cwd: project.workspaceRoot,
448 refName: `refs/heads/${WORKTREE_BRANCH_PREFIX}`,
449 })
450 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))))
451 ) {
452 branch = flattenTemporaryWorktreeBranchName(branch);
453 }
454 yield* setupTracker.stageStatus(threadId, "checkout", "running");
455 const worktree = yield* git
456 .createWorktree(
457 {
458 cwd: project.workspaceRoot,
459 refName: startRef,
460 newRefName: branch!,
461 baseRefName: input.workspaceStrategy.baseRef,
462 path: null,
463 },
464 {
465 progress: {
466 onWorktreeClaimed: (path) =>
467 Effect.sync(() => {
468 createdWorktreePath = path;
469 }),
470 onCheckoutProgress: (progress) =>
471 setupTracker.stage(threadId, "checkout", { percent: progress.percent }),
472 },
473 },
474 )
475 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
476 worktreePath = worktree.worktree.path;
477 branch = worktree.worktree.refName;
478 createdWorktreePath = worktreePath;
479 yield* setupTracker.update(threadId, (snapshot) => ({ ...snapshot, worktreePath, branch }));
480 yield* setupTracker.stageStatus(threadId, "checkout", "done");
481 }
482
483 // A reused worktree is already recorded, and rewriting it could undo
484 // the first attempt's branch rename.
485 if (reused === undefined) {
486 yield* threads
487 .dispatch({
488 type: "thread.metadata.update",
489 commandId: CommandId.make(`${input.commandId}:workspace`),
490 threadId,
491 branch,
492 worktreePath,
493 })
494 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
495 }
496 workspaceRecorded = true;
497
498 // Rename temporary branches (server-invented above, or sent by clients
499 // that name worktrees themselves) in the background so generation latency
500 // never delays provisioning or the provider turn. The temporary name
501 // simply sticks if generation or the rename fails.
502 if (
503 reused === undefined &&
504 worktreePath !== null &&
505 branch !== null &&
506 initialMessage !== undefined &&
507 isTemporaryWorktreeBranch(branch)
508 ) {
509 const oldBranch = branch;
510 const worktreeCwd = worktreePath;
511 yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe(
512 Effect.flatMap(({ branch: newBranch, exactName }) =>
513 git.renameBranch({
514 cwd: worktreeCwd,
515 oldBranch,
516 newBranch,
517 ...(exactName ? { exactName: true } : {}),
518 }),
519 ),
520 Effect.flatMap((renamed) =>
521 Effect.gen(function* () {
522 yield* threads
523 .dispatch({
524 type: "thread.metadata.update",
525 commandId: CommandId.make(`${input.commandId}:branch-rename`),
526 threadId,
527 branch: renamed.branch,
528 worktreePath: worktreeCwd,
529 expectedBranch: oldBranch,
530 expectedWorktreePath: worktreeCwd,
531 })
532 .pipe(
533 Effect.catchCause((cause) =>
534 Effect.logWarning("Parent thread worktree branch update failed", {
535 threadId,
536 cause,
537 }),
538 ),
539 );
540 // Updating the parent first makes later subagents inherit the new name.
541 // Re-read after each pass for children of subagents updated in that pass.
542 const visited = new Set([threadId]);
543 while (true) {
544 const snapshot = yield* threads.getShellSnapshot();
545 const sharing = [...snapshot.threads, ...snapshot.archivedThreads].filter(
546 (thread) =>
547 !visited.has(thread.id) &&
548 thread.worktreePath === worktreeCwd &&
549 thread.branch === oldBranch,
550 );
551 if (sharing.length === 0) break;
552 for (const thread of sharing) {
553 visited.add(thread.id);
554 yield* threads
555 .dispatch({
556 type: "thread.metadata.update",
557 commandId: CommandId.make(`${input.commandId}:branch-rename:${thread.id}`),
558 threadId: thread.id,
559 branch: renamed.branch,
560 expectedBranch: oldBranch,
561 expectedWorktreePath: worktreeCwd,
562 })
563 .pipe(
564 Effect.catchCause((cause) =>
565 Effect.logWarning("Shared thread worktree branch update failed", {
566 threadId: thread.id,
567 cause,
568 }),
569 ),
570 );
571 }
572 }
573 }),
574 ),
575 Effect.catchCause((cause) =>
576 Effect.logWarning("Thread worktree branch rename failed", {
577 commandId: input.commandId,
578 threadId,
579 oldBranch,
580 cause,
581 }),
582 ),
583 Effect.forkIn(preparationScope),
584 );
585 }
586
587 const cwd = worktreePath ?? project.workspaceRoot;
588 if (runId !== null) {
589 yield* threads
590 .dispatch({
591 type: "prepared-run.progress",
592 commandId: CommandId.make(`${input.commandId}:progress:setup`),
593 threadId,
594 runId,
595 phase: "setup",
596 })
597 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
598 }
599 yield* setupTracker.stageStatus(threadId, "setup-script", "running");
600 const setup = yield* setupScripts
601 .runForThread({
602 threadId,
603 projectId: input.projectId,
604 projectCwd: project.workspaceRoot,
605 worktreePath: cwd,
606 ...(tracked
607 ? {
608 observeCompletion: {
609 onOutputLine: (line: string) =>
610 setupTracker.appendTail(threadId, "setup-script", line),
611 },
612 }
613 : {}),
614 project: {
615 id: project.id,
616 workspaceRoot: project.workspaceRoot,
617 scripts: project.scripts,
618 },
619 })
620 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
621
622 let awaitAsyncSetup = Effect.void;
623 if (setup.status === "started") {
624 setupTerminalId = setup.terminalId;
625 yield* setupTracker.update(threadId, (snapshot) => ({
626 ...snapshot,
627 setupScript: {
628 name: setup.scriptName,
629 command: setup.scriptCommand,
630 terminalId: setup.terminalId,
631 },
632 }));
633 if (setup.completion) {
634 const awaitCompletion = Effect.gen(function* () {
635 const completion = yield* setup.completion!;
636 yield* setupTracker.stage(threadId, "setup-script", {
637 status: completion.exitCode === 0 ? "done" : "failed",
638 detail: `exited with ${completion.exitCode ?? "no exit code"}`,
639 });
640 if (completion.exitCode !== 0 && !setup.async)
641 return yield* mapError(
642 input,
643 "run-setup-script",
644 threadId,
645 )(`Setup script exited with ${completion.exitCode ?? "no exit code"}.`);
646 });
647 if (setup.async) {
648 awaitAsyncSetup = awaitCompletion.pipe(
649 Effect.catchCause((cause) =>
650 setupTracker.stage(threadId, "setup-script", {
651 status: "failed",
652 detail: failureDetail(Cause.squash(cause)),
653 }),
654 ),
655 );
656 } else {
657 yield* awaitCompletion;
658 }
659 } else {
660 yield* setupTracker.stageStatus(threadId, "setup-script", "done");
661 }
662 } else {
663 yield* setupTracker.stageStatus(threadId, "setup-script", "skipped");
664 }
665 yield* setupTracker.markUncancellable(threadId);
666 yield* setupTracker.stageStatus(threadId, "agent", "running");
667 if (runId !== null) {
668 yield* threads
669 .dispatch({
670 type: "prepared-run.release",
671 commandId: CommandId.make(`${input.commandId}:release`),
672 threadId,
673 runId,
674 })
675 .pipe(
676 Effect.mapError(mapError(input, "release-run", threadId)),
677 Effect.tap(() =>
678 Effect.sync(() => {
679 runReleased = true;
680 }),
681 ),
682 Effect.uninterruptible,
683 );
684 }
685 yield* setupTracker.stageStatus(threadId, "agent", "done");
686 yield* awaitAsyncSetup;
687 yield* setupTracker.finish(threadId, "done");
688 }).pipe(
689 Effect.onError((cause) =>
690 Effect.gen(function* () {
691 const cancelled = Cause.hasInterruptsOnly(cause);
692 yield* setupTracker.finish(
693 threadId,
694 cancelled ? "cancelled" : "failed",
695 cancelled ? null : failureDetail(Cause.squash(cause)),
696 );
697 if (cancelled && setupTerminalId)
698 yield* terminals
699 .close({ threadId, terminalId: setupTerminalId, deleteHistory: true })
700 .pipe(Effect.ignore);
701 if (
702 tracked &&
703 createdWorktreePath &&
704 ((cancelled && !runReleased) || !workspaceRecorded)
705 ) {
706 const removedPath = createdWorktreePath;
707 // The thread forgets the worktree only once it is gone; a failed
708 // removal leaves the directory for the user to clean up rather than
709 // reusing a checkout that may be half written.
710 yield* git
711 .removeWorktree({ cwd: project.workspaceRoot, path: removedPath, force: true })
712 .pipe(
713 Effect.andThen(
714 threads
715 .dispatch({
716 type: "thread.metadata.update",
717 commandId: CommandId.make(`${input.commandId}:cancel-workspace`),
718 threadId,
719 worktreePath: null,
720 branch: null,
721 })
722 .pipe(Effect.ignore),
723 ),
724 Effect.catchCause((removeCause) =>
725 Effect.logWarning("Failed to remove an abandoned thread worktree", {
726 commandId: input.commandId,
727 threadId,
728 path: removedPath,
729 cause: removeCause,
730 }),
731 ),
732 );
733 }
734 }),
735 ),
736 );
737 });
738
739 const failPreparedRun = (
740 input: Pick<PreparationInput, "commandId">,
741 threadId: ThreadId,
742 runId: RunId | null,
743 cause: unknown,
744 ) =>
745 runId === null
746 ? Effect.logWarning("Thread workspace preparation failed", {
747 commandId: input.commandId,
748 threadId,
749 cause,
750 })
751 : threads
752 .dispatch({
753 type: "prepared-run.fail",
754 commandId: CommandId.make(`${input.commandId}:fail`),
755 threadId,
756 runId,
757 failure: makeProviderFailure({
758 cause,
759 message: failureDetail(cause),
760 class: "validation_error",
761 retryable: false,
762 }),
763 })
764 .pipe(
765 Effect.catchCause((persistCause) =>
766 Effect.logWarning("Failed to persist thread workspace preparation failure", {
767 commandId: input.commandId,
768 threadId,
769 cause,
770 persistCause,
771 }),
772 ),
773 );
774
775 const reservePreparation = (commandId: CommandId) =>
776 Ref.modify(scheduledLaunches, (scheduled) => {
777 if (scheduled.has(commandId)) return [false, scheduled] as const;
778 const next = new Set(scheduled);
779 next.add(commandId);
780 return [true, next] as const;
781 });
782
783 const releasePreparation = (commandId: CommandId) =>
784 Ref.update(scheduledLaunches, (scheduled) => {
785 const next = new Set(scheduled);
786 next.delete(commandId);
787 return next;
788 });
789
790 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
791 input: PreparationInput,
792 threadId: ThreadId,
793 runId: RunId | null,
794 ) {
795 const preparation = Effect.gen(function* () {
796 const prepare = prepareInBackground(input, threadId, runId);
797 if (
798 runId === null ||
799 (input.workspaceStrategy.type !== "worktree" && input.reusedWorktree === undefined)
800 ) {
801 return yield* prepare;
802 }
803 const afterSequence = yield* threads.getThreadEventSequence(threadId);
804 const projection = yield* threads.getThreadRecords(threadId, ["runs"]);
805 if (projection.runs.find((run) => run.id === runId)?.status !== "preparing") return;
806 const interruption = threads
807 .streamStoredEventsFrom({ threadId, afterSequence, eventType: "run.updated" })
808 .pipe(
809 Stream.filter(
810 (stored) =>
811 stored.event.type === "run.updated" &&
812 stored.event.payload.id === runId &&
813 (stored.event.payload.status === "interrupted" ||
814 stored.event.payload.status === "cancelled"),
815 ),
816 Stream.runHead,
817 Effect.flatMap((event) => (Option.isSome(event) ? Effect.interrupt : Effect.never)),
818 );
819 yield* Effect.raceFirst(prepare, interruption);
820 });
821 yield* preparation.pipe(
822 Effect.onError((cause) =>
823 failPreparedRun(
824 input,
825 threadId,
826 runId,
827 Cause.hasInterruptsOnly(cause) ? "Worktree setup cancelled." : Cause.squash(cause),
828 ),
829 ),
830 Effect.ignoreCause,
831 Effect.ensuring(releasePreparation(input.commandId)),
832 Effect.forkIn(preparationScope),
833 );
834 });
835
836 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
837 function* (input) {
838 yield* ProjectCloneTracker.rejectCommandsDuringClone(cloneTracker, {
839 type: "thread.create",
840 projectId: input.projectId,
841 }).pipe(Effect.mapError(mapError(input, "resolve-project")));
842 const project = yield* projects.getById(input.projectId).pipe(
843 Effect.mapError(mapError(input, "resolve-project")),
844 Effect.flatMap(
845 Option.match({
846 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
847 onSome: Effect.succeed,
848 }),
849 ),
850 );
851 if (input.reuseExistingThread === true && input.threadId === undefined) {
852 return yield* mapError(
853 input,
854 "update-thread",
855 )("Reusing an existing thread requires a thread id.");
856 }
857
858 const launchReceipt = yield* readReceipt(input, input.commandId);
859 yield* threads.assertProviderInstanceEnabled({
860 projectId: input.projectId,
861 commandId: input.commandId,
862 instanceId: input.modelSelection.instanceId,
863 });
864 return yield* Effect.gen(function* () {
865 // A retried launch has no client-supplied id to replay against, so
866 // recover the thread id its accepted create was recorded under before
867 // allocating another one; a fresh id would only collide with the
868 // recorded receipt.
869 const reusableLaunchReceipt =
870 input.threadId === undefined &&
871 Option.isSome(launchReceipt) &&
872 launchReceipt.value.status === "accepted" &&
873 launchReceipt.value.commandType === "thread.create"
874 ? launchReceipt.value
875 : undefined;
876 const candidateThreadId =
877 input.threadId ??
878 reusableLaunchReceipt?.threadId ??
879 (yield* ids.allocate
880 .thread({ projectId: input.projectId })
881 .pipe(Effect.mapError(mapError(input, "create-thread"))));
882
883 if (reusableLaunchReceipt !== undefined) {
884 const shell = yield* threads
885 .getThreadShell(candidateThreadId)
886 .pipe(Effect.mapError(mapError(input, "create-thread", candidateThreadId)));
887 if (shell === null) {
888 return yield* mapError(input, "create-thread", candidateThreadId)("Thread not found.");
889 }
890 if (shell.projectId !== input.projectId) {
891 return yield* mapError(
892 input,
893 "resolve-project",
894 candidateThreadId,
895 )("Project identity changed.");
896 }
897 }
898
899 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
900 yield* validateReusableThread(input, candidateThreadId);
901 }
902
903 // A Scratch thread launched at the project root runs in a folder of its
904 // own. Only the first attempt claims one; a retry replays its create.
905 const workspaceStrategy: ThreadLaunchWorkspaceStrategy =
906 input.workspaceStrategy.type === "root" && Option.isNone(launchReceipt)
907 ? Option.match(
908 yield* managedFolders
909 .folderForThread({
910 projectId: input.projectId,
911 threadId: candidateThreadId,
912 text: input.initialMessage?.text ?? input.title,
913 })
914 .pipe(Effect.mapError(mapError(input, "provision-worktree", candidateThreadId))),
915 {
916 onNone: () => input.workspaceStrategy,
917 onSome: (worktreePath) => ({ type: "existing_worktree", worktreePath }),
918 },
919 )
920 : input.workspaceStrategy;
921 const initialBranch = workspaceStrategy.branch ?? null;
922 const initialWorktreePath =
923 workspaceStrategy.type === "existing_worktree" ? workspaceStrategy.worktreePath : null;
924 const claimDispatch =
925 input.reuseExistingThread === true
926 ? threads.dispatch({
927 type: "thread.metadata.update",
928 commandId: input.commandId,
929 threadId: candidateThreadId,
930 expectedEmpty: true,
931 })
932 : threads.dispatch({
933 type: "thread.create",
934 commandId: input.commandId,
935 threadId: candidateThreadId,
936 projectId: input.projectId,
937 title: input.title,
938 modelSelection: input.modelSelection,
939 runtimeMode: input.runtimeMode,
940 interactionMode: input.interactionMode,
941 branch: initialBranch,
942 worktreePath: initialWorktreePath,
943 ...(input.importedNativeThread === undefined
944 ? {}
945 : { importedNativeThread: input.importedNativeThread }),
946 createdBy: input.createdBy,
947 creationSource: input.creationSource,
948 });
949 const claimed = yield* claimDispatch.pipe(
950 Effect.mapError(
951 mapError(
952 input,
953 input.reuseExistingThread === true ? "update-thread" : "create-thread",
954 candidateThreadId,
955 ),
956 ),
957 );
958 const threadId =
959 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
960 .threadId ?? candidateThreadId;
961 if (project.id !== input.projectId) {
962 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
963 }
964
965 let runId: RunId | null = null;
966 let messageWasAlreadyAccepted = false;
967 if (input.initialMessage !== undefined) {
968 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
969 const messageReceipt = yield* readReceipt(input, messageCommandId);
970 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
971 const messageId =
972 input.initialMessage.messageId ??
973 (yield* ids.allocate
974 .message({ threadId, ordinal: 1 })
975 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
976 const dispatched = yield* threads
977 .dispatch({
978 type: "message.dispatch",
979 commandId: messageCommandId,
980 threadId,
981 messageId,
982 text: input.initialMessage.text,
983 ...(input.initialMessage.scheduledTaskId === undefined
984 ? {}
985 : { scheduledTaskId: input.initialMessage.scheduledTaskId }),
986 ...(input.initialMessage.senderThreadId === undefined
987 ? {}
988 : { senderThreadId: input.initialMessage.senderThreadId }),
989 attachments: input.initialMessage.attachments,
990 ...(input.initialMessage.context ? { context: input.initialMessage.context } : {}),
991 ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
992 modelSelection: input.modelSelection,
993 dispatchMode: { type: "defer_start", workspaceStrategy },
994 createdBy: input.createdBy,
995 creationSource: input.creationSource,
996 })
997 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
998 const runCreated = dispatched.storedEvents.find(
999 (stored) => stored.event.type === "run.created",
1000 );
1001 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
1002 if (runId === null) {
1003 return yield* mapError(
1004 input,
1005 "dispatch-message",
1006 threadId,
1007 )("Initial message was accepted without a durable run.");
1008 }
1009 }
1010
1011 const projection = yield* threads
1012 .getThreadProjection(threadId)
1013 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
1014 const runIsPreparing =
1015 runId !== null &&
1016 projection.runs.some((run) => run.id === runId && run.status === "preparing");
1017 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing;
1018 // A retried root launch prepares the folder its first attempt bound, so
1019 // a Scratch thread keeps its own. Other root launches bind no folder.
1020 const boundWorktreePath = projection.thread.worktreePath;
1021 const preparationStrategy: ThreadLaunchWorkspaceStrategy =
1022 Option.isSome(launchReceipt) &&
1023 workspaceStrategy.type === "root" &&
1024 boundWorktreePath !== null
1025 ? {
1026 type: "existing_worktree",
1027 worktreePath: boundWorktreePath,
1028 branch: workspaceStrategy.branch,
1029 }
1030 : workspaceStrategy;
1031 if (shouldSchedule) {
1032 const ownsPreparation = yield* reservePreparation(input.commandId);
1033 if (ownsPreparation) {
1034 yield* Effect.gen(function* () {
1035 const preparationStillRequired =
1036 runId === null
1037 ? true
1038 : yield* threads.getThreadRecords(threadId, ["runs"], { runIds: [runId] }).pipe(
1039 Effect.map((current) =>
1040 current.runs.some((run) => run.id === runId && run.status === "preparing"),
1041 ),
1042 Effect.mapError(mapError(input, "update-thread", threadId)),
1043 );
1044 if (preparationStillRequired) {
1045 yield* schedulePreparation(
1046 { ...input, workspaceStrategy: preparationStrategy },
1047 threadId,
1048 runId,
1049 );
1050 } else {
1051 yield* releasePreparation(input.commandId);
1052 }
1053 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
1054 }
1055 }
1056
1057 return {
1058 threadId,
1059 projection,
1060 resumed: Option.isSome(launchReceipt) || messageWasAlreadyAccepted,
1061 };
1062 });
1063 },
1064 );
1065
1066 const prepareRun: ThreadLaunchService["Service"]["prepareRun"] = Effect.fn(
1067 "ThreadLaunchService.prepareRun",
1068 )(function* (input) {
1069 const scheduled = yield* Effect.gen(function* () {
1070 const projection = yield* threads.getThreadProjection(input.threadId);
1071 const run = projection.runs.find((candidate) => candidate.id === input.runId);
1072 const workspacePreparation = run?.workspacePreparation;
1073 if (run?.status !== "preparing" || workspacePreparation === undefined) return;
1074 if (!(yield* reservePreparation(input.commandId))) return;
1075 yield* scheduleRunPreparation(input, projection, run, workspacePreparation).pipe(
1076 Effect.onError(() => releasePreparation(input.commandId)),
1077 );
1078 }).pipe(Effect.exit);
1079 if (Exit.isFailure(scheduled)) {
1080 yield* failPreparedRun(input, input.threadId, input.runId, Cause.squash(scheduled.cause));
1081 }
1082 });
1083
1084 const retryPreparation: ThreadLaunchService["Service"]["retryPreparation"] = Effect.fn(
1085 "ThreadLaunchService.retryPreparation",
1086 )(function* (input) {
1087 const dispatched = yield* threads.dispatch({
1088 type: "prepared-run.retry",
1089 commandId: input.commandId,
1090 threadId: input.threadId,
1091 runId: input.runId,
1092 });
1093 yield* prepareRun(input);
1094 return dispatched;
1095 });
1096
1097 const scheduleRunPreparation = (
1098 input: ThreadLaunchPreparationInput,
1099 projection: OrchestrationV2ThreadProjection,
1100 run: OrchestrationV2ThreadProjection["runs"][number],
1101 workspacePreparation: ThreadLaunchWorkspaceStrategy,
1102 ) => {
1103 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
1104 // A worktree the failed attempt already created is reused, not created again.
1105 const reuse =
1106 workspacePreparation.type === "worktree" &&
1107 projection.thread.worktreePath !== null &&
1108 projection.thread.branch !== null
1109 ? {
1110 strategy: {
1111 type: "existing_worktree" as const,
1112 worktreePath: projection.thread.worktreePath,
1113 branch: projection.thread.branch,
1114 },
1115 reusedWorktree: { baseRef: workspacePreparation.baseRef },
1116 }
1117 : null;
1118 return schedulePreparation(
1119 {
1120 commandId: input.commandId,
1121 projectId: projection.thread.projectId,
1122 workspaceStrategy: reuse?.strategy ?? workspacePreparation,
1123 ...(reuse === null ? {} : { reusedWorktree: reuse.reusedWorktree }),
1124 ...(message === undefined
1125 ? {}
1126 : {
1127 initialMessage: {
1128 text: message.text,
1129 attachments: message.attachments,
1130 ...(message.context ? { context: message.context } : {}),
1131 },
1132 }),
1133 },
1134 input.threadId,
1135 run.id,
1136 );
1137 };
1138
1139 return ThreadLaunchService.of({ launch, checkWorktreeBase, retryPreparation, prepareRun });
1140});
1141
1142export const layer = Layer.effect(ThreadLaunchService, make);