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

ThreadTitleRegenerationService.test.ts

953 lines36.6 KB

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