graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: distinguish clipboard failures without guessing permissions
yxlyx4f4f6c5e1162
diff --git a/TUI/issue_883_tests.zig b/TUI/issue_883_tests.zignew file mode 100644index 00000000..5587787b--- /dev/null+++ b/TUI/issue_883_tests.zig@@ -0,0 +1,113 @@+//! #883: exercise Ctrl-V dispatch without a terminal or clipboard access.+//! PasteFn exposes only image paths (>0), errors (<0), and no image (0).+//! Text fallback and image/text precedence require a seam inside pasteCb;+//! these tests deliberately make no claims about those backend decisions.++const std = @import("std");+const engine = @import("engine.zig");+const Term = @import("sim.zig").Term;++const Paste = struct {+ payload: []const u8,+ failed: bool = false,+ calls: usize = 0,++ fn call(ctx: ?*anyopaque, dest: []u8) isize {+ const self: *Paste = @ptrCast(@alignCast(ctx.?));+ self.calls += 1;+ const n = @min(self.payload.len, dest.len);+ @memcpy(dest[0..n], self.payload[0..n]);+ const result: isize = @intCast(n);+ return if (self.failed) -result else result;+ }+};++fn expectVisible(term: *Term, text: []const u8) !void {+ const screen = try term.screen();+ defer term.alloc.free(screen);+ try std.testing.expect(std.mem.indexOf(u8, screen, text) != null);+}++test "#883 Ctrl-V callback failures remain visible and preserve the prompt and attachments" {+ const saved_fn = engine.g_paste_fn;+ const saved_ctx = engine.g_turn_ctx;+ defer {+ engine.g_paste_fn = saved_fn;+ engine.g_turn_ctx = saved_ctx;+ }+ engine.g_paste_fn = Paste.call;++ // Synthetic backend errors: dispatch must display, not reinterpret them.+ for ([_][]const u8{ "clipboard read failed", "clipboard image export failed", "clipboard text read failed" }) |message| {+ var paste = Paste{ .payload = message, .failed = true };+ engine.g_turn_ctx = &paste;+ var term: Term = undefined;+ term.init(std.testing.allocator, 100, 24);+ defer term.deinit();+ _ = term.typeText("keep this prompt");+ _ = term.feed("\x1b[D");+ const cursor = term.model.input.cursor;+ term.model.attachImage("/synthetic/existing.png");++ _ = term.feed("\x16");++ try std.testing.expectEqual(@as(usize, 1), paste.calls);+ try std.testing.expectEqualStrings("keep this prompt", term.model.input.getValue());+ try std.testing.expectEqual(cursor, term.model.input.cursor);+ try std.testing.expectEqual(@as(usize, 1), term.model.images.items.len);+ try std.testing.expectEqualStrings("/synthetic/existing.png", term.model.images.items[0]);+ try expectVisible(&term, message);+ }+}++test "#883 Ctrl-V image result attaches without replacing prompt text" {+ const saved_fn = engine.g_paste_fn;+ const saved_ctx = engine.g_turn_ctx;+ defer {+ engine.g_paste_fn = saved_fn;+ engine.g_turn_ctx = saved_ctx;+ }+ var paste = Paste{ .payload = "/synthetic/clipboard.png" };+ engine.g_paste_fn = Paste.call;+ engine.g_turn_ctx = &paste;+ var term: Term = undefined;+ term.init(std.testing.allocator, 100, 24);+ defer term.deinit();+ _ = term.typeText("describe this");+ _ = term.feed("\x1b[D");+ const cursor = term.model.input.cursor;++ _ = term.feed("\x1b[118;5u");++ try std.testing.expectEqual(@as(usize, 1), paste.calls);+ try std.testing.expectEqualStrings("describe this", term.model.input.getValue());+ try std.testing.expectEqual(cursor, term.model.input.cursor);+ try std.testing.expectEqual(@as(usize, 1), term.model.images.items.len);+ try std.testing.expectEqualStrings(paste.payload, term.model.images.items[0]);+ try expectVisible(&term, "[Image #1] attached");+}++test "#883 Ctrl-V empty callback result is visible without changing the prompt" {+ const saved_fn = engine.g_paste_fn;+ const saved_ctx = engine.g_turn_ctx;+ defer {+ engine.g_paste_fn = saved_fn;+ engine.g_turn_ctx = saved_ctx;+ }+ var paste = Paste{ .payload = "" };+ engine.g_paste_fn = Paste.call;+ engine.g_turn_ctx = &paste;+ var term: Term = undefined;+ term.init(std.testing.allocator, 100, 24);+ defer term.deinit();+ _ = term.typeText("keep this prompt");+ const cursor = term.model.input.cursor;++ _ = term.feed("\x16");++ try std.testing.expectEqual(@as(usize, 1), paste.calls);+ try std.testing.expectEqualStrings("keep this prompt", term.model.input.getValue());+ try std.testing.expectEqual(cursor, term.model.input.cursor);+ try std.testing.expectEqual(@as(usize, 0), term.model.images.items.len);+ try expectVisible(&term, "no image on the clipboard");+}diff --git a/TUI/root.zig b/TUI/root.zigindex 0bb2bebb..20f02c6d 100644--- a/TUI/root.zig+++ b/TUI/root.zig@@ -113,6 +113,7 @@ test {_ = @import("selection.zig");_ = @import("selection_tests.zig");_ = @import("issue_845_tests.zig");+ _ = @import("issue_883_tests.zig");_ = @import("theme_tint.zig");_ = @import("hover.zig");_ = @import("hover_tests.zig");diff --git a/docs/adr/0111-clipboard-errors-need-evidence.md b/docs/adr/0111-clipboard-errors-need-evidence.mdnew file mode 100644index 00000000..0da8fe32--- /dev/null+++ b/docs/adr/0111-clipboard-errors-need-evidence.md@@ -0,0 +1,31 @@+# 0111. Clipboard failures do not imply Automation permission++Status: accepted 2026-09-14++## Context++Clipboard helper launch failures, timeouts, invalid output, and repeated+pasteboard changes all produced advice to grant Automation access (#883).+The exporter already uses AppKit directly through the system JXA runtime;+it does not send Apple Events to another application. Named-pasteboard+regressions exercise the real exporter without modifying the general board.++## Decision++Keep direct AppKit extraction and its image-flavor fallback. Do not introduce+application scripting or ask users to change Automation permissions for a+generic helper failure. Classify bounded process results before decoding the+export protocol, and identify denial only from an explicit, complete system+error. Never display helper stderr or clipboard contents in diagnostics.++Expose launch failure, timeout, clipboard churn, export failure, and conversion+failure separately. Offer retry and the existing terminal text-paste or+`/image <path>` workflows rather than inventing a permission requirement.++## Consequences++`osascript` remains the system JXA host, not an Automation target. This avoids+adding a platform-specific linked helper or runtime compiler dependency.+Unknown failures remain neutral read errors; they do not establish which+macOS privacy setting, if any, applies. Tests use private named pasteboards and+injected process failures, so normal clipboard contents remain untouched.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 8cb1e80b..302aed5a 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -121,6 +121,7 @@ record only when you need the evidence or the edge cases.| [0108](0108-browser-events-outrank-pending-snapshots.md) | Browser page-info events invalidate older pending IPC snapshots; a loaded page must not revert to loading. || [0109](0109-resume-retains-catalog-and-layout-snapshots.md) | Resume restores loaded tool selections and the same-workspace layout snapshot, without freezing current instructions or granting permissions. || [0110](0110-project-mcp-listing-opts-in-optional-servers.md) | Project MCP entries opt in optional servers; inherited extras still require opt-in, and startup consent applies to both. |+| [0111](0111-clipboard-errors-need-evidence.md) | Direct AppKit clipboard failures need typed evidence; generic helper failures never imply Automation permission. |## When to write onediff --git a/src/clipboard_edge_tests.zig b/src/clipboard_edge_tests.zignew file mode 100644index 00000000..25e84722--- /dev/null+++ b/src/clipboard_edge_tests.zig@@ -0,0 +1,109 @@+//! #883 edge cases use private named pasteboards, never the general clipboard.+const std = @import("std");+const clip = @import("vision_clipboard.zig");+const native = @import("clipboard_native.zig");+const runner = @import("process_runner.zig");++const setup =+ \\ObjC.import('AppKit');+ \\function run(argv) {+ \\ const pb=$.NSPasteboard.pasteboardWithName(argv[0]); pb.clearContents;+ \\ const kind=argv[1];+ \\ const png=$.NSData.alloc.initWithBase64EncodedStringOptions('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAEElEQVR4nGP4z8AARAwQCgAf7gP9i18U1AAAAABJRU5ErkJggg==',0);+ \\ const broken=$('not an image').dataUsingEncoding($.NSUTF8StringEncoding);+ \\ function put(types, values) {+ \\ pb.declareTypesOwner($(types),null);+ \\ for(let i=0;i<types.length;i++) {+ \\ const ok=typeof values[i]==='string'?pb.setStringForType(values[i],types[i]):pb.setDataForType(values[i],types[i]);+ \\ if(!ok) throw Error('fixture flavor write failed');+ \\ }+ \\ }+ \\ if(kind==='mixed') put(['public.utf8-plain-text','public.png'],['fixture text',png]);+ \\ else if(kind==='alternate') {+ \\ const image=$.NSImage.alloc.initWithData(png);+ \\ put(['public.png','public.tiff'],[broken,image.TIFFRepresentation]);+ \\ } else if(kind==='corrupt-text') put(['public.png','public.utf8-plain-text'],[broken,'fixture text']);+ \\ else if(kind==='unsupported') put(['org.example.clipboard-edge-unsupported'],[png]);+ \\ else if(kind==='unsupported-text') put(['public.html','public.utf8-plain-text'],['<b>fixture</b>','fixture']);+ \\ else if(kind==='remote') put(['public.file-url'],['https://example.invalid/image.png']);+ \\ else {+ \\ if(kind!=='missing') {+ \\ const data=kind==='nonimage'||kind==='nonimage-png'?broken:png;+ \\ if(!data.writeToFileAtomically(argv[2],true)) throw Error('fixture file write failed');+ \\ }+ \\ const url=ObjC.unwrap($.NSURL.fileURLWithPath(argv[2]).absoluteString);+ \\ if(kind==='file-alternate') put(['public.png','public.file-url'],[broken,url]);+ \\ else put(['public.file-url'],[url]);+ \\ }+ \\ return 'ready';+ \\}+;++const cleanup =+ \\ObjC.import('AppKit');+ \\function run(argv) { $.NSPasteboard.pasteboardWithName(argv[0]).releaseGlobally; }+;++fn releaseBoard(board: []const u8) void {+ const gpa = std.testing.allocator;+ const r = runner.runCapped(gpa, std.testing.io, &.{ "/usr/bin/osascript", "-l", "JavaScript", "-e", cleanup, board }, 64, 2048, 5000) catch return;+ defer gpa.free(r.stdout);+ defer gpa.free(r.stderr);+}++test "#883 named pasteboard edge cases mixed flavors alternate images file URLs and unsupported types" {+ if (@import("builtin").os.tag != .macos) return error.SkipZigTest;+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ const Expected = enum { png, furl, empty, convert };+ const Case = struct {+ kind: []const u8,+ ext: []const u8 = "png",+ expected: Expected,+ source_png: bool = false,+ };+ const cases = [_]Case{+ .{ .kind = "mixed", .expected = .png },+ .{ .kind = "alternate", .expected = .png },+ .{ .kind = "corrupt-text", .expected = .convert },+ .{ .kind = "file", .ext = "space # percent% quote' double\" café 雪.PNG", .expected = .furl, .source_png = true },+ .{ .kind = "file-alternate", .expected = .furl, .source_png = true },+ .{ .kind = "missing", .expected = .convert },+ .{ .kind = "nonimage", .ext = "txt", .expected = .empty },+ .{ .kind = "nonimage-png", .expected = .convert },+ .{ .kind = "unsupported-file", .ext = "unsupported", .expected = .empty, .source_png = true },+ .{ .kind = "remote", .expected = .empty },+ .{ .kind = "unsupported", .expected = .empty },+ .{ .kind = "unsupported-text", .expected = .empty },+ };+ for (cases) |case| {+ const board = clip.tempPath(io, gpa, "pasteboard") orelse return error.OutOfMemory;+ defer gpa.free(board);+ defer releaseBoard(board);+ const source = clip.tempPath(io, gpa, case.ext) orelse return error.OutOfMemory;+ defer clip.discard(io, gpa, source);+ const r = try runner.runCapped(gpa, io, &.{ "/usr/bin/osascript", "-l", "JavaScript", "-e", setup, board, case.kind, source }, 64, 2048, 5000);+ defer gpa.free(r.stdout);+ defer gpa.free(r.stderr);+ try std.testing.expect(runner.ranOk(r));+ try std.testing.expectEqualStrings("ready", std.mem.trim(u8, r.stdout, " \r\n"));+ const got = native.grab(io, gpa, board);+ defer if (got == .ok) got.ok.release(io, gpa);+ const matches = switch (case.expected) {+ .empty => got == .empty,+ .convert => got == .failed and got.failed == .convert,+ .png => got == .ok and got.ok.flavor == .png,+ .furl => got == .ok and got.ok.flavor == .furl,+ };+ if (!matches) std.debug.print("clipboard edge case {s}: expected {s}, got {s}\n", .{ case.kind, @tagName(case.expected), @tagName(got) });+ try std.testing.expect(matches);+ if (got == .ok) {+ try std.testing.expect(got.ok.owned);+ try std.testing.expect(clip.looksLikePng(io, got.ok.path));+ try std.testing.expect(!std.mem.eql(u8, source, got.ok.path));+ }+ if (case.source_png) try std.testing.expect(clip.looksLikePng(io, source));+ if (std.mem.eql(u8, case.kind, "missing")) try std.testing.expect(clip.regularFileSize(io, source) == null);+ if (std.mem.startsWith(u8, case.kind, "nonimage")) try std.testing.expectEqual(@as(?u64, 12), clip.regularFileSize(io, source));+ }+}diff --git a/src/clipboard_failure_tests.zig b/src/clipboard_failure_tests.zignew file mode 100644index 00000000..eafe6935--- /dev/null+++ b/src/clipboard_failure_tests.zig@@ -0,0 +1,147 @@+//! Synthetic process-boundary regressions for clipboard failures (#883).+const std = @import("std");+const native = @import("clipboard_native.zig");+const clip = @import("vision_clipboard.zig");+const paste = @import("vision_paste.zig");+const runner = @import("process_runner.zig");++const Reply = struct {+ stdout: []const u8 = "",+ stderr: []const u8 = "",+ exit_code: u8 = 0,+ truncated: bool = false,+ timed_out: bool = false,+ cancelled: bool = false,+ stderr_truncated: bool = false,+ missing: bool = false,+ file: ?[]const u8 = null,+};++fn check(comptime replies: []const Reply, expected: clip.GrabAttempt) !void {+ const Mock = struct {+ var calls: usize = 0;+ var path_buf: [1024]u8 = undefined;+ var path_len: usize = 0;++ fn run(gpa: std.mem.Allocator, io: std.Io, argv: []const []const u8, stdout_cap: usize, stderr_cap: usize, deadline_ms: u64) !runner.CappedRun {+ try std.testing.expectEqual(@as(usize, 7), argv.len);+ try std.testing.expectEqualStrings("clipboard-failure-test", argv[6]);+ try std.testing.expectEqual(@as(usize, 64), stdout_cap);+ try std.testing.expectEqual(@as(usize, 1024), stderr_cap);+ try std.testing.expectEqual(@as(u64, 5000), deadline_ms);+ try std.testing.expect(calls < replies.len);+ if (calls == 0) {+ try std.testing.expect(argv[5].len <= path_buf.len);+ path_len = argv[5].len;+ @memcpy(path_buf[0..path_len], argv[5]);+ } else {+ try std.testing.expectEqualStrings(path_buf[0..path_len], argv[5]);+ }+ const reply = replies[calls];+ calls += 1;+ if (reply.file) |bytes| {+ try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = argv[5], .data = bytes });+ }+ if (reply.missing) return error.FileNotFound;+ const stdout = try gpa.dupe(u8, reply.stdout);+ errdefer gpa.free(stdout);+ const stderr = try gpa.dupe(u8, reply.stderr);+ return .{+ .term = .{ .exited = reply.exit_code },+ .stdout = stdout,+ .stderr = stderr,+ .stdout_truncated = reply.truncated,+ .stderr_truncated = reply.stderr_truncated,+ .timed_out = reply.timed_out,+ .cancelled = reply.cancelled,+ };+ }+ };+ Mock.calls = 0;+ Mock.path_len = 0;+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ // Remove a leaked fixture even when a cleanup assertion fails.+ defer if (Mock.path_len != 0) std.Io.Dir.cwd().deleteFile(io, Mock.path_buf[0..Mock.path_len]) catch {};+ const got = native.grabWithRunner(io, gpa, "clipboard-failure-test", Mock.run);+ defer if (got == .ok) got.ok.release(io, gpa);+ try std.testing.expectEqual(replies.len, Mock.calls);+ try std.testing.expectEqual(std.meta.activeTag(expected), std.meta.activeTag(got));+ switch (expected) {+ .failed => |kind| {+ try std.testing.expectEqual(kind, got.failed);+ if (kind == .access) {+ const message = paste.pasteMessage(.{ .failed = got.failed });+ try std.testing.expect(std.mem.indexOf(u8, message, "Automation") == null);+ try std.testing.expect(std.mem.indexOf(u8, message, "synthetic helper error") == null);+ }+ },+ .empty => {},+ .ok => {+ try std.testing.expect(got.ok.owned);+ try std.testing.expectEqual(clip.Flavor.png, got.ok.flavor);+ try std.testing.expectEqualStrings(Mock.path_buf[0..Mock.path_len], got.ok.path);+ try std.testing.expect(clip.looksLikePng(io, got.ok.path));+ },+ }+ if (got != .ok) {+ try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().statFile(io, Mock.path_buf[0..Mock.path_len], .{}));+ }+}++test "#883 missing clipboard executable is unavailable" {+ try check(&.{.{ .missing = true }}, .{ .failed = .unavailable });+}++test "#883 clipboard timeout takes precedence over helper reply" {+ try check(&.{.{ .stdout = "ok:png", .timed_out = true, .file = "partial" }}, .{ .failed = .timeout });+}++test "#883 clipboard changed twice exhausts retry and removes partial file" {+ try check(&.{ .{ .stdout = "changed", .file = "partial" }, .{ .stdout = "changed", .file = "partial again" } }, .{ .failed = .changed });+}++test "#883 clipboard changed then PNG succeeds and retains owned file" {+ try check(&.{ .{ .stdout = "changed", .file = "partial" }, .{ .stdout = "ok:png", .file = clip.png_magic } }, .{ .ok = .{ .path = "", .flavor = .png, .owned = true } });+}++test "#883 unknown clipboard reply is extraction failure" {+ try check(&.{.{ .stdout = "unexpected" }}, .{ .failed = .extract });+}++test "#883 truncated clipboard reply is extraction failure" {+ try check(&.{.{ .stdout = "ok:png", .truncated = true, .file = clip.png_magic }}, .{ .failed = .extract });+}++test "#883 invalid clipboard flavor is extraction failure" {+ try check(&.{.{ .stdout = "ok:invalid", .file = clip.png_magic }}, .{ .failed = .extract });+}++test "#883 successful clipboard reply without file is extraction failure" {+ try check(&.{.{ .stdout = "ok:png" }}, .{ .failed = .extract });+}++test "#883 successful clipboard reply with bad file is extraction failure" {+ try check(&.{.{ .stdout = "ok:png", .file = "not a PNG" }}, .{ .failed = .extract });+}++test "#883 generic clipboard failure is access without Automation advice" {+ try check(&.{.{ .exit_code = 1, .stderr = "synthetic helper error", .file = "partial" }}, .{ .failed = .access });+}++test "#883 explicit Apple Event denial is denied" {+ try check(&.{.{ .exit_code = 1, .stderr = "synthetic helper error (-1743)\n" }}, .{ .failed = .denied });+}++test "#883 clipboard retry cannot accept stale output" {+ try check(&.{ .{ .stdout = "changed", .file = clip.png_magic }, .{ .stdout = "ok:png" } }, .{ .failed = .extract });+}++test "#883 truncated denial and cancellation never imply permission failure" {+ try check(&.{.{ .exit_code = 1, .stderr = "error (-1743)", .stderr_truncated = true }}, .{ .failed = .access });+ try check(&.{.{ .stdout = "ok:png", .cancelled = true, .file = clip.png_magic }}, .{ .failed = .access });+}++test "#883 empty clipboard removes partial file" {+ try check(&.{.{ .stdout = "empty", .file = "partial" }}, .empty);+}diff --git a/src/clipboard_native.zig b/src/clipboard_native.zigindex b6b2cc77..ad665418 100644--- a/src/clipboard_native.zig+++ b/src/clipboard_native.zig@@ -6,27 +6,38 @@ pub const script = @embedFile("clipboard_export.js");pub fn grab(io: std.Io, gpa: std.mem.Allocator, board: []const u8) clip.GrabAttempt {if (@import("builtin").os.tag != .macos) return .empty;- const path = clip.tempPath(io, gpa, "png") orelse return .{ .failed = .access };+ return grabWithRunner(io, gpa, board, runner.runCapped);+}++/// Same extraction path with an injected process boundary for failure tests.+pub fn grabWithRunner(io: std.Io, gpa: std.mem.Allocator, board: []const u8, run: anytype) clip.GrabAttempt {+ const path = clip.tempPath(io, gpa, "png") orelse return .{ .failed = .extract };var keep = false;defer if (!keep) clip.discard(io, gpa, path);// Retry only when the clipboard changed during the read. Promised flavors// can take time to materialize, but cannot block a paste indefinitely.for (0..2) |_| {- const r = runner.runCapped(gpa, io, &.{ "/usr/bin/osascript", "-l", "JavaScript", "-e", script, path, board }, 64, 1024, 5000) catch return .{ .failed = .access };+ const r = run(gpa, io, &.{ "/usr/bin/osascript", "-l", "JavaScript", "-e", script, path, board }, 64, 1024, 5000) catch |err| return .{ .failed = switch (err) {+ error.FileNotFound, error.AccessDenied => .unavailable,+ else => .access,+ } };defer gpa.free(r.stdout);defer gpa.free(r.stderr);- if (!runner.ranOk(r) or r.stdout_truncated) return .{ .failed = .access };- const status = std.mem.trim(u8, r.stdout, " \r\n");- if (std.mem.eql(u8, status, "changed")) continue;- if (std.mem.eql(u8, status, "empty")) return .empty;- if (std.mem.eql(u8, status, "convert")) return .{ .failed = .convert };- if (!std.mem.startsWith(u8, status, "ok:")) return .{ .failed = .extract };+ const flavor = switch (@import("clipboard_result.zig").classify(r)) {+ .changed => {+ // A retry must export fresh bytes, not accept an earlier file.+ std.Io.Dir.cwd().deleteFile(io, path) catch {};+ continue;+ },+ .empty => return .empty,+ .failed => |kind| return .{ .failed = kind },+ .image => |flavor| flavor,+ };if (!clip.looksLikePng(io, path)) return .{ .failed = .extract };- const flavor = std.meta.stringToEnum(clip.Flavor, status[3..]) orelse return .{ .failed = .extract };keep = true;return .{ .ok = .{ .path = path, .flavor = flavor, .owned = true } };}- return .{ .failed = .access };+ return .{ .failed = .changed };}test "#843 real named pasteboards export PNG TIFF JPEG file URLs and distinguish invalid data" {diff --git a/src/clipboard_result.zig b/src/clipboard_result.zignew file mode 100644index 00000000..b38ad34c--- /dev/null+++ b/src/clipboard_result.zig@@ -0,0 +1,35 @@+//! Privacy-safe classification of the clipboard helper's bounded reply.+//! AppKit reads do not send Apple Events; a failed helper is not evidence+//! that the terminal needs Automation permission (#883).+const std = @import("std");+const clip = @import("vision_clipboard.zig");+const runner = @import("process_runner.zig");++pub const Result = union(enum) {+ image: clip.Flavor,+ empty,+ changed,+ failed: clip.FailKind,+};++pub fn classify(r: runner.CappedRun) Result {+ if (r.timed_out) return .{ .failed = .timeout };+ if (r.cancelled) return .{ .failed = .access };+ if (!runner.ranOk(r)) {+ // Only the system's explicit Apple Event denial code warrants a+ // permission category. Never show raw stderr (it may contain paths).+ if (r.term == .exited and !r.stderr_truncated and std.mem.endsWith(u8, std.mem.trim(u8, r.stderr, " \r\n"), "(-1743)"))+ return .{ .failed = .denied };+ return .{ .failed = .access };+ }+ if (r.stdout_truncated) return .{ .failed = .extract };+ const status = std.mem.trim(u8, r.stdout, " \r\n");+ if (std.mem.eql(u8, status, "changed")) return .changed;+ if (std.mem.eql(u8, status, "empty")) return .empty;+ if (std.mem.eql(u8, status, "convert")) return .{ .failed = .convert };+ if (std.mem.startsWith(u8, status, "ok:")) {+ if (std.meta.stringToEnum(clip.Flavor, status[3..])) |flavor|+ return .{ .image = flavor };+ }+ return .{ .failed = .extract };+}diff --git a/src/main.zig b/src/main.zigindex a95fede8..0d225155 100644--- a/src/main.zig+++ b/src/main.zig@@ -49,7 +49,7 @@ const learn_store = @import("learn_store.zig");const learn_eval = @import("learn_eval.zig");const learn_cli = @import("learn_cli.zig");test {- _ = @import("clipboard_native.zig");+ _ = .{ @import("clipboard_native.zig"), @import("clipboard_edge_tests.zig"), @import("clipboard_failure_tests.zig"), @import("process_runner_clipboard_tests.zig") };_ = @import("server_orphan.zig");_ = @import("repo_transaction.zig");_ = .{ @import("pr_command.zig"), @import("pr_evidence.zig"), @import("pr_verify.zig") };diff --git a/src/process_runner.zig b/src/process_runner.zigindex dc9b121a..43480bf2 100644--- a/src/process_runner.zig+++ b/src/process_runner.zig@@ -183,6 +183,53 @@ fn terminateTree(child: *std.process.Child, io: Io, job: *WindowsJobHandle, grouchild.kill(io);}+// A canceled POSIX wait closes the pipes and clears id without reaping.+// Retain the id so the caller can still kill/reap after a deadline or Esc.+fn waitForExit(child: *std.process.Child, io: Io, started: Io.Timestamp, deadline_ms: u64, cancelled: *bool, timed_out: *bool) !std.process.Child.Term {+ const id = child.id;+ const Event = union(enum) { term: std.process.Child.WaitError!std.process.Child.Term, tick: Io.Cancelable!void };+ var buffer: [2]Event = undefined;+ var select = Io.Select(Event).init(io, &buffer);+ try select.concurrent(.term, std.process.Child.wait, .{ child, io });+ defer {+ while (select.cancel()) |event| switch (event) {+ .term => |result| {+ _ = result catch |err| {+ if (comptime posix_process_groups) if (err == error.Canceled) {+ child.id = id;+ };+ };+ },+ .tick => {},+ };+ }+ while (true) {+ select.async(.tick, Io.sleep, .{ io, .fromMilliseconds(20), .awake });+ switch (try select.await()) {+ .term => |result| return result catch |err| {+ if (comptime posix_process_groups) if (err == error.Canceled) {+ child.id = id;+ };+ return err;+ },+ .tick => |result| try result,+ }+ cancelled.* = Agent.esc_cancel.load(.acquire);+ timed_out.* = deadline_ms > 0 and started.untilNow(io, .awake).toMilliseconds() >= deadline_ms;+ if (cancelled.* or timed_out.*) {+ while (select.cancel()) |event| switch (event) {+ .term => |result| return result catch |err| {+ if (err != error.Canceled) return err;+ if (comptime posix_process_groups) child.id = id;+ return .{ .signal = .TERM };+ },+ .tick => {},+ };+ unreachable;+ }+ }+}+pub fn runCapped(gpa: Allocator, io: Io, argv: []const []const u8, stdout_cap: usize, stderr_cap: usize, deadline_ms: u64) !CappedRun {return runCappedWithOptions(gpa, io, argv, stdout_cap, stderr_cap, deadline_ms, .{});}@@ -276,9 +323,16 @@ pub fn runCappedWithOptions(gpa: Allocator, io: Io, argv: []const []const u8, st}if (!esc_killed and !timed_out) try multi_reader.checkAnyError();- const term: std.process.Child.Term = if (esc_killed or timed_out) .{ .signal = .TERM } else try child.wait(io);+ const term: std.process.Child.Term = if (esc_killed or timed_out) .{ .signal = .TERM } else blk: {+ const term = try waitForExit(&child, io, started, deadline_ms, &esc_killed, &timed_out);+ if (esc_killed or timed_out) {+ terminateTree(&child, io, &windows_job, group_id, options.kill_process_tree);+ cleanup_needed = false;+ }+ break :blk term;+ };const stdout = if (saved[0]) |bytes| bytes else try gpa.dupe(u8, readers[0].buffered());- errdefer gpa.free(stdout);+ errdefer if (saved[0] == null) gpa.free(stdout);const stderr = if (saved[1]) |bytes| bytes else try gpa.dupe(u8, readers[1].buffered());return .{.term = term,diff --git a/src/process_runner_clipboard_tests.zig b/src/process_runner_clipboard_tests.zignew file mode 100644index 00000000..ff77c792--- /dev/null+++ b/src/process_runner_clipboard_tests.zig@@ -0,0 +1,60 @@+const std = @import("std");+const builtin = @import("builtin");+const runner = @import("process_runner.zig");++test "clipboard runner deadline survives pipe EOF" {+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;+ const io = std.testing.io;+ const started = std.Io.Timestamp.now(io, .awake);+ const result = try runner.runCappedWithOptions(std.testing.allocator, io, &.{ "/bin/sh", "-c", "exec 1>&- 2>&-; exec sleep 30" }, 8, 8, 200, .{});+ defer std.testing.allocator.free(result.stdout);+ defer std.testing.allocator.free(result.stderr);+ try std.testing.expect(result.timed_out);+ try std.testing.expect(started.untilNow(io, .awake).toMilliseconds() < 2000);+}++test "clipboard runner EOF still returns natural exit and capped output" {+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;+ const result = try runner.runCappedWithOptions(std.testing.allocator, std.testing.io, &.{ "/bin/sh", "-c", "printf 123456789; printf error >&2; exec 1>&- 2>&-; sleep 0.05; exit 7" }, 4, 3, 0, .{});+ defer std.testing.allocator.free(result.stdout);+ defer std.testing.allocator.free(result.stderr);+ try std.testing.expectEqual(@as(u8, 7), result.term.exited);+ try std.testing.expectEqualStrings("1234", result.stdout);+ try std.testing.expectEqualStrings("err", result.stderr);+ try std.testing.expect(result.stdout_truncated and result.stderr_truncated);+ try std.testing.expect(!result.timed_out and !result.cancelled);+}++fn cancelSoon(io: std.Io) void {+ io.sleep(.fromMilliseconds(100), .awake) catch return;+ @import("agent.zig").Agent.esc_cancel.store(true, .release);+}++test "clipboard runner Esc survives pipe EOF without deadline" {+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;+ const io = std.testing.io;+ defer @import("agent.zig").Agent.esc_cancel.store(false, .release);+ var cancel = try io.concurrent(cancelSoon, .{io});+ defer cancel.cancel(io);+ const started = std.Io.Timestamp.now(io, .awake);+ const result = try runner.runCappedWithOptions(std.testing.allocator, io, &.{ "/bin/sh", "-c", "exec 1>&- 2>&-; exec sleep 30" }, 8, 8, 0, .{ .kill_process_tree = true });+ defer std.testing.allocator.free(result.stdout);+ defer std.testing.allocator.free(result.stderr);+ try std.testing.expect(result.cancelled and !result.timed_out);+ try std.testing.expect(started.untilNow(io, .awake).toMilliseconds() < 2000);+}++fn cappedAllocation(gpa: std.mem.Allocator) !void {+ const result = try runner.runCappedWithOptions(gpa, std.testing.io, &.{ "/bin/sh", "-c", "printf 123456789; printf err >&2" }, 4, 8, 2000, .{});+ defer gpa.free(result.stdout);+ defer gpa.free(result.stderr);+ try std.testing.expectEqualStrings("1234", result.stdout);+ try std.testing.expectEqualStrings("err", result.stderr);+ try std.testing.expect(result.stdout_truncated);+ try std.testing.expect(!result.stderr_truncated);+}++test "clipboard runner capped stdout allocation failures" {+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;+ try std.testing.checkAllAllocationFailures(std.testing.allocator, cappedAllocation, .{});+}diff --git a/src/vision_clipboard.zig b/src/vision_clipboard.zigindex 5db58aef..5e6a49e7 100644--- a/src/vision_clipboard.zig+++ b/src/vision_clipboard.zig@@ -52,7 +52,7 @@ pub const Flavor = enum {/// Why a clipboard extraction failed without yielding an image (#843)./// Categories stay privacy-safe: they never include clipboard contents.-pub const FailKind = enum { access, extract, convert };+pub const FailKind = enum { access, denied, unavailable, timeout, changed, extract, convert };/// Result of one pasteboard grab. Null used to mean both "nothing there"/// and "osascript/sips failed", which Ctrl-V then reported as an emptydiff --git a/src/vision_paste.zig b/src/vision_paste.zigindex b1b50ffb..7e3d4b36 100644--- a/src/vision_paste.zig+++ b/src/vision_paste.zig@@ -43,7 +43,11 @@ pub fn clipboardPasteSource(io: Io, gpa: Allocator, supports_vision: bool, is_mapub fn pasteFailMessage(kind: FailKind) []const u8 {return switch (kind) {- .access => "couldn't read the clipboard — grant Automation access for osascript, then try again",+ .access => "clipboard read failed — retry Copy; use Edit > Paste for text or /image <path>",+ .denied => "macOS denied clipboard access — use Edit > Paste for text or /image <path>",+ .unavailable => "clipboard helper unavailable — use Edit > Paste for text or /image <path>",+ .timeout => "clipboard read timed out — copy again, or save it and use /image <path>",+ .changed => "clipboard changed while reading — copy again and retry, or use /image <path>",.extract => "the clipboard image could not be exported — try Copy again, or save it and /image <path>",.convert => "the clipboard image could not be converted — try a PNG or JPEG",};@@ -103,6 +107,10 @@ test "pasteMessage: empty clipboard and extraction failure are distinct (#843)".unsupported_platform,.no_image,.{ .failed = .access },+ .{ .failed = .denied },+ .{ .failed = .unavailable },+ .{ .failed = .timeout },+ .{ .failed = .changed },.{ .failed = .extract },.{ .failed = .convert },};