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

ThreadTitleRegenerationService.ts

264 lines10.3 KB

1import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
2import { isAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
3import {
4 CommandId,
5 type ChatAttachment,
6 type MessageId,
7 type OrchestrationV2AppThread,
8 type OrchestrationV2ConversationMessage,
9 type RunId,
10 type ServerSettingsError,
11 TextGenerationError,
12 type ThreadId,
13} from "@t3tools/contracts";
14import * as Cause from "effect/Cause";
15import * as Context from "effect/Context";
16import * as Effect from "effect/Effect";
17import type * as DateTime from "effect/DateTime";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Schedule from "effect/Schedule";
22import * as Schema from "effect/Schema";
23​
24import * as ServerSettings from "../serverSettings.ts";
25import * as TextGeneration from "../textGeneration/TextGeneration.ts";
26import type { OrchestratorV2Error } from "./Orchestrator.ts";
27import * as ProjectStore from "./ProjectStore.ts";
28import { forkInheritedRunOrdinals, ProjectionStoreThreadNotFoundError } from "./ProjectionStore.ts";
29import * as ThreadManagementService from "./ThreadManagementService.ts";
30​
31import { formatThreadTitleContext } from "@t3tools/provider-core/server/threadTitleContext";
32export { formatThreadTitleContext } from "@t3tools/provider-core/server/threadTitleContext";
33​
34export class ThreadTitleRegenerationService extends Context.Service<
35 ThreadTitleRegenerationService,
36 {
37 readonly execute: (input: {
38 readonly threadId: ThreadId;
39 readonly requestId: CommandId;
40 readonly kind:
41 | { readonly type: "initial"; readonly messageId: MessageId }
42 | { readonly type: "regenerate" };
43 }) => Effect.Effect<
44 void,
45 | OrchestratorV2Error
46 | ProjectStore.ProjectStoreV2Error
47 | ServerSettingsError
48 | ThreadManagementService.ThreadManagementProviderInstanceDisabledError
49 >;
50 }
51>()("t3/orchestration-v2/ThreadTitleRegenerationService") {}
52​
53type Outcome =
54 | { readonly status: "renamed"; readonly title: string }
55 | { readonly status: "unchanged" }
56 | { readonly status: "failed"; readonly message: string };
57​
58const MAX_FAILURE_MESSAGE_LENGTH = 300;
59const isTextGenerationError = Schema.is(TextGenerationError);
60const isProjectionStoreThreadNotFoundError = Schema.is(ProjectionStoreThreadNotFoundError);
61​
62function failureMessage(cause: Cause.Cause<unknown>): string {
63 const error = Cause.squash(cause);
64 const lines = isTextGenerationError(error)
65 ? error.detail
66 .split("\n")
67 .map((line) => line.trim())
68 .filter((line) => line.length > 0)
69 : [];
70 const detail = lines.at(-1);
71 if (detail === undefined) return "Title generation failed.";
72 if (detail.length <= MAX_FAILURE_MESSAGE_LENGTH) return detail;
73 const keep = MAX_FAILURE_MESSAGE_LENGTH - 1;
74 const last = detail.charCodeAt(keep - 1);
75 const end = keep - (last >= 0xd800 && last <= 0xdbff ? 1 : 0);
76 return `${detail.slice(0, end)}…`;
78​
79const make = Effect.gen(function* () {
80 const threads = yield* ThreadManagementService.ThreadManagementService;
81 const projects = yield* ProjectStore.ProjectStoreV2;
82 const serverSettings = yield* ServerSettings.ServerSettingsService;
83 const textGeneration = yield* TextGeneration.TextGeneration;
84 const fileSystem = yield* FileSystem.FileSystem;
85​
86 const complete = (input: {
87 readonly threadId: ThreadId;
88 readonly requestId: CommandId;
89 readonly kind: { readonly type: "initial" | "regenerate" };
90 readonly outcome: Outcome;
91 }) =>
92 threads
93 .dispatch({
94 type: "thread.title.regeneration.complete",
95 commandId: CommandId.make(`${input.requestId}:title-complete`),
96 threadId: input.threadId,
97 requestId: input.requestId,
98 ...(input.outcome.status === "renamed" ? { title: input.outcome.title } : {}),
99 ...(input.kind.type === "regenerate"
100 ? {
101 outcome: {
102 status: input.outcome.status,
103 ...(input.outcome.status === "failed" ? { message: input.outcome.message } : {}),
104 },
105 }
106 : {}),
107 })
108 .pipe(Effect.asVoid);
109​
110 const messagesThroughRun = Effect.fn("ThreadTitleRegenerationService.messagesThroughRun")(
111 function* (threadId: ThreadId, runId: RunId, forkCreatedAt: DateTime.Utc) {
112 const source = yield* threads.getThreadRecords(threadId, ["messages", "runs"], {
113 messageRoles: ["user", "assistant"],
114 });
115 const ordinals = forkInheritedRunOrdinals(source.runs, forkCreatedAt);
116 const forkOrdinal = ordinals.get(runId);
117 if (forkOrdinal === undefined) return undefined;
118 const messages = source.messages.filter((message) => {
119 if (message.streaming) return false;
120 if (message.runId === null) return source.thread.historyOrigin === "v1_import";
121 return (ordinals.get(message.runId) ?? Infinity) <= forkOrdinal;
122 });
123 return { thread: source.thread, messages };
124 },
125 );
126​
127 // A fork starts with no messages of its own, so its subject lives in the history it inherited.
128 const forkSource = Effect.fn("ThreadTitleRegenerationService.forkSource")(function* (
129 thread: OrchestrationV2AppThread,
130 ) {
131 let title: string | undefined;
132 const history: Array<ReadonlyArray<OrchestrationV2ConversationMessage>> = [];
133 const seen = new Set([thread.id]);
134 let current = thread;
135 while (
136 current.forkedFrom?.type === "run" &&
137 current.lineage.sideChat !== true &&
138 !seen.has(current.forkedFrom.threadId)
139 ) {
140 const { threadId, runId } = current.forkedFrom;
141 seen.add(threadId);
142 const source = yield* messagesThroughRun(threadId, runId, current.createdAt);
143 if (source === undefined) break;
144 history.push(source.messages);
145 title ??= source.thread.title;
146 current = source.thread;
147 }
148 const context = formatThreadTitleContext(history.reverse().flat());
149 return title === undefined || context.message.length === 0
150 ? undefined
151 : { title, history: context.message };
152 });
153​
154 const execute: ThreadTitleRegenerationService["Service"]["execute"] = Effect.fn(
155 "ThreadTitleRegenerationService.execute",
156 )(function* (input) {
157 const outcome: Outcome | { readonly status: "stale" } = yield* Effect.gen(function* () {
158 const projection = yield* threads.getThreadRecords(
159 input.threadId,
160 ["messages"],
161 input.kind.type === "initial"
162 ? { messageIds: [input.kind.messageId] }
163 : { messageRoles: ["user", "assistant"] },
164 );
165 if (projection.thread.titleRegeneration?.requestId !== input.requestId) {
166 return { status: "stale" as const };
167 }
168​
169 const project = yield* projects.get(projection.thread.projectId);
170 if (Option.isNone(project)) {
171 return { status: "failed" as const, message: "This thread's project no longer exists." };
172 }
173​
174 let context: {
175 readonly message: string;
176 readonly attachments: ReadonlyArray<ChatAttachment>;
177 };
178 if (input.kind.type === "initial") {
179 const messageId = input.kind.messageId;
180 const message = projection.messages.find(
181 (candidate) => candidate.id === messageId && !candidate.streaming,
182 );
183 context =
184 message === undefined
185 ? { message: "", attachments: [] }
186 : {
187 message: isAttachmentOnlyBootstrapPrompt(message.text) ? "" : message.text,
188 attachments: message.attachments,
189 };
190 } else {
191 context = formatThreadTitleContext(
192 projection.messages.filter((message) => !message.streaming),
193 );
194 }
195 // A deleted source should not cost the fork its title.
196 const inherited = yield* forkSource(projection.thread).pipe(
197 Effect.catchTags({
198 OrchestratorProjectionError: (error) =>
199 isProjectionStoreThreadNotFoundError(error.cause)
200 ? Effect.undefined
201 : Effect.fail(error),
202 }),
203 );
204 if (
205 context.message.length === 0 &&
206 context.attachments.length === 0 &&
207 inherited === undefined
208 ) {
209 return {
210 status: "failed" as const,
211 message: "This thread has no messages to title yet.",
212 };
213 }
214 const settings = resolveProjectSettings(
215 yield* serverSettings.getSettings,
216 projection.thread.projectId,
217 ).settings;
218 // Storage cleanup removes worktrees but keeps the path; CLIs cannot spawn in a missing cwd.
219 const worktreePath = projection.thread.worktreePath;
220 const worktreeExists =
221 worktreePath !== null &&
222 (yield* fileSystem.exists(worktreePath).pipe(Effect.orElseSucceed(() => false)));
223 const result = yield* textGeneration.generateThreadTitle({
224 cwd: worktreeExists ? worktreePath : project.value.workspaceRoot,
225 message: context.message,
226 projectTitle: project.value.title,
227 attachments: context.attachments,
228 ...(input.kind.type === "regenerate" ? { previousTitle: projection.thread.title } : {}),
229 ...(inherited === undefined ? {} : { forkSource: inherited }),
230 instructions: settings.threadTitleInstructions,
231 modelSelection: settings.textGenerationModelSelection,
232 projectId: projection.thread.projectId,
233 });
234 const generatedTitle = result.title.trim();
235 return generatedTitle === "New thread" ||
236 (input.kind.type === "regenerate" && generatedTitle === projection.thread.title.trim())
237 ? { status: "unchanged" as const }
238 : { status: "renamed" as const, title: result.title };
239 }).pipe(
240 Effect.retry({
241 times: input.kind.type === "initial" ? 2 : 0,
242 schedule: Schedule.exponential("2 seconds"),
243 }),
244 Effect.catchCause((cause) =>
245 Cause.hasInterruptsOnly(cause)
246 ? Effect.interrupt
247 : Effect.logWarning("Thread title generation failed", {
248 threadId: input.threadId,
249 requestId: input.requestId,
250 cause,
251 }).pipe(Effect.as({ status: "failed" as const, message: failureMessage(cause) })),
252 ),
253 );
254​
255 if (outcome.status === "stale") {
256 return;
257 }
258 yield* complete({ ...input, outcome });
259 });
260​
261 return ThreadTitleRegenerationService.of({ execute });
262});
263​
264export const layer = Layer.effect(ThreadTitleRegenerationService, make);