Skip to content

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

Python

fix(tty): a completed run releases the terminal instead of suspending (#396)

justrach3fd0c501b571
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 52a6b727..b64a3e3b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -106,6 +106,9 @@ jobs:
- name: YOLO background-TTY job-control regression
run: python3 scripts/test-yolo-job-control.py zig-out/bin/graff
+ - name: Backgrounded prompt releases the TTY instead of suspending (#396)
+ run: python3 scripts/test-tty-release-on-exit.py zig-out/bin/graff
+
- name: PTY REPL interaction test
run: python3 scripts/test-pty-repl.py zig-out/bin/graff
diff --git a/scripts/test-tty-release-on-exit.py b/scripts/test-tty-release-on-exit.py
new file mode 100755
index 00000000..88135ea6
--- /dev/null
+++ b/scripts/test-tty-release-on-exit.py
@@ -0,0 +1,282 @@
+#!/usr/bin/env python3
+"""Regression for #396: a prompt that loses the terminal must exit, not suspend.
+
+Issue #396 was a COMPLETED graff still attached to the tty in state T while a
+NEWER graff owned the foreground process group: the finished run had gone back
+to its interactive prompt and blocked on a controlling-terminal read, so the
+kernel stopped it with SIGTTIN ("zsh: suspended (tty input)") — and it stopped
+holding the terminal in raw mode, which is what wrecked the surviving shell.
+
+The wrapper and graff occupy separate process groups in one real PTY session.
+Once graff is at its prompt the wrapper takes the foreground back and a byte is
+queued, exactly the situation a second graff on the same tty creates. The fixed
+prompt notices it is in the background, hands the terminal back and quits; the
+old one is stopped by the kernel instead.
+
+Asserts BOTH halves: graff exits (never WIFSTOPPED), and the terminal is left
+in canonical/echo mode rather than graff's raw mode.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import pty
+import select
+import signal
+import sys
+import tempfile
+import termios
+import time
+
+from codex_ws_mock import CodexMock, RecordedRequest, turn_events
+
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+
+# How long the wrapper waits for graff to leave after losing the foreground.
+# The prompt re-checks ownership on a 500ms cadence with a 2-tick grace, so a
+# second is the floor and this is comfortable slack for teardown.
+EXIT_BUDGET = 12.0
+
+
+def unused_events(request: RecordedRequest) -> list[dict]:
+ # No turn is ever run here; the mock exists only so the model is configured.
+ return turn_events(f"resp_unused_{request.ordinal}")
+
+
+def read_line(fd: int, timeout: float = 20.0) -> str:
+ deadline = time.monotonic() + timeout
+ data = bytearray()
+ while b"\n" not in data:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise AssertionError(f"timed out waiting for wrapper status: {data!r}")
+ ready, _, _ = select.select([fd], [], [], remaining)
+ if not ready:
+ continue
+ chunk = os.read(fd, 1024)
+ if not chunk:
+ raise AssertionError(f"wrapper status pipe closed early: {data!r}")
+ data.extend(chunk)
+ return bytes(data).split(b"\n", 1)[0].decode("ascii", errors="replace")
+
+
+def wait_for(master: int, needle: bytes, transcript: bytearray, timeout: float) -> None:
+ deadline = time.monotonic() + timeout
+ while needle not in transcript:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise AssertionError(
+ f"timed out waiting for {needle!r}; tail={bytes(transcript[-2000:])!r}"
+ )
+ ready, _, _ = select.select([master], [], [], min(0.1, remaining))
+ if not ready:
+ continue
+ try:
+ chunk = os.read(master, 65536)
+ except OSError:
+ chunk = b""
+ if not chunk:
+ raise AssertionError(
+ f"PTY closed before {needle!r}; tail={bytes(transcript[-2000:])!r}"
+ )
+ transcript.extend(chunk)
+
+
+def cooked() -> bool:
+ """True when the tty is back in canonical/echo mode (graff's raw mode undone)."""
+ try:
+ lflag = termios.tcgetattr(0)[3]
+ except termios.error:
+ return False
+ return bool(lflag & termios.ICANON) and bool(lflag & termios.ECHO)
+
+
+def wrapper(
+ control_fd: int,
+ status_fd: int,
+ argv: list[str],
+ cwd: str,
+ env: dict[str, str],
+) -> None:
+ """Session-leader child: move graff out of the PTY foreground, then watch it."""
+ signal.signal(signal.SIGTTOU, signal.SIG_IGN)
+ graff_pid = os.fork()
+ if graff_pid == 0:
+ try:
+ os.setpgid(0, 0)
+ os.chdir(cwd)
+ os.execvpe(argv[0], argv, env)
+ except BaseException:
+ os._exit(127)
+
+ try:
+ try:
+ os.setpgid(graff_pid, graff_pid)
+ except PermissionError:
+ pass
+ os.tcsetpgrp(0, graff_pid)
+ os.write(status_fd, f"READY {graff_pid}\n".encode("ascii"))
+ if os.read(control_fd, 1) != b"B":
+ raise RuntimeError("missing background command")
+
+ # graff is now a background job on this terminal — the #396 situation a
+ # second graff creates when it takes the foreground for itself.
+ os.tcsetpgrp(0, os.getpgrp())
+ os.write(status_fd, b"BACKGROUND\n")
+
+ deadline = time.monotonic() + EXIT_BUDGET
+ outcome = "RUNNING"
+ while time.monotonic() < deadline:
+ waited_pid, status = os.waitpid(
+ graff_pid, os.WNOHANG | os.WUNTRACED | os.WCONTINUED
+ )
+ if waited_pid == graff_pid and os.WIFSTOPPED(status):
+ outcome = f"STOPPED {os.WSTOPSIG(status)}"
+ os.kill(graff_pid, signal.SIGCONT)
+ break
+ if waited_pid == graff_pid and os.WIFEXITED(status):
+ outcome = f"EXITED {os.WEXITSTATUS(status)}"
+ break
+ if waited_pid == graff_pid and os.WIFSIGNALED(status):
+ outcome = f"KILLED {os.WTERMSIG(status)}"
+ break
+ time.sleep(0.05)
+
+ os.write(
+ status_fd,
+ f"{outcome} cooked={'yes' if cooked() else 'no'}\n".encode("ascii"),
+ )
+ if not outcome.startswith("EXITED"):
+ try:
+ os.kill(graff_pid, signal.SIGKILL)
+ os.waitpid(graff_pid, 0)
+ except (ProcessLookupError, ChildProcessError):
+ pass
+ os._exit(0 if outcome.startswith("EXITED") else 2)
+ except BaseException as exc:
+ try:
+ os.write(status_fd, f"WRAPPER_ERROR {exc!r}\n".encode("ascii"))
+ os.kill(graff_pid, signal.SIGKILL)
+ os.waitpid(graff_pid, 0)
+ except BaseException:
+ pass
+ os._exit(3)
+
+
+def main() -> None:
+ mock = CodexMock(events_for_request=unused_events)
+ port = mock.start()
+ try:
+ with tempfile.TemporaryDirectory(prefix="graff-tty-release-") as tmp:
+ codex_home = os.path.join(tmp, "codex-home")
+ os.makedirs(codex_home)
+ with open(os.path.join(codex_home, "auth.json"), "w", encoding="utf-8") as fh:
+ json.dump(
+ {
+ "tokens": {
+ "access_token": "tty-release-mock",
+ "account_id": "acct-tty-release",
+ }
+ },
+ fh,
+ )
+ harness_dir = os.path.join(tmp, ".harness")
+ os.makedirs(harness_dir)
+ with open(
+ os.path.join(harness_dir, "settings.json"), "w", encoding="utf-8"
+ ) as fh:
+ json.dump({"ai_title": False, "skills": {"codedbpro": False}}, fh)
+
+ env = {
+ key: value
+ for key, value in os.environ.items()
+ if not key.startswith("GRAFF_")
+ and not key.startswith("CODEX_")
+ and key != "NO_COLOR"
+ }
+ env.update(
+ {
+ "HOME": tmp,
+ "CODEX_HOME": codex_home,
+ "TERM": "xterm-256color",
+ "GRAFF_CODEX_URL": (
+ f"http://127.0.0.1:{port}/backend-api/codex/responses"
+ ),
+ "GRAFF_CODEX_WS": "off",
+ "GRAFF_FLEET": "off",
+ "GRAFF_LEARN_AUTO": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ }
+ )
+ argv = [
+ GRAFF,
+ "--model",
+ "codex",
+ "--no-telemetry",
+ "--no-resume",
+ "--yolo",
+ ]
+ control_r, control_w = os.pipe()
+ status_r, status_w = os.pipe()
+ wrapper_pid, master = pty.fork()
+ if wrapper_pid == 0:
+ os.close(control_w)
+ os.close(status_r)
+ wrapper(control_r, status_w, argv, tmp, env)
+
+ os.close(control_r)
+ os.close(status_w)
+ transcript = bytearray()
+ try:
+ ready = read_line(status_r)
+ if not ready.startswith("READY "):
+ raise AssertionError(f"wrapper failed to start graff: {ready}")
+ # Bracketed paste on == readLine is live and about to block on
+ # the terminal: the exact state the leftover process was in.
+ wait_for(master, b"\x1b[?2004h", transcript, 20.0)
+ os.write(control_w, b"B")
+ if read_line(status_r) != "BACKGROUND":
+ raise AssertionError("wrapper did not take the PTY foreground")
+ # Queue a byte, so a prompt that still issues a blocking read
+ # gets there (SIGTTIN) instead of idling harmlessly.
+ os.write(master, b"x")
+ outcome = read_line(status_r, timeout=EXIT_BUDGET + 10.0)
+ if outcome.startswith("STOPPED"):
+ raise AssertionError(
+ f"graff was suspended holding the terminal instead of "
+ f"releasing it: {outcome}"
+ )
+ if not outcome.startswith("EXITED"):
+ raise AssertionError(
+ f"graff did not leave the backgrounded prompt: {outcome}"
+ )
+ if "cooked=yes" not in outcome:
+ raise AssertionError(
+ f"graff exited but left the terminal in raw mode: {outcome}"
+ )
+ _, status = os.waitpid(wrapper_pid, 0)
+ if os.waitstatus_to_exitcode(status) != 0:
+ raise AssertionError(
+ f"wrapper exited {os.waitstatus_to_exitcode(status)}"
+ )
+ finally:
+ for fd in (master, control_w, status_r):
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+ try:
+ os.kill(wrapper_pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ finally:
+ mock.stop()
+
+ print("ok a backgrounded prompt released the terminal and exited")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/input_util.zig b/src/input_util.zig
index 18512a0d..da8473a4 100644
--- a/src/input_util.zig
+++ b/src/input_util.zig
@@ -32,6 +32,19 @@ const bash_stdout_cap = tools_mod.bash_stdout_cap;
pub var g_shine_phase: usize = 0; // ultracode input-wave animation frame
+/// One byte of terminal input for the editor's CONTINUATION reads — the DSR
+/// reply, an escape/CSI tail, a bracketed-paste body. Job-control aware via
+/// tty.promptByte (#396), and null means "stop reading this sequence" for both
+/// EOF and the backgrounded case, which is what every one of those call sites
+/// already did with a read error. The prompt's own idle read stays in
+/// readLine: only it can tell the two apart and must exit on the background.
+pub fn editByte(in: *Io.Reader) ?u8 {
+ return switch (terminal.tty.promptByte(in)) {
+ .byte => |b| b,
+ .eof, .background => null,
+ };
+}
+
/// Tab-completion candidates for the current input. After `/model ` →
/// model names (deduped) + provider ids matching the partial; a bare `/word`
/// → slash commands. Returns the byte offset of the word being completed
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 15038710..89bf7201 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -1,6 +1,5 @@
-//! Root interactive/JSON event loop. `main` owns setup and storage; `Ctx`
-//! contains borrowed pointers that stay valid until `run` returns for final
-//! session cleanup. Helpers are imported from their extracted sibling modules.
+//! Root interactive/JSON event loop. `main` owns setup and storage; `Ctx` holds
+//! borrowed pointers valid until `run` returns for final session cleanup.
const std = @import("std");
const Io = std.Io;
@@ -40,6 +39,7 @@ const readline = @import("readline.zig");
const title_mod = @import("title.zig");
const mainloop_title = @import("mainloop_title.zig");
const review = @import("review.zig");
+const terminal = @import("term.zig");
/// Borrowed pointers into main()'s stack plus immutable arena-owned prompt slices.
pub const Ctx = struct {
@@ -61,8 +61,8 @@ pub fn run(ctx: *Ctx) !void {
var title_jobs: mainloop_title.Jobs = .{};
defer title_jobs.deinit(ctx);
defer session.flushSavesAtExit(); // #273: the turn-path autosaves write in the background — no queued one may outlive this loop, on ANY exit (#364 stamps this teardown phase)
- // Trajectory spine state: each turn's parent is the previous turn, and a
- // changed prompt fingerprint marks a set_system_prompt mutation edge.
+ defer terminal.tty.releaseTerminal(); // #396: registered LAST so LIFO runs it FIRST — the tty goes back before the save/telemetry/learning phases that can take seconds
+ // Trajectory spine: each turn's parent is the previous; a changed prompt fingerprint marks a set_system_prompt edge.
var prev_turn_id: u64 = 0;
var prev_prompt_fp: [16]u8 = scoring.promptFingerprint(ctx.root.systemPrompt());
diff --git a/src/picker_auth.zig b/src/picker_auth.zig
index de398ac4..e1e18ec1 100644
--- a/src/picker_auth.zig
+++ b/src/picker_auth.zig
@@ -77,7 +77,7 @@ fn readSecret(root: *Agent, arena: Allocator, out: *Io.Writer) ?[]const u8 {
defer tty.restore(raw_state);
var secret: std.ArrayList(u8) = .empty;
while (true) {
- const byte = in.takeByte() catch return null;
+ const byte = @import("input_util.zig").editByte(in) orelse return null; // #396: guarded
switch (byte) {
'\r', '\n' => {
out.writeByte('\n') catch {};
diff --git a/src/pickers.zig b/src/pickers.zig
index d2b39599..abf7d27c 100644
--- a/src/pickers.zig
+++ b/src/pickers.zig
@@ -26,6 +26,7 @@ const command_catalog = @import("command_catalog.zig");
const picker_auth = @import("picker_auth.zig");
const util = @import("util.zig");
const shapes = @import("shapes.zig");
+const editByte = @import("input_util.zig").editByte; // #396: job-control-aware key reads
/// Case-insensitive subsequence match (fzf-style): every char of `needle`
/// appears in `hay` in order, gaps allowed — so "gpt5.5" matches "gpt-5.5".
@@ -274,7 +275,7 @@ pub fn modelPicker(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer)
out.writeAll(style.reset) catch {};
out.flush() catch {};
- const ch = in.takeByte() catch return null;
+ const ch = editByte(in) orelse return null;
switch (ch) {
'\r', '\n' => return if (filtered.items.len > 0) filtered.items[sel] else null,
0x03, 0x07 => return null, // Ctrl-C / Ctrl-G
@@ -283,8 +284,8 @@ pub fn modelPicker(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer)
sel = 0;
},
0x1b => {
- if ((in.takeByte() catch return null) != '[') continue;
- switch (in.takeByte() catch return null) {
+ if ((editByte(in) orelse return null) != '[') continue;
+ switch (editByte(in) orelse return null) {
'A' => if (sel > 0) {
sel -= 1;
},
@@ -370,7 +371,7 @@ pub fn listPickerAt(root: *Agent, arena: Allocator, out: *Io.Writer, title: []co
out.writeAll(style.reset) catch {};
out.flush() catch {};
- const ch = in.takeByte() catch return null;
+ const ch = editByte(in) orelse return null;
switch (ch) {
'\r', '\n' => return if (filtered.items.len > 0) filtered.items[sel] else null,
0x03, 0x07 => return null, // Ctrl-C / Ctrl-G
@@ -379,8 +380,8 @@ pub fn listPickerAt(root: *Agent, arena: Allocator, out: *Io.Writer, title: []co
sel = 0;
},
0x1b => {
- if ((in.takeByte() catch return null) != '[') return null; // bare Esc cancels
- switch (in.takeByte() catch return null) {
+ if ((editByte(in) orelse return null) != '[') return null; // bare Esc cancels
+ switch (editByte(in) orelse return null) {
'A' => if (sel > 0) {
sel -= 1;
},
diff --git a/src/readline.zig b/src/readline.zig
index 4d45c7ad..0899a241 100644
--- a/src/readline.zig
+++ b/src/readline.zig
@@ -39,6 +39,7 @@ const cleanDroppedPath = input_util.cleanDroppedPath;
const collectRepoFiles = input_util.collectRepoFiles;
const isImagePath = input_util.isImagePath;
const redraw = input_util.redraw;
+const editByte = input_util.editByte; // #396: job-control-aware continuation reads
const setLine = input_util.setLine;
const delRange = input_util.delRange;
const prevWord = input_util.prevWord;
@@ -105,8 +106,10 @@ pub fn readLine(
// A local terminal answers DSR in a few milliseconds. Do not hold
// every prompt for 500ms when a multiplexer drops/delays it: the
// main loop's CSI 'R' arm adopts a late reply without losing layout.
- if (in.buffered().len == 0 and !inputPendingTimed(20)) break :dsr;
- const b = in.takeByte() catch break :dsr;
+ if (tty.pendingBytes() == 0 and in.buffered().len == 0 and !inputPendingTimed(20)) break :dsr;
+ // #396: a byte landing in this 20ms window while we are in the
+ // background used to reach a bare blocking read → SIGTTIN → stopped.
+ const b = editByte(in) orelse break :dsr;
if (!in_esc) {
if (b == 0x1b) {
in_esc = true;
@@ -190,7 +193,20 @@ pub fn readLine(
input_util.g_shine_phase +%= 1;
redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);
}
- break :blk in.takeByte() catch return null;
+ break :blk switch (tty.promptByte(in)) {
+ .byte => |b| b,
+ .eof => return null,
+ // #396: no longer the foreground group. Blocking here anyway is
+ // what stopped a COMPLETED run ("suspended (tty input)") while it
+ // still held raw mode. Give the tty back FIRST, then quit like ^Z.
+ .background => {
+ shutdown_trace.mark("readline-background: releasing the tty");
+ tty.releaseTerminal();
+ tty.noteFromBackground("graff: no longer the foreground job — terminal released, session saved, exiting\n");
+ saveSession(root, root.arena, root.session_name) catch {};
+ return null;
+ },
+ };
};
if (c != 0x09) comp_active = false; // any non-Tab key ends the cycle
switch (c) {
@@ -334,13 +350,13 @@ pub fn readLine(
// A bare Esc (no byte follows) clears the line — without
// this the chord read below would block and silently eat
// the next keypress.
- if (in.buffered().len == 0 and !inputPending()) {
+ if (tty.pendingBytes() == 0 and in.buffered().len == 0 and !inputPending()) {
buf.clearRetainingCapacity();
cur = 0;
redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);
continue;
}
- const b1 = in.takeByte() catch break;
+ const b1 = editByte(in) orelse break; // #396: guarded
if (b1 == 0x7f or b1 == 0x08) { // Option/Alt+Delete → delete previous word
const s = prevWord(buf.items, cur);
if (s < cur) {
@@ -374,7 +390,7 @@ pub fn readLine(
var pn: usize = 0;
var final: u8 = 0;
while (true) {
- const x = in.takeByte() catch break;
+ const x = editByte(in) orelse break; // #396: guarded
if (x >= 0x40 and x <= 0x7e) {
final = x;
break;
@@ -434,7 +450,7 @@ pub fn readLine(
var blob: std.ArrayList(u8) = .empty;
defer blob.deinit(gpa);
while (true) { // read until the ESC[201~ end marker
- const x = in.takeByte() catch break;
+ const x = editByte(in) orelse break; // #396: guarded
blob.append(gpa, x) catch break;
if (std.mem.endsWith(u8, blob.items, "\x1b[201~")) {
blob.shrinkRetainingCapacity(blob.items.len - 6);
diff --git a/src/session_run.zig b/src/session_run.zig
index 161ea4ff..7ebbd754 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -1,8 +1,7 @@
-//! Agent-boot + run-loop entry helpers, split out of session_start.zig
-//! (600-line goal — session_start.zig itself crossed the line goal once this
-//! content grew). Covers everything from approvals/hooks/fleet-type loading
-//! through Agent construction, the `graff repl`/one-shot early-exit paths,
-//! session resume/finalize, and the skills/theme/PTY self-tests setup.
+//! Agent-boot + run-loop entry helpers, split out of session_start.zig (600-line
+//! goal). Covers approvals/hooks/fleet-type loading through Agent construction,
+//! the `graff repl`/one-shot early-exit paths, session resume/finalize, and the
+//! skills/theme/PTY self-tests setup.
//!
//! Same dangling-pointer discipline as session_start.zig: `buildRootAgent`
//! returns `agent_mod.Agent` by value — safe because its pointer fields
@@ -12,8 +11,7 @@
//! `restoreResumedSession`/`finalizeSession` take `root: *agent_mod.Agent` —
//! by the time any of these run, `root` is already stable main()-owned
//! storage, so passing its address around is ordinary pointer-passing.
-//! `setupSkillsAndTheme` hands back which reset `defer`s main() must register
-//! itself (a `defer` here would fire when THIS function returns, not main()).
+//! `setupSkillsAndTheme` hands back which reset `defer`s main() must register itself.
//!
//! Back-imports main (as main_mod) for Agent/the mutable globals it sets.
//! Sibling-imports everything else directly.
@@ -60,6 +58,7 @@ const run_budget_mod = @import("run_budget.zig");
const learning_privacy = @import("learning_privacy.zig");
const commands_privacy = @import("commands_privacy.zig");
const prompts = @import("prompts.zig");
+const terminal = @import("term.zig"); // #396: releaseTerminal at one-shot completion
/// `graff repl`: interactive chat REPL on the zigzag TUI, backed by the REAL
/// agent loop — each prompt runs a full root turn (tools + MCP) via
@@ -179,6 +178,7 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m
for (root.md_table.items) |r| gpa.free(r);
root.md_table.deinit(gpa);
root.tools_used.deinit(gpa);
+ terminal.tty.releaseTerminal(); // #396: the run is over — hand the tty back and latch the reader shut before main()'s teardown
}
/// Loads persisted command/tool approvals + lifecycle hooks + the MAP-Elites
diff --git a/src/term.zig b/src/term.zig
index 23035a67..7abf3e5f 100644
--- a/src/term.zig
+++ b/src/term.zig
@@ -104,6 +104,92 @@ pub const tty = struct {
}
};
+ /// Who owns the controlling terminal. A tty read issued from a BACKGROUND
+ /// process group is what raises SIGTTIN, so #396's prompt asks this before
+ /// it ever blocks. Anything unknowable answers "we do" — the pre-#396
+ /// behaviour — so a platform without the call, or a stdin that is not a
+ /// terminal, can never make Graff give up by mistake.
+ /// (std.posix.tcgetpgrp exists but resolves through std.c, which carries no
+ /// tcgetpgrp/getpgrp on Darwin — so each family declares its own: raw
+ /// syscalls on Linux, where a build may not link libc at all, and the libc
+ /// symbols everywhere else.)
+ const Foreground = if (is_windows) struct {
+ fn owned() bool {
+ return true;
+ }
+ } else if (builtin.os.tag == .linux) struct {
+ fn owned() bool {
+ var fg: std.posix.pid_t = undefined;
+ const rc = std.os.linux.tcgetpgrp(std.posix.STDIN_FILENO, &fg);
+ if (@as(isize, @bitCast(rc)) < 0) return true; // not a terminal
+ const own: std.posix.pid_t = @intCast(@as(u32, @truncate(std.os.linux.getpgid(0))));
+ return fg == own;
+ }
+ } else struct {
+ extern "c" fn tcgetpgrp(fd: std.posix.fd_t) std.posix.pid_t;
+ extern "c" fn getpgrp() std.posix.pid_t;
+
+ fn owned() bool {
+ const fg = tcgetpgrp(std.posix.STDIN_FILENO);
+ if (fg < 0) return true; // no controlling terminal / not a tty
+ return fg == getpgrp();
+ }
+ };
+
+ /// Terminal-reader lifecycle (#396), kept as pure state so the ordering
+ /// invariant — a run that has COMPLETED never blocks on the tty again — is
+ /// unit-testable with no terminal in sight. The syscalls stay in the
+ /// wrappers below; this only tracks how deep raw mode is and whether the
+ /// terminal has been handed back.
+ pub const Lifecycle = struct {
+ /// Nested raw-mode entries (a picker opened from the line editor).
+ raw_depth: u8 = 0,
+ /// The run finished and the terminal went back: no further blocking
+ /// read may be issued.
+ released: bool = false,
+
+ /// A raw-mode entry succeeded. True for the OUTERMOST one, whose saved
+ /// terminal state is the one a release has to put back.
+ pub fn entered(self: *Lifecycle) bool {
+ self.raw_depth +|= 1;
+ return self.raw_depth == 1;
+ }
+
+ /// A restore ran. True once raw mode is fully off again.
+ pub fn restored(self: *Lifecycle) bool {
+ self.raw_depth -|= 1;
+ return self.raw_depth == 0;
+ }
+
+ /// End of the run. True when raw mode is STILL on and the caller has to
+ /// put the terminal back — the leftover-process case in #396, where
+ /// teardown never reached the line editor's `defer restore`.
+ pub fn release(self: *Lifecycle) bool {
+ const still_raw = self.raw_depth > 0;
+ self.raw_depth = 0;
+ self.released = true;
+ return still_raw;
+ }
+
+ /// May a blocking read on the controlling terminal still be issued?
+ pub fn mayBlock(self: Lifecycle) bool {
+ return !self.released;
+ }
+
+ /// Re-arm for a fresh interactive session in the same process. Release
+ /// latches the reader shut; it is not a one-way door for the process.
+ pub fn rearm(self: *Lifecycle) void {
+ self.released = false;
+ }
+ };
+
+ /// Process-wide reader state. Driven from the main thread only — the Esc
+ /// watch task on the pool touches poll/readStdin, never this.
+ var life: Lifecycle = .{};
+ /// What the OUTERMOST enterRaw() captured, so a release can undo raw mode
+ /// from anywhere (including a path that never reached the editor's defer).
+ var raw_outer: ?RawState = null;
+
/// One-time: let the Windows console interpret ANSI/VT escapes. No-op
/// elsewhere. Call once from main before any styled output.
pub fn enableVtOutput() void {
@@ -155,6 +241,7 @@ pub const tty = struct {
raw |= win.ENABLE_VIRTUAL_TERMINAL_INPUT;
if (blocking) raw &= ~@as(u32, win.ENABLE_PROCESSED_INPUT) else raw |= win.ENABLE_PROCESSED_INPUT;
if (win.SetConsoleMode(h, raw) == 0) return null;
+ if (life.entered()) raw_outer = .{ .in_mode = mode };
return .{ .in_mode = mode };
}
const fd = std.posix.STDIN_FILENO;
@@ -171,11 +258,13 @@ pub const tty = struct {
var job_control = JobControlGuard.init(.output);
defer job_control.deinit();
std.posix.tcsetattr(fd, .NOW, raw) catch return null;
+ if (life.entered()) raw_outer = orig;
return orig;
}
/// Restore the mode captured by enterRaw().
pub fn restore(state: RawState) void {
+ if (life.restored()) raw_outer = null;
if (is_windows) {
_ = win.SetConsoleMode(win.GetStdHandle(win.STD_INPUT_HANDLE), state.in_mode);
return;
@@ -232,6 +321,127 @@ pub const tty = struct {
defer job_control.deinit();
return std.posix.read(std.posix.STDIN_FILENO, buf) catch 0;
}
+
+ /// Hand the controlling terminal back at the end of a run (#396): undo a raw
+ /// mode still in force and latch the reader shut, so nothing that runs after
+ /// completion can block on the tty. Idempotent; safe off a terminal.
+ pub fn releaseTerminal() void {
+ const still_raw = life.release();
+ const saved = raw_outer;
+ raw_outer = null;
+ if (still_raw) if (saved) |state| restore(state);
+ }
+
+ /// True while this process group owns the controlling terminal.
+ pub fn isForeground() bool {
+ return Foreground.owned();
+ }
+
+ /// Outcome of a blocking read on the controlling terminal.
+ pub const BlockingRead = union(enum) {
+ bytes: usize,
+ eof,
+ /// The read must not happen: this process is no longer the terminal's
+ /// foreground group, or the run already released the terminal. Do NOT
+ /// retry — retrying is what left a completed Graff stopped ("suspended
+ /// (tty input)") on a shared tty in #396.
+ background,
+ };
+
+ /// Blocking terminal read that can never be stopped by SIGTTIN: the signal
+ /// stays blocked around the syscall (#271's guard), so a read that runs from
+ /// the background fails with EIO and is REPORTED instead of suspending us.
+ pub fn readBlocking(buf: []u8) BlockingRead {
+ if (!life.mayBlock()) return .background;
+ if (is_windows) {
+ while (poll(-1)) {
+ const got = readStdin(buf);
+ if (got > 0) return .{ .bytes = got };
+ }
+ return .eof;
+ }
+ if (!isForeground()) return .background;
+ var job_control = JobControlGuard.init(.input);
+ defer job_control.deinit();
+ const n = std.posix.read(std.posix.STDIN_FILENO, buf) catch |err| switch (err) {
+ error.InputOutput => return .background, // EIO: the read ran from the background
+ else => return .eof,
+ };
+ return if (n == 0) .eof else .{ .bytes = n };
+ }
+
+ /// Prompt idle cadence. Two consecutive misses (~1s) is the grace before a
+ /// backgrounded prompt gives up, so a terminal handed over for a moment (a
+ /// shell mid-tcsetpgrp) never reads as abandoned.
+ const foreground_poll_ms: i32 = 500;
+ const background_grace: u8 = 2;
+
+ /// Wait for terminal input without ever blocking in a read this process is
+ /// not allowed to make. False means STOP READING: either input is waiting
+ /// while we sit in the background (the SIGTTIN case — the kernel would stop
+ /// us) or the terminal was released/abandoned.
+ pub fn waitForegroundInput() bool {
+ var missed: u8 = 0;
+ while (life.mayBlock()) {
+ if (poll(foreground_poll_ms)) return true;
+ if (isForeground()) {
+ missed = 0;
+ continue;
+ }
+ missed +|= 1;
+ if (missed >= background_grace) return false;
+ }
+ return false;
+ }
+
+ pub const PromptByte = union(enum) { byte: u8, eof, background };
+
+ /// Bytes the guarded read pulled off the terminal but the editor has not
+ /// consumed yet: one syscall per keystroke would be fine, one per byte of a
+ /// paste would not. Survives across readLine/picker calls exactly the way
+ /// the reader's own buffer used to, so typed-ahead still carries over.
+ var queued: [256]u8 = undefined;
+ var queued_len: usize = 0;
+ var queued_pos: usize = 0;
+
+ /// Terminal bytes already read and waiting. The editor's "is this a bare
+ /// Esc?" checks must count these as well as the reader's own buffer.
+ pub fn pendingBytes() usize {
+ return queued_len - queued_pos;
+ }
+
+ /// One byte of terminal input, job-control aware (#396). Every blocking
+ /// read the line editor and the pickers make goes through here, so none of
+ /// them can be the read the kernel stops with SIGTTIN. Order: our own
+ /// queue, then whatever the reader still holds, then a guarded read that
+ /// only happens while this process still owns the terminal.
+ pub fn promptByte(in: *std.Io.Reader) PromptByte {
+ if (queued_pos < queued_len) {
+ defer queued_pos += 1;
+ return .{ .byte = queued[queued_pos] };
+ }
+ if (in.buffered().len > 0) return if (in.takeByte()) |b| .{ .byte = b } else |_| .eof;
+ if (!waitForegroundInput()) return .background;
+ queued_len = 0;
+ queued_pos = 0;
+ switch (readBlocking(queued[0..])) {
+ .bytes => |n| {
+ queued_len = n;
+ queued_pos = 1;
+ return .{ .byte = queued[0] };
+ },
+ .eof => return .eof,
+ .background => return .background,
+ }
+ }
+
+ /// stderr with SIGTTOU blocked: the note explaining a background exit must
+ /// not itself stop Graff on a terminal with TOSTOP set.
+ pub fn noteFromBackground(msg: []const u8) void {
+ var job_control = JobControlGuard.init(.output);
+ defer job_control.deinit();
+ std.debug.print("{s}", .{msg});
+ }
};
/// Terminal column count; 80 on any failure.
@@ -289,3 +499,66 @@ pub fn inputPending() bool {
pub fn inputPendingTimed(timeout_ms: i32) bool {
return tty.poll(timeout_ms);
}
+
+test "#396 lifecycle: a completed run releases raw mode and latches the reader shut" {
+ var life: tty.Lifecycle = .{};
+ try std.testing.expect(life.mayBlock());
+ try std.testing.expect(life.entered()); // the line editor
+ try std.testing.expect(!life.entered()); // a picker opened from inside it
+ try std.testing.expect(!life.restored()); // picker closed; the editor is still raw
+ // The run ends with the editor still in raw mode — exactly the leftover
+ // process in #396. Release both reports the terminal needs putting back and
+ // stops any later blocking read from being issued.
+ try std.testing.expect(life.release());
+ try std.testing.expect(!life.mayBlock());
+ // Idempotent: teardown may release twice (mainloop defer + explicit call)
+ // and the second one must not claim there is raw mode left to undo.
+ try std.testing.expect(!life.release());
+ try std.testing.expect(!life.mayBlock());
+ life.rearm();
+ try std.testing.expect(life.mayBlock());
+}
+
+test "#396 lifecycle: a terminal already restored needs no release-time restore" {
+ var life: tty.Lifecycle = .{};
+ _ = life.entered();
+ try std.testing.expect(life.restored());
+ try std.testing.expect(!life.release()); // nothing raw left to undo
+ try std.testing.expect(!life.mayBlock()); // but the reader is still shut
+}
+
+test "#396 firewall: the idle prompt read is job-control aware and gives the tty back first" {
+ // The property is about the CALL SITE — that the ONE read which sits idle
+ // after a completed run can never be the bare blocking read the kernel
+ // stops with SIGTTIN — so it is pinned as source text (the #376 pattern).
+ const src = @embedFile("readline.zig");
+ const guarded = std.mem.indexOf(u8, src, "switch (tty.promptByte(in))").?;
+ const arm = std.mem.indexOf(u8, src[guarded..], ".background => {").? + guarded;
+ const window = src[arm..@min(src.len, arm + 700)];
+ // ORDER: hand the terminal back BEFORE the note and the session save, so a
+ // process that has already lost the foreground stops holding raw mode at
+ // once rather than after disk I/O.
+ const release_at = std.mem.indexOf(u8, window, "tty.releaseTerminal();").?;
+ const note_at = std.mem.indexOf(u8, window, "tty.noteFromBackground(").?;
+ const save_at = std.mem.indexOf(u8, window, "saveSession(root").?;
+ try std.testing.expect(release_at < note_at);
+ try std.testing.expect(note_at < save_at);
+ // And it must LEAVE, not loop back into another read of the same terminal.
+ try std.testing.expect(std.mem.indexOf(u8, window[save_at..], "return null;") != null);
+}
+
+test "#396 firewall: both completion paths release the terminal" {
+ // One-shot (`-p`, the headless --yolo path) releases at the end of the run,
+ // after the answer is printed and the session saved.
+ const oneshot = @embedFile("session_run.zig");
+ const answer_at = std.mem.indexOf(u8, oneshot, "session.saveSession(root, arena, root.session_name)").?;
+ const release_at = std.mem.indexOf(u8, oneshot, "terminal.tty.releaseTerminal();").?;
+ try std.testing.expect(answer_at < release_at);
+ // The interactive loop releases on ANY exit, and its defer is registered
+ // last so LIFO teardown runs it first — before flushSavesAtExit and the
+ // slower telemetry/learning phases main() owns.
+ const loop = @embedFile("mainloop.zig");
+ const flush_at = std.mem.indexOf(u8, loop, "defer session.flushSavesAtExit();").?;
+ const loop_release_at = std.mem.indexOf(u8, loop, "defer terminal.tty.releaseTerminal();").?;
+ try std.testing.expect(flush_at < loop_release_at);
+}