Skip to content

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

Python

fix(tui): make a single click an action, not just a dismissal

Rach Pradhan5e6c57a1ca16
diff --git a/TUI/app.zig b/TUI/app.zig
index 7205930c..415d95c2 100644
--- a/TUI/app.zig
+++ b/TUI/app.zig
@@ -130,6 +130,14 @@ pub const Model = struct {
prompt_origin: usize = 20,
/// How many mid-lines were clipped above the viewport.
mid_skip: usize = 0,
+ /// Composed mid-lines this frame: the transcript's wrapped total, or an
+ /// overlay body's own line count. A press past it landed on the BACKDROP
+ /// under a short panel and dismisses it, rather than on the panel itself.
+ mid_total: usize = 0,
+ /// Rows of the slash completion menu on screen, at the top of the bottom
+ /// block. A press there picks a command instead of merely focusing the
+ /// composer (click.zig); zero whenever the menu is closed.
+ slash_rows: usize = 0,
/// The scrollable band of the frame just composed, and the painter hint
/// derived from how it moved since the frame before it. Presentation state
/// for the diff painter's scroll fast path: render.zig is the only writer,
@@ -170,6 +178,9 @@ pub const Model = struct {
/// 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 = .{},
+ /// Single-click gesture state (click.zig) - whether the scroll gutter
+ /// currently owns the pointer. Presentation only, like `sel` and `hover`.
+ click: @import("click.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/chrome.zig b/TUI/chrome.zig
index 47a40b4e..2e0f0740 100644
--- a/TUI/chrome.zig
+++ b/TUI/chrome.zig
@@ -133,39 +133,58 @@ pub fn statusBar(self: *const Model, a: std.mem.Allocator, width: usize) ![]cons
return theme_mod.paint(a, th.muted, theme_mod.takeCols(" Enter:send · Shift+Enter:newline · Shift+Tab:mode", if (width == 0) 80 else width));
}
+/// A list row is CUT to the screen, never wrapped: render.zig wraps an
+/// overlay body to the width, and a row that wrapped would push every row
+/// under it off its own line — which is exactly the map a click rides on
+/// (overlays.rowSpan). Zero means "no width yet", which only happens in a
+/// unit test composing a body on its own.
+pub fn rowCols(width: usize) usize {
+ return if (width == 0) 80 else width;
+}
+
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),
+ .theme => try themeOverlay(self, a, width),
.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),
+ .model => try @import("models.zig").render(self, a, width),
+ .effort => try @import("effort.zig").render(self, a, width),
+ .settings => try settingsOverlay(self, a, width),
.image => try @import("image.zig").render(self, a, width),
- .file => try @import("files.zig").render(self, a),
- .jump => try jumpOverlay(self, a),
+ .file => try @import("files.zig").render(self, a, width),
+ .jump => try jumpOverlay(self, a, width),
.slash => "",
};
}
-pub fn slashMenu(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {
+/// The completion menu's window over the filtered command list: the rows it
+/// draws and the item the first of them shows. Clamped selection + a window
+/// that follows it, so the highlighted row is always visible and always the
+/// row Enter fires (#522) — and so a click can map a screen row straight back
+/// to a command (click.zig) instead of re-deriving the same three numbers.
+pub fn slashWindow(self: *const Model) ?struct { first: usize, show: usize, n: usize } {
const v = self.input.getValue();
- if (self.focus != .prompt or v.len == 0 or v[0] != '/') return "";
+ if (self.focus != .prompt or v.len == 0 or v[0] != '/') return null;
var idx: [catalog.items.len]usize = undefined;
const n = catalog.filter(v, &idx);
- if (n == 0) return "";
- const th = self.theme();
- var out = std.array_list.Managed(u8).init(a);
- // Clamped selection + a window that follows it, so the highlighted row is
- // always visible and always the row Enter fires (#522).
+ if (n == 0) return null;
const show = @min(n, @as(usize, 8));
const sel = @min(self.slash_sel, n - 1);
- const first = if (sel >= show) sel + 1 - show else 0;
- var i: usize = first;
- while (i < first + show) : (i += 1) {
+ return .{ .first = if (sel >= show) sel + 1 - show else 0, .show = show, .n = n };
+}
+
+pub fn slashMenu(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {
+ const w = slashWindow(self) orelse return "";
+ var idx: [catalog.items.len]usize = undefined;
+ _ = catalog.filter(self.input.getValue(), &idx);
+ const th = self.theme();
+ var out = std.array_list.Managed(u8).init(a);
+ const sel = @min(self.slash_sel, w.n - 1);
+ var i: usize = w.first;
+ while (i < w.first + w.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 click maps a screen row straight back to
@@ -203,7 +222,7 @@ fn listOverlay(self: *const Model, a: std.mem.Allocator, width: usize) ![]const
return out.items;
}
-fn themeOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+fn themeOverlay(self: *const Model, a: std.mem.Allocator, width: usize) ![]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"));
@@ -212,14 +231,14 @@ fn themeOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
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 });
+ const line = theme_mod.takeCols(try std.fmt.allocPrint(a, "{s}{s}{s}", .{ mark, id.label(), cur }), rowCols(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 jumpOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+fn jumpOverlay(self: *const Model, a: std.mem.Allocator, width: usize) ![]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"));
@@ -236,13 +255,13 @@ fn jumpOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
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 });
+ const line = theme_mod.takeCols(try std.fmt.allocPrint(a, "{s}#{d} {s}", .{ mark, no + 1, clip }), rowCols(width));
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.appendSlice(try theme_mod.paint(a, th.muted, theme_mod.takeCols("↑↓ move · click or Enter jumps · Esc", rowCols(width))));
try out.append('\n');
return out.items;
}
@@ -396,7 +415,7 @@ test "debug overlay is not the offline fallback when a hud is wired" {
pub const splitModels = @import("models.zig").splitModels;
-fn settingsOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+fn settingsOverlay(self: *const Model, a: std.mem.Allocator, width: usize) ![]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"));
@@ -410,12 +429,12 @@ fn settingsOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
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] });
+ const line = theme_mod.takeCols(try std.fmt.allocPrint(a, "{s}{s:<10} {s}", .{ mark, r[0], r[1] }), rowCols(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');
}
try out.append('\n');
- try out.appendSlice(try theme_mod.paint(a, th.muted, "Enter change · type /model to search · Esc"));
+ try out.appendSlice(try theme_mod.paint(a, th.muted, theme_mod.takeCols("click or Enter changes · Esc", rowCols(width))));
try out.append('\n');
return out.items;
}
diff --git a/TUI/click.zig b/TUI/click.zig
new file mode 100644
index 00000000..5cfa197b
--- /dev/null
+++ b/TUI/click.zig
@@ -0,0 +1,199 @@
+//! Single click as an ACTION.
+//!
+//! Everything AROUND the press was already wired: hover.zig tints the row
+//! under the pointer, the wheel scrolls, a drag paints a band and copies it,
+//! and scrollbar.zig draws a thumb on the right edge. The press itself still
+//! only ever did three things - focus the composer, toggle a fold, or dismiss
+//! whatever overlay was up - so every list on screen looked clickable and was
+//! not. This file is the missing half.
+//!
+//! THREE TARGETS, ONE RULE. A press answers the thing it LANDED on:
+//!
+//! * the scroll gutter (the last column of the band) seeks the viewport, and
+//! keeps seeking while the button is held,
+//! * a row of an open list picks it,
+//! * a row of the slash completion menu picks that command,
+//!
+//! and a press that lands on none of them falls through to exactly what it did
+//! before, byte for byte.
+//!
+//! SELECT, THEN CONFIRM. A click on a list row moves the highlight to it; a
+//! click on the row that ALREADY carries the highlight fires it, like Enter.
+//! That is one rule, not two, and it is also why a double click confirms
+//! without a second copy of the double-click window: the first press makes the
+//! row current and the second one lands on a current row. hover.zig's press
+//! counter stays out of it - a list has no "one net toggle" problem to solve.
+//!
+//! CLICK IS NOT DRAG. A gutter press never reaches selection.zig, so it can
+//! never anchor a band (a scrollbar that fought the copy gesture would be
+//! worse than no scrollbar). Everywhere else the boundary is the one
+//! selection.zig already owns: a press only ARMS the transcript's fold toggle
+//! and records an anchor, and the instant motion proves the gesture was a
+//! drag, `selection.extend` puts the fold back. So a motionless press+release
+//! is a click, a press that moved is a selection, and neither ever does both.
+//!
+//! PRESENTATION ONLY. Which row a list highlights, where the viewport sits and
+//! which command the menu offers are all screen state. What a picked row DOES
+//! is not re-implemented here: a list row goes through `overlays.activate` and
+//! a menu row through `dispatch.runCommand`, which are the two calls Enter
+//! already makes.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const catalog = @import("catalog.zig");
+const chrome = @import("chrome.zig");
+const dispatch = @import("dispatch.zig");
+const key_mod = @import("key.zig");
+const overlays = @import("overlays.zig");
+const scrollbar = @import("scrollbar.zig");
+const Model = app.Model;
+const Effect = app.Effect;
+
+/// Gesture state. One flag: whether the gutter currently owns the pointer.
+pub const State = struct {
+ /// A press landed on the scroll gutter and the button has not come up.
+ /// Every report until it does is a seek, and none of them is a selection.
+ gutter: bool = false,
+};
+
+// -------------------------------------------------------------- the gutter
+
+/// The gutter gesture, run BEFORE selection.zig sees the report. Returns true
+/// when the gutter owns this event.
+///
+/// A press on the track jumps toward it; the motion reports that follow keep
+/// seeking, which is what makes the thumb draggable. The release ends it. A
+/// motion report with NO button held (35) can only mean the release went
+/// missing - a terminal that lost focus mid-drag - so it ends the gesture
+/// rather than leaving the pointer captured forever.
+pub fn gutterGesture(self: *Model, ev: key_mod.Mouse) bool {
+ if (self.click.gutter) {
+ if (ev.btn == 35) {
+ self.click.gutter = false;
+ return false;
+ }
+ if (!ev.down) {
+ self.click.gutter = false;
+ return true;
+ }
+ if (ev.btn == 32 or ev.btn == 0) {
+ seek(self, ev.y);
+ return true;
+ }
+ return false;
+ }
+ if (!ev.down or ev.btn != 0) return false;
+ if (!onGutter(self, ev)) return false;
+ self.click.gutter = true;
+ seek(self, ev.y);
+ return true;
+}
+
+/// Is this press on the gutter? Only while a thumb is actually SHOWING: the
+/// gutter fades out of a tail-parked viewport (scrollbar.zig), and a column
+/// the user cannot see must not swallow a click on the text under it.
+fn onGutter(self: *const Model, ev: key_mod.Mouse) bool {
+ if (self.last_term_width < 2) return false;
+ const x: usize = if (ev.x > 0) ev.x - 1 else 0;
+ if (x != self.last_term_width - 1) return false;
+ const y: usize = if (ev.y > 0) ev.y - 1 else 0;
+ if (y < self.band.top or y >= self.band.top + self.band.len) return false;
+ return scrollbar.current(self) != null;
+}
+
+/// Put the viewport where the pointer is pointing.
+///
+/// The thumb is CENTRED on the row under the pointer, the way a browser's is:
+/// grabbing it anywhere and dragging then moves it by the number of rows the
+/// pointer moved, instead of snapping its top edge under the cursor.
+///
+/// The arithmetic runs in the scrollbar's own coordinates - `band.off` lines
+/// above the viewport, out of `band.total` - and comes back through the one
+/// door every other scroll uses (`keys.scrollBy`), so the fade clock, the
+/// follow latch and the hover drop are wound exactly once, here as anywhere.
+fn seek(self: *Model, row1: u16) void {
+ const b = self.band;
+ if (!b.live or b.len == 0 or b.total <= b.len) return;
+ const t = scrollbar.current(self) orelse return;
+ const y: usize = if (row1 > 0) row1 - 1 else 0;
+ const in_track = std.math.clamp(y, b.top, b.top + b.len - 1) - b.top;
+ const span = b.len - t.len; // rows the thumb's TOP can take
+ const max_off = b.total - b.len;
+ const want_top = @min(in_track -| t.len / 2, span);
+ const off = if (span == 0) max_off else (want_top * max_off + span / 2) / span;
+ // `scroll` counts from the BOTTOM, `off` from the top; the sticky header
+ // occludes rows the scroll never reaches, so the achievable maximum falls
+ // short of `max_off` by exactly those rows (render.zig).
+ const target = @min(max_off - off, b.total -| (b.len + self.sticky_rows));
+ if (target == self.scroll) return;
+ const d: i64 = @as(i64, @intCast(target)) - @as(i64, @intCast(self.scroll));
+ @import("keys.zig").scrollBy(self, std.math.lossyCast(i32, d));
+}
+
+// ---------------------------------------------------------------- the lists
+
+/// A press that reached the click layer: the wheel, the drag and the image
+/// card have all already declined it, and it is a left-button DOWN report.
+/// Returns the effect when a list answered it, else null - and null is what
+/// keeps every pre-existing meaning of a press intact.
+pub fn press(self: *Model, ev: key_mod.Mouse) ?Effect {
+ const y: usize = if (ev.y > 0) ev.y - 1 else 0;
+ if (self.overlay == .none) return slashPress(self, y);
+ if (self.overlay == .image) return null; // a card, not a panel
+ return overlayPress(self, y);
+}
+
+/// The list item on screen row `y` of an open overlay, or null. Shared with
+/// hover.zig so the tint and the click cannot disagree about what a row is.
+pub fn overlayRowAt(self: *const Model, y: usize) ?usize {
+ const span = overlays.rowSpan(self) orelse return null;
+ if (y < self.mid_origin or y >= self.prompt_origin) return null;
+ const line = (y - self.mid_origin) + self.mid_skip;
+ if (line < span.line0 or line >= span.line0 + span.rows) return null;
+ return span.first + (line - span.line0);
+}
+
+/// A press with a list overlay up. Inside the panel it picks a row or does
+/// nothing; OUTSIDE it - the backdrop under a short panel, the top bar, the
+/// composer - it declines, and the press closes the overlay exactly as it
+/// always has (keys.zig), which is the click-outside-to-dismiss half.
+fn overlayPress(self: *Model, y: usize) ?Effect {
+ // An overlay with no list (help, the observability HUD, the rewind
+ // prompt) has no rows to pick and keeps its click-anywhere dismissal.
+ _ = overlays.rowSpan(self) orelse return null;
+ if (y < self.mid_origin or y >= self.prompt_origin) return null;
+ const line = (y - self.mid_origin) + self.mid_skip;
+ if (line >= self.mid_total) return null; // padding below a short panel
+ const item = overlayRowAt(self, y) orelse return .stay; // title, footer: inert
+ return overlays.clickRow(self, item);
+}
+
+/// A press on the slash completion menu, which sits at the TOP of the bottom
+/// block - the rows `prompt_origin` names before the composer box starts. Same
+/// select-then-confirm rule as an overlay list.
+fn slashPress(self: *Model, y: usize) ?Effect {
+ if (self.slash_rows == 0) return null;
+ if (y < self.prompt_origin or y >= self.prompt_origin + self.slash_rows) return null;
+ const w = chrome.slashWindow(self) orelse return null;
+ // A short terminal trims the bottom block from the TOP (render.zig), so
+ // the first row still on screen is not the first row the menu wanted.
+ const item = w.first + (w.show -| self.slash_rows) + (y - self.prompt_origin);
+ if (item >= w.n) return null;
+ if (@min(self.slash_sel, w.n - 1) != item) {
+ self.slash_sel = item;
+ return .stay;
+ }
+ var idx: [catalog.items.len]usize = undefined;
+ const n = catalog.filter(self.input.getValue(), &idx);
+ if (n == 0 or item >= n) return .stay;
+ const pick = catalog.items[idx[item]];
+ self.input.setValue("") catch {};
+ return dispatch.runCommand(self, pick.name);
+}
+
+test {
+ // The tests live next door so this file stays under the ceiling. Without
+ // this reference they compile for nobody and silently never run.
+ _ = @import("click_tests.zig");
+}
diff --git a/TUI/click_tests.zig b/TUI/click_tests.zig
new file mode 100644
index 00000000..57d9bd7d
--- /dev/null
+++ b/TUI/click_tests.zig
@@ -0,0 +1,478 @@
+//! Single-click semantics (click.zig), pinned.
+//!
+//! Four boundaries live here, and every one of them is a place the gesture
+//! could quietly do the wrong thing:
+//!
+//! * a fold header answers a click with EXACTLY one net toggle, however fast
+//! the second click arrives,
+//! * a press that MOVED is a selection and never a fold toggle; a press that
+//! did not is a click and never touches the clipboard,
+//! * the scroll gutter owns its column before the selection can anchor in
+//! it, and gives the pointer back on the button-up,
+//! * a list row picks, the row that already carries the highlight confirms,
+//! and the backdrop around the panel dismisses it.
+//!
+//! The overlay cases drive a REAL composed frame and find their row by reading
+//! it back, so the click map (overlays.rowSpan) is checked against the bytes
+//! the renderer actually produced rather than against a second opinion.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const catalog = @import("catalog.zig");
+const chrome = @import("chrome.zig");
+const engine = @import("engine.zig");
+const hover = @import("hover.zig");
+const keys = @import("keys.zig");
+const overlays = @import("overlays.zig");
+const render_mod = @import("render.zig");
+const scrollbar = @import("scrollbar.zig");
+const theme_mod = @import("theme.zig");
+const Model = app.Model;
+
+const alloc = std.testing.allocator;
+const expect = std.testing.expect;
+const expectEqual = std.testing.expectEqual;
+
+fn press(m: *Model, x: u16, y: u16) app.Effect {
+ return keys.handle(m, .{ .mouse = .{ .btn = 0, .x = x, .y = y, .down = true } });
+}
+
+fn release(m: *Model, x: u16, y: u16) void {
+ _ = keys.handle(m, .{ .mouse = .{ .btn = 0, .x = x, .y = y, .down = false } });
+}
+
+fn motion(m: *Model, x: u16, y: u16) void {
+ _ = keys.handle(m, .{ .mouse = .{ .btn = 32, .x = x, .y = y, .down = true } });
+}
+
+/// A click: press and release on the SAME cell with nothing in between.
+fn clickAt(m: *Model, x: u16, y: u16) app.Effect {
+ const e = press(m, x, y);
+ release(m, x, y);
+ return e;
+}
+
+fn frame(m: *Model, w: usize, h: usize) ![]const u8 {
+ return render_mod.render(m, alloc, w, h, m.now_ms);
+}
+
+/// 0-based screen row of the first frame line carrying `needle`.
+fn rowOf(f: []const u8, needle: []const u8) ?usize {
+ var r: usize = 0;
+ var it = std.mem.splitScalar(u8, f, '\n');
+ while (it.next()) |ln| : (r += 1) {
+ if (std.mem.indexOf(u8, ln, needle) != null) return r;
+ }
+ return null;
+}
+
+/// A transcript with one collapsed tool group, laid out by hand so the row a
+/// press lands on is arithmetic rather than a search through the frame.
+fn foldModel(m: *Model) !void {
+ m.setup(alloc);
+ try m.push(.user, "hi");
+ try m.pushTool(.{ .name = "bash" });
+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });
+ m.last_term_width = 80;
+ m.last_term_height = 24;
+ m.mid_origin = 1;
+ m.mid_skip = 0;
+ m.prompt_origin = 20;
+}
+
+// ------------------------------------------------------------------- folds
+
+test "a motionless click on a fold header is exactly one net toggle" {
+ var m: Model = undefined;
+ try foldModel(&m);
+ defer m.deinit();
+ try expect(m.history.items[1].folded);
+ _ = clickAt(&m, 4, 3);
+ try expect(!m.history.items[1].folded);
+ // A click is not a selection: no band, no capture, no toast claiming one.
+ try expect(!m.sel.active);
+ try expect(!m.sel.pressed);
+ try expectEqual(@as(usize, 0), m.sel_text.len);
+ try std.testing.expectEqualStrings("", m.toast);
+ // ...and the next click, outside the double-click window, puts it back.
+ m.now_ms += hover.double_ms + 1;
+ _ = clickAt(&m, 4, 3);
+ try expect(m.history.items[1].folded);
+}
+
+test "two clicks inside the double-click window are ONE net toggle" {
+ // The pinned semantics: the first press toggles, the second REPLACES that
+ // action rather than repeating it, so the pair opens the group and leaves
+ // it open. Toggling twice would look like the gesture did nothing at all.
+ var m: Model = undefined;
+ try foldModel(&m);
+ defer m.deinit();
+ try expect(m.history.items[1].folded);
+ _ = clickAt(&m, 4, 3);
+ _ = clickAt(&m, 4, 3); // same cell, same millisecond
+ try expect(!m.history.items[1].folded);
+ // A third press, still inside the window, opens a fresh single click: the
+ // completed double disarmed, so the counter cannot fire twice in a row.
+ _ = clickAt(&m, 4, 3);
+ try expect(m.history.items[1].folded);
+}
+
+test "a press that MOVES is a selection, and leaves the fold as it was" {
+ var m: Model = undefined;
+ try foldModel(&m);
+ defer m.deinit();
+ try expect(m.history.items[1].folded);
+ _ = press(&m, 4, 3);
+ motion(&m, 30, 5);
+ // The optimistic expand is reverted the instant motion proves the drag.
+ try expect(m.history.items[1].folded);
+ try expect(m.sel.active);
+ // A gesture that moved can never be half of a double click either.
+ try expect(!m.hover.armed);
+ release(&m, 30, 5);
+ try expect(m.history.items[1].folded);
+}
+
+// --------------------------------------------------------------- the gutter
+
+/// A transcript long enough to scroll, composed for real so the band, the
+/// thumb and the viewport all agree with each other.
+fn scrolledModel(m: *Model) !void {
+ m.setup(alloc);
+ var i: usize = 0;
+ while (i < 200) : (i += 1) {
+ var buf: [32]u8 = undefined;
+ try m.push(.assistant, try std.fmt.bufPrint(&buf, "line {d:0>3}", .{i}));
+ }
+ const first = try frame(m, 80, 24);
+ alloc.free(first);
+ keys.scrollBy(m, 40);
+ const second = try frame(m, 80, 24);
+ alloc.free(second);
+}
+
+test "a press on the gutter seeks the viewport and never anchors a band" {
+ var m: Model = undefined;
+ try scrolledModel(&m);
+ defer m.deinit();
+ try expect(m.band.live);
+ try expect(scrollbar.current(&m) != null);
+ const track_top: u16 = @intCast(m.band.top + 1);
+ const track_bottom: u16 = @intCast(m.band.top + m.band.len);
+ // The bottom of the track is the tail of the transcript.
+ _ = press(&m, 80, track_bottom);
+ try expect(m.click.gutter);
+ try expectEqual(@as(usize, 0), m.scroll);
+ try expect(m.follow);
+ // A scrollbar gesture is never a drag-copy, and never a fold toggle.
+ try expect(!m.sel.pressed);
+ try expect(!m.sel.active);
+ try expectEqual(app.Focus.prompt, m.focus);
+ release(&m, 80, track_bottom);
+ try expect(!m.click.gutter);
+ // ...and the top of the track is the top of the transcript.
+ _ = press(&m, 80, track_top);
+ const f = try frame(&m, 80, 24);
+ defer alloc.free(f);
+ try expectEqual(@as(usize, 0), m.band.off -| m.sticky_rows);
+ try expect(rowOf(f, "line 000") != null);
+ release(&m, 80, track_top);
+}
+
+test "a drag down the gutter walks the viewport, one report at a time" {
+ var m: Model = undefined;
+ try scrolledModel(&m);
+ defer m.deinit();
+ const track_top: u16 = @intCast(m.band.top + 1);
+ _ = press(&m, 80, track_top);
+ try expect(m.click.gutter);
+ const at_top = m.scroll;
+ var y = track_top;
+ var last = at_top;
+ while (y < @as(u16, @intCast(m.band.top + m.band.len))) : (y += 1) {
+ motion(&m, 80, y + 1);
+ // Monotone: dragging DOWN the track only ever moves toward the tail.
+ try expect(m.scroll <= last);
+ last = m.scroll;
+ // Still the gutter's pointer — the motion never became a selection.
+ try expect(!m.sel.active);
+ }
+ try expect(last < at_top);
+ release(&m, 80, @intCast(m.band.top + m.band.len));
+ try expect(!m.click.gutter);
+}
+
+test "a faded gutter is not a target: the press means what it always meant" {
+ var m: Model = undefined;
+ try scrolledModel(&m);
+ defer m.deinit();
+ keys.scrollBy(&m, -1000); // back to the tail
+ const f = try frame(&m, 80, 24);
+ alloc.free(f);
+ m.now_ms += scrollbar.fade_ms + 1;
+ try expect(scrollbar.current(&m) == null);
+ const row: u16 = @intCast(m.band.top + 2);
+ _ = press(&m, 80, row);
+ try expect(!m.click.gutter);
+ try expectEqual(@as(usize, 0), m.scroll);
+ // The ordinary transcript press ran instead.
+ try expectEqual(app.Focus.scrollback, m.focus);
+ release(&m, 80, row);
+}
+
+test "a key hands the pointer back when the gutter's release goes missing" {
+ var m: Model = undefined;
+ try scrolledModel(&m);
+ defer m.deinit();
+ _ = press(&m, 80, @intCast(m.band.top + 1));
+ try expect(m.click.gutter);
+ _ = keys.handle(&m, .{ .char = 'x' });
+ try expect(!m.click.gutter);
+}
+
+// -------------------------------------------------------------- list rows
+
+fn modelOverlay(m: *Model) !void {
+ m.setup(alloc);
+ m.openOverlay(.model);
+}
+
+test "a click on a model row highlights it, and a second click picks it" {
+ engine.g_models = "alpha-one, beta-two, gamma-three";
+ engine.g_model_name = "alpha-one";
+ defer {
+ engine.g_models = "";
+ engine.g_model_name = "";
+ }
+ var m: Model = undefined;
+ try modelOverlay(&m);
+ defer m.deinit();
+ const f = try frame(&m, 80, 24);
+ defer alloc.free(f);
+ const row = rowOf(f, "gamma-three") orelse return error.NoModelRow;
+ _ = press(&m, 3, @intCast(row + 1));
+ try expectEqual(app.Overlay.model, m.overlay); // selecting is not picking
+ try expectEqual(@as(usize, 2), m.overlay_sel);
+ _ = press(&m, 3, @intCast(row + 1));
+ try expectEqual(app.Overlay.none, m.overlay);
+ try std.testing.expectEqualStrings("gamma-three", engine.g_model_name);
+}
+
+test "the panel keeps a press, and the backdrop around it dismisses" {
+ engine.g_models = "alpha-one, beta-two, gamma-three";
+ defer engine.g_models = "";
+ var m: Model = undefined;
+ try modelOverlay(&m);
+ defer m.deinit();
+ const f = try frame(&m, 80, 24);
+ defer alloc.free(f);
+ // The title is inside the panel: inert, and the overlay stays up.
+ const title = rowOf(f, "Model ›") orelse return error.NoTitle;
+ _ = press(&m, 3, @intCast(title + 1));
+ try expectEqual(app.Overlay.model, m.overlay);
+ try expectEqual(@as(usize, 0), m.overlay_sel);
+ // Below the body's last line is the backdrop, and a press there closes it
+ // exactly like Esc.
+ const below: u16 = @intCast(m.mid_origin + m.mid_total + 1);
+ try expect(below <= m.prompt_origin);
+ _ = press(&m, 3, below);
+ try expectEqual(app.Overlay.none, m.overlay);
+}
+
+test "an overlay with no rows to pick still closes on any press" {
+ var m: Model = undefined;
+ m.setup(alloc);
+ defer m.deinit();
+ m.openOverlay(.help);
+ const f = try frame(&m, 80, 24);
+ alloc.free(f);
+ try expect(overlays.rowSpan(&m) == null);
+ _ = press(&m, 10, @intCast(m.mid_origin + 3));
+ try expectEqual(app.Overlay.none, m.overlay);
+}
+
+test "a settings row opens the picker it names" {
+ var m: Model = undefined;
+ m.setup(alloc);
+ defer m.deinit();
+ m.openOverlay(.settings);
+ const f = try frame(&m, 80, 24);
+ defer alloc.free(f);
+ const row = rowOf(f, "Theme") orelse return error.NoSettingsRow;
+ _ = press(&m, 3, @intCast(row + 1)); // highlight
+ try expectEqual(@as(usize, 3), m.overlay_sel);
+ _ = press(&m, 3, @intCast(row + 1)); // confirm
+ try expectEqual(app.Overlay.theme, m.overlay);
+}
+
+test "hover announces a list row, so the tint and the click agree" {
+ engine.g_models = "alpha-one, beta-two, gamma-three";
+ defer engine.g_models = "";
+ var m: Model = undefined;
+ try modelOverlay(&m);
+ defer m.deinit();
+ const f = try frame(&m, 80, 24);
+ defer alloc.free(f);
+ const row = rowOf(f, "beta-two") orelse return error.NoModelRow;
+ const hit = hover.hitTest(&m, row);
+ try expectEqual(hover.Target.row, hit.target);
+ try expectEqual(@as(?usize, 1), hit.idx);
+ // The title is not a target — an affordance on a row a press ignores
+ // would be worse than none.
+ const title = rowOf(f, "Model ›") orelse return error.NoTitle;
+ try expectEqual(hover.Target.none, hover.hitTest(&m, title).target);
+}
+
+// ------------------------------------------------------------ slash menu
+
+test "a click on a completion row highlights it, and on the current one runs it" {
+ var m: Model = undefined;
+ m.setup(alloc);
+ defer m.deinit();
+ m.focus = .prompt;
+ try m.input.setValue("/");
+ const f = try frame(&m, 80, 24);
+ defer alloc.free(f);
+ try expect(m.slash_rows > 2);
+ try expectEqual(@as(usize, 0), m.slash_sel);
+ const w = chrome.slashWindow(&m) orelse return error.NoMenu;
+ const trimmed = w.show -| m.slash_rows;
+ _ = press(&m, 3, @intCast(m.prompt_origin + 3));
+ try expectEqual(w.first + trimmed + 2, m.slash_sel);
+ // ...and the draft is untouched: highlighting is not running.
+ try std.testing.expectEqualStrings("/", m.input.getValue());
+}
+
+test "a click on the highlighted completion row runs that command" {
+ var m: Model = undefined;
+ m.setup(alloc);
+ defer m.deinit();
+ m.focus = .prompt;
+ try m.input.setValue("/plan");
+ const f = try frame(&m, 80, 24);
+ defer alloc.free(f);
+ const w = chrome.slashWindow(&m) orelse return error.NoMenu;
+ try expectEqual(@as(usize, 1), w.n);
+ try expectEqual(@as(usize, 1), m.slash_rows);
+ try expectEqual(app.AgentMode.normal, m.mode);
+ _ = press(&m, 3, @intCast(m.prompt_origin + 1));
+ try expectEqual(app.AgentMode.plan, m.mode);
+ try std.testing.expectEqualStrings("", m.input.getValue());
+}
+
+// ------------------------------------------------------- the map vs the bytes
+
+/// Every body line fits the width, and the span's rows carry `want` in order.
+/// This is the drift guard: `rowSpan` states each renderer's header shape as
+/// arithmetic, and the day a renderer grows a line the arithmetic is a lie —
+/// clicks would land one row off, silently, on the wrong item.
+fn checkSpan(m: *Model, width: usize, want: []const []const u8) !void {
+ var arena = std.heap.ArenaAllocator.init(alloc);
+ defer arena.deinit();
+ const body = try chrome.overlay(m, arena.allocator(), width);
+ var lines = std.array_list.Managed([]const u8).init(arena.allocator());
+ var it = std.mem.splitScalar(u8, body, '\n');
+ while (it.next()) |ln| try lines.append(ln);
+ // A list row is CUT, never wrapped: one item is one line, or the map that
+ // turns a screen row into an item index cannot be arithmetic at all.
+ for (lines.items) |ln| try expect(theme_mod.visibleLen(ln) <= width);
+ const span = overlays.rowSpan(m) orelse return error.NoSpan;
+ try expectEqual(want.len, span.rows);
+ for (want, 0..) |text, k| {
+ const ln = lines.items[span.line0 + k];
+ if (std.mem.indexOf(u8, ln, text) == null) {
+ std.debug.print("row {d} (body line {d}) = {s}\n", .{ k, span.line0 + k, ln });
+ return error.RowDrifted;
+ }
+ }
+}
+
+test "the click map names the rows the model picker drew" {
+ engine.g_models = "alpha-one, beta-two, gamma-three";
+ defer engine.g_models = "";
+ var m: Model = undefined;
+ m.setup(alloc);
+ defer m.deinit();
+ m.openOverlay(.model);
+ try checkSpan(&m, 80, &.{ "alpha-one", "beta-two", "gamma-three" });
+}
+
+test "the click map names the rows the effort picker drew" {
+ var m: Model = undefined;
+ m.setup(alloc);
+ defer m.deinit();
+ m.openOverlay(.effort);
+ try checkSpan(&m, 80, &.{ "low", "medium", "high", "xhigh", "max", "ultra" });
+}
+
+test "the click map names the rows the file picker drew, however long the path" {
+ var m: Model = undefined;
+ m.setup(alloc);
+ defer m.deinit();
+ m.files_cache = try alloc.dupe(u8, "src/a.zig\n" ++
+ "a/very/deeply/nested/directory/tree/that/runs/past/the/screen/edge/file.zig\n" ++
+ "docs/b.md");
+ m.openOverlay(.file);
+ try checkSpan(&m, 80, &.{ "src/a.zig", "a/very/deeply", "docs/b.md" });
+ // ...and at a width where the long path can only be a cut row.
+ try checkSpan(&m, 40, &.{ "src/a.zig", "a/very/deeply", "docs/b.md" });
+}
+
+test "the click map names the rows the settings, theme and jump panels drew" {
+ var m: Model = undefined;
+ m.setup(alloc);
+ defer m.deinit();
+ m.openOverlay(.settings);
+ try checkSpan(&m, 80, &.{ "Model", "Effort", "Mode", "Theme" });
+ m.openOverlay(.theme);
+ var want: [theme_mod.all.len][]const u8 = undefined;
+ for (theme_mod.all, 0..) |id, i| want[i] = id.label();
+ try checkSpan(&m, 80, &want);
+ try m.push(.user, "first turn");
+ try m.push(.assistant, "ok");
+ try m.push(.user, "second turn");
+ m.openOverlay(.jump);
+ try checkSpan(&m, 80, &.{ "first turn", "second turn" });
+}
+
+test "the click map names the rows the command palette drew" {
+ var m: Model = undefined;
+ m.setup(alloc);
+ defer m.deinit();
+ m.openOverlay(.palette);
+ try m.input.setValue("/th");
+ var idx: [catalog.items.len]usize = undefined;
+ const n = catalog.filter("/th", &idx);
+ try expect(n > 0 and n <= 12);
+ var want = std.array_list.Managed([]const u8).init(alloc);
+ defer want.deinit();
+ for (idx[0..n]) |i| try want.append(catalog.items[i].name);
+ try checkSpan(&m, 80, want.items);
+}
+
+test "a click on a SCROLLED overlay body still names the row under it" {
+ // The picker's window follows the highlight and the body itself scrolls
+ // once it outgrows the viewport, so both offsets have to be in the map.
+ var list = std.array_list.Managed(u8).init(alloc);
+ defer list.deinit();
+ for (0..40) |i| {
+ if (i > 0) try list.appendSlice(", ");
+ var buf: [16]u8 = undefined;
+ try list.appendSlice(try std.fmt.bufPrint(&buf, "mdl-{d:0>2}", .{i}));
+ }
+ engine.g_models = list.items;
+ defer engine.g_models = "";
+ var m: Model = undefined;
+ m.setup(alloc);
+ defer m.deinit();
+ m.openOverlay(.model);
+ m.overlay_sel = 30; // window scrolled well down the list
+ const f = try frame(&m, 80, 20);
+ defer alloc.free(f);
+ try expect(m.mid_skip > 0); // the body scrolled too
+ const row = rowOf(f, "mdl-25") orelse return error.NoModelRow;
+ _ = press(&m, 3, @intCast(row + 1));
+ try expectEqual(@as(usize, 25), m.overlay_sel);
+ try expectEqual(app.Overlay.model, m.overlay);
+}
diff --git a/TUI/effort.zig b/TUI/effort.zig
index dbe9f79b..4229f9aa 100644
--- a/TUI/effort.zig
+++ b/TUI/effort.zig
@@ -38,30 +38,32 @@ pub fn pick(self: *const Model) ?engine.Effort {
return buf[self.overlay_sel % n];
}
-pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+pub fn render(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {
+ const w = @import("chrome.zig").rowCols(width);
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.appendSlice(try theme_mod.paint(a, th.accent, theme_mod.takeCols(try std.fmt.allocPrint(a, "Effort › {s}▋", .{q}), w)));
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, theme_mod.takeCols("no matches — Esc to close", w)));
+ try out.append('\n');
return out.items;
}
const sel = self.overlay_sel % n;
for (names[0..n], 0..) |e, i| {
const mark: []const u8 = if (i == sel) "› " else " ";
const cur: []const u8 = if (e == self.effort) " (current)" else "";
- const line = try std.fmt.allocPrint(a, "{s}{s:<8} {s}{s}", .{ mark, @tagName(e), blurb(e), cur });
+ const line = theme_mod.takeCols(try std.fmt.allocPrint(a, "{s}{s:<8} {s}{s}", .{ mark, @tagName(e), blurb(e), cur }), w);
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.appendSlice(try theme_mod.paint(a, th.muted, theme_mod.takeCols("type to filter · ↑↓ move · click or Enter picks · Esc", w)));
try out.append('\n');
return out.items;
}
@@ -82,7 +84,7 @@ test "effort overlay lists levels and marks current" {
m.overlay_sel = @intFromEnum(m.effort);
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
- const text = try render(&m, arena.allocator());
+ const text = try render(&m, arena.allocator(), 80);
try std.testing.expect(std.mem.indexOf(u8, text, "Effort ›") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "low") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "high") != null);
diff --git a/TUI/files.zig b/TUI/files.zig
index e279a42a..1278431c 100644
--- a/TUI/files.zig
+++ b/TUI/files.zig
@@ -8,7 +8,9 @@ const theme_mod = @import("theme.zig");
const Model = app.Model;
pub const max_files = 512;
-const visible_rows = 10;
+/// Rows the picker draws at once — the click map reads this same window
+/// (overlays.rowSpan) instead of keeping a second copy of it.
+pub const visible_rows = 10;
/// Newline-joined `list` filtered by substring-or-subsequence `query`.
pub fn filterList(list: []const u8, query: []const u8, out: [][]const u8) usize {
@@ -25,14 +27,15 @@ pub fn filterList(list: []const u8, query: []const u8, out: [][]const u8) usize
return n;
}
-pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+pub fn render(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {
+ const w = @import("chrome.zig").rowCols(width);
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});
+ const title = theme_mod.takeCols(try std.fmt.allocPrint(a, "File › {s}▋", .{self.overlay_filter}), w);
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 })));
@@ -44,7 +47,7 @@ pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
"no file list (offline?) — Esc"
else
"no matches — type to filter, Esc";
- try out.appendSlice(try theme_mod.paint(a, th.muted, hint));
+ try out.appendSlice(try theme_mod.paint(a, th.muted, theme_mod.takeCols(hint, w)));
try out.append('\n');
return out.items;
}
@@ -54,12 +57,12 @@ pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
var i = off;
while (i < n and i < off + vis) : (i += 1) {
const mark: []const u8 = if (i == sel) "› " else " ";
- const line = try std.fmt.allocPrint(a, "{s}{s}", .{ mark, names[i] });
+ const line = theme_mod.takeCols(try std.fmt.allocPrint(a, "{s}{s}", .{ mark, names[i] }), w);
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.appendSlice(try theme_mod.paint(a, th.muted, theme_mod.takeCols("type to search · ↑↓ · click or Enter inserts · Esc", w)));
try out.append('\n');
return out.items;
}
@@ -81,7 +84,7 @@ test "render shows the filtered file rows" {
m.openOverlay(.file);
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
- const text = try render(&m, arena.allocator());
+ const text = try render(&m, arena.allocator(), 80);
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);
diff --git a/TUI/hover.zig b/TUI/hover.zig
index 76f464b0..8d36b9c6 100644
--- a/TUI/hover.zig
+++ b/TUI/hover.zig
@@ -63,11 +63,15 @@ pub const Target = enum {
sticky,
/// The composer. A press focuses it.
composer,
+ /// A row of an open list overlay. A press moves the highlight there, and a
+ /// press on the row that already has it confirms (click.zig).
+ row,
};
pub const Hit = struct {
target: Target = .none,
- /// History index the row maps to. Set for `.tool` only.
+ /// What the row maps to: a history index for `.tool`, the list item for
+ /// `.row`. Null for every target that names no element.
idx: ?usize = null,
/// The group is folded, so its mark should announce that it opens.
collapsed: bool = false,
@@ -92,9 +96,14 @@ pub const State = struct {
/// 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 .{};
+ // An overlay owns the whole screen. Its LIST rows are clickable now, so
+ // they announce themselves through the same one hit test; its title,
+ // footer and backdrop are not, and stay quiet.
+ if (m.overlay != .none) {
+ if (m.overlay == .image or y >= m.prompt_origin) return .{};
+ const item = @import("click.zig").overlayRowAt(m, y) orelse return .{};
+ return .{ .target = .row, .idx = item };
+ }
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
diff --git a/TUI/keys.zig b/TUI/keys.zig
index a0e29144..86185b8c 100644
--- a/TUI/keys.zig
+++ b/TUI/keys.zig
@@ -4,6 +4,7 @@ const std = @import("std");
const app = @import("app.zig");
const catalog = @import("catalog.zig");
+const click = @import("click.zig");
const dispatch = @import("dispatch.zig");
const hover = @import("hover.zig");
const layout_cache = @import("layout_cache.zig");
@@ -20,7 +21,12 @@ pub fn handle(self: *Model, k: Key) Effect {
if (k == .ignore) return .stay;
// Anything that is not part of the drag gesture drops the selection band
// (#529). The OSC-11 polarity reply is the terminal talking, not the user.
- if (k != .mouse and k != .bg_report) selection.clear(self);
+ if (k != .mouse and k != .bg_report) {
+ selection.clear(self);
+ // A key can only arrive with the button up: a gutter drag whose
+ // release went missing must not keep the pointer captured (click.zig).
+ self.click.gutter = false;
+ }
if (@import("nav.zig").handle(self, k)) |e| return e;
// Job-control wins overlays so Ctrl+C always does something.
if (isCtrl(k, 'c')) return ctrlC(self);
@@ -261,11 +267,18 @@ fn mouseKey(self: *Model, ev: key_mod.Mouse) Effect {
// 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);
+ // The scroll gutter owns its column BEFORE the selection can anchor there:
+ // a press on the thumb is a scrollbar gesture and never a drag-copy.
+ if (click.gutterGesture(self, ev)) return .stay;
// 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;
if (@import("image.zig").mouse(self, ev)) return .stay;
if (!ev.down or ev.btn != 0) return .stay;
+ // An open list answers the press on its own row (click.zig). It declines
+ // everything else, including the backdrop around a panel and every overlay
+ // that has no rows to pick — those keep the dismissal below.
+ if (click.press(self, ev)) |e| return e;
if (self.overlay != .none) {
self.closeOverlay();
return .stay;
diff --git a/TUI/models.zig b/TUI/models.zig
index 59530bcb..2e094d8b 100644
--- a/TUI/models.zig
+++ b/TUI/models.zig
@@ -8,7 +8,9 @@ const theme_mod = @import("theme.zig");
const Model = app.Model;
pub const max_models = 256;
-const visible_rows = 14;
+/// Rows the picker draws at once. Public so the click map (overlays.rowSpan)
+/// reads the same window the renderer draws rather than a second copy of it.
+pub const visible_rows = 14;
/// Case-insensitive substring, else fzf-style subsequence ("gpt56" → gpt-5.6).
pub fn modelMatch(name: []const u8, query: []const u8) bool {
@@ -51,7 +53,8 @@ pub fn splitModels(list: []const u8, out: [][]const u8) usize {
return filterModels(list, "", out);
}
-pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+pub fn render(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {
+ const w = @import("chrome.zig").rowCols(width);
const th = self.theme();
var names: [max_models][]const u8 = undefined;
const total = splitModels(engine.g_models, &names);
@@ -59,14 +62,15 @@ pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
var out = std.array_list.Managed(u8).init(a);
const q = self.overlay_filter;
- const title = try std.fmt.allocPrint(a, "Model › {s}▋", .{q});
+ const title = theme_mod.takeCols(try std.fmt.allocPrint(a, "Model › {s}▋", .{q}), w);
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, theme_mod.takeCols("no matches — type to filter, Esc to close", w)));
+ try out.append('\n');
return out.items;
}
@@ -78,12 +82,12 @@ pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
const mark: []const u8 = if (i == sel) "› " else " ";
const cur: []const u8 = if (std.mem.eql(u8, names[i], engine.g_model_name)) " (current)" else "";
const shown = tailId(names[i]);
- const line = try std.fmt.allocPrint(a, "{s}{s}{s}", .{ mark, shown, cur });
+ const line = theme_mod.takeCols(try std.fmt.allocPrint(a, "{s}{s}{s}", .{ mark, shown, cur }), w);
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.appendSlice(try theme_mod.paint(a, th.muted, theme_mod.takeCols("type to search · ↑↓ move · click or Enter picks · Esc", w)));
try out.append('\n');
return out.items;
}
@@ -126,7 +130,7 @@ test "model overlay typed query is a filtered list, not the dump" {
for ("deepseek") |c| m.typeOverlayFilter(c);
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
- const text = try render(&m, arena.allocator());
+ const text = try render(&m, arena.allocator(), 80);
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);
diff --git a/TUI/overlays.zig b/TUI/overlays.zig
index 05fe22f6..431cad3e 100644
--- a/TUI/overlays.zig
+++ b/TUI/overlays.zig
@@ -69,6 +69,89 @@ pub fn wheel(self: *Model, up: bool) bool {
return true;
}
+// ------------------------------------------------------------- row geometry
+
+/// Where an open list overlay's ROWS sit inside its own composed body, in body
+/// lines. render.zig lays that body out exactly like the transcript - screen
+/// row `mid_origin + k` shows body line `mid_skip + k` - so this plus those two
+/// numbers is the whole row map a click needs.
+///
+/// The header shapes are the renderers' own: a bare title (palette, theme), a
+/// title and a blank (settings, jump), or a title, a count and a blank (the
+/// searchable model / effort / file pickers). Each list row is CUT to the
+/// screen width by its renderer, never wrapped, so one item is always one line
+/// and this map can be arithmetic rather than a second pass over the bytes.
+pub const Span = struct {
+ /// Body line of the first row drawn.
+ line0: usize,
+ /// Item index that row shows - a windowed list starts partway down.
+ first: usize,
+ /// Rows drawn.
+ rows: usize,
+ /// Items in the FILTERED list, which is what `overlay_sel` indexes.
+ total: usize,
+};
+
+pub fn rowSpan(self: *const Model) ?Span {
+ const models = @import("models.zig");
+ const effort_mod = @import("effort.zig");
+ switch (self.overlay) {
+ .palette => {
+ var idx: [catalog.items.len]usize = undefined;
+ const n = catalog.filter(self.input.getValue(), &idx);
+ const show = @min(n, @as(usize, 12));
+ if (show == 0) return null;
+ return .{ .line0 = 1, .first = 0, .rows = show, .total = show };
+ },
+ .theme => return .{ .line0 = 1, .first = 0, .rows = theme_mod.all.len, .total = theme_mod.all.len },
+ .settings => return .{ .line0 = 2, .first = 0, .rows = 4, .total = 4 },
+ .jump => {
+ const total = self.userTurnCount();
+ if (total == 0) return null;
+ return .{ .line0 = 2, .first = 0, .rows = total, .total = total };
+ },
+ .effort => {
+ var buf: [effort_mod.all.len]engine.Effort = undefined;
+ const n = effort_mod.filter(self.overlay_filter, &buf);
+ if (n == 0) return null;
+ return .{ .line0 = 3, .first = 0, .rows = n, .total = n };
+ },
+ .model => {
+ var names: [models.max_models][]const u8 = undefined;
+ const n = models.filterModels(engine.g_models, self.overlay_filter, &names);
+ if (n == 0) return null;
+ return windowed(3, n, self.overlay_sel % n, models.visible_rows);
+ },
+ .file => {
+ var names: [files_mod.max_files][]const u8 = undefined;
+ const n = files_mod.filterList(self.files_cache orelse "", self.overlay_filter, &names);
+ if (n == 0) return null;
+ return windowed(3, n, self.overlay_sel % n, files_mod.visible_rows);
+ },
+ else => return null,
+ }
+}
+
+/// The scrolling window the searchable pickers draw: `vis` rows that follow the
+/// highlight, so it is always on screen and always the row Enter fires.
+fn windowed(line0: usize, n: usize, sel: usize, vis_max: usize) Span {
+ const vis = @min(vis_max, n);
+ const off = if (sel >= vis) sel - vis + 1 else 0;
+ return .{ .line0 = line0, .first = off, .rows = @min(vis, n - off), .total = n };
+}
+
+/// A click landed on item `item`. The first click on a row moves the highlight
+/// there; a click on the row that already carries it CONFIRMS, exactly as
+/// Enter does. Those two halves are also what make a double click a confirm,
+/// without a second copy of hover.zig's double-click window.
+pub fn clickRow(self: *Model, item: usize) Effect {
+ const span = rowSpan(self) orelse return .stay;
+ if (item >= span.total) return .stay;
+ if (self.overlay_sel % span.total == item) return activate(self);
+ self.overlay_sel = item;
+ return .stay;
+}
+
/// Open the @-picker immediately and load the session file list in the
/// background. Loading it inline blocked the render+input thread for up to the
/// runCapped 10s cap on the first @ of a session (#533).
@@ -79,7 +162,7 @@ pub fn openFiles(self: *Model) void {
self.openOverlay(.file);
}
-fn activate(self: *Model) Effect {
+pub fn activate(self: *Model) Effect {
switch (self.overlay) {
.palette => {
var idx: [catalog.items.len]usize = undefined;
diff --git a/TUI/render.zig b/TUI/render.zig
index c895fcd7..9a2eb67a 100644
--- a/TUI/render.zig
+++ b/TUI/render.zig
@@ -102,6 +102,14 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
const room = if (height > top_lines + card_lines + 1) height - top_lines - card_lines - 1 else 1;
const bottom_block = lastLines(bottom.items, room);
const bottom_lines = countLines(bottom_block);
+ // The completion menu rides at the TOP of the bottom block, and a short
+ // terminal trims that block from the top — so what survives is what a
+ // click can land on (click.zig). Counted here, where both the untrimmed
+ // and the trimmed shapes are in hand.
+ self.slash_rows = if (slash.len == 0)
+ 0
+ else
+ (countLines(slash) - @intFromBool(slash[slash.len - 1] == '\n')) -| (countLines(bottom.items) - bottom_lines);
self.preview_rows = card_lines;
self.mid_origin = top_lines;
self.prompt_origin = if (height > bottom_lines) height - bottom_lines else 0;
@@ -120,6 +128,9 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
if (top.len > 0 and top[top.len - 1] != '\n') try out.append('\n');
const n = if (cache) |c| c.total else mid_lines.items.len;
+ // Mid lines this frame, transcript or overlay body alike. A press below
+ // the last of them is on the backdrop, not on the panel (click.zig).
+ self.mid_total = n;
self.sticky_rows = 0;
if (n <= view_h) {
self.scroll = 0;
diff --git a/TUI/root.zig b/TUI/root.zig
index 205af871..d5cfa737 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -69,6 +69,8 @@ test {
_ = @import("theme_tint.zig");
_ = @import("hover.zig");
_ = @import("hover_tests.zig");
+ _ = @import("click.zig");
+ _ = @import("click_tests.zig");
_ = @import("osc52.zig");
_ = @import("scrollbar.zig");
_ = @import("scrollbar_tests.zig");
diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.sh
index 593e130c..461e9ace 100644
--- a/scripts/eval-tier1.sh
+++ b/scripts/eval-tier1.sh
@@ -316,6 +316,18 @@ if wanted tuiguard; then
if python3 scripts/test-tui-hover.py zig-out/bin/graff; then :; else
record_fail tuiguard
fi
+ # A single click has to DO something. Drives real SGR press/release bytes
+ # through the same virtual screen: a motionless click paints no selection
+ # band and copies nothing (while the same press WITH motion does), a press
+ # on the scroll gutter seeks and a held one drags the viewport without ever
+ # anchoring a band, an overlay row selects and then confirms, the backdrop
+ # dismisses, and the highlighted completion row runs. Each of the five is a
+ # verified gate: disabling the gutter, the drag branch, the overlay press,
+ # the slash press, or making a press anchor a band each fails a different
+ # check.
+ if python3 scripts/test-tui-click.py zig-out/bin/graff; then :; else
+ record_fail tuiguard
+ fi
# The scroll gutter has to land on a CELL and then leave no trace, and the
# OSC 52 copy has to leave the process — neither is visible to a unit test.
# Reads the thumb off the last column of the virtual screen, compares that
diff --git a/scripts/test-tui-click.py b/scripts/test-tui-click.py
new file mode 100755
index 00000000..056f6334
--- /dev/null
+++ b/scripts/test-tui-click.py
@@ -0,0 +1,346 @@
+#!/usr/bin/env python3
+"""Live proof that a SINGLE click does something.
+
+Hover, the wheel, drag-copy and the scroll thumb all shipped before this; the
+press itself still only focused the composer, toggled a fold, or dismissed
+whatever overlay was up. Every list on screen looked clickable and was not.
+This probe drives the real binary under a pty, renders its output into a
+VIRTUAL SCREEN (scripts/ptyharness.py) and reads CELLS back, so each assertion
+is about what a terminal would actually show:
+
+ 1. click-vs-drag a press and a release on the SAME cell with no motion in
+ between paints no inverse-video band and copies nothing —
+ a click is not a one-cell selection — while the SAME press
+ with motion in it does paint one,
+ 2. gutter seek a press on the last column jumps the viewport toward that
+ position, and never anchors a selection there,
+ 3. gutter drag holding the button and moving down the track walks the
+ viewport continuously, still without a band,
+ 4. list rows a click on an overlay row moves the highlight to it, a
+ second click on that row confirms it like Enter, and a
+ click on the backdrop below the panel dismisses it,
+ 5. slash menu a click on the highlighted completion row runs it.
+
+The tool fold's own click lives in scripts/test-tui-hover.py, which already
+runs a real tool loop and asserts a single click expands the group and a double
+click is one net toggle.
+
+Nothing here needs a model: `!cmd` lines run in-session, so the transcript is
+known exactly and nothing streams while the mouse is moving.
+
+Usage: python3 scripts/test-tui-click.py [path/to/graff]
+Exit 0 = pass, or a skip when there is no pty.
+"""
+
+from __future__ import annotations
+
+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")
+COLS, ROWS = 100, 30
+THUMB = "❚" # glyphs.scroll_thumb
+MARK = "CLICKMARK_QX"
+BAND = b"\x1b[7m" # the drag-selection band's inverse video
+OSC52 = re.compile(rb"\x1b\]52;c;([A-Za-z0-9+/=]*)\x07")
+WHEEL_UP = b"\x1b[<64;40;10M"
+WHEEL_DOWN = b"\x1b[<65;40;10M"
+
+
+# ----------------------------------------------------------------- helpers
+
+
+def sgr(btn, col, row, press=True):
+ return f"\x1b[<{btn};{col};{row}{'M' if press else 'm'}".encode()
+
+
+def click(h, col, row, settle=0.45):
+ """A CLICK: press and release on one cell, with nothing in between."""
+ h.inject_keys(sgr(0, col, row))
+ h.pump(0.12)
+ h.inject_keys(sgr(0, col, row, press=False))
+ h.pump(settle)
+
+
+def thumb_rows(h):
+ return [y for y in range(ROWS) if h.cell(COLS - 1, y).ch == THUMB]
+
+
+def fill(h, blocks=9):
+ for tag in range(blocks):
+ body = "%s filler %d-%d padded out so the transcript outruns the viewport"
+ lines = "".join((body % (MARK, tag, k)) + r"\n" for k in range(4))
+ h.inject_keys((r"!printf '" + lines + r"'" + "\r").encode())
+ h.pump(0.9)
+ h.pump(1.2)
+
+
+def workspace():
+ ws = tempfile.mkdtemp(prefix="tui-click-")
+ empty = os.path.join(ws, "empty-mcp.json")
+ with open(empty, "w", encoding="utf-8") as fh:
+ fh.write('{"mcpServers": {}}')
+ env = {
+ "GRAFF_MCP_CONFIG": empty,
+ "GRAFF_LEARN_AUTO": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ }
+ for name in list(os.environ):
+ if (name.startswith("GRAFF_") or name == "NO_COLOR") and name not in env:
+ env[name] = None
+ return ws, env
+
+
+# ------------------------------------------------------------------ checks
+
+
+def check_click_is_not_drag(h):
+ """(1) A motionless press+release selects nothing and copies nothing."""
+ rows = [i for i, ln in enumerate(h.screen_lines()) if MARK in ln]
+ if len(rows) < 2:
+ return f"no {MARK} rows to click on\n{h.screen_contents()}"
+ seen = len(h.raw)
+ click(h, 8, rows[1] + 1, settle=1.2)
+ after = bytes(h.raw[seen:])
+ if BAND in after:
+ return "a motionless click painted a selection band"
+ if OSC52.search(after):
+ return "a motionless click wrote the clipboard"
+ if "copied" in h.screen_contents():
+ return "a motionless click claimed it copied something"
+ # ...and the control: the SAME press, moved, is a selection.
+ seen = len(h.raw)
+ h.inject_keys(sgr(0, 8, rows[0] + 1))
+ h.pump(0.2)
+ h.inject_keys(sgr(32, 60, rows[1] + 1))
+ h.pump(0.5)
+ if BAND not in bytes(h.raw[seen:]):
+ return "a press that MOVED painted no band — the control never engaged"
+ h.inject_keys(sgr(0, 60, rows[1] + 1, press=False))
+ h.pump(0.8)
+ h.inject_keys(b"\x1b") # drop the band before anything else runs
+ h.pump(0.4)
+ return None
+
+
+def track(h):
+ """The gutter's first and last row, calibrated off the thumb's extremes."""
+ for _ in range(60):
+ h.inject_keys(WHEEL_UP)
+ h.pump(0.02)
+ h.pump(0.8)
+ top = thumb_rows(h)
+ if not top:
+ return None, "scrolling to the top raised no thumb"
+ for _ in range(80):
+ h.inject_keys(WHEEL_DOWN)
+ h.pump(0.02)
+ h.pump(0.8)
+ bottom = thumb_rows(h)
+ if not bottom:
+ return None, "the thumb vanished before the tail was reached"
+ return (top[0], bottom[-1]), None
+
+
+def to_tail(h):
+ for _ in range(80):
+ h.inject_keys(WHEEL_DOWN)
+ h.pump(0.02)
+ h.pump(0.8)
+
+
+def check_gutter_seek(h, first, last):
+ """(2) A press on the track jumps the viewport, and anchors no band.
+
+ Both directions start from the far end, so neither assertion can pass
+ because the viewport happened to already be where it was aimed."""
+ to_tail(h)
+ at_tail = thumb_rows(h)
+ if not at_tail or at_tail[-1] != last:
+ return f"the wheel did not park the viewport at the tail: {at_tail}"
+ seen = len(h.raw)
+ click(h, COLS, first + 1, settle=0.9)
+ if BAND in bytes(h.raw[seen:]):
+ return "a press on the gutter anchored a selection band"
+ rows = thumb_rows(h)
+ if not rows:
+ return "the gutter disappeared after a press on its own track"
+ if rows[0] != first:
+ return f"a press on the top of the track left the thumb at {rows[0]}, wanted {first}"
+ if f"{MARK} filler 0-0" not in h.screen_contents():
+ return f"the top of the track did not show the top of the transcript\n{h.screen_contents()}"
+ click(h, COLS, last + 1, settle=0.9)
+ rows = thumb_rows(h)
+ if not rows or rows[-1] != last:
+ return f"a press on the bottom of the track left the thumb at {rows[-1:]}, wanted {last}"
+ if f"{MARK} filler 8-3" not in h.screen_contents():
+ return "the bottom of the track did not show the tail of the transcript"
+ return None
+
+
+def check_gutter_drag(h, first, last):
+ """(3) Holding the button and moving walks the viewport, band-free."""
+ to_tail(h)
+ seen = len(h.raw)
+ h.inject_keys(sgr(0, COLS, first + 1))
+ h.pump(0.3)
+ started = thumb_rows(h)
+ if not started or started[0] != first:
+ return f"the drag's opening press did not take the thumb to the top: {started}"
+ walked = [started[:1]]
+ step = first
+ while step < last:
+ step += max(1, (last - first) // 5)
+ h.inject_keys(sgr(32, COLS, min(step, last) + 1))
+ h.pump(0.25)
+ rows = thumb_rows(h)
+ if not rows:
+ return "the gutter vanished mid-drag"
+ walked.append(rows[:1])
+ h.inject_keys(sgr(0, COLS, last + 1, press=False))
+ h.pump(0.6)
+ if BAND in bytes(h.raw[seen:]):
+ return "a gutter drag painted a selection band"
+ tops = [w[0] for w in walked]
+ if tops != sorted(tops):
+ return f"the drag did not walk the thumb monotonically down: {tops}"
+ if tops[-1] <= tops[0]:
+ return f"the drag never moved the thumb: {tops}"
+ return None
+
+
+def panel_rows(h, title):
+ """(row, text) of every marked row of the open panel under `title`."""
+ lines = h.screen_lines()
+ head = next((i for i, ln in enumerate(lines) if ln.strip().startswith(title)), None)
+ if head is None:
+ return None
+ out = []
+ for i in range(head + 1, min(head + 12, ROWS)):
+ text = lines[i].strip()
+ if not text:
+ continue
+ if text.startswith("›"):
+ text = text[1:].strip()
+ out.append((i, text.split(" (current)")[0].strip()))
+ return out
+
+
+def check_list_rows(h):
+ """(4) Select, confirm, dismiss — the three things a panel owes a click."""
+ h.inject_keys(b"/theme\r")
+ h.pump(1.0)
+ rows = panel_rows(h, "Theme")
+ if not rows or len(rows) < 3:
+ return f"the theme panel did not open\n{h.screen_contents()}"
+ row, label = rows[2]
+ click(h, 4, row + 1, settle=0.7)
+ if panel_rows(h, "Theme") is None:
+ return "the first click on a row closed the panel instead of selecting"
+ marked = [ln for ln in h.screen_lines() if "›" in ln and label in ln]
+ if not marked:
+ return f"the first click did not move the highlight onto {label!r}"
+ click(h, 4, row + 1, settle=0.9)
+ if panel_rows(h, "Theme") is not None:
+ return "the second click on the highlighted row did not confirm it"
+ if label not in h.screen_contents():
+ return f"confirming did not report the picked row {label!r}"
+ # ...and the backdrop below the panel dismisses it, like Esc.
+ h.inject_keys(b"/theme\r")
+ h.pump(1.0)
+ rows = panel_rows(h, "Theme")
+ if not rows:
+ return "the theme panel did not reopen"
+ below = rows[-1][0] + 3
+ click(h, 4, below + 1, settle=0.8)
+ if panel_rows(h, "Theme") is not None:
+ return "a click on the backdrop below the panel left it open"
+ return None
+
+
+def check_slash_row(h):
+ """(5) The completion menu's highlighted row runs on a click."""
+ h.inject_keys(b"/theme")
+ h.pump(0.8)
+ lines = h.screen_lines()
+ hit = next((i for i, ln in enumerate(lines) if "›" in ln and "/theme" in ln), None)
+ if hit is None:
+ return f"the completion menu never offered /theme\n{h.screen_contents()}"
+ click(h, 4, hit + 1, settle=1.0)
+ if panel_rows(h, "Theme") is None:
+ return "a click on the highlighted completion row did not run it"
+ h.inject_keys(b"\x1b")
+ h.pump(0.4)
+ return None
+
+
+# --------------------------------------------------------------------- run
+
+
+def run():
+ ws, env = workspace()
+ h = PtyHarness([BIN, "tui", "--yolo"], cols=COLS, rows=ROWS, cwd=ws, env=env)
+ try:
+ if not h.wait_for_boot():
+ return f"the session never reached the alt screen\n{h.screen_contents()}"
+ fill(h)
+ err = check_click_is_not_drag(h)
+ if err:
+ return err
+ bounds, err = track(h)
+ if err:
+ return err
+ first, last = bounds
+ if last - first < 4:
+ return f"the gutter track is too short to aim at: rows {first}..{last}"
+ err = check_gutter_seek(h, first, last)
+ if err:
+ return err
+ err = check_gutter_drag(h, first, last)
+ if err:
+ return err
+ err = check_list_rows(h)
+ if err:
+ return err
+ return check_slash_row(h)
+ finally:
+ h.close()
+
+
+def main():
+ if not os.path.exists(BIN):
+ print(f"tui-click: {BIN} not built — skipping")
+ return 0
+ try:
+ import pty # noqa: F401
+ except ImportError:
+ print("tui-click: no pty support here — skipping")
+ return 0
+ started = time.time()
+ try:
+ err = run()
+ except OSError as e:
+ if getattr(e, "errno", None) == 5:
+ err = "pty EIO — the graff process died mid-check"
+ else:
+ print(f"tui-click: pty unavailable ({e}) — skipping")
+ return 0
+ if err:
+ print(f" ✗ click: {err}")
+ return 1
+ print(
+ " ✓ click: a motionless click selects nothing, the gutter seeks and drags without a "
+ f"band, a list row selects then confirms, the backdrop dismisses ({time.time() - started:.0f}s)"
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())