Skip to content

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

Python

fix(tui): claim the pager before boot and paint live markdown

Cursor Agente9b2b56830ba
diff --git a/TUI/restore.zig b/TUI/restore.zig
index 042d040f..c1c690c7 100644
--- a/TUI/restore.zig
+++ b/TUI/restore.zig
@@ -76,6 +76,51 @@ pub fn disarm() void {
armed.store(false, .release);
}
+/// True while a fatal-signal restore is hooked — `run` uses this so an
+/// early `claimScreen` (alt-screen before keys/MCP/prompt) is not armed
+/// twice, which would save already-raw termios and strand the shell.
+pub fn isArmed() bool {
+ return armed.load(.acquire);
+}
+
+/// Early alt-screen claim so leftover boot happens *inside* the pager.
+/// `run` takes ownership via `takeClaim`; `releaseIfOwned` (shutdown
+/// teardown + fatal signals already hooked by `arm`) restores if we never
+/// get there. No libc `atexit`: Zig exits via syscall and skips C exits.
+var claim_owned = std.atomic.Value(bool).init(false);
+var claim_raw: tty.RawState = undefined;
+
+pub fn claimScreen(enable_seq: []const u8) bool {
+ if (builtin.is_test) return false;
+ if (claim_owned.load(.acquire) or armed.load(.acquire)) return true;
+ const raw = tty.enterRaw() orelse return false;
+ claim_raw = raw;
+ arm(raw, enable_seq);
+ if (builtin.os.tag != .windows) {
+ _ = std.posix.system.write(std.posix.STDOUT_FILENO, enable_seq.ptr, enable_seq.len);
+ const wipe = "\x1b[H\x1b[2J";
+ _ = std.posix.system.write(std.posix.STDOUT_FILENO, wipe.ptr, wipe.len);
+ }
+ muteStderr();
+ claim_owned.store(true, .release);
+ return true;
+}
+
+/// Hand the claimed raw state to `run`. After this, `releaseIfOwned` no-ops
+/// — `run` owns restore. Null when nothing was claimed (off-TTY, or `run` first).
+pub fn takeClaim() ?tty.RawState {
+ if (!claim_owned.swap(false, .acq_rel)) return null;
+ return claim_raw;
+}
+
+/// Teardown / error-return path after an early claim that never reached `run`.
+/// First call wins; later stamps are a single atomic load.
+pub fn releaseIfOwned() void {
+ if (!claim_owned.load(.acquire)) return;
+ emergency();
+ claim_owned.store(false, .release);
+}
+
/// True exactly once per resume from SIGTSTP — run.zig drops its diff
/// baseline so the first frame after `fg` is a full repaint.
pub fn takeResumed() bool {
@@ -262,10 +307,22 @@ 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));
+ try std.testing.expect(isArmed());
disarm();
try std.testing.expect(!armed.load(.acquire));
}
+test "takeClaim is empty until a claim is owned" {
+ try std.testing.expect(takeClaim() == null);
+}
+
+test "takeClaim hands the raw state over exactly once" {
+ claim_raw = if (builtin.os.tag == .windows) .{} else undefined;
+ claim_owned.store(true, .release);
+ try std.testing.expect(takeClaim() != null);
+ try std.testing.expect(takeClaim() == null);
+}
+
test "crash signals are hooked, and they hand the signal back, not to SIG_DFL (#535/#547)" {
for ([_]std.posix.SIG{ .SEGV, .BUS, .ILL, .FPE, .TRAP }) |want| {
var found = false;
@@ -288,6 +345,8 @@ test "crash signals are hooked, and they hand the signal back, not to SIG_DFL (#
test "stderr is parked for the TUI's whole lifetime and unparked on every exit path" {
const run_src = @embedFile("run.zig");
+ // Early claim (ADR 0042) is taken here so run does not re-arm over raw termios.
+ try std.testing.expect(std.mem.indexOf(u8, run_src, "takeClaim()") != null);
// Parked right after the fullscreen enable, before the first frame...
const enable_at = std.mem.indexOf(u8, run_src, "w.writeAll(enable_seq) catch {};").?;
const mute_at = std.mem.indexOfPos(u8, run_src, enable_at, "restore_mod.muteStderr();").?;
diff --git a/TUI/root.zig b/TUI/root.zig
index 503c73f6..d60f629d 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -39,6 +39,13 @@ pub const PeerFn = engine.PeerFn;
pub const RunOpts = run_mod.RunOpts;
pub const run = run_mod.run;
pub const restore = @import("restore.zig");
+pub const enable_seq = run_mod.enable_seq;
+
+/// Claim the alt-screen as soon as the command is `tui`/`repl`, so leftover
+/// boot (keys, MCP, AGENTS.md) happens inside the pager. No-op off a TTY.
+pub fn claim() bool {
+ return restore.claimScreen(run_mod.enable_seq);
+}
/// Restore the terminal BEFORE std prints a panic, or the alt-screen exit in
/// the restore sequence erases the message and the stack trace (#535).
pub const panic = restore.Panic;
diff --git a/TUI/run.zig b/TUI/run.zig
index 5f19f0c6..9b87d4c4 100644
--- a/TUI/run.zig
+++ b/TUI/run.zig
@@ -67,8 +67,9 @@ pub fn run(
defer m.deinit();
if (opts.yolo) m.mode = .always_approve;
- var raw = tty.enterRaw() orelse return error.NotATty;
- restore_mod.arm(raw, enable_seq);
+ const claimed = restore_mod.takeClaim();
+ var raw = claimed orelse (tty.enterRaw() orelse return error.NotATty);
+ if (claimed == null) restore_mod.arm(raw, enable_seq);
defer restore_mod.disarm();
defer tty.restore(raw);
diff --git a/TUI/scrollback.zig b/TUI/scrollback.zig
index 19c9e581..ad006e0e 100644
--- a/TUI/scrollback.zig
+++ b/TUI/scrollback.zig
@@ -35,11 +35,12 @@ pub fn render(self: *const Model, a: std.mem.Allocator, width: usize, now_ms: u6
}
if (self.pending) |job| {
if (!self.cancel_requested) {
- const src = if (job.raw.len.load(.acquire) > 0) &job.raw else &job.stream;
+ const raw_bash = job.raw.len.load(.acquire) > 0;
+ const src = if (raw_bash) &job.raw else &job.stream;
if (src.snapshot(a)) |live| {
if (!first) try out.append('\n');
first = false;
- try out.appendSlice(try theme_mod.paint(a, self.theme().muted, try tail(a, strip(a, live), width, 4)));
+ try out.appendSlice(try theme_mod.paint(a, self.theme().muted, try liveTail(self, a, live, raw_bash, width)));
}
if (self.steer_queue.items.len > 0) {
if (!first) try out.append('\n');
@@ -338,6 +339,15 @@ pub fn strip(a: std.mem.Allocator, s: []const u8) []const u8 {
return @import("markdown.zig").sanitize(a, s) catch s;
}
+/// Live prose uses the same renderer as a settled assistant row. Raw bash
+/// stays sanitized-only — those bytes are a terminal, not markdown.
+fn liveTail(self: *const Model, a: std.mem.Allocator, live: []const u8, raw_bash: bool, width: usize) ![]const u8 {
+ const clean = strip(a, live);
+ if (raw_bash) return tail(a, clean, width, 4);
+ const painted = @import("markdown.zig").renderThemed(a, clean, self.theme(), width -| 4) catch clean;
+ return tail(a, painted, width, 8);
+}
+
pub fn tail(a: std.mem.Allocator, s: []const u8, width: usize, max_lines: usize) ![]const u8 {
var lines = std.array_list.Managed([]const u8).init(a);
var it = std.mem.splitScalar(u8, s, '\n');
diff --git a/TUI/scrollback_tests.zig b/TUI/scrollback_tests.zig
index 57d5a6eb..881121c9 100644
--- a/TUI/scrollback_tests.zig
+++ b/TUI/scrollback_tests.zig
@@ -243,3 +243,35 @@ test "a long system row breaks on a space, never through a token" {
try std.testing.expect(n > 1); // it really did wrap
}
}
+
+test "live prose tail paints markdown; raw bash stays plain" {
+ const engine = @import("engine.zig");
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ var sbuf: [256]u8 = undefined;
+ var rbuf: [256]u8 = undefined;
+ var job: engine.Job = .{
+ .gpa = std.testing.allocator,
+ .history = &.{},
+ .params = .{},
+ .stream = .{ .buf = &sbuf },
+ .raw = .{ .buf = &rbuf },
+ .threaded = false,
+ };
+ job.stream.appendBytes("- first\n**bold** word\n");
+ try m.push(.pending, "");
+ m.pending = &job;
+ defer m.pending = null;
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const prose = try scrollback.render(&m, arena.allocator(), 80, 0);
+ try std.testing.expect(std.mem.indexOf(u8, prose, "•") != null);
+ try std.testing.expect(std.mem.indexOf(u8, prose, "**bold**") == null);
+ try std.testing.expect(std.mem.indexOf(u8, prose, "bold") != null);
+
+ job.raw.appendBytes("**not markdown**\n- also raw\n");
+ const bash = try scrollback.render(&m, arena.allocator(), 80, 0);
+ try std.testing.expect(std.mem.indexOf(u8, bash, "**not markdown**") != null);
+ try std.testing.expect(std.mem.indexOf(u8, bash, "- also raw") != null);
+}
diff --git a/TUI/sim.zig b/TUI/sim.zig
index 9dd735b7..ed429b8b 100644
--- a/TUI/sim.zig
+++ b/TUI/sim.zig
@@ -462,3 +462,31 @@ test "the idle paste sweep never fires a phantom Escape at a live turn" {
_ = term.feed("[201~");
try std.testing.expectEqualStrings("draft text", term.model.input.getValue());
}
+
+test "live prose tail paints markdown before the turn settles" {
+ const engine = @import("engine.zig");
+ var term: Term = undefined;
+ term.init(std.testing.allocator, 80, 24);
+ defer term.deinit();
+ try term.model.push(.user, "list them");
+ var sbuf: [256]u8 = undefined;
+ const job = try std.testing.allocator.create(engine.Job);
+ defer std.testing.allocator.destroy(job);
+ job.* = .{
+ .gpa = std.testing.allocator,
+ .history = &.{},
+ .params = .{},
+ .stream = .{ .buf = &sbuf },
+ .threaded = false,
+ };
+ job.stream.appendBytes("- first item\nthis is **bold** text\n");
+ try term.model.push(.pending, "");
+ term.model.pending = job;
+ defer term.model.pending = null;
+ const vis = try term.screen();
+ defer std.testing.allocator.free(vis);
+ try std.testing.expect(std.mem.indexOf(u8, vis, "•") != null);
+ try std.testing.expect(std.mem.indexOf(u8, vis, "**bold**") == null);
+ try std.testing.expect(std.mem.indexOf(u8, vis, "bold") != null);
+ try std.testing.expect(std.mem.indexOf(u8, vis, "- first") == null);
+}
diff --git a/docs/adr/0021-transcript-is-the-task-not-the-bus.md b/docs/adr/0021-transcript-is-the-task-not-the-bus.md
index ba2c7fbc..df813826 100644
--- a/docs/adr/0021-transcript-is-the-task-not-the-bus.md
+++ b/docs/adr/0021-transcript-is-the-task-not-the-bus.md
@@ -31,4 +31,5 @@ not foreground UI. `batch` is `inspect`. Observe, then conclude, then act.
JSON events and tool results the model reads are unchanged. `/debug` and
`.graff/subagents/<id>.md` remain the escape hatch. A later TUI chrome pass
-can bind WORKING to the pager footer the same way.
+can bind WORKING to the pager footer the same way. The pager claims the
+alt-screen before session construction (ADR 0042); the welcome stays empty.
diff --git a/docs/adr/0042-tui-claims-screen-before-session.md b/docs/adr/0042-tui-claims-screen-before-session.md
new file mode 100644
index 00000000..5b871a80
--- /dev/null
+++ b/docs/adr/0042-tui-claims-screen-before-session.md
@@ -0,0 +1,34 @@
+# 0042. TUI claims the alt-screen before session construction
+
+Status: accepted 2026-08-28
+
+## Context
+
+`GRAFF_BOOT_DEBUG=1 graff tui --yolo` on this tree is ~12ms of Zig
+phases (args → credentials → MCP → prompt → root agent), then
+`tui.run` writes `\x1b[?1049h`. The user stares at the leftover shell
+for the whole of `main()` before that. Fat `AGENTS.md`, plugin consent,
+and companion spawn (see the deferred-companion hang) make that gap
+seconds on a real machine. Pi paints the pager first.
+
+ADR 0021 keeps the welcome empty. An essay on the first frame is not
+the steal — leaving the shell is.
+
+## Decision
+
+When the command is `tui` or `repl` (and not `--json` / `-p`),
+`startup.runSubcommand` claims the alt-screen (`tty.enterRaw` + enable
+seq + `restore.arm` + stderr mute) before credentials. `tui.run` takes
+that claim and does not re-arm over already-raw termios. If we never
+reach `run`, `restore.releaseIfOwned` on the shutdown stamps plus the
+panic hook / fatal signals restore the shell. No libc `atexit` — Zig
+exits via syscall and would skip it.
+
+Welcome stays empty. Off a TTY the claim is a no-op.
+
+## Consequences
+
+Boot diagnostics during `graff tui` land in `.graff/tui-stderr.log`
+(`muteStderr` at claim time), not on the leftover shell. A crash
+between claim and `run` must hit `restore.emergency` or the shell is
+stranded — same contract as a crash inside `run`.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index e76f1c51..5ff2e422 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -52,6 +52,7 @@ record only when you need the evidence or the edge cases.
| [0039](0039-local-tools-are-project-scripts.md) | Agent-authored local tools are project scripts under `.graff/tools/`; skills stay instructions. Runtime catalog extras, not `schema.effectiveRootSpecs`. |
| [0040](0040-codedb-stays-when-licensed.md) | Ordinary reads use native `codedb` / `read_file`; codedb-pro is extra search, not the default reader. |
| [0041](0041-tui-is-an-acp-client.md) | The fullscreen TUI is an in-process ACP client: session/prompt in, session/update thought/tool/text out. No child `graff acp`. |
+| [0042](0042-tui-claims-screen-before-session.md) | `graff tui` / TTY `graff repl` claim the alt-screen before keys/MCP/prompt; leftover boot happens inside the pager. |
## When to write one
diff --git a/src/repl_model_render.zig b/src/repl_model_render.zig
index 492f4490..d84f63be 100644
--- a/src/repl_model_render.zig
+++ b/src/repl_model_render.zig
@@ -80,11 +80,12 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, term_width: usize, term_heig
const g = try (zz.Style{}).fg(repl.accent).bold(true).render(a, self.spinnerFrame(now_ms));
const live = if (self.pending) |job| job.stream.snapshot(a) else null;
if (live) |s| {
- // Compact live activity: the last few lines of the
- // agent's output, control-stripped + width-truncated,
- // so tool chatter can't flood the pane.
+ // Same renderer the settled reply uses (repl_markdown),
+ // then a short tail so tool chatter cannot flood the pane.
+ const clean = stripControl(a, s);
+ const painted = repl.renderMarkdown(a, clean, term_width) catch clean;
try top.appendSlice(try std.fmt.allocPrint(a, "{s} working…\n", .{g}));
- try top.appendSlice(try tailPreview(a, stripControl(a, s), term_width, 3));
+ try top.appendSlice(try tailPreview(a, stripControl(a, painted), term_width, 8));
} else {
const t = try (zz.Style{}).dim(true).render(a, "thinking…");
try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, t }));
@@ -204,3 +205,27 @@ pub fn copySelection(self: *Model, ctx: *zz.Context, r0: usize, r1: usize) void
self.toast = if (ok) .copied else .failed;
self.toast_until_ms = (ctx.elapsed / std.time.ns_per_ms) + repl.TOAST_MS;
}
+
+test "live pending tail paints markdown before the turn settles" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ var sbuf: [256]u8 = undefined;
+ var none: [0]repl.Turn = .{};
+ var job: repl.Job = .{
+ .gpa = std.testing.allocator,
+ .history = &none,
+ .params = .{},
+ .stream = .{ .buf = &sbuf },
+ .threaded = false,
+ };
+ job.stream.appendBytes("- first\nthis is **bold** text\n");
+ try m.push(.pending, "");
+ m.pending = &job;
+ defer m.pending = null;
+ const out = try render(&m, std.testing.allocator, 80, 24, 0);
+ defer std.testing.allocator.free(out);
+ try std.testing.expect(std.mem.indexOf(u8, out, "•") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "**bold**") == null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "bold") != null);
+}
diff --git a/src/shutdown_trace.zig b/src/shutdown_trace.zig
index 68d17437..8d4f94df 100644
--- a/src/shutdown_trace.zig
+++ b/src/shutdown_trace.zig
@@ -56,6 +56,9 @@ pub fn arm(io: Io, environ_map: *const std.process.Environ.Map) Io {
/// tests, `graff repl`, any path that never called `arm`) or when the opt-in
/// is off, so a normal exit pays one bool load per phase.
pub fn mark(phase: []const u8) void {
+ // ADR 0042: an early pager claim that never reached `tui.run` still
+ // owns the alt-screen. Main's first teardown `at()` lands here.
+ @import("tui").restore.releaseIfOwned();
if (!enabled) return;
const io = clock orelse return;
const cumulative: i64 = @intCast(@max(0, started.untilNow(io, .awake).toMilliseconds()));
@@ -96,6 +99,11 @@ test "render degrades to the bare phase name rather than dropping it" {
try std.testing.expectEqualStrings("join-elites", render(&tiny, "join-elites", 1, 1));
}
+test "teardown stamps release an early pager claim" {
+ const src = @embedFile("shutdown_trace.zig");
+ try std.testing.expect(std.mem.indexOf(u8, src, "releaseIfOwned") != null);
+}
+
test "an unarmed process prints nothing and `at` stays a pass-through" {
setEnabledForTest(false);
mark("never-printed");
diff --git a/src/startup.zig b/src/startup.zig
index f851ae2d..a305aa7e 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -416,5 +416,17 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
try schema.emitSchema(&sw.interface);
return true;
}
+
+ // ADR 0042: claim the pager before keys / MCP / prompt so `graff tui`
+ // (and TTY `graff repl`) do not sit on a blank shell. No-op off a TTY.
+ if (!main_mod.json_mode and flags.oneshot_prompt == null and flags.isPager()) {
+ _ = @import("tui").claim();
+ }
return false;
}
+
+test "pager commands claim the alt screen before credentials" {
+ const src = @embedFile("startup.zig");
+ try std.testing.expect(std.mem.indexOf(u8, src, "flags.isPager()") != null);
+ try std.testing.expect(std.mem.indexOf(u8, src, ".claim()") != null);
+}
diff --git a/src/startup_timing.zig b/src/startup_timing.zig
index e1f068c7..1e4bbaa2 100644
--- a/src/startup_timing.zig
+++ b/src/startup_timing.zig
@@ -63,6 +63,10 @@ pub const Tracker = struct {
}
};
+test {
+ _ = shutdown_trace;
+}
+
test "startup phases retain order and non-negative deltas before attach" {
var tracker = Tracker.init(std.testing.io, false);
tracker.mark(std.testing.io, "args");