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

ThreadTitleRegenerationService.test.ts

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