Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ follows [Semantic Versioning](https://semver.org/).

## 2026-11-13

- API connections: a credit set to **Renews monthly** shows its expiry date and days left, and shows **Expired** if the date passes before the next fetch. Anthropic Max, Ultra and Team plan API credits expire at the end of each billing cycle; Settings explains how to enter them. See ADR 0049.
- API connections: the OpenAI API and Anthropic API cards show **Total credit**, **Used** and **Left**. Anthropic API can now estimate its balance from a credit amount and date entered in Settings, as OpenAI already could. **Renews monthly** counts spend from the latest monthly renewal day, for credits that reset each month. Card headings show spend with the snapshot's UTC month, such as **$3.42 in November**. See ADR 0049.

## 2026-11-12
Expand Down
6 changes: 5 additions & 1 deletion docs/API_USAGE_BETA.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,11 @@ under Anthropic API in Settings, save, then fetch billing again. The card shows
For a credit that renews each month, select **Renews monthly** and enter a
renewal date. Each fetch counts spend from the latest renewal on or before
today (UTC). A month without that day, such as the 31st, uses its last day.
This option is also available for OpenAI. The estimate assumes the cost report
A monthly credit expires at its next renewal. The card shows the expiry date and
days left, and shows **Expired** if the date passes before the next fetch.
Anthropic's Max, Ultra and Team plan API credits work this way: they arrive each
billing cycle and expire at its end. Enter the monthly amount and the date it
arrived. This option is also available for OpenAI. The estimate assumes the cost report
includes usage paid by credits; this is not verified with a real account. See
[ADR 0049](adr/0049-api-credit-total-used-left.md).

Expand Down
3 changes: 2 additions & 1 deletion docs/KB.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,8 @@ to open Settings. No window is shown or focused by preload.
- Both API cards show **Total credit**, **Used** and **Left** from one balance.
The heading names the snapshot's UTC month, such as **$3.42 in November**. Anthropic has no balance
endpoint, so its card uses the same prepaid estimate from per-provider
Settings values. **Renews monthly** counts spend from the latest renewal day.
Settings values. **Renews monthly** counts spend from the latest renewal day
and shows the next renewal as the credit's expiry, with days left.
Whether `cost_report` includes credit-paid usage is unverified. See
[ADR 0049](adr/0049-api-credit-total-used-left.md).
See [API billing](API_USAGE_BETA.md) and [ADR 0029](adr/0029-api-billing-snapshots.md).
Expand Down
2 changes: 1 addition & 1 deletion docs/PRIVACY.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ reject redirects, cap response size and pagination, and never start inference.
The helper writes only schema/provider, capture/period timestamps, currency,
daily USD totals and an optional balance (OpenAI granted, used and available
totals, or for either provider the prepaid amount, top-up or renewal date, a
monthly flag and spend since then). Identifiers, headers and raw responses/errors are discarded.
monthly flag, the computed expiry date and spend since then). Identifiers, headers and raw responses/errors are discarded.
Files and their final directory are owner-only; replacement is atomic and a
failed request preserves the previous file. The app validates the fixed files
and publishes only projected fields. Demo and isolated provider tests never
Expand Down
6 changes: 6 additions & 0 deletions docs/adr/0049-api-credit-total-used-left.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ Admin key; the Console shows it only to a signed-in user.
the date as a renewal day. Each fetch counts spend from the latest renewal
on or before now; a month without that day uses its last day. The snapshot
stores the renewal date used and `monthly: true`.
4. A monthly credit expires at its next renewal, as Anthropic's Max, Ultra and
Team plan API credits expire at the end of each billing cycle without
rollover. The snapshot stores that date as `expiresAt`. The card shows
**Expires YYYY-MM-DD UTC · N days left**. When the clock passes that date
before the next fetch, **Left** shows **Expired** and the card asks for a
fetch to count the new cycle.

Snapshots stay schema 1. The balance stays optional and never fails the spend
fetch. The environment helper reads no preferences, so it stores no estimate.
Expand Down
23 changes: 14 additions & 9 deletions src/domain/api-billing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ export const apiBillingNames = { openai: "OpenAI API", anthropic: "Anthropic API
// spend since that top-up.
export type ApiBillingBalance =
| { source: "creditGrants"; availableUSD: number; grantedUSD: number; usedUSD: number }
| { source: "manual"; availableUSD: number; prepaidUSD: number; since: number; spentSinceUSD: number; monthly?: true };
| { source: "manual"; availableUSD: number; prepaidUSD: number; since: number; spentSinceUSD: number; monthly?: true; expiresAt?: number };
export interface ApiBillingSnapshot {
schema: 1; provider: ApiBillingProvider; capturedAt: number; monthStart: number; periodEnd: number; currency: "USD";
daily: { start: number; end: number; amountUSD: number }[];
balance?: ApiBillingBalance;
}
export type ApiBillingReading = { status: "value"; value: ApiBillingSnapshot; stale: boolean } | { status: "missing"; code: "notConfigured" | "unavailable" };

export interface ApiBillingPrepaid { amountUSD: number; since: number; monthly?: true }
export interface ApiBillingPrepaid { amountUSD: number; since: number; monthly?: true; expiresAt?: number }
export const prepaidPreferenceKeys = {
openai: { amount: "openAIPrepaidCreditUSD", since: "openAIPrepaidSince", monthly: "openAIPrepaidMonthly" },
anthropic: { amount: "anthropicPrepaidCreditUSD", since: "anthropicPrepaidSince", monthly: "anthropicPrepaidMonthly" },
Expand All @@ -32,17 +32,22 @@ export function prepaidDay(v: unknown): number | undefined {
return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === v ? at : undefined;
}
export const validPrepaidSince = (v: unknown) => v === "" || prepaidDay(v) !== undefined;
/** Latest UTC renewal on or before `now` for a credit that renews on `anchor`'s day of month; short months use their last day. */
export function latestRenewal(anchor: number, now: number): number {
if (anchor > now) return anchor;
const day = new Date(anchor).getUTCDate(), at = new Date(now);
/**
* Billing cycle for a credit that renews on `anchor`'s day of month and expires at
* the next renewal: the latest renewal on or before `now`, and the one after it.
* Short months use their last day. A future anchor is its own cycle start.
*/
export function renewalCycle(anchor: number, now: number): { start: number; expiresAt: number } {
const day = new Date(anchor).getUTCDate(), at = new Date(Math.max(anchor, now));
const inMonth = (year: number, month: number) => Date.UTC(year, month, Math.min(day, new Date(Date.UTC(year, month + 1, 0)).getUTCDate()));
const current = inMonth(at.getUTCFullYear(), at.getUTCMonth());
return current <= now ? current : inMonth(at.getUTCFullYear(), at.getUTCMonth() - 1);
const year = at.getUTCFullYear(), month = at.getUTCMonth() - (anchor <= now && inMonth(at.getUTCFullYear(), at.getUTCMonth()) > now ? 1 : 0);
return { start: inMonth(year, month), expiresAt: inMonth(year, month + 1) };
}
/** Manual estimate configuration, present only when both amount and date are set. A monthly credit counts from its latest renewal. */
export function prepaidFrom(values: Record<string, unknown>, provider: ApiBillingProvider, now = Date.now()): ApiBillingPrepaid | undefined {
const keys = prepaidPreferenceKeys[provider], amountUSD = values[keys.amount], since = prepaidDay(values[keys.since]);
if (!validPrepaidAmount(amountUSD) || amountUSD <= 0 || since === undefined) return undefined;
return values[keys.monthly] === true ? { amountUSD, since: latestRenewal(since, now), monthly: true } : { amountUSD, since };
if (values[keys.monthly] !== true) return { amountUSD, since };
const cycle = renewalCycle(since, now);
return { amountUSD, since: cycle.start, monthly: true, expiresAt: cycle.expiresAt };
}
10 changes: 6 additions & 4 deletions src/main/providers/api-billing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function privateDirectory(home: string, platform: Platform, env: NodeJS.ProcessE
export function parseApiBillingSnapshot(raw: string, provider: ApiBillingProvider, now = Date.now()): ApiBillingSnapshot {
if (Buffer.byteLength(raw) > maxBytes) throw invalid();
const root = record(selectJSON(raw, { schema: true, provider: true, capturedAt: true, monthStart: true, periodEnd: true, currency: true, daily: { "*": { start: true, end: true, amountUSD: true } },
balance: { source: true, availableUSD: true, grantedUSD: true, usedUSD: true, prepaidUSD: true, since: true, spentSinceUSD: true, monthly: true } }, undefined, true));
balance: { source: true, availableUSD: true, grantedUSD: true, usedUSD: true, prepaidUSD: true, since: true, spentSinceUSD: true, monthly: true, expiresAt: true } }, undefined, true));
const scalarRows = record(selectJSON(raw, { daily: { "*": true } }));
if (Array.isArray(scalarRows.daily) && scalarRows.daily.length) throw invalid();
const capturedAt = timestamp(root.capturedAt), start = timestamp(root.monthStart), periodEnd = timestamp(root.periodEnd);
Expand All @@ -48,8 +48,10 @@ function parseBalance(row: Record<string, unknown>, provider: ApiBillingProvider
if (row.source !== "manual" || typeof row.availableUSD !== "number" || !Number.isFinite(row.availableUSD)) throw invalid();
const prepaidUSD = amount(row.prepaidUSD), spentSinceUSD = amount(row.spentSinceUSD), since = timestamp(row.since);
if (since % day !== 0 || since > periodEnd || row.monthly !== undefined && row.monthly !== true) throw invalid();
const expiresAt = row.expiresAt === undefined ? undefined : timestamp(row.expiresAt);
if (expiresAt !== undefined && (row.monthly !== true || expiresAt % day !== 0 || expiresAt <= periodEnd)) throw invalid();
// Derived, so a hand-edited file cannot show a remaining amount that disagrees with its inputs.
return { source: "manual", availableUSD: prepaidUSD - spentSinceUSD, prepaidUSD, since, spentSinceUSD, ...(row.monthly === true ? { monthly: true as const } : {}) };
return { source: "manual", availableUSD: prepaidUSD - spentSinceUSD, prepaidUSD, since, spentSinceUSD, ...(row.monthly === true ? { monthly: true as const } : {}), ...(expiresAt === undefined ? {} : { expiresAt }) };
}

export function readApiBilling(home: string, provider: ApiBillingProvider, now = Date.now(), platform: Platform = process.platform, env: NodeJS.ProcessEnv = process.env): ApiBillingReading {
Expand Down Expand Up @@ -166,11 +168,11 @@ export async function collectApiBilling(provider: ApiBillingProvider, key: strin
return { source: "creditGrants", availableUSD: amount(root.total_available), grantedUSD: amount(root.total_granted), usedUSD: amount(root.total_used) };
};

const manual = async (daily: ApiBillingSnapshot["daily"], { amountUSD, since, monthly }: ApiBillingPrepaid): Promise<ApiBillingBalance | undefined> => {
const manual = async (daily: ApiBillingSnapshot["daily"], { amountUSD, since, monthly, expiresAt }: ApiBillingPrepaid): Promise<ApiBillingBalance | undefined> => {
if (since > end || since % day !== 0) return undefined;
const earlier = since < start ? (await costs(since, start)).filter(row => row.end <= start) : [];
const spentSinceUSD = [...earlier, ...daily].filter(row => row.start >= since).reduce((sum, row) => sum + row.amountUSD, 0);
return { source: "manual", availableUSD: amountUSD - spentSinceUSD, prepaidUSD: amountUSD, since, spentSinceUSD, ...(monthly ? { monthly } : {}) };
return { source: "manual", availableUSD: amountUSD - spentSinceUSD, prepaidUSD: amountUSD, since, spentSinceUSD, ...(monthly ? { monthly } : {}), ...(monthly && expiresAt !== undefined ? { expiresAt } : {}) };
};

try {
Expand Down
9 changes: 7 additions & 2 deletions src/renderer/api-billing-setup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,19 @@ export function ApiBillingSetup({ provider, disabled, action, savedKey = true }:

const usd = (x: number) => new Intl.NumberFormat("en", { style: "currency", currency: "USD", maximumFractionDigits: 2 }).format(x);
const isoDay = (at: number) => new Date(at).toISOString().slice(0, 10);
const daysLeft = (ms: number) => { const days = Math.ceil(ms / 86400000); return `${days} day${days === 1 ? "" : "s"}`; };

// Total, used and left always come from the same three inputs, so the figures add up.
export function ApiBillingBalanceLine({ balance }: { balance?: ApiBillingBalance }) {
export function ApiBillingBalanceLine({ balance, now }: { balance?: ApiBillingBalance; now: number }) {
if (!balance) return null;
const reported = balance.source === "creditGrants";
const total = reported ? balance.grantedUSD : balance.prepaidUSD, used = reported ? balance.usedUSD : balance.spentSinceUSD;
const expiresAt = reported ? undefined : balance.expiresAt, expired = expiresAt !== undefined && now >= expiresAt;
const exhausted = balance.availableUSD < 0, mark = reported ? "" : "~";
return <div className="api-balance">
<dl className="metrics api-balance-metrics"><div><dt>Total credit</dt><dd>{usd(total)}</dd></div><div><dt>Used</dt><dd>{usd(used)}</dd></div><div><dt>Left</dt><dd className={exhausted ? "stale" : undefined}>{exhausted ? usd(0) : `${mark}${usd(balance.availableUSD)}`}</dd></div></dl>
<dl className="metrics api-balance-metrics"><div><dt>Total credit</dt><dd>{usd(total)}</dd></div><div><dt>Used</dt><dd>{usd(used)}</dd></div><div><dt>Left</dt><dd className={exhausted || expired ? "stale" : undefined}>{expired ? "Expired" : exhausted ? usd(0) : `${mark}${usd(balance.availableUSD)}`}</dd></div></dl>
{expired ? <p className="stale">This credit expired on {isoDay(expiresAt)}. Fetch billing to count the new cycle.</p>
: expiresAt !== undefined && <p className="secondary">Expires {isoDay(expiresAt)} UTC · {daysLeft(expiresAt - now)} left</p>}
{reported ? <p className="secondary">OpenAI credit grants (unofficial)</p>
: exhausted ? <p className="stale">Estimated balance exhausted · {usd(used)} spent since {isoDay(balance.since)} exceeds the {usd(total)} prepaid. Update prepaid credit in Settings.</p>
: <p className="secondary">Estimate: {usd(total)} {balance.monthly ? "monthly credit renewed" : "prepaid on"} {isoDay(balance.since)} minus {usd(used)} spent since</p>}
Expand All @@ -63,6 +67,7 @@ export function PrepaidCreditSetup({ provider, values, disabled, action }: { pro
};
return <form className="api-billing-setup api-prepaid" onSubmit={async event => { event.preventDefault(); await save(false); }}>
<p className="secondary connection-help">{provider === "openai" ? "Balance fallback: if OpenAI does not report a balance, MeterUsage estimates it" : "Anthropic does not report a credit balance to Admin keys. MeterUsage estimates it"} from your credit total and top-up date minus spend since that day. For a monthly credit, select Renews monthly. Fetch billing again after saving.</p>
{provider === "anthropic" && <p className="secondary connection-help">Max and Ultra plan API credits arrive each billing cycle and expire at the end of it. Enter the monthly amount and the date it arrived, and select Renews monthly.</p>}
<label className="api-key-field"><span className="secondary">Prepaid credit (USD)</span><input ref={amount} aria-label={`${name} prepaid credit in USD`} type="number" min="0.01" max={maxPrepaidUSD} step="0.01" required disabled={disabled || busy} defaultValue={typeof stored === "number" && stored > 0 ? stored : undefined} placeholder="e.g. 50" /></label>
<label className="api-key-field"><span className="secondary">Added on (UTC date)</span><input ref={since} aria-label={`${name} prepaid credit date`} type="date" required disabled={disabled || busy} defaultValue={typeof storedSince === "string" ? storedSince : undefined} /></label>
<label className="secondary connection-help api-key-save"><input ref={monthly} type="checkbox" disabled={disabled || busy} defaultChecked={values[keys.monthly] === true} /> Renews monthly: the credit resets on this day each month</label>
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -310,13 +310,13 @@ export function ApiBillingCards({ state }: { state: ViewState }) {
return <>{apiBillingProviders.map(provider => {
const reading = state.snapshot.apiBilling?.[provider];
if (reading?.status !== "value") return null;
return <section key={provider} className="provider-card" aria-label={`${apiBillingNames[provider]} billing`}><div className="row"><h2>{apiBillingNames[provider]} <small>API billing</small></h2><strong>{reading.value.daily.length ? `${money(reading.value.daily.reduce((sum, day) => sum + day.amountUSD, 0))} in ${new Date(reading.value.monthStart).toLocaleString("en", { month: "long", timeZone: "UTC" })}` : "No cost buckets reported"}</strong></div><ApiBillingBalanceLine balance={reading.value.balance} /><ApiBillingDetails reading={reading} />{provider === "anthropic" && <p className="secondary">Priority Tier excluded.</p>}</section>;
return <section key={provider} className="provider-card" aria-label={`${apiBillingNames[provider]} billing`}><div className="row"><h2>{apiBillingNames[provider]} <small>API billing</small></h2><strong>{reading.value.daily.length ? `${money(reading.value.daily.reduce((sum, day) => sum + day.amountUSD, 0))} in ${new Date(reading.value.monthStart).toLocaleString("en", { month: "long", timeZone: "UTC" })}` : "No cost buckets reported"}</strong></div><ApiBillingBalanceLine balance={reading.value.balance} now={state.snapshot.clock} /><ApiBillingDetails reading={reading} />{provider === "anthropic" && <p className="secondary">Priority Tier excluded.</p>}</section>;
})}</>;
}
export function ApiBillingConnections({ state, action }: { state: ViewState; action: (r: Request) => Promise<boolean | void> }) {
return <section className="connections" aria-label="API connections"><h2>API connections <small>Beta</small></h2><p className="secondary section-description">View organization API spend and your credit total, amount used and amount left. Use an Admin key, not a project key or ChatGPT or Claude subscription sign-in.</p><p className="secondary section-description">Use a saved key or paste an Admin key. Pasted keys are cleared on submit. On macOS, a pasted key is saved in Keychain after a successful fetch unless you clear Save key.</p>{state.snapshot.demo && <p className="secondary connection-demo">API access is disabled in this profile.</p>}<div className="settings-group">{apiBillingProviders.map(provider => {
const reading = state.snapshot.apiBilling?.[provider];
return <div className="provider-setting connection-row" key={provider}><strong>{apiBillingNames[provider]}</strong>{reading?.status === "value" ? <><ApiBillingBalanceLine balance={reading.value.balance} /><ApiBillingDetails reading={reading} /></> : <p className="secondary">{reading?.code === "unavailable" ? "Billing snapshot unavailable. Fetch again to replace it." : "No billing snapshot yet."}</p>}<ApiBillingSetup provider={provider} disabled={state.snapshot.demo} action={action} savedKey={state.platform !== "win32"} /><PrepaidCreditSetup provider={provider} values={state.settings.values} disabled={state.snapshot.demo} action={action} />{provider === "anthropic" && <p className="secondary">Priority Tier costs are excluded.</p>}</div>;
return <div className="provider-setting connection-row" key={provider}><strong>{apiBillingNames[provider]}</strong>{reading?.status === "value" ? <><ApiBillingBalanceLine balance={reading.value.balance} now={state.snapshot.clock} /><ApiBillingDetails reading={reading} /></> : <p className="secondary">{reading?.code === "unavailable" ? "Billing snapshot unavailable. Fetch again to replace it." : "No billing snapshot yet."}</p>}<ApiBillingSetup provider={provider} disabled={state.snapshot.demo} action={action} savedKey={state.platform !== "win32"} /><PrepaidCreditSetup provider={provider} values={state.settings.values} disabled={state.snapshot.demo} action={action} />{provider === "anthropic" && <p className="secondary">Priority Tier costs are excluded.</p>}</div>;
})}</div><p className="secondary">Fetch billing updates the snapshot automatically. Refresh rereads saved snapshots. OpenRouter keeps its existing connection.</p></section>;
}
export function Connections({ state, action }: { state: ViewState; action: (r: Request) => Promise<boolean | void> }) {
Expand Down
Loading
Loading