From 20d7091cea29adc24adab2d55baa3ecea9d4f2fd Mon Sep 17 00:00:00 2001 From: Janghoon Lee <44862514+its-janghoon@users.noreply.github.com> Date: Fri, 13 Nov 2026 06:55:52 +0000 Subject: [PATCH] feat(tui): show Console balance and spend in /status /status gets a Console block: the workspace balance, today's spend and this month's spend across every device, with request counts and the billing link. A complimentary workspace says so instead of showing a balance, and a balance under $1 is shown as a warning. The engine reads it through a new GET /experimental/console/usage?tz= route. It calls the Console's GET /usage/summary with the key and base URL the Redrob provider already uses for inference (options.apiKey, else the merged credential; options.baseURL, else CONSOLE_URL, so REDROB_CONSOLE_URL still selects dev). The key never reaches the TUI and is never logged. The TUI fetches once when /status opens, not on a timer. The engine waits at most 5 seconds. No key, 401, 400, 429, 404 (a Console without the route), a timeout or a body that does not parse all return null, and the dialog shows the plain billing link as before. --- packages/core/src/balance.ts | 64 ++++++++++++++ packages/core/test/balance.test.ts | 87 +++++++++++++++++++ .../instance/httpapi/groups/experimental.ts | 18 ++++ .../instance/httpapi/handlers/experimental.ts | 20 +++++ .../test/server/httpapi-exercise/index.ts | 10 +++ packages/sdk/js/src/v2/gen/sdk.gen.ts | 38 ++++++++ packages/sdk/js/src/v2/gen/types.gen.ts | 46 ++++++++++ packages/tui/src/component/dialog-status.tsx | 69 ++++++++++++++- packages/tui/src/i18n/en.ts | 9 ++ packages/tui/src/i18n/ko.ts | 9 ++ packages/tui/src/util/usage.ts | 31 +++++++ packages/tui/test/util/usage.test.ts | 33 +++++++ 12 files changed, 430 insertions(+), 4 deletions(-) create mode 100644 packages/core/src/balance.ts create mode 100644 packages/core/test/balance.test.ts diff --git a/packages/core/src/balance.ts b/packages/core/src/balance.ts new file mode 100644 index 0000000000..ec799f65c4 --- /dev/null +++ b/packages/core/src/balance.ts @@ -0,0 +1,64 @@ +export * as Balance from "./balance" + +import { Effect, Schema } from "effect" +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http" + +/** + * The workspace's balance and spend, read from the console for `/status`. + * + * `GET /usage/summary?tz=` with the same workspace API key the Redrob provider + * already sends for inference. The figures are the workspace's, across every device and app, which is + * what the local session totals cannot say. + * + * Every failure is quiet: no key, a refused key (401), a bad zone (400), the rate limit (429), a console + * that does not have the route yet (404), a timeout or a body that does not parse all return + * `undefined`, and the caller shows the billing link it showed before. Nothing here logs, and the key + * never leaves the request header. + */ + +/** `/status` waits for this, so it stays short: a slow console must not hold the dialog. */ +const TIMEOUT = "5 seconds" + +const Period = Schema.Struct({ + since: Schema.String, + spend: Schema.Finite, + requestCount: Schema.Finite, +}).annotate({ identifier: "ConsoleUsagePeriod" }) + +export const Summary = Schema.Struct({ + currency: Schema.String, + balance: Schema.Finite, + complimentary: Schema.Boolean, + plan: Schema.optional(Schema.String), + tz: Schema.String, + today: Period, + month: Period, +}).annotate({ identifier: "ConsoleUsageSummary" }) +export type Summary = Schema.Schema.Type + +export type Input = { + /** The console API base, `CONSOLE_URL` or the provider's configured `baseURL`. */ + url: string + key: string + tz: string +} + +const decode = Schema.decodeUnknownOption(Schema.fromJsonString(Summary)) + +const read = Effect.fn("Balance.read")(function* (input: Input) { + const http = yield* HttpClient.HttpClient + const url = `${input.url.replace(/\/+$/, "")}/usage/summary?${new URLSearchParams({ tz: input.tz })}` + const response = yield* http.execute( + HttpClientRequest.get(url).pipe(HttpClientRequest.acceptJson, HttpClientRequest.bearerToken(input.key)), + ) + if (response.status !== 200) return undefined + const parsed = decode(yield* response.text) + return parsed._tag === "Some" ? parsed.value : undefined +}) + +export const summary = (input: Input): Effect.Effect => + read(input).pipe( + Effect.timeout(TIMEOUT), + Effect.provide(FetchHttpClient.layer), + Effect.catchCause(() => Effect.succeed(undefined)), + ) diff --git a/packages/core/test/balance.test.ts b/packages/core/test/balance.test.ts new file mode 100644 index 0000000000..7f92b8d4f2 --- /dev/null +++ b/packages/core/test/balance.test.ts @@ -0,0 +1,87 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test" +import { Effect } from "effect" +import { Balance } from "@redrob-code/core/balance" + +/** + * A stand-in console on loopback. Each test picks the reply by the key it sends, so the request the + * module builds (path, query, bearer header) is checked on every call. + */ +const body = { + currency: "USD", + balance: 20.368355, + complimentary: false, + plan: "free", + tz: "Asia/Seoul", + today: { since: "2026-11-12T15:00:00.000Z", spend: 0, requestCount: 0 }, + month: { since: "2026-10-31T15:00:00.000Z", spend: 147.07, requestCount: 16764 }, +} + +const seen: { path: string; tz: string | null; auth: string | null }[] = [] +let server: ReturnType +let url: string + +beforeAll(() => { + server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + async fetch(request) { + const parsed = new URL(request.url) + const auth = request.headers.get("authorization") + seen.push({ path: parsed.pathname, tz: parsed.searchParams.get("tz"), auth }) + if (parsed.pathname !== "/api/backend/v1/usage/summary") return new Response("not found", { status: 404 }) + switch (auth) { + case "Bearer ok": + return Response.json(body) + case "Bearer slow": + await Bun.sleep(7_000) + return Response.json(body) + case "Bearer garbled": + return new Response("{not json", { status: 200 }) + case "Bearer partial": + return Response.json({ currency: "USD", balance: 1 }) + case "Bearer limited": + return Response.json({ message: "slow down" }, { status: 429, headers: { "retry-after": "30" } }) + default: + return Response.json({ message: "invalid api key" }, { status: 401 }) + } + }, + }) + url = `http://127.0.0.1:${server.port}/api/backend/v1` +}) + +afterAll(() => server.stop(true)) + +const run = (key: string, base = url) => Effect.runPromise(Balance.summary({ url: base, key, tz: "Asia/Seoul" })) + +describe("Balance.summary", () => { + test("reads the console's summary with the key as a bearer token and the zone as a query", async () => { + seen.length = 0 + expect(await run("ok")).toEqual(body) + expect(seen).toEqual([{ path: "/api/backend/v1/usage/summary", tz: "Asia/Seoul", auth: "Bearer ok" }]) + }) + + test("tolerates a trailing slash on the base URL", async () => { + expect(await run("ok", `${url}/`)).toEqual(body) + }) + + test("a refused key, the rate limit and a missing route fall back quietly", async () => { + expect(await run("wrong")).toBeUndefined() + expect(await run("limited")).toBeUndefined() + expect(await run("ok", `http://127.0.0.1:${server.port}/old`)).toBeUndefined() + }) + + test("a body that does not parse or misses fields falls back", async () => { + expect(await run("garbled")).toBeUndefined() + expect(await run("partial")).toBeUndefined() + }) + + test("an unreachable console falls back", async () => { + expect(await run("ok", "http://127.0.0.1:1/api/backend/v1")).toBeUndefined() + }) + + test("a console slower than the timeout falls back", async () => { + const start = Date.now() + expect(await run("slow")).toBeUndefined() + expect(Date.now() - start).toBeLessThan(6_500) + }, 10_000) +}) diff --git a/packages/redrob/src/server/routes/instance/httpapi/groups/experimental.ts b/packages/redrob/src/server/routes/instance/httpapi/groups/experimental.ts index 7d16f2a1eb..1e9d7d53a7 100644 --- a/packages/redrob/src/server/routes/instance/httpapi/groups/experimental.ts +++ b/packages/redrob/src/server/routes/instance/httpapi/groups/experimental.ts @@ -18,6 +18,7 @@ import { described } from "./metadata" import { QueryBoolean } from "./query" import { ProviderV2 } from "@redrob-code/core/provider" import { ModelV2 } from "@redrob-code/core/model" +import { Balance } from "@redrob-code/core/balance" const ConsoleStateResponse = Schema.Struct({ consoleManagedProviders: Schema.mutable(Schema.Array(Schema.String)), @@ -99,6 +100,11 @@ export class WorktreeApiError extends Schema.ErrorClass("Workt }, { httpApiStatus: 400 }, ) {} +/** The caller's IANA zone, so "today" and "this month" are the user's own. */ +export const ConsoleUsageQuery = Schema.Struct({ + ...WorkspaceRoutingQueryFields, + tz: Schema.String, +}) export const SessionListQuery = Schema.Struct({ ...WorkspaceRoutingQueryFields, roots: Schema.optional(QueryBoolean), @@ -121,6 +127,7 @@ export const ExperimentalPaths = { console: "/experimental/console", consoleOrgs: "/experimental/console/orgs", consoleSwitch: "/experimental/console/switch", + consoleUsage: "/experimental/console/usage", tool: "/experimental/tool", toolIDs: "/experimental/tool/ids", worktree: "/experimental/worktree", @@ -167,6 +174,17 @@ export const ExperimentalApi = HttpApi.make("experimental") description: "Get the available Console orgs across logged-in accounts, including the current active org.", }), ), + HttpApiEndpoint.get("consoleUsage", ExperimentalPaths.consoleUsage, { + query: ConsoleUsageQuery, + success: described(Schema.NullOr(Balance.Summary), "Console balance and spend, or null"), + }).annotateMerge( + OpenApi.annotations({ + identifier: "experimental.console.usage", + summary: "Get Console balance and spend", + description: + "The Redrob workspace's balance and today's and this month's spend across every device, read from the Console with the Redrob provider's key. Null when there is no key or the Console does not answer.", + }), + ), HttpApiEndpoint.post("consoleSwitch", ExperimentalPaths.consoleSwitch, { query: WorkspaceRoutingQuery, payload: ConsoleSwitchPayload, diff --git a/packages/redrob/src/server/routes/instance/httpapi/handlers/experimental.ts b/packages/redrob/src/server/routes/instance/httpapi/handlers/experimental.ts index 635abad9cc..4226629678 100644 --- a/packages/redrob/src/server/routes/instance/httpapi/handlers/experimental.ts +++ b/packages/redrob/src/server/routes/instance/httpapi/handlers/experimental.ts @@ -11,12 +11,17 @@ import type { SessionID } from "@/session/schema" import { ToolJsonSchema } from "@/tool/json-schema" import { ToolRegistry } from "@/tool/registry" import { Worktree } from "@/worktree" +import { Provider } from "@/provider/provider" +import { Balance } from "@redrob-code/core/balance" +import { CONSOLE_URL } from "@redrob-code/core/plugin/provider/redrob-constants" +import { ProviderV2 } from "@redrob-code/core/provider" import { Effect, Option } from "effect" import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" import { HttpApiBuilder, HttpApiError } from "effect/unstable/httpapi" import { InstanceHttpApi } from "../api" import { ConsoleSwitchPayload, + ConsoleUsageQuery, SessionListQuery, ToolListQuery, UsageQuery, @@ -41,6 +46,7 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper const sessions = yield* Session.Service const background = yield* BackgroundJob.Service const flags = yield* RuntimeFlags.Service + const providers = yield* Provider.Service const capabilities = Effect.fn("ExperimentalHttpApi.capabilities")(function* () { return { @@ -191,6 +197,19 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper return yield* sessions.usage({ day: ctx.query.day, month: ctx.query.month }) }) + const consoleUsage = Effect.fn("ExperimentalHttpApi.consoleUsage")(function* (ctx: { + query: typeof ConsoleUsageQuery.Type + }) { + // The key and base URL the Redrob provider sends inference with, resolved the way the SDK gets + // them (`options.apiKey`, else the merged credential). "public" is the keyless placeholder. + const info = (yield* providers.list())[ProviderV2.ID.redrob] + const options = (info?.options ?? {}) as { apiKey?: unknown; baseURL?: unknown } + const key = typeof options.apiKey === "string" ? options.apiKey : info?.key + if (!key || key === "public") return null + const url = typeof options.baseURL === "string" && options.baseURL ? options.baseURL : CONSOLE_URL + return (yield* Balance.summary({ url, key, tz: ctx.query.tz })) ?? null + }) + const resource = Effect.fn("ExperimentalHttpApi.resource")(function* () { return yield* mcp.resources() }) @@ -200,6 +219,7 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper .handle("console", getConsole) .handle("consoleOrgs", listConsoleOrgs) .handle("consoleSwitch", switchConsole) + .handle("consoleUsage", consoleUsage) .handle("tool", tool) .handle("toolIDs", toolIDs) .handle("worktree", worktree) diff --git a/packages/redrob/test/server/httpapi-exercise/index.ts b/packages/redrob/test/server/httpapi-exercise/index.ts index 02c330ca89..aa6a1e25b4 100644 --- a/packages/redrob/test/server/httpapi-exercise/index.ts +++ b/packages/redrob/test/server/httpapi-exercise/index.ts @@ -619,6 +619,16 @@ const scenarios: Scenario[] = [ check(body === false, "background route should be a no-op without running subagents") }), http.protected.get("/experimental/resource", "experimental.resource.list").json(), + http.protected + .get("/experimental/console/usage", "experimental.console.usage") + .at((ctx) => ({ + path: `/experimental/console/usage?${new URLSearchParams({ tz: "Asia/Seoul" })}`, + headers: ctx.headers(), + })) + .json(200, (body) => { + // The exerciser has no Redrob key, so the route answers null rather than reaching the console. + check(body === null, "console usage should be null without a Redrob key") + }), http.protected .get("/experimental/usage", "experimental.usage.get") .at((ctx) => ({ diff --git a/packages/sdk/js/src/v2/gen/sdk.gen.ts b/packages/sdk/js/src/v2/gen/sdk.gen.ts index 5a88a0f4e3..51e105eefe 100644 --- a/packages/sdk/js/src/v2/gen/sdk.gen.ts +++ b/packages/sdk/js/src/v2/gen/sdk.gen.ts @@ -42,6 +42,8 @@ import type { ExperimentalConsoleListOrgsErrors, ExperimentalConsoleListOrgsResponses, ExperimentalConsoleSwitchOrgResponses, + ExperimentalConsoleUsageErrors, + ExperimentalConsoleUsageResponses, ExperimentalControlPlaneMoveSessionErrors, ExperimentalControlPlaneMoveSessionResponses, ExperimentalExtensionsCallErrors, @@ -945,6 +947,42 @@ export class Console extends HeyApiClient { }) } + /** + * Get Console balance and spend + * + * The Redrob workspace's balance and today's and this month's spend across every device, read from the Console with the Redrob provider's key. Null when there is no key or the Console does not answer. + */ + public usage( + parameters: { + directory?: string + workspace?: string + tz: string + }, + options?: Options, + ) { + const params = buildClientParams( + [parameters], + [ + { + args: [ + { in: "query", key: "directory" }, + { in: "query", key: "workspace" }, + { in: "query", key: "tz" }, + ], + }, + ], + ) + return (options?.client ?? this.client).get< + ExperimentalConsoleUsageResponses, + ExperimentalConsoleUsageErrors, + ThrowOnError + >({ + url: "/experimental/console/usage", + ...options, + ...params, + }) + } + /** * Switch active Console org * diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index d2ad6e2f33..8ddf3e865d 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -2322,6 +2322,22 @@ export type EffectHttpApiErrorInternalServerError = { _tag: "InternalServerError" } +export type ConsoleUsagePeriod = { + since: string + spend: number + requestCount: number +} + +export type ConsoleUsageSummary = { + currency: string + balance: number + complimentary: boolean + plan?: string + tz: string + today: ConsoleUsagePeriod + month: ConsoleUsagePeriod +} + export type ToolListItem = { id: string description: string @@ -8510,6 +8526,36 @@ export type ExperimentalConsoleListOrgsResponses = { export type ExperimentalConsoleListOrgsResponse = ExperimentalConsoleListOrgsResponses[keyof ExperimentalConsoleListOrgsResponses] +export type ExperimentalConsoleUsageData = { + body?: never + path?: never + query: { + directory?: string + workspace?: string + tz: string + } + url: "/experimental/console/usage" +} + +export type ExperimentalConsoleUsageErrors = { + /** + * Bad request + */ + 400: BadRequestError +} + +export type ExperimentalConsoleUsageError = ExperimentalConsoleUsageErrors[keyof ExperimentalConsoleUsageErrors] + +export type ExperimentalConsoleUsageResponses = { + /** + * Console balance and spend, or null + */ + 200: ConsoleUsageSummary +} + +export type ExperimentalConsoleUsageResponse = + ExperimentalConsoleUsageResponses[keyof ExperimentalConsoleUsageResponses] + export type ExperimentalConsoleSwitchOrgData = { body?: { accountID: string diff --git a/packages/tui/src/component/dialog-status.tsx b/packages/tui/src/component/dialog-status.tsx index 0e4e383346..580a14c254 100644 --- a/packages/tui/src/component/dialog-status.tsx +++ b/packages/tui/src/component/dialog-status.tsx @@ -23,8 +23,9 @@ export function DialogStatus() { const sdk = useSDK() // The current session's running total is the footer's figure; the machine-wide periods come from - // the engine, which sums every session's step-finish parts. Console exposes no balance or spend - // route an API key may read, so the Console figure is a link rather than a number. + // the engine, which sums every session's step-finish parts. The Console block is the workspace's + // balance and spend across every device, which the engine reads from the Console with the Redrob + // provider's key (the key never reaches the TUI). Any failure leaves the plain billing link. const session = createMemo((): Usage.Total | undefined => { if (route.data.type !== "session") return const info = sync.session.get(route.data.sessionID) @@ -51,6 +52,21 @@ export function DialogStatus() { }) const width = createMemo(() => Math.max(...rows().map((row) => Bun.stringWidth(row.label)), 0)) const redrob = createMemo(() => sync.data.provider.some((item) => item.id === "redrob")) + // Read once when the dialog opens, never on a timer: the Console rate-limits this per workspace. + const [remote] = createResource(redrob, async () => { + const result = await sdk.client.experimental.console + .usage({ tz: Intl.DateTimeFormat().resolvedOptions().timeZone }) + .catch(() => undefined) + return result?.data ? Usage.workspace(result.data) : null + }) + const workspace = createMemo(() => (remote.error ? null : remote())) + const billing = `${CONSOLE_HOME_URL}/billing` + const labels = createMemo(() => [ + language.t("status.console.balance"), + language.t("status.console.today"), + language.t("status.console.month"), + ]) + const consoleWidth = createMemo(() => Math.max(...labels().map((label) => Bun.stringWidth(label)))) const enabledFormatters = createMemo(() => sync.data.formatter.filter((f) => f.enabled)) @@ -117,12 +133,57 @@ export function DialogStatus() { - + - {language.t("status.usage.console", { url: `${CONSOLE_HOME_URL}/billing` })} + {language.t("status.usage.console", { url: billing })} + + {(value) => ( + + {language.t("status.console")} + + + {labels()[0]} + + + + + {language.t("status.console.complimentary")} + + + + + {language.t("status.console.low", { balance: value().balance })} + + + + {value().balance} + + + + + + {labels()[1]} + + {language.t("status.console.spend", value().today)} + + + + {labels()[2]} + + {language.t("status.console.spend", value().month)} + + + {language.t("status.console.note")} + + + {language.t("status.console.billing", { url: billing })} + + + )} + 0} fallback={{language.t("status.mcp.empty")}} diff --git a/packages/tui/src/i18n/en.ts b/packages/tui/src/i18n/en.ts index 10657407c7..72a7dbed33 100644 --- a/packages/tui/src/i18n/en.ts +++ b/packages/tui/src/i18n/en.ts @@ -292,6 +292,15 @@ export const dict = { "status.usage.failed": "Could not load usage on this machine", "status.usage.note": "Today, this month and all time add up every session on this machine.", "status.usage.console": "Console balance: {{url}}", + "status.console": "Console", + "status.console.balance": "Balance", + "status.console.today": "Today", + "status.console.month": "This month", + "status.console.spend": "{{spend}} · {{count}} requests", + "status.console.complimentary": "Complimentary, nothing is charged", + "status.console.low": "{{balance}} · running low, top up below", + "status.console.note": "Workspace totals across every device.", + "status.console.billing": "Billing: {{url}}", "status.mcp.empty": "No MCP Servers", "status.mcp.count.one": "{{count}} MCP Server", "status.mcp.count.other": "{{count}} MCP Servers", diff --git a/packages/tui/src/i18n/ko.ts b/packages/tui/src/i18n/ko.ts index c37bc3bdaa..190a5f7078 100644 --- a/packages/tui/src/i18n/ko.ts +++ b/packages/tui/src/i18n/ko.ts @@ -278,6 +278,15 @@ export const dict: Record = { "status.usage.failed": "이 컴퓨터의 사용량을 불러오지 못했어요", "status.usage.note": "오늘, 이번 달, 전체는 이 컴퓨터의 모든 세션을 더한 값이에요.", "status.usage.console": "콘솔 잔액: {{url}}", + "status.console": "콘솔", + "status.console.balance": "잔액", + "status.console.today": "오늘", + "status.console.month": "이번 달", + "status.console.spend": "{{spend}} · 요청 {{count}}건", + "status.console.complimentary": "무료 제공 중이라 차감되지 않아요", + "status.console.low": "{{balance}} · 얼마 남지 않았어요, 아래에서 충전하세요", + "status.console.note": "모든 기기를 합친 워크스페이스 기준이에요.", + "status.console.billing": "결제: {{url}}", "status.mcp.empty": "MCP 서버 없음", "status.mcp.count.one": "MCP 서버 {{count}}개", "status.mcp.count.other": "MCP 서버 {{count}}개", diff --git a/packages/tui/src/util/usage.ts b/packages/tui/src/util/usage.ts index b859119364..80a4cb1ce9 100644 --- a/packages/tui/src/util/usage.ts +++ b/packages/tui/src/util/usage.ts @@ -39,4 +39,35 @@ export function format(total: Total) { } } +/** The console's `/usage/summary` reply, as the engine passes it through. */ +export type Console = { + currency: string + balance: number + complimentary: boolean + today: { spend: number; requestCount: number } + month: { spend: number; requestCount: number } +} + +/** Below this the balance is shown as a warning. */ +export const LOW_BALANCE = 1 + +/** The Console block's figures, formatted in the workspace's own currency. */ +export function workspace(value: Console) { + const currency = (() => { + try { + return new Intl.NumberFormat("en-US", { style: "currency", currency: value.currency }) + } catch { + return money + } + })() + const count = new Intl.NumberFormat("en-US") + return { + balance: currency.format(value.balance), + low: !value.complimentary && value.balance < LOW_BALANCE, + complimentary: value.complimentary, + today: { spend: currency.format(value.today.spend), count: count.format(value.today.requestCount) }, + month: { spend: currency.format(value.month.spend), count: count.format(value.month.requestCount) }, + } +} + export * as Usage from "./usage" diff --git a/packages/tui/test/util/usage.test.ts b/packages/tui/test/util/usage.test.ts index 4b39c99097..77c53420fe 100644 --- a/packages/tui/test/util/usage.test.ts +++ b/packages/tui/test/util/usage.test.ts @@ -27,4 +27,37 @@ describe("Usage", () => { expect(createTranslator("en").t("status.usage.line", value)).toBe("in 12 · out 3 · cache 0 · $0.00") expect(createTranslator("ko").t("status.usage.line", value)).toBe("입력 12 · 출력 3 · 캐시 0 · $0.00") }) + + const reply = { + currency: "USD", + balance: 20.368355, + complimentary: false, + today: { spend: 0, requestCount: 0 }, + month: { spend: 147.07, requestCount: 16764 }, + } + + test("workspace formats the Console balance and spend in the workspace's currency", () => { + expect(Usage.workspace(reply)).toEqual({ + balance: "$20.37", + low: false, + complimentary: false, + today: { spend: "$0.00", count: "0" }, + month: { spend: "$147.07", count: "16,764" }, + }) + expect(createTranslator("en").t("status.console.spend", Usage.workspace(reply).month)).toBe( + "$147.07 · 16,764 requests", + ) + expect(createTranslator("ko").t("status.console.spend", Usage.workspace(reply).month)).toBe( + "$147.07 · 요청 16,764건", + ) + }) + + test("a low balance warns, unless the workspace is complimentary", () => { + expect(Usage.workspace({ ...reply, balance: 0.4 }).low).toBe(true) + expect(Usage.workspace({ ...reply, balance: 0, complimentary: true }).low).toBe(false) + }) + + test("an unknown currency code still formats", () => { + expect(Usage.workspace({ ...reply, currency: "not-a-code" }).balance).toBe("$20.37") + }) })