Open History to see the last commit
1import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
2import {
3 CommandId,
4 type ChatAttachment,
5 type MessageId,
6 type OrchestrationV2AppThread,
7 type OrchestrationV2ConversationMessage,
8 type RunId,
9 type ServerSettingsError,
10 type ThreadId,
11} from "@t3tools/contracts";
12import * as Cause from "effect/Cause";
13import * as Context from "effect/Context";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Schedule from "effect/Schedule";
18
19import * as ServerSettings from "../serverSettings.ts";
20import * as TextGeneration from "../textGeneration/TextGeneration.ts";
21import type { OrchestratorV2Error } from "./Orchestrator.ts";
22import * as ProjectStore from "./ProjectStore.ts";
23import * as ThreadManagementService from "./ThreadManagementService.ts";
24
25import { formatThreadTitleContext } from "@t3tools/provider-core/server/threadTitleContext";
26export { formatThreadTitleContext } from "@t3tools/provider-core/server/threadTitleContext";
27
28export class ThreadTitleRegenerationService extends Context.Service<
29 ThreadTitleRegenerationService,
30 {
31 readonly execute: (input: {
32 readonly threadId: ThreadId;
33 readonly requestId: CommandId;
34 readonly kind:
35 | { readonly type: "initial"; readonly messageId: MessageId }
36 | { readonly type: "regenerate" };
37 }) => Effect.Effect<
38 void,
39 | OrchestratorV2Error
40 | ProjectStore.ProjectStoreV2Error
41 | ServerSettingsError
42 | ThreadManagementService.ThreadManagementProviderInstanceDisabledError
43 >;
44 }
45>()("t3/orchestration-v2/ThreadTitleRegenerationService") {}
46
47const make = Effect.gen(function* () {
48 const threads = yield* ThreadManagementService.ThreadManagementService;
49 const projects = yield* ProjectStore.ProjectStoreV2;
50 const serverSettings = yield* ServerSettings.ServerSettingsService;
51 const textGeneration = yield* TextGeneration.TextGeneration;
52
53 const complete = (input: {
54 readonly threadId: ThreadId;
55 readonly requestId: CommandId;
56 readonly title?: string;
57 }) =>
58 threads
59 .dispatch({
60 type: "thread.title.regeneration.complete",
61 commandId: CommandId.make(`${input.requestId}:title-complete`),
62 threadId: input.threadId,
63 requestId: input.requestId,
64 ...(input.title === undefined ? {} : { title: input.title }),
65 })
66 .pipe(Effect.asVoid);
67
68 const messagesThroughRun = Effect.fn("ThreadTitleRegenerationService.messagesThroughRun")(
69 function* (threadId: ThreadId, runId: RunId) {
70 const source = yield* threads.getThreadRecords(threadId, ["messages", "runs"], {
71 messageRoles: ["user", "assistant"],
72 });
73 const ordinals = new Map(
74 source.runs
75 .filter((run) => run.status !== "rolled_back")
76 .map((run) => [run.id, run.ordinal]),
77 );
78 const forkOrdinal = ordinals.get(runId) ?? -1;
79 const messages = source.messages.filter((message) => {
80 if (message.streaming) return false;
81 if (message.runId === null) return source.thread.historyOrigin === "v1_import";
82 return (ordinals.get(message.runId) ?? Infinity) <= forkOrdinal;
83 });
84 return { thread: source.thread, messages };
85 },
86 );
87
88 // A fork starts with no messages of its own, so its subject lives in the history it inherited.
89 const forkSource = Effect.fn("ThreadTitleRegenerationService.forkSource")(function* (
90 thread: OrchestrationV2AppThread,
91 ) {
92 let title: string | undefined;
93 let history: Array<OrchestrationV2ConversationMessage> = [];
94 let forkedFrom = thread.forkedFrom;
95 while (forkedFrom?.type === "run") {
96 const source = yield* messagesThroughRun(forkedFrom.threadId, forkedFrom.runId);
97 history = [...source.messages, ...history];
98 title ??= source.thread.title;
99 forkedFrom = source.thread.forkedFrom;
100 }
101 const context = formatThreadTitleContext(history);
102 return title === undefined || context.message.length === 0
103 ? undefined
104 : { title, history: context.message };
105 });
106
107 const execute: ThreadTitleRegenerationService["Service"]["execute"] = Effect.fn(
108 "ThreadTitleRegenerationService.execute",
109 )(function* (input) {
110 const outcome:
111 | { readonly type: "stale" }
112 | { readonly type: "complete"; readonly title?: string } = yield* Effect.gen(function* () {
113 const projection = yield* threads.getThreadRecords(
114 input.threadId,
115 ["messages"],
116 input.kind.type === "initial"
117 ? { messageIds: [input.kind.messageId] }
118 : { messageRoles: ["user", "assistant"] },
119 );
120 if (projection.thread.titleRegeneration?.requestId !== input.requestId) {
121 return { type: "stale" as const };
122 }
123
124 const project = yield* projects.get(projection.thread.projectId);
125 if (Option.isNone(project)) {
126 return { type: "complete" as const };
127 }
128
129 let context: {
130 readonly message: string;
131 readonly attachments: ReadonlyArray<ChatAttachment>;
132 };
133 if (input.kind.type === "initial") {
134 const messageId = input.kind.messageId;
135 const message = projection.messages.find(
136 (candidate) => candidate.id === messageId && !candidate.streaming,
137 );
138 context =
139 message === undefined
140 ? { message: "", attachments: [] }
141 : { message: message.text, attachments: message.attachments };
142 } else {
143 context = formatThreadTitleContext(
144 projection.messages.filter((message) => !message.streaming),
145 );
146 }
147 if (context.message.length === 0 && context.attachments.length === 0) {
148 return { type: "complete" as const };
149 }
150
151 // A deleted source should not cost the fork its title.
152 const inherited = yield* forkSource(projection.thread).pipe(
153 Effect.orElseSucceed(() => undefined),
154 );
155 const settings = resolveProjectSettings(
156 yield* serverSettings.getSettings,
157 projection.thread.projectId,
158 ).settings;
159 const result = yield* textGeneration.generateThreadTitle({
160 cwd: projection.thread.worktreePath ?? project.value.workspaceRoot,
161 message: context.message,
162 attachments: context.attachments,
163 ...(input.kind.type === "regenerate" ? { previousTitle: projection.thread.title } : {}),
164 ...(inherited === undefined ? {} : { forkSource: inherited }),
165 instructions: settings.threadTitleInstructions,
166 modelSelection: settings.textGenerationModelSelection,
167 });
168 const generatedTitle = result.title.trim();
169 return generatedTitle === "New thread" ||
170 (input.kind.type === "regenerate" && generatedTitle === projection.thread.title.trim())
171 ? { type: "complete" as const }
172 : { type: "complete" as const, title: result.title };
173 }).pipe(
174 Effect.retry({
175 times: input.kind.type === "initial" ? 2 : 0,
176 schedule: Schedule.exponential("2 seconds"),
177 }),
178 Effect.catchCause((cause) =>
179 Cause.hasInterruptsOnly(cause)
180 ? Effect.interrupt
181 : Effect.logWarning("Thread title generation failed", {
182 threadId: input.threadId,
183 requestId: input.requestId,
184 cause,
185 }).pipe(Effect.as({ type: "complete" as const })),
186 ),
187 );
188
189 if (outcome.type === "stale") {
190 return;
191 }
192 yield* complete({
193 ...input,
194 ...(outcome.title === undefined ? {} : { title: outcome.title }),
195 });
196 });
197
198 return ThreadTitleRegenerationService.of({ execute });
199});
200
201export const layer = Layer.effect(ThreadTitleRegenerationService, make);