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