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