Skip to content

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

Python

feat(cli): /images opens image URLs from the last response in the browser (#103)

Rach Pradhan32e058b228ae
diff --git a/scripts/test-pty-images.py b/scripts/test-pty-images.py
new file mode 100755
index 00000000..599fb2e6
--- /dev/null
+++ b/scripts/test-pty-images.py
@@ -0,0 +1,152 @@
+#!/usr/bin/env python3
+"""Real-PTY test for the /images command (#103).
+
+Points graff at a local OpenAI-compatible mock (the built-in `lmstudio` provider,
+127.0.0.1:1234) whose reply embeds two GitHub-attachment image URLs, drives a real
+turn, then runs `/images`. GRAFF_NO_BROWSER=1 suppresses the actual browser spawn
+so the test asserts the extracted URLs without opening real tabs. Also checks the
+zero-image path (no images before any turn) and that /images is discoverable.
+
+Requires 127.0.0.1:1234 to be free (the lmstudio URL is fixed); skips otherwise.
+"""
+
+import http.server
+import json
+import os
+import socket
+import sys
+import tempfile
+import threading
+
+from pty_harness import PtySession
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+
+IMG1 = "https://github.com/user-attachments/assets/one.png"
+IMG2 = "https://github.com/user-attachments/assets/two.png"
+
+
+class ChatMock:
+ """Serves one fixed OpenAI chat-completion for every /v1/chat/completions."""
+
+ def __init__(self, content: str) -> None:
+ self.body = json.dumps(
+ {
+ "id": "cmpl-1",
+ "object": "chat.completion",
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": content},
+ "finish_reason": "stop",
+ }
+ ],
+ "usage": {"prompt_tokens": 5, "completion_tokens": 10, "total_tokens": 15},
+ }
+ ).encode()
+ parent = self
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ def do_POST(self) -> None: # noqa: N802
+ length = int(self.headers.get("content-length", 0))
+ if length:
+ self.rfile.read(length)
+ self.send_response(200)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(parent.body)))
+ self.end_headers()
+ self.wfile.write(parent.body)
+
+ def do_GET(self) -> None: # noqa: N802
+ self.send_response(404)
+ self.end_headers()
+
+ def log_message(self, *_a) -> None:
+ pass
+
+ self.httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 1234), Handler)
+
+ def start(self) -> None:
+ threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
+
+ def stop(self) -> None:
+ self.httpd.shutdown()
+ self.httpd.server_close()
+
+
+def port_free() -> bool:
+ probe = socket.socket()
+ try:
+ probe.bind(("127.0.0.1", 1234))
+ return True
+ except OSError:
+ return False
+ finally:
+ probe.close()
+
+
+def main() -> None:
+ if not port_free():
+ print("skip 127.0.0.1:1234 already in use")
+ return
+
+ content = f"Here are the attachments: ![one]({IMG1}) and ![two]({IMG2})."
+ mock = ChatMock(content)
+ mock.start()
+ try:
+ with tempfile.TemporaryDirectory(prefix="graff-pty-images-") as tmp:
+ env = {
+ "HOME": tmp,
+ "LMSTUDIO_API_KEY": "local-pty-test",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ "GRAFF_NO_BROWSER": "1",
+ }
+ ambient = tuple(
+ k
+ for k in os.environ
+ if (k.startswith("GRAFF_") or k.startswith("CODEX_") or k == "NO_COLOR")
+ and k not in env
+ )
+ with PtySession(
+ GRAFF,
+ ["--model", "lmstudio", "--no-telemetry"],
+ cwd=tmp,
+ env=env,
+ unset_env=ambient,
+ timeout=20.0,
+ ) as session:
+ session.wait_for_literal("] ›")
+
+ # Zero-image path: nothing in the conversation yet.
+ c0 = len(session.raw)
+ session.send_line("/images")
+ session.wait_for_literal("no image URLs", start=c0)
+
+ # Drive a turn — the mock reply embeds the two image URLs.
+ c1 = len(session.raw)
+ session.send_line("show me the images")
+ session.wait_for_literal("attachments", start=c1)
+
+ # /images extracts both; GRAFF_NO_BROWSER=1 lists them (no spawn).
+ c2 = len(session.raw)
+ session.send_line("/images")
+ session.wait_for_literal("found 2 images", start=c2)
+ session.wait_for_literal(IMG1, start=c2)
+ session.wait_for_literal(IMG2, start=c2)
+
+ session.send_key("ctrl-d")
+ result = session.read_until_exit(5.0)
+ if result.timed_out or result.exit_code != 0:
+ raise SystemExit(
+ f"REPL did not exit cleanly: exit={result.exit_code} "
+ f"timed_out={result.timed_out}"
+ )
+ print("ok PTY /images extracts + lists issue image URLs (#103)")
+ finally:
+ mock.stop()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index ef3e8b51..6ddd6b6b 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -49,6 +49,7 @@ pub const commands = [_]Item{
.{ .name = "/compact", .desc = "summarize history into a fresh context" },
.{ .name = "/rewind", .usage = "/rewind [n]", .desc = "list past prompts; /rewind <n> drops prompt n+after & reverts its file edits" },
.{ .name = "/image", .usage = "/image <path>", .desc = "attach an image to your next message (vision models only)" },
+ .{ .name = "/images", .desc = "open image URLs from the last response (e.g. issue attachments) in your browser" },
.{ .name = "/paste", .desc = "attach the clipboard image — macOS; also Ctrl-V (⌘V can't be captured)" },
.{ .name = "/bash", .usage = "/bash <command>", .desc = "run a shell command directly" },
.{ .name = "/save", .usage = "/save [name]", .desc = "write the conversation to <name>.session.json (default: current)" },
diff --git a/src/commands_model.zig b/src/commands_model.zig
index 72323b7d..4ea7b4d5 100644
--- a/src/commands_model.zig
+++ b/src/commands_model.zig
@@ -44,6 +44,7 @@ const fallback_config = @import("fallback_config.zig");
const serde = @import("serde.zig");
const oauth = @import("oauth.zig");
+const images = @import("images.zig");
const reasoning_levels = [_]PickItem{
.{ .name = "Low", .desc = "Fast responses with lighter reasoning" },
@@ -59,6 +60,33 @@ const stageImagePath = vision.stageImagePath;
const visionCapable = vision.visionCapable;
const grabClipboardImage = vision.grabClipboardImage;
+/// Serialized JSON of the most recent turn (from the user's last typed prompt to
+/// the end) — what /images scans for image URLs. Provider-agnostic: URLs in
+/// assistant text and tool outputs survive JSON serialization intact.
+fn recentTurnText(root: *Agent, arena: Allocator) []const u8 {
+ const msgs = root.messages.items;
+ var start: usize = 0;
+ var k = msgs.len;
+ while (k > 0) : (k -= 1) {
+ // Stop at the genuinely most-recent user turn — plain text OR an image
+ // attachment (array content) — but not an anthropic tool_result-only user
+ // message; cleanUserTurn is exactly that discriminator.
+ if (Agent.cleanUserTurn(msgs[k - 1])) {
+ start = k - 1;
+ break;
+ }
+ }
+ var aw: Io.Writer.Allocating = .init(arena);
+ for (msgs[start..]) |m| {
+ // A fresh Stringify per message: one instance can only serialize a single
+ // top-level value. Newline-delimited is fine — we only scan for URLs.
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ s.write(m) catch {};
+ aw.writer.writeByte('\n') catch {};
+ }
+ return aw.writer.buffered();
+}
+
fn providerKnown(id: []const u8) bool {
for (provider_specs) |spec| if (std.mem.eql(u8, spec.id, id)) return true;
return false;
@@ -514,6 +542,40 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
try out.flush();
return true;
}
+ if (std.mem.eql(u8, line, "/images")) {
+ // Transient: serialize + scan the last turn in a scratch arena freed on
+ // return, so /images never accumulates in the long-lived session arena (#124).
+ var scratch = std.heap.ArenaAllocator.init(root.gpa);
+ defer scratch.deinit();
+ const sa = scratch.allocator();
+ const urls = images.extractImageUrls(sa, recentTurnText(root, sa)) catch &[_][]const u8{};
+ if (urls.len == 0) {
+ try out.writeAll("no image URLs in the last response — /images opens images from the most recent turn's output (e.g. a `gh issue view` with attachments)\n");
+ try out.flush();
+ return true;
+ }
+ // GRAFF_NO_BROWSER (headless/SSH) suppresses the spawn; the command then
+ // just lists the URLs, which also lets a test assert them without opening
+ // real browser tabs.
+ const suppress = main_mod.g_no_browser;
+ // Cap the spawn so a reply full of image URLs can't flood the browser with
+ // tabs; the full list is always printed so the rest are one copy away.
+ const max_open = 8;
+ if (!suppress) {
+ const n = @min(urls.len, max_open);
+ for (urls[0..n]) |u| oauth.openBrowser(root.io, u);
+ }
+ if (urls.len == 1) {
+ try out.print("{s} {s}\n", .{ if (suppress) "image:" else "opening", urls[0] });
+ } else {
+ try out.print("{s} {d} images:\n", .{ if (suppress) "found" else "opening", urls.len });
+ for (urls, 1..) |u, n| try out.print(" {d}. {s}\n", .{ n, u });
+ if (!suppress and urls.len > max_open)
+ try out.print("(opened the first {d}; open the rest from the list above)\n", .{max_open});
+ }
+ try out.flush();
+ return true;
+ }
if (std.mem.startsWith(u8, line, "/image")) {
const path = std.mem.trim(u8, line["/image".len..], " \t");
if (path.len == 0) {
diff --git a/src/images.zig b/src/images.zig
new file mode 100644
index 00000000..f7c7dc58
--- /dev/null
+++ b/src/images.zig
@@ -0,0 +1,178 @@
+//! Pull image URLs out of assistant/tool output text so `/images` can open them
+//! in a browser — the terminal can't render images, and a GitHub issue body
+//! (via `gh issue view`) carries them as markdown or attachment URLs. Recognizes
+//! markdown images (`![alt](url)`), bare URLs whose path ends in an image
+//! extension, and GitHub attachment hosts that serve images without one.
+//! Order-preserving, de-duplicated, arena-owned. Kept pure (no Agent/IO) so the
+//! load-bearing logic is unit-testable without a browser. (#103)
+
+const std = @import("std");
+
+const IMAGE_EXTS = [_][]const u8{ ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp", ".avif" };
+
+// Hosts that serve user-pasted images WITHOUT a file extension, so a bare URL to
+// one still counts as an image.
+const IMAGE_HOSTS = [_][]const u8{
+ "user-images.githubusercontent.com",
+ "private-user-images.githubusercontent.com",
+ "github.com/user-attachments/",
+};
+
+/// Bytes that continue a URL. Stops at whitespace and the delimiters that end a
+/// URL in prose, markdown, or serialized JSON (a `\n`/`\"` there ends the string).
+fn isUrlByte(c: u8) bool {
+ return switch (c) {
+ ' ', '\t', '\n', '\r', '"', '\'', '`', '<', '>', '(', ')', '[', ']', '{', '}', '|', '\\' => false,
+ else => true,
+ };
+}
+
+fn trimTrailingPunct(url: []const u8) []const u8 {
+ var end = url.len;
+ while (end > 0) : (end -= 1) {
+ switch (url[end - 1]) {
+ '.', ',', ';', ':', '!', '?' => {},
+ else => break,
+ }
+ }
+ return url[0..end];
+}
+
+fn isHttpUrl(url: []const u8) bool {
+ return std.mem.startsWith(u8, url, "https://") or std.mem.startsWith(u8, url, "http://");
+}
+
+fn looksLikeImage(url: []const u8) bool {
+ for (IMAGE_HOSTS) |h| if (std.mem.indexOf(u8, url, h) != null) return true;
+ var path = url;
+ if (std.mem.indexOfScalar(u8, path, '?')) |q| path = path[0..q];
+ if (std.mem.indexOfScalar(u8, path, '#')) |f| path = path[0..f];
+ for (IMAGE_EXTS) |ext| {
+ if (path.len >= ext.len and std.ascii.eqlIgnoreCase(path[path.len - ext.len ..], ext)) return true;
+ }
+ return false;
+}
+
+/// Extract image URLs from `text`, order-preserving and de-duplicated. The
+/// returned slice and its entries are owned by `arena`.
+pub fn extractImageUrls(arena: std.mem.Allocator, text: []const u8) ![]const []const u8 {
+ var out: std.ArrayList([]const u8) = .empty;
+ var seen: std.StringHashMap(void) = .init(arena);
+
+ var i: usize = 0;
+ while (i < text.len) {
+ // Markdown image `![alt](url)` — the `!` declares it an image, so accept
+ // the URL regardless of extension.
+ if (text[i] == '!' and i + 1 < text.len and text[i + 1] == '[') {
+ if (std.mem.indexOfPos(u8, text, i + 2, "](")) |bar| {
+ const us = bar + 2;
+ if (std.mem.indexOfScalarPos(u8, text, us, ')')) |ue| {
+ var dest = std.mem.trim(u8, text[us..ue], " \t");
+ // Drop a CommonMark title — ![alt](url "title") — at the space.
+ if (std.mem.indexOfAny(u8, dest, " \t")) |sp| dest = dest[0..sp];
+ // Unwrap an angle-bracket URL — ![alt](<url>).
+ if (dest.len >= 2 and dest[0] == '<' and dest[dest.len - 1] == '>') dest = dest[1 .. dest.len - 1];
+ try add(arena, &out, &seen, dest, false);
+ i = ue + 1;
+ continue;
+ }
+ }
+ }
+ // Bare URL — accept only if it looks like an image.
+ const scheme: usize = if (std.mem.startsWith(u8, text[i..], "https://"))
+ "https://".len
+ else if (std.mem.startsWith(u8, text[i..], "http://"))
+ "http://".len
+ else
+ 0;
+ if (scheme != 0) {
+ var j = i + scheme;
+ while (j < text.len and isUrlByte(text[j])) : (j += 1) {}
+ try add(arena, &out, &seen, trimTrailingPunct(text[i..j]), true);
+ i = j;
+ continue;
+ }
+ i += 1;
+ }
+ return out.toOwnedSlice(arena);
+}
+
+fn add(
+ arena: std.mem.Allocator,
+ out: *std.ArrayList([]const u8),
+ seen: *std.StringHashMap(void),
+ url: []const u8,
+ require_image: bool,
+) !void {
+ if (!isHttpUrl(url)) return; // opened in a browser, so must be http(s)
+ if (require_image and !looksLikeImage(url)) return;
+ if (seen.contains(url)) return;
+ const owned = try arena.dupe(u8, url);
+ try seen.put(owned, {});
+ try out.append(arena, owned);
+}
+
+const testing = std.testing;
+
+fn expectUrls(text: []const u8, expected: []const []const u8) !void {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const got = try extractImageUrls(arena.allocator(), text);
+ try testing.expectEqual(expected.len, got.len);
+ for (expected, got) |e, g| try testing.expectEqualStrings(e, g);
+}
+
+test "extractImageUrls: markdown image, with and without extension" {
+ try expectUrls("see ![diagram](https://ex.com/a.png) here", &.{"https://ex.com/a.png"});
+ try expectUrls("![chart](https://ex.com/chart?v=2)", &.{"https://ex.com/chart?v=2"});
+}
+
+test "extractImageUrls: bare image URL by extension (case-insensitive), skips non-image URLs" {
+ try expectUrls("open https://ex.com/b.JPG now", &.{"https://ex.com/b.JPG"});
+ try expectUrls("visit https://ex.com/page and https://ex.com/docs", &.{});
+}
+
+test "extractImageUrls: github attachment hosts without an extension" {
+ try expectUrls(
+ "![img](https://github.com/user-attachments/assets/abc-123)",
+ &.{"https://github.com/user-attachments/assets/abc-123"},
+ );
+ try expectUrls(
+ "raw https://user-images.githubusercontent.com/1/x",
+ &.{"https://user-images.githubusercontent.com/1/x"},
+ );
+}
+
+test "extractImageUrls: de-dupes and strips trailing sentence punctuation" {
+ try expectUrls(
+ "a https://ex.com/a.png and again https://ex.com/a.png.",
+ &.{"https://ex.com/a.png"},
+ );
+}
+
+test "extractImageUrls: order-preserving across multiple images" {
+ try expectUrls(
+ "![1](https://ex.com/1.png) then https://ex.com/2.gif",
+ &.{ "https://ex.com/1.png", "https://ex.com/2.gif" },
+ );
+}
+
+test "extractImageUrls: serialized-JSON context bounds the URL at \\n and quotes" {
+ // /images scans the serialized message JSON, where a URL is followed by an
+ // escaped \n (backslash+n) or a closing quote.
+ try expectUrls("{\"output\":\"pic https://ex.com/c.png\\nmore\"}", &.{"https://ex.com/c.png"});
+ try expectUrls("{\"content\":\"https://ex.com/d.webp\"}", &.{"https://ex.com/d.webp"});
+}
+
+test "extractImageUrls: empty, no-match, and non-http are skipped" {
+ try expectUrls("", &.{});
+ try expectUrls("no urls here at all", &.{});
+ try expectUrls("relative ![x](img/local.png) is skipped", &.{});
+}
+
+test "extractImageUrls: markdown CommonMark title and angle-bracket forms" {
+ try expectUrls("![a](https://ex.com/x.png \"a caption\")", &.{"https://ex.com/x.png"});
+ try expectUrls("![a](<https://ex.com/y.png>)", &.{"https://ex.com/y.png"});
+ // Serialized JSON escapes the title's quotes; the URL still ends at the space.
+ try expectUrls("![a](https://ex.com/z.png \\\"t\\\")", &.{"https://ex.com/z.png"});
+}
diff --git a/src/main.zig b/src/main.zig
index 200810ce..0a8689ac 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -185,6 +185,8 @@ pub var g_worktree_autocommit: bool = true; // --no-autocommit turns off the per
/// report its capacity next to the scratch arena's.
pub var g_session_arena: ?*std.heap.ArenaAllocator = null;
pub var g_mem_debug: bool = false;
+/// GRAFF_NO_BROWSER=1: don't spawn a browser (headless/SSH); /images just lists the URLs.
+pub var g_no_browser: bool = false;
/// Short task label for terminal/TUI headers (mirrors the GUI's first-prompt fallback: the user's first message as a compact tab/session title).
// Session-title + header rendering + provider-response text parsers live in title.zig.
const title_mod = @import("title.zig");
@@ -257,6 +259,7 @@ pub fn main(init: std.process.Init) !void {
defer scratch_state.deinit();
g_session_arena = init.arena;
g_mem_debug = init.environ_map.get("GRAFF_MEM_DEBUG") != null;
+ g_no_browser = init.environ_map.get("GRAFF_NO_BROWSER") != null;
// Windows: let the console interpret ANSI/VT escapes so the harness's color and cursor sequences render instead of literal text.
if (builtin.os.tag == .windows) tty.enableVtOutput();
// CLI flags: the Flags struct + parsing loop live in args.zig; downstream code reads flags.<name> in place of ~27 locals this block used to declare.
diff --git a/src/oauth.zig b/src/oauth.zig
index 116ba232..e268482d 100644
--- a/src/oauth.zig
+++ b/src/oauth.zig
@@ -279,7 +279,7 @@ fn queryParam(req_line: []const u8, key: []const u8) ?[]const u8 {
return null;
}
-fn openBrowser(io: Io, url: []const u8) void {
+pub fn openBrowser(io: Io, url: []const u8) void {
const argv: []const []const u8 = if (builtin.os.tag == .macos)
&.{ "open", url }
else
diff --git a/src/repl_model_commands.zig b/src/repl_model_commands.zig
index 4d8280a2..af4b14de 100644
--- a/src/repl_model_commands.zig
+++ b/src/repl_model_commands.zig
@@ -117,6 +117,8 @@ pub fn runCommand(self: *Model, line: []const u8) void {
self.push(.info, "trace/trajectory logging is a main-session feature") catch {};
} else if (eqlAny(cmd, &.{ "/save", "/resume", "/sessions" })) {
self.push(.info, "the chat repl is ephemeral — session save/resume/list lives in the main `graff` session") catch {};
+ } else if (std.mem.eql(u8, cmd, "/images")) {
+ self.push(.info, "/images opens image URLs from tool output (e.g. a `gh issue view` result); the chat repl runs no tools — use the main `graff` session for it") catch {};
} else if (eqlAny(cmd, &.{ "/image", "/paste" })) {
self.push(.info, "image/paste input isn't wired into the chat repl yet") catch {};
} else if (std.mem.eql(u8, cmd, "/key")) {