Skip to content

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

Python

feat(tui): make clickable rows look clickable — hover tint, chevron, double click

Rach Pradhan8ef069043a68
diff --git a/TUI/app.zig b/TUI/app.zig
index 5fab4d09..306b40a9 100644
--- a/TUI/app.zig
+++ b/TUI/app.zig
@@ -144,6 +144,10 @@ pub const Model = struct {
preview_rows: usize = 0,
/// Drag-selection band over the composed frame (#529) — presentation only.
sel: @import("selection.zig").Sel = .{},
+ /// Row under the pointer and the double-click window (hover.zig). Screen
+ /// state: which row is hovered is never an engine fact, and the affordance
+ /// it paints is derived from the typed entries the Model already holds.
+ hover: @import("hover.zig").State = .{},
/// Wrapped-line layout of the transcript, keyed by width/theme/fold/entry
/// identity (layout_cache.zig). Presentation state: a pure memo of what the
/// row builders would produce, so scrolling is a slice and not a re-layout.
diff --git a/TUI/glyphs.zig b/TUI/glyphs.zig
index 5f770900..e7d11b92 100644
--- a/TUI/glyphs.zig
+++ b/TUI/glyphs.zig
@@ -105,6 +105,10 @@ pub fn frame(anim: []const []const u8, i: usize) []const u8 {
// ── static ──────────────────────────────────────────────────────────────────
pub const caret = "\u{203A}"; // composer prompt
+/// Swapped in for `tool` on a COLLAPSED row under the pointer (hover.zig).
+/// Same codepoint as `caret` on purpose — one chevron means "this opens" —
+/// but named for its own role so the two call sites cannot drift.
+pub const expand = "\u{203A}";
pub const prompt_mark = "\u{276F}"; // sticky header
pub const assistant = "\u{25CF}";
pub const tool = "\u{25C6}";
diff --git a/TUI/hover.zig b/TUI/hover.zig
new file mode 100644
index 00000000..3651149b
--- /dev/null
+++ b/TUI/hover.zig
@@ -0,0 +1,240 @@
+//! Hover affordance: make a clickable row LOOK clickable before the click.
+//!
+//! ?1003h (any-event tracking) is already on for the image-chip preview, so
+//! the pointer's position reaches keys.mouseKey as a mouse report with button
+//! 35 on every motion. Until now every one of those that did not land on an
+//! image chip was DROPPED — the TUI knew where the pointer was and said
+//! nothing. This is the other half: the row under the pointer is looked up in
+//! the same map a click uses, and if it is a target it is painted with a
+//! background one step off the canvas and, when it is a collapsed group, with
+//! its leading mark swapped for the chevron that announces expandability.
+//!
+//! ONE HIT TEST. `hitTest` is the single answer to "what is on screen row y",
+//! and keys.mouseKey routes its click through the same function. Hover and
+//! click cannot disagree about what is clickable, because there is only one
+//! opinion in the codebase.
+//!
+//! PRESENTATION ONLY. The hovered row, the click counter and the tint are all
+//! screen state. What is FOLDABLE, and which entry a row belongs to, come from
+//! the Model's typed entries (`kind == .tool`, `Entry.folded`) and from the
+//! layout cache — never from reading the rendered text back.
+//!
+//! DOUBLE CLICK. Two presses on the same cell inside `double_ms`. The first
+//! press always does exactly what a press does today (the existing tests pin
+//! that); the SECOND suppresses the single-click action and runs the
+//! double-click one instead, so a double click on a fold header is one net
+//! toggle rather than an expand followed by a collapse. A press that MOVED is
+//! a drag, never a click: selection.zig owns that distinction and calls
+//! `dragged` the instant motion proves it, so the counter is not a second,
+//! divergent copy of the same state machine.
+//!
+//! COST. Hover repaints ride the ordinary frame path. A sweep across N rows is
+//! N motion reports, which pacing.zig's storm window folds into a bounded
+//! number of composed frames exactly as it folds a momentum flick — see the
+//! pacing lane's budget, and `scripts/test-tui-hover.py` for the pty proof.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const glyphs = @import("glyphs.zig");
+const key_mod = @import("key.zig");
+const layout_cache = @import("layout_cache.zig");
+const theme_mod = @import("theme.zig");
+const tint = @import("theme_tint.zig");
+const Model = app.Model;
+
+/// Two presses inside this window, on the same cell, are one double click.
+pub const double_ms: u64 = 400;
+
+/// SGR button for motion with no button held, under ?1003h. Motion WITH the
+/// left button down is 32 and belongs to the drag, not to hover.
+pub const motion_btn: u8 = 35;
+
+/// What sits on a screen row. Only rows a press actually does something to are
+/// targets: an affordance that announced a click which does nothing would be
+/// worse than no affordance at all.
+pub const Target = enum {
+ /// Nothing clickable (blank padding, an overlay body, chrome).
+ none,
+ /// A row belonging to a tool run — a press toggles the whole group.
+ tool,
+ /// The sticky-header pin: a scrolled-past user prompt. A press does
+ /// nothing today; a DOUBLE press jumps the viewport back to it.
+ sticky,
+ /// The composer. A press focuses it.
+ composer,
+};
+
+pub const Hit = struct {
+ target: Target = .none,
+ /// History index the row maps to. Set for `.tool` only.
+ idx: ?usize = null,
+ /// The group is folded, so its mark should announce that it opens.
+ collapsed: bool = false,
+};
+
+/// Presentation state. Lives on the Model beside `sel` and `layout`.
+pub const State = struct {
+ /// 0-based screen row under the pointer, or null when nothing is hovered.
+ row: ?usize = null,
+ hit: Hit = .{},
+ /// Cell and time of the last press, for the double-click window.
+ last_ms: u64 = 0,
+ last_row: usize = 0,
+ last_col: usize = 0,
+ /// A press is banked here; the next one on the same cell inside the window
+ /// completes a double. Zeroed by a drag and by every scroll.
+ armed: bool = false,
+};
+
+// --------------------------------------------------------------- hit test
+
+/// What screen row `y` (0-based) is, this frame. The row→entry map is the
+/// layout cache's, which is the same one keys.mouseKey clicks through.
+pub fn hitTest(m: *Model, y: usize) Hit {
+ // An overlay owns the whole screen and any press merely closes it; there is
+ // no per-row target to announce, so nothing is highlighted while one is up.
+ if (m.overlay != .none) return .{};
+ if (y >= m.prompt_origin) return .{ .target = .composer };
+ if (y < m.mid_origin) return .{};
+ // Sticky chrome OCCLUDES the top content rows: the blank separator row
+ // under the pin is chrome too, and neither maps to what is beneath them.
+ if (y < m.mid_origin + m.sticky_rows) {
+ return if (m.sticky_rows > 0 and y == m.mid_origin) .{ .target = .sticky } else .{};
+ }
+ const vis = y - m.mid_origin + m.mid_skip;
+ const i = layout_cache.indexAtVisual(m, vis, m.last_term_width) orelse return .{};
+ if (m.history.items[i].kind != .tool) return .{};
+ const run = m.toolRun(i);
+ return .{ .target = .tool, .idx = i, .collapsed = m.history.items[run.start].folded };
+}
+
+// ----------------------------------------------------------------- motion
+
+/// A mouse report. Returns true when it was pure hover motion and nothing else
+/// should see it. A drag in progress owns the pointer, so hover stands down.
+pub fn mouse(m: *Model, ev: key_mod.Mouse) bool {
+ if (ev.btn != motion_btn) return false;
+ if (m.sel.active or m.sel.pressed) {
+ clear(m);
+ return false; // image.zig still wants the report for its chip preview
+ }
+ const y: usize = if (ev.y > 0) ev.y - 1 else 0;
+ const hit = hitTest(m, y);
+ if (hit.target == .none) {
+ clear(m);
+ return false;
+ }
+ m.hover.row = y;
+ m.hover.hit = hit;
+ return false; // never consumed: the image chip preview reads it too
+}
+
+/// Drop the highlight. Called when the pointer leaves a target, when the
+/// screen scrolls under it (the row no longer means what it meant), and on
+/// every teardown of the frame's geometry.
+pub fn clear(m: *Model) void {
+ m.hover.row = null;
+ m.hover.hit = .{};
+}
+
+/// A scroll moved the content out from under the pointer, and the pointer did
+/// not move: the highlight would now be announcing a different row than the
+/// one the user is actually over. Drop it and let the next motion re-arm.
+pub fn scrolled(m: *Model) void {
+ clear(m);
+ m.hover.armed = false;
+}
+
+// ----------------------------------------------------------- click counting
+
+/// Record a press. True when it COMPLETES a double click, in which case the
+/// caller must run the double-click action INSTEAD of the single-click one:
+/// the first press already did today's thing, and repeating it would undo it.
+pub fn press(m: *Model, y: usize, x: usize) bool {
+ const same = m.hover.armed and
+ m.hover.last_row == y and m.hover.last_col == x and
+ m.now_ms -| m.hover.last_ms <= double_ms;
+ m.hover.last_row = y;
+ m.hover.last_col = x;
+ m.hover.last_ms = m.now_ms;
+ // A completed double disarms, so a third press opens a fresh single rather
+ // than firing the double action again on every press that follows.
+ m.hover.armed = !same;
+ return same;
+}
+
+/// selection.zig calls this the instant motion turns a press into a drag. A
+/// gesture that moved is not a click, so it can never be half of a double one.
+pub fn dragged(m: *Model) void {
+ m.hover.armed = false;
+ clear(m);
+}
+
+/// Double click on the sticky pin: put the prompt it is pinning back on the
+/// top row of the viewport. No-op when there is nothing pinned or nothing to
+/// scroll — the same numbers render.zig used to lay the frame out.
+pub fn jumpToSticky(m: *Model) void {
+ const c = layout_cache.ensure(m, m.last_term_width);
+ if (layout_cache.stickyUserAbove(c, m.mid_skip) == null) return;
+ var i = layout_cache.indexAt(c, m.mid_skip) orelse m.history.items.len;
+ const line = while (i > 0) {
+ i -= 1;
+ if (m.history.items[i].kind == .user) break layout_cache.lineOf(c, i) orelse return;
+ } else return;
+ const view_h = m.prompt_origin -| m.mid_origin -| m.preview_rows;
+ if (view_h == 0 or c.total <= view_h) return;
+ // `scroll` counts lines from the BOTTOM (render.zig: start = max - scroll).
+ m.scroll = (c.total - view_h) -| line;
+ m.follow = m.scroll == 0;
+ scrolled(m);
+}
+
+// ------------------------------------------------------------------ paint
+
+/// Post-pass over the COMPOSED frame, exactly like selection.paint: the row
+/// builders stay unaware of hover, and the row lands on the screen row the
+/// mouse reported.
+///
+/// The theme background is written per ROW by the painter, BEFORE the row's
+/// bytes (paint.zig), so opening the row with a different background is all it
+/// takes to retint it — including the padding the painter adds after it, which
+/// inherits whatever the row left active.
+pub fn paint(m: *Model, a: std.mem.Allocator, frame: []const u8, width: usize) ![]const u8 {
+ _ = width;
+ const row = m.hover.row orelse return frame;
+ if (m.hover.hit.target == .none) return frame;
+ const bg = tint.hoverBg(m.theme_id);
+ var out = std.array_list.Managed(u8).init(a);
+ var r: usize = 0;
+ var it = std.mem.splitScalar(u8, frame, '\n');
+ var found = false;
+ while (it.next()) |ln| : (r += 1) {
+ if (r > 0) try out.append('\n');
+ if (r != row) {
+ try out.appendSlice(ln);
+ continue;
+ }
+ found = true;
+ try out.appendSlice(bg);
+ if (m.hover.hit.collapsed) {
+ try out.appendSlice(try swapMark(a, ln));
+ } else try out.appendSlice(ln);
+ }
+ // The pointer is parked on a row the frame no longer reaches (the transcript
+ // shrank under it). Nothing to tint, and the stale row must not paint.
+ if (!found) return frame;
+ return out.items;
+}
+
+/// The affordance swap: a collapsed row's tool mark becomes the chevron, so
+/// "this opens" is said before the click rather than after it. Both glyphs are
+/// registered one-column (glyphs.zig), so nothing beside the mark moves.
+fn swapMark(a: std.mem.Allocator, ln: []const u8) ![]const u8 {
+ const at = std.mem.indexOf(u8, ln, glyphs.tool) orelse return ln;
+ return std.fmt.allocPrint(a, "{s}{s}{s}", .{
+ ln[0..at],
+ glyphs.expand,
+ ln[at + glyphs.tool.len ..],
+ });
+}
diff --git a/TUI/hover_tests.zig b/TUI/hover_tests.zig
new file mode 100644
index 00000000..1c465539
--- /dev/null
+++ b/TUI/hover_tests.zig
@@ -0,0 +1,287 @@
+//! Dispatch-level tests for the hover affordance: what a motion report does to
+//! the Model, what the post-pass does to the frame, and where the double-click
+//! window opens and closes. Reached from root.zig — a test module nobody
+//! references compiles for nobody and silently never runs.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const glyphs = @import("glyphs.zig");
+const hover = @import("hover.zig");
+const keys = @import("keys.zig");
+const render_mod = @import("render.zig");
+const tint = @import("theme_tint.zig");
+const Model = app.Model;
+
+const testing = std.testing;
+
+/// The mouse reports the TUI actually receives. `y`/`x` are 1-based, as a
+/// terminal sends them; every handler converts on the way in.
+fn motion(m: *Model, x: u16, y: u16) void {
+ _ = keys.handle(m, .{ .mouse = .{ .btn = hover.motion_btn, .x = x, .y = y, .down = true } });
+}
+
+fn press(m: *Model, x: u16, y: u16) void {
+ _ = keys.handle(m, .{ .mouse = .{ .btn = 0, .x = x, .y = y, .down = true } });
+}
+
+fn drag(m: *Model, x: u16, y: u16) void {
+ _ = keys.handle(m, .{ .mouse = .{ .btn = 32, .x = x, .y = y, .down = true } });
+}
+
+/// A model with one collapsed tool run in a fixed, hand-placed geometry — the
+/// same shape selection.zig's tests use, so the two agree about the viewport.
+fn folded(m: *Model) !void {
+ m.setup(testing.allocator);
+ try m.push(.user, "hi");
+ try m.pushTool(.{ .name = "bash" });
+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });
+ m.last_term_height = 24;
+ m.last_term_width = 80;
+ m.mid_origin = 1;
+ m.mid_skip = 0;
+ m.prompt_origin = 20;
+}
+
+test "motion over a collapsed tool row arms the hover; leaving it clears" {
+ var m: Model = undefined;
+ try folded(&m);
+ defer m.deinit();
+ try testing.expect(m.history.items[1].folded);
+
+ motion(&m, 4, 3); // screen row 2 — the folded group's summary
+ try testing.expectEqual(@as(?usize, 2), m.hover.row);
+ try testing.expectEqual(hover.Target.tool, m.hover.hit.target);
+ try testing.expect(m.hover.hit.collapsed);
+ // Hover NEVER folds, selects or focuses anything: it only says a click
+ // would do something.
+ try testing.expect(m.history.items[1].folded);
+
+ motion(&m, 4, 15); // blank padding below the transcript
+ try testing.expectEqual(@as(?usize, null), m.hover.row);
+ try testing.expectEqual(hover.Target.none, m.hover.hit.target);
+}
+
+test "the composer is a hover target; a row above the viewport is not" {
+ var m: Model = undefined;
+ try folded(&m);
+ defer m.deinit();
+ motion(&m, 5, 21); // inside the composer
+ try testing.expectEqual(hover.Target.composer, m.hover.hit.target);
+ try testing.expectEqual(@as(?usize, 20), m.hover.row);
+ motion(&m, 5, 1); // the top bar, above mid_origin
+ try testing.expectEqual(hover.Target.none, m.hover.hit.target);
+}
+
+test "an expanded group hovers as a target but never claims to expand" {
+ var m: Model = undefined;
+ try folded(&m);
+ defer m.deinit();
+ m.toggleToolGroup(1);
+ try testing.expect(!m.history.items[1].folded);
+ motion(&m, 4, 3);
+ try testing.expectEqual(hover.Target.tool, m.hover.hit.target);
+ // Already open: the chevron would be a lie, so the mark stays put.
+ try testing.expect(!m.hover.hit.collapsed);
+}
+
+/// Screen row (0-based) of the first composed line containing `needle`. The
+/// frame decides its own geometry, so a test that wants to point at a row has
+/// to ask the frame where it is rather than assume.
+fn rowOf(frame: []const u8, needle: []const u8) ?usize {
+ var r: usize = 0;
+ var it = std.mem.splitScalar(u8, frame, '\n');
+ while (it.next()) |ln| : (r += 1) {
+ if (std.mem.indexOf(u8, ln, needle) != null) return r;
+ }
+ return null;
+}
+
+test "the hovered row is repainted with the theme's hover background" {
+ var m: Model = undefined;
+ try folded(&m);
+ defer m.deinit();
+ const bg = tint.hoverBg(m.theme_id);
+
+ const cold = try render_mod.render(&m, testing.allocator, 80, 24, 0);
+ defer testing.allocator.free(cold);
+ try testing.expect(std.mem.indexOf(u8, cold, bg) == null);
+ const summary: u16 = @intCast(rowOf(cold, "Called").? + 1);
+
+ motion(&m, 4, summary);
+ const warm = try render_mod.render(&m, testing.allocator, 80, 24, 0);
+ defer testing.allocator.free(warm);
+ // Exactly one row carries it: hover highlights a row, not a region.
+ var rows: usize = 0;
+ var it = std.mem.splitScalar(u8, warm, '\n');
+ while (it.next()) |ln| {
+ if (std.mem.indexOf(u8, ln, bg) != null) rows += 1;
+ }
+ try testing.expectEqual(@as(usize, 1), rows);
+
+ // ...and moving off restores the frame byte for byte.
+ motion(&m, 4, 15);
+ const cooled = try render_mod.render(&m, testing.allocator, 80, 24, 0);
+ defer testing.allocator.free(cooled);
+ try testing.expectEqualStrings(cold, cooled);
+}
+
+test "a collapsed row under the pointer swaps its tool mark for the chevron" {
+ var m: Model = undefined;
+ try folded(&m);
+ defer m.deinit();
+ const cold = try render_mod.render(&m, testing.allocator, 80, 24, 0);
+ defer testing.allocator.free(cold);
+ try testing.expect(std.mem.indexOf(u8, cold, glyphs.tool) != null);
+
+ motion(&m, 4, @intCast(rowOf(cold, "Called").? + 1));
+ const warm = try render_mod.render(&m, testing.allocator, 80, 24, 0);
+ defer testing.allocator.free(warm);
+ // The one folded group's mark is gone, replaced by the expand chevron.
+ try testing.expect(std.mem.indexOf(u8, warm, glyphs.tool) == null);
+ try testing.expect(std.mem.indexOf(u8, warm, glyphs.expand) != null);
+ // The swap costs no columns, so nothing beside the mark steps sideways.
+ try testing.expectEqual(
+ @import("theme.zig").visibleLen(glyphs.tool),
+ @import("theme.zig").visibleLen(glyphs.expand),
+ );
+}
+
+test "an expanded row keeps its tool mark under the pointer" {
+ var m: Model = undefined;
+ try folded(&m);
+ defer m.deinit();
+ m.toggleToolGroup(1);
+ const cold = try render_mod.render(&m, testing.allocator, 80, 24, 0);
+ defer testing.allocator.free(cold);
+ motion(&m, 4, @intCast(rowOf(cold, "bash").? + 1));
+ const warm = try render_mod.render(&m, testing.allocator, 80, 24, 0);
+ defer testing.allocator.free(warm);
+ try testing.expect(std.mem.indexOf(u8, warm, glyphs.tool) != null);
+}
+
+test "a scroll drops the hover: the row under a still pointer now means something else" {
+ var m: Model = undefined;
+ try folded(&m);
+ defer m.deinit();
+ motion(&m, 4, 3);
+ try testing.expectEqual(hover.Target.tool, m.hover.hit.target);
+ _ = keys.handle(&m, .{ .mouse = .{ .btn = 64, .x = 4, .y = 3, .down = true } });
+ try testing.expectEqual(@as(?usize, null), m.hover.row);
+ try testing.expectEqual(hover.Target.none, m.hover.hit.target);
+}
+
+test "a drag stands the hover down and disarms the click counter" {
+ var m: Model = undefined;
+ try folded(&m);
+ defer m.deinit();
+ motion(&m, 4, 3);
+ press(&m, 4, 3);
+ drag(&m, 30, 6); // motion with the button held: this is a selection now
+ try testing.expect(m.sel.active);
+ try testing.expectEqual(@as(?usize, null), m.hover.row);
+ // The press that turned into a drag cannot be half of a double click, so
+ // the press that ends the drag opens a fresh single.
+ try testing.expect(!m.hover.armed);
+ // Motion WITH the button down is the drag's, never hover's.
+ try testing.expectEqual(hover.Target.none, m.hover.hit.target);
+}
+
+// ------------------------------------------------------- double-click window
+
+test "two presses on one cell inside the window are one double click" {
+ var m: Model = undefined;
+ try folded(&m);
+ defer m.deinit();
+ m.now_ms = 1000;
+ try testing.expect(!hover.press(&m, 5, 5));
+ m.now_ms = 1000 + hover.double_ms;
+ try testing.expect(hover.press(&m, 5, 5));
+ // A third press is a fresh single, not another double.
+ m.now_ms += 10;
+ try testing.expect(!hover.press(&m, 5, 5));
+}
+
+test "the window closes on time and on distance" {
+ var m: Model = undefined;
+ try folded(&m);
+ defer m.deinit();
+ // One millisecond past the window is a single click.
+ m.now_ms = 1000;
+ try testing.expect(!hover.press(&m, 5, 5));
+ m.now_ms = 1001 + hover.double_ms;
+ try testing.expect(!hover.press(&m, 5, 5));
+ // A different cell inside the window is a single click too — a double is
+ // two presses on ONE cell, not two presses anywhere.
+ m.now_ms += 10;
+ try testing.expect(!hover.press(&m, 6, 5));
+ m.now_ms += 10;
+ try testing.expect(!hover.press(&m, 5, 6));
+}
+
+test "a single click still expands, and a double click is one net toggle" {
+ var m: Model = undefined;
+ try folded(&m);
+ defer m.deinit();
+ m.now_ms = 5000;
+ try testing.expect(m.history.items[1].folded);
+
+ // Today's behaviour, unchanged: one press expands the group.
+ press(&m, 4, 3);
+ try testing.expect(!m.history.items[1].folded);
+
+ // A second press inside the window would have collapsed it again, leaving
+ // a double click looking like it did nothing. It is one net toggle now.
+ m.now_ms += 100;
+ press(&m, 4, 3);
+ try testing.expect(!m.history.items[1].folded);
+
+ // ...and two presses far enough apart are still two independent clicks.
+ m.now_ms += 10 * hover.double_ms;
+ press(&m, 4, 3);
+ try testing.expect(m.history.items[1].folded);
+}
+
+test "a double click on the sticky pin scrolls its prompt back onto the screen" {
+ var m: Model = undefined;
+ m.setup(testing.allocator);
+ defer m.deinit();
+ try m.push(.user, "FINDME the pinned prompt");
+ var i: usize = 0;
+ while (i < 60) : (i += 1) try m.push(.assistant, "a filler answer line");
+ // Compose once so the viewport, the sticky pin and the layout cache exist.
+ const first = try render_mod.render(&m, testing.allocator, 80, 24, 0);
+ testing.allocator.free(first);
+ try testing.expect(m.sticky_rows > 0); // the prompt HAS scrolled past
+ try testing.expect(m.mid_skip > 0);
+
+ m.now_ms = 9000;
+ const pin: u16 = @intCast(m.mid_origin + 1); // 1-based row of the pin
+ press(&m, 3, pin);
+ const after_single = m.mid_skip;
+ // A single press on the pin is inert, exactly as before.
+ const mid = try render_mod.render(&m, testing.allocator, 80, 24, 0);
+ testing.allocator.free(mid);
+ try testing.expectEqual(after_single, m.mid_skip);
+
+ m.now_ms += 100;
+ press(&m, 3, pin);
+ const jumped = try render_mod.render(&m, testing.allocator, 80, 24, 0);
+ defer testing.allocator.free(jumped);
+ // The prompt is on screen again, and the viewport is no longer following.
+ try testing.expect(std.mem.indexOf(u8, jumped, "FINDME") != null);
+ try testing.expect(!m.follow);
+ try testing.expect(m.mid_skip < after_single);
+}
+
+test "hover clears when the pointer is over an overlay, which has no row targets" {
+ var m: Model = undefined;
+ try folded(&m);
+ defer m.deinit();
+ motion(&m, 4, 3);
+ try testing.expectEqual(hover.Target.tool, m.hover.hit.target);
+ m.openOverlay(.help);
+ motion(&m, 4, 3);
+ try testing.expectEqual(hover.Target.none, m.hover.hit.target);
+ try testing.expectEqual(@as(?usize, null), m.hover.row);
+}
diff --git a/TUI/keys.zig b/TUI/keys.zig
index 2a8068ea..cfe8c8ac 100644
--- a/TUI/keys.zig
+++ b/TUI/keys.zig
@@ -5,6 +5,7 @@ const std = @import("std");
const app = @import("app.zig");
const catalog = @import("catalog.zig");
const dispatch = @import("dispatch.zig");
+const hover = @import("hover.zig");
const layout_cache = @import("layout_cache.zig");
const selection = @import("selection.zig");
const engine = @import("engine.zig");
@@ -169,6 +170,10 @@ fn pageSize(self: *const Model) u32 {
}
pub fn scrollBy(self: *Model, delta: i32) void {
+ // The content slid out from under a pointer that never moved: the hovered
+ // row now names a different entry, so the affordance is dropped and the
+ // next motion report re-arms it.
+ hover.scrolled(self);
if (delta > 0) {
self.scroll +|= @as(usize, @intCast(delta));
self.follow = false;
@@ -240,6 +245,9 @@ pub fn wheelScroll(self: *Model, notches: i32) Effect {
fn mouseKey(self: *Model, ev: key_mod.Mouse) Effect {
if (@import("pacing.zig").wheelNotch(.{ .mouse = ev })) |n| return wheelScroll(self, n);
+ // Pure motion under ?1003h: track the row so the frame can announce that it
+ // is clickable. Never consumed — the image-chip preview reads it too.
+ _ = hover.mouse(self, ev);
// A drag or its release belongs to the selection; a press only ANCHORS one
// and falls through, so a plain click keeps its meaning (#529).
if (selection.mouse(self, ev)) return .stay;
@@ -250,21 +258,32 @@ fn mouseKey(self: *Model, ev: key_mod.Mouse) Effect {
return .stay;
}
const y: usize = if (ev.y > 0) ev.y - 1 else 0;
+ const x: usize = if (ev.x > 0) ev.x - 1 else 0;
+ // Two presses on one cell inside the window. The FIRST is always today's
+ // click, unchanged; the second replaces it rather than repeating it.
+ const dbl = hover.press(self, y, x);
if (y >= self.prompt_origin) {
self.focus = .prompt;
return .stay;
}
if (y < self.mid_origin) return .stay;
// Sticky-header chrome occludes the top content rows — a click there must
- // not toggle whatever is hidden underneath it.
- if (y < self.mid_origin + self.sticky_rows) return .stay;
+ // not toggle whatever is hidden underneath it. A DOUBLE click on the pin
+ // scrolls the prompt it is pinning back onto the screen.
+ if (y < self.mid_origin + self.sticky_rows) {
+ if (dbl) hover.jumpToSticky(self);
+ return .stay;
+ }
const vis = y - self.mid_origin + self.mid_skip;
self.focus = .scrollback;
// A click on blank padding maps to no entry — it must not select or
// toggle anything (#519).
const i = layout_cache.indexAtVisual(self, vis, self.last_term_width) orelse return .stay;
self.selected = i;
- if (self.history.items[i].kind == .tool) {
+ if (self.history.items[i].kind == .tool and !dbl) {
+ // A double click is ONE net toggle of the whole group: the first press
+ // already toggled it, so toggling again would only put it back and the
+ // gesture would look like it did nothing at all.
self.toggleToolGroup(i);
// Remembered so the fold can be put back if this press turns out to be
// the start of a drag — selecting text must not restructure the view.
@@ -387,210 +406,8 @@ fn isChar(k: Key, c: u8) bool {
};
}
-test "Esc on a draft arms clear, second press clears" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- m.now_ms = 1000;
- m.input.setValue("draft") catch {};
- _ = esc(&m);
- try std.testing.expectEqual(app.EscArm.clear, m.esc_arm);
- try std.testing.expectEqualStrings("draft", m.input.getValue());
- m.now_ms = 1200;
- _ = esc(&m);
- try std.testing.expectEqualStrings("", m.input.getValue());
-}
-
-test "Ctrl+C quits when idle" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- try std.testing.expectEqual(Effect.quit, handle(&m, .{ .ctrl = 'c' }));
- try m.input.setValue("ab");
- _ = handle(&m, .{ .char = 'x' });
- try std.testing.expectEqual(Effect.stay, handle(&m, .{ .ctrl = 'z' }));
- try std.testing.expectEqualStrings("ab", m.input.getValue());
-}
-
-test "Ctrl+D quits an empty composer and is ignored with a draft (#549)" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- try m.input.setValue("half a thought");
- try std.testing.expectEqual(Effect.stay, handle(&m, .{ .ctrl = 'd' }));
- try std.testing.expectEqualStrings("half a thought", m.input.getValue());
- try m.input.setValue(" ");
- try std.testing.expectEqual(Effect.quit, handle(&m, .{ .ctrl = 'd' }));
- try m.input.setValue("");
- try std.testing.expectEqual(Effect.quit, handle(&m, .{ .ctrl = 'd' }));
-}
-
-test "Tab toggles focus" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- try std.testing.expectEqual(app.Focus.prompt, m.focus);
- _ = handle(&m, .tab);
- try std.testing.expectEqual(app.Focus.scrollback, m.focus);
- _ = handle(&m, .tab);
- try std.testing.expectEqual(app.Focus.prompt, m.focus);
-}
-
-test "Shift+Tab cycles Normal Plan Always-approve" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- try std.testing.expectEqual(app.AgentMode.normal, m.mode);
- _ = handle(&m, .shift_tab);
- try std.testing.expectEqual(app.AgentMode.plan, m.mode);
- _ = handle(&m, .shift_tab);
- try std.testing.expectEqual(app.AgentMode.always_approve, m.mode);
- _ = handle(&m, .shift_tab);
- try std.testing.expectEqual(app.AgentMode.normal, m.mode);
-}
-
-test "model overlay Enter picks the selected name" {
- engine.g_models = "grok-4, gpt-5.5";
- engine.g_model_name = "grok-4";
- defer {
- engine.g_models = "";
- engine.g_model_name = "";
- engine.g_model_fn = null;
- }
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- m.openOverlay(.model);
- m.overlay_sel = 1;
- _ = handle(&m, .enter);
- try std.testing.expectEqual(app.Overlay.none, m.overlay);
- try std.testing.expectEqualStrings("gpt-5.5", engine.g_model_name);
-}
-
-test "model overlay type-to-search picks the filtered name" {
- engine.g_models = "grok-4, gpt-5.5, deepseek-v4-pro";
- engine.g_model_name = "grok-4";
- defer {
- engine.g_models = "";
- engine.g_model_name = "";
- engine.g_model_fn = null;
- }
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- m.openOverlay(.model);
- _ = handle(&m, .{ .char = 'd' });
- _ = handle(&m, .{ .char = 'e' });
- _ = handle(&m, .{ .char = 'e' });
- try std.testing.expectEqualStrings("dee", m.overlay_filter);
- _ = handle(&m, .enter);
- try std.testing.expectEqual(app.Overlay.none, m.overlay);
- try std.testing.expectEqualStrings("deepseek-v4-pro", engine.g_model_name);
-}
-
-test "PgUp leaves follow; PgDn returns to the live tail" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- m.last_term_height = 24;
- try std.testing.expect(m.follow);
- _ = handle(&m, .page_up);
- try std.testing.expect(!m.follow);
- try std.testing.expect(m.scroll > 0);
- _ = handle(&m, .page_down);
- try std.testing.expect(m.follow);
- try std.testing.expectEqual(@as(usize, 0), m.scroll);
-}
-
-test "Cmd+Delete and Ctrl+U kill the draft, not the viewport" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- m.last_term_height = 24;
- try m.input.setValue("keep scrolling separate");
- m.input.cursor = m.input.getValue().len;
- _ = handle(&m, .delete_to_start);
- try std.testing.expectEqualStrings("", m.input.getValue());
- try std.testing.expect(m.follow);
- try m.input.setValue("word two");
- m.input.cursor = m.input.getValue().len;
- _ = handle(&m, .{ .ctrl = 'u' });
- try std.testing.expectEqualStrings("", m.input.getValue());
- try std.testing.expect(m.follow);
-}
-
-// The click-behaviour tests live beside the drag tests in selection.zig: a
-// click and a drag are two readings of the same press, and they only stay
-// separable if they are pinned together.
-
-test "slash selection clamps to the filtered list and stays visible (#522)" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- try m.input.setValue("/");
- var idx: [catalog.items.len]usize = undefined;
- const n = catalog.filter("/", &idx);
- try std.testing.expect(n > 8); // the bug needs more commands than visible rows
- var presses: usize = 0;
- while (presses < n + 10) : (presses += 1) _ = handle(&m, .down);
- try std.testing.expectEqual(n - 1, m.slash_sel);
- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena.deinit();
- const menu = try @import("chrome.zig").slashMenu(&m, arena.allocator(), 80);
- try std.testing.expect(std.mem.indexOf(u8, menu, "› ") != null);
-}
-
-test "empty Up scrolls transcript and keeps prompt focus" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- m.last_term_height = 24;
- try std.testing.expect(m.focus == .prompt);
- _ = handle(&m, .up);
- try std.testing.expect(!m.follow);
- try std.testing.expect(m.scroll > 0);
- try std.testing.expect(m.focus == .prompt);
- _ = handle(&m, .down);
- try std.testing.expect(m.follow);
- try std.testing.expectEqual(@as(usize, 0), m.scroll);
-}
-
-test "bracketed paste lands in the prompt as text" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- m.focus = .scrollback;
- _ = handle(&m, .paste_start);
- _ = handle(&m, .{ .char = 'h' });
- _ = handle(&m, .{ .char = 'i' });
- _ = handle(&m, .enter);
- _ = handle(&m, .{ .char = '!' });
- _ = handle(&m, .paste_end);
- try std.testing.expectEqualStrings("hi\n!", m.input.getValue());
- try std.testing.expect(m.focus == .prompt);
- try std.testing.expect(!m.pasting);
-}
-
-test "pasted image path becomes an attachment chip" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- _ = handle(&m, .paste_start);
- for ("/tmp/pic.png") |c| _ = handle(&m, .{ .char = c });
- _ = handle(&m, .paste_end);
- try std.testing.expectEqual(@as(usize, 1), m.images.items.len);
- try std.testing.expectEqualStrings("/tmp/pic.png", m.images.items[0]);
- try std.testing.expectEqualStrings("", m.input.getValue());
-}
-
-test "Ctrl+R walks prompt history" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- try m.prompt_hist.append(try std.testing.allocator.dupe(u8, "older"));
- try m.prompt_hist.append(try std.testing.allocator.dupe(u8, "newer"));
- _ = handle(&m, .{ .ctrl = 'r' });
- try std.testing.expectEqualStrings("newer", m.input.getValue());
- _ = handle(&m, .up);
- try std.testing.expectEqualStrings("older", m.input.getValue());
+test {
+ // The tests live next door (this file is at the line ceiling). Without this
+ // reference they compile for nobody and silently never run.
+ _ = @import("keys_tests.zig");
}
diff --git a/TUI/keys_tests.zig b/TUI/keys_tests.zig
new file mode 100644
index 00000000..03768302
--- /dev/null
+++ b/TUI/keys_tests.zig
@@ -0,0 +1,231 @@
+//! Tests for keys.zig — the dispatcher itself sits at the 600-line ceiling, so
+//! its test block lives here. Reached from keys.zig's test block, which is
+//! reached from root.zig: a module nobody references never runs its tests.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const catalog = @import("catalog.zig");
+const engine = @import("engine.zig");
+const key_mod = @import("key.zig");
+const keys = @import("keys.zig");
+const Key = key_mod.Key;
+const Model = app.Model;
+const Effect = app.Effect;
+
+const handle = keys.handle;
+
+/// The Escape key through the PUBLIC door. `keys.esc` is private, and it should
+/// stay that way: what a test wants pinned is what pressing Escape does, not
+/// which internal helper happens to implement it.
+fn esc(m: *Model) Effect {
+ return handle(m, .escape);
+}
+
+test "Esc on a draft arms clear, second press clears" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.now_ms = 1000;
+ m.input.setValue("draft") catch {};
+ _ = esc(&m);
+ try std.testing.expectEqual(app.EscArm.clear, m.esc_arm);
+ try std.testing.expectEqualStrings("draft", m.input.getValue());
+ m.now_ms = 1200;
+ _ = esc(&m);
+ try std.testing.expectEqualStrings("", m.input.getValue());
+}
+
+test "Ctrl+C quits when idle" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try std.testing.expectEqual(Effect.quit, handle(&m, .{ .ctrl = 'c' }));
+ try m.input.setValue("ab");
+ _ = handle(&m, .{ .char = 'x' });
+ try std.testing.expectEqual(Effect.stay, handle(&m, .{ .ctrl = 'z' }));
+ try std.testing.expectEqualStrings("ab", m.input.getValue());
+}
+
+test "Ctrl+D quits an empty composer and is ignored with a draft (#549)" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.input.setValue("half a thought");
+ try std.testing.expectEqual(Effect.stay, handle(&m, .{ .ctrl = 'd' }));
+ try std.testing.expectEqualStrings("half a thought", m.input.getValue());
+ try m.input.setValue(" ");
+ try std.testing.expectEqual(Effect.quit, handle(&m, .{ .ctrl = 'd' }));
+ try m.input.setValue("");
+ try std.testing.expectEqual(Effect.quit, handle(&m, .{ .ctrl = 'd' }));
+}
+
+test "Tab toggles focus" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try std.testing.expectEqual(app.Focus.prompt, m.focus);
+ _ = handle(&m, .tab);
+ try std.testing.expectEqual(app.Focus.scrollback, m.focus);
+ _ = handle(&m, .tab);
+ try std.testing.expectEqual(app.Focus.prompt, m.focus);
+}
+
+test "Shift+Tab cycles Normal Plan Always-approve" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try std.testing.expectEqual(app.AgentMode.normal, m.mode);
+ _ = handle(&m, .shift_tab);
+ try std.testing.expectEqual(app.AgentMode.plan, m.mode);
+ _ = handle(&m, .shift_tab);
+ try std.testing.expectEqual(app.AgentMode.always_approve, m.mode);
+ _ = handle(&m, .shift_tab);
+ try std.testing.expectEqual(app.AgentMode.normal, m.mode);
+}
+
+test "model overlay Enter picks the selected name" {
+ engine.g_models = "grok-4, gpt-5.5";
+ engine.g_model_name = "grok-4";
+ defer {
+ engine.g_models = "";
+ engine.g_model_name = "";
+ engine.g_model_fn = null;
+ }
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.openOverlay(.model);
+ m.overlay_sel = 1;
+ _ = handle(&m, .enter);
+ try std.testing.expectEqual(app.Overlay.none, m.overlay);
+ try std.testing.expectEqualStrings("gpt-5.5", engine.g_model_name);
+}
+
+test "model overlay type-to-search picks the filtered name" {
+ engine.g_models = "grok-4, gpt-5.5, deepseek-v4-pro";
+ engine.g_model_name = "grok-4";
+ defer {
+ engine.g_models = "";
+ engine.g_model_name = "";
+ engine.g_model_fn = null;
+ }
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.openOverlay(.model);
+ _ = handle(&m, .{ .char = 'd' });
+ _ = handle(&m, .{ .char = 'e' });
+ _ = handle(&m, .{ .char = 'e' });
+ try std.testing.expectEqualStrings("dee", m.overlay_filter);
+ _ = handle(&m, .enter);
+ try std.testing.expectEqual(app.Overlay.none, m.overlay);
+ try std.testing.expectEqualStrings("deepseek-v4-pro", engine.g_model_name);
+}
+
+test "PgUp leaves follow; PgDn returns to the live tail" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.last_term_height = 24;
+ try std.testing.expect(m.follow);
+ _ = handle(&m, .page_up);
+ try std.testing.expect(!m.follow);
+ try std.testing.expect(m.scroll > 0);
+ _ = handle(&m, .page_down);
+ try std.testing.expect(m.follow);
+ try std.testing.expectEqual(@as(usize, 0), m.scroll);
+}
+
+test "Cmd+Delete and Ctrl+U kill the draft, not the viewport" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.last_term_height = 24;
+ try m.input.setValue("keep scrolling separate");
+ m.input.cursor = m.input.getValue().len;
+ _ = handle(&m, .delete_to_start);
+ try std.testing.expectEqualStrings("", m.input.getValue());
+ try std.testing.expect(m.follow);
+ try m.input.setValue("word two");
+ m.input.cursor = m.input.getValue().len;
+ _ = handle(&m, .{ .ctrl = 'u' });
+ try std.testing.expectEqualStrings("", m.input.getValue());
+ try std.testing.expect(m.follow);
+}
+
+// The click-behaviour tests live beside the drag tests in selection.zig: a
+// click and a drag are two readings of the same press, and they only stay
+// separable if they are pinned together.
+
+test "slash selection clamps to the filtered list and stays visible (#522)" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.input.setValue("/");
+ var idx: [catalog.items.len]usize = undefined;
+ const n = catalog.filter("/", &idx);
+ try std.testing.expect(n > 8); // the bug needs more commands than visible rows
+ var presses: usize = 0;
+ while (presses < n + 10) : (presses += 1) _ = handle(&m, .down);
+ try std.testing.expectEqual(n - 1, m.slash_sel);
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const menu = try @import("chrome.zig").slashMenu(&m, arena.allocator(), 80);
+ try std.testing.expect(std.mem.indexOf(u8, menu, "› ") != null);
+}
+
+test "empty Up scrolls transcript and keeps prompt focus" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.last_term_height = 24;
+ try std.testing.expect(m.focus == .prompt);
+ _ = handle(&m, .up);
+ try std.testing.expect(!m.follow);
+ try std.testing.expect(m.scroll > 0);
+ try std.testing.expect(m.focus == .prompt);
+ _ = handle(&m, .down);
+ try std.testing.expect(m.follow);
+ try std.testing.expectEqual(@as(usize, 0), m.scroll);
+}
+
+test "bracketed paste lands in the prompt as text" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.focus = .scrollback;
+ _ = handle(&m, .paste_start);
+ _ = handle(&m, .{ .char = 'h' });
+ _ = handle(&m, .{ .char = 'i' });
+ _ = handle(&m, .enter);
+ _ = handle(&m, .{ .char = '!' });
+ _ = handle(&m, .paste_end);
+ try std.testing.expectEqualStrings("hi\n!", m.input.getValue());
+ try std.testing.expect(m.focus == .prompt);
+ try std.testing.expect(!m.pasting);
+}
+
+test "pasted image path becomes an attachment chip" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ _ = handle(&m, .paste_start);
+ for ("/tmp/pic.png") |c| _ = handle(&m, .{ .char = c });
+ _ = handle(&m, .paste_end);
+ try std.testing.expectEqual(@as(usize, 1), m.images.items.len);
+ try std.testing.expectEqualStrings("/tmp/pic.png", m.images.items[0]);
+ try std.testing.expectEqualStrings("", m.input.getValue());
+}
+
+test "Ctrl+R walks prompt history" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.prompt_hist.append(try std.testing.allocator.dupe(u8, "older"));
+ try m.prompt_hist.append(try std.testing.allocator.dupe(u8, "newer"));
+ _ = handle(&m, .{ .ctrl = 'r' });
+ try std.testing.expectEqualStrings("newer", m.input.getValue());
+ _ = handle(&m, .up);
+ try std.testing.expectEqualStrings("older", m.input.getValue());
+}
diff --git a/TUI/render.zig b/TUI/render.zig
index fdc5a0fe..453c7717 100644
--- a/TUI/render.zig
+++ b/TUI/render.zig
@@ -9,6 +9,7 @@ const app = @import("app.zig");
const chrome = @import("chrome.zig");
const engine = @import("engine.zig");
const glyphs = @import("glyphs.zig");
+const hover = @import("hover.zig");
const layout_cache = @import("layout_cache.zig");
const scrollpaint = @import("scrollpaint.zig");
const selection = @import("selection.zig");
@@ -188,10 +189,13 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
}
try out.appendSlice(bottom_block);
self.paint_hint = scrollHint(self, prev_band);
- // Selection is a post-pass over the finished frame: the row builders stay
- // unaware of it, and the band lands on screen rows exactly as the mouse
- // reported them (#529).
- return gpa.dupe(u8, try selection.paint(self, a, out.items, width));
+ // Hover and selection are both post-passes over the finished frame: the row
+ // builders stay unaware of either, and both land on screen rows exactly as
+ // the mouse reported them (#529). Hover runs FIRST so a drag band painted
+ // over the same row wins — a selection CLAIMS a region, a hover tint only
+ // announces one.
+ const hovered = try hover.paint(self, a, out.items, width);
+ return gpa.dupe(u8, try selection.paint(self, a, hovered, width));
}
/// `count` mid rows starting at `from`, taken from the layout cache when the
diff --git a/TUI/root.zig b/TUI/root.zig
index 4a167a43..fd6713c7 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -64,6 +64,9 @@ test {
_ = @import("layout_cache.zig");
_ = @import("selection.zig");
_ = @import("selection_tests.zig");
+ _ = @import("theme_tint.zig");
+ _ = @import("hover.zig");
+ _ = @import("hover_tests.zig");
_ = @import("chrome.zig");
_ = @import("models.zig");
_ = @import("markdown.zig");
diff --git a/TUI/selection.zig b/TUI/selection.zig
index 7fe38765..5d40cfda 100644
--- a/TUI/selection.zig
+++ b/TUI/selection.zig
@@ -95,6 +95,10 @@ fn extend(self: *Model, ev: key_mod.Mouse) void {
self.sel.h_row = p.row;
self.sel.h_col = p.col;
self.sel.active = true;
+ // This gesture MOVED, so it is a drag and not a click — it can never be
+ // half of a double click either. hover.zig is told rather than left to
+ // re-derive the same distinction from the same reports.
+ @import("hover.zig").dragged(self);
}
/// Mouse-up arms the copy. The band itself KEEPS painting: the user sees
diff --git a/TUI/theme_tint.zig b/TUI/theme_tint.zig
new file mode 100644
index 00000000..f3f0b34c
--- /dev/null
+++ b/TUI/theme_tint.zig
@@ -0,0 +1,119 @@
+//! Backgrounds DERIVED from a palette's own canvas, as tokens.
+//!
+//! This is theme.zig's material — it lives next door only because that file
+//! sits at the 600-line ceiling. Nothing here is a hand-picked colour: every
+//! value is computed from `theme.of(id).bg`, so a new palette gets its hover
+//! tint for free and no two palettes can drift out of step.
+//!
+//! POLARITY. A dark canvas is LIFTED toward white and a light canvas is SUNK
+//! toward black, decided by the same BT.709 rule theme.classifyLight uses for
+//! the OSC-11 reply. One step, both polarities, no second table.
+//!
+//! WEIGHT. The step is deliberately small. The drag-selection band is full
+//! inverse video (`\x1b[7m`) and CLAIMS a region; a hover tint only ANNOUNCES
+//! that the row under the pointer is a target, so it has to read as quieter
+//! than the band from across the room. `hover_step` is asserted below to be a
+//! small fraction of a channel, and the tint is asserted never to be inverse.
+
+const std = @import("std");
+
+const theme = @import("theme.zig");
+
+/// Channel step between the canvas and a hovered row, out of 255. Large enough
+/// to see on an OLED black (oscura's bg is 3,3,4), small enough that a sweep
+/// across the transcript never reads as a selection.
+pub const hover_step: u8 = 16;
+
+/// The hover background for a palette. Comptime-folded per theme, so this is a
+/// switch over string literals at runtime — no allocation, no formatting.
+pub fn hoverBg(id: theme.Id) []const u8 {
+ return switch (id) {
+ inline else => |tag| comptime step(theme.of(tag).bg, hover_step),
+ };
+}
+
+pub const Rgb = struct { r: u8, g: u8, b: u8 };
+
+/// The channels of a `\x1b[48;2;R;G;Bm` background, or null for any other
+/// shape. Every palette's bg is written that way; a future one that is not
+/// falls back to its own canvas rather than to a wrong colour.
+pub fn parseBg(sgr: []const u8) ?Rgb {
+ const head = "\x1b[48;2;";
+ if (!std.mem.startsWith(u8, sgr, head)) return null;
+ if (!std.mem.endsWith(u8, sgr, "m")) return null;
+ var it = std.mem.splitScalar(u8, sgr[head.len .. sgr.len - 1], ';');
+ var ch: [3]u8 = undefined;
+ for (&ch) |*c| {
+ const p = it.next() orelse return null;
+ c.* = std.fmt.parseInt(u8, p, 10) catch return null;
+ }
+ if (it.next() != null) return null;
+ return .{ .r = ch[0], .g = ch[1], .b = ch[2] };
+}
+
+/// `bg` moved one step away from its own polarity, as an SGR literal. Comptime
+/// only: the result is a literal folded into the binary, never a formatted
+/// buffer a frame has to own.
+pub fn step(comptime bg: []const u8, comptime by: u8) []const u8 {
+ const parsed = comptime parseBg(bg);
+ if (parsed == null) return bg;
+ const c = comptime parsed.?;
+ const lift = comptime !theme.classifyLight(c.r, c.g, c.b);
+ const r: u8 = comptime if (lift) c.r +| by else c.r -| by;
+ const g: u8 = comptime if (lift) c.g +| by else c.g -| by;
+ const b: u8 = comptime if (lift) c.b +| by else c.b -| by;
+ return std.fmt.comptimePrint("\x1b[48;2;{d};{d};{d}m", .{ r, g, b });
+}
+
+// ------------------------------------------------------------------ tests
+
+const testing = std.testing;
+
+test "every palette's hover tint is derived from its own canvas and differs from it" {
+ for (theme.all) |id| {
+ const bg = theme.of(id).bg;
+ const hov = hoverBg(id);
+ try testing.expect(!std.mem.eql(u8, bg, hov));
+ const base = parseBg(bg).?;
+ const tint = parseBg(hov).?;
+ // One step, in the direction the canvas's own polarity asks for.
+ const lift = !theme.classifyLight(base.r, base.g, base.b);
+ if (lift) {
+ try testing.expect(tint.r >= base.r and tint.g >= base.g and tint.b >= base.b);
+ } else {
+ try testing.expect(tint.r <= base.r and tint.g <= base.g and tint.b <= base.b);
+ }
+ // ...and never more than one step, on any channel, in either polarity.
+ const dr = if (tint.r > base.r) tint.r - base.r else base.r - tint.r;
+ const dg = if (tint.g > base.g) tint.g - base.g else base.g - tint.g;
+ const db = if (tint.b > base.b) tint.b - base.b else base.b - tint.b;
+ try testing.expect(dr <= hover_step and dg <= hover_step and db <= hover_step);
+ }
+}
+
+test "the hover tint is quieter than the selection band, and never inverse" {
+ // The band is `\x1b[7m` — it inverts the whole cell. A tint that reached
+ // for inverse video, or for a step big enough to read as one, would make
+ // hover and selection say the same thing.
+ for (theme.all) |id| {
+ const hov = hoverBg(id);
+ try testing.expect(std.mem.indexOf(u8, hov, "\x1b[7m") == null);
+ try testing.expect(std.mem.startsWith(u8, hov, "\x1b[48;2;"));
+ }
+ // A tenth of a channel or less: visible, never a claim.
+ try testing.expect(hover_step > 0 and hover_step <= 25);
+}
+
+test "a background that is not truecolor keeps its own bytes" {
+ try testing.expectEqualStrings("\x1b[44m", step("\x1b[44m", 16));
+ try testing.expectEqual(@as(?Rgb, null), parseBg("\x1b[48;2;1;2m"));
+ try testing.expectEqual(@as(?Rgb, null), parseBg("\x1b[48;2;1;2;3;4m"));
+ try testing.expectEqual(@as(?Rgb, null), parseBg("\x1b[48;5;12m"));
+}
+
+test "the step saturates instead of wrapping at either end of a channel" {
+ // A pure-black canvas cannot sink and a pure-white one cannot lift; both
+ // used to be where a wrapping subtract turned the tint into its opposite.
+ try testing.expectEqualStrings("\x1b[48;2;16;16;16m", comptime step("\x1b[48;2;0;0;0m", 16));
+ try testing.expectEqualStrings("\x1b[48;2;239;239;239m", comptime step("\x1b[48;2;255;255;255m", 16));
+}
diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.sh
index e32cf2ff..da6adbbe 100644
--- a/scripts/eval-tier1.sh
+++ b/scripts/eval-tier1.sh
@@ -299,6 +299,15 @@ if wanted tuiguard; then
if python3 scripts/test-tui-event-pacing.py zig-out/bin/graff; then :; else
record_fail tuiguard
fi
+ # A clickable row has to LOOK clickable. Runs a real tool loop against the
+ # codex mock, then reads CELLS off a virtual screen: the hovered summary
+ # takes the theme's hover background and its ◆ becomes ›, its neighbour is
+ # untouched, leaving restores it, a single click still expands, and a
+ # double click is one net toggle. With the post-pass refused the probe
+ # fails on the tint (verified), so this is a gate on both halves.
+ if python3 scripts/test-tui-hover.py zig-out/bin/graff; then :; else
+ record_fail tuiguard
+ fi
fi
fi
diff --git a/scripts/ptyharness.py b/scripts/ptyharness.py
old mode 100755
new mode 100644
index 747f17b2..1db9a86d
--- a/scripts/ptyharness.py
+++ b/scripts/ptyharness.py
@@ -537,7 +537,15 @@ class PtyHarness:
child_env = os.environ.copy()
child_env.setdefault("TERM", term)
if env:
- child_env.update(env)
+ # A None value UNSETS. A probe that needs a clean slate (no
+ # inherited GRAFF_*/CODEX_* from the developer's shell) cannot get
+ # there by setting the variable to "" — an empty string is a value,
+ # and graff reads several of them as one.
+ for k, v in env.items():
+ if v is None:
+ child_env.pop(k, None)
+ else:
+ child_env[k] = v
cwd = os.path.abspath(cwd or os.getcwd())
child_env["PWD"] = cwd
diff --git a/scripts/test-tui-hover.py b/scripts/test-tui-hover.py
new file mode 100644
index 00000000..6609a43f
--- /dev/null
+++ b/scripts/test-tui-hover.py
@@ -0,0 +1,389 @@
+#!/usr/bin/env python3
+"""Live proof that a clickable row LOOKS clickable before it is clicked.
+
+?1003h motion reports already reach the loop (they drive the image-chip
+preview); until TUI/hover.zig every one that missed a chip was dropped. This
+probe drives the real binary under a pty, renders its output into a VIRTUAL
+SCREEN (scripts/ptyharness.py) and reads CELLS back — glyph plus the pen that
+wrote it — so every assertion is about what a terminal would actually show:
+
+ 1. a real tool loop against the codex mock (no network, no model) leaves one
+ COLLAPSED tool summary row on screen,
+ 2. a motion report over that row repaints it: its cells take the theme's
+ hover background, one step off the canvas, and its leading ◆ becomes the
+ chevron › that announces the row opens,
+ 3. the row BELOW it is untouched — hover highlights a row, not a region,
+ 4. moving the pointer away restores the row cell for cell,
+ 5. a SINGLE click still expands the group, exactly as before,
+ 6. a DOUBLE click is ONE net toggle rather than an expand followed by a
+ collapse — which is what two presses used to add up to,
+ 7. and a hover SWEEP across 30 rows costs a bounded number of paints, read
+ off the loop's own counters (GRAFF_TUI_PAINT_STATS=1), not one per row.
+
+Usage: python3 scripts/test-tui-hover.py [path/to/graff]
+Exit 0 = pass, or a skip when there is no pty.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import sys
+import tempfile
+import time
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+from ptyharness import PtyHarness # noqa: E402
+
+BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")
+ROWS, COLS = 34, 100
+ANSWER_MAX = 30.0
+NOTE_BODY = "hover-probe payload"
+FINAL_REPLY = "HOVER_OK the run is done"
+
+TOOL_MARK = "◆" # ◆ glyphs.tool
+EXPAND_MARK = "›" # › glyphs.expand
+STATS = re.compile(r"tui-paint-stats:((?: \w+=\d+)+)")
+
+# TUI/theme_tint.zig: one step per channel, in the direction the canvas's own
+# polarity asks for. Kept here as a NUMBER so a change to the constant that was
+# never meant to be visible shows up as a failure rather than as a silent
+# repaint of nothing.
+HOVER_STEP = 16
+
+
+# ----------------------------------------------------------------- helpers
+
+
+def motion(h, x, y):
+ """A pure ?1003h motion report — button 35, no button held. 1-based."""
+ h.inject_keys(f"\x1b[<35;{x};{y}M".encode())
+
+
+def click(h, x, y, settle=0.6):
+ h.inject_keys(f"\x1b[<0;{x};{y}M".encode())
+ h.pump(0.15)
+ h.inject_keys(f"\x1b[<0;{x};{y}m".encode())
+ h.pump(settle)
+
+
+def row_cells(h, y):
+ return [h.cell(x, y) for x in range(h.cols)]
+
+
+def row_bgs(h, y):
+ """The distinct backgrounds on row `y`, ignoring cells nothing painted."""
+ return {c.bg for c in row_cells(h, y) if c.bg is not None}
+
+
+def summary_row(h):
+ for i, ln in enumerate(h.screen_lines()):
+ if "Called" in ln and "tool" in ln:
+ return i
+ return None
+
+
+def stepped(base, tint):
+ """`tint` is `base` moved one step, saturating, in one consistent direction."""
+ if not (isinstance(base, tuple) and isinstance(tint, tuple)):
+ return False
+ deltas = [t - b for b, t in zip(base, tint)]
+ if all(d == 0 for d in deltas):
+ return False
+ if not (all(d >= 0 for d in deltas) or all(d <= 0 for d in deltas)):
+ return False
+ return all(abs(d) <= HOVER_STEP for d in deltas)
+
+
+# ------------------------------------------------------------- mock session
+
+
+def message_item(text, item_id):
+ return {
+ "type": "message",
+ "id": item_id,
+ "status": "completed",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": text, "annotations": []}],
+ }
+
+
+def response_events(item, response_id):
+ return [
+ {"type": "response.output_item.done", "item": item},
+ {
+ "type": "response.completed",
+ "response": {
+ "id": response_id,
+ "usage": {
+ "input_tokens": 100,
+ "input_tokens_details": {"cached_tokens": 0},
+ "output_tokens": 10,
+ "total_tokens": 110,
+ },
+ },
+ },
+ ]
+
+
+def events(request):
+ if request.ordinal == 1:
+ return response_events(
+ {
+ "type": "function_call",
+ "id": "fc_hover_read",
+ "call_id": "call_hover_read",
+ "name": "read_file",
+ "arguments": json.dumps({"path": "note.txt"}),
+ "status": "completed",
+ },
+ "resp_hover_read",
+ )
+ return response_events(message_item(FINAL_REPLY, "msg_hover_done"), "resp_hover_done")
+
+
+def workspace(tmp, port):
+ with open(os.path.join(tmp, "note.txt"), "w", encoding="utf-8") as fh:
+ fh.write(NOTE_BODY)
+ codex_home = os.path.join(tmp, "codex-home")
+ os.makedirs(codex_home)
+ with open(os.path.join(codex_home, "auth.json"), "w", encoding="utf-8") as fh:
+ json.dump({"tokens": {"access_token": "hover-mock", "account_id": "acct-hover"}}, fh)
+ harness = os.path.join(tmp, ".harness")
+ os.makedirs(harness)
+ with open(os.path.join(harness, "settings.json"), "w", encoding="utf-8") as fh:
+ json.dump({"ai_title": False, "skills": {"codedbpro": False}}, fh)
+ empty_mcp = os.path.join(tmp, "empty-mcp.json")
+ with open(empty_mcp, "w", encoding="utf-8") as fh:
+ fh.write('{"mcpServers": {}}')
+ env = {
+ "HOME": tmp,
+ "CODEX_HOME": codex_home,
+ "GRAFF_CODEX_URL": f"http://127.0.0.1:{port}/backend-api/codex/responses",
+ "GRAFF_CODEX_WS": "off",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ "GRAFF_MCP_CONFIG": empty_mcp,
+ "GRAFF_LEARN_AUTO": "off",
+ }
+ # Everything else the developer's shell might be exporting is UNSET (None),
+ # not blanked: an empty string is a value graff would read.
+ for name in list(os.environ):
+ if (name.startswith("GRAFF_") or name.startswith("CODEX_") or name == "NO_COLOR") and name not in env:
+ env[name] = None
+ return env
+
+
+def check_affordance(h):
+ """(2)-(6): the tint, the mark swap, the neighbour, and the two gestures."""
+ y = summary_row(h)
+ if y is None:
+ return f"no folded tool summary on screen\n{h.screen_contents()}"
+ line = h.screen_lines()[y]
+ if TOOL_MARK not in line:
+ return f"the folded summary carries no tool mark: {line!r}"
+ base_bgs = row_bgs(h, y)
+ if len(base_bgs) != 1:
+ return f"the resting row has {len(base_bgs)} backgrounds, expected the canvas alone: {base_bgs}"
+ base = next(iter(base_bgs))
+ below = summary_row(h) + 1
+ below_before = [c.tuple() for c in row_cells(h, below)]
+
+ # (2) the pointer lands on the row.
+ motion(h, 5, y + 1)
+ h.pump(0.6)
+ warm = row_bgs(h, y)
+ if len(warm) != 1:
+ return f"the hovered row has {len(warm)} backgrounds: {warm}"
+ tint = next(iter(warm))
+ if not stepped(base, tint):
+ return f"the hovered row's background is not one step off the canvas: {base} -> {tint}"
+ hot_line = h.screen_lines()[y]
+ if EXPAND_MARK not in hot_line:
+ return f"the hovered collapsed row never announced that it opens: {hot_line!r}"
+ if TOOL_MARK in hot_line:
+ return f"the tool mark survived the swap: {hot_line!r}"
+
+ # (3) a row is a row: the one under it is untouched, cell for cell.
+ if [c.tuple() for c in row_cells(h, below)] != below_before:
+ return "hovering one row repainted its neighbour too"
+
+ # (4) leaving restores it.
+ motion(h, 5, h.rows - 1)
+ h.pump(0.6)
+ cold = row_bgs(h, y)
+ if cold != {base}:
+ return f"the row kept its hover background after the pointer left: {cold}"
+ if h.screen_lines()[y] != line:
+ return f"the row did not come back as it was:\n was {line!r}\n now {h.screen_lines()[y]!r}"
+
+ # (5) a single click still expands the group. Unchanged behaviour.
+ click(h, 5, y + 1)
+ if summary_row(h) is not None:
+ return "a single click no longer expands the tool group"
+ # ...and a single click on the open card folds it again.
+ head = next((i for i, ln in enumerate(h.screen_lines()) if TOOL_MARK in ln and "read" in ln), None)
+ if head is None:
+ return f"the expanded card has no field-backed head\n{h.screen_contents()}"
+ click(h, 5, head + 1)
+ if summary_row(h) is None:
+ return "a single click on the open card no longer folds it"
+
+ # (6) a double click is ONE net toggle: it opens and STAYS open. Two
+ # presses used to expand and then collapse, so the gesture looked inert.
+ y = summary_row(h)
+ h.inject_keys(f"\x1b[<0;5;{y + 1}M".encode())
+ h.pump(0.05)
+ h.inject_keys(f"\x1b[<0;5;{y + 1}m".encode())
+ h.pump(0.05)
+ h.inject_keys(f"\x1b[<0;5;{y + 1}M".encode())
+ h.pump(0.05)
+ h.inject_keys(f"\x1b[<0;5;{y + 1}m".encode())
+ h.pump(0.8)
+ if summary_row(h) is not None:
+ return "a double click expanded the group and collapsed it again — no net effect"
+ return None
+
+
+# ------------------------------------------------------------ storm session
+
+
+def storm_paints(tmp):
+ """(7) A hover sweep rides the frame budget. Returns (err, control, swept)."""
+ empty_mcp = os.path.join(tmp, "empty-mcp.json")
+ with open(empty_mcp, "w", encoding="utf-8") as fh:
+ fh.write('{"mcpServers": {}}')
+ env = {
+ "GRAFF_MCP_CONFIG": empty_mcp,
+ "GRAFF_LEARN_AUTO": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ "GRAFF_TUI_PAINT_STATS": "1",
+ }
+
+ def one(sweeps):
+ h = PtyHarness([BIN, "tui", "--yolo"], cols=COLS, rows=ROWS, cwd=tmp, env=env)
+ try:
+ if not h.wait_for_boot():
+ raise RuntimeError(f"the storm session never reached the alt screen\n{h.screen_contents()}")
+ # A transcript worth hovering: without one every row is blank and a
+ # sweep would compose the same bytes and prove nothing.
+ h.inject_keys(b"!seq 1 60\r")
+ h.pump(2.0)
+ for _ in range(sweeps):
+ for y in range(2, 32):
+ motion(h, 5, y)
+ h.pump(0.004)
+ h.pump(0.6)
+ h.inject_keys(b"\x11") # Ctrl+Q — the counters print after restore
+ h.pump(2.0)
+ m = STATS.search(h.raw.decode(errors="replace"))
+ return None if not m else {
+ k: int(v) for k, v in (p.split("=") for p in m.group(1).split())
+ }
+ finally:
+ h.close()
+
+ control = one(0)
+ if control is None:
+ return "the control session printed no tui-paint-stats line", None, None
+ swept = one(4)
+ if swept is None:
+ return "the sweep session printed no tui-paint-stats line", None, None
+ extra = swept["paints"] - control["paints"]
+ rows_swept = 4 * 30
+ if extra < 2:
+ return f"the sweep repainted {extra} times — it never highlighted anything", control, swept
+ if swept["events"] - control["events"] < rows_swept * 0.9:
+ return (
+ f"only {swept['events'] - control['events']}/{rows_swept} motion reports reached the loop",
+ control,
+ swept,
+ )
+ # THE claim: bounded by the frame budget, not by the report count. A loop
+ # that painted per report would land at ~120 here.
+ if extra > rows_swept // 2:
+ return (
+ f"{rows_swept} hover reports cost {extra} paints — the frame budget is not folding them",
+ control,
+ swept,
+ )
+ # ...and the budget is what bounded it: frames the loop WANTED and deferred.
+ if swept["skipped"] <= control["skipped"]:
+ return (
+ "the sweep deferred no frames at all — the paint count is low for some other reason",
+ control,
+ swept,
+ )
+ return None, control, swept
+
+
+# --------------------------------------------------------------------- run
+
+
+def run():
+ from codex_ws_mock import CodexMock
+
+ mock = CodexMock(events_for_request=events)
+ port = mock.start()
+ try:
+ with tempfile.TemporaryDirectory(prefix="graff-hover-") as tmp:
+ h = PtyHarness(
+ [BIN, "tui", "--yolo", "--model", "codex", "--no-telemetry"],
+ cols=COLS,
+ rows=ROWS,
+ cwd=tmp,
+ env=workspace(tmp, port),
+ )
+ try:
+ h.wait_for_boot()
+ h.inject_keys(b"read note.txt then report\r")
+ h.wait_for_text("HOVER_OK", timeout=ANSWER_MAX, settle=1.0)
+ err = check_affordance(h)
+ if err:
+ return err, None
+ finally:
+ h.close()
+ with tempfile.TemporaryDirectory(prefix="graff-hover-storm-") as tmp:
+ err, control, swept = storm_paints(tmp)
+ if err:
+ return err, None
+ return None, (control, swept)
+ finally:
+ mock.stop()
+
+
+def main():
+ if not os.path.exists(BIN):
+ print(f"tui-hover: {BIN} not built — skipping")
+ return 0
+ try:
+ import pty # noqa: F401
+ except ImportError:
+ print("tui-hover: no pty support here — skipping")
+ return 0
+ started = time.time()
+ try:
+ err, stats = run()
+ except OSError as e:
+ if getattr(e, "errno", None) == 5:
+ err, stats = "pty EIO — the graff process died mid-check", None
+ else:
+ print(f"tui-hover: pty unavailable ({e}) — skipping")
+ return 0
+ if err:
+ print(f" ✗ hover: {err}")
+ return 1
+ control, swept = stats
+ print(
+ f" ✓ hover: the row tints and its ◆ becomes › under the pointer, restores on leave, "
+ f"single click expands and a double click is one net toggle; "
+ f"120 hover reports cost {swept['paints'] - control['paints']} paints "
+ f"({time.time() - started:.0f}s)"
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())