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
feat: report free-tier usage on the Usage page from ledger with block-based estimates (#7408)
[._.]/ Adam Eivy20c2483bc50b
diff --git a/client/src/components/usage/FreeTierUsageCard.jsx b/client/src/components/usage/FreeTierUsageCard.jsxnew file mode 100644index 0000000000..6ff7abe6be--- /dev/null+++ b/client/src/components/usage/FreeTierUsageCard.jsx@@ -0,0 +1,166 @@+import Pill from '../ui/Pill';+import { formatCompactCount, timeAgo } from '../../utils/formatters';++// A free-tier token count that was never reported must never render as a+// confident zero: `—` means "the provider exposes no usage API and PortOS+// observed nothing", while a measured zero stays `0`. The `source` comes from+// the usage ledger (`measured` = the run's own event stream or transcript,+// anything else = estimated from prompt/stdout size).+function FreeTokens({ value, source }) {+ if (typeof value === 'number' && value > 0) {+ return <span className="text-white font-medium">{formatCompactCount(value)}</span>;+ }+ if (source === 'measured') {+ return <span className="text-white font-medium">0</span>;+ }+ return (+ <span+ className="text-gray-500"+ title="Not reported — this provider exposes no usage API, so PortOS tracks what its own runs observed"+ >+ —+ </span>+ );+}++const SOURCE_LABELS = {+ measured: { label: 'Measured', tone: 'success', title: 'Token counts read from the run itself' },+ mixed: { label: 'Part est.', tone: 'warning', title: 'Output tokens measured from the run, input estimated' },+ estimate: { label: 'Estimated', tone: 'context', title: 'Estimated from prompt length and captured output' }+};++function SourcePill({ source, className = '' }) {+ const meta = SOURCE_LABELS[source] || SOURCE_LABELS.estimate;+ return (+ <Pill tone={meta.tone} size="xs" className={className} title={meta.title}>{meta.label}</Pill>+ );+}++// Ledger volume since an observed block — the estimated-quota signal for a+// provider with no usage API: how much has run since it last refused.+function BlockVolume({ volume }) {+ if (!volume) return null;+ const queries = (volume.sessions || 0) + (volume.messages || 0);+ return (+ <span title="Ledger volume since this block — an estimate, not a provider reading">+ {formatCompactCount(queries)} queries · {formatCompactCount(volume.tokensIn || 0)} in /{' '}+ {formatCompactCount(volume.tokensOut || 0)} out since+ </span>+ );+}++function BlockRow({ block }) {+ return (+ <div className="py-1.5 border-b border-port-border last:border-0 text-xs sm:text-sm">+ <div className="flex items-center justify-between gap-2">+ <span className="min-w-0 truncate text-white">+ {block.providerId}+ {block.model && <span className="font-mono text-gray-400"> · {block.model}</span>}+ </span>+ <span className="shrink-0 text-gray-500">{timeAgo(block.at ? new Date(block.at) : null, 'unknown time')}</span>+ </div>+ <div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] sm:text-xs text-gray-400">+ {block.resetHint && <span title="What the provider said about recovery">provider said: {block.resetHint}</span>}+ <BlockVolume volume={block.volumeSince} />+ {!block.volumeSince && <span className="text-gray-500">volume unknown</span>}+ </div>+ </div>+ );+}++function ProviderRow({ provider }) {+ return (+ <div className="py-1.5 border-b border-port-border last:border-0">+ <div className="flex items-center justify-between gap-2">+ <div className="flex min-w-0 items-center gap-2">+ <span className="truncate text-sm font-medium text-white">{provider.name}</span>+ <Pill tone="success" size="xs" className="shrink-0 uppercase tracking-wide">Free</Pill>+ <SourcePill source={provider.source} className="shrink-0" />+ </div>+ <span className="shrink-0 text-xs text-gray-400">+ {formatCompactCount(provider.sessions || 0)} queries · {formatCompactCount(provider.messages || 0)} msgs+ </span>+ </div>+ <div className="mt-1 grid grid-cols-2 gap-2 text-xs text-gray-400">+ <div>+ <span className="block text-[10px] text-gray-500">Tokens (In / Out)</span>+ <FreeTokens value={provider.tokensIn} source={provider.source} />+ {' / '}+ <FreeTokens value={provider.tokensOut} source={provider.source} />+ </div>+ <div>+ <span className="block text-[10px] text-gray-500">Cache Read / Write</span>+ <FreeTokens value={provider.cacheReadTokens} source={provider.source} />+ {' / '}+ <FreeTokens value={provider.cacheWriteTokens} source={provider.source} />+ </div>+ </div>+ {(provider.models || []).length > 0 && (+ <div className="mt-1.5 space-y-1 border-t border-port-border/40 pt-1.5">+ {provider.models.map((m) => (+ <div key={m.model} className="flex items-center justify-between gap-2 text-xs text-gray-400">+ <span className="min-w-0 truncate font-mono text-[11px] text-gray-300" title={m.model}>{m.model}</span>+ <span className="flex shrink-0 items-center gap-2">+ <SourcePill source={m.source} />+ <span>{formatCompactCount((m.sessions || 0) + (m.messages || 0))} q</span>+ <FreeTokens value={m.tokensIn} source={m.source} />+ {'/'}+ <FreeTokens value={m.tokensOut} source={m.source} />+ </span>+ </div>+ ))}+ </div>+ )}+ </div>+ );+}++// Free-tier counterpart of the subscription-quota cards above it: queries and+// tokens per free-tier provider/model over the selected period, plus the+// observed limit blocks that stand in for a quota meter where the provider+// exposes no usage API. Everything here is ledger-derived — no provider call+// is made to build it (AI Provider Usage Policy), and every figure carries+// its measured/estimated provenance.+export default function FreeTierUsageCard({ freeTier }) {+ const providers = freeTier?.providers || [];+ const blocks = freeTier?.blocks || [];+ return (+ <div className="rounded-xl border border-port-border bg-port-card p-3 sm:p-4">+ <div className="mb-1 flex items-center justify-between gap-2">+ <h3 className="text-sm font-medium text-gray-400">Free-tier usage</h3>+ <Pill tone="context" size="xs" title="Counts come from the PortOS usage ledger, not from a provider usage API — no provider calls were made">+ Ledger-tracked+ </Pill>+ </div>+ <p className="mb-2 text-[10px] text-gray-500 sm:text-xs">+ Queries and tokens on free-tier quotas (e.g. opencode zen) over the selected period — tracked locally because+ these providers expose no usage API. Unreported counts render as —, never 0.+ </p>+ {providers.length === 0 ? (+ <div className="py-2 text-sm text-gray-500">No free-tier usage recorded in this period.</div>+ ) : (+ <div aria-label="Free-tier provider usage">+ {providers.map((provider) => (+ <ProviderRow key={provider.id} provider={provider} />+ ))}+ </div>+ )}+ {blocks.length > 0 && (+ <div className="mt-3 border-t border-port-border pt-2">+ <h4 className="mb-1 text-xs font-medium text-gray-400">+ Observed blocks <span className="font-normal text-gray-500">— estimated quota signal, not a provider meter</span>+ </h4>+ <div aria-label="Observed free-tier blocks">+ {blocks.map((block, i) => (+ <BlockRow key={`${block.providerId}-${block.at}-${i}`} block={block} />+ ))}+ </div>+ <p className="mt-1 text-[10px] text-gray-500">+ A block is a usage-limit refusal PortOS actually saw. Transient retries are not blocks. Volume since a+ block is ledger-derived and understates providers whose runs carry no token counts.+ </p>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/usage/FreeTierUsageCard.test.jsx b/client/src/components/usage/FreeTierUsageCard.test.jsxnew file mode 100644index 0000000000..76b230f9d5--- /dev/null+++ b/client/src/components/usage/FreeTierUsageCard.test.jsx@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest';+import { render, screen } from '@testing-library/react';+import FreeTierUsageCard from './FreeTierUsageCard';++// The unknown-render contract (#7408): a free-tier count that was never+// reported renders as —, never as a confident 0. Only a measured zero may+// render as 0.+describe('FreeTierUsageCard unknown counts', () => {+ const provider = (tokensIn, tokensOut, source) => ({+ id: 'opencode-zen-cli',+ name: 'OpenCode Zen CLI',+ free: true,+ sessions: 2,+ messages: 3,+ tokensIn,+ tokensOut,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ source,+ models: []+ });++ it('renders unreported estimate counts as —, never 0', () => {+ const { container } = render(+ <FreeTierUsageCard freeTier={{ basis: 'ledger', providers: [provider(0, 0, 'estimate')], blocks: [] }} />+ );+ const dashes = [...container.querySelectorAll('span')].filter((el) => el.textContent === '—');+ expect(dashes.length).toBeGreaterThan(0);+ expect(screen.getByText('OpenCode Zen CLI')).toBeInTheDocument();+ });++ it('renders a measured zero as 0', () => {+ const { container } = render(+ <FreeTierUsageCard freeTier={{ basis: 'ledger', providers: [provider(0, 100, 'measured')], blocks: [] }} />+ );+ const zeros = [...container.querySelectorAll('span')].filter((el) => el.textContent === '0');+ expect(zeros.length).toBeGreaterThan(0);+ });++ it('renders reported counts as numbers', () => {+ render(+ <FreeTierUsageCard freeTier={{ basis: 'ledger', providers: [provider(1200, 3400, 'mixed')], blocks: [] }} />+ );+ expect(screen.getByText('OpenCode Zen CLI')).toBeInTheDocument();+ });+});diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex 790f5dc68a..5f2a41c72c 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -10,6 +10,7 @@ import { useAsyncAction } from '../hooks/useAsyncAction';import { useAutoRefetch } from '../hooks/useAutoRefetch';import SubscriptionSavingsCard from '../components/usage/SubscriptionSavingsCard';import FleetUsageCard from '../components/usage/FleetUsageCard';+import FreeTierUsageCard from '../components/usage/FreeTierUsageCard';import ModelsTabsHeader from '../components/models/ModelsTabsHeader';// How often to re-ask while a provider's quota reading is still being taken. A@@ -866,11 +867,17 @@ function InternalUsageMetrics() {session transcript but no token fields, so its rows are sized from that transcript’s text, and a run with no sessionfile at all (local models) is approximated from the initial prompt only with no cache traffic counted — those rowsunderstate real usage substantially.- Rates are as of {report?.pricingAsOf || 'the last update'} and exclude batch and long-context tiers.+ {' '}OpenCode-backed runs (including zen) contribute the output tokens from the run’s own event stream and stay+ estimated on input. Rates are as of {report?.pricingAsOf || 'the last update'} and exclude batch and long-context tiers.{' '}Rows marked ~ use an approximated rate.</p></div>+ {/* Free-tier counterpart of the cost report above: ledger-tracked queries+ and tokens on quotas with no usage API (e.g. opencode zen), plus the+ observed limit blocks that stand in for a quota meter. */}+ <FreeTierUsageCard freeTier={usage.freeTier} />+{/* Same window, split by machine — renders only once a peer's usage hassynced, so a single-machine install sees no change. */}<FleetUsageCard fleet={usage.fleet} onSaved={fetchUsage} />diff --git a/client/src/pages/UsagePage.test.jsx b/client/src/pages/UsagePage.test.jsxindex 35b72e4012..9324a06432 100644--- a/client/src/pages/UsagePage.test.jsx+++ b/client/src/pages/UsagePage.test.jsx@@ -388,3 +388,63 @@ describe('UsagePage provider-quota loading state (#4147)', () => {expect(region.innerHTML).toContain('lg:grid-cols-2');});});++describe('UsagePage free-tier section (#7408)', () => {+ const freeTier = {+ basis: 'ledger',+ providers: [{+ id: 'opencode-zen-cli',+ name: 'OpenCode Zen CLI',+ free: true,+ sessions: 3,+ messages: 5,+ tokensIn: 1200,+ tokensOut: 3400,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ source: 'mixed',+ estimatedCost: 0,+ rateMatch: 'free',+ models: [{+ model: 'opencode/big-pickle',+ sessions: 3,+ messages: 5,+ tokensIn: 1200,+ tokensOut: 3400,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ source: 'mixed',+ estimatedCost: 0,+ rateMatch: 'free'+ }]+ }],+ blocks: [{+ providerId: 'opencode-zen-cli',+ model: null,+ category: 'usage-limit',+ message: 'hit your usage limit',+ resetHint: '2 hours',+ at: Date.now() - 60_000,+ volumeSince: { sessions: 1, messages: 2, tokensIn: 100, tokensOut: 200 }+ }]+ };++ it('renders free-tier queries, tokens, and the observed block from the report payload', async () => {+ api.getUsage.mockResolvedValue({ ...usage, freeTier });+ render(<MemoryRouter><UsagePage /></MemoryRouter>);++ expect(await screen.findByText('Free-tier usage')).toBeInTheDocument();+ expect(screen.getByText('OpenCode Zen CLI')).toBeInTheDocument();+ expect(screen.getByText('opencode/big-pickle')).toBeInTheDocument();+ // Observed block with its reset hint and since-volume.+ expect(screen.getByText(/provider said: 2 hours/)).toBeInTheDocument();+ expect(screen.getByText(/out since/)).toBeInTheDocument();+ });++ it('renders an empty state when no free-tier usage exists yet', async () => {+ api.getUsage.mockResolvedValue({ ...usage, freeTier: { basis: 'ledger', providers: [], blocks: [] } });+ render(<MemoryRouter><UsagePage /></MemoryRouter>);++ expect(await screen.findByText('No free-tier usage recorded in this period.')).toBeInTheDocument();+ });+});diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.mdindex 24d3916804..f3b41739f0 100644--- a/docs/QUOTA-BURN.md+++ b/docs/QUOTA-BURN.md@@ -121,6 +121,31 @@ usage-limit failure, `server/services/quotaBurnDenials.js` blocks that family in- **Bypassable by a forced run** (the ▶ on a step row), which is how a userretries a block they believe is stale.+## Free-tier usage reporting (Usage page)++Subscription families have scrapable quota panels; free-tier quotas (e.g.+opencode zen) do not, so the Usage page (`/devtools/usage`) reports them from+the PortOS ledger instead of from the provider:++- **Queries and tokens** per free-tier provider/model come from the existing+ usage report — the same `GET /api/usage` payload, filtered to rows+ free-classified by `isFreeProvider`/`isFreeModelId` (Zen provider ids,+ endpoint, and `-free`/`opencode/*` model ids resolve to $0). OpenCode-backed+ runs bill their stream's own output-token counts (`mixed` provenance: output+ measured, input still estimated); unreported counts render as —, never 0.+- **Observed blocks** (`usage.blockEvents` via `recordLimitBlock`) stand in for+ the missing quota meter: every applied `usage-limit` bench — from the runner+ or the agent finalizer — records timestamp + provider/model + reset hint, and+ the page shows ledger volume since each block as the estimated-remaining+ signal. Transient 429 retries are not blocks (same rule as above) and are+ never recorded. A repeat report of one incident coalesces rather than+ stacking. This ledger is NOT the burn-denial ledger above it: burn denials+ gate burn dispatch per family, while block events are a display signal for+ every provider.+- **No provider calls.** The section is ledger-derived behind the page's normal+ fetch — never boot-time, never background — and Zen has no quota adapter+ because it exposes no usage endpoint to adapt.+## Burn stepsA family's plan is an **ordered list of steps**, and that ordering is thediff --git a/server/lib/modelPricing.js b/server/lib/modelPricing.jsindex 5f74a4e153..8c56da1887 100644--- a/server/lib/modelPricing.js+++ b/server/lib/modelPricing.js@@ -263,6 +263,15 @@ export function resolveModelRates(providerId, model) {const LOCALHOST_ENDPOINT = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)(:|\/|$)/i;const FREE_ID = /ollama|lmstudio|lm-studio/i;+// OpenCode Zen is a free-tier quota, not API billing: the seeded `opencode-zen`+// providers (API + CLI/TUI wrappers, see scripts/migrations/336-*) spend a+// weekly/monthly allowance, so their rows resolve to $0 on the cost report and+// surface on the Usage page's free-tier section instead. Narrow on purpose — a+// bare `zen` substring would also match an unrelated paid id, so only the+// harness's own provider id and endpoint shapes count.+const ZEN_PROVIDER_ID = /opencode-zen/i;+const ZEN_ENDPOINT = /opencode\.ai\/zen/i;+// Ollama/LM Studio name their models `family:tag` — `qwen3.6:35b`,// `llama3.1:8b-instruct-q8_0` — or `org/repo` for a pulled GGUF.//@@ -282,6 +291,16 @@ const LOCAL_TAGGED_MODEL = /^[\w.-]+:[\w.-]*[a-z][\w.-]*$/i;// Only the tagged form above is self-evidently an Ollama/LM Studio id, so a// slash-form id needs corroborating evidence from the PROVIDER — which is what// `isFreeProvider` already supplies — rather than being inferred from syntax.+// The `opencode/` namespace is the one exception: it is the harness's own+// built-in provider (the Zen free tier), not a generic hosted catalog shape.++// The harness's own `opencode/*` namespace (exactly what `opencode models`+// prints — `opencode/big-pickle`, `opencode/mimo-v2.5-free`) is the Zen free+// tier, and a bare `-free` suffix is an explicit free-tier marker+// (`deepseek-v4-flash-free`). Both are provider-side labels, so they win over+// the family-guess rules below — unlike the slash form, which stays paid+// without corroboration (see the `org/repo` note above).+const FREE_TIER_MODEL = /^opencode\/.+|[^/]*-free$/i;/*** True when a MODEL id is local-inference (free), independent of which provider@@ -300,6 +319,10 @@ export function isFreeModelId(model) {if (!id) return false;// A hosted id we have a real rate for is never local, whatever its shape.if (EXACT_RATES[id]) return false;+ // An explicit free-tier label wins over the family guesses below: the+ // provider named this id free (`*-free`, the harness's own `opencode/*`+ // namespace), which is stronger evidence than a substring rate rule.+ if (FREE_TIER_MODEL.test(id)) return true;// Nor is one that resolves to a known hosted family (covers Bedrock-prefixed// and suffixed variants of every id in the table).if (resolveModelRates(null, id).matched !== 'fallback') return false;@@ -309,19 +332,21 @@ export function isFreeModelId(model) {/*** True when a provider's usage is free — local inference (Ollama, LM Studio,- * any Ollama-/MTPLX-/llama-/vLLM-backed CLI wrapper, or an API provider pointed at localhost).- * Accepts a provider config object or a bare provider-id string (usage records- * can outlive their provider config).+ * any Ollama-/MTPLX-/llama-/vLLM-backed CLI wrapper, or an API provider pointed at localhost),+ * or a free-tier quota (OpenCode Zen: the `opencode-zen*` provider ids or the+ * `opencode.ai/zen` endpoint). Accepts a provider config object or a bare provider-id string+ * (usage records can outlive their provider config).* @param {object|string|null|undefined} providerOrId* @returns {boolean}*/export function isFreeProvider(providerOrId) {if (providerOrId == null) return false;- if (typeof providerOrId === 'string') return FREE_ID.test(providerOrId);+ if (typeof providerOrId === 'string') return FREE_ID.test(providerOrId) || ZEN_PROVIDER_ID.test(providerOrId);const p = providerOrId;if (p.ollamaBacked === true || p.lmstudioBacked === true || p.mtplxBacked === true || p.llamaBacked === true || p.vllmBacked === true || p.sglangBacked === true) return true;if (FREE_ID.test(p.id || '') || FREE_ID.test(p.command || '')) return true;- if (typeof p.endpoint === 'string' && LOCALHOST_ENDPOINT.test(p.endpoint.trim())) return true;+ if (ZEN_PROVIDER_ID.test(p.id || '')) return true;+ if (typeof p.endpoint === 'string' && (LOCALHOST_ENDPOINT.test(p.endpoint.trim()) || ZEN_ENDPOINT.test(p.endpoint.trim()))) return true;return false;}diff --git a/server/lib/modelPricing.test.js b/server/lib/modelPricing.test.jsindex 055b46ac21..f72a88c341 100644--- a/server/lib/modelPricing.test.js+++ b/server/lib/modelPricing.test.js@@ -193,6 +193,19 @@ describe('isFreeProvider', () => {expect(isFreeProvider('codex')).toBe(false);expect(isFreeProvider(null)).toBe(false);});++ it('classifies OpenCode Zen providers as free-tier (id, endpoint, and string forms)', () => {+ expect(isFreeProvider('opencode-zen')).toBe(true);+ expect(isFreeProvider('opencode-zen-cli')).toBe(true);+ expect(isFreeProvider('opencode-zen-tui')).toBe(true);+ expect(isFreeProvider({ id: 'opencode-zen', type: 'api', endpoint: 'https://opencode.ai/zen/v1' })).toBe(true);+ expect(isFreeProvider({ id: 'my-zen', type: 'api', endpoint: 'https://opencode.ai/zen/v1' })).toBe(true);+ });++ it('does not classify an unrelated id containing "zen" as free', () => {+ expect(isFreeProvider('zen-model-paid')).toBe(false);+ expect(isFreeProvider({ id: 'kozen-api', type: 'api', endpoint: 'https://api.example.com/v1' })).toBe(false);+ });});describe('estimateCostUsd', () => {@@ -329,4 +342,25 @@ describe('isFreeModelId', () => {// The provider-level check can't catch this on its own — hence the model check.expect(isFreeProvider('claude-code')).toBe(false);});++ // Zen free-tier ids are provider-side free labels (#7408): the harness's own+ // `opencode/*` namespace and an explicit `-free` suffix resolve to $0, while+ // paid ids that merely contain those substrings as part of a longer name do+ // not (the exact-rate guard still wins for a literally-priced id).+ it('treats Zen free-tier model ids as free', () => {+ for (const id of [+ 'opencode/big-pickle',+ 'opencode/mimo-v2.5-free',+ 'opencode/muse-spark-1.3-contributor-free',+ 'deepseek-v4-flash-free'+ ]) {+ expect(isFreeModelId(id)).toBe(true);+ }+ });++ it('does NOT treat a paid id with a free-looking substring as free', () => {+ expect(isFreeModelId('claude-opus-5')).toBe(false);+ expect(isFreeModelId('gpt-5.3-codex')).toBe(false);+ expect(isFreeModelId('unsloth/Qwen3-30B-free-quant')).toBe(false);+ });});diff --git a/server/services/promptRunner.js b/server/services/promptRunner.jsindex 96576a0ecd..80804e39e3 100644--- a/server/services/promptRunner.js+++ b/server/services/promptRunner.js@@ -1060,7 +1060,7 @@ function coalesceFallbackMarkAndPick(failed, firstError, requestCapabilities) {return _fallbackMarkAndPick.run(`${failed.id}:${capabilityKey}`, async () => {const picked = await pickFallbackProvider(failed, requestCapabilities);if (!picked) return null;- await markProviderUnavailableFromError(failed, firstError.message, firstError.errorAnalysis).catch(err => {+ await markProviderUnavailableFromError(failed, firstError.message, firstError.errorAnalysis, firstError?.effectiveModel ?? null).catch(err => {console.error(`❌ markUnavailable failed for ${failed.id}: ${err.message}`);});return picked;@@ -1108,11 +1108,10 @@ async function pickFallbackProvider(failed, requestCapabilities) {* USAGE_LIMIT before firing onComplete) — re-marking would double-* increment `failureCount` and re-write the status file for no gain.*/-async function markProviderUnavailableFromError(failed, errorMessage, runnerAnalysis) {+async function markProviderUnavailableFromError(failed, errorMessage, runnerAnalysis, runModel = null) {const toolkit = getAIToolkitInstance();const providerStatus = toolkit?.services?.providerStatus;if (!providerStatus) return;- if (!providerStatus.isAvailable(failed.id)) return;const analysis = runnerAnalysis && typeof runnerAnalysis === 'object'? runnerAnalysis@@ -1125,6 +1124,22 @@ async function markProviderUnavailableFromError(failed, errorMessage, runnerAnalif (!bench) return;if (bench.marker === 'usage-limit') {+ // Observed-block ledger for the Usage page's free-tier estimated-quota+ // signal — recorded even when the provider is already benched (a repeated+ // refusal refreshes "since last block"). Transient 429 retries never reach+ // this branch: they classify as `rate-limit`, not `usage-limit`.+ await import('./usage.js')+ .then(({ recordLimitBlock }) => recordLimitBlock({+ providerId: failed.id,+ model: runModel,+ category: 'usage-limit',+ message: bench.message || errorMessage,+ resetHint: bench.waitTime+ }))+ .catch((err) => {+ console.error(`❌ Failed to record limit block for ${failed.id}: ${err.message}`);+ });+ if (!providerStatus.isAvailable(failed.id)) return;await providerStatus.markUsageLimit(failed.id, {message: bench.message || errorMessage,waitTime: bench.waitTime,@@ -1132,6 +1147,7 @@ async function markProviderUnavailableFromError(failed, errorMessage, runnerAnalreturn;}+ if (!providerStatus.isAvailable(failed.id)) return;await providerStatus.markUnavailable(failed.id, {reason: bench.category,message: bench.message || errorMessage || `Provider ${failed.name || failed.id} failed`,diff --git a/server/services/providerStatus.js b/server/services/providerStatus.jsindex 32f2ee9b01..57221675db 100644--- a/server/services/providerStatus.js+++ b/server/services/providerStatus.js@@ -88,6 +88,21 @@ export async function markProviderUnavailable(providerId, options = {}) {export async function markProviderUsageLimit(providerId, errorInfo) {const status = await getProviderStatusService().markUsageLimit(providerId, errorInfo);console.log(`⚠️ Provider ${providerId} marked unavailable: usage limit (retry after ${errorInfo?.waitTime || '24h'})`);+ // Observed-block ledger for the Usage page's free-tier estimated-quota+ // signal. This marker fires only for provider-origin structured usage-limit+ // signals — never a transient 429 retry (see `recordLimitBlock`). Lazy+ // import keeps this shim off the usage-service graph for the import budget.+ await import('./usage.js')+ .then(({ recordLimitBlock }) => recordLimitBlock({+ providerId,+ model: errorInfo?.model ?? null,+ category: 'usage-limit',+ message: errorInfo?.message ?? null,+ resetHint: errorInfo?.waitTime ?? null+ }))+ .catch((err) => {+ console.error(`❌ Failed to record limit block for ${providerId}: ${err.message}`);+ });return status;}diff --git a/server/services/usage.js b/server/services/usage.jsindex 8f465ba33d..0614587550 100644--- a/server/services/usage.js+++ b/server/services/usage.js@@ -67,6 +67,11 @@ function getEmptyUsage() {monthlyActivity: {},earliestActivityDay: null,hourlyActivity: Array(24).fill(0),+ // Observed provider limit blocks (`recordLimitBlock`): timestamped+ // `{ providerId, model, category, message, resetHint, at }` facts the+ // Usage page's free-tier section reads as an estimated-quota signal.+ // Additive: absent on installs that predate it, seeded on load.+ blockEvents: [],lastUpdated: null};}@@ -182,7 +187,14 @@ export async function loadUsage() {const earliestActivityDay = findEarliestActivityDay(usageData.dailyActivity, usageData.monthlyActivity);const earliestChanged = usageData.earliestActivityDay !== earliestActivityDay;usageData.earliestActivityDay = earliestActivityDay;- if (rolledUp || normalizedProviders || earliestChanged) {+ // Additive: installs that predate limit-block tracking read as "no blocks+ // observed" without a migration pass.+ let normalizedBlocks = false;+ if (!Array.isArray(usageData.blockEvents)) {+ usageData.blockEvents = [];+ normalizedBlocks = true;+ }+ if (rolledUp || normalizedProviders || earliestChanged || normalizedBlocks) {if (normalizedProviders) console.log('📊 Normalized undefined usage providers to unknown');if (rolledUp) console.log(`📊 Rolled up old daily usage into ${Object.keys(usageData.monthlyActivity).length} monthly buckets`);await saveUsage();@@ -721,6 +733,100 @@ export async function recordTokens(inputTokens, outputTokens) {await saveUsage();}+/**+ * Two reports of one incident, one minute apart, are the same block. The+ * runner benches a failed provider AND the agent finalizer benches it again+ * for the same failure, so without this every limit event would stack twice.+ */+export const LIMIT_BLOCK_DEDUPE_MS = 60_000;+/** Oldest block events are dropped past this — the Usage page reads the tail. */+export const LIMIT_BLOCK_CAP = 200;++/**+ * Record an observed provider limit block: a `usage-limit` bench the runner or+ * the agent finalizer actually applied (provider-origin, structured marker —+ * never a loose keyword sweep, never a transient 429 retry, which per+ * docs/QUOTA-BURN.md is a retry rather than a spent window).+ *+ * Fire-and-forget safe: callers invoke it beside a bench mark from completion+ * paths, so it owns its persistence and never rejects into them — chain a+ * `.catch` like the mark itself, or await it inside an existing guarded block.+ *+ * @param {{ providerId: string, model?: string|null, category?: string,+ * message?: string|null, resetHint?: string|null, at?: number }} event+ * @returns {Promise<object|null>} the stored entry, or null without a provider+ */+export async function recordLimitBlock({+ providerId,+ model = null,+ category = 'usage-limit',+ message = null,+ resetHint = null,+ at = Date.now()+} = {}) {+ if (!providerId) return null;+ if (!usageData) await loadUsage();+ if (!Array.isArray(usageData.blockEvents)) usageData.blockEvents = [];+ const entry = {+ providerId,+ model: typeof model === 'string' && model.trim() ? model.trim() : null,+ category,+ message: typeof message === 'string' && message ? message.slice(0, 500) : null,+ resetHint: typeof resetHint === 'string' && resetHint ? resetHint.slice(0, 120) : null,+ at: Number.isFinite(at) ? at : Date.now()+ };+ const last = usageData.blockEvents[usageData.blockEvents.length - 1];+ if (last && last.providerId === entry.providerId && last.category === entry.category+ && (entry.at - last.at) < LIMIT_BLOCK_DEDUPE_MS) {+ usageData.blockEvents[usageData.blockEvents.length - 1] = entry;+ } else {+ usageData.blockEvents.push(entry);+ }+ if (usageData.blockEvents.length > LIMIT_BLOCK_CAP) {+ usageData.blockEvents.splice(0, usageData.blockEvents.length - LIMIT_BLOCK_CAP);+ }+ await saveUsage();+ return entry;+}++/** Every recorded limit block, oldest-first. Pure read over the live ledger. */+export function getLimitBlocks() {+ const events = getUsage().blockEvents;+ return Array.isArray(events) ? [...events] : [];+}++const blockDayOf = (at) => {+ const ms = typeof at === 'number' ? at : Date.parse(at);+ if (!Number.isFinite(ms)) return null;+ return new Date(ms).toISOString().slice(0, 10);+};++/**+ * Ledger volume for one provider since a block's day (inclusive): the+ * heuristic half of the free-tier "estimated remaining" signal — how much has+ * run since the provider last refused. Null when the block carries no usable+ * timestamp (unknown, never zero-collapsed). Pure.+ */+export function providerVolumeSinceBlock(dailyActivity, monthlyActivity, providerId, day) {+ if (!day || !providerId) return null;+ const totals = { sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0 };+ const add = (bucket) => {+ const p = bucket?.byProvider?.[providerId];+ if (!p) return;+ totals.sessions += p.sessions || 0;+ totals.messages += p.messages || 0;+ totals.tokensIn += p.tokensIn || 0;+ totals.tokensOut += p.tokensOut || 0;+ };+ for (const [key, bucket] of Object.entries(monthlyActivity || {})) {+ if (key > day.slice(0, 7)) add(bucket);+ }+ for (const [key, bucket] of Object.entries(dailyActivity || {})) {+ if (DAY_KEY_RE.test(key) && key >= day) add(bucket);+ }+ return totals;+}+/*** Aggregate the per-day per-provider per-model buckets over a date range into* a cost report. `from`/`to` are inclusive `YYYY-MM-DD` strings (null = open@@ -1016,7 +1122,8 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {})estimatedCost: 0,topProviders: [],topModels: [],- report: buildUsageReport({}, { from, to, providers, monthlyActivity: {} })+ report: buildUsageReport({}, { from, to, providers, monthlyActivity: {} }),+ freeTier: { providers: [], blocks: [], basis: 'ledger' }};}@@ -1079,6 +1186,24 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {}).sort((a, b) => b.sessions - a.sessions).slice(0, 5),report,+ // Free-tier counterpart of the paid cost report: the report rows already+ // free-classified (local inference, Zen quota), plus the observed limit+ // blocks with ledger volume since each — the estimated-quota signal for+ // providers that expose no usage API. `basis: 'ledger'` is the card's+ // stated provenance (see UsagePage's free-tier section).+ freeTier: {+ providers: report.providers.filter((row) => row.free),+ blocks: getLimitBlocks().slice(-20).map((event) => ({+ ...event,+ volumeSince: providerVolumeSinceBlock(+ usageData.dailyActivity,+ usageData.monthlyActivity,+ event.providerId,+ blockDayOf(event.at)+ )+ })),+ basis: 'ledger'+ },lastUpdated: usageData.lastUpdated};if (summaryCache.size >= SUMMARY_CACHE_LIMIT) {diff --git a/server/services/usage.test.js b/server/services/usage.test.jsindex 870f481152..642a8e406e 100644--- a/server/services/usage.test.js+++ b/server/services/usage.test.js@@ -24,9 +24,12 @@ import {applyHistoricalUsageCorrections,buildUsageReport,getFirstActivityDay,+ getLimitBlocks,getUsage,getUsageSummary,loadUsage,+ providerVolumeSinceBlock,+ recordLimitBlock,recordMessages,recordRunUsage,recordSession,@@ -1292,3 +1295,119 @@ describe('buildUsageReport — local models under a paid provider', () => {expect(report.totals.estimatedCost).toBeCloseTo(25, 2);});});++describe('usage.js — limit-block ledger (#7408)', () => {+ beforeEach(async () => {+ vi.useFakeTimers();+ vi.setSystemTime(FIXED_DATE);+ vi.clearAllMocks();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ const loadEmpty = async (extras = {}) => {+ readJSONFile.mockResolvedValueOnce(makeUsage({}, extras));+ await loadUsage();+ };++ it('records a block with timestamp, provider, and reset hint', async () => {+ await loadEmpty();+ const entry = await recordLimitBlock({+ providerId: 'opencode-zen-cli',+ model: 'opencode/big-pickle',+ category: 'usage-limit',+ message: 'hit your usage limit',+ resetHint: '2 hours',+ at: new Date('2025-06-11T10:00:00.000Z').getTime()+ });+ expect(entry.providerId).toBe('opencode-zen-cli');+ expect(entry.model).toBe('opencode/big-pickle');+ expect(entry.resetHint).toBe('2 hours');+ expect(getLimitBlocks()).toHaveLength(1);+ });++ it('ignores a block without a provider id', async () => {+ await loadEmpty();+ expect(await recordLimitBlock({})).toBeNull();+ expect(getLimitBlocks()).toHaveLength(0);+ });++ it('coalesces a repeated report of the same incident instead of stacking', async () => {+ await loadEmpty();+ const at = Date.now();+ await recordLimitBlock({ providerId: 'opencode-zen', at });+ await recordLimitBlock({ providerId: 'opencode-zen', at: at + 30_000 });+ expect(getLimitBlocks()).toHaveLength(1);+ // A genuinely later block (past the dedupe window) is a new row.+ await recordLimitBlock({ providerId: 'opencode-zen', at: at + 120_000 });+ expect(getLimitBlocks()).toHaveLength(2);+ });++ it('seeds blockEvents on installs that predate the ledger', async () => {+ const legacy = makeUsage({});+ delete legacy.blockEvents;+ readJSONFile.mockResolvedValueOnce(legacy);+ await loadUsage();+ expect(getLimitBlocks()).toEqual([]);+ const entry = await recordLimitBlock({ providerId: 'opencode-zen' });+ expect(entry).not.toBeNull();+ });++ it('sums ledger volume since a block day, and nulls an undateable block', () => {+ const daily = {+ '2025-06-10': {+ sessions: 1, messages: 1,+ byProvider: { 'opencode-zen': { name: 'Zen', sessions: 1, messages: 2, tokensIn: 100, tokensOut: 200 } }+ },+ '2025-06-11': {+ sessions: 1, messages: 1,+ byProvider: { 'opencode-zen': { name: 'Zen', sessions: 2, messages: 3, tokensIn: 400, tokensOut: 800 } }+ }+ };+ const volume = providerVolumeSinceBlock(daily, {}, 'opencode-zen', '2025-06-11');+ expect(volume).toMatchObject({ sessions: 2, messages: 3, tokensIn: 400, tokensOut: 800 });+ expect(providerVolumeSinceBlock(daily, {}, 'opencode-zen', null)).toBeNull();+ expect(providerVolumeSinceBlock(daily, {}, 'other-provider', '2025-06-11'))+ .toMatchObject({ sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0 });+ });++ it('exposes free-tier rows and block signals on the summary', async () => {+ const day = daysAgo(0);+ readJSONFile.mockResolvedValueOnce(makeUsage({+ [day]: {+ sessions: 1, messages: 1,+ byProvider: {+ 'opencode-zen-cli': {+ name: 'OpenCode Zen CLI', sessions: 1, messages: 1,+ tokensIn: 100, tokensOut: 500, cacheReadTokens: 0, cacheWriteTokens: 0,+ source: 'mixed',+ byModel: {+ 'opencode/big-pickle': {+ sessions: 1, messages: 1, tokensIn: 100, tokensOut: 500,+ cacheReadTokens: 0, cacheWriteTokens: 0, source: 'mixed'+ }+ }+ }+ }+ }+ }, {+ blockEvents: [{+ providerId: 'opencode-zen-cli', model: null, category: 'usage-limit',+ message: 'hit your usage limit', resetHint: '2 hours',+ at: new Date(`${day}T10:00:00.000Z`).getTime()+ }]+ }));+ await loadUsage();+ const summary = getUsageSummary();+ expect(summary.freeTier.basis).toBe('ledger');+ expect(summary.freeTier.providers.map((row) => row.id)).toContain('opencode-zen-cli');+ const zen = summary.freeTier.providers.find((row) => row.id === 'opencode-zen-cli');+ expect(zen.free).toBe(true);+ expect(zen.estimatedCost).toBe(0);+ expect(zen.source).toBe('mixed');+ expect(summary.freeTier.blocks).toHaveLength(1);+ expect(summary.freeTier.blocks[0].volumeSince).toMatchObject({ sessions: 1, messages: 1 });+ });+});diff --git a/server/services/usageReconciler.js b/server/services/usageReconciler.jsindex 73fbe399b5..7ec1e2b86b 100644--- a/server/services/usageReconciler.js+++ b/server/services/usageReconciler.js@@ -59,6 +59,7 @@ import {} from '../lib/providerTranscriptUsage.js';import { familyForProvider } from '../lib/providerFamilies.js';import { commandBasename } from '../lib/providerModels.js';+import { summarizeOpenCodeEvents } from '../lib/opencodeStream.js';import { markUsageRunReconciled, recordRunUsage } from './usage.js';// Widen the correlation window past the recorded run bounds: the CLI writes its@@ -254,6 +255,24 @@ export function transcriptFamily({ providerId = null, command = null } = {}) {/** Every family whose CLI writes a readable session store. */export const TRANSCRIPT_FAMILIES = ['claude', 'codex', 'grok', 'agy', 'kimi'];+// OpenCode writes no transcript store — but its `--format json` event stream+// (captured stdout) already carries the provider's own output-token counts+// (`lib/opencodeStream.summarizeOpenCodeEvents`). An opencode run is therefore+// reconciled from its stream, not from a session file: matched the same way+// `transcriptFamily` matches (id or command), kept separate from it so the+// sibling scan (which keys off TRANSCRIPT_FAMILIES) never tries to open a+// nonexistent store for it.+const OPENCODE_ID = /opencode/i;++/**+ * Whether this run drove the OpenCode harness (Zen CLI/TUI wrappers included).+ * @param {{ providerId?: string|null, command?: string|null }} run+ * @returns {boolean}+ */+export function isOpencodeRun({ providerId = null, command = null } = {}) {+ return OPENCODE_ID.test(`${providerId || ''} ${command || ''}`);+}+/** `reconcileRunUsage` returns one record or several — normalize to a list. */const asRecordList = (records) => (Array.isArray(records) ? records : [records]);@@ -737,9 +756,13 @@ export function resolveFamilyProvider(providers, family, measured = null) {* @param {{ home?: string, providers?: Array<object>|null }} [opts] `providers`* enables the sibling scan; omitting it reconciles the parent family only* (which is what a caller with no access to the provider list should do).+ * @param {string} [opts.estimateSource] provenance for the parent fallback+ * record when no transcript matched (`estimate` by default). An OpenCode run+ * whose stream carried measured output tokens passes `mixed` — its output is+ * the provider's own count, its input still a chars estimate.* @returns {Promise<object|Array<object>>}*/-export async function reconcileRunUsage(run, estimate, { home = homedir(), providers = null } = {}) {+export async function reconcileRunUsage(run, estimate, { home = homedir(), providers = null, estimateSource = null } = {}) {const workspacePath = run?.workspacePath;const startTime = run?.startTime;const endTime = run?.endTime;@@ -765,7 +788,7 @@ export async function reconcileRunUsage(run, estimate, { home = homedir(), provitokensOut: Math.max(0, estimate?.tokensOut || 0),cacheReadTokens: 0,cacheWriteTokens: 0,- source: 'estimate'+ source: estimateSource ?? 'estimate'};const siblings = [];@@ -812,8 +835,23 @@ export async function reconcileRunUsage(run, estimate, { home = homedir(), proviexport async function recordCompletedRunUsage(metadata, output, { home = homedir(), providers = null } = {}) {if (!metadata?.providerId) return;+ // OpenCode runs have no transcript store, but their captured stdout IS the+ // provider's own event stream: when it carries output-token counts, bill+ // those instead of the chars estimate. The `null` sentinel is preserved —+ // a stream with no usage frames falls back to the estimate rather than+ // recording a measured zero. Input stays a chars estimate either way, so a+ // stream-upgraded run is `mixed`, never `measured`.+ let estimateSource = null;+ let measuredOutputTokens = null;+ if (isOpencodeRun({ providerId: metadata.providerId, command: metadata.command })) {+ const summary = summarizeOpenCodeEvents(output);+ if (typeof summary?.outputTokens === 'number') {+ measuredOutputTokens = summary.outputTokens;+ estimateSource = 'mixed';+ }+ }const estimate = {- tokensOut: estimateTokens(output),+ tokensOut: measuredOutputTokens ?? estimateTokens(output),tokensIn: estimateTokensFromChars(metadata.promptLength)};// The provider list enables the sibling-family scan (a nested `--review-with`@@ -827,7 +865,7 @@ export async function recordCompletedRunUsage(metadata, output, { home = homedir.catch(() => null);// One catch for the whole chain: whatever fails — reading a transcript or// persisting the record — usage accounting must not surface as a run failure.- await reconcileRunUsage(metadata, estimate, { home, providers: resolved })+ await reconcileRunUsage(metadata, estimate, { home, providers: resolved, estimateSource }).then(recordRunUsage).then(async () => {if (!metadata?.id) return;diff --git a/server/services/usageReconciler.test.js b/server/services/usageReconciler.test.jsindex e6b8d62cda..dc145a70e0 100644--- a/server/services/usageReconciler.test.js+++ b/server/services/usageReconciler.test.js@@ -11,6 +11,7 @@ vi.mock('./usage.js', () => ({const { markUsageRunReconciled, recordRunUsage } = await import('./usage.js');const {transcriptFamily,+ isOpencodeRun,readMeasuredUsage,reconcileRunUsage,recordCompletedRunUsage,@@ -156,6 +157,19 @@ describe('transcriptFamily', () => {expect(transcriptFamily({ providerId })).toBeNull();}});++ it('returns null for opencode providers — their stream is reconciled separately, not via a transcript store', () => {+ for (const run of [+ { providerId: 'opencode-zen-cli' },+ { providerId: 'opencode-zen-tui' },+ { providerId: 'custom', command: '/usr/local/bin/opencode' }+ ]) {+ expect(transcriptFamily(run)).toBeNull();+ expect(isOpencodeRun(run)).toBe(true);+ }+ expect(isOpencodeRun({ providerId: 'claude-code' })).toBe(false);+ expect(isOpencodeRun({})).toBe(false);+ });});describe('readMeasuredUsage', () => {@@ -519,6 +533,59 @@ describe('recordCompletedRunUsage', () => {endTime: '2026-07-01T10:10:00.000Z'}, 'out')).resolves.toBeUndefined();});++ // OpenCode writes no transcript store, so its output tokens come from the+ // run's own captured event stream (#7408). Input stays a chars estimate, so+ // a stream-upgraded run is `mixed`.+ it('bills measured stream output tokens for an opencode run', async () => {+ const stream = [+ JSON.stringify({ type: 'text', part: { type: 'text', text: 'done', tokens: { output: 42 } } }),+ JSON.stringify({ type: 'text', part: { type: 'text', text: 'more', tokens: { output: 8 } } })+ ].join('\n');+ await recordCompletedRunUsage({+ providerId: 'opencode-zen-cli',+ model: 'opencode/big-pickle',+ workspacePath: WORKSPACE,+ promptLength: 400,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z'+ }, stream, { home, providers: [] });++ expect(recordRunUsage).toHaveBeenCalledTimes(1);+ const record = recordRunUsage.mock.calls[0][0];+ expect(record).toMatchObject({ source: 'mixed', tokensOut: 50 });+ expect(record.tokensIn).toBeGreaterThan(0);+ });++ it('falls back to the chars estimate when an opencode stream carries no usage frames', async () => {+ await recordCompletedRunUsage({+ providerId: 'opencode-zen-cli',+ model: 'opencode/big-pickle',+ workspacePath: WORKSPACE,+ promptLength: 400,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z'+ }, 'plain stdout with no event envelope', { home, providers: [] });++ expect(recordRunUsage).toHaveBeenCalledTimes(1);+ const record = recordRunUsage.mock.calls[0][0];+ expect(record.source).toBe('estimate');+ expect(record.tokensOut).toBeGreaterThan(0);+ });++ it('honors an explicit estimate source on the parent fallback record', async () => {+ const run = {+ providerId: 'opencode-zen-cli',+ model: 'opencode/big-pickle',+ workspacePath: WORKSPACE,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z'+ };+ const record = await reconcileRunUsage(run, { tokensIn: 5, tokensOut: 7 }, { home, estimateSource: 'mixed' });+ expect(record.source).toBe('mixed');+ const fallback = await reconcileRunUsage(run, { tokensIn: 5, tokensOut: 7 }, { home });+ expect(fallback.source).toBe('estimate');+ });});