Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(tui): frame every overlay as a docked panel, and stop the composer lying about the clipboard

Rach Pradhan4708db054593
diff --git a/TUI/app.zig b/TUI/app.zig
index 7205930c..55a16107 100644
--- a/TUI/app.zig
+++ b/TUI/app.zig
@@ -116,6 +116,12 @@ pub const Model = struct {
/// the drain that delivered it returns.
model_override: ?[]const u8 = null,
scroll: usize = 0,
+ /// An overlay body is a DOCUMENT, not a transcript: it opens at its FIRST
+ /// row and scrolls downward, where the transcript is pinned to its tail.
+ /// Kept apart from `scroll` on purpose — sharing the field meant paging
+ /// /help left the transcript underneath parked mid-history the moment the
+ /// overlay closed. Presentation state, reset whenever an overlay opens.
+ overlay_scroll: usize = 0,
selected: usize = 0,
turns: usize = 0,
/// The engine's last reported meters (#551). Null until a turn has run —
@@ -427,6 +433,7 @@ pub const Model = struct {
pub fn closeOverlay(self: *Model) void {
self.overlay = .none;
self.overlay_sel = 0;
+ self.overlay_scroll = 0;
self.preview_path = "";
self.preview_n = 0;
self.preview_pin = false;
@@ -439,6 +446,7 @@ pub const Model = struct {
pub fn openOverlay(self: *Model, which: Overlay) void {
self.overlay = which;
self.overlay_sel = 0;
+ self.overlay_scroll = 0;
if (self.overlay_filter.len > 0) {
self.alloc.free(self.overlay_filter);
self.overlay_filter = "";
diff --git a/TUI/chrome.zig b/TUI/chrome.zig
index 47a40b4e..16620085 100644
--- a/TUI/chrome.zig
+++ b/TUI/chrome.zig
@@ -6,6 +6,7 @@ const app = @import("app.zig");
const catalog = @import("catalog.zig");
const engine = @import("engine.zig");
const glyphs = @import("glyphs.zig");
+const panel = @import("panel.zig");
const theme_mod = @import("theme.zig");
const Model = app.Model;
@@ -30,10 +31,11 @@ pub fn promptBox(self: *const Model, a: std.mem.Allocator, width: usize) ![]cons
const focused = self.focus == .prompt and self.overlay == .none;
const border = if (focused) th.focus else th.border;
var out = std.array_list.Managed(u8).init(a);
- if (self.input.getValue().len == 0 and self.images.items.len == 0 and engine.g_paste_fn != null) {
- try out.appendSlice(try theme_mod.paint(a, th.muted, " Image in clipboard · ctrl+v to paste"));
- try out.append('\n');
- }
+ // No standing row above the composer. The one that used to sit here read
+ // "Image in clipboard · ctrl+v to paste" whenever a paste hook was wired at
+ // all — which is always — so it announced an image nobody had copied, on
+ // every idle frame, at the cost of a row. The affordance belongs with the
+ // other keys, in the footer hint (statusBar).
try out.appendSlice(border);
try out.appendSlice("╭");
var n: usize = 0;
@@ -122,33 +124,78 @@ fn footer(a: std.mem.Allocator, border: []const u8, muted: []const u8, label: []
pub fn statusBar(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {
const th = self.theme();
if (self.now_ms < self.toast_until_ms and self.toast.len > 0) {
- return theme_mod.paint(a, th.accent, self.toast);
+ return theme_mod.paint(a, th.accent, theme_mod.takeCols(try std.fmt.allocPrint(a, " {s}", .{self.toast}), fitWidth(width)));
}
if (self.pending != null or self.bg != null) {
- const raw = try std.fmt.allocPrint(a, "{s} Enter:queue · Shift+Tab:mode · Esc:cancel · {s}[stop]{s}", .{
- th.muted, th.error_fg, theme_mod.reset,
+ return hintLine(self, a, width, &.{
+ .{ .text = "Enter:queue" },
+ .{ .text = "Shift+Tab:mode" },
+ .{ .text = "Esc:cancel" },
+ .{ .text = "[stop]", .sgr = th.error_fg, .pin = true },
});
- return theme_mod.takeCols(raw, if (width == 0) 80 else width);
}
- return theme_mod.paint(a, th.muted, theme_mod.takeCols(" Enter:send · Shift+Enter:newline · Shift+Tab:mode", if (width == 0) 80 else width));
+ return hintLine(self, a, width, &.{
+ .{ .text = "Enter:send" },
+ .{ .text = "Shift+Enter:newline" },
+ .{ .text = "Shift+Tab:mode" },
+ .{ .text = "Ctrl+V:image", .want = engine.g_paste_fn != null },
+ .{ .text = "Ctrl+X:help" },
+ });
}
-pub fn overlay(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {
- return switch (self.overlay) {
- .none => "",
- .palette => try listOverlay(self, a, width),
- .theme => try themeOverlay(self, a),
- .help => try helpOverlay(self, a),
- .rewind => try std.fmt.allocPrint(a, "{s}{s}Rewind last turn?{s}\n{s}Enter rewind · Esc cancel{s}\n", .{ theme_mod.bold, self.theme().accent, theme_mod.reset, self.theme().muted, theme_mod.reset }),
- .debug => try debugOverlay(self, a),
- .model => try @import("models.zig").render(self, a),
- .effort => try @import("effort.zig").render(self, a),
- .settings => try settingsOverlay(self, a),
- .image => try @import("image.zig").render(self, a, width),
- .file => try @import("files.zig").render(self, a),
- .jump => try jumpOverlay(self, a),
- .slash => "",
- };
+fn fitWidth(width: usize) usize {
+ return if (width == 0) 80 else width;
+}
+
+const Hint = struct {
+ text: []const u8,
+ /// Defaults to the muted token at paint time — a hint is never the accent.
+ sgr: []const u8 = "",
+ /// Reserved before anything else is measured, and painted last: the stop
+ /// control is the one segment a narrow terminal may not drop.
+ pin: bool = false,
+ /// False leaves the segment out entirely (an affordance that is not wired).
+ want: bool = true,
+};
+
+const hint_sep = " · ";
+
+/// The footer hint, assembled from the segments that FIT.
+///
+/// grok-build's footer is one line that never wraps and never runs off the
+/// edge. graff's was a fixed string handed to takeCols, so an 44-column
+/// terminal read "Enter:send · Shift+Enter:newl" — a key name cut in half.
+/// Segments are whole or absent, dropped from the right, and a pinned one keeps
+/// its room reserved before the walk begins.
+fn hintLine(self: *const Model, a: std.mem.Allocator, width: usize, segs: []const Hint) ![]const u8 {
+ const th = self.theme();
+ const room = fitWidth(width);
+ var reserved: usize = 0;
+ for (segs) |s| {
+ if (s.pin and s.want) reserved += theme_mod.visibleLen(s.text) + theme_mod.visibleLen(hint_sep);
+ }
+ var out = std.array_list.Managed(u8).init(a);
+ try out.append(' ');
+ var used: usize = 1;
+ var any = false;
+ for (segs) |s| {
+ if (s.pin or !s.want) continue;
+ const cost = theme_mod.visibleLen(s.text) + (if (any) theme_mod.visibleLen(hint_sep) else 0);
+ if (used + cost + reserved > room) break;
+ if (any) try out.appendSlice(hint_sep);
+ try out.appendSlice(try theme_mod.paint(a, if (s.sgr.len > 0) s.sgr else th.muted, s.text));
+ used += cost;
+ any = true;
+ }
+ for (segs) |s| {
+ if (!s.pin or !s.want) continue;
+ if (any) try out.appendSlice(hint_sep);
+ try out.appendSlice(try theme_mod.paint(a, if (s.sgr.len > 0) s.sgr else th.muted, s.text));
+ any = true;
+ }
+ // The separators are painted outside any span, so the row would otherwise
+ // wear whatever pen the previous paint left on it.
+ return theme_mod.paint(a, th.muted, out.items);
}
pub fn slashMenu(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {
@@ -175,146 +222,17 @@ pub fn slashMenu(self: *const Model, a: std.mem.Allocator, width: usize) ![]cons
try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
try out.append('\n');
}
- return out.items;
-}
-
-fn listOverlay(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {
- const th = self.theme();
- var idx: [catalog.items.len]usize = undefined;
- const n = catalog.filter(self.input.getValue(), &idx);
- var out = std.array_list.Managed(u8).init(a);
- try out.appendSlice(try theme_mod.paint(a, th.accent, "Commands"));
- try out.append('\n');
- const show = @min(n, @as(usize, 12));
- if (show == 0) {
- try out.appendSlice(try theme_mod.paint(a, th.muted, "no matches\n"));
- return out.items;
- }
- const sel = self.overlay_sel % show;
- var i: usize = 0;
- while (i < show) : (i += 1) {
- const it = catalog.items[idx[i]];
- const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(i != sel));
- // Same rule as the inline menu: one entry, one row, cut to fit.
- const line = theme_mod.takeCols(try std.fmt.allocPrint(a, "{s}{s} {s}", .{ mark, it.name, it.desc }), width);
- try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
- try out.append('\n');
- }
- return out.items;
-}
-
-fn themeOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
- const th = self.theme();
- var out = std.array_list.Managed(u8).init(a);
- try out.appendSlice(try theme_mod.paint(a, th.accent, "Theme"));
- try out.append('\n');
- const sel = self.overlay_sel % theme_mod.all.len;
- for (theme_mod.all, 0..) |id, i| {
- const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(i != sel));
- const cur: []const u8 = if (id == self.theme_id) " (current)" else "";
- const line = try std.fmt.allocPrint(a, "{s}{s}{s}", .{ mark, id.label(), cur });
- try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
- try out.append('\n');
- }
- return out.items;
-}
-
-fn jumpOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
- const th = self.theme();
- var out = std.array_list.Managed(u8).init(a);
- try out.appendSlice(try theme_mod.paint(a, th.accent, "Jump to turn"));
- try out.appendSlice("\n\n");
- const total = self.userTurnCount();
- if (total == 0) {
- try out.appendSlice(try theme_mod.paint(a, th.muted, "no turns yet\n"));
- return out.items;
- }
- const sel = self.overlay_sel % total;
- var no: usize = 0;
- for (self.history.items) |e| {
- if (e.kind != .user) continue;
- const nl = std.mem.indexOfScalar(u8, e.text, '\n') orelse e.text.len;
- const clip = e.text[0..@min(nl, 60)];
- const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(no != sel));
- const line = try std.fmt.allocPrint(a, "{s}#{d} {s}", .{ mark, no + 1, clip });
- try out.appendSlice(if (no == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
- try out.append('\n');
- no += 1;
- }
- try out.append('\n');
- try out.appendSlice(try theme_mod.paint(a, th.muted, "↑↓ move · Enter jump · Esc"));
- try out.append('\n');
- return out.items;
-}
-
-fn helpOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
- return theme_mod.paint(a, self.theme().text,
- \\Shortcuts
- \\
- \\ Tab prompt / scrollback
- \\ Enter send
- \\ Esc cancel · 2× clear · 2× rewind
- \\ Ctrl+C cancel, then quit
- \\ Ctrl+X / F1 this overlay
- \\ Ctrl+P command palette
- \\ Shift+Tab Normal → Plan → Always-approve
- \\ click / ← → collapse / expand tools
- \\ hover [Image] preview · y copy · Enter open
- \\ Shift+← → prev / next user turn
- \\ Ctrl+J / K scroll one line
- \\ Ctrl+N N new session
- \\ Ctrl+Q quit
- \\ drag select transcript · copy on release
- \\ Shift+drag the terminal's own selection (any region)
- \\ Ctrl+Z undo composer
- \\ Cmd+Delete kill to start of line
- \\ Option+Delete kill previous word
- \\ wheel scroll transcript
- \\ PgUp / PgDn page transcript
- \\ cmd+v paste text
- \\ Ctrl+V attach clipboard image
- \\ Ctrl+R prompt history
- \\ / slash menu
- \\ @ fuzzy file mention
- \\ !cmd run a shell command
- \\
- \\Commands
- \\ /quit /exit /q leave the pager
- \\ /help this overlay
- \\ /new /clear fresh session
- \\ /home welcome screen
- \\ /model switch model (type to search)
- \\ /effort reasoning depth (type to filter)
- \\ /settings model · effort · mode · theme
- \\ /usage /cost live token/cost line
- \\ /debug observability HUD
- \\ /plan toggle plan mode
- \\ /always-approve skip permission prompts
- \\ /import-claude copy Claude and Cursor MCP + skills
- \\ /jump jump to a previous turn
- \\ /copy copy the last reply
- \\ /btw queue an aside mid-turn
- \\ /vim-mode vim keys in the scrollback
- );
-}
-
-test "help overlay names the advertised pager commands" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- m.openOverlay(.help);
- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena.deinit();
- const text = try overlay(&m, arena.allocator(), 80);
- for ([_][]const u8{
- "/quit", "/help", "/new", "/home", "/model", "/settings", "/usage", "/debug", "/plan", "/always-approve",
- "Shift+Tab", "PgUp", "PgDn",
- "←",
- "→",
- "Tab", "Enter", "Esc",
- }) |name| {
- try std.testing.expect(std.mem.indexOf(u8, text, name) != null);
- }
+ if (n > show) try out.appendSlice(try panel.windowRow(a, th, first, show, n));
+ // The same box the palette wears (overlaypane.zig). The completion menu and
+ // Ctrl+P show the SAME catalogue; before this one was a framed panel and
+ // the other bare text hanging over the transcript, which read as two
+ // unrelated features rather than one list reached two ways.
+ return panel.wrap(a, th, width, .{
+ .title = "Commands",
+ .note = try std.fmt.allocPrint(a, "{d}/{d}", .{ n, catalog.items.len }),
+ .footer = "↑↓ move · Enter run · Esc",
+ .body = out.items,
+ });
}
test "composer footer shows the live agent mode" {
@@ -352,84 +270,12 @@ test "status paints coral [stop] while a turn is pending" {
try std.testing.expect(std.mem.indexOf(u8, text, "Esc:cancel") != null);
}
-test "model overlay lists engine.g_models" {
- engine.g_models = "grok-4, gpt-5.5";
- engine.g_model_name = "grok-4";
- defer {
- engine.g_models = "";
- engine.g_model_name = "";
- }
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- m.openOverlay(.model);
- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena.deinit();
- const text = try overlay(&m, arena.allocator(), 80);
- try std.testing.expect(std.mem.indexOf(u8, text, "grok-4") != null);
- try std.testing.expect(std.mem.indexOf(u8, text, "gpt-5.5") != null);
- try std.testing.expect(std.mem.indexOf(u8, text, "Model ›") != null);
-}
-
-test "debug overlay is not the offline fallback when a hud is wired" {
- engine.g_hud_fn = struct {
- fn f(kind: engine.HudKind, buf: []u8) usize {
- _ = kind;
- const s = "observability graff.schema v1\n usage 1 api call(s)";
- const n = @min(s.len, buf.len);
- @memcpy(buf[0..n], s[0..n]);
- return n;
- }
- }.f;
- defer engine.g_hud_fn = null;
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- m.openOverlay(.debug);
- const text = try overlay(&m, std.testing.allocator, 80);
- defer std.testing.allocator.free(text);
- try std.testing.expect(std.mem.indexOf(u8, text, "offline") == null);
- try std.testing.expect(std.mem.indexOf(u8, text, "usage") != null);
- try std.testing.expect(std.mem.indexOf(u8, text, "overlay debug") != null);
- try std.testing.expect(std.mem.indexOf(u8, text, "prompt-origin") != null);
-}
-
pub const splitModels = @import("models.zig").splitModels;
-fn settingsOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
- const th = self.theme();
- var out = std.array_list.Managed(u8).init(a);
- try out.appendSlice(try theme_mod.paint(a, th.accent, "Settings"));
- try out.appendSlice("\n\n");
- const rows = [_][2][]const u8{
- .{ "Model", if (engine.g_model_name.len > 0) engine.g_model_name else "—" },
- .{ "Effort", @tagName(self.effort) },
- .{ "Mode", self.modeLabel() },
- .{ "Theme", self.theme_id.label() },
- };
- const sel = self.overlay_sel % rows.len;
- for (rows, 0..) |r, i| {
- const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(i != sel));
- const line = try std.fmt.allocPrint(a, "{s}{s:<10} {s}", .{ mark, r[0], r[1] });
- try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
- try out.append('\n');
- }
- try out.append('\n');
- try out.appendSlice(try theme_mod.paint(a, th.muted, "Enter change · type /model to search · Esc"));
- try out.append('\n');
- return out.items;
-}
-
-fn debugOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
- const th = self.theme();
- var buf: [2048]u8 = undefined;
- const body: []const u8 = if (engine.g_hud_fn) |f| buf[0..f(.debug, &buf)] else "observability (offline — no session sink)\n";
- var lbuf: [256]u8 = undefined;
- const lay = @import("dump.zig").layoutBuf(&lbuf, self);
- return std.fmt.allocPrint(a, "{s}{s}Observability{s}\n{s}{s}{s}\n{s}Esc close{s}\n", .{
- theme_mod.bold, th.text, theme_mod.reset, th.text, body, lay, th.muted, theme_mod.reset,
- });
-}
+/// The overlay bodies live in overlaypane.zig — they are the panel's business,
+/// not the composer's, and keeping both here put this file over its ceiling.
+/// Re-exported so the frame composer still has one door to the chrome.
+pub const overlay = @import("overlaypane.zig").overlay;
test "the composer footer holds its columns as the context meter ticks" {
// The footer label is CENTRED, so a share that widened from 9% to 10%
diff --git a/TUI/effort.zig b/TUI/effort.zig
index dbe9f79b..72a9d714 100644
--- a/TUI/effort.zig
+++ b/TUI/effort.zig
@@ -3,6 +3,7 @@
const std = @import("std");
const app = @import("app.zig");
const engine = @import("engine.zig");
+const panel = @import("panel.zig");
const theme_mod = @import("theme.zig");
const Model = app.Model;
@@ -38,18 +39,25 @@ pub fn pick(self: *const Model) ?engine.Effort {
return buf[self.overlay_sel % n];
}
+/// The panel's top-edge slots (overlaypane.zig places them).
+pub fn head(self: *const Model, a: std.mem.Allocator) !panel.Head {
+ var names: [all.len]engine.Effort = undefined;
+ return .{
+ .title = try std.fmt.allocPrint(a, "Effort › {s}\u{258B}", .{self.overlay_filter}),
+ .note = try std.fmt.allocPrint(a, "{d}/{d}", .{ filter(self.overlay_filter, &names), all.len }),
+ };
+}
+
+pub const hint = "type to filter · ↑↓ move · Enter pick · Esc";
+
+/// The ROWS only — the frame carries the rest.
pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
const th = self.theme();
var names: [all.len]engine.Effort = undefined;
const n = filter(self.overlay_filter, &names);
var out = std.array_list.Managed(u8).init(a);
- const q = self.overlay_filter;
- try out.appendSlice(try theme_mod.paint(a, th.accent, try std.fmt.allocPrint(a, "Effort › {s}▋", .{q})));
- try out.append('\n');
- try out.appendSlice(try theme_mod.paint(a, th.muted, try std.fmt.allocPrint(a, "{d}/{d}", .{ n, all.len })));
- try out.appendSlice("\n\n");
if (n == 0) {
- try out.appendSlice(try theme_mod.paint(a, th.muted, "no matches — Esc to close\n"));
+ try out.appendSlice(try theme_mod.paint(a, th.muted, " no matches\n"));
return out.items;
}
const sel = self.overlay_sel % n;
@@ -60,9 +68,6 @@ pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
try out.append('\n');
}
- try out.append('\n');
- try out.appendSlice(try theme_mod.paint(a, th.muted, "type to filter · ↑↓ move · Enter pick · Esc"));
- try out.append('\n');
return out.items;
}
@@ -83,7 +88,7 @@ test "effort overlay lists levels and marks current" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const text = try render(&m, arena.allocator());
- try std.testing.expect(std.mem.indexOf(u8, text, "Effort ›") != null);
+ try std.testing.expect(std.mem.indexOf(u8, (try head(&m, arena.allocator())).title, "Effort ›") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "low") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "high") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "(current)") != null);
diff --git a/TUI/files.zig b/TUI/files.zig
index e279a42a..4ee26a0b 100644
--- a/TUI/files.zig
+++ b/TUI/files.zig
@@ -4,6 +4,7 @@ const std = @import("std");
const app = @import("app.zig");
const models = @import("models.zig");
+const panel = @import("panel.zig");
const theme_mod = @import("theme.zig");
const Model = app.Model;
@@ -25,26 +26,35 @@ pub fn filterList(list: []const u8, query: []const u8, out: [][]const u8) usize
return n;
}
+/// The panel's top-edge slots (overlaypane.zig places them).
+pub fn head(self: *const Model, a: std.mem.Allocator) !panel.Head {
+ var names: [max_files][]const u8 = undefined;
+ const list = self.files_cache orelse "";
+ const total = filterList(list, "", &names);
+ const n = filterList(list, self.overlay_filter, &names);
+ return .{
+ .title = try std.fmt.allocPrint(a, "File › {s}\u{258B}", .{self.overlay_filter}),
+ .note = try std.fmt.allocPrint(a, "{d}/{d}", .{ n, total }),
+ };
+}
+
+pub const hint = "type to search · ↑↓ move · Enter insert · Esc";
+
+/// The ROWS only — the frame carries the rest.
pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
const th = self.theme();
var names: [max_files][]const u8 = undefined;
const list = self.files_cache orelse "";
- const total = filterList(list, "", &names);
const n = filterList(list, self.overlay_filter, &names);
var out = std.array_list.Managed(u8).init(a);
- const title = try std.fmt.allocPrint(a, "File › {s}▋", .{self.overlay_filter});
- try out.appendSlice(try theme_mod.paint(a, th.accent, title));
- try out.append('\n');
- try out.appendSlice(try theme_mod.paint(a, th.muted, try std.fmt.allocPrint(a, "{d}/{d}", .{ n, total })));
- try out.appendSlice("\n\n");
if (n == 0) {
- const hint = if (@import("bgop.zig").loadingFiles(self))
- "loading files…"
+ const why = if (@import("bgop.zig").loadingFiles(self))
+ " loading files…"
else if (list.len == 0)
- "no file list (offline?) — Esc"
+ " no file list (offline?)"
else
- "no matches — type to filter, Esc";
- try out.appendSlice(try theme_mod.paint(a, th.muted, hint));
+ " no matches — type to filter";
+ try out.appendSlice(try theme_mod.paint(a, th.muted, why));
try out.append('\n');
return out.items;
}
@@ -58,9 +68,7 @@ pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
try out.append('\n');
}
- try out.append('\n');
- try out.appendSlice(try theme_mod.paint(a, th.muted, "type to search · ↑↓ · Enter insert · Esc"));
- try out.append('\n');
+ if (n > vis) try out.appendSlice(try panel.windowRow(a, th, off, vis, n));
return out.items;
}
@@ -84,6 +92,7 @@ test "render shows the filtered file rows" {
const text = try render(&m, arena.allocator());
try std.testing.expect(std.mem.indexOf(u8, text, "src/a.zig") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "docs/b.md") != null);
- try std.testing.expect(std.mem.indexOf(u8, text, "File ›") != null);
- try std.testing.expect(std.mem.indexOf(u8, text, "2/2") != null);
+ const hd = try head(&m, arena.allocator());
+ try std.testing.expect(std.mem.indexOf(u8, hd.title, "File ›") != null);
+ try std.testing.expectEqualStrings("2/2", hd.note);
}
diff --git a/TUI/models.zig b/TUI/models.zig
index 59530bcb..23c2b865 100644
--- a/TUI/models.zig
+++ b/TUI/models.zig
@@ -4,6 +4,7 @@ const std = @import("std");
const app = @import("app.zig");
const engine = @import("engine.zig");
+const panel = @import("panel.zig");
const theme_mod = @import("theme.zig");
const Model = app.Model;
@@ -51,22 +52,30 @@ pub fn splitModels(list: []const u8, out: [][]const u8) usize {
return filterModels(list, "", out);
}
+/// What the panel's top edge says: the live filter, and how much of the
+/// catalogue survives it. The picker owns these strings; the frame only places
+/// them (overlaypane.zig).
+pub fn head(self: *const Model, a: std.mem.Allocator) !panel.Head {
+ var names: [max_models][]const u8 = undefined;
+ const total = splitModels(engine.g_models, &names);
+ const n = filterModels(engine.g_models, self.overlay_filter, &names);
+ return .{
+ .title = try std.fmt.allocPrint(a, "Model › {s}\u{258B}", .{self.overlay_filter}),
+ .note = try std.fmt.allocPrint(a, "{d}/{d}", .{ n, total }),
+ };
+}
+
+pub const hint = "type to search · ↑↓ move · Enter pick · Esc";
+
+/// The ROWS only. Title, tally and keys ride in the panel's edges.
pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
const th = self.theme();
var names: [max_models][]const u8 = undefined;
- const total = splitModels(engine.g_models, &names);
const n = filterModels(engine.g_models, self.overlay_filter, &names);
var out = std.array_list.Managed(u8).init(a);
- const q = self.overlay_filter;
- const title = try std.fmt.allocPrint(a, "Model › {s}▋", .{q});
- try out.appendSlice(try theme_mod.paint(a, th.accent, title));
- try out.append('\n');
- try out.appendSlice(try theme_mod.paint(a, th.muted, try std.fmt.allocPrint(a, "{d}/{d}", .{ n, total })));
- try out.appendSlice("\n\n");
-
if (n == 0) {
- try out.appendSlice(try theme_mod.paint(a, th.muted, "no matches — type to filter, Esc to close\n"));
+ try out.appendSlice(try theme_mod.paint(a, th.muted, " no matches — type to filter\n"));
return out.items;
}
@@ -82,9 +91,7 @@ pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
try out.append('\n');
}
- try out.append('\n');
- try out.appendSlice(try theme_mod.paint(a, th.muted, "type to search · ↑↓ move · Enter pick · Esc"));
- try out.append('\n');
+ if (n > vis) try out.appendSlice(try panel.windowRow(a, th, off, vis, n));
return out.items;
}
@@ -129,6 +136,7 @@ test "model overlay typed query is a filtered list, not the dump" {
const text = try render(&m, arena.allocator());
try std.testing.expect(std.mem.indexOf(u8, text, "deepseek-v4-pro") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "gpt-5.5") == null);
- try std.testing.expect(std.mem.indexOf(u8, text, "1/3") != null);
- try std.testing.expect(std.mem.indexOf(u8, text, "Model › deepseek") != null);
+ const hd = try head(&m, arena.allocator());
+ try std.testing.expectEqualStrings("1/3", hd.note);
+ try std.testing.expect(std.mem.indexOf(u8, hd.title, "Model › deepseek") != null);
}
diff --git a/TUI/overlaypane.zig b/TUI/overlaypane.zig
new file mode 100644
index 00000000..9386bcec
--- /dev/null
+++ b/TUI/overlaypane.zig
@@ -0,0 +1,407 @@
+//! Overlay bodies, and the panel each one is framed in.
+//!
+//! Split out of chrome.zig: the composer and the overlays had grown into one
+//! file over its ceiling, and they answer to different rules. chrome.zig owns
+//! the rows that are ALWAYS on screen; this file owns the ones that replace the
+//! transcript while they are open.
+//!
+//! Every overlay is the same shape — a name, a tally, some rows, the keys —
+//! and panel.zig turns that shape into grok-build's bordered box. Nothing here
+//! paints an edge itself, so a panel cannot drift surface by surface.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const catalog = @import("catalog.zig");
+const engine = @import("engine.zig");
+const glyphs = @import("glyphs.zig");
+const panel = @import("panel.zig");
+const theme_mod = @import("theme.zig");
+const Model = app.Model;
+
+/// Scroll hint for the bodies that are PROSE rather than a list. It rides in
+/// the TOP edge: those are the bodies long enough to overflow the viewport, and
+/// an overflowing panel has its bottom edge off the bottom of the screen.
+const scroll_note = "↑↓ scroll · Esc";
+
+pub fn overlay(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {
+ // The image card is a preview pinned above the composer, not a panel that
+ // replaces the transcript; it keeps its own shape (image.zig).
+ if (self.overlay == .none or self.overlay == .slash) return "";
+ if (self.overlay == .image) return @import("image.zig").render(self, a, width);
+ return panel.wrap(a, self.theme(), width, try spec(self, a));
+}
+
+fn spec(self: *const Model, a: std.mem.Allocator) !panel.Spec {
+ const th = self.theme();
+ return switch (self.overlay) {
+ .palette => blk: {
+ var idx: [catalog.items.len]usize = undefined;
+ break :blk .{
+ .title = "Commands",
+ .note = try tally(a, catalog.filter(self.input.getValue(), &idx), catalog.items.len),
+ .footer = "↑↓ move · Enter run · Esc",
+ .body = try listBody(self, a),
+ };
+ },
+ // No tally: a list that cannot be filtered has nothing to count down.
+ .theme => .{
+ .title = "Theme",
+ .footer = "↑↓ move · Enter apply · Esc",
+ .body = try themeBody(self, a),
+ },
+ .help => .{
+ .title = "Shortcuts",
+ .note = scroll_note,
+ .footer = "Esc close",
+ .body = try theme_mod.paint(a, th.text, help_body),
+ },
+ .rewind => .{
+ .title = "Rewind",
+ .footer = "Enter rewind · Esc cancel",
+ .body = try theme_mod.paint(a, th.text, " Undo the last turn?"),
+ },
+ .debug => .{
+ .title = "Observability",
+ .note = scroll_note,
+ .footer = "Esc close",
+ .body = try debugBody(self, a),
+ },
+ .model => blk: {
+ const models = @import("models.zig");
+ const head = try models.head(self, a);
+ break :blk .{ .title = head.title, .note = head.note, .footer = models.hint, .body = try models.render(self, a) };
+ },
+ .effort => blk: {
+ const effort = @import("effort.zig");
+ const head = try effort.head(self, a);
+ break :blk .{ .title = head.title, .note = head.note, .footer = effort.hint, .body = try effort.render(self, a) };
+ },
+ .file => blk: {
+ const files = @import("files.zig");
+ const head = try files.head(self, a);
+ break :blk .{ .title = head.title, .note = head.note, .footer = files.hint, .body = try files.render(self, a) };
+ },
+ .settings => .{
+ .title = "Settings",
+ .footer = "↑↓ move · Enter change · Esc",
+ .body = try settingsBody(self, a),
+ },
+ .jump => .{
+ .title = "Jump to turn",
+ .note = if (self.userTurnCount() == 0) "" else try std.fmt.allocPrint(a, "{d} turns", .{self.userTurnCount()}),
+ .footer = "↑↓ move · Enter jump · Esc",
+ .body = try jumpBody(self, a),
+ },
+ else => .{ .body = "" },
+ };
+}
+
+fn tally(a: std.mem.Allocator, n: usize, total: usize) ![]const u8 {
+ return std.fmt.allocPrint(a, "{d}/{d}", .{ n, total });
+}
+
+fn listBody(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+ const th = self.theme();
+ var idx: [catalog.items.len]usize = undefined;
+ const n = catalog.filter(self.input.getValue(), &idx);
+ var out = std.array_list.Managed(u8).init(a);
+ const show = @min(n, @as(usize, 12));
+ if (show == 0) {
+ try out.appendSlice(try theme_mod.paint(a, th.muted, " no matches"));
+ try out.append('\n');
+ return out.items;
+ }
+ const sel = self.overlay_sel % show;
+ var i: usize = 0;
+ while (i < show) : (i += 1) {
+ const it = catalog.items[idx[i]];
+ const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(i != sel));
+ // One menu entry is one ROW: a long description is CUT by the panel
+ // wall, never wrapped — wrapping would slide every entry below it off
+ // its own row.
+ const line = try std.fmt.allocPrint(a, "{s}{s} {s}", .{ mark, it.name, it.desc });
+ try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
+ try out.append('\n');
+ }
+ if (n > show) try out.appendSlice(try panel.windowRow(a, th, 0, show, n));
+ return out.items;
+}
+
+fn themeBody(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+ const th = self.theme();
+ var out = std.array_list.Managed(u8).init(a);
+ const sel = self.overlay_sel % theme_mod.all.len;
+ for (theme_mod.all, 0..) |id, i| {
+ const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(i != sel));
+ const cur: []const u8 = if (id == self.theme_id) " (current)" else "";
+ const line = try std.fmt.allocPrint(a, "{s}{s}{s}", .{ mark, id.label(), cur });
+ try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
+ try out.append('\n');
+ }
+ return out.items;
+}
+
+fn jumpBody(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+ const th = self.theme();
+ var out = std.array_list.Managed(u8).init(a);
+ const total = self.userTurnCount();
+ if (total == 0) {
+ try out.appendSlice(try theme_mod.paint(a, th.muted, " no turns yet"));
+ try out.append('\n');
+ return out.items;
+ }
+ const sel = self.overlay_sel % total;
+ var no: usize = 0;
+ for (self.history.items) |e| {
+ if (e.kind != .user) continue;
+ const nl = std.mem.indexOfScalar(u8, e.text, '\n') orelse e.text.len;
+ const clip = e.text[0..@min(nl, 60)];
+ const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(no != sel));
+ const line = try std.fmt.allocPrint(a, "{s}#{d} {s}", .{ mark, no + 1, clip });
+ try out.appendSlice(if (no == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
+ try out.append('\n');
+ no += 1;
+ }
+ return out.items;
+}
+
+fn settingsBody(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+ const th = self.theme();
+ var out = std.array_list.Managed(u8).init(a);
+ const rows = [_][2][]const u8{
+ .{ "Model", if (engine.g_model_name.len > 0) engine.g_model_name else "—" },
+ .{ "Effort", @tagName(self.effort) },
+ .{ "Mode", self.modeLabel() },
+ .{ "Theme", self.theme_id.label() },
+ };
+ const sel = self.overlay_sel % rows.len;
+ for (rows, 0..) |r, i| {
+ const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(i != sel));
+ const line = try std.fmt.allocPrint(a, "{s}{s:<10} {s}", .{ mark, r[0], r[1] });
+ try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
+ try out.append('\n');
+ }
+ return out.items;
+}
+
+fn debugBody(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+ const th = self.theme();
+ var buf: [2048]u8 = undefined;
+ const hud: []const u8 = if (engine.g_hud_fn) |f| buf[0..f(.debug, &buf)] else "observability (offline — no session sink)\n";
+ var lbuf: [256]u8 = undefined;
+ const lay = @import("dump.zig").layoutBuf(&lbuf, self);
+ const joined = try std.fmt.allocPrint(a, "{s}{s}", .{ hud, lay });
+ // The HUD is written for a bare pager and starts every section flush left.
+ // Inside a panel that puts the section headings hard against the wall while
+ // their own rows sit two columns in, so the block is inset to the two the
+ // picker rows already use and the whole overlay set shares one left margin.
+ var out = std.array_list.Managed(u8).init(a);
+ try out.appendSlice(th.text);
+ var it = std.mem.splitScalar(u8, joined, '\n');
+ while (it.next()) |ln| {
+ if (ln.len == 0 and it.rest().len == 0) break;
+ try out.appendSlice(" ");
+ try out.appendSlice(ln);
+ try out.append('\n');
+ }
+ return out.items;
+}
+
+/// The shortcut sheet. No leading heading of its own: the panel's top edge
+/// already says "Shortcuts", and a body that repeated it spent a row saying
+/// what the frame had said one line earlier.
+const help_body =
+ \\ Tab prompt / scrollback
+ \\ Enter send
+ \\ Esc cancel · 2× clear · 2× rewind
+ \\ Ctrl+C cancel, then quit
+ \\ Ctrl+X / F1 this overlay
+ \\ Ctrl+P command palette
+ \\ Shift+Tab Normal → Plan → Always-approve
+ \\ click / ← → collapse / expand tools
+ \\ hover [Image] preview · y copy · Enter open
+ \\ Shift+← → prev / next user turn
+ \\ Ctrl+J / K scroll one line
+ \\ Ctrl+N N new session
+ \\ Ctrl+Q quit
+ \\ drag select transcript · copy on release
+ \\ Shift+drag the terminal's own selection (any region)
+ \\ Ctrl+Z undo composer
+ \\ Cmd+Delete kill to start of line
+ \\ Option+Delete kill previous word
+ \\ wheel scroll transcript
+ \\ PgUp / PgDn page transcript
+ \\ cmd+v paste text
+ \\ Ctrl+V attach clipboard image
+ \\ Ctrl+R prompt history
+ \\ / slash menu
+ \\ @ fuzzy file mention
+ \\ !cmd run a shell command
+ \\
+ \\Commands
+ \\ /quit /exit /q leave the pager
+ \\ /help this overlay
+ \\ /new /clear fresh session
+ \\ /home welcome screen
+ \\ /model switch model (type to search)
+ \\ /effort reasoning depth (type to filter)
+ \\ /settings model · effort · mode · theme
+ \\ /usage /cost live token/cost line
+ \\ /debug observability HUD
+ \\ /plan toggle plan mode
+ \\ /always-approve skip permission prompts
+ \\ /import-claude copy Claude and Cursor MCP + skills
+ \\ /jump jump to a previous turn
+ \\ /copy copy the last reply
+ \\ /btw queue an aside mid-turn
+ \\ /vim-mode vim keys in the scrollback
+;
+
+const testing = std.testing;
+
+test "help overlay names the advertised pager commands" {
+ var m: Model = undefined;
+ m.setup(testing.allocator);
+ defer m.deinit();
+ m.openOverlay(.help);
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const text = try overlay(&m, arena.allocator(), 80);
+ for ([_][]const u8{
+ "/quit", "/help", "/new", "/home", "/model", "/settings", "/usage", "/debug", "/plan", "/always-approve",
+ "Shift+Tab", "PgUp", "PgDn",
+ "←",
+ "→",
+ "Tab", "Enter", "Esc",
+ }) |name| {
+ try testing.expect(std.mem.indexOf(u8, text, name) != null);
+ }
+ // The name is in the FRAME, and the body no longer repeats it.
+ try testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "Shortcuts"));
+}
+
+test "model overlay lists engine.g_models" {
+ engine.g_models = "grok-4, gpt-5.5";
+ engine.g_model_name = "grok-4";
+ defer {
+ engine.g_models = "";
+ engine.g_model_name = "";
+ }
+ var m: Model = undefined;
+ m.setup(testing.allocator);
+ defer m.deinit();
+ m.openOverlay(.model);
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const text = try overlay(&m, arena.allocator(), 80);
+ try testing.expect(std.mem.indexOf(u8, text, "grok-4") != null);
+ try testing.expect(std.mem.indexOf(u8, text, "gpt-5.5") != null);
+ try testing.expect(std.mem.indexOf(u8, text, "Model ›") != null);
+}
+
+test "debug overlay is not the offline fallback when a hud is wired" {
+ engine.g_hud_fn = struct {
+ fn f(kind: engine.HudKind, buf: []u8) usize {
+ _ = kind;
+ const s = "observability graff.schema v1\n usage 1 api call(s)";
+ const n = @min(s.len, buf.len);
+ @memcpy(buf[0..n], s[0..n]);
+ return n;
+ }
+ }.f;
+ defer engine.g_hud_fn = null;
+ var m: Model = undefined;
+ m.setup(testing.allocator);
+ defer m.deinit();
+ m.openOverlay(.debug);
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const text = try overlay(&m, arena.allocator(), 80);
+ try testing.expect(std.mem.indexOf(u8, text, "offline") == null);
+ try testing.expect(std.mem.indexOf(u8, text, "usage") != null);
+ try testing.expect(std.mem.indexOf(u8, text, "overlay debug") != null);
+ try testing.expect(std.mem.indexOf(u8, text, "prompt-origin") != null);
+}
+
+test "every overlay is a bordered panel with its name in the frame" {
+ // The audit this pass exists for: before it, an open picker was bare text
+ // floating on the pager with no edge anywhere, and each surface spelled its
+ // own title row. One panel builder means one look, and the check is that
+ // NONE of them opts out.
+ engine.g_models = "grok-4, gpt-5.5";
+ defer engine.g_models = "";
+ const cases = [_]struct { o: app.Overlay, name: []const u8 }{
+ .{ .o = .palette, .name = "Commands" },
+ .{ .o = .theme, .name = "Theme" },
+ .{ .o = .help, .name = "Shortcuts" },
+ .{ .o = .rewind, .name = "Rewind" },
+ .{ .o = .debug, .name = "Observability" },
+ .{ .o = .model, .name = "Model" },
+ .{ .o = .effort, .name = "Effort" },
+ .{ .o = .file, .name = "File" },
+ .{ .o = .settings, .name = "Settings" },
+ .{ .o = .jump, .name = "Jump to turn" },
+ };
+ for (cases) |c| {
+ for ([_]usize{ 40, 60, 80, 120 }) |w| {
+ var m: Model = undefined;
+ m.setup(testing.allocator);
+ defer m.deinit();
+ try m.push(.user, "a turn so the jump list has a row");
+ m.openOverlay(c.o);
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const text = try overlay(&m, arena.allocator(), w);
+ var it = std.mem.splitScalar(u8, text, '\n');
+ const top = it.next() orelse return error.EmptyPanel;
+ if (std.mem.indexOf(u8, top, "╭") == null) {
+ std.debug.print("{s} @ {d} has no top edge: {s}\n", .{ @tagName(c.o), w, top });
+ return error.NoPanelEdge;
+ }
+ try testing.expect(std.mem.indexOf(u8, top, c.name) != null);
+ // ...and the last row is the closing edge, with the keys on it.
+ var last: []const u8 = top;
+ while (it.next()) |ln| {
+ if (ln.len > 0) last = ln;
+ }
+ try testing.expect(std.mem.indexOf(u8, last, "╰") != null);
+ try testing.expect(std.mem.indexOf(u8, last, "Esc") != null);
+ // Every row is exactly the frame width — the painter's contract.
+ var rows = std.mem.splitScalar(u8, text, '\n');
+ while (rows.next()) |ln| {
+ if (ln.len == 0 and rows.rest().len == 0) break;
+ try testing.expectEqual(w, theme_mod.visibleLen(ln));
+ }
+ }
+ }
+}
+
+test "a windowed list says how much of itself is off-screen" {
+ // 75 models in a 14-row window used to show 14 rows and no hint at all
+ // that the other 61 existed.
+ var arena0 = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena0.deinit();
+ var buf = std.array_list.Managed(u8).init(arena0.allocator());
+ for (0..75) |i| {
+ if (i > 0) try buf.appendSlice(", ");
+ try buf.appendSlice(try std.fmt.allocPrint(arena0.allocator(), "model-{d}", .{i}));
+ }
+ engine.g_models = buf.items;
+ defer engine.g_models = "";
+ var m: Model = undefined;
+ m.setup(testing.allocator);
+ defer m.deinit();
+ m.openOverlay(.model);
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const text = try overlay(&m, arena.allocator(), 80);
+ try testing.expect(std.mem.indexOf(u8, text, "61 below") != null);
+ try testing.expect(std.mem.indexOf(u8, text, "0/75") == null);
+ try testing.expect(std.mem.indexOf(u8, text, "75/75") != null);
+ // Walked to the end of the list, the marker turns around instead of
+ // vanishing — the row is reserved either way, so nothing below it jumps.
+ m.overlay_sel = 74;
+ const tail = try overlay(&m, arena.allocator(), 80);
+ try testing.expect(std.mem.indexOf(u8, tail, "61 above") != null);
+}
diff --git a/TUI/overlays.zig b/TUI/overlays.zig
index 05fe22f6..d26f024b 100644
--- a/TUI/overlays.zig
+++ b/TUI/overlays.zig
@@ -13,12 +13,40 @@ const Key = @import("key.zig").Key;
const Model = app.Model;
const Effect = app.Effect;
+/// Overlays whose body is a SHEET rather than a list: there is no highlight to
+/// move, so the arrows and the page keys scroll the body instead. keys.zig
+/// routes every key here before it reaches its own page handling, so without
+/// this a /help taller than the terminal had no way at all to show its second
+/// half — the arrows only walked an `overlay_sel` nothing rendered.
+fn scrolls(o: app.Overlay) bool {
+ return o == .help or o == .debug;
+}
+
+fn page(self: *const Model) usize {
+ const h = self.last_term_height;
+ return @max(if (h > 8) h - 6 else 3, 3);
+}
+
+/// One step of the sheet, clamped to its end by the frame composer (render.zig
+/// knows the row count; this does not).
+fn scrollSheet(self: *Model, k: Key) bool {
+ switch (k) {
+ .up => self.overlay_scroll -|= 3,
+ .down => self.overlay_scroll += 3,
+ .page_up => self.overlay_scroll -|= page(self),
+ .page_down => self.overlay_scroll += page(self),
+ else => return false,
+ }
+ return true;
+}
+
pub fn key(self: *Model, k: Key) Effect {
if (@import("image.zig").key(self, k)) return .stay;
if (k == .escape) {
self.closeOverlay();
return .stay;
}
+ if (scrolls(self.overlay) and scrollSheet(self, k)) return .stay;
if (k == .up) {
self.overlay_sel -|= 1;
return .stay;
@@ -52,7 +80,10 @@ pub fn wheel(self: *Model, up: bool) bool {
// The image card is a preview above the composer, not a list; it keeps its
// own key handling and the transcript keeps the wheel.
if (self.overlay != .none and self.overlay != .image) {
- if (up) self.overlay_sel -|= 1 else self.overlay_sel += 1;
+ // A sheet scrolls; only a LIST has a highlight for a notch to move.
+ if (scrolls(self.overlay)) {
+ if (up) self.overlay_scroll -|= 1 else self.overlay_scroll += 1;
+ } else if (up) self.overlay_sel -|= 1 else self.overlay_sel += 1;
return true;
}
const v = self.input.getValue();
diff --git a/TUI/panel.zig b/TUI/panel.zig
new file mode 100644
index 00000000..3fafd1dd
--- /dev/null
+++ b/TUI/panel.zig
@@ -0,0 +1,343 @@
+//! The bordered panel every overlay body sits inside.
+//!
+//! grok-build draws an overlay as a PANEL: a box whose TOP edge carries the
+//! name of the thing and whose BOTTOM edge carries the keys, so chrome and
+//! content never compete for a row. graff's overlays used to be bare text
+//! floating on the pager — the same rows, but with no edge telling the eye
+//! where the list stopped and the transcript resumed, and with the title
+//! spending a whole content row to say one word.
+//!
+//! The panel reuses the composer's own walls (╭ ─ ╮ │ ╰ ╯) at the same inset,
+//! so an open picker and the box under it read as one frame rather than two
+//! unrelated widgets.
+//!
+//! LAW: every row is EXACTLY `width` columns, corner to corner. The painter
+//! addresses screen row N as the Nth line of the composed frame (render.zig);
+//! a row that measured wider would be chopped by the terminal — or, on a
+//! terminal that ignores ?7l, wrapped — and every row below it would slide out
+//! from under the row-to-line map that clicks, the sticky header and the
+//! selection band all ride on.
+//!
+//! The two edge slots are not interchangeable. Anything the user must still be
+//! able to read when the body OVERFLOWS the viewport goes in the top edge: a
+//! panel taller than the screen has its bottom edge cut off, so a scroll hint
+//! parked down there would be visible only when it was not needed.
+
+const std = @import("std");
+
+const theme_mod = @import("theme.zig");
+const Theme = theme_mod.Theme;
+
+/// Below this the box is more chrome than content — two walls, two corner
+/// dashes and a title would leave nothing for the rows — so the body is
+/// returned unframed instead of being squeezed.
+pub const min_width: usize = 16;
+
+pub const Spec = struct {
+ /// Named in the TOP edge.
+ title: []const u8 = "",
+ /// Right-hand slot of the TOP edge: a tally, a window position, a scroll
+ /// hint. Top, never bottom — see the module note.
+ note: []const u8 = "",
+ /// Left-hand slot of the BOTTOM edge: what the keys do.
+ footer: []const u8 = "",
+ /// Body rows, newline-separated, already carrying their own SGR.
+ body: []const u8 = "",
+};
+
+/// The two TOP-edge slots a picker fills in: what it is, and how much of it
+/// the reader is looking at.
+pub const Head = struct { title: []const u8, note: []const u8 };
+
+/// The one row a WINDOWED list owes the reader: how much of it is off-screen.
+/// Present for as long as the list overflows its window and never for a moment
+/// less — a marker that came and went as the highlight moved would make every
+/// row above it jump a line on an arrow key.
+pub fn windowRow(a: std.mem.Allocator, th: Theme, off: usize, vis: usize, n: usize) ![]const u8 {
+ const below = n -| (off + vis);
+ const text = if (off > 0 and below > 0)
+ try std.fmt.allocPrint(a, " \u{2026} {d} above · {d} below", .{ off, below })
+ else if (off > 0)
+ try std.fmt.allocPrint(a, " \u{2026} {d} above", .{off})
+ else
+ try std.fmt.allocPrint(a, " \u{2026} {d} below", .{below});
+ return theme_mod.paint(a, th.muted, text);
+}
+
+/// `spec` as a box exactly `width` columns wide, newline-terminated.
+pub fn wrap(a: std.mem.Allocator, th: Theme, width: usize, spec: Spec) ![]const u8 {
+ if (width < min_width) return a.dupe(u8, spec.body);
+ var out = std.array_list.Managed(u8).init(a);
+ // Bold accent title, muted note. grok-build's modal draws the same pair on
+ // its top border: the dashes take the border colour and the title itself
+ // stays bold, so the name reads as a label ON the frame rather than a row
+ // of content that happens to be first.
+ const title_sgr = try std.fmt.allocPrint(a, "{s}{s}", .{ theme_mod.bold, th.accent });
+ try out.appendSlice(try edge(a, th, width, "╭", "╮", spec.title, title_sgr, spec.note, th.muted));
+ try out.append('\n');
+ // A body may paint MANY rows with one SGR prefix — the help block is one
+ // string in one colour — and the painter repaints rows independently, so a
+ // continuation row that carries no SGR of its own renders in whatever the
+ // previous paint left behind. Same rule, and the same tracker, as the
+ // wrappers in theme.zig: remember the pen and re-open it on every row.
+ var active: theme_mod.Sgr = .{};
+ var sgr_buf: [theme_mod.Sgr.max_render]u8 = undefined;
+ var it = std.mem.splitScalar(u8, spec.body, '\n');
+ while (it.next()) |ln| {
+ // A body built with an append('\n') after every row ends in an empty
+ // segment. Framing it would open a blank row above the footer that no
+ // caller asked for.
+ if (ln.len == 0 and it.rest().len == 0) break;
+ try out.appendSlice(try row(a, th, width, ln, active.render(&sgr_buf)));
+ try out.append('\n');
+ noteAll(&active, ln);
+ }
+ try out.appendSlice(try edge(a, th, width, "╰", "╯", spec.footer, th.muted, "", th.muted));
+ try out.append('\n');
+ // Owned, not `items`: an ArrayList's buffer is longer than what it holds,
+ // and a caller freeing the returned slice must be handed an allocation
+ // whose length is the one the allocator recorded.
+ return out.toOwnedSlice();
+}
+
+/// One body row: a wall, the text clipped and padded to the inner width, a
+/// wall. The pad is measured with visibleLen, so a wide glyph moves the right
+/// wall by the two cells it actually draws and never by the bytes it occupies.
+fn row(a: std.mem.Allocator, th: Theme, width: usize, text: []const u8, carry: []const u8) ![]const u8 {
+ const inner = width - 2;
+ const shown = theme_mod.takeCols(text, inner);
+ var out = std.array_list.Managed(u8).init(a);
+ try out.appendSlice(th.border);
+ try out.appendSlice("│");
+ try out.appendSlice(theme_mod.reset);
+ try out.appendSlice(carry);
+ try out.appendSlice(shown);
+ try out.appendSlice(theme_mod.reset);
+ const cols = theme_mod.visibleLen(shown);
+ if (cols < inner) try out.appendNTimes(' ', inner - cols);
+ try out.appendSlice(th.border);
+ try out.appendSlice("│");
+ try out.appendSlice(theme_mod.reset);
+ return out.items;
+}
+
+/// One horizontal edge, corner to corner, with the label and note inlaid.
+///
+/// Both slots degrade rather than overflow, in the order that keeps the panel
+/// legible: the note goes first (it is a tally), then the label is clipped, and
+/// a width with room for neither draws a plain rule. Nothing here may return a
+/// row that is not exactly `width` columns.
+fn edge(
+ a: std.mem.Allocator,
+ th: Theme,
+ width: usize,
+ left: []const u8,
+ right: []const u8,
+ label_in: []const u8,
+ label_sgr: []const u8,
+ note_in: []const u8,
+ note_sgr: []const u8,
+) ![]const u8 {
+ const inner = width - 2;
+ var out = std.array_list.Managed(u8).init(a);
+ try out.appendSlice(th.border);
+ try out.appendSlice(left);
+ if (inner < 2) {
+ try dashes(&out, inner);
+ try out.appendSlice(right);
+ try out.appendSlice(theme_mod.reset);
+ return out.items;
+ }
+ // One dash hugs each corner, so a label never touches the corner glyph.
+ const budget = inner - 2;
+ var label = label_in;
+ var note = note_in;
+ var label_cols = slotCols(label);
+ var note_cols = slotCols(note);
+ if (label_cols + note_cols > budget) {
+ note = "";
+ note_cols = 0;
+ }
+ if (label_cols > budget) {
+ label = fitLabel(label, budget);
+ label_cols = slotCols(label);
+ }
+ const fill = budget - label_cols - note_cols;
+ try dashes(&out, 1);
+ if (label_cols > 0) try slot(&out, th, label, label_sgr);
+ try dashes(&out, fill);
+ if (note_cols > 0) try slot(&out, th, note, note_sgr);
+ try dashes(&out, 1);
+ try out.appendSlice(right);
+ try out.appendSlice(theme_mod.reset);
+ return out.items;
+}
+
+/// A label too wide for its edge, made to fit.
+///
+/// Hints are a "·"-joined list, ordered least-urgent first: "type to search ·
+/// ↑↓ move · Enter pick · Esc". Clipping such a line from the RIGHT is exactly
+/// backwards — a 40-column terminal kept "type to search · ↑↓ move · Enter pi"
+/// and threw away the one key that closes the panel. Whole segments come off
+/// the FRONT instead, so the last thing to survive is the last thing named.
+fn fitLabel(label_in: []const u8, budget: usize) []const u8 {
+ var label = label_in;
+ while (slotCols(label) > budget) {
+ const cut = std.mem.indexOf(u8, label, " · ") orelse break;
+ label = label[cut + " · ".len ..];
+ }
+ // A single segment that still will not fit is clipped, as a title is.
+ return if (slotCols(label) > budget) theme_mod.takeCols(label, budget -| 2) else label;
+}
+
+/// Columns a slot spends: the text plus the space either side of it. An empty
+/// slot spends nothing at all — not even its spaces.
+fn slotCols(s: []const u8) usize {
+ return if (s.len == 0) 0 else theme_mod.visibleLen(s) + 2;
+}
+
+fn slot(out: *std.array_list.Managed(u8), th: Theme, text: []const u8, sgr: []const u8) !void {
+ try out.append(' ');
+ try out.appendSlice(sgr);
+ try out.appendSlice(text);
+ try out.appendSlice(theme_mod.reset);
+ try out.appendSlice(th.border);
+ try out.append(' ');
+}
+
+/// Fold every escape in `s` into the tracker — the whole line, not the clipped
+/// part: a colour set past the right wall still governs the row after it.
+fn noteAll(active: *theme_mod.Sgr, s: []const u8) void {
+ var i: usize = 0;
+ while (i < s.len) : (i += 1) {
+ if (s[i] != 0x1b) continue;
+ const end = theme_mod.skipEsc(s, i);
+ active.note(s[i..end]);
+ i = end - 1;
+ }
+}
+
+fn dashes(out: *std.array_list.Managed(u8), n: usize) !void {
+ var i: usize = 0;
+ while (i < n) : (i += 1) try out.appendSlice("─");
+}
+
+const testing = std.testing;
+
+test "every row of a panel is exactly `width` columns" {
+ // The painter contract, at the one place a box can break it. Titles and
+ // notes long enough to need every degrade step are in the table on purpose.
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const th = theme_mod.of(.night);
+ const specs = [_]Spec{
+ .{ .title = "Model", .note = "3/75", .footer = "↑↓ move · Enter pick · Esc", .body = "› one\n two\n" },
+ .{ .title = "", .note = "", .footer = "", .body = "bare\n" },
+ .{ .title = "a title far too long to fit any narrow terminal edge at all", .note = "999/999", .footer = "and a footer hint that is itself much too long to sit in the bottom rule", .body = "x\n" },
+ .{ .title = "Model › 日本語のフィルタ▋", .note = "0/75", .footer = "Esc", .body = " 🚀 wide glyph row that runs long enough to be clipped by the wall\n" },
+ .{ .title = "T", .note = "N", .footer = "F", .body = "" },
+ };
+ for (specs) |spec| {
+ for ([_]usize{ 16, 17, 20, 24, 40, 41, 60, 80, 120, 200 }) |w| {
+ const box = try wrap(a, th, w, spec);
+ var it = std.mem.splitScalar(u8, box, '\n');
+ var n: usize = 0;
+ while (it.next()) |ln| {
+ if (ln.len == 0 and it.rest().len == 0) break;
+ try testing.expectEqual(w, theme_mod.visibleLen(ln));
+ n += 1;
+ }
+ try testing.expect(n >= 2); // two edges, always
+ }
+ }
+}
+
+test "the title rides in the top edge and the footer in the bottom one" {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const box = try wrap(arena.allocator(), theme_mod.of(.night), 60, .{
+ .title = "Commands",
+ .note = "4/12",
+ .footer = "Enter run · Esc",
+ .body = "› /new\n /home\n",
+ });
+ var it = std.mem.splitScalar(u8, box, '\n');
+ const top = it.next().?;
+ try testing.expect(std.mem.indexOf(u8, top, "╭") != null);
+ try testing.expect(std.mem.indexOf(u8, top, "Commands") != null);
+ try testing.expect(std.mem.indexOf(u8, top, "4/12") != null);
+ // The note sits to the RIGHT of the title, never before it.
+ try testing.expect(std.mem.indexOf(u8, top, "Commands").? < std.mem.indexOf(u8, top, "4/12").?);
+ const r1 = it.next().?;
+ try testing.expect(std.mem.indexOf(u8, r1, "│") != null);
+ try testing.expect(std.mem.indexOf(u8, r1, "/new") != null);
+ _ = it.next().?;
+ const bottom = it.next().?;
+ try testing.expect(std.mem.indexOf(u8, bottom, "╰") != null);
+ try testing.expect(std.mem.indexOf(u8, bottom, "Enter run · Esc") != null);
+ try testing.expect(std.mem.indexOf(u8, bottom, "╯") != null);
+ // Three body rows would mean the body's trailing newline opened a blank one.
+ try testing.expectEqual(@as(usize, 4), std.mem.count(u8, box, "\n"));
+}
+
+test "a narrow edge drops the note before it clips the title" {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const th = theme_mod.of(.night);
+ // 24 columns: the title, its two spaces, the two corner dashes and the two
+ // corners come to exactly 22, so the tally has nowhere to go — and the
+ // title, which names the panel, survives whole.
+ const box = try wrap(a, th, 24, .{ .title = "Reasoning effort", .note = "6/6", .body = "x\n" });
+ const top = box[0..std.mem.indexOfScalar(u8, box, '\n').?];
+ try testing.expect(std.mem.indexOf(u8, top, "Reasoning effort") != null);
+ try testing.expect(std.mem.indexOf(u8, top, "6/6") == null);
+ try testing.expectEqual(@as(usize, 24), theme_mod.visibleLen(top));
+}
+
+test "a hint too wide for the edge loses its first segment, never its last" {
+ // "Esc" is what gets you out. Right-clipping dropped it and kept "type to
+ // sea"; segment-dropping keeps the keys and loses the prose.
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const th = theme_mod.of(.night);
+ const long = "type to search · ↑↓ move · Enter pick · Esc";
+ for ([_]usize{ 24, 32, 40, 48 }) |w| {
+ const box = try wrap(a, th, w, .{ .title = "Model", .footer = long, .body = "x\n" });
+ var it = std.mem.splitScalar(u8, box, '\n');
+ var last: []const u8 = "";
+ while (it.next()) |ln| {
+ if (ln.len > 0) last = ln;
+ }
+ try testing.expect(std.mem.indexOf(u8, last, "Esc") != null);
+ try testing.expectEqual(w, theme_mod.visibleLen(last));
+ }
+ // Wide enough and the whole hint is there.
+ const wide = try wrap(a, th, 80, .{ .title = "Model", .footer = long, .body = "x\n" });
+ try testing.expect(std.mem.indexOf(u8, wide, "type to search") != null);
+}
+
+test "below min_width the body comes back unframed" {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const got = try wrap(arena.allocator(), theme_mod.of(.night), 10, .{ .title = "X", .body = "row\n" });
+ try testing.expectEqualStrings("row\n", got);
+}
+
+test "panel colours come from the theme, never from a literal" {
+ // Every panel byte that is not content is a border token or a reset. A raw
+ // SGR literal here would survive a theme switch and paint grok-night walls
+ // on the day palette.
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ for (theme_mod.all) |id| {
+ const th = theme_mod.of(id);
+ const box = try wrap(a, th, 40, .{ .title = "T", .note = "N", .footer = "F", .body = "r\n" });
+ try testing.expect(std.mem.indexOf(u8, box, th.border) != null);
+ try testing.expect(std.mem.indexOf(u8, box, th.accent) != null);
+ try testing.expect(std.mem.indexOf(u8, box, th.muted) != null);
+ }
+}
diff --git a/TUI/render.zig b/TUI/render.zig
index c895fcd7..6d6ce3ce 100644
--- a/TUI/render.zig
+++ b/TUI/render.zig
@@ -124,23 +124,43 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
if (n <= view_h) {
self.scroll = 0;
self.mid_skip = 0;
+ // An overlay panel DOCKS to the composer, the way the slash menu does
+ // and grok-build's minimal pickers do: the list rises out of the box
+ // you are typing in. Top-anchored it floated at the ceiling with a
+ // field of blank rows between the thing being chosen and the caret
+ // choosing it. The transcript keeps its own habit, top-down.
+ const above: usize = if (overlay_body) view_h - n else 0;
+ var lead = above;
+ while (lead > 0) : (lead -= 1) try out.append('\n');
for (try midSlice(a, cache, mid_lines.items, 0, n)) |ln| {
try out.appendSlice(ln);
try out.append('\n');
}
- var pad: usize = view_h - n;
+ var pad: usize = view_h - n - above;
while (pad > 0) : (pad -= 1) try out.append('\n');
+ self.mid_origin += above;
} else {
const max_scroll = n - view_h;
- if (self.follow) self.scroll = 0;
- // Put the anchored logical line back on the top row. Saturating: when
- // the rewrap pushed it past the last possible top line the viewport
- // parks at the bottom, which still shows it.
- if (rewrap) |anc| {
- if (cache) |c| self.scroll = max_scroll -| anchor.rowAt(self, c, anc);
+ // An overlay body reads TOP-DOWN. The transcript is pinned to its tail
+ // because the newest line is the one you want; a shortcut sheet is a
+ // document, and opening one at its last row showed the tail of /help
+ // and nothing else. Its own cursor, so closing the overlay leaves the
+ // transcript's viewport where it was.
+ var start: usize = undefined;
+ if (overlay_body) {
+ if (self.overlay_scroll > max_scroll) self.overlay_scroll = max_scroll;
+ start = self.overlay_scroll;
+ } else {
+ if (self.follow) self.scroll = 0;
+ // Put the anchored logical line back on the top row. Saturating:
+ // when the rewrap pushed it past the last possible top line the
+ // viewport parks at the bottom, which still shows it.
+ if (rewrap) |anc| {
+ if (cache) |c| self.scroll = max_scroll -| anchor.rowAt(self, c, anc);
+ }
+ if (self.scroll > max_scroll) self.scroll = max_scroll;
+ start = max_scroll - self.scroll;
}
- if (self.scroll > max_scroll) self.scroll = max_scroll;
- const start = max_scroll - self.scroll;
self.mid_skip = start;
// grok sticky header (minimal single slot): once the last user prompt
// scrolls past the viewport top, its first line stays pinned as row 0
@@ -419,8 +439,11 @@ test "visible dump of a fixture frame shows chips, the fold header, composer, no
try std.testing.expect(std.mem.indexOf(u8, lay, "images") != null);
m.openOverlay(.debug);
- const dbg = try chrome.overlay(&m, std.testing.allocator, 80);
- defer std.testing.allocator.free(dbg);
+ // The overlay body is built from many small pieces now that it is framed
+ // (panel.zig), so it wants the arena every other chrome builder gets.
+ var oarena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer oarena.deinit();
+ const dbg = try chrome.overlay(&m, oarena.allocator(), 80);
const lay_dbg = try dump_mod.layout(std.testing.allocator, &m);
defer std.testing.allocator.free(lay_dbg);
try std.testing.expect(std.mem.indexOf(u8, lay_dbg, "overlay debug") != null);
@@ -448,8 +471,9 @@ test "debug overlay keeps the observability HUD and adds layout" {
const frame = try render(&m, std.testing.allocator, 80, 24, 0);
defer std.testing.allocator.free(frame);
m.openOverlay(.debug);
- const text = try chrome.overlay(&m, std.testing.allocator, 80);
- defer std.testing.allocator.free(text);
+ var oarena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer oarena.deinit();
+ const text = try chrome.overlay(&m, oarena.allocator(), 80);
try std.testing.expect(std.mem.indexOf(u8, text, "Observability") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "offline") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "overlay debug") != null);
diff --git a/TUI/root.zig b/TUI/root.zig
index 205af871..6321b720 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -73,6 +73,8 @@ test {
_ = @import("scrollbar.zig");
_ = @import("scrollbar_tests.zig");
_ = @import("chrome.zig");
+ _ = @import("panel.zig");
+ _ = @import("overlaypane.zig");
_ = @import("models.zig");
_ = @import("markdown.zig");
_ = @import("markdown_stream_tests.zig");
diff --git a/TUI/scrollback.zig b/TUI/scrollback.zig
index 013125ce..1ff50f68 100644
--- a/TUI/scrollback.zig
+++ b/TUI/scrollback.zig
@@ -247,11 +247,14 @@ pub fn row(self: *const Model, a: std.mem.Allocator, user_no: u32, e: app.Entry,
}
if (e.kind == .pending) {
const line = try std.fmt.allocPrint(a, "{s}{s}{s}{s}{s} {s}{s}", .{ sel, th.accent, thinkingGlyph(now_ms), theme_mod.reset, th.muted, body, theme_mod.reset });
- return theme_mod.wrapToWidth(a, line, width);
+ return theme_mod.wrapPreferWords(a, line, width);
}
const body_fg = if (e.kind == .err) th.error_fg else th.text;
const line = try std.fmt.allocPrint(a, "{s}{s}{s}{s}{s} {s}{s}", .{ sel, color, mark, theme_mod.reset, body_fg, body, theme_mod.reset });
- return theme_mod.wrapToWidth(a, line, width);
+ // Break on a SPACE where there is one: a system row is prose nothing
+ // pre-wrapped, and at 60 columns the usage line split "$0.0000" into
+ // "$0.0" and "000" — a different number on each row.
+ return theme_mod.wrapPreferWords(a, line, width);
}
fn userNo(self: *const Model, idx: usize) u32 {
diff --git a/TUI/scrollback_tests.zig b/TUI/scrollback_tests.zig
index 4351ecec..57d5a6eb 100644
--- a/TUI/scrollback_tests.zig
+++ b/TUI/scrollback_tests.zig
@@ -219,3 +219,27 @@ test "end to end: a wrapped diff keeps its band and bleeds onto nothing (#diff)"
try std.testing.expect(del_rows > 1); // the deletion really did fold
try std.testing.expectEqual(del_rows - 1, folds); // every fold is marked
}
+
+test "a long system row breaks on a space, never through a token" {
+ // The /usage line at 60 columns: hard wrapping cut "$0.0000" in half, so
+ // the transcript showed "$0.0" with "000" on the row below it.
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.push(.system, "3 api call(s) · 300 in (0 cached) + 30 out tokens · $0.0000 · 3 subscription call(s), flat-rate");
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ for ([_]usize{ 40, 52, 60, 72 }) |w| {
+ const rows = try scrollback.render(&m, arena.allocator(), w, 0);
+ var it = std.mem.splitScalar(u8, rows, '\n');
+ var n: usize = 0;
+ while (it.next()) |ln| : (n += 1) {
+ try std.testing.expect(theme_mod.visibleLen(ln) <= w);
+ // No row may END in the middle of the amount, and none may open
+ // with the tail of one.
+ try std.testing.expect(!std.mem.endsWith(u8, std.mem.trimEnd(u8, ln, " "), "$0.0"));
+ }
+ try std.testing.expect(std.mem.indexOf(u8, rows, "$0.0000") != null);
+ try std.testing.expect(n > 1); // it really did wrap
+ }
+}
diff --git a/TUI/sim.zig b/TUI/sim.zig
index 664e2602..7e2ca307 100644
--- a/TUI/sim.zig
+++ b/TUI/sim.zig
@@ -264,7 +264,17 @@ test "type /help then enter opens the help overlay" {
try std.testing.expectEqual(app.Overlay.help, term.model.overlay);
const vis = try term.screen();
defer std.testing.allocator.free(vis);
- try std.testing.expect(std.mem.indexOf(u8, vis, "/quit") != null);
+ // A sheet opens at its FIRST row — it used to open at its last, so the
+ // only part of /help you ever saw was the tail of the command list.
+ try std.testing.expect(std.mem.indexOf(u8, vis, "Shortcuts") != null);
+ try std.testing.expect(std.mem.indexOf(u8, vis, "Tab prompt / scrollback") != null);
+ try std.testing.expect(std.mem.indexOf(u8, vis, "/quit") == null);
+ // ...and paging it reaches the rest.
+ var i: usize = 0;
+ while (i < 4) : (i += 1) _ = term.feed("\x1b[6~");
+ const paged = try term.screen();
+ defer std.testing.allocator.free(paged);
+ try std.testing.expect(std.mem.indexOf(u8, paged, "/quit") != null);
}
test "hoverText on an image chip opens the preview" {
diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.sh
index 593e130c..9552ae5e 100644
--- a/scripts/eval-tier1.sh
+++ b/scripts/eval-tier1.sh
@@ -326,6 +326,15 @@ if wanted tuiguard; then
if python3 scripts/test-tui-scrollbar-osc52.py zig-out/bin/graff; then :; else
record_fail tuiguard
fi
+ # Every overlay is a bordered panel with its name in the top rule, docked to
+ # the composer, opened at its FIRST row; and the composer no longer claims a
+ # clipboard image on every idle frame. Border cells and the gap between the
+ # panel and the input box are geometry a unit test cannot see. Each of the
+ # four checks is verified: unframing the panel, undocking it, opening a
+ # sheet at its tail, or restoring the clipboard row each fails its own.
+ if python3 scripts/test-tui-overlay-panels.py zig-out/bin/graff; then :; else
+ record_fail tuiguard
+ fi
fi
fi
diff --git a/scripts/test-tui-overlay-panels.py b/scripts/test-tui-overlay-panels.py
new file mode 100755
index 00000000..38640f2d
--- /dev/null
+++ b/scripts/test-tui-overlay-panels.py
@@ -0,0 +1,240 @@
+#!/usr/bin/env python3
+"""Every overlay is a bordered panel, docked to the composer, opened at its top.
+
+grok-build renders a modal as a BLOCK with borders on all four sides and the
+title inlaid in the top rule (`─ <bold title> ─`, dashes in the border colour),
+with the keys on a dim footer row; its minimal-mode list panels dock to the
+prompt instead of floating mid-screen. graff's overlays used to be bare text
+hanging at the top of the pager with a field of blank rows between the list and
+the caret choosing from it, and a title that spent a content row.
+
+This drives the REAL binary on a virtual screen (scripts/ptyharness.py) and
+reads back what a terminal would show, at three widths, for four surfaces:
+
+ 1. /model — a windowed list: framed, tallied in the top rule, docked one
+ row above the composer, and honest about the rows it is not
+ showing ("… N below").
+ 2. / — the completion menu wears the SAME frame as the palette it
+ mirrors, so one catalogue reached two ways looks like one
+ thing.
+ 3. /help — a sheet taller than the screen OPENS AT ITS FIRST ROW (it used
+ to open at its last: the only part you ever saw was the tail of
+ the command list) and pages down to the rest.
+ 4. composer — the standing row that claimed "Image in clipboard" on every
+ idle frame is gone, and the paste key lives in the footer hint
+ with the other keys.
+
+Every panel row is checked against the frame width in CELLS, which is the one
+thing a raw-byte grep cannot do: a border that measured one column wide would
+be chopped by the terminal and slide every row below it.
+
+Usage: python3 scripts/test-tui-overlay-panels.py [path/to/graff]
+Exit 0 = pass. Skips (exit 0, notice) when the binary is absent or there is no
+pty here.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import tempfile
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+from ptyharness import PtyHarness, PtyTimeout # noqa: E402
+
+BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")
+ROWS = 30
+WIDTHS = (60, 80, 120)
+
+TL, TR, BL, BR = "╭", "╮", "╰", "╯"
+WALL = "│"
+
+
+def workspace(tmp: str) -> dict:
+ empty = os.path.join(tmp, "empty-mcp.json")
+ with open(empty, "w", encoding="utf-8") as fh:
+ fh.write('{"mcpServers": {}}')
+ harness = os.path.join(tmp, ".harness")
+ os.makedirs(harness, exist_ok=True)
+ with open(os.path.join(harness, "settings.json"), "w", encoding="utf-8") as fh:
+ json.dump({"ai_title": False, "skills": {"codedbpro": False}}, fh)
+ return {
+ "HOME": tmp,
+ "GRAFF_MCP_CONFIG": empty,
+ "GRAFF_LEARN_AUTO": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ "GRAFF_FLEET": "off",
+ # No request is ever made: the probe only opens overlays. A key is what
+ # gets the pager past its "no API key" refusal.
+ "XAI_API_KEY": "xai-overlay-panel-probe",
+ }
+
+
+def cells(pty, y: int) -> str:
+ return pty.screen_lines()[y].rstrip("\n")
+
+
+def panel_rows(pty, cols: int):
+ """(top, bottom) screen rows of the LAST panel above the composer, or None.
+
+ The composer is a box too, so the search runs upward from the composer's own
+ top edge and takes the first complete frame above it.
+ """
+ lines = pty.screen_lines()
+ tops = [y for y, ln in enumerate(lines) if ln.lstrip().startswith(TL)]
+ bots = [y for y, ln in enumerate(lines) if ln.lstrip().startswith(BL)]
+ if len(tops) < 2 or len(bots) < 2:
+ return None
+ # The composer is the last pair; the overlay panel is the one before it.
+ return tops[-2], bots[-2]
+
+
+def check_frame(pty, top: int, bot: int, cols: int, what: str):
+ """Every row of the box spans exactly `cols` cells and has both walls."""
+ problems = []
+ head = cells(pty, top)
+ tail = cells(pty, bot)
+ if not head.startswith(TL) or not head.rstrip().endswith(TR):
+ problems.append(f"{what}: top rule is not a closed edge: {head!r}")
+ if not tail.startswith(BL) or not tail.rstrip().endswith(BR):
+ problems.append(f"{what}: bottom rule is not a closed edge: {tail!r}")
+ for y in range(top, bot + 1):
+ row = cells(pty, y)
+ # The harness grid is exactly `cols` wide; a row that ends before the
+ # last column means the frame did not reach the wall.
+ painted = len(row.rstrip())
+ if painted != cols:
+ problems.append(f"{what}: row {y} paints {painted} of {cols} cells: {row!r}")
+ if top < y < bot and not (row.startswith(WALL) and row[cols - 1] == WALL):
+ problems.append(f"{what}: row {y} is missing a wall: {row!r}")
+ return problems
+
+
+def clear(pty):
+ pty.inject_keys(b"\x1b")
+ pty.pump(0.3)
+ pty.inject_keys(b"\x1b")
+ pty.pump(0.3)
+ for _ in range(80):
+ pty.inject_keys(b"\x7f")
+ pty.pump(0.4)
+
+
+def run_width(cols: int) -> list[str]:
+ bad: list[str] = []
+ with tempfile.TemporaryDirectory(prefix="graff-overlay-panel-") as tmp:
+ env = workspace(tmp)
+ argv = [BIN, "tui", "--yolo", "--no-telemetry"]
+ with PtyHarness(argv, cols=cols, rows=ROWS, cwd=tmp, env=env) as pty:
+ if not pty.wait_for_boot():
+ return [f"w={cols}: the TUI never took the alt screen"]
+
+ # 1. the model picker ------------------------------------------
+ pty.inject_keys(b"/model\r")
+ try:
+ pty.wait_for_text("Model", timeout=8.0)
+ except PtyTimeout as exc:
+ return [f"w={cols}: /model never opened: {exc}"]
+ pty.pump(0.5)
+ found = panel_rows(pty, cols)
+ if found is None:
+ bad.append(f"w={cols}: /model drew no bordered panel at all")
+ else:
+ top, bot = found
+ bad += check_frame(pty, top, bot, cols, f"w={cols} /model")
+ head = cells(pty, top)
+ if "Model" not in head:
+ bad.append(f"w={cols}: the panel's top rule does not name it: {head!r}")
+ tail = cells(pty, bot)
+ if "Esc" not in tail:
+ bad.append(f"w={cols}: the panel's bottom rule lost its keys: {tail!r}")
+ # DOCKED: the panel's bottom rule sits directly on the composer.
+ composer_top = None
+ for y in range(bot + 1, ROWS):
+ if cells(pty, y).startswith(TL):
+ composer_top = y
+ break
+ if composer_top != bot + 1:
+ bad.append(
+ f"w={cols}: the picker floats — its last row is {bot}, "
+ f"the composer starts at {composer_top}"
+ )
+ # WINDOWED: 14 rows of a longer list must say so.
+ body = "\n".join(cells(pty, y) for y in range(top, bot + 1))
+ if "below" not in body and "above" not in body:
+ bad.append(f"w={cols}: a windowed list gave no more-below marker")
+ clear(pty)
+
+ # 2. the completion menu wears the same frame -------------------
+ pty.inject_keys(b"/")
+ pty.pump(0.6)
+ found = panel_rows(pty, cols)
+ if found is None:
+ bad.append(f"w={cols}: the slash menu drew no bordered panel")
+ else:
+ top, bot = found
+ bad += check_frame(pty, top, bot, cols, f"w={cols} slash")
+ if "Commands" not in cells(pty, top):
+ bad.append(f"w={cols}: the slash menu's rule does not name it")
+ clear(pty)
+
+ # 3. a sheet opens at its FIRST row -----------------------------
+ pty.inject_keys(b"\x18") # Ctrl+X
+ try:
+ pty.wait_for_text("Shortcuts", timeout=8.0)
+ except PtyTimeout as exc:
+ return bad + [f"w={cols}: /help never opened: {exc}"]
+ pty.pump(0.4)
+ screen = pty.screen_contents()
+ if "prompt / scrollback" not in screen:
+ bad.append(f"w={cols}: the shortcut sheet did not open at its first row")
+ if "/vim-mode" in screen:
+ bad.append(f"w={cols}: the shortcut sheet opened at its LAST row")
+ pty.inject_keys(b"\x1b[6~" * 4) # PgDn
+ pty.pump(0.6)
+ if "/vim-mode" not in pty.screen_contents():
+ bad.append(f"w={cols}: paging the shortcut sheet never reached its end")
+ clear(pty)
+
+ # 4. the composer tells no story about a clipboard it never read
+ pty.pump(0.4)
+ screen = pty.screen_contents()
+ if "Image in clipboard" in screen:
+ bad.append(f"w={cols}: the composer still claims an image is in the clipboard")
+ if cols >= 80 and "Ctrl+V:image" not in screen:
+ bad.append(f"w={cols}: the paste key is not in the footer hint")
+ # ...and the hint never runs off the edge or ends mid-word.
+ hint = cells(pty, ROWS - 1)
+ if len(hint.rstrip()) > cols:
+ bad.append(f"w={cols}: the footer hint overruns the screen: {hint!r}")
+ for cut in ("Shift+Enter:newl", "Shift+Tab:mo", "Ctrl+V:im"):
+ if cut in hint and not hint.rstrip().endswith(("mode", "image", "help", "newline")):
+ bad.append(f"w={cols}: the footer hint is clipped mid-key: {hint!r}")
+ pty.quit()
+ return bad
+
+
+def main() -> int:
+ if not os.path.exists(BIN):
+ print(f"notice: {BIN} not built — skipping")
+ return 0
+ try:
+ import pty as _pty # noqa: F401
+ except Exception:
+ print("notice: no pty support here — skipping")
+ return 0
+ problems: list[str] = []
+ for cols in WIDTHS:
+ problems += run_width(cols)
+ if problems:
+ for p in problems:
+ print(f"FAIL {p}")
+ return 1
+ print(f"ok: overlay panels are framed, docked and top-opened at {WIDTHS}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())