Skip to content

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

Python

Fix session discovery and tool recovery for v0.0.302.18

justrachc65f354ed36f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 743d228c..8c9568d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,20 @@ The release workflow uses a tag's section here as its release notes (a
hand-written `docs/releases/<tag>.md` wins if present), so keeping this file
current is part of cutting a release.
+## v0.0.302.18
+
+### Sessions
+
+- Live sessions show meaningful activity age, deterministic recent-first ordering, and separated rows without repeated identifiers. Resume errors distinguish live identifiers from saved keys. (#1459–#1464)
+- Saved workspaces remain discoverable after their processes exit. Workspace-qualified targets distinguish same-named conversations, and cross-project resume enters the selected workspace before restoring history. (#1457, #1458)
+
+### Recovery
+
+- Empty or format-only terminal pastes recover an available clipboard image or show a warning instead of a misleading pasted-text chip. (#1468)
+- Explicit account-backed model selections tolerate omissions from dynamic catalogs while preserving credential validation. (#1466)
+- Stale MCP registrations and closed connections return recovery guidance; disconnected tools are withdrawn from the next catalog without automatically replaying calls. (#1465, #1467)
+- Added screen-level coverage for long blockquotes; the published reproduction already renders correctly. (#1470)
+
## v0.0.302.17
### Code mode
diff --git a/TUI/composer_paste.zig b/TUI/composer_paste.zig
index a4454d3c..009647c2 100644
--- a/TUI/composer_paste.zig
+++ b/TUI/composer_paste.zig
@@ -20,9 +20,14 @@ pub fn finish(self: *Model) void {
return;
};
defer self.input.endPaste();
- if (range.start == range.end) return;
-
const raw = self.input.getValue()[range.start..range.end];
+ // Rich clipboard selections can reach the terminal as only blank lines,
+ // NBSP, or object/format markers. They are not a usable text attachment.
+ if (!hasContent(raw)) {
+ if (range.start != range.end and !self.input.replacePaste(range, "", false)) return;
+ recoverImage(self);
+ return;
+ }
const path = normalizePath(self.alloc, raw) orelse {
self.input.ensurePasteSeparator();
return;
@@ -40,6 +45,48 @@ pub fn finish(self: *Model) void {
if (self.input.replacePaste(range, path, true)) self.input.ensurePasteSeparator();
}
+fn recoverImage(self: *Model) void {
+ const engine = @import("engine.zig");
+ if (engine.g_paste_fn) |f| {
+ var buf: [1024]u8 = undefined;
+ var owned = false;
+ const n = f(engine.g_turn_ctx, &buf, &owned);
+ if (n > 0) {
+ const before = self.images.items.len;
+ @import("owned_images.zig").attach(self, buf[0..@intCast(n)], owned);
+ if (self.images.items.len > before) return;
+ } else if (n < 0) {
+ self.setToast(buf[0..@intCast(-n)]);
+ return;
+ }
+ }
+ self.setToast("paste contained no usable text or image — copy the image itself or use /image <path>");
+}
+
+fn hasContent(raw: []const u8) bool {
+ const view = std.unicode.Utf8View.init(raw) catch return true;
+ var it = view.iterator();
+ while (it.nextCodepoint()) |cp| {
+ switch (cp) {
+ 0...0x20,
+ 0x7f...0xa0,
+ 0xad,
+ 0x61c,
+ 0x1680,
+ 0x180e,
+ 0x2000...0x200f,
+ 0x2028...0x202f,
+ 0x205f...0x206f,
+ 0x3000,
+ 0xfeff,
+ 0xfff9...0xfffc,
+ => {},
+ else => return true,
+ }
+ }
+ return false;
+}
+
fn pathExists(path: []const u8) bool {
const io = std.Io.Threaded.global_single_threaded.io();
_ = std.Io.Dir.cwd().statFile(io, path, .{}) catch return false;
@@ -85,6 +132,101 @@ fn normalizePath(alloc: std.mem.Allocator, raw: []const u8) ?[]u8 {
return out.toOwnedSlice() catch null;
}
+const TestPaste = struct {
+ payload: []const u8 = "",
+ failed: bool = false,
+ calls: usize = 0,
+
+ fn call(ctx: ?*anyopaque, dest: []u8, owned: *bool) isize {
+ const self: *TestPaste = @ptrCast(@alignCast(ctx.?));
+ self.calls += 1;
+ owned.* = false;
+ @memcpy(dest[0..self.payload.len], self.payload);
+ const n: isize = @intCast(self.payload.len);
+ return if (self.failed) -n else n;
+ }
+};
+
+test "#1468 empty and format-only terminal pastes warn without a false text chip" {
+ const engine = @import("engine.zig");
+ const saved_fn = engine.g_paste_fn;
+ const saved_ctx = engine.g_turn_ctx;
+ defer {
+ engine.g_paste_fn = saved_fn;
+ engine.g_turn_ctx = saved_ctx;
+ }
+ var callback = TestPaste{};
+ engine.g_paste_fn = TestPaste.call;
+ engine.g_turn_ctx = &callback;
+ for ([_][]const u8{ "", "\n\n\n", " \t\r\n", "\u{a0}\u{200b}\u{feff}\u{fffc}\n\n\n" }) |payload| {
+ var term: @import("sim.zig").Term = undefined;
+ term.init(std.testing.allocator, 120, 24);
+ defer term.deinit();
+ _ = term.typeText("beforeafter");
+ term.model.input.cursor = "before".len;
+ _ = term.feed("\x1b[200~");
+ _ = term.feed(payload);
+ _ = term.feed("\x1b[201~");
+ try std.testing.expectEqualStrings("beforeafter", term.model.input.getValue());
+ try std.testing.expectEqual(@as(usize, 6), term.model.input.cursor);
+ try std.testing.expectEqual(@as(usize, 0), term.model.images.items.len);
+ const screen = try term.screen();
+ defer term.alloc.free(screen);
+ try std.testing.expect(std.mem.indexOf(u8, screen, "paste contained no usable text or image") != null);
+ try std.testing.expect(std.mem.indexOf(u8, screen, "[Pasted text") == null);
+ }
+ try std.testing.expectEqual(@as(usize, 4), callback.calls);
+}
+
+test "#1468 format-only paste recovers an image through the live callback" {
+ const engine = @import("engine.zig");
+ const saved_fn = engine.g_paste_fn;
+ const saved_ctx = engine.g_turn_ctx;
+ defer {
+ engine.g_paste_fn = saved_fn;
+ engine.g_turn_ctx = saved_ctx;
+ }
+ var callback = TestPaste{ .payload = "/synthetic/clipboard.png" };
+ engine.g_paste_fn = TestPaste.call;
+ engine.g_turn_ctx = &callback;
+ var term: @import("sim.zig").Term = undefined;
+ term.init(std.testing.allocator, 120, 24);
+ defer term.deinit();
+ _ = term.typeText("describe this");
+ _ = term.feed("\x1b[200~\n\n\n\x1b[201~");
+ try std.testing.expectEqualStrings("describe this", term.model.input.getValue());
+ try std.testing.expectEqual(@as(usize, 1), callback.calls);
+ try std.testing.expectEqual(@as(usize, 1), term.model.images.items.len);
+ try std.testing.expectEqualStrings(callback.payload, term.model.images.items[0]);
+}
+
+test "#1468 recovery keeps actionable errors and never probes the clipboard for real text" {
+ const engine = @import("engine.zig");
+ const saved_fn = engine.g_paste_fn;
+ const saved_ctx = engine.g_turn_ctx;
+ defer {
+ engine.g_paste_fn = saved_fn;
+ engine.g_turn_ctx = saved_ctx;
+ }
+ var callback = TestPaste{ .payload = "clipboard image export failed", .failed = true };
+ engine.g_paste_fn = TestPaste.call;
+ engine.g_turn_ctx = &callback;
+ var term: @import("sim.zig").Term = undefined;
+ term.init(std.testing.allocator, 120, 24);
+ defer term.deinit();
+ _ = term.feed("\x1b[200~\n\n\n\x1b[201~");
+ const screen = try term.screen();
+ defer term.alloc.free(screen);
+ try std.testing.expect(std.mem.indexOf(u8, screen, callback.payload) != null);
+ try std.testing.expectEqualStrings("", term.model.input.getValue());
+ const text = "\n\u{200d}hello\u{a0}\nworld\n";
+ _ = term.feed("\x1b[200~");
+ _ = term.feed(text);
+ _ = term.feed("\x1b[201~");
+ try std.testing.expectEqualStrings(text, term.model.input.getValue());
+ try std.testing.expectEqual(@as(usize, 1), callback.calls);
+}
+
fn hexNibble(c: u8) ?u8 {
return switch (c) {
'0'...'9' => c - '0',
diff --git a/TUI/scrollback_tests.zig b/TUI/scrollback_tests.zig
index 881121c9..78eb6f7a 100644
--- a/TUI/scrollback_tests.zig
+++ b/TUI/scrollback_tests.zig
@@ -244,6 +244,29 @@ test "a long system row breaks on a space, never through a token" {
}
}
+test "long blockquote completion keeps every word after terminal wrapping" {
+ const quote = "This is a deliberately long copy-ready sentence that should continue across multiple terminal rows without losing any words from the completion.";
+ const source = "> " ++ quote ++ "\n\nFollowing section.";
+ for ([_]theme_mod.Id{ .night, .day }) |id| {
+ for ([_]usize{ 40, 60, 80 }) |width| {
+ var term: @import("sim.zig").Term = undefined;
+ term.init(std.testing.allocator, width, 30);
+ defer term.deinit();
+ term.model.theme_id = id;
+ try term.model.push(.assistant, source);
+ const screen = try term.screen();
+ defer std.testing.allocator.free(screen);
+ var words = std.mem.tokenizeScalar(u8, quote, ' ');
+ var pos: usize = 0;
+ while (words.next()) |word| {
+ const at = std.mem.indexOfPos(u8, screen, pos, word) orelse return error.MissingQuoteWord;
+ pos = at + word.len;
+ }
+ try std.testing.expect(std.mem.indexOfPos(u8, screen, pos, "Following section.") != null);
+ }
+ }
+}
+
test "live prose tail paints markdown; raw bash stays plain" {
const engine = @import("engine.zig");
var m: Model = undefined;
diff --git a/docs/adr/0239-saved-workspaces-have-durable-discovery.md b/docs/adr/0239-saved-workspaces-have-durable-discovery.md
new file mode 100644
index 00000000..50e3102e
--- /dev/null
+++ b/docs/adr/0239-saved-workspaces-have-durable-discovery.md
@@ -0,0 +1,19 @@
+# 0239. Saved workspaces have durable device-local discovery
+
+Status: accepted 2026-10-02
+
+## Context
+
+The live registry exposes sessions in unrelated repositories, while saved-session discovery covered only cwd, linked worktrees and home. A visible session could not be resumed, and removing the live process removed the only clue to its location (#1457–#1462).
+
+## Decision
+
+Remember workspace roots in a device-local index when saving meaningful conversation state. Use a separate file per root so unrelated saves do not race on a shared read-modify-write document. Discover saves in those roots without recursively scanning the device. The index contains paths, not conversation contents.
+
+Absolute `.graff/sessions/KEY.session.json` paths are explicit resume targets. Pickers and listings use these for remote saves so equal keys in different workspaces remain selectable. Bare keys retain cwd-first compatibility. Qualified resume enters the selected workspace before restoring history and refuses to proceed if entering fails. Home-origin saves retain ADR 0059's history-only behavior.
+
+ACP `session/load` retains its explicit client-cwd contract (ADR 0202); a client selects a remote save with that workspace and its basename. Slash-command resume and the TUI use the same engine discovery and restore paths.
+
+## Consequences
+
+Saved roots remain discoverable after their processes exit. Existing unindexed roots can be reached by an explicit target and become indexed on their next save. Stale roots contribute no rows; no global filesystem crawl or copying session files is required. The local index is metadata and must not be published.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 98265dc7..c7d8791f 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -265,6 +265,7 @@ record only when you need the evidence or the edge cases.
| [0236](0236-rlm-takes-json-literals-and-each-maps-plain-values.md) | `rlm` takes JSON array/object literals as arguments and binds (`name = [...]`, bound names allowed inside); its splitters nest `[]`/`{}`; `each(arr, tool[, field])` passes plain items as is, picks `field` from objects (default: an MCP tool's first parameter) and names the fields it found; an unsupported statement lists the forms that work. |
| [0237](0237-deepseek-thinks-at-its-low-level-by-default.md) | DeepSeek's default effort (`medium`) sends `reasoning_effort: low` with thinking enabled; `/effort low` still turns thinking off (ADR 0054), and `high` and above are unchanged. |
| [0238](0238-rlm-binds-keep-the-whole-mcp-result.md) | An MCP call inside an rlm script binds the whole result; `print()` shows the slim view (each item of an `each()` bind cut on its own), `project(x, field)` reads any field (`n`/`latest_author` through a comment list's fold), and `write_file` saves the whole result; inside rlm, `read_tool_result("tr_N")` with no range binds a stored result whole. |
+| [0239](0239-saved-workspaces-have-durable-discovery.md) | Remember saved workspace roots locally; remote picker targets are workspace-qualified, and resume must enter the selected tree before restoring it. |
## When to write one
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index ac4c4ba7..963deeda 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -15,7 +15,7 @@
"src/repl.zig",
"TUI/root.zig"
],
- "test_count_baseline": 3159,
+ "test_count_baseline": 3175,
"test_count_slack": 25,
"required_invariants": [
{
diff --git a/scripts/test-acp-workspace.py b/scripts/test-acp-workspace.py
index e82a9084..386e54aa 100755
--- a/scripts/test-acp-workspace.py
+++ b/scripts/test-acp-workspace.py
@@ -60,6 +60,38 @@ def run(binary):
a.close()
model.stop()
+ # Independent repositories remain discoverable after the saving process exits.
+ client_saves = list((client / ".graff" / "sessions").glob("*.session.json"))
+ assert len(client_saves) == 1, client_saves
+ remote_save = client_saves[0]
+ remote_key = remote_save.name.removesuffix(".session.json")
+ assert list((home / ".graff" / "session-workspaces").glob("*.json")), "save registers its workspace"
+ # Same-named local history must not hide or replace the explicitly selected remote save.
+ local_save = launch / ".graff" / "sessions" / remote_save.name
+ local_save.parent.mkdir(parents=True, exist_ok=True)
+ local_payload = json.loads(remote_save.read_text())
+ local_payload["workspace"] = str(launch)
+ local_payload["title"] = "different local conversation"
+ local_save.write_text(json.dumps(local_payload))
+ model = ScriptedModel([{"tool": "shell", "arguments": {"action": "run", "command": "pwd"}}, {"text": "restored"}])
+ port = model.start(0)
+ a = Acp(binary, launch, home, port, isolation_off)
+ try:
+ a.request("initialize", {"protocolVersion": 1})
+ active = a.request("session/new", {"cwd": str(launch), "mcpServers": []})["result"]["sessionId"]
+ before = len(a.events)
+ a.request("session/prompt", {"sessionId": active, "prompt": [{"type": "text", "text": "/sessions"}]})
+ assert str(remote_save) in json.dumps(a.events[before:]), "remote target remains visible beside duplicate local key"
+ resumed = a.request("session/prompt", {"sessionId": active, "prompt": [{"type": "text", "text": f"/resume {remote_save}"}]})
+ assert resumed["result"]["stopReason"] == "end_turn", resumed
+ turn = a.request("session/prompt", {"sessionId": active, "prompt": [{"type": "text", "text": "confirm restored workspace"}]}, 35)
+ assert turn["result"]["stopReason"] == "end_turn", turn
+ assert "where am I" in str(model.requests[0]), "resume restores the remote history"
+ assert any(str(client) in text for text in tool_text(model.requests[1])), "tools enter the remote workspace"
+ finally:
+ a.close()
+ model.stop()
+
# A relative cwd is invalid params, not a silent fallback.
model = ScriptedModel([])
port = model.start(0)
diff --git a/src/agent_catalog.zig b/src/agent_catalog.zig
index a5c816f2..afe3b983 100644
--- a/src/agent_catalog.zig
+++ b/src/agent_catalog.zig
@@ -64,8 +64,17 @@ pub fn invalidateRootTools(self: *Agent) void {
self.tools_interactions = "";
}
+pub fn refreshMcp(self: *Agent) bool {
+ if (self.sub) return false;
+ const registry = self.registry orelse return false;
+ if (!registry.catalog_dirty.swap(false, .acq_rel)) return false;
+ invalidateRootTools(self);
+ return true;
+}
+
pub fn ensureRootTools(self: *Agent, kind: Provider.Kind) !void {
if (self.sub and !main_mod.g_codedbpro_licensed) return;
+ _ = refreshMcp(self);
const dest = switch (kind) {
.anthropic => &self.tools_anthropic,
.openai => &self.tools_openai,
diff --git a/src/agent_request.zig b/src/agent_request.zig
index c595f57e..2beda2e0 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -104,7 +104,8 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
const joined = if (self.registry) |reg| @import("mcp_pages.zig").beforeRequest(reg) else false; // joins deferred starts, re-lists changed servers
if (self.registry) |reg| if (!self.sub) @import("mcp_connect_notice.zig").drain(reg, @import("engine_sink.zig").forAgent(self), self.io); // ADR 0230
const preloaded = @import("mcp_preload.zig").namedServers(self); // ADR 0231: a named server's schemas ride this request
- if (joined or preloaded or @import("additional_tools.zig").staleCatalog(self)) {
+ const withdrawn = @import("agent_catalog.zig").refreshMcp(self);
+ if (joined or preloaded or withdrawn or @import("additional_tools.zig").staleCatalog(self)) {
self.invalidateRootTools();
try self.ensureRootTools(self.provider.kind);
// The caller's snapshot is the catalog that just went stale. Send the
diff --git a/src/catalog_selection.zig b/src/catalog_selection.zig
index 6ba64f6e..b23a81c2 100644
--- a/src/catalog_selection.zig
+++ b/src/catalog_selection.zig
@@ -10,6 +10,15 @@ const pricing = @import("pricing.zig");
const provider = @import("provider.zig");
const serde = @import("serde.zig");
+/// Account-backed catalogs are discovery snapshots, not availability gates.
+/// Like a saved selection, an explicit model must reach the selected backend;
+/// credentials are still checked by providerById. API-key-only providers keep
+/// exact-row validation; callers retain their local-server exceptions.
+pub fn acceptsExplicitModel(spec: provider.ProviderSpec, model: []const u8) bool {
+ if (std.mem.trim(u8, model, " \t").len == 0) return false;
+ return spec.login != .api_key or pricing.providerModelInTable(spec.id, model);
+}
+
pub fn explicitProvider(query: []const u8) ?[]const u8 {
const trimmed = std.mem.trim(u8, query, " \t");
const end = std.mem.indexOfAny(u8, trimmed, " /\t") orelse trimmed.len;
diff --git a/src/cli.zig b/src/cli.zig
index 2f49c05a..e418d832 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -23,6 +23,10 @@ const update_target = @import("update_target.zig");
pub const changelog_text =
\\What's new
\\──────────
+ \\0.0.302.18
+ \\ • clearer session lists and cross-project resume
+ \\ • paste warnings, MCP recovery, and catalog-tolerant model selection
+ \\
\\0.0.302.17
\\ • rlm scripts keep whole MCP results; print() still shows the slim view
\\
diff --git a/src/commands_model.zig b/src/commands_model.zig
index 65fc8cb2..902c57f7 100644
--- a/src/commands_model.zig
+++ b/src/commands_model.zig
@@ -149,7 +149,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
const mdl = std.mem.trim(u8, arg[i + 1 ..], " \t");
if (provider_mod.specFor(pid)) |spec| {
if (mdl.len == 0) return true;
- if (!isLocalUrl(spec.url) and !pricing.providerModelInTable(pid, mdl)) {
+ if (!isLocalUrl(spec.url) and !@import("catalog_selection.zig").acceptsExplicitModel(spec, mdl)) {
try out.print("unknown model '{s}' for {s} — choose /model, or run `graff models refresh` first\n", .{ mdl, pid });
try out.flush();
return true;
diff --git a/src/commands_resume.zig b/src/commands_resume.zig
index 82cd5440..7cd8a9cb 100644
--- a/src/commands_resume.zig
+++ b/src/commands_resume.zig
@@ -58,12 +58,13 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
if (source.len == 0) {
if (!(main_mod.use_color and root.in != null)) return reject(out, "usage: /resume SOURCE [--branch DEST]\n", .{});
const picked = pickSource(root, arena, out) orelse return true;
- source = try arena.dupe(u8, picked.base);
+ source = try @import("session_workspaces.zig").target(arena, picked);
if (!picked.local and picked.workspace.len > 0) picked_remote = try arena.dupe(u8, picked.workspace);
}
const resumed = session_branch.restore(root, keys, arena, source, parsed.branch, null) catch |err| return switch (err) {
- error.FileNotFound => reject(out, "no session named '{s}' ({s}{s} not found in cwd or ~/{s}) — /sessions lists saved ones\n", .{ source, source, session.session_ext, session.sessions_dir }),
+ error.FileNotFound => reject(out, "{s}\n", .{try missingMessage(root, arena, source)}),
+ error.WorkspaceUnavailable => reject(out, "resume stopped: the selected workspace could not be entered; use /workspace use with its directory, then retry /resume\n", .{}),
error.InvalidSessionName => reject(out, "resume failed: invalid source or branch name\n", .{}),
error.BranchMatchesSource => reject(out, "branch failed: destination must differ from source\n", .{}),
error.BranchAlreadyExists => reject(out, "branch failed: destination already exists\n", .{}),
@@ -86,6 +87,39 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
return true;
}
+pub fn missingMessage(root: *Agent, arena: Allocator, source: []const u8) ![]const u8 {
+ const entries = session.listSavedSessionsAll(root, arena);
+ for (entries.items) |entry| {
+ if (entry.title) |title| if (std.mem.eql(u8, title, source))
+ return std.fmt.allocPrint(arena, "'{s}' is a saved-session title; use /resume {s}", .{ source, try @import("session_workspaces.zig").target(arena, entry) });
+ }
+ return missingLiveMessage(arena, source, presence.liveAllPeers(root.io, arena));
+}
+
+fn missingLiveMessage(arena: Allocator, source: []const u8, peers: []const @import("worktree_lease.zig").Owner) ![]const u8 {
+ for (peers) |peer| {
+ const pid = std.fmt.parseInt(i32, source, 10) catch 0;
+ if (!std.mem.eql(u8, source, peer.title) and !std.mem.eql(u8, source, peer.session_id) and
+ !std.mem.eql(u8, source, peer.session_base) and (pid == 0 or pid != peer.pid)) continue;
+ const key = if (peer.session_base.len > 0) peer.session_base else peer.session_id;
+ return std.fmt.allocPrint(arena, "'{s}' matches a live session, but no reachable save has that key. /resume takes a saved key, not a title, PID or live ID. In the originating workspace, /save {s}; then select it with bare /resume. Live workspace identity: {s}", .{ source, key, peer.identity });
+ }
+ return std.fmt.allocPrint(arena, "no reachable saved session named '{s}'. Searched cwd, linked worktrees, remembered workspaces and ~/.graff/sessions. /resume takes a saved key (not a title or PID), or an absolute .graff/sessions/KEY.session.json path. Use bare /resume to select a save; /sessions also lists live processes, which may have no save yet.", .{source});
+}
+
+test "resume missing diagnostic distinguishes live identifiers from saved keys" {
+ const a = std.testing.allocator;
+ const peers = [_]@import("worktree_lease.zig").Owner{.{ .pid = 42, .session_id = "live-id", .title = "Visible title", .session_base = "saved-key", .identity = "/project/.git" }};
+ const live = try missingLiveMessage(a, "42", &peers);
+ defer a.free(live);
+ try std.testing.expect(std.mem.indexOf(u8, live, "matches a live session") != null);
+ try std.testing.expect(std.mem.indexOf(u8, live, "/save saved-key") != null);
+ const absent = try missingLiveMessage(a, "missing", &peers);
+ defer a.free(absent);
+ try std.testing.expect(std.mem.indexOf(u8, absent, "no reachable saved session") != null);
+ try std.testing.expect(std.mem.indexOf(u8, absent, "remembered workspaces") != null);
+}
+
test "resume argument parser separates an explicit branch" {
const plain = session_branch.parseSpec(" baseline ").?;
try std.testing.expectEqualStrings("baseline", plain.source);
diff --git a/src/exec.zig b/src/exec.zig
index 314a9518..d52ee2ac 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -175,7 +175,9 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
// loads its schema inline and runs — the refusal round trip is gone
// (same user direction as the native fold). Still downstream of
// agent_tool_gate.gateTool: consent is already settled.
- mcp_schema_gate.autoLoad(gpa, reg.tools, call.name);
+ const connected = try reg.snapshotTools(gpa);
+ defer gpa.free(connected);
+ mcp_schema_gate.autoLoad(gpa, connected, call.name);
var prepared = codedbpro_paths.prepareInput(gpa, io, ctx.agent_cwd, call.name, call.input) catch |err| {
codedbpro_report.onFailure(ctx, call.name, @errorName(err));
return failure(gpa, err);
diff --git a/src/main.zig b/src/main.zig
index 7a65d043..c0525213 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -561,7 +561,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = .{ @import("beta_feed.zig"), @import("jev_tool.zig"), @import("jev_model_scope.zig"), @import("jev_provider_switch_tests.zig"), @import("jev_effort_state.zig") };
_ = .{ @import("mcp_apps.zig"), @import("html_view.zig"), @import("usage_trace.zig"), @import("providers_confirmation_tests.zig"), @import("repl_model_confirmation_tests.zig"), @import("repl_model_pick_tests.zig"), @import("engine_sink_citation_tests.zig"), @import("cite_markup_stream_tests.zig"), @import("oneshot_citation_tests.zig"), @import("tui_acp.zig"), @import("acp_permission.zig"), @import("acp_usage.zig") };
_ = .{ @import("mcp_server_tests.zig"), @import("main_test.zig"), @import("artifact_claim_command.zig"), @import("cli_path_hint.zig"), @import("run_budget.zig"), @import("pr_review_input.zig"), @import("pr_claim_review.zig"), @import("tui_paste_transfer.zig") };
- _ = .{ @import("session_catalog.zig"), @import("session_prompt.zig"), @import("session_discovery.zig") };
+ _ = .{ @import("session_catalog.zig"), @import("session_prompt.zig"), @import("session_discovery.zig"), @import("session_workspaces.zig"), @import("commands_resume.zig"), @import("peer_live.zig"), @import("presence_tests.zig"), @import("mcp_rpc_tests.zig") };
_ = .{ @import("prompt_astra.zig"), @import("prompt_guidance.zig"), @import("oauth_chatgpt.zig") }; // per-model guidance (Astra, GPT-5.6); ChatGPT plan sign-in
_ = .{ @import("agent_empty_completion.zig"), @import("agent_model_loop.zig"), @import("publication_policy_tests.zig"), @import("jobs_completion_tests.zig") };
_ = .{ @import("provider_routing_tests.zig"), @import("history_wire.zig"), @import("readline_paste_number_tests.zig"), @import("test_hooks.zig"), @import("peer_wake_loop.zig") };
diff --git a/src/mcp.zig b/src/mcp.zig
index 577eddfb..6a0fb0fc 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -24,11 +24,9 @@ const mcp_stdio = @import("mcp_stdio.zig");
const mcp_teardown = @import("mcp_teardown.zig");
const shutdown_trace = @import("shutdown_trace.zig"); // #364: teardown phase stamps
const mcp_rpc = @import("mcp_rpc.zig");
-const mcp_elicitation = @import("mcp_elicitation.zig");
const mcp_cache = @import("mcp_cache.zig");
const util = @import("util.zig");
const vision = @import("vision.zig"); // #249: MCP image results become staged vision blocks
-const renderContent = @import("mcp_content.zig").renderContent;
const rewriteOneOf = mcp_protocol.rewriteOneOf;
const HttpTransport = mcp_http.HttpTransport;
@@ -36,8 +34,6 @@ pub const validRemoteUrl = mcp_http.validRemoteUrl;
const Server = mcp_rpc.Server;
const Transport = mcp_rpc.Transport;
const deinitServer = mcp_rpc.deinitServer;
-const initializeServer = mcp_rpc.initializeServer;
-const request = mcp_rpc.request;
pub const Tool = struct {
server_name: ?[]const u8 = null, // raw configuration identity; null for legacy fixtures
@@ -53,15 +49,6 @@ pub const Tool = struct {
}
};
-/// One server/tool for MRTR retries (mcp_mrtr.resolve).
-const McpCall = struct {
- server: *Server,
- name: []const u8,
- fn send(self: McpCall, a: Allocator, params: []const u8) anyerror!Value {
- return request(self.server, a, params, "tools/call", self.name);
- }
-};
-
pub const Registry = struct {
last_app_path: ?[]const u8 = null,
gpa: Allocator,
@@ -71,6 +58,8 @@ pub const Registry = struct {
mutex: Io.Mutex = .init,
servers: []*Server = &.{},
tools: []Tool = &.{},
+ /// Transport failure withdrew tools; owner thread rebuilds its next catalog.
+ catalog_dirty: std.atomic.Value(bool) = .init(false),
/// Startup connection/failure lines are developer diagnostics, not normal REPL output.
show_diagnostics: bool = false,
/// The stdio spec's backward-compatibility SHOULD: a dual-era client
@@ -154,6 +143,8 @@ pub const Registry = struct {
/// callers must re-render their tool list afterward. Run between turns only
/// (no tool calls in flight).
pub fn addServer(reg: *Registry, name: []const u8, command: []const u8, args: []const []const u8) !usize {
+ reg.mutex.lockUncancelable(reg.io);
+ defer reg.mutex.unlock(reg.io);
for (reg.servers) |server| if (std.mem.eql(u8, server.name, name)) return error.McpServerAlreadyConnected;
const a = reg.arena();
var servers: std.ArrayList(*Server) = .empty;
@@ -177,6 +168,8 @@ pub const Registry = struct {
/// Connect a Streamable HTTP server at runtime. `headers` are copied into
/// registry storage and sent on every request (for example Authorization).
pub fn addRemoteServer(reg: *Registry, name: []const u8, url: []const u8, headers: []const std.http.Header) !usize {
+ reg.mutex.lockUncancelable(reg.io);
+ defer reg.mutex.unlock(reg.io);
for (reg.servers) |server| if (std.mem.eql(u8, server.name, name)) return error.McpServerAlreadyConnected;
const a = reg.arena();
var servers: std.ArrayList(*Server) = .empty;
@@ -210,6 +203,8 @@ pub const Registry = struct {
/// connected. Caller must re-render its tool list. Run between turns only
/// (no tool calls in flight).
pub fn trustWorkspace(reg: *Registry, config_path: []const u8) !usize {
+ reg.mutex.lockUncancelable(reg.io);
+ defer reg.mutex.unlock(reg.io);
const a = reg.arena();
const merged = mcp_config.load(reg.io, a, Io.Dir.cwd(), config_path, reg.global_config_path, reg.home, reg.global_is_override);
@@ -460,120 +455,14 @@ pub const Registry = struct {
return std.mem.startsWith(u8, name, "mcp__");
}
- /// Invoke a tool by its qualified name. `input` is the model-supplied
- /// argument object. Returns result text (caller-owned, allocated with
- /// `out_alloc`) and whether the server reported an error.
- const CallResult = struct { text: []u8, is_error: bool };
- pub fn call(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input: Value) !CallResult {
+ /// Calls and runtime registration share one lock, including tool lookup.
+ pub fn call(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input: Value) !@import("mcp_call.zig").CallResult {
return reg.callWithContext(out_alloc, qualified, input, null);
}
- pub fn callWithContext(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input: Value, context: ?@import("mcp_turn_context.zig").Snapshot) !CallResult {
+ pub fn callWithContext(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input: Value, context: ?@import("mcp_turn_context.zig").Snapshot) !@import("mcp_call.zig").CallResult {
reg.mutex.lockUncancelable(reg.io);
defer reg.mutex.unlock(reg.io);
- const tool = for (reg.tools) |t| {
- if (std.mem.eql(u8, t.qualified_name, qualified)) break t;
- } else return .{ .text = try out_alloc.dupe(u8, "unknown MCP tool"), .is_error = true };
-
- const server = reg.servers[tool.server_index];
- const turn_ctx = @import("mcp_turn_context.zig").effective(context, reg.io, server.name);
- const params = try @import("mcp_turn_context.zig").params(reg.gpa, server.name, tool.original_name, input, turn_ctx);
- defer reg.gpa.free(params);
-
- // Tool responses can be large and numerous; keep them out of the
- // session arena. Only the returned text is copied to `out_alloc`.
- var response_arena_state = std.heap.ArenaAllocator.init(reg.gpa);
- defer response_arena_state.deinit();
- const response_alloc = response_arena_state.allocator();
- if (server.transport == .dormant) @import("mcp_lazy.zig").wake(reg, server) catch |err|
- return .{ .text = try std.fmt.allocPrint(out_alloc, "MCP server {s} failed to start: {t}", .{ server.name, err }), .is_error = true };
- if (!server.initialized) try initializeServer(server, response_alloc, reg.arena(), null);
- server.elicit_source = params;
- defer server.elicit_source = "";
- const first_resp = request(server, response_alloc, params, "tools/call", tool.original_name) catch |err| switch (err) {
- // Streamable HTTP servers use 404 to expire a session. Re-run the
- // MCP handshake once, then retry the call without the stale ID.
- // A modern-era server never carries a session id in the first
- // place (mcp_http never sends/stores one for a modern request),
- // so this cannot structurally fire for one — the explicit guard
- // is defense-in-depth against a future refactor resurrecting a
- // re-handshake loop against a server that has no `initialize`.
- error.McpSessionExpired => retry: {
- if (server.era != .legacy) return err;
- try initializeServer(server, response_alloc, reg.arena(), null);
- break :retry try request(server, response_alloc, params, "tools/call", tool.original_name);
- },
- else => return err,
- };
- // 2026-07-28 input_required: answer and retry (bounded) until complete.
- const call_ctx: McpCall = .{ .server = server, .name = tool.original_name };
- const resp = try @import("mcp_mrtr.zig").resolve(response_alloc, params, first_resp, call_ctx, McpCall.send);
- if (resp != .object) return error.BadMcpResponse;
-
- if (resp.object.get("error")) |e| {
- // Protocol-level failure (unknown tool, invalid args, server
- // crash) — distinct from a tool that ran and *returned* an error
- // (isError below). Keep the JSON-RPC code: models retry better
- // when they can tell -32602 bad-params from a tool-side failure.
- const msg = if (e == .object) blk: {
- const m = e.object.get("message") orelse break :blk "MCP error";
- break :blk if (m == .string) m.string else "MCP error";
- } else "MCP error";
- const code: i64 = if (e == .object) blk: {
- const c = e.object.get("code") orelse break :blk 0;
- break :blk if (c == .integer) c.integer else 0;
- } else 0;
- if (mcp_elicitation.looksUnavailable(msg))
- return .{ .text = try out_alloc.dupe(u8, mcp_elicitation.fallback), .is_error = true };
- const text = if (code != 0)
- try std.fmt.allocPrint(out_alloc, "MCP error {d}: {s}", .{ code, msg })
- else
- try out_alloc.dupe(u8, msg);
- return .{ .text = text, .is_error = true };
- }
- // A well-formed JSON-RPC reply has `result` xor `error`; `error` was
- // handled above. Guard a malformed server that sends neither (or a
- // non-object result) instead of force-unwrapping into a panic.
- const result_val = resp.object.get("result") orelse
- return .{ .text = try out_alloc.dupe(u8, "MCP response had neither result nor error"), .is_error = true };
- if (result_val != .object)
- return .{ .text = try out_alloc.dupe(u8, "MCP response result was not an object"), .is_error = true };
- const result = result_val.object;
- // resultType absent MUST read as "complete". input_required was
- // resolved above; any other type is surfaced, never returned as "".
- if (!mcp_protocol.resultIsComplete(result))
- return .{ .text = try out_alloc.dupe(u8, "MCP server returned an unsupported resultType"), .is_error = true };
- const is_error = if (result.get("isError")) |v| (v == .bool and v.bool) else false;
-
- var ow: Io.Writer.Allocating = .init(out_alloc);
- errdefer ow.deinit();
- if (tool.ui_resource_uri) |uri| {
- const path = @import("mcp_apps.zig").snapshot(reg.io, response_alloc, reg.home, server, uri, input, result_val) catch null;
- if (path) |p| {
- reg.last_app_path = try reg.arena().dupe(u8, p);
- try ow.writer.print("[MCP app]({s}) — saved interactive result; /mcp apps opens it in a browser.\n", .{p});
- } else try ow.writer.writeAll("[MCP app view unavailable; ordinary tool output follows.]\n");
- }
- const prefix_len = ow.writer.buffered().len;
- if (result.get("content")) |content| try renderContent(&ow.writer, content, .{
- .arena = reg.arena(),
- .slot = &reg.pending_image,
- .label = qualified,
- .supports_vision = reg.vision_capable,
- });
- // 2025-06-18+ structured tool output: if the server sent only
- // structuredContent (no text blocks), surface it instead of "".
- if (ow.writer.buffered().len == prefix_len) {
- if (result.get("structuredContent")) |sc| {
- var sw: std.json.Stringify = .{ .writer = &ow.writer };
- try sw.write(sc);
- }
- }
- const text = try ow.toOwnedSlice();
- if (mcp_elicitation.looksUnavailable(text)) {
- out_alloc.free(text);
- return .{ .text = try out_alloc.dupe(u8, mcp_elicitation.fallback), .is_error = true };
- }
- return .{ .text = text, .is_error = is_error };
+ return @import("mcp_call.zig").call(reg, out_alloc, qualified, input, context);
}
};
diff --git a/src/mcp_call.zig b/src/mcp_call.zig
new file mode 100644
index 00000000..9be82fa3
--- /dev/null
+++ b/src/mcp_call.zig
@@ -0,0 +1,160 @@
+//! MCP invocation and recovery, separated from registry lifecycle.
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+const Registry = @import("mcp.zig").Registry;
+const mcp_rpc = @import("mcp_rpc.zig");
+const mcp_protocol = @import("mcp_protocol.zig");
+const mcp_elicitation = @import("mcp_elicitation.zig");
+const initializeServer = mcp_rpc.initializeServer;
+const request = mcp_rpc.request;
+const renderContent = @import("mcp_content.zig").renderContent;
+const Server = mcp_rpc.Server;
+
+/// One server/tool for MRTR retries (mcp_mrtr.resolve).
+const McpCall = struct {
+ server: *Server,
+ name: []const u8,
+ fn send(self: McpCall, a: Allocator, params: []const u8) anyerror!Value {
+ return request(self.server, a, params, "tools/call", self.name);
+ }
+};
+
+pub const CallResult = struct { text: []u8, is_error: bool };
+
+/// The registry lock is held throughout. Never replay a possibly executed call.
+pub fn call(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input: Value, context: ?@import("mcp_turn_context.zig").Snapshot) !CallResult {
+ return invoke(reg, out_alloc, qualified, input, context) catch |err| switch (err) {
+ error.McpClosed, error.ReadFailed, error.WriteFailed, error.BrokenPipe, error.ConnectionResetByPeer => blk: {
+ try withdrawServer(reg, qualified);
+ break :blk .{
+ .text = try std.fmt.allocPrint(out_alloc, "MCP service connection closed or failed ({s}). Its tools have been withdrawn from the catalog. The tool may not have completed; it was not retried automatically. Inspect /mcp, restart the service and this session, then reload its tool schemas.", .{@errorName(err)}),
+ .is_error = true,
+ };
+ },
+ else => return err,
+ };
+}
+
+fn withdrawServer(reg: *Registry, qualified: []const u8) !void {
+ const server_index = for (reg.tools) |tool| {
+ if (std.mem.eql(u8, tool.qualified_name, qualified)) break tool.server_index;
+ } else return;
+ var available: std.ArrayList(@import("mcp.zig").Tool) = .empty;
+ for (reg.tools) |tool| if (tool.server_index != server_index) try available.append(reg.arena(), tool);
+ // Replace the slice instead of mutating snapshots held by in-flight callers.
+ reg.tools = try available.toOwnedSlice(reg.arena());
+ reg.catalog_dirty.store(true, .release);
+}
+
+fn invoke(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input: Value, context: ?@import("mcp_turn_context.zig").Snapshot) !CallResult {
+ const tool = for (reg.tools) |t| {
+ if (std.mem.eql(u8, t.qualified_name, qualified)) break t;
+ } else {
+ reg.catalog_dirty.store(true, .release);
+ return .{ .text = try out_alloc.dupe(u8, "MCP tool is not registered in the current connection. Its loaded schema may be stale. The next catalog will reflect the current registration. Inspect /mcp, restart the session to reconnect the configured service, then reload its schema before retrying."), .is_error = true };
+ };
+
+ const server = reg.servers[tool.server_index];
+ const turn_ctx = @import("mcp_turn_context.zig").effective(context, reg.io, server.name);
+ const params = try @import("mcp_turn_context.zig").params(reg.gpa, server.name, tool.original_name, input, turn_ctx);
+ defer reg.gpa.free(params);
+
+ // Tool responses can be large and numerous; keep them out of the
+ // session arena. Only the returned text is copied to `out_alloc`.
+ var response_arena_state = std.heap.ArenaAllocator.init(reg.gpa);
+ defer response_arena_state.deinit();
+ const response_alloc = response_arena_state.allocator();
+ if (server.transport == .dormant) @import("mcp_lazy.zig").wake(reg, server) catch |err|
+ return .{ .text = try std.fmt.allocPrint(out_alloc, "MCP server {s} failed to start: {t}", .{ server.name, err }), .is_error = true };
+ if (!server.initialized) try initializeServer(server, response_alloc, reg.arena(), null);
+ server.elicit_source = params;
+ defer server.elicit_source = "";
+ const first_resp = request(server, response_alloc, params, "tools/call", tool.original_name) catch |err| switch (err) {
+ // Streamable HTTP servers use 404 to expire a session. Re-run the
+ // MCP handshake once, then retry the call without the stale ID.
+ // A modern-era server never carries a session id in the first
+ // place (mcp_http never sends/stores one for a modern request),
+ // so this cannot structurally fire for one — the explicit guard
+ // is defense-in-depth against a future refactor resurrecting a
+ // re-handshake loop against a server that has no `initialize`.
+ error.McpSessionExpired => retry: {
+ if (server.era != .legacy) return err;
+ try initializeServer(server, response_alloc, reg.arena(), null);
+ break :retry try request(server, response_alloc, params, "tools/call", tool.original_name);
+ },
+ else => return err,
+ };
+
+ // Resolve bounded MRTR input requests before interpreting the tool result.
+ const call_ctx: McpCall = .{ .server = server, .name = tool.original_name };
+ const resp = try @import("mcp_mrtr.zig").resolve(response_alloc, params, first_resp, call_ctx, McpCall.send);
+ if (resp != .object) return error.BadMcpResponse;
+
+ if (resp.object.get("error")) |e| {
+ // Protocol-level failure (unknown tool, invalid args, server
+ // crash) — distinct from a tool that ran and *returned* an error
+ // (isError below). Keep the JSON-RPC code: models retry better
+ // when they can tell -32602 bad-params from a tool-side failure.
+ const msg = if (e == .object) blk: {
+ const m = e.object.get("message") orelse break :blk "MCP error";
+ break :blk if (m == .string) m.string else "MCP error";
+ } else "MCP error";
+ const code: i64 = if (e == .object) blk: {
+ const c = e.object.get("code") orelse break :blk 0;
+ break :blk if (c == .integer) c.integer else 0;
+ } else 0;
+ if (mcp_elicitation.looksUnavailable(msg))
+ return .{ .text = try out_alloc.dupe(u8, mcp_elicitation.fallback), .is_error = true };
+ const text = if (code != 0)
+ try std.fmt.allocPrint(out_alloc, "MCP error {d}: {s}", .{ code, msg })
+ else
+ try out_alloc.dupe(u8, msg);
+ return .{ .text = text, .is_error = true };
+ }
+ // A well-formed JSON-RPC reply has `result` xor `error`; `error` was
+ // handled above. Guard a malformed server that sends neither (or a
+ // non-object result) instead of force-unwrapping into a panic.
+ const result_val = resp.object.get("result") orelse
+ return .{ .text = try out_alloc.dupe(u8, "MCP response had neither result nor error"), .is_error = true };
+ if (result_val != .object)
+ return .{ .text = try out_alloc.dupe(u8, "MCP response result was not an object"), .is_error = true };
+ const result = result_val.object;
+ // resultType absent MUST read as "complete". input_required was
+ // resolved above; any other type is surfaced, never returned as "".
+ if (!mcp_protocol.resultIsComplete(result))
+ return .{ .text = try out_alloc.dupe(u8, "MCP server returned an unsupported resultType"), .is_error = true };
+ const is_error = if (result.get("isError")) |v| (v == .bool and v.bool) else false;
+
+ var ow: Io.Writer.Allocating = .init(out_alloc);
+ errdefer ow.deinit();
+ if (tool.ui_resource_uri) |uri| {
+ const path = @import("mcp_apps.zig").snapshot(reg.io, response_alloc, reg.home, server, uri, input, result_val) catch null;
+ if (path) |p| {
+ reg.last_app_path = try reg.arena().dupe(u8, p);
+ try ow.writer.print("[MCP app]({s}) — saved interactive result; /mcp apps opens it in a browser.\n", .{p});
+ } else try ow.writer.writeAll("[MCP app view unavailable; ordinary tool output follows.]\n");
+ }
+ const prefix_len = ow.writer.buffered().len;
+ if (result.get("content")) |content| try renderContent(&ow.writer, content, .{
+ .arena = reg.arena(),
+ .slot = &reg.pending_image,
+ .label = qualified,
+ .supports_vision = reg.vision_capable,
+ });
+ // 2025-06-18+ structured tool output: if the server sent only
+ // structuredContent (no text blocks), surface it instead of "".
+ if (ow.writer.buffered().len == prefix_len) {
+ if (result.get("structuredContent")) |sc| {
+ var sw: std.json.Stringify = .{ .writer = &ow.writer };
+ try sw.write(sc);
+ }
+ }
+ const text = try ow.toOwnedSlice();
+ if (mcp_elicitation.looksUnavailable(text)) {
+ out_alloc.free(text);
+ return .{ .text = try out_alloc.dupe(u8, mcp_elicitation.fallback), .is_error = true };
+ }
+ return .{ .text = text, .is_error = is_error };
+}
diff --git a/src/mcp_rpc_tests.zig b/src/mcp_rpc_tests.zig
index 9c12bbb1..881b2c89 100644
--- a/src/mcp_rpc_tests.zig
+++ b/src/mcp_rpc_tests.zig
@@ -18,6 +18,126 @@ const mcp_stdio = @import("mcp_stdio.zig");
const modern_protocol = @import("mcp_protocol.zig").modern_protocol;
const Server = mcp_rpc.Server;
+const Registry = @import("mcp.zig").Registry;
+
+fn fixtureRegistry(reg: *Registry, server: *Server) !void {
+ const a = reg.arena();
+ reg.servers = try a.dupe(*Server, &.{server});
+ reg.tools = try a.dupe(@import("mcp.zig").Tool, &.{.{
+ .server_index = 0,
+ .server_name = "fixture",
+ .original_name = "whoami",
+ .qualified_name = "mcp__fixture__whoami",
+ .description = "fixture identity",
+ .input_schema = try parse(a, "{\"type\":\"object\"}"),
+ }});
+}
+
+test "MCP recovery #1467: first call EOF returns restart guidance without replay" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ var reg = Registry.empty(std.testing.allocator, std.testing.io);
+ defer reg.deinit();
+ const spawned = try spawnReplying(reg.arena(), reg.io, "read line; exit 0");
+ try fixtureRegistry(&reg, spawned.server);
+ const gate = @import("mcp_schema_gate.zig");
+ gate.reset();
+ defer gate.reset();
+ _ = try gate.loadInto(reg.arena(), reg.tools, try parse(reg.arena(), "{\"tools\":[\"mcp__fixture__whoami\"]}"));
+ var agent: @import("agent.zig").Agent = undefined;
+ agent.arena = reg.arena();
+ agent.sub = false;
+ agent.registry = &reg;
+ agent.tools_responses = "";
+ agent.provider = .{ .id = "xai", .kind = .responses, .auth = .bearer, .url = "", .api_key = "fixture", .model = "grok-4.6", .context = 100_000 };
+ try agent.ensureRootTools(.responses);
+ try std.testing.expect(std.mem.indexOf(u8, agent.toolsJson(), "mcp__fixture__whoami") != null);
+ const result = try reg.call(std.testing.allocator, "mcp__fixture__whoami", try parse(reg.arena(), "{}"));
+ defer std.testing.allocator.free(result.text);
+ try std.testing.expect(result.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, result.text, "McpClosed") != null);
+ try std.testing.expect(std.mem.indexOf(u8, result.text, "restart the service and this session") != null);
+ try std.testing.expectEqual(@as(i64, 2), spawned.server.next_id);
+ try std.testing.expectEqual(@as(usize, 0), (try reg.snapshotTools(reg.arena())).len);
+ try std.testing.expect(reg.catalog_dirty.load(.acquire));
+ try agent.ensureRootTools(.responses);
+ try std.testing.expect(std.mem.indexOf(u8, agent.toolsJson(), "mcp__fixture__whoami") == null);
+ try std.testing.expect(!reg.catalog_dirty.load(.acquire));
+}
+
+test "MCP recovery #1465: stale schema reports current registration and reload guidance" {
+ var reg = Registry.empty(std.testing.allocator, std.testing.io);
+ defer reg.deinit();
+ const result = try reg.call(std.testing.allocator, "mcp__fixture__whoami", .null);
+ defer std.testing.allocator.free(result.text);
+ try std.testing.expect(result.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, result.text, "schema may be stale") != null);
+ try std.testing.expect(std.mem.indexOf(u8, result.text, "reload its schema") != null);
+ try std.testing.expect(reg.catalog_dirty.load(.acquire));
+}
+
+test "MCP recovery #1465: advertised loaded schema dispatches across consecutive calls" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ const gate = @import("mcp_schema_gate.zig");
+ gate.reset();
+ defer gate.reset();
+ var reg = Registry.empty(std.testing.allocator, std.testing.io);
+ defer reg.deinit();
+ const spawned = try spawnReplying(reg.arena(), reg.io,
+ \\read line; printf '%s\n' '{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"ok"}]}}'
+ \\read line; printf '%s\n' '{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"ok"}]}}'
+ \\cat >/dev/null
+ );
+ try fixtureRegistry(&reg, spawned.server);
+ const a = reg.arena();
+ const loaded = try gate.loadInto(a, try reg.snapshotTools(a), try parse(a, "{\"tools\":[\"mcp__fixture__whoami\"]}"));
+ try std.testing.expect(!loaded.is_error);
+ try std.testing.expectEqual(@as(usize, 1), loaded.loaded);
+ for (0..2) |_| {
+ const result = try reg.call(std.testing.allocator, "mcp__fixture__whoami", try parse(a, "{}"));
+ defer std.testing.allocator.free(result.text);
+ try std.testing.expect(!result.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, result.text, "ok") != null);
+ }
+}
+
+test "MCP MRTR registry dispatch resolves input requests before rendering" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ var reg = Registry.empty(std.testing.allocator, std.testing.io);
+ defer reg.deinit();
+ const spawned = try spawnReplying(reg.arena(), reg.io,
+ \\read line; printf '%s\n' '{"jsonrpc":"2.0","id":1,"result":{"resultType":"input_required","inputRequests":{"roots":{"method":"roots/list"}},"requestState":"state"}}'
+ \\read line
+ \\case "$line" in *inputResponses*requestState*) ;; *) exit 1 ;; esac
+ \\printf '%s\n' '{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"done"}]}}'
+ \\cat >/dev/null
+ );
+ try fixtureRegistry(&reg, spawned.server);
+ const result = try reg.call(std.testing.allocator, "mcp__fixture__whoami", try parse(reg.arena(), "{}"));
+ defer std.testing.allocator.free(result.text);
+ try std.testing.expect(!result.is_error);
+ try std.testing.expectEqualStrings("done", result.text);
+ try std.testing.expectEqual(@as(i64, 3), spawned.server.next_id);
+ try std.testing.expect(!reg.catalog_dirty.load(.acquire));
+}
+
+test "MCP recovery during MRTR withdraws tools without replay" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ var reg = Registry.empty(std.testing.allocator, std.testing.io);
+ defer reg.deinit();
+ const spawned = try spawnReplying(reg.arena(), reg.io,
+ \\read line; printf '%s\n' '{"jsonrpc":"2.0","id":1,"result":{"resultType":"input_required","inputRequests":{"roots":{"method":"roots/list"}}}}'
+ \\read line; exit 0
+ );
+ try fixtureRegistry(&reg, spawned.server);
+ const result = try reg.call(std.testing.allocator, "mcp__fixture__whoami", try parse(reg.arena(), "{}"));
+ defer std.testing.allocator.free(result.text);
+ try std.testing.expect(result.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, result.text, "McpClosed") != null);
+ try std.testing.expectEqual(@as(i64, 3), spawned.server.next_id);
+ try std.testing.expectEqual(@as(usize, 0), (try reg.snapshotTools(reg.arena())).len);
+ try std.testing.expect(reg.catalog_dirty.load(.acquire));
+}
+
fn parse(a: std.mem.Allocator, json: []const u8) !Value {
return std.json.parseFromSliceLeaky(Value, a, json, .{ .allocate = .alloc_always });
}
diff --git a/src/peer_channel.zig b/src/peer_channel.zig
index bd2239ba..ebdc6279 100644
--- a/src/peer_channel.zig
+++ b/src/peer_channel.zig
@@ -468,29 +468,11 @@ pub fn peekCommand(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Wr
/// The "live now" section /sessions appends under the saved-session list:
/// this worktree first, then the rest of the device.
pub fn writeLiveSection(root: *Agent, arena: Allocator, out: *Io.Writer) !void {
- const everyone = presence.liveAllPeers(root.io, arena);
- if (everyone.len == 0) return;
- const mine = presence.ownIdentity();
- var wrote_local = false;
- var wrote_remote = false;
- for (everyone) |p| {
- const local = std.mem.eql(u8, p.identity, mine);
- if (local and !wrote_local) {
- try out.writeAll(" live now in this worktree:\n");
- wrote_local = true;
- }
- if (!local and !wrote_remote) {
- try out.writeAll(" live elsewhere on this device:\n");
- wrote_remote = true;
- }
- const goal = if (p.goal.len > 0) p.goal else "?";
- const shown = if (p.title.len > 0) p.title else p.session_id;
- const base = if (p.session_base.len > 0) p.session_base else p.session_id;
- if (local)
- try out.print(" ⚡ {s} · {s} · {s} · pid {d} · goal: {s}\n", .{ shown, base, p.session_id, p.pid, goal })
- else
- try out.print(" ⚡ {s} · {s} · {s} · pid {d} · {s} · goal: {s}\n", .{ shown, base, p.session_id, p.pid, p.identity, goal });
- }
+ try @import("peer_live.zig").write(arena, out, presence.liveAllPeers(root.io, arena), presence.ownIdentity(), @import("util.zig").unixMs(root.io));
+}
+
+test {
+ _ = @import("peer_live.zig");
}
test "summarizeTranscript: last prompt, last words, last tool, from complete lines only" {
diff --git a/src/peer_live.zig b/src/peer_live.zig
new file mode 100644
index 00000000..c2b8de5b
--- /dev/null
+++ b/src/peer_live.zig
@@ -0,0 +1,132 @@
+//! Human-facing live sessions: explicit groups, recent turn activity, readable fields.
+const std = @import("std");
+const Owner = @import("worktree_lease.zig").Owner;
+
+fn lessThan(_: void, a: Owner, b: Owner) bool {
+ const a_time = @max(0, a.last_activity_ms);
+ const b_time = @max(0, b.last_activity_ms);
+ if (a_time != b_time) return a_time > b_time;
+ const id_order = std.mem.order(u8, a.session_id, b.session_id);
+ if (id_order != .eq) return id_order == .lt;
+ const tree_order = std.mem.order(u8, a.identity, b.identity);
+ if (tree_order != .eq) return tree_order == .lt;
+ if (a.pid != b.pid) return a.pid < b.pid;
+ return a.start_id < b.start_id;
+}
+
+fn age(out: *std.Io.Writer, timestamp: i64, now: i64) !void {
+ if (timestamp <= 0) return out.writeAll("unknown");
+ const elapsed = @max(0, now -| timestamp);
+ if (elapsed < std.time.ms_per_min)
+ try out.writeAll("just now")
+ else if (elapsed < std.time.ms_per_hour)
+ try out.print("{d}m ago", .{@divTrunc(elapsed, std.time.ms_per_min)})
+ else if (elapsed < std.time.ms_per_day)
+ try out.print("{d}h ago", .{@divTrunc(elapsed, std.time.ms_per_hour)})
+ else
+ try out.print("{d}d ago", .{@divTrunc(elapsed, std.time.ms_per_day)});
+}
+
+// Preserve each field on one visual row even when a title or goal contains newlines.
+fn field(out: *std.Io.Writer, text: []const u8) !void {
+ for (text) |c| try out.writeByte(if (c < 0x20 or c == 0x7f) ' ' else c);
+}
+
+pub fn write(arena: std.mem.Allocator, out: *std.Io.Writer, peers: []const Owner, mine: []const u8, now: i64) !void {
+ const sorted = try arena.dupe(Owner, peers);
+ defer arena.free(sorted);
+ std.mem.sort(Owner, sorted, {}, lessThan);
+ for ([_]bool{ true, false }) |local_group| {
+ var heading = false;
+ for (sorted) |p| {
+ const local = std.mem.eql(u8, p.identity, mine);
+ if (local != local_group) continue;
+ if (!heading) {
+ try out.writeAll(if (local) " live now in this worktree:\n" else " live elsewhere on this device:\n");
+ heading = true;
+ }
+ const shown = if (p.title.len > 0) p.title else if (p.session_id.len > 0) p.session_id else "untitled session";
+ try out.writeAll(" ⚡ ");
+ try field(out, shown);
+ try out.writeAll("\n status: ");
+ try field(out, p.activity);
+ try out.writeAll(" · last active: ");
+ try age(out, p.last_activity_ms, now);
+ try out.print(" · pid {d}\n", .{p.pid});
+ if (p.session_id.len > 0 and !std.mem.eql(u8, shown, p.session_id)) {
+ try out.writeAll(" session: ");
+ try field(out, p.session_id);
+ try out.writeAll("\n");
+ }
+ if (p.session_base.len > 0 and !std.mem.eql(u8, p.session_base, shown) and !std.mem.eql(u8, p.session_base, p.session_id)) {
+ try out.writeAll(" saved as: ");
+ try field(out, p.session_base);
+ try out.writeAll("\n");
+ }
+ if (!local) {
+ try out.writeAll(" worktree: ");
+ try field(out, p.identity);
+ try out.writeAll("\n");
+ }
+ try out.writeAll(" goal: ");
+ try field(out, if (p.goal.len > 0) p.goal else "?");
+ try out.writeAll("\n\n");
+ }
+ }
+}
+
+test "live sessions group before sorting activity and never use registry freshness" {
+ const peers = [_]Owner{
+ .{ .session_id = "remote-new", .identity = "elsewhere", .last_activity_ms = 3000 },
+ .{ .session_id = "local-old", .identity = "here", .last_activity_ms = 1000, .last_seen_ms = 999999 },
+ .{ .session_id = "remote-old", .identity = "elsewhere", .last_activity_ms = 1000 },
+ .{ .session_id = "local-new", .identity = "here", .last_activity_ms = 2000 },
+ .{ .session_id = "local-unknown", .identity = "here", .last_seen_ms = 9999999 },
+ };
+ var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
+ defer out.deinit();
+ try write(std.testing.allocator, &out.writer, &peers, "here", 62000);
+ const text = out.writer.buffered();
+ var previous: usize = 0;
+ for ([_][]const u8{ "live now in this worktree:", "⚡ local-new", "⚡ local-old", "⚡ local-unknown", "live elsewhere on this device:", "⚡ remote-new", "⚡ remote-old" }) |needle| {
+ const index = std.mem.indexOf(u8, text, needle) orelse return error.MissingRow;
+ try std.testing.expect(index >= previous);
+ previous = index;
+ }
+ try std.testing.expect(std.mem.indexOf(u8, text, "last active: unknown") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "last active: 1m ago") != null);
+}
+
+test "live sessions stable ties and unknown times ignore directory order" {
+ const a: Owner = .{ .session_id = "a", .identity = "here" };
+ const b: Owner = .{ .session_id = "b", .identity = "here" };
+ var first: std.Io.Writer.Allocating = .init(std.testing.allocator);
+ defer first.deinit();
+ var second: std.Io.Writer.Allocating = .init(std.testing.allocator);
+ defer second.deinit();
+ try write(std.testing.allocator, &first.writer, &.{ b, a }, "here", 100000);
+ try write(std.testing.allocator, &second.writer, &.{ a, b }, "here", 100000);
+ try std.testing.expectEqualStrings(first.writer.buffered(), second.writer.buffered());
+}
+
+test "live sessions indented fields separate rows without repeated fallback ids" {
+ var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
+ defer out.deinit();
+ try write(std.testing.allocator, &out.writer, &.{
+ .{ .session_id = "session-id", .session_base = "session-id", .identity = "here", .pid = 7 },
+ .{ .session_id = "other-id", .title = "A title\nsecond line", .session_base = "a-slug", .identity = "elsewhere", .goal = "a goal\nnext", .pid = 8, .last_activity_ms = 200000 },
+ }, "here", 100000);
+ const text = out.writer.buffered();
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "session-id"));
+ try std.testing.expect(std.mem.indexOf(u8, text, " goal: ?\n\n live elsewhere") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "⚡ A title second line\n status:") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, " session: other-id\n saved as: a-slug\n worktree: elsewhere\n goal: a goal next\n\n") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "last active: just now") != null);
+}
+
+test "live sessions empty registry emits no headings" {
+ var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
+ defer out.deinit();
+ try write(std.testing.allocator, &out.writer, &.{}, "here", 0);
+ try std.testing.expectEqual(@as(usize, 0), out.writer.buffered().len);
+}
diff --git a/src/presence.zig b/src/presence.zig
index 907c2269..6026a45e 100644
--- a/src/presence.zig
+++ b/src/presence.zig
@@ -138,8 +138,11 @@ var g_acked: [max_peers]u64 = undefined;
var g_acked_len: usize = 0;
var g_activity: []const u8 = "waiting";
+var g_activity_ms: i64 = 0;
pub fn noteActivity(io: Io, arena: Allocator, working: bool) void {
+ if (g_own_name == null) return;
g_activity = if (working) "working" else "waiting";
+ g_activity_ms = unixMs(io);
writeOwn(io, arena);
}
@@ -149,6 +152,7 @@ fn writeOwn(io: Io, arena: Allocator) void {
var owner = worktree_lease.selfOwner(io, g_identity, g_session, unixMs(io));
owner.goal = g_goal;
owner.activity = g_activity;
+ owner.last_activity_ms = g_activity_ms;
owner.title = g_title;
owner.session_base = g_session_base;
const text = formatRecord(arena, owner) catch return;
@@ -242,6 +246,8 @@ pub fn deinit(gpa: Allocator) void {
g_device_off = 0;
g_tail_seeked = false;
g_acked_len = 0;
+ g_activity = "waiting";
+ g_activity_ms = 0;
}
pub fn retire(io: Io) void {
@@ -534,63 +540,42 @@ pub fn drainDevice(io: Io, arena: Allocator) []const Message {
return out.items;
}
-test "roomCursor adopt/reset: resume continues from the saved byte offset" {
- resetRoomCursorForTest();
- defer resetRoomCursorForTest();
- adoptRoomCursor(.{ .chan = 4096, .device = 128 });
- const cur = roomCursor();
- try std.testing.expectEqual(@as(u64, 4096), cur.chan);
- try std.testing.expectEqual(@as(u64, 128), cur.device);
- resetRoomCursorForTest();
- try std.testing.expectEqual(@as(u64, 0), roomCursor().chan);
+test {
+ _ = @import("presence_tests.zig");
}
-test "listPeers: probes liveness, reaps the provably dead, keeps the alive" {
- // Windows: the live self-record probes .gone on the runner (OpenProcess on own pid fails there) — skip until diagnosed on a real Windows box.
- if (builtin.os.tag == .windows) return error.SkipZigTest;
+test "presence activity records turn boundaries but not metadata rewrites" {
const io = std.testing.io;
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
- const self = proc_identity.selfRecord(io);
- const alive: Owner = .{ .pid = self.pid, .start_id = self.start_id, .session_id = "s-live", .identity = "/x/.git", .goal = "g" };
- try tmp.dir.writeFile(io, .{ .sub_path = "live.json", .data = try formatRecord(arena, alive) });
- // pid -7 can never hold a process (probe: pid <= 0 is .gone), so the reap path is exercised identically on every platform.
- const dead: Owner = .{ .pid = -7, .start_id = 1, .session_id = "s-dead", .identity = "/x/.git" };
- try tmp.dir.writeFile(io, .{ .sub_path = "dead.json", .data = try formatRecord(arena, dead) });
- // Reopen with .iterate: tmpDir's handle isn't iteration-capable on the Linux backend (dirRead seeks an O_PATH fd → EBADF panic, the CI crash).
- var idir = try tmp.dir.openDir(io, ".", .{ .iterate = true });
- defer idir.close(io);
- const peers = listPeers(io, arena, idir);
- try std.testing.expectEqual(1, peers.records.len);
- try std.testing.expectEqualStrings("s-live", peers.records[0].session_id);
- var buf: [16]u8 = undefined;
- try std.testing.expectError(error.FileNotFound, tmp.dir.readFile(io, "dead.json", &buf));
-}
-
-test "unackedPeer: returns the live foreign co-owner once, then yields to the ack" {
- const my_identity = "/repo/.git";
- const foreign: Owner = .{ .pid = 4242, .start_id = 99, .session_id = "s-b", .identity = "/repo/.git", .goal = "theirs" };
- const other_tree: Owner = .{ .pid = 4343, .start_id = 98, .session_id = "s-c", .identity = "/repo/.git/worktrees/wt1" };
- const records = [_]Owner{ other_tree, foreign };
- const probes = [_]proc_identity.Probe{ .{ .id = 98 }, .{ .id = 99 } };
- const peers: Peers = .{ .records = &records, .probes = &probes };
- const found = unackedPeer(peers, my_identity, 1, &.{}) orelse return error.ExpectedPeer;
- try std.testing.expectEqualStrings("s-b", found.session_id);
- const key = ackKey(found);
- try std.testing.expect(unackedPeer(peers, my_identity, 1, &.{key}) == null);
- // A new session reusing that pid is a NEW peer, not an acked one.
- const reused: Owner = .{ .pid = 4242, .start_id = 100, .session_id = "s-d", .identity = "/repo/.git" };
- const records2 = [_]Owner{reused};
- const probes2 = [_]proc_identity.Probe{.{ .id = 100 }};
- try std.testing.expect(unackedPeer(.{ .records = &records2, .probes = &probes2 }, my_identity, 1, &.{key}) != null);
-}
-
-test "lean one-shots skip the shared-tree checkpoint" {
- const saved = no_local_tools.lean;
- defer no_local_tools.lean = saved;
- no_local_tools.lean = true;
- try std.testing.expect(gateCheck(std.testing.io, std.testing.allocator) == null);
+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path_len = try tmp.dir.realPath(io, &path_buf);
+ bindForTest(path_buf[0..path_len], "/test/.git", "activity-test", proc_identity.selfRecord(io));
+ g_own_name = "activity.json";
+ defer {
+ g_own_name = null;
+ g_activity = "waiting";
+ g_activity_ms = 0;
+ unbindForTest();
+ }
+ // Startup/metadata refresh is not evidence of a turn.
+ writeOwn(io, arena);
+ const initial = parseRecord(arena, try tmp.dir.readFileAlloc(io, "activity.json", arena, .limited(record_max))).?;
+ try std.testing.expectEqual(@as(i64, 0), initial.last_activity_ms);
+ for ([_]bool{ true, false }) |working| {
+ noteActivity(io, arena, working);
+ const active = parseRecord(arena, try tmp.dir.readFileAlloc(io, "activity.json", arena, .limited(record_max))).?;
+ try std.testing.expect(active.last_activity_ms > 0);
+ try std.testing.expectEqualStrings(if (working) "working" else "waiting", active.activity);
+ // Make the distinction deterministic even on a same-millisecond rewrite.
+ g_activity_ms = 1234;
+ writeOwn(io, arena);
+ const refreshed = parseRecord(arena, try tmp.dir.readFileAlloc(io, "activity.json", arena, .limited(record_max))).?;
+ try std.testing.expectEqual(@as(i64, 1234), refreshed.last_activity_ms);
+ try std.testing.expect(refreshed.last_seen_ms > refreshed.last_activity_ms);
+ try std.testing.expectEqualStrings(active.activity, refreshed.activity);
+ }
}
diff --git a/src/presence_record.zig b/src/presence_record.zig
index b37165cb..f185f3c1 100644
--- a/src/presence_record.zig
+++ b/src/presence_record.zig
@@ -17,6 +17,7 @@ const RecordJson = struct {
identity: []const u8 = "",
goal: []const u8 = "",
last_seen_ms: i64 = 0,
+ last_activity_ms: i64 = 0,
activity: []const u8 = "connected",
title: []const u8 = "",
session_base: []const u8 = "",
@@ -32,6 +33,7 @@ pub fn formatRecord(arena: Allocator, owner: Owner) ![]const u8 {
.identity = owner.identity,
.goal = owner.goal,
.last_seen_ms = owner.last_seen_ms,
+ .last_activity_ms = owner.last_activity_ms,
.activity = owner.activity,
.title = owner.title,
.session_base = owner.session_base,
@@ -49,6 +51,7 @@ pub fn parseRecord(arena: Allocator, text: []const u8) ?Owner {
.identity = rec.identity,
.goal = rec.goal,
.last_seen_ms = rec.last_seen_ms,
+ .last_activity_ms = rec.last_activity_ms,
.activity = rec.activity,
.title = rec.title,
.session_base = rec.session_base,
@@ -66,6 +69,7 @@ test "presence record round-trips pid, identity, goal, title, and base" {
.identity = "/repo/.git",
.goal = "agent-inbox redesign",
.last_seen_ms = 123456,
+ .last_activity_ms = 120000,
.title = "Fixing login recovery",
.session_base = "fixing-login-recovery",
};
@@ -77,6 +81,7 @@ test "presence record round-trips pid, identity, goal, title, and base" {
try std.testing.expectEqualStrings(owner.identity, back.identity);
try std.testing.expectEqualStrings(owner.goal, back.goal);
try std.testing.expectEqual(owner.last_seen_ms, back.last_seen_ms);
+ try std.testing.expectEqual(owner.last_activity_ms, back.last_activity_ms);
try std.testing.expectEqualStrings(owner.title, back.title);
try std.testing.expectEqualStrings(owner.session_base, back.session_base);
}
@@ -89,6 +94,7 @@ test "parseRecord: rejects garbage and pid-less records, tolerates extra fields"
try std.testing.expect(parseRecord(arena, "{\"goal\":\"x\"}") == null);
const forward = parseRecord(arena, "{\"pid\":7,\"start_id\":3,\"future\":\"field\"}") orelse return error.ExpectedRecord;
try std.testing.expectEqual(7, forward.pid);
+ try std.testing.expectEqual(@as(i64, 0), forward.last_activity_ms);
try std.testing.expectEqualStrings("", forward.title);
try std.testing.expectEqualStrings("", forward.session_base);
}
diff --git a/src/presence_tests.zig b/src/presence_tests.zig
new file mode 100644
index 00000000..3fe43135
--- /dev/null
+++ b/src/presence_tests.zig
@@ -0,0 +1,77 @@
+//! Presence registry and room-cursor regressions.
+const std = @import("std");
+const builtin = @import("builtin");
+const presence = @import("presence.zig");
+const proc_identity = @import("proc_identity.zig");
+const no_local_tools = @import("no_local_tools.zig");
+const Owner = @import("worktree_lease.zig").Owner;
+const Peers = presence.Peers;
+const resetRoomCursorForTest = presence.resetRoomCursorForTest;
+const adoptRoomCursor = presence.adoptRoomCursor;
+const roomCursor = presence.roomCursor;
+const formatRecord = presence.formatRecord;
+const listPeers = presence.listPeers;
+const unackedPeer = presence.unackedPeer;
+const ackKey = presence.ackKey;
+const gateCheck = presence.gateCheck;
+
+test "roomCursor adopt/reset: resume continues from the saved byte offset" {
+ resetRoomCursorForTest();
+ defer resetRoomCursorForTest();
+ adoptRoomCursor(.{ .chan = 4096, .device = 128 });
+ const cur = roomCursor();
+ try std.testing.expectEqual(@as(u64, 4096), cur.chan);
+ try std.testing.expectEqual(@as(u64, 128), cur.device);
+ resetRoomCursorForTest();
+ try std.testing.expectEqual(@as(u64, 0), roomCursor().chan);
+}
+
+test "listPeers: probes liveness, reaps the provably dead, keeps the alive" {
+ // Windows: the live self-record probes .gone on the runner (OpenProcess on own pid fails there) — skip until diagnosed on a real Windows box.
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ const io = std.testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const self = proc_identity.selfRecord(io);
+ const alive: Owner = .{ .pid = self.pid, .start_id = self.start_id, .session_id = "s-live", .identity = "/x/.git", .goal = "g" };
+ try tmp.dir.writeFile(io, .{ .sub_path = "live.json", .data = try formatRecord(arena, alive) });
+ // pid -7 can never hold a process (probe: pid <= 0 is .gone), so the reap path is exercised identically on every platform.
+ const dead: Owner = .{ .pid = -7, .start_id = 1, .session_id = "s-dead", .identity = "/x/.git" };
+ try tmp.dir.writeFile(io, .{ .sub_path = "dead.json", .data = try formatRecord(arena, dead) });
+ // Reopen with .iterate: tmpDir's handle isn't iteration-capable on the Linux backend (dirRead seeks an O_PATH fd → EBADF panic, the CI crash).
+ var idir = try tmp.dir.openDir(io, ".", .{ .iterate = true });
+ defer idir.close(io);
+ const peers = listPeers(io, arena, idir);
+ try std.testing.expectEqual(1, peers.records.len);
+ try std.testing.expectEqualStrings("s-live", peers.records[0].session_id);
+ var buf: [16]u8 = undefined;
+ try std.testing.expectError(error.FileNotFound, tmp.dir.readFile(io, "dead.json", &buf));
+}
+
+test "unackedPeer: returns the live foreign co-owner once, then yields to the ack" {
+ const my_identity = "/repo/.git";
+ const foreign: Owner = .{ .pid = 4242, .start_id = 99, .session_id = "s-b", .identity = "/repo/.git", .goal = "theirs" };
+ const other_tree: Owner = .{ .pid = 4343, .start_id = 98, .session_id = "s-c", .identity = "/repo/.git/worktrees/wt1" };
+ const records = [_]Owner{ other_tree, foreign };
+ const probes = [_]proc_identity.Probe{ .{ .id = 98 }, .{ .id = 99 } };
+ const peers: Peers = .{ .records = &records, .probes = &probes };
+ const found = unackedPeer(peers, my_identity, 1, &.{}) orelse return error.ExpectedPeer;
+ try std.testing.expectEqualStrings("s-b", found.session_id);
+ const key = ackKey(found);
+ try std.testing.expect(unackedPeer(peers, my_identity, 1, &.{key}) == null);
+ // A new session reusing that pid is a NEW peer, not an acked one.
+ const reused: Owner = .{ .pid = 4242, .start_id = 100, .session_id = "s-d", .identity = "/repo/.git" };
+ const records2 = [_]Owner{reused};
+ const probes2 = [_]proc_identity.Probe{.{ .id = 100 }};
+ try std.testing.expect(unackedPeer(.{ .records = &records2, .probes = &probes2 }, my_identity, 1, &.{key}) != null);
+}
+
+test "lean one-shots skip the shared-tree checkpoint" {
+ const saved = no_local_tools.lean;
+ defer no_local_tools.lean = saved;
+ no_local_tools.lean = true;
+ try std.testing.expect(gateCheck(std.testing.io, std.testing.allocator) == null);
+}
diff --git a/src/providers.zig b/src/providers.zig
index e33f4bdb..d9524aa4 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -276,7 +276,7 @@ pub fn resolveProviderControlRequest(
if (provider_id.len != 0) {
if (provider_mod.specFor(provider_id)) |spec| {
const selected_model = if (model.len == 0) pricing.providerDefaultModel(spec.id, spec.default_model) else try arena.dupe(u8, model);
- if (model.len != 0 and !localProviderUrl(spec.url) and !pricing.providerModelInTable(spec.id, selected_model)) return error.InvalidModel;
+ if (model.len != 0 and !localProviderUrl(spec.url) and !catalog_selection.acceptsExplicitModel(spec, selected_model)) return error.InvalidModel;
return keys.providerById(spec.id, selected_model);
}
return error.InvalidProvider;
@@ -341,7 +341,7 @@ fn resolveProviderRequest(keys: *Keys, arena: Allocator, query: []const u8) !Pro
const mdl = std.mem.trim(u8, arg[i + 1 ..], " \t");
if (provider_mod.specFor(pid)) |spec| {
if (mdl.len == 0) return error.InvalidModel;
- if (!localProviderUrl(spec.url) and !pricing.providerModelInTable(pid, mdl)) return error.InvalidModel;
+ if (!localProviderUrl(spec.url) and !catalog_selection.acceptsExplicitModel(spec, mdl)) return error.InvalidModel;
const m = try arena.dupe(u8, mdl);
return keys.providerById(pid, m);
}
diff --git a/src/route_check.zig b/src/route_check.zig
index 6d812643..3780d640 100644
--- a/src/route_check.zig
+++ b/src/route_check.zig
@@ -78,7 +78,12 @@ test "qualified route keeps the selected provider and credential" {
var openai_only: provider_mod.Keys = .{ .values = @splat(null) };
try std.testing.expect(openai_only.set("openai", "metered-token", .session));
try std.testing.expect(seatFor(openai_only, "codex/shared-route-fixture") == .no_credential);
- try std.testing.expect(seatFor(keys, "codex/not-a-model") == .unknown);
+ // Account catalogs can omit a newly rolled-out model; explicit routing
+ // keeps that seat and lets the backend validate it. Metered catalogs stay strict.
+ const omitted = seatFor(keys, "codex/not-in-catalog");
+ try std.testing.expectEqualStrings("codex", omitted.seat.pid);
+ try std.testing.expectEqualStrings("not-in-catalog", omitted.seat.model);
+ try std.testing.expect(seatFor(keys, "openai/not-in-catalog") == .unknown);
}
pub fn billingLabel(b: pricing.Billing) []const u8 {
diff --git a/src/session.zig b/src/session.zig
index 009536a2..055ce2bd 100644
--- a/src/session.zig
+++ b/src/session.zig
@@ -259,6 +259,9 @@ fn queueSave(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !u64
// state — never leave a blank draft as an "Untitled session" on disk. Existing
// files are untouched (we skip the write, we do not delete).
if (!hasMeaningfulState(root)) return 0;
+ if (dir.realPathFileAlloc(root.io, ".", arena)) |workspace|
+ @import("session_workspaces.zig").remember(root.io, arena, root.home, workspace)
+ else |_| {}
// #273: nothing has changed since the last successful write of this session
// AND that write is still what the file holds (a second graff, an editor or
// an rm all invalidate it — the skip is never taken on trust).
diff --git a/src/session_branch.zig b/src/session_branch.zig
index 600c88b1..ca6d530c 100644
--- a/src/session_branch.zig
+++ b/src/session_branch.zig
@@ -46,10 +46,13 @@ pub fn parseSpec(raw: []const u8) ?Spec {
/// provider by startup: see the block after loadSession for why it wins.
/// `/resume` has no such flag and passes null.
pub fn restore(root: *agent_mod.Agent, keys: *provider_mod.Keys, arena: Allocator, source_raw: []const u8, branch_raw: ?[]const u8, model_override: ?provider_mod.Provider) !Result {
- const source = try arena.dupe(u8, source_raw);
+ const selection = try arena.dupe(u8, source_raw);
+ const qualified = @import("session_workspaces.zig").parseTarget(selection);
+ const source = if (qualified) |q| q.base else selection;
if (!session.validSessionName(source)) return Error.InvalidSessionName;
const branch = if (branch_raw) |raw| try arena.dupe(u8, raw) else null;
- const origin = session_discovery.enterOrigin(root, arena, source);
+ const origin = session_discovery.enterOrigin(root, arena, selection);
+ if (qualified != null and origin.kind == .failed) return error.WorkspaceUnavailable;
var reserved_path: ?[]const u8 = null;
if (branch) |dest| {
if (!session.validSessionName(dest)) return Error.InvalidSessionName;
@@ -68,7 +71,7 @@ pub fn restore(root: *agent_mod.Agent, keys: *provider_mod.Keys, arena: Allocato
errdefer if (reserved_path) |path| Io.Dir.cwd().deleteFile(root.io, path) catch {};
root.ensureStoredKeys(keys);
- try session.loadSession(root, keys, arena, source);
+ try session.loadSession(root, keys, arena, selection);
// An explicit --model outranks the model the session file carries: the flag
// is the user's live intent, the saved model is only what the conversation
// last ran on. Without this the restore silently reverted the flag, so a
diff --git a/src/session_discovery.zig b/src/session_discovery.zig
index 60c1d1cd..21c2fcdd 100644
--- a/src/session_discovery.zig
+++ b/src/session_discovery.zig
@@ -12,6 +12,7 @@ const session_index = @import("session_index.zig");
const workspace_switch = @import("workspace_switch.zig");
const Agent = agent_mod.Agent;
+const workspaces = @import("session_workspaces.zig");
pub const Located = struct {
path: []const u8,
@@ -93,10 +94,27 @@ fn extraWorktrees(root: *Agent, arena: Allocator) []const []const u8 {
if (t.path.len == 0) continue;
paths.append(arena, t.path) catch {};
}
+ // Migrate workspaces advertised by older live processes into durable discovery.
+ for (@import("presence.zig").liveAllPeers(root.io, arena)) |peer| {
+ const path = workspaces.fromIdentity(root.io, arena, peer.identity) orelse continue;
+ workspaces.remember(root.io, arena, root.home, path);
+ }
+ for (workspaces.list(root.io, arena, root.home)) |path| {
+ var seen = false;
+ for (paths.items) |p| if (session_index.sameWorkspace(p, path)) {
+ seen = true;
+ break;
+ };
+ if (!seen) paths.append(arena, path) catch {};
+ }
return paths.items;
}
pub fn locate(root: *Agent, arena: Allocator, name: []const u8) ?Located {
+ if (workspaces.parseTarget(name)) |target| {
+ if (!exists(root.io, name)) return null;
+ return .{ .path = name, .workspace = target.workspace, .local = session_index.sameWorkspace(target.workspace, cwdDisplay()) };
+ }
return locateIn(root.io, arena, name, cwdDisplay(), root.home, extraWorktrees(root, arena));
}
@@ -183,7 +201,7 @@ test "locateIn prefers cwd then a linked worktree then home (#1151)" {
try std.testing.expect(!notes.local);
}
-test "appendWorkspaceSessions skips names already listed (#1151)" {
+test "appendWorkspaceSessions preserves same-named saves from different workspaces" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{ .iterate = true });
defer tmp.cleanup();
@@ -205,9 +223,10 @@ test "appendWorkspaceSessions skips names already listed (#1151)" {
var entries: std.ArrayList(session_index.SessionEntry) = .empty;
try entries.append(arena, .{ .base = "shared", .title = "Cwd", .updated_ms = 1, .workspace = "/cwd", .local = true });
session_index.appendWorkspaceSessions(io, arena, &entries, wt, false);
- try std.testing.expectEqual(@as(usize, 2), entries.items.len);
+ try std.testing.expectEqual(@as(usize, 3), entries.items.len);
try std.testing.expectEqualStrings("shared", entries.items[0].base);
try std.testing.expect(entries.items[0].local);
- try std.testing.expectEqualStrings("only", entries.items[1].base);
try std.testing.expect(!entries.items[1].local);
+ session_index.appendWorkspaceSessions(io, arena, &entries, wt, false);
+ try std.testing.expectEqual(@as(usize, 3), entries.items.len);
}
diff --git a/src/session_index.zig b/src/session_index.zig
index 4ead554d..deed4733 100644
--- a/src/session_index.zig
+++ b/src/session_index.zig
@@ -153,7 +153,7 @@ pub fn appendWorkspaceSessions(
for (extra.items) |e| {
var seen = false;
for (entries.items) |c| {
- if (std.mem.eql(u8, c.base, e.base)) {
+ if (std.mem.eql(u8, c.base, e.base) and sameWorkspace(c.workspace, e.workspace)) {
seen = true;
break;
}
diff --git a/src/session_list.zig b/src/session_list.zig
index b9b90ff1..c0b90672 100644
--- a/src/session_list.zig
+++ b/src/session_list.zig
@@ -47,6 +47,7 @@ fn writeRows(root: *Agent, arena: Allocator, out: *Io.Writer, entries: []const s
} else {
try out.print(" {s}{s}{s}{s}{s}{s}{s}{s}\n", .{ e.base, parent, style.dim, if (age.len > 0) " " else "", age, where, style.reset, cur });
}
+ if (!local) try out.print(" /resume {s}\n", .{try @import("session_workspaces.zig").target(arena, e)});
}
}
diff --git a/src/session_workspaces.zig b/src/session_workspaces.zig
new file mode 100644
index 00000000..88351d7f
--- /dev/null
+++ b/src/session_workspaces.zig
@@ -0,0 +1,91 @@
+//! Device-local saved-workspace index. One file per root avoids shared RMW races.
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const index = @import("session_index.zig");
+
+const subdir = ".graff/session-workspaces";
+
+pub fn remember(io: Io, arena: Allocator, home: []const u8, workspace: []const u8) void {
+ if (home.len == 0 or !std.fs.path.isAbsolute(workspace)) return;
+ const path = std.fmt.allocPrint(arena, "{s}/{s}", .{ home, subdir }) catch return;
+ Io.Dir.cwd().createDirPath(io, path) catch return;
+ var dir = Io.Dir.cwd().openDir(io, path, .{}) catch return;
+ defer dir.close(io);
+ const name = std.fmt.allocPrint(arena, "{x}.json", .{std.hash.Wyhash.hash(0, workspace)}) catch return;
+ // Unchanged roots need no write on subsequent autosaves.
+ if (dir.readFileAlloc(io, name, arena, .limited(64 * 1024)) catch null) |old| {
+ const parsed = std.json.parseFromSliceLeaky([]const u8, arena, old, .{}) catch null;
+ if (parsed) |p| if (std.mem.eql(u8, p, workspace)) return;
+ }
+ var out: Io.Writer.Allocating = .init(arena);
+ std.json.Stringify.value(workspace, .{}, &out.writer) catch return;
+ dir.writeFile(io, .{ .sub_path = name, .data = out.written() }) catch {};
+}
+
+pub fn list(io: Io, arena: Allocator, home: []const u8) []const []const u8 {
+ if (home.len == 0) return &.{};
+ const path = std.fmt.allocPrint(arena, "{s}/{s}", .{ home, subdir }) catch return &.{};
+ var dir = Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch return &.{};
+ defer dir.close(io);
+ var roots: std.ArrayList([]const u8) = .empty;
+ var it = dir.iterate();
+ while (it.next(io) catch null) |entry| {
+ if (entry.kind != .file or !std.mem.endsWith(u8, entry.name, ".json")) continue;
+ const text = dir.readFileAlloc(io, entry.name, arena, .limited(64 * 1024)) catch continue;
+ const root = std.json.parseFromSliceLeaky([]const u8, arena, text, .{ .allocate = .alloc_always }) catch continue;
+ if (!std.fs.path.isAbsolute(root)) continue;
+ roots.append(arena, root) catch {};
+ }
+ return roots.items;
+}
+
+pub const Target = struct { workspace: []const u8, base: []const u8 };
+
+/// An absolute session-file path is an explicit workspace-qualified selection.
+pub fn parseTarget(raw: []const u8) ?Target {
+ if (!std.fs.path.isAbsolute(raw) or !std.mem.endsWith(u8, raw, index.session_ext)) return null;
+ const marker = "/" ++ index.sessions_dir ++ "/";
+ const at = std.mem.lastIndexOf(u8, raw, marker) orelse return null;
+ const base = raw[at + marker.len .. raw.len - index.session_ext.len];
+ if (!index.validSessionName(base)) return null;
+ return .{ .workspace = if (at == 0) "/" else raw[0..at], .base = base };
+}
+
+pub fn target(arena: Allocator, entry: index.SessionEntry) ![]const u8 {
+ if (entry.local or !std.fs.path.isAbsolute(entry.workspace)) return entry.base;
+ return std.fmt.allocPrint(arena, "{s}/{s}/{s}{s}", .{ std.mem.trimEnd(u8, entry.workspace, "/"), index.sessions_dir, entry.base, index.session_ext });
+}
+
+/// Presence identities are git directories, or cwd for non-git projects.
+pub fn fromIdentity(io: Io, arena: Allocator, identity: []const u8) ?[]const u8 {
+ if (!std.fs.path.isAbsolute(identity)) return null;
+ if (std.mem.endsWith(u8, identity, "/.git")) return identity[0 .. identity.len - 5];
+ const gitdir = std.fmt.allocPrint(arena, "{s}/gitdir", .{identity}) catch return null;
+ if (Io.Dir.cwd().readFileAlloc(io, gitdir, arena, .limited(64 * 1024)) catch null) |data| {
+ const path = std.mem.trim(u8, data, " \t\r\n");
+ if (std.fs.path.isAbsolute(path) and std.mem.endsWith(u8, path, "/.git")) return path[0 .. path.len - 5];
+ }
+ return identity;
+}
+
+test "session workspace index survives process state and disambiguates qualified targets" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer state.deinit();
+ const arena = state.allocator();
+ const home = try tmp.dir.realPathFileAlloc(io, ".", arena);
+ remember(io, arena, home, "/projects/one");
+ remember(io, arena, home, "/projects/two");
+ remember(io, arena, home, "/projects/one");
+ const roots = list(io, arena, home);
+ try std.testing.expectEqual(@as(usize, 2), roots.len);
+ const path = try target(arena, .{ .base = "same", .workspace = "/projects/two", .local = false });
+ const parsed = parseTarget(path).?;
+ try std.testing.expectEqualStrings("/projects/two", parsed.workspace);
+ try std.testing.expectEqualStrings("same", parsed.base);
+ try std.testing.expect(parseTarget("../same.session.json") == null);
+ try std.testing.expect(parseTarget("/projects/two/.graff/sessions/../same.session.json") == null);
+}
diff --git a/src/startup_keys.zig b/src/startup_keys.zig
index b268fabf..7401b214 100644
--- a/src/startup_keys.zig
+++ b/src/startup_keys.zig
@@ -58,6 +58,60 @@ test "saved startup pair survives a transient catalog omission and reaches the r
try std.testing.expect(std.mem.indexOf(u8, body, "\"model\":\"gpt-6-astra\"") == null);
}
+test "#1466 explicit account model survives an incomplete catalog on startup and ACP" {
+ const original = pricing.active_model_table;
+ defer pricing.active_model_table = original;
+ const snapshot = [_]pricing.ModelInfo{.{ .provider = "codex", .name = "gpt-6-astra", .context = 272_000 }};
+ pricing.active_model_table = &snapshot;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const providers = @import("providers.zig");
+ var keys: provider_mod.Keys = .{ .values = @splat(null) };
+ for (provider_mod.provider_specs) |spec| {
+ if (spec.login == .api_key) continue;
+ try std.testing.expect(keys.set(spec.id, "test-token", .session));
+ const model = "future-account-model";
+ const query = try std.fmt.allocPrint(arena, "{s}/{s}", .{ spec.id, model });
+ const saved = try savedProvider(keys, .{ .pid = spec.id, .model = model });
+ const selections = [_]provider_mod.Provider{
+ (try qualifiedProvider(keys, query)).?,
+ try providers.resolveProviderControlRequest(&keys, arena, spec.id, model, ""),
+ try providers.resolveProviderControlRequest(&keys, arena, "", "", query),
+ };
+ for (selections) |selected| {
+ try std.testing.expectEqualStrings(saved.id, selected.id);
+ try std.testing.expectEqualStrings(saved.model, selected.model);
+ try std.testing.expectEqual(saved.kind, selected.kind);
+ if (std.mem.eql(u8, spec.id, "codex")) {
+ var agent = try @import("agent_request_body_responses.zig").testAgentFor(arena, "codex", .responses, "placeholder");
+ agent.provider = selected;
+ const body = try agent.buildBody(null, false, true, true);
+ defer std.testing.allocator.free(body);
+ try std.testing.expect(std.mem.indexOf(u8, body, "\"model\":\"future-account-model\"") != null);
+ }
+ }
+ }
+}
+
+test "#1466 explicit account model still requires its own credential and nonempty model" {
+ var keys: provider_mod.Keys = .{ .values = @splat(null) };
+ try std.testing.expect(keys.set("codegraff", "unrelated-key", .session));
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const providers = @import("providers.zig");
+ try std.testing.expectError(error.MissingKey, qualifiedProvider(keys, "codex/future-account-model"));
+ try std.testing.expectError(error.MissingKey, providers.resolveProviderControlRequest(&keys, arena, "codex", "future-account-model", ""));
+ try std.testing.expectError(error.MissingKey, providers.resolveProviderControlRequest(&keys, arena, "", "", "codex/future-account-model"));
+ try std.testing.expectError(error.UnknownModel, qualifiedProvider(keys, "codex/"));
+ try std.testing.expectError(error.UnknownModel, qualifiedProvider(keys, "codex/ \t"));
+ try std.testing.expectError(error.InvalidModel, providers.resolveProviderControlRequest(&keys, arena, "", "", "codex/"));
+ try std.testing.expectError(error.InvalidProvider, providers.resolveProviderControlRequest(&keys, arena, "unknown-provider", "future-account-model", ""));
+ try std.testing.expectError(error.InvalidModel, providers.resolveProviderControlRequest(&keys, arena, "", "future-account-model", ""));
+ try std.testing.expectError(error.InvalidModel, providers.resolveProviderControlRequest(&keys, arena, "xiaomi", "future-account-model", ""));
+}
+
test "saved startup pair does not borrow another provider credential" {
var keys: provider_mod.Keys = .{ .values = @splat(null) };
try std.testing.expect(keys.set("codegraff", "unrelated-key", .session));
@@ -74,12 +128,12 @@ pub fn qualifiedProvider(keys: provider_mod.Keys, query: []const u8) error{ Miss
const pid = query[0..slash];
const spec = provider_mod.specFor(pid) orelse return null;
const model = query[slash + 1 ..];
- if (model.len == 0) return error.UnknownModel;
+ if (std.mem.trim(u8, model, " \t").len == 0) return error.UnknownModel;
// Key first: a dynamic router's rows are only in the table once its
// catalog loaded, which needs the key, so a missing credential would
// otherwise surface as an unknown model.
const p = try keys.providerById(pid, model);
- if (!keys_cli.isLocalUrl(spec.url) and !pricing.providerModelInTable(pid, model)) return error.UnknownModel;
+ if (!keys_cli.isLocalUrl(spec.url) and !catalog_selection.acceptsExplicitModel(spec, model)) return error.UnknownModel;
return p;
}
diff --git a/src/tui_session.zig b/src/tui_session.zig
index 36708f97..a62119b2 100644
--- a/src/tui_session.zig
+++ b/src/tui_session.zig
@@ -78,7 +78,14 @@ pub fn resumeCb(ctx_ptr: ?*anyopaque, gpa: Allocator, raw: []const u8, out: *tui
syncRoot(convo, root) catch |err| return failure(gpa, out, err);
session.saveSession(root, root.arena, root.session_name) catch |err| return failure(gpa, out, err);
}
- const resumed = session_branch.restore(root, &ctx.keys, root.arena, spec.source, spec.branch, null) catch |err| return failure(gpa, out, err);
+ const resumed = session_branch.restore(root, &ctx.keys, root.arena, spec.source, spec.branch, null) catch |err| {
+ if (err == error.FileNotFound) {
+ const note = @import("commands_resume.zig").missingMessage(root, root.arena, spec.source) catch return failure(gpa, out, err);
+ out.note = gpa.dupe(u8, note) catch &.{};
+ return false;
+ }
+ return failure(gpa, out, err);
+ };
if (ctx.convo) |convo| seed(convo, root) catch |err| return failure(gpa, out, err);
ctx.provider = root.provider;
ctx.last_context_tokens = root.last_context_tokens;
@@ -136,7 +143,8 @@ pub fn sessionsCb(ctx_ptr: ?*anyopaque, gpa: Allocator) ?[]const u8 {
if (age.len > 0) break :blk std.fmt.allocPrint(arena, "{s} · {s}", .{ age, e.base }) catch e.base;
break :blk e.base;
};
- const line = std.fmt.allocPrint(arena, "{s}\t{s}\t{s}", .{ e.base, title, desc }) catch continue;
+ const target = @import("session_workspaces.zig").target(arena, e) catch continue;
+ const line = std.fmt.allocPrint(arena, "{s}\t{s}\t{s}", .{ target, title, desc }) catch continue;
out.appendSlice(gpa, line) catch {
out.deinit(gpa);
return null;
diff --git a/src/worktree_lease.zig b/src/worktree_lease.zig
index 6e6e6c9f..7efc8f69 100644
--- a/src/worktree_lease.zig
+++ b/src/worktree_lease.zig
@@ -71,6 +71,8 @@ pub const Owner = struct {
/// peer reads to decide whether its work overlaps. Empty when unknown.
goal: []const u8 = "",
last_seen_ms: i64 = 0,
+ /// Last root-turn start/completion, not registry refresh. Zero means unknown.
+ last_activity_ms: i64 = 0,
activity: []const u8 = "connected",
/// #700: the human title from `.session.json`. Empty on older records.
title: []const u8 = "",