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