Skip to content

Commit dde3c4b

Browse files
authored
Merge pull request #1 from sakmist/feat/quota-display
feat(quota): show plan balances in the TUI panel and a `quota` CLI
2 parents 32ce94d + bc4f573 commit dde3c4b

6 files changed

Lines changed: 313 additions & 2 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@ services:
192192

193193
**周末/体验套餐自动领取 (claim)** —— 默认开启。代理每 5 分钟探测一次官方的限量套餐活动页,上新瞬间自动帮你抢(`claim.enabled: false` 可关闭)。手动抢:`bun run src/index.ts claim`。
194194

195+
**额度显示 (quota)** —— 登录后面板会自动查一次当前套餐的各模型额度(剩余 / 总额、到期时间),之后按 <kbd>r</kbd> 手动刷新。也可以命令行直接查:`bun run src/index.ts quota`(对应 HTTP 接口 `GET /quota`)。注意上游计费网关对频繁查询有限速,所以面板不做定时轮询。
196+
195197
</details>
196198

197199
## 🧮 可用模型

‎README_EN.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,8 @@ The plan type (`plan`: `coding-plan` personal / `start-plan` trial) can be toggl
193193

194194
**Weekend/trial plan auto-claiming (claim)** — enabled by default. The proxy probes the official limited-plan campaign page every 5 minutes and grabs new drops for you the instant they appear (`claim.enabled: false` to disable). Manual run: `bun run src/index.ts claim`.
195195

196+
**Quota display (quota)** — after login the panel fetches the plan's per-model balances (remaining / total units, expiry) once automatically; refresh manually with <kbd>r</kbd>. CLI: `bun run src/index.ts quota` (HTTP: `GET /quota`). The upstream billing gateway rate-limits frequent queries, so the panel does not poll on a timer.
197+
196198
</details>
197199

198200
## 🧮 Available Models

‎src/index.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ function dispatchCli(args: string[]): void {
9191
authCommand(args.slice(1));
9292
} else if (cmd === "claim") {
9393
void claimCommand(args.slice(1));
94+
} else if (cmd === "quota") {
95+
void quotaCommand();
9496
} else if (cmd === "android") {
9597
// Explicit catch: an async startup failure (e.g. control port already
9698
// bound by an orphaned process) must exit non-zero deterministically, not
@@ -148,6 +150,7 @@ Usage:
148150
zcode-proxy auth logout Clear stored credentials
149151
zcode-proxy auth status Show current authentication state
150152
zcode-proxy claim [list|now] List / claim weekend-plan trial packages
153+
zcode-proxy quota Show plan quota (per-model remaining/total)
151154
zcode-proxy version Show version
152155
zcode-proxy help Show this help
153156
@@ -399,6 +402,51 @@ async function claimCommand(args: string[]): Promise<void> {
399402
}
400403
}
401404

405+
/**
406+
* `quota` subcommand — print the live plan balance snapshot (per-model
407+
* remaining/total units + expiry) from the billing control plane. Reuses
408+
* collectQuotaSnapshot (same path GET /quota serves).
409+
*/
410+
async function quotaCommand(): Promise<void> {
411+
const path = process.env.ZCODE_PROXY_CONFIG ?? "config.yaml";
412+
if (!existsSync(path)) {
413+
console.error(`Config file not found: ${path} (run serve once or create it).`);
414+
process.exit(1);
415+
}
416+
ensureDeviceMidInConfig(path);
417+
const config = loadConfig(path);
418+
try {
419+
const { collectQuotaSnapshot } = await import("./server/routes-quota.js");
420+
const snap = await collectQuotaSnapshot(config);
421+
if (snap.balances.length === 0) {
422+
console.log("No balance windows reported by the billing endpoint.");
423+
}
424+
for (const b of snap.balances) {
425+
const exp = b.expiresAt ? ` · expires ${fmtQuotaExpiry(b.expiresAt)}` : "";
426+
console.log(` ${b.showName || "(unnamed)"}: ${b.remainingUnits.toLocaleString("en-US")} / ${b.totalUnits.toLocaleString("en-US")} units${exp}`);
427+
}
428+
for (const plan of snap.claimablePlans) {
429+
const grants = plan.entitlements
430+
.map((e) => `${e.showName || plan.name}: ${(e.grantUnits ?? 0).toLocaleString("en-US")} ${e.unitType}`)
431+
.join("; ");
432+
console.log(` claimable: ${plan.name}${grants ? ` (${grants})` : ""}`);
433+
}
434+
for (const err of snap.errors) console.error(` ⚠ ${err}`);
435+
if (snap.errors.length > 0) process.exitCode = 1;
436+
} catch (err) {
437+
console.error(`quota query failed: ${(err as Error).message}`);
438+
process.exit(1);
439+
}
440+
}
441+
442+
/** `YYYY-MM-DD HH:mm` local time; `expiresAt` may be seconds or milliseconds. */
443+
function fmtQuotaExpiry(expiresAt: number): string {
444+
const d = new Date(expiresAt > 1e12 ? expiresAt : expiresAt * 1000);
445+
if (Number.isNaN(d.getTime())) return String(expiresAt);
446+
const pad = (n: number): string => String(n).padStart(2, "0");
447+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
448+
}
449+
402450
async function authLogin(args: string[]): Promise<void> {
403451
const provider = args[0] as ProviderId | undefined;
404452
const importMode = args.includes("--import");

‎src/tui/app.ts‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,13 @@ import { openBrowser } from "../runtime/open-browser.js";
2424
import { pasteLoginInstructions, readPastedLine, boldIfTTY } from "../runtime/paste-login.js";
2525
import { isGuestOriginError, describeGuestError } from "../runtime/guest-error.js";
2626
import { ensureDeviceMidInConfig, VERSION, type ServeArgs } from "../index.js";
27+
import { collectQuotaSnapshot, type QuotaSnapshot } from "../server/routes-quota.js";
2728
import { appendFileSync } from "node:fs";
2829
import type { ProxyConfig } from "../config/types.js";
2930
import type { ProviderId } from "../provider/types.js";
3031
import { LogPane, type LogLevel } from "./log-pane.js";
3132
import { KeyParser, type KeyAction } from "./keys.js";
32-
import { buildFrame, findRegion, type ClickAction, type ClickRegion, type Frame } from "./frame.js";
33+
import { buildFrame, findRegion, type ClickAction, type ClickRegion, type Frame, type QuotaState } from "./frame.js";
3334

3435
type PlanTier = "coding-plan" | "start-plan";
3536
type ServerStatus = "stopped" | "starting" | "running" | "error";
@@ -74,6 +75,7 @@ export async function runTui(args: ServeArgs): Promise<void> {
7475
serverError: "",
7576
loginInFlight: false,
7677
loginHint: "",
78+
quota: null as QuotaState | null,
7779
toast: null as { text: string; kind: "ok" | "err" | "info" } | null,
7880
};
7981

@@ -194,6 +196,7 @@ export async function runTui(args: ServeArgs): Promise<void> {
194196
modelCount: config.models.length,
195197
responsesEnabled: config.responses.enabled,
196198
claimAuto: config.claim.enabled && config.claim.auto,
199+
quota: state.quota,
197200
logTotal: view.total,
198201
logView: view.lines,
199202
logFollowing: pane.following,
@@ -237,9 +240,52 @@ export async function runTui(args: ServeArgs): Promise<void> {
237240
const cred = await loadCredential().catch(() => null);
238241
state.loggedIn = cred != null;
239242
state.apiKeyPreview = cred ? `${cred.apiKey.slice(0, 8)}…` : "";
243+
// Logout hides the quota card (the billing calls need the JWT).
244+
if (!state.loggedIn) state.quota = null;
245+
else if (!state.quota) void refreshQuota();
240246
scheduleRender();
241247
}
242248

249+
// --- quota (billing balance windows; manual refresh only — the billing
250+
// gateway rate-limits frequent queries, so no polling timer) ---------------
251+
let quotaFetchInFlight = false;
252+
async function refreshQuota(): Promise<void> {
253+
if (quotaFetchInFlight) return;
254+
quotaFetchInFlight = true;
255+
const firstFetch = state.quota == null;
256+
state.quota = { status: "loading", balances: [], errors: [], error: "", fetchedAt: Date.now() };
257+
scheduleRender();
258+
try {
259+
const snap: QuotaSnapshot = await collectQuotaSnapshot(config);
260+
state.quota = {
261+
status: "ok",
262+
balances: snap.balances.map((b) => ({
263+
showName: b.showName,
264+
remainingUnits: b.remainingUnits,
265+
totalUnits: b.totalUnits,
266+
...(b.expiresAt !== undefined ? { expiresAt: b.expiresAt } : {}),
267+
})),
268+
errors: snap.errors,
269+
error: "",
270+
fetchedAt: Date.now(),
271+
};
272+
} catch (err) {
273+
// Replace the card content with the error — stale balances shown next to
274+
// a failure would read as current numbers.
275+
state.quota = {
276+
status: "error",
277+
balances: [],
278+
errors: [],
279+
error: (err as Error).message,
280+
fetchedAt: Date.now(),
281+
};
282+
if (!firstFetch) setToast(`quota refresh failed: ${(err as Error).message}`, "err");
283+
} finally {
284+
quotaFetchInFlight = false;
285+
scheduleRender();
286+
}
287+
}
288+
243289
// --- proxy lifecycle (mirrors the Android startProxy/stopProxy hooks) ----
244290
async function startProxy(): Promise<void> {
245291
if (state.serverStatus === "running" || state.serverStatus === "starting") return;
@@ -532,6 +578,7 @@ export async function runTui(args: ServeArgs): Promise<void> {
532578
case "s": toggleProxy(); return;
533579
case "l": void startLogin(); return;
534580
case "o": void logout(); return;
581+
case "r": void refreshQuota(); return;
535582
case "p": switchProvider(); return;
536583
case "t": switchPlan(); return;
537584
case "c": pane.clear(); scheduleRender(); return;

‎src/tui/frame.test.ts‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ function baseState(overrides: Partial<FrameState> = {}): FrameState {
1818
modelCount: 6,
1919
responsesEnabled: true,
2020
claimAuto: false,
21+
quota: null,
2122
logTotal: 0,
2223
logView: [],
2324
logFollowing: true,
@@ -238,4 +239,120 @@ describe("buildFrame", () => {
238239
expect(frame).toContain("terminal too small");
239240
expect(frame).not.toContain("╭");
240241
});
242+
243+
test("quota card hidden when quota is null (logged out)", () => {
244+
const text = plainLines(baseState({ quota: null })).join("\n");
245+
expect(text).not.toContain("Quota");
246+
});
247+
248+
test("quota card shows per-model remaining/total with expiry", () => {
249+
const text = plainLines(baseState({
250+
quota: {
251+
status: "ok",
252+
balances: [
253+
{ showName: "GLM-5.3", remainingUnits: 2000000, totalUnits: 3000000, expiresAt: 1767225600 },
254+
{ showName: "GLM Coding", remainingUnits: 5, totalUnits: 100 },
255+
],
256+
errors: [],
257+
error: "",
258+
fetchedAt: new Date("2026-09-29T12:00:00").getTime(),
259+
},
260+
})).join("\n");
261+
expect(text).toContain("Quota");
262+
expect(text).toContain("GLM-5.3");
263+
expect(text).toContain("2,000,000 / 3,000,000");
264+
expect(text).toContain("GLM Coding");
265+
expect(text).toContain("5 / 100");
266+
expect(text).toContain("12:00:00");
267+
expect(text).toContain(" Refresh ");
268+
});
269+
270+
test("quota card caps balance rows to keep the Logs card room", () => {
271+
const balances = Array.from({ length: 8 }, (_, i) => ({
272+
showName: `Model ${i}`,
273+
remainingUnits: i,
274+
totalUnits: 100,
275+
}));
276+
const text = plainLines(baseState({
277+
quota: { status: "ok", balances, errors: [], error: "", fetchedAt: Date.now() },
278+
})).join("\n");
279+
expect(text).toContain("Model 3");
280+
expect(text).not.toContain("Model 4");
281+
});
282+
283+
test("quota card shows error state and upstream warnings", () => {
284+
const text = plainLines(baseState({
285+
quota: {
286+
status: "error",
287+
balances: [],
288+
errors: [],
289+
error: "not logged in — no JWT credential",
290+
fetchedAt: Date.now(),
291+
},
292+
})).join("\n");
293+
expect(text).toContain("unavailable");
294+
expect(text).toContain("not logged in");
295+
const warned = plainLines(baseState({
296+
quota: { status: "ok", balances: [], errors: ["balance: 3012 risk"], error: "", fetchedAt: Date.now() },
297+
})).join("\n");
298+
expect(warned).toContain("⚠");
299+
expect(warned).toContain("3012");
300+
});
301+
302+
test("quota Refresh button is clickable and footer advertises [r]", () => {
303+
const f = buildFrame(baseState({
304+
quota: { status: "ok", balances: [], errors: [], error: "", fetchedAt: Date.now() },
305+
}));
306+
const actions = f.regions.map((r) => r.action);
307+
expect(actions).toContainEqual({ kind: "key", key: "r" });
308+
// The footer drops its tail on 80 columns (like [p]/[t]/[c]); [r] shows
309+
// only on wider terminals.
310+
const wide = buildFrame(baseState({
311+
width: 140,
312+
quota: { status: "ok", balances: [], errors: [], error: "", fetchedAt: Date.now() },
313+
}));
314+
const lines = wide.text.split("\n").map((l) => stripAnsi(l.replace(/\x1b\[K$/, "")));
315+
expect(lines.join("\n")).toContain("[r] quota refresh");
316+
});
317+
318+
test("quota card hides on short terminals so the Logs card keeps room", () => {
319+
const quota = { status: "ok" as const, balances: [{ showName: "GLM-5.3", remainingUnits: 1, totalUnits: 2 }], errors: [], error: "", fetchedAt: Date.now() };
320+
const text = plainLines(baseState({ height: 21, quota })).join("\n");
321+
expect(text).not.toContain("Quota");
322+
const textTall = plainLines(baseState({ height: 22, quota })).join("\n");
323+
expect(textTall).toContain("Quota");
324+
});
325+
326+
test("quota card never pushes the frame past the terminal height", () => {
327+
for (const height of [22, 24, 30, 40]) {
328+
const state = baseState({
329+
height,
330+
logTotal: 50,
331+
logView: Array.from({ length: 50 }, (_, i) => ({ level: "info", text: `log ${i}` })),
332+
quota: {
333+
status: "ok",
334+
balances: Array.from({ length: 6 }, (_, i) => ({ showName: `Model ${i}`, remainingUnits: i, totalUnits: 100 })),
335+
errors: [],
336+
error: "",
337+
fetchedAt: Date.now(),
338+
},
339+
});
340+
expect(plainLines(state).length).toBe(height);
341+
}
342+
});
343+
344+
test("no line exceeds the terminal width with a long quota showName", () => {
345+
const state = baseState({
346+
quota: {
347+
status: "ok",
348+
balances: [{ showName: "超长模型名称测试超长模型名称测试超长模型名称", remainingUnits: 1234567890, totalUnits: 9876543210, expiresAt: 1735689600 }],
349+
errors: [],
350+
error: "",
351+
fetchedAt: Date.now(),
352+
},
353+
});
354+
for (const raw of buildFrame(state).text.split("\n")) {
355+
expect(displayWidth(raw)).toBeLessThanOrEqual(state.width);
356+
}
357+
});
241358
});

0 commit comments

Comments
 (0)