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

ThreadTitleRegenerationService.test.ts

483 lines17.9 KB

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