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