Open History to see the last commit
1import {
2 CommandId,
3 type ChatAttachment,
4 type MessageId,
5 type ModelSelection,
6 type OrchestrationV2Actor,
7 type OrchestrationV2CreationSource,
8 type OrchestrationV2ThreadProjection,
9 type ProviderInteractionMode,
10 ProjectId,
11 type RunId,
12 type RuntimeMode,
13 ThreadId,
14} from "@t3tools/contracts";
15import * as Cause from "effect/Cause";
16import * as Context from "effect/Context";
17import * as Effect from "effect/Effect";
18import * as Exit from "effect/Exit";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Ref from "effect/Ref";
22import * as Schema from "effect/Schema";
23import * as Scope from "effect/Scope";
24import { buildTemporaryWorktreeBranchName, isTemporaryWorktreeBranch } from "@t3tools/shared/git";
25
26import * as GitWorkflow from "../git/GitWorkflowService.ts";
27import * as ProjectService from "../project/ProjectService.ts";
28import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
29import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
30import * as ServerSettings from "../serverSettings.ts";
31import * as TextGeneration from "../textGeneration/TextGeneration.ts";
32import * as CommandReceiptStore from "./CommandReceiptStore.ts";
33import * as IdAllocator from "./IdAllocator.ts";
34import { makeProviderFailure } from "./ProviderFailure.ts";
35import { randomUuidV4 } from "./RandomUuid.ts";
36import * as ThreadManagement from "./ThreadManagementService.ts";
37
38export type ThreadLaunchWorkspaceStrategy =
39 | { readonly type: "root"; readonly branch?: string | undefined }
40 | {
41 readonly type: "existing_worktree";
42 readonly worktreePath: string;
43 readonly branch?: string | undefined;
44 }
45 | {
46 readonly type: "worktree";
47 readonly baseRef: string;
48 readonly branch?: string | undefined;
49 readonly startFromOrigin?: boolean | undefined;
50 };
51
52export interface ThreadLaunchInitialMessage {
53 readonly messageId?: MessageId;
54 readonly text: string;
55 readonly attachments: ReadonlyArray<ChatAttachment>;
56}
57
58export interface ThreadLaunchInput {
59 readonly commandId: CommandId;
60 readonly threadId?: ThreadId;
61 readonly reuseExistingThread?: boolean;
62 readonly projectId: ProjectId;
63 readonly title: string;
64 readonly generateTitle?: boolean;
65 readonly modelSelection: ModelSelection;
66 readonly runtimeMode: RuntimeMode;
67 readonly interactionMode: ProviderInteractionMode;
68 readonly workspaceStrategy: ThreadLaunchWorkspaceStrategy;
69 readonly initialMessage?: ThreadLaunchInitialMessage;
70 readonly createdBy: OrchestrationV2Actor;
71 readonly creationSource: OrchestrationV2CreationSource;
72}
73
74export interface ThreadLaunchResult {
75 readonly threadId: ThreadId;
76 readonly projection: OrchestrationV2ThreadProjection;
77 readonly resumed: boolean;
78}
79
80export class ThreadLaunchError extends Schema.TaggedErrorClass<ThreadLaunchError>()(
81 "ThreadLaunchError",
82 {
83 operation: Schema.Literals([
84 "resolve-project",
85 "read-receipt",
86 "generate-metadata",
87 "provision-worktree",
88 "run-setup-script",
89 "create-thread",
90 "update-thread",
91 "dispatch-message",
92 "release-run",
93 "fail-run",
94 ]),
95 commandId: CommandId,
96 projectId: ProjectId,
97 threadId: Schema.optional(ThreadId),
98 cause: Schema.Defect(),
99 },
100) {
101 override get message(): string {
102 return `Thread launch ${this.commandId} failed during ${this.operation}.`;
103 }
104}
105
106export class ThreadLaunchService extends Context.Service<
107 ThreadLaunchService,
108 {
109 readonly launch: (
110 input: ThreadLaunchInput,
111 ) => Effect.Effect<ThreadLaunchResult, ThreadLaunchError>;
112 }
113>()("t3/orchestration-v2/ThreadLaunchService") {}
114
115const isThreadLaunchError = Schema.is(ThreadLaunchError);
116
117function failureDetail(error: unknown): string {
118 if (isThreadLaunchError(error)) {
119 const cause = error.cause;
120 const detail = cause instanceof Error ? cause.message : String(cause);
121 return `Workspace preparation failed during ${error.operation.replaceAll("-", " ")}: ${detail}`;
122 }
123 return `Workspace preparation failed: ${error instanceof Error ? error.message : String(error)}`;
124}
125
126export const make = Effect.gen(function* () {
127 const projects = yield* ProjectService.ProjectService;
128 const git = yield* GitWorkflow.GitWorkflowService;
129 const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
130 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
131 const serverSettings = yield* ServerSettings.ServerSettingsService;
132 const textGeneration = yield* TextGeneration.TextGeneration;
133 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
134 const ids = yield* IdAllocator.IdAllocatorV2;
135 const threads = yield* ThreadManagement.ThreadManagementService;
136 const preparationScope = yield* Scope.make("sequential");
137 const scheduledLaunches = yield* Ref.make<ReadonlySet<CommandId>>(new Set());
138 yield* Effect.addFinalizer(() => Scope.close(preparationScope, Exit.void));
139
140 const mapError =
141 (input: ThreadLaunchInput, operation: ThreadLaunchError["operation"], threadId?: ThreadId) =>
142 (cause: unknown) =>
143 new ThreadLaunchError({
144 operation,
145 commandId: input.commandId,
146 projectId: input.projectId,
147 ...(threadId === undefined ? {} : { threadId }),
148 cause,
149 });
150
151 const readReceipt = (input: ThreadLaunchInput, commandId: CommandId) =>
152 receipts
153 .getByCommandId(commandId)
154 .pipe(Effect.mapError(mapError(input, "read-receipt", input.threadId)));
155
156 const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")(function* (
157 input: ThreadLaunchInput,
158 threadId: ThreadId,
159 ) {
160 const projection = yield* threads
161 .getThreadProjection(threadId)
162 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
163 if (
164 projection.thread.projectId !== input.projectId ||
165 projection.thread.archivedAt !== null ||
166 projection.thread.deletedAt !== null ||
167 projection.messages.length > 0 ||
168 projection.runs.length > 0
169 ) {
170 return yield* mapError(
171 input,
172 "update-thread",
173 threadId,
174 )("Only an empty active thread in the target project can change workspace during launch.");
175 }
176 });
177
178 const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* (
179 input: ThreadLaunchInput,
180 threadId: ThreadId,
181 runId: RunId | null,
182 ) {
183 const project = yield* projects.getById(input.projectId).pipe(
184 Effect.mapError(mapError(input, "resolve-project", threadId)),
185 Effect.flatMap(
186 Option.match({
187 onNone: () =>
188 Effect.fail(mapError(input, "resolve-project", threadId)("Project no longer exists.")),
189 onSome: Effect.succeed,
190 }),
191 ),
192 );
193
194 const initialMessage = input.initialMessage;
195 const generateBranchNameFor = (cwd: string, message: ThreadLaunchInitialMessage) =>
196 Effect.gen(function* () {
197 const settings = yield* serverSettings.getSettings;
198 const modelSelection =
199 settings.sourceControlWriterModelSelection === null
200 ? settings.textGenerationModelSelection
201 : ServerSettings.resolveSourceControlWriterModelSelection(
202 settings,
203 yield* providerRegistry.getProviders,
204 );
205 return yield* textGeneration
206 .generateBranchName({
207 cwd,
208 message: message.text,
209 attachments: message.attachments,
210 modelSelection,
211 })
212 .pipe(Effect.map((result) => result.branch));
213 });
214
215 // The server owns worktree naming: without an explicit branch, provision
216 // under a temporary `t3code/<hash>` name so the worktree never waits on
217 // name generation, then rename in the background below.
218 const requestedBranch = input.workspaceStrategy.branch;
219 let branch: string | null;
220 if (input.workspaceStrategy.type === "worktree" && requestedBranch === undefined) {
221 const uuid = yield* randomUuidV4;
222 branch = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
223 } else {
224 branch = requestedBranch ?? null;
225 }
226 let worktreePath =
227 input.workspaceStrategy.type === "existing_worktree"
228 ? input.workspaceStrategy.worktreePath
229 : null;
230 if (input.workspaceStrategy.type === "worktree") {
231 if (runId !== null) {
232 yield* threads
233 .dispatch({
234 type: "prepared-run.progress",
235 commandId: CommandId.make(`${input.commandId}:progress:worktree`),
236 threadId,
237 runId,
238 phase: "worktree",
239 })
240 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
241 }
242 let startRef = input.workspaceStrategy.baseRef;
243 if (input.workspaceStrategy.startFromOrigin === true) {
244 yield* git
245 .fetchRemote({ cwd: project.workspaceRoot, remoteName: "origin" })
246 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
247 startRef = yield* git
248 .resolveRemoteTrackingCommit({
249 cwd: project.workspaceRoot,
250 refName: input.workspaceStrategy.baseRef,
251 fallbackRemoteName: "origin",
252 })
253 .pipe(
254 Effect.map((resolved) => resolved.commitSha),
255 Effect.mapError(mapError(input, "provision-worktree", threadId)),
256 );
257 }
258 const worktree = yield* git
259 .createWorktree({
260 cwd: project.workspaceRoot,
261 refName: startRef,
262 newRefName: branch!,
263 baseRefName: input.workspaceStrategy.baseRef,
264 path: null,
265 })
266 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
267 worktreePath = worktree.worktree.path;
268 branch = worktree.worktree.refName;
269 }
270
271 yield* threads
272 .dispatch({
273 type: "thread.metadata.update",
274 commandId: CommandId.make(`${input.commandId}:workspace`),
275 threadId,
276 branch,
277 worktreePath,
278 })
279 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
280
281 // Rename temporary branches (server-invented above, or sent by clients
282 // that name worktrees themselves) in the background so generation latency
283 // never delays provisioning or the provider turn. The temporary name
284 // simply sticks if generation or the rename fails.
285 if (
286 worktreePath !== null &&
287 branch !== null &&
288 initialMessage !== undefined &&
289 isTemporaryWorktreeBranch(branch)
290 ) {
291 const oldBranch = branch;
292 const worktreeCwd = worktreePath;
293 yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe(
294 Effect.flatMap((newBranch) => git.renameBranch({ cwd: worktreeCwd, oldBranch, newBranch })),
295 Effect.flatMap((renamed) =>
296 threads.dispatch({
297 type: "thread.metadata.update",
298 commandId: CommandId.make(`${input.commandId}:branch-rename`),
299 threadId,
300 branch: renamed.branch,
301 worktreePath: worktreeCwd,
302 }),
303 ),
304 Effect.catchCause((cause) =>
305 Effect.logWarning("Thread worktree branch rename failed", {
306 commandId: input.commandId,
307 threadId,
308 oldBranch,
309 cause,
310 }),
311 ),
312 Effect.forkIn(preparationScope),
313 );
314 }
315
316 const cwd = worktreePath ?? project.workspaceRoot;
317 if (runId !== null) {
318 yield* threads
319 .dispatch({
320 type: "prepared-run.progress",
321 commandId: CommandId.make(`${input.commandId}:progress:setup`),
322 threadId,
323 runId,
324 phase: "setup",
325 })
326 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
327 }
328 yield* setupScripts
329 .runForThread({
330 threadId,
331 projectId: input.projectId,
332 projectCwd: project.workspaceRoot,
333 worktreePath: cwd,
334 project: {
335 workspaceRoot: project.workspaceRoot,
336 scripts: project.scripts,
337 },
338 })
339 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
340
341 if (runId !== null) {
342 yield* threads
343 .dispatch({
344 type: "prepared-run.release",
345 commandId: CommandId.make(`${input.commandId}:release`),
346 threadId,
347 runId,
348 })
349 .pipe(Effect.mapError(mapError(input, "release-run", threadId)));
350 }
351 });
352
353 const failPreparedRun = (
354 input: ThreadLaunchInput,
355 threadId: ThreadId,
356 runId: RunId | null,
357 cause: unknown,
358 ) =>
359 runId === null
360 ? Effect.logWarning("Thread workspace preparation failed", {
361 commandId: input.commandId,
362 threadId,
363 cause,
364 })
365 : threads
366 .dispatch({
367 type: "prepared-run.fail",
368 commandId: CommandId.make(`${input.commandId}:fail`),
369 threadId,
370 runId,
371 failure: makeProviderFailure({
372 cause,
373 message: failureDetail(cause),
374 class: "validation_error",
375 retryable: false,
376 }),
377 })
378 .pipe(
379 Effect.mapError(mapError(input, "fail-run", threadId)),
380 Effect.catchCause((persistCause) =>
381 Effect.logWarning("Failed to persist thread workspace preparation failure", {
382 commandId: input.commandId,
383 threadId,
384 cause,
385 persistCause,
386 }),
387 ),
388 );
389
390 const reservePreparation = (commandId: CommandId) =>
391 Ref.modify(scheduledLaunches, (scheduled) => {
392 if (scheduled.has(commandId)) return [false, scheduled] as const;
393 const next = new Set(scheduled);
394 next.add(commandId);
395 return [true, next] as const;
396 });
397
398 const releasePreparation = (commandId: CommandId) =>
399 Ref.update(scheduledLaunches, (scheduled) => {
400 const next = new Set(scheduled);
401 next.delete(commandId);
402 return next;
403 });
404
405 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
406 input: ThreadLaunchInput,
407 threadId: ThreadId,
408 runId: RunId | null,
409 ) {
410 yield* prepareInBackground(input, threadId, runId).pipe(
411 Effect.catchCause((cause) =>
412 Cause.hasInterruptsOnly(cause)
413 ? Effect.void
414 : failPreparedRun(input, threadId, runId, Cause.squash(cause)),
415 ),
416 Effect.ensuring(releasePreparation(input.commandId)),
417 Effect.forkIn(preparationScope),
418 );
419 });
420
421 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
422 function* (input) {
423 const project = yield* projects.getById(input.projectId).pipe(
424 Effect.mapError(mapError(input, "resolve-project")),
425 Effect.flatMap(
426 Option.match({
427 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
428 onSome: Effect.succeed,
429 }),
430 ),
431 );
432 if (input.reuseExistingThread === true && input.threadId === undefined) {
433 return yield* mapError(
434 input,
435 "update-thread",
436 )("Reusing an existing thread requires a thread id.");
437 }
438
439 const launchReceipt = yield* readReceipt(input, input.commandId);
440 return yield* Effect.gen(function* () {
441 const candidateThreadId =
442 input.threadId ??
443 (yield* ids.allocate
444 .thread({ projectId: input.projectId })
445 .pipe(Effect.mapError(mapError(input, "create-thread"))));
446
447 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
448 yield* validateReusableThread(input, candidateThreadId);
449 }
450
451 const initialBranch = input.workspaceStrategy.branch ?? null;
452 const initialWorktreePath =
453 input.workspaceStrategy.type === "existing_worktree"
454 ? input.workspaceStrategy.worktreePath
455 : null;
456 const claimDispatch =
457 input.reuseExistingThread === true
458 ? threads.dispatch({
459 type: "thread.metadata.update",
460 commandId: input.commandId,
461 threadId: candidateThreadId,
462 })
463 : threads.dispatch({
464 type: "thread.create",
465 commandId: input.commandId,
466 threadId: candidateThreadId,
467 projectId: input.projectId,
468 title: input.title,
469 modelSelection: input.modelSelection,
470 runtimeMode: input.runtimeMode,
471 interactionMode: input.interactionMode,
472 branch: initialBranch,
473 worktreePath: initialWorktreePath,
474 createdBy: input.createdBy,
475 creationSource: input.creationSource,
476 });
477 const claimed = yield* claimDispatch.pipe(
478 Effect.mapError(
479 mapError(
480 input,
481 input.reuseExistingThread === true ? "update-thread" : "create-thread",
482 candidateThreadId,
483 ),
484 ),
485 );
486 const threadId =
487 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
488 .threadId ?? candidateThreadId;
489 if (project.id !== input.projectId) {
490 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
491 }
492
493 let runId: RunId | null = null;
494 let messageWasAlreadyAccepted = false;
495 if (input.initialMessage !== undefined) {
496 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
497 const messageReceipt = yield* readReceipt(input, messageCommandId);
498 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
499 const messageId =
500 input.initialMessage.messageId ??
501 (yield* ids.allocate
502 .message({ threadId, ordinal: 1 })
503 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
504 const dispatched = yield* threads
505 .dispatch({
506 type: "message.dispatch",
507 commandId: messageCommandId,
508 threadId,
509 messageId,
510 text: input.initialMessage.text,
511 attachments: input.initialMessage.attachments,
512 ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
513 modelSelection: input.modelSelection,
514 dispatchMode: { type: "defer_start" },
515 createdBy: input.createdBy,
516 creationSource: input.creationSource,
517 })
518 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
519 const runCreated = dispatched.storedEvents.find(
520 (stored) => stored.event.type === "run.created",
521 );
522 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
523 if (runId === null) {
524 return yield* mapError(
525 input,
526 "dispatch-message",
527 threadId,
528 )("Initial message was accepted without a durable run.");
529 }
530 }
531
532 const projection = yield* threads
533 .getThreadProjection(threadId)
534 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
535 const runIsPreparing =
536 runId !== null &&
537 projection.runs.some((run) => run.id === runId && run.status === "preparing");
538 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing;
539 if (shouldSchedule) {
540 const ownsPreparation = yield* reservePreparation(input.commandId);
541 if (ownsPreparation) {
542 yield* Effect.gen(function* () {
543 const preparationStillRequired =
544 runId === null
545 ? true
546 : yield* threads.getThreadProjection(threadId).pipe(
547 Effect.map((current) =>
548 current.runs.some((run) => run.id === runId && run.status === "preparing"),
549 ),
550 Effect.mapError(mapError(input, "update-thread", threadId)),
551 );
552 if (preparationStillRequired) {
553 yield* schedulePreparation(input, threadId, runId);
554 } else {
555 yield* releasePreparation(input.commandId);
556 }
557 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
558 }
559 }
560
561 return {
562 threadId,
563 projection,
564 resumed: Option.isSome(launchReceipt) || messageWasAlreadyAccepted,
565 };
566 });
567 },
568 );
569
570 return ThreadLaunchService.of({ launch });
571});
572
573export const layer = Layer.effect(ThreadLaunchService, make);