The best way to control Claude Code, Codex and more from any computer or phone

main
ts 680 lines 26.3 KB
Raw
1 // @effect-diagnostics-next-line nodeBuiltinImport:off - Effect's File.Info has no ctime or sub-millisecond mtime, which the cache tests compare.
2 import * as NodeFSP from "node:fs/promises";
3
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import { assert, describe, it } from "@effect/vitest";
6 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
7 import * as Context from "effect/Context";
8 import * as Effect from "effect/Effect";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Layer from "effect/Layer";
11 import * as Path from "effect/Path";
12 import * as SqlClient from "effect/sql/SqlClient";
13
14 import { parseRateTable, priceUsage } from "../../usage/usagePricing.ts";
15
16 import { makeAntigravityUsageCache, readAntigravityUsage } from "./antigravityUsageReader.ts";
17
18 const openDatabase = Effect.fn("openDatabase")(function* (filename: string) {
19 const context = yield* Layer.build(NodeSqliteClient.layer({ filename }));
20 const sql = Context.get(context, SqlClient.SqlClient);
21 return {
22 exec: (statement: string) => sql.unsafe(statement),
23 run: (statement: string, params: ReadonlyArray<unknown>) => sql.unsafe(statement, params),
24 };
25 });
26
27 const seedDatabase = <E>(
28 filename: string,
29 seed: (db: Effect.Success<ReturnType<typeof openDatabase>>) => Effect.Effect<void, E>,
30 ) =>
31 Effect.scoped(
32 Effect.gen(function* () {
33 yield* seed(yield* openDatabase(filename));
34 }),
35 );
36
37 const tempDir = Effect.gen(function* () {
38 const fileSystem = yield* FileSystem.FileSystem;
39 return yield* fileSystem.makeTempDirectoryScoped({ prefix: "usage-reader-test-" });
40 });
41
42 function protoNumber(field: number, value: number): number[] {
43 const varint = (number: number) => {
44 const bytes: number[] = [];
45 do {
46 const byte = number % 128;
47 number = Math.floor(number / 128);
48 bytes.push(byte + (number > 0 ? 128 : 0));
49 } while (number > 0);
50 return bytes;
51 };
52 return [...varint(field * 8), ...varint(value)];
53 }
54
55 function protoBytes(field: number, bytes: readonly number[]): number[] {
56 const encoded = protoNumber(field, bytes.length);
57 encoded[0] = encoded[0]! + 2;
58 return [...encoded, ...bytes];
59 }
60
61 function protoText(field: number, value: string): number[] {
62 return protoBytes(field, [...Buffer.from(value)]);
63 }
64
65 const TABLES =
66 "CREATE TABLE gen_metadata (idx INTEGER, data BLOB); CREATE TABLE steps (idx INTEGER, metadata BLOB)";
67
68 const createTables = (db: Effect.Success<ReturnType<typeof openDatabase>>) =>
69 Effect.forEach(TABLES.split("; "), db.exec, { discard: true });
70
71 const records = (result: Effect.Success<ReturnType<typeof readAntigravityUsage>>) =>
72 result.files.flatMap((file) => file.records);
73
74 describe("readAntigravityUsage", () => {
75 it.effect("learns numeric models from offline metadata and refreshes cached resolutions", () =>
76 Effect.gen(function* () {
77 const path = yield* Path.Path;
78 const fs = yield* FileSystem.FileSystem;
79 const dir = yield* tempDir;
80 const cache = makeAntigravityUsageCache();
81 yield* seedDatabase(path.join(dir, "a-usage.db"), (db) =>
82 Effect.gen(function* () {
83 yield* createTables(db);
84 for (const [idx, id] of [9001, 9002, 1319].entries()) {
85 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
86 idx,
87 new Uint8Array(protoBytes(9, [...protoNumber(1, id), ...protoNumber(2, 10)])),
88 ]);
89 }
90 }),
91 );
92 const first = yield* readAntigravityUsage(dir, 0, cache);
93 assert.strictEqual(records(first)[0]?.model, "antigravity-model-9001");
94 const evidence = path.join(dir, "z-names.db");
95 yield* seedDatabase(evidence, (db) =>
96 Effect.gen(function* () {
97 yield* createTables(db);
98 for (const [idx, [id, name]] of (
99 [
100 [9001, "Gemini 9.1 Flash (High)"],
101 [9002, "Gemini default"],
102 [1319, "Gemini 9.2 Flash"],
103 ] as const
104 ).entries()) {
105 yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
106 idx,
107 new Uint8Array(
108 protoBytes(1, [
109 ...protoNumber(3, id),
110 ...protoText(19, "gemini-default"),
111 ...protoText(21, name),
112 ]),
113 ),
114 ]);
115 }
116 }),
117 );
118 const next = yield* readAntigravityUsage(dir, 0, cache);
119 assert.deepStrictEqual(
120 records(next).map(({ model, rateModel }) => [model, rateModel]),
121 [
122 ["gemini-9.1-flash-high", "gemini-9.1-flash"],
123 ["antigravity-model-9002", undefined],
124 ["gemini-9.2-flash", undefined],
125 ],
126 );
127 assert.deepStrictEqual(records(yield* readAntigravityUsage(dir, 0, cache)), records(next));
128 yield* fs.remove(evidence);
129 assert.deepStrictEqual(records(yield* readAntigravityUsage(dir, 0, cache)), records(first));
130 }).pipe(Effect.provide(NodeServices.layer)),
131 );
132
133 it.effect("keeps explicit model evidence separate from retries and conflicting names", () =>
134 Effect.gen(function* () {
135 const path = yield* Path.Path;
136 const dir = yield* tempDir;
137 yield* seedDatabase(path.join(dir, "conflicts.db"), (db) =>
138 Effect.gen(function* () {
139 yield* createTables(db);
140 for (const [idx, name] of ["Gemini 9.1 Flash", "Gemini 9.2 Flash"].entries()) {
141 yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
142 idx,
143 new Uint8Array(
144 protoBytes(1, [
145 ...protoNumber(3, 1319),
146 ...protoText(19, name),
147 ...protoBytes(4, [
148 ...protoNumber(1, 1319),
149 ...protoNumber(2, 10),
150 ...protoText(11, `r-${idx}`),
151 ]),
152 ...protoBytes(
153 17,
154 protoBytes(2, [...protoNumber(1, 1026), ...protoNumber(2, 12)]),
155 ),
156 ]),
157 ),
158 ]);
159 }
160 for (const [idx, id] of [1319, 9003].entries()) {
161 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
162 10 + idx,
163 new Uint8Array(
164 protoBytes(9, [
165 ...protoNumber(1, id),
166 ...protoNumber(2, 10),
167 ...(idx === 0 ? protoText(11, "r-0") : []),
168 ]),
169 ),
170 ]);
171 }
172 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
173 2,
174 new Uint8Array(protoBytes(9, [...protoNumber(1, 1319), ...protoNumber(2, 10)])),
175 ]);
176 yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
177 3,
178 new Uint8Array(
179 protoBytes(1, [
180 ...protoText(19, "Gemini 9.3 Flash"),
181 ...protoBytes(17, protoBytes(2, [...protoNumber(1, 9004), ...protoNumber(2, 10)])),
182 ]),
183 ),
184 ]);
185 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
186 4,
187 new Uint8Array([
188 ...protoBytes(24, protoText(12, "Claude 5.5 Opus (Thinking)")),
189 ...protoBytes(9, [...protoNumber(1, 9005), ...protoNumber(2, 10)]),
190 ]),
191 ]);
192 }),
193 );
194 const result = yield* readAntigravityUsage(dir, 0);
195 assert.deepStrictEqual(result.errors, []);
196 assert.deepStrictEqual(
197 records(result)
198 .map(({ model }) => model)
199 .sort(),
200 [
201 "gemini-9.1-flash",
202 "antigravity-model-9003",
203 "antigravity-model-1319",
204 "claude-opus-4-6",
205 "gemini-9.2-flash",
206 "claude-opus-4-6",
207 "antigravity-model-9004",
208 "claude-opus-5-5-thinking",
209 ].sort(),
210 );
211 }).pipe(Effect.provide(NodeServices.layer)),
212 );
213
214 it.effect(
215 "deduplicates Antigravity generation and step usage while preserving retry model and token buckets",
216 () =>
217 Effect.gen(function* () {
218 const path = yield* Path.Path;
219 const dir = yield* tempDir;
220 const stamp = protoNumber(1, 1780000000);
221 const usage = [
222 ...protoNumber(2, 100),
223 ...protoNumber(3, 40),
224 ...protoNumber(4, 5),
225 ...protoNumber(5, 20),
226 ...protoNumber(9, 10),
227 ...protoText(11, "response-1"),
228 ];
229 const retry = [
230 ...protoNumber(1, 1026),
231 ...protoNumber(2, 12),
232 ...protoNumber(3, 3),
233 ...protoText(11, "retry-1"),
234 ];
235 const generation = protoBytes(1, [
236 ...protoBytes(4, usage),
237 ...protoText(19, "Gemini 3 Pro"),
238 ...protoBytes(9, protoBytes(4, stamp)),
239 ]);
240 const step = [
241 ...protoBytes(9, usage),
242 ...protoBytes(8, stamp),
243 ...protoBytes(28, protoBytes(2, retry)),
244 ];
245 yield* seedDatabase(path.join(dir, "session-1.db"), (db) =>
246 Effect.gen(function* () {
247 yield* createTables(db);
248 yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
249 0,
250 new Uint8Array(generation),
251 ]);
252 yield* db.run("INSERT INTO steps VALUES (?, ?)", [0, new Uint8Array(step)]);
253 }),
254 );
255 const result = yield* readAntigravityUsage(dir, 0);
256 assert.deepStrictEqual(result.errors, []);
257 const read = records(result);
258 assert.strictEqual(read.length, 2);
259 const main = read.find((record) => record.model === "gemini-3-pro");
260 assert.isDefined(main);
261 assert.strictEqual(main?.timestampMs, 1780000000000);
262 assert.strictEqual(main?.sessionId, "session-1");
263 assert.deepStrictEqual(main?.totals, {
264 uncachedInputTokens: 100,
265 cachedInputTokens: 20,
266 cacheCreationTokens: 5,
267 outputTokens: 40,
268 reasoningTokens: 10,
269 });
270 assert.strictEqual(
271 read.find((record) => record.model === "claude-opus-4-6")?.totals.uncachedInputTokens,
272 12,
273 );
274 assert.deepStrictEqual(records(yield* readAntigravityUsage(dir, 1780000000001)), []);
275 }).pipe(Effect.provide(NodeServices.layer)),
276 );
277
278 it.effect("uses the matching Antigravity generation model for each model-less step", () =>
279 Effect.gen(function* () {
280 const path = yield* Path.Path;
281 const dir = yield* tempDir;
282 yield* seedDatabase(path.join(dir, "model-switch.db"), (db) =>
283 Effect.gen(function* () {
284 yield* createTables(db);
285 for (const [idx, name] of ["Gemini 3 Pro", "Claude Opus 4.6"].entries()) {
286 yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
287 idx,
288 new Uint8Array(protoBytes(1, protoText(19, name))),
289 ]);
290 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
291 idx,
292 new Uint8Array(protoBytes(9, protoNumber(2, 10 + idx))),
293 ]);
294 }
295 }),
296 );
297 const result = yield* readAntigravityUsage(dir, 0);
298 assert.deepStrictEqual(result.errors, []);
299 assert.deepStrictEqual(
300 records(result).map((record) => record.model),
301 ["gemini-3-pro", "claude-opus-4-6"],
302 );
303 }).pipe(Effect.provide(NodeServices.layer)),
304 );
305
306 it.effect("prices Antigravity effort and routing variants at their base model", () =>
307 Effect.gen(function* () {
308 const path = yield* Path.Path;
309 const dir = yield* tempDir;
310 yield* seedDatabase(path.join(dir, "variants.db"), (db) =>
311 Effect.gen(function* () {
312 yield* createTables(db);
313 yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
314 0,
315 new Uint8Array(protoBytes(1, protoText(19, "Gemini 3.7 Flash Control"))),
316 ]);
317 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
318 0,
319 new Uint8Array(protoBytes(9, protoNumber(2, 10))),
320 ]);
321 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
322 1,
323 new Uint8Array(protoBytes(9, [...protoNumber(1, 1319), ...protoNumber(2, 11)])),
324 ]);
325 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
326 2,
327 new Uint8Array(protoBytes(9, [...protoNumber(1, 1132), ...protoNumber(2, 12)])),
328 ]);
329 // A model-less step that only learns its model by merging with a named generation.
330 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
331 5,
332 new Uint8Array(protoBytes(9, [...protoNumber(2, 100), ...protoText(11, "response")])),
333 ]);
334 yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
335 3,
336 new Uint8Array(
337 protoBytes(1, [
338 ...protoText(19, "Gemini 3.8 Flash High"),
339 ...protoBytes(4, [...protoNumber(2, 100), ...protoText(11, "response")]),
340 ]),
341 ),
342 ]);
343 }),
344 );
345 const result = yield* readAntigravityUsage(dir, 0);
346 assert.deepStrictEqual(result.errors, []);
347 assert.deepStrictEqual(
348 records(result).map((record) => [record.model, record.rateModel]),
349 [
350 ["gemini-3.7-flash-control", "gemini-3.7-flash"],
351 ["gemini-3.8-flash-medium", "gemini-3.8-flash"],
352 ["gemini-3.5-flash-high", "gemini-3.5-flash"],
353 ["gemini-3.8-flash-high", "gemini-3.8-flash"],
354 ],
355 );
356 const table = parseRateTable({
357 "gemini-3.7-flash": { input_cost_per_token: 0.75e-6, output_cost_per_token: 3.75e-6 },
358 "gemini-3.8-flash": { input_cost_per_token: 0.75e-6, output_cost_per_token: 3.75e-6 },
359 "gemini-3.5-flash": { input_cost_per_token: 0.5e-6, output_cost_per_token: 3e-6 },
360 });
361 const priced = records(result).map((record) => priceUsage(table, record));
362 assert.deepStrictEqual(
363 priced.map(({ costSource }) => costSource),
364 Array(4).fill("modelPriced"),
365 );
366 for (const [index, expected] of [7.5e-6, 8.25e-6, 6e-6, 75e-6].entries()) {
367 assert.closeTo(priced[index]!.costUsd, expected, 1e-12);
368 }
369 }).pipe(Effect.provide(NodeServices.layer)),
370 );
371
372 it.effect("prices ACP effort variants at the base model rate", () =>
373 Effect.gen(function* () {
374 const path = yield* Path.Path;
375 const dir = yield* tempDir;
376 yield* seedDatabase(path.join(dir, "effort.db"), (db) =>
377 Effect.gen(function* () {
378 yield* createTables(db);
379 for (const [idx, name] of [
380 "gemini-4-argon-high",
381 "gemini-4-argon",
382 "gemini-3.7-flash-safety-le",
383 "gemini-3-flash-agent",
384 "gemini-3-flash",
385 "gemini-default",
386 ].entries()) {
387 yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
388 idx,
389 new Uint8Array(protoBytes(1, protoText(19, name))),
390 ]);
391 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
392 idx,
393 new Uint8Array(protoBytes(9, protoNumber(2, 10 + idx))),
394 ]);
395 }
396 }),
397 );
398 const result = yield* readAntigravityUsage(dir, 0);
399 assert.deepStrictEqual(
400 records(result).map(({ model, rateModel }) => [model, rateModel]),
401 [
402 ["gemini-4-argon-high", "gemini-4-argon"],
403 ["gemini-4-argon", undefined],
404 ["gemini-3.7-flash-safety-le", "gemini-3.7-flash"],
405 ["gemini-3-flash-agent", "gemini-3.5-flash"],
406 ["gemini-3-flash", "gemini-3-flash-preview"],
407 ["gemini-default", undefined],
408 ],
409 );
410 }).pipe(Effect.provide(NodeServices.layer)),
411 );
412
413 it.effect("merges Antigravity aliases that bridge previously separate step records", () =>
414 Effect.gen(function* () {
415 const path = yield* Path.Path;
416 const dir = yield* tempDir;
417 yield* seedDatabase(path.join(dir, "bridge.db"), (db) =>
418 Effect.gen(function* () {
419 yield* createTables(db);
420 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
421 0,
422 new Uint8Array(protoBytes(9, [...protoNumber(2, 100), ...protoText(11, "response")])),
423 ]);
424 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
425 1,
426 new Uint8Array(protoBytes(9, [...protoNumber(3, 40), ...protoText(12, "provider")])),
427 ]);
428 yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
429 0,
430 new Uint8Array(
431 protoBytes(1, [
432 ...protoText(19, "Gemini 3 Pro"),
433 ...protoBytes(4, [
434 ...protoNumber(2, 50),
435 ...protoNumber(5, 20),
436 ...protoText(11, "response"),
437 ...protoText(12, "provider"),
438 ]),
439 ]),
440 ),
441 ]);
442 }),
443 );
444 const result = yield* readAntigravityUsage(dir, 0);
445 assert.deepStrictEqual(result.errors, []);
446 const read = records(result);
447 assert.strictEqual(read.length, 1);
448 assert.deepStrictEqual(read[0]?.totals, {
449 uncachedInputTokens: 100,
450 cachedInputTokens: 20,
451 cacheCreationTokens: 0,
452 outputTokens: 40,
453 reasoningTokens: 0,
454 });
455 }).pipe(Effect.provide(NodeServices.layer)),
456 );
457
458 it.effect(
459 "merges Antigravity provider and message aliases across configured roots while keeping original ownership",
460 () =>
461 Effect.gen(function* () {
462 const fileSystem = yield* FileSystem.FileSystem;
463 const path = yield* Path.Path;
464 const dir = yield* tempDir;
465 const roots = [path.join(dir, "first"), path.join(dir, "second")];
466 for (const [index, root] of roots.entries()) {
467 yield* fileSystem.makeDirectory(root);
468 yield* seedDatabase(path.join(root, `session-${index}.db`), (db) =>
469 Effect.gen(function* () {
470 yield* db.exec("CREATE TABLE steps (idx INTEGER, metadata BLOB)");
471 for (const identity of [7, 12]) {
472 const usage = [
473 ...protoNumber(1, 246),
474 ...protoNumber(2, index === 0 ? 100 : 150),
475 ...protoText(11, `response-${index}-${identity}`),
476 ...protoText(identity, `shared-${identity}`),
477 ];
478 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
479 identity,
480 new Uint8Array(protoBytes(9, usage)),
481 ]);
482 }
483 }),
484 );
485 }
486 const result = yield* readAntigravityUsage(roots, 0);
487 assert.deepStrictEqual(result.errors, []);
488 assert.strictEqual(result.files.length, 2);
489 assert.strictEqual(result.files[0]?.root, roots[0]);
490 assert.strictEqual(result.files[0]?.records.length, 2);
491 assert.strictEqual(result.files[1]?.records.length, 0);
492 assert.deepStrictEqual(
493 result.files[0]?.records.map((record) => record.totals.uncachedInputTokens),
494 [150, 150],
495 );
496 assert.isTrue(result.files[0]?.records.every((record) => record.sessionId === "session-0"));
497 }).pipe(Effect.provide(NodeServices.layer)),
498 );
499
500 it.effect("upgrades Antigravity fallback timestamps before applying the date window", () =>
501 Effect.gen(function* () {
502 const fileSystem = yield* FileSystem.FileSystem;
503 const path = yield* Path.Path;
504 const dir = yield* tempDir;
505 for (const fallback of ["mtime", "trajectory"]) {
506 const file = path.join(dir, `${fallback}.db`);
507 yield* seedDatabase(file, (db) =>
508 Effect.gen(function* () {
509 yield* createTables(db);
510 if (fallback === "trajectory") {
511 yield* db.exec("CREATE TABLE trajectory_metadata_blob (data BLOB)");
512 yield* db.run("INSERT INTO trajectory_metadata_blob VALUES (?)", [
513 new Uint8Array(protoBytes(2, protoNumber(1, 1780000200))),
514 ]);
515 }
516 for (const [index, seconds] of [1780000000, 1780000200].entries()) {
517 const usage = [...protoNumber(2, 10), ...protoText(11, `${fallback}-${index}`)];
518 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
519 index,
520 new Uint8Array(protoBytes(9, usage)),
521 ]);
522 yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
523 index,
524 new Uint8Array(
525 protoBytes(1, [
526 ...protoBytes(4, usage),
527 ...protoBytes(9, protoBytes(4, protoNumber(1, seconds))),
528 ]),
529 ),
530 ]);
531 }
532 }),
533 );
534 yield* fileSystem.utimes(file, 1780000000, 1780000000);
535 }
536 const result = yield* readAntigravityUsage(dir, 1780000100000);
537 assert.deepStrictEqual(result.errors, []);
538 const read = records(result);
539 assert.strictEqual(read.length, 2);
540 assert.deepStrictEqual(
541 read.map((record) => record.timestampMs),
542 [1780000200000, 1780000200000],
543 );
544 }).pipe(Effect.provide(NodeServices.layer)),
545 );
546
547 const antigravityGeneration = (responseId: string) =>
548 new Uint8Array(
549 protoBytes(1, [
550 ...protoBytes(4, [
551 ...protoNumber(2, 100),
552 ...protoNumber(3, 40),
553 ...protoText(11, responseId),
554 ]),
555 ...protoText(19, "Gemini 3 Pro"),
556 ...protoBytes(9, protoBytes(4, protoNumber(1, 1780000000))),
557 ]),
558 );
559
560 it.effect("rereads an Antigravity database when only its WAL changed", () =>
561 Effect.gen(function* () {
562 const pathService = yield* Path.Path;
563 const dir = yield* tempDir;
564 const path = pathService.join(dir, "session-1.db");
565 const db = yield* openDatabase(path);
566 yield* db.exec("PRAGMA journal_mode = WAL");
567 yield* db.exec("PRAGMA wal_autocheckpoint = 0");
568 yield* db.exec("CREATE TABLE gen_metadata (idx INTEGER, data BLOB)");
569 const insert = (idx: number, responseId: string) =>
570 db.run("INSERT INTO gen_metadata VALUES (?, ?)", [idx, antigravityGeneration(responseId)]);
571 yield* insert(0, "r-1");
572 const cache = makeAntigravityUsageCache();
573 const first = yield* readAntigravityUsage(dir, 0, cache);
574 assert.strictEqual(records(first).length, 1);
575
576 const before = yield* Effect.promise(() => NodeFSP.stat(path));
577 yield* insert(1, "r-2");
578 const after = yield* Effect.promise(() => NodeFSP.stat(path));
579 assert.strictEqual(after.size, before.size);
580 assert.strictEqual(after.mtimeMs, before.mtimeMs);
581
582 const next = yield* readAntigravityUsage(dir, 0, cache);
583 assert.deepStrictEqual(
584 records(next).map((record) => record.dedupeKey),
585 ["antigravity:11:r-1", "antigravity:11:r-2"],
586 );
587 }).pipe(Effect.provide(NodeServices.layer)),
588 );
589
590 it.effect(
591 "reads Antigravity step-only stores, skips index files and reports malformed databases",
592 () =>
593 Effect.gen(function* () {
594 const fileSystem = yield* FileSystem.FileSystem;
595 const path = yield* Path.Path;
596 const dir = yield* tempDir;
597 // agy 1.5.x keeps this index beside its conversations; it is not a conversation store.
598 yield* seedDatabase(path.join(dir, "conversation_summaries.db"), (db) =>
599 db.exec(
600 "CREATE TABLE conversation_summaries (conversation_id TEXT PRIMARY KEY, title TEXT, step_count INTEGER)",
601 ),
602 );
603 yield* seedDatabase(path.join(dir, "steps.db"), (db) =>
604 Effect.gen(function* () {
605 yield* db.exec("CREATE TABLE steps (idx INTEGER, metadata BLOB)");
606 const usage = [...protoNumber(1, 246), ...protoNumber(2, 10), ...protoNumber(3, 5)];
607 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
608 0,
609 new Uint8Array([
610 ...protoBytes(9, usage),
611 ...protoBytes(8, protoNumber(1, 1780000000)),
612 ]),
613 ]);
614 }),
615 );
616 yield* fileSystem.writeFileString(path.join(dir, "broken.db"), "not a sqlite database");
617 const result = yield* readAntigravityUsage(dir, 0);
618 assert.deepStrictEqual(result.errors, [path.join(dir, "broken.db")]);
619 assert.strictEqual(records(result)[0]?.model, "gemini-2.5-pro");
620 assert.strictEqual(records(result)[0]?.totals.outputTokens, 5);
621 }).pipe(Effect.provide(NodeServices.layer)),
622 );
623
624 it.effect("ignores large values in unused Antigravity protobuf fields", () =>
625 Effect.gen(function* () {
626 const path = yield* Path.Path;
627 const dir = yield* tempDir;
628 yield* seedDatabase(path.join(dir, "large-varint.db"), (db) =>
629 Effect.gen(function* () {
630 yield* db.exec("CREATE TABLE steps (idx INTEGER, metadata BLOB)");
631 const unusedField = [...protoNumber(99, 0).slice(0, -1), ...Array(9).fill(0xff), 0x01];
632 const usage = [...protoNumber(1, 246), ...protoNumber(2, 10), ...unusedField];
633 yield* db.run("INSERT INTO steps VALUES (?, ?)", [
634 0,
635 new Uint8Array(protoBytes(9, usage)),
636 ]);
637 }),
638 );
639 const result = yield* readAntigravityUsage(dir, 0);
640 assert.deepStrictEqual(result.errors, []);
641 assert.strictEqual(records(result)[0]?.totals.uncachedInputTokens, 10);
642 }).pipe(Effect.provide(NodeServices.layer)),
643 );
644
645 const stepUsage = (responseId: string) =>
646 new Uint8Array(protoBytes(9, [...protoNumber(2, 10), ...protoText(11, responseId)]));
647
648 it.effect("returns Antigravity records in idx order however the rows are stored", () =>
649 Effect.gen(function* () {
650 const path = yield* Path.Path;
651 const dir = yield* tempDir;
652 yield* seedDatabase(path.join(dir, "session-1.db"), (db) =>
653 Effect.gen(function* () {
654 yield* createTables(db);
655 yield* db.exec("BEGIN");
656 for (let idx = 99; idx >= 0; idx--) {
657 yield* db.run("INSERT INTO steps VALUES (?, ?)", [idx, stepUsage(`s-${idx}`)]);
658 }
659 for (const idx of [1, 0]) {
660 yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
661 idx,
662 antigravityGeneration(`g-${idx}`),
663 ]);
664 }
665 yield* db.exec("COMMIT");
666 }),
667 );
668 const result = yield* readAntigravityUsage(dir, 0);
669 assert.deepStrictEqual(result.errors, []);
670 assert.deepStrictEqual(
671 records(result).map((record) => record.dedupeKey),
672 [
673 ...Array.from({ length: 100 }, (_, idx) => `antigravity:11:s-${idx}`),
674 "antigravity:11:g-0",
675 "antigravity:11:g-1",
676 ],
677 );
678 }).pipe(Effect.provide(NodeServices.layer)),
679 );
680 });