Skip to content

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

Python

fix(line-repl): frame mid-turn paste and bound image drops

yxlyx36d47cb22835
diff --git a/docs/adr/0212-line-repl-paste-is-framed-and-typed.md b/docs/adr/0212-line-repl-paste-is-framed-and-typed.md
new file mode 100644
index 00000000..0699ff00
--- /dev/null
+++ b/docs/adr/0212-line-repl-paste-is-framed-and-typed.md
@@ -0,0 +1,17 @@
+# 0212. Line-REPL pastes remain framed and typed through active turns
+
+Status: accepted 2026-09-28
+
+## Context
+
+The idle line editor enabled bracketed paste but disabled it on submit. A multiline paste during model or tool work then reached the mid-turn stdin watcher as individual keystrokes: pasted newlines queued separate steering prompts, and an empty pasted line could force an interruption. The watcher and turn-boundary queue drain also shared mutable draft state. A dropped `data:image` URI could instead fall through as prompt text. See [#1367](https://github.com/justrach/codegraff/issues/1367).
+
+## Decision
+
+Keep bracketed-paste mode enabled from the first interactive line edit until terminal release; restore the editor's modified-key mode after each line. The mid-turn scanner tracks paste markers across reads and treats their contents as one draft. Only an Enter *after* the closing marker queues it; a later empty Enter still explicitly forces the queued turn. Serialize scanner input, draft/queue mutation, and turn-boundary reset.
+
+Before expanding an idle paste as text, classify recognized image data URIs. Validate their encoding and image type, bound their size, then stage a native image attachment or reject them locally. Never submit a rejected URI as prompt text. Structured context-overflow errors do not become transient gateway retries merely because their message says to try again.
+
+## Consequences
+
+Terminals supporting bracketed paste preserve multiline steering atomically; terminals without it still cannot distinguish a paste from repeated Enter keystrokes. Every graceful line-REPL exit must disable the terminal mode. Image drops now use bounded decoding memory and fail visibly when unsupported; ordinary text pastes and genuine transient gateway retries keep their existing behavior.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 48b477c5..743fd029 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -237,6 +237,7 @@ record only when you need the evidence or the edge cases.
| [0208](0208-hot-context-keyed-updates-keep-the-prefix.md) | A mid-session instruction-file edit or date rollover is appended before the next prompt as a keyed `<context>` message (developer role on Responses, system on Chat Completions, user elsewhere), and the system prompt is left as is. Compaction drops those messages and folds the latest values into the new system prompt. |
| [0209](0209-desktop-app-has-no-computer-use.md) | The desktop app has no computer use: the `computer` tool, endpoint and menu toggle are removed; the native input bridge remains a test-only driver. Supersedes the `computer` half of 0071. |
| [0210](0210-macos-cli-is-signed-in-ci-before-upload.md) | Tag releases sign and notarize the macOS CLI tarballs on a macOS runner before anything is uploaded, gated on all five signing secrets; without them the job no-ops and docs/notarization.md is the fallback. `SHA256SUMS` is computed once from the uploaded bytes. The desktop DMG stays a local `distribute.sh` step. |
+| [0212](0212-line-repl-paste-is-framed-and-typed.md) | Keep line-REPL paste framed through active turns; submit one draft on Enter, and stage or reject bounded image data URIs before text expansion. |
## When to write one
diff --git a/src/agent_gateway_retry.zig b/src/agent_gateway_retry.zig
index 6d45d58b..e5364fce 100644
--- a/src/agent_gateway_retry.zig
+++ b/src/agent_gateway_retry.zig
@@ -92,7 +92,7 @@ pub fn afterServerErrorOrParseReject(self: *Agent, etype: []const u8, code: ?[]c
// A structured terminal code outranks transient wording in the message.
// In particular, do not retry a model the gateway cannot serve even if
// its diagnostic also mentions capacity or a request-body parse error.
- if (isModelUnavailable(code)) return false;
+ if (isModelUnavailable(code) or isStructuredOverflow(code)) return false;
if (try retryTransientServerError(self, etype, code, msg, server_retries)) return true;
if (try retryShortGatewayFlake(self, etype, code, msg, server_retries)) return true;
return retryBodyParseAfterTimeouts(self, msg, state);
@@ -100,6 +100,14 @@ pub fn afterServerErrorOrParseReject(self: *Agent, etype: []const u8, code: ?[]c
pub const max_short_flake_retries: usize = 2;
+fn isStructuredOverflow(code: ?[]const u8) bool {
+ const c = code orelse return false;
+ return std.mem.eql(u8, c, "context_length_exceeded") or
+ std.mem.eql(u8, c, "context_window_exceeded") or
+ std.mem.eql(u8, c, "model_context_window_exceeded") or
+ std.mem.eql(u8, c, "request_too_large");
+}
+
fn isModelUnavailable(code: ?[]const u8) bool {
return if (code) |c| std.mem.eql(u8, c, "model_unavailable") else false;
}
@@ -111,7 +119,7 @@ fn isModelUnavailable(code: ?[]const u8) bool {
pub fn isShortGatewayFlake(etype: []const u8, code: ?[]const u8, msg: []const u8) bool {
// Gateway 110-byte follow-up. etype is often invalid_request_error, which
// would otherwise hard-fail on the "invalid" needle. Auth/quota still die.
- if (isModelUnavailable(code)) return false;
+ if (isModelUnavailable(code) or isStructuredOverflow(code)) return false;
if (isBodyParseRejection(msg)) return true;
const hard = [_][]const u8{ "invalid", "authentication", "unauthorized", "insufficient", "quota", "permission", "tool_choice", "not found" };
for (hard) |n| {
@@ -309,6 +317,14 @@ test "isShortGatewayFlake: internal/empty api_error retry; invalid/auth/quota do
try std.testing.expect(!isShortGatewayFlake("invalid_request_error", null, "invalid prompt"));
}
+test "structured context overflow wins over gateway flake wording" {
+ const msg = "context window exceeded; please try again";
+ try std.testing.expect(!isShortGatewayFlake("api_error", "context_length_exceeded", msg));
+ try std.testing.expect(!isShortGatewayFlake("api_error", "context_window_exceeded", "Body must be valid JSON"));
+ try std.testing.expect(isShortGatewayFlake("api_error", null, "try again"));
+ try std.testing.expect(isShortGatewayFlake("invalid_request_error", null, "Body must be valid JSON"));
+}
+
test "isTransientServerError (#opencode-parity): overload/server_error retry; quota/invalid/auth do not" {
// transient server conditions → retry like a 5xx
try std.testing.expect(isTransientServerError("overloaded_error", null, ""));
diff --git a/src/agent_interrupt.zig b/src/agent_interrupt.zig
index e0ada677..900d08f1 100644
--- a/src/agent_interrupt.zig
+++ b/src/agent_interrupt.zig
@@ -18,43 +18,22 @@ const Io = std.Io;
const main_mod = @import("main.zig");
const agent_mod = @import("agent.zig");
-const repl_glue = @import("repl_glue.zig");
+const steer_input = @import("steer_input.zig");
const Agent = agent_mod.Agent;
const cancel_source = @import("cancel_source.zig"); // #728
-const ansi = @import("ansi.zig");
-const style = &ansi.style;
-
const terminal = @import("term.zig");
const tty = terminal.tty;
const Stdin = struct {
- fn read(_: *Stdin, buf: []u8) usize {
+ pub fn read(_: *Stdin, buf: []u8) usize {
return tty.readStdin(buf);
}
- fn poll(_: *Stdin, timeout_ms: i32) bool {
+ pub fn poll(_: *Stdin, timeout_ms: i32) bool {
return tty.poll(timeout_ms);
}
};
-var stdin_scan_lock: std.atomic.Value(bool) = .init(false);
-
-fn lockStdinScan() void {
- while (stdin_scan_lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();
-}
-
-fn unlockStdinScan() void {
- stdin_scan_lock.store(false, .release);
-}
-
-fn popSteerCodepoint() void {
- const items = main_mod.g_steer_buf.items;
- if (items.len == 0) return;
- var start = items.len - 1;
- while (start > 0 and items[start] & 0xc0 == 0x80) start -= 1;
- main_mod.g_steer_buf.shrinkRetainingCapacity(start);
-}
-
pub fn escWatchTask() void {
while (!Agent.esc_watch_done.load(.acquire)) {
if (tty.poll(100) and escPressed(false)) {
@@ -74,184 +53,14 @@ pub fn escWatchTask() void {
/// Enter on an empty line (double-enter) with a non-empty queue
/// force-interrupts the current turn so the queue drains immediately.
pub fn escPressed(echo: bool) bool {
- lockStdinScan();
- defer unlockStdinScan();
var input: Stdin = .{};
return escPressedFrom(&input, echo);
}
-/// Testable scanner core. `input.read` must return at most `buf.len` bytes;
-/// `input.poll` reports whether another read can supply a continuation.
+/// Testable scanner core. The stateful parser owns bracketed-paste framing;
+/// the fake-input regressions exercise this same path as the live TTY.
pub fn escPressedFrom(input: anytype, echo: bool) bool {
- var buf: [256]u8 = undefined;
- var n = input.read(&buf);
- var esc_found = false;
- var i: usize = 0;
- while (i < n) : (i += 1) {
- const c = buf[i];
- if (c == 0x1b) {
- // A modifier-prefixed key or terminal reply may put ESC at the end
- // of one VMIN=0 read. Pull the continuation into this same buffer
- // so the branches below decode it instead of discarding it.
- if (i + 1 >= n and n < buf.len and input.poll(50)) {
- n += input.read(buf[n..]);
- }
- if (i + 1 < n and buf[i + 1] == '[') {
- // CSI escape sequence (arrows, Home/End, Delete, DSR reply,
- // mouse, etc.). Consume through the final byte (0x40..0x7e) so
- // bytes like "[A" never get captured as steering prompt text. A
- // CSI run can straddle a VMIN=0 read boundary — e.g. the
- // \x1b[<row>;<col>R cursor-position reply to our \x1b[6n, or a
- // burst of SGR mouse-wheel reports if click-to-fold reporting is
- // re-enabled. If the final byte hasn't landed yet, poll briefly and
- // pull the tail into the same buffer so its trailing digits/';'/
- // final byte don't leak in as steer text.
- var j = i + 2;
- while (true) {
- while (j < n) : (j += 1) {
- if (buf[j] >= 0x40 and buf[j] <= 0x7e) break;
- }
- if (j < n or n >= buf.len or !input.poll(50)) break;
- const more = input.read(buf[n..]);
- if (more == 0) break;
- n += more;
- }
- // SGR mouse report (ESC [ < btn ; col ; row, M=press/m=release):
- // a plain left-button press (btn 0) on the live Thinking block
- // toggles its fold — the clickable control for #92. Other mouse
- // events fall through and are swallowed like any CSI sequence.
- if (j < n and buf[j] == 'M' and i + 2 < n and buf[i + 2] == '<') {
- var mk = i + 3;
- var btn: usize = 0;
- var got = false;
- while (mk < j and buf[mk] >= '0' and buf[mk] <= '9') : (mk += 1) {
- btn = btn * 10 + (buf[mk] - '0');
- got = true;
- }
- if (got and btn == 0 and main_mod.g_thinking_open) main_mod.g_thinking_fold_request = true;
- }
- i = if (j < n) j else n - 1;
- continue;
- } else if (i + 1 < n and buf[i + 1] == 'O') {
- // SS3 escape sequence (common for function/cursor keys):
- // ESC O <final>. Its final byte may arrive in a later read.
- while (i + 2 >= n and n < buf.len and input.poll(50)) {
- const more = input.read(buf[n..]);
- if (more == 0) break;
- n += more;
- }
- i = if (i + 2 < n) i + 2 else n - 1;
- continue;
- } else if (i + 1 < n and buf[i + 1] == ']') {
- // OSC — a terminal's colour/title REPLY (ESC ] … BEL, or ESC \\):
- // never a keypress, so it must not read as Esc (#728). Swallow
- // through the terminator, pulling a split tail in like CSI.
- var j = i + 2;
- var terminator: ?usize = null;
- var trailing_esc = false;
- while (true) {
- while (j < n) : (j += 1) {
- const x = buf[j];
- if (x == 0x07 or (trailing_esc and x == '\\')) {
- terminator = j;
- break;
- }
- trailing_esc = x == 0x1b;
- }
- if (terminator != null or n >= buf.len or !input.poll(50)) break;
- const more = input.read(buf[n..]);
- if (more == 0) break;
- n += more;
- }
- i = terminator orelse n - 1;
- continue;
- } else if (i + 1 < n and (buf[i + 1] == 0x7f or buf[i + 1] == 0x08)) {
- // Cmd/Option+Delete may be encoded as ESC DEL/BS. The prefix is
- // a modifier, not an interruption; leave the deletion byte for
- // the next loop iteration so it edits the steering buffer.
- continue;
- } else if (i + 1 >= n) {
- // Nothing followed within the grace window: a genuine lone Esc.
- esc_found = true;
- main_mod.g_force_interrupt = false;
- } else {
- // ESC + a non-CSI/SS3 byte in the same chunk: a real Esc.
- esc_found = true;
- main_mod.g_force_interrupt = false;
- }
- continue;
- } else if (c == '\n' or c == '\r') {
- if (main_mod.g_steer_buf.items.len > 0) {
- // Flush the typed line to the queue as a regular
- // follow-up (runs after the current turn finishes).
- // Under steerLock so concurrent drainers serialize; skip an empty
- // flush (another arm drained it first) or one byte-identical to the
- // tail, so one submit can't enqueue as N copies each re-steered with
- // its own harness note (#129).
- repl_glue.steerLock();
- if (main_mod.g_steer_buf.toOwnedSlice(std.heap.page_allocator)) |dup| {
- if (repl_glue.steerFlushRedundant(main_mod.g_steer_queue.items, dup)) {
- std.heap.page_allocator.free(dup);
- } else {
- main_mod.g_steer_queue.append(std.heap.page_allocator, .{ .text = dup, .force = false }) catch std.heap.page_allocator.free(dup);
- @import("job_wait.zig").noteFollowup();
- }
- } else |_| main_mod.g_steer_buf.clearRetainingCapacity();
- repl_glue.steerUnlock();
- if (echo and main_mod.g_steer_echoed) {
- var qbuf: [64]u8 = undefined;
- const qmsg = std.fmt.bufPrint(&qbuf, " \x1b[2m[queued · {d} waiting]\x1b[0m\n", .{main_mod.g_steer_queue.items.len}) catch "\n";
- repl_glue.steerEcho(qmsg);
- }
- } else if (main_mod.g_steer_queue.items.len > 0) {
- // Double-enter (empty line + queue non-empty): force —
- // promote the first queued item and interrupt the
- // current turn so the queue drains starting now.
- main_mod.g_steer_queue.items[0].force = true;
- esc_found = true;
- main_mod.g_force_interrupt = true;
- if (echo) {
- if (main_mod.g_steer_echoed) repl_glue.steerEcho("\n");
- repl_glue.steerEcho(style.yellow);
- repl_glue.steerEcho("↳ force › interrupting…");
- repl_glue.steerEcho(style.reset);
- repl_glue.steerEcho("\n");
- }
- }
- main_mod.g_steer_echoed = false;
- main_mod.g_steer_visible.store(false, .release);
- continue;
- } else if (c == 0x7f or c == 0x08) { // backspace / Ctrl-H
- if (main_mod.g_steer_buf.items.len > 0) {
- popSteerCodepoint();
- if (echo) repl_glue.steerEcho("\x08 \x08");
- }
- continue;
- } else if (c == 0x14) { // Ctrl-T: fold/unfold the live Thinking block (#92)
- main_mod.g_thinking_fold_request = true;
- continue;
- } else if (c < 0x20) {
- continue; // other control bytes: ignore
- }
- main_mod.g_steer_buf.append(std.heap.page_allocator, c) catch continue;
- if (echo) {
- if (!main_mod.g_steer_echoed) {
- main_mod.g_steer_visible.store(true, .release);
- repl_glue.steerLock();
- repl_glue.steerEchoUnlocked("\n");
- repl_glue.steerEchoUnlocked(style.accent);
- repl_glue.steerEchoUnlocked("↳ steer ›");
- repl_glue.steerEchoUnlocked(style.reset);
- repl_glue.steerEchoUnlocked(" ");
- main_mod.g_steer_echoed = true;
- repl_glue.steerEchoUnlocked(buf[i .. i + 1]);
- repl_glue.steerUnlock();
- } else {
- repl_glue.steerEcho(buf[i .. i + 1]);
- }
- }
- }
- return esc_found;
+ return steer_input.scan(input, echo);
}
/// Process any bytes queued on stdin (terminal must be in VMIN=0 raw
diff --git a/src/agent_interrupt_escape_edges_tests.zig b/src/agent_interrupt_escape_edges_tests.zig
index 7c57084b..20584b07 100644
--- a/src/agent_interrupt_escape_edges_tests.zig
+++ b/src/agent_interrupt_escape_edges_tests.zig
@@ -3,6 +3,7 @@
const std = @import("std");
const interrupt = @import("agent_interrupt.zig");
const main_mod = @import("main.zig");
+const repl_glue = @import("repl_glue.zig");
const page = std.heap.page_allocator;
@@ -29,7 +30,7 @@ const FakeInput = struct {
fn resetGlobals() void {
for (main_mod.g_steer_queue.items) |entry| page.free(entry.text);
main_mod.g_steer_queue.clearRetainingCapacity();
- main_mod.g_steer_buf.clearRetainingCapacity();
+ repl_glue.resetSteerPartial();
main_mod.g_steer_echoed = false;
main_mod.g_steer_visible.store(false, .release);
main_mod.g_force_interrupt = false;
diff --git a/src/agent_interrupt_repl_tests.zig b/src/agent_interrupt_repl_tests.zig
index 68b533bf..de969c02 100644
--- a/src/agent_interrupt_repl_tests.zig
+++ b/src/agent_interrupt_repl_tests.zig
@@ -3,6 +3,8 @@
const std = @import("std");
const interrupt = @import("agent_interrupt.zig");
const main_mod = @import("main.zig");
+const repl_glue = @import("repl_glue.zig");
+const job_wait = @import("job_wait.zig");
const page = std.heap.page_allocator;
@@ -29,12 +31,13 @@ const FakeInput = struct {
fn resetGlobals() void {
for (main_mod.g_steer_queue.items) |entry| page.free(entry.text);
main_mod.g_steer_queue.clearRetainingCapacity();
- main_mod.g_steer_buf.clearRetainingCapacity();
+ repl_glue.resetSteerPartial();
main_mod.g_steer_echoed = false;
main_mod.g_steer_visible.store(false, .release);
main_mod.g_force_interrupt = false;
main_mod.g_thinking_fold_request = false;
main_mod.g_thinking_open = false;
+ job_wait.followup_pending.store(false, .release);
}
test "same-read ESC DEL edits steering without interrupting" {
@@ -104,3 +107,37 @@ test "lone ESC still interrupts" {
try std.testing.expectEqual(@as(usize, 1), input.poll_calls);
try std.testing.expect(!main_mod.g_force_interrupt);
}
+
+test "mid-turn bracketed multiline paste queues once only after Enter, not on pasted blank lines" {
+ resetGlobals();
+ defer resetGlobals();
+
+ var begin = FakeInput{ .chunks = &.{"\x1b[20"} };
+ try std.testing.expect(!interrupt.escPressedFrom(&begin, false));
+ var body = FakeInput{ .chunks = &.{"0~first\n\n"} };
+ try std.testing.expect(!interrupt.escPressedFrom(&body, false));
+ const many: [256]u8 = @splat('x');
+ var middle = FakeInput{ .chunks = &.{many[0..]} };
+ try std.testing.expect(!interrupt.escPressedFrom(&middle, false));
+ var end_head = FakeInput{ .chunks = &.{"\r\nlast\x1b"} };
+ try std.testing.expect(!interrupt.escPressedFrom(&end_head, false));
+ try std.testing.expectEqual(@as(usize, 0), main_mod.g_steer_queue.items.len);
+ var end_tail = FakeInput{ .chunks = &.{"[201~"} };
+ try std.testing.expect(!interrupt.escPressedFrom(&end_tail, false));
+ try std.testing.expectEqual(@as(usize, 0), main_mod.g_steer_queue.items.len);
+
+ var submit = FakeInput{ .chunks = &.{"\r\n"} };
+ try std.testing.expect(!interrupt.escPressedFrom(&submit, false));
+ try std.testing.expectEqual(@as(usize, 1), main_mod.g_steer_queue.items.len);
+ const entry = main_mod.g_steer_queue.items[0];
+ try std.testing.expect(!entry.force);
+ try std.testing.expect(std.mem.startsWith(u8, entry.text, "first\n\n"));
+ try std.testing.expect(std.mem.endsWith(u8, entry.text, "\nlast"));
+ try std.testing.expectEqual(@as(usize, 3), std.mem.count(u8, entry.text, "\n"));
+ try std.testing.expectEqual(@as(usize, 7 + 256 + 1 + 4), entry.text.len);
+
+ var force = FakeInput{ .chunks = &.{"\r"} };
+ try std.testing.expect(interrupt.escPressedFrom(&force, false));
+ try std.testing.expect(main_mod.g_steer_queue.items[0].force);
+ try std.testing.expect(main_mod.g_force_interrupt);
+}
diff --git a/src/line_repl_terminal.zig b/src/line_repl_terminal.zig
new file mode 100644
index 00000000..675655a2
--- /dev/null
+++ b/src/line_repl_terminal.zig
@@ -0,0 +1,22 @@
+//! Keep bracketed-paste framing enabled across active line-REPL turns, not
+//! just while the idle editor is reading. The modified-key protocol remains
+//! editor-scoped; only paste mode persists until the terminal is released.
+const std = @import("std");
+const Io = std.Io;
+const tty = @import("term.zig").tty;
+const keys = @import("readline_keys.zig");
+
+var paste_enabled: std.atomic.Value(bool) = .init(false);
+
+pub fn enable(out: *Io.Writer) void {
+ out.writeAll(keys.enable_seq) catch return;
+ paste_enabled.store(true, .release);
+}
+
+pub fn release(out: *Io.Writer) void {
+ if (paste_enabled.swap(false, .acq_rel)) {
+ out.writeAll("\x1b[?2004l") catch {};
+ out.flush() catch {};
+ }
+ tty.releaseTerminal();
+}
diff --git a/src/main_test.zig b/src/main_test.zig
index b0096259..08713a79 100644
--- a/src/main_test.zig
+++ b/src/main_test.zig
@@ -363,6 +363,7 @@ test "/save and /resume report a failed name copy instead of ending the REPL" {
// unreferenced module's test {} blocks silently compile to nothing.
test {
_ = @import("startup_tests.zig");
+ _ = @import("readline_data_uri.zig"); // bracketed image drop stages through the composer into native blocks
_ = @import("recap.zig"); // #419: session-recap bounds/heuristic/parsing tests
}
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 9ef77dab..4b68cfc7 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -71,7 +71,7 @@ pub fn run(ctx: *Ctx) !void {
defer recap_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)
defer ctx.root.closeCodexWs(); // #424: the held WS + response-id anchor deliberately span turns, so only loop exit may free them — without this they are the gpa's only exit leaks
- 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
+ defer @import("line_repl_terminal.zig").release(ctx.out); // #396: registered LAST so LIFO runs it FIRST — the tty goes back before the save/telemetry/learning phases that can take seconds
var prev_turn_id: u64 = 0;
var prev_prompt_fp: [16]u8 = scoring.promptFingerprint(ctx.root.systemPrompt());
// Armed only after a clean /loop turn and consumed by the next read (#226).
diff --git a/src/readline.zig b/src/readline.zig
index b6417698..13b5a809 100644
--- a/src/readline.zig
+++ b/src/readline.zig
@@ -43,6 +43,7 @@ const editByte = input_util.editByte; // #396: job-control-aware continuation re
const addMark = input_util.addMark;
const readline_commit = @import("readline_commit.zig");
const rl_image = @import("readline_image.zig");
+const data_uri = @import("readline_data_uri.zig");
const rl_keys = @import("readline_keys.zig");
const util = @import("util.zig");
@@ -79,7 +80,7 @@ pub fn readLine(
var cur: usize = 0; // cursor index within buf
var nav: HistoryNav = .init(history.items.len); // history + unsent-draft nav (#101)
defer if (nav.draft) |d| gpa.free(d);
- out.writeAll(rl_keys.enable_seq) catch {}; // bracketed paste + distinct Cmd/Option Backspace
+ @import("line_repl_terminal.zig").enable(out); // paste stays framed during the turn
defer out.writeAll(rl_keys.restore_seq) catch {};
out.flush() catch {};
// Ask the terminal (DSR 6) where input starts; the renderer treats those columns as a fixed prefix
@@ -156,14 +157,11 @@ pub fn readLine(
var comp_idx: usize = 0;
var comp_active = false;
- // Long pastes are semantic spans: their labels render as attachment chips,
- // move atomically, and cannot be recreated by typing the same display text.
+ // Long pastes render as semantic chips, not text lookalikes.
var pastes: PasteStore = .{};
defer pastes.deinit(gpa);
- // File paths inserted by the @ picker or a drag-and-drop (plus the
- // "[Image]" attachment marker): redraw renders these spans highlighted.
- // Editing inside a span just drops its highlight — the text stays.
+ // Highlight picker/drop paths and image markers until edited.
var marks: std.ArrayList([]const u8) = .empty;
defer {
for (marks.items) |m| gpa.free(m);
@@ -210,7 +208,7 @@ pub fn readLine(
// still held raw mode. Give the tty back FIRST, then quit like ^Z.
.background => {
shutdown_trace.mark("readline-background: releasing the tty");
- tty.releaseTerminal();
+ @import("line_repl_terminal.zig").release(out);
tty.noteFromBackground("graff: no longer the foreground job — terminal released, session saved, exiting\n");
saveSession(root, root.arena, root.session_name) catch {};
return null;
@@ -237,9 +235,7 @@ pub fn readLine(
redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);
},
'\r', '\n' => {
- // Replace the manually wrapped editor block with one logical
- // terminal line. Soft wraps can then reflow after a resize;
- // authored newlines remain hard and the blank gutter remains.
+ // Commit manual soft wraps as one logical line.
readline_commit.commit(out, buf.items, marks.items, &pastes, rstate.rows, rstate.crow, prompt_col, main_mod.use_color);
// Expand live semantic paste spans; typed lookalikes stay text.
try pastes.expand(gpa, buf);
@@ -452,28 +448,37 @@ pub fn readLine(
if (std.mem.eql(u8, ps, "200")) { // bracketed paste start
var blob: std.ArrayList(u8) = .empty;
defer blob.deinit(gpa);
- while (true) { // read until the ESC[201~ end marker
- 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);
+ var tail: [6]u8 = @splat(0);
+ var truncated = false;
+ while (true) { // consume through the end marker even past the image limit
+ const x = editByte(in) orelse break;
+ std.mem.copyForwards(u8, tail[0..5], tail[1..6]);
+ tail[5] = x;
+ if (std.mem.eql(u8, &tail, "\x1b[201~")) {
+ if (!truncated) blob.shrinkRetainingCapacity(blob.items.len - 5);
break;
}
+ if (data_uri.isCandidate(blob.items) and blob.items.len >= data_uri.max_paste_bytes) {
+ truncated = true;
+ } else if (!truncated) blob.append(gpa, x) catch break;
}
- const pasted = blob.items; // preserve the complete draft, including trailing LF/CRLF (#737)
+ const pasted = blob.items;
+ const uri = data_uri.stagePaste(root, gpa, buf, &cur, &marks, &pastes, pasted, truncated);
const lines = std.mem.count(u8, pasted, "\n") + 1;
- const dropped = cleanDroppedPath(gpa, root.home, pasted);
+ const dropped = if (uri == .not_uri) cleanDroppedPath(gpa, root.home, pasted) else null;
defer if (dropped) |dp| gpa.free(dp);
const drop_exists = if (dropped) |dp| blk: {
Io.Dir.cwd().access(root.io, dp, .{}) catch break :blk false;
break :blk true;
} else false;
- if (drop_exists) {
- // Drag-and-dropped file: terminals paste the path
- // escaped/quoted with a trailing space. An image on a
- // vision model is staged as an attachment (like /image
- // and Ctrl-V); anything else inlines the cleaned full
- // path however long it is.
+ if (uri != .not_uri) {
+ if (uri != .staged) {
+ if (rstate.rows - 1 > rstate.crow) out.print("\x1b[{d}B", .{rstate.rows - 1 - rstate.crow}) catch {};
+ out.print("\r\n{s}· {s}{s}", .{ style.dim, data_uri.feedback(uri), style.reset }) catch {};
+ root.prompt() catch {};
+ rstate = .{};
+ }
+ } else if (drop_exists) {
var staged = false;
var dmsg: ?[]const u8 = null;
var dbuf: [224]u8 = undefined;
@@ -485,7 +490,6 @@ pub fn readLine(
} else if (r == .no_vision) {
dmsg = "this model can't see images — ✓ in /models' vision column shows ones that can; path inlined instead";
} else {
- // Real numbers, not "missing or >5MB" (#349).
dmsg = vision.stageMessage(&dbuf, r, "that image");
}
}
@@ -515,7 +519,7 @@ pub fn readLine(
pastes.edited(gpa, at, at, pasted.len);
cur += pasted.len;
}
- } else { // multi-line/long: semantic chip, expanded on submit
+ } else {
pastes.insert(gpa, buf, &cur, pasted, lines) catch {};
}
redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);
@@ -583,15 +587,12 @@ pub fn readLine(
}
const trimmed = std.mem.trim(u8, buf.items, " \t\r");
- // The staged image is part of the entry's identity, so the same words with
- // a different attachment are not a duplicate (#108). root.pending_image is
- // still set here — mainloop consumes it after readLine returns.
+ // Pending image distinguishes duplicate text; mainloop consumes it (#108).
const images = rl_history.g_history_images.slice();
if (trimmed.len > 0 and util.rememberInput(buf.items) and !rl_history.repeatsLast(history.items, images, buf.items, root.pending_image)) {
const dup = gpa.dupe(u8, buf.items) catch return buf.items;
history.append(gpa, dup) catch return buf.items;
- // Session-arena backed, like the base64 payload it points at, so this
- // outlives the entry without a free of its own (#108).
+ // Session arena keeps the image live for history (#108).
rl_history.g_history_images.record(root.arena, history.items.len - 1, root.pending_image);
}
return buf.items;
diff --git a/src/readline_data_uri.zig b/src/readline_data_uri.zig
new file mode 100644
index 00000000..bd9059a8
--- /dev/null
+++ b/src/readline_data_uri.zig
@@ -0,0 +1,131 @@
+//! Terminal bracketed-paste data:image URI staging. Never let rejected pixels
+//! become prompt text (including an over-budget or truncated paste).
+const std = @import("std");
+const Agent = @import("agent.zig").Agent;
+const vision = @import("vision.zig");
+const queue = @import("vision_queue.zig");
+const image = @import("readline_image.zig");
+const PasteStore = @import("readline_paste.zig").Store;
+const Allocator = std.mem.Allocator;
+
+pub const max_paste_bytes: usize = std.base64.standard.Encoder.calcSize(@intCast(vision.max_staged_image_bytes)) + 128;
+pub const Result = enum { not_uri, staged, invalid, too_large, unsupported, full, no_vision, out_of_memory };
+
+pub fn isCandidate(paste: []const u8) bool {
+ const text = std.mem.trimStart(u8, paste, " \t\r\n");
+ return text.len >= "data:image".len and std.ascii.eqlIgnoreCase(text[0.."data:image".len], "data:image");
+}
+
+pub fn feedback(r: Result) []const u8 {
+ return switch (r) {
+ .not_uri, .staged => "",
+ .invalid => "image data URI is malformed or its bytes do not match its MIME type; image not attached",
+ .too_large => "image data URI exceeds the 3.5 MB image limit; image not attached",
+ .unsupported => "unsupported image data URI type (use PNG, JPEG, GIF or WebP); image not attached",
+ .full => "image queue is full (16 images); image not attached",
+ .no_vision => vision.no_vision_message,
+ .out_of_memory => "couldn't stage image data URI (out of memory); image not attached",
+ };
+}
+
+fn matchesMagic(mime: []const u8, bytes: []const u8) bool {
+ if (std.mem.eql(u8, mime, "image/png")) return std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n");
+ if (std.mem.eql(u8, mime, "image/jpeg")) return std.mem.startsWith(u8, bytes, "\xff\xd8\xff");
+ if (std.mem.eql(u8, mime, "image/gif")) return std.mem.startsWith(u8, bytes, "GIF87a") or std.mem.startsWith(u8, bytes, "GIF89a");
+ if (std.mem.eql(u8, mime, "image/webp")) return bytes.len >= 12 and std.mem.eql(u8, bytes[0..4], "RIFF") and std.mem.eql(u8, bytes[8..12], "WEBP");
+ return false;
+}
+
+/// Called on the actual bracketed-paste path, before normal paste expansion.
+/// Even malformed image candidates are consumed, never inserted as text.
+pub fn stagePaste(root: *Agent, gpa: Allocator, buf: *std.ArrayList(u8), cur: *usize, marks: *std.ArrayList([]const u8), pastes: *PasteStore, paste: []const u8, truncated: bool) Result {
+ if (!isCandidate(paste)) return .not_uri;
+ if (truncated or paste.len > max_paste_bytes) return .too_large;
+ const text = std.mem.trim(u8, paste, " \t\r\n");
+ const sep = std.mem.indexOfScalar(u8, text, ';') orelse return .invalid;
+ const escaped = sep > 0 and text[sep - 1] == '\\';
+ const mime_text = text[5 .. sep - @as(usize, if (escaped) 1 else 0)];
+ const b64_start: usize = if (text.len >= sep + ";base64,".len and std.ascii.eqlIgnoreCase(text[sep .. sep + ";base64,".len], ";base64,")) sep + ";base64,".len else return .invalid;
+ // Use static MIME labels: `text` belongs to the temporary paste buffer.
+ const mime: []const u8 = if (std.ascii.eqlIgnoreCase(mime_text, "image/png")) "image/png" else if (std.ascii.eqlIgnoreCase(mime_text, "image/jpeg")) "image/jpeg" else if (std.ascii.eqlIgnoreCase(mime_text, "image/gif")) "image/gif" else if (std.ascii.eqlIgnoreCase(mime_text, "image/webp")) "image/webp" else return .unsupported;
+ const b64 = text[b64_start..];
+ const size = std.base64.standard.Decoder.calcSizeForSlice(b64) catch return .invalid;
+ if (size > vision.max_staged_image_bytes) return .too_large;
+ if (size == 0) return .invalid;
+ const bytes = gpa.alloc(u8, size) catch return .out_of_memory;
+ defer gpa.free(bytes);
+ std.base64.standard.Decoder.decode(bytes, b64) catch return .invalid;
+ if (!matchesMagic(mime, bytes)) return .invalid;
+ if (!vision.visionCapable(root.provider)) return .no_vision;
+ image.afterEdit(root, gpa, buf, cur);
+ if (root.pending_image_len >= queue.cap) return .full;
+ buf.ensureUnusedCapacity(gpa, "[Image #16] ".len) catch return .out_of_memory;
+ const copy = root.arena.dupe(u8, b64) catch return .out_of_memory;
+ queue.stage(root, .{ .media_type = mime, .b64 = copy, .label = "terminal image", .from_composer = true });
+ image.insertComposerChip(root, gpa, buf, cur, marks, pastes);
+ return .staged;
+}
+
+fn testAgent(gpa: Allocator) Agent {
+ return .{ .gpa = gpa, .arena = gpa, .io = undefined, .client = undefined, .provider = .{ .id = "openai", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-4o", .context = 100_000 }, .messages = undefined, .sub = false, .label = "test", .out = null };
+}
+
+test "bracketed data URI stages escaped PNG and ordinary GIF drops as native image blocks" {
+ const a = std.testing.allocator;
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ var root = testAgent(a);
+ root.arena = arena.allocator();
+ var buf: std.ArrayList(u8) = .empty;
+ defer buf.deinit(a);
+ var marks: std.ArrayList([]const u8) = .empty;
+ defer {
+ for (marks.items) |mark| a.free(mark);
+ marks.deinit(a);
+ }
+ var pastes: PasteStore = .{};
+ defer pastes.deinit(a);
+ var cur: usize = 0;
+ const owned_drop = try a.dupe(u8, "DATA:IMAGE/PNG\\;BASE64,iVBORw0KGgo=");
+ defer a.free(owned_drop);
+ try std.testing.expectEqual(Result.staged, stagePaste(&root, a, &buf, &cur, &marks, &pastes, owned_drop, false));
+ @memset(owned_drop, '?'); // the queued MIME and base64 must not borrow the paste buffer
+ try std.testing.expectEqualStrings("image/png", root.pending_images[0].media_type);
+ try std.testing.expectEqual(Result.staged, stagePaste(&root, a, &buf, &cur, &marks, &pastes, "data:image/gif;base64,R0lGODlh", false));
+ try std.testing.expectEqualStrings("[Image #1] [Image #2] ", buf.items);
+ const msg = try queue.consumePromptImages(arena.allocator(), &root, buf.items);
+ try std.testing.expectEqual(@as(usize, 3), msg.object.get("content").?.array.items.len);
+ try std.testing.expectEqualStrings("input_image", msg.object.get("content").?.array.items[1].object.get("type").?.string);
+}
+
+test "rejected image URI never enters composer or overwrites a full queue" {
+ const a = std.testing.allocator;
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ var root = testAgent(a);
+ root.arena = arena.allocator();
+ var buf: std.ArrayList(u8) = .empty;
+ defer buf.deinit(a);
+ var marks: std.ArrayList([]const u8) = .empty;
+ defer {
+ for (marks.items) |mark| a.free(mark);
+ marks.deinit(a);
+ }
+ var pastes: PasteStore = .{};
+ defer pastes.deinit(a);
+ var cur: usize = 0;
+ for ([_]struct { []const u8, Result }{
+ .{ "data:image/png\\;base64,!!!", .invalid },
+ .{ "data:image/png;base64,aGVsbG8=", .invalid },
+ .{ "data:image/svg+xml;base64,aGVsbG8=", .unsupported },
+ .{ "data:image/png;base64,iVBORw0KGgo=", .too_large },
+ }) |case| {
+ try std.testing.expectEqual(case[1], stagePaste(&root, a, &buf, &cur, &marks, &pastes, case[0], case[1] == .too_large));
+ try std.testing.expect(feedback(case[1]).len > 0);
+ try std.testing.expectEqualStrings("", buf.items);
+ }
+ for (0..queue.cap) |i| queue.stage(&root, .{ .media_type = "image/png", .b64 = try std.fmt.allocPrint(arena.allocator(), "command-{d}", .{i}), .label = "command" });
+ try std.testing.expectEqual(Result.full, stagePaste(&root, a, &buf, &cur, &marks, &pastes, "data:image/png;base64,iVBORw0KGgo=", false));
+ try std.testing.expectEqual(@as(u8, queue.cap), root.pending_image_len);
+ try std.testing.expectEqualStrings("command-15", root.pending_images[queue.cap - 1].b64);
+}
diff --git a/src/readline_keys.zig b/src/readline_keys.zig
index 03d20ade..411d6936 100644
--- a/src/readline_keys.zig
+++ b/src/readline_keys.zig
@@ -7,7 +7,7 @@
const std = @import("std");
pub const enable_seq = "\x1b[?2004h\x1b[>4;2m";
-pub const restore_seq = "\x1b[>4;0m\x1b[?2004l";
+pub const restore_seq = "\x1b[>4;0m"; // paste mode stays on through the active turn
pub const ModifiedDelete = enum {
delete_word,
@@ -118,9 +118,9 @@ fn fieldEvent(field: []const u8) ?u32 {
return std.fmt.parseInt(u32, tail, 10) catch null;
}
-test "line REPL keyboard protocol setup and restore are balanced (#981)" {
+test "line REPL restores modified keys but keeps paste framed during active turns" {
try std.testing.expectEqualStrings("\x1b[?2004h\x1b[>4;2m", enable_seq);
- try std.testing.expectEqualStrings("\x1b[>4;0m\x1b[?2004l", restore_seq);
+ try std.testing.expectEqualStrings("\x1b[>4;0m", restore_seq);
}
test "legacy ESC Delete remains Option word-delete (#981)" {
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index 326a7166..7d189a92 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -34,6 +34,7 @@ const pricing = @import("pricing.zig");
const trace = @import("trace.zig");
const serde = @import("serde.zig");
const fallback_config = @import("fallback_config.zig");
+const steer_input_state = @import("steer_input_state.zig");
pub const ReplCtx = struct {
io: Io,
@@ -427,9 +428,12 @@ pub fn popSteer() ?SteerEntry {
/// of each REPL iteration so a partial mid-turn draft never leaks into the
/// next prompt.
pub fn resetSteerPartial() void {
+ steer_input_state.lock();
+ defer steer_input_state.unlock();
steerLock();
defer steerUnlock();
main_mod.g_steer_buf.clearRetainingCapacity();
+ steer_input_state.scan = .{};
main_mod.g_steer_echoed = false;
main_mod.g_steer_visible.store(false, .release);
}
diff --git a/src/steer_input.zig b/src/steer_input.zig
new file mode 100644
index 00000000..e23dc11a
--- /dev/null
+++ b/src/steer_input.zig
@@ -0,0 +1,199 @@
+//! Mid-turn line-REPL stdin framing. Bracketed paste is one draft until the
+//! terminal's end marker; only a real Enter after that marker queues it.
+const std = @import("std");
+const main_mod = @import("main.zig");
+const repl_glue = @import("repl_glue.zig");
+const state = @import("steer_input_state.zig");
+const style = &@import("ansi.zig").style;
+const page = std.heap.page_allocator;
+
+/// `input.read` is nonblocking and returns at most buf.len bytes; `poll`
+/// supplies a short continuation for split terminal control sequences.
+pub fn scan(input: anytype, echo: bool) bool {
+ state.lock();
+ defer state.unlock();
+ var buf: [256]u8 = undefined;
+ var found = feed(buf[0..input.read(&buf)], echo);
+ var pulls: usize = 0;
+ while (state.scan.mode != .normal and pulls < 4 and input.poll(50)) : (pulls += 1) {
+ const n = input.read(&buf);
+ if (n == 0) break;
+ found = feed(buf[0..n], echo) or found;
+ }
+ if (state.scan.mode == .esc and !state.scan.in_paste) {
+ state.scan.mode = .normal;
+ main_mod.g_force_interrupt = false;
+ found = true;
+ }
+ return found;
+}
+
+fn feed(bytes: []const u8, echo: bool) bool {
+ repl_glue.steerLock();
+ defer repl_glue.steerUnlock();
+ var found = false;
+ for (bytes) |c| {
+ switch (state.scan.mode) {
+ .normal => {
+ if (c == 0x1b) {
+ state.scan.mode = .esc;
+ state.scan.entered_cr = false;
+ } else found = normalByte(c, echo) or found;
+ },
+ .esc => {
+ state.scan.mode = .normal;
+ switch (c) {
+ '[' => {
+ state.scan.mode = .csi;
+ state.scan.csi_len = 0;
+ },
+ 'O' => state.scan.mode = .ss3,
+ ']' => state.scan.mode = .osc,
+ else => {
+ // ESC DEL/BS is a modified deletion, not cancellation.
+ if (!state.scan.in_paste and c != 0x7f and c != 0x08) {
+ main_mod.g_force_interrupt = false;
+ found = true;
+ }
+ if (c == 0x1b) state.scan.mode = .esc else found = normalByte(c, echo) or found;
+ },
+ }
+ },
+ .csi => {
+ if (state.scan.csi_len < state.scan.csi.len) {
+ state.scan.csi[state.scan.csi_len] = c;
+ state.scan.csi_len += 1;
+ }
+ if (c >= 0x40 and c <= 0x7e) {
+ const seq = state.scan.csi[0..state.scan.csi_len];
+ if (std.mem.eql(u8, seq, "200~")) {
+ state.scan.in_paste = true;
+ state.scan.paste_bytes = 0;
+ state.scan.paste_lines = 1;
+ state.scan.pasted_cr = false;
+ } else if (std.mem.eql(u8, seq, "201~")) {
+ finishPaste(echo);
+ } else if (main_mod.g_thinking_open and std.mem.startsWith(u8, seq, "<0;") and c == 'M') {
+ main_mod.g_thinking_fold_request = true;
+ }
+ state.scan.mode = .normal;
+ state.scan.csi_len = 0;
+ }
+ },
+ .ss3 => state.scan.mode = .normal,
+ .osc => {
+ if (c == 0x07) state.scan.mode = .normal else if (c == 0x1b) state.scan.mode = .osc_esc;
+ },
+ .osc_esc => {
+ if (c == '\\' or c == 0x07) state.scan.mode = .normal else state.scan.mode = if (c == 0x1b) .osc_esc else .osc;
+ },
+ }
+ }
+ return found;
+}
+
+fn normalByte(c: u8, echo: bool) bool {
+ if (state.scan.in_paste) {
+ if (c == '\r') {
+ appendPaste('\n');
+ state.scan.pasted_cr = true;
+ } else if (c == '\n') {
+ if (!state.scan.pasted_cr) appendPaste('\n');
+ state.scan.pasted_cr = false;
+ } else {
+ state.scan.pasted_cr = false;
+ if (c >= 0x20 or c == '\t') appendPaste(c);
+ }
+ return false;
+ }
+ if (c == '\n' and state.scan.entered_cr) {
+ state.scan.entered_cr = false;
+ return false; // CRLF is one Enter, never a second force-Enter.
+ }
+ state.scan.entered_cr = c == '\r';
+ if (c == '\n' or c == '\r') return enter(echo);
+ if (c == 0x7f or c == 0x08) {
+ const items = main_mod.g_steer_buf.items;
+ if (items.len > 0) {
+ var start = items.len - 1;
+ while (start > 0 and items[start] & 0xc0 == 0x80) start -= 1;
+ main_mod.g_steer_buf.shrinkRetainingCapacity(start);
+ if (echo) repl_glue.steerEchoUnlocked("\x08 \x08");
+ }
+ return false;
+ }
+ if (c == 0x14) {
+ main_mod.g_thinking_fold_request = true;
+ return false;
+ }
+ if (c < 0x20) return false;
+ main_mod.g_steer_buf.append(page, c) catch return false;
+ if (echo) {
+ startEcho();
+ const one = [_]u8{c};
+ repl_glue.steerEchoUnlocked(&one);
+ }
+ return false;
+}
+
+fn appendPaste(c: u8) void {
+ main_mod.g_steer_buf.append(page, c) catch return;
+ state.scan.paste_bytes += 1;
+ if (c == '\n') state.scan.paste_lines += 1;
+}
+
+fn finishPaste(echo: bool) void {
+ if (!state.scan.in_paste) return;
+ state.scan.in_paste = false;
+ if (echo and state.scan.paste_bytes > 0) {
+ startEcho();
+ var label: [80]u8 = undefined;
+ const text = std.fmt.bufPrint(&label, "[Pasted text +{d} lines]", .{state.scan.paste_lines}) catch "[Pasted text]";
+ repl_glue.steerEchoUnlocked(text);
+ }
+}
+
+fn startEcho() void {
+ if (main_mod.g_steer_echoed) return;
+ main_mod.g_steer_visible.store(true, .release);
+ repl_glue.steerEchoUnlocked("\n");
+ repl_glue.steerEchoUnlocked(style.accent);
+ repl_glue.steerEchoUnlocked("↳ steer ›");
+ repl_glue.steerEchoUnlocked(style.reset);
+ repl_glue.steerEchoUnlocked(" ");
+ main_mod.g_steer_echoed = true;
+}
+
+fn enter(echo: bool) bool {
+ var forced = false;
+ if (main_mod.g_steer_buf.items.len > 0) {
+ if (main_mod.g_steer_buf.toOwnedSlice(page)) |text| {
+ if (repl_glue.steerFlushRedundant(main_mod.g_steer_queue.items, text)) {
+ page.free(text);
+ } else {
+ if (main_mod.g_steer_queue.append(page, .{ .text = text, .force = false })) |_| {
+ @import("job_wait.zig").noteFollowup();
+ } else |_| page.free(text);
+ }
+ } else |_| main_mod.g_steer_buf.clearRetainingCapacity();
+ if (echo and main_mod.g_steer_echoed) {
+ var label: [64]u8 = undefined;
+ const text = std.fmt.bufPrint(&label, " \x1b[2m[queued · {d} waiting]\x1b[0m\n", .{main_mod.g_steer_queue.items.len}) catch "\n";
+ repl_glue.steerEchoUnlocked(text);
+ }
+ } else if (main_mod.g_steer_queue.items.len > 0) {
+ main_mod.g_steer_queue.items[0].force = true;
+ main_mod.g_force_interrupt = true;
+ forced = true;
+ if (echo) {
+ if (main_mod.g_steer_echoed) repl_glue.steerEchoUnlocked("\n");
+ repl_glue.steerEchoUnlocked(style.yellow);
+ repl_glue.steerEchoUnlocked("↳ force › interrupting…");
+ repl_glue.steerEchoUnlocked(style.reset);
+ repl_glue.steerEchoUnlocked("\n");
+ }
+ }
+ main_mod.g_steer_echoed = false;
+ main_mod.g_steer_visible.store(false, .release);
+ return forced;
+}
diff --git a/src/steer_input_state.zig b/src/steer_input_state.zig
new file mode 100644
index 00000000..336877ca
--- /dev/null
+++ b/src/steer_input_state.zig
@@ -0,0 +1,28 @@
+//! Framing state shared by the line-REPL stdin scanner and its turn-boundary
+//! reset. The scanner lock serializes terminal reads with reset; steerLock
+//! separately protects the mutable draft/queue and stdout row.
+const std = @import("std");
+
+pub const State = struct {
+ mode: Mode = .normal,
+ csi: [64]u8 = undefined,
+ csi_len: usize = 0,
+ in_paste: bool = false,
+ paste_bytes: usize = 0,
+ paste_lines: usize = 0,
+ pasted_cr: bool = false,
+ entered_cr: bool = false,
+
+ pub const Mode = enum { normal, esc, csi, ss3, osc, osc_esc };
+};
+
+pub var scan: State = .{};
+var scan_lock: std.atomic.Value(bool) = .init(false);
+
+pub fn lock() void {
+ while (scan_lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();
+}
+
+pub fn unlock() void {
+ scan_lock.store(false, .release);
+}
diff --git a/src/term.zig b/src/term.zig
index 37f806d8..d769b28c 100644
--- a/src/term.zig
+++ b/src/term.zig
@@ -509,7 +509,7 @@ test "#396 firewall: the idle prompt read is job-control aware and gives the tty
// 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 release_at = std.mem.indexOf(u8, window, "line_repl_terminal.zig\").release(out);").?;
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);
@@ -536,7 +536,7 @@ test "#396 firewall: both completion paths release the terminal" {
// 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();").?;
+ const loop_release_at = std.mem.indexOf(u8, loop, "defer @import(\"line_repl_terminal.zig\").release(ctx.out);").?;
try std.testing.expect(flush_at < loop_release_at);
}