Skip to content

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

Python

Track clipboard file ownership across active consumers

justrachd8e26f86cab3
diff --git a/TUI/app.zig b/TUI/app.zig
index 586c0a1d..da7f9e97 100644
--- a/TUI/app.zig
+++ b/TUI/app.zig
@@ -90,6 +90,7 @@ pub const Model = struct {
draft_images: ?[]const []const u8 = null,
steer_queue: std.array_list.Managed([]const u8),
images: std.array_list.Managed([]const u8),
+ owned_images: std.array_list.Managed([]const u8),
pending: ?*engine.Job = null,
/// A background engine op (/compact, !cmd, @-file list) — same thread +
/// done-flag contract as `pending`, so neither can freeze the loop (#533).
@@ -221,12 +222,15 @@ pub const Model = struct {
.prompt_hist_images = std.array_list.Managed([]const []const u8).init(alloc),
.steer_queue = std.array_list.Managed([]const u8).init(alloc),
.images = std.array_list.Managed([]const u8).init(alloc),
+ .owned_images = std.array_list.Managed([]const u8).init(alloc),
.chat = engine.g_turn_fn != null,
};
self.input.setPlaceholder("");
}
pub fn deinit(self: *Model) void {
+ const settled = (if (self.pending) |job| !job.threaded or job.done.load(.acquire) else true) and
+ (if (self.bg) |op| !op.threaded or op.done.load(.acquire) else true);
// Never an unbounded join in a destructor (#534): by the time deinit
// runs, run.zig's terminal defers have already handed the shell back,
// so joining a stalled provider call here hangs invisibly. run.zig
@@ -238,6 +242,7 @@ pub const Model = struct {
if (self.bg) |op| {
if (!op.threaded or op.done.load(.acquire)) @import("bgop.zig").reap(self) else self.bg = null;
}
+ @import("owned_images.zig").deinit(self, settled);
self.layout.deinit(self.alloc);
for (self.history.items) |e| self.freeEntry(e);
self.history.deinit();
@@ -276,6 +281,7 @@ pub const Model = struct {
job.events.deinit();
self.alloc.destroy(job);
self.pending = null;
+ @import("owned_images.zig").collect(self);
}
pub fn theme(self: *const Model) theme_mod.Theme {
diff --git a/TUI/dispatch.zig b/TUI/dispatch.zig
index 54e57521..ce59d610 100644
--- a/TUI/dispatch.zig
+++ b/TUI/dispatch.zig
@@ -441,9 +441,10 @@ pub fn recallNext(self: *Model) void {
pub fn pasteClipboard(self: *Model) void {
if (engine.g_paste_fn) |f| {
var buf: [1024]u8 = undefined;
- const n = f(engine.g_turn_ctx, &buf);
+ var owned = false;
+ const n = f(engine.g_turn_ctx, &buf, &owned);
if (n > 0) {
- self.attachImage(buf[0..@intCast(n)]);
+ @import("owned_images.zig").attach(self, buf[0..@intCast(n)], owned);
} else if (n < 0) {
self.setToast(buf[0..@intCast(-n)]);
} else self.setToast("no image on the clipboard — Ctrl+V (⌘V can't be captured)");
diff --git a/TUI/engine_types.zig b/TUI/engine_types.zig
index 1293b4c7..1a2016c1 100644
--- a/TUI/engine_types.zig
+++ b/TUI/engine_types.zig
@@ -118,8 +118,8 @@ pub const Picked = struct { model: []const u8, provider: []const u8 = "" };
/// by name, which is what the picker used to be stuck doing for every pick.
pub const ModelFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, provider: []const u8, name: []const u8) ?Picked;
pub const CancelFn = *const fn (turn_ctx: ?*anyopaque) void;
-/// Fill dest with a staged image path (return >0) or an error line (return <0).
-pub const PasteFn = *const fn (turn_ctx: ?*anyopaque, dest: []u8) isize;
+/// Fill dest with an image path (>0) and its ownership, or an error line (<0).
+pub const PasteFn = *const fn (turn_ctx: ?*anyopaque, dest: []u8, owned: *bool) isize;
/// Run a user-typed `!` shell line; return combined output (caller frees), the
/// gate's refusal, or null when the harness could not produce either. `params`
/// carries the session's policy because `!` goes through the same gate the
diff --git a/TUI/image.zig b/TUI/image.zig
index eacd57ba..546caa14 100644
--- a/TUI/image.zig
+++ b/TUI/image.zig
@@ -312,6 +312,7 @@ pub fn dropLast(self: *Model) bool {
const last = self.images.pop() orelse return false;
forgetPreview(self, last);
self.alloc.free(last);
+ @import("owned_images.zig").collect(self);
return true;
}
@@ -321,6 +322,7 @@ pub fn clearAll(self: *Model) void {
self.alloc.free(p);
}
self.images.clearRetainingCapacity();
+ @import("owned_images.zig").collect(self);
}
pub fn dropPreviewed(self: *Model) bool {
@@ -328,6 +330,7 @@ pub fn dropPreviewed(self: *Model) bool {
const path = self.images.orderedRemove(self.preview_n - 1);
forgetPreview(self, path);
self.alloc.free(path);
+ @import("owned_images.zig").collect(self);
return true;
}
diff --git a/TUI/imgproto.zig b/TUI/imgproto.zig
index bce2ed69..2cdae758 100644
--- a/TUI/imgproto.zig
+++ b/TUI/imgproto.zig
@@ -177,15 +177,31 @@ fn loadPng(alloc: std.mem.Allocator, path: []const u8) ?[]u8 {
fn convertToPng(alloc: std.mem.Allocator, path: []const u8) ?[]u8 {
if (builtin.os.tag != .macos) return null;
const io = ioHandle();
- var dst_buf: [80]u8 = undefined;
- const dst = std.fmt.bufPrint(&dst_buf, "/tmp/graff-img-{d}.png", .{std.c.getpid()}) catch return null;
+ var random: [16]u8 = undefined;
+ io.random(&random);
+ const hex = std.fmt.bytesToHex(random, .lower);
+ var dst_buf: [100]u8 = undefined;
+ const dst = std.fmt.bufPrint(&dst_buf, "/tmp/graff-img-{d}-{s}.png", .{ std.c.getpid(), hex }) catch return null;
+ return convertToPngAt(alloc, path, dst);
+}
+
+fn convertToPngAt(alloc: std.mem.Allocator, path: []const u8, dst: []const u8) ?[]u8 {
+ var threaded = Io.Threaded.init(alloc, .{});
+ defer threaded.deinit();
+ const io = threaded.io();
+ // Claim our output before the converter runs; never overwrite or clean up
+ // an existing file, including one belonging to another conversion.
+ const claim = Io.Dir.cwd().createFile(io, dst, .{ .exclusive = true, .permissions = .fromMode(0o600) }) catch return null;
+ claim.close(io);
+ defer Io.Dir.cwd().deleteFile(io, dst) catch {};
var child = std.process.spawn(io, .{
- .argv = &.{ "sips", "-s", "format", "png", path, "--out", dst },
+ .argv = &.{ "/usr/bin/sips", "-s", "format", "png", path, "--out", dst },
.stdin = .ignore,
.stdout = .ignore,
.stderr = .ignore,
}) catch return null;
- _ = child.wait(io) catch return null;
+ const term = child.wait(io) catch return null;
+ if (term != .exited or term.exited != 0) return null;
const file = std.Io.Dir.cwd().openFile(io, dst, .{}) catch return null;
defer file.close(io);
const info = file.stat(io) catch return null;
@@ -394,3 +410,57 @@ test "fitImageToCells matches Grok cell-aspect 0.5" {
try std.testing.expectEqual(@as(usize, 20), sq.cols);
try std.testing.expectEqual(@as(usize, 10), sq.rows);
}
+
+test "preview conversion removes its scratch output after reading valid pixels" {
+ if (builtin.os.tag != .macos) return error.SkipZigTest;
+ const alloc = std.testing.allocator;
+ const io = ioHandle();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ // A one-pixel 24-bit BMP, so the real converter must produce PNG bytes.
+ var bmp: [58]u8 = @splat(0);
+ @memcpy(bmp[0..2], "BM");
+ std.mem.writeInt(u32, bmp[2..6], 58, .little);
+ std.mem.writeInt(u32, bmp[10..14], 54, .little);
+ std.mem.writeInt(u32, bmp[14..18], 40, .little);
+ std.mem.writeInt(u32, bmp[18..22], 1, .little);
+ std.mem.writeInt(u32, bmp[22..26], 1, .little);
+ std.mem.writeInt(u16, bmp[26..28], 1, .little);
+ std.mem.writeInt(u16, bmp[28..30], 24, .little);
+ std.mem.writeInt(u32, bmp[34..38], 4, .little);
+ bmp[56] = 255;
+ try tmp.dir.writeFile(io, .{ .sub_path = "input.bmp", .data = &bmp });
+ const root = try tmp.dir.realPathFileAlloc(io, ".", alloc);
+ defer alloc.free(root);
+ const input = try std.fs.path.join(alloc, &.{ root, "input.bmp" });
+ defer alloc.free(input);
+ const output = try std.fs.path.join(alloc, &.{ root, "scratch.png" });
+ defer alloc.free(output);
+ const bytes = convertToPngAt(alloc, input, output) orelse return error.ConversionFailed;
+ defer alloc.free(bytes);
+ try std.testing.expect(isPng(bytes));
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "scratch.png", .{}));
+ const original = try tmp.dir.openFile(io, "input.bmp", .{});
+ original.close(io);
+}
+
+test "failed preview conversion removes only its claimed scratch output" {
+ if (builtin.os.tag != .macos) return error.SkipZigTest;
+ const alloc = std.testing.allocator;
+ const io = ioHandle();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(io, ".", alloc);
+ defer alloc.free(root);
+ const output = try std.fs.path.join(alloc, &.{ root, "scratch.png" });
+ defer alloc.free(output);
+ try std.testing.expect(convertToPngAt(alloc, "/missing-preview-input", output) == null);
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "scratch.png", .{}));
+ try tmp.dir.writeFile(io, .{ .sub_path = "scratch.png", .data = "existing original" });
+ try std.testing.expect(convertToPngAt(alloc, "/missing-preview-input", output) == null);
+ const original = try tmp.dir.openFile(io, "scratch.png", .{});
+ defer original.close(io);
+ var bytes: [32]u8 = undefined;
+ const count = try original.readPositionalAll(io, &bytes, 0);
+ try std.testing.expectEqualStrings("existing original", bytes[0..count]);
+}
diff --git a/TUI/issue_883_tests.zig b/TUI/issue_883_tests.zig
index 5587787b..393c8c9d 100644
--- a/TUI/issue_883_tests.zig
+++ b/TUI/issue_883_tests.zig
@@ -10,11 +10,13 @@ const Term = @import("sim.zig").Term;
const Paste = struct {
payload: []const u8,
failed: bool = false,
+ owned: bool = false,
calls: usize = 0,
- fn call(ctx: ?*anyopaque, dest: []u8) isize {
+ fn call(ctx: ?*anyopaque, dest: []u8, owned: *bool) isize {
const self: *Paste = @ptrCast(@alignCast(ctx.?));
self.calls += 1;
+ owned.* = self.owned;
const n = @min(self.payload.len, dest.len);
@memcpy(dest[0..n], self.payload[0..n]);
const result: isize = @intCast(n);
@@ -111,3 +113,110 @@ test "#883 Ctrl-V empty callback result is visible without changing the prompt"
try std.testing.expectEqual(@as(usize, 0), term.model.images.items.len);
try expectVisible(&term, "no image on the clipboard");
}
+
+test "clipboard-owned attachment removal deletes the export but preserves an original" {
+ 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;
+ const io = std.Io.Threaded.global_single_threaded.io();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(io, ".", std.testing.allocator);
+ defer std.testing.allocator.free(root);
+ const path = try std.fs.path.join(std.testing.allocator, &.{ root, "paste.png" });
+ defer std.testing.allocator.free(path);
+ for ([_]bool{ true, false }) |owned| {
+ try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });
+ var paste = Paste{ .payload = path, .owned = owned };
+ engine.g_turn_ctx = &paste;
+ var term: Term = undefined;
+ term.init(std.testing.allocator, 100, 24);
+ defer term.deinit();
+ _ = term.feed("\x16");
+ try std.testing.expectEqual(@as(usize, 1), term.model.images.items.len);
+ _ = term.feed("\x7f");
+ try std.testing.expectEqual(@as(usize, 0), term.model.images.items.len);
+ if (owned) {
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "paste.png", .{}));
+ } else {
+ const original = try tmp.dir.openFile(io, "paste.png", .{});
+ original.close(io);
+ }
+ }
+}
+
+test "sent clipboard export survives prompt recall and remains available for saved replay" {
+ 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;
+ const io = std.Io.Threaded.global_single_threaded.io();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });
+ const path = try tmp.dir.realPathFileAlloc(io, "paste.png", std.testing.allocator);
+ defer std.testing.allocator.free(path);
+ var paste = Paste{ .payload = path, .owned = true };
+ engine.g_turn_ctx = &paste;
+ {
+ var term: Term = undefined;
+ term.init(std.testing.allocator, 100, 24);
+ defer term.deinit();
+ _ = term.feed("\x16");
+ _ = term.typeText("describe this");
+ _ = term.enter();
+ @import("owned_images.zig").collect(&term.model);
+ const retained = try tmp.dir.openFile(io, "paste.png", .{});
+ retained.close(io);
+ @import("prompt_history.zig").recallPrev(&term.model);
+ try std.testing.expectEqualStrings(path, term.model.images.items[0]);
+ @import("image.zig").clearAll(&term.model);
+ const history = try tmp.dir.openFile(io, "paste.png", .{});
+ history.close(io);
+ }
+ const replay = try tmp.dir.openFile(io, "paste.png", .{});
+ replay.close(io);
+}
+
+test "queued clipboard exports remain readable until the queue releases them" {
+ const io = std.Io.Threaded.global_single_threaded.io();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });
+ const path = try tmp.dir.realPathFileAlloc(io, "paste.png", std.testing.allocator);
+ defer std.testing.allocator.free(path);
+ var term: Term = undefined;
+ term.init(std.testing.allocator, 100, 24);
+ defer term.deinit();
+ @import("owned_images.zig").attach(&term.model, path, true);
+ @import("dispatch.zig").queueSteerLine(&term.model, "describe this");
+ @import("owned_images.zig").collect(&term.model);
+ const retained = try tmp.dir.openFile(io, "paste.png", .{});
+ retained.close(io);
+ term.model.alloc.free(term.model.steer_queue.pop().?);
+ @import("owned_images.zig").collect(&term.model);
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "paste.png", .{}));
+}
+
+test "closing an unsent clipboard draft releases only its owned export" {
+ const io = std.Io.Threaded.global_single_threaded.io();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });
+ const path = try tmp.dir.realPathFileAlloc(io, "paste.png", std.testing.allocator);
+ defer std.testing.allocator.free(path);
+ {
+ var term: Term = undefined;
+ term.init(std.testing.allocator, 100, 24);
+ defer term.deinit();
+ @import("owned_images.zig").attach(&term.model, path, true);
+ }
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "paste.png", .{}));
+}
diff --git a/TUI/owned_images.zig b/TUI/owned_images.zig
new file mode 100644
index 00000000..adc03885
--- /dev/null
+++ b/TUI/owned_images.zig
@@ -0,0 +1,69 @@
+//! Owned clipboard exports outlive every live draft/history consumer.
+const std = @import("std");
+const Model = @import("app.zig").Model;
+
+pub fn attach(self: *Model, path: []const u8, owned: bool) void {
+ if (!owned) return self.attachImage(path);
+ const copy = self.alloc.dupe(u8, path) catch {
+ remove(path);
+ return;
+ };
+ self.owned_images.append(copy) catch {
+ self.alloc.free(copy);
+ remove(path);
+ return;
+ };
+ const before = self.images.items.len;
+ self.attachImage(path);
+ if (self.images.items.len == before) collect(self);
+}
+
+fn remove(path: []const u8) void {
+ std.Io.Dir.cwd().deleteFile(std.Io.Threaded.global_single_threaded.io(), path) catch {};
+}
+
+fn contains(paths: []const []const u8, path: []const u8) bool {
+ for (paths) |p| if (std.mem.eql(u8, p, path)) return true;
+ return false;
+}
+
+fn referenced(self: *const Model, path: []const u8) bool {
+ if (contains(self.images.items, path)) return true;
+ if (self.draft_images) |paths| if (contains(paths, path)) return true;
+ for (self.prompt_hist_images.items) |paths| if (contains(paths, path)) return true;
+ for (self.history.items) |entry| if (std.mem.indexOf(u8, entry.text, path) != null) return true;
+ for (self.steer_queue.items) |text| if (std.mem.indexOf(u8, text, path) != null) return true;
+ return false;
+}
+
+pub fn collect(self: *Model) void {
+ // Pending consumers may already hold a snapshot outside the model arrays.
+ if (self.pending != null or self.bg != null) return;
+ var i: usize = 0;
+ while (i < self.owned_images.items.len) {
+ const path = self.owned_images.items[i];
+ if (referenced(self, path)) {
+ i += 1;
+ continue;
+ }
+ remove(path);
+ self.alloc.free(self.owned_images.orderedRemove(i));
+ }
+}
+
+fn replayReferenced(self: *const Model, path: []const u8) bool {
+ for (self.history.items) |entry| {
+ if (entry.kind == .user and std.mem.indexOf(u8, entry.text, path) != null) return true;
+ }
+ return false;
+}
+
+pub fn deinit(self: *Model, settled: bool) void {
+ for (self.owned_images.items) |path| {
+ // Saved turns retain path markers. UI teardown is not proof that
+ // those replay consumers (or an abandoned worker) have released them.
+ if (settled and !replayReferenced(self, path)) remove(path);
+ self.alloc.free(path);
+ }
+ self.owned_images.deinit();
+}
diff --git a/TUI/prompt_history.zig b/TUI/prompt_history.zig
index c5592004..07de4e5e 100644
--- a/TUI/prompt_history.zig
+++ b/TUI/prompt_history.zig
@@ -24,6 +24,7 @@ pub fn remember(self: *Model, line: []const u8) void {
recordImages(self);
self.hist_idx = null;
clearDraft(self);
+ @import("owned_images.zig").collect(self);
}
pub fn recallPrev(self: *Model) void {
@@ -112,6 +113,7 @@ fn replaceImages(self: *Model, paths: []const []const u8) void {
const owned = self.alloc.dupe(u8, p) catch continue;
self.images.append(owned) catch self.alloc.free(owned);
}
+ @import("owned_images.zig").collect(self);
}
fn imagesAt(self: *const Model, idx: usize) []const []const u8 {
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.ts
index ee97d5e4..4b17e299 100644
--- a/apps/native/app/api/acp/route.ts
+++ b/apps/native/app/api/acp/route.ts
@@ -9,6 +9,7 @@ import { AcpTransport } from "@/lib/acp-transport";
import { createPromptStream } from "@/lib/acp-prompt-stream";
import { defaultRoot, resolveRoot } from "@/lib/server-root";
import { prepareGuiPrompt } from "@/lib/gui-skill-context";
+import { attachmentStore } from "@/lib/attachment-store";
import { retireWorker } from "@/lib/acp-retire";
import { initializeWorker } from "@/lib/acp-bootstrap";
@@ -303,6 +304,7 @@ export async function POST(req: NextRequest) {
if (slot.streaming) return Response.json({ error: "A turn is already active" }, { status: 409 });
const promptParams = await prepareGuiPrompt(body.params);
if (slot.streaming) return Response.json({ error: "A turn is already active" }, { status: 409 });
+ attachmentStore().retainPrompt(promptParams);
slot.streaming = true;
const { stream, pending } = createPromptStream(slot.transport,
{ ...promptParams, sessionId: slot.sessionId }, () => {
diff --git a/apps/native/app/api/attach/route.ts b/apps/native/app/api/attach/route.ts
index 3e17d1d0..e2fa8551 100644
--- a/apps/native/app/api/attach/route.ts
+++ b/apps/native/app/api/attach/route.ts
@@ -1,5 +1,5 @@
-import { mkdirSync, readFileSync, realpathSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
-import os from "node:os";
+import { readFileSync, realpathSync, statSync } from "node:fs";
+import { attachmentDirectory, attachmentStore } from "@/lib/attachment-store";
import path from "node:path";
import { NextRequest } from "next/server";
@@ -11,34 +11,13 @@ export const dynamic = "force-dynamic";
* bytes have to land on disk before a prompt can mention them. They go to a
* temp directory rather than the workspace: an attachment belongs to one
* message, not to the project the user happens to be sitting in. */
-const DIR = path.join(os.tmpdir(), "graff-native-attachments");
+const DIR = attachmentDirectory;
/** Generous on purpose. The harness downscales an oversized image to fit its
* own budget, so a tight limit here would refuse work it could actually do;
* this only stops something pathological. */
const MAX_BYTES = 25 * 1024 * 1024;
-/** Attachments are per-message scratch. Sweep anything from a previous day so
- * the directory cannot grow without bound. */
-const MAX_AGE_MS = 24 * 60 * 60 * 1000;
-
-function sweep(now: number) {
- let entries: string[];
- try {
- entries = readdirSync(DIR);
- } catch {
- return;
- }
- for (const name of entries) {
- const full = path.join(DIR, name);
- try {
- if (now - statSync(full).mtimeMs > MAX_AGE_MS) rmSync(full, { force: true });
- } catch {
- // raced with another sweep, or not ours to remove
- }
- }
-}
-
/** Keep the name recognisable in the chip, but never let it steer where the
* write lands. The extension carries meaning: `isImagePath` reads it to
* decide whether these bytes become a vision block. */
@@ -91,18 +70,25 @@ export async function POST(req: NextRequest) {
return Response.json({ error: `larger than the ${MAX_BYTES / (1024 * 1024)}MB attachment limit` }, { status: 413 });
}
- const now = Date.now();
- mkdirSync(DIR, { recursive: true });
- sweep(now);
-
+ attachmentStore().sweep();
const name = safeName(file.name, file.type);
- // Collisions are otherwise certain: every pasted screenshot has the same name.
- const stamped = `${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}-${name}`;
- const target = path.join(DIR, stamped);
+ let target: string;
try {
- writeFileSync(target, new Uint8Array(await file.arrayBuffer()));
+ target = attachmentStore().create(name, new Uint8Array(await file.arrayBuffer()));
} catch (err) {
return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 });
}
return Response.json({ ok: true, path: target, name, type: file.type, size: file.size });
}
+
+
+export async function DELETE(req: NextRequest) {
+ try {
+ const body = await req.json();
+ if (!Array.isArray(body.paths) || body.paths.length > 32 || !body.paths.every((p: unknown) => typeof p === "string")) {
+ return Response.json({ error: "Invalid attachments" }, { status: 400 });
+ }
+ for (const target of body.paths) attachmentStore().discard(target);
+ return Response.json({ ok: true });
+ } catch { return Response.json({ error: "Attachment cleanup failed" }, { status: 500 }); }
+}
diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsx
index 80f8fbd9..52b1a887 100644
--- a/apps/native/components/primitives/PromptBar.tsx
+++ b/apps/native/components/primitives/PromptBar.tsx
@@ -16,6 +16,7 @@ import type { AcpCommand } from "@/lib/acp";
import {
filesFrom,
releaseAttachments,
+ discardAttachments,
uploadAttachment,
withAttachmentMarkers,
} from "@/lib/attachments";
@@ -292,7 +293,7 @@ export default function PromptBar({
const removeAttachment = (id: string) => {
setAttachments((current) => {
- releaseAttachments(current.filter((a) => a.id === id));
+ discardAttachments(current.filter((a) => a.id === id));
return current.filter((a) => a.id !== id);
});
};
diff --git a/apps/native/electron/attachment-lifetime-frontend.cjs b/apps/native/electron/attachment-lifetime-frontend.cjs
new file mode 100644
index 00000000..be4b0b65
--- /dev/null
+++ b/apps/native/electron/attachment-lifetime-frontend.cjs
@@ -0,0 +1,58 @@
+// Exercise the actual paste handler, upload route and ACP image staging.
+const assert = require('node:assert/strict');
+const fs = require('node:fs'), path = require('node:path');
+const { nativeImage } = require('electron');
+async function runAttachments({win,origin,temp,output,requests,workspace,send,click,until,report}) {
+ const wc = win.webContents, js = code => wc.executeJavaScript(code);
+ if(await js(`!!document.querySelector('[aria-label="Close browser"]')`))await click('[aria-label="Close browser"]');
+ const directory = path.join(temp, 'graff-native-attachments');
+ const pixels = Buffer.alloc(64*48*4);
+ for(let i=0;i<pixels.length;i+=4) { pixels[i]=180;pixels[i+1]=120;pixels[i+2]=30;pixels[i+3]=255; }
+ const png = nativeImage.createFromBitmap(pixels,{width:64,height:48}).toPNG().toString('base64');
+ const paste = async name => {
+ await click('textarea[aria-label="Prompt"]');
+ await js(`(()=>{
+ const bytes=Uint8Array.from(atob(${JSON.stringify(png)}),c=>c.charCodeAt(0));
+ const data=new DataTransfer();data.items.add(new File([bytes],${JSON.stringify(name)},{type:'image/png'}));
+ document.querySelector('textarea[aria-label="Prompt"]').dispatchEvent(new ClipboardEvent('paste',{clipboardData:data,bubbles:true,cancelable:true}));
+ })()`);
+ await until(()=>js(`!!document.querySelector(${JSON.stringify(`[aria-label="Preview ${name}"]`)})`),'uploaded paste '+name);
+ const found=fs.readdirSync(directory).find(file=>file.endsWith('-'+name));
+ assert.ok(found,'Paste must write a real owned file');return path.join(directory,found);
+ };
+ await send('/model lmstudio mock-vision');
+ await until(()=>js(`document.body.textContent.includes('mock-vision') && !document.querySelector('article[aria-busy="true"]')`),'vision model selected');
+ const aged=await paste('aged.png');
+ const old=new Date(Date.now()-48*60*60*1000);fs.utimesSync(aged,old,old);
+ const removed=await paste('remove.png');
+ assert.ok(fs.existsSync(aged),'Another upload must preserve an aged active draft');
+ await click('[aria-label="Preview aged.png"]');
+ await until(()=>js(`!!document.querySelector('dialog img')?.complete`),'draft preview pixels');
+ fs.writeFileSync(path.join(output,'attachment-aged-draft.png'),(await wc.capturePage()).toPNG());
+ await click('[aria-label="Close image preview"]');
+ await click('[aria-label="Remove remove.png"]');
+ await until(()=>!fs.existsSync(removed),'discarded paste file cleanup');
+ await send('Describe the pasted image in one sentence.');
+ await until(()=>js(`document.body.textContent.includes('The pasted image was received.') && !document.querySelector('article[aria-busy="true"]')`),'real image turn completion',25000);
+ const calls=JSON.parse(fs.readFileSync(requests,'utf8'));
+ fs.writeFileSync(path.join(output,'attachment-requests.json'),JSON.stringify(calls,null,2));
+ assert.ok(JSON.stringify(calls).includes(png),'Actual model requests must contain the pasted PNG bytes');
+ const record=JSON.parse(fs.readFileSync(path.join(directory,'.ownership',path.basename(aged)+'.json'),'utf8'));
+ assert.equal(record.retained,true,'ACP acceptance must retain replay pixels');
+ await fetch(origin+'/api/attach',{method:'DELETE',headers:{'content-type':'application/json'},body:JSON.stringify({paths:[aged]})});
+ assert.ok(fs.existsSync(aged),'Discard cannot delete pixels retained by an accepted message');
+ assert.equal((await fetch(origin+'/api/attach?name='+encodeURIComponent(path.basename(aged)))).status,200);
+ fs.writeFileSync(path.join(output,'attachment-sent-retained.png'),(await wc.capturePage()).toPNG());
+ await click('[title="New chat (⌘T)"]');
+ const focused=await js(`document.querySelector('[data-chat][data-focused="true"]').dataset.chat`);
+ const closed=await paste('closed.png');
+ await click(`[data-tab-members="${focused}"] [aria-label="Close tab"]`);
+ await until(()=>!fs.existsSync(closed),'closed draft file cleanup');
+ for (const name of ['sessions','traces']) {
+ const source=path.join(workspace,'.graff',name);
+ if(fs.existsSync(source))fs.cpSync(source,path.join(output,'attachment-'+name),{recursive:true});
+ }
+ report.passed.push('synthetic clipboard event through real GUI paste/upload/ACP: aged draft survives, removed and closed drafts release files, sent PNG reaches model and stays available for replay');
+ fs.writeFileSync(path.join(output,'attachment-requests.json'),JSON.stringify(calls,null,2));
+}
+module.exports={runAttachments};
diff --git a/apps/native/electron/frontend-runtime.cjs b/apps/native/electron/frontend-runtime.cjs
index d5160dbd..faaf89b2 100644
--- a/apps/native/electron/frontend-runtime.cjs
+++ b/apps/native/electron/frontend-runtime.cjs
@@ -63,7 +63,7 @@ app.whenReady().then(async () => {
assert.ok(fs.existsSync(binary), 'Build graff before running test:frontend');
assert.ok(fs.existsSync(path.join(ui, '.next/BUILD_ID')), 'Build the production GUI before running test:frontend');
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.endsWith('_API_KEY')));
- Object.assign(env, { HOME: temp, LMSTUDIO_API_KEY: 'local', GRAFF_CWD: workspace, GRAFF_DESKTOP_TOKEN: '',
+ Object.assign(env, { HOME: temp, TMPDIR: temp, GRAFF_ATTACHMENT_OWNER_PID: String(process.pid), LMSTUDIO_API_KEY: 'local', GRAFF_CWD: workspace, GRAFF_DESKTOP_TOKEN: '',
GRAFF_NO_TELEMETRY: '1', GRAFF_FLEET: 'off', GRAFF_NO_SMOLIFY: '1', GRAFF_NO_CODEDB_GUARD: '1', NEXT_TELEMETRY_DISABLED: '1' });
const mcp = path.join(temp, 'mcp.json'); fs.writeFileSync(mcp, JSON.stringify({mcpServers:htmlTool ? {codegraff_desktop:{command:process.env.GRAFF_TEST_BUN || 'bun',args:[path.join(__dirname,'desktop-mcp.cjs')]}} : {}})); env.GRAFF_MCP_CONFIG = mcp;
const wrapper = path.join(temp, 'graff');
@@ -80,6 +80,7 @@ app.whenReady().then(async () => {
{ http_status: 400, error: 'Scripted final request rejected' },
{ tool: 'bash', arguments: { command: 'cat proof.txt' } },
{ text: 'The earlier result is still present.' },
+ { text: 'The pasted image was received.' },
]));
const requests = path.join(temp, 'requests.json');
const model = child('python3', [path.join(repo, 'scripts/eval/frontend_model.py'), '--script', script, '--requests', requests], env, 'model');
@@ -195,6 +196,7 @@ app.whenReady().then(async () => {
report.passed.push('bounded split churn, resize, cancellation and memory checks');
return;
}
+ await require('./attachment-lifetime-frontend.cjs').runAttachments({win,origin,temp,output,requests,workspace,send,click,until,report});
await require('./browser-focus-frontend.cjs').runBrowserFocus({ win, output, click, until, report });
await require('./tab-drag-visual.cjs').runTabDrag({ win, origin, output });
report.passed.push('trusted pointer and keyboard: tab reorder, horizontal/vertical splits, draft retention, Escape and four-pane limit');
diff --git a/apps/native/electron/server.cjs b/apps/native/electron/server.cjs
index f9a0d569..3d311f65 100644
--- a/apps/native/electron/server.cjs
+++ b/apps/native/electron/server.cjs
@@ -20,7 +20,7 @@ async function startServer(resources, root, token, logDirectory, desktopEnv = {}
const child = spawn(path.join(resources, 'bun'), [path.join(resources, 'ui/server.js')], {
cwd: path.join(resources, 'ui'), detached: !managed, stdio: ['ignore', log, log],
env: { ...process.env, ...desktopEnv, NODE_ENV: 'production', PORT: String(port), HOSTNAME: '127.0.0.1',
- GRAFF_BIN: path.join(resources, 'graff'), GRAFF_CWD: root, GRAFF_DESKTOP_TOKEN: token },
+ GRAFF_BIN: path.join(resources, 'graff'), GRAFF_CWD: root, GRAFF_DESKTOP_TOKEN: token, GRAFF_ATTACHMENT_OWNER_PID: String(process.pid) },
});
fs.closeSync(log);
let spawnError; child.on('error', error => { spawnError = error; });
diff --git a/apps/native/lib/attachment-store.test.ts b/apps/native/lib/attachment-store.test.ts
new file mode 100644
index 00000000..64d396f8
--- /dev/null
+++ b/apps/native/lib/attachment-store.test.ts
@@ -0,0 +1,62 @@
+import { afterEach, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, existsSync, utimesSync, writeFileSync, renameSync, chmodSync, readdirSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { AttachmentStore } from "./attachment-store";
+const fixtures: { store: AttachmentStore; root: string }[] = [];
+function fixture(owner = 12345, alive = (_pid: number) => true) {
+ const root = mkdtempSync(path.join(os.tmpdir(), "graff-attachment-lifetime-"));
+ const store = new AttachmentStore(root, owner, alive);
+ fixtures.push({ store, root }); return { store, root };
+}
+afterEach(() => { for (const {store, root} of fixtures.splice(0)) { store.close(); rmSync(root, { recursive: true, force: true }); } });
+test("aged drafts survive uploads and sweep while their desktop owner is alive", () => {
+ const {store} = fixture();
+ const draft = store.create("draft.png", new Uint8Array([1, 2, 3]));
+ const old = new Date(Date.now() - 48 * 60 * 60 * 1000); utimesSync(draft, old, old);
+ store.create("next.png", new Uint8Array([4]));
+ expect(store.sweep()).toBe(0); expect(existsSync(draft)).toBe(true);
+ expect(store.discard(draft)).toBe(true); expect(existsSync(draft)).toBe(false);
+});
+test("accepted prompt attachments survive producer exit and a new store instance", () => {
+ const {store, root} = fixture(12345, () => false);
+ const sent = store.create("sent.png", new Uint8Array([1]));
+ store.retainPrompt({ prompt: [{ type: "text", text: `Inspect @[${sent}]` }] });
+ store.close();
+ const restarted = new AttachmentStore(root, 67890, () => false);
+ try { expect(restarted.sweep()).toBe(0); expect(restarted.discard(sent)).toBe(false); expect(existsSync(sent)).toBe(true); }
+ finally { restarted.close(); }
+});
+test("recovery is bounded and removes only abandoned recorded pending uploads", () => {
+ const {store, root} = fixture(12345, () => false);
+ const files = Array.from({length: 5}, () => store.create("pending.png", new Uint8Array([1])));
+ writeFileSync(path.join(root, "original.png"), "original");
+ expect(store.sweep(2)).toBe(2); expect(files.filter(existsSync)).toHaveLength(3);
+ expect(store.sweep(2)).toBe(2); expect(files.filter(existsSync)).toHaveLength(1);
+ expect(store.sweep(2)).toBe(1); expect(files.filter(existsSync)).toHaveLength(0);
+ expect(existsSync(path.join(root, "original.png"))).toBe(true);
+});
+test("unknown ownership and replacement files are never recovery deletion authority", () => {
+ const unknown = fixture(0, () => false);
+ const pending = unknown.store.create("pending.png", new Uint8Array([1]));
+ expect(unknown.store.sweep()).toBe(0); expect(existsSync(pending)).toBe(true);
+ const {store, root} = fixture(12345, () => false);
+ const replaced = store.create("pending.png", new Uint8Array([2]));
+ const original = path.join(root, "original.png"); writeFileSync(original, "original"); renameSync(original, replaced);
+ expect(store.discard(replaced)).toBe(false); expect(store.sweep()).toBe(0); expect(existsSync(replaced)).toBe(true);
+ expect(store.discard(path.join(root, "..", "unrelated.png"))).toBe(false);
+});
+
+
+test("a failed ownership-record write removes its newly created upload", () => {
+ if (process.platform === "win32" || process.getuid?.() === 0) return;
+ const {store, root} = fixture();
+ const existing = store.create("existing.png", new Uint8Array([1]));
+ const records = path.join(root, ".ownership");
+ chmodSync(records, 0o500);
+ try {
+ expect(() => store.create("failed.png", new Uint8Array([2]))).toThrow();
+ expect(readdirSync(root).filter(name => name.endsWith("-failed.png"))).toEqual([]);
+ expect(existsSync(existing)).toBe(true);
+ } finally { chmodSync(records, 0o700); }
+});
diff --git a/apps/native/lib/attachment-store.ts b/apps/native/lib/attachment-store.ts
new file mode 100644
index 00000000..1d709352
--- /dev/null
+++ b/apps/native/lib/attachment-store.ts
@@ -0,0 +1,101 @@
+import { randomUUID } from "node:crypto";
+import { mkdirSync, openSync, closeSync, fstatSync, writeFileSync, readFileSync, renameSync, unlinkSync, lstatSync, opendirSync, type Dir } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+type Record = { version: 1; name: string; owner: number; retained: boolean; dev: number; ino: number };
+export const attachmentDirectory = path.join(os.tmpdir(), "graff-native-attachments");
+function ownerAlive(pid: number): boolean {
+ try { process.kill(pid, 0); return true; }
+ catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH"; }
+}
+
+/** Only recorded uploads are removable. Saved-message references are durable;
+ * a live desktop owns pending drafts independently of route-server restarts. */
+export class AttachmentStore {
+ private cursor: Dir | null = null;
+ private readonly records: string;
+ constructor(readonly directory: string, private readonly owner = 0, private readonly alive = ownerAlive) {
+ this.records = path.join(directory, ".ownership");
+ }
+ private recordPath(name: string) { return path.join(this.records, `${name}.json`); }
+ private valid(name: string) { return !!name && path.basename(name) === name && !name.startsWith("."); }
+ private save(record: Record) {
+ const destination = this.recordPath(record.name), temporary = `${destination}.${randomUUID()}`;
+ try {
+ writeFileSync(temporary, JSON.stringify(record), { flag: "wx", mode: 0o600 });
+ renameSync(temporary, destination);
+ } finally { try { unlinkSync(temporary); } catch {} }
+ }
+ private read(name: string): Record | null {
+ if (!this.valid(name)) return null;
+ try {
+ if (!lstatSync(this.recordPath(name)).isFile()) return null;
+ const record = JSON.parse(readFileSync(this.recordPath(name), "utf8")) as Record;
+ const file = lstatSync(path.join(this.directory, name));
+ return record.version === 1 && record.name === name && typeof record.retained === "boolean" && file.isFile() &&
+ file.dev === record.dev && file.ino === record.ino ? record : null;
+ } catch { return null; }
+ }
+ create(label: string, bytes: Uint8Array): string {
+ if (!this.valid(label)) throw new Error("Invalid attachment name");
+ mkdirSync(this.records, { recursive: true, mode: 0o700 });
+ const name = `${randomUUID()}-${label}`, target = path.join(this.directory, name);
+ const descriptor = openSync(target, "wx", 0o600);
+ try {
+ const file = fstatSync(descriptor);
+ try {
+ writeFileSync(descriptor, bytes);
+ this.save({ version: 1, name, owner: this.owner, retained: false, dev: file.dev, ino: file.ino });
+ } catch (error) {
+ try {
+ const current = lstatSync(target);
+ if (current.dev === file.dev && current.ino === file.ino) unlinkSync(target);
+ } catch {}
+ throw error;
+ }
+ } finally { closeSync(descriptor); }
+ return target;
+ }
+ retainPrompt(params: unknown) {
+ const prompt = (params as { prompt?: unknown } | undefined)?.prompt;
+ if (!Array.isArray(prompt)) return;
+ for (const part of prompt) {
+ if (part?.type !== "text" || typeof part.text !== "string") continue;
+ for (const match of part.text.matchAll(/@\[([^\]\n]+)\]/g)) {
+ if (path.dirname(match[1]) !== this.directory) continue;
+ const record = this.read(path.basename(match[1]));
+ if (record && !record.retained) this.save({ ...record, retained: true });
+ }
+ }
+ }
+ discard(target: string): boolean {
+ if (path.dirname(target) !== this.directory) return false;
+ const record = this.read(path.basename(target));
+ if (!record || record.retained) return false;
+ unlinkSync(target);
+ try { unlinkSync(this.recordPath(record.name)); } catch {}
+ return true;
+ }
+ sweep(limit = 64): number {
+ let removed = 0;
+ try {
+ this.cursor ??= opendirSync(this.records);
+ for (let i = 0; i < limit; i++) {
+ const entry = this.cursor.readSync();
+ if (!entry) { this.close(); break; }
+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
+ const record = this.read(entry.name.slice(0, -5));
+ if (!record || record.retained || !Number.isSafeInteger(record.owner) || record.owner <= 1 || this.alive(record.owner)) continue;
+ if (this.discard(path.join(this.directory, record.name))) removed++;
+ }
+ } catch { this.close(); }
+ return removed;
+ }
+ close() { try { this.cursor?.closeSync(); } catch {} this.cursor = null; }
+}
+const state = globalThis as typeof globalThis & { __graffAttachmentStore?: AttachmentStore };
+export function attachmentStore() {
+ const owner = Number(process.env.GRAFF_ATTACHMENT_OWNER_PID || 0);
+ return state.__graffAttachmentStore ??= new AttachmentStore(attachmentDirectory, Number.isSafeInteger(owner) ? owner : 0);
+}
diff --git a/apps/native/lib/attachments.ts b/apps/native/lib/attachments.ts
index 01ff1d76..616fba3d 100644
--- a/apps/native/lib/attachments.ts
+++ b/apps/native/lib/attachments.ts
@@ -95,3 +95,14 @@ export function withAttachmentMarkers(text: string, attachments: readonly Attach
export function releaseAttachments(attachments: readonly Attachment[]): void {
for (const a of attachments) if (a.preview) URL.revokeObjectURL(a.preview);
}
+
+
+/** Dropped drafts release their owned files; sent attachments only release URLs. */
+export function discardAttachments(attachments: readonly Attachment[]): void {
+ releaseAttachments(attachments);
+ if (!attachments.length) return;
+ for (let i = 0; i < attachments.length; i += 32) {
+ void fetch("/api/attach", { method: "DELETE", headers: { "content-type": "application/json" },
+ body: JSON.stringify({ paths: attachments.slice(i, i + 32).map(a => a.path) }), keepalive: true }).catch(() => {});
+ }
+}
diff --git a/apps/native/lib/composer-draft.ts b/apps/native/lib/composer-draft.ts
index 66b78fa9..9f51b5b6 100644
--- a/apps/native/lib/composer-draft.ts
+++ b/apps/native/lib/composer-draft.ts
@@ -1,10 +1,10 @@
-import { releaseAttachments, type Attachment } from "./attachments";
+import { discardAttachments, type Attachment } from "./attachments";
type Update<T> = T | ((current: T) => T);
export type ComposerDraft = { draft: string; attachments: Attachment[]; uploads: number; attachError: string | null };
/** A chat owns its unsent text and uploads even while its pane is hidden. */
-export function createComposerDraft(release = releaseAttachments) {
+export function createComposerDraft(release = discardAttachments) {
let snapshot: ComposerDraft = { draft: "", attachments: [], uploads: 0, attachError: null };
const listeners = new Set<() => void>();
let disposed = false;
diff --git a/docs/adr/0117-clipboard-files-follow-consumer-ownership.md b/docs/adr/0117-clipboard-files-follow-consumer-ownership.md
new file mode 100644
index 00000000..fcaece28
--- /dev/null
+++ b/docs/adr/0117-clipboard-files-follow-consumer-ownership.md
@@ -0,0 +1,33 @@
+# 0117. Clipboard files follow consumer ownership
+
+Status: accepted 2026-09-15
+
+## Context
+
+Clipboard exports are application-owned files, while copied file paths may name
+user originals. Discarding a composer chip does not imply that prompt history,
+a queued turn, a pending worker, or saved replay has stopped using its pixels.
+An age-only attachment sweep can remove a live draft when another file uploads.
+
+## Decision
+
+The TUI transfers clipboard ownership explicitly across its callback boundary.
+Only owned files without live consumers are released. Pending workers protect
+staging inputs, and sent path markers preserve files for saved replay. Preview
+conversion uses an exclusively claimed output and removes it on every outcome.
+
+The native desktop records upload ownership and file identity. Discarding an
+unsent draft releases its recorded upload; accepting a prompt retains referenced
+uploads before dispatching to ACP. Sent files remain available for replay.
+Recovery examines a bounded number of ownership records per upload and removes
+pending files only when their known desktop owner has exited. The desktop owns
+drafts independently of route-server restarts. Unknown owners and unrecorded or
+replaced files do not grant deletion authority. Age alone never grants it.
+
+## Consequences
+
+Conservative retention can keep files when their last consumer cannot be proved
+gone. Removing saved replay artifacts and recovering older unrecorded exports
+require separate evidence of ownership and references, rather than age guesses.
+Tests cover real conversion, transfer/removal, history and queue references,
+file replacement, recovery limits, and GUI upload through actual ACP staging.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 429735ae..89b51d46 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -126,6 +126,7 @@ record only when you need the evidence or the edge cases.
| [0113](0113-clipboard-errors-need-evidence.md) | Direct AppKit clipboard failures need typed evidence; generic helper failures never imply Automation permission. |
| [0114](0114-live-citations-are-terminal-presentation.md) | Live terminal citations use per-stream display filters with independent reasoning state; structured JSON/ACP output stays unchanged. |
| [0116](0116-informational-turns-have-bounded-scope.md) | Summary turns gather bounded evidence; coding completion requirements apply to requested changes. |
+| [0117](0117-clipboard-files-follow-consumer-ownership.md) | Clipboard cleanup requires file ownership and released consumers; age alone never deletes active or saved attachments. |
## When to write one
diff --git a/src/main.zig b/src/main.zig
index 3d1ac9ca..75bc8f0c 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -563,7 +563,7 @@ const workflow = @import("workflow_test.zig"); // the engine's tests live here (
const exec = @import("exec.zig");
test { // ── Unit tests (`zig build test`): pull in tests from imported modules (mcp.zig)
_ = .{ @import("mcp_apps.zig"), @import("html_view.zig"), @import("providers_confirmation_tests.zig"), @import("repl_model_confirmation_tests.zig"), @import("repl_model_pick_tests.zig"), @import("engine_sink_citation_tests.zig"), @import("cite_markup_stream_tests.zig"), @import("oneshot_citation_tests.zig"), @import("tui_acp.zig") };
- _ = .{ @import("main_test.zig"), @import("artifact_claim_command.zig"), @import("cli_path_hint.zig") };
+ _ = .{ @import("main_test.zig"), @import("artifact_claim_command.zig"), @import("cli_path_hint.zig"), @import("tui_paste_transfer.zig") };
_ = @import("session_catalog.zig");
_ = @import("session_prompt.zig");
_ = @import("prompt_astra.zig");
diff --git a/src/tui_launch.zig b/src/tui_launch.zig
index 595a93e7..c8ea680e 100644
--- a/src/tui_launch.zig
+++ b/src/tui_launch.zig
@@ -322,7 +322,8 @@ fn cancelCb(ctx: ?*anyopaque) void {
repl_glue.replCancelCb(ctx);
}
-fn pasteCb(ctx: ?*anyopaque, dest: []u8) isize {
+fn pasteCb(ctx: ?*anyopaque, dest: []u8, owned: *bool) isize {
+ owned.* = false;
const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return pasteErr(dest, "no session")));
if (!vision.visionCapable(c.provider)) return pasteErr(dest, vision.no_vision_message);
if (builtin.os.tag != .macos) return pasteErr(dest, "clipboard image paste is macOS-only — use /image <path>");
@@ -332,12 +333,10 @@ fn pasteCb(ctx: ?*anyopaque, dest: []u8) isize {
.empty => return 0,
.failed => |kind| return pasteErr(dest, vision.pasteFailMessage(kind)),
};
- const n = @min(grab.path.len, dest.len);
- @memcpy(dest[0..n], grab.path[0..n]);
- if (grab.owned) {
- gpa.free(grab.path);
- } else grab.release(c.io, gpa);
- return @intCast(n);
+ const result = @import("tui_paste_transfer.zig").transfer(grab, c.io, gpa, dest) orelse
+ return pasteErr(dest, "clipboard image path is too long");
+ owned.* = result.owned;
+ return @intCast(result.len);
}
fn pasteErr(dest: []u8, msg: []const u8) isize {
diff --git a/src/tui_paste_transfer.zig b/src/tui_paste_transfer.zig
new file mode 100644
index 00000000..2fd61477
--- /dev/null
+++ b/src/tui_paste_transfer.zig
@@ -0,0 +1,51 @@
+//! Transfer clipboard file ownership across the TUI's bounded callback buffer.
+const std = @import("std");
+const clip = @import("vision_clipboard.zig");
+const Transfer = struct { len: usize, owned: bool };
+
+pub fn transfer(grab: clip.Grab, io: std.Io, gpa: std.mem.Allocator, dest: []u8) ?Transfer {
+ if (grab.path.len > dest.len) {
+ grab.release(io, gpa);
+ return null;
+ }
+ @memcpy(dest[0..grab.path.len], grab.path);
+ defer gpa.free(grab.path);
+ return .{ .len = grab.path.len, .owned = grab.owned };
+}
+
+test "TUI clipboard transfer preserves ownership and leaves the exported pixels readable" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ for ([_]bool{ true, false }) |owned| {
+ try tmp.dir.writeFile(io, .{ .sub_path = "pixels.png", .data = "pixels" });
+ const original = try tmp.dir.realPathFileAlloc(io, "pixels.png", gpa);
+ defer gpa.free(original);
+ var dest: [4096]u8 = undefined;
+ const result = transfer(.{ .path = try gpa.dupe(u8, original), .owned = owned, .flavor = .png }, io, gpa, &dest).?;
+ try std.testing.expectEqual(owned, result.owned);
+ const pixels = try std.Io.Dir.cwd().openFile(io, dest[0..result.len], .{});
+ pixels.close(io);
+ }
+}
+
+test "a TUI clipboard path that does not fit releases an owned export but preserves an original" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ for ([_]bool{ true, false }) |owned| {
+ try tmp.dir.writeFile(io, .{ .sub_path = "pixels.png", .data = "pixels" });
+ const original = try tmp.dir.realPathFileAlloc(io, "pixels.png", gpa);
+ defer gpa.free(original);
+ var dest: [1]u8 = undefined;
+ try std.testing.expect(transfer(.{ .path = try gpa.dupe(u8, original), .owned = owned, .flavor = .png }, io, gpa, &dest) == null);
+ if (owned) {
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "pixels.png", .{}));
+ } else {
+ const pixels = try tmp.dir.openFile(io, "pixels.png", .{});
+ pixels.close(io);
+ }
+ }
+}