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

ThreadLaunchService.ts

589 lines21.2 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 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>;
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;
73​
74export interface ThreadLaunchResult {
75 readonly threadId: ThreadId;
76 readonly projection: OrchestrationV2ThreadProjection;
77 readonly resumed: boolean;
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 }
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)}`;
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 // "Start from origin" is a stored default; repos without the requested
244 // remote branch fall back to the local base branch.
245 const startFromOrigin =
246 input.workspaceStrategy.startFromOrigin === true &&
247 (yield* git
248 .remoteExists({ cwd: project.workspaceRoot, remoteName: "origin" })
249 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))));
250 if (startFromOrigin) {
251 yield* git
252 .fetchRemote({ cwd: project.workspaceRoot, remoteName: "origin" })
253 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
254 const remoteBaseExists = yield* git
255 .remoteBranchExists({
256 cwd: project.workspaceRoot,
257 refName: input.workspaceStrategy.baseRef,
258 remoteName: "origin",
259 })
260 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
261 if (remoteBaseExists) {
262 startRef = yield* git
263 .resolveRemoteTrackingCommit({
264 cwd: project.workspaceRoot,
265 refName: input.workspaceStrategy.baseRef,
266 fallbackRemoteName: "origin",
267 })
268 .pipe(
269 Effect.map((resolved) => resolved.commitSha),
270 Effect.mapError(mapError(input, "provision-worktree", threadId)),
271 );
272 }
273 }
274 const worktree = yield* git
275 .createWorktree({
276 cwd: project.workspaceRoot,
277 refName: startRef,
278 newRefName: branch!,
279 baseRefName: input.workspaceStrategy.baseRef,
280 path: null,
281 })
282 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
283 worktreePath = worktree.worktree.path;
284 branch = worktree.worktree.refName;
285 }
286​
287 yield* threads
288 .dispatch({
289 type: "thread.metadata.update",
290 commandId: CommandId.make(`${input.commandId}:workspace`),
291 threadId,
292 branch,
293 worktreePath,
294 })
295 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
296​
297 // Rename temporary branches (server-invented above, or sent by clients
298 // that name worktrees themselves) in the background so generation latency
299 // never delays provisioning or the provider turn. The temporary name
300 // simply sticks if generation or the rename fails.
301 if (
302 worktreePath !== null &&
303 branch !== null &&
304 initialMessage !== undefined &&
305 isTemporaryWorktreeBranch(branch)
306 ) {
307 const oldBranch = branch;
308 const worktreeCwd = worktreePath;
309 yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe(
310 Effect.flatMap((newBranch) => git.renameBranch({ cwd: worktreeCwd, oldBranch, newBranch })),
311 Effect.flatMap((renamed) =>
312 threads.dispatch({
313 type: "thread.metadata.update",
314 commandId: CommandId.make(`${input.commandId}:branch-rename`),
315 threadId,
316 branch: renamed.branch,
317 worktreePath: worktreeCwd,
318 }),
319 ),
320 Effect.catchCause((cause) =>
321 Effect.logWarning("Thread worktree branch rename failed", {
322 commandId: input.commandId,
323 threadId,
324 oldBranch,
325 cause,
326 }),
327 ),
328 Effect.forkIn(preparationScope),
329 );
330 }
331​
332 const cwd = worktreePath ?? project.workspaceRoot;
333 if (runId !== null) {
334 yield* threads
335 .dispatch({
336 type: "prepared-run.progress",
337 commandId: CommandId.make(`${input.commandId}:progress:setup`),
338 threadId,
339 runId,
340 phase: "setup",
341 })
342 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
343 }
344 yield* setupScripts
345 .runForThread({
346 threadId,
347 projectId: input.projectId,
348 projectCwd: project.workspaceRoot,
349 worktreePath: cwd,
350 project: {
351 workspaceRoot: project.workspaceRoot,
352 scripts: project.scripts,
353 },
354 })
355 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
356​
357 if (runId !== null) {
358 yield* threads
359 .dispatch({
360 type: "prepared-run.release",
361 commandId: CommandId.make(`${input.commandId}:release`),
362 threadId,
363 runId,
364 })
365 .pipe(Effect.mapError(mapError(input, "release-run", threadId)));
366 }
367 });
368​
369 const failPreparedRun = (
370 input: ThreadLaunchInput,
371 threadId: ThreadId,
372 runId: RunId | null,
373 cause: unknown,
374 ) =>
375 runId === null
376 ? Effect.logWarning("Thread workspace preparation failed", {
377 commandId: input.commandId,
378 threadId,
379 cause,
380 })
381 : threads
382 .dispatch({
383 type: "prepared-run.fail",
384 commandId: CommandId.make(`${input.commandId}:fail`),
385 threadId,
386 runId,
387 failure: makeProviderFailure({
388 cause,
389 message: failureDetail(cause),
390 class: "validation_error",
391 retryable: false,
392 }),
393 })
394 .pipe(
395 Effect.mapError(mapError(input, "fail-run", threadId)),
396 Effect.catchCause((persistCause) =>
397 Effect.logWarning("Failed to persist thread workspace preparation failure", {
398 commandId: input.commandId,
399 threadId,
400 cause,
401 persistCause,
402 }),
403 ),
404 );
405​
406 const reservePreparation = (commandId: CommandId) =>
407 Ref.modify(scheduledLaunches, (scheduled) => {
408 if (scheduled.has(commandId)) return [false, scheduled] as const;
409 const next = new Set(scheduled);
410 next.add(commandId);
411 return [true, next] as const;
412 });
413​
414 const releasePreparation = (commandId: CommandId) =>
415 Ref.update(scheduledLaunches, (scheduled) => {
416 const next = new Set(scheduled);
417 next.delete(commandId);
418 return next;
419 });
420​
421 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
422 input: ThreadLaunchInput,
423 threadId: ThreadId,
424 runId: RunId | null,
425 ) {
426 yield* prepareInBackground(input, threadId, runId).pipe(
427 Effect.catchCause((cause) =>
428 Cause.hasInterruptsOnly(cause)
429 ? Effect.void
430 : failPreparedRun(input, threadId, runId, Cause.squash(cause)),
431 ),
432 Effect.ensuring(releasePreparation(input.commandId)),
433 Effect.forkIn(preparationScope),
434 );
435 });
436​
437 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
438 function* (input) {
439 const project = yield* projects.getById(input.projectId).pipe(
440 Effect.mapError(mapError(input, "resolve-project")),
441 Effect.flatMap(
442 Option.match({
443 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
444 onSome: Effect.succeed,
445 }),
446 ),
447 );
448 if (input.reuseExistingThread === true && input.threadId === undefined) {
449 return yield* mapError(
450 input,
451 "update-thread",
452 )("Reusing an existing thread requires a thread id.");
453 }
454​
455 const launchReceipt = yield* readReceipt(input, input.commandId);
456 return yield* Effect.gen(function* () {
457 const candidateThreadId =
458 input.threadId ??
459 (yield* ids.allocate
460 .thread({ projectId: input.projectId })
461 .pipe(Effect.mapError(mapError(input, "create-thread"))));
462​
463 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
464 yield* validateReusableThread(input, candidateThreadId);
465 }
466​
467 const initialBranch = input.workspaceStrategy.branch ?? null;
468 const initialWorktreePath =
469 input.workspaceStrategy.type === "existing_worktree"
470 ? input.workspaceStrategy.worktreePath
471 : null;
472 const claimDispatch =
473 input.reuseExistingThread === true
474 ? threads.dispatch({
475 type: "thread.metadata.update",
476 commandId: input.commandId,
477 threadId: candidateThreadId,
478 })
479 : threads.dispatch({
480 type: "thread.create",
481 commandId: input.commandId,
482 threadId: candidateThreadId,
483 projectId: input.projectId,
484 title: input.title,
485 modelSelection: input.modelSelection,
486 runtimeMode: input.runtimeMode,
487 interactionMode: input.interactionMode,
488 branch: initialBranch,
489 worktreePath: initialWorktreePath,
490 createdBy: input.createdBy,
491 creationSource: input.creationSource,
492 });
493 const claimed = yield* claimDispatch.pipe(
494 Effect.mapError(
495 mapError(
496 input,
497 input.reuseExistingThread === true ? "update-thread" : "create-thread",
498 candidateThreadId,
499 ),
500 ),
501 );
502 const threadId =
503 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
504 .threadId ?? candidateThreadId;
505 if (project.id !== input.projectId) {
506 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
507 }
508​
509 let runId: RunId | null = null;
510 let messageWasAlreadyAccepted = false;
511 if (input.initialMessage !== undefined) {
512 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
513 const messageReceipt = yield* readReceipt(input, messageCommandId);
514 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
515 const messageId =
516 input.initialMessage.messageId ??
517 (yield* ids.allocate
518 .message({ threadId, ordinal: 1 })
519 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
520 const dispatched = yield* threads
521 .dispatch({
522 type: "message.dispatch",
523 commandId: messageCommandId,
524 threadId,
525 messageId,
526 text: input.initialMessage.text,
527 attachments: input.initialMessage.attachments,
528 ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
529 modelSelection: input.modelSelection,
530 dispatchMode: { type: "defer_start" },
531 createdBy: input.createdBy,
532 creationSource: input.creationSource,
533 })
534 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
535 const runCreated = dispatched.storedEvents.find(
536 (stored) => stored.event.type === "run.created",
537 );
538 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
539 if (runId === null) {
540 return yield* mapError(
541 input,
542 "dispatch-message",
543 threadId,
544 )("Initial message was accepted without a durable run.");
545 }
546 }
547​
548 const projection = yield* threads
549 .getThreadProjection(threadId)
550 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
551 const runIsPreparing =
552 runId !== null &&
553 projection.runs.some((run) => run.id === runId && run.status === "preparing");
554 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing;
555 if (shouldSchedule) {
556 const ownsPreparation = yield* reservePreparation(input.commandId);
557 if (ownsPreparation) {
558 yield* Effect.gen(function* () {
559 const preparationStillRequired =
560 runId === null
561 ? true
562 : yield* threads.getThreadProjection(threadId).pipe(
563 Effect.map((current) =>
564 current.runs.some((run) => run.id === runId && run.status === "preparing"),
565 ),
566 Effect.mapError(mapError(input, "update-thread", threadId)),
567 );
568 if (preparationStillRequired) {
569 yield* schedulePreparation(input, threadId, runId);
570 } else {
571 yield* releasePreparation(input.commandId);
572 }
573 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
574 }
575 }
576​
577 return {
578 threadId,
579 projection,
580 resumed: Option.isSome(launchReceipt) || messageWasAlreadyAccepted,
581 };
582 });
583 },
584 );
585​
586 return ThreadLaunchService.of({ launch });
587});
588​
589export const layer = Layer.effect(ThreadLaunchService, make);