Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadLaunchService.ts

595 lines21.5 KB

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