Open History to see the last commit
1import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
2import {
3 CommandId,
4 type ChatAttachment,
5 type MessageId,
6 type ServerSettingsError,
7 type ThreadId,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Context from "effect/Context";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Schedule from "effect/Schedule";
15
16import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
17import { ProjectionProjectRepository } from "../persistence/Services/ProjectionProjects.ts";
18import * as ServerSettings from "../serverSettings.ts";
19import * as TextGeneration from "../textGeneration/TextGeneration.ts";
20import type { OrchestratorV2Error } from "./Orchestrator.ts";
21import { ThreadManagementService } from "./ThreadManagementService.ts";
22
23import { formatThreadTitleContext } from "../textGeneration/ThreadTitleContext.ts";
24export { formatThreadTitleContext } from "../textGeneration/ThreadTitleContext.ts";
25
26export class ThreadTitleRegenerationService extends Context.Service<
27 ThreadTitleRegenerationService,
28 {
29 readonly execute: (input: {
30 readonly threadId: ThreadId;
31 readonly requestId: CommandId;
32 readonly kind:
33 | { readonly type: "initial"; readonly messageId: MessageId }
34 | { readonly type: "regenerate" };
35 }) => Effect.Effect<
36 void,
37 OrchestratorV2Error | ProjectionRepositoryError | ServerSettingsError
38 >;
39 }
40>()("t3/orchestration-v2/ThreadTitleRegenerationService") {}
41
42const make = Effect.gen(function* () {
43 const threads = yield* ThreadManagementService;
44 const projects = yield* ProjectionProjectRepository;
45 const serverSettings = yield* ServerSettings.ServerSettingsService;
46 const textGeneration = yield* TextGeneration.TextGeneration;
47
48 const complete = (input: {
49 readonly threadId: ThreadId;
50 readonly requestId: CommandId;
51 readonly title?: string;
52 }) =>
53 threads
54 .dispatch({
55 type: "thread.title.regeneration.complete",
56 commandId: CommandId.make(`${input.requestId}:title-complete`),
57 threadId: input.threadId,
58 requestId: input.requestId,
59 ...(input.title === undefined ? {} : { title: input.title }),
60 })
61 .pipe(Effect.asVoid);
62
63 const execute: ThreadTitleRegenerationService["Service"]["execute"] = Effect.fn(
64 "ThreadTitleRegenerationService.execute",
65 )(function* (input) {
66 const outcome:
67 | { readonly type: "stale" }
68 | { readonly type: "complete"; readonly title?: string } = yield* Effect.gen(function* () {
69 const projection = yield* threads.getThreadProjection(input.threadId);
70 if (projection.thread.titleRegeneration?.requestId !== input.requestId) {
71 return { type: "stale" as const };
72 }
73
74 const project = yield* projects.getById({ projectId: projection.thread.projectId });
75 if (Option.isNone(project)) {
76 return { type: "complete" as const };
77 }
78
79 let context: {
80 readonly message: string;
81 readonly attachments: ReadonlyArray<ChatAttachment>;
82 };
83 if (input.kind.type === "initial") {
84 const messageId = input.kind.messageId;
85 const message = projection.messages.find(
86 (candidate) => candidate.id === messageId && !candidate.streaming,
87 );
88 context =
89 message === undefined
90 ? { message: "", attachments: [] }
91 : { message: message.text, attachments: message.attachments };
92 } else {
93 context = formatThreadTitleContext(
94 projection.messages.filter((message) => !message.streaming),
95 );
96 }
97 if (context.message.length === 0 && context.attachments.length === 0) {
98 return { type: "complete" as const };
99 }
100
101 const settings = resolveProjectSettings(
102 yield* serverSettings.getSettings,
103 projection.thread.projectId,
104 ).settings;
105 const result = yield* textGeneration.generateThreadTitle({
106 cwd: projection.thread.worktreePath ?? project.value.workspaceRoot,
107 message: context.message,
108 attachments: context.attachments,
109 ...(input.kind.type === "regenerate" ? { previousTitle: projection.thread.title } : {}),
110 modelSelection: settings.textGenerationModelSelection,
111 });
112 const generatedTitle = result.title.trim();
113 return generatedTitle === "New thread" ||
114 (input.kind.type === "regenerate" && generatedTitle === projection.thread.title.trim())
115 ? { type: "complete" as const }
116 : { type: "complete" as const, title: result.title };
117 }).pipe(
118 Effect.retry({
119 times: input.kind.type === "initial" ? 2 : 0,
120 schedule: Schedule.exponential("2 seconds"),
121 }),
122 Effect.catchCause((cause) =>
123 Cause.hasInterruptsOnly(cause)
124 ? Effect.interrupt
125 : Effect.logWarning("Thread title generation failed", {
126 threadId: input.threadId,
127 requestId: input.requestId,
128 cause,
129 }).pipe(Effect.as({ type: "complete" as const })),
130 ),
131 );
132
133 if (outcome.type === "stale") {
134 return;
135 }
136 yield* complete({
137 ...input,
138 ...(outcome.title === undefined ? {} : { title: outcome.title }),
139 });
140 });
141
142 return ThreadTitleRegenerationService.of({ execute });
143});
144
145export const layer = Layer.effect(ThreadTitleRegenerationService, make);