graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Fix TUI pasted item boundaries and file spans
yxlyxb2d23810dc01
diff --git a/TUI/app.zig b/TUI/app.zigindex 1eff96e6..836406de 100644--- a/TUI/app.zig+++ b/TUI/app.zig@@ -84,7 +84,7 @@ pub const Model = struct {prompt_hist: std.array_list.Managed([]const u8),/// Image paths index-aligned with `prompt_hist` (#577). Empty slice = text-only.prompt_hist_images: std.array_list.Managed([]const []const u8),- draft_text: ?[]u8 = null,+ draft_input: ?input_mod.State = null,draft_images: ?[]const []const u8 = null,steer_queue: std.array_list.Managed([]const u8),images: std.array_list.Managed([]const u8),diff --git a/TUI/chrome.zig b/TUI/chrome.zigindex c2186f93..6ac16e06 100644--- a/TUI/chrome.zig+++ b/TUI/chrome.zig@@ -49,7 +49,7 @@ pub fn promptBox(self: *const Model, a: std.mem.Allocator, width: usize) ![]constry body.appendSlice(try imageChips(self, a, th.accent, th.text));try body.appendSlice(" ");}- try body.appendSlice(try self.input.view(a));+ try body.appendSlice(try self.input.viewStyled(a, th.accent, th.text));const wrapped = try theme_mod.wrapPreferWords(a, body.items, inner);var lines = std.array_list.Managed([]const u8).init(a);var it = std.mem.splitScalar(u8, wrapped, '\n');diff --git a/TUI/composer_paste.zig b/TUI/composer_paste.zignew file mode 100644index 00000000..a4454d3c--- /dev/null+++ b/TUI/composer_paste.zig@@ -0,0 +1,95 @@+//! Origin-aware bracketed-paste finalization for the TUI composer (#792).+//!+//! The decoder owns paste framing. This module owns the exact inserted range:+//! text receives a removable trailing separator, pasted file paths become+//! semantic spans, and an image consumes only its own pasted bytes.++const std = @import("std");+const app = @import("app.zig");+const dispatch = @import("dispatch.zig");+const image = @import("image.zig");+const Model = app.Model;++pub fn begin(self: *Model) void {+ self.input.beginPaste();+}++pub fn finish(self: *Model) void {+ const range = self.input.pasteRange() orelse {+ self.input.endPaste();+ return;+ };+ defer self.input.endPaste();+ if (range.start == range.end) return;++ const raw = self.input.getValue()[range.start..range.end];+ const path = normalizePath(self.alloc, raw) orelse {+ self.input.ensurePasteSeparator();+ return;+ };+ defer self.alloc.free(path);++ if (dispatch.looksLikeImagePath(path) and image.attachDropped(self, path)) {+ _ = self.input.replacePaste(range, "", false);+ return;+ }+ if (!pathExists(path)) {+ self.input.ensurePasteSeparator();+ return;+ }+ if (self.input.replacePaste(range, path, true)) self.input.ensurePasteSeparator();+}++fn pathExists(path: []const u8) bool {+ const io = std.Io.Threaded.global_single_threaded.io();+ _ = std.Io.Dir.cwd().statFile(io, path, .{}) catch return false;+ return true;+}++/// Normalize the one-path forms terminals emit for Finder paste/drop. Mixed+/// prose and multiline payloads remain ordinary pasted text.+fn normalizePath(alloc: std.mem.Allocator, raw: []const u8) ?[]u8 {+ var src = std.mem.trim(u8, raw, " \t\r\n");+ if (src.len < 2 or std.mem.indexOfAny(u8, src, "\r\n") != null) return null;+ if ((src[0] == '\'' and src[src.len - 1] == '\'') or (src[0] == '"' and src[src.len - 1] == '"')) {+ src = src[1 .. src.len - 1];+ }+ if (std.mem.startsWith(u8, src, "file://")) src = src["file://".len..];++ var out = std.array_list.Managed(u8).init(alloc);+ defer out.deinit();+ var i: usize = 0;+ while (i < src.len) {+ const c = src[i];+ if (c == 0 or (c < 0x20 and c != '\t')) return null;+ if (c == '%' and i + 2 < src.len) {+ const hi = hexNibble(src[i + 1]);+ const lo = hexNibble(src[i + 2]);+ if (hi != null and lo != null) {+ const decoded = (hi.? << 4) | lo.?;+ if (decoded == 0 or decoded < 0x20) return null;+ out.append(decoded) catch return null;+ i += 3;+ continue;+ }+ }+ if (c == '\\' and i + 1 < src.len) {+ out.append(src[i + 1]) catch return null;+ i += 2;+ continue;+ }+ out.append(c) catch return null;+ i += 1;+ }+ if (out.items.len == 0 or out.items[0] != '/') return null;+ return out.toOwnedSlice() catch null;+}++fn hexNibble(c: u8) ?u8 {+ return switch (c) {+ '0'...'9' => c - '0',+ 'a'...'f' => c - 'a' + 10,+ 'A'...'F' => c - 'A' + 10,+ else => null,+ };+}diff --git a/TUI/input.zig b/TUI/input.zigindex f4916ae7..c72a4172 100644--- a/TUI/input.zig+++ b/TUI/input.zig@@ -4,48 +4,109 @@ const std = @import("std");const glyphs = @import("glyphs.zig");const Key = @import("key.zig").Key;-const Snap = struct { text: []u8, cursor: usize };+pub const Span = struct {+ start: usize,+ end: usize,+};++pub const State = struct {+ text: []u8,+ cursor: usize,+ spans: []Span,+};++const Snap = State;+pub const Range = struct { start: usize, end: usize };pub const Input = struct {alloc: std.mem.Allocator,buf: std.array_list.Managed(u8),+ spans: std.array_list.Managed(Span),undo_stack: std.array_list.Managed(Snap),cursor: usize = 0,placeholder: []const u8 = "",+ paste_start: ?usize = null,+ compound_edit: bool = false,+ compound_snapshot: bool = false,pub fn init(alloc: std.mem.Allocator) Input {return .{.alloc = alloc,.buf = std.array_list.Managed(u8).init(alloc),+ .spans = std.array_list.Managed(Span).init(alloc),.undo_stack = std.array_list.Managed(Snap).init(alloc),};}pub fn deinit(self: *Input) void {- for (self.undo_stack.items) |sn| self.alloc.free(sn.text);+ for (self.undo_stack.items) |sn| freeState(self.alloc, sn);self.undo_stack.deinit();+ self.spans.deinit();self.buf.deinit();}+ pub fn snapshot(self: *const Input) !State {+ const text = try self.alloc.dupe(u8, self.buf.items);+ errdefer self.alloc.free(text);+ return .{+ .text = text,+ .cursor = self.cursor,+ .spans = try self.alloc.dupe(Span, self.spans.items),+ };+ }++ pub fn freeSnapshot(self: *const Input, state: State) void {+ freeState(self.alloc, state);+ }++ pub fn setState(self: *Input, state: State) !void {+ self.pushUndo();+ try self.buf.ensureTotalCapacity(state.text.len);+ try self.spans.ensureTotalCapacity(state.spans.len);+ self.buf.clearRetainingCapacity();+ self.spans.clearRetainingCapacity();+ try self.buf.appendSlice(state.text);+ try self.spans.appendSlice(state.spans);+ self.cursor = @min(state.cursor, self.buf.items.len);+ self.paste_start = null;+ self.compound_edit = false;+ self.compound_snapshot = false;+ }+fn pushUndo(self: *Input) void {- const text = self.alloc.dupe(u8, self.buf.items) catch return;- self.undo_stack.append(.{ .text = text, .cursor = self.cursor }) catch {- self.alloc.free(text);+ const snap = self.snapshot() catch return;+ self.undo_stack.append(snap) catch {+ freeState(self.alloc, snap);return;};if (self.undo_stack.items.len > 64) {- const old = self.undo_stack.orderedRemove(0);- self.alloc.free(old.text);+ freeState(self.alloc, self.undo_stack.orderedRemove(0));+ }+ }++ fn maybePushUndo(self: *Input) void {+ if (!self.compound_edit) {+ self.pushUndo();+ } else if (!self.compound_snapshot) {+ self.pushUndo();+ self.compound_snapshot = true;}}/// Restore the previous snapshot. False when the stack is empty.pub fn undo(self: *Input) bool {const snap = self.undo_stack.pop() orelse return false;- defer self.alloc.free(snap.text);+ defer freeState(self.alloc, snap);+ self.buf.ensureTotalCapacity(snap.text.len) catch return false;+ self.spans.ensureTotalCapacity(snap.spans.len) catch return false;self.buf.clearRetainingCapacity();- self.buf.appendSlice(snap.text) catch {};+ self.spans.clearRetainingCapacity();+ self.buf.appendSlice(snap.text) catch return false;+ self.spans.appendSlice(snap.spans) catch return false;self.cursor = @min(snap.cursor, self.buf.items.len);+ self.paste_start = null;+ self.compound_edit = false;+ self.compound_snapshot = false;return true;}@@ -53,20 +114,74 @@ pub const Input = struct {return self.buf.items;}+ pub fn semanticSpans(self: *const Input) []const Span {+ return self.spans.items;+ }++ pub fn spanEndAt(self: *const Input, at: usize) ?usize {+ for (self.spans.items) |span| {+ if (span.start == at and span.end <= self.buf.items.len) return span.end;+ }+ return null;+ }+pub fn setValue(self: *Input, text: []const u8) !void {- if (!std.mem.eql(u8, self.buf.items, text)) self.pushUndo();+ if (!std.mem.eql(u8, self.buf.items, text) or self.spans.items.len > 0) self.pushUndo();self.buf.clearRetainingCapacity();+ self.spans.clearRetainingCapacity();try self.buf.appendSlice(text);self.cursor = self.buf.items.len;+ self.paste_start = null;+ self.compound_edit = false;+ self.compound_snapshot = false;}pub fn insertSlice(self: *Input, text: []const u8) void {if (text.len == 0) return;- self.pushUndo();- self.buf.insertSlice(self.cursor, text) catch return;+ if (!self.replaceRange(self.cursor, self.cursor, text)) return;self.cursor += text.len;}+ pub fn beginPaste(self: *Input) void {+ if (self.paste_start != null) return;+ self.paste_start = self.cursor;+ self.compound_edit = true;+ self.compound_snapshot = false;+ }++ pub fn pasteRange(self: *const Input) ?Range {+ const start = self.paste_start orelse return null;+ if (self.cursor < start) return null;+ return .{ .start = start, .end = self.cursor };+ }++ pub fn endPaste(self: *Input) void {+ self.paste_start = null;+ self.compound_edit = false;+ self.compound_snapshot = false;+ }++ pub fn replacePaste(self: *Input, range: Range, text: []const u8, atomic: bool) bool {+ if (atomic) self.spans.ensureUnusedCapacity(1) catch return false;+ if (!self.replaceRange(range.start, range.end, text)) return false;+ self.cursor = range.start + text.len;+ if (atomic and text.len > 0) {+ self.spans.appendAssumeCapacity(.{ .start = range.start, .end = self.cursor });+ std.mem.sort(Span, self.spans.items, {}, spanLessThan);+ }+ return true;+ }++ /// The separator is ordinary text outside a semantic span: one Backspace+ /// removes it, and the next Backspace removes the whole pasted file.+ pub fn ensurePasteSeparator(self: *Input) void {+ if (self.cursor == 0) return;+ if (std.ascii.isWhitespace(self.buf.items[self.cursor - 1])) return;+ if (self.cursor < self.buf.items.len and std.ascii.isWhitespace(self.buf.items[self.cursor])) return;+ if (!self.replaceRange(self.cursor, self.cursor, " ")) return;+ self.cursor += 1;+ }+pub fn setPlaceholder(self: *Input, text: []const u8) void {self.placeholder = text;}@@ -74,9 +189,8 @@ pub const Input = struct {pub fn handle(self: *Input, k: Key) void {switch (k) {.char => |c| {- self.pushUndo();- self.buf.insert(self.cursor, c) catch return;- self.cursor += 1;+ var one = [_]u8{c};+ self.insertSlice(&one);},.codepoint => |cp| {var b: [4]u8 = undefined;@@ -85,72 +199,203 @@ pub const Input = struct {},.backspace => {if (self.cursor == 0) return;- self.pushUndo();- _ = self.buf.orderedRemove(self.cursor - 1);- self.cursor -= 1;- },- .left => self.cursor -|= 1,- .right => {- if (self.cursor < self.buf.items.len) self.cursor += 1;+ self.deleteAndLand(self.cursor - 1, self.cursor);},+ .left => self.cursor = self.left(self.cursor),+ .right => self.cursor = self.right(self.cursor),.home => self.cursor = 0,.end => self.cursor = self.buf.items.len,- .word_left => self.cursor = prevWord(self.buf.items, self.cursor),- .word_right => self.cursor = nextWord(self.buf.items, self.cursor),- .delete_word => self.killTo(prevWord(self.buf.items, self.cursor)),+ .word_left => self.cursor = self.prevWord(self.cursor),+ .word_right => self.cursor = self.nextWord(self.cursor),+ .delete_word => self.killTo(self.prevWord(self.cursor)),.delete_to_start => self.killTo(0),- .delete_to_end => self.killRange(self.cursor, self.buf.items.len),- .delete => self.killRange(self.cursor, if (self.cursor < self.buf.items.len) self.cursor + 1 else self.cursor),+ .delete_to_end => self.deleteAndLand(self.cursor, self.buf.items.len),+ .delete => self.deleteAndLand(self.cursor, if (self.cursor < self.buf.items.len) self.cursor + 1 else self.cursor),.ctrl => |c| switch (c) {'a' => self.cursor = 0,'e' => self.cursor = self.buf.items.len,- 'k' => self.killRange(self.cursor, self.buf.items.len),+ 'k' => self.deleteAndLand(self.cursor, self.buf.items.len),'u' => self.killTo(0),- 'w' => self.killTo(prevWord(self.buf.items, self.cursor)),- 'd' => self.killRange(self.cursor, if (self.cursor < self.buf.items.len) self.cursor + 1 else self.cursor),+ 'w' => self.killTo(self.prevWord(self.cursor)),+ 'd' => self.deleteAndLand(self.cursor, if (self.cursor < self.buf.items.len) self.cursor + 1 else self.cursor),else => {},},else => {},}}+ fn left(self: *const Input, cursor: usize) usize {+ for (self.spans.items) |span| {+ if (cursor > span.start and cursor <= span.end) return span.start;+ }+ return cursor -| 1;+ }++ fn right(self: *const Input, cursor: usize) usize {+ for (self.spans.items) |span| {+ if (cursor >= span.start and cursor < span.end) return span.end;+ }+ return @min(cursor + 1, self.buf.items.len);+ }++ fn prevWord(self: *const Input, cursor: usize) usize {+ for (self.spans.items) |span| {+ if (cursor > span.start and cursor <= span.end) return span.start;+ }+ const plain = plainPrevWord(self.buf.items, cursor);+ for (self.spans.items) |span| {+ if (plain > span.start and plain < span.end) return span.start;+ }+ return plain;+ }++ fn nextWord(self: *const Input, cursor: usize) usize {+ for (self.spans.items) |span| {+ if (cursor >= span.start and cursor < span.end) return span.end;+ }+ const plain = plainNextWord(self.buf.items, cursor);+ for (self.spans.items) |span| {+ if (plain > span.start and plain < span.end) return span.end;+ }+ return plain;+ }+fn killTo(self: *Input, at: usize) void {- self.killRange(at, self.cursor);- self.cursor = at;+ self.deleteAndLand(at, self.cursor);}- fn killRange(self: *Input, from: usize, to: usize) void {+ fn deleteAndLand(self: *Input, from: usize, to: usize) void {if (from >= to or to > self.buf.items.len) return;- self.pushUndo();+ const expanded = self.expandRange(from, to);+ if (!self.replaceRange(expanded.start, expanded.end, "")) return;+ self.cursor = expanded.start;+ }++ fn expandRange(self: *const Input, from: usize, to: usize) Range {+ var out = Range{ .start = from, .end = to };+ var changed = true;+ while (changed) {+ changed = false;+ for (self.spans.items) |span| {+ if (out.start >= span.end or out.end <= span.start) continue;+ const start = @min(out.start, span.start);+ const end = @max(out.end, span.end);+ if (start != out.start or end != out.end) changed = true;+ out = .{ .start = start, .end = end };+ }+ }+ return out;+ }++ fn replaceRange(self: *Input, from: usize, to: usize, text: []const u8) bool {+ if (from > to or to > self.buf.items.len) return false;+ self.buf.ensureUnusedCapacity(text.len) catch return false;+ self.maybePushUndo();+ self.updateSpans(from, to, text.len);var i = to;while (i > from) {i -= 1;_ = self.buf.orderedRemove(i);}+ self.buf.insertSlice(from, text) catch unreachable;+ return true;+ }++ fn updateSpans(self: *Input, from: usize, to: usize, inserted_len: usize) void {+ const removed_len = to - from;+ var i: usize = 0;+ while (i < self.spans.items.len) {+ const span = &self.spans.items[i];+ if (to <= span.start) {+ shiftSpan(span, removed_len, inserted_len);+ i += 1;+ } else if (from >= span.end) {+ i += 1;+ } else {+ _ = self.spans.orderedRemove(i);+ }+ }}pub fn view(self: *const Input, a: std.mem.Allocator) ![]const u8 {+ return self.viewStyled(a, "", "");+ }++ pub fn viewStyled(self: *const Input, a: std.mem.Allocator, accent: []const u8, base: []const u8) ![]const u8 {var out = std.array_list.Managed(u8).init(a);+ errdefer out.deinit();if (self.buf.items.len == 0) {try out.appendSlice(self.placeholder);try out.appendSlice(glyphs.cursor);- return out.items;+ return out.toOwnedSlice();}- try out.appendSlice(self.buf.items[0..self.cursor]);- try out.appendSlice(glyphs.cursor);- try out.appendSlice(self.buf.items[self.cursor..]);- return out.items;+ var source: usize = 0;+ var cursor_drawn = false;+ for (self.spans.items) |span| {+ if (span.start < source or span.end > self.buf.items.len) continue;+ try appendCursorSlice(&out, self.buf.items[source..span.start], source, self.cursor, &cursor_drawn);+ if (!cursor_drawn and self.cursor == span.start) {+ try out.appendSlice(glyphs.cursor);+ cursor_drawn = true;+ }+ try out.appendSlice(accent);+ try appendCursorSlice(&out, self.buf.items[span.start..span.end], span.start, self.cursor, &cursor_drawn);+ try out.appendSlice(base);+ source = span.end;+ }+ try appendCursorSlice(&out, self.buf.items[source..], source, self.cursor, &cursor_drawn);+ if (!cursor_drawn) try out.appendSlice(glyphs.cursor);+ return out.toOwnedSlice();}};-fn prevWord(s: []const u8, cur: usize) usize {+fn appendCursorSlice(+ out: *std.array_list.Managed(u8),+ text: []const u8,+ base: usize,+ cursor: usize,+ drawn: *bool,+) !void {+ if (!drawn.* and cursor >= base and cursor < base + text.len) {+ const at = cursor - base;+ try out.appendSlice(text[0..at]);+ try out.appendSlice(glyphs.cursor);+ try out.appendSlice(text[at..]);+ drawn.* = true;+ } else {+ try out.appendSlice(text);+ }+}++fn freeState(alloc: std.mem.Allocator, state: State) void {+ alloc.free(state.text);+ alloc.free(state.spans);+}++fn spanLessThan(_: void, a: Span, b: Span) bool {+ return a.start < b.start;+}++fn shiftSpan(span: *Span, removed_len: usize, inserted_len: usize) void {+ if (inserted_len >= removed_len) {+ const delta = inserted_len - removed_len;+ span.start += delta;+ span.end += delta;+ } else {+ const delta = removed_len - inserted_len;+ span.start -= delta;+ span.end -= delta;+ }+}++fn plainPrevWord(s: []const u8, cur: usize) usize {var i = cur;while (i > 0 and s[i - 1] == ' ') i -= 1;while (i > 0 and s[i - 1] != ' ') i -= 1;return i;}-fn nextWord(s: []const u8, cur: usize) usize {+fn plainNextWord(s: []const u8, cur: usize) usize {var i = cur;while (i < s.len and s[i] != ' ') i += 1;while (i < s.len and s[i] == ' ') i += 1;diff --git a/TUI/issue_537_reviewer_tests.zig b/TUI/issue_537_reviewer_tests.zigindex 159f2135..3d054cf7 100644--- a/TUI/issue_537_reviewer_tests.zig+++ b/TUI/issue_537_reviewer_tests.zig@@ -315,7 +315,7 @@ test "production folded SGR and X10 wheels are paste-aware on every trajectory"fixture.term.model.sel.active = true;fixture.term.model.sel.pressed = true;try std.testing.expectEqual(Effect.stay, try dispatchProductionBatch(&fixture.term.model, bytes));- try std.testing.expectEqualStrings("leftright", fixture.term.model.input.getValue());+ try std.testing.expectEqualStrings("leftright ", fixture.term.model.input.getValue());try std.testing.expectEqual(@as(usize, 7), fixture.term.model.scroll);try std.testing.expect(!fixture.term.model.follow);try std.testing.expect(fixture.term.model.sel.active and fixture.term.model.sel.pressed);@@ -553,7 +553,10 @@ test "one feed carries a 16KiB paste payload through its later terminator" {defer fixture.deinit();const history_len = fixture.term.model.history.items.len;try std.testing.expectEqual(Effect.stay, fixture.term.feed(&wire));- try std.testing.expectEqualStrings(&payload, fixture.term.model.input.getValue());+ const got = fixture.term.model.input.getValue();+ try std.testing.expectEqual(payload.len + 1, got.len);+ try std.testing.expectEqualStrings(&payload, got[0..payload.len]);+ try std.testing.expectEqual(@as(u8, ' '), got[got.len - 1]);try std.testing.expect(!fixture.term.model.pasting and !key_mod.inPaste());try std.testing.expectEqual(@as(usize, 0), fixture.term.pending);try std.testing.expectEqual(history_len, fixture.term.model.history.items.len);@@ -581,8 +584,10 @@ test "feed stops at Ctrl-Q across a 16KiB+1 paste-start/paste-end wire" {var fixture = try Fixture.init(trajectory);defer fixture.deinit();try std.testing.expectEqual(Effect.quit, fixture.term.feed(&wire));- try std.testing.expectEqual(payload_len, fixture.term.model.input.getValue().len);- try std.testing.expectEqualStrings(wire[start.len .. start.len + payload_len], fixture.term.model.input.getValue());+ const got = fixture.term.model.input.getValue();+ try std.testing.expectEqual(payload_len + 1, got.len);+ try std.testing.expectEqualStrings(wire[start.len .. start.len + payload_len], got[0..payload_len]);+ try std.testing.expectEqual(@as(u8, ' '), got[got.len - 1]);try std.testing.expect(!fixture.term.model.pasting and !key_mod.inPaste());}}diff --git a/TUI/issue_537_tests.zig b/TUI/issue_537_tests.zigindex 4a644c42..cdb85bae 100644--- a/TUI/issue_537_tests.zig+++ b/TUI/issue_537_tests.zig@@ -121,15 +121,15 @@ const C0PasteCase = struct {// These are the actual single-byte tty encodings, not synthetic Key values.// In particular, Ctrl-J is LF and is intentionally retained as paste newline.const c0_paste_cases = [_]C0PasteCase{- .{ .name = "Ctrl-Q", .byte = 0x11, .expected = "leftright" },- .{ .name = "Ctrl-C", .byte = 0x03, .expected = "leftright" },- .{ .name = "Ctrl-Z", .byte = 0x1a, .expected = "leftright" },- .{ .name = "Ctrl-N", .byte = 0x0e, .expected = "leftright" },- .{ .name = "Ctrl-J", .byte = 0x0a, .expected = "left\nright" },- .{ .name = "Ctrl-K", .byte = 0x0b, .expected = "leftright" },- .{ .name = "Tab", .byte = 0x09, .expected = "leftright" },- .{ .name = "Backspace (DEL)", .byte = 0x7f, .expected = "leftright" },- .{ .name = "Backspace (BS)", .byte = 0x08, .expected = "leftright" },+ .{ .name = "Ctrl-Q", .byte = 0x11, .expected = "leftright " },+ .{ .name = "Ctrl-C", .byte = 0x03, .expected = "leftright " },+ .{ .name = "Ctrl-Z", .byte = 0x1a, .expected = "leftright " },+ .{ .name = "Ctrl-N", .byte = 0x0e, .expected = "leftright " },+ .{ .name = "Ctrl-J", .byte = 0x0a, .expected = "left\nright " },+ .{ .name = "Ctrl-K", .byte = 0x0b, .expected = "leftright " },+ .{ .name = "Tab", .byte = 0x09, .expected = "leftright " },+ .{ .name = "Backspace (DEL)", .byte = 0x7f, .expected = "leftright " },+ .{ .name = "Backspace (BS)", .byte = 0x08, .expected = "leftright " },};fn pasteInvariantFailure(failures: *usize, trajectory: PasteTrajectory, case: C0PasteCase, what: []const u8) void {@@ -178,7 +178,7 @@ const ParsedPasteCase = struct {name: []const u8,bytes: []const u8,middle: []const u8 = "left",- final: []const u8 = "leftright",+ final: []const u8 = "leftright ",held: u32 = 0,};@@ -189,7 +189,7 @@ const parsed_paste_cases = [_]ParsedPasteCase{.{ .name = "kitty Super down", .bytes = "\x1b[57444;1:1u" },.{ .name = "kitty Super release", .bytes = "\x1b[57444;1:3u", .held = 8 },.{ .name = "kitty modified Backspace", .bytes = "\x1b[127;9u" },- .{ .name = "kitty text", .bytes = "\x1b[97u", .middle = "lefta", .final = "leftaright", .held = 8 },+ .{ .name = "kitty text", .bytes = "\x1b[97u", .middle = "lefta", .final = "leftaright ", .held = 8 },.{ .name = "CSI arrow", .bytes = "\x1b[A" },.{ .name = "CSI Delete", .bytes = "\x1b[3~" },.{ .name = "SS3 arrow", .bytes = "\x1bOA" },@@ -257,7 +257,7 @@ test "Escape remains the intentional bracketed paste hatch (#536/#548)" {try std.testing.expect(!term.model.pasting);try std.testing.expect(!key_mod.inPaste());try std.testing.expectEqual(@as(u32, 0), key_mod.held);- try std.testing.expectEqualStrings("draft", term.model.input.getValue());+ try std.testing.expectEqualStrings("draft ", term.model.input.getValue());// Once Escape intentionally closes the paste, a subsequent Ctrl-Q is an// ordinary key again; the hatch is not a permanent suppression switch.try std.testing.expectEqual(Effect.quit, term.feed("\x11"));@@ -373,7 +373,7 @@ test "X10 mouse survives every split on every TUI trajectory and in paste (#537)try std.testing.expect(key_mod.inPaste() and fixture.term.model.pasting);try std.testing.expectEqualStrings("left", fixture.term.model.input.getValue());_ = fixture.term.feed("right\x1b[201~");- try std.testing.expectEqualStrings("leftright", fixture.term.model.input.getValue());+ try std.testing.expectEqualStrings("leftright ", fixture.term.model.input.getValue());} else if (trajectory == .idle) {try std.testing.expectEqualStrings("draft survives", fixture.term.model.input.getValue());} else try std.testing.expectEqualStrings("", fixture.term.model.input.getValue());@@ -411,7 +411,7 @@ test "an ESC inside X10 payload reparses a paste terminator at every split (#537try std.testing.expectEqual(Effect.stay, fixture.term.feed(broken[cut..]));errdefer std.debug.print("X10 paste terminator failure [{s} / split {d}]\n", .{ trajectoryName(trajectory), cut });try std.testing.expect(!key_mod.inPaste() and !fixture.term.model.pasting);- try std.testing.expectEqualStrings("left", fixture.term.model.input.getValue());+ try std.testing.expectEqualStrings("left ", fixture.term.model.input.getValue());try std.testing.expectEqual(@as(usize, 0), fixture.term.pending);try expectOperationAlive(&fixture, trajectory);};@@ -576,7 +576,7 @@ test "abandoned kitty releases clear Super before a bare DEL (#537)" {try std.testing.expectEqual(@as(u32, 0), key_mod.held);_ = term.feed("\x1b[201~");try std.testing.expect(!key_mod.inPaste() and !term.model.pasting);- try std.testing.expectEqualStrings("left", term.model.input.getValue());+ try std.testing.expectEqualStrings("left ", term.model.input.getValue());}}diff --git a/TUI/issue_737_tests.zig b/TUI/issue_737_tests.zigindex 6a062b9a..d9bf654c 100644--- a/TUI/issue_737_tests.zig+++ b/TUI/issue_737_tests.zig@@ -5,7 +5,12 @@ const engine = @import("engine.zig");const key = @import("key.zig");fn draft(term: *sim.Term, expected: []const u8, history_len: usize) !void {- try std.testing.expectEqualStrings(expected, term.model.input.getValue());+ const got = term.model.input.getValue();+ if (expected.len > 0 and !std.ascii.isWhitespace(expected[expected.len - 1])) {+ try std.testing.expectEqual(expected.len + 1, got.len);+ try std.testing.expectEqualStrings(expected, got[0..expected.len]);+ try std.testing.expectEqual(@as(u8, ' '), got[got.len - 1]);+ } else try std.testing.expectEqualStrings(expected, got);try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);try std.testing.expectEqual(history_len, term.model.history.items.len);try std.testing.expect(term.model.pending != null);@@ -109,8 +114,8 @@ test "#737 delayed paste_end dispatch cannot reset a subsequent decoded paste" {_ = term.feed("\r");_ = term.feed("\nthird\x1b[201~");const got = term.model.input.getValue();- try std.testing.expect(std.mem.startsWith(u8, got, "firstsecond"));- try std.testing.expect(std.mem.endsWith(u8, got, "third"));+ try std.testing.expect(std.mem.startsWith(u8, got, "first second"));+ try std.testing.expect(std.mem.endsWith(u8, got, "third "));try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);try std.testing.expect(!term.model.cancel_requested);}diff --git a/TUI/issue_792_tests.zig b/TUI/issue_792_tests.zignew file mode 100644index 00000000..cfbfd8a5--- /dev/null+++ b/TUI/issue_792_tests.zig@@ -0,0 +1,246 @@+//! #792: pasted items need separators and paste-origin file paths need identity.++const std = @import("std");+const Term = @import("sim.zig").Term;++fn paste(term: *Term, text: []const u8) void {+ _ = term.feed("\x1b[200~");+ _ = term.feed(text);+ _ = term.feed("\x1b[201~");+}++fn writeTmp(tmp: anytype, name: []const u8, buf: []u8) ![]const u8 {+ const io = std.testing.io;+ try tmp.dir.writeFile(io, .{ .sub_path = name, .data = "file" });+ const n = try tmp.dir.realPath(io, buf);+ if (n + 1 + name.len > buf.len) return error.NameTooLong;+ buf[n] = '/';+ @memcpy(buf[n + 1 ..][0..name.len], name);+ return buf[0 .. n + 1 + name.len];+}++test "#792 bracketed text paste leaves one trailing separator" {+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();++ paste(&term, "hello");+ try std.testing.expectEqualStrings("hello ", term.model.input.getValue());+}++test "#792 existing trailing whitespace is not duplicated" {+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();++ paste(&term, "hello ");+ try std.testing.expectEqualStrings("hello ", term.model.input.getValue());+}++test "#792 consecutive pasted or dropped file paths stay separated" {+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var one_buf: [std.fs.max_path_bytes]u8 = undefined;+ var two_buf: [std.fs.max_path_bytes]u8 = undefined;+ const one = try writeTmp(&tmp, "one file.txt", &one_buf);+ const two = try writeTmp(&tmp, "two file.txt", &two_buf);+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();++ paste(&term, one);+ paste(&term, two);+ const expected = try std.fmt.allocPrint(std.testing.allocator, "{s} {s} ", .{ one, two });+ defer std.testing.allocator.free(expected);+ try std.testing.expectEqualStrings(expected, term.model.input.getValue());+}++test "#792 backspace removes a paste-origin file path as one item" {+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;+ const path = try writeTmp(&tmp, "one file.txt", &path_buf);+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();++ paste(&term, path);+ _ = term.feed("\x7f"); // remove the separator+ _ = term.feed("\x7f"); // remove the pasted path as one item+ try std.testing.expectEqualStrings("", term.model.input.getValue());+}++test "#792 delete removes a paste-origin file path at its leading edge" {+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;+ const path = try writeTmp(&tmp, "one file.txt", &path_buf);+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();++ paste(&term, path);+ _ = term.feed("\x1b[H"); // home+ _ = term.feed("\x1b[3~"); // delete at the span's leading edge+ try std.testing.expectEqualStrings(" ", term.model.input.getValue());+}++test "#792 word movement skips a paste-origin file path" {+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;+ const path = try writeTmp(&tmp, "one file.txt", &path_buf);+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();++ paste(&term, path);+ _ = term.feed("\x1bb"); // word-left from after the separator+ try std.testing.expectEqual(@as(usize, 0), term.model.input.cursor);+}++test "#792 manually typed path remains ordinary character-editable text" {+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;+ const path = try writeTmp(&tmp, "one file.txt", &path_buf);+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();++ _ = term.typeText(path);+ _ = term.feed("\x1bb"); // word-left stops at the path's internal space+ const boundary = std.mem.indexOfScalar(u8, path, ' ').? + 1;+ try std.testing.expectEqual(boundary, term.model.input.cursor);+ _ = term.feed("\x7f");+ const expected = try std.fmt.allocPrint(std.testing.allocator, "{s}file.txt", .{path[0 .. boundary - 1]});+ defer std.testing.allocator.free(expected);+ try std.testing.expectEqualStrings(expected, term.model.input.getValue());+}++test "#792 typing after a paste uses the removable separator" {+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();++ paste(&term, "hello");+ _ = term.typeText("world");+ try std.testing.expectEqualStrings("hello world", term.model.input.getValue());+}++test "#792 existing whitespace to the right is not duplicated" {+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();++ try term.model.input.setValue(" right");+ _ = term.press(.home);+ paste(&term, "hello");+ try std.testing.expectEqualStrings("hello right", term.model.input.getValue());+}++test "#792 file URL paste normalizes and highlights only the semantic span" {+ const theme = @import("theme.zig");+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;+ const path = try writeTmp(&tmp, "one file.txt", &path_buf);+ const space = std.mem.indexOfScalar(u8, path, ' ').?;+ const url = try std.fmt.allocPrint(std.testing.allocator, "file://{s}%20{s}", .{ path[0..space], path[space + 1 ..] });+ defer std.testing.allocator.free(url);+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();++ paste(&term, url);+ const expected = try std.fmt.allocPrint(std.testing.allocator, "{s} ", .{path});+ defer std.testing.allocator.free(expected);+ try std.testing.expectEqualStrings(expected, term.model.input.getValue());+ try std.testing.expectEqual(@as(usize, 1), term.model.input.semanticSpans().len);+ const styled = try term.model.input.viewStyled(std.testing.allocator, theme.of(.night).accent, theme.of(.night).text);+ defer std.testing.allocator.free(styled);+ try std.testing.expect(std.mem.indexOf(u8, styled, theme.of(.night).accent) != null);++ try term.model.input.setValue(path);+ const plain = try term.model.input.viewStyled(std.testing.allocator, theme.of(.night).accent, theme.of(.night).text);+ defer std.testing.allocator.free(plain);+ try std.testing.expect(std.mem.indexOf(u8, plain, theme.of(.night).accent) == null);+}++test "#792 undo restores file span identity after atomic deletion" {+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;+ const path = try writeTmp(&tmp, "undo file.txt", &path_buf);+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();++ paste(&term, path);+ _ = term.press(.backspace); // separator+ _ = term.press(.backspace); // span+ try std.testing.expectEqualStrings("", term.model.input.getValue());+ _ = term.press(.undo);+ try std.testing.expectEqualStrings(path, term.model.input.getValue());+ try std.testing.expectEqual(@as(usize, 1), term.model.input.semanticSpans().len);+ _ = term.press(.backspace);+ try std.testing.expectEqualStrings("", term.model.input.getValue());+}++test "#792 prompt history round trip preserves an unsent file span" {+ const history = @import("prompt_history.zig");+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;+ const path = try writeTmp(&tmp, "draft file.txt", &path_buf);+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();+ try term.model.prompt_hist.append(try std.testing.allocator.dupe(u8, "older"));+ try term.model.prompt_hist_images.append(&.{});++ paste(&term, path);+ history.recallPrev(&term.model);+ try std.testing.expectEqualStrings("older", term.model.input.getValue());+ history.recallNext(&term.model);+ try std.testing.expectEqual(@as(usize, 1), term.model.input.semanticSpans().len);+ _ = term.press(.backspace);+ _ = term.press(.backspace);+ try std.testing.expectEqualStrings("", term.model.input.getValue());+}++test "#792 image paste consumes only its inserted range" {+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();+ _ = term.typeText("keep me");++ paste(&term, "/tmp/pic.png");+ try std.testing.expectEqualStrings("keep me", term.model.input.getValue());+ try std.testing.expectEqual(@as(usize, 1), term.model.images.items.len);+ try std.testing.expectEqualStrings("/tmp/pic.png", term.model.images.items[0]);+}++test "#792 mid-buffer image paste does not edit surrounding text" {+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();+ _ = term.typeText("keepme");+ _ = term.press(.home);+ for (0..4) |_| _ = term.press(.right);++ paste(&term, "/tmp/pic.png");+ try std.testing.expectEqualStrings("keepme", term.model.input.getValue());+ try std.testing.expectEqual(@as(usize, 1), term.model.images.items.len);+}++test "#792 empty paste does not consume an undo step" {+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();+ _ = term.typeText("x");++ paste(&term, "");+ _ = term.press(.undo);+ try std.testing.expectEqualStrings("", term.model.input.getValue());+}diff --git a/TUI/keys.zig b/TUI/keys.zigindex 5b9d1e2f..63901cf2 100644--- a/TUI/keys.zig+++ b/TUI/keys.zig@@ -5,6 +5,7 @@ const std = @import("std");const app = @import("app.zig");const catalog = @import("catalog.zig");const click = @import("click.zig");+const composer_paste = @import("composer_paste.zig");const dispatch = @import("dispatch.zig");const hover = @import("hover.zig");const layout_cache = @import("layout_cache.zig");@@ -23,16 +24,14 @@ pub fn handle(self: *Model, k: Key) Effect {if (k == .paste_start) {self.pasting = true;self.focus = .prompt;+ composer_paste.begin(self);return .stay;}if (k == .paste_end) {self.pasting = false;// Decoder owns its latch: batching may already have decoded the next// paste_start. Rewinding it here turns that paste's LF into Enter (#737).- const v = std.mem.trim(u8, self.input.getValue(), " \t\r\n");- if (@import("image.zig").attachDropped(self, v)) {- self.input.setValue("") catch {};- }+ composer_paste.finish(self);return .stay;}if (self.pasting) {@@ -47,6 +46,7 @@ pub fn handle(self: *Model, k: Key) Effect {.escape => {self.pasting = false;key_mod.endPaste();+ composer_paste.finish(self);self.setToast("paste ended");},// Editor actions and non-newline controls are not paste text.diff --git a/TUI/keys_tests.zig b/TUI/keys_tests.zigindex f99a0465..af6e2afa 100644--- a/TUI/keys_tests.zig+++ b/TUI/keys_tests.zig@@ -286,7 +286,7 @@ test "bracketed paste lands in the prompt as text" {_ = handle(&m, .enter);_ = handle(&m, .{ .char = '!' });_ = handle(&m, .paste_end);- try std.testing.expectEqualStrings("hi\n!", m.input.getValue());+ try std.testing.expectEqualStrings("hi\n! ", m.input.getValue());try std.testing.expect(m.focus == .prompt);try std.testing.expect(!m.pasting);}@@ -403,7 +403,7 @@ test "idle bracketed multiline paste stays one unsent draft (#643)" {term.init(std.testing.allocator, 80, 24);defer term.deinit();_ = term.feed("\x1b[200~line1\nline2\nline3\x1b[201~");- try std.testing.expectEqualStrings("line1\nline2\nline3", term.model.input.getValue());+ try std.testing.expectEqualStrings("line1\nline2\nline3 ", term.model.input.getValue());try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);var users: usize = 0;for (term.model.history.items) |e| {@@ -427,7 +427,7 @@ test "streaming bracketed paste does not steer, Enter queues one (#643)" {term.deinit();}_ = term.feed("\x1b[200~first\nsecond\nthird\x1b[201~");- try std.testing.expectEqualStrings("first\nsecond\nthird", term.model.input.getValue());+ try std.testing.expectEqualStrings("first\nsecond\nthird ", term.model.input.getValue());try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);try std.testing.expect(!term.model.cancel_requested);_ = term.enter();@@ -443,7 +443,7 @@ test "bracketed CRLF paste cannot invoke Enter/send (#643)" {term.deinit();}_ = term.feed("\x1b[200~one\r\ntwo\r\nthree\x1b[201~");- try std.testing.expectEqualStrings("one\r\ntwo\r\nthree", term.model.input.getValue());+ try std.testing.expectEqualStrings("one\r\ntwo\r\nthree ", term.model.input.getValue());try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);try std.testing.expect(!term.model.cancel_requested);var forced: usize = 0;@@ -504,7 +504,7 @@ test "#737 delayed paste_end dispatch cannot reset a subsequent decoded paste" {_ = term.feed("\x1b[200~first\x1b[201~\x1b[200~second");_ = term.feed("\r");_ = term.feed("\nthird\x1b[201~");- try std.testing.expectEqualStrings("firstsecond\r\nthird", term.model.input.getValue());+ try std.testing.expectEqualStrings("first second\r\nthird ", term.model.input.getValue());try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);try std.testing.expect(!term.model.cancel_requested);}diff --git a/TUI/prompt_history.zig b/TUI/prompt_history.zigindex 3be85366..c5592004 100644--- a/TUI/prompt_history.zig+++ b/TUI/prompt_history.zig@@ -38,7 +38,7 @@ pub fn recallNext(self: *Model) void {const i = self.hist_idx orelse return;if (i + 1 >= self.prompt_hist.items.len) {self.hist_idx = null;- apply(self, self.draft_text orelse "", self.draft_images orelse &.{});+ restoreDraft(self);return;}self.hist_idx = i + 1;@@ -67,7 +67,7 @@ fn recordImages(self: *Model) void {fn snapshotDraft(self: *Model) void {clearDraft(self);- self.draft_text = self.alloc.dupe(u8, self.input.getValue()) catch null;+ self.draft_input = self.input.snapshot() catch null;if (self.images.items.len == 0) return;var paths = std.array_list.Managed([]const u8).init(self.alloc);for (self.images.items) |p| {@@ -82,9 +82,9 @@ fn snapshotDraft(self: *Model) void {}fn clearDraft(self: *Model) void {- if (self.draft_text) |t| {- self.alloc.free(t);- self.draft_text = null;+ if (self.draft_input) |state| {+ self.input.freeSnapshot(state);+ self.draft_input = null;}if (self.draft_images) |paths| {freePaths(self, paths);@@ -92,6 +92,13 @@ fn clearDraft(self: *Model) void {}}+fn restoreDraft(self: *Model) void {+ if (self.draft_input) |state| {+ self.input.setState(state) catch {};+ } else self.input.setValue("") catch {};+ replaceImages(self, self.draft_images orelse &.{});+}+fn apply(self: *Model, text: []const u8, paths: []const []const u8) void {self.input.setValue(text) catch {};replaceImages(self, paths);diff --git a/TUI/root.zig b/TUI/root.zigindex 3d5981bb..eb655d4e 100644--- a/TUI/root.zig+++ b/TUI/root.zig@@ -87,6 +87,7 @@ test {_ = @import("issue_537_reviewer_tests.zig");_ = @import("issue_524_tests.zig");_ = @import("issue_737_tests.zig");+ _ = @import("issue_792_tests.zig");_ = @import("input.zig");_ = @import("keys.zig");_ = @import("nav.zig");diff --git a/TUI/sim.zig b/TUI/sim.zigindex 88928e3a..16c1a119 100644--- a/TUI/sim.zig+++ b/TUI/sim.zig@@ -515,7 +515,7 @@ test "giving up on a split paste terminator closes the paste, tail and all (#532try std.testing.expect(!term.model.pasting);// The late `~` rejoins its carried head instead of typing itself._ = term.feed("~");- try std.testing.expectEqualStrings("hello", term.model.input.getValue());+ try std.testing.expectEqualStrings("hello ", term.model.input.getValue());}test "the idle paste sweep never fires a phantom Escape at a live turn" {@@ -557,12 +557,12 @@ test "the idle paste sweep never fires a phantom Escape at a live turn" {try std.testing.expect(!term.model.pasting);try std.testing.expect(!term.model.cancel_requested);try std.testing.expectEqual(@as(usize, 0), term.pending);- try std.testing.expectEqualStrings("draft text", term.model.input.getValue());+ try std.testing.expectEqualStrings("draft text ", term.model.input.getValue());// ...and the late terminator still rejoins its carried head rather than// typing `[201~` on the end of the draft._ = term.feed("[201~");- try std.testing.expectEqualStrings("draft text", term.model.input.getValue());+ try std.testing.expectEqualStrings("draft text ", term.model.input.getValue());}test "live prose tail paints markdown before the turn settles" {