graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(readline): make pasted text placeholders atomic
yxlyx4fee284d177c
diff --git a/src/input_util.zig b/src/input_util.zigindex c71898df..d812912e 100644--- a/src/input_util.zig+++ b/src/input_util.zig@@ -23,6 +23,7 @@ const runCapped = jobs.runCapped;const pricing = @import("pricing.zig");const util = @import("util.zig");+const readline_paste = @import("readline_paste.zig");const main_mod = @import("main.zig");const provider_mod = @import("provider.zig");@@ -303,12 +304,12 @@ pub fn cleanDroppedPath(gpa: Allocator, home: []const u8, pasted: []const u8) ?[// Redraw the whole input below a fixed prompt prefix, wrapping it// across rows. Spans listed in `marks` (paths from the @ picker or a-// file drop, plus "[Image]") render as an accent chip (reverse video +-// Codegraff emerald) so they keep reading as attached files, not typed words; a-// chip crossing a row break keeps its colour. `st` carries the row-// count + cursor row of the previous draw so this one can clear it-// with relative moves only — no DECSC anchor for a scroll to strand.-pub fn redraw(o: *Io.Writer, items: []const u8, c: usize, marks: []const []const u8, st: *LineRender, pcol: usize) void {+// file drop, plus "[Image]") and live semantic paste spans render as accent+// chips (reverse video + Codegraff emerald), so attachments do not look like+// typed words. A chip crossing a row break keeps its colour. `st` carries the+// row count + cursor row of the previous draw so this one can clear it with+// relative moves only — no DECSC anchor for a scroll to strand.+pub fn redraw(o: *Io.Writer, items: []const u8, c: usize, marks: []const []const u8, pastes: ?*const readline_paste.Store, st: *LineRender, pcol: usize) void {const cols = termCols();const plen = if (pcol > 0) pcol - 1 else 0; // columns the prompt holds on row 0@@ -357,18 +358,21 @@ pub fn redraw(o: *Io.Writer, items: []const u8, c: usize, marks: []const []constvcol = 0;}if (!mark_open) { // open a chip that starts here (longest wins)- var best: usize = 0;+ var best_end: usize = i;for (marks) |m| {if (m.len == 0 or i + m.len > items.len) continue;- if (std.mem.eql(u8, items[i .. i + m.len], m) and m.len > best) best = m.len;+ if (std.mem.eql(u8, items[i .. i + m.len], m)) best_end = @max(best_end, i + m.len);}- if (best > 0) {+ if (pastes) |store| {+ if (store.highlightEndAt(items, i)) |end| best_end = @max(best_end, end);+ }+ if (best_end > i) {if (shine_active) {o.writeAll("\x1b[0m") catch {};shine_active = false;}o.writeAll(if (main_mod.use_color) "\x1b[7;38;2;5;150;105m" else "\x1b[7m") catch {};- mark_end = i + best;+ mark_end = best_end;mark_open = true;}}diff --git a/src/readline.zig b/src/readline.zigindex 838f6887..37019316 100644--- a/src/readline.zig+++ b/src/readline.zig@@ -40,13 +40,9 @@ 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;-const nextWord = input_util.nextWord;const addMark = input_util.addMark;const insertImageChip = input_util.insertImageChip;-const markImageChips = input_util.markImageChips;const util = @import("util.zig");const main_mod = @import("main.zig");@@ -57,6 +53,8 @@ const saveSession = session.saveSession;const shutdown_trace = @import("shutdown_trace.zig"); // #364: the quit path's first phase stampconst rl_history = @import("readline_history.zig");const HistoryNav = rl_history.HistoryNav;+const PasteStore = @import("readline_paste.zig").Store;+const replayStep = @import("readline_replay.zig").apply;/// Read one input line with a tiny raw-mode editor: ↑/↓ walk history,/// Tab completes/cycles (models, providers, slash commands), backspace edits,@@ -156,18 +154,10 @@ pub fn readLine(var comp_idx: usize = 0;var comp_active = false;- // Bracketed-paste collapse: a multi-line paste becomes a "[Pasted text #N- // +L lines]" placeholder in the buffer; on submit each placeholder is- // expanded back to its full text.- const Paste = struct { ph: []const u8, body: []const u8 };- var pastes: std.ArrayList(Paste) = .empty;- defer {- for (pastes.items) |p| {- gpa.free(p.ph);- gpa.free(p.body);- }- pastes.deinit(gpa);- }+ // Long pastes are semantic spans: their labels render as attachment chips,+ // move atomically, and cannot be recreated by typing the same display text.+ 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.@@ -192,7 +182,7 @@ pub fn readLine(while (main_mod.use_color and util.indexOfIgnoreCase(buf.items, "ultracode") != null) {if (inputPendingTimed(140)) break; // keystroke ready — read it belowinput_util.g_shine_phase +%= 1;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);}break :blk switch (tty.promptByte(in)) {.byte => |b| b,@@ -221,10 +211,12 @@ pub fn readLine(} else if (comp_items.items.len > 0) {comp_idx = (comp_idx + 1) % comp_items.items.len;} else continue;+ const old_len = buf.items.len;buf.shrinkRetainingCapacity(comp_base);buf.appendSlice(gpa, comp_items.items[comp_idx]) catch {};+ pastes.edited(gpa, comp_base, old_len, buf.items.len - comp_base);cur = buf.items.len;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},'\r', '\n' => {// The cursor may be mid-block; step past the last input row so@@ -235,50 +227,45 @@ pub fn readLine(if (rstate.rows - 1 > rstate.crow) out.print("\x1b[{d}B", .{rstate.rows - 1 - rstate.crow}) catch {};out.writeAll("\r\n\r\n") catch {};out.flush() catch {};- // Expand any pasted placeholders back to their full text.- for (pastes.items) |p| {- if (std.mem.indexOf(u8, buf.items, p.ph) == null) continue;- const sz = std.mem.replacementSize(u8, buf.items, p.ph, p.body);- const tmp = gpa.alloc(u8, sz) catch break;- _ = std.mem.replace(u8, buf.items, p.ph, p.body, tmp);- buf.clearRetainingCapacity();- buf.appendSlice(gpa, tmp) catch {};- gpa.free(tmp);- }+ // Expand live semantic paste spans; typed lookalikes stay text.+ try pastes.expand(gpa, buf);break;},0x01 => { // Ctrl-A → start of linecur = 0;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},0x05 => { // Ctrl-E → end of linecur = buf.items.len;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},0x02 => if (cur > 0) { // Ctrl-B → left- cur -= 1;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ cur = pastes.left(cur);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},0x06 => if (cur < buf.items.len) { // Ctrl-F → right- cur += 1;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ cur = pastes.right(cur, buf.items.len);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},0x17, 0x1f => { // Ctrl-W / Ctrl-_ → delete previous word- const s = prevWord(buf.items, cur);+ const s = pastes.prevWord(buf.items, cur);if (s < cur) {+ pastes.edited(gpa, s, cur, 0);delRange(buf, s, cur);cur = s;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);}},0x15 => if (cur > 0) { // Ctrl-U → delete to start of line+ pastes.edited(gpa, 0, cur, 0);delRange(buf, 0, cur);cur = 0;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},0x0b => if (cur < buf.items.len) { // Ctrl-K → delete to end of line+ pastes.edited(gpa, cur, buf.items.len, 0);buf.shrinkRetainingCapacity(cur);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},0x16 => { // Ctrl-V: attach a clipboard image (macOS) at the cursorvar mbuf: [224]u8 = undefined;@@ -290,8 +277,10 @@ pub fn readLine(vision.tracePasteResult(root, grab.flavor, staged); // #350: every paste leaves a receiptif (staged.isOk()) {@import("vision_queue.zig").markLastComposer(root);+ const at = cur;insertImageChip(gpa, buf, &cur, &marks, root.pending_image_len);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ if (cur > at) pastes.edited(gpa, at, at, cur - at);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);} else {// No `.no_vision` arm here: clipboardPasteSource// already answers .no_vision above, so on a@@ -310,13 +299,15 @@ pub fn readLine(out.print("\r\n{s}· {s}{s}", .{ style.dim, m, style.reset }) catch {};root.prompt() catch {};rstate = .{};- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);}},- 0x7f, 0x08 => if (cur > 0) { // backspace → delete char before cursor- delRange(buf, cur - 1, cur);- cur -= 1;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ 0x7f, 0x08 => if (cur > 0) { // backspace → delete previous atom+ const start = pastes.left(cur);+ pastes.edited(gpa, start, cur, 0);+ delRange(buf, start, cur);+ cur = start;+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},0x03 => { // Ctrl-C: clear a non-empty line; on an empty line, quitif (buf.items.len == 0) {@@ -325,8 +316,9 @@ pub fn readLine(return null;}buf.clearRetainingCapacity();+ pastes.clear(gpa);cur = 0;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},0x1a => { // Ctrl-Z: save the session and quit (like a safe Ctrl-D)out.writeAll("^Z — saving & quit\n") catch {};@@ -341,8 +333,10 @@ pub fn readLine(return null;}if (cur < buf.items.len) {- delRange(buf, cur, cur + 1);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ const end = pastes.right(cur, buf.items.len);+ pastes.edited(gpa, cur, end, 0);+ delRange(buf, cur, end);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);}},0x1b => { // escape sequence: arrows, Alt/Option chords, CSI@@ -351,35 +345,38 @@ pub fn readLine(// the next keypress.if (tty.pendingBytes() == 0 and in.buffered().len == 0 and !inputPending()) {buf.clearRetainingCapacity();+ pastes.clear(gpa);cur = 0;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);continue;}const b1 = editByte(in) orelse break; // #396: guardedif (b1 == 0x7f or b1 == 0x08) { // Option/Alt+Delete → delete previous word- const s = prevWord(buf.items, cur);+ const s = pastes.prevWord(buf.items, cur);if (s < cur) {+ pastes.edited(gpa, s, cur, 0);delRange(buf, s, cur);cur = s;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);}continue;}if (b1 == 'b') { // Alt-b → word left- cur = prevWord(buf.items, cur);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ cur = pastes.prevWord(buf.items, cur);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);continue;}if (b1 == 'f') { // Alt-f → word right- cur = nextWord(buf.items, cur);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ cur = pastes.nextWord(buf.items, cur);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);continue;}if (b1 == 'd') { // Alt-d → delete next word- const e = nextWord(buf.items, cur);+ const e = pastes.nextWord(buf.items, cur);if (e > cur) {+ pastes.edited(gpa, cur, e, 0);delRange(buf, cur, e);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);}continue;}@@ -403,28 +400,28 @@ pub fn readLine(const word_mod = std.mem.indexOfScalar(u8, ps, ';') != null; // 1;3 (alt) / 1;5 (ctrl)switch (final) {'A' => if (nav.up(gpa, history.items, rl_history.g_history_images.slice(), buf.items, root.pending_image)) |step| { // up → history back; snapshots draft (#101)- replayStep(root, gpa, buf, &cur, &marks, step);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ replayStep(root, gpa, buf, &cur, &marks, &pastes, step);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},'B' => if (nav.down(history.items, rl_history.g_history_images.slice())) |step| { // down → history forward; restores draft past newest (#101)- replayStep(root, gpa, buf, &cur, &marks, step);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ replayStep(root, gpa, buf, &cur, &marks, &pastes, step);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},'C' => { // right (word-right with a modifier)- cur = if (word_mod) nextWord(buf.items, cur) else @min(cur + 1, buf.items.len);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ cur = if (word_mod) pastes.nextWord(buf.items, cur) else pastes.right(cur, buf.items.len);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},'D' => { // left (word-left with a modifier)- cur = if (word_mod) prevWord(buf.items, cur) else (if (cur > 0) cur - 1 else 0);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ cur = if (word_mod) pastes.prevWord(buf.items, cur) else pastes.left(cur);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},'H' => {cur = 0;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},'F' => {cur = buf.items.len;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},'R' => { // late DSR cursor-position reply (slow or// multiplexed terminal missed the 20ms startup@@ -442,7 +439,7 @@ pub fn readLine(} else prompt_col = col;}}- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},'~' => {if (std.mem.eql(u8, ps, "200")) { // bracketed paste start@@ -487,11 +484,18 @@ pub fn readLine(}if (staged) {@import("vision_queue.zig").markLastComposer(root);+ const at = cur;insertImageChip(gpa, buf, &cur, &marks, root.pending_image_len);+ if (cur > at) pastes.edited(gpa, at, at, cur - at);} else {+ const at = cur;+ const old_len = buf.items.len;buf.insertSlice(gpa, cur, dropped.?) catch {};- cur += dropped.?.len;- addMark(gpa, &marks, dropped.?);+ if (buf.items.len == old_len + dropped.?.len) {+ pastes.edited(gpa, at, at, dropped.?.len);+ cur += dropped.?.len;+ addMark(gpa, &marks, dropped.?);+ }}if (dmsg) |m| { // feedback below the input, then redraw fresh (below)if (rstate.rows - 1 > rstate.crow) out.print("\x1b[{d}B", .{rstate.rows - 1 - rstate.crow}) catch {};@@ -500,29 +504,30 @@ pub fn readLine(rstate = .{};}} else if (lines == 1 and pasted.len <= 80) {+ const at = cur;+ const old_len = buf.items.len;buf.insertSlice(gpa, cur, pasted) catch {}; // short single-line paste: inline- cur += pasted.len;- } else { // multi-line/long: collapse to a placeholder, expand on submit- const ph = std.fmt.allocPrint(gpa, "[Pasted text #{d} +{d} lines]", .{ pastes.items.len + 1, lines }) catch "";- const body = gpa.dupe(u8, pasted) catch "";- if (ph.len > 0 and body.len > 0) {- pastes.append(gpa, .{ .ph = ph, .body = body }) catch {};- buf.insertSlice(gpa, cur, ph) catch {};- cur += ph.len;+ if (buf.items.len == old_len + pasted.len) {+ pastes.edited(gpa, at, at, pasted.len);+ cur += pasted.len;}+ } else { // multi-line/long: semantic chip, expanded on submit+ pastes.insert(gpa, buf, &cur, pasted, lines) catch {};}- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);} else if (std.mem.eql(u8, ps, "3")) { // forward deleteif (cur < buf.items.len) {- delRange(buf, cur, cur + 1);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ const end = pastes.right(cur, buf.items.len);+ pastes.edited(gpa, cur, end, 0);+ delRange(buf, cur, end);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);}} else if (std.mem.eql(u8, ps, "1") or std.mem.eql(u8, ps, "7")) {cur = 0;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);} else if (std.mem.eql(u8, ps, "4") or std.mem.eql(u8, ps, "8")) {cur = buf.items.len;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);}},else => {},@@ -549,17 +554,27 @@ pub fn readLine(// screen and cursor on exit, so the input block and// rstate still match — just redraw over them below.if (picked) |idx| {+ const at = cur;+ const old_len = buf.items.len;buf.insertSlice(gpa, cur, files.items[idx]) catch {};- cur += files.items[idx].len;- addMark(gpa, &marks, files.items[idx]);+ if (buf.items.len == old_len + files.items[idx].len) {+ pastes.edited(gpa, at, at, files.items[idx].len);+ cur += files.items[idx].len;+ addMark(gpa, &marks, files.items[idx]);+ }}- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);continue;}}+ const at = cur;+ const old_len = buf.items.len;buf.insert(gpa, cur, c) catch {};- cur += 1;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ if (buf.items.len == old_len + 1) {+ pastes.edited(gpa, at, at, 1);+ cur += 1;+ }+ redraw(out, buf.items, cur, marks.items, &pastes, &rstate, prompt_col);},}}@@ -578,20 +593,3 @@ pub fn readLine(}return buf.items;}--/// Apply one history step to the editor: text into the buffer, and the entry's-/// attachment back onto the agent so resending sends the image and not just the-/// literal "[Image]" marker (#108). A text-only entry clears whatever was staged.-fn replayStep(- root: *Agent,- gpa: Allocator,- buf: *std.ArrayList(u8),- cur: *usize,- marks: *std.ArrayList([]const u8),- step: rl_history.Step,-) void {- setLine(gpa, buf, step.text);- cur.* = buf.items.len;- root.pending_image = step.image;- if (step.image != null) markImageChips(gpa, marks, buf.items);-}diff --git a/src/readline_paste.zig b/src/readline_paste.zignew file mode 100644index 00000000..9206d512--- /dev/null+++ b/src/readline_paste.zig@@ -0,0 +1,338 @@+//! Semantic long-paste spans for the raw readline composer (#673).+//!+//! The visible `[Pasted text …]` label is presentation, not identity. Each live+//! span owns its hidden body and tracks its byte range as surrounding text is+//! edited. An edit touching the range detaches it, so retyping the same label+//! cannot resurrect a removed paste.++const std = @import("std");+const Allocator = std.mem.Allocator;++const Entry = struct {+ start: usize,+ end: usize,+ label: []u8,+ body: []u8,+};++pub const Store = struct {+ entries: std.ArrayList(Entry) = .empty,+ next_id: usize = 1,++ pub fn deinit(self: *Store, gpa: Allocator) void {+ self.clear(gpa);+ self.entries.deinit(gpa);+ }++ pub fn clear(self: *Store, gpa: Allocator) void {+ for (self.entries.items) |entry| freeEntry(gpa, entry);+ self.entries.clearRetainingCapacity();+ }++ pub fn count(self: *const Store) usize {+ return self.entries.items.len;+ }++ /// Insert one collapsed long paste at the cursor. Existing spans move with+ /// the surrounding text; the new span is inserted in positional order.+ pub fn insert(+ self: *Store,+ gpa: Allocator,+ buf: *std.ArrayList(u8),+ cursor: *usize,+ body: []const u8,+ lines: usize,+ ) !void {+ const label = try std.fmt.allocPrint(gpa, "[Pasted text #{d} +{d} lines]", .{ self.next_id, lines });+ errdefer gpa.free(label);+ const owned_body = try gpa.dupe(u8, body);+ errdefer gpa.free(owned_body);+ try self.entries.ensureUnusedCapacity(gpa, 1);+ try buf.insertSlice(gpa, cursor.*, label);+ self.edited(gpa, cursor.*, cursor.*, label.len);+ self.entries.appendAssumeCapacity(.{+ .start = cursor.*,+ .end = cursor.* + label.len,+ .label = label,+ .body = owned_body,+ });+ std.mem.sort(Entry, self.entries.items, {}, lessThan);+ self.next_id += 1;+ cursor.* += label.len;+ }++ /// Update semantic ranges after replacing `[from,to)` with `inserted_len`+ /// bytes. Touching any part of a span detaches it; edits at either boundary+ /// remain ordinary surrounding edits.+ pub fn edited(self: *Store, gpa: Allocator, from: usize, to: usize, inserted_len: usize) void {+ std.debug.assert(from <= to);+ const removed_len = to - from;+ var i: usize = 0;+ while (i < self.entries.items.len) {+ const entry = &self.entries.items[i];+ if (to <= entry.start) {+ shift(entry, removed_len, inserted_len);+ i += 1;+ } else if (from >= entry.end) {+ i += 1;+ } else {+ freeEntry(gpa, self.entries.orderedRemove(i));+ }+ }+ }++ /// Replace every live semantic span with its body, then consume the entries.+ /// Lookalike text without an entry is copied verbatim, and a stale/corrupt+ /// range is never expanded.+ pub fn expand(self: *Store, gpa: Allocator, buf: *std.ArrayList(u8)) !void {+ if (self.entries.items.len == 0) return;+ var out: std.ArrayList(u8) = .empty;+ defer out.deinit(gpa);+ var source: usize = 0;+ var expanded = false;+ for (self.entries.items) |entry| {+ if (entry.start < source or entry.end > buf.items.len) continue;+ if (!std.mem.eql(u8, buf.items[entry.start..entry.end], entry.label)) continue;+ try out.appendSlice(gpa, buf.items[source..entry.start]);+ try out.appendSlice(gpa, entry.body);+ source = entry.end;+ expanded = true;+ }+ if (!expanded) return;+ try out.appendSlice(gpa, buf.items[source..]);+ try buf.ensureTotalCapacity(gpa, out.items.len);+ buf.clearRetainingCapacity();+ try buf.appendSlice(gpa, out.items);+ self.clear(gpa);+ }++ /// End byte for the live span beginning at `at`, used by readline's chip+ /// renderer. Position plus label validation prevents a typed lookalike at a+ /// different location from receiving attachment styling.+ pub fn highlightEndAt(self: *const Store, items: []const u8, at: usize) ?usize {+ for (self.entries.items) |entry| {+ if (entry.start != at or entry.end > items.len) continue;+ if (std.mem.eql(u8, items[entry.start..entry.end], entry.label)) return entry.end;+ }+ return null;+ }++ pub fn left(self: *const Store, cursor: usize) usize {+ for (self.entries.items) |entry| {+ if (cursor > entry.start and cursor <= entry.end) return entry.start;+ }+ return cursor -| 1;+ }++ pub fn right(self: *const Store, cursor: usize, len: usize) usize {+ for (self.entries.items) |entry| {+ if (cursor >= entry.start and cursor < entry.end) return entry.end;+ }+ return @min(cursor + 1, len);+ }++ pub fn prevWord(self: *const Store, items: []const u8, cursor: usize) usize {+ for (self.entries.items) |entry| {+ if (cursor > entry.start and cursor <= entry.end) return entry.start;+ }+ const plain = plainPrevWord(items, cursor);+ for (self.entries.items) |entry| {+ if (plain > entry.start and plain < entry.end) return entry.start;+ }+ return plain;+ }++ pub fn nextWord(self: *const Store, items: []const u8, cursor: usize) usize {+ for (self.entries.items) |entry| {+ if (cursor >= entry.start and cursor < entry.end) return entry.end;+ }+ const plain = plainNextWord(items, cursor);+ for (self.entries.items) |entry| {+ if (plain > entry.start and plain < entry.end) return entry.end;+ }+ return plain;+ }+};++fn lessThan(_: void, a: Entry, b: Entry) bool {+ return a.start < b.start;+}++fn freeEntry(gpa: Allocator, entry: Entry) void {+ gpa.free(entry.label);+ gpa.free(entry.body);+}++fn shift(entry: *Entry, removed_len: usize, inserted_len: usize) void {+ if (inserted_len >= removed_len) {+ const delta = inserted_len - removed_len;+ entry.start += delta;+ entry.end += delta;+ } else {+ const delta = removed_len - inserted_len;+ entry.start -= delta;+ entry.end -= delta;+ }+}++fn plainPrevWord(items: []const u8, cursor: usize) usize {+ var i = cursor;+ while (i > 0 and items[i - 1] == ' ') i -= 1;+ while (i > 0 and items[i - 1] != ' ') i -= 1;+ return i;+}++fn plainNextWord(items: []const u8, cursor: usize) usize {+ var i = cursor;+ while (i < items.len and items[i] == ' ') i += 1;+ while (i < items.len and items[i] != ' ') i += 1;+ return i;+}++fn deleteRange(buf: *std.ArrayList(u8), from: usize, to: usize) void {+ std.mem.copyForwards(u8, buf.items[from..], buf.items[to..]);+ buf.shrinkRetainingCapacity(buf.items.len - (to - from));+}++const testing = std.testing;++test "paste span is highlighted and navigated as one unit" {+ var store: Store = .{};+ defer store.deinit(testing.allocator);+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(testing.allocator);+ try buf.appendSlice(testing.allocator, "before after");+ var cursor: usize = 7;+ try store.insert(testing.allocator, &buf, &cursor, "one\ntwo", 2);+ const start: usize = 7;+ const end = cursor;++ try testing.expectEqual(end, store.highlightEndAt(buf.items, start).?);+ try testing.expectEqual(start, store.left(end));+ try testing.expectEqual(end, store.right(start, buf.items.len));+ try testing.expectEqual(start, store.prevWord(buf.items, end));+ try testing.expectEqual(end, store.nextWord(buf.items, start));+}++test "deleting a span prevents a typed lookalike from resurrecting its body" {+ var store: Store = .{};+ defer store.deinit(testing.allocator);+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(testing.allocator);+ var cursor: usize = 0;+ try store.insert(testing.allocator, &buf, &cursor, "secret\nbody", 2);+ const label = try testing.allocator.dupe(u8, buf.items);+ defer testing.allocator.free(label);++ store.edited(testing.allocator, 0, cursor, 0);+ deleteRange(&buf, 0, cursor);+ try buf.appendSlice(testing.allocator, label);+ store.edited(testing.allocator, 0, 0, label.len);+ try store.expand(testing.allocator, &buf);++ try testing.expectEqual(@as(usize, 0), store.count());+ try testing.expectEqualStrings(label, buf.items);+ try testing.expect(store.highlightEndAt(buf.items, 0) == null);+}++test "two paste spans expand independently exactly once" {+ var store: Store = .{};+ defer store.deinit(testing.allocator);+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(testing.allocator);+ var cursor: usize = 0;+ try store.insert(testing.allocator, &buf, &cursor, "alpha\nbeta", 2);+ try buf.insertSlice(testing.allocator, cursor, " + ");+ store.edited(testing.allocator, cursor, cursor, 3);+ cursor += 3;+ try store.insert(testing.allocator, &buf, &cursor, "gamma\ndelta", 2);+ try store.expand(testing.allocator, &buf);++ try testing.expectEqualStrings("alpha\nbeta + gamma\ndelta", buf.items);+}++test "removing one paste keeps and shifts the other" {+ var store: Store = .{};+ defer store.deinit(testing.allocator);+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(testing.allocator);+ var cursor: usize = 0;+ try store.insert(testing.allocator, &buf, &cursor, "first\nbody", 2);+ const first_end = cursor;+ try buf.insertSlice(testing.allocator, cursor, " ");+ store.edited(testing.allocator, cursor, cursor, 1);+ cursor += 1;+ try store.insert(testing.allocator, &buf, &cursor, "second\nbody", 2);++ store.edited(testing.allocator, 0, first_end, 0);+ deleteRange(&buf, 0, first_end);+ try store.expand(testing.allocator, &buf);++ try testing.expectEqual(@as(usize, 0), store.count());+ try testing.expectEqualStrings(" second\nbody", buf.items);+}++test "surrounding insertions shift a span without detaching it" {+ var store: Store = .{};+ defer store.deinit(testing.allocator);+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(testing.allocator);+ var cursor: usize = 0;+ try store.insert(testing.allocator, &buf, &cursor, "kept\nbody", 2);+ try buf.insertSlice(testing.allocator, 0, "prefix ");+ store.edited(testing.allocator, 0, 0, 7);+ try buf.appendSlice(testing.allocator, " suffix");+ store.edited(testing.allocator, buf.items.len - 7, buf.items.len - 7, 7);+ try store.expand(testing.allocator, &buf);++ try testing.expectEqualStrings("prefix kept\nbody suffix", buf.items);+}++test "typed duplicate beside a live span stays literal and unhighlighted" {+ var store: Store = .{};+ defer store.deinit(testing.allocator);+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(testing.allocator);+ var cursor: usize = 0;+ try store.insert(testing.allocator, &buf, &cursor, "real\nbody", 2);+ const label = try testing.allocator.dupe(u8, buf.items);+ defer testing.allocator.free(label);+ try buf.append(testing.allocator, ' ');+ try buf.appendSlice(testing.allocator, label);+ store.edited(testing.allocator, cursor, cursor, label.len + 1);++ try testing.expect(store.highlightEndAt(buf.items, cursor + 1) == null);+ try store.expand(testing.allocator, &buf);+ try testing.expectEqualStrings("real\nbody [Pasted text #1 +2 lines]", buf.items);+}++test "paste ids are not reused after an attachment is removed" {+ var store: Store = .{};+ defer store.deinit(testing.allocator);+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(testing.allocator);+ var cursor: usize = 0;+ try store.insert(testing.allocator, &buf, &cursor, "first\nbody", 2);+ store.edited(testing.allocator, 0, cursor, 0);+ deleteRange(&buf, 0, cursor);+ cursor = 0;+ try store.insert(testing.allocator, &buf, &cursor, "second\nbody", 2);++ try testing.expectEqualStrings("[Pasted text #2 +2 lines]", buf.items);+}++test "expansion consumes identity even when the body begins with its label" {+ var store: Store = .{};+ defer store.deinit(testing.allocator);+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(testing.allocator);+ var cursor: usize = 0;+ const body = "[Pasted text #1 +2 lines]\nX";+ try store.insert(testing.allocator, &buf, &cursor, body, 2);++ try store.expand(testing.allocator, &buf);+ try store.expand(testing.allocator, &buf);++ try testing.expectEqual(@as(usize, 0), store.count());+ try testing.expectEqualStrings(body, buf.items);+}diff --git a/src/readline_replay.zig b/src/readline_replay.zignew file mode 100644index 00000000..abfce227--- /dev/null+++ b/src/readline_replay.zig@@ -0,0 +1,28 @@+//! History-step replay for the raw readline composer.+//!+//! Replacing the draft invalidates semantic paste spans: history stores their+//! display labels, not their hidden bodies, so a replayed lookalike must remain+//! ordinary text rather than resurrecting an attachment (#673).++const std = @import("std");+const Allocator = std.mem.Allocator;+const Agent = @import("agent.zig").Agent;+const input_util = @import("input_util.zig");+const PasteStore = @import("readline_paste.zig").Store;+const Step = @import("readline_history.zig").Step;++pub fn apply(+ root: *Agent,+ gpa: Allocator,+ buf: *std.ArrayList(u8),+ cursor: *usize,+ marks: *std.ArrayList([]const u8),+ pastes: *PasteStore,+ step: Step,+) void {+ pastes.clear(gpa);+ input_util.setLine(gpa, buf, step.text);+ cursor.* = buf.items.len;+ root.pending_image = step.image;+ if (step.image != null) input_util.markImageChips(gpa, marks, buf.items);+}