Skip to content

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

Python

fix(tui): restore images on prompt recall and highlight only backed chips

Cursor Agent863335f8c812
diff --git a/TUI/app.zig b/TUI/app.zig
index 09be41ba..946c53aa 100644
--- a/TUI/app.zig
+++ b/TUI/app.zig
@@ -76,6 +76,10 @@ pub const Model = struct {
input: input_mod.Input,
history: std.array_list.Managed(Entry),
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_images: ?[]const []const u8 = null,
steer_queue: std.array_list.Managed([]const u8),
images: std.array_list.Managed([]const u8),
pending: ?*engine.Job = null,
@@ -205,6 +209,7 @@ pub const Model = struct {
.input = input_mod.Input.init(alloc),
.history = std.array_list.Managed(Entry).init(alloc),
.prompt_hist = std.array_list.Managed([]const u8).init(alloc),
+ .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),
.chat = engine.g_turn_fn != null,
@@ -229,6 +234,7 @@ pub const Model = struct {
self.history.deinit();
for (self.prompt_hist.items) |s| self.alloc.free(s);
self.prompt_hist.deinit();
+ @import("prompt_history.zig").deinit(self);
for (self.steer_queue.items) |s| self.alloc.free(s);
self.steer_queue.deinit();
for (self.images.items) |s| self.alloc.free(s);
diff --git a/TUI/chrome.zig b/TUI/chrome.zig
index 128f526c..0b378941 100644
--- a/TUI/chrome.zig
+++ b/TUI/chrome.zig
@@ -46,7 +46,7 @@ pub fn promptBox(self: *const Model, a: std.mem.Allocator, width: usize) ![]cons
var body = std.array_list.Managed(u8).init(a);
try body.appendSlice(glyphs.caret ++ " ");
if (self.images.items.len > 0) {
- try body.appendSlice(try imageChips(self, a));
+ try body.appendSlice(try imageChips(self, a, th.accent, th.text));
try body.appendSlice(" ");
}
try body.appendSlice(try self.input.view(a));
@@ -78,12 +78,19 @@ pub fn promptBox(self: *const Model, a: std.mem.Allocator, width: usize) ![]cons
return out.items;
}
-fn imageChips(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+fn imageChips(self: *const Model, a: std.mem.Allocator, accent: []const u8, text: []const u8) ![]const u8 {
var chips = std.array_list.Managed(u8).init(a);
- for (self.images.items, 0..) |_, i| {
+ for (self.images.items, 0..) |path, i| {
if (i > 0) try chips.append(' ');
var buf: [24]u8 = undefined;
- try chips.appendSlice(try std.fmt.bufPrint(&buf, "[Image #{d}]", .{i + 1}));
+ const label = try std.fmt.bufPrint(&buf, "[Image #{d}]", .{i + 1});
+ if (@import("image.zig").pathBacked(path)) {
+ try chips.appendSlice(accent);
+ try chips.appendSlice(label);
+ try chips.appendSlice(text);
+ } else {
+ try chips.appendSlice(label);
+ }
}
return chips.items;
}
diff --git a/TUI/dispatch.zig b/TUI/dispatch.zig
index 357a9c81..43754dd9 100644
--- a/TUI/dispatch.zig
+++ b/TUI/dispatch.zig
@@ -20,7 +20,7 @@ pub const busy_note = "an engine call is still running — press Esc to cancel i
pub fn applyLine(self: *Model, raw: []const u8) Effect {
const line = std.mem.trim(u8, raw, " \t\r\n");
if (line.len == 0 and self.images.items.len == 0) return .stay;
- if (line.len > 0) rememberPrompt(self, line);
+ if (line.len > 0 or self.images.items.len > 0) rememberPrompt(self, line);
if (line.len > 0 and line[0] == '/') return runCommand(self, line);
if (line.len > 1 and line[0] == '!') return bang(self, std.mem.trim(u8, line[1..], " \t"));
if (self.bg != null) {
@@ -44,10 +44,7 @@ pub fn applyLine(self: *Model, raw: []const u8) Effect {
}
fn rememberPrompt(self: *Model, line: []const u8) void {
- if (self.alloc.dupe(u8, line)) |dup| {
- self.prompt_hist.append(dup) catch self.alloc.free(dup);
- } else |_| {}
- self.hist_idx = null;
+ @import("prompt_history.zig").remember(self, line);
}
pub fn runCommand(self: *Model, line: []const u8) Effect {
@@ -308,21 +305,11 @@ pub fn compact(self: *Model) void {
}
pub fn recallPrev(self: *Model) void {
- if (self.prompt_hist.items.len == 0) return;
- const next_i: usize = if (self.hist_idx) |i| (if (i == 0) 0 else i - 1) else self.prompt_hist.items.len - 1;
- self.hist_idx = next_i;
- self.input.setValue(self.prompt_hist.items[next_i]) catch {};
+ @import("prompt_history.zig").recallPrev(self);
}
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;
- self.input.setValue("") catch {};
- return;
- }
- self.hist_idx = i + 1;
- self.input.setValue(self.prompt_hist.items[i + 1]) catch {};
+ @import("prompt_history.zig").recallNext(self);
}
pub fn pasteClipboard(self: *Model) void {
diff --git a/TUI/image.zig b/TUI/image.zig
index e1af011a..3c474b84 100644
--- a/TUI/image.zig
+++ b/TUI/image.zig
@@ -6,6 +6,16 @@ const theme_mod = @import("theme.zig");
const key_mod = @import("key.zig");
const Model = app.Model;
+/// A path still has bytes behind it. Used to decide whether a chip is a real
+/// attachment (#577) or just the letters `[Image]`.
+pub fn pathBacked(path: []const u8) bool {
+ if (path.len == 0) return false;
+ const io = ioHandle();
+ const file = std.Io.Dir.cwd().openFile(io, path, .{}) catch return false;
+ file.close(io);
+ return true;
+}
+
pub fn render(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {
const th = self.theme();
const path = self.preview_path;
@@ -489,6 +499,17 @@ test "click on a user image chip opens the preview overlay" {
try std.testing.expect(m.preview_pin);
}
+test "pathBacked is true only when the file is there (#577)" {
+ try std.testing.expect(!pathBacked(""));
+ try std.testing.expect(!pathBacked("/no/such/image-577.png"));
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(.{ .sub_path = "y.png", .data = "y" });
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const live = try tmp.dir.realpath("y.png", &buf);
+ try std.testing.expect(pathBacked(live));
+}
+
test "hover on a composer chip opens an unpinned preview" {
var m: Model = undefined;
m.setup(std.testing.allocator);
diff --git a/TUI/keys_tests.zig b/TUI/keys_tests.zig
index b85a308b..98a6573a 100644
--- a/TUI/keys_tests.zig
+++ b/TUI/keys_tests.zig
@@ -314,3 +314,22 @@ test "Ctrl+R walks prompt history" {
_ = handle(&m, .up);
try std.testing.expectEqualStrings("older", m.input.getValue());
}
+
+test "Ctrl+R after an image prompt restores the attachment (#577)" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(.{ .sub_path = "shot.png", .data = "png" });
+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const live = try tmp.dir.realpath("shot.png", &path_buf);
+
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.attachImage(live);
+ _ = @import("dispatch.zig").applyLine(&m, "what is this");
+ try std.testing.expectEqual(@as(usize, 0), m.images.items.len);
+ _ = handle(&m, .{ .ctrl = 'r' });
+ try std.testing.expectEqualStrings("what is this", m.input.getValue());
+ try std.testing.expectEqual(@as(usize, 1), m.images.items.len);
+ try std.testing.expectEqualStrings(live, m.images.items[0]);
+}
diff --git a/TUI/markdown.zig b/TUI/markdown.zig
index 6fb0210d..d9c32c7c 100644
--- a/TUI/markdown.zig
+++ b/TUI/markdown.zig
@@ -5,6 +5,7 @@ const diff = @import("diff.zig");
const theme_mod = @import("theme.zig");
const mdtable = @import("mdtable.zig");
const syntax = @import("syntax.zig");
+const image = @import("image.zig");
/// Headers, fences, bullets, `code`, **bold**, and `/slash` tokens.
pub fn render(a: std.mem.Allocator, src: []const u8, accent: []const u8) ![]const u8 {
@@ -250,9 +251,16 @@ pub fn renderUser(a: std.mem.Allocator, src: []const u8, accent: []const u8, tex
img_n += 1;
var chip: [24]u8 = undefined;
const label = std.fmt.bufPrint(&chip, "[Image #{d}]", .{img_n}) catch "[Image]";
- try out.appendSlice(accent);
- try out.appendSlice(label);
- try out.appendSlice(text);
+ const path = clean[i + 2 .. close];
+ // Accent only when the file is still there (#577). A stale or
+ // typed `@[path]` is ordinary text, not an attachment chip.
+ if (image.pathBacked(path)) {
+ try out.appendSlice(accent);
+ try out.appendSlice(label);
+ try out.appendSlice(text);
+ } else {
+ try out.appendSlice(label);
+ }
i = close + 1;
if (i < clean.len and clean[i] == ' ') i += 1;
continue;
diff --git a/TUI/markdown_tests.zig b/TUI/markdown_tests.zig
index 58c475a9..3ae7fafb 100644
--- a/TUI/markdown_tests.zig
+++ b/TUI/markdown_tests.zig
@@ -109,11 +109,26 @@ test "no code background leaks past a closed fence or off the last fence row" {
}
test "renderUser chips @[path] and paints slash commands" {
- const text = try renderUser(std.testing.allocator, "@[/tmp/a.png] /goal look at this", theme_mod.emerald, theme_mod.zinc200);
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(.{ .sub_path = "a.png", .data = "png" });
+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const live = try tmp.dir.realpath("a.png", &path_buf);
+ const src = try std.fmt.allocPrint(std.testing.allocator, "@[{s}] /goal look at this", .{live});
+ defer std.testing.allocator.free(src);
+ const text = try renderUser(std.testing.allocator, src, theme_mod.emerald, theme_mod.zinc200);
defer std.testing.allocator.free(text);
try std.testing.expect(std.mem.indexOf(u8, text, "[Image #1]") != null);
- try std.testing.expect(std.mem.indexOf(u8, text, "/tmp/a.png") == null);
+ try std.testing.expect(std.mem.indexOf(u8, text, live) == null);
try std.testing.expect(std.mem.indexOf(u8, text, "/goal") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, theme_mod.emerald ++ "[Image #1]") != null);
+}
+
+test "renderUser leaves an unbacked @[path] uncolored (#577)" {
+ const text = try renderUser(std.testing.allocator, "@[/no/such/image-577.png] look", theme_mod.emerald, theme_mod.zinc200);
+ defer std.testing.allocator.free(text);
+ try std.testing.expect(std.mem.indexOf(u8, text, "[Image #1]") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, theme_mod.emerald ++ "[Image #1]") == null);
}
test "render paints a Grok-style box table and hides raw pipes" {
diff --git a/TUI/prompt_history.zig b/TUI/prompt_history.zig
new file mode 100644
index 00000000..17315aae
--- /dev/null
+++ b/TUI/prompt_history.zig
@@ -0,0 +1,174 @@
+//! TUI prompt-history sidecar (#577). Recalling a line restores the image
+//! paths that were attached when it was submitted; only a path that still
+//! exists is put back on the composer. Split out of dispatch.zig (600-line
+//! cap). Modeled on src/readline_history.zig.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const image = @import("image.zig");
+const Model = app.Model;
+
+pub fn deinit(self: *Model) void {
+ for (self.prompt_hist_images.items) |paths| freePaths(self, paths);
+ self.prompt_hist_images.deinit();
+ clearDraft(self);
+}
+
+pub fn remember(self: *Model, line: []const u8) void {
+ const dup = self.alloc.dupe(u8, line) catch return;
+ self.prompt_hist.append(dup) catch {
+ self.alloc.free(dup);
+ return;
+ };
+ recordImages(self);
+ self.hist_idx = null;
+ clearDraft(self);
+}
+
+pub fn recallPrev(self: *Model) void {
+ if (self.prompt_hist.items.len == 0) return;
+ if (self.hist_idx == null) snapshotDraft(self);
+ const next_i: usize = if (self.hist_idx) |i| (if (i == 0) 0 else i - 1) else self.prompt_hist.items.len - 1;
+ self.hist_idx = next_i;
+ apply(self, self.prompt_hist.items[next_i], imagesAt(self, next_i));
+}
+
+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 &.{});
+ return;
+ }
+ self.hist_idx = i + 1;
+ apply(self, self.prompt_hist.items[i + 1], imagesAt(self, i + 1));
+}
+
+fn recordImages(self: *Model) void {
+ while (self.prompt_hist_images.items.len + 1 < self.prompt_hist.items.len) {
+ self.prompt_hist_images.append(&.{}) catch return;
+ }
+ var paths = std.array_list.Managed([]const u8).init(self.alloc);
+ for (self.images.items) |p| {
+ const owned = self.alloc.dupe(u8, p) catch continue;
+ paths.append(owned) catch self.alloc.free(owned);
+ }
+ const slice = paths.toOwnedSlice() catch {
+ for (paths.items) |p| self.alloc.free(p);
+ paths.deinit();
+ self.prompt_hist_images.append(&.{}) catch {};
+ return;
+ };
+ self.prompt_hist_images.append(slice) catch {
+ freePaths(self, slice);
+ };
+}
+
+fn snapshotDraft(self: *Model) void {
+ clearDraft(self);
+ self.draft_text = self.alloc.dupe(u8, self.input.getValue()) 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| {
+ const owned = self.alloc.dupe(u8, p) catch continue;
+ paths.append(owned) catch self.alloc.free(owned);
+ }
+ self.draft_images = paths.toOwnedSlice() catch {
+ for (paths.items) |p| self.alloc.free(p);
+ paths.deinit();
+ return;
+ };
+}
+
+fn clearDraft(self: *Model) void {
+ if (self.draft_text) |t| {
+ self.alloc.free(t);
+ self.draft_text = null;
+ }
+ if (self.draft_images) |paths| {
+ freePaths(self, paths);
+ self.draft_images = null;
+ }
+}
+
+fn apply(self: *Model, text: []const u8, paths: []const []const u8) void {
+ self.input.setValue(text) catch {};
+ replaceImages(self, paths);
+}
+
+fn replaceImages(self: *Model, paths: []const []const u8) void {
+ for (self.images.items) |p| self.alloc.free(p);
+ self.images.clearRetainingCapacity();
+ for (paths) |p| {
+ if (!image.pathBacked(p)) continue;
+ const owned = self.alloc.dupe(u8, p) catch continue;
+ self.images.append(owned) catch self.alloc.free(owned);
+ }
+}
+
+fn imagesAt(self: *const Model, idx: usize) []const []const u8 {
+ if (idx < self.prompt_hist_images.items.len) return self.prompt_hist_images.items[idx];
+ return &.{};
+}
+
+fn freePaths(self: *Model, paths: []const []const u8) void {
+ for (paths) |p| self.alloc.free(p);
+ if (paths.len > 0) self.alloc.free(paths);
+}
+
+test "remember + recall restores backed image paths and drops missing ones" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(.{ .sub_path = "shot.png", .data = "png" });
+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const live = try tmp.dir.realpath("shot.png", &path_buf);
+
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.attachImage(live);
+ m.attachImage("/no/such/image-577.png");
+ remember(&m, "what is this");
+ try std.testing.expectEqual(@as(usize, 1), m.prompt_hist.items.len);
+ try std.testing.expectEqual(@as(usize, 2), m.images.items.len);
+
+ for (m.images.items) |p| m.alloc.free(p);
+ m.images.clearRetainingCapacity();
+ try std.testing.expectEqual(@as(usize, 0), m.images.items.len);
+
+ recallPrev(&m);
+ try std.testing.expectEqualStrings("what is this", m.input.getValue());
+ try std.testing.expectEqual(@as(usize, 1), m.images.items.len);
+ try std.testing.expectEqualStrings(live, m.images.items[0]);
+}
+
+test "down past newest restores the draft and its attachments" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(.{ .sub_path = "a.png", .data = "a" });
+ try tmp.dir.writeFile(.{ .sub_path = "b.png", .data = "b" });
+ var a_buf: [std.fs.max_path_bytes]u8 = undefined;
+ var b_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const older = try tmp.dir.realpath("a.png", &a_buf);
+ const draft_path = try tmp.dir.realpath("b.png", &b_buf);
+
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.attachImage(older);
+ remember(&m, "older");
+ for (m.images.items) |p| m.alloc.free(p);
+ m.images.clearRetainingCapacity();
+
+ m.attachImage(draft_path);
+ m.input.setValue("draft in progress") catch {};
+ recallPrev(&m);
+ try std.testing.expectEqualStrings("older", m.input.getValue());
+ try std.testing.expectEqualStrings(older, m.images.items[0]);
+
+ recallNext(&m);
+ try std.testing.expectEqualStrings("draft in progress", m.input.getValue());
+ try std.testing.expectEqual(@as(usize, 1), m.images.items.len);
+ try std.testing.expectEqualStrings(draft_path, m.images.items[0]);
+}
diff --git a/TUI/root.zig b/TUI/root.zig
index ea72b8f8..2aa69658 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -53,6 +53,7 @@ test {
_ = catalog;
_ = app;
_ = @import("dispatch.zig");
+ _ = @import("prompt_history.zig");
_ = @import("meters.zig");
_ = @import("key.zig");
_ = @import("key_orphan.zig");
diff --git a/src/repl_convo.zig b/src/repl_convo.zig
index f2bffc62..25e20e4c 100644
--- a/src/repl_convo.zig
+++ b/src/repl_convo.zig
@@ -127,7 +127,20 @@ fn isUserPrompt(v: Value) bool {
const role = v.object.get("role") orelse return false;
if (role != .string or !std.mem.eql(u8, role.string, "user")) return false;
const content = v.object.get("content") orelse return false;
- return content == .string;
+ if (content == .string) return true;
+ // Image user messages are an array of text + image blocks (#577), not a
+ // tool_result wrapper (those also ride the user role).
+ if (content != .array) return false;
+ for (content.array.items) |b| {
+ if (b != .object) continue;
+ const ty = b.object.get("type") orelse continue;
+ if (ty != .string) continue;
+ if (std.mem.eql(u8, ty.string, "tool_result")) return false;
+ if (std.mem.eql(u8, ty.string, "image") or
+ std.mem.eql(u8, ty.string, "image_url") or
+ std.mem.eql(u8, ty.string, "input_image")) return true;
+ }
+ return false;
}
const testing = std.testing;
@@ -200,3 +213,18 @@ test "a tool result is not mistaken for the human prompt on rewind" {
// Back to before "run it" — not to just before the tool result.
try testing.expectEqual(@as(usize, 0), convo.len());
}
+
+test "rewind treats an image user message as the human prompt (#577)" {
+ var convo = Conversation.init(testing.allocator);
+ defer convo.deinit();
+ const a = convo.alloc();
+ const img = try @import("vision.zig").imageMessage(a, .anthropic, "look", .{
+ .media_type = "image/png",
+ .b64 = "AAA=",
+ .label = "/tmp/a.png",
+ });
+ try convo.list().append(img);
+ try testing.expectEqual(@as(usize, 1), convo.len());
+ convo.rewind();
+ try testing.expectEqual(@as(usize, 0), convo.len());
+}
diff --git a/src/repl_turn.zig b/src/repl_turn.zig
index 6b36933c..624e9e98 100644
--- a/src/repl_turn.zig
+++ b/src/repl_turn.zig
@@ -24,6 +24,8 @@ const providers = @import("providers.zig");
const repl = @import("repl.zig");
const repl_glue = @import("repl_glue.zig");
const ReplCtx = repl_glue.ReplCtx;
+const vision = @import("vision.zig");
+const vision_queue = @import("vision_queue.zig");
/// What a turn's permission mode means to the engine. One place, so the gate
/// and the badge can never drift again.
@@ -119,20 +121,35 @@ pub fn turnAgent(
fn borrowHistory(c: *ReplCtx, agent: *Agent, history: []const repl.Turn, arena: Allocator, scratch: *std.heap.ArenaAllocator) !void {
const cv = c.convo orelse {
for (history) |t| {
- const role = switch (t.role) {
- .user => "user",
- .assistant => "assistant",
- };
- try agent.messages.append(try textMessage(arena, role, t.text));
+ try agent.messages.append(try userOrText(agent, arena, t));
}
return;
};
try cv.adopt(history);
+ try promoteTailImages(agent, cv, history);
agent.messages = cv.list().*;
// Transient parse garbage goes here instead of the session arena (#124).
agent.scratch_arena = scratch;
}
+/// A recalled TUI prompt carries `@[path]` markers. Stage the files so the
+/// model gets pixels, not the literal marker (#577).
+fn userOrText(agent: *Agent, arena: Allocator, t: repl.Turn) !std.json.Value {
+ if (t.role != .user) return textMessage(arena, "assistant", t.text);
+ vision.stageGuiImageAttachment(agent, t.text);
+ return vision_queue.consumePromptImages(arena, agent, t.text);
+}
+
+fn promoteTailImages(agent: *Agent, cv: anytype, history: []const repl.Turn) !void {
+ if (history.len == 0 or history[history.len - 1].role != .user) return;
+ const text = history[history.len - 1].text;
+ vision.stageGuiImageAttachment(agent, text);
+ if (agent.pending_image_len == 0) return;
+ const msgs = cv.list();
+ if (msgs.items.len == 0) return;
+ msgs.items[msgs.items.len - 1] = try vision_queue.consumePromptImages(cv.alloc(), agent, text);
+}
+
/// Hand the conversation back. runTurn appended this turn's assistant message
/// and every tool_use/tool_result pair to the borrowed list, and a managed
/// ArrayList is a VALUE — not copying it back would drop the whole turn.