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