Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import {
3 DEFAULT_SERVER_SETTINGS,
4 EventId,
5 MessageId,
6 NodeId,
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 ProviderThreadId,
11 ProviderTurnId,
12 RunId,
13 ThreadId,
14 type OrchestrationV2DomainEvent,
15 type OrchestrationV2ServerCommand,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as Queue from "effect/Queue";
21import * as Stream from "effect/Stream";
22import { TestClock } from "effect/testing";
23
24import * as SqlitePersistence from "../persistence/Sqlite.ts";
25import * as ServerSettings from "../serverSettings.ts";
26import { idleCompactionWindow, type IdleCompactionRecords } from "./IdleCompaction.ts";
27import * as IdleCompactionService from "./IdleCompactionService.ts";
28import * as Orchestrator from "./Orchestrator.ts";
29import * as ProjectionStore from "./ProjectionStore.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("starts two minutes before the cache Claude reported expires", () => {
152 expect(idleCompactionWindow(records({ cacheExpiresInMs: 60 * MINUTE_MS }), NOW_MS)).toEqual({
153 runId,
154 startMs: NOW_MS + 58 * MINUTE_MS,
155 endMs: NOW_MS + 60 * MINUTE_MS,
156 });
157 // A 5m cache whose last request started 3 minutes before the run ended.
158 const late = records({ cacheExpiresInMs: 2 * MINUTE_MS });
159 expect(idleCompactionWindow(late, NOW_MS)).toMatchObject({ startMs: NOW_MS });
160 expect(idleCompactionWindow(late, NOW_MS + 2 * MINUTE_MS)).toBeNull();
161 });
162
163 it("skips small contexts, unknown expiry, other providers, switched threads, and compactions", () => {
164 const cache = { cacheExpiresInMs: 60 * MINUTE_MS };
165 expect(idleCompactionWindow(records({ ...cache, usedTokens: 199_999 }), NOW_MS)).toBeNull();
166 expect(idleCompactionWindow(records(), NOW_MS)).toBeNull();
167 const codex = records(cache);
168 codex.providerThreads = [
169 { ...codex.providerThreads[0]!, driver: ProviderDriverKind.make("codex") },
170 ];
171 expect(idleCompactionWindow(codex, NOW_MS)).toBeNull();
172 const switched = records(cache);
173 switched.thread = { ...switched.thread, providerInstanceId: ProviderInstanceId.make("codex") };
174 expect(idleCompactionWindow(switched, NOW_MS)).toBeNull();
175 const compacted = records(cache);
176 compacted.messages = [{ ...compacted.messages[0]!, text: "/compact" }];
177 expect(idleCompactionWindow(compacted, NOW_MS)).toBeNull();
178 const archived = records(cache);
179 archived.thread = { ...archived.thread, archivedAt: at() };
180 expect(idleCompactionWindow(archived, NOW_MS)).toBeNull();
181 });
182});
183
184const seed = Effect.fn("seedIdleThread")(function* (value: IdleCompactionRecords) {
185 const store = yield* ProjectionStore.ProjectionStoreV2;
186 const event = { threadId, occurredAt: at() };
187 yield* store.apply({
188 ...event,
189 id: EventId.make("e1"),
190 type: "thread.created",
191 payload: value.thread,
192 });
193 yield* store.apply({
194 ...event,
195 id: EventId.make("e2"),
196 type: "run.created",
197 payload: value.runs[0]!,
198 });
199 yield* store.apply({
200 ...event,
201 id: EventId.make("e3"),
202 type: "message.updated",
203 payload: value.messages[0]!,
204 });
205 yield* store.apply({
206 ...event,
207 id: EventId.make("e4"),
208 type: "provider-thread.updated",
209 payload: value.providerThreads[0]!,
210 });
211 yield* store.apply({
212 ...event,
213 id: EventId.make("e5"),
214 type: "provider-turn.updated",
215 payload: value.providerTurns[0]!,
216 });
217});
218
219it.effect("sends /compact as T3 Code once the cache is about to expire", () =>
220 Effect.gen(function* () {
221 yield* TestClock.setTime(NOW_MS);
222 const value = records({ cacheExpiresInMs: 5 * MINUTE_MS });
223 yield* seed(value);
224 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
225 const commands = yield* Queue.unbounded<OrchestrationV2ServerCommand>();
226 const reads = yield* Queue.unbounded<void>();
227 const store = yield* ProjectionStore.ProjectionStoreV2;
228 const dependencies = Layer.mergeAll(
229 Layer.succeed(ProjectionStore.ProjectionStoreV2, {
230 ...store,
231 getThreadRecords: (...args) =>
232 store.getThreadRecords(...args).pipe(Effect.tap(() => Queue.offer(reads, undefined))),
233 }),
234 Layer.mock(ServerSettings.ServerSettingsService)({
235 getSettings: Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, compactIdleThreads: true }),
236 }),
237 Layer.mock(Orchestrator.OrchestratorV2)({
238 streamDomainEvents: Stream.fromQueue(events),
239 dispatch: (command) =>
240 Queue.offer(commands, command).pipe(Effect.as({ sequence: 1, storedEvents: [] })),
241 }),
242 );
243 yield* Effect.gen(function* () {
244 const service = yield* IdleCompactionService.make;
245 yield* service.start();
246 yield* Queue.offer(events, {
247 id: EventId.make("completed"),
248 type: "run.updated",
249 threadId,
250 occurredAt: at(),
251 payload: value.runs[0]!,
252 });
253 yield* Queue.take(reads);
254 yield* TestClock.adjust("2 minutes");
255 expect(yield* Queue.size(commands)).toBe(0);
256 yield* TestClock.adjust("1 minute");
257 expect(yield* Queue.take(commands)).toMatchObject({
258 type: "message.dispatch",
259 threadId,
260 text: "/compact",
261 createdBy: "agent",
262 creationSource: "server",
263 });
264 }).pipe(Effect.provide(dependencies));
265 }).pipe(
266 Effect.provide(ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory))),
267 Effect.scoped,
268 ),
269);