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