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 archived = records(cache);
167 archived.thread = { ...archived.thread, archivedAt: at() };
168 expect(idleCompactionWindow(archived, NOW_MS)).toBeNull();
169 const sideChat = records(cache);
170 expect(idleCompactionWindow(sideChat, NOW_MS)).not.toBeNull();
171 sideChat.thread = {
172 ...sideChat.thread,
173 lineage: { ...sideChat.thread.lineage, relationshipToParent: "fork", sideChat: true },
174 };
175 expect(idleCompactionWindow(sideChat, NOW_MS)).toBeNull();
176 });
177});
178
179describe("IdleCompactionService", () => {
180 it.effect.each([
181 { mode: "onReturn", reads: 0 },
182 { mode: "off", reads: 0 },
183 { mode: "beforeCacheExpires", reads: 1 },
184 { mode: "beforeCacheExpires", override: "off", reads: 0 },
185 { mode: "onReturn", override: "beforeCacheExpires", reads: 1 },
186 { mode: "beforeCacheExpires", projectDisabled: true, reads: 0 },
187 { mode: "beforeCacheExpires", enabled: false, reads: 0 },
188 { mode: "beforeCacheExpires", driver: "codex", instance: "codex", reads: 0 },
189 { mode: "beforeCacheExpires", driver: "codex", instance: "custom-codex", reads: 0 },
190 { mode: "beforeCacheExpires", driver: "claudeAgent", instance: "custom-claude", reads: 1 },
191 { mode: "beforeCacheExpires", unconfigured: true, reads: 1 },
192 ] as const)(
193 "loads history only for eligible idle compaction: $mode/$override/$enabled/$projectDisabled/$instance/$unconfigured",
194 (scenario) => {
195 const test = {
196 override: "default",
197 enabled: true,
198 projectDisabled: false,
199 ...scenario,
200 } as const;
201 return Effect.scoped(
202 Effect.gen(function* () {
203 yield* TestClock.setTime(NOW_MS);
204 const selectedInstance = ProviderInstanceId.make(
205 "instance" in test ? test.instance : "claudeAgent",
206 );
207 const driver = ProviderDriverKind.make("driver" in test ? test.driver : "claudeAgent");
208 const base = records({ cacheExpiresInMs: 2 * MINUTE_MS });
209 const data: OrchestrationV2ThreadProjection = {
210 ...base,
211 thread: {
212 ...base.thread,
213 providerInstanceId: selectedInstance,
214 modelSelection: { ...base.thread.modelSelection, instanceId: selectedInstance },
215 },
216 runs: base.runs.map((run) => ({
217 ...run,
218 providerInstanceId: selectedInstance,
219 modelSelection: { ...run.modelSelection, instanceId: selectedInstance },
220 })),
221 providerThreads: base.providerThreads.map((thread) => ({
222 ...thread,
223 driver,
224 providerInstanceId: selectedInstance,
225 })),
226 attempts: [],
227 nodes: [],
228 subagents: [],
229 providerSessions: [],
230 plans: [],
231 checkpointScopes: [],
232 checkpoints: [],
233 contextHandoffs: [],
234 visibleTurnItems: [],
235 updatedAt: at(),
236 };
237 let historyReads = 0;
238 let dispatches = 0;
239 const done = yield* Deferred.make<void>();
240 const tracer = Tracer.make({
241 span(options) {
242 const span = new Tracer.NativeSpan(options);
243 const end = span.end.bind(span);
244 span.end = (...args) => {
245 end(...args);
246 if (span.name === "IdleCompactionService.compactWhenDue")
247 Deferred.doneUnsafe(done, Effect.void);
248 };
249 return span;
250 },
251 });
252 const dependencies = Layer.mergeAll(
253 Layer.mock(Orchestrator.OrchestratorV2)({
254 streamDomainEvents: Stream.make({
255 id: EventId.make("idle-completed"),
256 type: "run.updated",
257 threadId,
258 runId,
259 occurredAt: at(),
260 payload: data.runs[0]!,
261 }),
262 dispatch: () =>
263 Effect.sync(() => {
264 dispatches++;
265 return { sequence: 1, storedEvents: [] };
266 }),
267 }),
268 Layer.mock(ProjectionStore.ProjectionStoreV2)({
269 getThread: () => Effect.succeed(data.thread),
270 getThreadRecords: () =>
271 Effect.sync(() => {
272 historyReads++;
273 return data;
274 }),
275 }),
276 Layer.mock(ServerSettings.ServerSettingsService)({
277 getSettings: Effect.succeed({
278 ...DEFAULT_SERVER_SETTINGS,
279 idleCompaction: test.mode,
280 providerInstances:
281 "unconfigured" in test
282 ? {}
283 : {
284 [selectedInstance]: {
285 driver,
286 enabled: test.enabled,
287 config: { idleCompaction: test.override },
288 },
289 },
290 projectSettingsOverrides: test.projectDisabled
291 ? {
292 [data.thread.projectId]: {
293 providerInstances: { [selectedInstance]: { enabled: false } },
294 },
295 }
296 : {},
297 }),
298 }),
299 );
300 yield* Effect.gen(function* () {
301 const service = yield* IdleCompactionService.make;
302 yield* service.start();
303 yield* Deferred.await(done);
304 }).pipe(Effect.provide(dependencies), Effect.withTracer(tracer));
305 expect(historyReads).toBe(test.reads);
306 expect(dispatches).toBe(test.reads);
307 }),
308 );
309 },
310 );
311});