Skip to content

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

Python

feat(native): the desktop app carries the interface it shows

justrach4057060a6320
diff --git a/apps/native/desktop/README.md b/apps/native/desktop/README.md
index 20498ea8..3686ac61 100644
--- a/apps/native/desktop/README.md
+++ b/apps/native/desktop/README.md
@@ -22,14 +22,98 @@ is embedded in the binary and handed to `NSApplication` at startup, so the
Dock and ⌘-Tab show it even when the shell runs as a loose binary with no
bundle for macOS to read an icon from.
+## What is inside the app
+
+The app carries the interface it shows, so a downloaded copy works with
+nothing else installed — no checkout, no `npm install`, no Node:
+
+| `Contents/Resources/` | | |
+| --- | --- | --- |
+| `ui` | 46 MB | the interface, built with Next's `output: "standalone"` |
+| `bun` | 59 MB | the JS runtime that runs it |
+| `graff` | 6 MB | the harness the interface drives |
+
+That is what makes the bundle ~113 MB. The standalone build does not trace
+static assets into itself, so `build-app.sh` copies `.next/static` and
+`public` in afterwards; without that every page loads with no CSS or JS.
+It also deletes `node_modules/@img`, 31 MB of image-resizing native code
+that nothing ever loads because `images` are `unoptimized` in
+`next.config.ts` — which also leaves the payload with no native code to
+sign.
+
+`SKIP_UI=1` builds the window alone (1.3 MB), which is the fast path when
+you are working on the shell itself. Such a build starts no server and
+shows the "not running" page, exactly like a loose dev binary.
+
+The JS runtime is resolved from `BUN_BIN`, else `command -v bun`, and is
+copied as a real file — `command -v` can hand back a symlink into a version
+manager's store, which would not survive being shipped to another machine.
+
+## Starting it
+
+Order of precedence, decided before the window opens:
+
+1. `GRAFF_NATIVE_URL`, if set.
+2. A dev server already listening on 3777, then 3000. A developer's own
+ server wins over the bundled one: they are working on it, and two
+ servers would fight over the same sessions.
+3. The interface inside the bundle, on the first free port from 3778 up.
+4. Otherwise the page that says what to start.
+
+The bundled server is spawned with `PORT`, `HOSTNAME=127.0.0.1` (it spawns
+processes and reads the disk on request, so it is the app's own back end
+and not something to put on the network), `GRAFF_BIN` pointing at the
+bundled harness, and `GRAFF_CWD` set to the home directory. That last one
+matters: the workspace root otherwise defaults to the server's own cwd,
+which inside a bundle is a signed, read-only directory. An existing
+`GRAFF_CWD` wins, and `GRAFF_ACP_CWD` is left alone so it still overrides.
+
+`GRAFF_NATIVE_NO_SERVER=1` skips the bundled server, for debugging the
+packaged app against a server you start yourself.
+
+## Stopping it
+
+The server must not outlive the window, so it is killed three ways over:
+
+- The app quits when its last window closes, and its delegate's
+ `applicationWillTerminate:` stops the server. ⌘Q works because the app
+ now builds a menu with a Quit item — a key equivalent lives in a menu
+ item, so an app with no menu cannot be quit with the keyboard at all.
+- An `atexit` handler, for any other orderly exit.
+- `SIGINT`, `SIGTERM` and `SIGHUP` handlers, which `atexit` does not cover,
+ for a shell started from a terminal.
+
+All of them kill the process *group*, not the server's pid: the interface
+spawns a harness per chat tab, and killing only its parent would leave
+those running.
+
+A `SIGKILL` outruns all of that, so the group id is also written to
+`~/Library/Caches/dev.codegraff.native.pid` and the next launch kills what
+it names — but only after `ps` confirms that pid is still the very runtime
+this bundle is about to start. Pids get recycled, and killing a stranger's
+process group because it inherited an old number would be a real bug.
+
## A signed, notarized app
```bash
apps/native/desktop/build-app.sh # build + sign
+SKIP_UI=1 apps/native/desktop/build-app.sh # window only
NOTARIZE=1 apps/native/desktop/build-app.sh # …and send it to Apple
NOTARIZE=1 INSTALL=1 apps/native/desktop/build-app.sh # …and put it in /Applications
```
+Signing goes inside out, because the outer signature seals the bundle and
+anything signed after it invalidates it: the nested executables first, then
+the app. Each gets its own hardened runtime — `--deep` is deprecated for
+signing (it is still the right flag for *verifying*) and would not give
+them one.
+
+The JS runtime is signed with `runtime.entitlements`, which grants
+`allow-jit` and `allow-unsigned-executable-memory`. The hardened runtime
+forbids writable-executable memory, which is exactly what a JavaScript JIT
+needs; without those the runtime is killed the moment it compiles anything
+and the app opens onto nothing.
+
Install what was notarized, not a later re-signed build: re-signing
replaces the signature the stapled ticket belongs to, and the copy stops
being notarized. `INSTALL_DIR` moves the destination.
@@ -90,9 +174,9 @@ updates itself either.
The version logic has tests: `zig test apps/native/desktop/update.zig`.
-Launched from Finder an app inherits no environment, so with
-`GRAFF_NATIVE_URL` unset the shell looks for a dev server on 3777 and then
-3000, and falls back to the first so the window still opens.
+Launched from Finder an app inherits no environment, which is why none of
+the variables above can be relied on to be set — see "Starting it" for what
+the shell does instead.
The document is fetched with `NSURLRequestReloadIgnoringLocalCacheData`.
The window points at a dev server whose bundle changes underneath it, and
diff --git a/apps/native/desktop/build-app.sh b/apps/native/desktop/build-app.sh
old mode 100755
new mode 100644
index 8fb4c4b7..28b125e9
--- a/apps/native/desktop/build-app.sh
+++ b/apps/native/desktop/build-app.sh
@@ -3,6 +3,12 @@
#
# apps/native/desktop/build-app.sh # build + sign
# NOTARIZE=1 apps/native/desktop/build-app.sh # …and send it to Apple
+# SKIP_UI=1 apps/native/desktop/build-app.sh # window only, for shell work
+#
+# The app carries the interface it shows: a standalone build of it, the JS
+# runtime that runs it and the harness it drives, so a downloaded app works
+# with nothing else installed. That is what makes it ~150 MB; SKIP_UI is
+# the fast path for iterating on the window itself.
#
# macOS only: the shell is AppKit + WKWebView, and everything below
# (codesign, iconutil, notarytool) is part of Xcode's command line tools.
@@ -40,6 +46,43 @@ iconutil -c icns "$iconset" -o "$app/Contents/Resources/icon.icns"
cp "$here/Info.plist" "$app/Contents/Info.plist"
+if [[ "${SKIP_UI:-0}" != "1" ]]; then
+ ui="$root/apps/native"
+
+ echo "▸ building the interface"
+ # `output: standalone` in next.config.ts emits a server that runs with no
+ # node_modules tree beside it; the static assets are not traced into it
+ # and have to be copied in, or every page loads without its JS and CSS.
+ [[ -d "$ui/node_modules" ]] || npm --prefix "$ui" install
+ ( cd "$ui" && npx next build )
+ rm -rf "$app/Contents/Resources/ui"
+ ditto "$ui/.next/standalone" "$app/Contents/Resources/ui"
+ ditto "$ui/.next/static" "$app/Contents/Resources/ui/.next/static"
+ if [[ -d "$ui/public" ]]; then
+ ditto "$ui/public" "$app/Contents/Resources/ui/public"
+ fi
+ # 31 MB of image-resizing native code that this app never runs: images
+ # are `unoptimized` in next.config.ts, so nothing ever loads it. Dropping
+ # it also leaves the payload with no native code at all to sign.
+ rm -rf "$app/Contents/Resources/ui/node_modules/@img"
+
+ echo "▸ the harness"
+ # `graff` rather than the default step: the app needs the CLI, not the
+ # REPL, the TUI and the wasm target as well.
+ ( cd "$root" && zig build graff -Doptimize=ReleaseFast )
+ cp "$root/zig-out/bin/graff" "$app/Contents/Resources/graff"
+
+ echo "▸ the JS runtime"
+ # Resolved, then copied as a real file: `command -v` can hand back a
+ # symlink into a version manager's store, which would not survive being
+ # signed and shipped to someone else's machine.
+ runtime="${BUN_BIN:-$(command -v bun || true)}"
+ [[ -n "$runtime" ]] || { echo "no bun found — install it or set BUN_BIN (the app needs a JS runtime inside it)"; exit 1; }
+ cp "$(readlink -f "$runtime" 2>/dev/null || echo "$runtime")" "$app/Contents/Resources/bun"
+ chmod +x "$app/Contents/Resources/bun"
+ echo "▸ bundled bun $("$app/Contents/Resources/bun" --version)"
+fi
+
# The app compares this against the newest release tag to decide whether it
# is out of date, so a build that does not know its own version can never
# update itself. Take it from the argument, else the current tag.
@@ -55,6 +98,31 @@ fi
echo "▸ signing as: $identity"
# Hardened runtime and a secure timestamp are what notarization requires.
+#
+# Inside out: the outer signature seals the bundle, so anything signed
+# afterwards invalidates it. The two nested executables get signed first,
+# each with its own hardened runtime — `--deep` is deprecated for signing
+# (it is still the right flag for *verifying*) and would not give them one.
+if [[ -f "$app/Contents/Resources/bun" ]]; then
+ # The JS runtime needs the JIT entitlements or the hardened runtime kills
+ # it as soon as it compiles anything.
+ codesign --force --options runtime --timestamp \
+ --entitlements "$here/runtime.entitlements" \
+ --sign "$identity" "$app/Contents/Resources/bun"
+fi
+if [[ -f "$app/Contents/Resources/graff" ]]; then
+ codesign --force --options runtime --timestamp --sign "$identity" "$app/Contents/Resources/graff"
+fi
+# Anything a dependency dragged in. The payload carries no native code
+# today, but one unsigned Mach-O file anywhere inside the bundle fails
+# notarization, and that is a bad thing to learn from Apple rather than here.
+if [[ -d "$app/Contents/Resources/ui" ]]; then
+ while IFS= read -r -d '' macho; do
+ echo " signing $(basename "$macho")"
+ codesign --force --options runtime --timestamp --sign "$identity" "$macho"
+ done < <(/usr/bin/find "$app/Contents/Resources/ui" -type f \
+ \( -name '*.node' -o -name '*.dylib' -o -name '*.so' \) -print0)
+fi
codesign --force --options runtime --timestamp --sign "$identity" "$app"
codesign --verify --deep --strict --verbose=2 "$app"
diff --git a/apps/native/desktop/main.zig b/apps/native/desktop/main.zig
index 01cd0da2..55364dab 100644
--- a/apps/native/desktop/main.zig
+++ b/apps/native/desktop/main.zig
@@ -11,6 +11,7 @@
const std = @import("std");
const builtin = @import("builtin");
const update = @import("update.zig");
+const server = @import("server.zig");
/// The Dock and ⌘-Tab icon. A bare binary has no bundle to read an icon
/// from, so the image travels inside it and is handed to NSApplication at
@@ -23,14 +24,15 @@ fn openLinux(url: []const u8) void {
/// Where the UI is served. A bundled app is launched from Finder with no
/// environment to inherit, so when `GRAFF_NATIVE_URL` is unset the shell
-/// looks for a dev server on the ports this app uses, newest first, and
-/// falls back to the first of them so the window still opens (and shows
-/// the browser's own "cannot connect" page) when nothing is listening.
+/// looks for a dev server on the ports this app uses, newest first. A
+/// developer's own server is preferred over the copy inside the bundle:
+/// they are working on it, and two servers would fight over the sessions.
const default_urls = [_][]const u8{ "http://127.0.0.1:3777", "http://127.0.0.1:3000" };
-/// Shown when no interface is serving. The window is a shell around a local
-/// app that is not inside the bundle, and a blank connection error tells a
-/// first-time user nothing about that.
+/// Shown when no interface is serving. A packaged app carries its own and
+/// never gets here; a loose binary, a build made without one, or a bundled
+/// server that refused to start does, and a blank connection error tells
+/// the reader nothing about which.
const no_server_html =
\\<meta name="viewport" content="width=device-width,initial-scale=1">
\\<style>
@@ -47,8 +49,8 @@ const no_server_html =
\\</style>
\\<main>
\\<h1>The interface is not running yet</h1>
- \\<p>This window shows the codegraff interface, which runs on your machine
- \\and is not part of the app. Start it from a checkout of the repository:</p>
+ \\<p>This build does not carry the codegraff interface, so it needs one
+ \\running on your machine. Start it from a checkout of the repository:</p>
\\<pre><code>zig build # builds the graff binary
\\cd apps/native
\\npm install &amp;&amp; npm run dev # serves the interface</code></pre>
@@ -70,25 +72,39 @@ fn listening(url: []const u8) bool {
}
pub fn main(init: std.process.Init) !void {
- var serving = true;
- const url = init.environ_map.get("GRAFF_NATIVE_URL") orelse blk: {
- for (default_urls) |candidate| {
- if (listening(candidate)) break :blk candidate;
- }
- // Nothing is listening. The app is a window onto an interface it does
- // not contain, so this is the normal first-run state, not a fault —
- // say what to start rather than showing WebKit's connection error.
- serving = false;
- break :blk default_urls[0];
- };
// Set this to pin a build: a machine mid-debug should not have the app
// swapped underneath it because a release happened to land.
const updates = init.environ_map.get("GRAFF_NATIVE_NO_UPDATE") == null;
if (comptime builtin.os.tag == .macos) {
- try runMac(url, updates, serving);
+ try runMac(init, updates);
} else {
- openLinux(url);
+ openLinux(init.environ_map.get("GRAFF_NATIVE_URL") orelse default_urls[0]);
+ }
+}
+
+/// The URL the window opens, and whether anything is actually serving it.
+/// Order matters: an explicit pin wins, then a dev server the developer is
+/// already running, then the interface inside this bundle.
+fn resolve(init: std.process.Init, buf: []u8) struct { []const u8, bool } {
+ if (init.environ_map.get("GRAFF_NATIVE_URL")) |pinned| return .{ pinned, true };
+ for (default_urls) |candidate| {
+ if (listening(candidate)) return .{ candidate, true };
+ }
+ // Set this to debug against a server you start yourself while still
+ // running the packaged app.
+ if (init.environ_map.get("GRAFF_NATIVE_NO_SERVER") == null) {
+ if (bundlePath(init.gpa)) |bundle| {
+ if (server.start(init.gpa, init.io, init.environ_map, bundle)) |port| {
+ const url = std.fmt.bufPrint(buf, "http://127.0.0.1:{d}", .{port}) catch
+ return .{ default_urls[0], false };
+ return .{ url, true };
+ }
+ }
}
+ // Nothing to show: a loose dev binary, a build made without the
+ // interface, or a bundled server that would not start. Say what to do
+ // rather than showing WebKit's connection error.
+ return .{ default_urls[0], false };
}
// ── macOS AppKit / WKWebView (merjs examples/desktop) ─────────────────
@@ -96,6 +112,9 @@ pub fn main(init: std.process.Init) !void {
extern fn objc_getClass(name: [*:0]const u8) ?*anyopaque;
extern fn sel_registerName(name: [*:0]const u8) ?*anyopaque;
extern fn objc_msgSend() void;
+extern fn objc_allocateClassPair(superclass: ?*anyopaque, name: [*:0]const u8, extra: usize) ?*anyopaque;
+extern fn class_addMethod(class: ?*anyopaque, name: ?*anyopaque, imp: *const anyopaque, types: [*:0]const u8) i8;
+extern fn objc_registerClassPair(class: ?*anyopaque) void;
const Id = ?*anyopaque;
const Sel = ?*anyopaque;
@@ -168,6 +187,12 @@ fn send2(recv: Id, s: Sel, a: Id, b: Id) Id {
const F = *const fn (Id, Sel, Id, Id) callconv(.c) Id;
return @as(F, @ptrCast(&objc_msgSend))(recv, s, a, b);
}
+/// The middle argument is a selector, not an object — that is what a menu
+/// item's action is.
+fn send3(recv: Id, s: Sel, a: Id, action: Sel, c: Id) Id {
+ const F = *const fn (Id, Sel, Id, Sel, Id) callconv(.c) Id;
+ return @as(F, @ptrCast(&objc_msgSend))(recv, s, a, action, c);
+}
fn sendRequestInit(recv: Id, s: Sel, url: Id, policy: NSUInteger, timeout: f64) Id {
const F = *const fn (Id, Sel, Id, NSUInteger, f64) callconv(.c) Id;
return @as(F, @ptrCast(&objc_msgSend))(recv, s, url, policy, timeout);
@@ -177,6 +202,61 @@ fn sendBytes(recv: Id, s: Sel, ptr: [*]const u8, len: NSUInteger) Id {
return @as(F, @ptrCast(&objc_msgSend))(recv, s, ptr, len);
}
+/// The window is the whole app, and it now holds a server: leaving a
+/// windowless shell alive would leave that server and every harness it
+/// started running invisibly.
+fn shouldTerminate(_: Id, _: Sel, _: Id) callconv(.c) BOOL {
+ return YES;
+}
+
+/// Belt and braces with the `atexit` handler in server.zig. This is the
+/// hook that runs while the app is still a running app, so it is the one
+/// that fires on an orderly quit.
+fn willTerminate(_: Id, _: Sel, _: Id) callconv(.c) void {
+ server.stop();
+}
+
+/// An app with no menu has no Quit item, and ⌘Q lives in that item — so
+/// without this there is no way to quit but Force Quit, which skips every
+/// cleanup path and strands the server.
+fn addMenu(app: Id) void {
+ const bar = send(send(cls("NSMenu"), sel("alloc")), sel("init"));
+ const app_item = send(send(cls("NSMenuItem"), sel("alloc")), sel("init"));
+ send1v(bar, sel("addItem:"), app_item);
+ send1v(app, sel("setMainMenu:"), bar);
+
+ const menu = send(send(cls("NSMenu"), sel("alloc")), sel("init"));
+ const title = sendStr(cls("NSString"), sel("stringWithUTF8String:"), "Quit Codegraff");
+ const key = sendStr(cls("NSString"), sel("stringWithUTF8String:"), "q");
+ const quit = send3(
+ send(cls("NSMenuItem"), sel("alloc")),
+ sel("initWithTitle:action:keyEquivalent:"),
+ title,
+ sel("terminate:"),
+ key,
+ );
+ send1v(menu, sel("addItem:"), quit);
+ send1v(app_item, sel("setSubmenu:"), menu);
+}
+
+/// Quit when the last window closes, and tear the server down on the way
+/// out. Built at runtime because there is no ObjC compiler here — the
+/// runtime's own class API is what merjs uses for the same reason.
+fn setDelegate(app: Id) void {
+ const class = objc_allocateClassPair(cls("NSObject"), "GraffAppDelegate", 0) orelse return;
+ // ObjC type encodings: `c@:@` is "returns char, takes self, _cmd, id".
+ _ = class_addMethod(
+ class,
+ sel("applicationShouldTerminateAfterLastWindowClosed:"),
+ @ptrCast(&shouldTerminate),
+ "c@:@",
+ );
+ _ = class_addMethod(class, sel("applicationWillTerminate:"), @ptrCast(&willTerminate), "v@:@");
+ objc_registerClassPair(class);
+ const delegate = send(send(class, sel("alloc")), sel("init"));
+ send1v(app, sel("setDelegate:"), delegate);
+}
+
/// Give the app its icon. Best effort: a shell without one still runs.
fn setAppIcon(app: Id) void {
const data = sendBytes(cls("NSData"), sel("dataWithBytes:length:"), icon_png.ptr, icon_png.len);
@@ -206,13 +286,20 @@ fn updateWorker(bundle: []const u8) void {
update.check(std.heap.page_allocator, bundle);
}
-fn runMac(url: []const u8, updates: bool, serving: bool) !void {
+fn runMac(init: std.process.Init, updates: bool) !void {
+ // Resolved before the window exists: starting the bundled server takes
+ // a moment, and an empty window while it boots looks like a hang.
+ var resolved_buf: [64]u8 = undefined;
+ const url, const serving = resolve(init, &resolved_buf);
+
var url_buf: [256]u8 = undefined;
const url_z = try std.fmt.bufPrintSentinel(&url_buf, "{s}", .{url}, 0);
const app = send(cls("NSApplication"), sel("sharedApplication"));
sendIntv(app, sel("setActivationPolicy:"), NSApplicationActivationPolicyRegular);
setAppIcon(app);
+ addMenu(app);
+ setDelegate(app);
const frame = CGRect{ .origin = .{ .x = 0, .y = 0 }, .size = .{ .width = 1280, .height = 820 } };
const style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
diff --git a/apps/native/desktop/runtime.entitlements b/apps/native/desktop/runtime.entitlements
new file mode 100644
index 00000000..0f889d6b
--- /dev/null
+++ b/apps/native/desktop/runtime.entitlements
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- For the bundled JS runtime only. The hardened runtime forbids
+ writable-executable memory, which is exactly what a JavaScript JIT
+ needs: without this the runtime is killed the moment it compiles
+ anything, and the app opens onto nothing. -->
+ <key>com.apple.security.cs.allow-jit</key>
+ <true/>
+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
+ <true/>
+ <!-- The interface loads whatever its dependencies bring with them, which
+ is not signed by this team. -->
+ <key>com.apple.security.cs.disable-library-validation</key>
+ <true/>
+</dict>
+</plist>
diff --git a/apps/native/desktop/server.zig b/apps/native/desktop/server.zig
new file mode 100644
index 00000000..0347d358
--- /dev/null
+++ b/apps/native/desktop/server.zig
@@ -0,0 +1,207 @@
+//! The interface, shipped inside the app.
+//!
+//! A downloaded app has no repository to serve the UI from, so the bundle
+//! carries a standalone build of it (`Resources/ui`), the JS runtime that
+//! runs it (`Resources/bun`) and the harness it drives (`Resources/graff`).
+//! This starts that server and hands the window back a port.
+//!
+//! A developer's own `npm run dev` still wins: main.zig only calls this
+//! when nothing is already listening, so a checkout keeps its live reload
+//! and never has two servers fighting over the same sessions.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const Io = std.Io;
+
+/// Ports to try, in order. 3777 and 3000 belong to a developer's own dev
+/// server; binding one here would collide the moment they start it.
+const first_port: u16 = 3778;
+const port_attempts: u16 = 40;
+
+/// Nothing is compiled at startup — the build already happened — but a JS
+/// runtime still has to boot and load the server. Past this the window
+/// gives up and shows the "not running" page rather than a blank frame.
+const boot_timeout_ms: u64 = 20_000;
+const poll_ms: u64 = 100;
+
+/// The process group the server runs in, so the app can take it down on
+/// the way out. A group rather than a pid: the server spawns a harness per
+/// chat tab, and killing only its parent would leave those running.
+var group: std.posix.pid_t = 0;
+
+/// libc's. Registering here means the group dies with any ordinary exit,
+/// including ⌘Q, which ends in `exit()` inside `-[NSApplication terminate:]`.
+extern "c" fn atexit(func: *const fn () callconv(.c) void) c_int;
+
+/// Kill the server and everything it spawned. Idempotent, and safe when
+/// nothing was ever started.
+pub fn stop() callconv(.c) void {
+ if (group == 0) return;
+ // A negative pid is "the whole process group" to kill(2).
+ std.posix.kill(-group, .TERM) catch {};
+ group = 0;
+}
+
+/// A signal skips `atexit` entirely, so Ctrl-C on a shell started from a
+/// terminal would otherwise leave the server behind. Stop it, then die the
+/// way the signal asked: re-raising through the default handler keeps the
+/// exit status honest for whatever started us.
+fn onSignal(sig: std.posix.SIG) callconv(.c) void {
+ stop();
+ std.posix.sigaction(sig, &.{
+ .handler = .{ .handler = std.posix.SIG.DFL },
+ .mask = std.posix.sigemptyset(),
+ .flags = 0,
+ }, null);
+ std.posix.raise(sig) catch {};
+}
+
+fn catchSignals() void {
+ const action = std.posix.Sigaction{
+ .handler = .{ .handler = &onSignal },
+ .mask = std.posix.sigemptyset(),
+ .flags = 0,
+ };
+ for ([_]std.posix.SIG{ .INT, .TERM, .HUP }) |sig| {
+ std.posix.sigaction(sig, &action, null);
+ }
+}
+
+/// Start the interface that ships inside `bundle`, and return the port it
+/// answers on. Null means this build has no interface inside it — a loose
+/// dev binary, or one built with `SKIP_UI=1` — which is not an error: the
+/// caller falls back to the page that says what to start.
+pub fn start(gpa: Allocator, io: Io, env: *std.process.Environ.Map, bundle: []const u8) ?u16 {
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const res = std.fmt.allocPrint(arena, "{s}/Contents/Resources", .{bundle}) catch return null;
+ const ui = std.fmt.allocPrint(arena, "{s}/ui", .{res}) catch return null;
+ const entry = std.fmt.allocPrint(arena, "{s}/server.js", .{ui}) catch return null;
+ const runtime = std.fmt.allocPrint(arena, "{s}/bun", .{res}) catch return null;
+ const harness = std.fmt.allocPrint(arena, "{s}/graff", .{res}) catch return null;
+
+ const cwd = Io.Dir.cwd();
+ cwd.access(io, entry, .{}) catch return null;
+ cwd.access(io, runtime, .{}) catch {
+ // The interface is here but its runtime is not, which is a packaging
+ // fault rather than a loose binary. Say so instead of silently
+ // showing the "start it yourself" page.
+ std.log.warn("the bundled interface has no runtime beside it", .{});
+ return null;
+ };
+
+ if (pidPath(arena, env)) |path| reap(gpa, io, path, runtime);
+
+ const port = freePort(io) orelse {
+ std.log.warn("no free port for the bundled interface", .{});
+ return null;
+ };
+
+ var port_buf: [8]u8 = undefined;
+ const port_text = std.fmt.bufPrint(&port_buf, "{d}", .{port}) catch return null;
+ env.put("PORT", port_text) catch return null;
+ // Loopback only. This server spawns processes and reads the disk on
+ // request; it is the app's own back end, not something to put on a
+ // network the machine happens to be on.
+ env.put("HOSTNAME", "127.0.0.1") catch return null;
+ env.put("GRAFF_BIN", harness) catch return null;
+ // Without this the workspace would default to the server's own cwd,
+ // which inside a bundle is a signed, read-only directory. An existing
+ // value wins: someone who pinned a workspace meant it.
+ if (env.get("GRAFF_CWD") == null) {
+ if (env.get("HOME")) |home| env.put("GRAFF_CWD", home) catch return null;
+ }
+
+ const child = std.process.spawn(io, .{
+ .argv = &.{ runtime, entry },
+ .cwd = .{ .path = ui },
+ .environ_map = env,
+ // Its own group, so one kill takes the server and every harness it
+ // started. Killing just the server would orphan those.
+ .pgid = 0,
+ }) catch |err| {
+ std.log.warn("the bundled interface did not start: {t}", .{err});
+ return null;
+ };
+ group = child.id orelse return null;
+
+ _ = atexit(&stop);
+ catchSignals();
+ if (pidPath(arena, env)) |path| remember(io, path, group);
+
+ if (!ready(io, port)) {
+ std.log.warn("the bundled interface did not answer on {d}", .{port});
+ stop();
+ return null;
+ }
+ return port;
+}
+
+/// Where the running server's group id is left for the next launch. A
+/// crash takes the atexit handler with it, so without this a killed shell
+/// would leave a server — and its harnesses — running for good.
+fn pidPath(arena: Allocator, env: *std.process.Environ.Map) ?[]const u8 {
+ const home = env.get("HOME") orelse return null;
+ return std.fmt.allocPrint(arena, "{s}/Library/Caches/dev.codegraff.native.pid", .{home}) catch null;
+}
+
+fn remember(io: Io, path: []const u8, pid: std.posix.pid_t) void {
+ var buf: [16]u8 = undefined;
+ const text = std.fmt.bufPrint(&buf, "{d}", .{pid}) catch return;
+ Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = text }) catch {};
+}
+
+/// Kill a server left behind by a previous run. Guarded by `ps`: pids are
+/// recycled, and killing a stranger's process group because it inherited
+/// an old number would be a genuinely bad bug.
+fn reap(gpa: Allocator, io: Io, path: []const u8, runtime: []const u8) void {
+ const text = Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(64)) catch return;
+ defer gpa.free(text);
+ const pid = std.fmt.parseInt(std.posix.pid_t, std.mem.trim(u8, text, " \t\r\n"), 10) catch return;
+ if (pid <= 1) return;
+
+ var buf: [16]u8 = undefined;
+ const arg = std.fmt.bufPrint(&buf, "{d}", .{pid}) catch return;
+ const seen = std.process.run(gpa, io, .{
+ .argv = &.{ "ps", "-o", "command=", "-p", arg },
+ .stdout_limit = .limited(8 * 1024),
+ .stderr_limit = .limited(8 * 1024),
+ }) catch return;
+ defer gpa.free(seen.stdout);
+ defer gpa.free(seen.stderr);
+ // Only ours: the command has to be the very runtime we are about to
+ // start, out of this same bundle.
+ if (std.mem.indexOf(u8, seen.stdout, runtime) == null) return;
+ std.posix.kill(-pid, .TERM) catch {};
+}
+
+/// A port nothing is bound to. Tested by binding it rather than by
+/// connecting to it: a port can refuse connections and still be taken.
+fn freePort(io: Io) ?u16 {
+ var port = first_port;
+ while (port < first_port + port_attempts) : (port += 1) {
+ const address = Io.net.IpAddress.parseIp4("127.0.0.1", port) catch return null;
+ var probe = Io.net.IpAddress.listen(&address, io, .{}) catch continue;
+ probe.deinit(io);
+ return port;
+ }
+ return null;
+}
+
+/// Wait for the server to answer. Polling a connect is the only honest
+/// signal: the child exists long before it is listening, and loading the
+/// window early just shows WebKit's connection error.
+fn ready(io: Io, port: u16) bool {
+ const address = Io.net.IpAddress.parseIp4("127.0.0.1", port) catch return false;
+ var waited: u64 = 0;
+ while (waited < boot_timeout_ms) : (waited += poll_ms) {
+ if (Io.net.IpAddress.connect(&address, io, .{ .mode = .stream })) |stream| {
+ stream.close(io);
+ return true;
+ } else |_| {}
+ Io.sleep(io, Io.Duration.fromMilliseconds(poll_ms), .awake) catch return false;
+ }
+ return false;
+}
diff --git a/apps/native/next.config.ts b/apps/native/next.config.ts
index 7f03cb19..237b7f48 100644
--- a/apps/native/next.config.ts
+++ b/apps/native/next.config.ts
@@ -2,6 +2,13 @@ import type { NextConfig } from "next";
const nextConfig: NextConfig = {
images: { unoptimized: true },
+ // The desktop app ships this interface inside its bundle, so the build has
+ // to produce a server that runs without the repository or a node_modules
+ // tree beside it.
+ output: "standalone",
+ // Without this the tracer walks up to the repository root and copies the
+ // Zig build outputs into the payload.
+ outputFileTracingRoot: __dirname,
// The app is opened at 127.0.0.1 (the desktop shell points there), which
// Next 16 treats as cross-origin for its dev resources unless it is
// listed here; without it hot reloading is refused.