Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import {
3 DEFAULT_SERVER_SETTINGS,
4 EventId,
5 MessageId,
6 type OrchestrationV2ThreadProjection,
7 NodeId,
8 ProjectId,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 ProviderThreadId,
12 ProviderTurnId,
13 RunId,
14 ThreadId,
15} from "@t3tools/contracts";
16import * as DateTime from "effect/DateTime";
17import * as Deferred from "effect/Deferred";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as Stream from "effect/Stream";
21import * as Tracer from "effect/Tracer";
22import * as TestClock from "effect/testing/TestClock";
23
24import * as ServerSettings from "../serverSettings.ts";
25import * as IdleCompactionService from "./IdleCompactionService.ts";
26import * as Orchestrator from "./Orchestrator.ts";
27import * as ProjectionStore from "./ProjectionStore.ts";
28
29import { idleCompactionWindow, type IdleCompactionRecords } from "./IdleCompaction.ts";
30
31const NOW_MS = Date.parse("2026-10-19T12:00:00.000Z");
32const MINUTE_MS = 60_000;
33const at = (offset = 0) => DateTime.makeUnsafe(NOW_MS + offset);
34const threadId = ThreadId.make("idle-thread");
35const runId = RunId.make("run-1");
36const instanceId = ProviderInstanceId.make("claudeAgent");
37const providerThreadId = ProviderThreadId.make("provider-thread");
38const modelSelection = { instanceId, model: "claude-opus-5-5" };
39
40function records(
41 usage: { readonly usedTokens?: number; readonly cacheExpiresInMs?: number } = {},
42): { -readonly [Key in keyof IdleCompactionRecords]: IdleCompactionRecords[Key] } {
43 const messageId = MessageId.make("message-1");
44 const nodeId = NodeId.make("root-node");
45 return {
46 thread: {
47 id: threadId,
48 projectId: ProjectId.make("project"),
49 title: "Idle thread",
50 createdBy: "user",
51 creationSource: "web",
52 providerInstanceId: instanceId,
53 modelSelection,
54 runtimeMode: "full-access",
55 interactionMode: "default",
56 branch: null,
57 worktreePath: null,
58 activeProviderThreadId: providerThreadId,
59 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
60 forkedFrom: null,
61 createdAt: at(-MINUTE_MS),
62 updatedAt: at(),
63 archivedAt: null,
64 settledOverride: null,
65 settledAt: null,
66 lastVisitedAt: at(),
67 deletedAt: null,
68 },
69 runs: [
70 {
71 id: runId,
72 threadId,
73 ordinal: 1,
74 providerInstanceId: instanceId,
75 modelSelection,
76 providerThreadId,
77 userMessageId: messageId,
78 rootNodeId: nodeId,
79 activeAttemptId: null,
80 status: "completed",
81 requestedAt: at(-MINUTE_MS),
82 startedAt: at(-MINUTE_MS),
83 completedAt: at(),
84 checkpointId: null,
85 contextHandoffId: null,
86 },
87 ],
88 messages: [
89 {
90 id: messageId,
91 threadId,
92 runId,
93 nodeId,
94 role: "user",
95 text: "Explain this code",
96 attachments: [],
97 streaming: false,
98 createdBy: "user",
99 creationSource: "web",
100 createdAt: at(-MINUTE_MS),
101 updatedAt: at(-MINUTE_MS),
102 },
103 ],
104 providerThreads: [
105 {
106 id: providerThreadId,
107 driver: ProviderDriverKind.make("claudeAgent"),
108 providerInstanceId: instanceId,
109 providerSessionId: null,
110 appThreadId: threadId,
111 ownerNodeId: nodeId,
112 nativeThreadRef: null,
113 nativeConversationHeadRef: null,
114 status: "idle",
115 firstRunOrdinal: 1,
116 lastRunOrdinal: 1,
117 handoffIds: [],
118 forkedFrom: null,
119 pendingBackgroundTasks: [],
120 createdAt: at(-MINUTE_MS),
121 updatedAt: at(),
122 },
123 ],
124 providerTurns: [
125 {
126 id: ProviderTurnId.make("provider-turn-1"),
127 providerThreadId,
128 nodeId,
129 runAttemptId: null,
130 nativeTurnRef: null,
131 ordinal: 1,
132 status: "completed",
133 startedAt: at(-MINUTE_MS),
134 completedAt: at(),
135 tokenUsage: {
136 usedTokens: usage.usedTokens ?? 250_000,
137 ...(usage.cacheExpiresInMs === undefined
138 ? {}
139 : { promptCacheExpiresAt: DateTime.formatIso(at(usage.cacheExpiresInMs)) }),
140 updatedAt: DateTime.formatIso(at()),
141 },
142 },
143 ],
144 runtimeRequests: [],
145 turnItems: [],
146 contextTransfers: [],
147 };
148}
149
150describe("idleCompactionWindow", () => {
151 it("skips small contexts, unknown expiry, other providers, switched threads, compactions, and side chats", () => {
152 const cache = { cacheExpiresInMs: 60 * MINUTE_MS };
153 expect(idleCompactionWindow(records({ ...cache, usedTokens: 199_999 }), NOW_MS)).toBeNull();
154 expect(idleCompactionWindow(records(), NOW_MS)).toBeNull();
155 const codex = records(cache);
156 codex.providerThreads = [
157 { ...codex.providerThreads[0]!, driver: ProviderDriverKind.make("codex") },
158 ];
159 expect(idleCompactionWindow(codex, NOW_MS)).toBeNull();
160 const switched = records(cache);
161 switched.thread = { ...switched.thread, providerInstanceId: ProviderInstanceId.make("codex") };
162 expect(idleCompactionWindow(switched, NOW_MS)).toBeNull();
163 const compacted = records(cache);
164 compacted.messages = [{ ...compacted.messages[0]!, text: "/compact" }];
165 expect(idleCompactionWindow(compacted, NOW_MS)).toBeNull();
166 const steered = records(cache);
167 steered.runs = [
168 ...steered.runs,
169 {
170 ...steered.runs[0]!,
171 id: RunId.make("run-2"),
172 ordinal: 2,
173 userMessageId: MessageId.make("message-2"),
174 status: "cancelled",
175 startedAt: null,
176 },
177 ];
178 expect(idleCompactionWindow(steered, NOW_MS)?.runId).toBe(runId);
179 // A turn Claude itself reported as cancelled did run, so it stays the latest.
180 steered.runs = steered.runs.map((run) => ({ ...run, startedAt: at(-MINUTE_MS) }));
181 expect(idleCompactionWindow(steered, NOW_MS)).toBeNull();
182 const archived = records(cache);
183 archived.thread = { ...archived.thread, archivedAt: at() };
184 expect(idleCompactionWindow(archived, NOW_MS)).toBeNull();
185 const sideChat = records(cache);
186 expect(idleCompactionWindow(sideChat, NOW_MS)).not.toBeNull();
187 sideChat.thread = {
188 ...sideChat.thread,
189 lineage: { ...sideChat.thread.lineage, relationshipToParent: "fork", sideChat: true },
190 };
191 expect(idleCompactionWindow(sideChat, NOW_MS)).toBeNull();
192 });
193});
194
195describe("IdleCompactionService", () => {
196 it.effect.each([
197 { mode: "onReturn", reads: 0 },
198 { mode: "off", reads: 0 },
199 { mode: "beforeCacheExpires", reads: 1 },
200 { mode: "beforeCacheExpires", override: "off", reads: 0 },
201 { mode: "onReturn", override: "beforeCacheExpires", reads: 1 },
202 { mode: "beforeCacheExpires", projectDisabled: true, reads: 0 },
203 { mode: "beforeCacheExpires", enabled: false, reads: 0 },
204 { mode: "beforeCacheExpires", driver: "codex", instance: "codex", reads: 0 },
205 { mode: "beforeCacheExpires", driver: "codex", instance: "custom-codex", reads: 0 },
206 { mode: "beforeCacheExpires", driver: "claudeAgent", instance: "custom-claude", reads: 1 },
207 { mode: "beforeCacheExpires", unconfigured: true, reads: 1 },
208 ] as const)(
209 "loads history only for eligible idle compaction: $mode/$override/$enabled/$projectDisabled/$instance/$unconfigured",
210 (scenario) => {
211 const test = {
212 override: "default",
213 enabled: true,
214 projectDisabled: false,
215 ...scenario,
216 } as const;
217 return Effect.gen(function* () {
218 yield* TestClock.setTime(NOW_MS);
219 const selectedInstance = ProviderInstanceId.make(
220 "instance" in test ? test.instance : "claudeAgent",
221 );
222 const driver = ProviderDriverKind.make("driver" in test ? test.driver : "claudeAgent");
223 const base = records({ cacheExpiresInMs: 2 * MINUTE_MS });
224 const data: OrchestrationV2ThreadProjection = {
225 ...base,
226 thread: {
227 ...base.thread,
228 providerInstanceId: selectedInstance,
229 modelSelection: { ...base.thread.modelSelection, instanceId: selectedInstance },
230 },
231 runs: base.runs.map((run) => ({
232 ...run,
233 providerInstanceId: selectedInstance,
234 modelSelection: { ...run.modelSelection, instanceId: selectedInstance },
235 })),
236 providerThreads: base.providerThreads.map((thread) => ({
237 ...thread,
238 driver,
239 providerInstanceId: selectedInstance,
240 })),
241 attempts: [],
242 nodes: [],
243 subagents: [],
244 providerSessions: [],
245 plans: [],
246 checkpointScopes: [],
247 checkpoints: [],
248 contextHandoffs: [],
249 visibleTurnItems: [],
250 updatedAt: at(),
251 };
252 let historyReads = 0;
253 let dispatches = 0;
254 const done = yield* Deferred.make<void>();
255 const tracer = Tracer.make({
256 span(options) {
257 const span = new Tracer.NativeSpan(options);
258 const end = span.end.bind(span);
259 span.end = (...args) => {
260 end(...args);
261 if (span.name === "IdleCompactionService.compactWhenDue")
262 Deferred.doneUnsafe(done, Effect.void);
263 };
264 return span;
265 },
266 });
267 const dependencies = Layer.mergeAll(
268 Layer.mock(Orchestrator.OrchestratorV2)({
269 streamDomainEvents: Stream.make({
270 id: EventId.make("idle-completed"),
271 type: "run.updated",
272 threadId,
273 runId,
274 occurredAt: at(),
275 payload: data.runs[0]!,
276 }),
277 dispatch: () =>
278 Effect.sync(() => {
279 dispatches++;
280 return { sequence: 1, storedEvents: [] };
281 }),
282 }),
283 Layer.mock(ProjectionStore.ProjectionStoreV2)({
284 getThread: () => Effect.succeed(data.thread),
285 getThreadRecords: () =>
286 Effect.sync(() => {
287 historyReads++;
288 return data;
289 }),
290 }),
291 Layer.mock(ServerSettings.ServerSettingsService)({
292 getSettings: Effect.succeed({
293 ...DEFAULT_SERVER_SETTINGS,
294 idleCompaction: test.mode,
295 providerInstances:
296 "unconfigured" in test
297 ? {}
298 : {
299 [selectedInstance]: {
300 driver,
301 enabled: test.enabled,
302 config: { idleCompaction: test.override },
303 },
304 },
305 projectSettingsOverrides: test.projectDisabled
306 ? {
307 [data.thread.projectId]: {
308 providerInstances: { [selectedInstance]: { enabled: false } },
309 },
310 }
311 : {},
312 }),
313 }),
314 );
315 yield* Effect.gen(function* () {
316 const service = yield* IdleCompactionService.make;
317 yield* service.start();
318 yield* Deferred.await(done);
319 }).pipe(Effect.provide(dependencies), Effect.withTracer(tracer));
320 expect(historyReads).toBe(test.reads);
321 expect(dispatches).toBe(test.reads);
322 });
323 },
324 );
325
326 it.effect("keeps the latest run's compaction when an earlier run reports completed again", () =>
327 Effect.gen(function* () {
328 yield* TestClock.setTime(NOW_MS);
329 const base = records({ cacheExpiresInMs: 10 * MINUTE_MS });
330 const laterRunId = RunId.make("run-2");
331 const laterMessageId = MessageId.make("message-2");
332 const earlierRun = base.runs[0]!;
333 const laterRun = {
334 ...earlierRun,
335 id: laterRunId,
336 ordinal: 2,
337 userMessageId: laterMessageId,
338 };
339 const cancelledRun = {
340 ...earlierRun,
341 id: RunId.make("run-3"),
342 ordinal: 3,
343 userMessageId: MessageId.make("message-3"),
344 status: "cancelled" as const,
345 startedAt: null,
346 };
347 const data: OrchestrationV2ThreadProjection = {
348 ...base,
349 runs: [earlierRun, laterRun, cancelledRun],
350 messages: [
351 ...base.messages,
352 { ...base.messages[0]!, id: laterMessageId, runId: laterRunId, text: "Keep going" },
353 ],
354 providerThreads: [{ ...base.providerThreads[0]!, lastRunOrdinal: 2 }],
355 attempts: [],
356 nodes: [],
357 subagents: [],
358 providerSessions: [],
359 plans: [],
360 checkpointScopes: [],
361 checkpoints: [],
362 contextHandoffs: [],
363 visibleTurnItems: [],
364 updatedAt: at(),
365 };
366 const completed = (run: typeof earlierRun) => ({
367 id: EventId.make(`completed-${run.id}`),
368 type: "run.updated" as const,
369 threadId,
370 runId: run.id,
371 occurredAt: at(),
372 payload: run,
373 });
374 const dispatched: Array<string> = [];
375 const streamDone = yield* Deferred.make<void>();
376 const dependencies = Layer.mergeAll(
377 Layer.mock(Orchestrator.OrchestratorV2)({
378 // A delegated completion on the earlier run lands after the later run completed.
379 streamDomainEvents: Stream.make(completed(laterRun), completed(earlierRun)).pipe(
380 Stream.ensuring(Deferred.succeed(streamDone, undefined)),
381 ),
382 dispatch: (command) =>
383 Effect.sync(() => {
384 dispatched.push(command.commandId);
385 return { sequence: 1, storedEvents: [] };
386 }),
387 }),
388 Layer.mock(ProjectionStore.ProjectionStoreV2)({
389 getThread: () => Effect.succeed(data.thread),
390 getThreadRecords: (_threadId, _keys, options) =>
391 Effect.succeed({
392 ...data,
393 messages: data.messages.filter(
394 (message) =>
395 options?.messageRunIds === undefined ||
396 (message.runId !== null && options.messageRunIds.includes(message.runId)),
397 ),
398 }),
399 }),
400 Layer.mock(ServerSettings.ServerSettingsService)({
401 getSettings: Effect.succeed({
402 ...DEFAULT_SERVER_SETTINGS,
403 idleCompaction: "beforeCacheExpires",
404 }),
405 }),
406 );
407 yield* Effect.gen(function* () {
408 const service = yield* IdleCompactionService.make;
409 yield* service.start();
410 yield* Deferred.await(streamDone);
411 yield* TestClock.adjust(9 * MINUTE_MS);
412 }).pipe(Effect.provide(dependencies));
413 expect(dispatched).toEqual(["server:idle-compact:idle-thread:run-2"]);
414 }),
415 );
416});