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

ThreadTitleRegenerationService.test.ts

309 lines11.8 KB

1import { assert, describe, it, vi } from "@effect/vitest";
2import {
3 CommandId,
4 MessageId,
5 ProjectId,
6 ProviderDriverKind,
7 ProviderInstanceId,
8 ThreadId,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13​
14import * as SqlitePersistence from "../persistence/Sqlite.ts";
15import * as ProjectStore from "./ProjectStore.ts";
16import * as ServerSettings from "../serverSettings.ts";
17import * as TextGeneration from "../textGeneration/TextGeneration.ts";
18import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
19import * as CommandReceiptStore from "./CommandReceiptStore.ts";
20import * as EffectOutbox from "./EffectOutbox.ts";
21import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
22import * as ThreadManagement from "./ThreadManagementService.ts";
23import * as ThreadTitleRegeneration from "./ThreadTitleRegenerationService.ts";
24import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
25import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
26​
27const projectId = ProjectId.make("project:title-regeneration");
28const modelSelection = {
29 instanceId: ProviderInstanceId.make("codex"),
30 model: "gpt-5.1-codex",
31} as const;
32​
33const adapter = {
34 instanceId: modelSelection.instanceId,
35 driver: ProviderDriverKind.make("codex"),
36 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
37 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
38 openSession: () => Effect.die("provider execution is disabled in title regeneration tests"),
39} as ProviderAdapter.ProviderAdapterV2["Service"];
40​
41function makeHarness(
42 options: {
43 readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"];
44 } = {},
45) {
46 const layerDatabase = SqlitePersistence.layerMemory;
47 const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([adapter]);
48 const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
49 { name: "thread-title-regeneration" },
50 layerRegistry,
51 { databaseLayer: layerDatabase, runEffectWorker: false },
52 );
53 const layerServerSettings = ServerSettings.layerTest({});
54 const layerThreadManagement = ThreadManagement.layer.pipe(
55 Layer.provide(layerOrchestrator),
56 Layer.provide(layerServerSettings),
57 Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
58 );
59 const layerOutbox = EffectOutbox.layer.pipe(Layer.provide(layerDatabase));
60 const generateThreadTitle = vi.fn(
61 options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })),
62 );
63 const layerProjectedProjects = Layer.mock(ProjectStore.ProjectStoreV2)({
64 get: (requestedProjectId) =>
65 Effect.succeed(
66 requestedProjectId === projectId
67 ? Option.some({
68 projectId,
69 title: "Project",
70 workspaceRoot: "/repo",
71 defaultModelSelection: modelSelection,
72 defaultThreadEnvMode: null,
73 autoPull: false,
74 faviconPath: null,
75 projectIcon: null,
76 scripts: [],
77 createdAt: "2026-06-20T00:00:00.000Z",
78 updatedAt: "2026-06-20T00:00:00.000Z",
79 deletedAt: null,
80 })
81 : Option.none(),
82 ),
83 });
84 const layerTitleRegeneration = ThreadTitleRegeneration.layer.pipe(
85 Layer.provide(
86 Layer.mergeAll(
87 layerThreadManagement,
88 layerProjectedProjects,
89 Layer.mock(TextGeneration.TextGeneration)({ generateThreadTitle }),
90 layerServerSettings,
91 ),
92 ),
93 );
94 return {
95 layer: Layer.mergeAll(
96 layerThreadManagement,
97 layerTitleRegeneration,
98 layerOutbox,
99 layerDatabase,
100 ),
101 generateThreadTitle,
102 };
104​
105function createThread(input: { readonly command: string; readonly thread: string }) {
106 return Effect.gen(function* () {
107 const threads = yield* ThreadManagement.ThreadManagementService;
108 const threadId = ThreadId.make(input.thread);
109 yield* threads.dispatch({
110 type: "thread.create",
111 commandId: CommandId.make(input.command),
112 threadId,
113 projectId,
114 title: "Seed title",
115 modelSelection,
116 runtimeMode: "full-access",
117 interactionMode: "default",
118 branch: null,
119 worktreePath: null,
120 createdBy: "user",
121 creationSource: "web",
122 });
123 return threadId;
124 });
126​
127function dispatchUserMessage(input: {
128 readonly command: string;
129 readonly threadId: ThreadId;
130 readonly text: string;
131}) {
132 return Effect.gen(function* () {
133 const threads = yield* ThreadManagement.ThreadManagementService;
134 yield* threads.dispatch({
135 type: "message.dispatch",
136 commandId: CommandId.make(input.command),
137 threadId: input.threadId,
138 messageId: MessageId.make(`${input.command}:message`),
139 text: input.text,
140 attachments: [],
141 modelSelection,
142 dispatchMode: { type: "defer_start" },
143 createdBy: "user",
144 creationSource: "web",
145 });
146 });
148​
149function armRegeneration(input: { readonly command: string; readonly threadId: ThreadId }) {
150 return Effect.gen(function* () {
151 const threads = yield* ThreadManagement.ThreadManagementService;
152 const requestId = CommandId.make(input.command);
153 yield* threads.dispatch({
154 type: "thread.metadata.update",
155 commandId: requestId,
156 threadId: input.threadId,
157 regenerateTitle: true,
158 });
159 return requestId;
160 });
162​
163describe("formatThreadTitleContext", () => {
164 it("pins the first user message ahead of the retained tail once content stops fitting", () => {
165 const context = ThreadTitleRegeneration.formatThreadTitleContext([
166 { role: "user", text: `Ancient context that anchors the topic ${"x".repeat(600)}` },
167 { role: "assistant", text: "y".repeat(6_000) },
168 { role: "user", text: "z".repeat(1_500) },
169 ]);
170 assert.isTrue(context.message.includes("USER:\nAncient context that anchors the topic"));
171 assert.isTrue(context.message.includes("[Earlier content truncated]\n\n"));
172 assert.isTrue(context.message.includes("y".repeat(100)));
173 });
174});
175​
176describe("ThreadTitleRegenerationService", () => {
177 it.effect("arms and clears the regeneration marker through metadata commands", () =>
178 Effect.gen(function* () {
179 const harness = makeHarness();
180 yield* Effect.gen(function* () {
181 const threads = yield* ThreadManagement.ThreadManagementService;
182 const outbox = yield* EffectOutbox.EffectOutboxV2;
183 const threadId = yield* createThread({
184 command: "command:title:arm:create",
185 thread: "thread:title:arm",
186 });
187​
188 const firstRequest = yield* armRegeneration({ command: "command:title:arm:1", threadId });
189 const armed = yield* threads.getThreadProjection(threadId);
190 assert.equal(armed.thread.titleRegeneration?.requestId, firstRequest);
191 assert.deepEqual(
192 (yield* outbox.listByCommandId(firstRequest)).map((effect) => effect.request),
193 [{ type: "thread-title.generate", kind: { type: "regenerate" } }],
194 );
195​
196 yield* threads.dispatch({
197 type: "thread.metadata.update",
198 commandId: CommandId.make("command:title:arm:abandon"),
199 threadId,
200 regenerateTitle: false,
201 });
202 const abandoned = yield* threads.getThreadProjection(threadId);
203 assert.isNotOk(abandoned.thread.titleRegeneration);
204​
205 yield* armRegeneration({ command: "command:title:arm:2", threadId });
206 yield* threads.dispatch({
207 type: "thread.metadata.update",
208 commandId: CommandId.make("command:title:arm:rename"),
209 threadId,
210 title: "Manual title",
211 });
212 const renamed = yield* threads.getThreadProjection(threadId);
213 assert.equal(renamed.thread.title, "Manual title");
214 assert.isNotOk(renamed.thread.titleRegeneration);
215 }).pipe(Effect.provide(harness.layer));
216 }),
217 );
218​
219 it.effect("skips execution when the marker was superseded by a newer request", () =>
220 Effect.gen(function* () {
221 const harness = makeHarness();
222 yield* Effect.gen(function* () {
223 const threads = yield* ThreadManagement.ThreadManagementService;
224 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
225 const threadId = yield* createThread({
226 command: "command:title:stale:create",
227 thread: "thread:title:stale",
228 });
229 const staleRequest = yield* armRegeneration({ command: "command:title:stale:1", threadId });
230 const currentRequest = yield* armRegeneration({
231 command: "command:title:stale:2",
232 threadId,
233 });
234​
235 yield* titleRegeneration.execute({
236 threadId,
237 requestId: staleRequest,
238 kind: { type: "regenerate" },
239 });
240​
241 assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
242 const projection = yield* threads.getThreadProjection(threadId);
243 assert.equal(projection.thread.title, "Seed title");
244 assert.equal(projection.thread.titleRegeneration?.requestId, currentRequest);
245 }).pipe(Effect.provide(harness.layer));
246 }),
247 );
248​
249 it.effect("lands the regenerated title from the conversation digest", () =>
250 Effect.gen(function* () {
251 const harness = makeHarness({
252 generateTitle: () => Effect.succeed({ title: "Fresh title" }),
253 });
254 yield* Effect.gen(function* () {
255 const threads = yield* ThreadManagement.ThreadManagementService;
256 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
257 const threadId = yield* createThread({
258 command: "command:title:landing:create",
259 thread: "thread:title:landing",
260 });
261 yield* dispatchUserMessage({
262 command: "command:title:landing:message",
263 threadId,
264 text: "Investigate the flaky login test",
265 });
266 const requestId = yield* armRegeneration({ command: "command:title:landing:1", threadId });
267​
268 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
269​
270 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
271 assert.equal(call?.previousTitle, "Seed title");
272 assert.equal(call?.cwd, "/repo");
273 assert.include(call?.message, "USER:\nInvestigate the flaky login test");
274 const projection = yield* threads.getThreadProjection(threadId);
275 assert.equal(projection.thread.title, "Fresh title");
276 assert.isNotOk(projection.thread.titleRegeneration);
277 }).pipe(Effect.provide(harness.layer));
278 }),
279 );
280​
281 it.effect("clears the marker and keeps the title when generation fails", () =>
282 Effect.gen(function* () {
283 const harness = makeHarness({
284 generateTitle: () => Effect.die(new Error("model unavailable")),
285 });
286 yield* Effect.gen(function* () {
287 const threads = yield* ThreadManagement.ThreadManagementService;
288 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
289 const threadId = yield* createThread({
290 command: "command:title:failure:create",
291 thread: "thread:title:failure",
292 });
293 yield* dispatchUserMessage({
294 command: "command:title:failure:message",
295 threadId,
296 text: "Some conversation",
297 });
298 const requestId = yield* armRegeneration({ command: "command:title:failure:1", threadId });
299​
300 yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
301​
302 assert.equal(harness.generateThreadTitle.mock.calls.length, 1);
303 const projection = yield* threads.getThreadProjection(threadId);
304 assert.equal(projection.thread.title, "Seed title");
305 assert.isNotOk(projection.thread.titleRegeneration);
306 }).pipe(Effect.provide(harness.layer));
307 }),
308 );
309});