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 * as Stream from "effect/Stream";
32import {
33 buildTemporaryWorktreeBranchName,
34 flattenTemporaryWorktreeBranchName,
35 isTemporaryWorktreeBranch,
36 WORKTREE_BRANCH_PREFIX,
37} from "@t3tools/shared/git";
38
39import * as GitWorkflow from "../git/GitWorkflowService.ts";
40import * as ProjectService from "../project/ProjectService.ts";
41import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
42import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
43import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
44import * as ServerSettings from "../serverSettings.ts";
45import * as TextGeneration from "../textGeneration/TextGeneration.ts";
46import * as CommandReceiptStore from "./CommandReceiptStore.ts";
47import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
48import type * as Orchestrator from "./Orchestrator.ts";
49import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
50import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
51import * as ThreadManagement from "./ThreadManagementService.ts";
52
53export type ThreadLaunchWorkspaceStrategy =
54 | { readonly type: "root"; readonly branch?: string | undefined }
55 | {
56 readonly type: "existing_worktree";
57 readonly worktreePath: string;
58 readonly branch?: string | undefined;
59 }
60 | {
61 readonly type: "worktree";
62 readonly baseRef: string;
63 readonly branch?: string | undefined;
64 readonly startFromOrigin?: boolean | undefined;
65 };
66
67export interface ThreadLaunchInitialMessage {
68 readonly messageId?: MessageId;
69 readonly scheduledTaskId?: ScheduledTaskId;
70 readonly senderThreadId?: ThreadId;
71 readonly text: string;
72 readonly attachments: ReadonlyArray<ChatAttachment>;
73 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
74}
75
76export interface ThreadLaunchInput {
77 readonly commandId: CommandId;
78 readonly threadId?: ThreadId;
79 readonly reuseExistingThread?: boolean;
80 readonly projectId: ProjectId;
81 readonly title: string;
82 readonly generateTitle?: boolean;
83 readonly modelSelection: ModelSelection;
84 readonly runtimeMode: RuntimeMode;
85 readonly interactionMode: ProviderInteractionMode;
86 readonly workspaceStrategy: ThreadLaunchWorkspaceStrategy;
87 readonly initialMessage?: ThreadLaunchInitialMessage;
88 readonly importedNativeThread?: {
89 readonly ref: {
90 readonly driver: ProviderDriverKind;
91 readonly nativeId: string;
92 readonly strength: "strong";
93 };
94 readonly metadata?: OrchestrationV2ProviderThreadNativeMetadata;
95 };
96 readonly createdBy: OrchestrationV2Actor;
97 readonly creationSource: OrchestrationV2CreationSource;
98}
99
100type PreparationInput = Pick<
101 ThreadLaunchInput,
102 "commandId" | "projectId" | "workspaceStrategy" | "initialMessage"
103> & {
104 readonly reusedWorktree?: { readonly baseRef: string };
105};
106
107export interface ThreadLaunchPreparationInput {
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 ThreadLaunchBaseRefError extends Schema.TaggedError<ThreadLaunchBaseRefError>()(
146 "ThreadLaunchBaseRefError",
147 {
148 projectId: ProjectId,
149 projectTitle: Schema.String,
150 workspaceRoot: Schema.String,
151 baseRef: Schema.String,
152 },
153) {
154 override get message(): string {
155 return `Base ref "${this.baseRef}" does not resolve to a commit in project "${this.projectTitle}" (${this.workspaceRoot}).`;
156 }
157}
158
159export class ThreadLaunchService extends Context.Service<
160 ThreadLaunchService,
161 {
162 readonly launch: (
163 input: ThreadLaunchInput,
164 ) => Effect.Effect<
165 ThreadLaunchResult,
166 ThreadLaunchError | ThreadManagement.ThreadManagementProviderInstanceDisabledError
167 >;
168 /**
169 * `launch` accepts such a launch and reports the failure inside the
170 * thread; a caller that needs it before a thread exists checks first.
171 */
172 readonly checkWorktreeBase: (
173 input: Pick<ThreadLaunchInput, "projectId" | "workspaceStrategy">,
174 ) => Effect.Effect<void, ThreadLaunchBaseRefError>;
175 readonly retryPreparation: (
176 input: ThreadLaunchPreparationInput,
177 ) => Effect.Effect<
178 Orchestrator.OrchestratorV2DispatchResult,
179 | Orchestrator.OrchestratorV2Error
180 | ThreadManagement.ThreadManagementProviderInstanceDisabledError
181 >;
182 readonly prepareRun: (input: ThreadLaunchPreparationInput) => Effect.Effect<void>;
183 }
184>()("t3/orchestration-v2/ThreadLaunchService") {}
185
186const isThreadLaunchError = Schema.is(ThreadLaunchError);
187
188function failureDetail(error: unknown): string {
189 if (isThreadLaunchError(error)) {
190 const cause = error.cause;
191 const detail = cause instanceof Error ? cause.message : String(cause);
192 return `Workspace preparation failed during ${error.operation.replaceAll("-", " ")}: ${detail}`;
193 }
194 return `Workspace preparation failed: ${error instanceof Error ? error.message : String(error)}`;
195}
196
197const make = Effect.gen(function* () {
198 const projects = yield* ProjectService.ProjectService;
199 const setupTracker = yield* WorktreeSetupTracker.WorktreeSetupTracker;
200 const cloneTracker = yield* ProjectCloneTracker.ProjectCloneTracker;
201 const terminals = yield* TerminalManager.TerminalManager;
202 const git = yield* GitWorkflow.GitWorkflowService;
203 const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
204 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
205 const serverSettings = yield* ServerSettings.ServerSettingsService;
206 const textGeneration = yield* TextGeneration.TextGeneration;
207 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
208 const ids = yield* IdAllocator.IdAllocatorV2;
209 const threads = yield* ThreadManagement.ThreadManagementService;
210 const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;
211 const preparationScope = yield* Scope.make("sequential");
212 const scheduledLaunches = yield* Ref.make<ReadonlySet<CommandId>>(new Set());
213 yield* Effect.addFinalizer(() => Scope.close(preparationScope, Exit.void));
214
215 const mapError =
216 (input: PreparationInput, operation: ThreadLaunchError["operation"], threadId?: ThreadId) =>
217 (cause: unknown) =>
218 new ThreadLaunchError({
219 operation,
220 commandId: input.commandId,
221 projectId: input.projectId,
222 ...(threadId === undefined ? {} : { threadId }),
223 cause,
224 });
225
226 const readReceipt = (input: ThreadLaunchInput, commandId: CommandId) =>
227 receipts
228 .getByCommandId(commandId)
229 .pipe(Effect.mapError(mapError(input, "read-receipt", input.threadId)));
230
231 const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")(function* (
232 input: ThreadLaunchInput,
233 threadId: ThreadId,
234 ) {
235 const projection = yield* threads
236 .getThreadRecords(threadId, ["runs"])
237 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
238 if (
239 projection.thread.projectId !== input.projectId ||
240 projection.thread.archivedAt !== null ||
241 projection.thread.deletedAt !== null ||
242 (yield* threads
243 .getMessageCount(threadId)
244 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)))) > 0 ||
245 projection.runs.length > 0
246 ) {
247 return yield* mapError(
248 input,
249 "update-thread",
250 threadId,
251 )("Only an empty active thread in the target project can change workspace during launch.");
252 }
253 });
254
255 const checkWorktreeBase: ThreadLaunchService["Service"]["checkWorktreeBase"] = Effect.fn(
256 "ThreadLaunchService.checkWorktreeBase",
257 )(function* (input) {
258 const strategy = input.workspaceStrategy;
259 // `:/text` is a commit search, which cannot be asked for a commit type.
260 if (strategy.type !== "worktree" || strategy.baseRef.startsWith(":")) return;
261 const { baseRef } = strategy;
262 const unresolved = yield* Effect.gen(function* () {
263 const project = Option.getOrUndefined(yield* projects.getById(input.projectId));
264 if (project === undefined) return undefined;
265 const cwd = project.workspaceRoot;
266 // `git worktree add` reads `-` as the previous checkout.
267 if (yield* git.hasCommit({ cwd, refName: baseRef === "-" ? "@{-1}" : baseRef }))
268 return undefined;
269 if (
270 strategy.startFromOrigin === true &&
271 (yield* git.remoteExists({ cwd, remoteName: "origin" }))
272 )
273 return undefined;
274 // `git worktree add` also starts from a remote-tracking branch of that
275 // name; any ref carrying it is reason enough to let Git decide.
276 if (yield* git.hasRefNamed({ cwd, refName: baseRef })) return undefined;
277 return (yield* git.hasCommit({ cwd, refName: "HEAD" })) ? project : undefined;
278 }).pipe(Effect.orElseSucceed(() => undefined));
279 if (unresolved !== undefined)
280 return yield* new ThreadLaunchBaseRefError({
281 projectId: unresolved.id,
282 projectTitle: unresolved.title,
283 workspaceRoot: unresolved.workspaceRoot,
284 baseRef,
285 });
286 });
287
288 const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* (
289 input: PreparationInput,
290 threadId: ThreadId,
291 runId: RunId | null,
292 ) {
293 const project = yield* projects.getById(input.projectId).pipe(
294 Effect.mapError(mapError(input, "resolve-project", threadId)),
295 Effect.flatMap(
296 Option.match({
297 onNone: () =>
298 Effect.fail(mapError(input, "resolve-project", threadId)("Project no longer exists.")),
299 onSome: Effect.succeed,
300 }),
301 ),
302 );
303
304 const reused = input.reusedWorktree;
305 const tracked = input.workspaceStrategy.type === "worktree" || reused !== undefined;
306 let createdWorktreePath: string | null = null;
307 let setupTerminalId: string | null = null;
308 let workspaceRecorded = false;
309 let runReleased = false;
310 if (input.workspaceStrategy.type === "worktree") {
311 yield* setupTracker.begin({
312 threadId,
313 branch: input.workspaceStrategy.branch ?? null,
314 baseRef: input.workspaceStrategy.baseRef,
315 stages: ["fetch", "checkout", "setup-script", "agent"],
316 fiber: yield* Effect.fiber,
317 });
318 } else if (reused !== undefined) {
319 yield* setupTracker.begin({
320 threadId,
321 branch: input.workspaceStrategy.branch ?? null,
322 baseRef: reused.baseRef,
323 stages: ["setup-script", "agent"],
324 fiber: yield* Effect.fiber,
325 });
326 }
327 yield* Effect.gen(function* () {
328 const initialMessage = input.initialMessage;
329 const generateBranchNameFor = (cwd: string, message: ThreadLaunchInitialMessage) =>
330 Effect.gen(function* () {
331 const settings = resolveProjectSettings(
332 yield* serverSettings.getSettings,
333 input.projectId,
334 ).settings;
335 const modelSelection =
336 settings.sourceControlWriterModelSelection === null
337 ? settings.textGenerationModelSelection
338 : ServerSettings.resolveSourceControlWriterModelSelection(
339 settings,
340 yield* providerRegistry.getProviders,
341 input.projectId,
342 );
343 return yield* textGeneration
344 .generateBranchName({
345 naming: {
346 mode: settings.branchNamingMode,
347 prefix: settings.branchNamePrefix,
348 instructions: settings.branchNameInstructions,
349 },
350 cwd,
351 message: message.text,
352 attachments: message.attachments,
353 ...(message.context ? { context: message.context } : {}),
354 modelSelection,
355 })
356 .pipe(
357 Effect.map((result) => ({
358 branch: result.branch,
359 exactName: settings.branchNamingMode === "custom",
360 })),
361 );
362 });
363
364 const requestedBranch = input.workspaceStrategy.branch;
365 let branch: string | null;
366 if (input.workspaceStrategy.type === "worktree" && requestedBranch === undefined) {
367 const uuid = yield* randomUuidV4;
368 branch = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
369 } else {
370 branch = requestedBranch ?? null;
371 }
372 let worktreePath =
373 input.workspaceStrategy.type === "existing_worktree"
374 ? input.workspaceStrategy.worktreePath
375 : null;
376 if (input.workspaceStrategy.type === "worktree") {
377 if (runId !== null) {
378 yield* threads
379 .dispatch({
380 type: "prepared-run.progress",
381 commandId: CommandId.make(`${input.commandId}:progress:worktree`),
382 threadId,
383 runId,
384 phase: "worktree",
385 })
386 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
387 }
388 let startRef = input.workspaceStrategy.baseRef;
389 const startFromOrigin =
390 input.workspaceStrategy.startFromOrigin === true &&
391 (yield* git
392 .remoteExists({ cwd: project.workspaceRoot, remoteName: "origin" })
393 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))));
394 yield* setupTracker.stageStatus(threadId, "fetch", startFromOrigin ? "running" : "skipped");
395 if (startFromOrigin) {
396 yield* git
397 .fetchRemote({
398 cwd: project.workspaceRoot,
399 remoteName: "origin",
400 refName: input.workspaceStrategy.baseRef,
401 })
402 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
403 const remoteBaseExists = yield* git
404 .remoteBranchExists({
405 cwd: project.workspaceRoot,
406 refName: input.workspaceStrategy.baseRef,
407 remoteName: "origin",
408 })
409 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
410 if (remoteBaseExists) {
411 startRef = yield* git
412 .resolveRemoteTrackingCommit({
413 cwd: project.workspaceRoot,
414 refName: input.workspaceStrategy.baseRef,
415 fallbackRemoteName: "origin",
416 })
417 .pipe(
418 Effect.map((resolved) => resolved.commitSha),
419 Effect.mapError(mapError(input, "provision-worktree", threadId)),
420 );
421 }
422 }
423 if (startFromOrigin) yield* setupTracker.stageStatus(threadId, "fetch", "done");
424 if (
425 branch !== null &&
426 isTemporaryWorktreeBranch(branch) &&
427 (yield* git
428 .hasCommit({
429 cwd: project.workspaceRoot,
430 refName: `refs/heads/${WORKTREE_BRANCH_PREFIX}`,
431 })
432 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))))
433 ) {
434 branch = flattenTemporaryWorktreeBranchName(branch);
435 }
436 yield* setupTracker.stageStatus(threadId, "checkout", "running");
437 const worktree = yield* git
438 .createWorktree(
439 {
440 cwd: project.workspaceRoot,
441 refName: startRef,
442 newRefName: branch!,
443 baseRefName: input.workspaceStrategy.baseRef,
444 path: null,
445 },
446 {
447 progress: {
448 onWorktreeClaimed: (path) =>
449 Effect.sync(() => {
450 createdWorktreePath = path;
451 }),
452 onCheckoutProgress: (progress) =>
453 setupTracker.stage(threadId, "checkout", { percent: progress.percent }),
454 },
455 },
456 )
457 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
458 worktreePath = worktree.worktree.path;
459 branch = worktree.worktree.refName;
460 createdWorktreePath = worktreePath;
461 yield* setupTracker.update(threadId, (snapshot) => ({ ...snapshot, worktreePath, branch }));
462 yield* setupTracker.stageStatus(threadId, "checkout", "done");
463 }
464
465 // A reused worktree is already recorded, and rewriting it could undo
466 // the first attempt's branch rename.
467 if (reused === undefined) {
468 yield* threads
469 .dispatch({
470 type: "thread.metadata.update",
471 commandId: CommandId.make(`${input.commandId}:workspace`),
472 threadId,
473 branch,
474 worktreePath,
475 })
476 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
477 }
478 workspaceRecorded = true;
479
480 if (
481 reused === undefined &&
482 worktreePath !== null &&
483 branch !== null &&
484 initialMessage !== undefined &&
485 isTemporaryWorktreeBranch(branch)
486 ) {
487 const oldBranch = branch;
488 const worktreeCwd = worktreePath;
489 yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe(
490 Effect.flatMap(({ branch: newBranch, exactName }) =>
491 git.renameBranch({
492 cwd: worktreeCwd,
493 oldBranch,
494 newBranch,
495 ...(exactName ? { exactName: true } : {}),
496 }),
497 ),
498 Effect.flatMap((renamed) =>
499 Effect.gen(function* () {
500 yield* threads
501 .dispatch({
502 type: "thread.metadata.update",
503 commandId: CommandId.make(`${input.commandId}:branch-rename`),
504 threadId,
505 branch: renamed.branch,
506 worktreePath: worktreeCwd,
507 expectedBranch: oldBranch,
508 expectedWorktreePath: worktreeCwd,
509 })
510 .pipe(
511 Effect.catchCause((cause) =>
512 Effect.logWarning("Parent thread worktree branch update failed", {
513 threadId,
514 cause,
515 }),
516 ),
517 );
518 // Updating the parent first makes later subagents inherit the new name.
519 // Re-read after each pass for children of subagents updated in that pass.
520 const visited = new Set([threadId]);
521 while (true) {
522 const snapshot = yield* threads.getShellSnapshot();
523 const sharing = [...snapshot.threads, ...snapshot.archivedThreads].filter(
524 (thread) =>
525 !visited.has(thread.id) &&
526 thread.worktreePath === worktreeCwd &&
527 thread.branch === oldBranch,
528 );
529 if (sharing.length === 0) break;
530 for (const thread of sharing) {
531 visited.add(thread.id);
532 yield* threads
533 .dispatch({
534 type: "thread.metadata.update",
535 commandId: CommandId.make(`${input.commandId}:branch-rename:${thread.id}`),
536 threadId: thread.id,
537 branch: renamed.branch,
538 expectedBranch: oldBranch,
539 expectedWorktreePath: worktreeCwd,
540 })
541 .pipe(
542 Effect.catchCause((cause) =>
543 Effect.logWarning("Shared thread worktree branch update failed", {
544 threadId: thread.id,
545 cause,
546 }),
547 ),
548 );
549 }
550 }
551 }),
552 ),
553 Effect.catchCause((cause) =>
554 Effect.logWarning("Thread worktree branch rename failed", {
555 commandId: input.commandId,
556 threadId,
557 oldBranch,
558 cause,
559 }),
560 ),
561 Effect.forkIn(preparationScope),
562 );
563 }
564
565 const cwd = worktreePath ?? project.workspaceRoot;
566 if (runId !== null) {
567 yield* threads
568 .dispatch({
569 type: "prepared-run.progress",
570 commandId: CommandId.make(`${input.commandId}:progress:setup`),
571 threadId,
572 runId,
573 phase: "setup",
574 })
575 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
576 }
577 yield* setupTracker.stageStatus(threadId, "setup-script", "running");
578 const setup = yield* setupScripts
579 .runForThread({
580 threadId,
581 projectId: input.projectId,
582 projectCwd: project.workspaceRoot,
583 worktreePath: cwd,
584 ...(tracked
585 ? {
586 observeCompletion: {
587 onOutputLine: (line: string) =>
588 setupTracker.appendTail(threadId, "setup-script", line),
589 },
590 }
591 : {}),
592 project: {
593 id: project.id,
594 workspaceRoot: project.workspaceRoot,
595 scripts: project.scripts,
596 },
597 })
598 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
599
600 let awaitAsyncSetup = Effect.void;
601 if (setup.status === "started") {
602 setupTerminalId = setup.terminalId;
603 yield* setupTracker.update(threadId, (snapshot) => ({
604 ...snapshot,
605 setupScript: {
606 name: setup.scriptName,
607 command: setup.scriptCommand,
608 terminalId: setup.terminalId,
609 },
610 }));
611 if (setup.completion) {
612 const awaitCompletion = Effect.gen(function* () {
613 const completion = yield* setup.completion!;
614 yield* setupTracker.stage(threadId, "setup-script", {
615 status: completion.exitCode === 0 ? "done" : "failed",
616 detail: `exited with ${completion.exitCode ?? "no exit code"}`,
617 });
618 if (completion.exitCode !== 0 && !setup.async)
619 return yield* mapError(
620 input,
621 "run-setup-script",
622 threadId,
623 )(`Setup script exited with ${completion.exitCode ?? "no exit code"}.`);
624 });
625 if (setup.async) {
626 awaitAsyncSetup = awaitCompletion.pipe(
627 Effect.catchCause((cause) =>
628 setupTracker.stage(threadId, "setup-script", {
629 status: "failed",
630 detail: failureDetail(Cause.squash(cause)),
631 }),
632 ),
633 );
634 } else {
635 yield* awaitCompletion;
636 }
637 } else {
638 yield* setupTracker.stageStatus(threadId, "setup-script", "done");
639 }
640 } else {
641 yield* setupTracker.stageStatus(threadId, "setup-script", "skipped");
642 }
643 yield* setupTracker.markUncancellable(threadId);
644 yield* setupTracker.stageStatus(threadId, "agent", "running");
645 if (runId !== null) {
646 yield* threads
647 .dispatch({
648 type: "prepared-run.release",
649 commandId: CommandId.make(`${input.commandId}:release`),
650 threadId,
651 runId,
652 })
653 .pipe(
654 Effect.mapError(mapError(input, "release-run", threadId)),
655 Effect.tap(() =>
656 Effect.sync(() => {
657 runReleased = true;
658 }),
659 ),
660 Effect.uninterruptible,
661 );
662 }
663 yield* setupTracker.stageStatus(threadId, "agent", "done");
664 yield* awaitAsyncSetup;
665 yield* setupTracker.finish(threadId, "done");
666 }).pipe(
667 Effect.onError((cause) =>
668 Effect.gen(function* () {
669 const cancelled = Cause.hasInterruptsOnly(cause);
670 yield* setupTracker.finish(
671 threadId,
672 cancelled ? "cancelled" : "failed",
673 cancelled ? null : failureDetail(Cause.squash(cause)),
674 );
675 if (cancelled && setupTerminalId)
676 yield* terminals
677 .close({ threadId, terminalId: setupTerminalId, deleteHistory: true })
678 .pipe(Effect.ignore);
679 if (
680 tracked &&
681 createdWorktreePath &&
682 ((cancelled && !runReleased) || !workspaceRecorded)
683 ) {
684 const removedPath = createdWorktreePath;
685 // The thread forgets the worktree only once it is gone; a failed
686 // removal leaves the directory for the user to clean up rather than
687 // reusing a checkout that may be half written.
688 yield* git
689 .removeWorktree({ cwd: project.workspaceRoot, path: removedPath, force: true })
690 .pipe(
691 Effect.andThen(
692 threads
693 .dispatch({
694 type: "thread.metadata.update",
695 commandId: CommandId.make(`${input.commandId}:cancel-workspace`),
696 threadId,
697 worktreePath: null,
698 branch: null,
699 })
700 .pipe(Effect.ignore),
701 ),
702 Effect.catchCause((removeCause) =>
703 Effect.logWarning("Failed to remove an abandoned thread worktree", {
704 commandId: input.commandId,
705 threadId,
706 path: removedPath,
707 cause: removeCause,
708 }),
709 ),
710 );
711 }
712 }),
713 ),
714 );
715 });
716
717 const failPreparedRun = (
718 input: Pick<PreparationInput, "commandId">,
719 threadId: ThreadId,
720 runId: RunId | null,
721 cause: unknown,
722 ) =>
723 runId === null
724 ? Effect.logWarning("Thread workspace preparation failed", {
725 commandId: input.commandId,
726 threadId,
727 cause,
728 })
729 : threads
730 .dispatch({
731 type: "prepared-run.fail",
732 commandId: CommandId.make(`${input.commandId}:fail`),
733 threadId,
734 runId,
735 failure: makeProviderFailure({
736 cause,
737 message: failureDetail(cause),
738 class: "validation_error",
739 retryable: false,
740 }),
741 })
742 .pipe(
743 Effect.catchCause((persistCause) =>
744 Effect.logWarning("Failed to persist thread workspace preparation failure", {
745 commandId: input.commandId,
746 threadId,
747 cause,
748 persistCause,
749 }),
750 ),
751 );
752
753 const reservePreparation = (commandId: CommandId) =>
754 Ref.modify(scheduledLaunches, (scheduled) => {
755 if (scheduled.has(commandId)) return [false, scheduled] as const;
756 const next = new Set(scheduled);
757 next.add(commandId);
758 return [true, next] as const;
759 });
760
761 const releasePreparation = (commandId: CommandId) =>
762 Ref.update(scheduledLaunches, (scheduled) => {
763 const next = new Set(scheduled);
764 next.delete(commandId);
765 return next;
766 });
767
768 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
769 input: PreparationInput,
770 threadId: ThreadId,
771 runId: RunId | null,
772 ) {
773 const preparation = Effect.gen(function* () {
774 const prepare = prepareInBackground(input, threadId, runId);
775 if (
776 runId === null ||
777 (input.workspaceStrategy.type !== "worktree" && input.reusedWorktree === undefined)
778 ) {
779 return yield* prepare;
780 }
781 const afterSequence = yield* threads.getThreadEventSequence(threadId);
782 const projection = yield* threads.getThreadRecords(threadId, ["runs"]);
783 if (projection.runs.find((run) => run.id === runId)?.status !== "preparing") return;
784 const interruption = threads
785 .streamStoredEventsFrom({ threadId, afterSequence, eventType: "run.updated" })
786 .pipe(
787 Stream.filter(
788 (stored) =>
789 stored.event.type === "run.updated" &&
790 stored.event.payload.id === runId &&
791 (stored.event.payload.status === "interrupted" ||
792 stored.event.payload.status === "cancelled"),
793 ),
794 Stream.runHead,
795 Effect.flatMap((event) => (Option.isSome(event) ? Effect.interrupt : Effect.never)),
796 );
797 yield* Effect.raceFirst(prepare, interruption);
798 });
799 yield* preparation.pipe(
800 Effect.onError((cause) =>
801 failPreparedRun(
802 input,
803 threadId,
804 runId,
805 Cause.hasInterruptsOnly(cause) ? "Worktree setup cancelled." : Cause.squash(cause),
806 ),
807 ),
808 Effect.ignoreCause,
809 Effect.ensuring(releasePreparation(input.commandId)),
810 Effect.forkIn(preparationScope),
811 );
812 });
813
814 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
815 function* (input) {
816 yield* ProjectCloneTracker.rejectCommandsDuringClone(cloneTracker, {
817 type: "thread.create",
818 projectId: input.projectId,
819 }).pipe(Effect.mapError(mapError(input, "resolve-project")));
820 const project = yield* projects.getById(input.projectId).pipe(
821 Effect.mapError(mapError(input, "resolve-project")),
822 Effect.flatMap(
823 Option.match({
824 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
825 onSome: Effect.succeed,
826 }),
827 ),
828 );
829 if (input.reuseExistingThread === true && input.threadId === undefined) {
830 return yield* mapError(
831 input,
832 "update-thread",
833 )("Reusing an existing thread requires a thread id.");
834 }
835
836 const launchReceipt = yield* readReceipt(input, input.commandId);
837 yield* threads.assertProviderInstanceEnabled({
838 projectId: input.projectId,
839 commandId: input.commandId,
840 instanceId: input.modelSelection.instanceId,
841 });
842 return yield* Effect.gen(function* () {
843 // A retried launch has no client-supplied id to replay against, so
844 // recover the thread id its accepted create was recorded under before
845 // allocating another one; a fresh id would only collide with the
846 // recorded receipt.
847 const reusableLaunchReceipt =
848 input.threadId === undefined &&
849 Option.isSome(launchReceipt) &&
850 launchReceipt.value.status === "accepted" &&
851 launchReceipt.value.commandType === "thread.create"
852 ? launchReceipt.value
853 : undefined;
854 const candidateThreadId =
855 input.threadId ??
856 reusableLaunchReceipt?.threadId ??
857 (yield* ids.allocate
858 .thread({ projectId: input.projectId })
859 .pipe(Effect.mapError(mapError(input, "create-thread"))));
860
861 if (reusableLaunchReceipt !== undefined) {
862 const shell = yield* threads
863 .getThreadShell(candidateThreadId)
864 .pipe(Effect.mapError(mapError(input, "create-thread", candidateThreadId)));
865 if (shell === null) {
866 return yield* mapError(input, "create-thread", candidateThreadId)("Thread not found.");
867 }
868 if (shell.projectId !== input.projectId) {
869 return yield* mapError(
870 input,
871 "resolve-project",
872 candidateThreadId,
873 )("Project identity changed.");
874 }
875 }
876
877 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
878 yield* validateReusableThread(input, candidateThreadId);
879 }
880
881 const workspaceStrategy: ThreadLaunchWorkspaceStrategy =
882 input.workspaceStrategy.type === "root" && Option.isNone(launchReceipt)
883 ? Option.match(
884 yield* managedFolders
885 .folderForThread({
886 projectId: input.projectId,
887 threadId: candidateThreadId,
888 text: input.initialMessage?.text ?? input.title,
889 })
890 .pipe(Effect.mapError(mapError(input, "provision-worktree", candidateThreadId))),
891 {
892 onNone: () => input.workspaceStrategy,
893 onSome: (worktreePath) => ({ type: "existing_worktree", worktreePath }),
894 },
895 )
896 : input.workspaceStrategy;
897 const initialBranch = workspaceStrategy.branch ?? null;
898 const initialWorktreePath =
899 workspaceStrategy.type === "existing_worktree" ? workspaceStrategy.worktreePath : null;
900 const claimDispatch =
901 input.reuseExistingThread === true
902 ? threads.dispatch({
903 type: "thread.metadata.update",
904 commandId: input.commandId,
905 threadId: candidateThreadId,
906 expectedEmpty: true,
907 })
908 : threads.dispatch({
909 type: "thread.create",
910 commandId: input.commandId,
911 threadId: candidateThreadId,
912 projectId: input.projectId,
913 title: input.title,
914 modelSelection: input.modelSelection,
915 runtimeMode: input.runtimeMode,
916 interactionMode: input.interactionMode,
917 branch: initialBranch,
918 worktreePath: initialWorktreePath,
919 ...(input.importedNativeThread === undefined
920 ? {}
921 : { importedNativeThread: input.importedNativeThread }),
922 createdBy: input.createdBy,
923 creationSource: input.creationSource,
924 });
925 const claimed = yield* claimDispatch.pipe(
926 Effect.mapError(
927 mapError(
928 input,
929 input.reuseExistingThread === true ? "update-thread" : "create-thread",
930 candidateThreadId,
931 ),
932 ),
933 );
934 const threadId =
935 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
936 .threadId ?? candidateThreadId;
937 if (project.id !== input.projectId) {
938 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
939 }
940
941 let runId: RunId | null = null;
942 let messageWasAlreadyAccepted = false;
943 if (input.initialMessage !== undefined) {
944 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
945 const messageReceipt = yield* readReceipt(input, messageCommandId);
946 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
947 const messageId =
948 input.initialMessage.messageId ??
949 (yield* ids.allocate
950 .message({ threadId, ordinal: 1 })
951 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
952 const dispatched = yield* threads
953 .dispatch({
954 type: "message.dispatch",
955 commandId: messageCommandId,
956 threadId,
957 messageId,
958 text: input.initialMessage.text,
959 ...(input.initialMessage.scheduledTaskId === undefined
960 ? {}
961 : { scheduledTaskId: input.initialMessage.scheduledTaskId }),
962 ...(input.initialMessage.senderThreadId === undefined
963 ? {}
964 : { senderThreadId: input.initialMessage.senderThreadId }),
965 attachments: input.initialMessage.attachments,
966 ...(input.initialMessage.context ? { context: input.initialMessage.context } : {}),
967 ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
968 modelSelection: input.modelSelection,
969 dispatchMode: { type: "defer_start", workspaceStrategy },
970 createdBy: input.createdBy,
971 creationSource: input.creationSource,
972 })
973 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
974 const runCreated = dispatched.storedEvents.find(
975 (stored) => stored.event.type === "run.created",
976 );
977 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
978 if (runId === null) {
979 return yield* mapError(
980 input,
981 "dispatch-message",
982 threadId,
983 )("Initial message was accepted without a durable run.");
984 }
985 }
986
987 const projection = yield* threads
988 .getThreadProjection(threadId)
989 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
990 const runIsPreparing =
991 runId !== null &&
992 projection.runs.some((run) => run.id === runId && run.status === "preparing");
993 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing;
994 const boundWorktreePath = projection.thread.worktreePath;
995 const preparationStrategy: ThreadLaunchWorkspaceStrategy =
996 Option.isSome(launchReceipt) &&
997 workspaceStrategy.type === "root" &&
998 boundWorktreePath !== null
999 ? {
1000 type: "existing_worktree",
1001 worktreePath: boundWorktreePath,
1002 branch: workspaceStrategy.branch,
1003 }
1004 : workspaceStrategy;
1005 if (shouldSchedule) {
1006 const ownsPreparation = yield* reservePreparation(input.commandId);
1007 if (ownsPreparation) {
1008 yield* Effect.gen(function* () {
1009 const preparationStillRequired =
1010 runId === null
1011 ? true
1012 : yield* threads.getThreadRecords(threadId, ["runs"], { runIds: [runId] }).pipe(
1013 Effect.map((current) =>
1014 current.runs.some((run) => run.id === runId && run.status === "preparing"),
1015 ),
1016 Effect.mapError(mapError(input, "update-thread", threadId)),
1017 );
1018 if (preparationStillRequired) {
1019 yield* schedulePreparation(
1020 { ...input, workspaceStrategy: preparationStrategy },
1021 threadId,
1022 runId,
1023 );
1024 } else {
1025 yield* releasePreparation(input.commandId);
1026 }
1027 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
1028 }
1029 }
1030
1031 return {
1032 threadId,
1033 projection,
1034 resumed: Option.isSome(launchReceipt) || messageWasAlreadyAccepted,
1035 };
1036 });
1037 },
1038 );
1039
1040 const prepareRun: ThreadLaunchService["Service"]["prepareRun"] = Effect.fn(
1041 "ThreadLaunchService.prepareRun",
1042 )(function* (input) {
1043 const scheduled = yield* Effect.gen(function* () {
1044 const projection = yield* threads.getThreadProjection(input.threadId);
1045 const run = projection.runs.find((candidate) => candidate.id === input.runId);
1046 const workspacePreparation = run?.workspacePreparation;
1047 if (run?.status !== "preparing" || workspacePreparation === undefined) return;
1048 if (!(yield* reservePreparation(input.commandId))) return;
1049 yield* scheduleRunPreparation(input, projection, run, workspacePreparation).pipe(
1050 Effect.onError(() => releasePreparation(input.commandId)),
1051 );
1052 }).pipe(Effect.exit);
1053 if (Exit.isFailure(scheduled)) {
1054 yield* failPreparedRun(input, input.threadId, input.runId, Cause.squash(scheduled.cause));
1055 }
1056 });
1057
1058 const retryPreparation: ThreadLaunchService["Service"]["retryPreparation"] = Effect.fn(
1059 "ThreadLaunchService.retryPreparation",
1060 )(function* (input) {
1061 const dispatched = yield* threads.dispatch({
1062 type: "prepared-run.retry",
1063 commandId: input.commandId,
1064 threadId: input.threadId,
1065 runId: input.runId,
1066 });
1067 yield* prepareRun(input);
1068 return dispatched;
1069 });
1070
1071 const scheduleRunPreparation = (
1072 input: ThreadLaunchPreparationInput,
1073 projection: OrchestrationV2ThreadProjection,
1074 run: OrchestrationV2ThreadProjection["runs"][number],
1075 workspacePreparation: ThreadLaunchWorkspaceStrategy,
1076 ) => {
1077 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
1078 const reuse =
1079 workspacePreparation.type === "worktree" &&
1080 projection.thread.worktreePath !== null &&
1081 projection.thread.branch !== null
1082 ? {
1083 strategy: {
1084 type: "existing_worktree" as const,
1085 worktreePath: projection.thread.worktreePath,
1086 branch: projection.thread.branch,
1087 },
1088 reusedWorktree: { baseRef: workspacePreparation.baseRef },
1089 }
1090 : null;
1091 return schedulePreparation(
1092 {
1093 commandId: input.commandId,
1094 projectId: projection.thread.projectId,
1095 workspaceStrategy: reuse?.strategy ?? workspacePreparation,
1096 ...(reuse === null ? {} : { reusedWorktree: reuse.reusedWorktree }),
1097 ...(message === undefined
1098 ? {}
1099 : {
1100 initialMessage: {
1101 text: message.text,
1102 attachments: message.attachments,
1103 ...(message.context ? { context: message.context } : {}),
1104 },
1105 }),
1106 },
1107 input.threadId,
1108 run.id,
1109 );
1110 };
1111
1112 return ThreadLaunchService.of({ launch, checkWorktreeBase, retryPreparation, prepareRun });
1113});
1114
1115export const layer = Layer.effect(ThreadLaunchService, make);