graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: distinguish unchanged model selections
yxlyxeb948eaf43b7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d5537c2c..445193ff 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -142,6 +142,9 @@ jobs:- name: PTY REPL interaction testrun: python3 scripts/test-pty-repl.py zig-out/bin/graff+ - name: Terminal model-selection confirmation regression+ run: python3 scripts/test-model-confirmation.py zig-out/bin/graff+- name: PTY Markdown rendering testrun: python3 scripts/test-pty-markdown.py zig-out/bin/graffdiff --git a/TUI/dispatch.zig b/TUI/dispatch.zigindex 710634a0..54e57521 100644--- a/TUI/dispatch.zig+++ b/TUI/dispatch.zig@@ -149,9 +149,11 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {} else if (engine.g_model_fn) |f| {// A hand-typed name names no provider, so the engine routes it —// the picker is the surface that knows which seat was meant.+ const previous: engine.Picked = .{ .model = engine.g_model_name, .provider = engine.g_model_provider };if (f(engine.g_turn_ctx, self.alloc, "", arg)) |got| {+ const same = std.mem.eql(u8, previous.model, got.model) and std.mem.eql(u8, previous.provider, got.provider);self.adoptModel(got);- self.pushFmt(.system, "switched to {s} · {s}", .{ got.model, got.provider }) catch {};+ self.pushFmt(.system, "{s} {s} · {s}", .{ if (same) "already using" else "switched to", got.model, got.provider }) catch {};} else self.pushFmt(.err, "couldn't switch to '{s}'", .{arg}) catch {};} else self.push(.system, "model switching isn't available (offline)") catch {};} else if (std.mem.eql(u8, canon, "/effort")) {diff --git a/TUI/model_confirmation_tests.zig b/TUI/model_confirmation_tests.zignew file mode 100644index 00000000..d6060a39--- /dev/null+++ b/TUI/model_confirmation_tests.zig@@ -0,0 +1,208 @@+//! /model confirmation regressions, driven through terminal command dispatch.+//! Imported by the parent test root; callbacks never contact a provider.+const std = @import("std");+const engine = @import("engine.zig");+const sim = @import("sim.zig");++const Fixture = struct {+ provider: []const u8 = "seat-a",+ model: []const u8 = "model-a",+ requested: []const u8 = "model-a",+ fail: bool = false,+ picker: bool = false,+ calls: usize = 0,+ valid_request: bool = true,++ fn select(ctx: ?*anyopaque, alloc: std.mem.Allocator, provider: []const u8, name: []const u8) ?engine.Picked {+ const self: *Fixture = @ptrCast(@alignCast(ctx.?));+ self.calls += 1;+ // Typed commands must leave routing to the backend, unlike picker rows.+ const expected_provider = if (self.picker) self.provider else "";+ self.valid_request = self.valid_request and std.mem.eql(u8, provider, expected_provider) and std.mem.eql(u8, name, self.requested);+ if (self.fail) return null;+ return .{+ .model = alloc.dupe(u8, self.model) catch return null,+ .provider = self.provider,+ };+ }+};++const Saved = struct {+ ctx: ?*anyopaque,+ callback: ?engine.ModelFn,+ model: []const u8,+ provider: []const u8,++ fn install(fixture: *Fixture) Saved {+ const saved: Saved = .{+ .ctx = engine.g_turn_ctx,+ .callback = engine.g_model_fn,+ .model = engine.g_model_name,+ .provider = engine.g_model_provider,+ };+ engine.g_turn_ctx = fixture;+ engine.g_model_fn = Fixture.select;+ engine.g_model_name = "model-a";+ engine.g_model_provider = "seat-a";+ return saved;+ }++ fn restore(self: Saved) void {+ engine.g_turn_ctx = self.ctx;+ engine.g_model_fn = self.callback;+ engine.g_model_name = self.model;+ engine.g_model_provider = self.provider;+ }+};++fn submit(term: *sim.Term, name: []const u8) !void {+ _ = term.typeText("/model ");+ _ = term.typeText(name);+ _ = term.enter();+ try std.testing.expect(term.model.pending == null);+ try std.testing.expect(term.model.bg == null);+}++fn expectConfirmation(term: *sim.Term, expected: []const u8) !void {+ const history = term.model.history.items;+ try std.testing.expect(history.len > 0);+ const last = history[history.len - 1];+ try std.testing.expectEqual(.system, last.kind);+ try std.testing.expectEqualStrings(expected, last.text);+}++fn successfulSelection(fixture: *Fixture, expected: []const u8, repetitions: usize) !void {+ const saved = Saved.install(fixture);+ defer saved.restore();+ var term: sim.Term = undefined;+ term.init(std.testing.allocator, 100, 30);+ defer term.deinit();+ for (0..repetitions) |_| {+ try submit(&term, fixture.requested);+ try expectConfirmation(&term, expected);+ try std.testing.expectEqualStrings(fixture.model, engine.g_model_name);+ try std.testing.expectEqualStrings(fixture.provider, engine.g_model_provider);+ }+ try std.testing.expectEqual(repetitions, fixture.calls);+ try std.testing.expect(fixture.valid_request);+}++test "model confirmation: repeated resolved selection is already using" {+ var fixture: Fixture = .{};+ // The second result is freshly allocated while the previous model is owned+ // by the UI: compare values before adoption frees the previous allocation.+ try successfulSelection(&fixture, "already using model-a · seat-a", 2);+}++test "model confirmation: alias resolving to current selection is already using" {+ var fixture: Fixture = .{ .requested = "friendly-alias" };+ try successfulSelection(&fixture, "already using model-a · seat-a", 1);+}++test "model confirmation: provider-only change is switched to" {+ var fixture: Fixture = .{ .provider = "seat-b" };+ try successfulSelection(&fixture, "switched to model-a · seat-b", 1);+}++test "model confirmation: actual model change is switched to" {+ var fixture: Fixture = .{ .model = "model-b", .requested = "model-b" };+ try successfulSelection(&fixture, "switched to model-b · seat-a", 1);+}++test "model confirmation: failure retains error and current selection" {+ var fixture: Fixture = .{};+ const saved = Saved.install(&fixture);+ defer saved.restore();+ var term: sim.Term = undefined;+ term.init(std.testing.allocator, 100, 30);+ defer term.deinit();+ // Establish an owned selection first, then ensure failure leaves it intact.+ try submit(&term, fixture.requested);+ const owned = term.model.model_override.?;+ fixture.fail = true;+ fixture.requested = "unavailable";+ try submit(&term, fixture.requested);+ const history = term.model.history.items;+ const last = history[history.len - 1];+ try std.testing.expectEqual(.err, last.kind);+ try std.testing.expectEqualStrings("couldn't switch to 'unavailable'", last.text);+ try std.testing.expectEqualStrings("model-a", engine.g_model_name);+ try std.testing.expectEqualStrings("seat-a", engine.g_model_provider);+ try std.testing.expect(term.model.model_override.?.ptr == owned.ptr);+ try std.testing.expectEqual(@as(usize, 2), fixture.calls);+ try std.testing.expect(fixture.valid_request);+}++fn pick(term: *sim.Term) !void {+ _ = term.typeText("/model");+ _ = term.enter();+ try std.testing.expectEqual(.model, term.model.overlay);+ _ = term.enter();+ try std.testing.expect(term.model.pending == null);+ try std.testing.expect(term.model.bg == null);+}++fn pickerSelection(fixture: *Fixture, expected: []const u8, repetitions: usize) !void {+ fixture.picker = true;+ const saved = Saved.install(fixture);+ defer saved.restore();+ const previous = engine.g_model_entries;+ defer engine.g_model_entries = previous;+ const rows = [_]engine.ModelEntry{.{ .name = fixture.requested, .provider = fixture.provider, .has_key = true }};+ engine.g_model_entries = &rows;+ var term: sim.Term = undefined;+ term.init(std.testing.allocator, 100, 30);+ defer term.deinit();+ for (0..repetitions) |_| {+ try pick(&term);+ try expectConfirmation(&term, expected);+ try std.testing.expectEqualStrings(if (repetitions > 1) "already using this model" else fixture.model, term.model.toast);+ try std.testing.expectEqualStrings(fixture.model, engine.g_model_name);+ try std.testing.expectEqualStrings(fixture.provider, engine.g_model_provider);+ }+ try std.testing.expectEqual(repetitions, fixture.calls);+ try std.testing.expect(fixture.valid_request);+}++test "model confirmation: picker same row twice is already using" {+ var fixture: Fixture = .{};+ try pickerSelection(&fixture, "already using model-a · seat-a", 2);+}++test "model confirmation: picker provider change retains model arrow" {+ var fixture: Fixture = .{ .provider = "seat-b" };+ try pickerSelection(&fixture, "model → model-a · seat-b", 1);+}++test "model confirmation: picker model change retains model arrow" {+ var fixture: Fixture = .{ .model = "model-b", .requested = "model-b" };+ try pickerSelection(&fixture, "model → model-b · seat-a", 1);+}++test "model confirmation: failed picker retains owned selection and error toast" {+ var fixture: Fixture = .{};+ const saved = Saved.install(&fixture);+ defer saved.restore();+ const previous = engine.g_model_entries;+ defer engine.g_model_entries = previous;+ const rows = [_]engine.ModelEntry{.{ .name = "unavailable", .provider = "seat-b", .has_key = true }};+ engine.g_model_entries = &rows;+ var term: sim.Term = undefined;+ term.init(std.testing.allocator, 100, 30);+ defer term.deinit();+ try submit(&term, fixture.requested);+ const owned = term.model.model_override.?;+ const history_len = term.model.history.items.len;+ fixture.fail = true;+ fixture.picker = true;+ fixture.provider = "seat-b";+ fixture.requested = "unavailable";+ try pick(&term);+ try std.testing.expectEqualStrings("couldn't switch", term.model.toast);+ try std.testing.expectEqualStrings("model-a", engine.g_model_name);+ try std.testing.expectEqualStrings("seat-a", engine.g_model_provider);+ try std.testing.expect(term.model.model_override.?.ptr == owned.ptr);+ try std.testing.expectEqual(history_len, term.model.history.items.len);+ try std.testing.expectEqual(@as(usize, 2), fixture.calls);+ try std.testing.expect(fixture.valid_request);+}diff --git a/TUI/overlays.zig b/TUI/overlays.zigindex df7d18f3..099af022 100644--- a/TUI/overlays.zig+++ b/TUI/overlays.zig@@ -246,10 +246,12 @@ pub fn activate(self: *Model) Effect {// openai row for a model codex also serves landed on codex.const pick = rows[sel];if (engine.g_model_fn) |f| {+ const previous: engine.Picked = .{ .model = engine.g_model_name, .provider = engine.g_model_provider };if (f(engine.g_turn_ctx, self.alloc, pick.provider, pick.name)) |got| {+ const same = std.mem.eql(u8, previous.model, got.model) and std.mem.eql(u8, previous.provider, got.provider);self.adoptModel(got);- self.setToast(got.model);- self.pushFmt(.system, "model → {s} · {s}", .{ got.model, got.provider }) catch {};+ self.setToast(if (same) "already using this model" else got.model);+ self.pushFmt(.system, "{s} {s} · {s}", .{ if (same) "already using" else "model →", got.model, got.provider }) catch {};} else self.setToast("couldn't switch");} else {engine.g_model_name = pick.name;diff --git a/TUI/root.zig b/TUI/root.zigindex 0bb2bebb..5fa5264d 100644--- a/TUI/root.zig+++ b/TUI/root.zig@@ -74,6 +74,7 @@ test {_ = app;_ = @import("app_tests.zig");_ = @import("dispatch.zig");+ _ = @import("model_confirmation_tests.zig");_ = @import("resume.zig");_ = @import("peer_cmd.zig");_ = @import("peer_tests.zig");diff --git a/scripts/test-model-confirmation.py b/scripts/test-model-confirmation.pynew file mode 100644index 00000000..48484d06--- /dev/null+++ b/scripts/test-model-confirmation.py@@ -0,0 +1,75 @@+#!/usr/bin/env python3+"""Offline terminal /model confirmation regression (#890).++Tier 2's JSON set_model control bypasses the terminal confirmation printer.+Use the line-terminal dispatcher and a scripted follow-up request instead.+"""+from __future__ import annotations++import os+import pathlib+import subprocess+import sys+import tempfile++ROOT = pathlib.Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "scripts" / "eval"))+from mock_model import ScriptedModel # noqa: E402+++def main() -> None:+ binary = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else ROOT / "zig-out/bin/graff").resolve()+ # Auxiliary requests may precede the user turn; all receive the same reply.+ mock = ScriptedModel([], exhausted_text="offline ready")+ mock.start(1234)+ try:+ with tempfile.TemporaryDirectory() as workspace:+ env = {+ "PATH": os.environ["PATH"],+ "HOME": workspace,+ "LMSTUDIO_API_KEY": "local",+ "GRAFF_NO_TELEMETRY": "1",+ "GRAFF_FLEET": "off",+ "GRAFF_NO_SMOLIFY": "1",+ "NO_COLOR": "1",+ }+ result = subprocess.run(+ [str(binary), "--old", "--yolo", "--model", "lmstudio"],+ cwd=workspace, env=env, text=True, capture_output=True, timeout=60,+ input=(+ "/model lmstudio regression-a\n"+ "/model lmstudio regression-a\n"+ "/model lmstudio regression-a\n"+ "/model lmstudio regression-b\n"+ "/model lmstudio regression-b\n"+ "Reply with offline ready.\n"+ "/quit\n"+ ),+ )+ assert result.returncode == 0, result.stderr+ output = result.stdout + "\n" + result.stderr+ confirmations = [+ line.strip() for line in output.splitlines()+ if line.strip().startswith(("switched to ", "already using "))+ ]+ expected = [+ "switched to regression-a via lmstudio",+ "already using regression-a via lmstudio",+ "already using regression-a via lmstudio",+ "switched to regression-b via lmstudio",+ "already using regression-b via lmstudio",+ ]+ assert len(confirmations) == len(expected), confirmations+ for actual, prefix in zip(confirmations, expected):+ assert actual.startswith(prefix), (actual, prefix)+ # Check that the final selection also reaches the real request path.+ turns = [r for r in mock.requests if r.get("model") == "regression-b"]+ assert turns, "The selected model never reached the scripted server"+ assert "offline ready" in output, "The scripted follow-up reply was not displayed"+ print("model confirmation: repeated selection, real change, and follow-up passed")+ finally:+ mock.stop()+++if __name__ == "__main__":+ main()diff --git a/src/main.zig b/src/main.zigindex a95fede8..8e15255d 100644--- a/src/main.zig+++ b/src/main.zig@@ -563,7 +563,7 @@ const agentJobsReap = subagent.agentJobsReap; // #276 P0-3: background subagentsconst workflow = @import("workflow_test.zig"); // the engine's tests live here (workflow.zig hit the 600-line cap)const exec = @import("exec.zig");test { // ── Unit tests (`zig build test`): pull in tests from imported modules (mcp.zig)- _ = .{ @import("mcp_apps.zig"), @import("html_view.zig") };+ _ = .{ @import("mcp_apps.zig"), @import("html_view.zig"), @import("providers_confirmation_tests.zig"), @import("repl_model_confirmation_tests.zig"), @import("repl_model_pick_tests.zig") };_ = @import("main_test.zig");_ = @import("session_catalog.zig");_ = @import("session_prompt.zig");diff --git a/src/providers.zig b/src/providers.zigindex a986d924..e63a270e 100644--- a/src/providers.zig+++ b/src/providers.zig@@ -389,9 +389,10 @@ pub fn setModelRequestLabel(arena: Allocator, provider_query: []const u8, model_}pub fn switchProvider(root: *Agent, arena: Allocator, p: Provider, out: *Io.Writer) !void {+ const same = std.mem.eql(u8, root.provider.id, p.id) and std.mem.eql(u8, root.provider.model, p.model);const note = try applyProvider(root, arena, p);- try out.print("switched to {s} via {s} ({t} format, {d}k ctx) — {s} · saved for next session\n", .{- p.model, p.id, p.kind, p.context / 1000, note,+ try out.print("{s} {s} via {s} ({t} format, {d}k ctx) — {s} · saved for next session\n", .{+ if (same) "already using" else "switched to", p.model, p.id, p.kind, p.context / 1000, note,});try out.flush();}diff --git a/src/providers_confirmation_tests.zig b/src/providers_confirmation_tests.zignew file mode 100644index 00000000..3299dab2--- /dev/null+++ b/src/providers_confirmation_tests.zig@@ -0,0 +1,163 @@+//! Offline /model confirmation regressions (#890). Imported by the test root.+const std = @import("std");+const Agent = @import("agent.zig").Agent;+const provider_mod = @import("provider.zig");+const Provider = provider_mod.Provider;+const Keys = provider_mod.Keys;+const providers = @import("providers.zig");+const pricing = @import("pricing.zig");+const serde = @import("serde.zig");++// Match the minimal applyProviderInner fixture in providers.zig. No catalog+// refresh or turn execution is involved; credentials are inert test strings.+fn agent(arena: std.mem.Allocator, home: []const u8, p: Provider) !Agent {+ var root: Agent = undefined;+ root.io = std.testing.io;+ root.home = home;+ root.provider = p;+ root.subagent_provider = null;+ root.subagent_provider_explicit = true;+ root.arena = arena;+ root.registry = null;+ root.messages = std.json.Array.init(arena);+ try root.messages.append(try @import("messages.zig").textMessage(arena, "user", "keep this conversation"));+ root.sub = false;+ root.strict = false;+ root.sys_normal = "";+ root.sys_strict = "";+ root.tools_anthropic = "";+ root.tools_openai = "";+ root.tools_responses = "";+ root.keep_context = true;+ root.last_context_tokens = 220_000;+ root.context_local_tokens = 321;+ root.last_cache_read = 12_345;+ root.cap_new = true;+ root.sox_json_object = true;+ root.effort_rejected = true;+ root.ws_off = true;+ root.ws_transport_failures = 2;+ root.compact_transport_failures = 3;+ root.fallback_active = true;+ root.fallback_blocked = true;+ return root;+}++fn confirm(root: *Agent, arena: std.mem.Allocator, p: Provider, changed: bool) !void {+ const history = root.messages.items.ptr;+ const same_format = root.provider.kind == p.kind;+ var output: std.Io.Writer.Allocating = .init(std.testing.allocator);+ defer output.deinit();+ try providers.switchProvider(root, arena, p, &output.writer);+ const text = output.writer.buffered();+ const prefix = try std.fmt.allocPrint(arena, "{s} {s} via {s} (", .{+ if (changed) "switched to" else "already using", p.model, p.id,+ });+ try std.testing.expect(std.mem.startsWith(u8, text, prefix));+ try std.testing.expect(std.mem.indexOf(u8, text, if (changed) "already using" else "switched to") == null);+ try std.testing.expect(std.mem.indexOf(u8, text, if (same_format) "context kept" else "context translated & kept") != null);+ try std.testing.expect(std.mem.endsWith(u8, text, "saved for next session\n"));+ try std.testing.expectEqualStrings(p.id, root.provider.id);+ try std.testing.expectEqualStrings(p.model, root.provider.model);+ if (same_format) try std.testing.expect(history == root.messages.items.ptr);+ try std.testing.expectEqual(@as(usize, 1), root.messages.items.len);+ try std.testing.expectEqualStrings("keep this conversation", providers.extractText(arena, root.messages.items[0]));+ try std.testing.expect(!root.fallback_active);+ try std.testing.expect(!root.fallback_blocked);+ const saved = serde.loadModel(root.io, arena, root.home) orelse return error.ModelNotSaved;+ try std.testing.expectEqualStrings(p.id, saved.pid);+ try std.testing.expectEqualStrings(p.model, saved.model);+}++fn exercise(query: []const u8, target_provider: []const u8, target_model: []const u8, changed: bool) !void {+ 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 home = try tmp.dir.realPathFileAlloc(std.testing.io, ".", arena);+ // Own the catalog for deterministic alias/routing tests, not live accounts.+ const previous = pricing.active_model_table;+ defer pricing.active_model_table = previous;+ const rows = [_]pricing.ModelInfo{+ .{ .provider = "openai", .name = "confirmation-model", .context = 270_000 },+ .{ .provider = "openai", .name = "confirmation-next", .context = 270_000 },+ .{ .provider = "codegraff", .name = "confirmation-model", .context = 270_000 },+ };+ pricing.active_model_table = &rows;+ var keys: Keys = .{ .values = @splat("offline-test-key") };+ const initial = try providers.resolveProviderControlRequest(&keys, arena, "openai", "confirmation-model", "");+ const selected = try providers.resolveProviderControlRequest(&keys, arena, target_provider, target_model, query);+ try std.testing.expectEqualStrings(if (target_provider.len == 0) "openai" else target_provider, selected.id);+ try std.testing.expectEqualStrings(if (target_model.len == 0) "confirmation-model" else target_model, selected.model);+ var root = try agent(arena, home, initial);+ // A stale saved preference proves no-op confirmation still applies/persists.+ serde.saveModel(root.io, home, "stale-provider", "stale-model");+ try confirm(&root, arena, selected, changed);+ if (!changed) {+ try std.testing.expectEqual(@as(u64, 220_000), root.last_context_tokens);+ try std.testing.expectEqual(@as(u64, 321), root.context_local_tokens);+ try std.testing.expectEqual(@as(u64, 12_345), root.last_cache_read);+ try std.testing.expect(root.cap_new and root.sox_json_object and root.effort_rejected and root.ws_off);+ try std.testing.expectEqual(@as(u8, 2), root.ws_transport_failures);+ try std.testing.expectEqual(@as(u8, 3), root.compact_transport_failures);+ } else {+ try std.testing.expectEqual(root.fullRequestEstimateTokens(), root.last_context_tokens);+ try std.testing.expectEqual(root.last_context_tokens, root.context_local_tokens);+ try std.testing.expectEqual(@as(u64, 0), root.last_cache_read);+ try std.testing.expect(!root.cap_new and !root.sox_json_object and !root.effort_rejected and !root.ws_off);+ try std.testing.expectEqual(@as(u8, 0), root.ws_transport_failures);+ try std.testing.expectEqual(@as(u8, 0), root.compact_transport_failures);+ }+ // Repeating even a genuine switch must now announce the current selection.+ try confirm(&root, arena, selected, false);+}++test "#890 confirmation: repeated resolved selection preserves server state and persists" {+ try exercise("", "openai", "confirmation-model", false);+}++test "#890 confirmation: normalized alias resolves to the active selection" {+ try exercise("CONFIRMATION_MODEL", "", "", false);+}++test "#890 confirmation: different provider with the same model is a switch" {+ try exercise("", "codegraff", "confirmation-model", true);+}++test "#890 confirmation: different model on the same provider is a switch" {+ try exercise("", "openai", "confirmation-next", true);+}++test "#890 confirmation: same identity refreshes context endpoint and wire format" {+ 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 home = try tmp.dir.realPathFileAlloc(std.testing.io, ".", arena);+ const initial: Provider = .{+ .id = "openai",+ .model = "confirmation-model",+ .kind = .openai,+ .auth = .bearer,+ .url = "https://initial.invalid/v1/chat/completions",+ .api_key = "offline-test-key",+ .context = 270_000,+ };+ var root = try agent(arena, home, initial);+ serde.saveModel(root.io, home, "stale-provider", "stale-model");+ var refreshed = initial;+ refreshed.context = 400_000;+ refreshed.url = "https://refreshed.invalid/v1/messages";+ refreshed.kind = .anthropic;+ try confirm(&root, arena, refreshed, false);+ try std.testing.expectEqual(refreshed.context, root.provider.context);+ try std.testing.expectEqualStrings(refreshed.url, root.provider.url);+ try std.testing.expectEqual(refreshed.kind, root.provider.kind);+ // Explicitly choosing the active fallback still persists that identity.+ root.fallback_active = true;+ root.fallback_blocked = true;+ serde.saveModel(root.io, home, "stale-provider", "stale-model");+ try confirm(&root, arena, refreshed, false);+}diff --git a/src/repl.zig b/src/repl.zigindex 96b5d5f9..0363b33b 100644--- a/src/repl.zig+++ b/src/repl.zig@@ -68,7 +68,9 @@ pub const TurnFn = repl_types.TurnFn;pub var g_turn_fn: ?TurnFn = null;pub var g_turn_ctx: ?*anyopaque = null;pub var g_model_name: []const u8 = "";-pub const ModelFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, name: []const u8) ?[]const u8;+/// The backend compares provider AND model; a model-only display cannot detect a seat change.+pub const ModelPick = struct { model: []const u8, changed: bool };+pub const ModelFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, name: []const u8) ?ModelPick;pub var g_models: []const u8 = ""; // comma-joined model names (for /models)pub var g_model_fn: ?ModelFn = null; // switch the active model by namepub const CancelFn = *const fn (turn_ctx: ?*anyopaque) void;diff --git a/src/repl_glue.zig b/src/repl_glue.zigindex 403a74b1..050c7e81 100644--- a/src/repl_glue.zig+++ b/src/repl_glue.zig@@ -311,9 +311,11 @@ test {/// using the same model-routing rules as /model, then persist that/// explicit choice for the next launch. Automatic turn fallback updates only/// `c.provider`, never this preference file.-pub fn replModelCb(ctx_ptr: ?*anyopaque, gpa: Allocator, name: []const u8) ?[]const u8 {+pub fn replModelCb(ctx_ptr: ?*anyopaque, gpa: Allocator, name: []const u8) ?repl.ModelPick {+ const c: *ReplCtx = @ptrCast(@alignCast(ctx_ptr orelse return null));+ const previous = c.provider;const picked = replModelPick(ctx_ptr, gpa, "", name) orelse return null;- return picked.model;+ return .{ .model = picked.model, .changed = !std.mem.eql(u8, previous.id, picked.provider) or !std.mem.eql(u8, previous.model, picked.model) };}/// What a model switch settled on. The provider id travels back because the@@ -339,12 +341,14 @@ fn catalogName(provider_id: []const u8, name: []const u8) ?[]const u8 {/// job.pub fn replModelPick(ctx_ptr: ?*anyopaque, gpa: Allocator, provider_id: []const u8, name: []const u8) ?Picked {const c: *ReplCtx = @ptrCast(@alignCast(ctx_ptr orelse return null));+ var selected: Provider = undefined;+ var owned = false;if (provider_id.len > 0 and provider_mod.specFor(provider_id) != null) {// Off-catalog names (a live LM Studio id) have no table slice to// borrow, so those — and only those — are copied.- const owned = catalogName(provider_id, name) == null;+ owned = catalogName(provider_id, name) == null;const model = if (owned) (gpa.dupe(u8, name) catch return null) else catalogName(provider_id, name).?;- c.provider = c.keys.providerById(provider_id, model) catch {+ selected = c.keys.providerById(provider_id, model) catch {if (owned) gpa.free(model);return null;};@@ -352,12 +356,17 @@ pub fn replModelPick(ctx_ptr: ?*anyopaque, gpa: Allocator, provider_id: []const// `resolveModelName` answers with the catalog's own slice, never with// a piece of the query, so there is nothing to copy here either.const resolved = pricing.resolveModelName(c.keys, name) orelse return null;- c.provider = c.keys.providerFor(resolved) catch return null;+ selected = c.keys.providerFor(resolved) catch return null;}+ const display = gpa.dupe(u8, selected.model) catch {+ if (owned) gpa.free(selected.model);+ return null;+ };+ c.provider = selected;c.fallback_active = false;c.fallback_blocked = false;serde.saveModel(c.io, c.home, c.provider.id, c.provider.model);- return .{ .model = gpa.dupe(u8, c.provider.model) catch return null, .provider = c.provider.id };+ return .{ .model = display, .provider = c.provider.id };}/// repl.CancelFn adapter — force-interrupt the running repl turn. Sets thediff --git a/src/repl_model_commands.zig b/src/repl_model_commands.zigindex 6326cf57..85f0888d 100644--- a/src/repl_model_commands.zig+++ b/src/repl_model_commands.zig@@ -51,9 +51,9 @@ pub fn runCommand(self: *Model, line: []const u8) void {if (arg.len == 0) {if (repl.g_model_name.len > 0) self.pushFmt(.info, "model: {s}", .{repl.g_model_name}) catch {} else self.push(.info, "no model configured") catch {};} else if (repl.g_model_fn) |f| {- if (f(repl.g_turn_ctx, self.alloc, arg)) |nm| {- repl.g_model_name = nm;- self.pushFmt(.info, "switched to {s}", .{nm}) catch {};+ if (f(repl.g_turn_ctx, self.alloc, arg)) |picked| {+ repl.g_model_name = picked.model;+ self.pushFmt(.info, "{s} {s}", .{ if (picked.changed) "switched to" else "already using", picked.model }) catch {};} else self.pushFmt(.err, "couldn't switch to '{s}' — see /models (need a key/login for it)", .{arg}) catch {};} else self.push(.info, "model switching isn't available (offline mode)") catch {};} else if (std.mem.eql(u8, cmd, "/models")) {diff --git a/src/repl_model_confirmation_tests.zig b/src/repl_model_confirmation_tests.zignew file mode 100644index 00000000..a0f44c77--- /dev/null+++ b/src/repl_model_confirmation_tests.zig@@ -0,0 +1,126 @@+//! Offline `/model` confirmation regressions (#890).+//! Exercise the dispatcher using the backend's resolved change result.+const std = @import("std");+const repl = @import("repl.zig");++const Stub = struct {+ calls: usize = 0,+ last_name: []const u8 = "",+ // Separate storage makes equal resolved names distinct slices, so equality+ // must compare bytes rather than pointer identity.+ resolved: [7]u8 = "model-a".*,+ current: []const u8 = "model-a",++ fn select(ctx: ?*anyopaque, _: std.mem.Allocator, name: []const u8) ?repl.ModelPick {+ const self: *Stub = @ptrCast(@alignCast(ctx orelse return null));+ self.calls += 1;+ self.last_name = name;+ const model: []const u8 = if (std.mem.eql(u8, name, "model-a") or std.mem.eql(u8, name, "alias-a")) &self.resolved else if (std.mem.eql(u8, name, "model-b")) "model-b" else return null;+ const changed = !std.mem.eql(u8, self.current, model);+ self.current = model;+ return .{ .model = model, .changed = changed };+ }+};++const Saved = struct {+ model_fn: ?repl.ModelFn,+ turn_fn: ?repl.TurnFn,+ ctx: ?*anyopaque,+ name: []const u8,++ fn install(stub: *Stub) Saved {+ const saved: Saved = .{+ .model_fn = repl.g_model_fn,+ .turn_fn = repl.g_turn_fn,+ .ctx = repl.g_turn_ctx,+ .name = repl.g_model_name,+ };+ repl.g_model_fn = Stub.select;+ repl.g_turn_fn = null;+ repl.g_turn_ctx = stub;+ repl.g_model_name = "model-a";+ return saved;+ }++ fn restore(self: Saved) void {+ repl.g_model_fn = self.model_fn;+ repl.g_turn_fn = self.turn_fn;+ repl.g_turn_ctx = self.ctx;+ repl.g_model_name = self.name;+ }+};++fn expectInfo(m: *const repl.Model, text: []const u8) !void {+ const entry = m.history.items[m.history.items.len - 1];+ try std.testing.expect(entry.kind == .info);+ try std.testing.expectEqualStrings(text, entry.text);+}++test "model confirmation: repeated resolved selection is already using (#890)" {+ var stub: Stub = .{};+ const saved = Saved.install(&stub);+ defer saved.restore();+ var m: repl.Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();++ for (0..2) |i| {+ m.runCommand("/model model-a");+ try expectInfo(&m, "already using model-a");+ try std.testing.expectEqualStrings("model-a", repl.g_model_name);+ try std.testing.expectEqual(i + 1, stub.calls);+ try std.testing.expectEqual(i + 2, m.history.items.len);+ }+}++test "model confirmation: alias resolving to current model is already using (#890)" {+ var stub: Stub = .{};+ const saved = Saved.install(&stub);+ defer saved.restore();+ var m: repl.Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();++ m.runCommand("/model alias-a \t");+ try expectInfo(&m, "already using model-a");+ try std.testing.expectEqualStrings("alias-a", stub.last_name);+ try std.testing.expectEqualStrings("model-a", repl.g_model_name);+ try std.testing.expectEqual(@as(usize, 1), stub.calls);+ try std.testing.expectEqual(@as(usize, 2), m.history.items.len);+}++test "model confirmation: actual change switches then repeated selection does not (#890)" {+ var stub: Stub = .{};+ const saved = Saved.install(&stub);+ defer saved.restore();+ var m: repl.Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();++ m.runCommand("/model model-b");+ try expectInfo(&m, "switched to model-b");+ try std.testing.expectEqualStrings("model-b", repl.g_model_name);+ m.runCommand("/model model-b");+ try expectInfo(&m, "already using model-b");+ try std.testing.expectEqualStrings("model-b", repl.g_model_name);+ try std.testing.expectEqual(@as(usize, 2), stub.calls);+ try std.testing.expectEqual(@as(usize, 3), m.history.items.len);+}++test "model confirmation: failed selection retains current model and reports error (#890)" {+ var stub: Stub = .{};+ const saved = Saved.install(&stub);+ defer saved.restore();+ var m: repl.Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();++ m.runCommand("/model unavailable");+ const entry = m.history.items[m.history.items.len - 1];+ try std.testing.expect(entry.kind == .err);+ try std.testing.expectEqualStrings("couldn't switch to 'unavailable' — see /models (need a key/login for it)", entry.text);+ try std.testing.expectEqualStrings("model-a", repl.g_model_name);+ try std.testing.expectEqualStrings("unavailable", stub.last_name);+ try std.testing.expectEqual(@as(usize, 1), stub.calls);+ try std.testing.expectEqual(@as(usize, 2), m.history.items.len);+}diff --git a/src/repl_model_pick_tests.zig b/src/repl_model_pick_tests.zignew file mode 100644index 00000000..5d520db1--- /dev/null+++ b/src/repl_model_pick_tests.zig@@ -0,0 +1,161 @@+//! Offline engine-side model selection regressions (#890).+const std = @import("std");+const provider_mod = @import("provider.zig");+const repl_glue = @import("repl_glue.zig");+const pricing = @import("pricing.zig");+const serde = @import("serde.zig");++const rows = [_]pricing.ModelInfo{+ .{ .provider = "openai", .name = "pick-model", .context = 270_000 },+ .{ .provider = "openai", .name = "pick-next", .context = 270_000 },+ .{ .provider = "codegraff", .name = "pick-model", .context = 270_000 },+};++fn keyedFor(id: []const u8) provider_mod.Keys {+ var keys: provider_mod.Keys = .{ .values = @splat(null) };+ _ = keys.set(id, "offline-test-key", .stored);+ return keys;+}++// Like repl_model_pick_test.zig: no client operations or turns are needed.+fn switchCtx(client: *std.http.Client, home: []const u8) !repl_glue.ReplCtx {+ const keys = keyedFor("openai");+ return .{+ .io = std.testing.io,+ .client = client,+ .keys = keys,+ .home = home,+ .provider = try keys.providerById("openai", "pick-model"),+ .fallback_allow = &.{},+ .fallback_active = false,+ .fallback_blocked = false,+ .registry = null,+ .tracer = null,+ .run_budget = null,+ .sys_normal = "",+ .tools_anthropic = "",+ .tools_openai = "",+ .tools_responses = "",+ };+}++fn expectSaved(arena: std.mem.Allocator, ctx: *const repl_glue.ReplCtx) !void {+ const saved = serde.loadModel(ctx.io, arena, ctx.home) orelse return error.ModelNotSaved;+ try std.testing.expectEqualStrings(ctx.provider.id, saved.pid);+ try std.testing.expectEqualStrings(ctx.provider.model, saved.model);+}++fn exercise(query: []const u8, provider_id: []const u8, model: []const u8, changed: bool, fallback: bool) !void {+ 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 home = try tmp.dir.realPathFileAlloc(std.testing.io, ".", arena);+ const previous = pricing.active_model_table;+ defer pricing.active_model_table = previous;+ pricing.active_model_table = &rows;+ var client: std.http.Client = undefined;+ var ctx = try switchCtx(&client, home);+ // Change routing credentials without changing the active engine provider.+ ctx.keys = keyedFor(provider_id);+ ctx.fallback_active = fallback;+ ctx.fallback_blocked = fallback;+ serde.saveModel(ctx.io, home, "stale-provider", "stale-model");++ const picked = repl_glue.replModelCb(&ctx, std.testing.allocator, query) orelse+ return error.TestUnexpectedResult;+ defer std.testing.allocator.free(picked.model);+ try std.testing.expectEqual(changed, picked.changed);+ try std.testing.expectEqualStrings(model, picked.model);+ try std.testing.expectEqualStrings(model, ctx.provider.model);+ try std.testing.expectEqualStrings(provider_id, ctx.provider.id);+ try std.testing.expect(!ctx.fallback_active);+ try std.testing.expect(!ctx.fallback_blocked);+ try expectSaved(arena, &ctx);++ // The changed bit describes this dispatch, not the original session seat.+ const repeated = repl_glue.replModelCb(&ctx, std.testing.allocator, query) orelse+ return error.TestUnexpectedResult;+ defer std.testing.allocator.free(repeated.model);+ try std.testing.expect(!repeated.changed);+ try std.testing.expectEqualStrings(model, repeated.model);+ try expectSaved(arena, &ctx);+}++test "#890 replModelCb: unchanged normalized alias" {+ try exercise("PICK_MODEL", "openai", "pick-model", false, false);+}++test "#890 replModelCb: real model change" {+ try exercise("pick-next", "openai", "pick-next", true, false);+}++test "#890 replModelCb: same model with changed credential routing switches provider" {+ try exercise("pick-model", "codegraff", "pick-model", true, false);+}++test "#890 replModelCb: explicitly reselected fallback is unchanged but saved and cleared" {+ try exercise("pick-model", "openai", "pick-model", false, true);+}++test "#890 replModelCb: result allocation failure keeps selection and preference" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const home = try tmp.dir.realPathFileAlloc(std.testing.io, ".", arena_state.allocator());+ const previous = pricing.active_model_table;+ defer pricing.active_model_table = previous;+ pricing.active_model_table = &rows;+ var client: std.http.Client = undefined;+ var ctx = try switchCtx(&client, home);+ ctx.fallback_active = true;+ ctx.fallback_blocked = true;+ serde.saveModel(ctx.io, home, ctx.provider.id, ctx.provider.model);+ var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 });+ try std.testing.expect(repl_glue.replModelCb(&ctx, failing.allocator(), "pick-next") == null);+ try std.testing.expect(failing.has_induced_failure);+ try std.testing.expectEqualStrings("openai", ctx.provider.id);+ try std.testing.expectEqualStrings("pick-model", ctx.provider.model);+ try std.testing.expect(ctx.fallback_active and ctx.fallback_blocked);+ try expectSaved(arena_state.allocator(), &ctx);+ // Named off-catalog selections allocate both the provider name and display.+ // Failing either allocation must leave the same state and free any temporary.+ for (0..2) |fail_index| {+ var named_failure = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = fail_index });+ try std.testing.expect(repl_glue.replModelPick(&ctx, named_failure.allocator(), "openai", "off-catalog") == null);+ try std.testing.expect(named_failure.has_induced_failure);+ try std.testing.expectEqualStrings("openai", ctx.provider.id);+ try std.testing.expectEqualStrings("pick-model", ctx.provider.model);+ try std.testing.expect(ctx.fallback_active and ctx.fallback_blocked);+ try expectSaved(arena_state.allocator(), &ctx);+ }+}++test "#890 replModelPick: named provider returns the resolved engine seat" {+ 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 home = try tmp.dir.realPathFileAlloc(std.testing.io, ".", arena);+ const previous = pricing.active_model_table;+ defer pricing.active_model_table = previous;+ pricing.active_model_table = &rows;+ var client: std.http.Client = undefined;+ var ctx = try switchCtx(&client, home);+ _ = ctx.keys.set("codegraff", "offline-test-key", .stored);+ ctx.fallback_active = true;+ ctx.fallback_blocked = true;+ const picked = repl_glue.replModelPick(&ctx, std.testing.allocator, "codegraff", "pick-model") orelse+ return error.TestUnexpectedResult;+ defer std.testing.allocator.free(picked.model);+ try std.testing.expectEqualStrings("codegraff", picked.provider);+ try std.testing.expectEqualStrings(ctx.provider.id, picked.provider);+ try std.testing.expectEqualStrings("pick-model", picked.model);+ try std.testing.expectEqualStrings(ctx.provider.model, picked.model);+ try std.testing.expect(!ctx.fallback_active);+ try std.testing.expect(!ctx.fallback_blocked);+ try expectSaved(arena, &ctx);+}