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

ThreadLaunchService.ts

1,343 lines52.4 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 OrchestrationV2DelegatedFrom,
13 type OrchestrationV2LinkOrigin,
14 type OrchestrationV2ProviderThreadNativeMetadata,
15 type OrchestrationV2ThreadProjection,
16 type ProviderDriverKind,
17 type ProviderInteractionMode,
18 ProjectId,
19 type RunId,
20 type RuntimeMode,
21 type ScheduledTaskId,
22 ThreadId,
23} from "@t3tools/contracts";
24import * as Cause from "effect/Cause";
25import * as Clock from "effect/Clock";
26import * as Context from "effect/Context";
27import * as DateTime from "effect/DateTime";
28import * as Effect from "effect/Effect";
29import * as Exit from "effect/Exit";
30import * as Fiber from "effect/Fiber";
31import * as Layer from "effect/Layer";
32import * as Option from "effect/Option";
33import * as Ref from "effect/Ref";
34import * as Schema from "effect/Schema";
35import * as Scope from "effect/Scope";
36import * as Stream from "effect/Stream";
37import {
38 buildTemporaryWorktreeBranchName,
39 flattenTemporaryWorktreeBranchName,
40 isTemporaryWorktreeBranch,
41 WORKTREE_BRANCH_PREFIX,
42} from "@t3tools/shared/git";
43​
44import * as GitWorkflow from "../git/GitWorkflowService.ts";
45import { parseGitCloneProgressLine } from "../project/gitCloneProgress.ts";
46import * as ProjectService from "../project/ProjectService.ts";
47import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
48import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
49import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
50import * as ServerSettings from "../serverSettings.ts";
51import * as TextGeneration from "../textGeneration/TextGeneration.ts";
52import * as CommandReceiptStore from "./CommandReceiptStore.ts";
53import * as EventSink from "./EventSink.ts";
54import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
55import type * as Orchestrator from "./Orchestrator.ts";
56import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
57import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
58import { DispatchModeLimit } from "./DispatchModeLimit.ts";
59import * as ThreadManagement from "./ThreadManagementService.ts";
60​
61export type ThreadLaunchWorkspaceStrategy =
62 | { readonly type: "root"; readonly branch?: string | undefined }
63 | {
64 readonly type: "existing_worktree";
65 readonly worktreePath: string;
66 readonly branch?: string | undefined;
67 }
68 | {
69 readonly type: "worktree";
70 readonly baseRef: string;
71 readonly branch?: string | undefined;
72 readonly startFromOrigin?: boolean | undefined;
73 };
74​
75export interface ThreadLaunchInitialMessage {
76 readonly messageId?: MessageId;
77 readonly scheduledTaskId?: ScheduledTaskId;
78 readonly senderThreadId?: ThreadId;
79 readonly text: string;
80 readonly attachments: ReadonlyArray<ChatAttachment>;
81 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
83​
84export interface ThreadLaunchInput {
85 readonly commandId: CommandId;
86 readonly threadId?: ThreadId;
87 readonly reuseExistingThread?: boolean;
88 readonly projectId: ProjectId;
89 readonly title: string;
90 readonly generateTitle?: boolean;
91 readonly modelSelection: ModelSelection;
92 readonly runtimeMode: RuntimeMode;
93 readonly interactionMode: ProviderInteractionMode;
94 readonly workspaceStrategy: ThreadLaunchWorkspaceStrategy;
95 readonly initialMessage?: ThreadLaunchInitialMessage;
96 readonly importedNativeThread?: {
97 readonly ref: {
98 readonly driver: ProviderDriverKind;
99 readonly nativeId: string;
100 readonly strength: "strong";
101 };
102 readonly metadata?: OrchestrationV2ProviderThreadNativeMetadata;
103 };
104 readonly createdBy: OrchestrationV2Actor;
105 readonly creationSource: OrchestrationV2CreationSource;
106 /** The linked environment this launch is for, if one asked for it. */
107 readonly linkOrigin?: OrchestrationV2LinkOrigin;
108 /** The parent there, when that environment's agent delegated this as a task. */
109 readonly delegatedFrom?: OrchestrationV2DelegatedFrom;
111​
112type PreparationInput = Pick<
113 ThreadLaunchInput,
114 "commandId" | "projectId" | "workspaceStrategy" | "initialMessage"
115> & {
116 readonly reusedWorktree?: { readonly baseRef: string };
117};
118​
119export interface ThreadLaunchPreparationInput {
120 readonly commandId: CommandId;
121 readonly threadId: ThreadId;
122 readonly runId: RunId;
124​
125export interface ThreadLaunchResult {
126 readonly threadId: ThreadId;
127 readonly projection: OrchestrationV2ThreadProjection;
128 /** The launch's last write (the initial message, else the thread claim) was accepted before this call. */
129 readonly resumed: boolean;
130 readonly sequence?: number;
132​
133export class ThreadLaunchError extends Schema.TaggedError<ThreadLaunchError>()(
134 "ThreadLaunchError",
135 {
136 operation: Schema.Literals([
137 "resolve-project",
138 "read-receipt",
139 "generate-metadata",
140 "provision-worktree",
141 "run-setup-script",
142 "create-thread",
143 "update-thread",
144 "dispatch-message",
145 "release-run",
146 "fail-run",
147 ]),
148 commandId: CommandId,
149 projectId: ProjectId,
150 threadId: Schema.optional(ThreadId),
151 cause: Schema.Defect(),
152 },
153) {
154 override get message(): string {
155 return `Thread launch ${this.commandId} failed during ${this.operation}.`;
156 }
158​
159export class ThreadLaunchBaseRefError extends Schema.TaggedError<ThreadLaunchBaseRefError>()(
160 "ThreadLaunchBaseRefError",
161 {
162 projectId: ProjectId,
163 projectTitle: Schema.String,
164 workspaceRoot: Schema.String,
165 baseRef: Schema.String,
166 },
167) {
168 override get message(): string {
169 return `Base ref "${this.baseRef}" does not resolve to a commit in project "${this.projectTitle}" (${this.workspaceRoot}).`;
170 }
172​
173export class ThreadLaunchBranchConflictError extends Schema.TaggedError<ThreadLaunchBranchConflictError>()(
174 "ThreadLaunchBranchConflictError",
175 {
176 projectId: ProjectId,
177 projectTitle: Schema.String,
178 branch: Schema.String,
179 conflictingBranch: Schema.String,
180 },
181) {
182 override get message(): string {
183 return `Branch "${this.branch}" cannot be created in project "${this.projectTitle}": branch "${this.conflictingBranch}" exists.`;
184 }
186​
187export class ThreadLaunchNotRepositoryError extends Schema.TaggedError<ThreadLaunchNotRepositoryError>()(
188 "ThreadLaunchNotRepositoryError",
189 {
190 projectId: ProjectId,
191 projectTitle: Schema.String,
192 workspaceRoot: Schema.String,
193 },
194) {
195 override get message(): string {
196 return `Project "${this.projectTitle}" (${this.workspaceRoot}) is not a Git repository.`;
197 }
199​
200export class ThreadLaunchService extends Context.Service<
201 ThreadLaunchService,
202 {
203 readonly launch: (
204 input: ThreadLaunchInput,
205 ) => Effect.Effect<
206 ThreadLaunchResult,
207 ThreadLaunchError | ThreadManagement.ThreadManagementProviderInstanceDisabledError
208 >;
209 /** Check a new worktree's base ref and branch name before creation for early errors; launch otherwise accepts and reports these failures inside the thread. */
210 readonly checkWorktreeBase: (
211 input: Pick<ThreadLaunchInput, "projectId" | "workspaceStrategy"> & {
212 /** Skips the check when this launch was already accepted, so its retry replays. */
213 readonly commandId?: CommandId;
214 },
215 ) => Effect.Effect<
216 void,
217 ThreadLaunchBaseRefError | ThreadLaunchBranchConflictError | ThreadLaunchNotRepositoryError
218 >;
219 readonly retryPreparation: (
220 input: ThreadLaunchPreparationInput,
221 ) => Effect.Effect<
222 Orchestrator.OrchestratorV2DispatchResult,
223 | Orchestrator.OrchestratorV2Error
224 | ThreadManagement.ThreadManagementProviderInstanceDisabledError
225 >;
226 readonly prepareRun: (input: ThreadLaunchPreparationInput) => Effect.Effect<void>;
227 }
228>()("t3/orchestration-v2/ThreadLaunchService") {}
229​
230const isThreadLaunchError = Schema.is(ThreadLaunchError);
231​
232function failureDetail(error: unknown): string {
233 if (isThreadLaunchError(error)) {
234 const cause = error.cause;
235 const detail = cause instanceof Error ? cause.message : String(cause);
236 return `Workspace preparation failed during ${error.operation.replaceAll("-", " ")}: ${detail}`;
237 }
238 return `Workspace preparation failed: ${error instanceof Error ? error.message : String(error)}`;
240​
241const make = Effect.gen(function* () {
242 const projects = yield* ProjectService.ProjectService;
243 const setupTracker = yield* WorktreeSetupTracker.WorktreeSetupTracker;
244 const cloneTracker = yield* ProjectCloneTracker.ProjectCloneTracker;
245 const terminals = yield* TerminalManager.TerminalManager;
246 const git = yield* GitWorkflow.GitWorkflowService;
247 const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
248 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
249 const serverSettings = yield* ServerSettings.ServerSettingsService;
250 const textGeneration = yield* TextGeneration.TextGeneration;
251 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
252 const ids = yield* IdAllocator.IdAllocatorV2;
253 const threads = yield* ThreadManagement.ThreadManagementService;
254 const eventSink = yield* EventSink.EventSinkV2;
255 const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;
256 // A project-folder launch that names no branch records the folder's checkout, as the composer does.
257 const launchBranch = (strategy: ThreadLaunchWorkspaceStrategy, workspaceRoot: string) =>
258 strategy.type === "root" && strategy.branch === undefined
259 ? git.currentBranch(workspaceRoot).pipe(Effect.orElseSucceed(() => null))
260 : Effect.succeed(strategy.branch ?? null);
261 const preparationScope = yield* Scope.make("sequential");
262 const scheduledLaunches = yield* Ref.make<ReadonlySet<CommandId>>(new Set());
263 yield* Effect.addFinalizer(() => Scope.close(preparationScope, Exit.void));
264​
265 const mapError =
266 (input: PreparationInput, operation: ThreadLaunchError["operation"], threadId?: ThreadId) =>
267 (cause: unknown) =>
268 new ThreadLaunchError({
269 operation,
270 commandId: input.commandId,
271 projectId: input.projectId,
272 ...(threadId === undefined ? {} : { threadId }),
273 cause,
274 });
275​
276 const recordBranchRenameFailure = Effect.fn("ThreadLaunchService.recordBranchRenameFailure")(
277 function* (threadId: ThreadId, runId: RunId, branch: string, cause: Cause.Cause<unknown>) {
278 const error = Cause.squash(cause);
279 const now = yield* DateTime.now;
280 yield* eventSink.write({
281 events: [
282 {
283 id: yield* ids.allocate.event({ threadId }),
284 type: "turn-item.updated",
285 threadId,
286 runId,
287 occurredAt: now,
288 payload: {
289 id: ids.derive.runSignalTurnItem({ runId, signal: "branch-rename" }),
290 threadId,
291 runId,
292 nodeId: null,
293 providerThreadId: null,
294 providerTurnId: null,
295 nativeItemRef: null,
296 parentItemId: null,
297 // EventSink allocates the real position, after the run's existing items.
298 ordinal: 0,
299 status: "completed",
300 title: "Branch not renamed",
301 startedAt: now,
302 completedAt: now,
303 updatedAt: now,
304 type: "system_notice",
305 message: `Could not rename the worktree branch, so it stays ${branch}. ${error instanceof Error ? error.message : String(error)}`,
306 },
307 },
308 ],
309 });
310 },
311 Effect.catchCause((cause) =>
312 Effect.logWarning("Could not record the branch rename failure", { cause }),
313 ),
314 );
315​
316 const readReceipt = (input: ThreadLaunchInput, commandId: CommandId) =>
317 receipts
318 .getByCommandId(commandId)
319 .pipe(Effect.mapError(mapError(input, "read-receipt", input.threadId)));
320​
321 const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")(function* (
322 input: ThreadLaunchInput,
323 threadId: ThreadId,
324 ) {
325 const projection = yield* threads
326 .getThreadRecords(threadId, ["runs"])
327 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
328 if (
329 projection.thread.projectId !== input.projectId ||
330 projection.thread.archivedAt !== null ||
331 projection.thread.deletedAt !== null ||
332 (yield* threads
333 .getMessageCount(threadId)
334 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)))) > 0 ||
335 projection.runs.length > 0
336 ) {
337 return yield* mapError(
338 input,
339 "update-thread",
340 threadId,
341 )("Only an empty active thread in the target project can change workspace during launch.");
342 }
343 });
344​
345 const checkWorktreeBase: ThreadLaunchService["Service"]["checkWorktreeBase"] = Effect.fn(
346 "ThreadLaunchService.checkWorktreeBase",
347 )(function* (input) {
348 const strategy = input.workspaceStrategy;
349 // launch() turns a Scratch worktree request into a root launch.
350 if (strategy.type !== "worktree" || (yield* managedFolders.isScratchProject(input.projectId)))
351 return;
352 if (input.commandId !== undefined) {
353 const receipt = yield* receipts
354 .getByCommandId(input.commandId)
355 .pipe(Effect.orElseSucceed(() => Option.none()));
356 if (Option.isSome(receipt) && receipt.value.status === "accepted") return;
357 }
358 const project = Option.getOrUndefined(
359 yield* projects.getById(input.projectId).pipe(Effect.orElseSucceed(() => Option.none())),
360 );
361 if (project === undefined) return;
362 const cwd = project.workspaceRoot;
363 const repositoryRoot = yield* git
364 .repositoryRoot(cwd)
365 .pipe(Effect.orElseSucceed(() => undefined));
366 if (repositoryRoot === null)
367 return yield* new ThreadLaunchNotRepositoryError({
368 projectId: project.id,
369 projectTitle: project.title,
370 workspaceRoot: cwd,
371 });
372 const { baseRef, branch } = strategy;
373 const baseResolves =
374 // `:/text` is a commit search, which cannot be asked for a commit type.
375 baseRef.startsWith(":") ||
376 (yield* Effect.gen(function* () {
377 // `git worktree add` reads `-` as the previous checkout.
378 if (yield* git.hasCommit({ cwd, refName: baseRef === "-" ? "@{-1}" : baseRef }))
379 return true;
380 if (
381 strategy.startFromOrigin === true &&
382 (yield* git.resolveWorktreeBaseRemote({ cwd, refName: baseRef })) !== null
383 )
384 return true;
385 // git worktree add accepts remote-tracking branches; let Git decide when any matching ref exists.
386 if (yield* git.hasRefNamed({ cwd, refName: baseRef })) return true;
387 return !(yield* git.hasCommit({ cwd, refName: "HEAD" }));
388 }).pipe(Effect.orElseSucceed(() => true)));
389 if (!baseResolves)
390 return yield* new ThreadLaunchBaseRefError({
391 projectId: project.id,
392 projectTitle: project.title,
393 workspaceRoot: project.workspaceRoot,
394 baseRef,
395 });
396 // Provisioning flattens temporary names that collide, so only explicit names are refused.
397 if (branch === undefined || isTemporaryWorktreeBranch(branch)) return;
398 const conflictingBranch = (yield* git
399 .listLocalBranchNames(cwd)
400 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []))).find(
401 (existing) => existing.startsWith(`${branch}/`) || branch.startsWith(`${existing}/`),
402 );
403 if (conflictingBranch !== undefined)
404 return yield* new ThreadLaunchBranchConflictError({
405 projectId: project.id,
406 projectTitle: project.title,
407 branch,
408 conflictingBranch,
409 });
410 });
411​
412 const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* (
413 input: PreparationInput,
414 threadId: ThreadId,
415 runId: RunId | null,
416 ) {
417 const project = yield* projects.getById(input.projectId).pipe(
418 Effect.mapError(mapError(input, "resolve-project", threadId)),
419 Effect.flatMap(
420 Option.match({
421 onNone: () =>
422 Effect.fail(mapError(input, "resolve-project", threadId)("Project no longer exists.")),
423 onSome: Effect.succeed,
424 }),
425 ),
426 );
427​
428 const reused = input.reusedWorktree;
429 const tracked = input.workspaceStrategy.type === "worktree" || reused !== undefined;
430 let createdWorktreePath: string | null = null;
431 let createdBranch: string | null = null;
432 let setupTerminalId: string | null = null;
433 let workspaceRecorded = false;
434 let runReleased = false;
435 // Stop background renames before forgetting worktrees; completed renames record them again.
436 let branchRename: Fiber.Fiber<unknown> | null = null;
437 if (input.workspaceStrategy.type === "worktree") {
438 yield* setupTracker.begin({
439 threadId,
440 branch: input.workspaceStrategy.branch ?? null,
441 baseRef: input.workspaceStrategy.baseRef,
442 stages: ["fetch", "checkout", "submodules", "setup-script", "agent"],
443 fiber: yield* Effect.fiber,
444 });
445 } else if (reused !== undefined) {
446 yield* setupTracker.begin({
447 threadId,
448 branch: input.workspaceStrategy.branch ?? null,
449 baseRef: reused.baseRef,
450 stages: ["setup-script", "agent"],
451 fiber: yield* Effect.fiber,
452 });
453 }
454 yield* Effect.gen(function* () {
455 const initialMessage = input.initialMessage;
456 const generateBranchNameFor = Effect.fn("ThreadLaunchService.generateBranchNameFor")(
457 function* (cwd: string, message: ThreadLaunchInitialMessage) {
458 const settings = resolveProjectSettings(
459 yield* serverSettings.getSettings,
460 input.projectId,
461 ).settings;
462 const modelSelection =
463 settings.sourceControlWriterModelSelection === null
464 ? settings.textGenerationModelSelection
465 : ServerSettings.resolveSourceControlWriterModelSelection(
466 settings,
467 yield* providerRegistry.getProviders,
468 input.projectId,
469 );
470 return yield* textGeneration
471 .generateBranchName({
472 naming: {
473 mode: settings.branchNamingMode,
474 prefix: settings.branchNamePrefix,
475 instructions: settings.branchNameInstructions,
476 },
477 cwd,
478 message: message.text,
479 attachments: message.attachments,
480 ...(message.context ? { context: message.context } : {}),
481 modelSelection,
482 projectId: input.projectId,
483 })
484 .pipe(
485 Effect.map((result) => ({
486 branch: result.branch,
487 exactName: settings.branchNamingMode === "custom",
488 })),
489 );
490 },
491 );
492​
493 const requestedBranch = input.workspaceStrategy.branch;
494 let branch: string | null;
495 if (input.workspaceStrategy.type === "worktree" && requestedBranch === undefined) {
496 const uuid = yield* randomUuidV4;
497 branch = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
498 } else {
499 branch = yield* launchBranch(input.workspaceStrategy, project.workspaceRoot);
500 }
501 let worktreePath =
502 input.workspaceStrategy.type === "existing_worktree"
503 ? input.workspaceStrategy.worktreePath
504 : null;
505 if (input.workspaceStrategy.type === "worktree") {
506 if (runId !== null) {
507 yield* threads
508 .dispatch({
509 type: "prepared-run.progress",
510 commandId: CommandId.make(`${input.commandId}:progress:worktree`),
511 threadId,
512 runId,
513 phase: "worktree",
514 })
515 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
516 }
517 let startRef = input.workspaceStrategy.baseRef;
518 let baseRefName = input.workspaceStrategy.baseRef;
519 const remote =
520 input.workspaceStrategy.startFromOrigin === true
521 ? yield* git
522 .resolveWorktreeBaseRemote({
523 cwd: project.workspaceRoot,
524 refName: input.workspaceStrategy.baseRef,
525 })
526 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)))
527 : null;
528 const shouldFetch = remote !== null;
529 yield* setupTracker.stageStatus(threadId, "fetch", shouldFetch ? "running" : "skipped");
530 if (remote !== null) {
531 const remoteBase = yield* git
532 .fetchWorktreeBaseCommit({
533 cwd: project.workspaceRoot,
534 refName: input.workspaceStrategy.baseRef,
535 remote,
536 })
537 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
538 if (remoteBase !== null) {
539 startRef = remoteBase.commitSha;
540 baseRefName = `refs/remotes/${remoteBase.remoteRefName}`;
541 }
542 }
543 if (shouldFetch) yield* setupTracker.stageStatus(threadId, "fetch", "done");
544 if (
545 branch !== null &&
546 isTemporaryWorktreeBranch(branch) &&
547 (yield* git
548 .hasCommit({
549 cwd: project.workspaceRoot,
550 refName: `refs/heads/${WORKTREE_BRANCH_PREFIX}`,
551 })
552 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))))
553 ) {
554 branch = flattenTemporaryWorktreeBranchName(branch);
555 }
556 yield* setupTracker.stageStatus(threadId, "checkout", "running");
557 let submoduleProgressReportedAt = Number.NEGATIVE_INFINITY;
558 const worktree = yield* git
559 .createWorktree(
560 {
561 cwd: project.workspaceRoot,
562 refName: startRef,
563 newRefName: branch!,
564 baseRefName,
565 path: null,
566 },
567 {
568 progress: {
569 onWorktreeClaimed: (path) =>
570 Effect.sync(() => {
571 createdWorktreePath = path;
572 createdBranch = branch;
573 }),
574 onCheckoutProgress: (progress) =>
575 setupTracker.stage(threadId, "checkout", { percent: progress.percent }),
576 onSubmodulesStarted: () =>
577 setupTracker
578 .stageStatus(threadId, "checkout", "done")
579 .pipe(
580 Effect.andThen(setupTracker.stageStatus(threadId, "submodules", "running")),
581 ),
582 onSubmodulesDisabled: ({ source }) =>
583 setupTracker.stageStatus(
584 threadId,
585 "submodules",
586 "skipped",
587 `disabled in ${source}`,
588 ),
589 onSubmoduleLine: (line) => {
590 // Paths may contain quotes; git closes the path with "': ".
591 const submodulePath = /^\s*Submodule path '(.+)': /.exec(line)?.[1];
592 if (submodulePath !== undefined) {
593 return setupTracker.stage(threadId, "submodules", { detail: submodulePath });
594 }
595 if (parseGitCloneProgressLine(line) === null) return Effect.void;
596 // Git redraws on every percent; hold the websocket to one update a second.
597 return Effect.flatMap(Clock.currentTimeMillis, (now) => {
598 if (now - submoduleProgressReportedAt < 1000) return Effect.void;
599 submoduleProgressReportedAt = now;
600 return setupTracker.stage(threadId, "submodules", {
601 detail: line.trim().replace(/\s+/g, " "),
602 });
603 });
604 },
605 onSubmodulesFinished: ({ ok, detail }) =>
606 setupTracker.stageStatus(
607 threadId,
608 "submodules",
609 ok ? "done" : "warning",
610 ok ? undefined : (detail ?? "submodule checkout failed"),
611 ),
612 },
613 },
614 )
615 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
616 worktreePath = worktree.worktree.path;
617 branch = worktree.worktree.refName;
618 createdWorktreePath = worktreePath;
619 createdBranch = branch;
620 yield* setupTracker.update(threadId, (snapshot) => ({
621 ...snapshot,
622 worktreePath,
623 branch,
624 stages: snapshot.stages.map((stage) =>
625 stage.id === "submodules" && stage.status === "pending"
626 ? { ...stage, status: "skipped", detail: "none" }
627 : stage,
628 ),
629 }));
630 yield* setupTracker.stageStatus(threadId, "checkout", "done");
631 }
632​
633 // Do not rewrite reused worktrees; that could undo the original branch rename.
634 if (reused === undefined) {
635 yield* threads
636 .dispatch({
637 type: "thread.metadata.update",
638 commandId: CommandId.make(`${input.commandId}:workspace`),
639 threadId,
640 branch,
641 worktreePath,
642 })
643 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
644 }
645 workspaceRecorded = true;
646​
647 if (
648 reused === undefined &&
649 worktreePath !== null &&
650 branch !== null &&
651 initialMessage !== undefined &&
652 isTemporaryWorktreeBranch(branch)
653 ) {
654 const oldBranch = branch;
655 const worktreeCwd = worktreePath;
656 branchRename = yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe(
657 Effect.flatMap(({ branch: newBranch, exactName }) =>
658 git
659 .renameBranch({
660 cwd: worktreeCwd,
661 oldBranch,
662 newBranch,
663 ...(exactName ? { exactName: true } : {}),
664 })
665 .pipe(
666 // A cancel must see the renamed branch, or its cleanup deletes the old name.
667 Effect.tap((renamed) =>
668 Effect.sync(() => {
669 createdBranch = renamed.branch;
670 }),
671 ),
672 Effect.uninterruptible,
673 ),
674 ),
675 Effect.flatMap((renamed) =>
676 Effect.gen(function* () {
677 yield* threads
678 .dispatch({
679 type: "thread.metadata.update",
680 commandId: CommandId.make(`${input.commandId}:branch-rename`),
681 threadId,
682 branch: renamed.branch,
683 worktreePath: worktreeCwd,
684 expectedBranch: oldBranch,
685 expectedWorktreePath: worktreeCwd,
686 })
687 .pipe(
688 Effect.catchCause((cause) =>
689 Effect.logWarning("Parent thread worktree branch update failed", {
690 threadId,
691 cause,
692 }),
693 ),
694 );
695 // Update parents first so children inherit names; reread each pass for newly updated descendants.
696 const visited = new Set([threadId]);
697 while (true) {
698 const snapshot = yield* threads.getShellSnapshot({ worktreePath: worktreeCwd });
699 const sharing = [...snapshot.threads, ...snapshot.archivedThreads].filter(
700 (thread) => !visited.has(thread.id) && thread.branch === oldBranch,
701 );
702 if (sharing.length === 0) break;
703 for (const thread of sharing) {
704 visited.add(thread.id);
705 yield* threads
706 .dispatch({
707 type: "thread.metadata.update",
708 commandId: CommandId.make(`${input.commandId}:branch-rename:${thread.id}`),
709 threadId: thread.id,
710 branch: renamed.branch,
711 expectedBranch: oldBranch,
712 expectedWorktreePath: worktreeCwd,
713 })
714 .pipe(
715 Effect.catchCause((cause) =>
716 Effect.logWarning("Shared thread worktree branch update failed", {
717 threadId: thread.id,
718 cause,
719 }),
720 ),
721 );
722 }
723 }
724 }),
725 ),
726 Effect.catchCause((cause) =>
727 Effect.logWarning("Thread worktree branch rename failed", {
728 commandId: input.commandId,
729 threadId,
730 oldBranch,
731 cause,
732 }).pipe(
733 Effect.andThen(
734 runId === null || Cause.hasInterruptsOnly(cause)
735 ? Effect.void
736 : recordBranchRenameFailure(threadId, runId, oldBranch, cause),
737 ),
738 ),
739 ),
740 Effect.forkIn(preparationScope),
741 );
742 }
743​
744 if (runId !== null && worktreePath !== null) {
745 yield* threads
746 .dispatch({
747 type: "prepared-run.progress",
748 commandId: CommandId.make(`${input.commandId}:progress:setup`),
749 threadId,
750 runId,
751 phase: "setup",
752 })
753 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
754 }
755 yield* setupTracker.stageStatus(threadId, "setup-script", "running");
756 const setup =
757 worktreePath === null
758 ? ({ status: "no-script" } as const)
759 : yield* setupScripts
760 .runForThread({
761 threadId,
762 projectId: input.projectId,
763 projectCwd: project.workspaceRoot,
764 worktreePath,
765 ...(tracked
766 ? {
767 observeCompletion: {
768 onOutputLine: (line: string) =>
769 setupTracker.appendTail(threadId, "setup-script", line),
770 },
771 }
772 : {}),
773 project: {
774 id: project.id,
775 workspaceRoot: project.workspaceRoot,
776 scripts: project.scripts,
777 },
778 })
779 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
780​
781 let awaitAsyncSetup = Effect.void;
782 if (setup.status === "started") {
783 setupTerminalId = setup.terminalId;
784 yield* setupTracker.update(threadId, (snapshot) => ({
785 ...snapshot,
786 setupScript: {
787 name: setup.scriptName,
788 command: setup.scriptCommand,
789 terminalId: setup.terminalId,
790 },
791 }));
792 if (setup.completion) {
793 const awaitCompletion = Effect.gen(function* () {
794 const completion = yield* setup.completion!;
795 yield* setupTracker.stage(threadId, "setup-script", {
796 status: completion.exitCode === 0 ? "done" : "failed",
797 detail: `exited with ${completion.exitCode ?? "no exit code"}`,
798 });
799 if (completion.exitCode !== 0 && !setup.async)
800 return yield* mapError(
801 input,
802 "run-setup-script",
803 threadId,
804 )(`Setup script exited with ${completion.exitCode ?? "no exit code"}.`);
805 });
806 if (setup.async) {
807 awaitAsyncSetup = awaitCompletion.pipe(
808 Effect.catchCause((cause) =>
809 setupTracker.stage(threadId, "setup-script", {
810 status: "failed",
811 detail: failureDetail(Cause.squash(cause)),
812 }),
813 ),
814 );
815 } else {
816 yield* awaitCompletion;
817 }
818 } else {
819 yield* setupTracker.stageStatus(threadId, "setup-script", "done");
820 }
821 } else {
822 yield* setupTracker.stageStatus(threadId, "setup-script", "skipped");
823 }
824 // The agent must start on the branch name the thread will show.
825 if (branchRename !== null) yield* Fiber.join(branchRename);
826 yield* setupTracker.markUncancellable(threadId);
827 yield* setupTracker.stageStatus(threadId, "agent", "running");
828 if (runId !== null) {
829 yield* threads
830 .dispatch({
831 type: "prepared-run.release",
832 commandId: CommandId.make(`${input.commandId}:release`),
833 threadId,
834 runId,
835 })
836 .pipe(
837 Effect.mapError(mapError(input, "release-run", threadId)),
838 Effect.tap(() =>
839 Effect.sync(() => {
840 runReleased = true;
841 }),
842 ),
843 Effect.uninterruptible,
844 );
845 }
846 yield* setupTracker.stageStatus(threadId, "agent", "done");
847 yield* awaitAsyncSetup;
848 yield* setupTracker.finish(threadId, "done");
849 }).pipe(
850 Effect.onError((cause) =>
851 Effect.gen(function* () {
852 const cancelled = Cause.hasInterruptsOnly(cause);
853 yield* setupTracker.finish(
854 threadId,
855 cancelled ? "cancelled" : "failed",
856 cancelled ? null : failureDetail(Cause.squash(cause)),
857 );
858 if (cancelled && setupTerminalId)
859 yield* terminals
860 .close({ threadId, terminalId: setupTerminalId, deleteHistory: true })
861 .pipe(Effect.ignore);
862 if (
863 tracked &&
864 createdWorktreePath &&
865 ((cancelled && !runReleased) || !workspaceRecorded)
866 ) {
867 if (branchRename !== null) yield* Fiber.interrupt(branchRename);
868 const removedPath = createdWorktreePath;
869 const removedBranch = createdBranch;
870 // Forget worktrees only after removal succeeds; failed removals must not reuse partially written checkouts.
871 yield* git
872 .removeWorktree({ cwd: project.workspaceRoot, path: removedPath, force: true })
873 .pipe(
874 Effect.andThen(
875 removedBranch === null
876 ? Effect.void
877 : git
878 .deleteLocalBranch({
879 cwd: project.workspaceRoot,
880 refName: removedBranch,
881 force: true,
882 })
883 .pipe(Effect.ignoreCause({ log: true })),
884 ),
885 Effect.andThen(
886 threads
887 .dispatch({
888 type: "thread.metadata.update",
889 commandId: CommandId.make(`${input.commandId}:cancel-workspace`),
890 threadId,
891 worktreePath: null,
892 branch: null,
893 })
894 .pipe(Effect.ignore),
895 ),
896 Effect.catchCause((removeCause) =>
897 Effect.logWarning("Failed to remove an abandoned thread worktree", {
898 commandId: input.commandId,
899 threadId,
900 path: removedPath,
901 cause: removeCause,
902 }),
903 ),
904 );
905 }
906 }),
907 ),
908 );
909 });
910​
911 const failPreparedRun = (
912 input: Pick<PreparationInput, "commandId">,
913 threadId: ThreadId,
914 runId: RunId | null,
915 cause: unknown,
916 ) =>
917 runId === null
918 ? Effect.logWarning("Thread workspace preparation failed", {
919 commandId: input.commandId,
920 threadId,
921 cause,
922 })
923 : threads
924 .dispatch({
925 type: "prepared-run.fail",
926 commandId: CommandId.make(`${input.commandId}:fail`),
927 threadId,
928 runId,
929 failure: makeProviderFailure({
930 cause,
931 message: failureDetail(cause),
932 class: "validation_error",
933 retryable: false,
934 }),
935 })
936 .pipe(
937 Effect.catchCause((persistCause) =>
938 Effect.logWarning("Failed to persist thread workspace preparation failure", {
939 commandId: input.commandId,
940 threadId,
941 cause,
942 persistCause,
943 }),
944 ),
945 );
946​
947 const reservePreparation = (commandId: CommandId) =>
948 Ref.modify(scheduledLaunches, (scheduled) => {
949 if (scheduled.has(commandId)) return [false, scheduled] as const;
950 const next = new Set(scheduled);
951 next.add(commandId);
952 return [true, next] as const;
953 });
954​
955 const releasePreparation = (commandId: CommandId) =>
956 Ref.update(scheduledLaunches, (scheduled) => {
957 const next = new Set(scheduled);
958 next.delete(commandId);
959 return next;
960 });
961​
962 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
963 input: PreparationInput,
964 threadId: ThreadId,
965 runId: RunId | null,
966 ) {
967 const preparation = Effect.gen(function* () {
968 const prepare = prepareInBackground(input, threadId, runId);
969 if (
970 runId === null ||
971 (input.workspaceStrategy.type !== "worktree" && input.reusedWorktree === undefined)
972 ) {
973 return yield* prepare;
974 }
975 const afterSequence = yield* threads.getThreadEventSequence(threadId);
976 const projection = yield* threads.getThreadRecords(threadId, ["runs"]);
977 if (projection.runs.find((run) => run.id === runId)?.status !== "preparing") return;
978 const interruption = threads
979 .streamStoredEventsFrom({ threadId, afterSequence, eventType: "run.updated" })
980 .pipe(
981 Stream.filter(
982 (stored) =>
983 stored.event.type === "run.updated" &&
984 stored.event.payload.id === runId &&
985 (stored.event.payload.status === "interrupted" ||
986 stored.event.payload.status === "cancelled"),
987 ),
988 Stream.runHead,
989 Effect.flatMap((event) => (Option.isSome(event) ? Effect.interrupt : Effect.never)),
990 );
991 yield* Effect.raceFirst(prepare, interruption);
992 });
993 yield* preparation.pipe(
994 Effect.onError((cause) =>
995 failPreparedRun(
996 input,
997 threadId,
998 runId,
999 Cause.hasInterruptsOnly(cause) ? "Worktree setup cancelled." : Cause.squash(cause),
1000 ),
1001 ),
1002 Effect.ignoreCause,
1003 Effect.ensuring(releasePreparation(input.commandId)),
1004 Effect.forkIn(preparationScope),
1005 );
1006 });
1007​
1008 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
1009 function* (request) {
1010 // Scratch has no Git repository. Normalize before folder allocation so
1011 // durable preparation and retries use the thread's own Scratch folder.
1012 const input: ThreadLaunchInput =
1013 request.workspaceStrategy.type === "worktree" &&
1014 (yield* managedFolders.isScratchProject(request.projectId))
1015 ? { ...request, workspaceStrategy: { type: "root" } }
1016 : request;
1017 yield* ProjectCloneTracker.rejectCommandsDuringClone(cloneTracker, {
1018 type: "thread.create",
1019 projectId: input.projectId,
1020 }).pipe(Effect.mapError(mapError(input, "resolve-project")));
1021 const project = yield* projects.getById(input.projectId).pipe(
1022 Effect.mapError(mapError(input, "resolve-project")),
1023 Effect.flatMap(
1024 Option.match({
1025 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
1026 onSome: Effect.succeed,
1027 }),
1028 ),
1029 );
1030 if (input.reuseExistingThread === true && input.threadId === undefined) {
1031 return yield* mapError(
1032 input,
1033 "update-thread",
1034 )("Reusing an existing thread requires a thread id.");
1036​
1037 const launchReceipt = yield* readReceipt(input, input.commandId);
1038 yield* threads.assertProviderInstanceEnabled({
1039 projectId: input.projectId,
1040 commandId: input.commandId,
1041 instanceId: input.modelSelection.instanceId,
1042 });
1043 return yield* Effect.gen(function* () {
1044 // Recover ids from accepted launch receipts before allocating; retries have no client id and new ids collide with receipts.
1045 const reusableLaunchReceipt =
1046 input.threadId === undefined &&
1047 Option.isSome(launchReceipt) &&
1048 launchReceipt.value.status === "accepted" &&
1049 launchReceipt.value.commandType === "thread.create"
1050 ? launchReceipt.value
1051 : undefined;
1052 const candidateThreadId =
1053 input.threadId ??
1054 reusableLaunchReceipt?.threadId ??
1055 (yield* ids.allocate
1056 .thread({ projectId: input.projectId })
1057 .pipe(Effect.mapError(mapError(input, "create-thread"))));
1058​
1059 if (reusableLaunchReceipt !== undefined) {
1060 const shell = yield* threads
1061 .getThreadShell(candidateThreadId)
1062 .pipe(Effect.mapError(mapError(input, "create-thread", candidateThreadId)));
1063 if (shell === null) {
1064 return yield* mapError(input, "create-thread", candidateThreadId)("Thread not found.");
1066 if (shell.projectId !== input.projectId) {
1067 return yield* mapError(
1068 input,
1069 "resolve-project",
1070 candidateThreadId,
1071 )("Project identity changed.");
1074​
1075 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
1076 yield* validateReusableThread(input, candidateThreadId);
1078​
1079 const workspaceStrategy: ThreadLaunchWorkspaceStrategy =
1080 input.workspaceStrategy.type === "root" && Option.isNone(launchReceipt)
1081 ? Option.match(
1082 yield* managedFolders
1083 .folderForThread({
1084 projectId: input.projectId,
1085 threadId: candidateThreadId,
1086 text: input.initialMessage?.text ?? input.title,
1087 })
1088 .pipe(Effect.mapError(mapError(input, "provision-worktree", candidateThreadId))),
1090 onNone: () => input.workspaceStrategy,
1091 onSome: (worktreePath) => ({ type: "existing_worktree", worktreePath }),
1092 },
1094 : input.workspaceStrategy;
1095 const initialBranch = yield* launchBranch(workspaceStrategy, project.workspaceRoot);
1096 const initialWorktreePath =
1097 workspaceStrategy.type === "existing_worktree" ? workspaceStrategy.worktreePath : null;
1098 const claimDispatch =
1099 input.reuseExistingThread === true
1100 ? threads.dispatch({
1101 type: "thread.metadata.update",
1102 commandId: input.commandId,
1103 threadId: candidateThreadId,
1104 expectedEmpty: true,
1105 })
1106 : threads.dispatch({
1107 type: "thread.create",
1108 commandId: input.commandId,
1109 threadId: candidateThreadId,
1110 projectId: input.projectId,
1111 title: input.title,
1112 modelSelection: input.modelSelection,
1113 runtimeMode: input.runtimeMode,
1114 interactionMode: input.interactionMode,
1115 branch: initialBranch,
1116 worktreePath: initialWorktreePath,
1117 ...(input.importedNativeThread === undefined
1118 ? {}
1119 : { importedNativeThread: input.importedNativeThread }),
1120 ...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }),
1121 ...(input.delegatedFrom === undefined
1122 ? {}
1123 : { delegatedFrom: input.delegatedFrom }),
1124 createdBy: input.createdBy,
1125 creationSource: input.creationSource,
1126 });
1127 const claimed = yield* claimDispatch.pipe(
1128 Effect.mapError(
1129 mapError(
1130 input,
1131 input.reuseExistingThread === true ? "update-thread" : "create-thread",
1132 candidateThreadId,
1133 ),
1134 ),
1135 );
1136 const threadId =
1137 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
1138 .threadId ?? candidateThreadId;
1139 if (project.id !== input.projectId) {
1140 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
1142 let runId: RunId | null = null;
1143 let messageSequence: number | undefined;
1144 let messageWasAlreadyAccepted = false;
1145 if (input.initialMessage !== undefined) {
1146 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
1147 const messageReceipt = yield* readReceipt(input, messageCommandId);
1148 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
1149 const messageId =
1150 input.initialMessage.messageId ??
1151 (yield* ids.allocate
1152 .message({ threadId, ordinal: 1 })
1153 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
1154 const dispatched = yield* threads
1155 .dispatch({
1156 type: "message.dispatch",
1157 commandId: messageCommandId,
1158 threadId,
1159 messageId,
1160 text: input.initialMessage.text,
1161 ...(input.initialMessage.scheduledTaskId === undefined
1162 ? {}
1163 : { scheduledTaskId: input.initialMessage.scheduledTaskId }),
1164 ...(input.initialMessage.senderThreadId === undefined
1165 ? {}
1166 : { senderThreadId: input.initialMessage.senderThreadId }),
1167 attachments: input.initialMessage.attachments,
1168 ...(input.initialMessage.context ? { context: input.initialMessage.context } : {}),
1169 ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
1170 modelSelection: input.modelSelection,
1171 dispatchMode: { type: "defer_start", workspaceStrategy },
1172 createdBy: input.createdBy,
1173 creationSource: input.creationSource,
1174 })
1175 .pipe(
1176 // An agent's launch can land on a thread that a replay, or a concurrent
1177 // launch with the same key, created with broader modes. The orchestrator
1178 // refuses the message under the thread's lock; the user's own clients
1179 // launch into their own drafts, whatever modes those hold.
1180 input.createdBy === "agent"
1181 ? Effect.provideService(DispatchModeLimit, {
1182 runtimeMode: input.runtimeMode,
1183 interactionMode: input.interactionMode,
1184 })
1185 : (effect) => effect,
1186 Effect.mapError(mapError(input, "dispatch-message", threadId)),
1187 );
1188 // A concurrent retry can read no receipt and still replay the dispatch.
1189 messageWasAlreadyAccepted ||= dispatched.replayed === true;
1190 messageSequence = dispatched.sequence;
1191 const runCreated = dispatched.storedEvents.find(
1192 (stored) => stored.event.type === "run.created",
1193 );
1194 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
1195 if (runId === null) {
1196 return yield* mapError(
1197 input,
1198 "dispatch-message",
1199 threadId,
1200 )("Initial message was accepted without a durable run.");
1203​
1204 const projection = yield* threads
1205 .getThreadProjection(threadId)
1206 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
1207 const runIsPreparing =
1208 runId !== null &&
1209 projection.runs.some((run) => run.id === runId && run.status === "preparing");
1210 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing;
1211 const boundWorktreePath = projection.thread.worktreePath;
1212 const preparationStrategy: ThreadLaunchWorkspaceStrategy =
1213 Option.isSome(launchReceipt) &&
1214 workspaceStrategy.type === "root" &&
1215 boundWorktreePath !== null
1216 ? {
1217 type: "existing_worktree",
1218 worktreePath: boundWorktreePath,
1219 branch: workspaceStrategy.branch,
1221 : workspaceStrategy;
1222 if (shouldSchedule) {
1223 const ownsPreparation = yield* reservePreparation(input.commandId);
1224 if (ownsPreparation) {
1225 yield* Effect.gen(function* () {
1226 const preparationStillRequired =
1227 runId === null
1228 ? true
1229 : yield* threads.getThreadRecords(threadId, ["runs"], { runIds: [runId] }).pipe(
1230 Effect.map((current) =>
1231 current.runs.some((run) => run.id === runId && run.status === "preparing"),
1232 ),
1233 Effect.mapError(mapError(input, "update-thread", threadId)),
1234 );
1235 if (preparationStillRequired) {
1236 yield* schedulePreparation(
1237 { ...input, workspaceStrategy: preparationStrategy },
1238 threadId,
1239 runId,
1240 );
1241 } else {
1242 yield* releasePreparation(input.commandId);
1244 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
1247​
1248 return {
1249 threadId,
1250 projection,
1251 // An attempt that failed after claiming the thread recorded nothing, so
1252 // only a repeat of the final write counts as resumed.
1253 resumed:
1254 input.initialMessage === undefined
1255 ? Option.isSome(launchReceipt) || claimed.replayed === true
1256 : messageWasAlreadyAccepted,
1257 ...(messageSequence === undefined ? {} : { sequence: messageSequence }),
1258 };
1259 });
1260 },
1261 );
1262​
1263 const prepareRun: ThreadLaunchService["Service"]["prepareRun"] = Effect.fn(
1264 "ThreadLaunchService.prepareRun",
1265 )(function* (input) {
1266 const scheduled = yield* Effect.gen(function* () {
1267 const { thread, runs } = yield* threads.getThreadRecords(input.threadId, ["runs"], {
1268 runIds: [input.runId],
1269 });
1270 const run = runs.find((candidate) => candidate.id === input.runId);
1271 const workspacePreparation = run?.workspacePreparation;
1272 if (run?.status !== "preparing" || workspacePreparation === undefined) return;
1273 if (!(yield* reservePreparation(input.commandId))) return;
1274 yield* scheduleRunPreparation(input, thread, run, workspacePreparation).pipe(
1275 Effect.onError(() => releasePreparation(input.commandId)),
1276 );
1277 }).pipe(Effect.exit);
1278 if (Exit.isFailure(scheduled)) {
1279 yield* failPreparedRun(input, input.threadId, input.runId, Cause.squash(scheduled.cause));
1281 });
1282​
1283 const retryPreparation: ThreadLaunchService["Service"]["retryPreparation"] = Effect.fn(
1284 "ThreadLaunchService.retryPreparation",
1285 )(function* (input) {
1286 const dispatched = yield* threads.dispatch({
1287 type: "prepared-run.retry",
1288 commandId: input.commandId,
1289 threadId: input.threadId,
1290 runId: input.runId,
1291 });
1292 yield* prepareRun(input);
1293 return dispatched;
1294 });
1295​
1296 const scheduleRunPreparation = Effect.fn("ThreadLaunchService.scheduleRunPreparation")(function* (
1297 input: ThreadLaunchPreparationInput,
1298 thread: OrchestrationV2ThreadProjection["thread"],
1299 run: OrchestrationV2ThreadProjection["runs"][number],
1300 workspacePreparation: ThreadLaunchWorkspaceStrategy,
1301 ) {
1302 const { messages } = yield* threads.getThreadRecords(input.threadId, ["messages"], {
1303 messageIds: [run.userMessageId],
1304 });
1305 const message = messages.find((candidate) => candidate.id === run.userMessageId);
1306 const reuse =
1307 workspacePreparation.type === "worktree" &&
1308 thread.worktreePath !== null &&
1309 thread.branch !== null
1310 ? {
1311 strategy: {
1312 type: "existing_worktree" as const,
1313 worktreePath: thread.worktreePath,
1314 branch: thread.branch,
1315 },
1316 reusedWorktree: { baseRef: workspacePreparation.baseRef },
1318 : null;
1319 return yield* schedulePreparation(
1321 commandId: input.commandId,
1322 projectId: thread.projectId,
1323 workspaceStrategy: reuse?.strategy ?? workspacePreparation,
1324 ...(reuse === null ? {} : { reusedWorktree: reuse.reusedWorktree }),
1325 ...(message === undefined
1326 ? {}
1327 : {
1328 initialMessage: {
1329 text: message.text,
1330 attachments: message.attachments,
1331 ...(message.context ? { context: message.context } : {}),
1332 },
1333 }),
1334 },
1335 input.threadId,
1336 run.id,
1337 );
1338 });
1339​
1340 return ThreadLaunchService.of({ launch, checkWorktreeBase, retryPreparation, prepareRun });
1341});
1342​
1343export const layer = Layer.effect(ThreadLaunchService, make);