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