Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(costs): Antigravity Spend survives spaced paths and keeps call dates

rubenluetke10-beep974671469c95
diff --git a/jarvis/agentic_ide/agent_sessions.py b/jarvis/agentic_ide/agent_sessions.py
index 7b6f1596a9..dd12c33295 100644
--- a/jarvis/agentic_ide/agent_sessions.py
+++ b/jarvis/agentic_ide/agent_sessions.py
@@ -57,7 +57,7 @@ from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
-from urllib.parse import unquote, urlparse
+from urllib.parse import quote, unquote, urlparse
from uuid import uuid4
from loguru import logger
@@ -1146,7 +1146,7 @@ def _agy_summaries_for_cwd(root: Path, cwd: str) -> list[tuple[float, str]]:
import sqlite3
try:
- uri = f"file:{db.as_posix()}?mode=ro"
+ uri = f"file:{quote(db.as_posix(), safe='/:')}?mode=ro"
conn = sqlite3.connect(uri, uri=True, timeout=2.0)
except Exception: # noqa: BLE001 - summaries are a convenience
return []
diff --git a/jarvis/costs/cli_usage_index.py b/jarvis/costs/cli_usage_index.py
index e9327b09f1..b19ddc470a 100644
--- a/jarvis/costs/cli_usage_index.py
+++ b/jarvis/costs/cli_usage_index.py
@@ -652,6 +652,15 @@ def _roots_for(agent: str, home: Path | None) -> list[Path]:
return _kimi_roots(home)
+def _sqlite_uri(path: Path) -> str:
+ """Read-only SQLite URI that survives spaces and ``#`` in the path.
+
+ An unquoted ``file:C:/Users/First Last/...`` makes SQLite open a
+ different, empty database (the same trap ``_open_ro`` documents).
+ """
+ return f"file:{quote(path.as_posix(), safe='/:')}?mode=ro"
+
+
def _sqlite_stat(path: Path) -> tuple[int, int]:
"""``(size, mtime_ns)`` for a SQLite file, WAL included.
@@ -1226,11 +1235,58 @@ def _agy_cwd_from_blob(buf: bytes) -> str:
return unquote(path)
+def _agy_iso_ms(value: str) -> int:
+ try:
+ stamp = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except (TypeError, ValueError):
+ return 0
+ if stamp.tzinfo is None:
+ stamp = stamp.replace(tzinfo=UTC)
+ return int(stamp.timestamp() * 1000)
+
+
+def _agy_transcript_times(db_path: Path) -> list[int]:
+ """``created_at`` of the model steps in this conversation, oldest first.
+
+ The SQLite blobs do not carry a wall clock. The JSONL transcript next to
+ them does. User and system rows are skipped so a usage row lines up with
+ the model call that spent the tokens, not the prompt that triggered it.
+ """
+ transcript = (
+ db_path.parent.parent
+ / "brain"
+ / db_path.stem
+ / ".system_generated"
+ / "logs"
+ / "transcript.jsonl"
+ )
+ times: list[int] = []
+ try:
+ with transcript.open("rb") as handle:
+ for raw in handle:
+ if b'"created_at"' not in raw:
+ continue
+ record = _decode(raw)
+ if record is None:
+ continue
+ kind = str(record.get("type") or "")
+ if kind in {"USER_INPUT", "CHECKPOINT", "SYSTEM_MESSAGE"}:
+ continue
+ ms = _agy_iso_ms(str(record.get("created_at") or ""))
+ if ms:
+ times.append(ms)
+ except OSError:
+ return []
+ return times
+
+
def _scan_antigravity(cand: _Candidate, start: int) -> _FileScan:
"""Read one Antigravity conversation database.
``start`` is unused: a conversation DB is small and the WAL can rewrite
earlier rows, so a change always re-reads. Dedup is ``session_id:idx``.
+ A connect failure must NOT record the file as fully consumed, or a path
+ with a space would stay at $0 forever.
"""
del start
rows: list[_Row] = []
@@ -1239,12 +1295,11 @@ def _scan_antigravity(cand: _Candidate, start: int) -> _FileScan:
model = ""
failed = False
try:
- uri = f"file:{cand.path.as_posix()}?mode=ro"
- conn = sqlite3.connect(uri, uri=True, timeout=_DB_TIMEOUT_S)
+ conn = sqlite3.connect(_sqlite_uri(cand.path), uri=True, timeout=_DB_TIMEOUT_S)
except sqlite3.Error as exc:
log.warning("cli usage index: %s not readable (%s)", cand.path, exc)
return _FileScan(
- rows=[], offset=cand.size, cursor=_Cursor(), bytes_read=0, reason="error", failed=True
+ rows=[], offset=0, cursor=_Cursor(), bytes_read=0, reason="error", failed=True
)
try:
conn.row_factory = sqlite3.Row
@@ -1261,8 +1316,10 @@ def _scan_antigravity(cand: _Candidate, start: int) -> _FileScan:
except sqlite3.Error as exc:
log.debug("cli usage index: %s has no gen_metadata (%s)", cand.path, exc)
meta_rows = []
- ts_ms = cand.mtime_ns // 1_000_000
+ fallback_ms = cand.mtime_ns // 1_000_000
+ step_times = _agy_transcript_times(cand.path)
label = _clip(Path(cwd).name if cwd else session_id)
+ call_n = 0
for meta in meta_rows:
blob = meta["data"]
if not blob:
@@ -1273,6 +1330,13 @@ def _scan_antigravity(cand: _Candidate, start: int) -> _FileScan:
_agy_collect_usage(blob, found)
idx = _int(meta["idx"])
for call_i, (tokens_in, tokens_out, tokens_cached) in enumerate(found):
+ if call_n < len(step_times):
+ ts_ms = step_times[call_n]
+ elif step_times:
+ ts_ms = step_times[-1]
+ else:
+ ts_ms = fallback_ms
+ call_n += 1
rows.append(
(
cand.agent,
@@ -1295,7 +1359,7 @@ def _scan_antigravity(cand: _Candidate, start: int) -> _FileScan:
conn.close()
return _FileScan(
rows=rows,
- offset=cand.size,
+ offset=0 if failed else cand.size,
cursor=_Cursor(
session_id=session_id,
model=model,
@@ -1303,7 +1367,7 @@ def _scan_antigravity(cand: _Candidate, start: int) -> _FileScan:
label=_clip(Path(cwd).name if cwd else session_id),
),
bytes_read=cand.size,
- reason="eof",
+ reason="error" if failed else "eof",
failed=failed,
)
diff --git a/tests/unit/costs/test_cli_usage_index.py b/tests/unit/costs/test_cli_usage_index.py
index 082e6eef64..3c576a47ee 100644
--- a/tests/unit/costs/test_cli_usage_index.py
+++ b/tests/unit/costs/test_cli_usage_index.py
@@ -25,6 +25,7 @@ from __future__ import annotations
import json
import sqlite3
import time
+from datetime import UTC, datetime
from pathlib import Path
from jarvis.costs.cli_usage_index import (
@@ -605,17 +606,25 @@ def _pb_len(field: int, blob: bytes) -> bytes:
return _pb_varint((field << 3) | 2) + _pb_varint(len(blob)) + blob
-def test_antigravity_conversation_db_is_indexed(tmp_path: Path) -> None:
- """agy 1.1.20 stores usage in protobuf gen_metadata, not JSONL."""
+def _agy_usage_blob(*, tokens_in: int, tokens_out: int, cached: int, model: str) -> bytes:
usage = (
- _pb_var(2, 1000)
- + _pb_var(3, 40)
- + _pb_var(5, 200)
+ _pb_var(2, tokens_in)
+ + _pb_var(3, tokens_out)
+ + _pb_var(5, cached)
+ _pb_str(7, "bot-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")
)
- blob = _pb_len(1, _pb_len(4, usage)) + _pb_str(19, "gemini-3.7-flash-medium")
- db = tmp_path / ".gemini" / "antigravity-cli" / "conversations" / "sess-agy.db"
- db.parent.mkdir(parents=True)
+ return _pb_len(1, _pb_len(4, usage)) + _pb_str(19, model)
+
+
+def _agy_conversation_db(
+ home: Path,
+ session_id: str,
+ blobs: list[bytes],
+ *,
+ cwd_uri: bytes = b"file:///C:/work/personal-jarvis",
+) -> Path:
+ db = home / ".gemini" / "antigravity-cli" / "conversations" / f"{session_id}.db"
+ db.parent.mkdir(parents=True, exist_ok=True)
con = sqlite3.connect(db)
con.execute(
"CREATE TABLE gen_metadata (idx integer, data blob, size integer NOT NULL DEFAULT 0, "
@@ -624,13 +633,26 @@ def test_antigravity_conversation_db_is_indexed(tmp_path: Path) -> None:
con.execute(
"CREATE TABLE trajectory_metadata_blob (id text, data blob, PRIMARY KEY (id))"
)
- con.execute("INSERT INTO gen_metadata (idx, data, size) VALUES (0, ?, ?)", (blob, len(blob)))
+ for idx, blob in enumerate(blobs):
+ con.execute(
+ "INSERT INTO gen_metadata (idx, data, size) VALUES (?, ?, ?)",
+ (idx, blob, len(blob)),
+ )
con.execute(
"INSERT INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)",
- (b"file:///C:/work/personal-jarvis",),
+ (cwd_uri,),
)
con.commit()
con.close()
+ return db
+
+
+def test_antigravity_conversation_db_is_indexed(tmp_path: Path) -> None:
+ """agy 1.1.20 stores usage in protobuf gen_metadata, not JSONL."""
+ blob = _agy_usage_blob(
+ tokens_in=1000, tokens_out=40, cached=200, model="gemini-3.7-flash-medium"
+ )
+ _agy_conversation_db(tmp_path, "sess-agy", [blob])
data = tmp_path / "data"
refresh(data_dir=data, home=tmp_path)
@@ -645,6 +667,84 @@ def test_antigravity_conversation_db_is_indexed(tmp_path: Path) -> None:
assert "personal-jarvis" in turn.cwd or turn.cwd.endswith("personal-jarvis")
+def test_antigravity_indexes_a_home_path_with_a_space(tmp_path: Path) -> None:
+ """Windows homes are often ``C:\\Users\\First Last``; an unquoted URI misses them."""
+ home = tmp_path / "First Last"
+ blob = _agy_usage_blob(tokens_in=10, tokens_out=2, cached=0, model="gemini-3.7-flash")
+ _agy_conversation_db(home, "sess-space", [blob])
+ data = tmp_path / "data"
+
+ refresh(data_dir=data, home=home)
+
+ (turn,) = _all(data)
+ assert turn.session_id == "sess-space"
+ assert turn.tokens_in == 10
+
+
+def test_antigravity_stamps_each_call_from_the_transcript(tmp_path: Path) -> None:
+ """File mtime would dump a month-old thread into 'today'."""
+ blobs = [
+ _agy_usage_blob(tokens_in=10, tokens_out=1, cached=0, model="gemini-3.7-flash"),
+ _agy_usage_blob(tokens_in=20, tokens_out=2, cached=0, model="gemini-3.7-flash"),
+ ]
+ _agy_conversation_db(tmp_path, "sess-aged", blobs)
+ transcript = (
+ tmp_path
+ / ".gemini"
+ / "antigravity-cli"
+ / "brain"
+ / "sess-aged"
+ / ".system_generated"
+ / "logs"
+ / "transcript.jsonl"
+ )
+ transcript.parent.mkdir(parents=True)
+ transcript.write_text(
+ "\n".join(
+ [
+ json.dumps(
+ {
+ "step_index": 0,
+ "type": "USER_INPUT",
+ "created_at": "2026-06-01T12:00:00Z",
+ }
+ ),
+ json.dumps(
+ {
+ "step_index": 1,
+ "type": "PLANNER_RESPONSE",
+ "created_at": "2026-06-01T12:00:05Z",
+ }
+ ),
+ json.dumps(
+ {
+ "step_index": 2,
+ "type": "PLANNER_RESPONSE",
+ "created_at": "2026-06-08T09:00:00Z",
+ }
+ ),
+ ]
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+ data = tmp_path / "data"
+
+ refresh(data_dir=data, home=tmp_path)
+
+ turns = sorted(_all(data), key=lambda t: t.ts_ms)
+ assert len(turns) == 2
+ assert turns[0].ts_ms != turns[1].ts_ms
+ assert turns[0].tokens_in == 10
+ assert turns[1].tokens_in == 20
+ assert turns[0].ts_ms == int(
+ datetime(2026, 6, 1, 12, 0, 5, tzinfo=UTC).timestamp() * 1000
+ )
+ assert turns[1].ts_ms == int(
+ datetime(2026, 6, 8, 9, 0, 0, tzinfo=UTC).timestamp() * 1000
+ )
+
+
def test_agy_setup_only_transcript_yields_nothing(tmp_path: Path) -> None:
"""What every current-layout transcript on the reference machine looks like."""
data = tmp_path / "data"