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

ThreadTitleRegenerationService.test.ts

1,015 lines38.9 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, titleRenamed, compactFirst, expectedTitle, generates] of [
347 [
348 "preset",
349 "[API] #4821 - retry webhook deliveries after a timeout",
350 false,
351 false,
352 undefined,
353 false,
354 ],
355 ["placeholder", placeholderThreadTitle("Parent", 0), false, false, seed, true],
356 ["named like a placeholder", "Release thread 2", true, false, undefined, false],
357 ["named, then compacted", "Release notes", true, true, undefined, false],
358 ["draft titled by its /compact", "/compact", false, true, seed, true],
359 ] as const) {
360 const threadId = ThreadId.make(`thread:title:${key}`);
361 yield* threads.dispatch({
362 type: "thread.create",
363 commandId: CommandId.make(`command:title:${key}:create`),
364 threadId,
365 projectId,
366 title,
367 ...(titleRenamed ? { titleRenamed } : {}),
368 modelSelection,
369 runtimeMode: "full-access",
370 interactionMode: "default",
371 branch: null,
372 worktreePath: null,
373 createdBy: "agent",
374 creationSource: "mcp",
375 });
376 if (compactFirst) {
377 yield* threads.dispatch({
378 type: "message.dispatch",
379 commandId: CommandId.make(`command:title:${key}:compact`),
380 threadId,
381 messageId: MessageId.make(`command:title:${key}:compact:message`),
382 text: "/compact",
383 titleSeed: "/compact",
384 attachments: [],
385 modelSelection,
386 dispatchMode: { type: "defer_start" },
387 createdBy: "user",
388 creationSource: "web",
389 });
390 }
391 const requestId = CommandId.make(`command:title:${key}:message`);
392 yield* threads.dispatch({
393 type: "message.dispatch",
394 commandId: requestId,
395 threadId,
396 messageId: MessageId.make(`command:title:${key}:message:message`),
397 text: seed,
398 titleSeed: seed,
399 attachments: [],
400 modelSelection,
401 dispatchMode: { type: "defer_start" },
402 createdBy: "user",
403 creationSource: "web",
404 });
405​
406 const settled = yield* threads.getThreadProjection(threadId);
407 assert.equal(settled.thread.title, expectedTitle ?? title, key);
408 assert.equal(
409 (yield* outbox.listByCommandId(requestId)).some(
410 (effect) => effect.request.type === "thread-title.generate",
411 ),
412 generates,
413 key,
414 );
415 }
416 }).pipe(Effect.provide(harness.layer));
417 }),
418 );
419​
420 it.effect("keeps a fork's own rename when its first message arrives", () =>
421 Effect.gen(function* () {
422 const seed = "Try SQLite instead";
423 const harness = makeHarness();
424 yield* Effect.gen(function* () {
425 const threads = yield* ThreadManagement.ThreadManagementService;
426 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
427 const outbox = yield* EffectOutbox.EffectOutboxV2;
428 const prefix = "thread:title:renamed-fork";
429 const { sourceThreadId, forkRunId, forkThreadId } = yield* forkSeededSource(prefix);
430 const rename = (key: string, threadId: ThreadId, title: string) =>
431 threads.dispatch({
432 type: "thread.metadata.update",
433 commandId: CommandId.make(`${prefix}:${key}:rename`),
434 threadId,
435 title,
436 });
437 const fork = (key: string) =>
438 Effect.gen(function* () {
439 const targetThreadId = ThreadId.make(`${prefix}:${key}`);
440 yield* threads.dispatch({
441 type: "thread.fork",
442 commandId: CommandId.make(`${prefix}:${key}:fork`),
443 sourceThreadId,
444 targetThreadId,
445 sourcePoint: { type: "run", runId: forkRunId },
446 createdBy: "user",
447 creationSource: "web",
448 });
449 return targetThreadId;
450 });
451 yield* rename("renamed", forkThreadId, "Storage migration notes");
452 yield* rename("source", sourceThreadId, "Renamed source");
453 const forkOfRenamedSource = yield* fork("fork-of-renamed-source");
454 const regenerated = yield* fork("regenerated");
455 yield* rename("regenerated", regenerated, "Scratch name");
456 yield* titleRegeneration.execute({
457 threadId: regenerated,
458 requestId: yield* armRegeneration({
459 command: `${prefix}:regenerated:regenerate`,
460 threadId: regenerated,
461 }),
462 kind: { type: "regenerate" },
463 });
464​
465 for (const [key, threadId, expectedTitle, generates] of [
466 ["renamed", forkThreadId, "Storage migration notes", false],
467 ["fork of a renamed source", forkOfRenamedSource, seed, true],
468 ["renamed, then regenerated", regenerated, seed, true],
469 ] as const) {
470 const requestId = CommandId.make(`${prefix}:${key}:message`);
471 yield* threads.dispatch({
472 type: "message.dispatch",
473 commandId: requestId,
474 threadId,
475 messageId: MessageId.make(`${prefix}:${key}:message:message`),
476 text: seed,
477 titleSeed: seed,
478 attachments: [],
479 modelSelection,
480 dispatchMode: { type: "defer_start" },
481 createdBy: "user",
482 creationSource: "web",
483 });
484​
485 const settled = yield* threads.getThreadProjection(threadId);
486 assert.equal(settled.thread.title, expectedTitle, key);
487 assert.equal(
488 (yield* outbox.listByCommandId(requestId)).some(
489 (effect) => effect.request.type === "thread-title.generate",
490 ),
491 generates,
492 key,
493 );
494 }
495 }).pipe(Effect.provide(harness.layer));
496 }),
497 );
498​
499 it.effect(
500 "titles an image-only first message without sending bootstrap text to the title model",
501 () =>
502 Effect.gen(function* () {
503 for (const prefix of ["", "Ultrathink:\n"]) {
504 const harness = makeHarness();
505 yield* Effect.gen(function* () {
506 const threads = yield* ThreadManagement.ThreadManagementService;
507 const service = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
508 const threadId = yield* createThread({
509 command: "image:create",
510 thread: "image:thread",
511 });
512 const text = prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT;
513 const attachments = [
514 {
515 type: "image" as const,
516 id: ChatAttachmentId.make("diagram"),
517 name: "diagram.png",
518 mimeType: "image/png",
519 sizeBytes: 10,
520 },
521 ];
522 yield* dispatchUserMessage({ command: "image:message", threadId, text, attachments });
523 const requestId = yield* armRegeneration({ command: "image:title", threadId });
524 const messageId = MessageId.make("image:message:message");
525 yield* service.execute({ threadId, requestId, kind: { type: "initial", messageId } });
526 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
527 assert.equal(call?.message, "");
528 assert.deepEqual(call?.attachments, attachments);
529 const projection = yield* threads.getThreadProjection(threadId);
530 assert.equal(projection.messages[0]?.text, text);
531 assert.equal(projection.thread.title, "Generated title");
532 }).pipe(Effect.provide(harness.layer));
533 }
534 }),
535 );
536​
537 it.effect("arms and clears the regeneration marker through metadata commands", () =>
538 Effect.gen(function* () {
539 const harness = makeHarness();
540 yield* Effect.gen(function* () {
541 const threads = yield* ThreadManagement.ThreadManagementService;
542 const outbox = yield* EffectOutbox.EffectOutboxV2;
543 const threadId = yield* createThread({
544 command: "command:title:arm:create",
545 thread: "thread:title:arm",
546 });
547​
548 const firstRequest = yield* armRegeneration({ command: "command:title:arm:1", threadId });
549 const armed = yield* threads.getThreadProjection(threadId);
550 assert.equal(armed.thread.titleRegeneration?.requestId, firstRequest);
551 assert.deepEqual(
552 (yield* outbox.listByCommandId(firstRequest)).map((effect) => effect.request),
553 [{ type: "thread-title.generate", kind: { type: "regenerate" } }],
554 );
555​
556 yield* threads.dispatch({
557 type: "thread.metadata.update",
558 commandId: CommandId.make("command:title:arm:abandon"),
559 threadId,
560 regenerateTitle: false,
561 });
562 const abandoned = yield* threads.getThreadProjection(threadId);
563 assert.isNotOk(abandoned.thread.titleRegeneration);
564​
565 yield* armRegeneration({ command: "command:title:arm:2", threadId });
566 yield* threads.dispatch({
567 type: "thread.metadata.update",
568 commandId: CommandId.make("command:title:arm:rename"),
569 threadId,
570 title: "Manual title",
571 });
572 const renamed = yield* threads.getThreadProjection(threadId);
573 assert.equal(renamed.thread.title, "Manual title");
574 assert.isNotOk(renamed.thread.titleRegeneration);
575 }).pipe(Effect.provide(harness.layer));
576 }),
577 );
578​
579 it.effect("skips execution when the marker was superseded by a newer request", () =>
580 Effect.gen(function* () {
581 const harness = makeHarness();
582 yield* Effect.gen(function* () {
583 const threads = yield* ThreadManagement.ThreadManagementService;
584 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
585 const threadId = yield* createThread({
586 command: "command:title:stale:create",
587 thread: "thread:title:stale",
588 });
589 const staleRequest = yield* armRegeneration({ command: "command:title:stale:1", threadId });
590 const currentRequest = yield* armRegeneration({
591 command: "command:title:stale:2",
592 threadId,
593 });
594​
595 yield* titleRegeneration.execute({
596 threadId,
597 requestId: staleRequest,
598 kind: { type: "regenerate" },
599 });
600​
601 assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
602 const projection = yield* threads.getThreadProjection(threadId);
603 assert.equal(projection.thread.title, "Seed title");
604 assert.equal(projection.thread.titleRegeneration?.requestId, currentRequest);
605 }).pipe(Effect.provide(harness.layer));
606 }),
607 );
608​
609 it.effect("lands the regenerated title from the conversation digest", () =>
610 Effect.gen(function* () {
611 const harness = makeHarness({
612 generateTitle: () => Effect.succeed({ title: "Fresh title" }),
613 });
614 const fs = yield* FileSystem.FileSystem;
615 const existingWorktree = yield* fs.makeTempDirectoryScoped({ prefix: "title-worktree-" });
616 yield* Effect.gen(function* () {
617 const threads = yield* ThreadManagement.ThreadManagementService;
618 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
619 const cases = [
620 { name: "removed", worktreePath: "/repo-worktrees/removed-by-cleanup", cwd: "/repo" },
621 { name: "existing", worktreePath: existingWorktree, cwd: existingWorktree },
622 ];
623 for (const [index, testCase] of cases.entries()) {
624 const threadId = yield* createThread({
625 command: `command:title:landing:${testCase.name}:create`,
626 thread: `thread:title:landing:${testCase.name}`,
627 worktreePath: testCase.worktreePath,
628 });
629 yield* dispatchUserMessage({
630 command: `command:title:landing:${testCase.name}:message`,
631 threadId,
632 text: "Investigate the flaky login test",
633 });
634 const requestId = yield* armRegeneration({
635 command: `command:title:landing:${testCase.name}:1`,
636 threadId,
637 });
638​
639 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
640​
641 const call = harness.generateThreadTitle.mock.calls[index]?.[0];
642 assert.equal(call?.previousTitle, "Seed title");
643 assert.equal(call?.cwd, testCase.cwd);
644 assert.include(call?.message, "USER:\nInvestigate the flaky login test");
645 const projection = yield* threads.getThreadProjection(threadId);
646 assert.equal(projection.thread.title, "Fresh title");
647 assert.isNotOk(projection.thread.titleRegeneration);
648 assert.deepInclude(projection.thread.lastTitleRegeneration, {
649 requestId,
650 status: "renamed",
651 });
652 }
653 }).pipe(Effect.provide(harness.layer));
654 }).pipe(Effect.provide(NodeServices.layer)),
655 );
656​
657 it.effect.each([
658 { name: "its first message", followUp: true },
659 { name: "no message of its own yet", followUp: false },
660 ])("titles a fork with $name from the source history up to the fork point", ({ followUp }) =>
661 Effect.gen(function* () {
662 const harness = makeHarness();
663 yield* Effect.gen(function* () {
664 const threads = yield* ThreadManagement.ThreadManagementService;
665 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
666 const { forkThreadId } = yield* forkSeededSource("thread:title:fork");
667 const requestId = CommandId.make("command:title:fork:request");
668 const messageId = MessageId.make("command:title:fork:request:message");
669 if (followUp) {
670 yield* threads.dispatch({
671 type: "message.dispatch",
672 commandId: requestId,
673 threadId: forkThreadId,
674 messageId,
675 text: "Try SQLite instead",
676 titleSeed: "Try SQLite instead",
677 attachments: [],
678 modelSelection,
679 dispatchMode: { type: "defer_start" },
680 createdBy: "user",
681 creationSource: "web",
682 });
683 } else {
684 yield* armRegeneration({ command: requestId, threadId: forkThreadId });
685 }
686​
687 yield* titleRegeneration.execute({
688 threadId: forkThreadId,
689 requestId,
690 kind: followUp ? { type: "initial", messageId } : { type: "regenerate" },
691 });
692​
693 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
694 assert.equal(call?.message, followUp ? "Try SQLite instead" : "");
695 assert.equal(call?.forkSource?.title, "Seed title");
696 assert.include(call?.forkSource?.history, "Move session storage from Redis to Postgres");
697 assert.include(call?.forkSource?.history, "Sessions now persist in the Postgres");
698 assert.notInclude(call?.forkSource?.history, "Later work the fork never saw");
699 assert.notInclude(call?.forkSource?.history, "Rolled back attempt");
700 const fork = yield* threads.getThreadRecords(forkThreadId, []);
701 assert.equal(fork.thread.title, "Generated title");
702 }).pipe(Effect.provide(harness.layer));
703 }),
704 );
705​
706 it.effect.each(["plain", "deleted source"] as const)(
707 "refuses to title an empty thread with %s history",
708 (history) =>
709 Effect.gen(function* () {
710 const harness = makeHarness();
711 yield* Effect.gen(function* () {
712 const threads = yield* ThreadManagement.ThreadManagementService;
713 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
714 const { forkThreadId } = yield* forkSeededSource("thread:title:empty");
715 const { thread } = yield* threads.getThreadProjection(forkThreadId);
716 const eventSink = yield* EventSink.EventSinkV2;
717 yield* eventSink.write({
718 events: [
719 {
720 id: EventId.make("empty:lineage"),
721 type: "thread.metadata-updated",
722 threadId: forkThreadId,
723 occurredAt: yield* DateTime.now,
724 payload: {
725 ...thread,
726 forkedFrom:
727 history === "plain"
728 ? null
729 : {
730 type: "run",
731 threadId: ThreadId.make("absent"),
732 runId: RunId.make("absent"),
733 },
734 },
735 },
736 ],
737 });
738 const requestId = yield* armRegeneration({
739 command: "empty:request",
740 threadId: forkThreadId,
741 });
742 yield* titleRegeneration.execute({
743 threadId: forkThreadId,
744 requestId,
745 kind: { type: "regenerate" },
746 });
747 assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
748 const fork = yield* threads.getThreadRecords(forkThreadId, []);
749 assert.deepInclude(fork.thread.lastTitleRegeneration, {
750 requestId,
751 status: "failed",
752 message: "This thread has no messages to title yet.",
753 });
754 }).pipe(Effect.provide(harness.layer));
755 }),
756 );
757​
758 it.effect("keeps the fork point when the source rolls it back after forking", () =>
759 Effect.gen(function* () {
760 const harness = makeHarness();
761 yield* Effect.gen(function* () {
762 const threads = yield* ThreadManagement.ThreadManagementService;
763 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
764 const { sourceThreadId, forkRunId, forkThreadId } = yield* forkSeededSource(
765 "thread:title:rollback",
766 false,
767 false,
768 );
769 yield* TestClock.adjust(1);
770 const source = yield* threads.getThreadRecords(sourceThreadId, ["runs"]);
771 const run = source.runs.find((run) => run.id === forkRunId);
772 assert.isDefined(run);
773 const now = yield* DateTime.now;
774 const eventSink = yield* EventSink.EventSinkV2;
775 yield* eventSink.write({
776 events: [
777 {
778 id: EventId.make("source:rollback"),
779 type: "run.updated",
780 threadId: sourceThreadId,
781 runId: run.id,
782 occurredAt: now,
783 payload: { ...run, status: "rolled_back", completedAt: now },
784 },
785 ],
786 });
787 const requestId = yield* armRegeneration({
788 command: "rollback:request",
789 threadId: forkThreadId,
790 });
791 yield* titleRegeneration.execute({
792 threadId: forkThreadId,
793 requestId,
794 kind: { type: "regenerate" },
795 });
796 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
797 assert.include(call?.forkSource?.history, "Move session storage from Redis to Postgres");
798 assert.include(call?.forkSource?.history, "Rolled back attempt");
799 assert.notInclude(call?.forkSource?.history, "Later work the fork never saw");
800 const fork = yield* threads.getThreadRecords(forkThreadId, []);
801 assert.equal(fork.thread.title, "Generated title");
802 }).pipe(Effect.provide(harness.layer));
803 }),
804 );
805​
806 it.effect("does not inherit imported history when the fork point is missing", () =>
807 Effect.gen(function* () {
808 const harness = makeHarness();
809 yield* Effect.gen(function* () {
810 const threads = yield* ThreadManagement.ThreadManagementService;
811 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
812 const { sourceThreadId, forkThreadId } = yield* forkSeededSource("thread:title:invalid");
813 yield* dispatchUserMessage({
814 command: "imported:message",
815 threadId: sourceThreadId,
816 text: "Imported history",
817 });
818 const source = yield* threads.getThreadRecords(sourceThreadId, []);
819 const fork = yield* threads.getThreadRecords(forkThreadId, []);
820 const eventSink = yield* EventSink.EventSinkV2;
821 yield* eventSink.write({
822 events: [
823 {
824 id: EventId.make("source:imported"),
825 type: "thread.metadata-updated",
826 threadId: sourceThreadId,
827 occurredAt: yield* DateTime.now,
828 payload: { ...source.thread, historyOrigin: "v1_import" },
829 },
830 {
831 id: EventId.make("fork:missing-run"),
832 type: "thread.metadata-updated",
833 threadId: forkThreadId,
834 occurredAt: yield* DateTime.now,
835 payload: {
836 ...fork.thread,
837 forkedFrom: {
838 type: "run",
839 threadId: sourceThreadId,
840 runId: RunId.make("absent:run"),
841 },
842 },
843 },
844 ],
845 });
846 const requestId = yield* armRegeneration({
847 command: "invalid:request",
848 threadId: forkThreadId,
849 });
850 yield* titleRegeneration.execute({
851 threadId: forkThreadId,
852 requestId,
853 kind: { type: "regenerate" },
854 });
855 assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
856 const updated = yield* threads.getThreadRecords(forkThreadId, []);
857 assert.deepInclude(updated.thread.lastTitleRegeneration, {
858 requestId,
859 status: "failed",
860 message: "This thread has no messages to title yet.",
861 });
862 }).pipe(Effect.provide(harness.layer));
863 }),
864 );
865​
866 it.effect("inherits a side chat's own exchange without its parent's history", () =>
867 Effect.gen(function* () {
868 const harness = makeHarness();
869 yield* Effect.gen(function* () {
870 const threads = yield* ThreadManagement.ThreadManagementService;
871 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
872 const { forkThreadId: sideChatId } = yield* forkSeededSource(
873 "thread:title:side-ancestor",
874 true,
875 );
876 const runId = RunId.make("side:run");
877 yield* recordRun({
878 threadId: sideChatId,
879 runId,
880 ordinal: 1,
881 user: "Side topic",
882 assistant: "Side answer",
883 });
884 const threadId = ThreadId.make("side:fork");
885 yield* threads.dispatch({
886 type: "thread.fork",
887 commandId: CommandId.make("side:fork"),
888 sourceThreadId: sideChatId,
889 targetThreadId: threadId,
890 sourcePoint: { type: "run", runId },
891 title: "Side fork",
892 createdBy: "user",
893 creationSource: "web",
894 });
895 const requestId = yield* armRegeneration({ command: "side:request", threadId });
896 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
897 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
898 assert.equal(call?.forkSource?.title, "Seed title fork");
899 assert.include(call?.forkSource?.history, "Side topic");
900 assert.include(call?.forkSource?.history, "Side answer");
901 assert.notInclude(call?.forkSource?.history, "Move session storage");
902 }).pipe(Effect.provide(harness.layer));
903 }),
904 );
905​
906 it.effect("clears the marker and keeps the title when generation fails", () =>
907 Effect.gen(function* () {
908 const harness = makeHarness({
909 generateTitle: () =>
910 Effect.fail(
911 new TextGenerationError({
912 operation: "generateThreadTitle",
913 detail:
914 "Codex CLI command failed: OpenAI Codex\nuser\nConversation text\nmodel unavailable\n",
915 }),
916 ),
917 });
918 yield* Effect.gen(function* () {
919 const threads = yield* ThreadManagement.ThreadManagementService;
920 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
921 const threadId = yield* createThread({
922 command: "command:title:failure:create",
923 thread: "thread:title:failure",
924 });
925 yield* dispatchUserMessage({
926 command: "command:title:failure:message",
927 threadId,
928 text: "Some conversation",
929 });
930 const requestId = yield* armRegeneration({ command: "command:title:failure:1", threadId });
931​
932 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
933​
934 assert.equal(harness.generateThreadTitle.mock.calls.length, 1);
935 const projection = yield* threads.getThreadProjection(threadId);
936 assert.equal(projection.thread.title, "Seed title");
937 assert.isNotOk(projection.thread.titleRegeneration);
938 assert.deepInclude(projection.thread.lastTitleRegeneration, {
939 requestId,
940 status: "failed",
941 message: "model unavailable",
942 });
943 }).pipe(Effect.provide(harness.layer));
944 }),
945 );
946​
947 it.effect("cuts a long failure message without splitting an emoji", () =>
948 Effect.gen(function* () {
949 const harness = makeHarness({
950 generateTitle: () =>
951 Effect.fail(
952 new TextGenerationError({
953 operation: "generateThreadTitle",
954 detail: `${"a".repeat(298)}πŸš€ and the rest of the error`,
955 }),
956 ),
957 });
958 yield* Effect.gen(function* () {
959 const threads = yield* ThreadManagement.ThreadManagementService;
960 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
961 const threadId = yield* createThread({
962 command: "command:title:long-failure:create",
963 thread: "thread:title:long-failure",
964 });
965 yield* dispatchUserMessage({
966 command: "command:title:long-failure:message",
967 threadId,
968 text: "Some conversation",
969 });
970 const requestId = yield* armRegeneration({
971 command: "command:title:long-failure:1",
972 threadId,
973 });
974​
975 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
976​
977 const projection = yield* threads.getThreadProjection(threadId);
978 assert.equal(projection.thread.lastTitleRegeneration?.message, `${"a".repeat(298)}…`);
979 }).pipe(Effect.provide(harness.layer));
980 }),
981 );
982​
983 it.effect("records an unchanged outcome when the model keeps the current title", () =>
984 Effect.gen(function* () {
985 const harness = makeHarness({
986 generateTitle: () => Effect.succeed({ title: "Seed title" }),
987 });
988 yield* Effect.gen(function* () {
989 const threads = yield* ThreadManagement.ThreadManagementService;
990 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
991 const threadId = yield* createThread({
992 command: "command:title:unchanged:create",
993 thread: "thread:title:unchanged",
994 });
995 yield* dispatchUserMessage({
996 command: "command:title:unchanged:message",
997 threadId,
998 text: "Some conversation",
999 });
1000 const requestId = yield* armRegeneration({
1001 command: "command:title:unchanged:1",
1002 threadId,
1003 });
1004​
1005 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
1006​
1007 const projection = yield* threads.getThreadProjection(threadId);
1008 assert.deepInclude(projection.thread.lastTitleRegeneration, {
1009 requestId,
1010 status: "unchanged",
1011 });
1012 }).pipe(Effect.provide(harness.layer));
1013 }),
1014 );
1015});