From ea51a574c160e5c645cd54c19ea37a8477ec7198 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Mon, 16 Nov 2026 12:29:47 +0100 Subject: [PATCH] feat(status): render state as centered overlay Replace the /smart-compact notify() text with a ctx.ui.custom overlay panel (the /dcp context look): usage bar, threshold rows with crossed indicators, cycle flags, esc/enter/q/ctrl+c dismissal (keybindings-aware with a raw kitty/legacy fallback set), and notify() fallback for print/RPC mode. Hardened by a fresh-context reviewer fanout (ponytail/security/general): kitty explicit-modifier close forms added, render() now honors the requested width exactly with a degenerate-narrow fallback, label width simplified. Harness gains a ctx.ui.custom mock; 22 tests green. --- AGENTS.md | 5 +- README.md | 2 +- ...t-status-overlay-panel-fanout-audit_log.md | 62 +++++ docs/devlog/INDEX.md | 1 + harness.ts | 212 +++++++++++++++++- index.ts | 162 ++++++++++++- 6 files changed, 424 insertions(+), 20 deletions(-) create mode 100644 docs/devlog/20261116-smart-compact-status-overlay-panel-fanout-audit_log.md diff --git a/AGENTS.md b/AGENTS.md index 448011b..5a82982 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # GitNexus — Code Intelligence -This project is indexed by GitNexus as **smart-compact** (44 symbols, 65 relationships, 2 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **smart-compact** (107 symbols, 141 relationships, 2 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). @@ -59,5 +59,6 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-11-16 | [20261116-smart-compact-status-overlay-panel-fanout-audit_log.md](docs/devlog/20261116-smart-compact-status-overlay-panel-fanout-audit_log.md) | | 2026-11-15 | [20261115-reviewer-fanout-audit-hardening_log.md](docs/devlog/20261115-reviewer-fanout-audit-hardening_log.md) | - \ No newline at end of file + diff --git a/README.md b/README.md index 569ad7f..56a5432 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ Optional. `~/.pi/agent/settings.json` (global) or `.pi/settings.json` (project; ## Command -`/smart-compact` shows live state: current tokens, window, both effective thresholds (with crossed indicators), and cycle flags. Useful for checking what a given model's thresholds resolve to without filling a session. +`/smart-compact` opens a centered overlay panel (the `/dcp context` look): current tokens, a usage bar, both effective thresholds (with crossed indicators), and cycle flags. Dismiss it with esc, enter, q, or ctrl+c. Where overlays are unavailable (print/RPC mode) it falls back to a plain notification. Useful for checking what a given model's thresholds resolve to without filling a session. ## Install diff --git a/docs/devlog/20261116-smart-compact-status-overlay-panel-fanout-audit_log.md b/docs/devlog/20261116-smart-compact-status-overlay-panel-fanout-audit_log.md new file mode 100644 index 0000000..90461fc --- /dev/null +++ b/docs/devlog/20261116-smart-compact-status-overlay-panel-fanout-audit_log.md @@ -0,0 +1,62 @@ +# /smart-compact status overlay panel + reviewer-fanout audit + +> **Date:** 2026-11-16 +> **Type:** generic +> **Reference:** None + +## Goal + +Replace the `/smart-compact` status command's plain `notify()` output with a centered bordered overlay panel (the `/dcp context` look) — current tokens, usage bar, effective thresholds, cycle flags — then audit the session's diff with a fresh-context reviewer fanout (ponytail / security / general) and fix every accepted finding. + +## What Was Done + +- **Overlay panel** (`index.ts`): new `StatusRow` type, `CLOSE_KEYS` raw close-key set (legacy + Kitty CSI-u forms), and `showStatusPanel()` — a `ctx.ui.custom` component with a width-cached renderer (bordered box, dark 234-background slab, themed border, dim footer hint), `invalidate()` for theme changes, and `handleInput` close detection. Falls back to `notify()` where `ctx.ui.custom` is unavailable (print/RPC mode). +- **Command handler** (`index.ts`): rows with label alignment, threshold-colored usage bar (24 cells, only when window is known), warn/force thresholds with crossed indicators and warning/error colors, cycle flags. +- **Tests** (`harness.ts`): `ctx.ui.custom` mock in `makeCtx` (captures overlay options, instantiates component, resolves on `done()`); overlay-mode, bordered-width, close-keys (legacy + kitty), keybindings-remap preference, notify-fallback, and unknown-window tests. +- **Reviewer fanout** (workflow `43c1076a`, 3 fresh-context reviewers): security STRIDE clean; ponytail 1 finding; general 3 findings. All 4 accepted, 0 withdrawn, fixed in-session: + - Added Kitty explicit-modifier close forms `\x1b[13;1u` (enter) and `\x1b[113;1u` (q) to `CLOSE_KEYS` + close-key loop test. + - `render()` now honors the requested width exactly; widths < 6 (border+padding floor) degrade to plain truncated lines never wider than requested (was: `Math.max(20, width)` floor that violated the contract at narrow widths). + - `labelWidth` replaced `Math.max(...duplicated label list.map(...))` with `"warned this cycle".length` (longest label literal). + - New tests: *"overlay honors requested width, including degenerate narrow"* and *"render cache: same-width hit, width-change and invalidate rebuild"*. +- **README.md**: command section updated for overlay + fallback behavior. +- **GitNexus**: re-indexed after the changes (44 → 107 nodes, 141 edges). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Primary close detection via `keybindings.matches("tui.select.cancel"/"confirm")`, `CLOSE_KEYS` raw set as fallback | `matches()` protocol-normalizes every Kitty form and honors user remaps; raw set covers hosts without keybindings. Reviewer-confirmed gap (explicit-modifier forms) fixed by adding encodings, not a protocol parser — smallest fix. | +| Truncate/pad rows as plain text before theming | No ANSI-aware width math needed; panel content is single-width only. | +| Raw 256-color background (`\x1b[48;5;234m`) for the slab instead of a theme API | Reads as a distinct panel on every shipped theme; no theme dependency for the background. | +| Render cache keyed by width + `invalidate()` on theme change | Re-render is pure string assembly; cache avoids rebuild per frame, `invalidate()` rebuilds themed strings after theme switches. | +| Degenerate-width fallback (plain truncation below width 6) instead of a width floor | `render(width)` must never emit lines wider than requested; below the border floor a bordered layout is impossible, so degrade content, not the contract. | +| Kept fanout results despite wrong model pin | Reviewers ran on `openai-codex/gpt-6.1-sol` (from `pi model` output); user confirmed session model is `zai/glm-5.3` and chose to keep the results. Correction saved to persistent memory. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Reviewer children pinned to wrong model | `pi model` CLI reported `openai-codex/gpt-6.1-sol` while settings.json says `zai`/`glm-5.3` | Trust settings.json over `pi model` when pinning children; memory saved | +| Kitty `q`/`enter` with explicit modifier (`\x1b[113;1u`, `\x1b[13;1u`) didn't close | `CLOSE_KEYS` had `\x1b[27;1u` (esc) but not the enter/q modifier forms | Added both forms | +| `render(10)` emitted 20-wide lines | `Math.max(20, width)` floor overrode the requested width | Honor width exactly; < 6 → plain truncated lines | +| `showStatusPanel` missing from GitNexus impact analysis | Index predated the session's new symbols | `node .gitnexus/run.cjs analyze` (44 → 107 nodes) | + +## Files Changed + +| File | Change Summary | +|------|----------------| +| `index.ts` | Overlay panel (`StatusRow`, `CLOSE_KEYS`, `showStatusPanel`), status handler rows/usage bar, audit fixes | +| `harness.ts` | `ctx.ui.custom` mock; 6 overlay tests pre-audit + 2 audit tests (width contract, cache/invalidate) | +| `README.md` | Command section describes overlay + fallback | +| `docs/devlog/` | This log + INDEX.md row | +| `_code_review/` (untracked) | Materialized diffs + cumulative ledger for the fanout | + +## Open Items & Next Steps + +- [ ] Optional: verification fanout round on `zai/glm-5.3` (ledger at `_code_review/ledger.md` ready to paste as "already fixed") +- [ ] Decide whether `_code_review/` should be gitignored (currently untracked) +- [ ] No CHANGELOG.md exists in this repo — skipped per commit skill + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 0202eb7..c57e465 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,4 +5,5 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-11-16 | generic | [20261116-smart-compact-status-overlay-panel-fanout-audit_log.md](20261116-smart-compact-status-overlay-panel-fanout-audit_log.md) | Status overlay panel with usage bar; reviewer fanout fixed kitty close keys, width contract, label padding | | 2026-11-15 | generic | [20261115-reviewer-fanout-audit-hardening_log.md](20261115-reviewer-fanout-audit-hardening_log.md) | Reviewer fanout converged in 4 rounds: force tier moved to agent_settled, config validated, 15-test harness added | diff --git a/harness.ts b/harness.ts index babcbc5..76bdd57 100644 --- a/harness.ts +++ b/harness.ts @@ -51,13 +51,37 @@ function load(settings: Record) { } function makeCtx({ tokens, window, onCompact, idle = true }: CtxOverrides) { - const calls: { compact: number; notified: string[] } = { compact: 0, notified: [] }; + const calls: { + compact: number; + notified: string[]; + overlays: { overlay?: boolean; overlayOptions?: Record }[]; + components: any[]; + renders: number; + } = { compact: 0, notified: [], overlays: [], components: [], renders: 0 }; return { calls, ctx: { isIdle: () => idle, getContextUsage: () => ({ tokens, contextWindow: window }), - ui: { notify: (msg: string) => calls.notified.push(msg) }, + ui: { + notify: (msg: string) => calls.notified.push(msg), + // Minimal ctx.ui.custom: captures overlay options, instantiates the + // component, resolves the promise when done() fires. + custom: (factory: any, opts?: any) => { + calls.overlays.push(opts ?? {}); + return new Promise((resolve) => { + calls.components.push( + factory( + { requestRender: () => calls.renders++ }, + // Identity theme: styling is a no-op so assertions see plain text. + { fg: (_c: string, s: string) => s, bg: (_c: string, s: string) => s, bold: (s: string) => s }, + {}, + (result: unknown) => resolve(result), + ), + ); + }); + }, + }, compact: (opts: any) => { calls.compact++; (onCompact ?? ((o: any) => o?.onComplete?.({})))(opts); @@ -185,15 +209,189 @@ test("enabled: false registers nothing", () => { assert.equal(Object.keys(pi.commands).length, 0); }); -test("status command reports thresholds and crossed indicators", async () => { +test("status command opens a centered overlay panel with thresholds", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); + const pending = pi.commands["smart-compact"].handler(undefined, ctx); + await new Promise((r) => setImmediate(r)); // let the component factory run + assert.equal(calls.overlays.length, 1); + assert.equal(calls.overlays[0].overlay, true); + assert.deepEqual(calls.overlays[0].overlayOptions, { + width: "70%", + minWidth: 50, + maxHeight: "85%", + anchor: "center", + margin: 2, + }); + assert.equal(calls.notified.length, 0); // overlay mode, not notify + const comp = calls.components[0]; + const text = comp.render(80).join("\n"); + assert.match(text, /smart-compact status/); + assert.match(text, /tokens now\s+56k/); + assert.match(text, /window\s+100k/); + assert.match(text, /56% of window/); + assert.match(text, /warn threshold\s+55k \(crossed\)/); + assert.match(text, /force threshold\s+80k(?!\s*\(crossed\))/); + assert.match(text, /esc\/enter\/q to close/); + comp.handleInput("\x1b"); + await pending; // resolves once done() fires + assert.ok(calls.renders >= 1); +}); + +test("overlay renders a bordered box of constant line width", async () => { + const pi = load(FULL); + const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); + const pending = pi.commands["smart-compact"].handler(undefined, ctx); + await new Promise((r) => setImmediate(r)); + const stripAnsi = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, ""); + const lines = calls.components[0].render(80) as string[]; + assert.ok(lines.length >= 5); + for (const line of lines) { + assert.equal(stripAnsi(line).length, 80); // borders and padding align + } + assert.match(stripAnsi(lines[0]!), /^┌─+┐$/); + assert.match(stripAnsi(lines.at(-1)!), /^└─+┘$/); + calls.components[0].handleInput("\r"); + await pending; +}); + +test("overlay honors requested width, including degenerate narrow", async () => { + const pi = load(FULL); + const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); + const pending = pi.commands["smart-compact"].handler(undefined, ctx); + await new Promise((r) => setImmediate(r)); + const comp = calls.components[0]; + const stripAnsi = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, ""); + for (const line of comp.render(10) as string[]) { + assert.equal(stripAnsi(line).length, 10); // never exceeds the given width + } + const tiny = comp.render(4) as string[]; // below border floor: plain truncation + assert.ok(tiny.length >= 5); + for (const line of tiny) { + assert.ok(stripAnsi(line).length <= 4); + assert.ok(!line.includes("┌")); // no border glyphs at degenerate widths + } + comp.handleInput("\x1b"); + await pending; +}); + +test("render cache: same-width hit, width-change and invalidate rebuild", async () => { + const pi = load(FULL); + const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); + const pending = pi.commands["smart-compact"].handler(undefined, ctx); + await new Promise((r) => setImmediate(r)); + const comp = calls.components[0]; + const stripAnsi = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, ""); + const a = comp.render(80) as string[]; + assert.ok(comp.render(80) === a); // same width → cached instance + const c = comp.render(60) as string[]; // width change → rebuild at 60 + assert.notEqual(c, a); + assert.equal(stripAnsi(c[0]!).length, 60); + comp.invalidate(); // theme change → rebuild even at the same width + const d = comp.render(60) as string[]; + assert.notEqual(d, c); + comp.handleInput("\x1b"); + await pending; +}); + +test("overlay closes on esc, enter, q, ctrl+c (legacy and kitty forms) — not on other keys", async () => { + for (const key of ["\x1b", "\r", "\n", "q", "\x03", "\x1b[27u", "\x1b[27;1u", "\x1b[13u", "\x1b[13;1u", "\x1b[113u", "\x1b[113;1u", "\x1b[99;5u"]) { + const pi = load(FULL); + const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); + const pending = pi.commands["smart-compact"].handler(undefined, ctx); + await new Promise((r) => setImmediate(r)); + calls.components[0].handleInput(key); + await pending; // must resolve + } + const pi = load(FULL); + const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); + const pending = pi.commands["smart-compact"].handler(undefined, ctx); + await new Promise((r) => setImmediate(r)); + let closed = false; + void pending.then(() => { + closed = true; + }); + calls.components[0].handleInput("x"); + calls.components[0].handleInput("\x1b[A"); // arrow-up sequence ≠ bare esc + await new Promise((r) => setImmediate(r)); + assert.equal(closed, false); // still open + calls.components[0].handleInput("\x1b"); + await pending; +}); + +// Primary close path in the real TUI: keybindings.matches normalizes kitty +// CSI-u sequences and honors user-remapped cancel/confirm bindings. +test("overlay close prefers keybindings.matches (remapped bindings honored)", async () => { + const pi = load(FULL); + const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); + // Swap in a custom() mock whose keybindings only cancel on "ZZ". + (ctx.ui as any).custom = (factory: any, opts: any) => { + calls.overlays.push(opts ?? {}); + return new Promise((resolve) => { + calls.components.push( + factory( + { requestRender: () => calls.renders++ }, + { fg: (_c: string, s: string) => s, bg: (_c: string, s: string) => s, bold: (s: string) => s }, + { matches: (data: string, id: string) => id === "tui.select.cancel" && data === "ZZ" }, + (result: unknown) => resolve(result), + ), + ); + }); + }; + const pending = pi.commands["smart-compact"].handler(undefined, ctx); + await new Promise((r) => setImmediate(r)); + let closed = false; + void pending.then(() => { + closed = true; + }); + calls.components[0].handleInput("\x1b[27u"); // kitty esc — still closes via the CLOSE_KEYS fallback + await pending; + assert.equal(closed, true); + + // And the remapped binding closes too, even though "ZZ" is in no set. + const pi2 = load(FULL); + const { ctx: ctx2, calls: calls2 } = makeCtx({ tokens: 56_000, window: 100_000 }); + (ctx2.ui as any).custom = (factory: any, opts: any) => { + calls2.overlays.push(opts ?? {}); + return new Promise((resolve) => { + calls2.components.push( + factory( + { requestRender: () => calls2.renders++ }, + { fg: (_c: string, s: string) => s, bg: (_c: string, s: string) => s, bold: (s: string) => s }, + { matches: (data: string, id: string) => id === "tui.select.cancel" && data === "ZZ" }, + (result: unknown) => resolve(result), + ), + ); + }); + }; + const pending2 = pi2.commands["smart-compact"].handler(undefined, ctx2); + await new Promise((r) => setImmediate(r)); + calls2.components[0].handleInput("ZZ"); + await pending2; +}); + +test("status falls back to notify when overlay UI is unavailable", async () => { + const pi = load(FULL); + const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); + delete (ctx.ui as any).custom; await pi.commands["smart-compact"].handler(undefined, ctx); + assert.equal(calls.overlays.length, 0); const text = calls.notified.join("\n"); - assert.match(text, /smart-compact enabled/); - assert.match(text, /warn threshold:\s+55k \(crossed\)/); - assert.match(text, /force threshold:\s+80k/); - assert.doesNotMatch(text, /force threshold:.*crossed/); + assert.match(text, /smart-compact status/); + assert.match(text, /56k/); + assert.doesNotMatch(text, /to close/); // hint is overlay-mode only +}); + +test("usage bar hidden when window is unknown", async () => { + const pi = load(FULL); + const { ctx, calls } = makeCtx({ tokens: 56_000, window: 0 }); + const pending = pi.commands["smart-compact"].handler(undefined, ctx); + await new Promise((r) => setImmediate(r)); + const text = calls.components[0].render(80).join("\n"); + assert.match(text, /window\s+unknown/); + assert.doesNotMatch(text, /% of window/); + calls.components[0].handleInput("\x1b"); + await pending; }); test("force does not fire when settled reports not idle", async () => { diff --git a/index.ts b/index.ts index f1a061e..10bc8fd 100644 --- a/index.ts +++ b/index.ts @@ -98,6 +98,116 @@ function resolveConfig(): SmartCompactConfig { const FAILURE_COOLDOWN_MS = 60_000; +/** A panel row: plain text plus optional theme color name / bold title. */ +interface StatusRow { + text: string; + color?: string; + bold?: boolean; +} + +/** + * Raw input sequences that close the status overlay — legacy forms plus + * Kitty-protocol CSI-u forms. With the kitty keyboard protocol active (Pi + * enables it when the terminal supports it) ESC arrives as \x1b[27u, not a + * bare \x1b byte, which is why raw matching alone misses it. Primary close + * detection is keybindings.matches("tui.select.cancel"/"confirm"), which + * normalizes every form and honors user remaps; this set is the fallback + * when keybindings is unavailable. + */ +const CLOSE_KEYS = new Set([ + "\x1b", + "\r", + "\n", + "q", + "\x03", + "\x1b[27u", // escape (kitty) + "\x1b[27;1u", // escape, explicit modifier field (kitty) + "\x1b[13u", // enter (kitty) + "\x1b[13;1u", // enter, explicit modifier field (kitty) + "\x1b[113u", // q (kitty) + "\x1b[113;1u", // q, explicit modifier field (kitty) + "\x1b[99;5u", // ctrl+c (kitty) +]); + +/** + * Centered bordered overlay in the /dcp context style: dark slab, themed + * border, dim footer hint. Resolves when the user closes the panel + * (esc / enter / q / ctrl+c). Falls back to notify() where ctx.ui.custom + * is unavailable (print/RPC mode). + * + * Dependency-free on purpose: rows are truncated and padded as PLAIN text + * before theming, so no ANSI-aware width math is needed; panel content uses + * single-width characters only. + */ +async function showStatusPanel(ctx: any, title: string, rows: StatusRow[]): Promise { + const custom = ctx.ui?.custom; + if (typeof custom !== "function") { + ctx.ui?.notify?.([title, ...rows.map((r) => r.text)].join("\n"), "info"); + return; + } + await custom( + (tui: any, theme: any, keybindings: any, done: (result?: unknown) => void) => { + const lines: StatusRow[] = [ + { text: title, color: "accent", bold: true }, + { text: "" }, + ...rows, + { text: "" }, + { text: "esc/enter/q to close", color: "dim" }, + ]; + const border = (s: string) => theme.fg("borderAccent", s); + // Dark slab via raw 256-color ANSI (color 234); reads as a distinct + // panel on every shipped theme. \x1b[49m resets background only. + const bg = (s: string) => `\x1b[48;5;234m${s}\x1b[49m`; + let cached: string[] | undefined; + let cachedWidth = -1; + + return { + render(width: number): string[] { + const w = Math.max(1, width); + if (cached && cachedWidth === w) return cached; + // Degenerate narrow (below the border+padding floor): plain + // truncated lines, so the panel never exceeds the given width. + if (w < 6) { + const narrow = lines.map((row) => (row.text.length > w ? row.text.slice(0, w) : row.text)); + cachedWidth = w; + cached = narrow; + return narrow; + } + const innerWidth = w - 4; // 2 border glyphs + 2 padding spaces + const out: string[] = [bg(border(`┌${"─".repeat(w - 2)}┐`))]; + for (const row of lines) { + const text = row.text.length > innerWidth ? row.text.slice(0, innerWidth) : row.text; + const content = row.bold ? theme.bold(text) : text; + const styled = row.color ? theme.fg(row.color, content) : content; + const padSpaces = " ".repeat(Math.max(0, innerWidth - text.length)); + out.push(bg(`${border("│")} ${styled}${padSpaces} ${border("│")}`)); + } + out.push(bg(border(`└${"─".repeat(w - 2)}┘`))); + cachedWidth = w; + cached = out; + return out; + }, + invalidate(): void { + cached = undefined; // theme may have changed; rebuild themed strings + }, + handleInput(data: string): void { + const binding = (id: string) => keybindings?.matches?.(data, id) === true; + // cancel = escape/ctrl+c, confirm = enter (default bindings), + // protocol-normalized by pi-tui's parser inside keybindings.matches. + if (binding("tui.select.cancel") || binding("tui.select.confirm") || CLOSE_KEYS.has(data)) { + done(undefined); + tui.requestRender(); + } + }, + }; + }, + { + overlay: true, + overlayOptions: { width: "70%", minWidth: 50, maxHeight: "85%", anchor: "center", margin: 2 }, + }, + ); +} + export default function smartCompact(pi: any) { const cfg = resolveConfig(); if (!cfg.enabled) return; @@ -216,22 +326,54 @@ export default function smartCompact(pi: any) { }); // ── Debug/status command ───────────────────────────────────────── + // Shows a centered bordered overlay (the /dcp context look): current + // tokens, a usage bar, both effective thresholds, and cycle flags. + // Dismissed with esc / enter / q / ctrl+c; notify() remains the + // fallback where ctx.ui.custom is unavailable (print/RPC mode). pi.registerCommand?.("smart-compact", { description: "Show smart-compact thresholds and current state", handler: async (_args: string | undefined, ctx: any) => { const { tokens, window } = currentTokens(ctx); const warnAt = effective(cfg.warnTokens, cfg.warnFraction, window); const forceAt = effective(cfg.forceTokens, cfg.forceFraction, window); - const lines = [ - "smart-compact enabled", - ` tokens now: ${tokens === null ? "unknown" : `${Math.round(tokens / 1000)}k`}`, - ` window: ${window ? `${Math.round(window / 1000)}k` : "unknown"}`, - ` warn threshold: ${Math.round(warnAt / 1000)}k${tokens !== null && tokens >= warnAt ? " (crossed)" : ""}`, - ` force threshold: ${Math.round(forceAt / 1000)}k${tokens !== null && tokens >= forceAt ? " (crossed)" : ""}`, - ` warned this cycle: ${warnedThisCycle}`, - ` force in flight: ${forceInFlight}`, - ]; - ctx.ui?.notify?.(lines.join("\n"), "info"); + const fmt = (n: number): string => `${Math.round(n / 1000)}k`; + + const rows: StatusRow[] = []; + const add = (l: string, value: string, color?: string) => + rows.push({ text: `${l} ${value}`, color }); + // Longest label literal used below; keeps the value column aligned. + const labelWidth = "warned this cycle".length; + const pad = (l: string) => l.padEnd(labelWidth, " "); + + add(pad("tokens now"), tokens === null ? "unknown" : fmt(tokens)); + add(pad("window"), window ? fmt(window) : "unknown"); + + // Usage bar with threshold-colored fill, only when the ratio is known. + if (tokens !== null && window && window > 0) { + const cells = 24; + const ratio = Math.min(1, tokens / window); + const filled = Math.round(cells * ratio); + const barColor = tokens >= forceAt ? "error" : tokens >= warnAt ? "warning" : undefined; + rows.push({ + text: `${"█".repeat(filled)}${"░".repeat(cells - filled)} ${Math.round(ratio * 100)}% of window`, + color: barColor, + }); + } + + add( + pad("warn threshold"), + `${fmt(warnAt)}${tokens !== null && tokens >= warnAt ? " (crossed)" : ""}`, + tokens !== null && tokens >= warnAt ? "warning" : undefined, + ); + add( + pad("force threshold"), + `${fmt(forceAt)}${tokens !== null && tokens >= forceAt ? " (crossed)" : ""}`, + tokens !== null && tokens >= forceAt ? "error" : undefined, + ); + add(pad("warned this cycle"), String(warnedThisCycle)); + add(pad("force in flight"), String(forceInFlight)); + + await showStatusPanel(ctx, "smart-compact status", rows); }, }); }