From e017a35026c8fb191d096d1de1be2665bcd0d289 Mon Sep 17 00:00:00 2001 From: rakxdev Date: Sun, 22 Nov 2026 00:22:30 +0530 Subject: [PATCH 01/11] feat(quota): add plan-quota service for the standalone CLI/TUI - read-only file credential reader (enc:v2:env incl. key fingerprint, legacy enc:v1 candidates, plaintext passthrough; keyring records stay null) - shared OAuth session via the existing readStartPlanSession hook - billing/balance client with the desktop billing-plane header set (X-Device-Mid from the isolated telemetry state, UA/version/platform/ channel/locale/timezone/OS + per-call x-request-id) - pure parser: plans[] + per-model balance slots with percent left - loadCurrentQuotaOverview one-shot with soft-failure reasons --- src/quota.ts | 357 +++++++++++++++++++++++++++++++++++++++++++++ test/quota.test.ts | 289 ++++++++++++++++++++++++++++++++++++ 2 files changed, 646 insertions(+) create mode 100644 src/quota.ts create mode 100644 test/quota.test.ts diff --git a/src/quota.ts b/src/quota.ts new file mode 100644 index 00000000..e9bdd100 --- /dev/null +++ b/src/quota.ts @@ -0,0 +1,357 @@ +import { createDecipheriv, createHash, randomUUID } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { homedir, release, userInfo } from "node:os"; +import { join } from "node:path"; +import { credentialsPath, sharedDataBaseDir } from "./config-paths.ts"; +import { readStartPlanSession } from "./start-plan.ts"; + +/** + * Plan-quota service for the standalone CLI/TUI. + * + * Reads the shared OAuth session (`readStartPlanSession`) from the runtime-owned + * credentials file, queries the Start Plan billing/balance endpoint with the + * same device identity the runtime already uses, and parses the per-model + * balance slots shown by the desktop's Start Plan panel. + * + * Read-only: this module never writes credentials and never creates identities. + */ + +const BILLING_BALANCE_URL = "https://zcode.z.ai/api/v1/zcode-plan/billing/balance"; +const DEFAULT_APP_VERSION = "3.18.2"; +const IV_BYTES = 12; +const TAG_BYTES = 16; +const SECRET_MIN_BYTES = 32; +const SECRET_MAX_BYTES = 4096; + +export interface QuotaSlot { + name: string | undefined; + meter: string | undefined; + totalUnits: number | undefined; + usedUnits: number | undefined; + remainingUnits: number | undefined; + availableUnits: number | undefined; + percentLeft: number | undefined; + expiresAt: number | undefined; +} + +export interface QuotaPlan { + planId: string | undefined; + name: string | undefined; + status: string | undefined; + startsAt: number | undefined; + endsAt: number | undefined; +} + +export interface QuotaOverview { + serverTime: number | undefined; + plans: QuotaPlan[]; + balances: QuotaSlot[]; +} + +export interface QuotaSession { + family: "zai" | "bigmodel"; + identity: string; + token: string; +} + +export type QuotaReadResult = + | { ok: true; overview: QuotaOverview } + | { + ok: false; + reason: "no-oauth-session" | "secure-storage-unavailable" | "request-failed"; + detail?: string; + }; + +interface CredentialReader { + loadMany(keys: string[]): Promise>; +} + +function digest(value: string | Buffer): Buffer { + return createHash("sha256").update(value).digest(); +} + +function keyFingerprint(key: Buffer): string { + return digest(key).toString("hex").slice(0, 24); +} + +function isPrintableBase64Url(part: string): boolean { + return /^[A-Za-z0-9_-]*$/.test(part); +} + +/** `enc:v2:env::..` — base64url, AES-256-GCM, no AAD. */ +function tryOpenV2Env(body: string, secretCandidates: string[]): string | undefined { + const colon = body.indexOf(":"); + const fingerprint = colon >= 0 ? body.slice(0, colon) : undefined; + const payload = colon >= 0 ? body.slice(colon + 1) : body; + const parts = payload.split("."); + if (parts.length !== 3 || parts.some(part => !isPrintableBase64Url(part))) return undefined; + const [iv, tag, bytes] = parts.map(part => Buffer.from(part, "base64url")); + if (!iv || !tag || !bytes || iv.length !== IV_BYTES || tag.length !== TAG_BYTES) return undefined; + for (const candidate of secretCandidates) { + const key = digest(candidate); + if (fingerprint && fingerprint !== keyFingerprint(key)) continue; + try { + const decipher = createDecipheriv("aes-256-gcm", key, iv); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(bytes), decipher.final()]).toString("utf8"); + } catch { + // try the next candidate + } + } + return undefined; +} + +/** `enc:v1:..` — legacy records; key candidates mirror the runtime. */ +function tryOpenLegacy(record: string, env: NodeJS.ProcessEnv): string | undefined { + const body = record.replace(/^enc:v1:/, ""); + const parts = body.split("."); + if (parts.length !== 3 || parts.some(part => !isPrintableBase64Url(part))) return undefined; + const [iv, tag, bytes] = parts.map(part => Buffer.from(part, "base64url")); + if (!iv || !tag || !bytes || iv.length !== IV_BYTES || tag.length !== TAG_BYTES) return undefined; + const fallback = legacyFallbackSecret(env); + const secret = resolveCredentialSecret(env); + const candidates = secret + ? [...new Set([secret, secret.trim(), fallback])] + : [fallback]; + for (const key of candidates.map(digest)) { + try { + const decipher = createDecipheriv("aes-256-gcm", key, iv); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(bytes), decipher.final()]).toString("utf8"); + } catch { + // try the next candidate + } + } + return undefined; +} + +function legacyFallbackSecret(env: NodeJS.ProcessEnv): string { + let username = "unknown"; + try { + username = userInfo().username; + } catch { + // userInfo can fail on restricted passwd access; the runtime uses "unknown" too + } + return `zcode-credential-fallback:${process.platform}:${homedir()}:${username}`; +} + +/** + * Mirrors the runtime's managed-secret resolution: the env variable wins, then + * the secret file whose content is used verbatim (no trim — the runtime derives + * its key from the raw file content, trailing newline included). + */ +function resolveCredentialSecret(env: NodeJS.ProcessEnv): string | undefined { + if (env.ZCODE_CREDENTIAL_SECRET && env.ZCODE_CREDENTIAL_SECRET_FILE) return undefined; + if (env.ZCODE_CREDENTIAL_SECRET) return env.ZCODE_CREDENTIAL_SECRET; + const explicit = env.ZCODE_CREDENTIAL_SECRET_FILE; + if (!explicit) return undefined; + try { + const value = readFileSync(explicit, "utf8"); + const bytes = Buffer.byteLength(value, "utf8"); + if (bytes < SECRET_MIN_BYTES || bytes > SECRET_MAX_BYTES) return undefined; + return value; + } catch { + return undefined; + } +} + +function decryptRecord(value: string, env: NodeJS.ProcessEnv): string | null { + if (value.startsWith("enc:v2:env:")) { + const secret = resolveCredentialSecret(env); + const candidates = secret ? [...new Set([secret, secret.trim()])] : []; + return tryOpenV2Env(value.slice("enc:v2:env:".length), candidates) ?? null; + } + if (value.startsWith("enc:v1:")) return tryOpenLegacy(value, env) ?? null; + if (value.startsWith("enc:v2:os:")) return null; // keyring-protected: not readable outside the owning environment + return value; // plaintext record +} + +/** + * Read-only CredentialReader over the runtime-owned credentials file. + * Follows the same path resolution as the runtime (config-paths helpers), + * so an isolated `ZCODE_DATA_BASE_DIR` yields that account's records only. + */ +export function createFileCredentialReader(env: NodeJS.ProcessEnv = process.env): CredentialReader { + return { + async loadMany(keys: string[]): Promise> { + let parsed: unknown; + try { + parsed = JSON.parse(readFileSync(credentialsPath(env), "utf8")); + } catch { + return Object.fromEntries(keys.map(key => [key, null])); + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + return Object.fromEntries(keys.map(key => [key, null])); + } + const records = parsed as Record; + return Object.fromEntries(keys.map(key => { + const value = records[key]; + const plain = typeof value === "string" ? decryptRecord(value, env) : null; + return [key, plain && plain.length > 0 ? plain : null]; + })); + } + }; +} + +/** DeviceMid from the isolated telemetry state — the runtime creates it on first model request. */ +export function readDeviceMid(env: NodeJS.ProcessEnv = process.env): string | undefined { + try { + const stateFile = join(sharedDataBaseDir(env), ".zcode", "v2", "telemetry-state.json"); + const parsed = JSON.parse(readFileSync(stateFile, "utf8")) as { deviceMid?: unknown }; + const mid = parsed.deviceMid; + return typeof mid === "string" && mid.trim() ? mid.trim() : undefined; + } catch { + return undefined; + } +} + +/** + * Billing-plane headers, mirroring the desktop's Start Plan request shape + * (User-Agent/Referer/Title/Version/Platform/Channel/Language/Timezone/OS/ + * Device-Mid/Authorization + a fresh x-request-id per call). + */ +export function billingHeaders( + session: QuotaSession, + options: { deviceMid?: string; appVersion?: string } = {}, +): Record { + const version = options.appVersion ?? DEFAULT_APP_VERSION; + const headers: Record = { + "User-Agent": `ZCode/${version}`, + "HTTP-Referer": "https://zcode.z.ai", + "X-Title": "Z Code@electron", + "X-ZCode-App-Version": version, + "X-Platform": process.platform, + "X-Release-Channel": "stable", + "X-Client-Language": Intl.DateTimeFormat().resolvedOptions().locale || "unknown", + "X-Client-Timezone": Intl.DateTimeFormat().resolvedOptions().timeZone || "unknown", + "X-Os-Category": process.platform, + "X-Os-Version": release(), + "Authorization": `Bearer ${session.token}`, + "x-request-id": randomUUID() + }; + if (options.deviceMid) headers["X-Device-Mid"] = options.deviceMid; + return headers; +} + +function asNumber(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +function asText(value: unknown): string | undefined { + return typeof value === "string" && value.trim() ? value.trim() : undefined; +} + +function asRecord(value: unknown): Record | undefined { + return typeof value === "object" && value !== null && !Array.isArray(value) + ? value as Record + : undefined; +} + +/** Pure parser for the billing/balance payload (accepts the `{code, data}` envelope or bare data). */ +export function parseBillingBalance(payload: unknown): QuotaOverview { + const envelope = asRecord(payload); + const root = envelope && "data" in envelope ? asRecord(envelope.data) : envelope; + if (!root) return { serverTime: undefined, plans: [], balances: [] }; + + const plans = Array.isArray(root.plans) + ? root.plans.map(plan => { + const record = asRecord(plan) ?? {}; + return { + planId: asText(record.plan_id), + name: asText(record.name), + status: asText(record.status), + startsAt: asNumber(record.starts_at), + endsAt: asNumber(record.ends_at) + }; + }) + : []; + const balances = Array.isArray(root.balances) + ? root.balances.map(balance => { + const record = asRecord(balance) ?? {}; + const totalUnits = asNumber(record.total_units); + const remainingUnits = asNumber(record.remaining_units); + const percentLeft = totalUnits !== undefined && totalUnits > 0 && remainingUnits !== undefined + ? Math.max(0, Math.min(100, (remainingUnits / totalUnits) * 100)) + : undefined; + return { + name: asText(record.show_name), + meter: asText(record.meter), + totalUnits, + usedUnits: asNumber(record.used_units), + remainingUnits, + availableUnits: asNumber(record.available_units), + percentLeft, + expiresAt: asNumber(record.expires_at) + }; + }) + : []; + return { serverTime: asNumber(root.server_time), plans, balances }; +} + +export class QuotaRequestError extends Error {} + +export async function fetchQuotaOverview( + session: QuotaSession, + options: { + deviceMid?: string; + appVersion?: string; + signal?: AbortSignal; + fetchImpl?: typeof fetch; + } = {} +): Promise { + const doFetch = options.fetchImpl ?? fetch; + let response: Response; + try { + response = await doFetch(BILLING_BALANCE_URL, { + headers: billingHeaders(session, options), + signal: options.signal + }); + } catch (error) { + throw new QuotaRequestError(error instanceof Error ? error.message : String(error)); + } + let payload: unknown; + try { + payload = await response.json(); + } catch { + throw new QuotaRequestError(`billing/balance returned non-JSON response (HTTP ${response.status})`); + } + const envelope = asRecord(payload); + if (response.status !== 200 || (envelope && envelope.code !== undefined && envelope.code !== 0)) { + const message = envelope && typeof envelope.msg === "string" ? envelope.msg : `HTTP ${response.status}`; + throw new QuotaRequestError(`billing/balance rejected the request: ${message}`); + } + return parseBillingBalance(payload); +} + +/** + * One-shot read for the TUI: shared OAuth session → billing/balance → parsed overview. + * Fails soft with a reason the UI can present. + */ +export async function loadCurrentQuotaOverview( + options: { + env?: NodeJS.ProcessEnv; + appVersion?: string; + signal?: AbortSignal; + fetchImpl?: typeof fetch; + } = {} +): Promise { + const env = options.env ?? process.env; + const session = await readStartPlanSession(createFileCredentialReader(env), options.signal); + if (!session) return { ok: false, reason: "no-oauth-session" }; + try { + const overview = await fetchQuotaOverview(session, { + deviceMid: readDeviceMid(env), + appVersion: options.appVersion, + signal: options.signal, + fetchImpl: options.fetchImpl + }); + return { ok: true, overview }; + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + const reason = detail.includes("Secure credential storage") || detail.includes("CREDENTIAL_SECURE_STORAGE_UNAVAILABLE") + ? "secure-storage-unavailable" + : "request-failed"; + return { ok: false, reason, detail }; + } +} + diff --git a/test/quota.test.ts b/test/quota.test.ts new file mode 100644 index 00000000..92b8b07e --- /dev/null +++ b/test/quota.test.ts @@ -0,0 +1,289 @@ +import { expect, test } from "bun:test"; +import { createCipheriv, createHash, randomBytes } from "node:crypto"; +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + billingHeaders, + createFileCredentialReader, + fetchQuotaOverview, + loadCurrentQuotaOverview, + parseBillingBalance, + readDeviceMid +} from "../src/quota.ts"; +import { readStartPlanSession } from "../src/start-plan.ts"; + +// Random per run: the seal/decrypt round-trip shares this constant, so the test +// stays deterministic without baking any secret material into the repository. +const SECRET = randomBytes(32).toString("hex"); +const APP_JWT = `e30.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })).toString("base64url")}.fixture-signature`; + +function sealV2Env(value: string, secret = SECRET): string { + const key = createHash("sha256").update(secret, "utf8").digest(); + const iv = randomBytes(12); + const cipher = createCipheriv("aes-256-gcm", key, iv); + const bytes = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]); + const fingerprint = createHash("sha256").update(key).digest("hex").slice(0, 24); + const payload = [iv, cipher.getAuthTag(), bytes].map(part => part.toString("base64url")).join("."); + return `enc:v2:env:${fingerprint}:${payload}`; +} + +/** The real billing/balance shape captured from a Start Plan account (values adjusted). */ +function billingFixture(): unknown { + return { + code: 0, + msg: "", + data: { + server_time: 1795285880, + plans: [{ + user_plan_id: "upl_1", + plan_id: "zcode-v3-start-plan-wk-1120", + name: "ZCODE WEEKEND BUILD", + description: "", + priority: 101, + status: "active", + starts_at: 1795187372, + ends_at: 1795395600, + entitlements: [{ + entitlement_id: "ent-1", + show_name: "GLM-5.3-Flash", + meter: "model_usage", + unit_type: "token", + capabilities: ["model:glm-5.3-flash"], + grant_units: 500000000, + period: "one_time", + priority: 101, + effective_at: 1795186800 + }] + }], + balances: [{ + bucket_id: "bucket_1", + user_plan_id: "upl_1", + plan_id: "zcode-v3-start-plan-wk-1120", + entitlement_id: "ent-1", + show_name: "GLM-5.3-Flash", + meter: "model_usage", + unit_type: "token", + capabilities: ["model:glm-5.3-flash"], + priority: 101, + plan_priority: 101, + entitlement_priority: 101, + total_units: 500000000, + used_units: 200179, + remaining_units: 499799821, + available_units: 499799821, + period_start: 1795187372, + period_end: 1795395600, + expires_at: 1795395600 + }] + } + }; +} + +function isolatedEnv(files: Record): { env: NodeJS.ProcessEnv; dir: string } { + const dir = mkdtempSync(join(tmpdir(), "zcode-quota-test-")); + for (const [relative, content] of Object.entries(files)) { + const absolute = join(dir, relative); + mkdirSync(join(absolute, ".."), { recursive: true }); + writeFileSync(absolute, content); + } + const secretFile = join(dir, ".zcred"); + writeFileSync(secretFile, SECRET); + return { + dir, + env: { + ZCODE_DATA_BASE_DIR: dir, + ZCODE_CREDENTIAL_SECRET_FILE: secretFile + } as NodeJS.ProcessEnv + }; +} + +test("parseBillingBalance maps plans and per-model balances with percent left", () => { + const overview = parseBillingBalance(billingFixture()); + expect(overview.serverTime).toBe(1795285880); + expect(overview.plans).toHaveLength(1); + expect(overview.plans[0]).toMatchObject({ + planId: "zcode-v3-start-plan-wk-1120", + name: "ZCODE WEEKEND BUILD", + status: "active", + endsAt: 1795395600 + }); + expect(overview.balances).toHaveLength(1); + expect(overview.balances[0]).toMatchObject({ + name: "GLM-5.3-Flash", + meter: "model_usage", + totalUnits: 500000000, + usedUnits: 200179, + remainingUnits: 499799821, + availableUnits: 499799821, + expiresAt: 1795395600 + }); + expect(overview.balances[0]?.percentLeft).toBeCloseTo(99.9599642, 4); +}); + +test("parseBillingBalance renders every model slot a plan carries", () => { + const fixture = billingFixture() as { data: { balances: Array> } }; + fixture.data.balances.push({ + bucket_id: "bucket_2", + show_name: "GLM-5.3", + meter: "model_usage", + unit_type: "token", + total_units: 200000000, + used_units: 200000000, + remaining_units: 0, + available_units: 0, + expires_at: 1795395600 + }); + const overview = parseBillingBalance(fixture); + expect(overview.balances).toHaveLength(2); + expect(overview.balances[1]?.name).toBe("GLM-5.3"); + expect(overview.balances[1]?.percentLeft).toBe(0); +}); + +test("parseBillingBalance accepts a bare payload and empty plan lists", () => { + const bare = parseBillingBalance(billingFixture()); + expect(bare.balances).toHaveLength(1); + + const freeTier = parseBillingBalance({ code: 0, msg: "", data: { server_time: 1, plans: [], balances: [] } }); + expect(freeTier.plans).toEqual([]); + expect(freeTier.balances).toEqual([]); + + const malformed = parseBillingBalance("not-json-object"); + expect(malformed.plans).toEqual([]); + expect(malformed.balances).toEqual([]); +}); + +test("billingHeaders mirror the desktop billing-plane shape", () => { + const headers = billingHeaders( + { family: "zai", identity: "user-1", token: "jwt-value" }, + { deviceMid: "device-mid-1", appVersion: "3.18.2" } + ); + expect(headers["User-Agent"]).toBe("ZCode/3.18.2"); + expect(headers["HTTP-Referer"]).toBe("https://zcode.z.ai"); + expect(headers["X-Title"]).toBe("Z Code@electron"); + expect(headers["X-ZCode-App-Version"]).toBe("3.18.2"); + expect(headers["X-Platform"]).toBe(process.platform); + expect(headers["X-Release-Channel"]).toBe("stable"); + expect(headers["X-Os-Category"]).toBe(process.platform); + expect(headers["X-Device-Mid"]).toBe("device-mid-1"); + expect(headers["Authorization"]).toBe("Bearer jwt-value"); + expect(headers["x-request-id"]).toMatch(/^[0-9a-f-]{36}$/u); +}); + +test("billingHeaders omit X-Device-Mid when the environment has none yet", () => { + const headers = billingHeaders({ family: "zai", identity: "user-1", token: "jwt-value" }); + expect(headers["X-Device-Mid"]).toBeUndefined(); +}); + +test("file credential reader decrypts enc:v2:env records from the isolated data dir", async () => { + const { env } = isolatedEnv({ + ".zcode/v2/credentials.json": JSON.stringify({ + "oauth:active_provider": sealV2Env("zai"), + "zcodejwttoken": sealV2Env(APP_JWT), + "oauth:zai:user_info": sealV2Env(JSON.stringify({ user_id: "desktop-user" })), + "account-provider:account:zai-individual-coding-plan:auth-source": sealV2Env("oauth") + }) + }); + const store = createFileCredentialReader(env); + const values = await store.loadMany(["oauth:active_provider", "zcodejwttoken", "oauth:zai:user_info", "missing"]); + expect(values["oauth:active_provider"]).toBe("zai"); + expect(values["zcodejwttoken"]).toBe(APP_JWT); + expect(values["oauth:zai:user_info"]).toBe(JSON.stringify({ user_id: "desktop-user" })); + expect(values["missing"]).toBeNull(); +}); + +test("file credential reader returns nulls for unreadable or keyring-protected records", async () => { + const { env } = isolatedEnv({ + ".zcode/v2/credentials.json": JSON.stringify({ + "zcodejwttoken": "enc:v2:os:deadbeef:aGVsbG8.AAAAAAAAAAAAAAAAAAAAAA.aGVsbG8", + "plain": "plain-value", + "broken": "enc:v2:env:not-a-valid-record" + }) + }); + const values = await createFileCredentialReader(env).loadMany(["zcodejwttoken", "plain", "broken"]); + expect(values["zcodejwttoken"]).toBeNull(); + expect(values["plain"]).toBe("plain-value"); + expect(values["broken"]).toBeNull(); +}); + +test("file credential reader decrypts legacy enc:v1 records when a managed secret exists", async () => { + const key = createHash("sha256").update(SECRET, "utf8").digest(); + const iv = randomBytes(12); + const cipher = createCipheriv("aes-256-gcm", key, iv); + const bytes = Buffer.concat([cipher.update("legacy-value", "utf8"), cipher.final()]); + const legacy = `enc:v1:${[iv, cipher.getAuthTag(), bytes].map(part => part.toString("base64url")).join(".")}`; + const { env } = isolatedEnv({ ".zcode/v2/credentials.json": JSON.stringify({ "zcodejwttoken": legacy }) }); + const values = await createFileCredentialReader(env).loadMany(["zcodejwttoken"]); + expect(values["zcodejwttoken"]).toBe("legacy-value"); +}); + +test("file credential reader feeds readStartPlanSession for the shared OAuth session", async () => { + const { env } = isolatedEnv({ + ".zcode/v2/credentials.json": JSON.stringify({ + "oauth:active_provider": sealV2Env("zai"), + "zcodejwttoken": sealV2Env(APP_JWT), + "oauth:zai:user_info": sealV2Env(JSON.stringify({ user_id: "desktop-user" })) + }) + }); + const session = await readStartPlanSession(createFileCredentialReader(env)); + expect(session).toMatchObject({ family: "zai", identity: "desktop-user", token: APP_JWT }); +}); + +test("readDeviceMid reads the runtime-created telemetry state from the isolated dir", () => { + const { env, dir } = isolatedEnv({ ".zcode/v2/telemetry-state.json": JSON.stringify({ deviceMid: "device-mid-42" }) }); + expect(readDeviceMid(env)).toBe("device-mid-42"); + expect(dir).toBeTruthy(); +}); + +test("loadCurrentQuotaOverview returns the parsed overview through a mocked transport", async () => { + const { env } = isolatedEnv({ + ".zcode/v2/credentials.json": JSON.stringify({ + "oauth:active_provider": sealV2Env("zai"), + "zcodejwttoken": sealV2Env(APP_JWT), + "oauth:zai:user_info": sealV2Env(JSON.stringify({ user_id: "desktop-user" })) + }), + ".zcode/v2/telemetry-state.json": JSON.stringify({ deviceMid: "device-mid-42" }) + }); + let capturedHeaders: Record | undefined; + const fetchImpl = (async (input: unknown, init?: { headers?: Record }) => { + capturedHeaders = init?.headers; + return new Response(JSON.stringify(billingFixture()), { status: 200 }); + }) as unknown as typeof fetch; + const result = await loadCurrentQuotaOverview({ env, fetchImpl }); + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.overview.plans[0]?.name).toBe("ZCODE WEEKEND BUILD"); + expect(result.overview.balances[0]?.remainingUnits).toBe(499799821); + expect(capturedHeaders?.["X-Device-Mid"]).toBe("device-mid-42"); + expect(capturedHeaders?.["Authorization"]).toBe(`Bearer ${APP_JWT}`); +}); + +test("loadCurrentQuotaOverview reports a missing OAuth session without calling the endpoint", async () => { + const { env } = isolatedEnv({ ".zcode/v2/credentials.json": JSON.stringify({}) }); + let endpointCalled = false; + const fetchImpl = (async () => { + endpointCalled = true; + return new Response("{}", { status: 200 }); + }) as unknown as typeof fetch; + const result = await loadCurrentQuotaOverview({ env, fetchImpl }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.reason).toBe("no-oauth-session"); + expect(endpointCalled).toBe(false); +}); + +test("loadCurrentQuotaOverview surfaces endpoint rejections as request failures", async () => { + const { env } = isolatedEnv({ + ".zcode/v2/credentials.json": JSON.stringify({ + "oauth:active_provider": sealV2Env("zai"), + "zcodejwttoken": sealV2Env(APP_JWT), + "oauth:zai:user_info": sealV2Env(JSON.stringify({ user_id: "desktop-user" })) + }) + }); + const fetchImpl = (async () => new Response(JSON.stringify({ code: 500, msg: "Z.ai user information is invalid" }), { status: 500 })) as unknown as typeof fetch; + const result = await loadCurrentQuotaOverview({ env, fetchImpl }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.reason).toBe("request-failed"); + expect(result.detail).toContain("Z.ai user information is invalid"); +}); From 80b927b047f7ebe5cf34c21a5b3a736265b000f4 Mon Sep 17 00:00:00 2001 From: rakxdev Date: Sun, 22 Nov 2026 00:27:01 +0530 Subject: [PATCH 02/11] feat(tui): add /quota command with resize-safe balance card - QuotaView renders the plan header, per-model remaining bars and footnotes inside the standard choice dialog (no nested boxes) - bars clamp to the viewport (8-40 chars, context-status-view formula) and every line is truncated, so resize/zoom never breaks the layout - slots-driven rows: whatever models billing/balance returns render automatically; free-tier and signed-out states degrade gracefully - width assertions use pi-tui visibleWidth (ANSI-safe) --- packages/zcode-tui/src/index.ts | 33 ++++++++ packages/zcode-tui/src/quota-view.ts | 121 +++++++++++++++++++++++++++ test/tui/quota-view.test.ts | 49 +++++++++++ 3 files changed, 203 insertions(+) create mode 100644 packages/zcode-tui/src/quota-view.ts create mode 100644 test/tui/quota-view.test.ts diff --git a/packages/zcode-tui/src/index.ts b/packages/zcode-tui/src/index.ts index 1aa7c75d..f04876e8 100644 --- a/packages/zcode-tui/src/index.ts +++ b/packages/zcode-tui/src/index.ts @@ -245,6 +245,8 @@ import { } from "./shortcuts.ts"; import { createTheme, type ZCodeTheme } from "./theme.ts"; import { StatusLine, type StatusLineField } from "./status-line.ts"; +import { QuotaView } from "./quota-view.ts"; +import { loadCurrentQuotaOverview } from "../../../src/quota.ts"; import { SystemEventView, type SystemEventData } from "./system-event-view.ts"; import { sanitizeTerminalText, stripCaretHighlight } from "./terminal-text.ts"; import { ThinkingView } from "./thinking-view.ts"; @@ -1528,6 +1530,7 @@ class ZCodeTui { { name: "sessions", description: "Browse and resume past sessions (desktop and CLI)" }, { name: "context", description: "Inspect context usage and prompt composition" }, { name: "status", description: "Inspect detailed runtime and session status" }, + { name: "quota", description: "Inspect plan quota and balances for the signed-in account" }, { name: "rename", description: "Rename the current session", argumentHint: "" }, { name: "config", description: "Configure ZCode TUI settings" }, { name: "settings", description: "Configure ZCode TUI settings" }, @@ -1845,6 +1848,11 @@ class ZCodeTui { await this.showStatusDetails(); return; } + + if (input === "/quota") { + await this.showQuotaDetails(); + return; + } const renameRequest = sessionRenameRequest(input); if (renameRequest !== undefined) { await this.handleSessionRename(renameRequest); @@ -5302,6 +5310,31 @@ class ZCodeTui { }); } + private async showQuotaDetails(): Promise<void> { + const result = await loadCurrentQuotaOverview(); + if (!result.ok) { + if (result.reason === "no-oauth-session") { + this.addNotice("No shared OAuth session for quota — sign in with /login first.", "warning"); + } else if (result.reason === "secure-storage-unavailable") { + this.addNotice("Secure credential storage is unavailable; configure ZCODE_CREDENTIAL_SECRET or ZCODE_CREDENTIAL_SECRET_FILE to read quota.", "warning"); + } else { + this.addNotice(`Quota request failed: ${result.detail ?? "unknown error"}`, "warning"); + } + return; + } + const overview = result.overview; + if (overview.plans.length === 0 && overview.balances.length === 0) { + this.addNotice("No plan balances on this account for the signed-in session.", "warning"); + return; + } + await this.showChoice({ + title: "Quota", + prompt: "Live plan balances for the signed-in account. The compact statusline stays minimal.", + content: new QuotaView(this.theme, overview, new Date().toLocaleTimeString("en-US")), + items: [{ value: "close", label: "Close" }] + }); + } + /** * `/rename <title>`: persists a user-owned session title through the * runtime's setCustomSessionTitle capability, so the runtime's own title diff --git a/packages/zcode-tui/src/quota-view.ts b/packages/zcode-tui/src/quota-view.ts new file mode 100644 index 00000000..ea9a587e --- /dev/null +++ b/packages/zcode-tui/src/quota-view.ts @@ -0,0 +1,121 @@ +import { truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui"; +import type { QuotaOverview, QuotaSlot } from "../../../src/quota.ts"; +import type { ZCodeTheme } from "./theme.ts"; + +/** + * `/quota` card: plan header + one bar per model slot the plan carries. + * + * Width-safe by contract: every component implements `render(width)` and + * re-renders at the new size on resize/zoom; bars clamp to the viewport + * (8–40 chars, the same formula `context-status-view.ts` uses) and every + * line is truncated so nothing wraps or breaks. Renders whatever model + * slots `billing/balance` returns — plans with one, two or many models + * all work without hardcoded rows. + */ + +const MAX_RENDERED_SLOTS = 8; +const BAR_MIN = 8; +const BAR_MAX = 40; + +function formatUnits(value: number | undefined): string { + return value === undefined ? "—" : value.toLocaleString("en-US"); +} + +function formatExpiry(seconds: number | undefined): string | undefined { + if (seconds === undefined) return undefined; + const date = new Date(seconds * 1000); + if (Number.isNaN(date.getTime())) return undefined; + return date.toLocaleString("en-US", { + month: "short", + day: "numeric", + hour: "2-digit", + minute: "2-digit" + }); +} + +export class QuotaView implements Component { + constructor( + private readonly theme: ZCodeTheme, + private readonly overview: QuotaOverview, + private readonly updatedAt: string | undefined = undefined + ) {} + + render(width: number): string[] { + const safeWidth = Math.max(1, width); + const lines: string[] = []; + const plan = this.overview.plans[0]; + if (plan?.name) { + const status = plan.status && plan.status !== "active" ? ` (${plan.status})` : ""; + lines.push(this.theme.accent(`${plan.name}${status}`)); + } + const expiry = formatExpiry(plan?.endsAt); + if (expiry) lines.push(this.theme.muted(`Expires ${expiry} · server clock`)); + if (plan?.name || expiry) lines.push(""); + + const slots = this.overview.balances.slice(0, MAX_RENDERED_SLOTS); + if (slots.length === 0) { + lines.push(this.theme.muted("No plan balances on this account.")); + if (!plan) lines.push(this.theme.muted("Sign in with /login to use Start Plan and Coding Plan providers.")); + } + + for (const slot of slots) { + lines.push(this.slotTitle(slot, safeWidth)); + lines.push(this.slotBar(slot, safeWidth)); + lines.push(this.theme.muted(this.slotDetail(slot))); + lines.push(""); + } + const hidden = this.overview.balances.length - slots.length; + if (hidden > 0) lines.push(this.theme.muted(`+${hidden} more…`)); + + const footnote = this.updatedAt + ? `updated ${this.updatedAt} · billing/balance · /quota refreshes` + : "billing/balance · /quota refreshes"; + lines.push(this.theme.muted(footnote)); + return lines.map(line => truncateToWidth(line, safeWidth, "…")); + } + + invalidate(): void {} + + private slotTint(slot: QuotaSlot): (text: string) => string { + const percentLeft = slot.percentLeft; + if (percentLeft === undefined) return this.theme.muted; + if (percentLeft <= 0) return this.theme.error; + if (percentLeft <= 20) return this.theme.warning; + return this.theme.accent; + } + + private slotTitle(slot: QuotaSlot, safeWidth: number): string { + const name = slot.name ?? "model"; + const tint = this.slotTint(slot); + const percent = slot.percentLeft === undefined + ? undefined + : slot.percentLeft <= 0 + ? "exhausted" + : `${Math.round(slot.percentLeft)}% left`; + if (percent === undefined) return truncateToWidth(name, safeWidth, "…"); + const gap = Math.max(1, safeWidth - visibleWidth(name) - visibleWidth(percent) - 1); + const padded = name + " ".repeat(Math.min(gap, 64)) + tint(percent); + return truncateToWidth(padded, safeWidth, "…"); + } + + private slotBar(slot: QuotaSlot, safeWidth: number): string { + const safe = Math.max(1, safeWidth); + const barWidth = Math.max(BAR_MIN, Math.min(BAR_MAX, safe - 2)); + const total = slot.totalUnits; + const remaining = slot.remainingUnits ?? 0; + const filled = total && total > 0 + ? Math.max(0, Math.min(barWidth, Math.round((remaining / total) * barWidth))) + : 0; + const tint = this.slotTint(slot); + const bar = tint("█".repeat(filled)) + this.theme.muted("░".repeat(Math.max(0, barWidth - filled))); + return truncateToWidth(bar, safe, "…"); + } + + private slotDetail(slot: QuotaSlot): string { + const reset = formatExpiry(slot.expiresAt); + const exhausted = slot.remainingUnits !== undefined && slot.remainingUnits <= 0; + const totals = `${formatUnits(slot.remainingUnits)} / ${formatUnits(slot.totalUnits)}`; + if (exhausted) return `${totals} · exhausted`; + return reset ? `${totals} · resets ${reset}` : totals; + } +} diff --git a/test/tui/quota-view.test.ts b/test/tui/quota-view.test.ts new file mode 100644 index 00000000..e28d6ca9 --- /dev/null +++ b/test/tui/quota-view.test.ts @@ -0,0 +1,49 @@ +import { expect, test } from "bun:test"; +import { visibleWidth } from "@earendil-works/pi-tui"; +import { QuotaView } from "../../packages/zcode-tui/src/quota-view.ts"; +import type { QuotaOverview } from "../../src/quota.ts"; + +// Minimal theme stub: tints are identity transforms so assertions stay text-based. +const theme = { + accent: (text: string) => text, + muted: (text: string) => text, + warning: (text: string) => text, + error: (text: string) => text +}; + +function overviewFixture(): QuotaOverview { + return { + serverTime: 1795285880, + plans: [{ planId: "p1", name: "ZCODE WEEKEND BUILD", status: "active", startsAt: 1, endsAt: 1795395600 }], + balances: [ + { name: "GLM-5.3-Flash", meter: "model_usage", totalUnits: 500000000, usedUnits: 200179, remainingUnits: 499799821, availableUnits: 499799821, percentLeft: 99.96, expiresAt: 1795395600 }, + { name: "GLM-5.3", meter: "model_usage", totalUnits: 200000000, usedUnits: 200000000, remainingUnits: 0, availableUnits: 0, percentLeft: 0, expiresAt: 1795395600 } + ] + }; +} + +test("quota view renders plan header, per-model bars and stays within width", () => { + const overview = overviewFixture(); + // No overflow at any width (pi-tui re-renders at the new size on resize/zoom). + for (const width of [200, 120, 80, 40, 20, 10, 1]) { + const lines = new QuotaView(theme as never, overview, "21:47:03").render(width); + for (const line of lines) { + expect(visibleWidth(line)).toBeLessThanOrEqual(width); + } + } + // Full content survives at usable widths (truncation only bites when narrow). + for (const width of [200, 120, 80]) { + const joined = new QuotaView(theme as never, overview, "21:47:03").render(width).join("\n"); + expect(joined).toContain("ZCODE WEEKEND BUILD"); + expect(joined).toContain("GLM-5.3-Flash"); + expect(joined).toContain("GLM-5.3"); + expect(joined).toContain("exhausted"); + } +}); + +test("quota view renders the empty state without plan or balances", () => { + const empty: QuotaOverview = { serverTime: undefined, plans: [], balances: [] }; + const lines = new QuotaView(theme as never, empty).render(80); + expect(lines.join("\n")).toContain("No plan balances"); + expect(lines.join("\n")).toContain("/login"); +}); From 31904220469ff5ea2f8f4beb0bacd821b044583a Mon Sep 17 00:00:00 2001 From: rakxdev <rakxdev@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:28:47 +0530 Subject: [PATCH 03/11] feat(tui): optional quota statusline segment behind ui.quotaStatusline - setting helper mirrors tool-call-style conventions (ui.* namespace, strict boolean, default off, unreadable settings degrade to off) - background loop refreshes every 5 minutes (unref'd) after runTui starts; the statusline shows the lowest remaining balance across the account's plan slots, warning-tinted below 20% --- packages/zcode-tui/src/index.ts | 52 +++++++++++++++++++++- packages/zcode-tui/src/quota-statusline.ts | 26 +++++++++++ test/tui/quota-statusline.test.ts | 28 ++++++++++++ 3 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 packages/zcode-tui/src/quota-statusline.ts create mode 100644 test/tui/quota-statusline.test.ts diff --git a/packages/zcode-tui/src/index.ts b/packages/zcode-tui/src/index.ts index f04876e8..38bd5bd1 100644 --- a/packages/zcode-tui/src/index.ts +++ b/packages/zcode-tui/src/index.ts @@ -245,6 +245,7 @@ import { } from "./shortcuts.ts"; import { createTheme, type ZCodeTheme } from "./theme.ts"; import { StatusLine, type StatusLineField } from "./status-line.ts"; +import { readQuotaStatusline } from "./quota-statusline.ts"; import { QuotaView } from "./quota-view.ts"; import { loadCurrentQuotaOverview } from "../../../src/quota.ts"; import { SystemEventView, type SystemEventData } from "./system-event-view.ts"; @@ -710,6 +711,7 @@ class ZCodeTui { private terminalFocus: TerminalFocusState = "unknown"; private copyOnSelect = true; private toolCallStyle: ToolCallStyle = "regular"; + private quotaStatusPercent: number | undefined = undefined; private thoughtLevel?: string; private showReasoning: boolean; private modelOptions: unknown[]; @@ -5891,6 +5893,12 @@ class ZCodeTui { return this.sessionModelRecovery; } + /** Background quota refresh (ui.quotaStatusline) updates the statusline through this setter. */ + setQuotaStatusPercent(percent: number | undefined): void { + this.quotaStatusPercent = percent; + this.updateMetadata(); + } + private updateMetadata(): void { this.editor.planEnabled = this.planEnabled; const fields: StatusLineField[] = [ @@ -5953,6 +5961,19 @@ class ZCodeTui { priority: 85 }); } + if (this.quotaStatusPercent !== undefined) { + const percent = Math.round(this.quotaStatusPercent); + const style = percent <= 0 + ? this.theme.error + : percent <= 20 + ? this.theme.warning + : this.theme.muted; + fields.push({ + text: style(`quota ${percent}%`), + compactText: style(`quota ${percent}%`), + priority: 70 + }); + } if (this.sessionMetrics.totalTokens !== undefined) { const tokens = formatTokens(this.sessionMetrics.totalTokens); fields.push({ @@ -6455,8 +6476,37 @@ class ZCodeTui { } } +async function refreshQuotaStatusline(tui: ZCodeTui): Promise<void> { + try { + const result = await loadCurrentQuotaOverview(); + if (!result.ok) { + tui.setQuotaStatusPercent(undefined); + return; + } + const percents = result.overview.balances + .map(balance => balance.percentLeft) + .filter((percent): percent is number => percent !== undefined); + tui.setQuotaStatusPercent(percents.length ? Math.min(...percents) : undefined); + } catch { + // background refresh must never surface into the statusline + } +} + +async function startQuotaStatuslineLoop(tui: ZCodeTui): Promise<void> { + if (!(await readQuotaStatusline())) return; + const refresh = (): void => { + void refreshQuotaStatusline(tui); + }; + refresh(); + const timer = setInterval(refresh, 300_000); + timer.unref?.(); +} + export async function runTui(options: TuiOptions): Promise<void> { suppressTuiAiSdkWarnings(); const readyOptions = await loadTuiStartupOptions(options); - if (readyOptions) await new ZCodeTui(readyOptions).run(); + if (!readyOptions) return; + const tui = new ZCodeTui(readyOptions); + startQuotaStatuslineLoop(tui); + await tui.run(); } diff --git a/packages/zcode-tui/src/quota-statusline.ts b/packages/zcode-tui/src/quota-statusline.ts new file mode 100644 index 00000000..ccf51325 --- /dev/null +++ b/packages/zcode-tui/src/quota-statusline.ts @@ -0,0 +1,26 @@ +import { readCliSettings } from "../../../src/model-access.ts"; + +/** + * `ui.quotaStatusline` (default **off**): when enabled, the compact statusline + * gains a `quota <percent>%` segment showing the lowest remaining balance of + * the signed-in account's plan slots. Configured in `setting.json` only — the + * statusline stays minimal unless the user opts in. + */ + +function record(value: unknown): Record<string, unknown> | undefined { + return typeof value === "object" && value !== null && !Array.isArray(value) + ? value as Record<string, unknown> + : undefined; +} + +export function resolveQuotaStatusline(config: unknown): boolean { + return record(record(config)?.ui)?.quotaStatusline === true; +} + +export async function readQuotaStatusline(env: NodeJS.ProcessEnv = process.env): Promise<boolean> { + try { + return resolveQuotaStatusline(await readCliSettings(env)); + } catch { + return false; // unreadable settings must never break the statusline + } +} diff --git a/test/tui/quota-statusline.test.ts b/test/tui/quota-statusline.test.ts new file mode 100644 index 00000000..4084f9e3 --- /dev/null +++ b/test/tui/quota-statusline.test.ts @@ -0,0 +1,28 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { resolveQuotaStatusline } from "../../packages/zcode-tui/src/quota-statusline.ts"; + +test("ui.quotaStatusline defaults to off and only accepts an explicit boolean", () => { + expect(resolveQuotaStatusline({})).toBe(false); + expect(resolveQuotaStatusline({ ui: {} })).toBe(false); + expect(resolveQuotaStatusline({ ui: { quotaStatusline: false } })).toBe(false); + expect(resolveQuotaStatusline({ ui: { quotaStatusline: "yes" } })).toBe(false); + expect(resolveQuotaStatusline({ ui: { quotaStatusline: 1 } })).toBe(false); +}); + +test("ui.quotaStatusline enables with an explicit boolean", () => { + expect(resolveQuotaStatusline({ ui: { quotaStatusline: true } })).toBe(true); +}); + +test("readQuotaStatusline reads the isolated settings file and survives unreadable configs", async () => { + const dir = mkdtempSync(join(tmpdir(), "zcode-quota-setting-")); + const settingsFile = join(dir, "setting.json"); + writeFileSync(settingsFile, JSON.stringify({ ui: { quotaStatusline: true } })); + expect(await resolveQuotaStatusline({})).toBe(false); + const { readQuotaStatusline } = await import("../../packages/zcode-tui/src/quota-statusline.ts"); + expect(await readQuotaStatusline({ ZCODE_CLI_SETTINGS_FILE: settingsFile })).toBe(true); + writeFileSync(settingsFile, "{ not json"); + expect(await readQuotaStatusline({ ZCODE_CLI_SETTINGS_FILE: settingsFile })).toBe(false); +}); From 40702c9022dd361932d8fab11a0c37041cbd566d Mon Sep 17 00:00:00 2001 From: rakxdev <rakxdev@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:09:01 +0530 Subject: [PATCH 04/11] fix(tui): surface /quota and TUI-local commands in /help and the header hint - bare /help now renders a merged command dialog (runtime-provided via the host + TUI-local commands incl. /quota) instead of forwarding to the runtime, whose own listing omits TUI-handled commands - /help <command> still forwards to the runtime for per-command details - fullscreen header hint gains '/quota balances' --- packages/zcode-tui/src/fullscreen-header.ts | 2 +- packages/zcode-tui/src/help-summary-view.ts | 24 +++++++++++++++++++++ packages/zcode-tui/src/index.ts | 24 +++++++++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 packages/zcode-tui/src/help-summary-view.ts diff --git a/packages/zcode-tui/src/fullscreen-header.ts b/packages/zcode-tui/src/fullscreen-header.ts index 97148589..985ac78b 100644 --- a/packages/zcode-tui/src/fullscreen-header.ts +++ b/packages/zcode-tui/src/fullscreen-header.ts @@ -231,7 +231,7 @@ export class SessionWelcome implements Component { frameContent(this.theme.bold("Ask a task about this workspace"), frameWidth, this.theme), frameRule( "bottom", - this.theme.muted("/help commands · /status details"), + this.theme.muted("/help commands · /status details · /quota balances"), frameWidth, this.theme ) diff --git a/packages/zcode-tui/src/help-summary-view.ts b/packages/zcode-tui/src/help-summary-view.ts new file mode 100644 index 00000000..2ce87fe7 --- /dev/null +++ b/packages/zcode-tui/src/help-summary-view.ts @@ -0,0 +1,24 @@ +import { truncateToWidth, type Component } from "@earendil-works/pi-tui"; +import type { ZCodeTheme } from "./theme.ts"; + +/** + * Bare `/help` content: the merged command list (runtime-provided commands via + * the host + TUI-local commands like /status and /quota). Width-safe: every + * line truncates to the dialog width, never wraps. + */ +export class HelpSummaryView implements Component { + constructor( + private readonly theme: ZCodeTheme, + private readonly lines: string[], + private readonly footnote: string | undefined = undefined + ) {} + + render(width: number): string[] { + const safeWidth = Math.max(1, width); + const rendered = this.lines.map(line => truncateToWidth(line, safeWidth, "…")); + if (this.footnote) rendered.push("", this.theme.muted(truncateToWidth(this.footnote, safeWidth, "…"))); + return rendered; + } + + invalidate(): void {} +} diff --git a/packages/zcode-tui/src/index.ts b/packages/zcode-tui/src/index.ts index 38bd5bd1..b1f8b6fa 100644 --- a/packages/zcode-tui/src/index.ts +++ b/packages/zcode-tui/src/index.ts @@ -246,6 +246,7 @@ import { import { createTheme, type ZCodeTheme } from "./theme.ts"; import { StatusLine, type StatusLineField } from "./status-line.ts"; import { readQuotaStatusline } from "./quota-statusline.ts"; +import { HelpSummaryView } from "./help-summary-view.ts"; import { QuotaView } from "./quota-view.ts"; import { loadCurrentQuotaOverview } from "../../../src/quota.ts"; import { SystemEventView, type SystemEventData } from "./system-event-view.ts"; @@ -1851,6 +1852,11 @@ class ZCodeTui { return; } + if (input === "/help") { + await this.showHelpSummary(); + return; + } + if (input === "/quota") { await this.showQuotaDetails(); return; @@ -5312,6 +5318,24 @@ class ZCodeTui { }); } + /** + * Bare `/help` renders the merged command list (runtime-provided + TUI-local). + * `/help <command>` still forwards to the runtime, which owns per-command details. + */ + private async showHelpSummary(): Promise<void> { + const commands = this.autocompleteCommands(); + const lines = commands.map(command => { + const hint = command.argumentHint ? ` [${command.argumentHint}]` : ""; + return `- /${command.name}${hint}: ${command.description}`; + }); + await this.showChoice({ + title: "Help", + prompt: "All slash commands — runtime-provided and TUI-local.", + content: new HelpSummaryView(this.theme, lines, "Use /help <command> for runtime command details. Custom plugin commands live under /plugins."), + items: [{ value: "close", label: "Close" }] + }); + } + private async showQuotaDetails(): Promise<void> { const result = await loadCurrentQuotaOverview(); if (!result.ok) { From 0a081d0568f6352df1aba6a0cdc912f7616a2eb5 Mon Sep 17 00:00:00 2001 From: rakxdev <rakxdev@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:16:52 +0530 Subject: [PATCH 05/11] =?UTF-8?q?feat(tui):=20tighten=20/quota=20slot=20ti?= =?UTF-8?q?tles=20=E2=80=94=20bare=20percent=20beside=20the=20name?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - percent renders as bare 'NNN%' right after the model name with a bounded gap (6 spaces max, shrinks on narrow terminals) instead of right-aligning to the far edge of the dialog - drop the redundant 'server clock' note from the expiry line - exhausted slots keep the error tint; detail line carries state --- packages/zcode-tui/src/quota-view.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/zcode-tui/src/quota-view.ts b/packages/zcode-tui/src/quota-view.ts index ea9a587e..e986d130 100644 --- a/packages/zcode-tui/src/quota-view.ts +++ b/packages/zcode-tui/src/quota-view.ts @@ -49,7 +49,7 @@ export class QuotaView implements Component { lines.push(this.theme.accent(`${plan.name}${status}`)); } const expiry = formatExpiry(plan?.endsAt); - if (expiry) lines.push(this.theme.muted(`Expires ${expiry} · server clock`)); + if (expiry) lines.push(this.theme.muted(`Expires ${expiry}`)); if (plan?.name || expiry) lines.push(""); const slots = this.overview.balances.slice(0, MAX_RENDERED_SLOTS); @@ -87,14 +87,15 @@ export class QuotaView implements Component { private slotTitle(slot: QuotaSlot, safeWidth: number): string { const name = slot.name ?? "model"; const tint = this.slotTint(slot); + // Bare percent (the detail line carries used/total and "exhausted"), placed + // beside the name with a bounded, comfortable gap — wide terminals never + // push it to the far edge, and it shrinks before getting cut on narrow ones. const percent = slot.percentLeft === undefined ? undefined - : slot.percentLeft <= 0 - ? "exhausted" - : `${Math.round(slot.percentLeft)}% left`; + : `${Math.round(slot.percentLeft)}%`; if (percent === undefined) return truncateToWidth(name, safeWidth, "…"); - const gap = Math.max(1, safeWidth - visibleWidth(name) - visibleWidth(percent) - 1); - const padded = name + " ".repeat(Math.min(gap, 64)) + tint(percent); + const gap = Math.max(2, Math.min(6, safeWidth - visibleWidth(name) - visibleWidth(percent) - 1)); + const padded = name + " ".repeat(gap) + tint(percent); return truncateToWidth(padded, safeWidth, "…"); } From 1bacf5d09f326272c72f4e0528a39c10adaef3ac Mon Sep 17 00:00:00 2001 From: rakxdev <rakxdev@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:01:29 +0530 Subject: [PATCH 06/11] fix(tui): avoid double-wrapping argument hints in the help summary --- packages/zcode-tui/src/index.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/zcode-tui/src/index.ts b/packages/zcode-tui/src/index.ts index b1f8b6fa..6ce2f809 100644 --- a/packages/zcode-tui/src/index.ts +++ b/packages/zcode-tui/src/index.ts @@ -5325,7 +5325,8 @@ class ZCodeTui { private async showHelpSummary(): Promise<void> { const commands = this.autocompleteCommands(); const lines = commands.map(command => { - const hint = command.argumentHint ? ` [${command.argumentHint}]` : ""; + const rawHint = command.argumentHint?.trim() ?? ""; + const hint = rawHint ? ` ${rawHint.startsWith("[") ? rawHint : `[${rawHint}]`}` : ""; return `- /${command.name}${hint}: ${command.description}`; }); await this.showChoice({ From 3bf27f1dd6afcd8afcf127b9d36552e3aaf81382 Mon Sep 17 00:00:00 2001 From: rakxdev <rakxdev@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:05:54 +0530 Subject: [PATCH 07/11] feat(tui): sort the merged /help listing alphabetically --- packages/zcode-tui/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/zcode-tui/src/index.ts b/packages/zcode-tui/src/index.ts index 6ce2f809..e6238dc2 100644 --- a/packages/zcode-tui/src/index.ts +++ b/packages/zcode-tui/src/index.ts @@ -5323,7 +5323,7 @@ class ZCodeTui { * `/help <command>` still forwards to the runtime, which owns per-command details. */ private async showHelpSummary(): Promise<void> { - const commands = this.autocompleteCommands(); + const commands = this.autocompleteCommands().slice().sort((a, b) => a.name.localeCompare(b.name)); const lines = commands.map(command => { const rawHint = command.argumentHint?.trim() ?? ""; const hint = rawHint ? ` ${rawHint.startsWith("[") ? rawHint : `[${rawHint}]`}` : ""; From 461dba8a0a190c50f81f23fced303ee8790ce515 Mon Sep 17 00:00:00 2001 From: rakxdev <rakxdev@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:18:32 +0530 Subject: [PATCH 08/11] feat(tui): add /model default to save the default model for new sessions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - /model default opens the existing Default model picker (showModelProviderSettings → options.setDefaultModel → the runtime's saveConfiguredDefault), which was previously reachable only via /settings → Model providers - the transient-switch notice now points at '/model default' - parse helper isModelDefaultRequest + tests --- packages/zcode-tui/src/index.ts | 10 +++++++++- packages/zcode-tui/src/selectors.ts | 4 ++++ test/selectors.test.ts | 20 ++++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 test/selectors.test.ts diff --git a/packages/zcode-tui/src/index.ts b/packages/zcode-tui/src/index.ts index e6238dc2..cd7f4090 100644 --- a/packages/zcode-tui/src/index.ts +++ b/packages/zcode-tui/src/index.ts @@ -162,6 +162,7 @@ import { explicitModelRequest, isEffortPickerRequest, isModePickerRequest, + isModelDefaultRequest, isModelPickerRequest, modePicker, modelPicker, @@ -1901,6 +1902,13 @@ class ZCodeTui { } return; } + // `/model default` opens the default-model picker: it persists the shared + // default (used by new sessions) via the runtime's saveConfiguredDefault. + if (isModelDefaultRequest(input)) { + this.addUserMessage(submission.displayInput); + await this.showModelProviderSettings(); + return; + } // Explicit `/model <provider/model>` is also a session-only switch — the // bridge persists the native session selection without changing the shared default. const explicitModel = explicitModelRequest(input); @@ -4302,7 +4310,7 @@ class ZCodeTui { await this.handleResult(result, false); const status = !recovering && this.model === previousModel ? "already active" : "now"; this.addNotice( - `Session model ${status}: ${this.model} · saved defaults unchanged.`, + `Session model ${status}: ${this.model} · saved defaults unchanged · /model default saves it for new sessions.`, "muted" ); } catch (error) { diff --git a/packages/zcode-tui/src/selectors.ts b/packages/zcode-tui/src/selectors.ts index 1c735e51..3bf4347e 100644 --- a/packages/zcode-tui/src/selectors.ts +++ b/packages/zcode-tui/src/selectors.ts @@ -60,6 +60,10 @@ export function explicitModelRequest(input: string): string | undefined { return argument; } +export function isModelDefaultRequest(input: string): boolean { + return /^\/model\s+default$/iu.test(input.trim()); +} + export function isEffortPickerRequest(input: string): boolean { return pickerRequest(input, new Set(["effort", "variant"])); } diff --git a/test/selectors.test.ts b/test/selectors.test.ts new file mode 100644 index 00000000..7c6bae52 --- /dev/null +++ b/test/selectors.test.ts @@ -0,0 +1,20 @@ +import { expect, test } from "bun:test"; +import { explicitModelRequest, isModelDefaultRequest } from "../packages/zcode-tui/src/selectors.ts"; + +test("isModelDefaultRequest matches only the exact /model default form", () => { + expect(isModelDefaultRequest("/model default")).toBe(true); + expect(isModelDefaultRequest(" /model default ")).toBe(true); + expect(isModelDefaultRequest("/MODEL DEFAULT")).toBe(true); + expect(isModelDefaultRequest("/model default ")).toBe(true); + expect(isModelDefaultRequest("/model")).toBe(false); + expect(isModelDefaultRequest("/model list")).toBe(false); + expect(isModelDefaultRequest("/model account:zai-start-plan/GLM-5.3-Flash")).toBe(false); + expect(isModelDefaultRequest("/model defaults")).toBe(false); + expect(isModelDefaultRequest("")).toBe(false); +}); + +test("explicitModelRequest still treats other /model arguments as transient switches", () => { + expect(explicitModelRequest("/model default")).toBeUndefined(); + expect(explicitModelRequest("/model account:zai-start-plan/GLM-5.3-Flash")).toBe("account:zai-start-plan/GLM-5.3-Flash"); + expect(explicitModelRequest("/model main")).toBe("main"); +}); From 32ffd99b7e86ec47c48366df25be85003d195cf5 Mon Sep 17 00:00:00 2001 From: rakxdev <rakxdev@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:30:44 +0530 Subject: [PATCH 09/11] docs: document /quota, /model default and ui.quotaStatusline - README: quota card + statusline in Features; /model default in the model-default paragraph - setting.example.json: ui.quotaStatusline example (default false) - docs/CONFIGURATION.md + zh-CN: Plan quota statusline sections --- README.md | 5 ++++- docs/CONFIGURATION.md | 10 ++++++++++ docs/CONFIGURATION.zh-CN.md | 12 ++++++++++++ setting.example.json | 1 + 4 files changed, 27 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ebb51d33..56788179 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,8 @@ workflow panels; status-bar-only Shift+Tab mode cycling cycling (Tab also cycles effort on an empty prompt); structured session-goal status in the right side of the turn footer; animated active-turn timer with a static `ZCODE_TUI_REDUCED_MOTION=1` fallback; responsive context-remaining and session-token metrics. +optional plan-quota statusline segment (`ui.quotaStatusline`) and a +`/quota` balance card for signed-in Coding Plan / Start Plan accounts. **Session discovery.** Bare `/resume` opens a directory-scoped picker; `/sessions` browses desktop and CLI sessions across directories, including forks @@ -567,7 +569,8 @@ overrides leave Desktop's credentials and provider configuration untouched. Client headers and a local usage row do not independently prove server-side bonus accounting. -`/settings` saves the default model; `/model` changes only the current session. +`/settings` and `/model default` save the default model; `/model` changes only +the current session. See [`provider.example.json`](./provider.example.json) for complete field examples and the [provider configuration reference](./docs/PROVIDER_CONFIG.md) for multimodal capabilities, native search, token limits, reasoning maps and automatic upstream diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 39fff6bb..4aa29d69 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -637,6 +637,16 @@ user config: `~/.zcode/cli/setting.json` on macOS/Linux or takes priority over terminal probing. `auto` queries the terminal background color and color scheme at startup and re-applies the matching palette. +## Plan quota statusline + +Set `ui.quotaStatusline` to `true` in the user config to add a `quota <percent>%` +segment to the compact statusline. It shows the lowest remaining balance across +the signed-in account's plan slots, warning-tinted below 20% and error-tinted +when exhausted, refreshed in the background every five minutes. It renders only +for OAuth sessions (Start Plan / Coding Plan); manual API-key providers have no +zcode-plan balance to read. `/quota` opens the full balance card on demand and +refreshes immediately. + ## Turn completion notifications Notifications are enabled by default and emitted after a normal agent turn diff --git a/docs/CONFIGURATION.zh-CN.md b/docs/CONFIGURATION.zh-CN.md index 826b60da..0caaff70 100644 --- a/docs/CONFIGURATION.zh-CN.md +++ b/docs/CONFIGURATION.zh-CN.md @@ -513,6 +513,18 @@ ZCODE_TUI_RUNTIME_LOG=/tmp/zcode-tui-runtime.log zcode } } ``` +``` + +## 计划额度状态栏 + +在用户配置中将 `ui.quotaStatusline` 设为 `true`,紧凑状态栏会追加 +`quota <percent>%` 段:显示登录账号所有计划槽位中剩余最少的一项, +低于 20% 时以警告色显示,耗尽时以错误色显示,后台每五分钟刷新一次。 +该功能仅适用于 OAuth 会话(Start Plan / Coding Plan);手动 API-key +提供商没有可读取的 zcode-plan 余额。`/quota` 可随时打开完整余额卡片 +并立即刷新。 + + 正常退出或处理 `SIGINT`、`SIGTERM`、`SIGHUP` 时会恢复终端状态。 任何终端程序都无法拦截强制的 `SIGKILL`。 diff --git a/setting.example.json b/setting.example.json index 82bdb55e..684154b9 100644 --- a/setting.example.json +++ b/setting.example.json @@ -56,6 +56,7 @@ "theme": "auto", "tuiMode": "regular", "toolCallStyle": "regular", + "quotaStatusline": false, "copyOnSelect": true, "notifications": { "method": "auto", From e9451efd294e68b7878c9efdb175561a22ebfebd Mon Sep 17 00:00:00 2001 From: Kingsword <kingsword09@gmail.com> Date: Mon, 23 Nov 2026 16:16:51 +0800 Subject: [PATCH 10/11] fix(quota): read existing keychain credentials --- packages/zcode-tui/src/index.ts | 64 ++++++++++++++--------- src/quota.ts | 91 +++++++++++++++++++++++++-------- test/quota.test.ts | 61 +++++++++++++++++++++- 3 files changed, 171 insertions(+), 45 deletions(-) diff --git a/packages/zcode-tui/src/index.ts b/packages/zcode-tui/src/index.ts index cd7f4090..2a07c3a6 100644 --- a/packages/zcode-tui/src/index.ts +++ b/packages/zcode-tui/src/index.ts @@ -5351,7 +5351,7 @@ class ZCodeTui { if (result.reason === "no-oauth-session") { this.addNotice("No shared OAuth session for quota — sign in with /login first.", "warning"); } else if (result.reason === "secure-storage-unavailable") { - this.addNotice("Secure credential storage is unavailable; configure ZCODE_CREDENTIAL_SECRET or ZCODE_CREDENTIAL_SECRET_FILE to read quota.", "warning"); + this.addNotice("Could not read the existing sign-in from secure credential storage. Check that the system keychain is available; signing in again is not required.", "warning"); } else { this.addNotice(`Quota request failed: ${result.detail ?? "unknown error"}`, "warning"); } @@ -6509,30 +6509,42 @@ class ZCodeTui { } } -async function refreshQuotaStatusline(tui: ZCodeTui): Promise<void> { - try { - const result = await loadCurrentQuotaOverview(); - if (!result.ok) { - tui.setQuotaStatusPercent(undefined); - return; +async function startQuotaStatuslineLoop(tui: ZCodeTui): Promise<() => void> { + if (!(await readQuotaStatusline())) return () => {}; + let stopped = false; + let refreshInFlight = false; + let requestController: AbortController | undefined; + const refresh = async (): Promise<void> => { + if (stopped || refreshInFlight) return; + refreshInFlight = true; + const controller = new AbortController(); + requestController = controller; + try { + const result = await loadCurrentQuotaOverview({ signal: controller.signal }); + if (stopped) return; + if (!result.ok) { + tui.setQuotaStatusPercent(undefined); + return; + } + const percents = result.overview.balances + .map(balance => balance.percentLeft) + .filter((percent): percent is number => percent !== undefined); + tui.setQuotaStatusPercent(percents.length ? Math.min(...percents) : undefined); + } catch { + // Background refresh must not surface into the statusline. + } finally { + refreshInFlight = false; + if (requestController === controller) requestController = undefined; } - const percents = result.overview.balances - .map(balance => balance.percentLeft) - .filter((percent): percent is number => percent !== undefined); - tui.setQuotaStatusPercent(percents.length ? Math.min(...percents) : undefined); - } catch { - // background refresh must never surface into the statusline - } -} - -async function startQuotaStatuslineLoop(tui: ZCodeTui): Promise<void> { - if (!(await readQuotaStatusline())) return; - const refresh = (): void => { - void refreshQuotaStatusline(tui); }; - refresh(); - const timer = setInterval(refresh, 300_000); + void refresh(); + const timer = setInterval(() => { void refresh(); }, 300_000); timer.unref?.(); + return () => { + stopped = true; + clearInterval(timer); + requestController?.abort(); + }; } export async function runTui(options: TuiOptions): Promise<void> { @@ -6540,6 +6552,10 @@ export async function runTui(options: TuiOptions): Promise<void> { const readyOptions = await loadTuiStartupOptions(options); if (!readyOptions) return; const tui = new ZCodeTui(readyOptions); - startQuotaStatuslineLoop(tui); - await tui.run(); + const stopQuotaStatuslineLoop = await startQuotaStatuslineLoop(tui); + try { + await tui.run(); + } finally { + stopQuotaStatuslineLoop(); + } } diff --git a/src/quota.ts b/src/quota.ts index e9bdd100..20e8672d 100644 --- a/src/quota.ts +++ b/src/quota.ts @@ -1,8 +1,9 @@ import { createDecipheriv, createHash, randomUUID } from "node:crypto"; import { readFileSync } from "node:fs"; import { homedir, release, userInfo } from "node:os"; -import { join } from "node:path"; +import { join, resolve } from "node:path"; import { credentialsPath, sharedDataBaseDir } from "./config-paths.ts"; +import { createKeychainRecovery } from "./runtime-keychain-recovery.ts"; import { readStartPlanSession } from "./start-plan.ts"; /** @@ -22,6 +23,8 @@ const IV_BYTES = 12; const TAG_BYTES = 16; const SECRET_MIN_BYTES = 32; const SECRET_MAX_BYTES = 4096; +const OS_KEYRING_SERVICE = "ZCode Credential Encryption"; +const BILLING_REQUEST_TIMEOUT_MS = 10_000; export interface QuotaSlot { name: string | undefined; @@ -78,25 +81,30 @@ function isPrintableBase64Url(part: string): boolean { return /^[A-Za-z0-9_-]*$/.test(part); } -/** `enc:v2:env:<keyFingerprint>:<iv>.<tag>.<ct>` — base64url, AES-256-GCM, no AAD. */ -function tryOpenV2Env(body: string, secretCandidates: string[]): string | undefined { +function tryOpenV2Key(body: string, key: Buffer): string | undefined { const colon = body.indexOf(":"); const fingerprint = colon >= 0 ? body.slice(0, colon) : undefined; const payload = colon >= 0 ? body.slice(colon + 1) : body; const parts = payload.split("."); if (parts.length !== 3 || parts.some(part => !isPrintableBase64Url(part))) return undefined; const [iv, tag, bytes] = parts.map(part => Buffer.from(part, "base64url")); - if (!iv || !tag || !bytes || iv.length !== IV_BYTES || tag.length !== TAG_BYTES) return undefined; + if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) return undefined; + if (fingerprint && fingerprint !== keyFingerprint(key)) return undefined; + try { + const decipher = createDecipheriv("aes-256-gcm", key, iv); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(bytes), decipher.final()]).toString("utf8"); + } catch { + return undefined; + } +} + +/** `enc:v2:env:<keyFingerprint>:<iv>.<tag>.<ct>` — base64url, AES-256-GCM, no AAD. */ +function tryOpenV2Env(body: string, secretCandidates: string[]): string | undefined { for (const candidate of secretCandidates) { const key = digest(candidate); - if (fingerprint && fingerprint !== keyFingerprint(key)) continue; - try { - const decipher = createDecipheriv("aes-256-gcm", key, iv); - decipher.setAuthTag(tag); - return Buffer.concat([decipher.update(bytes), decipher.final()]).toString("utf8"); - } catch { - // try the next candidate - } + const opened = tryOpenV2Key(body, key); + if (opened !== undefined) return opened; } return undefined; } @@ -162,16 +170,41 @@ function decryptRecord(value: string, env: NodeJS.ProcessEnv): string | null { return tryOpenV2Env(value.slice("enc:v2:env:".length), candidates) ?? null; } if (value.startsWith("enc:v1:")) return tryOpenLegacy(value, env) ?? null; - if (value.startsWith("enc:v2:os:")) return null; // keyring-protected: not readable outside the owning environment return value; // plaintext record } +function secureStorageError(message = "System credential storage is unavailable."): Error { + return Object.assign(new Error(message), { code: "CREDENTIAL_SECURE_STORAGE_UNAVAILABLE" }); +} + +async function readOsCredentialKey(filePath: string): Promise<Buffer> { + const { AsyncEntry } = await import("@napi-rs/keyring"); + const account = digest(resolve(filePath)).toString("hex"); + const entry = new AsyncEntry(OS_KEYRING_SERVICE, account, { linux: { store: "secret-service" } }); + let encoded: string | null; + try { + encoded = await createKeychainRecovery()(async () => await entry.getPassword()); + } catch (cause) { + throw Object.assign(secureStorageError(), { cause }); + } + if (!encoded || !/^[A-Za-z0-9_-]{43}$/u.test(encoded)) { + throw secureStorageError("The system credential key for this account is unavailable."); + } + const key = Buffer.from(encoded, "base64url"); + if (key.length !== 32) throw secureStorageError("The system credential key for this account is invalid."); + return key; +} + /** * Read-only CredentialReader over the runtime-owned credentials file. * Follows the same path resolution as the runtime (config-paths helpers), * so an isolated `ZCODE_DATA_BASE_DIR` yields that account's records only. */ -export function createFileCredentialReader(env: NodeJS.ProcessEnv = process.env): CredentialReader { +export function createFileCredentialReader( + env: NodeJS.ProcessEnv = process.env, + options: { readOsKey?: (filePath: string) => Promise<Buffer> } = {} +): CredentialReader { + let osKeyPromise: Promise<Buffer> | undefined; return { async loadMany(keys: string[]): Promise<Record<string, string | null>> { let parsed: unknown; @@ -184,9 +217,22 @@ export function createFileCredentialReader(env: NodeJS.ProcessEnv = process.env) return Object.fromEntries(keys.map(key => [key, null])); } const records = parsed as Record<string, unknown>; + const requestedValues = keys.map(key => records[key]); + const needsOsKey = requestedValues.some(value => typeof value === "string" && value.startsWith("enc:v2:os:")); + if (needsOsKey && !osKeyPromise) { + osKeyPromise = (options.readOsKey ?? readOsCredentialKey)(credentialsPath(env)); + } + const osKey = needsOsKey ? await osKeyPromise : undefined; return Object.fromEntries(keys.map(key => { const value = records[key]; - const plain = typeof value === "string" ? decryptRecord(value, env) : null; + let plain: string | null = null; + if (typeof value === "string") { + if (value.startsWith("enc:v2:os:")) { + plain = tryOpenV2Key(value.slice("enc:v2:os:".length), osKey!) ?? null; + } else { + plain = decryptRecord(value, env); + } + } return [key, plain && plain.length > 0 ? plain : null]; })); } @@ -297,14 +343,17 @@ export async function fetchQuotaOverview( appVersion?: string; signal?: AbortSignal; fetchImpl?: typeof fetch; + timeoutMs?: number; } = {} ): Promise<QuotaOverview> { const doFetch = options.fetchImpl ?? fetch; + const timeout = AbortSignal.timeout(options.timeoutMs ?? BILLING_REQUEST_TIMEOUT_MS); + const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout; let response: Response; try { response = await doFetch(BILLING_BALANCE_URL, { headers: billingHeaders(session, options), - signal: options.signal + signal }); } catch (error) { throw new QuotaRequestError(error instanceof Error ? error.message : String(error)); @@ -336,19 +385,21 @@ export async function loadCurrentQuotaOverview( } = {} ): Promise<QuotaReadResult> { const env = options.env ?? process.env; - const session = await readStartPlanSession(createFileCredentialReader(env), options.signal); - if (!session) return { ok: false, reason: "no-oauth-session" }; try { + const session = await readStartPlanSession(createFileCredentialReader(env), options.signal); + if (!session) return { ok: false, reason: "no-oauth-session" }; const overview = await fetchQuotaOverview(session, { deviceMid: readDeviceMid(env), - appVersion: options.appVersion, + appVersion: options.appVersion ?? env.ZCODE_APP_VERSION, signal: options.signal, fetchImpl: options.fetchImpl }); return { ok: true, overview }; } catch (error) { const detail = error instanceof Error ? error.message : String(error); - const reason = detail.includes("Secure credential storage") || detail.includes("CREDENTIAL_SECURE_STORAGE_UNAVAILABLE") + const code = error && typeof error === "object" && "code" in error ? error.code : undefined; + const reason = code === "CREDENTIAL_SECURE_STORAGE_UNAVAILABLE" + || detail.includes("Secure credential storage") || detail.includes("System credential storage") ? "secure-storage-unavailable" : "request-failed"; return { ok: false, reason, detail }; diff --git a/test/quota.test.ts b/test/quota.test.ts index 92b8b07e..a72286cb 100644 --- a/test/quota.test.ts +++ b/test/quota.test.ts @@ -28,6 +28,15 @@ function sealV2Env(value: string, secret = SECRET): string { return `enc:v2:env:${fingerprint}:${payload}`; } +function sealV2Os(value: string, key: Buffer): string { + const iv = randomBytes(12); + const cipher = createCipheriv("aes-256-gcm", key, iv); + const bytes = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]); + const fingerprint = createHash("sha256").update(key).digest("hex").slice(0, 24); + const payload = [iv, cipher.getAuthTag(), bytes].map(part => part.toString("base64url")).join("."); + return `enc:v2:os:${fingerprint}:${payload}`; +} + /** The real billing/balance shape captured from a Start Plan account (values adjusted). */ function billingFixture(): unknown { return { @@ -192,10 +201,48 @@ test("file credential reader decrypts enc:v2:env records from the isolated data expect(values["missing"]).toBeNull(); }); +test("file credential reader decrypts OS-keyring records without changing the login", async () => { + const key = randomBytes(32); + const { env } = isolatedEnv({ + ".zcode/v2/credentials.json": JSON.stringify({ + "oauth:active_provider": sealV2Os("zai", key), + "zcodejwttoken": sealV2Os(APP_JWT, key), + "oauth:zai:user_info": sealV2Os(JSON.stringify({ user_id: "desktop-user" }), key) + }) + }); + let keyReads = 0; + const store = createFileCredentialReader(env, { + readOsKey: async () => { + keyReads++; + return key; + } + }); + const session = await readStartPlanSession(store); + expect(session).toMatchObject({ family: "zai", identity: "desktop-user", token: APP_JWT }); + expect(keyReads).toBe(1); +}); + +test("file credential reader propagates unavailable OS credential storage", async () => { + const key = randomBytes(32); + const { env } = isolatedEnv({ + ".zcode/v2/credentials.json": JSON.stringify({ + "oauth:active_provider": sealV2Os("zai", key) + }) + }); + const store = createFileCredentialReader(env, { + readOsKey: async () => { + throw Object.assign(new Error("keychain is locked"), { code: "CREDENTIAL_SECURE_STORAGE_UNAVAILABLE" }); + } + }); + await expect(store.loadMany(["oauth:active_provider"])).rejects.toMatchObject({ + code: "CREDENTIAL_SECURE_STORAGE_UNAVAILABLE" + }); +}); + test("file credential reader returns nulls for unreadable or keyring-protected records", async () => { const { env } = isolatedEnv({ ".zcode/v2/credentials.json": JSON.stringify({ - "zcodejwttoken": "enc:v2:os:deadbeef:aGVsbG8.AAAAAAAAAAAAAAAAAAAAAA.aGVsbG8", + "zcodejwttoken": "enc:v2:env:deadbeef:aGVsbG8.AAAAAAAAAAAAAAAAAAAAAA.aGVsbG8", "plain": "plain-value", "broken": "enc:v2:env:not-a-valid-record" }) @@ -244,6 +291,7 @@ test("loadCurrentQuotaOverview returns the parsed overview through a mocked tran }), ".zcode/v2/telemetry-state.json": JSON.stringify({ deviceMid: "device-mid-42" }) }); + env.ZCODE_APP_VERSION = "3.19.1"; let capturedHeaders: Record<string, string> | undefined; const fetchImpl = (async (input: unknown, init?: { headers?: Record<string, string> }) => { capturedHeaders = init?.headers; @@ -255,6 +303,7 @@ test("loadCurrentQuotaOverview returns the parsed overview through a mocked tran expect(result.overview.plans[0]?.name).toBe("ZCODE WEEKEND BUILD"); expect(result.overview.balances[0]?.remainingUnits).toBe(499799821); expect(capturedHeaders?.["X-Device-Mid"]).toBe("device-mid-42"); + expect(capturedHeaders?.["X-ZCode-App-Version"]).toBe("3.19.1"); expect(capturedHeaders?.["Authorization"]).toBe(`Bearer ${APP_JWT}`); }); @@ -287,3 +336,13 @@ test("loadCurrentQuotaOverview surfaces endpoint rejections as request failures" expect(result.reason).toBe("request-failed"); expect(result.detail).toContain("Z.ai user information is invalid"); }); + +test("fetchQuotaOverview aborts requests that exceed the configured timeout", async () => { + const fetchImpl = ((_input: unknown, init?: { signal?: AbortSignal }) => new Promise<Response>((_resolve, reject) => { + init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true }); + })) as unknown as typeof fetch; + await expect(fetchQuotaOverview( + { family: "zai", identity: "user-1", token: APP_JWT }, + { fetchImpl, timeoutMs: 5 } + )).rejects.toThrow(/timed out/iu); +}); From 0fb8f125041f729bbff4b578023bc4439693e1a0 Mon Sep 17 00:00:00 2001 From: Kingsword <kingsword09@gmail.com> Date: Tue, 24 Nov 2026 00:09:14 +0800 Subject: [PATCH 11/11] test(tui): align smoke flow with help dialog --- scripts/smoke-tui.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/scripts/smoke-tui.ts b/scripts/smoke-tui.ts index 8f1ed796..513dbc32 100755 --- a/scripts/smoke-tui.ts +++ b/scripts/smoke-tui.ts @@ -237,7 +237,9 @@ try { await waitFor("BigModel session model", new RegExp(`Model\\s+${literal(bigmodelModel)}(?:\\s|$)`, "i"), statusStart); terminal.write("\r"); await Bun.sleep(50); - await sendAndWait("/help\r", "help output", /Slash commands:|Usage:/i); + await sendAndWait("/help\r", "help output", /All slash commands.*runtime-provided and TUI-local/i); + terminal.write("\x1b"); + await Bun.sleep(50); await sendAndWait("/plan on\r", "plan enabled", /Plan enabled · permission mode: build/i); await sendAndWait("/mode edit\r", "edit permission mode", /mode switched to edit/i); await sendAndWait("/plan off\r", "plan disabled with permissions preserved", /Plan disabled · permission mode: edit/i); @@ -360,7 +362,7 @@ if (`${selected.providerId}/${selected.modelId}` !== bigmodelModel) { if (leakedFiles.length > 0) { throw new Error(`The API key leaked into a plaintext file: ${leakedFiles.join(", ")}`); } -if (!/Slash commands:|Usage:/i.test(plain)) { +if (!/All slash commands.*runtime-provided and TUI-local/i.test(plain)) { throw new Error(`The /help command did not render.\n${plain.slice(-4_000)}`); } if (!/Plan enabled · permission mode: build/i.test(plain)) {