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 = (cwd: string, message: ThreadLaunchInitialMessage) =>
334 Effect.gen(function* () {
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 const requestedBranch = input.workspaceStrategy.branch;
369 let branch: string | null;
370 if (input.workspaceStrategy.type === "worktree" && requestedBranch === undefined) {
371 const uuid = yield* randomUuidV4;
372 branch = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
373 } else {
374 branch = requestedBranch ?? null;
375 }
376 let worktreePath =
377 input.workspaceStrategy.type === "existing_worktree"
378 ? input.workspaceStrategy.worktreePath
379 : null;
380 if (input.workspaceStrategy.type === "worktree") {
381 if (runId !== null) {
382 yield* threads
383 .dispatch({
384 type: "prepared-run.progress",
385 commandId: CommandId.make(`${input.commandId}:progress:worktree`),
386 threadId,
387 runId,
388 phase: "worktree",
389 })
390 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
391 }
392 let startRef = input.workspaceStrategy.baseRef;
393 let baseRefName = input.workspaceStrategy.baseRef;
394 const shouldFetch =
395 input.workspaceStrategy.startFromOrigin === true &&
396 (yield* git
397 .resolveWorktreeBaseRemote({
398 cwd: project.workspaceRoot,
399 refName: input.workspaceStrategy.baseRef,
400 })
401 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)))) !== null;
402 yield* setupTracker.stageStatus(threadId, "fetch", shouldFetch ? "running" : "skipped");
403 if (shouldFetch) {
404 const remoteBase = yield* git
405 .fetchWorktreeBaseCommit({
406 cwd: project.workspaceRoot,
407 refName: input.workspaceStrategy.baseRef,
408 })
409 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
410 if (remoteBase !== null) {
411 startRef = remoteBase.commitSha;
412 baseRefName = `refs/remotes/${remoteBase.remoteRefName}`;
413 }
414 }
415 if (shouldFetch) yield* setupTracker.stageStatus(threadId, "fetch", "done");
416 if (
417 branch !== null &&
418 isTemporaryWorktreeBranch(branch) &&
419 (yield* git
420 .hasCommit({
421 cwd: project.workspaceRoot,
422 refName: `refs/heads/${WORKTREE_BRANCH_PREFIX}`,
423 })
424 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))))
425 ) {
426 branch = flattenTemporaryWorktreeBranchName(branch);
427 }
428 yield* setupTracker.stageStatus(threadId, "checkout", "running");
429 const worktree = yield* git
430 .createWorktree(
431 {
432 cwd: project.workspaceRoot,
433 refName: startRef,
434 newRefName: branch!,
435 baseRefName,
436 path: null,
437 },
438 {
439 progress: {
440 onWorktreeClaimed: (path) =>
441 Effect.sync(() => {
442 createdWorktreePath = path;
443 }),
444 onCheckoutProgress: (progress) =>
445 setupTracker.stage(threadId, "checkout", { percent: progress.percent }),
446 },
447 },
448 )
449 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
450 worktreePath = worktree.worktree.path;
451 branch = worktree.worktree.refName;
452 createdWorktreePath = worktreePath;
453 yield* setupTracker.update(threadId, (snapshot) => ({ ...snapshot, worktreePath, branch }));
454 yield* setupTracker.stageStatus(threadId, "checkout", "done");
455 }
456
457 // A reused worktree is already recorded, and rewriting it could undo
458 // the first attempt's branch rename.
459 if (reused === undefined) {
460 yield* threads
461 .dispatch({
462 type: "thread.metadata.update",
463 commandId: CommandId.make(`${input.commandId}:workspace`),
464 threadId,
465 branch,
466 worktreePath,
467 })
468 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
469 }
470 workspaceRecorded = true;
471
472 if (
473 reused === undefined &&
474 worktreePath !== null &&
475 branch !== null &&
476 initialMessage !== undefined &&
477 isTemporaryWorktreeBranch(branch)
478 ) {
479 const oldBranch = branch;
480 const worktreeCwd = worktreePath;
481 branchRename = yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe(
482 Effect.flatMap(({ branch: newBranch, exactName }) =>
483 git.renameBranch({
484 cwd: worktreeCwd,
485 oldBranch,
486 newBranch,
487 ...(exactName ? { exactName: true } : {}),
488 }),
489 ),
490 Effect.flatMap((renamed) =>
491 Effect.gen(function* () {
492 yield* threads
493 .dispatch({
494 type: "thread.metadata.update",
495 commandId: CommandId.make(`${input.commandId}:branch-rename`),
496 threadId,
497 branch: renamed.branch,
498 worktreePath: worktreeCwd,
499 expectedBranch: oldBranch,
500 expectedWorktreePath: worktreeCwd,
501 })
502 .pipe(
503 Effect.catchCause((cause) =>
504 Effect.logWarning("Parent thread worktree branch update failed", {
505 threadId,
506 cause,
507 }),
508 ),
509 );
510 // Updating the parent first makes later subagents inherit the new name.
511 // Re-read after each pass for children of subagents updated in that pass.
512 const visited = new Set([threadId]);
513 while (true) {
514 const snapshot = yield* threads.getShellSnapshot();
515 const sharing = [...snapshot.threads, ...snapshot.archivedThreads].filter(
516 (thread) =>
517 !visited.has(thread.id) &&
518 thread.worktreePath === worktreeCwd &&
519 thread.branch === oldBranch,
520 );
521 if (sharing.length === 0) break;
522 for (const thread of sharing) {
523 visited.add(thread.id);
524 yield* threads
525 .dispatch({
526 type: "thread.metadata.update",
527 commandId: CommandId.make(`${input.commandId}:branch-rename:${thread.id}`),
528 threadId: thread.id,
529 branch: renamed.branch,
530 expectedBranch: oldBranch,
531 expectedWorktreePath: worktreeCwd,
532 })
533 .pipe(
534 Effect.catchCause((cause) =>
535 Effect.logWarning("Shared thread worktree branch update failed", {
536 threadId: thread.id,
537 cause,
538 }),
539 ),
540 );
541 }
542 }
543 }),
544 ),
545 Effect.catchCause((cause) =>
546 Effect.logWarning("Thread worktree branch rename failed", {
547 commandId: input.commandId,
548 threadId,
549 oldBranch,
550 cause,
551 }),
552 ),
553 Effect.forkIn(preparationScope),
554 );
555 }
556
557 if (runId !== null && worktreePath !== null) {
558 yield* threads
559 .dispatch({
560 type: "prepared-run.progress",
561 commandId: CommandId.make(`${input.commandId}:progress:setup`),
562 threadId,
563 runId,
564 phase: "setup",
565 })
566 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
567 }
568 yield* setupTracker.stageStatus(threadId, "setup-script", "running");
569 const setup =
570 worktreePath === null
571 ? ({ status: "no-script" } as const)
572 : yield* setupScripts
573 .runForThread({
574 threadId,
575 projectId: input.projectId,
576 projectCwd: project.workspaceRoot,
577 worktreePath,
578 ...(tracked
579 ? {
580 observeCompletion: {
581 onOutputLine: (line: string) =>
582 setupTracker.appendTail(threadId, "setup-script", line),
583 },
584 }
585 : {}),
586 project: {
587 id: project.id,
588 workspaceRoot: project.workspaceRoot,
589 scripts: project.scripts,
590 },
591 })
592 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
593
594 let awaitAsyncSetup = Effect.void;
595 if (setup.status === "started") {
596 setupTerminalId = setup.terminalId;
597 yield* setupTracker.update(threadId, (snapshot) => ({
598 ...snapshot,
599 setupScript: {
600 name: setup.scriptName,
601 command: setup.scriptCommand,
602 terminalId: setup.terminalId,
603 },
604 }));
605 if (setup.completion) {
606 const awaitCompletion = Effect.gen(function* () {
607 const completion = yield* setup.completion!;
608 yield* setupTracker.stage(threadId, "setup-script", {
609 status: completion.exitCode === 0 ? "done" : "failed",
610 detail: `exited with ${completion.exitCode ?? "no exit code"}`,
611 });
612 if (completion.exitCode !== 0 && !setup.async)
613 return yield* mapError(
614 input,
615 "run-setup-script",
616 threadId,
617 )(`Setup script exited with ${completion.exitCode ?? "no exit code"}.`);
618 });
619 if (setup.async) {
620 awaitAsyncSetup = awaitCompletion.pipe(
621 Effect.catchCause((cause) =>
622 setupTracker.stage(threadId, "setup-script", {
623 status: "failed",
624 detail: failureDetail(Cause.squash(cause)),
625 }),
626 ),
627 );
628 } else {
629 yield* awaitCompletion;
630 }
631 } else {
632 yield* setupTracker.stageStatus(threadId, "setup-script", "done");
633 }
634 } else {
635 yield* setupTracker.stageStatus(threadId, "setup-script", "skipped");
636 }
637 yield* setupTracker.markUncancellable(threadId);
638 yield* setupTracker.stageStatus(threadId, "agent", "running");
639 if (runId !== null) {
640 yield* threads
641 .dispatch({
642 type: "prepared-run.release",
643 commandId: CommandId.make(`${input.commandId}:release`),
644 threadId,
645 runId,
646 })
647 .pipe(
648 Effect.mapError(mapError(input, "release-run", threadId)),
649 Effect.tap(() =>
650 Effect.sync(() => {
651 runReleased = true;
652 }),
653 ),
654 Effect.uninterruptible,
655 );
656 }
657 yield* setupTracker.stageStatus(threadId, "agent", "done");
658 yield* awaitAsyncSetup;
659 yield* setupTracker.finish(threadId, "done");
660 }).pipe(
661 Effect.onError((cause) =>
662 Effect.gen(function* () {
663 const cancelled = Cause.hasInterruptsOnly(cause);
664 yield* setupTracker.finish(
665 threadId,
666 cancelled ? "cancelled" : "failed",
667 cancelled ? null : failureDetail(Cause.squash(cause)),
668 );
669 if (cancelled && setupTerminalId)
670 yield* terminals
671 .close({ threadId, terminalId: setupTerminalId, deleteHistory: true })
672 .pipe(Effect.ignore);
673 if (
674 tracked &&
675 createdWorktreePath &&
676 ((cancelled && !runReleased) || !workspaceRecorded)
677 ) {
678 if (branchRename !== null) yield* Fiber.interrupt(branchRename);
679 const removedPath = createdWorktreePath;
680 // The thread forgets the worktree only once it is gone; a failed
681 // removal leaves the directory for the user to clean up rather than
682 // reusing a checkout that may be half written.
683 yield* git
684 .removeWorktree({ cwd: project.workspaceRoot, path: removedPath, force: true })
685 .pipe(
686 Effect.andThen(
687 threads
688 .dispatch({
689 type: "thread.metadata.update",
690 commandId: CommandId.make(`${input.commandId}:cancel-workspace`),
691 threadId,
692 worktreePath: null,
693 branch: null,
694 })
695 .pipe(Effect.ignore),
696 ),
697 Effect.catchCause((removeCause) =>
698 Effect.logWarning("Failed to remove an abandoned thread worktree", {
699 commandId: input.commandId,
700 threadId,
701 path: removedPath,
702 cause: removeCause,
703 }),
704 ),
705 );
706 }
707 }),
708 ),
709 );
710 });
711
712 const failPreparedRun = (
713 input: Pick<PreparationInput, "commandId">,
714 threadId: ThreadId,
715 runId: RunId | null,
716 cause: unknown,
717 ) =>
718 runId === null
719 ? Effect.logWarning("Thread workspace preparation failed", {
720 commandId: input.commandId,
721 threadId,
722 cause,
723 })
724 : threads
725 .dispatch({
726 type: "prepared-run.fail",
727 commandId: CommandId.make(`${input.commandId}:fail`),
728 threadId,
729 runId,
730 failure: makeProviderFailure({
731 cause,
732 message: failureDetail(cause),
733 class: "validation_error",
734 retryable: false,
735 }),
736 })
737 .pipe(
738 Effect.catchCause((persistCause) =>
739 Effect.logWarning("Failed to persist thread workspace preparation failure", {
740 commandId: input.commandId,
741 threadId,
742 cause,
743 persistCause,
744 }),
745 ),
746 );
747
748 const reservePreparation = (commandId: CommandId) =>
749 Ref.modify(scheduledLaunches, (scheduled) => {
750 if (scheduled.has(commandId)) return [false, scheduled] as const;
751 const next = new Set(scheduled);
752 next.add(commandId);
753 return [true, next] as const;
754 });
755
756 const releasePreparation = (commandId: CommandId) =>
757 Ref.update(scheduledLaunches, (scheduled) => {
758 const next = new Set(scheduled);
759 next.delete(commandId);
760 return next;
761 });
762
763 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
764 input: PreparationInput,
765 threadId: ThreadId,
766 runId: RunId | null,
767 ) {
768 const preparation = Effect.gen(function* () {
769 const prepare = prepareInBackground(input, threadId, runId);
770 if (
771 runId === null ||
772 (input.workspaceStrategy.type !== "worktree" && input.reusedWorktree === undefined)
773 ) {
774 return yield* prepare;
775 }
776 const afterSequence = yield* threads.getThreadEventSequence(threadId);
777 const projection = yield* threads.getThreadRecords(threadId, ["runs"]);
778 if (projection.runs.find((run) => run.id === runId)?.status !== "preparing") return;
779 const interruption = threads
780 .streamStoredEventsFrom({ threadId, afterSequence, eventType: "run.updated" })
781 .pipe(
782 Stream.filter(
783 (stored) =>
784 stored.event.type === "run.updated" &&
785 stored.event.payload.id === runId &&
786 (stored.event.payload.status === "interrupted" ||
787 stored.event.payload.status === "cancelled"),
788 ),
789 Stream.runHead,
790 Effect.flatMap((event) => (Option.isSome(event) ? Effect.interrupt : Effect.never)),
791 );
792 yield* Effect.raceFirst(prepare, interruption);
793 });
794 yield* preparation.pipe(
795 Effect.onError((cause) =>
796 failPreparedRun(
797 input,
798 threadId,
799 runId,
800 Cause.hasInterruptsOnly(cause) ? "Worktree setup cancelled." : Cause.squash(cause),
801 ),
802 ),
803 Effect.ignoreCause,
804 Effect.ensuring(releasePreparation(input.commandId)),
805 Effect.forkIn(preparationScope),
806 );
807 });
808
809 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
810 function* (request) {
811 // Scratch has no Git repository. Normalize before folder allocation so
812 // durable preparation and retries use the thread's own Scratch folder.
813 const input: ThreadLaunchInput =
814 request.workspaceStrategy.type === "worktree" &&
815 (yield* managedFolders.isScratchProject(request.projectId))
816 ? { ...request, workspaceStrategy: { type: "root" } }
817 : request;
818 yield* ProjectCloneTracker.rejectCommandsDuringClone(cloneTracker, {
819 type: "thread.create",
820 projectId: input.projectId,
821 }).pipe(Effect.mapError(mapError(input, "resolve-project")));
822 const project = yield* projects.getById(input.projectId).pipe(
823 Effect.mapError(mapError(input, "resolve-project")),
824 Effect.flatMap(
825 Option.match({
826 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
827 onSome: Effect.succeed,
828 }),
829 ),
830 );
831 if (input.reuseExistingThread === true && input.threadId === undefined) {
832 return yield* mapError(
833 input,
834 "update-thread",
835 )("Reusing an existing thread requires a thread id.");
836 }
837
838 const launchReceipt = yield* readReceipt(input, input.commandId);
839 yield* threads.assertProviderInstanceEnabled({
840 projectId: input.projectId,
841 commandId: input.commandId,
842 instanceId: input.modelSelection.instanceId,
843 });
844 return yield* Effect.gen(function* () {
845 // A retried launch has no client-supplied id to replay against, so
846 // recover the thread id its accepted create was recorded under before
847 // allocating another one; a fresh id would only collide with the
848 // recorded receipt.
849 const reusableLaunchReceipt =
850 input.threadId === undefined &&
851 Option.isSome(launchReceipt) &&
852 launchReceipt.value.status === "accepted" &&
853 launchReceipt.value.commandType === "thread.create"
854 ? launchReceipt.value
855 : undefined;
856 const candidateThreadId =
857 input.threadId ??
858 reusableLaunchReceipt?.threadId ??
859 (yield* ids.allocate
860 .thread({ projectId: input.projectId })
861 .pipe(Effect.mapError(mapError(input, "create-thread"))));
862
863 if (reusableLaunchReceipt !== undefined) {
864 const shell = yield* threads
865 .getThreadShell(candidateThreadId)
866 .pipe(Effect.mapError(mapError(input, "create-thread", candidateThreadId)));
867 if (shell === null) {
868 return yield* mapError(input, "create-thread", candidateThreadId)("Thread not found.");
869 }
870 if (shell.projectId !== input.projectId) {
871 return yield* mapError(
872 input,
873 "resolve-project",
874 candidateThreadId,
875 )("Project identity changed.");
876 }
877 }
878
879 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
880 yield* validateReusableThread(input, candidateThreadId);
881 }
882
883 const workspaceStrategy: ThreadLaunchWorkspaceStrategy =
884 input.workspaceStrategy.type === "root" && Option.isNone(launchReceipt)
885 ? Option.match(
886 yield* managedFolders
887 .folderForThread({
888 projectId: input.projectId,
889 threadId: candidateThreadId,
890 text: input.initialMessage?.text ?? input.title,
891 })
892 .pipe(Effect.mapError(mapError(input, "provision-worktree", candidateThreadId))),
893 {
894 onNone: () => input.workspaceStrategy,
895 onSome: (worktreePath) => ({ type: "existing_worktree", worktreePath }),
896 },
897 )
898 : input.workspaceStrategy;
899 const initialBranch = workspaceStrategy.branch ?? null;
900 const initialWorktreePath =
901 workspaceStrategy.type === "existing_worktree" ? workspaceStrategy.worktreePath : null;
902 const claimDispatch =
903 input.reuseExistingThread === true
904 ? threads.dispatch({
905 type: "thread.metadata.update",
906 commandId: input.commandId,
907 threadId: candidateThreadId,
908 expectedEmpty: true,
909 })
910 : threads.dispatch({
911 type: "thread.create",
912 commandId: input.commandId,
913 threadId: candidateThreadId,
914 projectId: input.projectId,
915 title: input.title,
916 modelSelection: input.modelSelection,
917 runtimeMode: input.runtimeMode,
918 interactionMode: input.interactionMode,
919 branch: initialBranch,
920 worktreePath: initialWorktreePath,
921 ...(input.importedNativeThread === undefined
922 ? {}
923 : { importedNativeThread: input.importedNativeThread }),
924 createdBy: input.createdBy,
925 creationSource: input.creationSource,
926 });
927 const claimed = yield* claimDispatch.pipe(
928 Effect.mapError(
929 mapError(
930 input,
931 input.reuseExistingThread === true ? "update-thread" : "create-thread",
932 candidateThreadId,
933 ),
934 ),
935 );
936 const threadId =
937 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
938 .threadId ?? candidateThreadId;
939 if (project.id !== input.projectId) {
940 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
941 }
942
943 let runId: RunId | null = null;
944 let messageWasAlreadyAccepted = false;
945 if (input.initialMessage !== undefined) {
946 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
947 const messageReceipt = yield* readReceipt(input, messageCommandId);
948 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
949 const messageId =
950 input.initialMessage.messageId ??
951 (yield* ids.allocate
952 .message({ threadId, ordinal: 1 })
953 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
954 const dispatched = yield* threads
955 .dispatch({
956 type: "message.dispatch",
957 commandId: messageCommandId,
958 threadId,
959 messageId,
960 text: input.initialMessage.text,
961 ...(input.initialMessage.scheduledTaskId === undefined
962 ? {}
963 : { scheduledTaskId: input.initialMessage.scheduledTaskId }),
964 ...(input.initialMessage.senderThreadId === undefined
965 ? {}
966 : { senderThreadId: input.initialMessage.senderThreadId }),
967 attachments: input.initialMessage.attachments,
968 ...(input.initialMessage.context ? { context: input.initialMessage.context } : {}),
969 ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
970 modelSelection: input.modelSelection,
971 dispatchMode: { type: "defer_start", workspaceStrategy },
972 createdBy: input.createdBy,
973 creationSource: input.creationSource,
974 })
975 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
976 const runCreated = dispatched.storedEvents.find(
977 (stored) => stored.event.type === "run.created",
978 );
979 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
980 if (runId === null) {
981 return yield* mapError(
982 input,
983 "dispatch-message",
984 threadId,
985 )("Initial message was accepted without a durable run.");
986 }
987 }
988
989 const projection = yield* threads
990 .getThreadProjection(threadId)
991 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
992 const runIsPreparing =
993 runId !== null &&
994 projection.runs.some((run) => run.id === runId && run.status === "preparing");
995 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing;
996 const boundWorktreePath = projection.thread.worktreePath;
997 const preparationStrategy: ThreadLaunchWorkspaceStrategy =
998 Option.isSome(launchReceipt) &&
999 workspaceStrategy.type === "root" &&
1000 boundWorktreePath !== null
1001 ? {
1002 type: "existing_worktree",
1003 worktreePath: boundWorktreePath,
1004 branch: workspaceStrategy.branch,
1005 }
1006 : workspaceStrategy;
1007 if (shouldSchedule) {
1008 const ownsPreparation = yield* reservePreparation(input.commandId);
1009 if (ownsPreparation) {
1010 yield* Effect.gen(function* () {
1011 const preparationStillRequired =
1012 runId === null
1013 ? true
1014 : yield* threads.getThreadRecords(threadId, ["runs"], { runIds: [runId] }).pipe(
1015 Effect.map((current) =>
1016 current.runs.some((run) => run.id === runId && run.status === "preparing"),
1017 ),
1018 Effect.mapError(mapError(input, "update-thread", threadId)),
1019 );
1020 if (preparationStillRequired) {
1021 yield* schedulePreparation(
1022 { ...input, workspaceStrategy: preparationStrategy },
1023 threadId,
1024 runId,
1025 );
1026 } else {
1027 yield* releasePreparation(input.commandId);
1028 }
1029 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
1030 }
1031 }
1032
1033 return {
1034 threadId,
1035 projection,
1036 resumed: Option.isSome(launchReceipt) || messageWasAlreadyAccepted,
1037 };
1038 });
1039 },
1040 );
1041
1042 const prepareRun: ThreadLaunchService["Service"]["prepareRun"] = Effect.fn(
1043 "ThreadLaunchService.prepareRun",
1044 )(function* (input) {
1045 const scheduled = yield* Effect.gen(function* () {
1046 const projection = yield* threads.getThreadProjection(input.threadId);
1047 const run = projection.runs.find((candidate) => candidate.id === input.runId);
1048 const workspacePreparation = run?.workspacePreparation;
1049 if (run?.status !== "preparing" || workspacePreparation === undefined) return;
1050 if (!(yield* reservePreparation(input.commandId))) return;
1051 yield* scheduleRunPreparation(input, projection, run, workspacePreparation).pipe(
1052 Effect.onError(() => releasePreparation(input.commandId)),
1053 );
1054 }).pipe(Effect.exit);
1055 if (Exit.isFailure(scheduled)) {
1056 yield* failPreparedRun(input, input.threadId, input.runId, Cause.squash(scheduled.cause));
1057 }
1058 });
1059
1060 const retryPreparation: ThreadLaunchService["Service"]["retryPreparation"] = Effect.fn(
1061 "ThreadLaunchService.retryPreparation",
1062 )(function* (input) {
1063 const dispatched = yield* threads.dispatch({
1064 type: "prepared-run.retry",
1065 commandId: input.commandId,
1066 threadId: input.threadId,
1067 runId: input.runId,
1068 });
1069 yield* prepareRun(input);
1070 return dispatched;
1071 });
1072
1073 const scheduleRunPreparation = (
1074 input: ThreadLaunchPreparationInput,
1075 projection: OrchestrationV2ThreadProjection,
1076 run: OrchestrationV2ThreadProjection["runs"][number],
1077 workspacePreparation: ThreadLaunchWorkspaceStrategy,
1078 ) => {
1079 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
1080 const reuse =
1081 workspacePreparation.type === "worktree" &&
1082 projection.thread.worktreePath !== null &&
1083 projection.thread.branch !== null
1084 ? {
1085 strategy: {
1086 type: "existing_worktree" as const,
1087 worktreePath: projection.thread.worktreePath,
1088 branch: projection.thread.branch,
1089 },
1090 reusedWorktree: { baseRef: workspacePreparation.baseRef },
1091 }
1092 : null;
1093 return schedulePreparation(
1094 {
1095 commandId: input.commandId,
1096 projectId: projection.thread.projectId,
1097 workspaceStrategy: reuse?.strategy ?? workspacePreparation,
1098 ...(reuse === null ? {} : { reusedWorktree: reuse.reusedWorktree }),
1099 ...(message === undefined
1100 ? {}
1101 : {
1102 initialMessage: {
1103 text: message.text,
1104 attachments: message.attachments,
1105 ...(message.context ? { context: message.context } : {}),
1106 },
1107 }),
1108 },
1109 input.threadId,
1110 run.id,
1111 );
1112 };
1113
1114 return ThreadLaunchService.of({ launch, checkWorktreeBase, retryPreparation, prepareRun });
1115});
1116
1117export const layer = Layer.effect(ThreadLaunchService, make);