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

ThreadTitleRegenerationService.ts

264 lines9.4 KB

1import {
2 type ChatAttachment,
3 CommandId,
4 type MessageId,
5 type ServerSettingsError,
6 type ThreadId,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import * as Context from "effect/Context";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Schedule from "effect/Schedule";
14​
15import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
16import { ProjectionProjectRepository } from "../persistence/Services/ProjectionProjects.ts";
17import * as ServerSettings from "../serverSettings.ts";
18import * as TextGeneration from "../textGeneration/TextGeneration.ts";
19import type { OrchestratorV2Error } from "./Orchestrator.ts";
20import { ThreadManagementService } from "./ThreadManagementService.ts";
21​
22const MAX_REGENERATION_ATTACHMENTS = 4;
23const MAX_THREAD_TITLE_CONTEXT_CHARS = 8_000;
24const MAX_FIRST_USER_TITLE_CONTEXT_CHARS = 2_000;
25const THREAD_TITLE_CONTEXT_TRUNCATION_MARKER = "[Earlier content truncated]\n\n";
26const FIRST_USER_CONTEXT_TRUNCATION_MARKER = "\n[First user message truncated]";
27​
28type ThreadTitleMessage = {
29 readonly role: "user" | "assistant" | "system";
30 readonly text: string;
31 readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
32};
33​
34function formatThreadTitleSection(message: ThreadTitleMessage): string | undefined {
35 if (message.role === "system") {
36 return undefined;
37 }
38 const text = message.text.trim();
39 const attachmentSummary = (message.attachments ?? [])
40 .map((attachment) => attachment.name)
41 .join(", ");
42 const contents = [
43 ...(text.length > 0 ? [text] : []),
44 ...(attachmentSummary.length > 0 ? [`[Attachments: ${attachmentSummary}]`] : []),
45 ].join("\n");
46 return contents.length > 0 ? `${message.role.toUpperCase()}:\n${contents}` : undefined;
48​
49function limitFirstUserSection(section: string): string {
50 if (section.length <= MAX_FIRST_USER_TITLE_CONTEXT_CHARS) {
51 return section;
52 }
53 return `${section.slice(
54 0,
55 MAX_FIRST_USER_TITLE_CONTEXT_CHARS - FIRST_USER_CONTEXT_TRUNCATION_MARKER.length,
56 )}${FIRST_USER_CONTEXT_TRUNCATION_MARKER}`;
58​
59function collectRecentThreadTitleContext(
60 messages: ReadonlyArray<ThreadTitleMessage>,
61 maxChars: number,
62): {
63 readonly context: string;
64 readonly attachments: ReadonlyArray<ChatAttachment>;
65 readonly truncated: boolean;
66} {
67 let context = "";
68 let truncated = false;
69 const retainedAttachments: Array<ChatAttachment> = [];
70​
71 for (const message of messages.toReversed()) {
72 const section = formatThreadTitleSection(message);
73 if (section === undefined) {
74 continue;
75 }
76​
77 const separator = context.length > 0 ? "\n\n" : "";
78 const available = maxChars - context.length - separator.length;
79 if (section.length > available) {
80 if (available > 0) {
81 context = `${section.slice(-available)}${separator}${context}`;
82 retainedAttachments.unshift(...(message.attachments ?? []));
83 }
84 truncated = true;
85 break;
86 }
87 context = `${section}${separator}${context}`;
88 retainedAttachments.unshift(...(message.attachments ?? []));
89 }
90​
91 return { context, attachments: retainedAttachments, truncated };
93​
94/**
95 * Conversation digest for the title prompt. Recent messages fill the budget
96 * newest-first; when the conversation no longer fits, the first user message
97 * is pinned ahead of the recent tail so regenerated titles stay anchored to
98 * what the thread is actually about. Mirrors the v1 reactor's flow (#5365).
99 */
100export function formatThreadTitleContext(messages: ReadonlyArray<ThreadTitleMessage>): {
101 readonly message: string;
102 readonly attachments: ReadonlyArray<ChatAttachment>;
103} {
104 const recent = collectRecentThreadTitleContext(messages, MAX_THREAD_TITLE_CONTEXT_CHARS);
105 if (!recent.truncated) {
106 return {
107 message: recent.context,
108 attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),
109 };
110 }
111​
112 const firstUserMessage = messages.find(
113 (message) => message.role === "user" && formatThreadTitleSection(message),
114 );
115 const firstUserSection = firstUserMessage
116 ? formatThreadTitleSection(firstUserMessage)
117 : undefined;
118 if (!firstUserMessage || !firstUserSection) {
119 return {
120 message: `${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${recent.context}`,
121 attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),
122 };
123 }
124​
125 const pinnedSection = limitFirstUserSection(firstUserSection);
126 const recentContextBudget =
127 MAX_THREAD_TITLE_CONTEXT_CHARS -
128 pinnedSection.length -
129 "\n\n".length -
130 THREAD_TITLE_CONTEXT_TRUNCATION_MARKER.length;
131 const retainedRecent = collectRecentThreadTitleContext(messages, recentContextBudget);
132 const pinnedAttachment = firstUserMessage.attachments?.[0];
133 const recentAttachments = retainedRecent.attachments.filter(
134 (attachment) => attachment.id !== pinnedAttachment?.id,
135 );
136​
137 return {
138 message: `${pinnedSection}\n\n${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${retainedRecent.context}`,
139 attachments: [
140 ...(pinnedAttachment ? [pinnedAttachment] : []),
141 ...recentAttachments.slice(
142 -(MAX_REGENERATION_ATTACHMENTS - (pinnedAttachment === undefined ? 0 : 1)),
143 ),
144 ],
145 };
147​
148export class ThreadTitleRegenerationService extends Context.Service<
149 ThreadTitleRegenerationService,
150 {
151 readonly execute: (input: {
152 readonly threadId: ThreadId;
153 readonly requestId: CommandId;
154 readonly kind:
155 | { readonly type: "initial"; readonly messageId: MessageId }
156 | { readonly type: "regenerate" };
157 }) => Effect.Effect<
158 void,
159 OrchestratorV2Error | ProjectionRepositoryError | ServerSettingsError
160 >;
161 }
162>()("t3/orchestration-v2/ThreadTitleRegenerationService") {}
163​
164const make = Effect.gen(function* () {
165 const threads = yield* ThreadManagementService;
166 const projects = yield* ProjectionProjectRepository;
167 const serverSettings = yield* ServerSettings.ServerSettingsService;
168 const textGeneration = yield* TextGeneration.TextGeneration;
169​
170 const complete = (input: {
171 readonly threadId: ThreadId;
172 readonly requestId: CommandId;
173 readonly title?: string;
174 }) =>
175 threads
176 .dispatch({
177 type: "thread.title.regeneration.complete",
178 commandId: CommandId.make(`${input.requestId}:title-complete`),
179 threadId: input.threadId,
180 requestId: input.requestId,
181 ...(input.title === undefined ? {} : { title: input.title }),
182 })
183 .pipe(Effect.asVoid);
184​
185 const execute: ThreadTitleRegenerationService["Service"]["execute"] = Effect.fn(
186 "ThreadTitleRegenerationService.execute",
187 )(function* (input) {
188 const outcome:
189 | { readonly type: "stale" }
190 | { readonly type: "complete"; readonly title?: string } = yield* Effect.gen(function* () {
191 const projection = yield* threads.getThreadProjection(input.threadId);
192 if (projection.thread.titleRegeneration?.requestId !== input.requestId) {
193 return { type: "stale" as const };
194 }
195​
196 const project = yield* projects.getById({ projectId: projection.thread.projectId });
197 if (Option.isNone(project)) {
198 return { type: "complete" as const };
199 }
200​
201 let context: {
202 readonly message: string;
203 readonly attachments: ReadonlyArray<ChatAttachment>;
204 };
205 if (input.kind.type === "initial") {
206 const messageId = input.kind.messageId;
207 const message = projection.messages.find(
208 (candidate) => candidate.id === messageId && !candidate.streaming,
209 );
210 context =
211 message === undefined
212 ? { message: "", attachments: [] }
213 : { message: message.text, attachments: message.attachments };
214 } else {
215 context = formatThreadTitleContext(
216 projection.messages.filter((message) => !message.streaming),
217 );
218 }
219 if (context.message.length === 0 && context.attachments.length === 0) {
220 return { type: "complete" as const };
221 }
222​
223 const settings = yield* serverSettings.getSettings;
224 const result = yield* textGeneration.generateThreadTitle({
225 cwd: projection.thread.worktreePath ?? project.value.workspaceRoot,
226 message: context.message,
227 attachments: context.attachments,
228 ...(input.kind.type === "regenerate" ? { previousTitle: projection.thread.title } : {}),
229 modelSelection: settings.textGenerationModelSelection,
230 });
231 const generatedTitle = result.title.trim();
232 return generatedTitle === "New thread" ||
233 (input.kind.type === "regenerate" && generatedTitle === projection.thread.title.trim())
234 ? { type: "complete" as const }
235 : { type: "complete" as const, title: result.title };
236 }).pipe(
237 Effect.retry({
238 times: input.kind.type === "initial" ? 2 : 0,
239 schedule: Schedule.exponential("2 seconds"),
240 }),
241 Effect.catchCause((cause) =>
242 Cause.hasInterruptsOnly(cause)
243 ? Effect.interrupt
244 : Effect.logWarning("Thread title generation failed", {
245 threadId: input.threadId,
246 requestId: input.requestId,
247 cause,
248 }).pipe(Effect.as({ type: "complete" as const })),
249 ),
250 );
251​
252 if (outcome.type === "stale") {
253 return;
254 }
255 yield* complete({
256 ...input,
257 ...(outcome.title === undefined ? {} : { title: outcome.title }),
258 });
259 });
260​
261 return ThreadTitleRegenerationService.of({ execute });
262});
263​
264export const layer = Layer.effect(ThreadTitleRegenerationService, make);