diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cad513..782d803 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/API_USAGE_BETA.md b/docs/API_USAGE_BETA.md index 31a3890..a68fcbe 100644 --- a/docs/API_USAGE_BETA.md +++ b/docs/API_USAGE_BETA.md @@ -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). diff --git a/docs/KB.md b/docs/KB.md index 1899a35..f794c89 100644 --- a/docs/KB.md +++ b/docs/KB.md @@ -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). diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index b55b8a1..c7ec8f7 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -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 diff --git a/docs/adr/0049-api-credit-total-used-left.md b/docs/adr/0049-api-credit-total-used-left.md index 64d23d2..e568d9a 100644 --- a/docs/adr/0049-api-credit-total-used-left.md +++ b/docs/adr/0049-api-credit-total-used-left.md @@ -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. diff --git a/src/domain/api-billing.ts b/src/domain/api-billing.ts index efd5154..e6b2d88 100644 --- a/src/domain/api-billing.ts +++ b/src/domain/api-billing.ts @@ -7,7 +7,7 @@ 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 }[]; @@ -15,7 +15,7 @@ export interface ApiBillingSnapshot { } 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" }, @@ -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, 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 }; } diff --git a/src/main/providers/api-billing.ts b/src/main/providers/api-billing.ts index 6eb7966..7b4a664 100644 --- a/src/main/providers/api-billing.ts +++ b/src/main/providers/api-billing.ts @@ -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); @@ -48,8 +48,10 @@ function parseBalance(row: Record, 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 { @@ -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 => { + const manual = async (daily: ApiBillingSnapshot["daily"], { amountUSD, since, monthly, expiresAt }: ApiBillingPrepaid): Promise => { 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 { diff --git a/src/renderer/api-billing-setup.tsx b/src/renderer/api-billing-setup.tsx index 4962f09..cec13dd 100644 --- a/src/renderer/api-billing-setup.tsx +++ b/src/renderer/api-billing-setup.tsx @@ -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
-
Total credit
{usd(total)}
Used
{usd(used)}
Left
{exhausted ? usd(0) : `${mark}${usd(balance.availableUSD)}`}
+
Total credit
{usd(total)}
Used
{usd(used)}
Left
{expired ? "Expired" : exhausted ? usd(0) : `${mark}${usd(balance.availableUSD)}`}
+ {expired ?

This credit expired on {isoDay(expiresAt)}. Fetch billing to count the new cycle.

+ : expiresAt !== undefined &&

Expires {isoDay(expiresAt)} UTC · {daysLeft(expiresAt - now)} left

} {reported ?

OpenAI credit grants (unofficial)

: exhausted ?

Estimated balance exhausted · {usd(used)} spent since {isoDay(balance.since)} exceeds the {usd(total)} prepaid. Update prepaid credit in Settings.

:

Estimate: {usd(total)} {balance.monthly ? "monthly credit renewed" : "prepaid on"} {isoDay(balance.since)} minus {usd(used)} spent since

} @@ -63,6 +67,7 @@ export function PrepaidCreditSetup({ provider, values, disabled, action }: { pro }; return
{ event.preventDefault(); await save(false); }}>

{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.

+ {provider === "anthropic" &&

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.

} diff --git a/src/renderer/app.tsx b/src/renderer/app.tsx index f7e3b8b..387c882 100644 --- a/src/renderer/app.tsx +++ b/src/renderer/app.tsx @@ -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

{apiBillingNames[provider]} API billing

{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"}
{provider === "anthropic" &&

Priority Tier excluded.

}
; + return

{apiBillingNames[provider]} API billing

{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"}
{provider === "anthropic" &&

Priority Tier excluded.

}
; })}; } export function ApiBillingConnections({ state, action }: { state: ViewState; action: (r: Request) => Promise }) { return

API connections Beta

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.

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.

{state.snapshot.demo &&

API access is disabled in this profile.

}
{apiBillingProviders.map(provider => { const reading = state.snapshot.apiBilling?.[provider]; - return
{apiBillingNames[provider]}{reading?.status === "value" ? <> :

{reading?.code === "unavailable" ? "Billing snapshot unavailable. Fetch again to replace it." : "No billing snapshot yet."}

}{provider === "anthropic" &&

Priority Tier costs are excluded.

}
; + return
{apiBillingNames[provider]}{reading?.status === "value" ? <> :

{reading?.code === "unavailable" ? "Billing snapshot unavailable. Fetch again to replace it." : "No billing snapshot yet."}

}{provider === "anthropic" &&

Priority Tier costs are excluded.

}
; })}

Fetch billing updates the snapshot automatically. Refresh rereads saved snapshots. OpenRouter keeps its existing connection.

; } export function Connections({ state, action }: { state: ViewState; action: (r: Request) => Promise }) { diff --git a/tests/api-billing-balance.test.ts b/tests/api-billing-balance.test.ts index f70d82d..762233d 100644 --- a/tests/api-billing-balance.test.ts +++ b/tests/api-billing-balance.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { createElement } from "react"; import { renderToStaticMarkup } from "react-dom/server"; -import { latestRenewal, prepaidDay, prepaidFrom, type ApiBillingSnapshot } from "../src/domain/api-billing"; +import { renewalCycle, prepaidDay, prepaidFrom, type ApiBillingSnapshot } from "../src/domain/api-billing"; import { collectApiBilling, parseApiBillingSnapshot } from "../src/main/providers/api-billing"; import { parseRequest } from "../src/main/ipc"; import { ApiBillingBalanceLine } from "../src/renderer/api-billing-setup"; @@ -90,10 +90,10 @@ describe("OpenAI remaining balance", () => { expect(JSON.stringify(value)).not.toContain("PRIVATE"); }); - it("keeps the monthly flag on an estimate from a renewing credit", async () => { + it("keeps the monthly flag and expiry on an estimate from a renewing credit", async () => { const since = start + 5 * day; - const value = await collectApiBilling("anthropic", "synthetic-key", now, async () => Response.json({ data: [{ starting_at: new Date(since).toISOString(), ending_at: new Date(since + day).toISOString(), results: [{ amount: "300", currency: "USD" }] }], has_more: false }), { amountUSD: 20, since, monthly: true }); - expect(value.balance).toEqual({ source: "manual", availableUSD: 17, prepaidUSD: 20, since, spentSinceUSD: 3, monthly: true }); + const value = await collectApiBilling("anthropic", "synthetic-key", now, async () => Response.json({ data: [{ starting_at: new Date(since).toISOString(), ending_at: new Date(since + day).toISOString(), results: [{ amount: "300", currency: "USD" }] }], has_more: false }), { amountUSD: 20, since, monthly: true, expiresAt: since + 31 * day }); + expect(value.balance).toEqual({ source: "manual", availableUSD: 17, prepaidUSD: 20, since, spentSinceUSD: 3, monthly: true, expiresAt: since + 31 * day }); expect(parseApiBillingSnapshot(JSON.stringify(value), "anthropic", now).balance).toEqual(value.balance); }); @@ -104,6 +104,7 @@ describe("OpenAI remaining balance", () => { { source: "other", availableUSD: 1 }, { source: "creditGrants", availableUSD: -1, grantedUSD: 1, usedUSD: 1 }, { source: "creditGrants", availableUSD: 1, grantedUSD: 1 }, { ...manual, since: start + 1 }, { ...manual, since: now + day }, { ...manual, prepaidUSD: -1 }, { ...manual, availableUSD: "1" }, { ...manual, monthly: false }, { ...manual, monthly: "yes" }, + { ...manual, expiresAt: start + 31 * day }, { ...manual, monthly: true, expiresAt: start + 31 * day + 1 }, { ...manual, monthly: true, expiresAt: start }, { ...manual, monthly: true, expiresAt: "soon" }, ]) expect(() => parseApiBillingSnapshot(JSON.stringify(base(balance)), "openai", now), JSON.stringify(balance)).toThrow(); expect(parseApiBillingSnapshot(JSON.stringify({ ...base(manual), provider: "anthropic" }), "anthropic", now).balance).toEqual({ ...manual, availableUSD: -2 }); expect(() => parseApiBillingSnapshot(JSON.stringify({ ...base({ source: "creditGrants", availableUSD: 1, grantedUSD: 1, usedUSD: 0 }), provider: "anthropic" }), "anthropic", now)).toThrow(); @@ -125,23 +126,30 @@ describe("prepaid credit preferences", () => { expect(prepaidFrom({ openAIPrepaidCreditUSD: 25, openAIPrepaidSince: "2026-10-05" }, "anthropic")).toBeUndefined(); expect(prepaidFrom({ anthropicPrepaidCreditUSD: 10, anthropicPrepaidSince: "2026-10-05" }, "anthropic", now)).toEqual({ amountUSD: 10, since: Date.UTC(2026, 9, 5) }); }); - it("counts a monthly credit from its latest renewal", () => { - expect(prepaidFrom({ anthropicPrepaidCreditUSD: 10, anthropicPrepaidSince: "2026-08-05", anthropicPrepaidMonthly: true }, "anthropic", now)).toEqual({ amountUSD: 10, since: Date.UTC(2026, 9, 5), monthly: true }); - expect(latestRenewal(Date.UTC(2026, 7, 20), now)).toBe(Date.UTC(2026, 8, 20)); - expect(latestRenewal(Date.UTC(2026, 0, 31), Date.parse("2026-03-01T12:00:00Z"))).toBe(Date.UTC(2026, 1, 28)); - expect(latestRenewal(Date.UTC(2026, 0, 31), Date.parse("2026-03-31T00:00:00Z"))).toBe(Date.UTC(2026, 2, 31)); - expect(latestRenewal(Date.UTC(2026, 9, 16), now)).toBe(Date.UTC(2026, 9, 16)); - expect(latestRenewal(now + day, now)).toBe(now + day); + it("counts a monthly credit from its latest renewal and expires it at the next", () => { + expect(prepaidFrom({ anthropicPrepaidCreditUSD: 10, anthropicPrepaidSince: "2026-08-05", anthropicPrepaidMonthly: true }, "anthropic", now)).toEqual({ amountUSD: 10, since: Date.UTC(2026, 9, 5), monthly: true, expiresAt: Date.UTC(2026, 10, 5) }); + const cycle = (start: number, expiresAt: number) => ({ start, expiresAt }); + expect(renewalCycle(Date.UTC(2026, 7, 20), now)).toEqual(cycle(Date.UTC(2026, 8, 20), Date.UTC(2026, 9, 20))); + expect(renewalCycle(Date.UTC(2026, 0, 31), Date.parse("2026-03-01T12:00:00Z"))).toEqual(cycle(Date.UTC(2026, 1, 28), Date.UTC(2026, 2, 31))); + expect(renewalCycle(Date.UTC(2026, 0, 31), Date.parse("2026-03-31T00:00:00Z"))).toEqual(cycle(Date.UTC(2026, 2, 31), Date.UTC(2026, 3, 30))); + expect(renewalCycle(Date.UTC(2026, 11, 15), Date.parse("2027-01-02T00:00:00Z"))).toEqual(cycle(Date.UTC(2026, 11, 15), Date.UTC(2027, 0, 15))); + expect(renewalCycle(Date.UTC(2026, 9, 16), now)).toEqual(cycle(Date.UTC(2026, 9, 16), Date.UTC(2026, 10, 16))); + expect(renewalCycle(Date.UTC(2026, 9, 20), now)).toEqual(cycle(Date.UTC(2026, 9, 20), Date.UTC(2026, 10, 20))); }); }); describe("balance line", () => { - const html = (balance: ApiBillingSnapshot["balance"]) => renderToStaticMarkup(createElement(ApiBillingBalanceLine, { balance })); + const html = (balance: ApiBillingSnapshot["balance"], at = now) => renderToStaticMarkup(createElement(ApiBillingBalanceLine, { balance, now: at })); it("shows total credit, used and left for reported, estimated, monthly and exhausted balances", () => { expect(html(undefined)).toBe(""); expect(html({ source: "creditGrants", availableUSD: 62.5, grantedUSD: 100, usedUSD: 37.5 })).toMatch(/Total credit<\/dt>
\$100\.00<.*Used<\/dt>
\$37\.50<.*Left<\/dt>
\$62\.50<.*unofficial/); expect(html({ source: "manual", availableUSD: 16.5, prepaidUSD: 20, since: Date.UTC(2026, 9, 6), spentSinceUSD: 3.5 })).toMatch(/Total credit<\/dt>
\$20\.00<.*Used<\/dt>
\$3\.50<.*Left<\/dt>
~\$16\.50<.*Estimate.*\$20\.00 prepaid on 2026-10-06/); expect(html({ source: "manual", availableUSD: 7, prepaidUSD: 10, since: Date.UTC(2026, 10, 1), spentSinceUSD: 3, monthly: true })).toMatch(/monthly credit renewed 2026-11-01/); + const monthly = { source: "manual", availableUSD: 150, prepaidUSD: 200, since: Date.UTC(2026, 9, 5), spentSinceUSD: 50, monthly: true, expiresAt: Date.UTC(2026, 10, 5) } as const; + expect(html(monthly)).toMatch(/Left<\/dt>
~\$150\.00<.*Expires 2026-11-05 UTC · 20 days left/); + expect(html(monthly, Date.UTC(2026, 10, 4, 12))).toMatch(/1 day left/); + expect(html(monthly, Date.UTC(2026, 10, 5))).toMatch(/Left<\/dt>
Expired<.*expired on 2026-11-05\. Fetch billing to count the new cycle/); + expect(html(monthly)).not.toMatch(/Expired/); expect(html({ source: "manual", availableUSD: -2, prepaidUSD: 10, since: Date.UTC(2026, 9, 6), spentSinceUSD: 12 })).toMatch(/Left<\/dt>
\$0\.00<.*exhausted/); }); }); diff --git a/tests/api-billing-setup.test.ts b/tests/api-billing-setup.test.ts index 052ba0b..302d448 100644 --- a/tests/api-billing-setup.test.ts +++ b/tests/api-billing-setup.test.ts @@ -111,6 +111,7 @@ describe.each([ const html = renderToStaticMarkup(createElement(PrepaidCreditSetup, { provider, values: { [monthlyKey]: true }, disabled: false, action: vi.fn() })); expect(html).toContain("Renews monthly"); expect(html).toContain('checked=""'); expect(html).toContain(`${provider === "openai" ? "OpenAI" : "Anthropic"} API prepaid credit in USD`); + expect(html.includes("expire at the end of it")).toBe(provider === "anthropic"); }); it("stops at the first failed write so the amount never pairs with a stale date", async () => { const { action, form } = mount({ [amountKey]: 10, [sinceKey]: "2026-09-01" }, "25", "2026-10-05", [true, false]);