graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Shut down the simulators a session booted when it ends (#407)
justrach5506365134d5
diff --git a/docs/adr/0300-a-session-shuts-down-the-simulators-it-booted.md b/docs/adr/0300-a-session-shuts-down-the-simulators-it-booted.mdnew file mode 100644index 00000000..6e009e41--- /dev/null+++ b/docs/adr/0300-a-session-shuts-down-the-simulators-it-booted.md@@ -0,0 +1,42 @@+# 0300. A session shuts down the simulators it booted++Status: accepted 2026-10-22++## Context++Agents verify iOS work with ad-hoc shell commands (`xcrun simctl boot`,+`xcodebuild test`, a project's run script). A device booted that way outlives+the command and the session: stopping the command's process group does not+shut a CoreSimulator device down. Finished runs left devices booted, their+apps running and the Simulator app open, and parallel verification tasks+accumulated them (#407). The in-repo iOS scripts that once guarded this have+left the repository.++## Decision++`sim_ledger.zig` brackets each shell command that looks like simulator work+with two `simctl list devices booted` snapshots. A device booted after the+command that was not booted before it belongs to the session and is recorded+under `~/.codegraff/simulators/<udid>/` with a lease naming the process+(`proc_identity` records). When the session ends, the job reaper shuts down+every recorded device that no live graff process holds a lease on, then+removes its record.++- A device already booted before the command is never recorded, so the+ user's own devices are left alone.+- Another graff session that runs simulator commands while a recorded device+ is booted takes its own lease; the last session to end shuts it down.+- A session that died leaves only dead leases; the next session to end shuts+ its devices down.+- The Simulator app is quit only when this session started it and no device+ remains booted.+- `GRAFF_KEEP_SIMULATORS=1` turns the ledger off.++## Consequences++Sessions that run simulator commands pay two `simctl` runs per such command+and a shutdown per device at exit. A snapshot cannot tell who booted a+device: one the user boots while a bracketed command runs is attributed to+the session, and a command with no simulator or iOS word in it (a script+named for something else) is not bracketed. Apps launched on a device the+user had already booted are not terminated.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 9acd6780..b6c15cb1 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -316,6 +316,7 @@ record only when you need the evidence or the edge cases.| [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. |+| [0300](0300-a-session-shuts-down-the-simulators-it-booted.md) | Shell commands that look like simulator work are bracketed by booted-device snapshots; devices a session booted are leased under `~/.codegraff/simulators/` and shut down when the last live leaseholder ends, never devices booted before. `GRAFF_KEEP_SIMULATORS=1` opts out. |## When to write onediff --git a/src/exec_bash.zig b/src/exec_bash.zigindex 36465a47..bef790a0 100644--- a/src/exec_bash.zig+++ b/src/exec_bash.zig@@ -383,8 +383,12 @@ pub fn exec(ctx: ToolCtx, call: tools.ToolCall) !ToolOutput {.clear => {},}};+ // #407: a simulator this command boots is shut down when the session ends.+ const sim_ledger = @import("sim_ledger.zig");+ const sim_bracket = if (approved) sim_ledger.g.before(ctx.gpa, ctx.io, cmd) else null;var result = try execUnchecked(ctx, call);errdefer ctx.gpa.free(result.text);+ if (sim_bracket) |b| sim_ledger.g.after(ctx.gpa, ctx.io, b, !result.pending);try @import("cli_path_hint.zig").append(ctx.gpa, ctx.io, cmd, &result);if (warning) {const text = try std.mem.concat(ctx.gpa, u8, &.{ server_port.unknown_warning, result.text });diff --git a/src/jobs.zig b/src/jobs.zigindex 62a50f90..b0e3e21a 100644--- a/src/jobs.zig+++ b/src/jobs.zig@@ -549,6 +549,7 @@ pub fn jobsReap(gpa: Allocator, io: Io) void {for (jobs) |job| freeJob(gpa, io, job);gpa.free(jobs);// toOwnedSlice already emptied the pool; deinit would poison reuse.+ _ = @import("sim_ledger.zig").g.release(gpa, io); // #407: after the jobs that may use them}test { // split-out modules: unreferenced, their tests silently never rundiff --git a/src/sim_ledger.zig b/src/sim_ledger.zignew file mode 100644index 00000000..b5a3f6c1--- /dev/null+++ b/src/sim_ledger.zig@@ -0,0 +1,362 @@+//! Simulator devices a session boots are shut down when it ends (#407).+//!+//! Agents verify iOS work with ad-hoc shell commands (`xcrun simctl boot`,+//! `xcodebuild test`, a project's run script). A device booted that way+//! outlives the command and the session: stopping the command's process+//! group does not shut a CoreSimulator device down. Finished runs left+//! devices booted with their apps running and the Simulator app open, and+//! parallel verification tasks piled them up.+//!+//! A shell command that looks like simulator work (`relevant`) is bracketed+//! by two snapshots of the booted devices. A device booted after the command+//! that was not booted before it is this session's: graff records it under+//! `~/.codegraff/simulators/<udid>/` with a lease naming this process. When+//! the session ends (`release`, from the job reaper), each recorded device+//! with no live lease left is shut down and its record removed.+//!+//! - A device that was already booted is never recorded, so the user's own+//! devices are never shut down.+//! - Another live graff session that runs simulator commands while a+//! recorded device is booted takes a lease on it too. The device stays up+//! until the last of them ends.+//! - A session that died without releasing leaves a dead lease; the next+//! session to end shuts that device down.+//! - The Simulator app is quit only when this session started it and no+//! device is booted any more.+//! - `GRAFF_KEEP_SIMULATORS=1` turns all of this off.+//!+//! A snapshot cannot tell who booted a device. One the user boots while a+//! bracketed command runs is attributed to that command, and a command that+//! does not look like simulator work is not bracketed.++const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const proc_identity = @import("proc_identity.zig");++pub const keep_env = "GRAFF_KEEP_SIMULATORS";+pub const records_subdir = ".codegraff/simulators";+const booted_by = "booted-by";+const lease_prefix = "lease-";++/// A CoreSimulator UDID: a UUID, used as a directory name and an argument,+/// so anything else is rejected.+pub const Udid = [36]u8;++pub fn parseUdid(text: []const u8) ?Udid {+ if (text.len != 36) return null;+ for (text, 0..) |c, i| {+ const dash = i == 8 or i == 13 or i == 18 or i == 23;+ if (dash != (c == '-')) return null;+ if (!dash and !std.ascii.isHex(c)) return null;+ }+ return text[0..36].*;+}++/// One host command's outcome. `code` is null when it did not run or did not+/// exit normally. `stdout` is gpa-owned.+pub const Run = struct { code: ?u8, stdout: []const u8 };+pub const Runner = *const fn (gpa: Allocator, io: Io, argv: []const []const u8) Run;+pub const Liveness = *const fn (io: Io, rec: proc_identity.Record) bool;++fn hostRun(gpa: Allocator, io: Io, argv: []const []const u8) Run {+ const run = @import("process_runner.zig").runCapped(gpa, io, argv, 1 << 20, 4096, 60_000) catch+ return .{ .code = null, .stdout = &.{} };+ gpa.free(run.stderr);+ const code: ?u8 = switch (run.term) {+ .exited => |c| if (run.timed_out or run.cancelled) null else c,+ else => null,+ };+ return .{ .code = code, .stdout = run.stdout };+}++fn isLive(io: Io, rec: proc_identity.Record) bool {+ return proc_identity.stateOf(io, rec) == .held;+}++/// Whether a shell command looks like simulator work. Bracketing costs two+/// `simctl` runs, so ordinary commands are not.+pub fn relevant(cmd: []const u8) bool {+ for ([_][]const u8{ "simctl", "simulator", "xcodebuild" }) |needle| {+ if (@import("util.zig").indexOfIgnoreCase(cmd, needle) != null) return true;+ }+ // Whole words only: "ios" is in "scenarios".+ var words = std.mem.tokenizeAny(u8, cmd, " \t\r\n/._-:=,;'\"()[]{}|&<>$`");+ while (words.next()) |word| {+ for ([_][]const u8{ "ios", "iphone", "ipad", "watchos", "tvos", "visionos", "xros" }) |w| {+ if (std.ascii.eqlIgnoreCase(word, w)) return true;+ }+ }+ return false;+}++pub const Gui = enum { running, stopped, unknown };++/// What `before` saw, handed back to `after`.+pub const Bracket = struct { gui: Gui };++pub const Ledger = struct {+ /// Absolute records directory; empty turns the ledger off.+ root: []const u8 = "",+ run: Runner = hostRun,+ live: Liveness = isLive,+ self: proc_identity.Record = .{},+ mutex: Io.Mutex = .init,+ /// Devices seen booted before a bracketed command: never this session's.+ foreign: std.ArrayList(Udid) = .empty,+ /// A bracketed command was still running when its tool call returned.+ pending: bool = false,+ pending_gui: Gui = .unknown,+ gui_started: bool = false,++ fn enabled(l: *const Ledger) bool {+ return l.root.len != 0; // `init` sets it on macOS only+ }++ /// Snapshot before a shell command. Null when the command is not+ /// simulator work or the snapshot failed: nothing is attributed then.+ pub fn before(l: *Ledger, gpa: Allocator, io: Io, cmd: []const u8) ?Bracket {+ if (!l.enabled() or !relevant(cmd)) return null;+ l.mutex.lockUncancelable(io);+ defer l.mutex.unlock(io);+ const booted = l.snapshot(gpa, io) orelse return null;+ defer gpa.free(booted);+ for (booted) |u| {+ // A device a graff session booted: this one now uses it as well.+ if (l.recorded(io, u)) l.lease(io, u) else l.addForeign(gpa, u);+ }+ return .{ .gui = l.gui(gpa, io) };+ }++ /// Snapshot after the command; record the devices it booted. `finished`+ /// is false when the command is still running in the background.+ pub fn after(l: *Ledger, gpa: Allocator, io: Io, bracket: Bracket, finished: bool) void {+ l.mutex.lockUncancelable(io);+ defer l.mutex.unlock(io);+ l.attribute(gpa, io);+ if (bracket.gui == .stopped and l.gui(gpa, io) == .running) l.gui_started = true;+ if (!finished) {+ l.pending = true;+ if (bracket.gui == .stopped) l.pending_gui = .stopped;+ }+ }++ fn attribute(l: *Ledger, gpa: Allocator, io: Io) void {+ const booted = l.snapshot(gpa, io) orelse return;+ defer gpa.free(booted);+ for (booted) |u| {+ if (l.isForeign(u) or l.recorded(io, u)) continue;+ l.record(io, u);+ }+ }++ /// Session end: shut down every recorded device no live session holds.+ /// Returns how many devices were shut down.+ pub fn release(l: *Ledger, gpa: Allocator, io: Io) usize {+ if (!l.enabled()) return 0;+ l.mutex.lockUncancelable(io);+ defer l.mutex.unlock(io);+ defer {+ l.foreign.clearAndFree(gpa);+ l.pending = false;+ l.pending_gui = .unknown;+ l.gui_started = false;+ }+ if (l.pending) {+ // A command that outlived its tool call may have booted more.+ l.attribute(gpa, io);+ if (l.pending_gui == .stopped and l.gui(gpa, io) == .running) l.gui_started = true;+ }+ var shut: usize = 0;+ const records = l.listRecords(gpa, io);+ defer gpa.free(records);+ if (records.len != 0) {+ const booted = l.snapshot(gpa, io);+ defer if (booted) |b| gpa.free(b);+ for (records) |u| {+ l.unlease(io, u);+ if (l.heldByOther(io, u)) continue;+ const up = if (booted) |b| contains(b, u) else true;+ if (up) {+ // Without a snapshot the device may still be up: keep its+ // record so a later session retries.+ if (booted == null) continue;+ const r = l.run(gpa, io, &.{ "xcrun", "simctl", "shutdown", &u });+ gpa.free(r.stdout);+ if (r.code != 0) continue;+ shut += 1;+ }+ l.forget(io, u);+ }+ }+ if (l.gui_started) {+ const left = l.snapshot(gpa, io);+ defer if (left) |b| gpa.free(b);+ if (left != null and left.?.len == 0) {+ const r = l.run(gpa, io, &.{ "pkill", "-x", "Simulator" });+ gpa.free(r.stdout);+ }+ }+ return shut;+ }++ fn snapshot(l: *Ledger, gpa: Allocator, io: Io) ?[]Udid {+ const r = l.run(gpa, io, &.{ "xcrun", "simctl", "list", "devices", "booted", "-j" });+ defer gpa.free(r.stdout);+ if (r.code != 0) return null;+ return parseBooted(gpa, r.stdout) catch null;+ }++ fn gui(l: *Ledger, gpa: Allocator, io: Io) Gui {+ const r = l.run(gpa, io, &.{ "pgrep", "-x", "Simulator" });+ gpa.free(r.stdout);+ return if (r.code == 0) .running else if (r.code == 1) .stopped else .unknown;+ }++ fn addForeign(l: *Ledger, gpa: Allocator, u: Udid) void {+ if (l.isForeign(u)) return;+ l.foreign.append(gpa, u) catch {};+ }++ fn isForeign(l: *const Ledger, u: Udid) bool {+ return contains(l.foreign.items, u);+ }++ fn rootDir(l: *const Ledger, io: Io) ?Io.Dir {+ return Io.Dir.cwd().openDir(io, l.root, .{ .iterate = true }) catch null;+ }++ fn recorded(l: *const Ledger, io: Io, u: Udid) bool {+ var root = l.rootDir(io) orelse return false;+ defer root.close(io);+ var dir = root.openDir(io, &u, .{}) catch return false;+ dir.close(io);+ return true;+ }++ fn stamp(l: *const Ledger, buf: *[proc_identity.record_max]u8) []const u8 {+ return proc_identity.formatRecord(buf, l.self);+ }++ fn leaseName(l: *const Ledger, buf: *[32]u8) []const u8 {+ return std.fmt.bufPrint(buf, lease_prefix ++ "{d}", .{l.self.pid}) catch unreachable;+ }++ fn record(l: *Ledger, io: Io, u: Udid) void {+ Io.Dir.cwd().createDirPath(io, l.root) catch return;+ var root = l.rootDir(io) orelse return;+ defer root.close(io);+ root.createDirPath(io, &u) catch return;+ var dir = root.openDir(io, &u, .{}) catch return;+ defer dir.close(io);+ var buf: [proc_identity.record_max]u8 = undefined;+ dir.writeFile(io, .{ .sub_path = booted_by, .data = l.stamp(&buf) }) catch {};+ l.leaseIn(io, dir);+ }++ fn lease(l: *Ledger, io: Io, u: Udid) void {+ var root = l.rootDir(io) orelse return;+ defer root.close(io);+ var dir = root.openDir(io, &u, .{}) catch return;+ defer dir.close(io);+ l.leaseIn(io, dir);+ }++ fn leaseIn(l: *Ledger, io: Io, dir: Io.Dir) void {+ var name_buf: [32]u8 = undefined;+ var buf: [proc_identity.record_max]u8 = undefined;+ dir.writeFile(io, .{ .sub_path = l.leaseName(&name_buf), .data = l.stamp(&buf) }) catch {};+ }++ fn unlease(l: *Ledger, io: Io, u: Udid) void {+ var root = l.rootDir(io) orelse return;+ defer root.close(io);+ var dir = root.openDir(io, &u, .{}) catch return;+ defer dir.close(io);+ var name_buf: [32]u8 = undefined;+ dir.deleteFile(io, l.leaseName(&name_buf)) catch {};+ }++ /// A lease from a live process other than this one.+ fn heldByOther(l: *Ledger, io: Io, u: Udid) bool {+ var root = l.rootDir(io) orelse return false;+ defer root.close(io);+ var dir = root.openDir(io, &u, .{ .iterate = true }) catch return false;+ defer dir.close(io);+ var it = dir.iterate();+ while (it.next(io) catch return true) |entry| {+ if (!std.mem.startsWith(u8, entry.name, lease_prefix)) continue;+ const rec = proc_identity.readOwnerFile(io, dir, entry.name) orelse continue;+ if (rec.pid == l.self.pid) continue;+ if (l.live(io, rec)) return true;+ }+ return false;+ }++ fn forget(l: *Ledger, io: Io, u: Udid) void {+ var root = l.rootDir(io) orelse return;+ defer root.close(io);+ root.deleteTree(io, &u) catch {};+ }++ pub fn listRecords(l: *Ledger, gpa: Allocator, io: Io) []const Udid {+ var out: std.ArrayList(Udid) = .empty;+ var root = l.rootDir(io) orelse return out.toOwnedSlice(gpa) catch &.{};+ defer root.close(io);+ var it = root.iterate();+ while (it.next(io) catch null) |entry| {+ if (entry.kind != .directory) continue;+ const u = parseUdid(entry.name) orelse continue;+ out.append(gpa, u) catch break;+ }+ return out.toOwnedSlice(gpa) catch &.{};+ }++ pub fn deinit(l: *Ledger, gpa: Allocator) void {+ l.foreign.deinit(gpa);+ }+};++fn contains(list: []const Udid, u: Udid) bool {+ for (list) |item| if (std.mem.eql(u8, &item, &u)) return true;+ return false;+}++/// The booted devices in `xcrun simctl list devices booted -j` output.+pub fn parseBooted(gpa: Allocator, text: []const u8) ![]Udid {+ const parsed = try std.json.parseFromSlice(std.json.Value, gpa, text, .{});+ defer parsed.deinit();+ if (parsed.value != .object) return error.BadSimctlList;+ const devices = parsed.value.object.get("devices") orelse return error.BadSimctlList;+ if (devices != .object) return error.BadSimctlList;+ var out: std.ArrayList(Udid) = .empty;+ errdefer out.deinit(gpa);+ var runtimes = devices.object.iterator();+ while (runtimes.next()) |runtime| {+ if (runtime.value_ptr.* != .array) continue;+ for (runtime.value_ptr.array.items) |device| {+ if (device != .object) continue;+ const state = device.object.get("state") orelse continue;+ if (state != .string or !std.mem.eql(u8, state.string, "Booted")) continue;+ const udid = device.object.get("udid") orelse continue;+ if (udid != .string) continue;+ try out.append(gpa, parseUdid(udid.string) orelse continue);+ }+ }+ return out.toOwnedSlice(gpa);+}++/// The process's ledger, on once startup knows HOME (`init`).+pub var g: Ledger = .{};++pub fn init(arena: Allocator, io: Io, home: []const u8, environ_map: anytype) void {+ if (builtin.os.tag != .macos or home.len == 0) return;+ if (environ_map.get(keep_env)) |v| if (!std.mem.eql(u8, v, "0")) return;+ g.root = std.fmt.allocPrint(arena, "{s}/" ++ records_subdir, .{std.mem.trimEnd(u8, home, "/")}) catch return;+ g.self = proc_identity.selfRecord(io);+}++test {+ _ = @import("sim_ledger_tests.zig");+}diff --git a/src/sim_ledger_tests.zig b/src/sim_ledger_tests.zignew file mode 100644index 00000000..7fb21ad8--- /dev/null+++ b/src/sim_ledger_tests.zig@@ -0,0 +1,264 @@+//! Tests for sim_ledger.zig (#407) against a fake host: no real simulator,+//! `simctl`, `pgrep` or `pkill` is ever run.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const proc_identity = @import("proc_identity.zig");+const sim = @import("sim_ledger.zig");+const Ledger = sim.Ledger;+const Udid = sim.Udid;+const Run = sim.Run;+const relevant = sim.relevant;+const parseBooted = sim.parseBooted;++const testing = std.testing;++const A = "AAAAAAAA-0000-4000-8000-00000000000A".*; // the user's own device+const B = "BBBBBBBB-0000-4000-8000-00000000000B".*;++/// The host as `simctl`, `pgrep` and `pkill` see it.+const Host = struct {+ var booted: [8]Udid = undefined;+ var n: usize = 0;+ var gui: bool = false;+ /// What the bracketed command does: booted on the first list after it starts.+ var boots: ?Udid = null;+ var opens_gui = false;+ var lists: usize = 0;+ var fail_list = false;+ var dead_pid: i32 = 0;+ var log_buf: [512]u8 = undefined;+ var log_len: usize = 0;++ fn reset(devices: []const Udid) void {+ @memcpy(booted[0..devices.len], devices);+ n = devices.len;+ gui = false;+ boots = null;+ opens_gui = false;+ lists = 0;+ fail_list = false;+ dead_pid = 0;+ log_len = 0;+ }++ fn log() []const u8 {+ return log_buf[0..log_len];+ }++ fn note(comptime fmt: []const u8, args: anytype) void {+ const s = std.fmt.bufPrint(log_buf[log_len..], fmt, args) catch return;+ log_len += s.len;+ }++ /// Each bracket lists twice (before, after): the command runs between.+ fn commandRuns() void {+ if (boots) |u| {+ booted[n] = u;+ n += 1;+ boots = null;+ }+ if (opens_gui) gui = true;+ opens_gui = false;+ }++ fn run(gpa: Allocator, io: Io, argv: []const []const u8) Run {+ _ = io;+ const empty: []const u8 = &.{};+ if (std.mem.eql(u8, argv[0], "pgrep")) return .{ .code = if (gui) 0 else 1, .stdout = empty };+ if (std.mem.eql(u8, argv[0], "pkill")) {+ gui = false;+ note("quit Simulator\n", .{});+ return .{ .code = 0, .stdout = empty };+ }+ if (std.mem.eql(u8, argv[2], "shutdown")) {+ for (booted[0..n], 0..) |u, i| if (std.mem.eql(u8, &u, argv[3])) {+ booted[i] = booted[n - 1];+ n -= 1;+ break;+ };+ note("shutdown {s}\n", .{argv[3][0..8]});+ return .{ .code = 0, .stdout = empty };+ }+ // list devices booted -j+ if (fail_list) return .{ .code = null, .stdout = &.{} };+ var aw: Io.Writer.Allocating = .init(gpa);+ aw.writer.writeAll("{\"devices\":{\"com.apple.CoreSimulator.SimRuntime.iOS-18-0\":[") catch unreachable;+ for (booted[0..n], 0..) |u, i| aw.writer.print("{s}{{\"udid\":\"{s}\",\"state\":\"Booted\",\"name\":\"iPhone\"}}", .{ if (i == 0) "" else ",", &u }) catch unreachable;+ aw.writer.writeAll("],\"com.apple.CoreSimulator.SimRuntime.watchOS-11-0\":[{\"udid\":\"CCCCCCCC-0000-4000-8000-00000000000C\",\"state\":\"Shutdown\"}]}}") catch unreachable;+ lists += 1;+ return .{ .code = 0, .stdout = aw.toOwnedSlice() catch unreachable };+ }++ fn live(io: Io, rec: proc_identity.Record) bool {+ _ = io;+ return rec.pid != dead_pid;+ }+};++fn testLedger(root: []const u8, pid: i32) Ledger {+ return .{ .root = root, .run = Host.run, .live = Host.live, .self = .{ .pid = pid, .start_id = 1 } };+}++/// One bracketed shell command on `l`: snapshot, the command, snapshot.+fn bracketed(l: *Ledger, cmd: []const u8, finished: bool) void {+ const b = l.before(testing.allocator, testing.io, cmd) orelse return;+ Host.commandRuns();+ l.after(testing.allocator, testing.io, b, finished);+}++fn tmpRoot(tmp: *std.testing.TmpDir, buf: *[std.fs.max_path_bytes]u8) ![]const u8 {+ const len = try tmp.dir.realPath(testing.io, buf);+ return buf[0..len];+}++test "#407: simulator work is recognized by the command, not every command" {+ for ([_][]const u8{ "xcrun simctl boot 'iPhone 16'", "open -a Simulator", "xcodebuild test -scheme App -destination 'platform=iOS Simulator,name=iPhone 16'", "./apps/ios/build-sim.sh", "npx react-native run-ios", "npm run ios", "flutter run -d iPhone" }) |cmd|+ try testing.expect(relevant(cmd));+ for ([_][]const u8{ "zig build test", "cat scenarios.md", "git status", "ls bios/" }) |cmd|+ try testing.expect(!relevant(cmd));+}++test "#407: simctl's booted list parses to UDIDs, and only booted ones" {+ const text =+ \\{"devices":{"rt.iOS":[{"udid":"AAAAAAAA-0000-4000-8000-00000000000A","state":"Booted"},{"udid":"../../etc","state":"Booted"},{"udid":"BBBBBBBB-0000-4000-8000-00000000000B","state":"Shutdown"}],"rt.watch":[]}}+ ;+ const got = try parseBooted(testing.allocator, text);+ defer testing.allocator.free(got);+ try testing.expectEqual(@as(usize, 1), got.len);+ try testing.expectEqualStrings(&A, &got[0]);+}++test "#407: a finished run shuts down the device it booted and not the user's" {+ var tmp = testing.tmpDir(.{});+ defer tmp.cleanup();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ var l = testLedger(try tmpRoot(&tmp, &buf), 101);+ defer l.deinit(testing.allocator);+ Host.reset(&.{A});+ Host.gui = true; // the user already has the Simulator app open+ Host.boots = B;+ bracketed(&l, "xcrun simctl boot BBBBBBBB-0000-4000-8000-00000000000B", true);+ bracketed(&l, "xcrun simctl install booted App.app && xcrun simctl launch booted com.example.app", true);+ try testing.expectEqual(@as(usize, 1), l.release(testing.allocator, testing.io));+ try testing.expectEqualStrings("shutdown BBBBBBBB\n", Host.log());+ try testing.expectEqual(@as(usize, 1), Host.n);+ try testing.expectEqualStrings(&A, &Host.booted[0]);+ try testing.expect(Host.gui);+ const left = l.listRecords(testing.allocator, testing.io);+ defer testing.allocator.free(left);+ try testing.expectEqual(@as(usize, 0), left.len);+}++test "#407: the Simulator app a run opened is quit once no device is left" {+ var tmp = testing.tmpDir(.{});+ defer tmp.cleanup();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ var l = testLedger(try tmpRoot(&tmp, &buf), 101);+ defer l.deinit(testing.allocator);+ Host.reset(&.{});+ Host.boots = B;+ Host.opens_gui = true;+ bracketed(&l, "xcrun simctl boot B && open -a Simulator", true);+ try testing.expectEqual(@as(usize, 1), l.release(testing.allocator, testing.io));+ try testing.expectEqualStrings("shutdown BBBBBBBB\nquit Simulator\n", Host.log());+ try testing.expect(!Host.gui);+}++test "#407: a device another live session uses stays up until the last one ends" {+ var tmp = testing.tmpDir(.{});+ defer tmp.cleanup();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const root = try tmpRoot(&tmp, &buf);+ var first = testLedger(root, 101);+ defer first.deinit(testing.allocator);+ var second = testLedger(root, 102);+ defer second.deinit(testing.allocator);+ Host.reset(&.{});+ Host.boots = B;+ bracketed(&first, "xcrun simctl boot B", true);+ bracketed(&second, "xcodebuild test -destination 'platform=iOS Simulator,id=B'", true);+ try testing.expectEqual(@as(usize, 0), first.release(testing.allocator, testing.io));+ try testing.expectEqualStrings("", Host.log());+ try testing.expectEqual(@as(usize, 1), second.release(testing.allocator, testing.io));+ try testing.expectEqualStrings("shutdown BBBBBBBB\n", Host.log());+}++test "#407: a dead session's device is shut down by the next session to end" {+ var tmp = testing.tmpDir(.{});+ defer tmp.cleanup();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const root = try tmpRoot(&tmp, &buf);+ var crashed = testLedger(root, 101);+ defer crashed.deinit(testing.allocator);+ Host.reset(&.{A});+ Host.boots = B;+ bracketed(&crashed, "xcrun simctl boot B", true);+ Host.dead_pid = 101; // it never released+ var later = testLedger(root, 103); // ran no simulator command at all+ defer later.deinit(testing.allocator);+ try testing.expectEqual(@as(usize, 1), later.release(testing.allocator, testing.io));+ try testing.expectEqualStrings("shutdown BBBBBBBB\n", Host.log());+}++test "#407: without a snapshot before the command nothing is attributed" {+ var tmp = testing.tmpDir(.{});+ defer tmp.cleanup();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ var l = testLedger(try tmpRoot(&tmp, &buf), 101);+ defer l.deinit(testing.allocator);+ Host.reset(&.{A});+ Host.fail_list = true;+ try testing.expect(l.before(testing.allocator, testing.io, "xcrun simctl boot B") == null);+ Host.fail_list = false;+ try testing.expectEqual(@as(usize, 0), l.release(testing.allocator, testing.io));+ try testing.expectEqualStrings("", Host.log());+}++test "#407: a device a backgrounded command boots later is still the session's" {+ var tmp = testing.tmpDir(.{});+ defer tmp.cleanup();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ var l = testLedger(try tmpRoot(&tmp, &buf), 101);+ defer l.deinit(testing.allocator);+ Host.reset(&.{A});+ const b = l.before(testing.allocator, testing.io, "xcodebuild test -destination 'platform=iOS Simulator,name=iPhone 16'").?;+ l.after(testing.allocator, testing.io, b, false); // parked, nothing booted yet+ Host.booted[1] = B; // the parked job boots it later+ Host.n = 2;+ try testing.expectEqual(@as(usize, 1), l.release(testing.allocator, testing.io));+ try testing.expectEqualStrings("shutdown BBBBBBBB\n", Host.log());+}++test "#407: a shell command that boots a simulator has it shut down when the session's jobs are reaped" {+ var tmp = testing.tmpDir(.{});+ defer tmp.cleanup();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const saved = sim.g;+ defer sim.g = saved;+ sim.g = testLedger(try tmpRoot(&tmp, &buf), 101);+ defer sim.g.deinit(testing.allocator);+ Host.reset(&.{A});+ Host.boots = B; // the fake host boots B while the command runs+ const tools = @import("tools.zig");+ const input = try std.json.parseFromSlice(std.json.Value, testing.allocator, "{\"command\":\"echo xcrun simctl boot\"}", .{});+ defer input.deinit();+ const ctx: tools.ToolCtx = .{ .gpa = testing.allocator, .io = testing.io, .client = undefined, .provider = undefined, .registry = null, .from_sub = true, .approvals = null, .tracer = null };+ // The before snapshot is the first list; the command "boots" B by the next.+ const saved_run = sim.g.run;+ sim.g.run = struct {+ fn run(gpa: Allocator, io: Io, argv: []const []const u8) Run {+ const r = Host.run(gpa, io, argv);+ if (Host.lists == 1) Host.commandRuns();+ return r;+ }+ }.run;+ defer sim.g.run = saved_run;+ const out = try @import("exec_bash.zig").exec(ctx, .{ .id = "c", .name = "bash", .input = input.value });+ defer testing.allocator.free(out.text);+ try testing.expect(!out.is_error);+ @import("jobs.zig").jobsReap(testing.allocator, testing.io);+ try testing.expectEqualStrings("shutdown BBBBBBBB\n", Host.log());+ try testing.expectEqual(@as(usize, 1), Host.n);+}diff --git a/src/startup.zig b/src/startup.zigindex a24a8c31..2343c0a0 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -281,6 +281,7 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process// the login flow writes instead of "/.kimi/...".oauth.initHome(keys_cli.homeEnv(init.environ_map) orelse "");job_registry.home = keys_cli.homeEnv(init.environ_map) orelse ""; // #199: ownership records for background jobs+ @import("sim_ledger.zig").init(arena, io, keys_cli.homeEnv(init.environ_map) orelse "", init.environ_map); // #407// #1267: tool children get graff's environment minus its credentials.// After router_config.load (its key is one of them), before `serve` and// the other subcommands below can spawn a tool.diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex fcc79cd7..ce1e6b44 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -404,6 +404,7 @@ test {_ = @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("sim_ledger.zig"); // #407: sessions shut down the simulators they booted_ = @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