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

ThreadTitleRegenerationService.test.ts

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