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