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

ThreadLaunchService.ts

1,375 lines53.9 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 formatGeneratedBranchName,
41 isTemporaryWorktreeBranch,
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 if (strategy.type !== "worktree") return;
350 const commandId = input.commandId;
351 const [isScratch, receipt, projectOption] = yield* Effect.all(
352 [
353 managedFolders.isScratchProject(input.projectId),
354 commandId === undefined
355 ? Effect.succeedNone
356 : receipts.getByCommandId(commandId).pipe(Effect.orElseSucceed(() => Option.none())),
357 projects.getById(input.projectId).pipe(Effect.orElseSucceed(() => Option.none())),
358 ],
359 { concurrency: "unbounded" },
360 );
361 // launch() turns a Scratch worktree request into a root launch.
362 if (isScratch) return;
363 if (Option.isSome(receipt) && receipt.value.status === "accepted") return;
364 const project = Option.getOrUndefined(projectOption);
365 if (project === undefined) return;
366 const cwd = project.workspaceRoot;
367 const { baseRef, branch } = strategy;
368 const checksBranch = branch !== undefined && !isTemporaryWorktreeBranch(branch);
369 // Errors keep their order below: missing repository, then base ref, then branch conflict.
370 const [repositoryRoot, hasBaseCommit, localBranches] = yield* Effect.all(
371 [
372 git.repositoryRoot(cwd).pipe(Effect.orElseSucceed(() => undefined)),
373 // `:/text` is a commit search, which cannot be asked for a commit type.
374 baseRef.startsWith(":")
375 ? Effect.succeed(true)
376 : // `git worktree add` reads `-` as the previous checkout.
377 git
378 .hasCommit({ cwd, refName: baseRef === "-" ? "@{-1}" : baseRef })
379 .pipe(Effect.orElseSucceed(() => true)),
380 checksBranch
381 ? git
382 .listLocalBranchNames(cwd)
383 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []))
384 : Effect.succeed<ReadonlyArray<string>>([]),
385 ],
386 { concurrency: "unbounded" },
387 );
388 if (repositoryRoot === null)
389 return yield* new ThreadLaunchNotRepositoryError({
390 projectId: project.id,
391 projectTitle: project.title,
392 workspaceRoot: cwd,
393 });
394 const baseResolves =
395 hasBaseCommit ||
396 (yield* Effect.gen(function* () {
397 if (strategy.startFromOrigin === true) {
398 const remote = yield* git.resolveWorktreeBaseRemote({ cwd, refName: baseRef });
399 // The remote may have deleted the branch; ask it rather than trusting the name.
400 if (
401 remote !== null &&
402 (yield* git.fetchWorktreeBaseCommit({ cwd, refName: baseRef, remote })) !== null
403 )
404 return true;
405 }
406 // git worktree add accepts remote-tracking branches; let Git decide when any matching ref exists.
407 if (yield* git.hasRefNamed({ cwd, refName: baseRef })) return true;
408 return !(yield* git.hasCommit({ cwd, refName: "HEAD" }));
409 }).pipe(Effect.orElseSucceed(() => true)));
410 if (!baseResolves)
411 return yield* new ThreadLaunchBaseRefError({
412 projectId: project.id,
413 projectTitle: project.title,
414 workspaceRoot: project.workspaceRoot,
415 baseRef,
416 });
417 // Provisioning flattens temporary names that collide, so only explicit names are refused.
418 if (!checksBranch) return;
419 const conflictingBranch = localBranches.find(
420 (existing) => existing.startsWith(`${branch}/`) || branch.startsWith(`${existing}/`),
421 );
422 if (conflictingBranch !== undefined)
423 return yield* new ThreadLaunchBranchConflictError({
424 projectId: project.id,
425 projectTitle: project.title,
426 branch,
427 conflictingBranch,
428 });
429 });
430​
431 const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* (
432 input: PreparationInput,
433 threadId: ThreadId,
434 runId: RunId | null,
435 ) {
436 const project = yield* projects.getById(input.projectId).pipe(
437 Effect.mapError(mapError(input, "resolve-project", threadId)),
438 Effect.flatMap(
439 Option.match({
440 onNone: () =>
441 Effect.fail(mapError(input, "resolve-project", threadId)("Project no longer exists.")),
442 onSome: Effect.succeed,
443 }),
444 ),
445 );
446​
447 const reused = input.reusedWorktree;
448 const tracked = input.workspaceStrategy.type === "worktree" || reused !== undefined;
449 let createdWorktreePath: string | null = null;
450 let createdBranch: string | null = null;
451 let setupTerminalId: string | null = null;
452 let workspaceRecorded = false;
453 let runReleased = false;
454 // Stop background renames before forgetting worktrees; completed renames record them again.
455 let branchRename: Fiber.Fiber<unknown> | null = null;
456 if (input.workspaceStrategy.type === "worktree") {
457 yield* setupTracker.begin({
458 threadId,
459 branch: input.workspaceStrategy.branch ?? null,
460 baseRef: input.workspaceStrategy.baseRef,
461 stages: ["fetch", "checkout", "submodules", "setup-script", "agent"],
462 fiber: yield* Effect.fiber,
463 });
464 } else if (reused !== undefined) {
465 yield* setupTracker.begin({
466 threadId,
467 branch: input.workspaceStrategy.branch ?? null,
468 baseRef: reused.baseRef,
469 stages: ["setup-script", "agent"],
470 fiber: yield* Effect.fiber,
471 });
472 }
473 yield* Effect.gen(function* () {
474 const initialMessage = input.initialMessage;
475 const generateBranchNameFor = Effect.fn("ThreadLaunchService.generateBranchNameFor")(
476 function* (cwd: string, message: ThreadLaunchInitialMessage) {
477 const settings = resolveProjectSettings(
478 yield* serverSettings.getSettings,
479 input.projectId,
480 ).settings;
481 const modelSelection =
482 settings.sourceControlWriterModelSelection === null
483 ? settings.textGenerationModelSelection
484 : ServerSettings.resolveSourceControlWriterModelSelection(
485 settings,
486 yield* providerRegistry.getProviders,
487 input.projectId,
488 );
489 return yield* textGeneration
490 .generateBranchName({
491 naming: {
492 mode: settings.branchNamingMode,
493 prefix: settings.branchNamePrefix,
494 instructions: settings.branchNameInstructions,
495 },
496 cwd,
497 message: message.text,
498 attachments: message.attachments,
499 ...(message.context ? { context: message.context } : {}),
500 modelSelection,
501 projectId: input.projectId,
502 })
503 .pipe(
504 Effect.map((result) => ({
505 branch: result.branch,
506 exactName: settings.branchNamingMode === "custom",
507 })),
508 );
509 },
510 );
511​
512 const requestedBranch = input.workspaceStrategy.branch;
513 const generatedTemporaryBranch =
514 input.workspaceStrategy.type === "worktree" && requestedBranch === undefined;
515 let branch: string | null;
516 if (generatedTemporaryBranch) {
517 const uuid = yield* randomUuidV4;
518 branch = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
519 const settings = yield* serverSettings.getSettings.pipe(
520 Effect.map((settings) => resolveProjectSettings(settings, input.projectId).settings),
521 Effect.orElseSucceed(() => null),
522 );
523 if (settings?.branchNamingMode === "static") {
524 branch = formatGeneratedBranchName(branch.slice(-8), {
525 mode: "static",
526 prefix: settings.branchNamePrefix,
527 instructions: "",
528 });
529 }
530 } else {
531 branch = yield* launchBranch(input.workspaceStrategy, project.workspaceRoot);
532 }
533 let worktreePath =
534 input.workspaceStrategy.type === "existing_worktree"
535 ? input.workspaceStrategy.worktreePath
536 : null;
537 if (input.workspaceStrategy.type === "worktree") {
538 if (runId !== null) {
539 yield* threads
540 .dispatch({
541 type: "prepared-run.progress",
542 commandId: CommandId.make(`${input.commandId}:progress:worktree`),
543 threadId,
544 runId,
545 phase: "worktree",
546 })
547 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
548 }
549 let startRef = input.workspaceStrategy.baseRef;
550 let baseRefName = input.workspaceStrategy.baseRef;
551 const remote =
552 input.workspaceStrategy.startFromOrigin === true
553 ? yield* git
554 .resolveWorktreeBaseRemote({
555 cwd: project.workspaceRoot,
556 refName: input.workspaceStrategy.baseRef,
557 })
558 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)))
559 : null;
560 const shouldFetch = remote !== null;
561 yield* setupTracker.stageStatus(threadId, "fetch", shouldFetch ? "running" : "skipped");
562 if (remote !== null) {
563 const remoteBase = yield* git
564 .fetchWorktreeBaseCommit({
565 cwd: project.workspaceRoot,
566 refName: input.workspaceStrategy.baseRef,
567 remote,
568 })
569 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
570 if (remoteBase !== null) {
571 startRef = remoteBase.commitSha;
572 baseRefName = `refs/remotes/${remoteBase.remoteRefName}`;
573 }
574 }
575 if (shouldFetch) yield* setupTracker.stageStatus(threadId, "fetch", "done");
576 if (branch !== null && (generatedTemporaryBranch || isTemporaryWorktreeBranch(branch))) {
577 const parts = branch.split("/");
578 for (let depth = 1; depth < parts.length; depth++) {
579 if (
580 yield* git
581 .hasCommit({
582 cwd: project.workspaceRoot,
583 refName: `refs/heads/${parts.slice(0, depth).join("/")}`,
584 })
585 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)))
586 ) {
587 branch = generatedTemporaryBranch
588 ? branch.replaceAll("/", "-")
589 : flattenTemporaryWorktreeBranchName(branch);
590 break;
591 }
592 }
593 }
594 yield* setupTracker.stageStatus(threadId, "checkout", "running");
595 let submoduleProgressReportedAt = Number.NEGATIVE_INFINITY;
596 const worktree = yield* git
597 .createWorktree(
598 {
599 cwd: project.workspaceRoot,
600 refName: startRef,
601 newRefName: branch!,
602 baseRefName,
603 path: null,
604 },
605 {
606 progress: {
607 onWorktreeClaimed: (path) =>
608 Effect.sync(() => {
609 createdWorktreePath = path;
610 createdBranch = branch;
611 }),
612 onCheckoutProgress: (progress) =>
613 setupTracker.stage(threadId, "checkout", { percent: progress.percent }),
614 onSubmodulesStarted: () =>
615 setupTracker
616 .stageStatus(threadId, "checkout", "done")
617 .pipe(
618 Effect.andThen(setupTracker.stageStatus(threadId, "submodules", "running")),
619 ),
620 onSubmodulesDisabled: ({ source }) =>
621 setupTracker.stageStatus(
622 threadId,
623 "submodules",
624 "skipped",
625 `disabled in ${source}`,
626 ),
627 onSubmoduleLine: (line) => {
628 // Paths may contain quotes; git closes the path with "': ".
629 const submodulePath = /^\s*Submodule path '(.+)': /.exec(line)?.[1];
630 if (submodulePath !== undefined) {
631 return setupTracker.stage(threadId, "submodules", { detail: submodulePath });
632 }
633 if (parseGitCloneProgressLine(line) === null) return Effect.void;
634 // Git redraws on every percent; hold the websocket to one update a second.
635 return Effect.flatMap(Clock.currentTimeMillis, (now) => {
636 if (now - submoduleProgressReportedAt < 1000) return Effect.void;
637 submoduleProgressReportedAt = now;
638 return setupTracker.stage(threadId, "submodules", {
639 detail: line.trim().replace(/\s+/g, " "),
640 });
641 });
642 },
643 onSubmodulesFinished: ({ ok, detail }) =>
644 setupTracker.stageStatus(
645 threadId,
646 "submodules",
647 ok ? "done" : "warning",
648 ok ? undefined : (detail ?? "submodule checkout failed"),
649 ),
650 },
651 },
652 )
653 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
654 worktreePath = worktree.worktree.path;
655 branch = worktree.worktree.refName;
656 createdWorktreePath = worktreePath;
657 createdBranch = branch;
658 yield* setupTracker.update(threadId, (snapshot) => ({
659 ...snapshot,
660 worktreePath,
661 branch,
662 stages: snapshot.stages.map((stage) =>
663 stage.id === "submodules" && stage.status === "pending"
664 ? { ...stage, status: "skipped", detail: "none" }
665 : stage,
666 ),
667 }));
668 yield* setupTracker.stageStatus(threadId, "checkout", "done");
669 }
670​
671 // Do not rewrite reused worktrees; that could undo the original branch rename.
672 if (reused === undefined) {
673 yield* threads
674 .dispatch({
675 type: "thread.metadata.update",
676 commandId: CommandId.make(`${input.commandId}:workspace`),
677 threadId,
678 branch,
679 worktreePath,
680 })
681 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
682 }
683 workspaceRecorded = true;
684​
685 if (
686 reused === undefined &&
687 worktreePath !== null &&
688 branch !== null &&
689 initialMessage !== undefined &&
690 (generatedTemporaryBranch || isTemporaryWorktreeBranch(branch))
691 ) {
692 const oldBranch = branch;
693 const worktreeCwd = worktreePath;
694 branchRename = yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe(
695 Effect.flatMap(({ branch: newBranch, exactName }) =>
696 git
697 .renameBranch({
698 cwd: worktreeCwd,
699 oldBranch,
700 newBranch,
701 ...(exactName ? { exactName: true } : {}),
702 })
703 .pipe(
704 // A cancel must see the renamed branch, or its cleanup deletes the old name.
705 Effect.tap((renamed) =>
706 Effect.sync(() => {
707 createdBranch = renamed.branch;
708 }),
709 ),
710 Effect.uninterruptible,
711 ),
712 ),
713 Effect.flatMap((renamed) =>
714 Effect.gen(function* () {
715 yield* threads
716 .dispatch({
717 type: "thread.metadata.update",
718 commandId: CommandId.make(`${input.commandId}:branch-rename`),
719 threadId,
720 branch: renamed.branch,
721 worktreePath: worktreeCwd,
722 expectedBranch: oldBranch,
723 expectedWorktreePath: worktreeCwd,
724 })
725 .pipe(
726 Effect.catchCause((cause) =>
727 Effect.logWarning("Parent thread worktree branch update failed", {
728 threadId,
729 cause,
730 }),
731 ),
732 );
733 // Update parents first so children inherit names; reread each pass for newly updated descendants.
734 const visited = new Set([threadId]);
735 while (true) {
736 const snapshot = yield* threads.getShellSnapshot({ worktreePath: worktreeCwd });
737 const sharing = [...snapshot.threads, ...snapshot.archivedThreads].filter(
738 (thread) => !visited.has(thread.id) && thread.branch === oldBranch,
739 );
740 if (sharing.length === 0) break;
741 for (const thread of sharing) {
742 visited.add(thread.id);
743 yield* threads
744 .dispatch({
745 type: "thread.metadata.update",
746 commandId: CommandId.make(`${input.commandId}:branch-rename:${thread.id}`),
747 threadId: thread.id,
748 branch: renamed.branch,
749 expectedBranch: oldBranch,
750 expectedWorktreePath: worktreeCwd,
751 })
752 .pipe(
753 Effect.catchCause((cause) =>
754 Effect.logWarning("Shared thread worktree branch update failed", {
755 threadId: thread.id,
756 cause,
757 }),
758 ),
759 );
760 }
761 }
762 }),
763 ),
764 Effect.catchCause((cause) =>
765 Effect.logWarning("Thread worktree branch rename failed", {
766 commandId: input.commandId,
767 threadId,
768 oldBranch,
769 cause,
770 }).pipe(
771 Effect.andThen(
772 runId === null || Cause.hasInterruptsOnly(cause)
773 ? Effect.void
774 : recordBranchRenameFailure(threadId, runId, oldBranch, cause),
775 ),
776 ),
777 ),
778 Effect.forkIn(preparationScope),
779 );
780 }
781​
782 if (runId !== null && worktreePath !== null) {
783 yield* threads
784 .dispatch({
785 type: "prepared-run.progress",
786 commandId: CommandId.make(`${input.commandId}:progress:setup`),
787 threadId,
788 runId,
789 phase: "setup",
790 })
791 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
792 }
793 yield* setupTracker.stageStatus(threadId, "setup-script", "running");
794 const setup =
795 worktreePath === null
796 ? ({ status: "no-script" } as const)
797 : yield* setupScripts
798 .runForThread({
799 threadId,
800 projectId: input.projectId,
801 projectCwd: project.workspaceRoot,
802 worktreePath,
803 ...(tracked
804 ? {
805 observeCompletion: {
806 onOutputLine: (line: string) =>
807 setupTracker.appendTail(threadId, "setup-script", line),
808 },
809 }
810 : {}),
811 project: {
812 id: project.id,
813 workspaceRoot: project.workspaceRoot,
814 scripts: project.scripts,
815 },
816 })
817 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
818​
819 let awaitAsyncSetup = Effect.void;
820 if (setup.status === "started") {
821 setupTerminalId = setup.terminalId;
822 yield* setupTracker.update(threadId, (snapshot) => ({
823 ...snapshot,
824 setupScript: {
825 name: setup.scriptName,
826 command: setup.scriptCommand,
827 terminalId: setup.terminalId,
828 },
829 }));
830 if (setup.completion) {
831 const awaitCompletion = Effect.gen(function* () {
832 const completion = yield* setup.completion!;
833 yield* setupTracker.stage(threadId, "setup-script", {
834 status: completion.exitCode === 0 ? "done" : "failed",
835 detail: `exited with ${completion.exitCode ?? "no exit code"}`,
836 });
837 if (completion.exitCode !== 0 && !setup.async)
838 return yield* mapError(
839 input,
840 "run-setup-script",
841 threadId,
842 )(`Setup script exited with ${completion.exitCode ?? "no exit code"}.`);
843 });
844 if (setup.async) {
845 awaitAsyncSetup = awaitCompletion.pipe(
846 Effect.catchCause((cause) =>
847 setupTracker.stage(threadId, "setup-script", {
848 status: "failed",
849 detail: failureDetail(Cause.squash(cause)),
850 }),
851 ),
852 );
853 } else {
854 yield* awaitCompletion;
855 }
856 } else {
857 yield* setupTracker.stageStatus(threadId, "setup-script", "done");
858 }
859 } else {
860 yield* setupTracker.stageStatus(threadId, "setup-script", "skipped");
861 }
862 // The agent must start on the branch name the thread will show.
863 if (branchRename !== null) yield* Fiber.join(branchRename);
864 yield* setupTracker.markUncancellable(threadId);
865 yield* setupTracker.stageStatus(threadId, "agent", "running");
866 if (runId !== null) {
867 yield* threads
868 .dispatch({
869 type: "prepared-run.release",
870 commandId: CommandId.make(`${input.commandId}:release`),
871 threadId,
872 runId,
873 })
874 .pipe(
875 Effect.mapError(mapError(input, "release-run", threadId)),
876 Effect.tap(() =>
877 Effect.sync(() => {
878 runReleased = true;
879 }),
880 ),
881 Effect.uninterruptible,
882 );
883 }
884 yield* setupTracker.stageStatus(threadId, "agent", "done");
885 yield* awaitAsyncSetup;
886 yield* setupTracker.finish(threadId, "done");
887 }).pipe(
888 Effect.onError((cause) =>
889 Effect.gen(function* () {
890 const cancelled = Cause.hasInterruptsOnly(cause);
891 yield* setupTracker.finish(
892 threadId,
893 cancelled ? "cancelled" : "failed",
894 cancelled ? null : failureDetail(Cause.squash(cause)),
895 );
896 if (cancelled && setupTerminalId)
897 yield* terminals
898 .close({ threadId, terminalId: setupTerminalId, deleteHistory: true })
899 .pipe(Effect.ignore);
900 if (
901 tracked &&
902 createdWorktreePath &&
903 ((cancelled && !runReleased) || !workspaceRecorded)
904 ) {
905 if (branchRename !== null) yield* Fiber.interrupt(branchRename);
906 const removedPath = createdWorktreePath;
907 const removedBranch = createdBranch;
908 // Forget worktrees only after removal succeeds; failed removals must not reuse partially written checkouts.
909 yield* git
910 .removeWorktree({ cwd: project.workspaceRoot, path: removedPath, force: true })
911 .pipe(
912 Effect.andThen(
913 removedBranch === null
914 ? Effect.void
915 : git
916 .deleteLocalBranch({
917 cwd: project.workspaceRoot,
918 refName: removedBranch,
919 force: true,
920 })
921 .pipe(Effect.ignoreCause({ log: true })),
922 ),
923 Effect.andThen(
924 threads
925 .dispatch({
926 type: "thread.metadata.update",
927 commandId: CommandId.make(`${input.commandId}:cancel-workspace`),
928 threadId,
929 worktreePath: null,
930 branch: null,
931 })
932 .pipe(Effect.ignore),
933 ),
934 Effect.catchCause((removeCause) =>
935 Effect.logWarning("Failed to remove an abandoned thread worktree", {
936 commandId: input.commandId,
937 threadId,
938 path: removedPath,
939 cause: removeCause,
940 }),
941 ),
942 );
943 }
944 }),
945 ),
946 );
947 });
948​
949 const failPreparedRun = (
950 input: Pick<PreparationInput, "commandId">,
951 threadId: ThreadId,
952 runId: RunId | null,
953 cause: unknown,
954 ) =>
955 runId === null
956 ? Effect.logWarning("Thread workspace preparation failed", {
957 commandId: input.commandId,
958 threadId,
959 cause,
960 })
961 : threads
962 .dispatch({
963 type: "prepared-run.fail",
964 commandId: CommandId.make(`${input.commandId}:fail`),
965 threadId,
966 runId,
967 failure: makeProviderFailure({
968 cause,
969 message: failureDetail(cause),
970 class: "validation_error",
971 retryable: false,
972 }),
973 })
974 .pipe(
975 Effect.catchCause((persistCause) =>
976 Effect.logWarning("Failed to persist thread workspace preparation failure", {
977 commandId: input.commandId,
978 threadId,
979 cause,
980 persistCause,
981 }),
982 ),
983 );
984​
985 const reservePreparation = (commandId: CommandId) =>
986 Ref.modify(scheduledLaunches, (scheduled) => {
987 if (scheduled.has(commandId)) return [false, scheduled] as const;
988 const next = new Set(scheduled);
989 next.add(commandId);
990 return [true, next] as const;
991 });
992​
993 const releasePreparation = (commandId: CommandId) =>
994 Ref.update(scheduledLaunches, (scheduled) => {
995 const next = new Set(scheduled);
996 next.delete(commandId);
997 return next;
998 });
999​
1000 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
1001 input: PreparationInput,
1002 threadId: ThreadId,
1003 runId: RunId | null,
1004 ) {
1005 const preparation = Effect.gen(function* () {
1006 const prepare = prepareInBackground(input, threadId, runId);
1007 if (
1008 runId === null ||
1009 (input.workspaceStrategy.type !== "worktree" && input.reusedWorktree === undefined)
1010 ) {
1011 return yield* prepare;
1013 const afterSequence = yield* threads.getThreadEventSequence(threadId);
1014 const projection = yield* threads.getThreadRecords(threadId, ["runs"], { runIds: [runId] });
1015 if (projection.runs.find((run) => run.id === runId)?.status !== "preparing") return;
1016 const interruption = threads
1017 .streamStoredEventsFrom({ threadId, afterSequence, eventType: "run.updated" })
1018 .pipe(
1019 Stream.filter(
1020 (stored) =>
1021 stored.event.type === "run.updated" &&
1022 stored.event.payload.id === runId &&
1023 (stored.event.payload.status === "interrupted" ||
1024 stored.event.payload.status === "cancelled"),
1025 ),
1026 Stream.runHead,
1027 Effect.flatMap((event) => (Option.isSome(event) ? Effect.interrupt : Effect.never)),
1028 );
1029 yield* Effect.raceFirst(prepare, interruption);
1030 });
1031 yield* preparation.pipe(
1032 Effect.onError((cause) =>
1033 failPreparedRun(
1034 input,
1035 threadId,
1036 runId,
1037 Cause.hasInterruptsOnly(cause) ? "Worktree setup cancelled." : Cause.squash(cause),
1038 ),
1039 ),
1040 Effect.ignoreCause,
1041 Effect.ensuring(releasePreparation(input.commandId)),
1042 Effect.forkIn(preparationScope),
1043 );
1044 });
1045​
1046 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
1047 function* (request) {
1048 // Scratch has no Git repository. Normalize before folder allocation so
1049 // durable preparation and retries use the thread's own Scratch folder.
1050 const input: ThreadLaunchInput =
1051 request.workspaceStrategy.type === "worktree" &&
1052 (yield* managedFolders.isScratchProject(request.projectId))
1053 ? { ...request, workspaceStrategy: { type: "root" } }
1054 : request;
1055 yield* ProjectCloneTracker.rejectCommandsDuringClone(cloneTracker, {
1056 type: "thread.create",
1057 projectId: input.projectId,
1058 }).pipe(Effect.mapError(mapError(input, "resolve-project")));
1059 const project = yield* projects.getById(input.projectId).pipe(
1060 Effect.mapError(mapError(input, "resolve-project")),
1061 Effect.flatMap(
1062 Option.match({
1063 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
1064 onSome: Effect.succeed,
1065 }),
1066 ),
1067 );
1068 if (input.reuseExistingThread === true && input.threadId === undefined) {
1069 return yield* mapError(
1070 input,
1071 "update-thread",
1072 )("Reusing an existing thread requires a thread id.");
1074​
1075 const launchReceipt = yield* readReceipt(input, input.commandId);
1076 yield* threads.assertProviderInstanceEnabled({
1077 projectId: input.projectId,
1078 commandId: input.commandId,
1079 instanceId: input.modelSelection.instanceId,
1080 });
1081 return yield* Effect.gen(function* () {
1082 // Recover ids from accepted launch receipts before allocating; retries have no client id and new ids collide with receipts.
1083 const reusableLaunchReceipt =
1084 input.threadId === undefined &&
1085 Option.isSome(launchReceipt) &&
1086 launchReceipt.value.status === "accepted" &&
1087 launchReceipt.value.commandType === "thread.create"
1088 ? launchReceipt.value
1089 : undefined;
1090 const candidateThreadId =
1091 input.threadId ??
1092 reusableLaunchReceipt?.threadId ??
1093 (yield* ids.allocate
1094 .thread({ projectId: input.projectId })
1095 .pipe(Effect.mapError(mapError(input, "create-thread"))));
1096​
1097 if (reusableLaunchReceipt !== undefined) {
1098 const shell = yield* threads
1099 .getThreadShell(candidateThreadId)
1100 .pipe(Effect.mapError(mapError(input, "create-thread", candidateThreadId)));
1101 if (shell === null) {
1102 return yield* mapError(input, "create-thread", candidateThreadId)("Thread not found.");
1104 if (shell.projectId !== input.projectId) {
1105 return yield* mapError(
1106 input,
1107 "resolve-project",
1108 candidateThreadId,
1109 )("Project identity changed.");
1112​
1113 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
1114 yield* validateReusableThread(input, candidateThreadId);
1116​
1117 const workspaceStrategy: ThreadLaunchWorkspaceStrategy =
1118 input.workspaceStrategy.type === "root" && Option.isNone(launchReceipt)
1119 ? Option.match(
1120 yield* managedFolders
1121 .folderForThread({
1122 projectId: input.projectId,
1123 threadId: candidateThreadId,
1124 text: input.initialMessage?.text ?? input.title,
1125 })
1126 .pipe(Effect.mapError(mapError(input, "provision-worktree", candidateThreadId))),
1128 onNone: () => input.workspaceStrategy,
1129 onSome: (worktreePath) => ({ type: "existing_worktree", worktreePath }),
1130 },
1132 : input.workspaceStrategy;
1133 const initialBranch = yield* launchBranch(workspaceStrategy, project.workspaceRoot);
1134 const initialWorktreePath =
1135 workspaceStrategy.type === "existing_worktree" ? workspaceStrategy.worktreePath : null;
1136 const claimDispatch =
1137 input.reuseExistingThread === true
1138 ? threads.dispatch({
1139 type: "thread.metadata.update",
1140 commandId: input.commandId,
1141 threadId: candidateThreadId,
1142 expectedEmpty: true,
1143 })
1144 : threads.dispatch({
1145 type: "thread.create",
1146 commandId: input.commandId,
1147 threadId: candidateThreadId,
1148 projectId: input.projectId,
1149 title: input.title,
1150 modelSelection: input.modelSelection,
1151 runtimeMode: input.runtimeMode,
1152 interactionMode: input.interactionMode,
1153 branch: initialBranch,
1154 worktreePath: initialWorktreePath,
1155 ...(input.importedNativeThread === undefined
1156 ? {}
1157 : { importedNativeThread: input.importedNativeThread }),
1158 ...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }),
1159 ...(input.delegatedFrom === undefined
1160 ? {}
1161 : { delegatedFrom: input.delegatedFrom }),
1162 createdBy: input.createdBy,
1163 creationSource: input.creationSource,
1164 });
1165 const claimed = yield* claimDispatch.pipe(
1166 Effect.mapError(
1167 mapError(
1168 input,
1169 input.reuseExistingThread === true ? "update-thread" : "create-thread",
1170 candidateThreadId,
1171 ),
1172 ),
1173 );
1174 const threadId =
1175 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
1176 .threadId ?? candidateThreadId;
1177 if (project.id !== input.projectId) {
1178 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
1180 let runId: RunId | null = null;
1181 let messageSequence: number | undefined;
1182 let messageWasAlreadyAccepted = false;
1183 if (input.initialMessage !== undefined) {
1184 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
1185 const messageReceipt = yield* readReceipt(input, messageCommandId);
1186 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
1187 const messageId =
1188 input.initialMessage.messageId ??
1189 (yield* ids.allocate
1190 .message({ threadId, ordinal: 1 })
1191 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
1192 const dispatched = yield* threads
1193 .dispatch({
1194 type: "message.dispatch",
1195 commandId: messageCommandId,
1196 threadId,
1197 messageId,
1198 text: input.initialMessage.text,
1199 ...(input.initialMessage.scheduledTaskId === undefined
1200 ? {}
1201 : { scheduledTaskId: input.initialMessage.scheduledTaskId }),
1202 ...(input.initialMessage.senderThreadId === undefined
1203 ? {}
1204 : { senderThreadId: input.initialMessage.senderThreadId }),
1205 attachments: input.initialMessage.attachments,
1206 ...(input.initialMessage.context ? { context: input.initialMessage.context } : {}),
1207 ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
1208 modelSelection: input.modelSelection,
1209 dispatchMode: { type: "defer_start", workspaceStrategy },
1210 createdBy: input.createdBy,
1211 creationSource: input.creationSource,
1212 })
1213 .pipe(
1214 // An agent's launch can land on a thread that a replay, or a concurrent
1215 // launch with the same key, created with broader modes. The orchestrator
1216 // refuses the message under the thread's lock; the user's own clients
1217 // launch into their own drafts, whatever modes those hold.
1218 input.createdBy === "agent"
1219 ? Effect.provideService(DispatchModeLimit, {
1220 runtimeMode: input.runtimeMode,
1221 interactionMode: input.interactionMode,
1222 })
1223 : (effect) => effect,
1224 Effect.mapError(mapError(input, "dispatch-message", threadId)),
1225 );
1226 // A concurrent retry can read no receipt and still replay the dispatch.
1227 messageWasAlreadyAccepted ||= dispatched.replayed === true;
1228 messageSequence = dispatched.sequence;
1229 const runCreated = dispatched.storedEvents.find(
1230 (stored) => stored.event.type === "run.created",
1231 );
1232 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
1233 if (runId === null) {
1234 return yield* mapError(
1235 input,
1236 "dispatch-message",
1237 threadId,
1238 )("Initial message was accepted without a durable run.");
1241​
1242 // Fork preparation before the full projection read; it is only part of the reply.
1243 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : true;
1244 if (shouldSchedule && (yield* reservePreparation(input.commandId))) {
1245 yield* Effect.gen(function* () {
1246 const current =
1247 runId === null
1248 ? null
1249 : yield* threads
1250 .getThreadRecords(threadId, ["runs"], { runIds: [runId] })
1251 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
1252 if (
1253 current !== null &&
1254 !current.runs.some((run) => run.id === runId && run.status === "preparing")
1255 ) {
1256 return yield* releasePreparation(input.commandId);
1258 const boundWorktreePath = current?.thread.worktreePath ?? null;
1259 const preparationStrategy: ThreadLaunchWorkspaceStrategy =
1260 Option.isSome(launchReceipt) &&
1261 workspaceStrategy.type === "root" &&
1262 boundWorktreePath !== null
1263 ? {
1264 type: "existing_worktree",
1265 worktreePath: boundWorktreePath,
1266 branch: workspaceStrategy.branch,
1268 : workspaceStrategy;
1269 yield* schedulePreparation(
1270 { ...input, workspaceStrategy: preparationStrategy },
1271 threadId,
1272 runId,
1273 );
1274 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
1276 const projection = yield* threads
1277 .getThreadProjection(threadId)
1278 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
1279​
1280 return {
1281 threadId,
1282 projection,
1283 // An attempt that failed after claiming the thread recorded nothing, so
1284 // only a repeat of the final write counts as resumed.
1285 resumed:
1286 input.initialMessage === undefined
1287 ? Option.isSome(launchReceipt) || claimed.replayed === true
1288 : messageWasAlreadyAccepted,
1289 ...(messageSequence === undefined ? {} : { sequence: messageSequence }),
1290 };
1291 });
1292 },
1293 );
1294​
1295 const prepareRun: ThreadLaunchService["Service"]["prepareRun"] = Effect.fn(
1296 "ThreadLaunchService.prepareRun",
1297 )(function* (input) {
1298 const scheduled = yield* Effect.gen(function* () {
1299 const { thread, runs } = yield* threads.getThreadRecords(input.threadId, ["runs"], {
1300 runIds: [input.runId],
1301 });
1302 const run = runs.find((candidate) => candidate.id === input.runId);
1303 const workspacePreparation = run?.workspacePreparation;
1304 if (run?.status !== "preparing" || workspacePreparation === undefined) return;
1305 if (!(yield* reservePreparation(input.commandId))) return;
1306 yield* scheduleRunPreparation(input, thread, run, workspacePreparation).pipe(
1307 Effect.onError(() => releasePreparation(input.commandId)),
1308 );
1309 }).pipe(Effect.exit);
1310 if (Exit.isFailure(scheduled)) {
1311 yield* failPreparedRun(input, input.threadId, input.runId, Cause.squash(scheduled.cause));
1313 });
1314​
1315 const retryPreparation: ThreadLaunchService["Service"]["retryPreparation"] = Effect.fn(
1316 "ThreadLaunchService.retryPreparation",
1317 )(function* (input) {
1318 const dispatched = yield* threads.dispatch({
1319 type: "prepared-run.retry",
1320 commandId: input.commandId,
1321 threadId: input.threadId,
1322 runId: input.runId,
1323 });
1324 yield* prepareRun(input);
1325 return dispatched;
1326 });
1327​
1328 const scheduleRunPreparation = Effect.fn("ThreadLaunchService.scheduleRunPreparation")(function* (
1329 input: ThreadLaunchPreparationInput,
1330 thread: OrchestrationV2ThreadProjection["thread"],
1331 run: OrchestrationV2ThreadProjection["runs"][number],
1332 workspacePreparation: ThreadLaunchWorkspaceStrategy,
1333 ) {
1334 const { messages } = yield* threads.getThreadRecords(input.threadId, ["messages"], {
1335 messageIds: [run.userMessageId],
1336 });
1337 const message = messages.find((candidate) => candidate.id === run.userMessageId);
1338 const reuse =
1339 workspacePreparation.type === "worktree" &&
1340 thread.worktreePath !== null &&
1341 thread.branch !== null
1342 ? {
1343 strategy: {
1344 type: "existing_worktree" as const,
1345 worktreePath: thread.worktreePath,
1346 branch: thread.branch,
1347 },
1348 reusedWorktree: { baseRef: workspacePreparation.baseRef },
1350 : null;
1351 return yield* schedulePreparation(
1353 commandId: input.commandId,
1354 projectId: thread.projectId,
1355 workspaceStrategy: reuse?.strategy ?? workspacePreparation,
1356 ...(reuse === null ? {} : { reusedWorktree: reuse.reusedWorktree }),
1357 ...(message === undefined
1358 ? {}
1359 : {
1360 initialMessage: {
1361 text: message.text,
1362 attachments: message.attachments,
1363 ...(message.context ? { context: message.context } : {}),
1364 },
1365 }),
1366 },
1367 input.threadId,
1368 run.id,
1369 );
1370 });
1371​
1372 return ThreadLaunchService.of({ launch, checkWorktreeBase, retryPreparation, prepareRun });
1373});
1374​
1375export const layer = Layer.effect(ThreadLaunchService, make);