Skip to content

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

Python

fix(tui): kitty input overhaul + grok-build parity commands

Rach Pradhan1384a583a4cb
diff --git a/TUI/app.zig b/TUI/app.zig
index 809c150d..3476d688 100644
--- a/TUI/app.zig
+++ b/TUI/app.zig
@@ -9,7 +9,7 @@ const theme_mod = @import("theme.zig");
pub const Screen = enum { welcome, agent };
pub const Focus = enum { prompt, scrollback };
-pub const Overlay = enum { none, palette, help, theme, model, effort, settings, rewind, slash, debug, image };
+pub const Overlay = enum { none, palette, help, theme, model, effort, settings, rewind, slash, debug, image, file, jump };
pub const AgentMode = enum { normal, plan, always_approve };
pub const EscArm = enum { none, clear, rewind };
pub const EntryKind = enum { user, assistant, tool, system, err, pending };
@@ -71,6 +71,8 @@ pub const Model = struct {
mid_skip: usize = 0,
now_ms: u64 = 0,
hist_idx: ?usize = null,
+ /// Newline-joined paths for the @-file picker, loaded once per session.
+ files_cache: ?[]const u8 = null,
toast: []const u8 = "",
toast_until_ms: u64 = 0,
@@ -112,6 +114,7 @@ pub const Model = struct {
if (self.goal) |g| self.alloc.free(g);
if (self.session_name) |s| self.alloc.free(s);
if (self.overlay_filter.len > 0) self.alloc.free(self.overlay_filter);
+ if (self.files_cache) |f| self.alloc.free(f);
self.input.deinit();
}
@@ -130,7 +133,7 @@ pub const Model = struct {
}
pub fn push(self: *Model, kind: EntryKind, text: []const u8) !void {
- const owned = try self.alloc.dupe(u8, text);
+ const owned = try sanitized(self.alloc, text);
errdefer self.alloc.free(owned);
try self.history.append(.{ .kind = kind, .text = owned, .folded = kind == .tool });
if (kind == .user or kind == .assistant) {
@@ -141,7 +144,9 @@ pub const Model = struct {
}
pub fn pushFmt(self: *Model, kind: EntryKind, comptime fmt: []const u8, args: anytype) !void {
- const text = try std.fmt.allocPrint(self.alloc, fmt, args);
+ const raw = try std.fmt.allocPrint(self.alloc, fmt, args);
+ defer self.alloc.free(raw);
+ const text = try sanitized(self.alloc, raw);
errdefer self.alloc.free(text);
try self.history.append(.{ .kind = kind, .text = text });
}
@@ -282,6 +287,30 @@ pub const Model = struct {
}
};
+/// History entries render verbatim inside the alt screen — drop escape
+/// sequences and stray C0 controls a tool result (or the model) may carry.
+fn sanitized(alloc: std.mem.Allocator, text: []const u8) ![]u8 {
+ if (std.mem.indexOfScalar(u8, text, 0x1b) == null and
+ std.mem.indexOfScalar(u8, text, '\r') == null) return alloc.dupe(u8, text);
+ var out = std.array_list.Managed(u8).init(alloc);
+ errdefer out.deinit();
+ var i: usize = 0;
+ while (i < text.len) {
+ const c = text[i];
+ if (c == 0x1b) {
+ i = theme_mod.skipEsc(text, i);
+ continue;
+ }
+ if ((c < 0x20 and c != '\n' and c != '\t') or c == 0x7f) {
+ i += 1;
+ continue;
+ }
+ try out.append(c);
+ i += 1;
+ }
+ return out.toOwnedSlice();
+}
+
test "cycleMode walks Normal → Plan → Always-approve" {
var m: Model = undefined;
m.setup(std.testing.allocator);
@@ -301,3 +330,11 @@ test "push user flips welcome to agent" {
try m.push(.user, "hi");
try std.testing.expectEqual(Screen.agent, m.screen);
}
+
+test "push strips raw ANSI, OSC, and CR from tool text" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.push(.tool, "⚙ bash | \x1b[31mred\x1b[0m\x1b]0;title\x07 done\r");
+ try std.testing.expectEqualStrings("⚙ bash | red done", m.history.items[0].text);
+}
diff --git a/TUI/catalog.zig b/TUI/catalog.zig
index 1a965989..9ecb9bde 100644
--- a/TUI/catalog.zig
+++ b/TUI/catalog.zig
@@ -37,6 +37,10 @@ pub const items = [_]Item{
.{ .name = "/image", .desc = "Attach an image to the next message" },
.{ .name = "/paste", .desc = "Attach the clipboard image (Ctrl+V)" },
.{ .name = "/import-claude", .desc = "Adopt Claude and Cursor MCP + skills into graff folders" },
+ .{ .name = "/jump", .desc = "Jump to a previous turn" },
+ .{ .name = "/copy", .desc = "Copy the last reply to the clipboard" },
+ .{ .name = "/btw", .desc = "Queue an aside without interrupting" },
+ .{ .name = "/vim-mode", .desc = "Vim keys in the scrollback", .aliases = &.{"/vim"} },
.{ .name = "/help", .desc = "List commands" },
.{ .name = "/doctor", .desc = "Health check" },
.{ .name = "/shortcuts", .desc = "Keyboard shortcuts", .aliases = &.{"/keys"} },
diff --git a/TUI/chrome.zig b/TUI/chrome.zig
index 490bc4a2..b2b4a117 100644
--- a/TUI/chrome.zig
+++ b/TUI/chrome.zig
@@ -131,6 +131,8 @@ pub fn overlay(self: *const Model, a: std.mem.Allocator, width: usize) ![]const
.effort => try @import("effort.zig").render(self, a),
.settings => try settingsOverlay(self, a),
.image => try @import("image.zig").render(self, a, width),
+ .file => try @import("files.zig").render(self, a),
+ .jump => try jumpOverlay(self, a),
.slash => "",
};
}
@@ -198,6 +200,34 @@ fn themeOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
return out.items;
}
+fn jumpOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+ const th = self.theme();
+ var out = std.array_list.Managed(u8).init(a);
+ try out.appendSlice(try theme_mod.paint(a, th.accent, "Jump to turn"));
+ try out.appendSlice("\n\n");
+ const total = self.userTurnCount();
+ if (total == 0) {
+ try out.appendSlice(try theme_mod.paint(a, th.muted, "no turns yet\n"));
+ return out.items;
+ }
+ const sel = self.overlay_sel % total;
+ var no: usize = 0;
+ for (self.history.items) |e| {
+ if (e.kind != .user) continue;
+ const nl = std.mem.indexOfScalar(u8, e.text, '\n') orelse e.text.len;
+ const clip = e.text[0..@min(nl, 60)];
+ const mark: []const u8 = if (no == sel) "› " else " ";
+ const line = try std.fmt.allocPrint(a, "{s}#{d} {s}", .{ mark, no + 1, clip });
+ try out.appendSlice(if (no == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
+ try out.append('\n');
+ no += 1;
+ }
+ try out.append('\n');
+ try out.appendSlice(try theme_mod.paint(a, th.muted, "↑↓ move · Enter jump · Esc"));
+ try out.append('\n');
+ return out.items;
+}
+
fn helpOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
return theme_mod.paint(a, self.theme().text,
\\Shortcuts
@@ -225,6 +255,8 @@ fn helpOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
\\ Ctrl+V attach clipboard image
\\ Ctrl+R prompt history
\\ / slash menu
+ \\ @ fuzzy file mention
+ \\ !cmd run a shell command
\\
\\Commands
\\ /quit /exit /q leave the pager
@@ -239,6 +271,10 @@ fn helpOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
\\ /plan toggle plan mode
\\ /always-approve skip permission prompts
\\ /import-claude copy Claude and Cursor MCP + skills
+ \\ /jump jump to a previous turn
+ \\ /copy copy the last reply
+ \\ /btw queue an aside mid-turn
+ \\ /vim-mode vim keys in the scrollback
);
}
diff --git a/TUI/dispatch.zig b/TUI/dispatch.zig
index e5b4d83b..e25bf04a 100644
--- a/TUI/dispatch.zig
+++ b/TUI/dispatch.zig
@@ -16,6 +16,7 @@ pub fn applyLine(self: *Model, raw: []const u8) Effect {
if (line.len == 0 and self.images.items.len == 0) return .stay;
if (line.len > 0) rememberPrompt(self, line);
if (line.len > 0 and line[0] == '/') return runCommand(self, line);
+ if (line.len > 1 and line[0] == '!') return bang(self, std.mem.trim(u8, line[1..], " \t"));
const prefix = self.takeImagesPrefix(self.alloc);
const payload = if (prefix.len == 0) line else (std.fmt.allocPrint(self.alloc, "{s}{s}", .{ prefix, line }) catch line);
if (prefix.len > 0) self.alloc.free(prefix);
@@ -153,12 +154,77 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {
self.pushFmt(.system, "ok · model={s} · cwd={s} · theme={s} · vim={s}", .{ engine.g_model_name, engine.g_cwd, @tagName(self.theme_id), onOff(self.vim_mode) }) catch {};
} else if (std.mem.eql(u8, canon, "/import-claude")) {
self.push(.system, "adopting Claude/Cursor MCP writes ~/.codegraff — run `graff mcp import` from this repo") catch {};
+ } else if (std.mem.eql(u8, canon, "/jump")) {
+ if (self.userTurnCount() == 0) {
+ self.push(.system, "nothing to jump to yet") catch {};
+ } else self.openOverlay(.jump);
+ } else if (std.mem.eql(u8, canon, "/vim-mode")) {
+ self.vim_mode = !self.vim_mode;
+ self.pushFmt(.system, "vim scrollback: {s}", .{onOff(self.vim_mode)}) catch {};
+ } else if (std.mem.eql(u8, canon, "/copy")) {
+ copyLastReply(self);
+ } else if (std.mem.eql(u8, canon, "/btw")) {
+ if (arg.len == 0) {
+ self.push(.system, "usage: /btw <aside> — queue a note without interrupting") catch {};
+ } else if (self.pending != null) {
+ if (self.alloc.dupe(u8, arg)) |dup| {
+ self.steer_queue.append(dup) catch self.alloc.free(dup);
+ self.pushFmt(.system, "↳ aside queued ({d} waiting)", .{self.steer_queue.items.len}) catch {};
+ } else |_| {}
+ } else {
+ return applyLine(self, arg);
+ }
} else {
self.pushFmt(.err, "unknown command: {s} — try /help", .{cmd}) catch {};
}
return if (self.quit_requested) .quit else .stay;
}
+/// `!cmd` — run a shell line locally (grok-style bash mode). Output stays
+/// out of the model history: EntryKind.system never reaches startJob.
+fn bang(self: *Model, cmd: []const u8) Effect {
+ if (cmd.len == 0) return .stay;
+ self.pushFmt(.system, "$ {s}", .{cmd}) catch {};
+ if (engine.g_bash_fn == null) {
+ self.push(.err, "! needs a live session (offline)") catch {};
+ return .stay;
+ }
+ if (engine.g_bash_fn.?(engine.g_turn_ctx, self.alloc, cmd)) |out| {
+ defer self.alloc.free(out);
+ self.push(.system, lastLines(out, 40)) catch {};
+ } else {
+ self.push(.err, "command failed to start") catch {};
+ }
+ return .stay;
+}
+
+/// Tail of `s` capped to `max` lines, for `!` output in the scrollback.
+fn lastLines(s: []const u8, max: usize) []const u8 {
+ var count: usize = 0;
+ var i = s.len;
+ while (i > 0) {
+ i -= 1;
+ if (s[i] == '\n') {
+ count += 1;
+ if (count == max) return s[i + 1 ..];
+ }
+ }
+ return s;
+}
+
+fn copyLastReply(self: *Model) void {
+ var i = self.history.items.len;
+ const text: ?[]const u8 = while (i > 0) {
+ i -= 1;
+ if (self.history.items[i].kind == .assistant) break self.history.items[i].text;
+ } else null;
+ if (text == null) {
+ self.push(.system, "nothing to copy yet") catch {};
+ } else if (engine.g_copy_fn) |f| {
+ self.setToast(if (f(engine.g_turn_ctx, text.?)) "copied last reply" else "copy failed");
+ } else self.setToast("clipboard needs a live session");
+}
+
pub fn rewind(self: *Model) void {
var i = self.history.items.len;
while (i > 0) : (i -= 1) {
@@ -424,3 +490,58 @@ test "/effort with no arg opens the effort menu" {
try std.testing.expectEqual(app.Effect.stay, applyLine(&m, "/effort low"));
try std.testing.expectEqual(engine.Effort.low, m.effort);
}
+
+test "! runs through the bash callback and lands in the scrollback" {
+ engine.g_bash_fn = struct {
+ fn f(_: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8) ?[]const u8 {
+ return std.fmt.allocPrint(gpa, "ran: {s}", .{cmd}) catch null;
+ }
+ }.f;
+ defer engine.g_bash_fn = null;
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ _ = applyLine(&m, "!git status");
+ try std.testing.expectEqual(@as(usize, 2), m.history.items.len);
+ try std.testing.expectEqualStrings("$ git status", m.history.items[0].text);
+ try std.testing.expectEqualStrings("ran: git status", m.history.items[1].text);
+ try std.testing.expectEqual(app.EntryKind.system, m.history.items[1].kind);
+}
+
+test "/vim-mode toggles and /jump without turns explains" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try std.testing.expect(!m.vim_mode);
+ _ = applyLine(&m, "/vim-mode");
+ try std.testing.expect(m.vim_mode);
+ _ = applyLine(&m, "/vim");
+ try std.testing.expect(!m.vim_mode);
+ _ = applyLine(&m, "/jump");
+ const last = m.history.items[m.history.items.len - 1].text;
+ try std.testing.expect(std.mem.indexOf(u8, last, "nothing to jump") != null);
+ try m.push(.user, "hi");
+ _ = applyLine(&m, "/jump");
+ try std.testing.expectEqual(app.Overlay.jump, m.overlay);
+}
+
+test "/btw queues an aside while a turn is pending" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ const job = try std.testing.allocator.create(engine.Job);
+ job.* = .{ .gpa = std.testing.allocator, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };
+ m.pending = job;
+ defer {
+ m.pending = null;
+ std.testing.allocator.destroy(job);
+ }
+ _ = applyLine(&m, "/btw remember the tests");
+ try std.testing.expectEqual(@as(usize, 1), m.steer_queue.items.len);
+ try std.testing.expectEqualStrings("remember the tests", m.steer_queue.items[0]);
+}
+
+test "lastLines caps ! output to the tail" {
+ try std.testing.expectEqualStrings("c\nd", lastLines("a\nb\nc\nd", 2));
+ try std.testing.expectEqualStrings("a\nb", lastLines("a\nb", 5));
+}
diff --git a/TUI/engine.zig b/TUI/engine.zig
index 9c376308..46d4fecd 100644
--- a/TUI/engine.zig
+++ b/TUI/engine.zig
@@ -45,6 +45,13 @@ pub const ModelFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, na
pub const CancelFn = *const fn (turn_ctx: ?*anyopaque) void;
/// Fill dest with a staged image path (return >0) or an error line (return <0).
pub const PasteFn = *const fn (turn_ctx: ?*anyopaque, dest: []u8) isize;
+/// Run a user-typed `!` shell line in the session cwd; return combined
+/// output (caller frees) or null when the spawn itself failed.
+pub const BashFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8) ?[]const u8;
+/// Newline-joined repo-relative paths for @-search (caller frees), or null.
+pub const FilesFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8;
+/// Copy text to the system clipboard; true on success.
+pub const CopyFn = *const fn (turn_ctx: ?*anyopaque, text: []const u8) bool;
pub const Job = struct {
thread: std.Thread = undefined,
@@ -66,6 +73,9 @@ pub var g_model_fn: ?ModelFn = null;
pub var g_cancel_fn: ?CancelFn = null;
pub var g_hud_fn: ?HudFn = null;
pub var g_paste_fn: ?PasteFn = null;
+pub var g_bash_fn: ?BashFn = null;
+pub var g_files_fn: ?FilesFn = null;
+pub var g_copy_fn: ?CopyFn = null;
pub var g_model_name: []const u8 = "";
pub var g_models: []const u8 = "";
pub var g_cwd: []const u8 = ".";
diff --git a/TUI/files.zig b/TUI/files.zig
new file mode 100644
index 00000000..7cf42c42
--- /dev/null
+++ b/TUI/files.zig
@@ -0,0 +1,84 @@
+//! @-mention file picker: fuzzy filter over the session file list.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const models = @import("models.zig");
+const theme_mod = @import("theme.zig");
+const Model = app.Model;
+
+pub const max_files = 512;
+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 {
+ var n: usize = 0;
+ var it = std.mem.splitScalar(u8, list, '\n');
+ while (it.next()) |raw| {
+ const name = std.mem.trim(u8, raw, " \t\r");
+ if (name.len == 0) continue;
+ if (!models.modelMatch(name, query)) continue;
+ if (n >= out.len) break;
+ out[n] = name;
+ n += 1;
+ }
+ return n;
+}
+
+pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+ const th = self.theme();
+ var names: [max_files][]const u8 = undefined;
+ const list = self.files_cache orelse "";
+ const total = filterList(list, "", &names);
+ const n = filterList(list, self.overlay_filter, &names);
+ var out = std.array_list.Managed(u8).init(a);
+ const title = try std.fmt.allocPrint(a, "File › {s}▋", .{self.overlay_filter});
+ try out.appendSlice(try theme_mod.paint(a, th.accent, title));
+ try out.append('\n');
+ try out.appendSlice(try theme_mod.paint(a, th.muted, try std.fmt.allocPrint(a, "{d}/{d}", .{ n, total })));
+ try out.appendSlice("\n\n");
+ if (n == 0) {
+ const hint = if (list.len == 0) "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.append('\n');
+ return out.items;
+ }
+ const sel = self.overlay_sel % n;
+ const vis = @min(visible_rows, n);
+ const off = if (sel >= vis) sel - vis + 1 else 0;
+ 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] });
+ try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
+ try out.append('\n');
+ }
+ try out.append('\n');
+ try out.appendSlice(try theme_mod.paint(a, th.muted, "type to search · ↑↓ · Enter insert · Esc"));
+ try out.append('\n');
+ return out.items;
+}
+
+test "filterList matches substring and subsequence" {
+ var buf: [8][]const u8 = undefined;
+ const list = "src/main.zig\nTUI/key.zig\nREADME.md";
+ try std.testing.expectEqual(@as(usize, 3), filterList(list, "", &buf));
+ try std.testing.expectEqual(@as(usize, 1), filterList(list, "tuikey", &buf));
+ try std.testing.expectEqualStrings("TUI/key.zig", buf[0]);
+ try std.testing.expectEqual(@as(usize, 1), filterList(list, "readme", &buf));
+}
+
+test "render shows the filtered file rows" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.files_cache = try std.testing.allocator.dupe(u8, "src/a.zig\ndocs/b.md");
+ m.openOverlay(.file);
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const text = try render(&m, arena.allocator());
+ try std.testing.expect(std.mem.indexOf(u8, text, "src/a.zig") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "docs/b.md") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "File ›") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "2/2") != null);
+}
diff --git a/TUI/input.zig b/TUI/input.zig
index 44056236..490cf5c7 100644
--- a/TUI/input.zig
+++ b/TUI/input.zig
@@ -77,6 +77,11 @@ pub const Input = struct {
self.buf.insert(self.cursor, c) catch return;
self.cursor += 1;
},
+ .codepoint => |cp| {
+ var b: [4]u8 = undefined;
+ const n = std.unicode.utf8Encode(cp, &b) catch return;
+ self.insertSlice(b[0..n]);
+ },
.backspace => {
if (self.cursor == 0) return;
self.pushUndo();
@@ -185,3 +190,10 @@ test "ctrl-z undoes the last edit" {
try std.testing.expectEqualStrings("", in.getValue());
try std.testing.expect(!in.undo());
}
+
+test "kitty codepoint inserts UTF-8" {
+ var in = Input.init(std.testing.allocator);
+ defer in.deinit();
+ in.handle(.{ .codepoint = 0xe9 });
+ try std.testing.expectEqualStrings("é", in.getValue());
+}
diff --git a/TUI/key.zig b/TUI/key.zig
index 6f87a5cd..42048767 100644
--- a/TUI/key.zig
+++ b/TUI/key.zig
@@ -1,4 +1,4 @@
-//! Keyboard tokens. Understands classic CSI and kitty CSI-u (Ghostty).
+//! Keyboard tokens. Understands classic CSI, SS3, and kitty CSI-u (Ghostty).
const std = @import("std");
@@ -8,6 +8,8 @@ var held: u32 = 0;
pub const Key = union(enum) {
char: u8,
+ /// Non-ASCII codepoint delivered via kitty CSI-u (é and friends).
+ codepoint: u21,
ctrl: u8,
ignore,
enter,
@@ -65,7 +67,13 @@ pub fn next(bytes: []const u8, i: *usize) ?Key {
}
fn escapeSeq(bytes: []const u8, i: *usize) ?Key {
- if (i.* >= bytes.len) return .escape;
+ if (i.* >= bytes.len) {
+ // Trailing lone ESC: the Esc key, or a sequence split across reads —
+ // we can't know yet. Rewind; run.zig delivers a real .escape only if
+ // nothing follows within its grace poll (#94).
+ i.* -= 1;
+ return null;
+ }
const c0 = bytes[i.*];
if (c0 == 0x7f or c0 == 0x08) {
i.* += 1;
@@ -83,7 +91,15 @@ fn escapeSeq(bytes: []const u8, i: *usize) ?Key {
i.* += 1;
return .shift_enter;
}
- if (c0 != '[') return .escape;
+ if (c0 == 0x1b) return .escape; // ESC ESC — deliver one, reparse the rest
+ if (c0 == 'O') return ss3(bytes, i);
+ if (c0 == ']' or c0 == 'P' or c0 == '_' or c0 == '^' or c0 == 'X') return stringSeq(bytes, i);
+ if (c0 != '[') {
+ // Unbound Alt+<char> chord: swallow both bytes so the char is not
+ // typed into the composer behind a phantom Escape.
+ i.* += 1;
+ return .ignore;
+ }
i.* += 1;
const start = i.*;
while (i.* < bytes.len) : (i.* += 1) {
@@ -92,6 +108,7 @@ fn escapeSeq(bytes: []const u8, i: *usize) ?Key {
const final = c;
const params = bytes[start..i.*];
i.* += 1;
+ if (final == 'M' and params.len == 0) return x10Mouse(bytes, i, start);
return decodeCsi(params, final);
}
}
@@ -100,11 +117,74 @@ fn escapeSeq(bytes: []const u8, i: *usize) ?Key {
return null;
}
+/// OSC/DCS/APC/PM/SOS reply on stdin (e.g. a color query answer) — consume
+/// through BEL or ST so the payload is never typed into the prompt.
+fn stringSeq(bytes: []const u8, i: *usize) ?Key {
+ var j = i.* + 1;
+ while (j < bytes.len) : (j += 1) {
+ if (bytes[j] == 0x07) {
+ i.* = j + 1;
+ return .ignore;
+ }
+ if (bytes[j] == 0x1b) {
+ if (j + 1 < bytes.len) {
+ // ST (ESC \) ends the string; any other ESC starts a new
+ // sequence — leave it for the next parse.
+ i.* = if (bytes[j + 1] == '\\') j + 2 else j;
+ return .ignore;
+ }
+ break; // ST split across reads — wait for the backslash
+ }
+ }
+ i.* -= 1; // rewind to the ESC; the terminator is still in flight
+ return null;
+}
+
+/// ESC O <final> — SS3 application keys (tmux/screen, macOS Terminal).
+fn ss3(bytes: []const u8, i: *usize) ?Key {
+ if (i.* + 1 >= bytes.len) {
+ i.* -= 1; // rewind to the ESC; the final byte is still in flight
+ return null;
+ }
+ const final = bytes[i.* + 1];
+ i.* += 2;
+ return switch (final) {
+ 'A' => .up,
+ 'B' => .down,
+ 'C' => .right,
+ 'D' => .left,
+ 'H' => .home,
+ 'F' => .end,
+ 'P' => .f1,
+ 'Q' => .f2,
+ 'M' => .enter,
+ else => .ignore,
+ };
+}
+
+/// CSI M b x y — X10 mouse fallback when the terminal ignores SGR 1006.
+/// Without this the three payload bytes are typed into the prompt as garbage
+/// on every click and pointer move.
+fn x10Mouse(bytes: []const u8, i: *usize, start: usize) ?Key {
+ if (i.* + 3 > bytes.len) {
+ i.* = start - 2;
+ return null;
+ }
+ const b = bytes[i.*] -| 32;
+ const x = bytes[i.* + 1] -| 32;
+ const y = bytes[i.* + 2] -| 32;
+ i.* += 3;
+ return .{ .mouse = .{ .btn = b, .x = x, .y = y, .down = (b & 3) != 3 } };
+}
+
fn decodeCsi(params: []const u8, final: u8) Key {
const mods = csiMods(params);
const alt = mods & 2 != 0;
const ctrl = mods & 4 != 0;
const super = mods & 8 != 0;
+ // With kitty report-event-types on, releases arrive as `CSI 1;1:3 A` etc.
+ // Acting on them double-fires every arrow / PgUp / Delete.
+ if (final != 'u' and final != 'M' and final != 'm' and eventOf(params) == 3) return .ignore;
return switch (final) {
'A' => .up,
'B' => .down,
@@ -119,16 +199,20 @@ fn decodeCsi(params: []const u8, final: u8) Key {
4, 8 => .end,
5 => .page_up,
6 => .page_down,
+ 11 => .f1,
+ 12 => .f2,
200 => .paste_start,
201 => .paste_end,
27 => fixterms(params),
- else => .escape,
+ // 2 (Insert), 13-24 (F3-F12) and friends: inert, never Escape.
+ else => .ignore,
},
'u' => kitty(params),
'P' => .f1,
'Q' => .f2,
'M', 'm' => sgrMouse(params, final == 'M'),
- else => .escape,
+ // Unknown final — a stray reply or unsupported key, not the Esc key.
+ else => .ignore,
};
}
@@ -139,33 +223,64 @@ fn csiMods(params: []const u8) u32 {
return mods;
}
+/// kitty event-type sub-param (field 2 after ':'): 1 press, 2 repeat, 3 release.
+fn eventOf(params: []const u8) u32 {
+ const s = std.mem.indexOfScalar(u8, params, ';') orelse return 1;
+ const rest = params[s + 1 ..];
+ const c = std.mem.indexOfScalar(u8, rest, ':') orelse return 1;
+ return leadingInt(rest[c + 1 ..]);
+}
+
/// CSI unicode ; mods u — kitty/ghostty. mods bit 2 = ctrl, 1 = shift.
fn kitty(params: []const u8) Key {
const code = leadingInt(params);
var mods: u32 = 0;
+ var has_mods = false;
if (std.mem.indexOfScalar(u8, params, ';')) |s| {
+ has_mods = true;
mods = leadingInt(params[s + 1 ..]);
if (mods > 0) mods -= 1; // kitty encodes mods+1
}
- const ev = kittyEvent(params);
- if (code == 57444 or code == 57448) {
- if (ev == 3) held &= ~@as(u32, 8) else held |= 8;
- return .ignore;
- }
- if (code == 57443 or code == 57447) {
- if (ev == 3) held &= ~@as(u32, 2) else held |= 2;
- return .ignore;
- }
- if (code >= 57441 and code <= 57448) return .ignore;
+ const ev = eventOf(params);
+ if (code >= 57344 and code <= 57454) return functional(code, mods, ev);
if (ev == 3) return .ignore;
+ // A live key with an explicit mods field is ground truth for held
+ // modifiers — resync so a missed release can't latch alt/super forever.
+ if (has_mods) held = mods & 10;
return mapCode(code, mods);
}
-fn kittyEvent(params: []const u8) u32 {
- const s = std.mem.indexOfScalar(u8, params, ';') orelse return 1;
- const rest = params[s + 1 ..];
- const c = std.mem.indexOfScalar(u8, rest, ':') orelse return 1;
- return leadingInt(rest[c + 1 ..]);
+/// kitty functional block (57344-57454): modifiers, locks, F13+, media, keypad.
+fn functional(code: u32, mods: u32, ev: u32) Key {
+ // Real kitty table: 57443/57449 = L/R Alt, 57444/57450 = L/R Super.
+ // (57447/57448 are Right-Shift/Right-Ctrl — NOT alt/super.)
+ const bit: u32 = switch (code) {
+ 57443, 57449 => 2,
+ 57444, 57450 => 8,
+ else => 0,
+ };
+ if (bit != 0) {
+ if (ev == 3) held &= ~bit else held |= bit;
+ return .ignore;
+ }
+ if (ev == 3) return .ignore;
+ return switch (code) {
+ 57344 => .escape,
+ 57345, 57414 => if (mods & 3 != 0) .shift_enter else .enter,
+ 57346 => if (mods & 1 != 0) .shift_tab else .tab,
+ 57347 => mapCode(127, mods),
+ 57349, 57426 => .delete,
+ 57350, 57417 => .left,
+ 57351, 57418 => .right,
+ 57352, 57419 => .up,
+ 57353, 57420 => .down,
+ 57354, 57421 => .page_up,
+ 57355, 57422 => .page_down,
+ 57356, 57423 => .home,
+ 57357, 57424 => .end,
+ // Locks, PrintScreen, remaining keypad, media, F13+: inert.
+ else => .ignore,
+ };
}
fn fixterms(params: []const u8) Key {
@@ -197,11 +312,14 @@ fn mapCode(code: u32, mods: u32) Key {
if (ctrl and ch >= 'A' and ch <= 'Z') return .{ .ctrl = ch + 32 };
return .{ .char = ch };
}
- return .escape;
+ if (code >= 57344 and code <= 57454) return .ignore; // functional block, handled upstream
+ if (code >= 128 and code <= 0x10ffff) return .{ .codepoint = @intCast(code) };
+ // Unknown code: inert. Only a real Esc (27) may become .escape.
+ return .ignore;
}
fn sgrMouse(params: []const u8, down: bool) Key {
- if (params.len == 0 or params[0] != '<') return .escape;
+ if (params.len == 0 or params[0] != '<') return .ignore;
var it = std.mem.splitScalar(u8, params[1..], ';');
const btn = leadingInt(it.next() orelse "0");
const x = leadingInt(it.next() orelse "1");
@@ -257,6 +375,7 @@ test "next: letters, enter, ctrl-c, arrows, kitty ctrl-p" {
try std.testing.expectEqual(Key{ .char = 0xa9 }, next("\xc3\xa9", &i).?);
i = 0;
try std.testing.expectEqual(Key.delete_to_start, next("\x1b[127;9u", &i).?);
+ held = 0;
i = 0;
try std.testing.expectEqual(Key.delete_word, next("\x1b\x7f", &i).?);
i = 0;
@@ -280,3 +399,126 @@ test "next: letters, enter, ctrl-c, arrows, kitty ctrl-p" {
try std.testing.expectEqual(Key.delete_to_start, next("\x7f", &i).?);
held = 0;
}
+
+test "lone trailing ESC stays pending, not an instant Escape" {
+ var i: usize = 0;
+ try std.testing.expect(next("\x1b", &i) == null);
+ try std.testing.expectEqual(@as(usize, 0), i);
+}
+
+test "ESC ESC delivers an Escape and leaves the second pending" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key.escape, next("\x1b\x1b", &i).?);
+ try std.testing.expectEqual(@as(usize, 1), i);
+ try std.testing.expect(next("\x1b\x1b", &i) == null);
+ try std.testing.expectEqual(@as(usize, 1), i);
+}
+
+test "kitty release events never fire keys" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[1;1:3A", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[3;1:3~", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[5;1:3~", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[97;1:3u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.up, next("\x1b[1;1:2A", &i).?); // repeat acts
+}
+
+test "right-side modifiers follow the real kitty table, never Escape" {
+ held = 0;
+ var i: usize = 0;
+ // Right-Shift (57447) and Right-Ctrl (57448) must not latch held bits.
+ try std.testing.expectEqual(Key.ignore, next("\x1b[57447;1:1u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[57448;1:1u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);
+ // Right-Alt (57449) latches alt; its release clears it.
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[57449;1:1u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.delete_word, next("\x7f", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[57449;1:3u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);
+ held = 0;
+}
+
+test "unknown keys and replies are inert, never Escape" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[57376u", &i).?); // F13
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[17~", &i).?); // F6
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[2~", &i).?); // Insert
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[?1;2c", &i).?); // DA reply
+}
+
+test "kitty functional arrows and keypad map; a stale super latch resyncs" {
+ held = 8; // pretend we missed the Super release
+ var i: usize = 0;
+ try std.testing.expectEqual(Key.up, next("\x1b[57352u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key{ .char = 'a' }, next("\x1b[97;1u", &i).?);
+ try std.testing.expectEqual(@as(u32, 0), held);
+ i = 0;
+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.enter, next("\x1b[57414u", &i).?); // KP_ENTER
+ held = 0;
+}
+
+test "SS3 application keys and unbound alt-chords" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key.up, next("\x1bOA", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.f1, next("\x1bOP", &i).?);
+ i = 0;
+ // Split SS3 stays pending.
+ try std.testing.expect(next("\x1bO", &i) == null);
+ try std.testing.expectEqual(@as(usize, 0), i);
+ i = 0;
+ // Unbound Alt+p swallows both bytes — no phantom Escape, no stray 'p'.
+ try std.testing.expectEqual(Key.ignore, next("\x1bp", &i).?);
+ try std.testing.expectEqual(@as(usize, 2), i);
+ try std.testing.expect(next("\x1bp", &i) == null);
+}
+
+test "X10 mouse fallback consumes its payload instead of typing it" {
+ var i: usize = 0;
+ const ev = next("\x1b[M\x20\x2c\x28", &i).?;
+ try std.testing.expect(ev == .mouse);
+ try std.testing.expectEqual(@as(u8, 0), ev.mouse.btn);
+ try std.testing.expectEqual(@as(u16, 12), ev.mouse.x);
+ try std.testing.expectEqual(@as(u16, 8), ev.mouse.y);
+ try std.testing.expect(ev.mouse.down);
+ try std.testing.expectEqual(@as(usize, 6), i);
+ i = 0;
+ // Split short — wait for the rest.
+ try std.testing.expect(next("\x1b[M\x20", &i) == null);
+ try std.testing.expectEqual(@as(usize, 0), i);
+}
+
+test "non-ASCII CSI-u codepoints type text instead of Escape" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key{ .codepoint = 0xe9 }, next("\x1b[233;1u", &i).?);
+ held = 0;
+}
+
+test "OSC and APC replies on stdin are consumed, never typed" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b]11;rgb:14/14/14\x07", &i).?);
+ try std.testing.expectEqual(@as(usize, 18), i);
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b_Gi=1;OK\x1b\\", &i).?);
+ try std.testing.expectEqual(@as(usize, 11), i);
+ i = 0;
+ // Unterminated reply stays pending until the rest arrives.
+ try std.testing.expect(next("\x1b]11;rgb:14", &i) == null);
+ try std.testing.expectEqual(@as(usize, 0), i);
+}
diff --git a/TUI/keys.zig b/TUI/keys.zig
index fd9306ad..2ddc967b 100644
--- a/TUI/keys.zig
+++ b/TUI/keys.zig
@@ -41,13 +41,20 @@ pub fn handle(self: *Model, k: Key) Effect {
switch (k) {
.enter => self.input.handle(.{ .char = '\n' }),
.char => |c| self.input.handle(.{ .char = c }),
+ .codepoint => self.input.handle(k),
else => {},
}
return .stay;
}
- if (self.overlay != .none) return overlayKey(self, k);
+ if (self.overlay != .none) return @import("overlays.zig").key(self, k);
if (slashOpen(self) and slashKey(self, k)) return .stay;
+ if (isChar(k, '@') and self.focus == .prompt and !slashOpen(self)) {
+ // Grok-style file mention: keep the typed @, open the fuzzy picker.
+ self.input.handle(.{ .char = '@' });
+ @import("overlays.zig").openFiles(self);
+ return .stay;
+ }
if (k == .escape) return esc(self);
if (isCtrl(k, 'p') or (isChar(k, '?') and std.mem.trim(u8, self.input.getValue(), " \t").len == 0)) {
@@ -176,7 +183,7 @@ fn scrollbackKey(self: *Model, k: Key) Effect {
return .stay;
}
if (!self.vim_mode) {
- if (k == .char or k == .ctrl) {
+ if (k == .char or k == .codepoint or k == .ctrl) {
self.focus = .prompt;
return promptKey(self, k);
}
@@ -224,97 +231,7 @@ fn mouseKey(self: *Model, ev: key_mod.Mouse) Effect {
return .stay;
}
-fn overlayKey(self: *Model, k: Key) Effect {
- if (@import("image.zig").key(self, k)) return .stay;
- if (k == .escape) {
- self.closeOverlay();
- return .stay;
- }
- if (k == .up) {
- self.overlay_sel -|= 1;
- return .stay;
- }
- if (k == .down) {
- self.overlay_sel += 1;
- return .stay;
- }
- if (k == .enter) return activateOverlay(self);
- if (self.overlay == .model or self.overlay == .effort) {
- switch (k) {
- .char => |c| self.typeOverlayFilter(c),
- .backspace => self.backspaceOverlayFilter(),
- else => {},
- }
- return .stay;
- }
- if (self.overlay == .palette or self.overlay == .theme) {
- self.input.handle(k);
- }
- return .stay;
-}
-fn activateOverlay(self: *Model) Effect {
- switch (self.overlay) {
- .palette => {
- var idx: [catalog.items.len]usize = undefined;
- const n = catalog.filter(self.input.getValue(), &idx);
- if (n == 0) return .stay;
- const pick = catalog.items[idx[@min(self.overlay_sel, n - 1)]];
- self.closeOverlay();
- self.input.setValue("") catch {};
- return dispatch.runCommand(self, pick.name);
- },
- .theme => {
- const id: theme_mod.Id = @enumFromInt(self.overlay_sel % theme_mod.all.len);
- self.theme_id = id;
- self.closeOverlay();
- self.setToast(id.label());
- },
- .rewind => {
- self.closeOverlay();
- dispatch.rewind(self);
- },
- .model => {
- const models = @import("models.zig");
- var names: [models.max_models][]const u8 = undefined;
- const n = models.filterModels(engine.g_models, self.overlay_filter, &names);
- const sel = if (n == 0) 0 else self.overlay_sel % n;
- self.closeOverlay();
- if (n == 0) return .stay;
- const pick = names[sel];
- if (engine.g_model_fn) |f| {
- if (f(engine.g_turn_ctx, self.alloc, pick)) |nm| {
- engine.g_model_name = nm;
- self.setToast(nm);
- } else self.setToast("couldn't switch");
- } else {
- engine.g_model_name = pick;
- self.setToast(pick);
- }
- },
- .effort => {
- if (@import("effort.zig").pick(self)) |e| {
- self.effort = e;
- self.setToast(@tagName(e));
- }
- self.closeOverlay();
- },
- .settings => {
- const which = self.overlay_sel % 4;
- switch (which) {
- 0 => self.openOverlay(.model),
- 1 => {
- self.openOverlay(.effort);
- self.overlay_sel = @intFromEnum(self.effort);
- },
- 2 => self.cycleMode(),
- else => self.openOverlay(.theme),
- }
- },
- else => self.closeOverlay(),
- }
- return .stay;
-}
fn slashOpen(self: *const Model) bool {
const v = self.input.getValue();
diff --git a/TUI/nav.zig b/TUI/nav.zig
index 2e50cc28..1d145be1 100644
--- a/TUI/nav.zig
+++ b/TUI/nav.zig
@@ -60,6 +60,24 @@ fn ctrlN(self: *Model) void {
self.setToast("press Ctrl+N again to start a new session");
}
+/// Land the viewport on history entry `idx` (used by /jump).
+pub fn jumpTo(self: *Model, idx: usize) void {
+ self.selected = idx;
+ self.focus = .scrollback;
+ self.follow = false;
+ const sb = @import("scrollback.zig");
+ const width = if (self.last_term_width == 0) 80 else self.last_term_width;
+ const total = sb.totalVisualLines(self, width);
+ const at = sb.visualOfIndex(self, idx, width) orelse return;
+ const view_h = if (self.prompt_origin > self.mid_origin) self.prompt_origin - self.mid_origin else 8;
+ if (total <= view_h) {
+ self.scroll = 0;
+ return;
+ }
+ const max_scroll = total - view_h;
+ self.scroll = if (at >= max_scroll) 0 else max_scroll - at;
+}
+
fn jumpTurn(self: *Model, dir: i32) void {
if (self.history.items.len == 0) return;
var i = self.selected;
diff --git a/TUI/overlays.zig b/TUI/overlays.zig
new file mode 100644
index 00000000..037fbe9a
--- /dev/null
+++ b/TUI/overlays.zig
@@ -0,0 +1,170 @@
+//! Overlay key routing + activation (palette, theme, model, effort, settings,
+//! rewind, @-file picker, /jump). Split from keys.zig for the line budget.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const catalog = @import("catalog.zig");
+const dispatch = @import("dispatch.zig");
+const engine = @import("engine.zig");
+const files_mod = @import("files.zig");
+const theme_mod = @import("theme.zig");
+const Key = @import("key.zig").Key;
+const Model = app.Model;
+const Effect = app.Effect;
+
+pub fn key(self: *Model, k: Key) Effect {
+ if (@import("image.zig").key(self, k)) return .stay;
+ if (k == .escape) {
+ self.closeOverlay();
+ return .stay;
+ }
+ if (k == .up) {
+ self.overlay_sel -|= 1;
+ return .stay;
+ }
+ if (k == .down) {
+ self.overlay_sel += 1;
+ return .stay;
+ }
+ if (k == .enter) return activate(self);
+ if (self.overlay == .model or self.overlay == .effort or self.overlay == .file) {
+ switch (k) {
+ .char => |c| self.typeOverlayFilter(c),
+ .backspace => self.backspaceOverlayFilter(),
+ else => {},
+ }
+ return .stay;
+ }
+ if (self.overlay == .palette or self.overlay == .theme) {
+ self.input.handle(k);
+ }
+ return .stay;
+}
+
+/// Load the session file list once, then open the @-picker.
+pub fn openFiles(self: *Model) void {
+ if (self.files_cache == null) {
+ if (engine.g_files_fn) |f| self.files_cache = f(engine.g_turn_ctx, self.alloc);
+ }
+ self.openOverlay(.file);
+}
+
+fn activate(self: *Model) Effect {
+ switch (self.overlay) {
+ .palette => {
+ var idx: [catalog.items.len]usize = undefined;
+ const n = catalog.filter(self.input.getValue(), &idx);
+ if (n == 0) return .stay;
+ const pick = catalog.items[idx[@min(self.overlay_sel, n - 1)]];
+ self.closeOverlay();
+ self.input.setValue("") catch {};
+ return dispatch.runCommand(self, pick.name);
+ },
+ .theme => {
+ const id: theme_mod.Id = @enumFromInt(self.overlay_sel % theme_mod.all.len);
+ self.theme_id = id;
+ self.closeOverlay();
+ self.setToast(id.label());
+ },
+ .rewind => {
+ self.closeOverlay();
+ dispatch.rewind(self);
+ },
+ .model => {
+ const models = @import("models.zig");
+ var names: [models.max_models][]const u8 = undefined;
+ const n = models.filterModels(engine.g_models, self.overlay_filter, &names);
+ const sel = if (n == 0) 0 else self.overlay_sel % n;
+ self.closeOverlay();
+ if (n == 0) return .stay;
+ const pick = names[sel];
+ if (engine.g_model_fn) |f| {
+ if (f(engine.g_turn_ctx, self.alloc, pick)) |nm| {
+ engine.g_model_name = nm;
+ self.setToast(nm);
+ } else self.setToast("couldn't switch");
+ } else {
+ engine.g_model_name = pick;
+ self.setToast(pick);
+ }
+ },
+ .effort => {
+ if (@import("effort.zig").pick(self)) |e| {
+ self.effort = e;
+ self.setToast(@tagName(e));
+ }
+ self.closeOverlay();
+ },
+ .settings => {
+ const which = self.overlay_sel % 4;
+ switch (which) {
+ 0 => self.openOverlay(.model),
+ 1 => {
+ self.openOverlay(.effort);
+ self.overlay_sel = @intFromEnum(self.effort);
+ },
+ 2 => self.cycleMode(),
+ else => self.openOverlay(.theme),
+ }
+ },
+ .file => {
+ var names: [files_mod.max_files][]const u8 = undefined;
+ const n = files_mod.filterList(self.files_cache orelse "", self.overlay_filter, &names);
+ const sel = if (n == 0) 0 else self.overlay_sel % n;
+ self.closeOverlay();
+ if (n == 0) return .stay;
+ // names point into files_cache, which closeOverlay leaves alone.
+ self.input.insertSlice(names[sel]);
+ self.input.handle(.{ .char = ' ' });
+ self.focus = .prompt;
+ },
+ .jump => {
+ const total = self.userTurnCount();
+ const sel = if (total == 0) 0 else self.overlay_sel % total;
+ self.closeOverlay();
+ if (total == 0) return .stay;
+ var seen: usize = 0;
+ for (self.history.items, 0..) |e, i| {
+ if (e.kind != .user) continue;
+ if (seen == sel) {
+ @import("nav.zig").jumpTo(self, i);
+ break;
+ }
+ seen += 1;
+ }
+ },
+ else => self.closeOverlay(),
+ }
+ return .stay;
+}
+
+test "file overlay Enter inserts the picked path after the @" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.files_cache = try std.testing.allocator.dupe(u8, "src/a.zig\ndocs/b.md");
+ try m.input.setValue("look at @");
+ m.openOverlay(.file);
+ for ("bmd") |c| m.typeOverlayFilter(c);
+ _ = key(&m, .enter);
+ try std.testing.expectEqual(app.Overlay.none, m.overlay);
+ try std.testing.expectEqualStrings("look at @docs/b.md ", m.input.getValue());
+}
+
+test "jump overlay Enter selects the chosen user turn" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.push(.user, "one");
+ try m.push(.assistant, "a");
+ try m.push(.user, "two");
+ try m.push(.assistant, "b");
+ m.openOverlay(.jump);
+ m.overlay_sel = 1;
+ _ = key(&m, .enter);
+ try std.testing.expectEqual(app.Overlay.none, m.overlay);
+ try std.testing.expectEqual(@as(usize, 2), m.selected);
+ try std.testing.expect(m.focus == .scrollback);
+ try std.testing.expect(!m.follow);
+}
diff --git a/TUI/restore.zig b/TUI/restore.zig
new file mode 100644
index 00000000..870a23e2
--- /dev/null
+++ b/TUI/restore.zig
@@ -0,0 +1,77 @@
+//! Terminal-state restoration that must survive abnormal exits.
+//! The kitty keyboard pop and alt-screen exit live here so SIGTERM/SIGHUP
+//! (or an abort) cannot strand the shell in raw fullscreen mode with the
+//! kitty protocol still pushed, the cursor hidden, and mouse tracking on.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const tty = @import("tty.zig");
+
+/// Inverse of run.zig's enable string: modifyOtherKeys off, kitty pop,
+/// autowrap on, mouse off (1006/1003/1000), bracketed paste off, cursor
+/// visible. The alt-screen exit stays last so everything lands on the
+/// primary screen.
+pub const seq = "\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l";
+
+var armed = std.atomic.Value(bool).init(false);
+var saved: tty.RawState = undefined;
+
+/// Remember the pre-raw termios and hook fatal signals. Test builds skip the
+/// signal hooks so the test runner's dispositions stay untouched.
+pub fn arm(orig: tty.RawState) void {
+ saved = orig;
+ armed.store(true, .release);
+ if (builtin.os.tag == .windows or builtin.is_test) return;
+ installFatalHandlers();
+}
+
+pub fn disarm() void {
+ armed.store(false, .release);
+}
+
+fn installFatalHandlers() void {
+ if (builtin.os.tag == .windows) return;
+ var sa = std.posix.Sigaction{
+ .handler = .{ .handler = onFatal },
+ .mask = std.posix.sigemptyset(),
+ .flags = 0,
+ };
+ const fatal = [_]std.posix.SIG{ .TERM, .HUP, .INT, .QUIT, .ABRT };
+ for (fatal) |sig| std.posix.sigaction(sig, &sa, null);
+}
+
+/// Async-signal-safe: one raw write + tcsetattr, nothing else.
+pub fn emergency() void {
+ if (builtin.os.tag == .windows) return;
+ if (!armed.swap(false, .acq_rel)) return;
+ _ = std.posix.system.write(std.posix.STDOUT_FILENO, seq.ptr, seq.len);
+ std.posix.tcsetattr(std.posix.STDIN_FILENO, .NOW, saved) catch {};
+}
+
+fn onFatal(sig: std.posix.SIG) callconv(.c) void {
+ emergency();
+ var dfl = std.posix.Sigaction{
+ .handler = .{ .handler = std.posix.SIG.DFL },
+ .mask = std.posix.sigemptyset(),
+ .flags = 0,
+ };
+ std.posix.sigaction(sig, &dfl, null);
+ std.posix.raise(sig) catch {};
+}
+
+test "restore pops kitty before leaving the alt screen, cursor back on" {
+ const kitty_pop = std.mem.indexOf(u8, seq, "\x1b[<u").?;
+ const alt_exit = std.mem.indexOf(u8, seq, "\x1b[?1049l").?;
+ try std.testing.expect(kitty_pop < alt_exit);
+ try std.testing.expect(std.mem.endsWith(u8, seq, "\x1b[?1049l"));
+ try std.testing.expect(std.mem.indexOf(u8, seq, "\x1b[?25h") != null);
+ try std.testing.expect(std.mem.indexOf(u8, seq, "\x1b[?2004l") != null);
+}
+
+test "arm and disarm toggle the emergency latch" {
+ try std.testing.expect(!armed.load(.acquire));
+ arm(if (builtin.os.tag == .windows) .{} else undefined);
+ try std.testing.expect(armed.load(.acquire));
+ disarm();
+ try std.testing.expect(!armed.load(.acquire));
+}
diff --git a/TUI/root.zig b/TUI/root.zig
index 156d8f1d..70ce760d 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -49,6 +49,9 @@ test {
_ = @import("sim.zig");
_ = @import("render.zig");
_ = @import("tty.zig");
+ _ = @import("restore.zig");
+ _ = @import("files.zig");
+ _ = @import("overlays.zig");
_ = run_mod;
}
diff --git a/TUI/run.zig b/TUI/run.zig
index 1d2f2307..24ee32e5 100644
--- a/TUI/run.zig
+++ b/TUI/run.zig
@@ -9,11 +9,18 @@ const engine = @import("engine.zig");
const key_mod = @import("key.zig");
const keys = @import("keys.zig");
const render_mod = @import("render.zig");
+const restore_mod = @import("restore.zig");
const theme_mod = @import("theme.zig");
const turn = @import("turn.zig");
const tty = @import("tty.zig");
const Model = app.Model;
+// 1000/1003/1006: click + hover + wheel as buttons 64/65 (not arrows).
+// 2004: bracketed paste. 7l: no autowrap into the prompt.
+// >11u: kitty disambiguate + event types + all-keys (Cmd+Delete / Super latch).
+// >4;2m: xterm modifyOtherKeys so Super+Backspace also arrives as CSI 27;9;127~.
+const enable_seq = "\x1b[?1049h\x1b[?25l\x1b[?2004h\x1b[?1000h\x1b[?1003h\x1b[?1006h\x1b[?7l\x1b[>11u\x1b[>4;2m";
+
pub const RunOpts = struct {
turn_ctx: ?*anyopaque = null,
turn_fn: ?engine.TurnFn = null,
@@ -25,6 +32,9 @@ pub const RunOpts = struct {
yolo: bool = false,
hud_fn: ?engine.HudFn = null,
paste_fn: ?engine.PasteFn = null,
+ bash_fn: ?engine.BashFn = null,
+ files_fn: ?engine.FilesFn = null,
+ copy_fn: ?engine.CopyFn = null,
};
pub fn run(
@@ -40,6 +50,9 @@ pub fn run(
engine.g_cancel_fn = opts.cancel_fn;
engine.g_hud_fn = opts.hud_fn;
engine.g_paste_fn = opts.paste_fn;
+ engine.g_bash_fn = opts.bash_fn;
+ engine.g_files_fn = opts.files_fn;
+ engine.g_copy_fn = opts.copy_fn;
engine.g_model_name = opts.model_name;
engine.g_models = opts.models;
engine.g_cwd = opts.cwd;
@@ -50,24 +63,24 @@ pub fn run(
if (opts.yolo) m.mode = .always_approve;
var raw = tty.enterRaw() orelse return error.NotATty;
+ restore_mod.arm(raw);
+ defer restore_mod.disarm();
defer tty.restore(raw);
var out_buf: [64 * 1024]u8 = undefined;
var stdout = Io.File.stdout().writer(io, &out_buf);
const w = &stdout.interface;
- // 1000/1003/1006: click + hover + wheel as buttons 64/65 (not arrows).
- // 2004: bracketed paste. 7l: no autowrap into the prompt.
- // >11u: kitty disambiguate + event types + all-keys (Cmd+Delete / Super latch).
- // >4;2m: xterm modifyOtherKeys so Super+Backspace also arrives as CSI 27;9;127~.
- w.writeAll("\x1b[?1049h\x1b[?25l\x1b[?2004h\x1b[?1000h\x1b[?1003h\x1b[?1006h\x1b[?7l\x1b[>11u\x1b[>4;2m") catch {};
+ w.writeAll(enable_seq) catch {};
w.flush() catch {};
defer {
- w.writeAll("\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l") catch {};
+ w.writeAll(restore_mod.seq) catch {};
w.flush() catch {};
}
var inbuf: [4096]u8 = undefined;
var pending_len: usize = 0;
+ var esc_stall: u8 = 0;
+ var zero_reads: u8 = 0;
var last_hash: u64 = 0;
var saw_gfx: bool = false;
var prev: []u8 = &.{};
@@ -83,9 +96,6 @@ pub fn run(
}
const cols = @max(tty.cols(), @as(usize, 40));
const rows = @max(tty.rows(), @as(usize, 12));
- // Always drop leftover Kitty layers — they outlive cell redraws.
- w.writeAll("\x1b_Ga=d,d=A,q=2\x1b\\") catch {};
- w.flush() catch {};
const frame = render_mod.render(&m, gpa, cols, rows, m.now_ms) catch "tui: render error";
defer gpa.free(frame);
const hash = std.hash.Wyhash.hash(0, frame);
@@ -103,14 +113,31 @@ pub fn run(
saw_gfx = has_gfx;
}
- const wait: i32 = if (m.pending != null) 50 else 200;
- if (!tty.poll(wait)) continue;
+ // Short wait while an unfinished escape sequence is pending: if
+ // nothing follows, the lone ESC was a real Escape keypress (#94).
+ const wait: i32 = if (pending_len > 0) 25 else if (m.pending != null) 50 else 200;
+ if (!tty.poll(wait)) {
+ if (pending_len > 0) {
+ esc_stall += 1;
+ if (esc_stall >= 2) {
+ if (inbuf[0] == 0x1b and keys.handle(&m, .escape) == .quit) m.running = false;
+ pending_len = 0;
+ esc_stall = 0;
+ }
+ }
+ continue;
+ }
+ esc_stall = 0;
const got = tty.readStdin(inbuf[pending_len..]);
- const n = pending_len + got;
- if (n == 0) {
- pending_len = 0;
+ if (got == 0) {
+ // poll says readable but read gives nothing: hangup or transient
+ // error. Three in a row means the TTY is gone.
+ zero_reads += 1;
+ if (zero_reads >= 3) m.running = false;
continue;
}
+ zero_reads = 0;
+ const n = pending_len + got;
var i: usize = 0;
while (key_mod.next(inbuf[0..n], &i)) |k| {
switch (keys.handle(&m, k)) {
@@ -119,7 +146,13 @@ pub fn run(
m.running = false;
break;
},
- .background => parkToShell(io, w, &raw),
+ .background => {
+ parkToShell(io, w, &raw);
+ // Full repaint after fg — the diff baseline is stale.
+ last_hash = 0;
+ if (prev.len != 0) gpa.free(prev);
+ prev = &.{};
+ },
}
}
if (i < n) {
@@ -131,14 +164,14 @@ pub fn run(
}
fn parkToShell(io: Io, w: *Io.Writer, raw: *tty.RawState) void {
- w.writeAll("\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l") catch {};
+ w.writeAll(restore_mod.seq) catch {};
w.flush() catch {};
tty.restore(raw.*);
if (builtin.os.tag != .windows) {
std.posix.raise(std.posix.SIG.TSTP) catch {};
}
raw.* = tty.enterRaw() orelse raw.*;
- w.writeAll("\x1b[?1049h\x1b[?25l\x1b[?2004h\x1b[?1000h\x1b[?1003h\x1b[?1006h\x1b[?7l\x1b[>11u\x1b[>4;2m") catch {};
+ w.writeAll(enable_seq) catch {};
w.flush() catch {};
_ = io;
}
diff --git a/TUI/scrollback.zig b/TUI/scrollback.zig
index 094c3776..1958d928 100644
--- a/TUI/scrollback.zig
+++ b/TUI/scrollback.zig
@@ -93,6 +93,45 @@ pub fn indexAtVisual(self: *const Model, visual_row: usize, width: usize) ?usize
return null;
}
+/// Total visual rows of the transcript at `width` (mirrors render()).
+pub fn totalVisualLines(self: *const Model, width: usize) usize {
+ var arena = std.heap.ArenaAllocator.init(self.alloc);
+ defer arena.deinit();
+ const text = render(self, arena.allocator(), width, self.now_ms) catch return 0;
+ return lineCount(text);
+}
+
+/// First visual row of entry `idx` (a collapsed group maps to its start).
+pub fn visualOfIndex(self: *const Model, idx: usize, width: usize) ?usize {
+ var arena = std.heap.ArenaAllocator.init(self.alloc);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var v: usize = 0;
+ var i: usize = 0;
+ while (i < self.history.items.len) {
+ if (self.history.items[i].kind == .tool) {
+ const run = self.toolRun(i);
+ if (idx >= run.start and idx < run.end) return v;
+ const collapsed = self.history.items[run.start].folded;
+ if (collapsed) {
+ v += lineCount(summary(self, a, run.start, run.end, false) catch "");
+ } else {
+ var t = run.start;
+ while (t < run.end) {
+ v += lineCount(toolVisual(self, a, t, run.end, width, self.now_ms, false) catch "");
+ t = nextTool(self, t, run.end);
+ }
+ }
+ i = run.end;
+ continue;
+ }
+ if (i == idx) return v;
+ v += lineCount(row(self, a, i, self.history.items[i], width, self.now_ms, false) catch "");
+ i += 1;
+ }
+ return null;
+}
+
fn lineCount(s: []const u8) usize {
if (s.len == 0) return 1;
return std.mem.count(u8, s, "\n") + 1;
@@ -302,12 +341,7 @@ fn strip(a: std.mem.Allocator, s: []const u8) []const u8 {
var i: usize = 0;
while (i < s.len) {
if (s[i] == 0x1b) {
- i += 1;
- if (i < s.len and s[i] == '[') {
- i += 1;
- while (i < s.len and (s[i] < 0x40 or s[i] > 0x7e)) : (i += 1) {}
- if (i < s.len) i += 1;
- }
+ i = theme_mod.skipEsc(s, i);
continue;
}
out.append(s[i]) catch {};
diff --git a/TUI/theme.zig b/TUI/theme.zig
index a29adef9..1640e37e 100644
--- a/TUI/theme.zig
+++ b/TUI/theme.zig
@@ -94,18 +94,44 @@ pub fn next(id: Id) Id {
return @enumFromInt((@intFromEnum(id) + 1) % all.len);
}
+/// Index just past the escape sequence starting at `start` (s[start] == 0x1b).
+/// Skips CSI, OSC/DCS/APC/PM/SOS (to BEL or ST), SS3, and ESC+char — a
+/// truncation mid-sequence would emit broken escapes into the frame.
+pub fn skipEsc(s: []const u8, start: usize) usize {
+ var i = start + 1;
+ if (i >= s.len) return i;
+ switch (s[i]) {
+ '[' => {
+ i += 1;
+ while (i < s.len and (s[i] < 0x40 or s[i] > 0x7e)) : (i += 1) {}
+ if (i < s.len) i += 1;
+ },
+ ']', 'P', '_', '^', 'X' => {
+ i += 1;
+ while (i < s.len) : (i += 1) {
+ if (s[i] == 0x07) {
+ i += 1;
+ break;
+ }
+ if (s[i] == 0x1b) {
+ i += if (i + 1 < s.len and s[i + 1] == '\\') 2 else 1;
+ break;
+ }
+ }
+ },
+ 'O' => i = @min(i + 2, s.len),
+ else => i += 1,
+ }
+ return i;
+}
+
/// Columns in `s`, skipping SGR. Assumes 1-col codepoints (no CJK/emoji width).
pub fn visibleLen(s: []const u8) usize {
var n: usize = 0;
var i: usize = 0;
while (i < s.len) {
if (s[i] == 0x1b) {
- i += 1;
- if (i < s.len and s[i] == '[') {
- i += 1;
- while (i < s.len and (s[i] < 0x40 or s[i] > 0x7e)) : (i += 1) {}
- if (i < s.len) i += 1;
- }
+ i = skipEsc(s, i);
continue;
}
const w = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;
@@ -120,12 +146,7 @@ pub fn takeCols(s: []const u8, max: usize) []const u8 {
var i: usize = 0;
while (i < s.len and n < max) {
if (s[i] == 0x1b) {
- i += 1;
- if (i < s.len and s[i] == '[') {
- i += 1;
- while (i < s.len and (s[i] < 0x40 or s[i] > 0x7e)) : (i += 1) {}
- if (i < s.len) i += 1;
- }
+ i = skipEsc(s, i);
continue;
}
const w = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;
@@ -191,12 +212,7 @@ pub fn wrapToWidth(a: std.mem.Allocator, s: []const u8, width: usize) ![]const u
}
if (s[i] == 0x1b) {
const start = i;
- i += 1;
- if (i < s.len and s[i] == '[') {
- i += 1;
- while (i < s.len and (s[i] < 0x40 or s[i] > 0x7e)) : (i += 1) {}
- if (i < s.len) i += 1;
- }
+ i = skipEsc(s, i);
try out.appendSlice(s[start..i]);
continue;
}
@@ -228,3 +244,10 @@ test "wrapToWidth splits a long line and keeps SGR" {
try std.testing.expect(visibleLen(ln) <= 4);
}
}
+
+test "visibleLen and takeCols treat OSC/APC as invisible" {
+ try std.testing.expectEqual(@as(usize, 4), visibleLen("\x1b]8;;http://x\x07link\x1b]8;;\x07"));
+ try std.testing.expectEqual(@as(usize, 2), visibleLen("\x1b_Ga=d,d=A\x1b\\ok"));
+ const cut = takeCols("\x1b]8;;u\x07ab", 1);
+ try std.testing.expectEqualStrings("\x1b]8;;u\x07a", cut);
+}
diff --git a/src/tui_launch.zig b/src/tui_launch.zig
index 3b71446c..d141ef4f 100644
--- a/src/tui_launch.zig
+++ b/src/tui_launch.zig
@@ -10,6 +10,7 @@ const agent_mod = @import("agent.zig");
const provider_mod = @import("provider.zig");
const pricing = @import("pricing.zig");
const providers = @import("providers.zig");
+const process_runner = @import("process_runner.zig");
const repl = @import("repl.zig");
const repl_glue = @import("repl_glue.zig");
const tui = @import("tui");
@@ -104,6 +105,9 @@ pub fn run(
.yolo = yolo,
.hud_fn = hudCb,
.paste_fn = pasteCb,
+ .bash_fn = bashCb,
+ .files_fn = filesCb,
+ .copy_fn = copyCb,
});
}
@@ -191,6 +195,78 @@ fn pasteErr(dest: []u8, msg: []const u8) isize {
return -@as(isize, @intCast(n));
}
+/// `!cmd` bash mode: run in the session cwd, cap output, 20s deadline.
+fn bashCb(ctx: ?*anyopaque, gpa: Allocator, cmd: []const u8) ?[]const u8 {
+ const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));
+ const argv: []const []const u8 = if (builtin.os.tag == .windows)
+ &.{ "cmd.exe", "/C", cmd }
+ else
+ &.{ "/bin/sh", "-c", cmd };
+ const run_res = process_runner.runCapped(gpa, c.io, argv, 64 * 1024, 16 * 1024, 20_000) catch return null;
+ defer gpa.free(run_res.stdout);
+ defer gpa.free(run_res.stderr);
+ var out = std.array_list.Managed(u8).init(gpa);
+ defer out.deinit();
+ const so = std.mem.trimEnd(u8, run_res.stdout, "\r\n");
+ const se = std.mem.trimEnd(u8, run_res.stderr, "\r\n");
+ out.appendSlice(so) catch {};
+ if (se.len > 0) {
+ if (out.items.len > 0) out.append('\n') catch {};
+ out.appendSlice(se) catch {};
+ }
+ if (run_res.timed_out) {
+ if (out.items.len > 0) out.append('\n') catch {};
+ out.appendSlice("(timed out after 20s)") catch {};
+ } else if (!process_runner.ranOk(run_res)) {
+ if (out.items.len > 0) out.append('\n') catch {};
+ var nb: [32]u8 = undefined;
+ const note = switch (run_res.term) {
+ .exited => |code| std.fmt.bufPrint(&nb, "(exit {d})", .{code}) catch "(exit ?)",
+ else => "(terminated)",
+ };
+ out.appendSlice(note) catch {};
+ }
+ if (out.items.len == 0) out.appendSlice("(no output)") catch {};
+ return out.toOwnedSlice() catch null;
+}
+
+/// @-mention source: tracked+untracked files (gitignore honored), find fallback.
+fn filesCb(ctx: ?*anyopaque, gpa: Allocator) ?[]const u8 {
+ const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));
+ if (builtin.os.tag == .windows) return null;
+ const cmd = "(git ls-files --cached --others --exclude-standard 2>/dev/null || find . -type f -not -path '*/.*' 2>/dev/null | sed 's|^\\./||') | head -3000";
+ const run_res = process_runner.runCapped(gpa, c.io, &.{ "/bin/sh", "-c", cmd }, 512 * 1024, 4 * 1024, 10_000) catch return null;
+ gpa.free(run_res.stderr);
+ if (run_res.stdout.len == 0) {
+ gpa.free(run_res.stdout);
+ return null;
+ }
+ return run_res.stdout;
+}
+
+fn copyCb(ctx: ?*anyopaque, text: []const u8) bool {
+ const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return false));
+ const argv: []const []const u8 = switch (builtin.os.tag) {
+ .macos => &.{"pbcopy"},
+ .linux => &.{ "xclip", "-selection", "clipboard" },
+ else => return false,
+ };
+ var child = std.process.spawn(c.io, .{
+ .argv = argv,
+ .stdin = .pipe,
+ .stdout = .ignore,
+ .stderr = .ignore,
+ }) catch return false;
+ var wbuf: [4096]u8 = undefined;
+ var fw = child.stdin.?.writerStreaming(c.io, &wbuf);
+ fw.interface.writeAll(text) catch {};
+ fw.interface.flush() catch {};
+ child.stdin.?.close(c.io);
+ child.stdin = null;
+ const term = child.wait(c.io) catch return false;
+ return term == .exited and term.exited == 0;
+}
+
fn hudCb(kind: tui.HudKind, buf: []u8) usize {
var w: Io.Writer = .fixed(buf);
switch (kind) {