graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(tui): run /compact, !cmd and the @-file list off the render thread
Rach Pradhan800633074194
diff --git a/TUI/app.zig b/TUI/app.zigindex 8ef3f2e8..362fd506 100644--- a/TUI/app.zig+++ b/TUI/app.zig@@ -32,6 +32,9 @@ pub const Model = struct {steer_queue: std.array_list.Managed([]const u8),images: std.array_list.Managed([]const u8),pending: ?*engine.Job = null,+ /// A background engine op (/compact, !cmd, @-file list) — same thread ++ /// done-flag contract as `pending`, so neither can freeze the loop (#533).+ bg: ?*engine.BgOp = null,screen: Screen = .welcome,focus: Focus = .prompt,@@ -115,6 +118,9 @@ pub const Model = struct {if (self.pending) |job| {if (!job.threaded or job.done.load(.acquire)) self.destroyJob(job) else self.pending = null;}+ if (self.bg) |op| {+ if (!op.threaded or op.done.load(.acquire)) @import("bgop.zig").reap(self) else self.bg = null;+ }for (self.history.items) |e| self.alloc.free(e.text);self.history.deinit();for (self.prompt_hist.items) |s| self.alloc.free(s);diff --git a/TUI/bgop.zig b/TUI/bgop.zignew file mode 100644index 00000000..4bc82f71--- /dev/null+++ b/TUI/bgop.zig@@ -0,0 +1,263 @@+//! Background engine ops. `/compact`, `!cmd` and the @-file list used to call+//! straight into the engine from keys.handle, i.e. from inside run.zig's byte+//! parse loop: no render, no poll, no key handling, no cancel for the whole+//! round trip — a 5-60 s freeze indistinguishable from a hang (#533).+//!+//! They now take the same route a model turn takes (turn.zig): one thread, one+//! done flag, polled from the top of the loop. Nothing here reimplements+//! engine behavior — each op is exactly one engine callback, moved off the+//! render+input thread, with the result applied on the main thread.++const std = @import("std");++const app = @import("app.zig");+const engine = @import("engine.zig");+const turn = @import("turn.zig");+const Model = app.Model;+const Op = engine.BgOp;++/// Spawn `kind` in the background, taking ownership of `turns` and `cmd`.+/// A non-empty `label` pushes a live row so the wait is visible. Returns false+/// when a turn or another op already holds the engine — the caller still owns+/// its inputs then.+pub fn start(self: *Model, kind: Op.Kind, turns: []engine.Turn, cmd: []const u8, label: []const u8) bool {+ if (self.bg != null or self.pending != null) return false;+ const op = self.alloc.create(Op) catch return false;+ op.* = .{ .kind = kind, .gpa = self.alloc, .turns = turns, .cmd = cmd };+ if (label.len > 0) self.push(.pending, label) catch {};+ self.bg = op;+ if (std.Thread.spawn(.{}, engine.bgRun, .{op})) |th| {+ op.thread = th;+ } else |_| {+ // No thread available: run it inline rather than dropping the command.+ op.threaded = false;+ engine.bgRun(op);+ }+ return true;+}++/// Esc / Ctrl+C during an op. The engine-side cancel is the same one a turn+/// uses: process_runner kills a running `!cmd` child within 200 ms, and the+/// compaction request's stall watchdogs abort between polls.+pub fn cancel(self: *Model) void {+ const op = self.bg orelse return;+ if (op.cancelled) return;+ op.cancelled = true;+ if (engine.g_cancel_fn) |f| f(engine.g_turn_ctx);+}++/// Apply a finished op on the main thread. No-op while it is still running.+pub fn finish(self: *Model) void {+ const op = self.bg orelse return;+ if (!op.done.load(.acquire)) return;+ if (op.threaded) op.thread.join();+ op.threaded = false; // release() must not join a second time+ _ = turn.removePendingRows(self);+ switch (op.kind) {+ .compact => applyCompact(self, op),+ .bash => applyBash(self, op),+ .files => applyFiles(self, op),+ }+ release(self, op);+ self.scroll = 0;+ self.follow = true;+}++/// Free a finished op without applying it — Model.deinit's path.+pub fn reap(self: *Model) void {+ const op = self.bg orelse return;+ release(self, op);+}++/// Give up on an op whose thread ignored the cancel. Everything it owns is+/// leaked on purpose: the detached worker still writes into it. Callers exit+/// the process straight after (same contract as turn.abandonJob).+pub fn abandon(self: *Model) void {+ self.bg = null;+}++/// One step of the quit-time settle, mirroring turn.quitStep so run.zig can+/// wait for a turn and an op with a single deadline.+pub fn quitStep(self: *Model, elapsed_ms: u64) turn.QuitStep {+ const op = self.bg orelse return .reap;+ if (!op.threaded or op.done.load(.acquire)) return .reap;+ return if (elapsed_ms >= turn.quit_drain_ms) .abandon else .wait;+}++/// True while the @-file list is still loading, so the picker can say so+/// instead of claiming there is no file list.+pub fn loadingFiles(self: *const Model) bool {+ const op = self.bg orelse return false;+ return op.kind == .files;+}++fn release(self: *Model, op: *Op) void {+ if (op.threaded) op.thread.join();+ for (op.turns) |t| self.alloc.free(t.text);+ if (op.turns.len > 0) self.alloc.free(op.turns);+ if (op.cmd.len > 0) self.alloc.free(op.cmd);+ if (op.compact.note.len > 0) self.alloc.free(op.compact.note);+ for (op.compact.turns) |t| self.alloc.free(t.text);+ if (op.compact.turns.len > 0) self.alloc.free(op.compact.turns);+ if (op.text) |t| self.alloc.free(t);+ self.alloc.destroy(op);+ self.bg = null;+}++fn applyCompact(self: *Model, op: *Op) void {+ if (!op.ok) {+ const why: []const u8 = if (op.cancelled)+ "compaction cancelled, history unchanged"+ else if (op.compact.note.len > 0)+ op.compact.note+ else+ "compaction failed, history unchanged";+ self.push(.system, why) catch {};+ return;+ }+ self.clearHistory();+ if (op.compact.note.len > 0) self.push(.system, op.compact.note) catch {};+ for (op.compact.turns) |t| {+ self.push(switch (t.role) {+ .user => .user,+ .assistant => .assistant,+ }, t.text) catch {};+ }+}++fn applyBash(self: *Model, op: *Op) void {+ if (op.text) |out| {+ self.push(.system, @import("dispatch.zig").lastLines(out, 40)) catch {};+ } else if (op.cancelled) {+ self.push(.system, "■ interrupted") catch {};+ } else {+ self.push(.err, "command failed to start") catch {};+ }+}++fn applyFiles(self: *Model, op: *Op) void {+ if (self.files_cache != null) return;+ const t = op.text orelse return;+ self.files_cache = self.alloc.dupe(u8, t) catch null;+}++const testing = std.testing;++fn drain(m: *Model) !void {+ var spins: usize = 0;+ while (m.bg) |op| {+ if (op.done.load(.acquire)) break;+ spins += 1;+ if (spins > 1_000_000) return error.OpNeverFinished;+ std.Thread.yield() catch {};+ }+ finish(m);+}++test "a bash op runs off the render thread and its output lands in the scrollback (#533)" {+ engine.g_bash_fn = struct {+ fn f(_: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8) ?[]const u8 {+ return std.fmt.allocPrint(gpa, "ran: {s}", .{cmd}) catch null;+ }+ }.f;+ defer engine.g_bash_fn = null;+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ const cmd = try testing.allocator.dupe(u8, "git status");+ try testing.expect(start(&m, .bash, &.{}, cmd, "running"));+ // The op is in flight: the model is usable and a live row is showing.+ try testing.expect(m.bg != null);+ try testing.expectEqual(app.EntryKind.pending, m.history.items[0].kind);+ try drain(&m);+ try testing.expect(m.bg == null);+ for (m.history.items) |e| try testing.expect(e.kind != .pending);+ try testing.expectEqualStrings("ran: git status", m.history.items[m.history.items.len - 1].text);+}++test "a compact op replaces the history only when the engine says it worked (#533)" {+ engine.g_compact_fn = struct {+ fn f(_: ?*anyopaque, gpa: std.mem.Allocator, history: []const engine.Turn, out: *engine.CompactOut) bool {+ if (history.len == 0) return false;+ var turns = gpa.alloc(engine.Turn, 1) catch return false;+ turns[0] = .{ .role = .user, .text = gpa.dupe(u8, "summary") catch return false };+ out.turns = turns;+ out.note = gpa.dupe(u8, "history compacted") catch "";+ return true;+ }+ }.f;+ defer engine.g_compact_fn = null;+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ try m.push(.user, "one");+ try m.push(.assistant, "two");+ const turns = try testing.allocator.alloc(engine.Turn, 1);+ turns[0] = .{ .role = .user, .text = try testing.allocator.dupe(u8, "one") };+ try testing.expect(start(&m, .compact, turns, "", "compacting"));+ try drain(&m);+ try testing.expect(m.bg == null);+ try testing.expectEqualStrings("history compacted", m.history.items[0].text);+ try testing.expectEqualStrings("summary", m.history.items[1].text);+ try testing.expectEqual(@as(usize, 2), m.history.items.len);+}++test "a second op is refused while one is in flight, and Esc cancels the live one" {+ const Gate = struct {+ var go: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);+ var entered: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);+ var saw_cancel: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);+ fn bash(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const u8) ?[]const u8 {+ entered.store(true, .release);+ while (!go.load(.acquire)) std.Thread.yield() catch {};+ return gpa.dupe(u8, "done") catch null;+ }+ fn cancelled(_: ?*anyopaque) void {+ saw_cancel.store(true, .release);+ go.store(true, .release);+ }+ };+ Gate.go.store(false, .release);+ Gate.entered.store(false, .release);+ Gate.saw_cancel.store(false, .release);+ engine.g_bash_fn = Gate.bash;+ engine.g_cancel_fn = Gate.cancelled;+ defer {+ Gate.go.store(true, .release);+ engine.g_bash_fn = null;+ engine.g_cancel_fn = null;+ }+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ const cmd = try testing.allocator.dupe(u8, "sleep 30");+ try testing.expect(start(&m, .bash, &.{}, cmd, "running"));+ var spins: usize = 0;+ while (!Gate.entered.load(.acquire)) : (spins += 1) {+ if (spins > 1_000_000) return error.OpNeverStarted;+ std.Thread.yield() catch {};+ }+ // The engine is busy: a second op must not stack on top of it.+ try testing.expect(!start(&m, .bash, &.{}, "", "running"));+ // Esc reaches the engine — which is the whole point of the thread.+ cancel(&m);+ try testing.expect(Gate.saw_cancel.load(.acquire));+ try drain(&m);+ try testing.expect(m.bg == null);+}++test "quit gives a stuck op a bounded wait, then abandons it (#533/#534)" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ const op = try testing.allocator.create(Op);+ defer testing.allocator.destroy(op); // the real path leaks it on purpose+ op.* = .{ .kind = .bash, .gpa = testing.allocator, .threaded = true };+ m.bg = op;+ try testing.expectEqual(turn.QuitStep.wait, quitStep(&m, 0));+ try testing.expectEqual(turn.QuitStep.abandon, quitStep(&m, turn.quit_drain_ms));+ op.done.store(true, .release);+ try testing.expectEqual(turn.QuitStep.reap, quitStep(&m, turn.quit_drain_ms));+ abandon(&m);+ try testing.expect(m.bg == null);+}diff --git a/TUI/chrome.zig b/TUI/chrome.zigindex 3c275c59..e2440fed 100644--- a/TUI/chrome.zig+++ b/TUI/chrome.zig@@ -111,7 +111,7 @@ pub fn statusBar(self: *const Model, a: std.mem.Allocator, width: usize) ![]consif (self.now_ms < self.toast_until_ms and self.toast.len > 0) {return theme_mod.paint(a, th.accent, self.toast);}- if (self.pending != null) {+ if (self.pending != null or self.bg != null) {const raw = try std.fmt.allocPrint(a, "{s} Enter:queue · Shift+Tab:mode · Esc:cancel · {s}[stop]{s}", .{th.muted, th.error_fg, theme_mod.reset,});diff --git a/TUI/dispatch.zig b/TUI/dispatch.zigindex e591a3a3..937b58ec 100644--- a/TUI/dispatch.zig+++ b/TUI/dispatch.zig@@ -4,6 +4,7 @@const std = @import("std");const app = @import("app.zig");+const bgop = @import("bgop.zig");const catalog = @import("catalog.zig");const engine = @import("engine.zig");const theme_mod = @import("theme.zig");@@ -11,12 +12,22 @@ const turn = @import("turn.zig");const Model = app.Model;const Effect = app.Effect;+/// Shown whenever an engine call is already in flight — /compact, `!cmd` and+/// a model turn all use the one engine, so they queue behind each other.+pub const busy_note = "an engine call is still running — press Esc to cancel it";+pub fn applyLine(self: *Model, raw: []const u8) Effect {const line = std.mem.trim(u8, raw, " \t\r\n");if (line.len == 0 and self.images.items.len == 0) return .stay;if (line.len > 0) rememberPrompt(self, line);if (line.len > 0 and line[0] == '/') return runCommand(self, line);if (line.len > 1 and line[0] == '!') return bang(self, std.mem.trim(u8, line[1..], " \t"));+ if (self.bg != null) {+ // /compact rewrites the history the next turn would send — never race+ // a turn against it.+ self.push(.system, busy_note) catch {};+ return .stay;+ }const prefix = self.takeImagesPrefix(self.alloc);const payload = if (prefix.len == 0) line else (std.fmt.allocPrint(self.alloc, "{s}{s}", .{ prefix, line }) catch line);if (prefix.len > 0) self.alloc.free(prefix);@@ -54,6 +65,11 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {self.push(.system, "a turn is still running — press Esc to cancel it first") catch {};return .stay;}+ // Same for a background engine op: /compact is itself one of them.+ if (self.bg != null and destroys) {+ self.push(.system, busy_note) catch {};+ return .stay;+ }if (std.mem.eql(u8, canon, "/quit")) {self.quit_requested = true;@@ -190,8 +206,10 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {return if (self.quit_requested) .quit else .stay;}-/// `!cmd` — run a shell line locally (grok-style bash mode). Output stays-/// out of the model history: EntryKind.system never reaches startJob.+/// `!cmd` — run a shell line locally (grok-style bash mode) on a background+/// thread, so a slow command no longer freezes the frame for its whole 20s+/// cap (#533). Output stays out of the model history: EntryKind.system never+/// reaches startJob.fn bang(self: *Model, cmd: []const u8) Effect {if (cmd.len == 0) return .stay;self.pushFmt(.system, "$ {s}", .{cmd}) catch {};@@ -199,17 +217,16 @@ fn bang(self: *Model, cmd: []const u8) Effect {self.push(.err, "! needs a live session (offline)") catch {};return .stay;}- if (engine.g_bash_fn.?(engine.g_turn_ctx, self.alloc, cmd)) |out| {- defer self.alloc.free(out);- self.push(.system, lastLines(out, 40)) catch {};- } else {- self.push(.err, "command failed to start") catch {};+ const owned = self.alloc.dupe(u8, cmd) catch return .stay;+ if (!bgop.start(self, .bash, &.{}, owned, "running")) {+ self.alloc.free(owned);+ self.push(.system, busy_note) catch {};}return .stay;}/// Tail of `s` capped to `max` lines, for `!` output in the scrollback.-fn lastLines(s: []const u8, max: usize) []const u8 {+pub fn lastLines(s: []const u8, max: usize) []const u8 {var count: usize = 0;var i = s.len;while (i > 0) {@@ -250,16 +267,15 @@ pub fn rewind(self: *Model) void {self.push(.system, "rewound the last turn") catch {};}+/// `/compact` — hand the history to the engine on a background thread. Running+/// it inline froze the render+input loop for the whole summarization round+/// trip, with no paint, no key handling and no way to cancel (#533).pub fn compact(self: *Model) void {- const f = engine.g_compact_fn orelse {+ if (engine.g_compact_fn == null) {self.push(.system, "compaction needs a live session") catch {};return;- };- var turns = std.array_list.Managed(engine.Turn).init(self.alloc);- defer {- for (turns.items) |t| self.alloc.free(t.text);- turns.deinit();}+ var turns = std.array_list.Managed(engine.Turn).init(self.alloc);for (self.history.items) |e| {const role: ?engine.Turn.Role = switch (e.kind) {.user => .user,@@ -271,24 +287,11 @@ pub fn compact(self: *Model) void {turns.append(.{ .role = r, .text = t }) catch self.alloc.free(t);}}- var out: engine.CompactOut = .{};- const ok = f(engine.g_turn_ctx, self.alloc, turns.items, &out);- defer {- if (out.note.len > 0) self.alloc.free(out.note);- for (out.turns) |t| self.alloc.free(t.text);- if (out.turns.len > 0) self.alloc.free(out.turns);- }- if (!ok) {- self.push(.system, if (out.note.len > 0) out.note else "compaction failed, history unchanged") catch {};- return;- }- self.clearHistory();- if (out.note.len > 0) self.push(.system, out.note) catch {};- for (out.turns) |t| {- self.push(switch (t.role) {- .user => .user,- .assistant => .assistant,- }, t.text) catch {};+ const owned: []engine.Turn = turns.toOwnedSlice() catch &.{};+ if (!bgop.start(self, .compact, owned, "", "compacting")) {+ for (owned) |t| self.alloc.free(t.text);+ if (owned.len > 0) self.alloc.free(owned);+ self.push(.system, busy_note) catch {};}}@@ -528,23 +531,6 @@ test "/effort with no arg opens the effort menu" {try std.testing.expectEqual(engine.Effort.low, m.effort);}-test "! runs through the bash callback and lands in the scrollback" {- engine.g_bash_fn = struct {- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8) ?[]const u8 {- return std.fmt.allocPrint(gpa, "ran: {s}", .{cmd}) catch null;- }- }.f;- defer engine.g_bash_fn = null;- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- _ = applyLine(&m, "!git status");- try std.testing.expectEqual(@as(usize, 2), m.history.items.len);- try std.testing.expectEqualStrings("$ git status", m.history.items[0].text);- try std.testing.expectEqualStrings("ran: git status", m.history.items[1].text);- try std.testing.expectEqual(app.EntryKind.system, m.history.items[1].kind);-}-test "/vim-mode toggles and /jump without turns explains" {var m: Model = undefined;m.setup(std.testing.allocator);diff --git a/TUI/dispatch_tests.zig b/TUI/dispatch_tests.zigindex b0dde112..0c665a55 100644--- a/TUI/dispatch_tests.zig+++ b/TUI/dispatch_tests.zig@@ -3,10 +3,66 @@const std = @import("std");const app = @import("app.zig");+const bgop = @import("bgop.zig");const dispatch = @import("dispatch.zig");const engine = @import("engine.zig");const Model = app.Model;+/// Spin until the background op finishes, then apply it — what run.zig's loop+/// does every frame while the frame keeps painting.+fn settle(m: *Model) !void {+ var spins: usize = 0;+ while (m.bg) |op| {+ if (op.done.load(.acquire)) break;+ spins += 1;+ if (spins > 1_000_000) return error.OpNeverFinished;+ std.Thread.yield() catch {};+ }+ bgop.finish(m);+}++test "! runs through the bash callback in the background and lands in the scrollback (#533)" {+ engine.g_bash_fn = struct {+ fn f(_: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8) ?[]const u8 {+ return std.fmt.allocPrint(gpa, "ran: {s}", .{cmd}) catch null;+ }+ }.f;+ defer engine.g_bash_fn = null;+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ _ = dispatch.applyLine(&m, "!git status");+ // The command is OFF the render thread: applyLine already returned.+ try std.testing.expect(m.bg != null);+ try settle(&m);+ try std.testing.expectEqual(@as(usize, 2), m.history.items.len);+ try std.testing.expectEqualStrings("$ git status", m.history.items[0].text);+ try std.testing.expectEqualStrings("ran: git status", m.history.items[1].text);+ try std.testing.expectEqual(app.EntryKind.system, m.history.items[1].kind);+}++test "a model turn cannot start while /compact is rewriting the history (#533)" {+ engine.g_compact_fn = struct {+ fn f(_: ?*anyopaque, _: std.mem.Allocator, _: []const engine.Turn, _: *engine.CompactOut) bool {+ return false;+ }+ }.f;+ defer engine.g_compact_fn = null;+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ m.chat = true;+ try m.push(.user, "one");+ dispatch.compact(&m);+ try std.testing.expect(m.bg != null);+ try std.testing.expectEqual(app.Effect.stay, dispatch.applyLine(&m, "next question"));+ try std.testing.expect(m.pending == null);+ const last = m.history.items[m.history.items.len - 1].text;+ try std.testing.expect(std.mem.indexOf(u8, last, "still running") != null);+ try settle(&m);+ try std.testing.expect(m.bg == null);+}+test "/new /compact /rewind are blocked while a job is pending (#521)" {var m: Model = undefined;m.setup(std.testing.allocator);@@ -52,6 +108,7 @@ test "/compact never crops locally; engine stub rewrites history" {}.f;defer engine.g_compact_fn = null;_ = dispatch.applyLine(&m, "/compact");+ try settle(&m); // the engine call runs off the render thread now (#533)try std.testing.expectEqual(@as(usize, 2), m.history.items.len);try std.testing.expectEqual(app.EntryKind.system, m.history.items[0].kind);try std.testing.expectEqual(app.EntryKind.user, m.history.items[1].kind);diff --git a/TUI/engine.zig b/TUI/engine.zigindex 30cb56ec..847cb3d5 100644--- a/TUI/engine.zig+++ b/TUI/engine.zig@@ -71,6 +71,47 @@ pub const Job = struct {stream: StreamBuf,};+/// A background engine op: `/compact`, `!cmd`, or the @-file list. Same+/// thread + done-flag contract as Job, so the render+input loop keeps painting+/// and Esc keeps reaching keys.handle while the engine works (#533). Every+/// field the worker writes is read only after `done`.+pub const BgOp = struct {+ pub const Kind = enum { compact, bash, files };++ kind: Kind,+ gpa: std.mem.Allocator,+ thread: std.Thread = undefined,+ threaded: bool = true,+ done: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),+ /// Esc/Ctrl+C asked the engine to stop; the callbacks observe it through+ /// the same cancel signal a turn uses.+ cancelled: bool = false,+ /// compact input — gpa-owned turns.+ turns: []Turn = &.{},+ /// bash input — gpa-owned command line.+ cmd: []const u8 = "",+ /// compact output — gpa-owned.+ compact: CompactOut = .{},+ ok: bool = false,+ /// bash / files output — gpa-owned.+ text: ?[]const u8 = null,+};++pub fn bgRun(op: *BgOp) void {+ switch (op.kind) {+ .compact => if (g_compact_fn) |f| {+ op.ok = f(g_turn_ctx, op.gpa, op.turns, &op.compact);+ },+ .bash => if (g_bash_fn) |f| {+ op.text = f(g_turn_ctx, op.gpa, op.cmd);+ },+ .files => if (g_files_fn) |f| {+ op.text = f(g_turn_ctx, op.gpa);+ },+ }+ op.done.store(true, .release);+}+pub const HudKind = enum { debug, usage };pub const HudFn = *const fn (kind: HudKind, buf: []u8) usize;diff --git a/TUI/files.zig b/TUI/files.zigindex 7cf42c42..e279a42a 100644--- a/TUI/files.zig+++ b/TUI/files.zig@@ -38,7 +38,12 @@ pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {try out.appendSlice(try theme_mod.paint(a, th.muted, try std.fmt.allocPrint(a, "{d}/{d}", .{ n, total })));try out.appendSlice("\n\n");if (n == 0) {- const hint = if (list.len == 0) "no file list (offline?) — Esc" else "no matches — type to filter, Esc";+ const hint = if (@import("bgop.zig").loadingFiles(self))+ "loading files…"+ else if (list.len == 0)+ "no file list (offline?) — Esc"+ else+ "no matches — type to filter, Esc";try out.appendSlice(try theme_mod.paint(a, th.muted, hint));try out.append('\n');return out.items;diff --git a/TUI/keys.zig b/TUI/keys.zigindex f8fc2e03..f5c88556 100644--- a/TUI/keys.zig+++ b/TUI/keys.zig@@ -273,6 +273,13 @@ fn esc(self: *Model) Effect {self.input.setValue("") catch {};return .stay;}+ if (self.bg != null) {+ // A background engine op (/compact, !cmd) is exactly as interruptible+ // as a turn now that it no longer blocks this thread (#533).+ @import("bgop.zig").cancel(self);+ self.setToast("cancelled");+ return .stay;+ }if (self.pending != null) {turn.cancelTurn(self);self.setToast("cancelled");@@ -304,6 +311,13 @@ fn esc(self: *Model) Effect {}fn ctrlC(self: *Model) Effect {+ if (self.bg) |op| {+ if (!op.cancelled) {+ @import("bgop.zig").cancel(self);+ self.setToast("cancelled — Ctrl+C again to quit");+ return .stay;+ }+ }if (self.pending != null and !self.cancel_requested) {turn.cancelTurn(self);self.setToast("cancelled — Ctrl+C again to quit");diff --git a/TUI/overlays.zig b/TUI/overlays.zigindex 037fbe9a..8bee880d 100644--- a/TUI/overlays.zig+++ b/TUI/overlays.zig@@ -42,10 +42,12 @@ pub fn key(self: *Model, k: Key) Effect {return .stay;}-/// Load the session file list once, then open the @-picker.+/// Open the @-picker immediately and load the session file list in the+/// background. Loading it inline blocked the render+input thread for up to the+/// runCapped 10s cap on the first @ of a session (#533).pub fn openFiles(self: *Model) void {- if (self.files_cache == null) {- if (engine.g_files_fn) |f| self.files_cache = f(engine.g_turn_ctx, self.alloc);+ if (self.files_cache == null and engine.g_files_fn != null) {+ _ = @import("bgop.zig").start(self, .files, &.{}, "", "");}self.openOverlay(.file);}diff --git a/TUI/root.zig b/TUI/root.zigindex 116ee75f..1ffd2355 100644--- a/TUI/root.zig+++ b/TUI/root.zig@@ -46,6 +46,7 @@ test {_ = @import("nav.zig");_ = @import("image.zig");_ = @import("turn.zig");+ _ = @import("bgop.zig");_ = @import("welcome.zig");_ = @import("scrollback.zig");_ = @import("chrome.zig");diff --git a/TUI/run.zig b/TUI/run.zigindex 604d98b1..ff05322a 100644--- a/TUI/run.zig+++ b/TUI/run.zig@@ -5,6 +5,7 @@ const builtin = @import("builtin");const Io = std.Io;const app = @import("app.zig");+const bgop = @import("bgop.zig");const engine = @import("engine.zig");const key_mod = @import("key.zig");const keys = @import("keys.zig");@@ -109,6 +110,9 @@ pub fn run(if (turn.drainSteer(&m) == .quit) break;}}+ // Background engine ops (/compact, !cmd, @-file list) land here too —+ // the same poll that keeps a turn from freezing the loop (#533).+ bgop.finish(&m);const cols = @max(tty.cols(), @as(usize, 40));const rows = @max(tty.rows(), @as(usize, 12));const frame = render_mod.render(&m, gpa, cols, rows, m.now_ms) catch "tui: render error";@@ -144,7 +148,7 @@ pub fn run(// Short wait while an unfinished escape sequence is pending: if// nothing follows, the lone ESC was a real Escape keypress (#94).- const wait: i32 = if (pending_len > 0) 25 else if (m.pending != null) 50 else 200;+ const wait: i32 = if (pending_len > 0) 25 else if (m.pending != null or m.bg != null) 50 else 200;if (!tty.poll(wait)) {if (pending_len > 0) {esc_stall += 1;@@ -213,9 +217,10 @@ pub fn run(// palette's /quit never did — then wait for the thread here, with the alt// screen still up and a frame explaining the wait, instead of joining from// Model.deinit after the terminal has already been handed back (#534).- if (m.pending != null) {+ if (m.pending != null or m.bg != null) {turn.cancelTurn(&m);- m.push(.system, "■ stopping the model…") catch {};+ bgop.cancel(&m);+ m.push(.system, "■ stopping…") catch {};const cols = @max(tty.cols(), @as(usize, 40));const rows = @max(tty.rows(), @as(usize, 12));if (render_mod.render(&m, gpa, cols, rows, m.now_ms)) |frame| {@@ -225,7 +230,9 @@ pub fn run(} else |_| {}const start = m.now_ms;var forced = false;- while (!forced and turn.quitStep(&m, m.now_ms -| start) == .wait) {+ while (!forced and (turn.quitStep(&m, m.now_ms -| start) == .wait or+ bgop.quitStep(&m, m.now_ms -| start) == .wait))+ {if (tty.poll(50)) {const got = tty.readStdin(&inbuf);// A second Ctrl+C / Esc during the wait means "go now".@@ -236,13 +243,16 @@ pub fn run(m.now_ms = nowMs(io);}const elapsed = if (forced) turn.quit_drain_ms else m.now_ms -| start;- if (turn.quitStep(&m, elapsed) == .reap) {+ const stuck = turn.quitStep(&m, elapsed) == .abandon or bgop.quitStep(&m, elapsed) == .abandon;+ if (!stuck) {turn.finishJob(&m);+ bgop.finish(&m);} else {turn.abandonJob(&m);- // The thread is still writing into the job, so the process must- // not outlive the restore: put the terminal back with the same- // bytes the defers would have written, then leave.+ bgop.abandon(&m);+ // The threads are still writing into the job and the op, so the+ // process must not outlive the restore: put the terminal back with+ // the same bytes the defers would have written, then leave.w.flush() catch {};restore_mod.emergency();std.process.exit(0);diff --git a/TUI/scrollback.zig b/TUI/scrollback.zigindex 3d14ab8c..49defe21 100644--- a/TUI/scrollback.zig+++ b/TUI/scrollback.zig@@ -238,7 +238,9 @@ fn row(self: *const Model, a: std.mem.Allocator, idx: usize, e: app.Entry, width.err => th.error_fg,};const raw = if (e.kind == .pending)- thinkingLabel(now_ms)+ // A background engine op (/compact, !cmd) names itself; a model turn+ // pushes an empty row and gets the generic label.+ (if (e.text.len > 0) e.text else thinkingLabel(now_ms))else if (e.kind == .tool)try toolTitle(a, e.text)else if (e.folded)diff --git a/TUI/turn.zig b/TUI/turn.zigindex 43707d56..5d13f936 100644--- a/TUI/turn.zig+++ b/TUI/turn.zig@@ -175,7 +175,7 @@ pub fn harvestLiveTools(self: *Model) void {/// Remove every .pending row wherever it sits. Steering pushes "↳ queued"/// rows after the pending entry, so "pending is last" is not an invariant —/// assuming it stranded a permanent thinking row in the transcript (#520).-fn removePendingRows(self: *Model) bool {+pub fn removePendingRows(self: *Model) bool {var had = false;var i: usize = self.history.items.len;while (i > 0) {