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.
This commit is contained in:
1 parent
692c9c6c37
commit
ea51a574c1
6 files changed
+424
-20
No files matched your search
@@ -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<void> {
|
||||
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);
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user