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