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