Skip to content

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

Python

fix(tui): the model picker names its provider and what that seat costs

Rach Pradhan8f610579458c
diff --git a/TUI/app.zig b/TUI/app.zig
index 7205930c..41f77d07 100644
--- a/TUI/app.zig
+++ b/TUI/app.zig
@@ -305,6 +305,18 @@ pub const Model = struct {
try self.history.append(.{ .kind = kind, .text = text });
}
+ /// Take ownership of what the engine says a model switch landed on. The
+ /// name is allocated by the callback out of THIS Model's allocator and the
+ /// globals point into it, so the Model holds exactly one such buffer and
+ /// deinit already knows how to drop it. The provider id is a static spec
+ /// literal and is not owned.
+ pub fn adoptModel(self: *Model, picked: engine.Picked) void {
+ if (self.model_override) |old| self.alloc.free(old);
+ self.model_override = picked.model;
+ engine.g_model_name = picked.model;
+ engine.g_model_provider = picked.provider;
+ }
+
pub fn setToast(self: *Model, text: []const u8) void {
self.toast = text;
self.toast_until_ms = self.now_ms + 1500;
diff --git a/TUI/chrome.zig b/TUI/chrome.zig
index 47a40b4e..96a63a92 100644
--- a/TUI/chrome.zig
+++ b/TUI/chrome.zig
@@ -352,12 +352,17 @@ test "status paints coral [stop] while a turn is pending" {
try std.testing.expect(std.mem.indexOf(u8, text, "Esc:cancel") != null);
}
-test "model overlay lists engine.g_models" {
- engine.g_models = "grok-4, gpt-5.5";
+test "model overlay lists engine.g_model_entries with their providers" {
+ engine.g_model_entries = &.{
+ .{ .name = "grok-4", .provider = "xai", .has_key = true, .cost = .plan },
+ .{ .name = "gpt-5.5", .provider = "openai", .has_key = true, .cost = .api },
+ };
engine.g_model_name = "grok-4";
+ engine.g_model_provider = "xai";
defer {
- engine.g_models = "";
+ engine.g_model_entries = &.{};
engine.g_model_name = "";
+ engine.g_model_provider = "";
}
var m: Model = undefined;
m.setup(std.testing.allocator);
@@ -369,6 +374,9 @@ test "model overlay lists engine.g_models" {
try std.testing.expect(std.mem.indexOf(u8, text, "grok-4") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "gpt-5.5") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "Model ›") != null);
+ // The blind spot this fixes: the provider was nowhere on the surface.
+ try std.testing.expect(std.mem.indexOf(u8, text, "xai · plan") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "openai · api") != null);
}
test "debug overlay is not the offline fallback when a hud is wired" {
@@ -394,8 +402,6 @@ test "debug overlay is not the offline fallback when a hud is wired" {
try std.testing.expect(std.mem.indexOf(u8, text, "prompt-origin") != null);
}
-pub const splitModels = @import("models.zig").splitModels;
-
fn settingsOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {
const th = self.theme();
var out = std.array_list.Managed(u8).init(a);
diff --git a/TUI/dispatch.zig b/TUI/dispatch.zig
index 38a16652..65ecbc58 100644
--- a/TUI/dispatch.zig
+++ b/TUI/dispatch.zig
@@ -105,9 +105,11 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {
if (arg.len == 0) {
self.openOverlay(.model);
} else if (engine.g_model_fn) |f| {
- if (f(engine.g_turn_ctx, self.alloc, arg)) |nm| {
- engine.g_model_name = nm;
- self.pushFmt(.system, "switched to {s}", .{nm}) catch {};
+ // A hand-typed name names no provider, so the engine routes it —
+ // the picker is the surface that knows which seat was meant.
+ if (f(engine.g_turn_ctx, self.alloc, "", arg)) |got| {
+ self.adoptModel(got);
+ self.pushFmt(.system, "switched to {s} · {s}", .{ 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")) {
@@ -177,7 +179,7 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {
} else if (std.mem.eql(u8, canon, "/paste")) {
pasteClipboard(self);
} else if (std.mem.eql(u8, canon, "/doctor")) {
- self.pushFmt(.system, "ok · model={s} · cwd={s} · theme={s} · vim={s}", .{ engine.g_model_name, engine.g_cwd, @tagName(self.theme_id), onOff(self.vim_mode) }) catch {};
+ self.pushFmt(.system, "ok · model={s} via {s} · cwd={s} · theme={s} · vim={s}", .{ engine.g_model_name, engine.g_model_provider, engine.g_cwd, @tagName(self.theme_id), onOff(self.vim_mode) }) catch {};
} else if (std.mem.eql(u8, canon, "/import-claude")) {
self.push(.system, "adopting Claude/Cursor MCP writes ~/.codegraff — run `graff mcp import` from this repo") catch {};
} else if (std.mem.eql(u8, canon, "/jump")) {
diff --git a/TUI/engine.zig b/TUI/engine.zig
index e3e34514..3cf10a83 100644
--- a/TUI/engine.zig
+++ b/TUI/engine.zig
@@ -85,7 +85,46 @@ pub const StreamBuf = struct {
/// as an event. The TUI used to recover the second kind by parsing the first,
/// which is the defect this seam removes.
pub const TurnFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, params: Params, stream: *StreamBuf, events: *events_mod.Queue) ?[]const u8;
-pub const ModelFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, name: []const u8) ?[]const u8;
+/// How a seat is PAID FOR. The TUI never derives this — src/billing.zig owns
+/// the rule and the engine hands the answer over with the catalog, the same
+/// way it hands over the model names themselves.
+pub const CostClass = enum {
+ plan,
+ credits,
+ api,
+ local,
+
+ pub fn badge(self: CostClass) []const u8 {
+ return switch (self) {
+ .plan => "plan",
+ .credits => "credits",
+ .api => "api",
+ .local => "local",
+ };
+ }
+};
+
+/// One row of the model catalog. A bare name was ambiguous: the same model
+/// served by codex (a ChatGPT plan), codegraff (gateway credits) and openai (a
+/// metered key) drew three identical rows, and picking one resolved the
+/// provider by first-name-match rather than by the row the user chose.
+pub const ModelEntry = struct {
+ name: []const u8,
+ provider: []const u8 = "",
+ /// False when this provider has no credential in this session. The row
+ /// stays — knowing the seat EXISTS is the point — but it is dimmed.
+ has_key: bool = false,
+ cost: CostClass = .api,
+};
+
+/// What a switch actually landed on. The provider travels back with the model
+/// so the current-row marker can tell two same-named seats apart.
+pub const Picked = struct { model: []const u8, provider: []const u8 = "" };
+
+/// Switch to `name` ON `provider`. An empty `provider` means "the caller does
+/// not know one" (a hand-typed `/model <name>`) and asks the engine to route
+/// by name, which is what the picker used to be stuck doing for every pick.
+pub const ModelFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, provider: []const u8, name: []const u8) ?Picked;
pub const CancelFn = *const fn (turn_ctx: ?*anyopaque) void;
/// Fill dest with a staged image path (return >0) or an error line (return <0).
pub const PasteFn = *const fn (turn_ctx: ?*anyopaque, dest: []u8) isize;
@@ -174,6 +213,29 @@ pub fn bgRun(op: *BgOp) void {
pub const HudKind = enum { debug, usage };
pub const HudFn = *const fn (kind: HudKind, buf: []u8) usize;
+/// Everything the host frontend hands the loop at startup: the callbacks that
+/// reach the real agent and the facts the chrome renders from. Lives with the
+/// seam it describes; `run.zig` re-exports it as `run.RunOpts`.
+pub const RunOpts = struct {
+ turn_ctx: ?*anyopaque = null,
+ turn_fn: ?TurnFn = null,
+ model_fn: ?ModelFn = null,
+ cancel_fn: ?CancelFn = null,
+ model_name: []const u8 = "",
+ model_provider: []const u8 = "",
+ /// The model catalog with its provider column (see ModelEntry).
+ model_entries: []const ModelEntry = &.{},
+ cwd: []const u8 = ".",
+ yolo: bool = false,
+ hud_fn: ?HudFn = null,
+ paste_fn: ?PasteFn = null,
+ bash_fn: ?BashFn = null,
+ files_fn: ?FilesFn = null,
+ copy_fn: ?CopyFn = null,
+ compact_fn: ?CompactFn = null,
+ history_fn: ?HistoryFn = null,
+};
+
pub var g_turn_fn: ?TurnFn = null;
pub var g_turn_ctx: ?*anyopaque = null;
pub var g_model_fn: ?ModelFn = null;
@@ -192,7 +254,11 @@ pub fn historyChanged(op: HistoryOp) void {
if (g_history_fn) |f| f(g_turn_ctx, op);
}
pub var g_model_name: []const u8 = "";
-pub var g_models: []const u8 = "";
+/// Provider id serving `g_model_name`. Empty offline.
+pub var g_model_provider: []const u8 = "";
+/// The model catalog, provider column and all. Single source of truth for
+/// every model surface in the TUI — there is no flat name-only string left.
+pub var g_model_entries: []const ModelEntry = &.{};
pub var g_cwd: []const u8 = ".";
pub fn jobRun(job: *Job) void {
diff --git a/TUI/keys_tests.zig b/TUI/keys_tests.zig
index 03768302..b85a308b 100644
--- a/TUI/keys_tests.zig
+++ b/TUI/keys_tests.zig
@@ -84,12 +84,18 @@ test "Shift+Tab cycles Normal Plan Always-approve" {
try std.testing.expectEqual(app.AgentMode.normal, m.mode);
}
+const two_models = [_]engine.ModelEntry{
+ .{ .name = "grok-4", .provider = "xai", .has_key = true, .cost = .plan },
+ .{ .name = "gpt-5.5", .provider = "openai", .has_key = true, .cost = .api },
+};
+
test "model overlay Enter picks the selected name" {
- engine.g_models = "grok-4, gpt-5.5";
+ engine.g_model_entries = &two_models;
engine.g_model_name = "grok-4";
defer {
- engine.g_models = "";
+ engine.g_model_entries = &.{};
engine.g_model_name = "";
+ engine.g_model_provider = "";
engine.g_model_fn = null;
}
var m: Model = undefined;
@@ -100,14 +106,20 @@ test "model overlay Enter picks the selected name" {
_ = handle(&m, .enter);
try std.testing.expectEqual(app.Overlay.none, m.overlay);
try std.testing.expectEqualStrings("gpt-5.5", engine.g_model_name);
+ try std.testing.expectEqualStrings("openai", engine.g_model_provider);
}
test "model overlay type-to-search picks the filtered name" {
- engine.g_models = "grok-4, gpt-5.5, deepseek-v4-pro";
+ engine.g_model_entries = &.{
+ .{ .name = "grok-4", .provider = "xai", .has_key = true },
+ .{ .name = "gpt-5.5", .provider = "openai", .has_key = true },
+ .{ .name = "deepseek-v4-pro", .provider = "codegraff", .has_key = true, .cost = .credits },
+ };
engine.g_model_name = "grok-4";
defer {
- engine.g_models = "";
+ engine.g_model_entries = &.{};
engine.g_model_name = "";
+ engine.g_model_provider = "";
engine.g_model_fn = null;
}
var m: Model = undefined;
@@ -121,6 +133,79 @@ test "model overlay type-to-search picks the filtered name" {
_ = handle(&m, .enter);
try std.testing.expectEqual(app.Overlay.none, m.overlay);
try std.testing.expectEqualStrings("deepseek-v4-pro", engine.g_model_name);
+ try std.testing.expectEqualStrings("codegraff", engine.g_model_provider);
+}
+
+/// Records what the engine was ASKED to switch to. The bug this pins: the
+/// picker handed over a name and the engine re-resolved the provider itself.
+var asked_provider: []const u8 = "";
+var asked_name: []const u8 = "";
+
+fn recordSwitch(_: ?*anyopaque, gpa: std.mem.Allocator, provider: []const u8, name: []const u8) ?engine.Picked {
+ asked_provider = provider;
+ asked_name = name;
+ return .{ .model = gpa.dupe(u8, name) catch return null, .provider = provider };
+}
+
+test "picking the SECOND of two same-named rows switches to that row's provider" {
+ // codex serves gpt-5.6 on a ChatGPT plan and openai serves it on a metered
+ // key. Both rows read "gpt-5.6"; picking the openai one used to send the
+ // bare name and land wherever the router preferred — usually codex.
+ engine.g_model_entries = &.{
+ .{ .name = "gpt-5.6", .provider = "codex", .has_key = true, .cost = .plan },
+ .{ .name = "gpt-5.6", .provider = "openai", .has_key = true, .cost = .api },
+ };
+ engine.g_model_fn = recordSwitch;
+ asked_provider = "";
+ asked_name = "";
+ defer {
+ engine.g_model_entries = &.{};
+ engine.g_model_name = "";
+ engine.g_model_provider = "";
+ engine.g_model_fn = null;
+ }
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.openOverlay(.model);
+ m.overlay_sel = 1;
+ _ = handle(&m, .enter);
+ try std.testing.expectEqualStrings("openai", asked_provider);
+ try std.testing.expectEqualStrings("gpt-5.6", asked_name);
+ try std.testing.expectEqualStrings("openai", engine.g_model_provider);
+ try std.testing.expectEqualStrings("gpt-5.6", engine.g_model_name);
+
+ // ...and the first row still reaches codex, so this is a routed pick and
+ // not a constant.
+ m.openOverlay(.model);
+ m.overlay_sel = 0;
+ _ = handle(&m, .enter);
+ try std.testing.expectEqualStrings("codex", asked_provider);
+ try std.testing.expectEqualStrings("codex", engine.g_model_provider);
+}
+
+test "a provider-filtered pick keeps the provider of the row it matched" {
+ engine.g_model_entries = &.{
+ .{ .name = "gpt-5.6", .provider = "codex", .has_key = true, .cost = .plan },
+ .{ .name = "gpt-5.6", .provider = "openai", .has_key = true, .cost = .api },
+ .{ .name = "k3", .provider = "kimi", .has_key = true, .cost = .plan },
+ };
+ engine.g_model_fn = recordSwitch;
+ asked_provider = "";
+ defer {
+ engine.g_model_entries = &.{};
+ engine.g_model_name = "";
+ engine.g_model_provider = "";
+ engine.g_model_fn = null;
+ }
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.openOverlay(.model);
+ for ("openai") |c| _ = handle(&m, .{ .char = c });
+ _ = handle(&m, .enter);
+ try std.testing.expectEqualStrings("openai", asked_provider);
+ try std.testing.expectEqualStrings("gpt-5.6", asked_name);
}
test "PgUp leaves follow; PgDn returns to the live tail" {
diff --git a/TUI/models.zig b/TUI/models.zig
index 59530bcb..63134af9 100644
--- a/TUI/models.zig
+++ b/TUI/models.zig
@@ -31,31 +31,59 @@ fn containsIgnoreCase(hay: []const u8, needle: []const u8) bool {
return false;
}
-/// Split `engine.g_models` (", "-joined) and keep names matching `query`.
-pub fn filterModels(list: []const u8, query: []const u8, out: [][]const u8) usize {
+/// Match one catalog row. The provider is searchable too: typing "codex"
+/// narrows to the codex seats, which is the only way to answer "show me what
+/// my plan serves" now that the same names appear under several providers.
+pub fn entryMatch(e: engine.ModelEntry, query: []const u8) bool {
+ return modelMatch(e.name, query) or containsIgnoreCase(e.provider, query);
+}
+
+/// Keep the catalog rows matching `query`, in catalog order.
+pub fn filterModels(list: []const engine.ModelEntry, query: []const u8, out: []engine.ModelEntry) usize {
var n: usize = 0;
- var it = std.mem.splitSequence(u8, list, ", ");
- while (it.next()) |raw| {
- const name = std.mem.trim(u8, raw, " \t");
- if (name.len == 0) continue;
- if (!modelMatch(name, query)) continue;
+ for (list) |e| {
+ if (e.name.len == 0) continue;
+ if (!entryMatch(e, query)) continue;
if (n >= out.len) break;
- out[n] = name;
+ out[n] = e;
n += 1;
}
return n;
}
-/// Unfiltered split (empty query). Kept so callers that do not search still work.
-pub fn splitModels(list: []const u8, out: [][]const u8) usize {
- return filterModels(list, "", out);
+/// The row that is live right now: name AND provider, because the same name
+/// under two providers is two different seats and only one of them is current.
+fn isCurrent(e: engine.ModelEntry) bool {
+ if (!std.mem.eql(u8, e.name, engine.g_model_name)) return false;
+ if (engine.g_model_provider.len == 0 or e.provider.len == 0) return true;
+ return std.mem.eql(u8, e.provider, engine.g_model_provider);
+}
+
+/// Display columns, not bytes — model ids are ASCII today, but a padded byte
+/// count would silently skew the provider column the day one is not.
+fn cellWidth(text: []const u8) usize {
+ var n: usize = 0;
+ for (text) |c| {
+ if (c & 0xC0 != 0x80) n += 1;
+ }
+ return n;
+}
+
+/// Column width for the model names in the visible window: wide enough that
+/// the provider column lines up, never wider than the pane can hold.
+fn nameColumn(rows: []const engine.ModelEntry, term_width: usize) usize {
+ const cap = if (term_width > 46) @min(term_width - 34, 40) else 12;
+ var w: usize = 12;
+ for (rows) |e| w = @max(w, cellWidth(tailId(e.name)));
+ return @min(w, cap);
}
pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
const th = self.theme();
- var names: [max_models][]const u8 = undefined;
- const total = splitModels(engine.g_models, &names);
- const n = filterModels(engine.g_models, self.overlay_filter, &names);
+ var rows: [max_models]engine.ModelEntry = undefined;
+ const all = engine.g_model_entries;
+ const total = @min(all.len, max_models);
+ const n = filterModels(all, self.overlay_filter, &rows);
var out = std.array_list.Managed(u8).init(a);
const q = self.overlay_filter;
@@ -73,17 +101,30 @@ pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {
const sel = self.overlay_sel % n;
const vis = @min(visible_rows, n);
const off = if (sel >= vis) sel - vis + 1 else 0;
+ const col = nameColumn(rows[off..@min(n, off + vis)], self.last_term_width);
var i = off;
while (i < n and i < off + vis) : (i += 1) {
- const mark: []const u8 = if (i == sel) "› " else " ";
- const cur: []const u8 = if (std.mem.eql(u8, names[i], engine.g_model_name)) " (current)" else "";
- const shown = tailId(names[i]);
- const line = try std.fmt.allocPrint(a, "{s}{s}{s}", .{ mark, shown, cur });
- try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));
+ const e = rows[i];
+ try out.appendSlice(if (i == sel) "› " else " ");
+ const shown = tailId(e.name);
+ // A seat with no credential keeps its row — the catalog is the map —
+ // but reads as unavailable rather than as one more thing to pick.
+ const dim: []const u8 = if (e.has_key) "" else theme_mod.dim;
+ const name_sgr = try std.fmt.allocPrint(a, "{s}{s}", .{ dim, if (i == sel) th.accent else th.text });
+ try out.appendSlice(try theme_mod.paint(a, name_sgr, shown));
+ try out.appendNTimes(' ', col -| cellWidth(shown));
+ // provider · cost · key — the three facts a bare name hid.
+ const meta = try std.fmt.allocPrint(a, " {s} · {s} {s}{s}", .{
+ e.provider,
+ e.cost.badge(),
+ if (e.has_key) "✓" else "—",
+ if (isCurrent(e)) " (current)" else "",
+ });
+ try out.appendSlice(try theme_mod.paint(a, try std.fmt.allocPrint(a, "{s}{s}", .{ dim, th.muted }), meta));
try out.append('\n');
}
try out.append('\n');
- try out.appendSlice(try theme_mod.paint(a, th.muted, "type to search · ↑↓ move · Enter pick · Esc"));
+ try out.appendSlice(try theme_mod.paint(a, th.muted, "type to search (name or provider) · ↑↓ move · Enter pick · Esc · — no key"));
try out.append('\n');
return out.items;
}
@@ -103,20 +144,39 @@ test "modelMatch: substring and subsequence" {
try std.testing.expect(!modelMatch("gpt-5.6", "claude"));
}
-test "filterModels ranks by query, not the first 32 only" {
- const list = "aaa, bbb, ccc, accounts/fireworks/models/deepseek-v4-pro, gpt-5.6";
- var buf: [8][]const u8 = undefined;
- const n = filterModels(list, "deepseek", &buf);
+const sample = [_]engine.ModelEntry{
+ .{ .name = "aaa", .provider = "openai", .has_key = true, .cost = .api },
+ .{ .name = "bbb", .provider = "codegraff", .has_key = true, .cost = .credits },
+ .{ .name = "ccc", .provider = "codex", .cost = .plan },
+ .{ .name = "accounts/fireworks/models/deepseek-v4-pro", .provider = "fireworks", .has_key = true, .cost = .api },
+ .{ .name = "gpt-5.6", .provider = "codex", .has_key = true, .cost = .plan },
+};
+
+test "filterModels keeps whole catalog rows, not names" {
+ var buf: [8]engine.ModelEntry = undefined;
+ const n = filterModels(&sample, "deepseek", &buf);
try std.testing.expectEqual(@as(usize, 1), n);
- try std.testing.expectEqualStrings("accounts/fireworks/models/deepseek-v4-pro", buf[0]);
- try std.testing.expectEqual(@as(usize, 5), filterModels(list, "", &buf));
+ try std.testing.expectEqualStrings("accounts/fireworks/models/deepseek-v4-pro", buf[0].name);
+ try std.testing.expectEqualStrings("fireworks", buf[0].provider);
+ try std.testing.expectEqual(@as(usize, 5), filterModels(&sample, "", &buf));
+}
+
+test "the query searches the provider column too" {
+ // "show me what my plan serves" — impossible while rows were name-only.
+ var buf: [8]engine.ModelEntry = undefined;
+ const n = filterModels(&sample, "codex", &buf);
+ try std.testing.expectEqual(@as(usize, 2), n);
+ try std.testing.expectEqualStrings("ccc", buf[0].name);
+ try std.testing.expectEqualStrings("gpt-5.6", buf[1].name);
+ try std.testing.expectEqual(@as(usize, 1), filterModels(&sample, "codegraff", &buf));
+ try std.testing.expectEqual(@as(usize, 0), filterModels(&sample, "anthropic", &buf));
}
test "model overlay typed query is a filtered list, not the dump" {
- engine.g_models = "grok-4, gpt-5.5, accounts/fireworks/models/deepseek-v4-pro";
- engine.g_model_name = "grok-4";
+ engine.g_model_entries = &sample;
+ engine.g_model_name = "aaa";
defer {
- engine.g_models = "";
+ engine.g_model_entries = &.{};
engine.g_model_name = "";
}
var m: Model = undefined;
@@ -128,7 +188,93 @@ test "model overlay typed query is a filtered list, not the dump" {
defer arena.deinit();
const text = try render(&m, arena.allocator());
try std.testing.expect(std.mem.indexOf(u8, text, "deepseek-v4-pro") != null);
- try std.testing.expect(std.mem.indexOf(u8, text, "gpt-5.5") == null);
- try std.testing.expect(std.mem.indexOf(u8, text, "1/3") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "gpt-5.6") == null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "1/5") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "Model › deepseek") != null);
}
+
+test "picker rows carry the provider, a cost badge and a key marker" {
+ // The reported bug: two seats for the same model rendered identically, so
+ // "codex (free) vs codegraff (paid) vs openai (paid)" was invisible.
+ const dupes = [_]engine.ModelEntry{
+ .{ .name = "gpt-5.6", .provider = "codex", .has_key = true, .cost = .plan },
+ .{ .name = "gpt-5.6", .provider = "openai", .has_key = true, .cost = .api },
+ .{ .name = "gpt-5.6", .provider = "codegraff", .cost = .credits },
+ };
+ engine.g_model_entries = &dupes;
+ engine.g_model_name = "gpt-5.6";
+ engine.g_model_provider = "openai";
+ defer {
+ engine.g_model_entries = &.{};
+ engine.g_model_name = "";
+ engine.g_model_provider = "";
+ }
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.openOverlay(.model);
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const text = try render(&m, arena.allocator());
+ // provider · cost · key, per row — the keyless seat is marked, not hidden.
+ for ([_][]const u8{ "codex · plan ✓", "openai · api ✓", "codegraff · credits —" }) |want|
+ try std.testing.expect(std.mem.indexOf(u8, text, want) != null);
+ // Exactly one row is current, and it is the one whose PROVIDER matches —
+ // by name alone all three would have claimed it.
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "(current)"));
+ const cur = std.mem.indexOf(u8, text, "(current)").?;
+ const openai = std.mem.indexOf(u8, text, "openai · api").?;
+ try std.testing.expect(openai < cur and cur - openai < 24);
+ // ...and that row is the only dimmed one.
+ try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, text, theme_mod.dim));
+}
+
+test "the provider column lines up under ragged model names" {
+ const ragged = [_]engine.ModelEntry{
+ .{ .name = "k3", .provider = "kimi", .has_key = true, .cost = .plan },
+ .{ .name = "claude-opus-4-8", .provider = "anthropic", .has_key = true, .cost = .api },
+ };
+ engine.g_model_entries = &ragged;
+ defer engine.g_model_entries = &.{};
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.openOverlay(.model);
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const text = try render(&m, arena.allocator());
+ var col: ?usize = null;
+ var seen: usize = 0;
+ var it = std.mem.splitScalar(u8, text, '\n');
+ var buf: [512]u8 = undefined;
+ while (it.next()) |line| {
+ const plain = strip(line, &buf);
+ // Only the catalog rows: they alone open with the selection gutter.
+ if (!std.mem.startsWith(u8, plain, " ") and !std.mem.startsWith(u8, plain, "› ")) continue;
+ const sep = std.mem.indexOf(u8, plain, " · ") orelse continue;
+ var start = sep;
+ while (start > 0 and plain[start - 1] != ' ') start -= 1;
+ const at = cellWidth(plain[0..start]);
+ if (col) |c| try std.testing.expectEqual(c, at) else col = at;
+ seen += 1;
+ }
+ try std.testing.expectEqual(@as(usize, 2), seen);
+}
+
+/// `line` with its SGR sequences removed, written into `buf`. The padding is
+/// what is under test and an escape sequence is zero cells wide.
+fn strip(line: []const u8, buf: []u8) []const u8 {
+ var n: usize = 0;
+ var i: usize = 0;
+ while (i < line.len and n < buf.len) {
+ if (line[i] == 0x1b) {
+ while (i < line.len and line[i] != 'm') i += 1;
+ i += 1;
+ continue;
+ }
+ buf[n] = line[i];
+ n += 1;
+ i += 1;
+ }
+ return buf[0..n];
+}
diff --git a/TUI/overlays.zig b/TUI/overlays.zig
index 05fe22f6..5cbfb978 100644
--- a/TUI/overlays.zig
+++ b/TUI/overlays.zig
@@ -102,20 +102,25 @@ fn activate(self: *Model) Effect {
},
.model => {
const models = @import("models.zig");
- var names: [models.max_models][]const u8 = undefined;
- const n = models.filterModels(engine.g_models, self.overlay_filter, &names);
+ var rows: [models.max_models]engine.ModelEntry = undefined;
+ const n = models.filterModels(engine.g_model_entries, self.overlay_filter, &rows);
const sel = if (n == 0) 0 else self.overlay_sel % n;
self.closeOverlay();
if (n == 0) return .stay;
- const pick = names[sel];
+ // THE row the user chose, provider and all. Handing the engine the
+ // name alone let it re-route by first-name-match, so picking the
+ // openai row for a model codex also serves landed on codex.
+ const pick = rows[sel];
if (engine.g_model_fn) |f| {
- if (f(engine.g_turn_ctx, self.alloc, pick)) |nm| {
- engine.g_model_name = nm;
- self.setToast(nm);
+ if (f(engine.g_turn_ctx, self.alloc, pick.provider, pick.name)) |got| {
+ self.adoptModel(got);
+ self.setToast(got.model);
+ self.pushFmt(.system, "model → {s} · {s}", .{ got.model, got.provider }) catch {};
} else self.setToast("couldn't switch");
} else {
- engine.g_model_name = pick;
- self.setToast(pick);
+ engine.g_model_name = pick.name;
+ engine.g_model_provider = pick.provider;
+ self.setToast(pick.name);
}
},
.effort => {
diff --git a/TUI/root.zig b/TUI/root.zig
index 205af871..dd6352ef 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -23,6 +23,9 @@ pub const ToolEvent = engine.ToolEvent;
pub const Status = engine.Status;
pub const TurnFn = engine.TurnFn;
pub const ModelFn = engine.ModelFn;
+pub const ModelEntry = engine.ModelEntry;
+pub const CostClass = engine.CostClass;
+pub const Picked = engine.Picked;
pub const CancelFn = engine.CancelFn;
pub const CompactOut = engine.CompactOut;
pub const CompactFn = engine.CompactFn;
diff --git a/TUI/run.zig b/TUI/run.zig
index caad21ed..f2a0067d 100644
--- a/TUI/run.zig
+++ b/TUI/run.zig
@@ -30,23 +30,9 @@ pub const enable_seq = "\x1b[?1049h\x1b[?25l\x1b[?2004h\x1b[?1000h\x1b[?1003h\x1
/// is unchanged, so the repaint is the same bytes into a synchronized swap.
pub const heal_interval_ms: u64 = 3000;
-pub const RunOpts = struct {
- turn_ctx: ?*anyopaque = null,
- turn_fn: ?engine.TurnFn = null,
- model_fn: ?engine.ModelFn = null,
- cancel_fn: ?engine.CancelFn = null,
- model_name: []const u8 = "",
- models: []const u8 = "",
- cwd: []const u8 = ".",
- yolo: bool = false,
- hud_fn: ?engine.HudFn = null,
- paste_fn: ?engine.PasteFn = null,
- bash_fn: ?engine.BashFn = null,
- files_fn: ?engine.FilesFn = null,
- copy_fn: ?engine.CopyFn = null,
- compact_fn: ?engine.CompactFn = null,
- history_fn: ?engine.HistoryFn = null,
-};
+/// Every seam the frontend is handed, declared with the engine that owns
+/// them (engine.RunOpts). Re-exported here because `run` is its only caller.
+pub const RunOpts = engine.RunOpts;
pub fn run(
gpa: std.mem.Allocator,
@@ -70,7 +56,8 @@ pub fn run(
engine.g_compact_fn = opts.compact_fn;
engine.g_history_fn = opts.history_fn;
engine.g_model_name = opts.model_name;
- engine.g_models = opts.models;
+ engine.g_model_provider = opts.model_provider;
+ engine.g_model_entries = opts.model_entries;
engine.g_cwd = opts.cwd;
var m: Model = undefined;
diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.sh
index 593e130c..b82bfa0c 100644
--- a/scripts/eval-tier1.sh
+++ b/scripts/eval-tier1.sh
@@ -326,6 +326,14 @@ if wanted tuiguard; then
if python3 scripts/test-tui-scrollbar-osc52.py zig-out/bin/graff; then :; else
record_fail tuiguard
fi
+ # #560: the picker has to say WHO serves each model. Reads the open overlay
+ # off the virtual screen and checks that every row carries a provider and a
+ # cost badge, that gpt-5.5 draws one distinguishable row per provider with
+ # the right badge on each (codex plan / openai api / codegraff credits),
+ # and that typing a provider name filters to that provider's seats.
+ if python3 scripts/test-tui-model-picker.py zig-out/bin/graff; then :; else
+ record_fail tuiguard
+ fi
fi
fi
diff --git a/scripts/test-tui-model-picker.py b/scripts/test-tui-model-picker.py
new file mode 100755
index 00000000..758bf5a9
--- /dev/null
+++ b/scripts/test-tui-model-picker.py
@@ -0,0 +1,215 @@
+#!/usr/bin/env python3
+"""Live proof that the TUI model picker says WHO serves each model (#560).
+
+The report: "i cant see who the provider is when i use /models ... being codex
+(free) vs codegraff(paid) vs openai(paid) is mad diff". The picker rendered
+bare model names, so one model served by three providers drew three identical
+rows and the pick resolved by name.
+
+This probe drives the real binary under a pty, renders its output into a
+VIRTUAL SCREEN (scripts/ptyharness.py) and reads CELLS back, so every assertion
+is about what a terminal would actually show:
+
+ 1. opening the picker shows a provider AND a cost badge on every row, with
+ the three classes from the report visible at once — a plan seat (codex),
+ a credits seat (codegraff) and a metered api seat (openai),
+ 2. one model name that several providers serve appears once per provider and
+ those rows are distinguishable,
+ 3. typing a PROVIDER name filters to that provider's seats,
+ 4. a provider with no credential still has rows, marked with — rather than
+ dropped, and
+ 5. Esc closes the picker without switching anything.
+
+Usage: python3 scripts/test-tui-model-picker.py [path/to/graff]
+Exit 0 = pass, or a skip when there is no pty.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import tempfile
+import time
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+from ptyharness import PtyHarness # noqa: E402
+
+BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")
+ROWS, COLS = 40, 110
+
+
+def workspace(tmp):
+ codex_home = os.path.join(tmp, "codex-home")
+ os.makedirs(codex_home)
+ with open(os.path.join(codex_home, "auth.json"), "w", encoding="utf-8") as fh:
+ json.dump({"tokens": {"access_token": "picker-mock", "account_id": "acct-picker"}}, fh)
+ harness = os.path.join(tmp, ".harness")
+ os.makedirs(harness)
+ with open(os.path.join(harness, "settings.json"), "w", encoding="utf-8") as fh:
+ json.dump({"ai_title": False, "skills": {"codedbpro": False}}, fh)
+ empty_mcp = os.path.join(tmp, "empty-mcp.json")
+ with open(empty_mcp, "w", encoding="utf-8") as fh:
+ fh.write('{"mcpServers": {}}')
+ env = {
+ "HOME": tmp,
+ "CODEX_HOME": codex_home,
+ # One metered key and one gateway credential, so all three cost
+ # classes the user named are on screen at the same time.
+ "OPENAI_API_KEY": "sk-picker-test",
+ "CODEGRAFF_API_KEY": "cg_sk_picker_test",
+ "GRAFF_CODEX_WS": "off",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ "GRAFF_MCP_CONFIG": empty_mcp,
+ "GRAFF_LEARN_AUTO": "off",
+ }
+ for name in list(os.environ):
+ if (name.startswith("GRAFF_") or name.startswith("CODEX_") or name == "NO_COLOR") and name not in env:
+ env[name] = None
+ return env
+
+
+BADGES = ("plan", "credits", "api", "local")
+
+
+def picker_rows(h):
+ """Screen lines that are catalog rows: `name provider \u00b7 badge [marker]`."""
+ out = []
+ for ln in h.screen_lines():
+ s = ln.rstrip()
+ if not (s.startswith(" ") or s.startswith("\u203a ") or s.startswith(" \u203a ")):
+ continue
+ head, sep, tail = s.partition(" \u00b7 ")
+ if not sep or not head.strip():
+ continue
+ words = tail.split()
+ if not words or words[0] not in BADGES:
+ continue
+ out.append(s)
+ return out
+
+
+def open_picker(h, query=b""):
+ h.inject_keys(b"/models\r")
+ h.pump(1.0)
+ if query:
+ for ch in query:
+ h.inject_keys(bytes([ch]))
+ h.pump(0.9)
+ return picker_rows(h)
+
+
+def close_picker(h):
+ h.inject_keys(b"\x1b")
+ h.pump(0.6)
+
+
+def seat(row):
+ """(name, provider, badge) off a rendered picker row."""
+ head, _, tail = row.partition(" \u00b7 ")
+ parts = head.split()
+ provider = parts[-1] if parts else ""
+ name = " ".join(parts[:-1]).lstrip("\u203a ").strip()
+ badge = tail.split()[0] if tail.split() else ""
+ return name, provider, badge
+
+
+def check(h):
+ # (1) the resting picker: every row names a provider and a cost class.
+ rows = open_picker(h)
+ if "Model \u203a" not in h.screen_contents():
+ return f"the picker never opened\n{h.screen_contents()}"
+ if len(rows) < 8:
+ return f"only {len(rows)} picker rows carry a provider column\n{h.screen_contents()}"
+ for row in rows:
+ name, provider, badge = seat(row)
+ if not name or not provider:
+ return f"a picker row has no provider column: {row!r}"
+ if badge not in ("plan", "credits", "api", "local"):
+ return f"a picker row has no cost badge: {row!r}"
+
+ # (4) a provider with no credential keeps its rows, marked rather than gone.
+ if not any(r.rstrip().endswith("\u2014") for r in rows):
+ return f"no keyless row is marked\n{chr(10).join(rows)}"
+ # (2) THE report: one model, three providers, three different bills, and
+ # three rows a human can tell apart.
+ close_picker(h)
+ shared = open_picker(h, b"gpt-5.5")
+ seats = [seat(r) for r in shared if seat(r)[0] == "gpt-5.5"]
+ providers = {p for _, p, _ in seats}
+ badges = {p: b for _, p, b in seats}
+ for want, cost in (("codex", "plan"), ("openai", "api"), ("codegraff", "credits")):
+ if want not in providers:
+ return f"gpt-5.5 has no {want} row — providers seen: {providers}\n{chr(10).join(shared)}"
+ if badges[want] != cost:
+ return f"gpt-5.5 on {want} is badged {badges[want]!r}, expected {cost!r}"
+ if len({r.strip() for r in shared}) != len(shared):
+ return f"two gpt-5.5 rows render identically:\n{chr(10).join(shared)}"
+
+ # (3) typing a PROVIDER filters to it. codegraff appears in no model name,
+ # so every surviving row must be a codegraff seat.
+ close_picker(h)
+ gateway = open_picker(h, b"codegraff")
+ if not gateway:
+ return f"typing 'codegraff' emptied the picker\n{h.screen_contents()}"
+ off = [r for r in gateway if seat(r)[1] != "codegraff" or seat(r)[2] != "credits"]
+ if off:
+ return f"the codegraff filter left foreign rows: {off}"
+
+ # ...and the plan seats are reachable the same way.
+ close_picker(h)
+ plan = open_picker(h, b"codex")
+ if not any(seat(r)[1] == "codex" and seat(r)[2] == "plan" for r in plan):
+ return f"typing 'codex' surfaced no plan seat\n{chr(10).join(plan)}"
+
+ # (5) Esc closes it without switching anything.
+ close_picker(h)
+ if "Model \u203a" in h.screen_contents():
+ return "Esc did not close the picker"
+ return None
+
+
+def run():
+ with tempfile.TemporaryDirectory(prefix="graff-picker-") as tmp:
+ h = PtyHarness([BIN, "tui", "--yolo", "--no-telemetry"], cols=COLS, rows=ROWS, cwd=tmp, env=workspace(tmp))
+ try:
+ if not h.wait_for_boot():
+ return f"the session never reached the alt screen\n{h.screen_contents()}"
+ return check(h)
+ finally:
+ h.close()
+
+
+def main():
+ if not os.path.exists(BIN):
+ print(f"tui-model-picker: {BIN} not built — skipping")
+ return 0
+ try:
+ import pty # noqa: F401
+ except ImportError:
+ print("tui-model-picker: no pty support here — skipping")
+ return 0
+ started = time.time()
+ try:
+ err = run()
+ except OSError as e:
+ if getattr(e, "errno", None) == 5:
+ err = "pty EIO — the graff process died mid-check"
+ else:
+ print(f"tui-model-picker: pty unavailable ({e}) — skipping")
+ return 0
+ if err:
+ print(f" ✗ model-picker: {err}")
+ return 1
+ print(
+ " ✓ model-picker: every row names its provider and cost class "
+ f"(plan/credits/api), same-named seats are distinguishable, and typing a "
+ f"provider filters to it ({time.time() - started:.0f}s)"
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/src/billing.zig b/src/billing.zig
index c4ba8ab6..7d1cd0a9 100644
--- a/src/billing.zig
+++ b/src/billing.zig
@@ -46,6 +46,57 @@ pub fn subscriptionLogin(provider_id: []const u8) bool {
return false;
}
+/// A seat served from THIS MACHINE — a local OpenAI-compatible server (LM
+/// Studio :1234, mlx-lm :8080). The rule mirrors `keys_cli.isLocalUrl`, which
+/// this module deliberately does not import: keys_cli is the interactive key
+/// CLI and billing is a leaf.
+fn localSeat(provider_id: []const u8) bool {
+ const spec = provider_mod.specFor(provider_id) orelse return false;
+ return std.mem.indexOf(u8, spec.url, "127.0.0.1") != null or
+ std.mem.indexOf(u8, spec.url, "localhost") != null;
+}
+
+/// What a turn on this seat COSTS THE USER, in the terms they think in.
+/// `Billing` answers "does /cost add a number", which is the accountant's
+/// question; this answers "am I about to spend my plan, my gateway balance, or
+/// my metered key", which is the one a model picker has to answer BEFORE the
+/// turn. The same `gpt-5.6` reached through codex, codegraff and openai is
+/// three different bills and used to render as three identical rows.
+pub const CostClass = enum {
+ /// Flat-rate subscription login: ChatGPT plan, SuperGrok, Kimi.
+ plan,
+ /// The codegraff gateway, drawn against a credit balance.
+ credits,
+ /// A metered vendor key — the meter runs per token.
+ api,
+ /// A server on this machine. No bill exists.
+ local,
+
+ pub fn badge(self: CostClass) []const u8 {
+ return switch (self) {
+ .plan => "plan",
+ .credits => "credits",
+ .api => "api",
+ .local => "local",
+ };
+ }
+};
+
+/// Classify a seat. Where a credential exists it decides — the same discipline
+/// `forSeat` uses, because it is the LOGIN that is flat-rate and not the
+/// vendor. A seat with no credential yet falls back to the provider table and
+/// there advertises what signing in would buy, which is the only useful thing
+/// to say on a row the user cannot pick yet.
+pub fn costFor(provider_id: []const u8, source: CredentialSource) CostClass {
+ if (localSeat(provider_id)) return .local;
+ if (std.mem.eql(u8, provider_id, "codegraff")) return .credits;
+ if (!subscriptionLogin(provider_id)) return .api;
+ return switch (source) {
+ .login, .none => .plan,
+ .environment, .stored, .session => .api,
+ };
+}
+
/// The billing class of one API call on this seat.
pub fn forSeat(provider_id: []const u8, model: []const u8, source: CredentialSource) Billing {
if (source == .login and subscriptionLogin(provider_id)) return .sub;
@@ -118,3 +169,59 @@ test "freeAtTheMargin follows the credential, not the vendor" {
try std.testing.expect(!freeAtTheMargin(seat("xai", "grok-4.3", .environment)));
try std.testing.expect(!freeAtTheMargin(seat("anthropic", "claude-opus-4-8", .environment)));
}
+
+test "costFor: the picker's badge follows the credential, then the provider" {
+ // The user's complaint, encoded: codex is a ChatGPT plan, the codegraff
+ // gateway spends credits, and a raw OpenAI key runs a meter — three
+ // different bills that used to render as the same bare model name.
+ try std.testing.expectEqual(CostClass.plan, costFor("codex", .login));
+ try std.testing.expectEqual(CostClass.credits, costFor("codegraff", .login));
+ try std.testing.expectEqual(CostClass.credits, costFor("codegraff", .environment));
+ try std.testing.expectEqual(CostClass.api, costFor("openai", .environment));
+ try std.testing.expectEqual(CostClass.api, costFor("anthropic", .stored));
+
+ // Same provider, two credentials, two answers — `graff login xai` buys a
+ // plan, XAI_API_KEY buys metered api.x.ai.
+ try std.testing.expectEqual(CostClass.plan, costFor("xai", .login));
+ try std.testing.expectEqual(CostClass.api, costFor("xai", .environment));
+ try std.testing.expectEqual(CostClass.plan, costFor("kimi", .login));
+ try std.testing.expectEqual(CostClass.api, costFor("kimi", .stored));
+
+ // localhost is nobody's bill.
+ try std.testing.expectEqual(CostClass.local, costFor("lmstudio", .environment));
+ try std.testing.expectEqual(CostClass.local, costFor("mlx", .none));
+
+ // No credential: the row still says what signing in would buy.
+ try std.testing.expectEqual(CostClass.plan, costFor("codex", .none));
+ try std.testing.expectEqual(CostClass.api, costFor("openai", .none));
+
+ // An id nothing knows is metered, the same safe direction `forSeat` takes.
+ try std.testing.expectEqual(CostClass.api, costFor("no-such-provider", .login));
+}
+
+test "costFor agrees with forSeat wherever both have an opinion" {
+ // Two classifiers over one fact is how #471 happened. They answer
+ // different questions, but a plan seat must never be a metered badge.
+ for (provider_mod.provider_specs) |spec| {
+ for ([_]CredentialSource{ .none, .environment, .login, .stored, .session }) |src| {
+ const class = costFor(spec.id, src);
+ const sub = forSeat(spec.id, "definitely-not-in-the-price-sheet", src) == .sub;
+ if (sub) try std.testing.expectEqual(CostClass.plan, class);
+ if (class == .plan) try std.testing.expect(sub or src == .none);
+ }
+ }
+}
+
+test "every CostClass badge is short, distinct and non-empty" {
+ // The badge is a table column in two surfaces; an empty or oversized one
+ // silently breaks alignment rather than failing anywhere.
+ var seen: [4][]const u8 = undefined;
+ var n: usize = 0;
+ for ([_]CostClass{ .plan, .credits, .api, .local }) |c| {
+ const b = c.badge();
+ try std.testing.expect(b.len > 0 and b.len <= 7);
+ for (seen[0..n]) |prev| try std.testing.expect(!std.mem.eql(u8, prev, b));
+ seen[n] = b;
+ n += 1;
+ }
+}
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index 8a330e53..bb288df1 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -21,8 +21,8 @@ pub const Item = struct {
/// The canonical command list, in menu / help display order.
pub const commands = [_]Item{
- .{ .name = "/model", .usage = "/model <name>", .desc = "switch model/provider, fuzzy match (e.g. \"sonnet\", \"opus\")" },
- .{ .name = "/models", .usage = "/models [health]", .desc = "list known models, context windows, compaction points; health shows live state" },
+ .{ .name = "/model", .usage = "/model [<provider>] <name>", .desc = "switch model/provider, fuzzy match (e.g. \"sonnet\", \"opus\"); name a provider to pin the seat" },
+ .{ .name = "/models", .usage = "/models [health]", .desc = "list known models: context window, compaction point, provider and what that seat costs (plan/credits/api/local); health shows live state" },
.{ .name = "/clear", .desc = "wipe the conversation and start fresh" },
.{ .name = "/new", .desc = "start a fresh autosaved session" },
.{ .name = "/rename", .usage = "/rename <title>", .desc = "set the current session title" },
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index 35595ec9..e9e2ddfa 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -37,6 +37,12 @@ const jobs = @import("jobs.zig");
const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: which listed MCP tools are still schema-deferred
const subagent = @import("subagent.zig"); // #276 P0-3: g_agent_jobs, for /jobs
+const billing = @import("billing.zig");
+const models_table = @import("models_table.zig");
+
+test { // main.zig is the test root, so this reference is what runs its tests
+ _ = models_table;
+}
const pricing = @import("pricing.zig");
const obs = @import("obs.zig");
const default_context = pricing.default_context;
@@ -373,21 +379,19 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
// TTL that made /models show a boot-time snapshot until restart.
const pinged = providers.refreshModelListing(root, keys.*);
if (pinged > 0) try out.print("{s}(pinged {d} provider catalog(s) live){s}\n", .{ style.dim, pinged, style.reset });
- try out.writeAll("model ctx compact@ provider key vision\n");
- for (pricing.models()) |m| {
- const has_key = keys.get(m.provider) != null;
- const current = std.mem.eql(u8, m.name, root.provider.model) and std.mem.eql(u8, m.provider, root.provider.id);
- const context = pricing.contextFor(m.provider, m.name);
- try out.print("{s:<26} {d:>5}k {d:>5}k {s:<11} {s} {s}{s}\n", .{
- m.name,
- context / 1000,
- context / 10 * 8 / 1000,
- m.provider,
- if (has_key) "✓" else "—",
- if (visionModel(m.name)) "✓" else "—",
- if (current) " ← current" else "",
- });
- }
+ // `cost` answers what a model name cannot: the same model through codex
+ // (plan), codegraff (credits) and openai (api) is three different
+ // bills. Same wording as the TUI picker; the surfaces must agree.
+ try out.writeAll(models_table.header);
+ for (pricing.models()) |m| try models_table.writeRow(out, .{
+ .name = m.name,
+ .context = pricing.contextFor(m.provider, m.name),
+ .provider = m.provider,
+ .cost = billing.costFor(m.provider, keys.source(m.provider)).badge(),
+ .has_key = keys.get(m.provider) != null,
+ .vision = visionModel(m.name),
+ .current = std.mem.eql(u8, m.name, root.provider.model) and std.mem.eql(u8, m.provider, root.provider.id),
+ });
try out.print("(codex catalog: {s})\n", .{models_cache.codex_catalog_source});
try out.print("(kimi catalog: {s})\n", .{kimi_catalog.catalog_source});
try out.print("(unknown models: {d}k ctx; claude* → anthropic, else → codegraff)\n", .{default_context / 1000});
diff --git a/src/models_table.zig b/src/models_table.zig
new file mode 100644
index 00000000..94b88086
--- /dev/null
+++ b/src/models_table.zig
@@ -0,0 +1,118 @@
+//! Column layout of the line-REPL `/models` table (#560).
+//!
+//! One place, so the header and the rows cannot drift apart and so the
+//! 80-column budget is something a test can hold us to. The `cost` column is
+//! the point: `/models` used to say WHICH provider serves a model but not what
+//! that seat costs, and the TUI picker did not even say the provider — the two
+//! surfaces now print the same provider and the same badge.
+
+const std = @import("std");
+const Io = std.Io;
+
+pub const header = "model ctx compact@ provider cost key vision\n";
+const row_fmt = "{s:<24} {d:>5}k {d:>5}k {s:<10} {s:<7} {s} {s}{s}\n";
+
+pub const Row = struct {
+ name: []const u8,
+ /// Context window in tokens; the table prints it, and 80% of it, in k.
+ context: u64,
+ provider: []const u8,
+ /// `billing.CostClass.badge()` — plan / credits / api / local.
+ cost: []const u8,
+ has_key: bool = false,
+ vision: bool = false,
+ current: bool = false,
+};
+
+pub fn writeRow(out: *Io.Writer, r: Row) !void {
+ try out.print(row_fmt, .{
+ r.name,
+ r.context / 1000,
+ r.context / 10 * 8 / 1000,
+ r.provider,
+ r.cost,
+ if (r.has_key) "✓" else "—",
+ if (r.vision) "✓" else "—",
+ if (r.current) " ← current" else "",
+ });
+}
+
+/// Terminal cells, not bytes: ✓ and — are three bytes and one column each, so
+/// a byte count would report this table as far wider than it prints.
+fn cells(text: []const u8) usize {
+ var n: usize = 0;
+ for (text) |c| {
+ if (c & 0xC0 != 0x80) n += 1;
+ }
+ return n;
+}
+
+/// Cell column at which `needle` starts in `line`, or null.
+fn columnOf(line: []const u8, needle: []const u8) ?usize {
+ const at = std.mem.indexOf(u8, line, needle) orelse return null;
+ return cells(line[0..at]);
+}
+
+fn sample(buf: []u8, r: Row) ![]const u8 {
+ var w: Io.Writer = .fixed(buf);
+ try writeRow(&w, r);
+ const out = w.buffered();
+ return if (std.mem.endsWith(u8, out, "\n")) out[0 .. out.len - 1] else out;
+}
+
+test "header labels sit over the columns their values land in" {
+ // The regression this blocks is silent: change one width and the table
+ // still prints, just with `cost` sitting over the provider ids.
+ var buf: [256]u8 = undefined;
+ const line = try sample(&buf, .{
+ .name = "claude-opus-4-8",
+ .context = 200_000,
+ .provider = "anthropic",
+ .cost = "api",
+ .has_key = true,
+ .vision = true,
+ });
+ for ([_][]const u8{ "provider", "cost" }) |label| {
+ const want = columnOf(header, label) orelse return error.MissingLabel;
+ const got = switch (label[0]) {
+ 'p' => columnOf(line, "anthropic"),
+ else => columnOf(line, "api"),
+ } orelse return error.MissingValue;
+ try std.testing.expectEqual(want, got);
+ }
+ // key and vision are single glyphs; they must land inside their labels.
+ const key_at = cells(line[0..std.mem.indexOf(u8, line, "✓").?]);
+ try std.testing.expectEqual(columnOf(header, "key").?, key_at);
+}
+
+test "a row with the current marker still fits 80 columns" {
+ var buf: [256]u8 = undefined;
+ const line = try sample(&buf, .{
+ .name = "gpt-5.6-sol",
+ .context = 272_000,
+ .provider = "codegraff",
+ .cost = "credits",
+ .has_key = true,
+ .vision = true,
+ .current = true,
+ });
+ try std.testing.expect(cells(line) <= 80);
+ try std.testing.expect(cells(header) <= 80);
+ try std.testing.expect(std.mem.endsWith(u8, line, "← current"));
+ try std.testing.expect(std.mem.indexOf(u8, line, "credits") != null);
+}
+
+test "the compact@ column is 80% of the context window" {
+ var buf: [256]u8 = undefined;
+ const line = try sample(&buf, .{ .name = "m", .context = 200_000, .provider = "p", .cost = "api" });
+ try std.testing.expect(std.mem.indexOf(u8, line, "200k") != null);
+ try std.testing.expect(std.mem.indexOf(u8, line, "160k") != null);
+}
+
+test "a keyless row is marked, not dropped" {
+ var buf: [256]u8 = undefined;
+ const line = try sample(&buf, .{ .name = "m", .context = 1000, .provider = "fugu", .cost = "api" });
+ try std.testing.expect(std.mem.indexOf(u8, line, "fugu") != null);
+ try std.testing.expect(std.mem.indexOf(u8, line, "—") != null);
+ try std.testing.expect(std.mem.indexOf(u8, line, "✓") == null);
+}
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index 64a908a0..bd61a86b 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -67,8 +67,9 @@ pub const ReplCtx = struct {
pub const Conversation = repl_convo.Conversation;
const repl_convo = @import("repl_convo.zig");
-test {
+test { // or their tests silently never run (unit_tests' root is main.zig)
_ = repl_convo;
+ _ = @import("repl_model_pick_test.zig");
}
/// The live-pane writer, in repl_stream_sink.zig (move+alias, #123).
@@ -306,14 +307,54 @@ test {
/// 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 {
+ const picked = replModelPick(ctx_ptr, gpa, "", name) orelse return null;
+ return picked.model;
+}
+
+/// What a model switch settled on. The provider id travels back because the
+/// caller may have asked for a model TWO providers serve, and which one it
+/// landed on is the difference between spending a plan and spending a key.
+pub const Picked = struct { model: []const u8, provider: []const u8 };
+
+/// The catalog's own copy of this seat's model name. Borrowing it rather than
+/// duplicating keeps the switched Provider pointing at storage that outlives
+/// the caller's buffer, which is what the name-routed path has always done.
+fn catalogName(provider_id: []const u8, name: []const u8) ?[]const u8 {
+ for (pricing.models()) |m|
+ if (std.mem.eql(u8, m.provider, provider_id) and std.mem.eql(u8, m.name, name)) return m.name;
+ return null;
+}
+
+/// Switch to `name` on a NAMED provider. An empty `provider_id` means the
+/// caller does not know one (a hand-typed `/model <name>`) and the router
+/// picks, which is the old behaviour. When it IS known — the catalog row the
+/// user clicked — that seat is honoured or the switch fails; silently
+/// rerouting to whichever provider the router prefers is the bug this closes,
+/// because choosing between two seats for one model name is the picker's whole
+/// 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));
- const resolved = pricing.resolveModelName(c.keys, name) orelse return null;
- c.provider = c.keys.providerFor(gpa.dupe(u8, resolved) catch return null) catch return null;
+ 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;
+ 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 {
+ if (owned) gpa.free(model);
+ return null;
+ };
+ } else {
+ // `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;
+ }
c.fallback_active = false;
c.fallback_blocked = false;
serde.saveModel(c.io, c.home, c.provider.id, c.provider.model);
- return gpa.dupe(u8, c.provider.model) catch null;
+ return .{ .model = gpa.dupe(u8, c.provider.model) catch return null, .provider = c.provider.id };
}
+
/// repl.CancelFn adapter — force-interrupt the running repl turn. Sets the
/// Agent-wide esc_cancel flag the streaming loops + watchdog poll, so the
/// in-flight runTurn unwinds (error.Interrupted) and the repl drains its steer
diff --git a/src/repl_model_pick_test.zig b/src/repl_model_pick_test.zig
new file mode 100644
index 00000000..1f32a15d
--- /dev/null
+++ b/src/repl_model_pick_test.zig
@@ -0,0 +1,104 @@
+//! Provider-aware model switching (#560).
+//!
+//! The reported bug: the TUI picker showed bare model names, so a model served
+//! by codex (a ChatGPT plan), codegraff (gateway credits) and openai (a metered
+//! key) drew three identical rows — and picking one sent only the NAME to the
+//! engine, which re-resolved the provider by router preference. Choosing the
+//! openai row could land on codex. These tests pin the engine half of the fix.
+
+const std = @import("std");
+const provider_mod = @import("provider.zig");
+const repl_glue = @import("repl_glue.zig");
+const Keys = provider_mod.Keys;
+
+/// A ReplCtx with nothing wired but the credentials — enough for a model
+/// switch, which touches keys and provider and nothing else. `home` is empty,
+/// which `serde.saveModel` documents as a no-op, so no test writes to disk.
+fn switchCtx(client: *std.http.Client, keys: Keys) repl_glue.ReplCtx {
+ return .{
+ .io = std.testing.io,
+ .client = client,
+ .keys = keys,
+ .home = "",
+ .provider = .{ .id = "codegraff", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "start", .context = 0 },
+ .fallback_allow = &.{},
+ .fallback_active = true,
+ .fallback_blocked = true,
+ .registry = null,
+ .tracer = null,
+ .run_budget = null,
+ .sys_normal = "",
+ .tools_anthropic = "",
+ .tools_openai = "",
+ .tools_responses = "",
+ };
+}
+
+fn keyedFor(ids: []const []const u8) Keys {
+ var keys: Keys = .{ .values = @splat(null) };
+ for (ids) |id| _ = keys.set(id, "test-key", .stored);
+ return keys;
+}
+
+test "replModelPick honours the provider the row named (#560)" {
+ // gpt-5.5 really is served by codex, openai AND codegraff, which is the
+ // shape the user hit: three identical-looking rows, wildly different bills.
+ var client: std.http.Client = undefined;
+ var keys = keyedFor(&.{ "codex", "openai", "codegraff" });
+ keys.codex_account = "acct";
+ var ctx = switchCtx(&client, keys);
+ const picked = repl_glue.replModelPick(&ctx, std.testing.allocator, "openai", "gpt-5.5") orelse
+ return error.TestUnexpectedResult;
+ defer std.testing.allocator.free(picked.model);
+ try std.testing.expectEqualStrings("openai", picked.provider);
+ try std.testing.expectEqualStrings("openai", ctx.provider.id);
+ try std.testing.expectEqualStrings("gpt-5.5", ctx.provider.model);
+ // An explicit choice also clears a temporary failover.
+ try std.testing.expect(!ctx.fallback_active);
+ try std.testing.expect(!ctx.fallback_blocked);
+
+ // The SAME name asked for on codex lands on codex — routed, not rewritten.
+ var ctx2 = switchCtx(&client, keys);
+ const codex = repl_glue.replModelPick(&ctx2, std.testing.allocator, "codex", "gpt-5.5") orelse
+ return error.TestUnexpectedResult;
+ defer std.testing.allocator.free(codex.model);
+ try std.testing.expectEqualStrings("codex", codex.provider);
+ try std.testing.expectEqualStrings("codex", ctx2.provider.id);
+}
+
+test "a name with no provider still routes by name, as /model always did" {
+ var client: std.http.Client = undefined;
+ const keys = keyedFor(&.{"openai"});
+ var ctx = switchCtx(&client, keys);
+ const picked = repl_glue.replModelPick(&ctx, std.testing.allocator, "", "gpt-5.5") orelse
+ return error.TestUnexpectedResult;
+ defer std.testing.allocator.free(picked.model);
+ try std.testing.expectEqualStrings("openai", picked.provider);
+
+ // A named provider with no credential FAILS the switch rather than quietly
+ // sending the turn somewhere the user did not choose.
+ var ctx2 = switchCtx(&client, keys);
+ try std.testing.expect(repl_glue.replModelPick(&ctx2, std.testing.allocator, "anthropic", "claude-opus-4-8") == null);
+ try std.testing.expectEqualStrings("codegraff", ctx2.provider.id);
+ try std.testing.expectEqualStrings("start", ctx2.provider.model);
+}
+
+test "an off-catalog model on a named provider is copied, not borrowed" {
+ // LM Studio serves whatever is loaded, so those ids are in no table. The
+ // switch must still work and the copy must be the caller's to free.
+ var client: std.http.Client = undefined;
+ const keys = keyedFor(&.{"lmstudio"});
+ var ctx = switchCtx(&client, keys);
+ var name_buf: [16]u8 = undefined;
+ const name = name_buf[0.."local/thing".len];
+ @memcpy(name, "local/thing");
+ const picked = repl_glue.replModelPick(&ctx, std.testing.allocator, "lmstudio", name) orelse
+ return error.TestUnexpectedResult;
+ defer std.testing.allocator.free(picked.model);
+ try std.testing.expectEqualStrings("lmstudio", ctx.provider.id);
+ try std.testing.expectEqualStrings("local/thing", ctx.provider.model);
+ // It is a COPY: scribbling on the caller's buffer must not move the seat.
+ @memcpy(name, "scribbled!!");
+ try std.testing.expectEqualStrings("local/thing", ctx.provider.model);
+ std.testing.allocator.free(ctx.provider.model);
+}
diff --git a/src/tui_launch.zig b/src/tui_launch.zig
index addb26af..bd86e9a1 100644
--- a/src/tui_launch.zig
+++ b/src/tui_launch.zig
@@ -8,6 +8,7 @@ const Allocator = std.mem.Allocator;
const args = @import("args.zig");
const agent_mod = @import("agent.zig");
const provider_mod = @import("provider.zig");
+const billing = @import("billing.zig");
const pricing = @import("pricing.zig");
const providers = @import("providers.zig");
const process_runner = @import("process_runner.zig");
@@ -94,12 +95,7 @@ pub fn run(
var convo = repl_glue.Conversation.init(gpa);
defer convo.deinit();
repl_ctx.convo = &convo;
- var models_buf = std.array_list.Managed(u8).init(arena);
- for (pricing.models()) |mi| {
- if (mi.name.len == 0) continue;
- if (models_buf.items.len != 0) models_buf.appendSlice(", ") catch {};
- models_buf.appendSlice(mi.name) catch {};
- }
+ const entries = modelEntries(arena, keys.*);
engine_sink.hosted_frontend = true;
defer engine_sink.hosted_frontend = false;
obs.ensureSession();
@@ -109,7 +105,8 @@ pub fn run(
.model_fn = modelCb,
.cancel_fn = cancelCb,
.model_name = root.provider.model,
- .models = models_buf.items,
+ .model_provider = root.provider.id,
+ .model_entries = entries,
.cwd = cwd,
.yolo = yolo,
.hud_fn = hudCb,
@@ -211,10 +208,39 @@ fn turnCb(
return result;
}
-fn modelCb(ctx: ?*anyopaque, gpa: Allocator, name: []const u8) ?[]const u8 {
- const nm = repl_glue.replModelCb(ctx, gpa, name);
- if (nm) |n| obs.modelSwitch(n);
- return nm;
+/// The catalog the picker draws, with the provider column the TUI used to be
+/// blind to. Rows for providers with no credential are KEPT — the catalog is
+/// the map of what exists — and marked so the picker can dim them.
+///
+/// The cost class is classified HERE, on the src side, because it is a fact
+/// about credentials (src/billing.zig owns the rule); the TUI is handed the
+/// answer. The two enums are mapped by hand so a new class on either side is a
+/// compile error rather than a badge that quietly means nothing.
+pub fn modelEntries(arena: Allocator, keys: provider_mod.Keys) []const tui.ModelEntry {
+ var out = std.array_list.Managed(tui.ModelEntry).init(arena);
+ for (pricing.models()) |mi| {
+ if (mi.name.len == 0) continue;
+ out.append(.{
+ .name = mi.name,
+ .provider = mi.provider,
+ .has_key = keys.get(mi.provider) != null,
+ .cost = switch (billing.costFor(mi.provider, keys.source(mi.provider))) {
+ .plan => .plan,
+ .credits => .credits,
+ .api => .api,
+ .local => .local,
+ },
+ }) catch break;
+ }
+ return out.items;
+}
+
+/// A picker row names its provider; a typed `/model <name>` does not and is
+/// routed by name, exactly as before.
+fn modelCb(ctx: ?*anyopaque, gpa: Allocator, provider: []const u8, name: []const u8) ?tui.Picked {
+ const picked = repl_glue.replModelPick(ctx, gpa, provider, name) orelse return null;
+ obs.modelSwitch(picked.model);
+ return .{ .model = picked.model, .provider = picked.provider };
}
fn compactCb(ctx: ?*anyopaque, gpa: Allocator, history: []const tui.Turn, out: *tui.CompactOut) bool {
@@ -416,3 +442,57 @@ test "liveStream publishes len as appendBytes arrive" {
rstream.appendBytes("✓ bash\n");
try std.testing.expect(std.mem.endsWith(u8, tstream.buf[0..tstream.len.load(.acquire)], "✓ bash\n"));
}
+
+test "modelEntries carries the provider column the picker was blind to" {
+ var keys: provider_mod.Keys = .{ .values = @splat(null) };
+ _ = keys.set("codex", "tok", .login);
+ _ = keys.set("openai", "sk-test", .environment);
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const entries = modelEntries(arena_state.allocator(), keys);
+ try std.testing.expect(entries.len > 0);
+ try std.testing.expectEqual(pricing.models().len, entries.len);
+
+ var codex: ?tui.ModelEntry = null;
+ var openai: ?tui.ModelEntry = null;
+ var unkeyed: ?tui.ModelEntry = null;
+ for (entries) |e| {
+ try std.testing.expect(e.provider.len > 0);
+ if (codex == null and std.mem.eql(u8, e.provider, "codex")) codex = e;
+ if (openai == null and std.mem.eql(u8, e.provider, "openai")) openai = e;
+ if (unkeyed == null and std.mem.eql(u8, e.provider, "anthropic")) unkeyed = e;
+ }
+ // The three classes from the report: a plan seat, a metered seat, and a
+ // seat with no credential that stays on the list so the user can see it.
+ try std.testing.expectEqual(tui.CostClass.plan, codex.?.cost);
+ try std.testing.expect(codex.?.has_key);
+ try std.testing.expectEqual(tui.CostClass.api, openai.?.cost);
+ try std.testing.expect(openai.?.has_key);
+ try std.testing.expectEqual(tui.CostClass.api, unkeyed.?.cost);
+ try std.testing.expect(!unkeyed.?.has_key);
+}
+
+test "the same model under two providers is two distinguishable entries" {
+ // gpt-5.5 is served by codex, openai and codegraff. Before this the picker
+ // had three rows reading "gpt-5.5" and no way to tell them apart.
+ var keys: provider_mod.Keys = .{ .values = @splat(null) };
+ _ = keys.set("codex", "tok", .login);
+ _ = keys.set("codegraff", "cg", .login);
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ var seen: usize = 0;
+ var costs: [8]tui.CostClass = undefined;
+ for (modelEntries(arena_state.allocator(), keys)) |e| {
+ if (!std.mem.eql(u8, e.name, "gpt-5.5")) continue;
+ if (seen < costs.len) costs[seen] = e.cost;
+ seen += 1;
+ }
+ try std.testing.expect(seen >= 2);
+ var has_plan = false;
+ var has_credits = false;
+ for (costs[0..@min(seen, costs.len)]) |c| {
+ if (c == .plan) has_plan = true;
+ if (c == .credits) has_credits = true;
+ }
+ try std.testing.expect(has_plan and has_credits);
+}