Skip to content

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

Python

Launch apps from tool commands in the background (#832)

justrach275860cf7ccc
diff --git a/docs/adr/0299-tool-commands-launch-apps-in-the-background.md b/docs/adr/0299-tool-commands-launch-apps-in-the-background.md
new file mode 100644
index 00000000..7152b4a1
--- /dev/null
+++ b/docs/adr/0299-tool-commands-launch-apps-in-the-background.md
@@ -0,0 +1,32 @@
+# 0299. Tool commands launch apps in the background
+
+Status: accepted 2026-10-22
+
+## Context
+
+ADR 0101 kept the in-repo desktop app's automated tests off the user's
+desktop. That app and its tests have since left this repository; GUI
+verification now happens through the agent's own shell commands. On macOS a
+command that runs `open` (a URL, a built app, `open -a Simulator`) brings the
+app to the front and takes keyboard focus from whatever the user is doing,
+and each later verification step takes it again (#832).
+
+## Decision
+
+On macOS, tool children (`tool_env.zig`) get a directory first on `PATH`
+whose `open` passes `-g` to `/usr/bin/open`: Launch Services starts the app or
+opens the document without bringing it to the front. graff writes that shim
+at startup under `~/.codegraff/shims/background-gui/` (`gui_background.zig`).
+
+Foreground is an explicit opt-in. `GRAFF_GUI_FOREGROUND=1` on one command lets
+that command activate the app; in graff's own environment it leaves the shim
+off for the whole session.
+
+## Consequences
+
+Apps the agent opens appear behind the active app; windows can still overlap
+it. The shim does not cover an app that activates itself once running,
+`osascript` `activate`, `/usr/bin/open` by its full path, or synthesized input
+posted to the HID event tap, which moves the user's own pointer whatever app
+is in front. Those still need the user's consent before they run. Other
+platforms are unchanged.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 4fa549d2..9acd6780 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -315,6 +315,7 @@ record only when you need the evidence or the edge cases.
| [0295](0295-worker-native-turns-share-the-chat-step.md) | Experimental Worker-native turns share the native chat step; JSPI supplies bounded host I/O, not a proxy or a second agent loop. |
| [0296](0296-worker-tasks-own-remote-sandbox-cleanup.md) | Worker/DO tasks retain the agent loop and delegate Linux execution to remote sandboxes with explicit ownership, deletion and bounded leases. |
| [0297](0297-sdk-managed-replay-reuses-the-relay.md) | The fetch-only managed SDK reuses account relay/device tapes; prompt retries are explicit, durability limits are stated, and content-free OTLP export remains opt-in and observational. |
+| [0299](0299-tool-commands-launch-apps-in-the-background.md) | On macOS tool commands' `open` launches apps without activating them (a `-g` shim first on the tool PATH); `GRAFF_GUI_FOREGROUND=1` on a command is the explicit foreground opt-in. |
## When to write one
diff --git a/src/gui_background.zig b/src/gui_background.zig
new file mode 100644
index 00000000..a9b96279
--- /dev/null
+++ b/src/gui_background.zig
@@ -0,0 +1,159 @@
+//! Apps that tool commands launch open behind the user's work (#832).
+//!
+//! On macOS a verification command that runs `open` (a URL, a built app,
+//! `open -a Simulator`) brought that app to the front and took keyboard
+//! focus from whatever the user was doing, and every later step took it
+//! again. Tool children (tool_env.zig) get a directory first on PATH whose
+//! `open` adds `-g`, Launch Services' "do not bring the application to the
+//! foreground". The app still launches and its windows still open, behind
+//! the active app.
+//!
+//! Foreground is an explicit opt-in. `GRAFF_GUI_FOREGROUND=1` on one command
+//! (`GRAFF_GUI_FOREGROUND=1 open ...`) lets that command activate; set in
+//! graff's own environment it turns the shim off for the session.
+//!
+//! Not covered: an app that activates itself once running, `osascript`
+//! `activate`, `/usr/bin/open` by its full path, and synthesized input
+//! (events posted to the HID event tap move the user's own pointer and keys
+//! whatever app is in front).
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+const Map = std.process.Environ.Map;
+
+pub const foreground_env = "GRAFF_GUI_FOREGROUND";
+pub const shim_subdir = ".codegraff/shims/background-gui";
+pub const real_open = "/usr/bin/open";
+
+/// The shim's text, launching `target` (the real `open`).
+pub fn script(buf: []u8, target: []const u8) ![]const u8 {
+ return std.fmt.bufPrint(buf,
+ \\#!/bin/sh
+ \\# graff (#832): apps launched from tool commands open in the background.
+ \\# GRAFF_GUI_FOREGROUND=1 on a command lets it bring the app to the front.
+ \\if [ "${{GRAFF_GUI_FOREGROUND:-}}" = 1 ]; then exec '{s}' "$@"; fi
+ \\exec '{s}' -g "$@"
+ \\
+ , .{ target, target });
+}
+
+fn foregroundAsked(value: ?[]const u8) bool {
+ const v = value orelse return false;
+ return v.len != 0 and !std.mem.eql(u8, v, "0");
+}
+
+/// The shim directory for `home`, or null where it does not apply: not
+/// macOS, no home, or foreground asked for in graff's own environment.
+pub fn dir(buf: []u8, os: std.Target.Os.Tag, home: ?[]const u8, foreground: ?[]const u8) ?[]const u8 {
+ if (os != .macos or foregroundAsked(foreground)) return null;
+ const h = std.mem.trimEnd(u8, home orelse return null, "/");
+ if (h.len == 0) return null;
+ return std.fmt.bufPrint(buf, "{s}/" ++ shim_subdir, .{h}) catch null;
+}
+
+/// Put the shim directory first on the tool environment's PATH.
+pub fn applyTo(m: *Map, os: std.Target.Os.Tag) std.mem.Allocator.Error!void {
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const d = dir(&buf, os, m.get("HOME"), m.get(foreground_env)) orelse return;
+ const path = m.get("PATH") orelse "";
+ if (std.mem.startsWith(u8, path, d) and (path.len == d.len or path[d.len] == ':')) return;
+ var joined: std.ArrayList(u8) = .empty;
+ defer joined.deinit(m.allocator);
+ try joined.appendSlice(m.allocator, d);
+ if (path.len != 0) {
+ try joined.append(m.allocator, ':');
+ try joined.appendSlice(m.allocator, path);
+ }
+ try m.put("PATH", joined.items);
+}
+
+/// Write the shim under `home` unless it is already there. Best effort: if
+/// it cannot be written, `open` on PATH is the real one, as before.
+pub fn install(io: Io, home: []const u8, target: []const u8) void {
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const d = dir(&buf, builtin.os.tag, home, null) orelse return;
+ var text_buf: [512]u8 = undefined;
+ const text = script(&text_buf, target) catch return;
+ const cwd = Io.Dir.cwd();
+ cwd.createDirPath(io, d) catch return;
+ var shim_dir = cwd.openDir(io, d, .{}) catch return;
+ defer shim_dir.close(io);
+ var have_buf: [512]u8 = undefined;
+ if (shim_dir.readFile(io, "open", &have_buf)) |have| {
+ if (std.mem.eql(u8, have, text)) return;
+ } else |_| {}
+ // A concurrent graff may be writing the same bytes: stage, then rename.
+ var tmp_buf: [32]u8 = undefined;
+ const tmp = std.fmt.bufPrint(&tmp_buf, "open.{d}.tmp", .{@import("proc_identity.zig").selfPid()}) catch return;
+ shim_dir.writeFile(io, .{ .sub_path = tmp, .data = text }) catch return;
+ shim_dir.setFilePermissions(io, tmp, .fromMode(0o755), .{}) catch {};
+ shim_dir.rename(tmp, shim_dir, "open", io) catch shim_dir.deleteFile(io, tmp) catch {};
+}
+
+const testing = std.testing;
+
+test "#832: the background-launch shim applies on macOS only, and not when foreground is asked for" {
+ var buf: [256]u8 = undefined;
+ try testing.expectEqualStrings("/Users/u/" ++ shim_subdir, dir(&buf, .macos, "/Users/u/", null).?);
+ try testing.expect(dir(&buf, .linux, "/home/u", null) == null);
+ try testing.expect(dir(&buf, .macos, null, null) == null);
+ try testing.expect(dir(&buf, .macos, "/Users/u", "1") == null);
+ try testing.expect(dir(&buf, .macos, "/Users/u", "0") != null);
+}
+
+test "#832: PATH gets the shim once, in front" {
+ var m = Map.init(testing.allocator);
+ defer m.deinit();
+ try m.put("HOME", "/Users/u");
+ try m.put("PATH", "/usr/bin:/bin");
+ try applyTo(&m, .macos);
+ try applyTo(&m, .macos);
+ try testing.expectEqualStrings("/Users/u/" ++ shim_subdir ++ ":/usr/bin:/bin", m.get("PATH").?);
+ var linux = Map.init(testing.allocator);
+ defer linux.deinit();
+ try linux.put("HOME", "/home/u");
+ try linux.put("PATH", "/usr/bin");
+ try applyTo(&linux, .linux);
+ try testing.expectEqualStrings("/usr/bin", linux.get("PATH").?);
+}
+
+test "#832: `open` in a tool shell launches in the background unless the command opts in" {
+ if (builtin.os.tag != .macos) return error.SkipZigTest;
+ const io = testing.io;
+ const gpa = testing.allocator;
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const home = path_buf[0..try tmp.dir.realPath(io, &path_buf)];
+ // A stand-in for /usr/bin/open that only reports its arguments.
+ try tmp.dir.writeFile(io, .{ .sub_path = "fake-open", .data = "#!/bin/sh\necho \"open $*\"\n" });
+ try tmp.dir.setFilePermissions(io, "fake-open", .fromMode(0o755), .{});
+ var target_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const target = try std.fmt.bufPrint(&target_buf, "{s}/fake-open", .{home});
+ install(io, home, target);
+
+ var parent = Map.init(gpa);
+ defer parent.deinit();
+ try parent.put("HOME", home);
+ try parent.put("PATH", "/usr/bin:/bin");
+ var env = try @import("tool_env.zig").build(gpa, &parent);
+ defer env.deinit();
+ const jobs = @import("jobs.zig");
+ var opts = jobs.toolRunOptions(null);
+ opts.environ_map = &env;
+ // Never the real `open`: anything but the shim is reported, not run.
+ const guard = "p=$(command -v open); case \"$p\" in \"$HOME\"/.codegraff/*) ;; *) echo \"unshimmed $p\"; exit 1 ;; esac; ";
+ for ([_][2][]const u8{
+ .{ "open https://example.invalid/page", "open -g https://example.invalid/page\n" },
+ .{ "GRAFF_GUI_FOREGROUND=1 open -a Simulator", "open -a Simulator\n" },
+ }) |case| {
+ const cmd = try std.mem.concat(gpa, u8, &.{ guard, case[0] });
+ defer gpa.free(cmd);
+ const sh = jobs.shellArgv(cmd);
+ const run = try jobs.runCappedWithOptions(gpa, io, &sh, 4096, 4096, 10_000, opts);
+ defer gpa.free(run.stdout);
+ defer gpa.free(run.stderr);
+ try testing.expectEqualStrings(case[1], run.stdout);
+ }
+}
diff --git a/src/startup.zig b/src/startup.zig
index 852361ec..a24a8c31 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -285,6 +285,7 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
// After router_config.load (its key is one of them), before `serve` and
// the other subcommands below can spawn a tool.
@import("tool_env.zig").init(arena, init.environ_map);
+ @import("gui_background.zig").install(io, keys_cli.homeEnv(init.environ_map) orelse "", @import("gui_background.zig").real_open); // #832
// #557: same pin for GRAFF_PRICES_PATH, before `graff models` is dispatched
// below — the hydration points (router_catalog, models_cache) all sit well
// under the last call that still holds the environment.
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index cf3714f4..fcc79cd7 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -403,6 +403,7 @@ test {
_ = @import("subagent_brief.zig"); // structured delegation brief + harness environment header
_ = @import("idle_wake_sources.zig"); // shared idle auto-turn sources for REPL / TUI / ACP
_ = @import("tool_env.zig"); // #1267/#1268: tool children's environment
+ _ = @import("gui_background.zig"); // #832: tool commands launch apps in the background
_ = @import("destructive_git.zig"); // #1269: destructive-git tokenizer tables
_ = @import("output_elide.zig"); // #1271: over-cap output keeps head and tail
_ = @import("graff_dir.zig"); // #1273: .graff/.gitignore keeps run state out of git
diff --git a/src/tool_env.zig b/src/tool_env.zig
index d1224bf8..71fcf692 100644
--- a/src/tool_env.zig
+++ b/src/tool_env.zig
@@ -21,6 +21,9 @@
//! instead. Not on Windows, where these commands and that failure mode do
//! not apply the same way.
//!
+//! #832: on macOS `open` in a tool child launches apps in the background
+//! (gui_background.zig puts its shim first on PATH).
+//!
//! Children graff launches as graff (learning runs) and MCP servers do not
//! come through here: they keep the full environment, because they are the
//! ones that legitimately read those keys. Subagents run in-process.
@@ -96,6 +99,7 @@ pub fn build(gpa: Allocator, parent: *const Map) Allocator.Error!Map {
for (non_interactive) |kv| if (!passed(pass, kv[0])) try m.put(kv[0], kv[1]);
try gitEditors(&m, pass);
}
+ try @import("gui_background.zig").applyTo(&m, builtin.os.tag); // #832: `open` launches in the background
return m;
}
@@ -164,7 +168,7 @@ test "#1267: tool env drops the provider keys graff reads and keeps the rest" {
defer m.deinit();
for ([_][]const u8{ "OPENAI_API_KEY", "XAI_API_KEY", "CODEGRAFF_API_KEY", "GRAFF_TELEMETRY_KEY", "MYROUTER_API_KEY" }) |name|
try std.testing.expect(m.get(name) == null);
- try std.testing.expectEqualStrings("/usr/bin:/bin", m.get("PATH").?);
+ try std.testing.expect(std.mem.endsWith(u8, m.get("PATH").?, "/usr/bin:/bin")); // #832 may put its shim first
try std.testing.expectEqualStrings("/tmp", m.get("HOME").?);
try std.testing.expectEqualStrings("sk-fake-openai", parent.get("OPENAI_API_KEY").?); // graff keeps its own
}
@@ -208,7 +212,7 @@ test "#1267: a real tool child (both shell paths) cannot see the key" {
const run = try jobs.runCappedWithOptions(gpa, io, &sh, 64 * 1024, 4096, 10_000, jobs.toolRunOptions(null));
defer gpa.free(run.stdout);
defer gpa.free(run.stderr);
- try std.testing.expect(std.mem.indexOf(u8, run.stdout, "PATH=/usr/bin:/bin") != null);
+ try std.testing.expect(std.mem.indexOf(u8, run.stdout, "/usr/bin:/bin\n") != null);
try std.testing.expect(std.mem.indexOf(u8, run.stdout, "sk-fake-openai") == null);
try std.testing.expect(std.mem.indexOf(u8, run.stdout, "OPENAI_API_KEY") == null);
@@ -223,7 +227,7 @@ test "#1267: a real tool child (both shell paths) cannot see the key" {
.cancelled => |c| gpa.free(c.output),
};
try std.testing.expect(waited == .done);
- try std.testing.expect(std.mem.indexOf(u8, waited.done.output, "PATH=/usr/bin:/bin") != null);
+ try std.testing.expect(std.mem.indexOf(u8, waited.done.output, "/usr/bin:/bin\n") != null);
try std.testing.expect(std.mem.indexOf(u8, waited.done.output, "xai-fake") == null);
try std.testing.expect(std.mem.indexOf(u8, waited.done.output, "OPENAI_API_KEY") == null);
}
@@ -319,7 +323,7 @@ test "#1267: control flags and essentials survive a provider env_key naming them
provider.additional_router = .{ .id = "myrouter", .display_name = "My Router", .kind = .openai, .auth = .bearer, .url = "http://127.0.0.1:9/v1/chat/completions", .env_key = "PATH", .default_model = "m" };
var m = try build(gpa, &parent);
defer m.deinit();
- try std.testing.expectEqualStrings("/usr/bin:/bin", m.get("PATH").?);
+ try std.testing.expect(std.mem.endsWith(u8, m.get("PATH").?, "/usr/bin:/bin"));
try std.testing.expectEqualStrings("1", m.get("CODEX_DISABLED").?);
try std.testing.expect(m.get("OPENAI_API_KEY") == null);
}
@@ -395,3 +399,18 @@ test "#1268: an explicit git -c core.editor / sequence.editor still wins in a to
try std.testing.expect(std.mem.indexOf(u8, run.stdout, "squash=2\n") != null);
try std.testing.expect(std.mem.indexOf(u8, run.stdout, "subject=edited\n") != null);
}
+
+test "#832: a tool child's PATH finds the background-launch `open` first on macOS" {
+ const gpa = std.testing.allocator;
+ var parent = try fakeParent(gpa);
+ defer parent.deinit();
+ var m = try build(gpa, &parent);
+ defer m.deinit();
+ const want = if (builtin.os.tag == .macos) "/tmp/.codegraff/shims/background-gui:/usr/bin:/bin" else "/usr/bin:/bin";
+ try std.testing.expectEqualStrings(want, m.get("PATH").?);
+ // Foreground asked for in graff's own environment: PATH is left alone.
+ try parent.put("GRAFF_GUI_FOREGROUND", "1");
+ var fg = try build(gpa, &parent);
+ defer fg.deinit();
+ try std.testing.expectEqualStrings("/usr/bin:/bin", fg.get("PATH").?);
+}