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

ThreadLaunchService.ts

983 lines37.8 KB

1import * as WorktreeSetupTracker from "../project/WorktreeSetupTracker.ts";
2import * as ProjectCloneTracker from "../project/ProjectCloneTracker.ts";
3import * as TerminalManager from "../terminal/Manager.ts";
4import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
5import {
6 CommandId,
7 type ChatAttachment,
8 type MessageId,
9 type ModelSelection,
10 type OrchestrationV2Actor,
11 type OrchestrationV2CreationSource,
12 type OrchestrationV2ProviderThreadNativeMetadata,
13 type OrchestrationV2ThreadProjection,
14 type ProviderDriverKind,
15 type ProviderInteractionMode,
16 ProjectId,
17 type RunId,
18 type RuntimeMode,
19 type ScheduledTaskId,
20 ThreadId,
21} from "@t3tools/contracts";
22import * as Cause from "effect/Cause";
23import * as Context from "effect/Context";
24import * as Effect from "effect/Effect";
25import * as Exit from "effect/Exit";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Ref from "effect/Ref";
29import * as Schema from "effect/Schema";
30import * as Scope from "effect/Scope";
31import {
32 buildTemporaryWorktreeBranchName,
33 flattenTemporaryWorktreeBranchName,
34 isTemporaryWorktreeBranch,
35 WORKTREE_BRANCH_PREFIX,
36} from "@t3tools/shared/git";
37​
38import * as GitWorkflow from "../git/GitWorkflowService.ts";
39import * as ProjectService from "../project/ProjectService.ts";
40import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
41import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
42import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
43import * as ServerSettings from "../serverSettings.ts";
44import * as TextGeneration from "../textGeneration/TextGeneration.ts";
45import * as CommandReceiptStore from "./CommandReceiptStore.ts";
46import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
47import type * as Orchestrator from "./Orchestrator.ts";
48import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
49import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
50import * as ThreadManagement from "./ThreadManagementService.ts";
51​
52export type ThreadLaunchWorkspaceStrategy =
53 | { readonly type: "root"; readonly branch?: string | undefined }
54 | {
55 readonly type: "existing_worktree";
56 readonly worktreePath: string;
57 readonly branch?: string | undefined;
58 }
59 | {
60 readonly type: "worktree";
61 readonly baseRef: string;
62 readonly branch?: string | undefined;
63 readonly startFromOrigin?: boolean | undefined;
64 };
65​
66export interface ThreadLaunchInitialMessage {
67 readonly messageId?: MessageId;
68 readonly scheduledTaskId?: ScheduledTaskId;
69 readonly senderThreadId?: ThreadId;
70 readonly text: string;
71 readonly attachments: ReadonlyArray<ChatAttachment>;
72 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
74​
75export interface ThreadLaunchInput {
76 readonly commandId: CommandId;
77 readonly threadId?: ThreadId;
78 readonly reuseExistingThread?: boolean;
79 readonly projectId: ProjectId;
80 readonly title: string;
81 readonly generateTitle?: boolean;
82 readonly modelSelection: ModelSelection;
83 readonly runtimeMode: RuntimeMode;
84 readonly interactionMode: ProviderInteractionMode;
85 readonly workspaceStrategy: ThreadLaunchWorkspaceStrategy;
86 readonly initialMessage?: ThreadLaunchInitialMessage;
87 readonly importedNativeThread?: {
88 readonly ref: {
89 readonly driver: ProviderDriverKind;
90 readonly nativeId: string;
91 readonly strength: "strong";
92 };
93 readonly metadata?: OrchestrationV2ProviderThreadNativeMetadata;
94 };
95 readonly createdBy: OrchestrationV2Actor;
96 readonly creationSource: OrchestrationV2CreationSource;
98​
99/** What workspace preparation reads from a launch; a retry rebuilds it from the run. */
100type PreparationInput = Pick<
101 ThreadLaunchInput,
102 "commandId" | "projectId" | "workspaceStrategy" | "initialMessage"
103> & {
104 /**
105 * Set when a retry reuses the worktree its failed attempt created and
106 * recorded. Its setup is tracked like a new one, but the thread already
107 * records the workspace, and a branch rename may still be running.
108 */
109 readonly reusedWorktree?: { readonly baseRef: string };
110};
111​
112export interface ThreadLaunchRetryInput {
113 readonly commandId: CommandId;
114 readonly threadId: ThreadId;
115 readonly runId: RunId;
117​
118export interface ThreadLaunchResult {
119 readonly threadId: ThreadId;
120 readonly projection: OrchestrationV2ThreadProjection;
121 readonly resumed: boolean;
123​
124export class ThreadLaunchError extends Schema.TaggedError<ThreadLaunchError>()(
125 "ThreadLaunchError",
126 {
127 operation: Schema.Literals([
128 "resolve-project",
129 "read-receipt",
130 "generate-metadata",
131 "provision-worktree",
132 "run-setup-script",
133 "create-thread",
134 "update-thread",
135 "dispatch-message",
136 "release-run",
137 "fail-run",
138 ]),
139 commandId: CommandId,
140 projectId: ProjectId,
141 threadId: Schema.optional(ThreadId),
142 cause: Schema.Defect(),
143 },
144) {
145 override get message(): string {
146 return `Thread launch ${this.commandId} failed during ${this.operation}.`;
147 }
149​
150export class ThreadLaunchService extends Context.Service<
151 ThreadLaunchService,
152 {
153 readonly launch: (
154 input: ThreadLaunchInput,
155 ) => Effect.Effect<ThreadLaunchResult, ThreadLaunchError>;
156 /** Dispatches prepared-run.retry and prepares the run's workspace again. */
157 readonly retryPreparation: (
158 input: ThreadLaunchRetryInput,
159 ) => Effect.Effect<Orchestrator.OrchestratorV2DispatchResult, Orchestrator.OrchestratorV2Error>;
160 }
161>()("t3/orchestration-v2/ThreadLaunchService") {}
162​
163const isThreadLaunchError = Schema.is(ThreadLaunchError);
164​
165function failureDetail(error: unknown): string {
166 if (isThreadLaunchError(error)) {
167 const cause = error.cause;
168 const detail = cause instanceof Error ? cause.message : String(cause);
169 return `Workspace preparation failed during ${error.operation.replaceAll("-", " ")}: ${detail}`;
170 }
171 return `Workspace preparation failed: ${error instanceof Error ? error.message : String(error)}`;
173​
174const make = Effect.gen(function* () {
175 const projects = yield* ProjectService.ProjectService;
176 const setupTracker = yield* WorktreeSetupTracker.WorktreeSetupTracker;
177 const cloneTracker = yield* ProjectCloneTracker.ProjectCloneTracker;
178 const terminals = yield* TerminalManager.TerminalManager;
179 const git = yield* GitWorkflow.GitWorkflowService;
180 const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
181 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
182 const serverSettings = yield* ServerSettings.ServerSettingsService;
183 const textGeneration = yield* TextGeneration.TextGeneration;
184 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
185 const ids = yield* IdAllocator.IdAllocatorV2;
186 const threads = yield* ThreadManagement.ThreadManagementService;
187 const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;
188 const preparationScope = yield* Scope.make("sequential");
189 const scheduledLaunches = yield* Ref.make<ReadonlySet<CommandId>>(new Set());
190 yield* Effect.addFinalizer(() => Scope.close(preparationScope, Exit.void));
191​
192 const mapError =
193 (input: PreparationInput, operation: ThreadLaunchError["operation"], threadId?: ThreadId) =>
194 (cause: unknown) =>
195 new ThreadLaunchError({
196 operation,
197 commandId: input.commandId,
198 projectId: input.projectId,
199 ...(threadId === undefined ? {} : { threadId }),
200 cause,
201 });
202​
203 const readReceipt = (input: ThreadLaunchInput, commandId: CommandId) =>
204 receipts
205 .getByCommandId(commandId)
206 .pipe(Effect.mapError(mapError(input, "read-receipt", input.threadId)));
207​
208 const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")(function* (
209 input: ThreadLaunchInput,
210 threadId: ThreadId,
211 ) {
212 const projection = yield* threads
213 .getThreadRecords(threadId, ["runs"])
214 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
215 if (
216 projection.thread.projectId !== input.projectId ||
217 projection.thread.archivedAt !== null ||
218 projection.thread.deletedAt !== null ||
219 (yield* threads
220 .getMessageCount(threadId)
221 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)))) > 0 ||
222 projection.runs.length > 0
223 ) {
224 return yield* mapError(
225 input,
226 "update-thread",
227 threadId,
228 )("Only an empty active thread in the target project can change workspace during launch.");
229 }
230 });
231​
232 const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* (
233 input: PreparationInput,
234 threadId: ThreadId,
235 runId: RunId | null,
236 ) {
237 const project = yield* projects.getById(input.projectId).pipe(
238 Effect.mapError(mapError(input, "resolve-project", threadId)),
239 Effect.flatMap(
240 Option.match({
241 onNone: () =>
242 Effect.fail(mapError(input, "resolve-project", threadId)("Project no longer exists.")),
243 onSome: Effect.succeed,
244 }),
245 ),
246 );
247​
248 const reused = input.reusedWorktree;
249 const tracked = input.workspaceStrategy.type === "worktree" || reused !== undefined;
250 let createdWorktreePath: string | null = null;
251 let setupTerminalId: string | null = null;
252 let workspaceRecorded = false;
253 if (input.workspaceStrategy.type === "worktree") {
254 yield* setupTracker.begin({
255 threadId,
256 branch: input.workspaceStrategy.branch ?? null,
257 baseRef: input.workspaceStrategy.baseRef,
258 stages: ["fetch", "checkout", "setup-script", "agent"],
259 fiber: yield* Effect.fiber,
260 });
261 } else if (reused !== undefined) {
262 yield* setupTracker.begin({
263 threadId,
264 branch: input.workspaceStrategy.branch ?? null,
265 baseRef: reused.baseRef,
266 stages: ["setup-script", "agent"],
267 fiber: yield* Effect.fiber,
268 });
269 }
270 yield* Effect.gen(function* () {
271 const initialMessage = input.initialMessage;
272 const generateBranchNameFor = (cwd: string, message: ThreadLaunchInitialMessage) =>
273 Effect.gen(function* () {
274 const settings = resolveProjectSettings(
275 yield* serverSettings.getSettings,
276 input.projectId,
277 ).settings;
278 const modelSelection =
279 settings.sourceControlWriterModelSelection === null
280 ? settings.textGenerationModelSelection
281 : ServerSettings.resolveSourceControlWriterModelSelection(
282 settings,
283 yield* providerRegistry.getProviders,
284 );
285 return yield* textGeneration
286 .generateBranchName({
287 naming: {
288 mode: settings.branchNamingMode,
289 prefix: settings.branchNamePrefix,
290 instructions: settings.branchNameInstructions,
291 },
292 cwd,
293 message: message.text,
294 attachments: message.attachments,
295 ...(message.context ? { context: message.context } : {}),
296 modelSelection,
297 })
298 .pipe(
299 Effect.map((result) => ({
300 branch: result.branch,
301 exactName: settings.branchNamingMode === "custom",
302 })),
303 );
304 });
305​
306 // The server owns worktree naming: without an explicit branch, provision
307 // under a temporary `t3/<hash>` name so the worktree never waits on
308 // name generation, then rename in the background below.
309 const requestedBranch = input.workspaceStrategy.branch;
310 let branch: string | null;
311 if (input.workspaceStrategy.type === "worktree" && requestedBranch === undefined) {
312 const uuid = yield* randomUuidV4;
313 branch = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
314 } else {
315 branch = requestedBranch ?? null;
316 }
317 let worktreePath =
318 input.workspaceStrategy.type === "existing_worktree"
319 ? input.workspaceStrategy.worktreePath
320 : null;
321 if (input.workspaceStrategy.type === "worktree") {
322 if (runId !== null) {
323 yield* threads
324 .dispatch({
325 type: "prepared-run.progress",
326 commandId: CommandId.make(`${input.commandId}:progress:worktree`),
327 threadId,
328 runId,
329 phase: "worktree",
330 })
331 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
332 }
333 let startRef = input.workspaceStrategy.baseRef;
334 // "Start from origin" is a stored default; repos without the requested
335 // remote branch fall back to the local base branch.
336 const startFromOrigin =
337 input.workspaceStrategy.startFromOrigin === true &&
338 (yield* git
339 .remoteExists({ cwd: project.workspaceRoot, remoteName: "origin" })
340 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))));
341 yield* setupTracker.stageStatus(threadId, "fetch", startFromOrigin ? "running" : "skipped");
342 if (startFromOrigin) {
343 yield* git
344 .fetchRemote({
345 cwd: project.workspaceRoot,
346 remoteName: "origin",
347 refName: input.workspaceStrategy.baseRef,
348 })
349 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
350 const remoteBaseExists = yield* git
351 .remoteBranchExists({
352 cwd: project.workspaceRoot,
353 refName: input.workspaceStrategy.baseRef,
354 remoteName: "origin",
355 })
356 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
357 if (remoteBaseExists) {
358 startRef = yield* git
359 .resolveRemoteTrackingCommit({
360 cwd: project.workspaceRoot,
361 refName: input.workspaceStrategy.baseRef,
362 fallbackRemoteName: "origin",
363 })
364 .pipe(
365 Effect.map((resolved) => resolved.commitSha),
366 Effect.mapError(mapError(input, "provision-worktree", threadId)),
367 );
368 }
369 }
370 if (startFromOrigin) yield* setupTracker.stageStatus(threadId, "fetch", "done");
371 if (
372 branch !== null &&
373 isTemporaryWorktreeBranch(branch) &&
374 (yield* git
375 .hasCommit({
376 cwd: project.workspaceRoot,
377 refName: `refs/heads/${WORKTREE_BRANCH_PREFIX}`,
378 })
379 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))))
380 ) {
381 branch = flattenTemporaryWorktreeBranchName(branch);
382 }
383 yield* setupTracker.stageStatus(threadId, "checkout", "running");
384 const worktree = yield* git
385 .createWorktree(
386 {
387 cwd: project.workspaceRoot,
388 refName: startRef,
389 newRefName: branch!,
390 baseRefName: input.workspaceStrategy.baseRef,
391 path: null,
392 },
393 {
394 progress: {
395 onWorktreeClaimed: (path) =>
396 Effect.sync(() => {
397 createdWorktreePath = path;
398 }),
399 onCheckoutProgress: (progress) =>
400 setupTracker.stage(threadId, "checkout", { percent: progress.percent }),
401 },
402 },
403 )
404 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
405 worktreePath = worktree.worktree.path;
406 branch = worktree.worktree.refName;
407 createdWorktreePath = worktreePath;
408 yield* setupTracker.update(threadId, (snapshot) => ({ ...snapshot, worktreePath, branch }));
409 yield* setupTracker.stageStatus(threadId, "checkout", "done");
410 }
411​
412 // A reused worktree is already recorded, and rewriting it could undo
413 // the first attempt's branch rename.
414 if (reused === undefined) {
415 yield* threads
416 .dispatch({
417 type: "thread.metadata.update",
418 commandId: CommandId.make(`${input.commandId}:workspace`),
419 threadId,
420 branch,
421 worktreePath,
422 })
423 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
424 }
425 workspaceRecorded = true;
426​
427 // Rename temporary branches (server-invented above, or sent by clients
428 // that name worktrees themselves) in the background so generation latency
429 // never delays provisioning or the provider turn. The temporary name
430 // simply sticks if generation or the rename fails.
431 if (
432 reused === undefined &&
433 worktreePath !== null &&
434 branch !== null &&
435 initialMessage !== undefined &&
436 isTemporaryWorktreeBranch(branch)
437 ) {
438 const oldBranch = branch;
439 const worktreeCwd = worktreePath;
440 yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe(
441 Effect.flatMap(({ branch: newBranch, exactName }) =>
442 git.renameBranch({
443 cwd: worktreeCwd,
444 oldBranch,
445 newBranch,
446 ...(exactName ? { exactName: true } : {}),
447 }),
448 ),
449 Effect.flatMap((renamed) =>
450 threads.dispatch({
451 type: "thread.metadata.update",
452 commandId: CommandId.make(`${input.commandId}:branch-rename`),
453 threadId,
454 branch: renamed.branch,
455 worktreePath: worktreeCwd,
456 }),
457 ),
458 Effect.catchCause((cause) =>
459 Effect.logWarning("Thread worktree branch rename failed", {
460 commandId: input.commandId,
461 threadId,
462 oldBranch,
463 cause,
464 }),
465 ),
466 Effect.forkIn(preparationScope),
467 );
468 }
469​
470 const cwd = worktreePath ?? project.workspaceRoot;
471 if (runId !== null) {
472 yield* threads
473 .dispatch({
474 type: "prepared-run.progress",
475 commandId: CommandId.make(`${input.commandId}:progress:setup`),
476 threadId,
477 runId,
478 phase: "setup",
479 })
480 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
481 }
482 yield* setupTracker.stageStatus(threadId, "setup-script", "running");
483 const setup = yield* setupScripts
484 .runForThread({
485 threadId,
486 projectId: input.projectId,
487 projectCwd: project.workspaceRoot,
488 worktreePath: cwd,
489 ...(tracked
490 ? {
491 observeCompletion: {
492 onOutputLine: (line: string) =>
493 setupTracker.appendTail(threadId, "setup-script", line),
494 },
495 }
496 : {}),
497 project: {
498 id: project.id,
499 workspaceRoot: project.workspaceRoot,
500 scripts: project.scripts,
501 },
502 })
503 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
504​
505 let awaitAsyncSetup = Effect.void;
506 if (setup.status === "started") {
507 setupTerminalId = setup.terminalId;
508 yield* setupTracker.update(threadId, (snapshot) => ({
509 ...snapshot,
510 setupScript: {
511 name: setup.scriptName,
512 command: setup.scriptCommand,
513 terminalId: setup.terminalId,
514 },
515 }));
516 if (setup.completion) {
517 const awaitCompletion = Effect.gen(function* () {
518 const completion = yield* setup.completion!;
519 yield* setupTracker.stage(threadId, "setup-script", {
520 status: completion.exitCode === 0 ? "done" : "failed",
521 detail: `exited with ${completion.exitCode ?? "no exit code"}`,
522 });
523 if (completion.exitCode !== 0 && !setup.async)
524 return yield* mapError(
525 input,
526 "run-setup-script",
527 threadId,
528 )(`Setup script exited with ${completion.exitCode ?? "no exit code"}.`);
529 });
530 if (setup.async) {
531 awaitAsyncSetup = awaitCompletion.pipe(
532 Effect.catchCause((cause) =>
533 setupTracker.stage(threadId, "setup-script", {
534 status: "failed",
535 detail: failureDetail(Cause.squash(cause)),
536 }),
537 ),
538 );
539 } else {
540 yield* awaitCompletion;
541 }
542 } else {
543 yield* setupTracker.stageStatus(threadId, "setup-script", "done");
544 }
545 } else {
546 yield* setupTracker.stageStatus(threadId, "setup-script", "skipped");
547 }
548 yield* setupTracker.markUncancellable(threadId);
549 yield* setupTracker.stageStatus(threadId, "agent", "running");
550 if (runId !== null) {
551 yield* threads
552 .dispatch({
553 type: "prepared-run.release",
554 commandId: CommandId.make(`${input.commandId}:release`),
555 threadId,
556 runId,
557 })
558 .pipe(Effect.mapError(mapError(input, "release-run", threadId)));
559 }
560 yield* setupTracker.stageStatus(threadId, "agent", "done");
561 yield* awaitAsyncSetup;
562 yield* setupTracker.finish(threadId, "done");
563 }).pipe(
564 Effect.onError((cause) =>
565 Effect.gen(function* () {
566 const cancelled = Cause.hasInterruptsOnly(cause);
567 yield* setupTracker.finish(
568 threadId,
569 cancelled ? "cancelled" : "failed",
570 cancelled ? null : failureDetail(Cause.squash(cause)),
571 );
572 // A cancelled setup leaves nothing behind. A failed one keeps a worktree
573 // the thread recorded, so a retry reuses it, and removes one it never
574 // recorded, which a retry would otherwise duplicate.
575 if (tracked && createdWorktreePath && (cancelled || !workspaceRecorded)) {
576 if (setupTerminalId)
577 yield* terminals
578 .close({ threadId, terminalId: setupTerminalId, deleteHistory: true })
579 .pipe(Effect.ignore);
580 const removedPath = createdWorktreePath;
581 // The thread forgets the worktree only once it is gone; a failed
582 // removal leaves the directory for the user to clean up rather than
583 // reusing a checkout that may be half written.
584 yield* git
585 .removeWorktree({ cwd: project.workspaceRoot, path: removedPath, force: true })
586 .pipe(
587 Effect.andThen(
588 threads
589 .dispatch({
590 type: "thread.metadata.update",
591 commandId: CommandId.make(`${input.commandId}:cancel-workspace`),
592 threadId,
593 worktreePath: null,
594 branch: null,
595 })
596 .pipe(Effect.ignore),
597 ),
598 Effect.catchCause((removeCause) =>
599 Effect.logWarning("Failed to remove an abandoned thread worktree", {
600 commandId: input.commandId,
601 threadId,
602 path: removedPath,
603 cause: removeCause,
604 }),
605 ),
606 );
607 }
608 }),
609 ),
610 );
611 });
612​
613 const failPreparedRun = (
614 input: Pick<PreparationInput, "commandId">,
615 threadId: ThreadId,
616 runId: RunId | null,
617 cause: unknown,
618 ) =>
619 runId === null
620 ? Effect.logWarning("Thread workspace preparation failed", {
621 commandId: input.commandId,
622 threadId,
623 cause,
624 })
625 : threads
626 .dispatch({
627 type: "prepared-run.fail",
628 commandId: CommandId.make(`${input.commandId}:fail`),
629 threadId,
630 runId,
631 failure: makeProviderFailure({
632 cause,
633 message: failureDetail(cause),
634 class: "validation_error",
635 retryable: false,
636 }),
637 })
638 .pipe(
639 Effect.catchCause((persistCause) =>
640 Effect.logWarning("Failed to persist thread workspace preparation failure", {
641 commandId: input.commandId,
642 threadId,
643 cause,
644 persistCause,
645 }),
646 ),
647 );
648​
649 const reservePreparation = (commandId: CommandId) =>
650 Ref.modify(scheduledLaunches, (scheduled) => {
651 if (scheduled.has(commandId)) return [false, scheduled] as const;
652 const next = new Set(scheduled);
653 next.add(commandId);
654 return [true, next] as const;
655 });
656​
657 const releasePreparation = (commandId: CommandId) =>
658 Ref.update(scheduledLaunches, (scheduled) => {
659 const next = new Set(scheduled);
660 next.delete(commandId);
661 return next;
662 });
663​
664 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
665 input: PreparationInput,
666 threadId: ThreadId,
667 runId: RunId | null,
668 ) {
669 yield* prepareInBackground(input, threadId, runId).pipe(
670 Effect.onError((cause) =>
671 failPreparedRun(
672 input,
673 threadId,
674 runId,
675 Cause.hasInterruptsOnly(cause) ? "Worktree setup cancelled." : Cause.squash(cause),
676 ),
677 ),
678 Effect.ignoreCause,
679 Effect.ensuring(releasePreparation(input.commandId)),
680 Effect.forkIn(preparationScope),
681 );
682 });
683​
684 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
685 function* (input) {
686 yield* ProjectCloneTracker.rejectCommandsDuringClone(cloneTracker, {
687 type: "thread.create",
688 projectId: input.projectId,
689 }).pipe(Effect.mapError(mapError(input, "resolve-project")));
690 const project = yield* projects.getById(input.projectId).pipe(
691 Effect.mapError(mapError(input, "resolve-project")),
692 Effect.flatMap(
693 Option.match({
694 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
695 onSome: Effect.succeed,
696 }),
697 ),
698 );
699 if (input.reuseExistingThread === true && input.threadId === undefined) {
700 return yield* mapError(
701 input,
702 "update-thread",
703 )("Reusing an existing thread requires a thread id.");
704 }
705​
706 const launchReceipt = yield* readReceipt(input, input.commandId);
707 return yield* Effect.gen(function* () {
708 // A retried launch has no client-supplied id to replay against, so
709 // recover the thread id its accepted create was recorded under before
710 // allocating another one; a fresh id would only collide with the
711 // recorded receipt.
712 const reusableLaunchReceipt =
713 input.threadId === undefined &&
714 Option.isSome(launchReceipt) &&
715 launchReceipt.value.status === "accepted" &&
716 launchReceipt.value.commandType === "thread.create"
717 ? launchReceipt.value
718 : undefined;
719 const candidateThreadId =
720 input.threadId ??
721 reusableLaunchReceipt?.threadId ??
722 (yield* ids.allocate
723 .thread({ projectId: input.projectId })
724 .pipe(Effect.mapError(mapError(input, "create-thread"))));
725​
726 if (reusableLaunchReceipt !== undefined) {
727 const shell = yield* threads
728 .getThreadShell(candidateThreadId)
729 .pipe(Effect.mapError(mapError(input, "create-thread", candidateThreadId)));
730 if (shell === null) {
731 return yield* mapError(input, "create-thread", candidateThreadId)("Thread not found.");
732 }
733 if (shell.projectId !== input.projectId) {
734 return yield* mapError(
735 input,
736 "resolve-project",
737 candidateThreadId,
738 )("Project identity changed.");
739 }
740 }
741​
742 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
743 yield* validateReusableThread(input, candidateThreadId);
744 }
745​
746 // A Scratch thread launched at the project root runs in a folder of its
747 // own. Only the first attempt claims one; a retry replays its create.
748 const workspaceStrategy: ThreadLaunchWorkspaceStrategy =
749 input.workspaceStrategy.type === "root" && Option.isNone(launchReceipt)
750 ? Option.match(
751 yield* managedFolders
752 .folderForThread({
753 projectId: input.projectId,
754 threadId: candidateThreadId,
755 text: input.initialMessage?.text ?? input.title,
756 })
757 .pipe(Effect.mapError(mapError(input, "provision-worktree", candidateThreadId))),
758 {
759 onNone: () => input.workspaceStrategy,
760 onSome: (worktreePath) => ({ type: "existing_worktree", worktreePath }),
761 },
762 )
763 : input.workspaceStrategy;
764 const initialBranch = workspaceStrategy.branch ?? null;
765 const initialWorktreePath =
766 workspaceStrategy.type === "existing_worktree" ? workspaceStrategy.worktreePath : null;
767 const claimDispatch =
768 input.reuseExistingThread === true
769 ? threads.dispatch({
770 type: "thread.metadata.update",
771 commandId: input.commandId,
772 threadId: candidateThreadId,
773 expectedEmpty: true,
774 })
775 : threads.dispatch({
776 type: "thread.create",
777 commandId: input.commandId,
778 threadId: candidateThreadId,
779 projectId: input.projectId,
780 title: input.title,
781 modelSelection: input.modelSelection,
782 runtimeMode: input.runtimeMode,
783 interactionMode: input.interactionMode,
784 branch: initialBranch,
785 worktreePath: initialWorktreePath,
786 ...(input.importedNativeThread === undefined
787 ? {}
788 : { importedNativeThread: input.importedNativeThread }),
789 createdBy: input.createdBy,
790 creationSource: input.creationSource,
791 });
792 const claimed = yield* claimDispatch.pipe(
793 Effect.mapError(
794 mapError(
795 input,
796 input.reuseExistingThread === true ? "update-thread" : "create-thread",
797 candidateThreadId,
798 ),
799 ),
800 );
801 const threadId =
802 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
803 .threadId ?? candidateThreadId;
804 if (project.id !== input.projectId) {
805 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
806 }
807​
808 let runId: RunId | null = null;
809 let messageWasAlreadyAccepted = false;
810 if (input.initialMessage !== undefined) {
811 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
812 const messageReceipt = yield* readReceipt(input, messageCommandId);
813 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
814 const messageId =
815 input.initialMessage.messageId ??
816 (yield* ids.allocate
817 .message({ threadId, ordinal: 1 })
818 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
819 const dispatched = yield* threads
820 .dispatch({
821 type: "message.dispatch",
822 commandId: messageCommandId,
823 threadId,
824 messageId,
825 text: input.initialMessage.text,
826 ...(input.initialMessage.scheduledTaskId === undefined
827 ? {}
828 : { scheduledTaskId: input.initialMessage.scheduledTaskId }),
829 ...(input.initialMessage.senderThreadId === undefined
830 ? {}
831 : { senderThreadId: input.initialMessage.senderThreadId }),
832 attachments: input.initialMessage.attachments,
833 ...(input.initialMessage.context ? { context: input.initialMessage.context } : {}),
834 ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
835 modelSelection: input.modelSelection,
836 dispatchMode: { type: "defer_start", workspaceStrategy },
837 createdBy: input.createdBy,
838 creationSource: input.creationSource,
839 })
840 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
841 const runCreated = dispatched.storedEvents.find(
842 (stored) => stored.event.type === "run.created",
843 );
844 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
845 if (runId === null) {
846 return yield* mapError(
847 input,
848 "dispatch-message",
849 threadId,
850 )("Initial message was accepted without a durable run.");
851 }
852 }
853​
854 const projection = yield* threads
855 .getThreadProjection(threadId)
856 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
857 const runIsPreparing =
858 runId !== null &&
859 projection.runs.some((run) => run.id === runId && run.status === "preparing");
860 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing;
861 // A retried root launch prepares the folder its first attempt bound, so
862 // a Scratch thread keeps its own. Other root launches bind no folder.
863 const boundWorktreePath = projection.thread.worktreePath;
864 const preparationStrategy: ThreadLaunchWorkspaceStrategy =
865 Option.isSome(launchReceipt) &&
866 workspaceStrategy.type === "root" &&
867 boundWorktreePath !== null
868 ? {
869 type: "existing_worktree",
870 worktreePath: boundWorktreePath,
871 branch: workspaceStrategy.branch,
872 }
873 : workspaceStrategy;
874 if (shouldSchedule) {
875 const ownsPreparation = yield* reservePreparation(input.commandId);
876 if (ownsPreparation) {
877 yield* Effect.gen(function* () {
878 const preparationStillRequired =
879 runId === null
880 ? true
881 : yield* threads.getThreadRecords(threadId, ["runs"], { runIds: [runId] }).pipe(
882 Effect.map((current) =>
883 current.runs.some((run) => run.id === runId && run.status === "preparing"),
884 ),
885 Effect.mapError(mapError(input, "update-thread", threadId)),
886 );
887 if (preparationStillRequired) {
888 yield* schedulePreparation(
889 { ...input, workspaceStrategy: preparationStrategy },
890 threadId,
891 runId,
892 );
893 } else {
894 yield* releasePreparation(input.commandId);
895 }
896 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
897 }
898 }
899​
900 return {
901 threadId,
902 projection,
903 resumed: Option.isSome(launchReceipt) || messageWasAlreadyAccepted,
904 };
905 });
906 },
907 );
908​
909 const retryPreparation: ThreadLaunchService["Service"]["retryPreparation"] = Effect.fn(
910 "ThreadLaunchService.retryPreparation",
911 )(function* (input) {
912 const dispatched = yield* threads.dispatch({
913 type: "prepared-run.retry",
914 commandId: input.commandId,
915 threadId: input.threadId,
916 runId: input.runId,
917 });
918 // A replayed retry finds the run already past preparation, or prepared by
919 // the attempt that first reserved this command.
920 // From here the run is preparing again; anything that stops preparation
921 // from being scheduled must fail it, or it would wait in preparing forever.
922 const scheduled = yield* Effect.gen(function* () {
923 const projection = yield* threads.getThreadProjection(input.threadId);
924 const run = projection.runs.find((candidate) => candidate.id === input.runId);
925 const workspacePreparation = run?.workspacePreparation;
926 if (run?.status !== "preparing" || workspacePreparation === undefined) return;
927 if (!(yield* reservePreparation(input.commandId))) return;
928 yield* scheduleRetriedPreparation(input, projection, run, workspacePreparation).pipe(
929 Effect.onError(() => releasePreparation(input.commandId)),
930 );
931 }).pipe(Effect.exit);
932 if (Exit.isFailure(scheduled)) {
933 yield* failPreparedRun(input, input.threadId, input.runId, Cause.squash(scheduled.cause));
934 }
935 return dispatched;
936 });
937​
938 const scheduleRetriedPreparation = (
939 input: ThreadLaunchRetryInput,
940 projection: OrchestrationV2ThreadProjection,
941 run: OrchestrationV2ThreadProjection["runs"][number],
942 workspacePreparation: ThreadLaunchWorkspaceStrategy,
943 ) => {
944 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
945 // A worktree the failed attempt already created is reused, not created again.
946 const reuse =
947 workspacePreparation.type === "worktree" &&
948 projection.thread.worktreePath !== null &&
949 projection.thread.branch !== null
950 ? {
951 strategy: {
952 type: "existing_worktree" as const,
953 worktreePath: projection.thread.worktreePath,
954 branch: projection.thread.branch,
955 },
956 reusedWorktree: { baseRef: workspacePreparation.baseRef },
957 }
958 : null;
959 return schedulePreparation(
960 {
961 commandId: input.commandId,
962 projectId: projection.thread.projectId,
963 workspaceStrategy: reuse?.strategy ?? workspacePreparation,
964 ...(reuse === null ? {} : { reusedWorktree: reuse.reusedWorktree }),
965 ...(message === undefined
966 ? {}
967 : {
968 initialMessage: {
969 text: message.text,
970 attachments: message.attachments,
971 ...(message.context ? { context: message.context } : {}),
972 },
973 }),
974 },
975 input.threadId,
976 run.id,
977 );
978 };
979​
980 return ThreadLaunchService.of({ launch, retryPreparation });
981});
982​
983export const layer = Layer.effect(ThreadLaunchService, make);