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