xonecas.io
79113
Ma

mini-coding-agent / commit 4e73d0e

feat: better resize handling, restory the terminal on exit when possible

xonecas2026-10-05 4e73d0e657aae50b87970c35b8e57be0af8ae232 parent 8ec6a30

3 files changed

src/main.zig+20−0
@@ -11,6 +11,26 @@ const types = @import("types.zig");
1111 const agent = @import("agent.zig");
1212 const tools = @import("tools/index.zig");
1313 const tui = @import("tui/tui.zig");
14+const term = @import("tui/term.zig");
15+
16+/// The terminal is process-wide state, so its reset is too: a panic or a
17+/// segfault must hand the tty back before the process dies, exactly as the
18+/// signal and exit paths do. Both handlers below are allocation-free.
19+pub const panic = std.debug.FullPanic(panicRestore);
20+
21+fn panicRestore(msg: []const u8, ra: ?usize) noreturn {
22+ term.restore();
23+ std.debug.defaultPanic(msg, ra);
24+}
25+
26+/// `std.debug` routes SEGV/ILL/BUS/FPE here when the root file declares it, so
27+/// a crash in the allocator or a bad pointer cannot leave the tty raw either.
28+pub const debug = struct {
29+ pub fn handleSegfault(addr: ?usize, name: []const u8, ctx: ?std.debug.CpuContextPtr) noreturn {
30+ term.restore();
31+ std.debug.defaultHandleSegfault(addr, name, ctx);
32+ }
33+};
1434
1535 var cancel = std.atomic.Value(bool).init(false);
1636
src/tui/term.zig+46−12
@@ -1,6 +1,11 @@
11 const std = @import("std");
22 const platform = @import("../platform.zig");
33
4+/// Emitted when the terminal is handed back: kitty keyboard protocol off inside
5+/// its push/pop stack, then bracketed paste off.
6+const EXIT_SEQUENCE = "\x1b[<u\x1b[?2004l";
7+const ENTER_SEQUENCE = "\x1b[?2004h\x1b[>1u\x1b[?u";
8+
49 pub const Key = union(enum) {
510 text: []const u8,
611 submit,
@@ -266,9 +271,33 @@ fn normalizePaste(a: std.mem.Allocator, text: []const u8) []const u8 {
266271 return out.items;
267272 }
268273
274+/// The mode the tty was in before we took it, reachable without a `Terminal`
275+/// instance: the exit-signal handler and the panic handler must be able to
276+/// restore it while the `Tui` that owns the terminal is out of reach, and
277+/// neither of them may allocate.
278+var saved: std.posix.termios = undefined;
279+/// Set once the mode has been switched, cleared by the restore itself, so a
280+/// signal and the exit path cannot both put the mode back.
281+var raw_mode = std.atomic.Value(bool).init(false);
282+/// Set once the enter sequences have been written, cleared by the restore.
283+var entered = std.atomic.Value(bool).init(false);
284+
285+/// Writes bytes straight to the tty. The `Io` machinery is not safe to use from
286+/// a signal handler; `write` is.
287+fn writeRaw(bytes: []const u8) void {
288+ _ = std.posix.system.write(std.posix.STDOUT_FILENO, bytes.ptr, bytes.len);
289+}
290+
291+/// Puts the terminal back the way it was found: mode first, then the exit
292+/// sequences. Idempotent, allocation-free, and safe to call from a signal
293+/// handler or a panic handler; whichever of the two gets there first does the
294+/// work, and the exit path's later call is a no-op.
295+pub fn restore() void {
296+ if (raw_mode.swap(false, .seq_cst)) std.posix.tcsetattr(std.posix.STDIN_FILENO, .NOW, saved) catch {};
297+ if (entered.swap(false, .seq_cst)) writeRaw(EXIT_SEQUENCE);
298+}
299+
269300 pub const Terminal = struct {
270- original: std.posix.termios = undefined,
271- raw: bool = false,
272301 started: bool = false,
273302 winsize: [2]usize = .{ 80, 24 },
274303
@@ -300,8 +329,8 @@ pub const Terminal = struct {
300329 self.started = true;
301330 self.refreshSize();
302331 if (std.Io.File.stdin().isTty(platform.io) catch false) {
303- self.original = std.posix.tcgetattr(std.posix.STDIN_FILENO) catch return;
304- var raw = self.original;
332+ const original = std.posix.tcgetattr(std.posix.STDIN_FILENO) catch return;
333+ var raw = original;
305334 raw.lflag.ICANON = false;
306335 raw.lflag.ECHO = false;
307336 raw.lflag.ISIG = false;
@@ -311,20 +340,25 @@ pub const Terminal = struct {
311340 raw.oflag.OPOST = false;
312341 raw.cc[@intFromEnum(std.posix.V.MIN)] = 1;
313342 raw.cc[@intFromEnum(std.posix.V.TIME)] = 0;
314- std.posix.tcsetattr(std.posix.STDIN_FILENO, .NOW, raw) catch {};
315- self.raw = true;
343+ // The saved mode is published before the switch, so a signal that
344+ // arrives mid-`tcsetattr` can still undo it.
345+ saved = original;
346+ raw_mode.store(true, .seq_cst);
347+ std.posix.tcsetattr(std.posix.STDIN_FILENO, .NOW, raw) catch {
348+ raw_mode.store(false, .seq_cst);
349+ return;
350+ };
316351 }
317- platform.writeOut("\x1b[?2004h\x1b[>1u\x1b[?u");
352+ // Published before the write: a signal between the two must not skip
353+ // the exit sequences.
354+ entered.store(true, .seq_cst);
355+ platform.writeOut(ENTER_SEQUENCE);
318356 }
319357
320358 pub fn stop(self: *Terminal) void {
321359 if (!self.started) return;
322360 self.started = false;
323- platform.writeOut("\x1b[<u\x1b[?2004l");
324- if (self.raw) {
325- std.posix.tcsetattr(std.posix.STDIN_FILENO, .NOW, self.original) catch {};
326- self.raw = false;
327- }
361+ restore();
328362 }
329363
330364 pub fn write(self: *Terminal, text: []const u8) void {
src/tui/tui.zig+50−4
@@ -27,6 +27,10 @@ const SPINNER_MS = 120;
2727 const BODY_PREFIX = " | ";
2828 const ERROR_PREFIX = " ! ";
2929
30+/// Lines of scrollback kept in memory so a resize can re-wrap them. Rows are
31+/// rebuilt from these, so the value bounds the memory a session can hold.
32+const HISTORY_LINES = 1000;
33+
3034 /// Display-only elision for tool bodies; `edit` diffs are always shown in full.
3135 const MAX_BODY_ROWS = 12;
3236 const ELIDED_HEAD = 4;
@@ -316,7 +320,10 @@ fn onWinch(_: std.posix.SIG) callconv(.c) void {
316320 }
317321
318322 /// A signal that must restore the terminal before the process ends.
323+/// The restore happens here, not in the event loop: a signal that arrives while
324+/// the loop is blocked on a prompt or a lock must not leave the tty raw.
319325 fn onExitSignal(_: std.posix.SIG) callconv(.c) void {
326+ term.restore();
320327 exit_flag.store(true, .seq_cst);
321328 }
322329
@@ -365,6 +372,7 @@ const Tui = struct {
365372 abort: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
366373
367374 scroll: std.ArrayList(u8) = .empty,
375+ history: std.ArrayList([]const u8) = .empty,
368376 wrote: bool = false,
369377 last_blank: bool = false,
370378 separator: bool = false,
@@ -435,11 +443,19 @@ const Tui = struct {
435443 const blank = clean.len == 0 or (self.separator and self.wrote);
436444 self.separator = false;
437445 if (blank and self.wrote and !self.last_blank) {
446+ self.history.append(platform.gpa, "") catch {};
447+ self.capHistory();
438448 self.scroll.appendSlice(self.a, paintRow(self.sa, "")) catch {};
439449 self.scroll.appendSlice(self.a, "\r\n") catch {};
440450 self.last_blank = true;
441451 }
442452 if (clean.len != 0) {
453+ // `clean` may point at scratch or at the agent's event buffer, both
454+ // of which are reset before a resize can read this line back, so
455+ // the history keeps a copy or drops the line.
456+ if (platform.gpa.dupe(u8, clean)) |owned| {
457+ if (self.history.append(platform.gpa, owned)) |_| self.capHistory() else |_| platform.gpa.free(owned);
458+ } else |_| {}
443459 self.scroll.appendSlice(self.a, paintRow(self.sa, clean)) catch {};
444460 self.scroll.appendSlice(self.a, "\r\n") catch {};
445461 self.wrote = true;
@@ -448,6 +464,36 @@ const Tui = struct {
448464 self.dirty = true;
449465 }
450466
467+ /// Drops the oldest history line past the cap. Both the list and its
468+ /// strings use the process allocator, not a session arena, so an evicted
469+ /// line's memory comes back and a long session stays bounded.
470+ fn capHistory(self: *Tui) void {
471+ while (self.history.items.len > HISTORY_LINES) {
472+ const old = self.history.orderedRemove(0);
473+ if (old.len > 0) platform.gpa.free(old);
474+ }
475+ }
476+
477+ /// Rebuilds the whole scrollback at the current width. The terminal cannot
478+ /// reflow rows it has already been given, so the history is re-wrapped and
479+ /// the screen is rewritten from scratch; the terminal's own scrollback is
480+ /// dropped too, since it holds the old, narrow rendering.
481+ fn reflow(self: *Tui) void {
482+ self.term.refreshSize();
483+ self.live.rows = 0;
484+ self.live.cursor_up = 0;
485+ self.scroll.clearRetainingCapacity();
486+ self.term.write("\x1b[2J\x1b[3J\x1b[H");
487+ const width = @max(self.term.width(), 1);
488+ for (self.history.items) |line| {
489+ for (render.wrapLine(self.s, line, width)) |row| {
490+ self.scroll.appendSlice(self.a, paintRow(self.sa, row)) catch {};
491+ self.scroll.appendSlice(self.a, "\r\n") catch {};
492+ }
493+ }
494+ self.dirty = true;
495+ }
496+
451497 fn commitLines(self: *Tui, lines: []const stream.BodyLine) void {
452498 const width = @max(self.term.width(), 1);
453499 for (renderRows(self.s, lines, width)) |row| self.push(row);
@@ -1149,6 +1195,7 @@ pub fn run(opts: agent.Options, cfg: *const config.Config, tool_names: []const c
11491195 self.bindAllocators();
11501196
11511197 self.term.start();
1198+ defer self.term.stop();
11521199 const act = std.posix.Sigaction{
11531200 .handler = .{ .handler = onWinch },
11541201 .mask = std.posix.sigemptyset(),
@@ -1162,6 +1209,8 @@ pub fn run(opts: agent.Options, cfg: *const config.Config, tool_names: []const c
11621209 };
11631210 std.posix.sigaction(std.posix.SIG.TERM, &term_act, null);
11641211 std.posix.sigaction(std.posix.SIG.INT, &term_act, null);
1212+ std.posix.sigaction(std.posix.SIG.HUP, &term_act, null);
1213+ std.posix.sigaction(std.posix.SIG.QUIT, &term_act, null);
11651214
11661215 self.pushBanner();
11671216 self.draw();
@@ -1216,10 +1265,7 @@ pub fn run(opts: agent.Options, cfg: *const config.Config, tool_names: []const c
12161265 self.dirty = true;
12171266 }
12181267
1219- if (resize_flag.swap(false, .seq_cst)) {
1220- self.term.refreshSize();
1221- self.dirty = true;
1222- }
1268+ if (resize_flag.swap(false, .seq_cst)) self.reflow();
12231269 if (exit_flag.swap(false, .seq_cst)) self.exit();
12241270
12251271 const now = util.nowMs();