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

ThreadTitleRegenerationService.test.ts

506 lines19.5 KB

1import { assert, describe, it, vi } from "@effect/vitest";
2import {
3 type ChatAttachment,
4 CommandId,
5 MessageId,
6 ProjectId,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 ThreadId,
10 TextGenerationError,
11} from "@t3tools/contracts";
12import * as Effect from "effect/Effect";
13import * as Deferred from "effect/Deferred";
14import * as Fiber from "effect/Fiber";
15import * as TestClock from "effect/testing/TestClock";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18​
19import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
20import * as ProjectStore from "./ProjectStore.ts";
21import * as ServerSettings from "../serverSettings.ts";
22import * as TextGeneration from "../textGeneration/TextGeneration.ts";
23import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
24import * as EffectOutbox from "./EffectOutbox.ts";
25import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
26import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
27import * as ThreadManagement from "./ThreadManagementService.ts";
28import * as ThreadTitleRegeneration from "./ThreadTitleRegenerationService.ts";
29import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts";
30​
31const projectId = ProjectId.make("project:title-regeneration");
32const modelSelection = {
33 instanceId: ProviderInstanceId.make("codex"),
34 model: "gpt-5.1-codex",
35} as const;
36​
37const adapter = {
38 instanceId: modelSelection.instanceId,
39 driver: ProviderDriverKind.make("codex"),
40 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
41 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
42 openSession: () => Effect.die("provider execution is disabled in title regeneration tests"),
43} as ProviderAdapterV2Shape;
44​
45function makeHarness(
46 options: {
47 readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"];
48 } = {},
49) {
50 const database = SqlitePersistenceMemory;
51 const registry = ProviderAdapterRegistry.makeLayer([adapter]);
52 const orchestrator = makeOrchestratorV2ReplayLayerWithRegistry(
53 { name: "thread-title-regeneration" },
54 registry,
55 { databaseLayer: database, runEffectWorker: false },
56 );
57 const threadManagement = ThreadManagement.layer.pipe(Layer.provide(orchestrator));
58 const outbox = EffectOutbox.layer.pipe(Layer.provide(database));
59 const generateThreadTitle = vi.fn(
60 options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })),
61 );
62 const projectedProjects = Layer.mock(ProjectStore.ProjectStoreV2)({
63 get: (requestedProjectId) =>
64 Effect.succeed(
65 requestedProjectId === projectId
66 ? Option.some({
67 projectId,
68 title: "Project",
69 workspaceRoot: "/repo",
70 defaultModelSelection: modelSelection,
71 defaultThreadEnvMode: null,
72 autoPull: false,
73 faviconPath: null,
74 projectIcon: null,
75 scripts: [],
76 createdAt: "2026-06-20T00:00:00.000Z",
77 updatedAt: "2026-06-20T00:00:00.000Z",
78 deletedAt: null,
79 })
80 : Option.none(),
81 ),
82 });
83 const titleRegeneration = ThreadTitleRegeneration.layer.pipe(
84 Layer.provide(
85 Layer.mergeAll(
86 threadManagement,
87 projectedProjects,
88 Layer.mock(TextGeneration.TextGeneration)({ generateThreadTitle }),
89 ServerSettings.layerTest({}),
90 ),
91 ),
92 );
93 return {
94 layer: Layer.mergeAll(threadManagement, titleRegeneration, outbox, database),
95 generateThreadTitle,
96 };
98​
99function createThread(input: { readonly command: string; readonly thread: string }) {
100 return Effect.gen(function* () {
101 const threads = yield* ThreadManagement.ThreadManagementService;
102 const threadId = ThreadId.make(input.thread);
103 yield* threads.dispatch({
104 type: "thread.create",
105 commandId: CommandId.make(input.command),
106 threadId,
107 projectId,
108 title: "Seed title",
109 modelSelection,
110 runtimeMode: "full-access",
111 interactionMode: "default",
112 branch: null,
113 worktreePath: null,
114 createdBy: "user",
115 creationSource: "web",
116 });
117 return threadId;
118 });
120​
121function dispatchUserMessage(input: {
122 readonly command: string;
123 readonly threadId: ThreadId;
124 readonly text: string;
125}) {
126 return Effect.gen(function* () {
127 const threads = yield* ThreadManagement.ThreadManagementService;
128 yield* threads.dispatch({
129 type: "message.dispatch",
130 commandId: CommandId.make(input.command),
131 threadId: input.threadId,
132 messageId: MessageId.make(`${input.command}:message`),
133 text: input.text,
134 attachments: [],
135 modelSelection,
136 dispatchMode: { type: "defer_start" },
137 createdBy: "user",
138 creationSource: "web",
139 });
140 });
142​
143function armRegeneration(input: { readonly command: string; readonly threadId: ThreadId }) {
144 return Effect.gen(function* () {
145 const threads = yield* ThreadManagement.ThreadManagementService;
146 const requestId = CommandId.make(input.command);
147 yield* threads.dispatch({
148 type: "thread.metadata.update",
149 commandId: requestId,
150 threadId: input.threadId,
151 regenerateTitle: true,
152 });
153 return requestId;
154 });
156​
157describe("formatThreadTitleContext", () => {
158 const attachment = (id: string): ChatAttachment => ({
159 type: "image",
160 id,
161 name: `${id}.png`,
162 mimeType: "image/png",
163 sizeBytes: 1,
164 });
165​
166 it("builds a newest-first digest, skipping system messages and empty sections", () => {
167 const context = ThreadTitleRegeneration.formatThreadTitleContext([
168 { role: "user", text: "First question" },
169 { role: "system", text: "Hidden instructions" },
170 { role: "assistant", text: "" },
171 { role: "assistant", text: "Second answer", attachments: [attachment("shot")] },
172 ]);
173 assert.equal(
174 context.message,
175 "USER:\nFirst question\n\nASSISTANT:\nSecond answer\n[Attachments: shot.png]",
176 );
177 assert.deepEqual(
178 context.attachments.map((entry) => entry.name),
179 ["shot.png"],
180 );
181 });
182​
183 it("pins the first user message ahead of the retained tail once content stops fitting", () => {
184 const context = ThreadTitleRegeneration.formatThreadTitleContext([
185 { role: "user", text: `Ancient context that anchors the topic ${"x".repeat(600)}` },
186 { role: "assistant", text: "y".repeat(6_000) },
187 { role: "user", text: "z".repeat(1_500) },
188 ]);
189 assert.isTrue(context.message.includes("USER:\nAncient context that anchors the topic"));
190 assert.isTrue(context.message.includes("[Earlier content truncated]\n\n"));
191 assert.isTrue(context.message.includes("y".repeat(100)));
192 });
193​
194 it("truncates an oversized pinned first user message", () => {
195 const context = ThreadTitleRegeneration.formatThreadTitleContext([
196 { role: "user", text: `Topic anchor ${"a".repeat(4_000)}` },
197 { role: "assistant", text: "y".repeat(9_000) },
198 { role: "user", text: "z".repeat(1_500) },
199 ]);
200 assert.isTrue(context.message.includes("USER:\nTopic anchor"));
201 assert.isTrue(context.message.includes("[Content truncated]"));
202 assert.isTrue(context.message.includes("[Earlier content truncated]\n\n"));
203 });
204​
205 it("retains at most four attachments from the newest messages", () => {
206 const context = ThreadTitleRegeneration.formatThreadTitleContext([
207 { role: "user", text: "older", attachments: [attachment("a"), attachment("b")] },
208 {
209 role: "user",
210 text: "newer",
211 attachments: [attachment("c"), attachment("d"), attachment("e")],
212 },
213 ]);
214 assert.deepEqual(
215 context.attachments.map((entry) => entry.name),
216 ["a.png", "c.png", "d.png", "e.png"],
217 );
218 });
219});
220​
221describe("ThreadTitleRegenerationService", () => {
222 it.effect("arms and clears the regeneration marker through metadata commands", () =>
223 Effect.gen(function* () {
224 const harness = makeHarness();
225 yield* Effect.gen(function* () {
226 const threads = yield* ThreadManagement.ThreadManagementService;
227 const outbox = yield* EffectOutbox.EffectOutboxV2;
228 const threadId = yield* createThread({
229 command: "command:title:arm:create",
230 thread: "thread:title:arm",
231 });
232​
233 const firstRequest = yield* armRegeneration({ command: "command:title:arm:1", threadId });
234 const armed = yield* threads.getThreadProjection(threadId);
235 assert.equal(armed.thread.titleRegeneration?.requestId, firstRequest);
236 assert.deepEqual(
237 (yield* outbox.listByCommandId(firstRequest)).map((effect) => effect.request),
238 [{ type: "thread-title.generate", kind: { type: "regenerate" } }],
239 );
240​
241 yield* threads.dispatch({
242 type: "thread.metadata.update",
243 commandId: CommandId.make("command:title:arm:abandon"),
244 threadId,
245 regenerateTitle: false,
246 });
247 const abandoned = yield* threads.getThreadProjection(threadId);
248 assert.isNotOk(abandoned.thread.titleRegeneration);
249​
250 yield* armRegeneration({ command: "command:title:arm:2", threadId });
251 yield* threads.dispatch({
252 type: "thread.metadata.update",
253 commandId: CommandId.make("command:title:arm:rename"),
254 threadId,
255 title: "Manual title",
256 });
257 const renamed = yield* threads.getThreadProjection(threadId);
258 assert.equal(renamed.thread.title, "Manual title");
259 assert.isNotOk(renamed.thread.titleRegeneration);
260 }).pipe(Effect.provide(harness.layer));
261 }),
262 );
263​
264 it.effect("skips execution when the marker was superseded by a newer request", () =>
265 Effect.gen(function* () {
266 const harness = makeHarness();
267 yield* Effect.gen(function* () {
268 const threads = yield* ThreadManagement.ThreadManagementService;
269 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
270 const threadId = yield* createThread({
271 command: "command:title:stale:create",
272 thread: "thread:title:stale",
273 });
274 const staleRequest = yield* armRegeneration({ command: "command:title:stale:1", threadId });
275 const currentRequest = yield* armRegeneration({
276 command: "command:title:stale:2",
277 threadId,
278 });
279​
280 yield* titleRegeneration.execute({
281 threadId,
282 requestId: staleRequest,
283 kind: { type: "regenerate" },
284 });
285​
286 assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
287 const projection = yield* threads.getThreadProjection(threadId);
288 assert.equal(projection.thread.title, "Seed title");
289 assert.equal(projection.thread.titleRegeneration?.requestId, currentRequest);
290 }).pipe(Effect.provide(harness.layer));
291 }),
292 );
293​
294 it.effect("lands the regenerated title from the conversation digest", () =>
295 Effect.gen(function* () {
296 const harness = makeHarness({
297 generateTitle: () => Effect.succeed({ title: "Fresh title" }),
298 });
299 yield* Effect.gen(function* () {
300 const threads = yield* ThreadManagement.ThreadManagementService;
301 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
302 const threadId = yield* createThread({
303 command: "command:title:landing:create",
304 thread: "thread:title:landing",
305 });
306 yield* dispatchUserMessage({
307 command: "command:title:landing:message",
308 threadId,
309 text: "Investigate the flaky login test",
310 });
311 const requestId = yield* armRegeneration({ command: "command:title:landing:1", threadId });
312​
313 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
314​
315 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
316 assert.equal(call?.previousTitle, "Seed title");
317 assert.equal(call?.cwd, "/repo");
318 assert.include(call?.message, "USER:\nInvestigate the flaky login test");
319 const projection = yield* threads.getThreadProjection(threadId);
320 assert.equal(projection.thread.title, "Fresh title");
321 assert.isNotOk(projection.thread.titleRegeneration);
322 }).pipe(Effect.provide(harness.layer));
323 }),
324 );
325​
326 it.effect("keeps the current title when generation returns the fallback", () =>
327 Effect.gen(function* () {
328 const harness = makeHarness({
329 generateTitle: () => Effect.succeed({ title: "New thread" }),
330 });
331 yield* Effect.gen(function* () {
332 const threads = yield* ThreadManagement.ThreadManagementService;
333 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
334 const threadId = yield* createThread({
335 command: "command:title:fallback:create",
336 thread: "thread:title:fallback",
337 });
338 yield* dispatchUserMessage({
339 command: "command:title:fallback:message",
340 threadId,
341 text: "Some conversation",
342 });
343 const requestId = yield* armRegeneration({ command: "command:title:fallback:1", threadId });
344​
345 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
346​
347 const projection = yield* threads.getThreadProjection(threadId);
348 assert.equal(projection.thread.title, "Seed title");
349 assert.isNotOk(projection.thread.titleRegeneration);
350 }).pipe(Effect.provide(harness.layer));
351 }),
352 );
353​
354 it.effect("keeps the current title when regeneration reproduces it", () =>
355 Effect.gen(function* () {
356 const harness = makeHarness({
357 generateTitle: () => Effect.succeed({ title: "Seed title" }),
358 });
359 yield* Effect.gen(function* () {
360 const threads = yield* ThreadManagement.ThreadManagementService;
361 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
362 const threadId = yield* createThread({
363 command: "command:title:unchanged:create",
364 thread: "thread:title:unchanged",
365 });
366 yield* dispatchUserMessage({
367 command: "command:title:unchanged:message",
368 threadId,
369 text: "Some conversation",
370 });
371 const requestId = yield* armRegeneration({
372 command: "command:title:unchanged:1",
373 threadId,
374 });
375​
376 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
377​
378 const projection = yield* threads.getThreadProjection(threadId);
379 assert.equal(projection.thread.title, "Seed title");
380 assert.isNotOk(projection.thread.titleRegeneration);
381 }).pipe(Effect.provide(harness.layer));
382 }),
383 );
384​
385 it.effect("clears the marker and keeps the title when generation fails", () =>
386 Effect.gen(function* () {
387 const harness = makeHarness({
388 generateTitle: () => Effect.die(new Error("model unavailable")),
389 });
390 yield* Effect.gen(function* () {
391 const threads = yield* ThreadManagement.ThreadManagementService;
392 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
393 const threadId = yield* createThread({
394 command: "command:title:failure:create",
395 thread: "thread:title:failure",
396 });
397 yield* dispatchUserMessage({
398 command: "command:title:failure:message",
399 threadId,
400 text: "Some conversation",
401 });
402 const requestId = yield* armRegeneration({ command: "command:title:failure:1", threadId });
403​
404 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
405​
406 assert.equal(harness.generateThreadTitle.mock.calls.length, 1);
407 const projection = yield* threads.getThreadProjection(threadId);
408 assert.equal(projection.thread.title, "Seed title");
409 assert.isNotOk(projection.thread.titleRegeneration);
410 }).pipe(Effect.provide(harness.layer));
411 }),
412 );
413​
414 it.effect("completes without generating when the initial message is unavailable", () =>
415 Effect.gen(function* () {
416 const harness = makeHarness();
417 yield* Effect.gen(function* () {
418 const threads = yield* ThreadManagement.ThreadManagementService;
419 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
420 const threadId = yield* createThread({
421 command: "command:title:missing:create",
422 thread: "thread:title:missing",
423 });
424 const requestId = yield* armRegeneration({ command: "command:title:missing:1", threadId });
425​
426 yield* titleRegeneration.execute({
427 threadId,
428 requestId,
429 kind: { type: "initial", messageId: MessageId.make("message:title:missing") },
430 });
431​
432 assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
433 const projection = yield* threads.getThreadProjection(threadId);
434 assert.equal(projection.thread.title, "Seed title");
435 assert.isNotOk(projection.thread.titleRegeneration);
436 }).pipe(Effect.provide(harness.layer));
437 }),
438 );
439});
440​
441it.effect.each(["success", "exhausted", "stale", "interrupted"] as const)(
442 "initial title retry: %s",
443 (outcome) =>
444 Effect.gen(function* () {
445 const attempted = yield* Deferred.make<void>();
446 let attempts = 0;
447 const harness = makeHarness({
448 generateTitle: () =>
449 Effect.gen(function* () {
450 attempts += 1;
451 yield* Deferred.succeed(attempted, undefined);
452 if (outcome === "success" && attempts === 3) return { title: "Recovered title" };
453 return yield* new TextGenerationError({
454 operation: "generateThreadTitle",
455 detail: "Temporary failure",
456 });
457 }),
458 });
459 yield* Effect.gen(function* () {
460 const threads = yield* ThreadManagement.ThreadManagementService;
461 const service = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
462 const threadId = yield* createThread({
463 command: `create:${outcome}`,
464 thread: `thread:${outcome}`,
465 });
466 const messageCommand = `message:${outcome}`;
467 yield* dispatchUserMessage({ command: messageCommand, threadId, text: "Fix the title" });
468 const requestId = yield* armRegeneration({ command: `title:${outcome}`, threadId });
469 const fiber = yield* service
470 .execute({
471 threadId,
472 requestId,
473 kind: { type: "initial", messageId: MessageId.make(`${messageCommand}:message`) },
474 })
475 .pipe(Effect.forkChild);
476 yield* Deferred.await(attempted);
477 if (outcome === "interrupted") {
478 yield* Fiber.interrupt(fiber);
479 } else {
480 if (outcome === "stale")
481 yield* threads.dispatch({
482 type: "thread.metadata.update",
483 commandId: CommandId.make("manual-title"),
484 threadId,
485 title: "Manual title",
486 });
487 yield* TestClock.adjust("2 seconds");
488 if (outcome !== "stale") yield* TestClock.adjust("4 seconds");
489 yield* Fiber.join(fiber);
490 }
491 assert.equal(attempts, outcome === "success" || outcome === "exhausted" ? 3 : 1);
492 const projection = yield* threads.getThreadProjection(threadId);
493 assert.equal(
494 projection.thread.title,
495 outcome === "success"
496 ? "Recovered title"
497 : outcome === "stale"
498 ? "Manual title"
499 : "Seed title",
500 );
501 if (outcome === "interrupted")
502 assert.equal(projection.thread.titleRegeneration?.requestId, requestId);
503 else assert.isNotOk(projection.thread.titleRegeneration);
504 }).pipe(Effect.provide(harness.layer));
505 }),
506);