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