Combine main and sub-agent token totals in sidebar

This commit is contained in:
nhat.nguyenhong 2026-09-28 14:03:55 +00:00
parent a31297c197
commit fa1c8e9354
2 changed files with 63 additions and 24 deletions

View File

@ -225,19 +225,21 @@ Linux/macOS). Two rules for the entry:
not a plugin — it loads as dead weight into every session. not a plugin — it loads as dead weight into every session.
Restart opencode after registering the plugin; then type `/cc-` for autocomplete. The plugin also Restart opencode after registering the plugin; then type `/cc-` for autocomplete. The plugin also
renders a **CommandCode panel in the session sidebar** (`zdr` / `debug`, session token totals, a renders a **CommandCode panel in the session sidebar** (`zdr` / `debug`, combined main + sub-agent
`sub:` line for sub-agent descendants, plus live quota, above the built-in panels) that updates live token totals (`in` / `out` / cache `hit`), plus live quota, above the built-in panels) that updates
as you toggle. Note that in opencode 1.x the slash menu and the live as you toggle. `in` and `out` show the combined main-agent and descendant total with the
sub-agent-only contribution in parentheses (omitted when there are no sub-agents); `hit` is the
cache-read percentage weighted across both. Note that in opencode 1.x the slash menu and the
`Ctrl+P` palette read the same command registry, so these entries appear in both. If you run opencode `Ctrl+P` palette read the same command registry, so these entries appear in both. If you run opencode
against a remote server, the TUI-side file is not visible to the provider on the server host — use against a remote server, the TUI-side file is not visible to the provider on the server host — use
the env vars or `providerOptions` there. the env vars or `providerOptions` there.
Sub-agent tokens are aggregated separately: `task`-tool subagents run in child sessions Sub-agent tokens are included in the same totals: `task`-tool subagents run in child sessions
(`session.parent_id`), so their usage is not in the current session's message list. The panel walks (`session.parent_id`), so their usage is not in the current session's message list. The panel walks
descendants with the SDK's `session.children` endpoint (bounded depth/breadth), reads each child's descendants with the SDK's `session.children` endpoint (bounded depth/breadth), reads each child's
aggregate tokens from the session store or falls back to summing its assistant messages, and shows aggregate tokens from the session store or falls back to summing its assistant messages, and adds
the total on the `sub:` line. The parent's own tokens are unchanged; `sub: none` means no descendant them to the combined `in` / `out` / `hit`. The parenthetical delta in `in` and `out` is sub-agent
sessions were found. usage alone; it is omitted when no descendant sessions were found.
## Quota tracking ## Quota tracking
@ -264,10 +266,10 @@ event that may never reach the TUI bus — all debounced) and when the active se
but never more than once every 2 minutes; every 5 minutes as a fallback but never more than once every 2 minutes; every 5 minutes as a fallback
(`COMMANDCODE_QUOTA_INTERVAL_MS` overrides the fallback interval — see (`COMMANDCODE_QUOTA_INTERVAL_MS` overrides the fallback interval — see
[Environment variables](#environment-variables)) and the [Environment variables](#environment-variables)) and the
countdown ticks every 30 seconds. The `sub:` line is refreshed on the same triggers (it is countdown ticks every 30 seconds. The token totals (including the sub-agent delta) are refreshed on
independent of quota rate-limiting). Key resolution and fetch failures are redacted and shown the same triggers (they are independent of quota rate-limiting). Key resolution and fetch failures
inline; the panel never stays on `loading…` and never blocks the provider. Extra trace lines are redacted and shown inline; the panel never stays on `loading…` and never blocks the provider.
(`tui-quota`) are appended to the debug log only when debug tracing is on. Extra trace lines (`tui-quota`) are appended to the debug log only when debug tracing is on.
Headless check (no TUI), reading the key from `COMMANDCODE_API_KEY` or the opencode config: Headless check (no TUI), reading the key from `COMMANDCODE_API_KEY` or the opencode config:
@ -300,7 +302,7 @@ The API key is never logged; quota errors pass through `redact()` like every oth
| Retry with backoff | Yes — 429/5xx and network errors, honouring `Retry-After`; also retryable `error` events that arrive inside an HTTP 200 stream before any content (gateway 520s) | | Retry with backoff | Yes — 429/5xx and network errors, honouring `Retry-After`; also retryable `error` events that arrive inside an HTTP 200 stream before any content (gateway 520s) |
| Credential redaction | Yes — error bodies are scrubbed before surfacing | | Credential redaction | Yes — error bodies are scrubbed before surfacing |
| Runtime toggles | Yes — `/cc-zdr` and `/cc-debug` flip the shared toggle file without a restart | | Runtime toggles | Yes — `/cc-zdr` and `/cc-debug` flip the shared toggle file without a restart |
| Sidebar status panel | Yes — a `sidebar_content` panel shows `zdr`/`debug`, session token totals (`in`/`out`/cache `hit`), a separate `sub:` line aggregating every descendant sub-agent session's tokens, and live quota | | Sidebar status panel | Yes — a `sidebar_content` panel shows `zdr`/`debug`, combined main + sub-agent token totals (`in`/`out` with a sub-agent-only delta, plus cache `hit`), and live quota |
| Quota tracking | Yes — 5-hour/weekly/monthly meters via `/cc-usage`, the sidebar, and `npm run quota` | | Quota tracking | Yes — 5-hour/weekly/monthly meters via `/cc-usage`, the sidebar, and `npm run quota` |
### `tool_choice` handling ### `tool_choice` handling

View File

@ -203,7 +203,7 @@ function resolveBaseURL(api: TuiApi): string | undefined {
return resolveRef(commandCodeOptions(api)?.["baseURL"]); return resolveRef(commandCodeOptions(api)?.["baseURL"]);
} }
type CacheSummary = { input: number; output: number; hit: number | undefined }; type CacheSummary = { input: number; output: number; hit: number | undefined; read: number };
type TokenTotals = { input: number; output: number; read: number; seen: number }; type TokenTotals = { input: number; output: number; read: number; seen: number };
@ -218,7 +218,12 @@ function addMessageTokens(totals: TokenTotals, tokens: TuiSessionTokens | undefi
function summarizeTotals(totals: TokenTotals): CacheSummary | undefined { function summarizeTotals(totals: TokenTotals): CacheSummary | undefined {
if (totals.seen === 0) return undefined; if (totals.seen === 0) return undefined;
return { input: totals.input, output: totals.output, hit: totals.input > 0 ? (totals.read / totals.input) * 100 : undefined }; return {
input: totals.input,
output: totals.output,
hit: totals.input > 0 ? (totals.read / totals.input) * 100 : undefined,
read: totals.read,
};
} }
/** /**
@ -312,16 +317,46 @@ async function collectFamily(api: TuiApi, rootID: string): Promise<CacheSummary
return summarizeTotals(totals); return summarizeTotals(totals);
} }
function formatCache(summary: CacheSummary | undefined): string { type TokenView = {
if (!summary) return "in: -- · out: -- · hit: --"; input: number;
const hit = summary.hit === undefined ? "--" : `${summary.hit.toFixed(1)}%`; output: number;
return `in: ${summary.input.toLocaleString()} · out: ${summary.output.toLocaleString()} · hit: ${hit}`; subInput: number;
subOutput: number;
hasSub: boolean;
hit: number | undefined;
empty: boolean;
};
function combineTokens(main: CacheSummary | undefined, sub: CacheSummary | undefined): TokenView {
const input = (main?.input ?? 0) + (sub?.input ?? 0);
const output = (main?.output ?? 0) + (sub?.output ?? 0);
const read = (main?.read ?? 0) + (sub?.read ?? 0);
return {
input,
output,
subInput: sub?.input ?? 0,
subOutput: sub?.output ?? 0,
hasSub: sub !== undefined,
hit: input > 0 ? (read / input) * 100 : undefined,
empty: main === undefined && sub === undefined,
};
} }
function formatFamily(summary: CacheSummary | undefined): string { function formatIn(view: TokenView): string {
if (!summary) return "sub: none"; if (view.empty) return "in: --";
const hit = summary.hit === undefined ? "--" : `${summary.hit.toFixed(1)}%`; const delta = view.hasSub ? ` (+${view.subInput.toLocaleString()})` : "";
return `sub: in: ${summary.input.toLocaleString()} · out: ${summary.output.toLocaleString()} · hit: ${hit}`; return `in: ${view.input.toLocaleString()}${delta}`;
}
function formatOut(view: TokenView): string {
if (view.empty) return "out: --";
const delta = view.hasSub ? ` (+${view.subOutput.toLocaleString()})` : "";
return `out: ${view.output.toLocaleString()}${delta}`;
}
function formatHit(view: TokenView): string {
if (view.empty || view.hit === undefined) return "hit: --";
return `hit: ${view.hit.toFixed(1)}%`;
} }
function quotaIntervalMs(): number { function quotaIntervalMs(): number {
@ -472,6 +507,7 @@ export const tui = async (api: TuiApi): Promise<void> => {
const Status = () => { const Status = () => {
const theme = api.theme; const theme = api.theme;
const view = () => combineTokens(sessionCacheSummary(api, sessionId()), family());
return ( return (
<box flexDirection="column" gap={0}> <box flexDirection="column" gap={0}>
<text fg={theme.current.text}> <text fg={theme.current.text}>
@ -480,8 +516,9 @@ export const tui = async (api: TuiApi): Promise<void> => {
<text fg={theme.current.textMuted}> <text fg={theme.current.textMuted}>
zdr:{state(toggles().zdr)} debug:{state(toggles().debug)} zdr:{state(toggles().zdr)} debug:{state(toggles().debug)}
</text> </text>
<text fg={theme.current.textMuted}>{formatCache(sessionCacheSummary(api, sessionId()))}</text> <text fg={theme.current.textMuted}>{formatIn(view())}</text>
<text fg={theme.current.textMuted}>{formatFamily(family())}</text> <text fg={theme.current.textMuted}>{formatOut(view())}</text>
<text fg={theme.current.textMuted}>{formatHit(view())}</text>
{windowsOf(quota()).map((w) => ( {windowsOf(quota()).map((w) => (
<text fg={tone(w, theme)}>{shortWindow(w, now())}</text> <text fg={tone(w, theme)}>{shortWindow(w, now())}</text>
))} ))}