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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions docs/CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`。
Expand Down
2 changes: 1 addition & 1 deletion packages/zcode-tui/src/fullscreen-header.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
24 changes: 24 additions & 0 deletions packages/zcode-tui/src/help-summary-view.ts
Original file line number Diff line number Diff line change
@@ -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 {}
}
136 changes: 134 additions & 2 deletions packages/zcode-tui/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ import {
explicitModelRequest,
isEffortPickerRequest,
isModePickerRequest,
isModelDefaultRequest,
isModelPickerRequest,
modePicker,
modelPicker,
Expand Down Expand Up @@ -245,6 +246,10 @@ 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 { 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";
import { sanitizeTerminalText, stripCaretHighlight } from "./terminal-text.ts";
import { ThinkingView } from "./thinking-view.ts";
Expand Down Expand Up @@ -708,6 +713,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[];
Expand Down Expand Up @@ -1528,6 +1534,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: "<title>" },
{ name: "config", description: "Configure ZCode TUI settings" },
{ name: "settings", description: "Configure ZCode TUI settings" },
Expand Down Expand Up @@ -1845,6 +1852,16 @@ class ZCodeTui {
await this.showStatusDetails();
return;
}

if (input === "/help") {
await this.showHelpSummary();
return;
}

if (input === "/quota") {
await this.showQuotaDetails();
return;
}
const renameRequest = sessionRenameRequest(input);
if (renameRequest !== undefined) {
await this.handleSessionRename(renameRequest);
Expand Down Expand Up @@ -1885,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);
Expand Down Expand Up @@ -4286,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) {
Expand Down Expand Up @@ -5302,6 +5326,50 @@ 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().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}]`}` : "";
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) {
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("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");
}
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
Expand Down Expand Up @@ -5858,6 +5926,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[] = [
Expand Down Expand Up @@ -5920,6 +5994,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({
Expand Down Expand Up @@ -6422,8 +6509,53 @@ class ZCodeTui {
}
}

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;
}
};
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> {
suppressTuiAiSdkWarnings();
const readyOptions = await loadTuiStartupOptions(options);
if (readyOptions) await new ZCodeTui(readyOptions).run();
if (!readyOptions) return;
const tui = new ZCodeTui(readyOptions);
const stopQuotaStatuslineLoop = await startQuotaStatuslineLoop(tui);
try {
await tui.run();
} finally {
stopQuotaStatuslineLoop();
}
}
26 changes: 26 additions & 0 deletions packages/zcode-tui/src/quota-statusline.ts
Original file line number Diff line number Diff line change
@@ -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
}
}
Loading
Loading