Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(usage): count Antigravity context replay and terminal Grok/Antigravity sessions
[._.]/ Adam Eivyad7adace27df
diff --git a/client/src/components/usage/SubscriptionSavingsCard.jsx b/client/src/components/usage/SubscriptionSavingsCard.jsxindex ecace53d57..03c7741d7c 100644--- a/client/src/components/usage/SubscriptionSavingsCard.jsx+++ b/client/src/components/usage/SubscriptionSavingsCard.jsx@@ -95,6 +95,14 @@ export function CostInput({ row, value, onChange, idPrefix }) {);}+// A plan whose API figure is not fully measured. Estimates for Antigravity (no+// token counts on disk) and killed sessions understate real usage, so the row+// says so instead of presenting a low number as a bargain-less plan.+const SOURCE_LABELS = { estimate: 'estimated', mixed: 'partly estimated' };+const SourceBadge = ({ source }) => (+ SOURCE_LABELS[source] ? <Pill tone="context" size="xs" className="ml-2">{SOURCE_LABELS[source]}</Pill> : null+);+export const NotPriced = () => <span className="text-gray-600">not priced</span>;export function CellValue({ cell }) {@@ -195,6 +203,7 @@ export default function SubscriptionSavingsCard({ savings, onSaved }) {<label htmlFor={`mobile-subscription-cost-${row.family}`} className="text-sm font-medium text-white truncate">{row.label}{!row.enabled && <Pill tone="context" size="xs" className="ml-2">disabled</Pill>}+ <SourceBadge source={row.source} /></label><CostInput row={row} value={displayValue(drafts, row)} onChange={onChange} idPrefix="mobile" /></div>@@ -246,6 +255,7 @@ export default function SubscriptionSavingsCard({ savings, onSaved }) {{row.label}</label>{!row.enabled && <Pill tone="context" size="xs" className="ml-2">disabled</Pill>}+ <SourceBadge source={row.source} /></td><td className="py-2 px-2"><CostInput row={row} value={displayValue(drafts, row)} onChange={onChange} idPrefix="desktop" />@@ -287,7 +297,7 @@ export default function SubscriptionSavingsCard({ savings, onSaved }) {usage no subscription covers (pay-as-you-go API providers or pre-breakdown legacy rows) and is excluded from savings.</>)}- {' '}Savings inherit the estimate’s accuracy — rows marked Estimated above understate real usage.+ {' '}Savings inherit the estimate’s accuracy — rows badged estimated above understate real usage.</p></div>);diff --git a/client/src/components/usage/SubscriptionSavingsCard.test.jsx b/client/src/components/usage/SubscriptionSavingsCard.test.jsxindex 7610819c97..a1b70c524e 100644--- a/client/src/components/usage/SubscriptionSavingsCard.test.jsx+++ b/client/src/components/usage/SubscriptionSavingsCard.test.jsx@@ -75,6 +75,15 @@ describe('SubscriptionSavingsCard', () => {expect(screen.getAllByText('not priced').length).toBeGreaterThan(0);});+ // An estimated plan usually UNDERSTATES its API cost, so a low number must+ // not read as a plan that was not worth its price.+ it('badges a plan whose API cost is not fully measured', () => {+ const rows = savings.families.map((f) => (f.family === 'codex' ? { ...f, source: 'estimate' } : { ...f, source: 'measured' }));+ render(<SubscriptionSavingsCard savings={{ ...savings, families: rows }} />);+ expect(screen.getAllByText('estimated').length).toBeGreaterThan(0);+ expect(screen.queryByText('partly estimated')).toBeNull();+ });+// The mobile layout used to omit the totals entirely, so a phone user could// price their plans and never see what they saved.it('renders the totals in both the mobile and desktop layouts', () => {diff --git a/server/index.js b/server/index.jsindex e82e25b94c..6ec2d2b214 100644--- a/server/index.js+++ b/server/index.js@@ -558,4 +558,7 @@ if (!isSmokeBoot()) {// token history current even when the usage page is never opened.import('./services/claudeCodeTranscriptUsage.js').then(({ startTranscriptUsageRefresh }) => startTranscriptUsageRefresh()).catch((err) => console.error(`❌ Claude Code transcript usage refresh could not start: ${err.message}`));+ // Same for interactive Grok / Antigravity sessions (local files, zero provider calls).+ import('./services/usageInteractiveScan.js').then(({ startInteractiveUsageRefresh }) => startInteractiveUsageRefresh())+ .catch((err) => console.error(`❌ Interactive usage scan could not start: ${err.message}`));}diff --git a/server/lib/README.md b/server/lib/README.mdindex bd162f91ef..e6bc3e2138 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -265,7 +265,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `providerRef.js` | Provider REFERENCE grammar (#7564, epic #7561) — the two spellings a `{ providerId, model, effort }` selection may name a provider by: a PRESET record id (`PRESET_ID_RE`, the slug `createProvider` mints) or a COMPOSITE `<harness>.<cli|tui|api>@<service-slug>[+<bootstrap-slug>]` (`COMPOSITE_ID_RE`; the bootstrap suffix only with a process method). `parseProviderRef(id)` → `{kind:'preset'}` / `{kind:'composite', harnessId, method, serviceSlug, bootstrapSlug}` / `null`, `isCompositeProviderId` / `isPresetProviderId`, `formatCompositeId(parts)` (throws on parts that would not parse back), `MAX_PROVIDER_REF_LENGTH`, and the two validation messages (`PROVIDER_REF_MESSAGE`, `PRESET_ONLY_MESSAGE`). The zod forms — `providerRefSchema` / `providerRefFieldSchema` (either grammar) and `presetProviderIdSchema` (preset-only, for `PUT /providers/active`, a record's `fallbackProvider`, an app's `taskTypeOverrides` pin) — live in `zodCompat.js` so `cosValidation.js` can share them. Pure and dependency-free; mirrored in `aiToolkit/internal/providerRef.js` (the toolkit may not import out) behind `providerRef.parity.test.js`. Resolution is host-side: `services/compositeProviders.js`. || `providerRouteRecipes.js` | Minting a FRESH executable route from a connection and a harness command recipe (#6369) — the reverse of `providerConnections.js`, which reads an existing record. `buildRouteRecord({harnessId, mode, providerId, name, connection})` materializes a connection's endpoint, credentials and backend marker into a DISABLED `data/providers.json` record through `PROVIDER_HARNESSES[].recipe`; `mintRouteIds` allocates readable ids keeping the `<stem>` / `<stem>-tui` pairing `providerModeGroups` recognizes; `bindingBlocker` is the pre-write refusal (no recipe, unsupported mode, a transport the backend does not declare, a credential the program requires); `CREATABLE_CONNECTION_KINDS` / `connectionKindLabel` / `connectionKindMarkers` bound the backends a route can honestly describe (`slotstream` and `vendor` deliberately excluded); `bindingProtocol` names the wire a binding needs. `materializeRoute({harness, method, serviceInstance, bootstrap?, selection?, overrides?})` (#7562) generalizes `buildRouteRecord` from a connection to a SERVICE instance: picks the harness's first compatible binding, writes base URL / credential / static env / backend markers / inline OpenCode config / Pi `--provider` per that binding plus the recipe's mode argv, stamps `harnessId` / `method` / `serviceId` / `servicePlan`, and — for a non-`api` method with a bootstrap app — the `credentialBootstrap` object `composeBootstrapSpawn` turns into `<bootstrap> run <harness> -- <args>`; throws typed errors (`HARNESS_SERVICE_INCOMPATIBLE`, `SERVICE_ENDPOINT_REQUIRED`, `SERVICE_CREDENTIAL_REQUIRED`, `SERVICE_CREDENTIAL_BOOTSTRAP_REQUIRED`) rather than minting a route that cannot run. `materializeRouteOutcome(input)` is the same body as a VERDICT (`{ record }` or `{ error }` — the typed 400 without the throw) for the composite resolver (#7564), which reads a refusal as the reason to show beside a saved selection. `routeDescribesService(profile, instance)` is the round-trip contract: fed back through `providerConnectionProfile`, a materialized record classifies onto the service it was built for. Pure: no I/O, no spawn, no provider call.| `providerRouteSettings.js` | The MODE-OVERRIDE half of a provider route (#6369) — the route-owned fields a human tunes per execution mode (`args`, `timeout`, `effort` and the `defaultModel`/`lightModel`/`mediumModel`/`heavyModel`/`ultraModel` pins), mirroring what the toolkit's `sharedModeUpdates` already declares mode-specific. `ROUTE_SETTING_FIELDS` / `ROUTE_SETTING_KEYS` / `routeSettingKeys(mode)` name the set (`args` reaches cli/tui only); `routeSettingsFor(provider)` reads it off a record with absent and cleared collapsing to `null`; `routeSettingsSchema` is the wire shape `GET /api/providers/management` publishes; `unsupportedRouteSettings` rejects a key the route's mode does not accept; and `routeSettingsRevision` is the stale-edit fingerprint — a hash of the values as they are in providers.json rather than a graph row revision, so an edit made through `/ai/edit/:providerId` is caught too. Connection-owned values and execution consent (`enabled`) are deliberately absent. Pure: no I/O.-| `providerTranscriptUsage.js` | Parsers for the session files the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `parseGrokTurns`/`parseGrokChatHistory`/`decodeGrokSessionDir` (`~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/`), `parseAgyTranscript`/`parseAgyHistory` (`~/.gemini/antigravity-cli/`), `parseKimiWireLog`/`parseKimiSessionIndex` (`~/.kimi-code/sessions/.../agents/<id>/wire.jsonl`, indexed by `~/.kimi-code/session_index.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, Codex's `total_token_usage` is cumulative and repeated, grok's `turn_completed.usage` has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its `_meta.totalTokens` is context occupancy and never billed. Antigravity writes no token fields at all, so its parser returns chars for the caller to estimate from. Kimi's `usage.record` lines are already discrete per-call deltas (no cumulative-snapshot trap), but split across one `wire.jsonl` per agent — a subagent's spend is never in its parent's file. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |+| `providerTranscriptUsage.js` | Parsers for the session files the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `parseGrokTurns`/`parseGrokChatHistory`/`decodeGrokSessionDir` (`~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/`), `parseAgyTranscript`/`parseAgyHistory` (`~/.gemini/antigravity-cli/`), `parseKimiWireLog`/`parseKimiSessionIndex` (`~/.kimi-code/sessions/.../agents/<id>/wire.jsonl`, indexed by `~/.kimi-code/session_index.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, Codex's `total_token_usage` is cumulative and repeated, grok's `turn_completed.usage` has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its `_meta.totalTokens` is context occupancy and never billed. Antigravity writes no token fields at all, so its parser returns chars for the caller to estimate from — including `contextChars`, the prompt each model call replays (priced as cache reads; omitting it made the plan read far cheaper than it was). Grok/Antigravity sessions PortOS never launched are billed by `services/usageInteractiveScan.js`. Kimi's `usage.record` lines are already discrete per-call deltas (no cumulative-snapshot trap), but split across one `wire.jsonl` per agent — a subagent's spend is never in its parent's file. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. || `opencodeCatalogCache.js` | Primes the on-disk catalog `opencode models` prints from — `primeOpencodeCatalogCache()` fetches OpenCode's `api.json` with Node's fetch and atomically writes `$XDG_CACHE_HOME/opencode/models.json` (`~/.cache` when unset). OpenCode refreshes that file from a forked task whose failures it swallows (`opencode models --refresh` still prints `Models cache refreshed`) and its HTTP client has no Happy Eyeballs, so a host advertising an unreachable IPv6 default route freezes the catalog indefinitely while other machines on the same account list newer models. Refuses to fetch or write when `OPENCODE_MODELS_PATH` / a custom `OPENCODE_MODELS_URL` / `OPENCODE_DISABLE_MODELS_FETCH` means PortOS cannot be sure which file OpenCode reads, when the file is under five minutes old, or when the body did not parse as a catalog — a stale list beats an empty picker. Never throws; the caller probes either way. || `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring model ids under the namespace the provider's marker selects: a local runtime (`ollama` / `mtplx` / `llama` / `vllm` / `sglang`, bare ids) or a hosted gateway from `providerGateways.js` (`vendor/model` ids kept whole). Fixes --model rejection. Also attaches the key for a key-bearing namespace, and pins `small_model` to the run model for a gateway so OpenCode's own side calls (titles, summarization) can't land on its built-in default — a billed model the operator never chose. Under a `no-tool` public-review profile it also applies `hardenOpencodeConfigForNoTool` — root `permission: deny`, an emptied tool map on every agent, `tool_call: false` on every declared model, and no MCP/plugins/share/autoupdate — which IS OpenCode's enforced tool-free recipe, since it ships no read-only argv flag (`providerVendors.js` pairs it with `run --agent` + `OPENCODE_PUBLIC_REVIEW_AGENT`). The harden step also copies `agent.build`'s generation settings onto that agent, so the stage's configured thinking effort reaches the model that actually runs. || `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localEndpointPort` + `isLocalInstanceHost`, and re-exports of `localBackendForProvider` / `localRuntimeKind` / `modelPinIsOffered` — all three now live in the browser-safe leaf `modelPinMembership.js` (a picker needs the pin rule and must not pull the endpoint graph below to get it), so existing importers here are untouched — `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — and `null` when that resolved endpoint fails `isLocalInstanceEndpoint` (an API provider on another machine has no local daemon to check, whatever its name says) — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. Optional `setupStateDetail` overrides `providerReadiness`'s per-state prose for a runtime whose local setup is not a model cache (vLLM's is a compose project); `standbyWhenStopped` marks an installed runtime such as llama.cpp whose stopped state is intentional standby rather than incomplete setup. |diff --git a/server/lib/providerTranscriptUsage.js b/server/lib/providerTranscriptUsage.jsindex 89434129e9..968060df4e 100644--- a/server/lib/providerTranscriptUsage.js+++ b/server/lib/providerTranscriptUsage.js@@ -43,10 +43,13 @@ export function claudeProjectSlug(cwd) {* Parse newline-delimited JSON, skipping blank lines and any line that doesn't* parse. A partially-flushed final line is the common case for a session still* being appended to, so an unparseable line is normal input, not an error.- * @param {string} text+ * Already-parsed entries pass straight through, so a caller that windows one+ * file several times parses it once.+ * @param {string|object[]} text* @returns {object[]}*/-function parseJsonLines(text) {+export function parseJsonLines(text) {+ if (Array.isArray(text)) return text;const out = [];for (const line of String(text || '').split('\n')) {const trimmed = line.trim();@@ -643,6 +646,18 @@ export function parseGrokChatHistory(jsonlText) {return { model, charsIn, charsOut, messages };}+/** Chars one agy step contributes: its content, plus thinking and tool-call args for a model turn. */+function agyStepChars(entry) {+ let chars = typeof entry.content === 'string' ? entry.content.length : 0;+ if (entry.type === 'PLANNER_RESPONSE') {+ chars += typeof entry.thinking === 'string' ? entry.thinking.length : 0;+ for (const call of entry.tool_calls || []) {+ chars += typeof call?.args === 'object' ? JSON.stringify(call.args).length : 0;+ }+ }+ return chars;+}+/*** ---------------------------------------------------------------------------* Antigravity (`agy`)@@ -662,9 +677,20 @@ export function parseGrokChatHistory(jsonlText) {* those tool-result steps carry `source: 'MODEL'` even though the text is the* tool's, which is why the split keys off `type`, not `source`.*+ * **Context replay.** An agent loop re-sends the whole conversation on every+ * model call, so counting each step's text once (the original estimate) missed+ * the bulk of the real bill. Each `PLANNER_RESPONSE` is one model call whose+ * prompt is everything before it, so `contextChars` sums, over every in-window+ * call, the chars that preceded it (prompt-cache reads; only the delta since the+ * previous call is fresh input, which is what `charsIn` holds). The running+ * context includes steps BEFORE the window, so a later run in a long+ * conversation still pays for the history it replays. The hidden system prompt+ * and tool schemas are not in the transcript, so this remains a floor, and+ * callers keep the row an `estimate`.+ ** @param {string} jsonlText raw file contents (may end mid-line)* @param {{ from?: number|null, to?: number|null, exclude?: {has:(k:string)=>boolean}|null }} [opts]- * @returns {{ charsIn: number, charsOut: number, messages: number,+ * @returns {{ charsIn: number, charsOut: number, contextChars: number, messages: number,* countedKeys: string[], steps: number }} `steps` is the number of steps SEEN* before windowing — the sentinel separating "unreadable/empty transcript"* from "read, and this window's share is zero".@@ -672,34 +698,36 @@ export function parseGrokChatHistory(jsonlText) {export function parseAgyTranscript(jsonlText, { from = null, to = null, exclude = null } = {}) {let charsIn = 0;let charsOut = 0;+ let contextChars = 0;let messages = 0;let steps = 0;const counted = [];+ // Chars of every step so far (windowed or not): the prompt the NEXT model call replays.+ let runningContext = 0;for (const [index, entry] of parseJsonLines(jsonlText).entries()) {if (typeof entry.type !== 'string') continue;steps += 1;+ const stepChars = agyStepChars(entry);+ const replayed = runningContext;+ runningContext += stepChars;if (!inWindow(toEpoch(entry.created_at), from, to)) continue;// `step_index` is the CLI's own ordinal and is stable across appends; the// parse ordinal only fills in for a step that somehow lacks one.const key = Number.isFinite(entry.step_index) ? `step-${entry.step_index}` : `#${index}`;if (exclude?.has(key)) continue;- let chars = typeof entry.content === 'string' ? entry.content.length : 0;if (entry.type === 'PLANNER_RESPONSE') {- chars += typeof entry.thinking === 'string' ? entry.thinking.length : 0;- for (const call of entry.tool_calls || []) {- chars += typeof call?.args === 'object' ? JSON.stringify(call.args).length : 0;- }- charsOut += chars;+ charsOut += stepChars;+ contextChars += replayed;messages += 1;} else {- charsIn += chars;+ charsIn += stepChars;}counted.push(key);}- return { charsIn, charsOut, messages, countedKeys: counted, steps };+ return { charsIn, charsOut, contextChars, messages, countedKeys: counted, steps };}/**diff --git a/server/lib/providerTranscriptUsage.test.js b/server/lib/providerTranscriptUsage.test.jsindex 63e0805536..a633a12054 100644--- a/server/lib/providerTranscriptUsage.test.js+++ b/server/lib/providerTranscriptUsage.test.js@@ -652,6 +652,22 @@ describe('parseAgyTranscript', () => {expect(parsed.countedKeys).toEqual(['step-0', 'step-1', 'step-2']);});+ it('prices each model call\'s replayed context, including steps before the window', () => {+ const text = [+ agyStep({ index: 0, type: 'USER_INPUT', createdAt: '2026-07-01T09:00:00Z', content: 'u'.repeat(100) }),+ agyStep({ index: 1, type: 'PLANNER_RESPONSE', createdAt: '2026-07-01T09:01:00Z', content: 'p'.repeat(50) }),+ agyStep({ index: 2, type: 'VIEW_FILE', createdAt: '2026-07-01T10:00:00Z', content: 'v'.repeat(200) }),+ agyStep({ index: 3, type: 'PLANNER_RESPONSE', createdAt: '2026-07-01T10:01:00Z', content: 'q'.repeat(30) })+ ].join('\n');+ // Whole transcript: call 1 replays 100 chars, call 2 replays 100+50+200.+ expect(parseAgyTranscript(text).contextChars).toBe(100 + 350);+ // A later run sees only call 2, but still pays for the history it replays.+ const later = parseAgyTranscript(text, { from: Date.parse('2026-07-01T09:30:00Z') });+ expect(later.contextChars).toBe(350);+ expect(later.charsIn).toBe(200);+ expect(later.charsOut).toBe(30);+ });+it('windows steps by created_at and reports how many it saw', () => {const text = [agyStep({ index: 0, type: 'GENERIC', createdAt: '2026-07-01T09:00:00Z', content: 'a'.repeat(80) }),diff --git a/server/lib/subscriptionSavings.js b/server/lib/subscriptionSavings.jsindex 8efd305f9c..e9920f653c 100644--- a/server/lib/subscriptionSavings.js+++ b/server/lib/subscriptionSavings.js@@ -90,17 +90,26 @@ export function costMultiplier(apiCost, periodCost) {* (uninstalled provider, `legacy`, `unknown`, a pay-as-you-go API provider)* lands in `unmatched` and is reported on its own rather than being credited to* a plan no one was paying.+ *+ * `sources` carries each family's provenance (`measured` / `estimate` /+ * `mixed`) so the savings table can say when a plan's API figure is a guess —+ * an estimated row usually UNDERSTATES, which reads as a plan that "cost more+ * than it was worth".*/export function attributeReportCostToFamilies(report) {const byFamily = new Map();+ const sources = new Map();let unmatched = 0;for (const row of report?.providers || []) {const cost = Number(row?.estimatedCost) || 0;if (cost <= 0) continue;if (!row.family) { unmatched += cost; continue; }byFamily.set(row.family, (byFamily.get(row.family) || 0) + cost);+ const source = row.source || 'estimate';+ const seen = sources.get(row.family);+ sources.set(row.family, seen && seen !== source ? 'mixed' : source);}- return { byFamily, unmatched };+ return { byFamily, sources, unmatched };}/**@@ -134,6 +143,7 @@ export function buildSubscriptionSavings({ entries = [], range, unmatchedApiCostconfigured,periodCost,apiCost,+ source: entry.source ?? null,savings: configured ? roundCents(apiCost - periodCost) : 0,multiplier: configured ? costMultiplier(apiCost, periodCost) : null};diff --git a/server/lib/subscriptionSavings.test.js b/server/lib/subscriptionSavings.test.jsindex 488f0aecc8..9f694f825e 100644--- a/server/lib/subscriptionSavings.test.js+++ b/server/lib/subscriptionSavings.test.js@@ -103,7 +103,20 @@ describe('attributeReportCostToFamilies', () => {});it('is empty-safe on a missing report', () => {- expect(attributeReportCostToFamilies(null)).toEqual({ byFamily: new Map(), unmatched: 0 });+ expect(attributeReportCostToFamilies(null)).toEqual({ byFamily: new Map(), sources: new Map(), unmatched: 0 });+ });++ it('reports a family as estimated or mixed unless every row is measured', () => {+ const { sources } = attributeReportCostToFamilies({+ providers: [+ { family: 'agy', estimatedCost: 1, source: 'estimate' },+ { family: 'grok', estimatedCost: 1, source: 'measured' },+ { family: 'grok', estimatedCost: 1, source: 'estimate' },+ { family: 'claude', estimatedCost: 1, source: 'measured' },+ { family: 'codex', estimatedCost: 1 }+ ]+ });+ expect(Object.fromEntries(sources)).toEqual({ agy: 'estimate', grok: 'mixed', claude: 'measured', codex: 'estimate' });});});diff --git a/server/services/subscriptionCosts.js b/server/services/subscriptionCosts.jsindex 4178efae9c..46e8f5aeab 100644--- a/server/services/subscriptionCosts.js+++ b/server/services/subscriptionCosts.js@@ -104,11 +104,12 @@ const utcToday = () => new Date().toISOString().split('T')[0];*/export async function getSubscriptionSavings({ report, providers = [], from = null, to = null, firstActivityDay = null, today = utcToday() }) {const costs = await getSubscriptionCosts();- const { byFamily, unmatched } = attributeReportCostToFamilies(report);+ const { byFamily, sources, unmatched } = attributeReportCostToFamilies(report);const entries = resolveSubscriptionFamilies(providers, costs, [...byFamily.keys()]).map((f) => ({...f,monthlyCost: costs[f.family] ?? 0,- apiCost: byFamily.get(f.family) || 0+ apiCost: byFamily.get(f.family) || 0,+ source: sources.get(f.family)}));return buildSubscriptionSavings({entries,diff --git a/server/services/usage.js b/server/services/usage.jsindex 9d72e34ce8..da87b4f4a5 100644--- a/server/services/usage.js+++ b/server/services/usage.js@@ -323,6 +323,20 @@ export function getReconciledUsageRunIds() {* A separate marker from `reconciledRuns` on purpose: the sibling pass has to be* able to run on a run whose own transcript was reconciled long ago (#5831).*/+/**+ * Drop sibling markers that only guarded a single apply — the interactive scan's+ * synthetic ids, which its own watermark makes redundant once the batch lands.+ * Left in place they would grow `usage.json` by a key per family per day per scan.+ */+export async function forgetSiblingReconciledUsageRuns(runIds = []) {+ if (!usageData?.siblingReconciledRuns) return;+ let dropped = 0;+ for (const runId of runIds) {+ if (delete usageData.siblingReconciledRuns[runId]) dropped++;+ }+ if (dropped > 0) await saveUsage();+}+export function getSiblingReconciledUsageRunIds() {return Object.keys(usageData?.siblingReconciledRuns || {});}diff --git a/server/services/usageInteractiveScan.js b/server/services/usageInteractiveScan.jsnew file mode 100644index 0000000000..4824c1d295--- /dev/null+++ b/server/services/usageInteractiveScan.js@@ -0,0 +1,252 @@+import { stat } from 'fs/promises';+import { homedir } from 'os';+import { join } from 'path';+import { atomicWrite, PATHS, readJSONFile, tryReadFile } from '../lib/fileUtils.js';+import { createMutex } from '../lib/asyncMutex.js';+import {+ UNKNOWN_MODEL,+ decodeGrokSessionDir,+ parseAgyHistory,+ parseAgyTranscript,+ parseGrokTurns,+ parseJsonLines,+ totalTranscriptTokens+} from '../lib/providerTranscriptUsage.js';+import {+ WINDOW_SLACK_MS,+ agyEstimatedBuckets,+ cwdMatches,+ listSubdirs,+ recordsFromMeasured,+ resolveFamilyProvider+} from './usageReconciler.js';+import { applyHistoricalUsageCorrections, forgetSiblingReconciledUsageRuns } from './usage.js';++/**+ * Attribute Grok and Antigravity sessions that PortOS never launched.+ *+ * `usageReconciler.js` only reads a CLI's session store inside a PortOS run's+ * own workspace and time window, so everything the user does in a terminal —+ * the interactive `grok` / `agy` sessions that actually burn the weekly quota —+ * never reached the cost report, and both plans read as far cheaper than their+ * subscription. This scan walks every session on the machine and bills what the+ * run path did NOT.+ *+ * Exclusivity with the run path is by TIME, not by ledger: a run's claim ledger+ * is in-memory and lost on restart, so a message is billed here only when its+ * timestamp falls outside every PortOS run window (widened by the same slack the+ * run path uses) in that session's cwd. A per-family watermark then makes each+ * scan cover only new time, so nothing is billed by two scans. Reads local files+ * only — no provider calls.+ *+ * The exclusion is only as tight as the run path's own window: both use+ * `WINDOW_SLACK_MS`, so widening one without the other opens a gap or an overlap.+ *+ * Results land per UTC day through `applyHistoricalUsageCorrections` (its+ * sibling-add path), so a first scan over past weeks fills the right days+ * instead of dumping a month onto today.+ */++export const INTERACTIVE_SCAN_FILE = join(PATHS.data, 'usage-interactive-scan.json');++const FAMILIES = ['grok', 'agy'];+const DAY_MS = 86_400_000;+// A CLI flushes an event slightly after it stamps it; leaving the newest few+// minutes for the next scan keeps a still-being-written turn from being cut.+const SETTLE_MS = 5 * 60_000;+// First scan reaches back this far; later scans start at the stored watermark.+const FIRST_SCAN_LOOKBACK_DAYS = 35;++const withLock = createMutex();+const yieldToEventLoop = () => new Promise((resolve) => setImmediate(resolve));++/** Pure: `[from, to]` minus every window, as inclusive ms intervals. */+export function subtractWindows(from, to, windows) {+ let pieces = [[from, to]];+ for (const [ws, we] of windows) {+ pieces = pieces.flatMap(([a, b]) => {+ if (we < a || ws > b) return [[a, b]];+ const out = [];+ if (ws > a) out.push([a, ws - 1]);+ if (we < b) out.push([we + 1, b]);+ return out;+ });+ }+ return pieces.filter(([a, b]) => b >= a);+}++/** Pure: split an inclusive interval at UTC midnights → `[{ day, from, to }]`. */+export function splitByUtcDay(from, to) {+ const out = [];+ for (let cursor = from; cursor <= to;) {+ const dayStart = Math.floor(cursor / DAY_MS) * DAY_MS;+ const end = Math.min(to, dayStart + DAY_MS - 1);+ out.push({ day: new Date(dayStart).toISOString().slice(0, 10), from: cursor, to: end });+ cursor = end + 1;+ }+ return out;+}++/** Every PortOS run's `[start, end]` (slack applied) by workspace, for runs touching `[from, now]`. */+async function loadRunWindows(runsDir, from, now) {+ const byCwd = new Map();+ for (const name of await listSubdirs(runsDir)) {+ const dir = join(runsDir, name);+ // A run directory untouched since before the window cannot overlap it.+ const info = await stat(dir).catch(() => null);+ if (!info || info.mtimeMs < from - DAY_MS) continue;+ const metadata = await readJSONFile(join(dir, 'metadata.json'), null);+ const start = Date.parse(metadata?.startTime || '');+ if (!metadata?.workspacePath || Number.isNaN(start)) continue;+ // No endTime yet: the run is still going, so its window is open-ended.+ const end = Date.parse(metadata.endTime || '');+ const window = [start - WINDOW_SLACK_MS, (Number.isNaN(end) ? now : end) + WINDOW_SLACK_MS];+ if (!byCwd.has(metadata.workspacePath)) byCwd.set(metadata.workspacePath, []);+ byCwd.get(metadata.workspacePath).push(window);+ }+ return byCwd;+}++const windowsFor = (byCwd, sessionCwd) => {+ const out = [];+ for (const [workspacePath, windows] of byCwd) {+ if (cwdMatches(sessionCwd, workspacePath)) out.push(...windows);+ }+ return out;+};++/** Session files written since `from`: `{ cwd, path, mtimeMs, birthMs }`. */+async function listSessions(family, home, from) {+ const sessions = [];+ const add = async (cwd, path) => {+ const info = await stat(path).catch(() => null);+ if (!info || info.mtimeMs < from) return;+ sessions.push({ cwd, path, mtimeMs: info.mtimeMs, birthMs: info.birthtimeMs || info.mtimeMs });+ };+ if (family === 'grok') {+ const root = join(home, '.grok', 'sessions');+ for (const dirName of await listSubdirs(root)) {+ const cwd = decodeGrokSessionDir(dirName);+ const cwdDir = join(root, dirName);+ for (const sessionId of await listSubdirs(cwdDir)) {+ await add(cwd, join(cwdDir, sessionId, 'updates.jsonl'));+ }+ }+ } else {+ const root = join(home, '.gemini', 'antigravity-cli');+ const historyText = await tryReadFile(join(root, 'history.jsonl'));+ for (const conversation of historyText ? parseAgyHistory(historyText) : []) {+ await add(conversation.workspace, join(root, 'brain', conversation.conversationId, '.system_generated', 'logs', 'transcript.jsonl'));+ }+ }+ return sessions;+}++const BUCKET_FIELDS = ['messages', 'tokensIn', 'tokensOut', 'cacheReadTokens', 'cacheWriteTokens'];+const addBuckets = (target, buckets) => {+ for (const field of BUCKET_FIELDS) target[field] = (target[field] || 0) + (buckets[field] || 0);+};++/** One session file's billed buckets per `{ day, model }` inside `[from, to]`, minus run windows. */+async function parseSession(family, session, from, to, byCwd) {+ const text = await tryReadFile(session.path);+ if (!text) return [];+ // Parsed once and windowed per day slice: re-splitting a multi-MB file per+ // slice would cost ~35 parses of it on a first scan.+ const entries = parseJsonLines(text);+ // A file cannot hold anything before it existed or after it was last written.+ // A birth time AFTER the last write means the file was copied or restored, so+ // it says nothing about when its content began — read from the window start.+ const lo = session.birthMs <= session.mtimeMs ? Math.max(from, session.birthMs - DAY_MS) : from;+ const hi = Math.min(to, session.mtimeMs + WINDOW_SLACK_MS);+ const results = [];+ for (const [a, b] of subtractWindows(lo, hi, windowsFor(byCwd, session.cwd))) {+ for (const slice of splitByUtcDay(a, b)) {+ if (family === 'grok') {+ const parsed = parseGrokTurns(entries, { from: slice.from, to: slice.to });+ for (const [model, buckets] of Object.entries(parsed.byModel)) {+ if (totalTranscriptTokens(buckets) > 0) results.push({ day: slice.day, model, buckets });+ }+ } else {+ const buckets = agyEstimatedBuckets(parseAgyTranscript(entries, { from: slice.from, to: slice.to }));+ if (totalTranscriptTokens(buckets) > 0) results.push({ day: slice.day, model: UNKNOWN_MODEL, buckets });+ }+ }+ }+ return results;+}++/**+ * Bill every un-launched Grok / Antigravity session since the last scan.+ *+ * Resolves with `{ families: { [family]: { days, tokens } } }`. A family with no+ * configured provider is skipped WITHOUT advancing its watermark, so enabling+ * one later still bills what was skipped (within the first-scan lookback).+ */+export function refreshInteractiveUsage({ home = homedir(), runsDir = PATHS.runs, providers = null, now = Date.now() } = {}) {+ return withLock(async () => {+ const state = await readJSONFile(INTERACTIVE_SCAN_FILE, { watermarks: {} });+ const watermarks = { ...(state?.watermarks || {}) };+ const to = now - SETTLE_MS;+ // Not caught: a provider-list failure must surface, not read as "none configured".+ const providerList = providers ?? await import('./providers.js').then((m) => m.listProviders());+ const summary = { families: {} };+ const byCwd = await loadRunWindows(runsDir, now - FIRST_SCAN_LOOKBACK_DAYS * DAY_MS, now);++ for (const family of FAMILIES) {+ if (!resolveFamilyProvider(providerList, family)) continue;+ const from = watermarks[family] != null ? watermarks[family] + 1 : now - FIRST_SCAN_LOOKBACK_DAYS * DAY_MS;+ if (to < from) continue;++ const perDay = new Map();+ for (const session of await listSessions(family, home, from)) {+ for (const { day, model, buckets } of await parseSession(family, session, from, to, byCwd)) {+ if (!perDay.has(day)) perDay.set(day, { byModel: {} });+ const dayTotals = perDay.get(day);+ addBuckets(dayTotals, buckets);+ dayTotals.byModel[model] ??= {};+ addBuckets(dayTotals.byModel[model], buckets);+ }+ // A first scan parses many multi-MB files back to back; let the server breathe.+ await yieldToEventLoop();+ }++ const corrections = [];+ let tokens = 0;+ for (const [day, totals] of perDay) {+ const measured = { ...totals, source: family === 'grok' ? 'measured' : 'estimate', model: null };+ const provider = resolveFamilyProvider(providerList, family, measured);+ if (!provider) continue;+ tokens += totalTranscriptTokens(totals);+ corrections.push({+ // Synthetic id: only satisfies the sibling-add path's idempotency marker+ // for the duration of one apply (forgotten right after).+ runId: `interactive:${family}:${day}:${from}-${to}`,+ day,+ providerId: provider.id,+ siblings: recordsFromMeasured(provider.id, provider.defaultModel ?? null, measured, 'sibling'),+ siblingScanned: true+ });+ }+ if (corrections.length) {+ await applyHistoricalUsageCorrections(corrections);+ // The watermark, not these ids, prevents re-billing — don't leave a key per scan behind.+ await forgetSiblingReconciledUsageRuns(corrections.map((c) => c.runId));+ }+ watermarks[family] = to;+ summary.families[family] = { days: corrections.length, tokens };+ if (tokens > 0) console.log(`💸 Interactive ${family} usage billed: ${tokens} tokens over ${corrections.length} day(s)`);+ }++ await atomicWrite(INTERACTIVE_SCAN_FILE, { watermarks, updatedAt: new Date(now).toISOString() });+ return summary;+ });+}++export function startInteractiveUsageRefresh({ intervalMs = 30 * 60_000, firstDelayMs = 90_000 } = {}) {+ const run = () => refreshInteractiveUsage().catch((err) => {+ console.error(`❌ Interactive usage scan failed: ${err.message}`);+ });+ setTimeout(run, firstDelayMs).unref();+ setInterval(run, intervalMs).unref();+}diff --git a/server/services/usageInteractiveScan.test.js b/server/services/usageInteractiveScan.test.jsnew file mode 100644index 0000000000..b9957829e1--- /dev/null+++ b/server/services/usageInteractiveScan.test.js@@ -0,0 +1,123 @@+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';++const { makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-interactive-usage-' });+vi.mock('../lib/fileUtils.js', async () => makeProxy(await vi.importActual('../lib/fileUtils.js')));+const applied = [];+vi.mock('./usage.js', () => ({+ applyHistoricalUsageCorrections: vi.fn(async (corrections) => { applied.push(...corrections); return { corrected: corrections.length, correctedRunIds: [] }; }),+ forgetSiblingReconciledUsageRuns: vi.fn(async () => {})+}));+afterAll(cleanup);++const { refreshInteractiveUsage, subtractWindows, splitByUtcDay, INTERACTIVE_SCAN_FILE } = await import('./usageInteractiveScan.js');++const GROK = { id: 'grok-cli', type: 'cli', command: 'grok', enabled: true, defaultModel: 'example-grok-model' };+const AGY = { id: 'antigravity-cli', type: 'cli', command: 'agy', enabled: true, defaultModel: 'example-agy-model' };+// Real time: a file's birth time can't be faked, and the scan prunes on it.+const NOW = Date.now();+const HOUR = 3_600_000;+const dayOf = (ms) => new Date(ms).toISOString().slice(0, 10);+// Within the day before the file was created: the scan prunes on birth time (minus a day).+const P1 = NOW - 20 * HOUR;+const P2 = NOW - HOUR;+const P3 = NOW - HOUR + 5 * 60_000;+const CWD = '/example/workspace';++// Input varies per turn so the stream is not (accidentally) monotonic, which the parser reads as cumulative.+const grokTurn = (promptId, ms, output, input = 1000) => JSON.stringify({+ timestamp: Math.round(ms / 1000),+ params: {+ sessionId: 's1',+ update: {+ sessionUpdate: 'turn_completed',+ prompt_id: promptId,+ usage: { inputTokens: input, outputTokens: output, cachedReadTokens: 400, modelUsage: { 'example-grok-model': {} } }+ },+ _meta: { agentTimestampMs: ms }+ }+});++describe('window helpers', () => {+ it('subtracts run windows from an interval', () => {+ expect(subtractWindows(0, 100, [[20, 30], [50, 60]])).toEqual([[0, 19], [31, 49], [61, 100]]);+ expect(subtractWindows(0, 100, [[-5, 200]])).toEqual([]);+ expect(subtractWindows(0, 100, [[300, 400]])).toEqual([[0, 100]]);+ });++ it('splits at UTC midnight', () => {+ const day = 86_400_000;+ const start = Date.parse('2026-09-09T23:00:00Z');+ expect(splitByUtcDay(start, start + day).map((s) => s.day)).toEqual(['2026-09-09', '2026-09-10']);+ });+});++describe('refreshInteractiveUsage', () => {+ let home;+ let runsDir;+ beforeEach(async () => {+ applied.length = 0;+ home = await mkdtemp(join(tmpdir(), 'interactive-home-'));+ runsDir = await mkdtemp(join(tmpdir(), 'interactive-runs-'));+ await rm(INTERACTIVE_SCAN_FILE, { force: true });+ const dir = join(home, '.grok', 'sessions', encodeURIComponent(CWD), 'session-1');+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, 'updates.jsonl'), [+ grokTurn('p1', P1, 100),+ grokTurn('p2', P2, 200, 800),+ grokTurn('p3', P3, 400, 900)+ ].join('\n'));+ });+ afterEach(async () => {+ await rm(home, { recursive: true, force: true });+ await rm(runsDir, { recursive: true, force: true });+ });++ it('bills terminal sessions per UTC day, outside PortOS run windows, exactly once', async () => {+ // A PortOS run covers p3 in this cwd: the run path owns it, so the scan must not.+ const runDir = join(runsDir, 'run-1');+ await mkdir(runDir, { recursive: true });+ await writeFile(join(runDir, 'metadata.json'), JSON.stringify({+ workspacePath: CWD, startTime: new Date(P3 - 60_000).toISOString(), endTime: new Date(P3 + 60_000).toISOString()+ }));++ const first = await refreshInteractiveUsage({ home, runsDir, providers: [GROK], now: NOW });+ // Per turn: 600 fresh in (1000 - 400 cached) + 400 cache read + output.+ expect(first.families.grok.tokens).toBe((600 + 400 + 100) + (400 + 400 + 200));+ const byDay = Object.fromEntries(applied.map((c) => [c.day, c.siblings[0]]));+ expect(applied.every((c) => [dayOf(P1), dayOf(P2)].includes(c.day))).toBe(true);+ expect(applied[0].siblings[0]).toMatchObject({ providerId: 'grok-cli', cacheReadTokens: 400, source: 'measured' });+ // p3 fell inside the run window, so the scan bills only p2 (and p1) — never p3's 400.+ expect(Object.values(byDay).reduce((sum, r) => sum + r.tokensOut, 0)).toBe(300);++ applied.length = 0;+ await refreshInteractiveUsage({ home, runsDir, providers: [GROK], now: NOW + 60_000 });+ expect(applied).toEqual([]);+ });++ it('leaves a family with no provider unbilled and its watermark unmoved', async () => {+ const summary = await refreshInteractiveUsage({ home, runsDir, providers: [], now: NOW });+ expect(summary.families).toEqual({});+ await refreshInteractiveUsage({ home, runsDir, providers: [GROK], now: NOW });+ expect(applied.length).toBeGreaterThan(0);+ });++ it('estimates Antigravity from the transcript, replayed context as cache reads', async () => {+ const root = join(home, '.gemini', 'antigravity-cli');+ const logs = join(root, 'brain', 'conv-1', '.system_generated', 'logs');+ await mkdir(logs, { recursive: true });+ await writeFile(join(root, 'history.jsonl'), JSON.stringify({ timestamp: NOW, workspace: CWD, conversationId: 'conv-1' }));+ const step = (i, type, at, content) => JSON.stringify({ step_index: i, type, created_at: at, content });+ await writeFile(join(logs, 'transcript.jsonl'), [+ step(0, 'USER_INPUT', new Date(NOW - 2 * HOUR).toISOString(), 'u'.repeat(400)),+ step(1, 'PLANNER_RESPONSE', new Date(NOW - 2 * HOUR + 60_000).toISOString(), 'p'.repeat(200))+ ].join('\n'));++ await refreshInteractiveUsage({ home, runsDir, providers: [AGY], now: NOW });+ const record = applied.find((c) => c.providerId === 'antigravity-cli').siblings[0];+ expect(record).toMatchObject({ source: 'estimate', tokensIn: 100, tokensOut: 50, cacheReadTokens: 100, model: 'example-agy-model' });+ });+});diff --git a/server/services/usageReconciler.js b/server/services/usageReconciler.jsindex 7ec1e2b86b..596f4c7915 100644--- a/server/services/usageReconciler.js+++ b/server/services/usageReconciler.js@@ -72,7 +72,7 @@ import { markUsageRunReconciled, recordRunUsage } from './usage.js';// 144 once this slack is applied. Two overlapping runs would each fold the whole// overlap and double-bill it, so exclusivity is enforced separately by the// per-message claim below, not by the window.-const WINDOW_SLACK_MS = 60_000;+export const WINDOW_SLACK_MS = 60_000;// Messages already billed to a run, keyed `<transcript-key>:<message-key>`.// A transcript message must be counted exactly ONCE across every run that can@@ -137,7 +137,7 @@ export function mergeUsageClaims({ claimedMessages: claimed = [], codexHighWater// install root — is what the CLI records; matching is therefore exact on the// recorded `workspacePath`, with a prefix allowance for a CLI invoked in a// subdirectory of the workspace (`server/`, `client/`).-const cwdMatches = (transcriptCwd, workspacePath) => {+export const cwdMatches = (transcriptCwd, workspacePath) => {if (!transcriptCwd || !workspacePath) return false;if (transcriptCwd === workspacePath) return true;return transcriptCwd.startsWith(`${workspacePath}/`);@@ -286,7 +286,7 @@ const listDir = async (dir) => readdir(dir).catch(() => []);* `listDir` there hands that filename to callers expecting a session id, which* then fails `ENOTDIR` trying to read `<file>/summary.json` (#6218).*/-const listSubdirs = async (dir) => {+export const listSubdirs = async (dir) => {const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);};@@ -321,6 +321,20 @@ function codexDateDirs(root, fromMs, toMs) {return [...days];}+/**+ * Token buckets for a `parseAgyTranscript` result. Antigravity writes no token+ * counts, so every figure is chars/4 — but the model calls' replayed context is+ * priced as cache reads (`contextChars`) rather than dropped, since dropping it+ * is what made the plan read as cheaper than its subscription.+ */+export const agyEstimatedBuckets = (parsed) => ({+ messages: parsed.messages,+ tokensIn: estimateTokensFromChars(parsed.charsIn),+ tokensOut: estimateTokensFromChars(parsed.charsOut),+ cacheReadTokens: estimateTokensFromChars(parsed.contextChars),+ cacheWriteTokens: 0+});+/*** Sum every transcript that overlaps a run's window in its working directory.* Returns null when no transcript could be attributed (so the caller keeps its@@ -514,13 +528,7 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, famconst text = await tryReadFile(transcriptPath);if (!text) continue;const parsed = parseAgyTranscript(text, { from, to, exclude: excludeFor(transcriptPath) });- const estimated = {- messages: parsed.messages,- tokensIn: estimateTokensFromChars(parsed.charsIn),- tokensOut: estimateTokensFromChars(parsed.charsOut),- cacheReadTokens: 0,- cacheWriteTokens: 0- };+ const estimated = agyEstimatedBuckets(parsed);if (totalTranscriptTokens(estimated) === 0) continue;reserveFrom(transcriptPath, parsed);// No model is named anywhere in the transcript — the UNKNOWN_MODEL bucket@@ -651,7 +659,7 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam* and provider ids alone can't express it. `recordRunUsage` reads only the* count fields, so the marker never reaches usage.json.*/-function recordsFromMeasured(providerId, recordedModel, measured, role) {+export function recordsFromMeasured(providerId, recordedModel, measured, role) {// A family that mixed a measured session with an estimated one reports// `mixed` on every record it produced: the two shapes fold into the same// per-model buckets, so no record can honestly claim to be purely measured.diff --git a/server/services/usageReconciler.test.js b/server/services/usageReconciler.test.jsindex dc145a70e0..2e62925d29 100644--- a/server/services/usageReconciler.test.js+++ b/server/services/usageReconciler.test.js@@ -1405,6 +1405,8 @@ describe('nested sibling-family attribution', () => {expect(agy.source).toBe('estimate');expect(agy.tokensIn).toBe(100);expect(agy.tokensOut).toBe(50);+ // The planner call replays the 400-char user turn: 100 tokens of cache read.+ expect(agy.cacheReadTokens).toBe(100);// The transcript names no model, so the provider's own default is used.expect(agy.model).toBe('example-agy-model');});