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 Fiber from "effect/Fiber";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as TestClock from "effect/testing/TestClock";
24import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
25
26import * as SqlitePersistence from "../persistence/Sqlite.ts";
27import * as ProjectStore from "./ProjectStore.ts";
28import * as ServerSettings from "../serverSettings.ts";
29import * as TextGeneration from "../textGeneration/TextGeneration.ts";
30import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
31import * as CommandReceiptStore from "./CommandReceiptStore.ts";
32import * as EffectOutbox from "./EffectOutbox.ts";
33import * as EventSink from "./EventSink.ts";
34import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
35import * as ThreadManagement from "./ThreadManagementService.ts";
36import * as ThreadTitleRegeneration from "./ThreadTitleRegenerationService.ts";
37import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
38import { placeholderThreadTitle } from "./placeholderThreadTitle.ts";
39import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
40
41const projectId = ProjectId.make("project:title-regeneration");
42const modelSelection = {
43 instanceId: ProviderInstanceId.make("codex"),
44 model: "gpt-5.1-codex",
45} as const;
46
47const adapter = {
48 instanceId: modelSelection.instanceId,
49 driver: ProviderDriverKind.make("codex"),
50 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
51 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
52 openSession: () => Effect.die("provider execution is disabled in title regeneration tests"),
53} as ProviderAdapter.ProviderAdapterV2["Service"];
54
55function makeHarness(
56 options: {
57 readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"];
58 } = {},
59) {
60 const layerDatabase = SqlitePersistence.layerMemory;
61 const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([adapter]);
62 const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
63 { name: "thread-title-regeneration" },
64 layerRegistry,
65 { databaseLayer: layerDatabase, runEffectWorker: false },
66 );
67 const layerServerSettings = ServerSettings.layerTest({});
68 const layerThreadManagement = ThreadManagement.layer.pipe(
69 Layer.provide(layerOrchestrator),
70 Layer.provide(layerServerSettings),
71 Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
72 );
73 const layerOutbox = EffectOutbox.layer.pipe(Layer.provide(layerDatabase));
74 const generateThreadTitle = vi.fn(
75 options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })),
76 );
77 const layerProjectedProjects = Layer.mock(ProjectStore.ProjectStoreV2)({
78 get: (requestedProjectId) =>
79 Effect.succeed(
80 requestedProjectId === projectId
81 ? Option.some({
82 projectId,
83 title: "Project",
84 workspaceRoot: "/repo",
85 defaultModelSelection: modelSelection,
86 defaultThreadEnvMode: null,
87 hasCustomTitle: false,
88 autoPull: false,
89 faviconPath: null,
90 projectIcon: null,
91 scripts: [],
92 trackedFolders: [],
93 pinnedAt: null,
94 archivedAt: null,
95 createdAt: "2026-06-20T00:00:00.000Z",
96 updatedAt: "2026-06-20T00:00:00.000Z",
97 deletedAt: null,
98 })
99 : Option.none(),
100 ),
101 });
102 const layerTitleRegeneration = ThreadTitleRegeneration.layer.pipe(
103 Layer.provide(
104 Layer.mergeAll(
105 layerThreadManagement,
106 layerProjectedProjects,
107 Layer.mock(TextGeneration.TextGeneration)({ generateThreadTitle }),
108 layerServerSettings,
109 NodeServices.layer,
110 ),
111 ),
112 );
113 return {
114 layer: Layer.mergeAll(
115 layerOrchestrator,
116 layerThreadManagement,
117 layerTitleRegeneration,
118 layerOutbox,
119 layerDatabase,
120 ),
121 generateThreadTitle,
122 };
123}
124
125function createThread(input: {
126 readonly command: string;
127 readonly thread: string;
128 readonly worktreePath?: string;
129}) {
130 return Effect.gen(function* () {
131 const threads = yield* ThreadManagement.ThreadManagementService;
132 const threadId = ThreadId.make(input.thread);
133 yield* threads.dispatch({
134 type: "thread.create",
135 commandId: CommandId.make(input.command),
136 threadId,
137 projectId,
138 title: "Seed title",
139 modelSelection,
140 runtimeMode: "full-access",
141 interactionMode: "default",
142 branch: null,
143 worktreePath: input.worktreePath ?? null,
144 createdBy: "user",
145 creationSource: "web",
146 });
147 return threadId;
148 });
149}
150
151function dispatchUserMessage(input: {
152 readonly command: string;
153 readonly threadId: ThreadId;
154 readonly text: string;
155 readonly attachments?: ReadonlyArray<ChatAttachment>;
156}) {
157 return Effect.gen(function* () {
158 const threads = yield* ThreadManagement.ThreadManagementService;
159 yield* threads.dispatch({
160 type: "message.dispatch",
161 commandId: CommandId.make(input.command),
162 threadId: input.threadId,
163 messageId: MessageId.make(`${input.command}:message`),
164 text: input.text,
165 attachments: input.attachments ?? [],
166 modelSelection,
167 dispatchMode: { type: "defer_start" },
168 createdBy: "user",
169 creationSource: "web",
170 });
171 });
172}
173
174/** Records a settled source run with one exchange, as a provider turn would. */
175function recordRun(input: {
176 readonly threadId: ThreadId;
177 readonly runId: RunId;
178 readonly ordinal: number;
179 readonly user: string;
180 readonly assistant: string;
181 readonly status?: "completed" | "rolled_back";
182}) {
183 return Effect.gen(function* () {
184 const eventSink = yield* EventSink.EventSinkV2;
185 const now = yield* DateTime.now;
186 const providerThreadId = ProviderThreadId.make(`${input.threadId}:provider`);
187 const message = (role: "user" | "assistant", text: string) => ({
188 id: EventId.make(`${input.runId}:${role}`),
189 type: "message.updated" as const,
190 threadId: input.threadId,
191 runId: input.runId,
192 occurredAt: now,
193 payload: {
194 id: MessageId.make(`${input.runId}:${role}`),
195 threadId: input.threadId,
196 runId: input.runId,
197 nodeId: null,
198 role,
199 text,
200 attachments: [],
201 streaming: false,
202 createdBy: "user" as const,
203 creationSource: "web" as const,
204 createdAt: now,
205 updatedAt: now,
206 },
207 });
208 yield* eventSink.write({
209 events: [
210 {
211 id: EventId.make(`${input.runId}:created`),
212 type: "run.created",
213 threadId: input.threadId,
214 runId: input.runId,
215 occurredAt: now,
216 payload: {
217 id: input.runId,
218 threadId: input.threadId,
219 ordinal: input.ordinal,
220 providerInstanceId: modelSelection.instanceId,
221 modelSelection,
222 providerThreadId,
223 userMessageId: MessageId.make(`${input.runId}:user`),
224 rootNodeId: null,
225 activeAttemptId: null,
226 status: input.status ?? "completed",
227 requestedAt: now,
228 startedAt: now,
229 completedAt: now,
230 checkpointId: null,
231 contextHandoffId: null,
232 },
233 },
234 {
235 id: EventId.make(`${input.runId}:provider-thread`),
236 type: "provider-thread.updated",
237 threadId: input.threadId,
238 occurredAt: now,
239 payload: {
240 id: providerThreadId,
241 driver: adapter.driver,
242 providerInstanceId: modelSelection.instanceId,
243 providerSessionId: null,
244 appThreadId: input.threadId,
245 ownerNodeId: null,
246 nativeThreadRef: { driver: adapter.driver, nativeId: "native", strength: "strong" },
247 nativeConversationHeadRef: null,
248 status: "idle",
249 firstRunOrdinal: 1,
250 lastRunOrdinal: input.ordinal,
251 handoffIds: [],
252 forkedFrom: null,
253 createdAt: now,
254 updatedAt: now,
255 },
256 },
257 message("user", input.user),
258 message("assistant", input.assistant),
259 ],
260 });
261 });
262}
263
264function armRegeneration(input: { readonly command: string; readonly threadId: ThreadId }) {
265 return Effect.gen(function* () {
266 const threads = yield* ThreadManagement.ThreadManagementService;
267 const requestId = CommandId.make(input.command);
268 yield* threads.dispatch({
269 type: "thread.metadata.update",
270 commandId: requestId,
271 threadId: input.threadId,
272 regenerateTitle: true,
273 });
274 return requestId;
275 });
276}
277
278/** Forks a source thread at its middle run, between a rolled-back run and later work. */
279function forkSeededSource(prefix: string, sideChat = false, rollbackPriorRun = true) {
280 return Effect.gen(function* () {
281 const threads = yield* ThreadManagement.ThreadManagementService;
282 const sourceThreadId = yield* createThread({
283 command: `${prefix}:create`,
284 thread: `${prefix}:source`,
285 });
286 yield* recordRun({
287 threadId: sourceThreadId,
288 runId: RunId.make(`${prefix}:run:0`),
289 ordinal: 1,
290 user: "Rolled back attempt",
291 assistant: "Discarded.",
292 status: rollbackPriorRun ? "rolled_back" : "completed",
293 });
294 yield* TestClock.adjust(1);
295 const forkRunId = RunId.make(`${prefix}:run:1`);
296 yield* recordRun({
297 threadId: sourceThreadId,
298 runId: forkRunId,
299 ordinal: 2,
300 user: "Move session storage from Redis to Postgres",
301 assistant: "Sessions now persist in the Postgres sessions table.",
302 });
303 yield* recordRun({
304 threadId: sourceThreadId,
305 runId: RunId.make(`${prefix}:run:2`),
306 ordinal: 3,
307 user: "Later work the fork never saw",
308 assistant: "Done.",
309 });
310 const forkThreadId = ThreadId.make(`${prefix}:target`);
311 yield* threads.dispatch({
312 type: "thread.fork",
313 commandId: CommandId.make(`${prefix}:fork`),
314 sourceThreadId,
315 targetThreadId: forkThreadId,
316 sourcePoint: { type: "run", runId: forkRunId },
317 sideChat,
318 createdBy: "user",
319 creationSource: "web",
320 });
321 return { sourceThreadId, forkRunId, forkThreadId };
322 });
323}
324
325describe("formatThreadTitleContext", () => {
326 it("pins the first user message ahead of the retained tail once content stops fitting", () => {
327 const context = ThreadTitleRegeneration.formatThreadTitleContext([
328 { role: "user", text: `Ancient context that anchors the topic ${"x".repeat(600)}` },
329 { role: "assistant", text: "y".repeat(6_000) },
330 { role: "user", text: "z".repeat(1_500) },
331 ]);
332 assert.isTrue(context.message.includes("USER:\nAncient context that anchors the topic"));
333 assert.isTrue(context.message.includes("[Earlier content truncated]\n\n"));
334 assert.isTrue(context.message.includes("y".repeat(100)));
335 });
336});
337
338describe("ThreadTitleRegenerationService", () => {
339 it.effect("keeps a title set before the first message unless it is a placeholder", () =>
340 Effect.gen(function* () {
341 const seed = "work on this and pr to dev";
342 const harness = makeHarness();
343 yield* Effect.gen(function* () {
344 const threads = yield* ThreadManagement.ThreadManagementService;
345 const outbox = yield* EffectOutbox.EffectOutboxV2;
346 // An MCP launch names the thread, or leaves a placeholder, and sends no message.
347 for (const [key, title, titleRenamed, compactFirst, expectedTitle, generates] of [
348 [
349 "preset",
350 "[API] #4821 - retry webhook deliveries after a timeout",
351 false,
352 false,
353 undefined,
354 false,
355 ],
356 ["placeholder", placeholderThreadTitle("Parent", 0), false, false, seed, true],
357 ["named like a placeholder", "Release thread 2", true, false, undefined, false],
358 ["named, then compacted", "Release notes", true, true, undefined, false],
359 ["draft titled by its /compact", "/compact", false, true, seed, true],
360 ] as const) {
361 const threadId = ThreadId.make(`thread:title:${key}`);
362 yield* threads.dispatch({
363 type: "thread.create",
364 commandId: CommandId.make(`command:title:${key}:create`),
365 threadId,
366 projectId,
367 title,
368 ...(titleRenamed ? { titleRenamed } : {}),
369 modelSelection,
370 runtimeMode: "full-access",
371 interactionMode: "default",
372 branch: null,
373 worktreePath: null,
374 createdBy: "agent",
375 creationSource: "mcp",
376 });
377 if (compactFirst) {
378 yield* threads.dispatch({
379 type: "message.dispatch",
380 commandId: CommandId.make(`command:title:${key}:compact`),
381 threadId,
382 messageId: MessageId.make(`command:title:${key}:compact:message`),
383 text: "/compact",
384 titleSeed: "/compact",
385 attachments: [],
386 modelSelection,
387 dispatchMode: { type: "defer_start" },
388 createdBy: "user",
389 creationSource: "web",
390 });
391 }
392 const requestId = CommandId.make(`command:title:${key}:message`);
393 yield* threads.dispatch({
394 type: "message.dispatch",
395 commandId: requestId,
396 threadId,
397 messageId: MessageId.make(`command:title:${key}:message:message`),
398 text: seed,
399 titleSeed: seed,
400 attachments: [],
401 modelSelection,
402 dispatchMode: { type: "defer_start" },
403 createdBy: "user",
404 creationSource: "web",
405 });
406
407 const settled = yield* threads.getThreadProjection(threadId);
408 assert.equal(settled.thread.title, expectedTitle ?? title, key);
409 assert.equal(
410 (yield* outbox.listByCommandId(requestId)).some(
411 (effect) => effect.request.type === "thread-title.generate",
412 ),
413 generates,
414 key,
415 );
416 }
417 }).pipe(Effect.provide(harness.layer));
418 }),
419 );
420
421 it.effect("keeps a fork's own rename when its first message arrives", () =>
422 Effect.gen(function* () {
423 const seed = "Try SQLite instead";
424 const harness = makeHarness();
425 yield* Effect.gen(function* () {
426 const threads = yield* ThreadManagement.ThreadManagementService;
427 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
428 const outbox = yield* EffectOutbox.EffectOutboxV2;
429 const prefix = "thread:title:renamed-fork";
430 const { sourceThreadId, forkRunId, forkThreadId } = yield* forkSeededSource(prefix);
431 const rename = (key: string, threadId: ThreadId, title: string) =>
432 threads.dispatch({
433 type: "thread.metadata.update",
434 commandId: CommandId.make(`${prefix}:${key}:rename`),
435 threadId,
436 title,
437 });
438 const fork = (key: string) =>
439 Effect.gen(function* () {
440 const targetThreadId = ThreadId.make(`${prefix}:${key}`);
441 yield* threads.dispatch({
442 type: "thread.fork",
443 commandId: CommandId.make(`${prefix}:${key}:fork`),
444 sourceThreadId,
445 targetThreadId,
446 sourcePoint: { type: "run", runId: forkRunId },
447 createdBy: "user",
448 creationSource: "web",
449 });
450 return targetThreadId;
451 });
452 yield* rename("renamed", forkThreadId, "Storage migration notes");
453 yield* rename("source", sourceThreadId, "Renamed source");
454 const forkOfRenamedSource = yield* fork("fork-of-renamed-source");
455 const regenerated = yield* fork("regenerated");
456 yield* rename("regenerated", regenerated, "Scratch name");
457 yield* titleRegeneration.execute({
458 threadId: regenerated,
459 requestId: yield* armRegeneration({
460 command: `${prefix}:regenerated:regenerate`,
461 threadId: regenerated,
462 }),
463 kind: { type: "regenerate" },
464 });
465
466 for (const [key, threadId, expectedTitle, generates] of [
467 ["renamed", forkThreadId, "Storage migration notes", false],
468 ["fork of a renamed source", forkOfRenamedSource, seed, true],
469 ["renamed, then regenerated", regenerated, seed, true],
470 ] as const) {
471 const requestId = CommandId.make(`${prefix}:${key}:message`);
472 yield* threads.dispatch({
473 type: "message.dispatch",
474 commandId: requestId,
475 threadId,
476 messageId: MessageId.make(`${prefix}:${key}:message:message`),
477 text: seed,
478 titleSeed: seed,
479 attachments: [],
480 modelSelection,
481 dispatchMode: { type: "defer_start" },
482 createdBy: "user",
483 creationSource: "web",
484 });
485
486 const settled = yield* threads.getThreadProjection(threadId);
487 assert.equal(settled.thread.title, expectedTitle, key);
488 assert.equal(
489 (yield* outbox.listByCommandId(requestId)).some(
490 (effect) => effect.request.type === "thread-title.generate",
491 ),
492 generates,
493 key,
494 );
495 }
496 }).pipe(Effect.provide(harness.layer));
497 }),
498 );
499
500 it.effect(
501 "titles an image-only first message without sending bootstrap text to the title model",
502 () =>
503 Effect.gen(function* () {
504 for (const prefix of ["", "Ultrathink:\n"]) {
505 const harness = makeHarness();
506 yield* Effect.gen(function* () {
507 const threads = yield* ThreadManagement.ThreadManagementService;
508 const service = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
509 const threadId = yield* createThread({
510 command: "image:create",
511 thread: "image:thread",
512 });
513 const text = prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT;
514 const attachments = [
515 {
516 type: "image" as const,
517 id: ChatAttachmentId.make("diagram"),
518 name: "diagram.png",
519 mimeType: "image/png",
520 sizeBytes: 10,
521 },
522 ];
523 yield* dispatchUserMessage({ command: "image:message", threadId, text, attachments });
524 const requestId = yield* armRegeneration({ command: "image:title", threadId });
525 const messageId = MessageId.make("image:message:message");
526 yield* service.execute({ threadId, requestId, kind: { type: "initial", messageId } });
527 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
528 assert.equal(call?.message, "");
529 assert.deepEqual(call?.attachments, attachments);
530 const projection = yield* threads.getThreadProjection(threadId);
531 assert.equal(projection.messages[0]?.text, text);
532 assert.equal(projection.thread.title, "Generated title");
533 }).pipe(Effect.provide(harness.layer));
534 }
535 }),
536 );
537
538 it.effect("arms and clears the regeneration marker through metadata commands", () =>
539 Effect.gen(function* () {
540 const harness = makeHarness();
541 yield* Effect.gen(function* () {
542 const threads = yield* ThreadManagement.ThreadManagementService;
543 const outbox = yield* EffectOutbox.EffectOutboxV2;
544 const threadId = yield* createThread({
545 command: "command:title:arm:create",
546 thread: "thread:title:arm",
547 });
548
549 const firstRequest = yield* armRegeneration({ command: "command:title:arm:1", threadId });
550 const armed = yield* threads.getThreadProjection(threadId);
551 assert.equal(armed.thread.titleRegeneration?.requestId, firstRequest);
552 assert.deepEqual(
553 (yield* outbox.listByCommandId(firstRequest)).map((effect) => effect.request),
554 [{ type: "thread-title.generate", kind: { type: "regenerate" } }],
555 );
556
557 yield* threads.dispatch({
558 type: "thread.metadata.update",
559 commandId: CommandId.make("command:title:arm:abandon"),
560 threadId,
561 regenerateTitle: false,
562 });
563 const abandoned = yield* threads.getThreadProjection(threadId);
564 assert.isNotOk(abandoned.thread.titleRegeneration);
565
566 yield* armRegeneration({ command: "command:title:arm:2", threadId });
567 yield* threads.dispatch({
568 type: "thread.metadata.update",
569 commandId: CommandId.make("command:title:arm:rename"),
570 threadId,
571 title: "Manual title",
572 });
573 const renamed = yield* threads.getThreadProjection(threadId);
574 assert.equal(renamed.thread.title, "Manual title");
575 assert.isNotOk(renamed.thread.titleRegeneration);
576 }).pipe(Effect.provide(harness.layer));
577 }),
578 );
579
580 it.effect("skips execution when the marker was superseded by a newer request", () =>
581 Effect.gen(function* () {
582 const harness = makeHarness();
583 yield* Effect.gen(function* () {
584 const threads = yield* ThreadManagement.ThreadManagementService;
585 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
586 const threadId = yield* createThread({
587 command: "command:title:stale:create",
588 thread: "thread:title:stale",
589 });
590 const staleRequest = yield* armRegeneration({ command: "command:title:stale:1", threadId });
591 const currentRequest = yield* armRegeneration({
592 command: "command:title:stale:2",
593 threadId,
594 });
595
596 yield* titleRegeneration.execute({
597 threadId,
598 requestId: staleRequest,
599 kind: { type: "regenerate" },
600 });
601
602 assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
603 const projection = yield* threads.getThreadProjection(threadId);
604 assert.equal(projection.thread.title, "Seed title");
605 assert.equal(projection.thread.titleRegeneration?.requestId, currentRequest);
606 }).pipe(Effect.provide(harness.layer));
607 }),
608 );
609
610 it.effect("lands the regenerated title from the conversation digest", () =>
611 Effect.gen(function* () {
612 const harness = makeHarness({
613 generateTitle: () => Effect.succeed({ title: "Fresh title" }),
614 });
615 const fs = yield* FileSystem.FileSystem;
616 const existingWorktree = yield* fs.makeTempDirectoryScoped({ prefix: "title-worktree-" });
617 yield* Effect.gen(function* () {
618 const threads = yield* ThreadManagement.ThreadManagementService;
619 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
620 const cases = [
621 { name: "removed", worktreePath: "/repo-worktrees/removed-by-cleanup", cwd: "/repo" },
622 { name: "existing", worktreePath: existingWorktree, cwd: existingWorktree },
623 ];
624 for (const [index, testCase] of cases.entries()) {
625 const threadId = yield* createThread({
626 command: `command:title:landing:${testCase.name}:create`,
627 thread: `thread:title:landing:${testCase.name}`,
628 worktreePath: testCase.worktreePath,
629 });
630 yield* dispatchUserMessage({
631 command: `command:title:landing:${testCase.name}:message`,
632 threadId,
633 text: "Investigate the flaky login test",
634 });
635 const requestId = yield* armRegeneration({
636 command: `command:title:landing:${testCase.name}:1`,
637 threadId,
638 });
639
640 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
641
642 const call = harness.generateThreadTitle.mock.calls[index]?.[0];
643 assert.equal(call?.previousTitle, "Seed title");
644 assert.equal(call?.cwd, testCase.cwd);
645 assert.include(call?.message, "USER:\nInvestigate the flaky login test");
646 const projection = yield* threads.getThreadProjection(threadId);
647 assert.equal(projection.thread.title, "Fresh title");
648 assert.isNotOk(projection.thread.titleRegeneration);
649 assert.deepInclude(projection.thread.lastTitleRegeneration, {
650 requestId,
651 status: "renamed",
652 });
653 }
654 }).pipe(Effect.provide(harness.layer));
655 }).pipe(Effect.provide(NodeServices.layer)),
656 );
657
658 it.effect.each([
659 { name: "its first message", followUp: true },
660 { name: "no message of its own yet", followUp: false },
661 ])("titles a fork with $name from the source history up to the fork point", ({ followUp }) =>
662 Effect.gen(function* () {
663 const harness = makeHarness();
664 yield* Effect.gen(function* () {
665 const threads = yield* ThreadManagement.ThreadManagementService;
666 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
667 const { forkThreadId } = yield* forkSeededSource("thread:title:fork");
668 const requestId = CommandId.make("command:title:fork:request");
669 const messageId = MessageId.make("command:title:fork:request:message");
670 if (followUp) {
671 yield* threads.dispatch({
672 type: "message.dispatch",
673 commandId: requestId,
674 threadId: forkThreadId,
675 messageId,
676 text: "Try SQLite instead",
677 titleSeed: "Try SQLite instead",
678 attachments: [],
679 modelSelection,
680 dispatchMode: { type: "defer_start" },
681 createdBy: "user",
682 creationSource: "web",
683 });
684 } else {
685 yield* armRegeneration({ command: requestId, threadId: forkThreadId });
686 }
687
688 yield* titleRegeneration.execute({
689 threadId: forkThreadId,
690 requestId,
691 kind: followUp ? { type: "initial", messageId } : { type: "regenerate" },
692 });
693
694 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
695 assert.equal(call?.message, followUp ? "Try SQLite instead" : "");
696 assert.equal(call?.forkSource?.title, "Seed title");
697 assert.include(call?.forkSource?.history, "Move session storage from Redis to Postgres");
698 assert.include(call?.forkSource?.history, "Sessions now persist in the Postgres");
699 assert.notInclude(call?.forkSource?.history, "Later work the fork never saw");
700 assert.notInclude(call?.forkSource?.history, "Rolled back attempt");
701 const fork = yield* threads.getThreadRecords(forkThreadId, []);
702 assert.equal(fork.thread.title, "Generated title");
703 }).pipe(Effect.provide(harness.layer));
704 }),
705 );
706
707 it.effect.each(["plain", "deleted source"] as const)(
708 "refuses to title an empty thread with %s history",
709 (history) =>
710 Effect.gen(function* () {
711 const harness = makeHarness();
712 yield* Effect.gen(function* () {
713 const threads = yield* ThreadManagement.ThreadManagementService;
714 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
715 const { forkThreadId } = yield* forkSeededSource("thread:title:empty");
716 const { thread } = yield* threads.getThreadProjection(forkThreadId);
717 const eventSink = yield* EventSink.EventSinkV2;
718 yield* eventSink.write({
719 events: [
720 {
721 id: EventId.make("empty:lineage"),
722 type: "thread.metadata-updated",
723 threadId: forkThreadId,
724 occurredAt: yield* DateTime.now,
725 payload: {
726 ...thread,
727 forkedFrom:
728 history === "plain"
729 ? null
730 : {
731 type: "run",
732 threadId: ThreadId.make("absent"),
733 runId: RunId.make("absent"),
734 },
735 },
736 },
737 ],
738 });
739 const requestId = yield* armRegeneration({
740 command: "empty:request",
741 threadId: forkThreadId,
742 });
743 yield* titleRegeneration.execute({
744 threadId: forkThreadId,
745 requestId,
746 kind: { type: "regenerate" },
747 });
748 assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
749 const fork = yield* threads.getThreadRecords(forkThreadId, []);
750 assert.deepInclude(fork.thread.lastTitleRegeneration, {
751 requestId,
752 status: "failed",
753 message: "This thread has no messages to title yet.",
754 });
755 }).pipe(Effect.provide(harness.layer));
756 }),
757 );
758
759 it.effect("keeps the fork point when the source rolls it back after forking", () =>
760 Effect.gen(function* () {
761 const harness = makeHarness();
762 yield* Effect.gen(function* () {
763 const threads = yield* ThreadManagement.ThreadManagementService;
764 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
765 const { sourceThreadId, forkRunId, forkThreadId } = yield* forkSeededSource(
766 "thread:title:rollback",
767 false,
768 false,
769 );
770 yield* TestClock.adjust(1);
771 const source = yield* threads.getThreadRecords(sourceThreadId, ["runs"]);
772 const run = source.runs.find((run) => run.id === forkRunId);
773 assert.isDefined(run);
774 const now = yield* DateTime.now;
775 const eventSink = yield* EventSink.EventSinkV2;
776 yield* eventSink.write({
777 events: [
778 {
779 id: EventId.make("source:rollback"),
780 type: "run.updated",
781 threadId: sourceThreadId,
782 runId: run.id,
783 occurredAt: now,
784 payload: { ...run, status: "rolled_back", completedAt: now },
785 },
786 ],
787 });
788 const requestId = yield* armRegeneration({
789 command: "rollback:request",
790 threadId: forkThreadId,
791 });
792 yield* titleRegeneration.execute({
793 threadId: forkThreadId,
794 requestId,
795 kind: { type: "regenerate" },
796 });
797 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
798 assert.include(call?.forkSource?.history, "Move session storage from Redis to Postgres");
799 assert.include(call?.forkSource?.history, "Rolled back attempt");
800 assert.notInclude(call?.forkSource?.history, "Later work the fork never saw");
801 const fork = yield* threads.getThreadRecords(forkThreadId, []);
802 assert.equal(fork.thread.title, "Generated title");
803 }).pipe(Effect.provide(harness.layer));
804 }),
805 );
806
807 it.effect("does not inherit imported history when the fork point is missing", () =>
808 Effect.gen(function* () {
809 const harness = makeHarness();
810 yield* Effect.gen(function* () {
811 const threads = yield* ThreadManagement.ThreadManagementService;
812 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
813 const { sourceThreadId, forkThreadId } = yield* forkSeededSource("thread:title:invalid");
814 yield* dispatchUserMessage({
815 command: "imported:message",
816 threadId: sourceThreadId,
817 text: "Imported history",
818 });
819 const source = yield* threads.getThreadRecords(sourceThreadId, []);
820 const fork = yield* threads.getThreadRecords(forkThreadId, []);
821 const eventSink = yield* EventSink.EventSinkV2;
822 yield* eventSink.write({
823 events: [
824 {
825 id: EventId.make("source:imported"),
826 type: "thread.metadata-updated",
827 threadId: sourceThreadId,
828 occurredAt: yield* DateTime.now,
829 payload: { ...source.thread, historyOrigin: "v1_import" },
830 },
831 {
832 id: EventId.make("fork:missing-run"),
833 type: "thread.metadata-updated",
834 threadId: forkThreadId,
835 occurredAt: yield* DateTime.now,
836 payload: {
837 ...fork.thread,
838 forkedFrom: {
839 type: "run",
840 threadId: sourceThreadId,
841 runId: RunId.make("absent:run"),
842 },
843 },
844 },
845 ],
846 });
847 const requestId = yield* armRegeneration({
848 command: "invalid:request",
849 threadId: forkThreadId,
850 });
851 yield* titleRegeneration.execute({
852 threadId: forkThreadId,
853 requestId,
854 kind: { type: "regenerate" },
855 });
856 assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
857 const updated = yield* threads.getThreadRecords(forkThreadId, []);
858 assert.deepInclude(updated.thread.lastTitleRegeneration, {
859 requestId,
860 status: "failed",
861 message: "This thread has no messages to title yet.",
862 });
863 }).pipe(Effect.provide(harness.layer));
864 }),
865 );
866
867 it.effect("inherits a side chat's own exchange without its parent's history", () =>
868 Effect.gen(function* () {
869 const harness = makeHarness();
870 yield* Effect.gen(function* () {
871 const threads = yield* ThreadManagement.ThreadManagementService;
872 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
873 const { forkThreadId: sideChatId } = yield* forkSeededSource(
874 "thread:title:side-ancestor",
875 true,
876 );
877 const runId = RunId.make("side:run");
878 yield* recordRun({
879 threadId: sideChatId,
880 runId,
881 ordinal: 1,
882 user: "Side topic",
883 assistant: "Side answer",
884 });
885 const threadId = ThreadId.make("side:fork");
886 yield* threads.dispatch({
887 type: "thread.fork",
888 commandId: CommandId.make("side:fork"),
889 sourceThreadId: sideChatId,
890 targetThreadId: threadId,
891 sourcePoint: { type: "run", runId },
892 title: "Side fork",
893 createdBy: "user",
894 creationSource: "web",
895 });
896 const requestId = yield* armRegeneration({ command: "side:request", threadId });
897 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
898 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
899 assert.equal(call?.forkSource?.title, "Seed title fork");
900 assert.include(call?.forkSource?.history, "Side topic");
901 assert.include(call?.forkSource?.history, "Side answer");
902 assert.notInclude(call?.forkSource?.history, "Move session storage");
903 }).pipe(Effect.provide(harness.layer));
904 }),
905 );
906
907 it.effect("clears the marker and keeps the title when generation fails", () =>
908 Effect.gen(function* () {
909 const harness = makeHarness({
910 generateTitle: () =>
911 Effect.fail(
912 new TextGenerationError({
913 operation: "generateThreadTitle",
914 detail:
915 "Codex CLI command failed: OpenAI Codex\nuser\nConversation text\nmodel unavailable\n",
916 }),
917 ),
918 });
919 yield* Effect.gen(function* () {
920 const threads = yield* ThreadManagement.ThreadManagementService;
921 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
922 const threadId = yield* createThread({
923 command: "command:title:failure:create",
924 thread: "thread:title:failure",
925 });
926 yield* dispatchUserMessage({
927 command: "command:title:failure:message",
928 threadId,
929 text: "Some conversation",
930 });
931 const requestId = yield* armRegeneration({ command: "command:title:failure:1", threadId });
932
933 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
934
935 assert.equal(harness.generateThreadTitle.mock.calls.length, 1);
936 const projection = yield* threads.getThreadProjection(threadId);
937 assert.equal(projection.thread.title, "Seed title");
938 assert.isNotOk(projection.thread.titleRegeneration);
939 assert.deepInclude(projection.thread.lastTitleRegeneration, {
940 requestId,
941 status: "failed",
942 message: "model unavailable",
943 });
944 }).pipe(Effect.provide(harness.layer));
945 }),
946 );
947
948 it.effect("does not retry an initial title after the provider refuses with 403", () =>
949 Effect.gen(function* () {
950 const harness = makeHarness({
951 generateTitle: () =>
952 Effect.fail(
953 new TextGenerationError({
954 operation: "generateThreadTitle",
955 detail:
956 "Codex CLI command failed: OpenAI Codex\nERROR: Reconnecting... 5/5\nERROR: unexpected status 403 Forbidden: model: gpt-6-luna\n",
957 }),
958 ),
959 });
960 yield* Effect.gen(function* () {
961 const service = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
962 const threadId = yield* createThread({
963 command: "command:title:forbidden:create",
964 thread: "thread:title:forbidden",
965 });
966 yield* dispatchUserMessage({
967 command: "command:title:forbidden:message",
968 threadId,
969 text: "Fix the flaky login test",
970 });
971 const requestId = yield* armRegeneration({ command: "command:title:forbidden", threadId });
972 const messageId = MessageId.make("command:title:forbidden:message:message");
973
974 const fiber = yield* Effect.forkChild(
975 service.execute({ threadId, requestId, kind: { type: "initial", messageId } }),
976 );
977 yield* TestClock.adjust("1 minute");
978 yield* Fiber.join(fiber);
979
980 assert.equal(harness.generateThreadTitle.mock.calls.length, 1);
981 }).pipe(Effect.provide(harness.layer));
982 }),
983 );
984
985 it.effect("retries an initial title after a transient failure", () =>
986 Effect.gen(function* () {
987 const harness = makeHarness({
988 generateTitle: () =>
989 Effect.fail(
990 new TextGenerationError({
991 operation: "generateThreadTitle",
992 detail: "Codex CLI request timed out.",
993 }),
994 ),
995 });
996 yield* Effect.gen(function* () {
997 const service = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
998 const threadId = yield* createThread({
999 command: "command:title:timeout:create",
1000 thread: "thread:title:timeout",
1001 });
1002 yield* dispatchUserMessage({
1003 command: "command:title:timeout:message",
1004 threadId,
1005 text: "Fix the flaky login test",
1006 });
1007 const requestId = yield* armRegeneration({ command: "command:title:timeout", threadId });
1008 const messageId = MessageId.make("command:title:timeout:message:message");
1009
1010 const fiber = yield* Effect.forkChild(
1011 service.execute({ threadId, requestId, kind: { type: "initial", messageId } }),
1012 );
1013 yield* TestClock.adjust("1 minute");
1014 yield* Fiber.join(fiber);
1015
1016 assert.equal(harness.generateThreadTitle.mock.calls.length, 3);
1017 }).pipe(Effect.provide(harness.layer));
1018 }),
1019 );
1020
1021 it.effect("cuts a long failure message without splitting an emoji", () =>
1022 Effect.gen(function* () {
1023 const harness = makeHarness({
1024 generateTitle: () =>
1025 Effect.fail(
1026 new TextGenerationError({
1027 operation: "generateThreadTitle",
1028 detail: `${"a".repeat(298)}🚀 and the rest of the error`,
1029 }),
1030 ),
1031 });
1032 yield* Effect.gen(function* () {
1033 const threads = yield* ThreadManagement.ThreadManagementService;
1034 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
1035 const threadId = yield* createThread({
1036 command: "command:title:long-failure:create",
1037 thread: "thread:title:long-failure",
1038 });
1039 yield* dispatchUserMessage({
1040 command: "command:title:long-failure:message",
1041 threadId,
1042 text: "Some conversation",
1043 });
1044 const requestId = yield* armRegeneration({
1045 command: "command:title:long-failure:1",
1046 threadId,
1047 });
1048
1049 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
1050
1051 const projection = yield* threads.getThreadProjection(threadId);
1052 assert.equal(projection.thread.lastTitleRegeneration?.message, `${"a".repeat(298)}…`);
1053 }).pipe(Effect.provide(harness.layer));
1054 }),
1055 );
1056
1057 it.effect("records an unchanged outcome when the model keeps the current title", () =>
1058 Effect.gen(function* () {
1059 const harness = makeHarness({
1060 generateTitle: () => Effect.succeed({ title: "Seed title" }),
1061 });
1062 yield* Effect.gen(function* () {
1063 const threads = yield* ThreadManagement.ThreadManagementService;
1064 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
1065 const threadId = yield* createThread({
1066 command: "command:title:unchanged:create",
1067 thread: "thread:title:unchanged",
1068 });
1069 yield* dispatchUserMessage({
1070 command: "command:title:unchanged:message",
1071 threadId,
1072 text: "Some conversation",
1073 });
1074 const requestId = yield* armRegeneration({
1075 command: "command:title:unchanged:1",
1076 threadId,
1077 });
1078
1079 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
1080
1081 const projection = yield* threads.getThreadProjection(threadId);
1082 assert.deepInclude(projection.thread.lastTitleRegeneration, {
1083 requestId,
1084 status: "unchanged",
1085 });
1086 }).pipe(Effect.provide(harness.layer));
1087 }),
1088 );
1089});