Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadLaunchService.ts

1,129 lines43.1 KB

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