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

ThreadTitleRegenerationService.test.ts

527 lines19.9 KB

1import { assert, describe, it, vi } from "@effect/vitest";
2import {
3 CommandId,
4 ChatAttachmentId,
5 type ChatAttachment,
6 EventId,
7 MessageId,
8 ProjectId,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 ProviderThreadId,
12 RunId,
13 ThreadId,
14} from "@t3tools/contracts";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
20​
21import * as SqlitePersistence from "../persistence/Sqlite.ts";
22import * as ProjectStore from "./ProjectStore.ts";
23import * as ServerSettings from "../serverSettings.ts";
24import * as TextGeneration from "../textGeneration/TextGeneration.ts";
25import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
26import * as CommandReceiptStore from "./CommandReceiptStore.ts";
27import * as EffectOutbox from "./EffectOutbox.ts";
28import * as EventSink from "./EventSink.ts";
29import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
30import * as ThreadManagement from "./ThreadManagementService.ts";
31import * as ThreadTitleRegeneration from "./ThreadTitleRegenerationService.ts";
32import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
33import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
34​
35const projectId = ProjectId.make("project:title-regeneration");
36const modelSelection = {
37 instanceId: ProviderInstanceId.make("codex"),
38 model: "gpt-5.1-codex",
39} as const;
40​
41const adapter = {
42 instanceId: modelSelection.instanceId,
43 driver: ProviderDriverKind.make("codex"),
44 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
45 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
46 openSession: () => Effect.die("provider execution is disabled in title regeneration tests"),
47} as ProviderAdapter.ProviderAdapterV2["Service"];
48​
49function makeHarness(
50 options: {
51 readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"];
52 } = {},
53) {
54 const layerDatabase = SqlitePersistence.layerMemory;
55 const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([adapter]);
56 const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
57 { name: "thread-title-regeneration" },
58 layerRegistry,
59 { databaseLayer: layerDatabase, runEffectWorker: false },
60 );
61 const layerServerSettings = ServerSettings.layerTest({});
62 const layerThreadManagement = ThreadManagement.layer.pipe(
63 Layer.provide(layerOrchestrator),
64 Layer.provide(layerServerSettings),
65 Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
66 );
67 const layerOutbox = EffectOutbox.layer.pipe(Layer.provide(layerDatabase));
68 const generateThreadTitle = vi.fn(
69 options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })),
70 );
71 const layerProjectedProjects = Layer.mock(ProjectStore.ProjectStoreV2)({
72 get: (requestedProjectId) =>
73 Effect.succeed(
74 requestedProjectId === projectId
75 ? Option.some({
76 projectId,
77 title: "Project",
78 workspaceRoot: "/repo",
79 defaultModelSelection: modelSelection,
80 defaultThreadEnvMode: null,
81 autoPull: false,
82 faviconPath: null,
83 projectIcon: null,
84 scripts: [],
85 pinnedAt: null,
86 archivedAt: null,
87 createdAt: "2026-06-20T00:00:00.000Z",
88 updatedAt: "2026-06-20T00:00:00.000Z",
89 deletedAt: null,
90 })
91 : Option.none(),
92 ),
93 });
94 const layerTitleRegeneration = ThreadTitleRegeneration.layer.pipe(
95 Layer.provide(
96 Layer.mergeAll(
97 layerThreadManagement,
98 layerProjectedProjects,
99 Layer.mock(TextGeneration.TextGeneration)({ generateThreadTitle }),
100 layerServerSettings,
101 ),
102 ),
103 );
104 return {
105 layer: Layer.mergeAll(
106 layerOrchestrator,
107 layerThreadManagement,
108 layerTitleRegeneration,
109 layerOutbox,
110 layerDatabase,
111 ),
112 generateThreadTitle,
113 };
115​
116function createThread(input: { readonly command: string; readonly thread: string }) {
117 return Effect.gen(function* () {
118 const threads = yield* ThreadManagement.ThreadManagementService;
119 const threadId = ThreadId.make(input.thread);
120 yield* threads.dispatch({
121 type: "thread.create",
122 commandId: CommandId.make(input.command),
123 threadId,
124 projectId,
125 title: "Seed title",
126 modelSelection,
127 runtimeMode: "full-access",
128 interactionMode: "default",
129 branch: null,
130 worktreePath: null,
131 createdBy: "user",
132 creationSource: "web",
133 });
134 return threadId;
135 });
137​
138function dispatchUserMessage(input: {
139 readonly command: string;
140 readonly threadId: ThreadId;
141 readonly text: string;
142 readonly attachments?: ReadonlyArray<ChatAttachment>;
143}) {
144 return Effect.gen(function* () {
145 const threads = yield* ThreadManagement.ThreadManagementService;
146 yield* threads.dispatch({
147 type: "message.dispatch",
148 commandId: CommandId.make(input.command),
149 threadId: input.threadId,
150 messageId: MessageId.make(`${input.command}:message`),
151 text: input.text,
152 attachments: input.attachments ?? [],
153 modelSelection,
154 dispatchMode: { type: "defer_start" },
155 createdBy: "user",
156 creationSource: "web",
157 });
158 });
160​
161/** Records a settled source run with one exchange, as a provider turn would. */
162function recordRun(input: {
163 readonly threadId: ThreadId;
164 readonly runId: RunId;
165 readonly ordinal: number;
166 readonly user: string;
167 readonly assistant: string;
168 readonly status?: "completed" | "rolled_back";
169}) {
170 return Effect.gen(function* () {
171 const eventSink = yield* EventSink.EventSinkV2;
172 const now = yield* DateTime.now;
173 const providerThreadId = ProviderThreadId.make(`${input.threadId}:provider`);
174 const message = (role: "user" | "assistant", text: string) => ({
175 id: EventId.make(`${input.runId}:${role}`),
176 type: "message.updated" as const,
177 threadId: input.threadId,
178 runId: input.runId,
179 occurredAt: now,
180 payload: {
181 id: MessageId.make(`${input.runId}:${role}`),
182 threadId: input.threadId,
183 runId: input.runId,
184 nodeId: null,
185 role,
186 text,
187 attachments: [],
188 streaming: false,
189 createdBy: "user" as const,
190 creationSource: "web" as const,
191 createdAt: now,
192 updatedAt: now,
193 },
194 });
195 yield* eventSink.write({
196 events: [
197 {
198 id: EventId.make(`${input.runId}:created`),
199 type: "run.created",
200 threadId: input.threadId,
201 runId: input.runId,
202 occurredAt: now,
203 payload: {
204 id: input.runId,
205 threadId: input.threadId,
206 ordinal: input.ordinal,
207 providerInstanceId: modelSelection.instanceId,
208 modelSelection,
209 providerThreadId,
210 userMessageId: MessageId.make(`${input.runId}:user`),
211 rootNodeId: null,
212 activeAttemptId: null,
213 status: input.status ?? "completed",
214 requestedAt: now,
215 startedAt: now,
216 completedAt: now,
217 checkpointId: null,
218 contextHandoffId: null,
219 },
220 },
221 {
222 id: EventId.make(`${input.runId}:provider-thread`),
223 type: "provider-thread.updated",
224 threadId: input.threadId,
225 occurredAt: now,
226 payload: {
227 id: providerThreadId,
228 driver: adapter.driver,
229 providerInstanceId: modelSelection.instanceId,
230 providerSessionId: null,
231 appThreadId: input.threadId,
232 ownerNodeId: null,
233 nativeThreadRef: { driver: adapter.driver, nativeId: "native", strength: "strong" },
234 nativeConversationHeadRef: null,
235 status: "idle",
236 firstRunOrdinal: 1,
237 lastRunOrdinal: input.ordinal,
238 handoffIds: [],
239 forkedFrom: null,
240 createdAt: now,
241 updatedAt: now,
242 },
243 },
244 message("user", input.user),
245 message("assistant", input.assistant),
246 ],
247 });
248 });
250​
251function armRegeneration(input: { readonly command: string; readonly threadId: ThreadId }) {
252 return Effect.gen(function* () {
253 const threads = yield* ThreadManagement.ThreadManagementService;
254 const requestId = CommandId.make(input.command);
255 yield* threads.dispatch({
256 type: "thread.metadata.update",
257 commandId: requestId,
258 threadId: input.threadId,
259 regenerateTitle: true,
260 });
261 return requestId;
262 });
264​
265describe("formatThreadTitleContext", () => {
266 it("pins the first user message ahead of the retained tail once content stops fitting", () => {
267 const context = ThreadTitleRegeneration.formatThreadTitleContext([
268 { role: "user", text: `Ancient context that anchors the topic ${"x".repeat(600)}` },
269 { role: "assistant", text: "y".repeat(6_000) },
270 { role: "user", text: "z".repeat(1_500) },
271 ]);
272 assert.isTrue(context.message.includes("USER:\nAncient context that anchors the topic"));
273 assert.isTrue(context.message.includes("[Earlier content truncated]\n\n"));
274 assert.isTrue(context.message.includes("y".repeat(100)));
275 });
276});
277​
278describe("ThreadTitleRegenerationService", () => {
279 it.effect(
280 "titles an image-only first message without sending bootstrap text to the title model",
281 () =>
282 Effect.gen(function* () {
283 for (const prefix of ["", "Ultrathink:\n"]) {
284 const harness = makeHarness();
285 yield* Effect.gen(function* () {
286 const threads = yield* ThreadManagement.ThreadManagementService;
287 const service = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
288 const threadId = yield* createThread({
289 command: "image:create",
290 thread: "image:thread",
291 });
292 const text = prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT;
293 const attachments = [
294 {
295 type: "image" as const,
296 id: ChatAttachmentId.make("diagram"),
297 name: "diagram.png",
298 mimeType: "image/png",
299 sizeBytes: 10,
300 },
301 ];
302 yield* dispatchUserMessage({ command: "image:message", threadId, text, attachments });
303 const requestId = yield* armRegeneration({ command: "image:title", threadId });
304 const messageId = MessageId.make("image:message:message");
305 yield* service.execute({ threadId, requestId, kind: { type: "initial", messageId } });
306 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
307 assert.equal(call?.message, "");
308 assert.deepEqual(call?.attachments, attachments);
309 const projection = yield* threads.getThreadProjection(threadId);
310 assert.equal(projection.messages[0]?.text, text);
311 assert.equal(projection.thread.title, "Generated title");
312 }).pipe(Effect.provide(harness.layer));
313 }
314 }),
315 );
316​
317 it.effect("arms and clears the regeneration marker through metadata commands", () =>
318 Effect.gen(function* () {
319 const harness = makeHarness();
320 yield* Effect.gen(function* () {
321 const threads = yield* ThreadManagement.ThreadManagementService;
322 const outbox = yield* EffectOutbox.EffectOutboxV2;
323 const threadId = yield* createThread({
324 command: "command:title:arm:create",
325 thread: "thread:title:arm",
326 });
327​
328 const firstRequest = yield* armRegeneration({ command: "command:title:arm:1", threadId });
329 const armed = yield* threads.getThreadProjection(threadId);
330 assert.equal(armed.thread.titleRegeneration?.requestId, firstRequest);
331 assert.deepEqual(
332 (yield* outbox.listByCommandId(firstRequest)).map((effect) => effect.request),
333 [{ type: "thread-title.generate", kind: { type: "regenerate" } }],
334 );
335​
336 yield* threads.dispatch({
337 type: "thread.metadata.update",
338 commandId: CommandId.make("command:title:arm:abandon"),
339 threadId,
340 regenerateTitle: false,
341 });
342 const abandoned = yield* threads.getThreadProjection(threadId);
343 assert.isNotOk(abandoned.thread.titleRegeneration);
344​
345 yield* armRegeneration({ command: "command:title:arm:2", threadId });
346 yield* threads.dispatch({
347 type: "thread.metadata.update",
348 commandId: CommandId.make("command:title:arm:rename"),
349 threadId,
350 title: "Manual title",
351 });
352 const renamed = yield* threads.getThreadProjection(threadId);
353 assert.equal(renamed.thread.title, "Manual title");
354 assert.isNotOk(renamed.thread.titleRegeneration);
355 }).pipe(Effect.provide(harness.layer));
356 }),
357 );
358​
359 it.effect("skips execution when the marker was superseded by a newer request", () =>
360 Effect.gen(function* () {
361 const harness = makeHarness();
362 yield* Effect.gen(function* () {
363 const threads = yield* ThreadManagement.ThreadManagementService;
364 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
365 const threadId = yield* createThread({
366 command: "command:title:stale:create",
367 thread: "thread:title:stale",
368 });
369 const staleRequest = yield* armRegeneration({ command: "command:title:stale:1", threadId });
370 const currentRequest = yield* armRegeneration({
371 command: "command:title:stale:2",
372 threadId,
373 });
374​
375 yield* titleRegeneration.execute({
376 threadId,
377 requestId: staleRequest,
378 kind: { type: "regenerate" },
379 });
380​
381 assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
382 const projection = yield* threads.getThreadProjection(threadId);
383 assert.equal(projection.thread.title, "Seed title");
384 assert.equal(projection.thread.titleRegeneration?.requestId, currentRequest);
385 }).pipe(Effect.provide(harness.layer));
386 }),
387 );
388​
389 it.effect("lands the regenerated title from the conversation digest", () =>
390 Effect.gen(function* () {
391 const harness = makeHarness({
392 generateTitle: () => Effect.succeed({ title: "Fresh title" }),
393 });
394 yield* Effect.gen(function* () {
395 const threads = yield* ThreadManagement.ThreadManagementService;
396 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
397 const threadId = yield* createThread({
398 command: "command:title:landing:create",
399 thread: "thread:title:landing",
400 });
401 yield* dispatchUserMessage({
402 command: "command:title:landing:message",
403 threadId,
404 text: "Investigate the flaky login test",
405 });
406 const requestId = yield* armRegeneration({ command: "command:title:landing:1", threadId });
407​
408 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
409​
410 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
411 assert.equal(call?.previousTitle, "Seed title");
412 assert.equal(call?.cwd, "/repo");
413 assert.include(call?.message, "USER:\nInvestigate the flaky login test");
414 const projection = yield* threads.getThreadProjection(threadId);
415 assert.equal(projection.thread.title, "Fresh title");
416 assert.isNotOk(projection.thread.titleRegeneration);
417 }).pipe(Effect.provide(harness.layer));
418 }),
419 );
420​
421 it.effect("titles a fork's first message with the source history up to the fork point", () =>
422 Effect.gen(function* () {
423 const harness = makeHarness();
424 yield* Effect.gen(function* () {
425 const threads = yield* ThreadManagement.ThreadManagementService;
426 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
427 const sourceThreadId = yield* createThread({
428 command: "command:title:fork:create",
429 thread: "thread:title:fork:source",
430 });
431 yield* recordRun({
432 threadId: sourceThreadId,
433 runId: RunId.make("run:title:fork:0"),
434 ordinal: 1,
435 user: "Rolled back attempt",
436 assistant: "Discarded.",
437 status: "rolled_back",
438 });
439 const forkRunId = RunId.make("run:title:fork:1");
440 yield* recordRun({
441 threadId: sourceThreadId,
442 runId: forkRunId,
443 ordinal: 2,
444 user: "Move session storage from Redis to Postgres",
445 assistant: "Sessions now persist in the Postgres sessions table.",
446 });
447 yield* recordRun({
448 threadId: sourceThreadId,
449 runId: RunId.make("run:title:fork:2"),
450 ordinal: 3,
451 user: "Later work the fork never saw",
452 assistant: "Done.",
453 });
454 const forkThreadId = ThreadId.make("thread:title:fork:target");
455 yield* threads.dispatch({
456 type: "thread.fork",
457 commandId: CommandId.make("command:title:fork:fork"),
458 sourceThreadId,
459 targetThreadId: forkThreadId,
460 sourcePoint: { type: "run", runId: forkRunId },
461 createdBy: "user",
462 creationSource: "web",
463 });
464 const requestId = CommandId.make("command:title:fork:message");
465 const messageId = MessageId.make("command:title:fork:message:message");
466 yield* threads.dispatch({
467 type: "message.dispatch",
468 commandId: requestId,
469 threadId: forkThreadId,
470 messageId,
471 text: "Try SQLite instead",
472 titleSeed: "Try SQLite instead",
473 attachments: [],
474 modelSelection,
475 dispatchMode: { type: "defer_start" },
476 createdBy: "user",
477 creationSource: "web",
478 });
479​
480 yield* titleRegeneration.execute({
481 threadId: forkThreadId,
482 requestId,
483 kind: { type: "initial", messageId },
484 });
485​
486 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
487 assert.equal(call?.message, "Try SQLite instead");
488 assert.equal(call?.forkSource?.title, "Seed title");
489 assert.include(call?.forkSource?.history, "Move session storage from Redis to Postgres");
490 assert.include(call?.forkSource?.history, "Sessions now persist in the Postgres");
491 assert.notInclude(call?.forkSource?.history, "Later work the fork never saw");
492 assert.notInclude(call?.forkSource?.history, "Rolled back attempt");
493 const fork = yield* threads.getThreadProjection(forkThreadId);
494 assert.equal(fork.thread.title, "Generated title");
495 }).pipe(Effect.provide(harness.layer));
496 }),
497 );
498​
499 it.effect("clears the marker and keeps the title when generation fails", () =>
500 Effect.gen(function* () {
501 const harness = makeHarness({
502 generateTitle: () => Effect.die(new Error("model unavailable")),
503 });
504 yield* Effect.gen(function* () {
505 const threads = yield* ThreadManagement.ThreadManagementService;
506 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
507 const threadId = yield* createThread({
508 command: "command:title:failure:create",
509 thread: "thread:title:failure",
510 });
511 yield* dispatchUserMessage({
512 command: "command:title:failure:message",
513 threadId,
514 text: "Some conversation",
515 });
516 const requestId = yield* armRegeneration({ command: "command:title:failure:1", threadId });
517​
518 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
519​
520 assert.equal(harness.generateThreadTitle.mock.calls.length, 1);
521 const projection = yield* threads.getThreadProjection(threadId);
522 assert.equal(projection.thread.title, "Seed title");
523 assert.isNotOk(projection.thread.titleRegeneration);
524 }).pipe(Effect.provide(harness.layer));
525 }),
526 );
527});