Skip to content

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

Python

Fix: an explicit --model no longer loses to a resumed session's saved model

justrach2a29d29d6e32
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index 98cb519f..ab9f9a5d 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -25,6 +25,7 @@ import SidebarNav from "@/components/primitives/SidebarNav";
import { type BrowserPin } from "@/lib/browser/annotations";
import { browserClose } from "@/lib/browser-client";
import ChatColumn from "./ChatColumn";
+import ModelSwitchDialog from "@/components/site/ModelSwitchDialog";
import {
AgentsPane, AppSettings, BrowserPane, ChangesPane, ConversationsPane, FilesPane,
ProjectsPane, ReviewsPane, TasksSidebar, TerminalPane, WorkspaceDialog,
@@ -141,6 +142,8 @@ export default function GraffHarness() {
const [, setFollowing] = useState(true);
const { queuesRef, queues, queueIdRef, setQueue, steerer, steerStatus, remove: removeQueued, edit: editQueued, beginEdit, cancelEdit, changeEdit, take: takeQueuedPrompt } = usePromptQueue();
const [cancelError, setCancelError] = useState<Record<number, string>>({});
+ // A model pick awaiting confirmation: switching respawns the tab's agent.
+ const [pendingModel, setPendingModel] = useState<{ key: string; chatId: number } | null>(null);
const runningRef = useRef(new Set<number>());
const queueResumesRef = useRef(new Set<number>());
// Closed tabs, oldest first, for the reopen shortcut.
@@ -199,17 +202,30 @@ export default function GraffHarness() {
openChanges();
}, [filesOpen, fileRequest, openChanges]);
- const changeModel = (key: string, forChat?: number) => {
- // New tabs inherit the pick; the tab respawns its agent with it
- // (a fresh context — the agent cannot swap models mid-session).
- const chatId = forChat ?? chatThread.id;
+ /** Respawn this tab's agent on `key` and reload its conversation: the
+ * `--resume` target carries the history across, so the switch keeps the chat
+ * instead of starting it over. New tabs inherit the pick. */
+ const applyModel = (key: string, chatId: number) => {
setModelKey(key);
setChatModel(chatId, key);
void requireSession(chatId, true, key)
.then(() => adoptCatalog(chatId))
- .catch(() => undefined);
+ // A respawn that fails leaves the tab on its old model; say so rather
+ // than let the picker look like it silently did nothing.
+ .catch(error => setCancelError(current => ({ ...current, [chatId]: error instanceof Error ? error.message : "Could not switch model" })));
};
+ const changeModel = (key: string, forChat?: number) => {
+ const chatId = forChat ?? chatThread.id;
+ // A tab with a conversation (or a turn in flight) has state to reload, so
+ // confirm the restart first; an empty tab has nothing to carry over.
+ const chat = chatsRef.current.find(c => c.id === chatId);
+ if ((chat?.messages.length ?? 0) > 0 || runningRef.current.has(chatId)) setPendingModel({ key, chatId });
+ else applyModel(key, chatId);
+ };
+
+ const modelLabel = (key: string | null | undefined) => models.find(m => m.key === key)?.name ?? key ?? "the current model";
+
const runPrompt = createPromptRunner({ onStarted: started, onCompleted: completed,
runningRef, steerer, setFollowing, chatsRef, model, msgIdRef, setChats, setBusyFor, setHistory, pinsRef, handleOf, setPins, requireSession, adoptCatalog, refreshStored, takeQueuedPrompt, setCancelError
});
@@ -603,6 +619,14 @@ export default function GraffHarness() {
{terminalUsed && chatCwd && <TerminalPane key={chatCwd} cwd={chatCwd} visible={terminalVisible} onHide={() => setTerminalVisible(false)} />}
</div>
+ {pendingModel && (
+ <ModelSwitchDialog
+ from={modelLabel(chatsRef.current.find(c => c.id === pendingModel.chatId)?.model ?? model)}
+ to={modelLabel(pendingModel.key)}
+ onCancel={() => setPendingModel(null)}
+ onConfirm={() => { const picked = pendingModel; setPendingModel(null); applyModel(picked.key, picked.chatId); }}
+ />
+ )}
{dialog && (
<WorkspaceDialog
mode={dialog.mode}
diff --git a/apps/native/components/site/ModelSwitchDialog.tsx b/apps/native/components/site/ModelSwitchDialog.tsx
new file mode 100644
index 00000000..d6dd2dc2
--- /dev/null
+++ b/apps/native/components/site/ModelSwitchDialog.tsx
@@ -0,0 +1,128 @@
+"use client";
+
+import { useLayoutEffect, useRef } from "react";
+import { createPortal } from "react-dom";
+import { IconCrossSmall } from "@/lib/icons";
+
+/* ─────────────────────────────────────────────────────────
+ * MODEL SWITCH DIALOG
+ * The composer's picker cannot swap a model inside a live agent: it
+ * respawns `graff acp --model <new> --resume <session>`, so the tab goes
+ * quiet for a moment while the old worker is retired and the conversation
+ * is reloaded onto the new model. Anything the outgoing agent was still
+ * running — background jobs, subagents — stops with it. That is worth
+ * confirming once, instead of silently restarting the chat under the user.
+ * ───────────────────────────────────────────────────────── */
+
+const BUTTON = "h-8 shrink-0 rounded-full px-3 text-[12.5px] font-medium transition-colors";
+
+type Props = {
+ /** The model being left, as the composer showed it. */
+ from: string;
+ /** The model being switched to. */
+ to: string;
+ onCancel: () => void;
+ onConfirm: () => void;
+};
+
+export default function ModelSwitchDialog({ from, to, onCancel, onConfirm }: Props) {
+ const panel = useRef<HTMLDivElement>(null);
+ const confirm = useRef<HTMLButtonElement>(null);
+ const cancel = useRef(onCancel);
+ cancel.current = onCancel;
+
+ useLayoutEffect(() => {
+ const dialog = panel.current!;
+ const previous = document.activeElement as HTMLElement | null;
+ // The portal is a direct body child. Inert background roots keep native
+ // and programmatic focus out of the chat behind the modal.
+ const background = Array.from(document.body.children)
+ .filter((element): element is HTMLElement => element instanceof HTMLElement && !element.contains(dialog))
+ .map((element) => ({ element, inert: element.inert }));
+ background.forEach(({ element }) => { element.inert = true; });
+ const controls = () => Array.from(dialog.querySelectorAll<HTMLButtonElement>("button"))
+ .filter((element) => !element.disabled && element.getClientRects().length > 0);
+ confirm.current?.focus({ preventScroll: true });
+ const keepFocus = (event: FocusEvent) => {
+ if (!dialog.contains(event.target as Node)) (controls()[0] ?? dialog).focus({ preventScroll: true });
+ };
+ const onKey = (event: KeyboardEvent) => {
+ if (event.isComposing) return;
+ if (event.key === "Escape") {
+ event.preventDefault(); event.stopPropagation(); cancel.current();
+ return;
+ }
+ if (event.key !== "Tab") return;
+ const items = controls(), first = items[0], last = items.at(-1);
+ if (!first || !last) return;
+ if (!dialog.contains(document.activeElement) || (event.shiftKey ? document.activeElement === first : document.activeElement === last)) {
+ event.preventDefault();
+ (event.shiftKey ? last : first).focus({ preventScroll: true });
+ }
+ };
+ document.addEventListener("keydown", onKey);
+ document.addEventListener("focusin", keepFocus, true);
+ return () => {
+ document.removeEventListener("keydown", onKey);
+ document.removeEventListener("focusin", keepFocus, true);
+ background.forEach(({ element, inert }) => { element.inert = inert; });
+ if (previous?.isConnected) previous.focus({ preventScroll: true });
+ };
+ }, []);
+
+ return createPortal(
+ <div
+ className="fixed inset-0 z-[60] flex items-center justify-center p-4"
+ style={{ background: "color-mix(in oklab, var(--ink) 22%, transparent)", animation: "fade-in 160ms ease both" }}
+ onPointerDown={(event) => {
+ if (event.target === event.currentTarget) onCancel();
+ }}
+ >
+ <div
+ ref={panel}
+ role="dialog"
+ tabIndex={-1}
+ aria-modal="true"
+ aria-label={`Switch model to ${to}`}
+ className="flex w-full max-w-[440px] flex-col overflow-hidden rounded-window bg-surface shadow-overlay"
+ style={{ animation: "pop-in 180ms cubic-bezier(0.23,1,0.32,1) both" }}
+ >
+ <div className="flex h-11 shrink-0 items-center gap-2 border-b border-line px-4">
+ <span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-ink">Switch model</span>
+ <button
+ type="button"
+ aria-label="Close"
+ onClick={onCancel}
+ className="flex size-7 items-center justify-center rounded-[6px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"
+ >
+ <IconCrossSmall size={16} />
+ </button>
+ </div>
+
+ <div className="flex flex-col gap-2 px-4 py-4 text-[12.5px] leading-5 text-ink-2">
+ <p>
+ This chat restarts its agent on <span className="font-medium text-ink">{to}</span>
+ {from !== to && <> instead of <span className="font-medium text-ink">{from}</span></>}.
+ </p>
+ <p>The conversation is reloaded onto the new model, so its history carries over.</p>
+ <p className="text-ink-3">Anything the current agent is still running — background jobs, subagents — stops.</p>
+ </div>
+
+ <div className="flex shrink-0 items-center justify-end gap-2 border-t border-line px-4 py-3">
+ <button type="button" onClick={onCancel} className={`${BUTTON} text-ink-2 hover:bg-hover hover:text-ink`}>
+ Cancel
+ </button>
+ <button
+ ref={confirm}
+ type="button"
+ onClick={onConfirm}
+ className={`${BUTTON} bg-ink px-3.5 text-canvas hover:opacity-90`}
+ >
+ Switch model
+ </button>
+ </div>
+ </div>
+ </div>,
+ document.body,
+ );
+}
diff --git a/src/additional_tests.zig b/src/additional_tests.zig
index 5eb355ed..662a1cf5 100644
--- a/src/additional_tests.zig
+++ b/src/additional_tests.zig
@@ -8,6 +8,7 @@ test {
_ = @import("agent_request_body_responses.zig");
_ = @import("agent_server_compact_tests.zig");
_ = @import("provider_codegraff_tests.zig");
+ _ = @import("session_branch.zig");
}
test "oneshot -p still uses the live stall-watched transport" {
diff --git a/src/commands_resume.zig b/src/commands_resume.zig
index e08bab28..6bf6c459 100644
--- a/src/commands_resume.zig
+++ b/src/commands_resume.zig
@@ -62,7 +62,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
if (!picked.local and picked.workspace.len > 0) picked_remote = try arena.dupe(u8, picked.workspace);
}
- const resumed = session_branch.restore(root, keys, arena, source, parsed.branch) catch |err| return switch (err) {
+ const resumed = session_branch.restore(root, keys, arena, source, parsed.branch, null) catch |err| return switch (err) {
error.FileNotFound => reject(out, "no session named '{s}' ({s}{s} not found in cwd or ~/{s}) — /sessions lists saved ones\n", .{ source, source, session.session_ext, session.sessions_dir }),
error.InvalidSessionName => reject(out, "resume failed: invalid source or branch name\n", .{}),
error.BranchMatchesSource => reject(out, "branch failed: destination must differ from source\n", .{}),
diff --git a/src/providers.zig b/src/providers.zig
index 31905ebc..220f13b7 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -73,7 +73,7 @@ fn translateHistory(arena: Allocator, msgs: *std.json.Array, to_kind: Provider.K
msgs.* = out;
}
-fn applyProviderInner(root: *Agent, arena: Allocator, p: Provider, persist: bool) ![]const u8 {
+pub fn applyProviderInner(root: *Agent, arena: Allocator, p: Provider, persist: bool) ![]const u8 {
const same_format = root.provider.kind == p.kind;
const same_selection = same_format and
root.provider.context == p.context and
diff --git a/src/session_branch.zig b/src/session_branch.zig
index c93044cc..23b2a1c1 100644
--- a/src/session_branch.zig
+++ b/src/session_branch.zig
@@ -6,6 +6,7 @@ const Allocator = std.mem.Allocator;
const agent_mod = @import("agent.zig");
const provider_mod = @import("provider.zig");
+const providers = @import("providers.zig");
const session = @import("session.zig");
const http_headers = @import("http_headers.zig");
const prompts = @import("prompts.zig");
@@ -37,7 +38,10 @@ pub fn parseSpec(raw: []const u8) ?Spec {
return .{ .source = source, .branch = branch };
}
-pub fn restore(root: *agent_mod.Agent, keys: *provider_mod.Keys, arena: Allocator, source_raw: []const u8, branch_raw: ?[]const u8) !Result {
+/// `model_override` is an explicit startup `--model`, already resolved to a
+/// provider by startup: see the block after loadSession for why it wins.
+/// `/resume` has no such flag and passes null.
+pub fn restore(root: *agent_mod.Agent, keys: *provider_mod.Keys, arena: Allocator, source_raw: []const u8, branch_raw: ?[]const u8, model_override: ?provider_mod.Provider) !Result {
const source = try arena.dupe(u8, source_raw);
if (!session.validSessionName(source)) return Error.InvalidSessionName;
const branch = if (branch_raw) |raw| try arena.dupe(u8, raw) else null;
@@ -59,6 +63,18 @@ pub fn restore(root: *agent_mod.Agent, keys: *provider_mod.Keys, arena: Allocato
root.ensureStoredKeys(keys);
try session.loadSession(root, keys, arena, source);
+ // An explicit --model outranks the model the session file carries: the flag
+ // is the user's live intent, the saved model is only what the conversation
+ // last ran on. Without this the restore silently reverted the flag, so a
+ // host that respawns to switch models (the desktop picker) came back up on
+ // the OLD model and the switch looked like a no-op. Same precedence the
+ // --goal flag gets below. `keep_context` still decides whether the restored
+ // conversation is translated or dropped across a wire-format change,
+ // exactly as a mid-session /model does.
+ if (model_override) |p| {
+ _ = providers.applyProviderInner(root, arena, p, false) catch {};
+ root.fallback_active = false; // an explicit choice, never a repaired credential
+ }
root.session_name = branch orelse source;
if (branch) |dest| {
root.session_parent = source;
@@ -73,3 +89,48 @@ pub fn restore(root: *agent_mod.Agent, keys: *provider_mod.Keys, arena: Allocato
}
return .{ .source = source, .target = root.session_name, .branched = branch != null };
}
+
+test "--model outranks the model a resumed session saved" {
+ const gpa = std.testing.allocator;
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ var keys: provider_mod.Keys = .{ .values = @splat("test-key") };
+
+ var root: agent_mod.Agent = .{
+ .gpa = gpa,
+ .arena = arena,
+ .io = io,
+ .client = &client,
+ .provider = try keys.providerById("anthropic", "sonnet"),
+ .messages = (try std.json.parseFromSliceLeaky(std.json.Value, arena, "[{\"role\":\"user\",\"content\":\"switch me\"}]", .{})).array,
+ .subagent_provider_explicit = true,
+ .sub = false,
+ .label = "root",
+ .out = null,
+ .home = try std.fmt.allocPrint(arena, ".zig-cache/tmp/{s}", .{tmp.sub_path}),
+ };
+ try session.saveSessionTo(&root, arena, tmp.dir, "switch-1");
+ session.flushSaves();
+
+ // What the desktop picker does: respawn this conversation onto another
+ // model with `--model <new> --resume <session>`. Before the fix the session
+ // file's own model won, so the worker came back on the old one.
+ const deepseek = try keys.providerById("deepseek", "deepseek-chat");
+ const resumed = try restore(&root, &keys, arena, "switch-1", null, deepseek);
+ try std.testing.expectEqualStrings("switch-1", resumed.target);
+ try std.testing.expectEqualStrings("deepseek", root.provider.id);
+ try std.testing.expectEqualStrings("deepseek-chat", root.provider.model);
+ try std.testing.expectEqual(@as(usize, 1), root.messages.items.len); // the conversation rides along
+ try std.testing.expect(!root.fallback_active); // an explicit choice, not failover
+
+ // No flag: the saved model still wins, exactly as before.
+ _ = try restore(&root, &keys, arena, "switch-1", null, null);
+ try std.testing.expectEqualStrings("anthropic", root.provider.id);
+ try std.testing.expectEqualStrings("sonnet", root.provider.model);
+}
diff --git a/src/session_run.zig b/src/session_run.zig
index a5070d83..9cf690f1 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -411,7 +411,7 @@ pub fn saveOrResumeSession(root: *agent_mod.Agent, keys: *provider_mod.Keys, are
if (!will_resume) session.saveSession(root, arena, root.session_name) catch {};
if (flags.oneshot_prompt != null and will_resume) {
const source = flags.resume_flag.?;
- _ = session_branch.restore(root, keys, arena, source, flags.branch_flag) catch |err| std.process.fatal("cannot resume/branch from '{s}': {t}", .{ source, err });
+ _ = session_branch.restore(root, keys, arena, source, flags.branch_flag, if (flags.model_flag != null) root.provider else null) catch |err| std.process.fatal("cannot resume/branch from '{s}': {t}", .{ source, err });
}
}
@@ -424,7 +424,7 @@ pub fn saveOrResumeSession(root: *agent_mod.Agent, keys: *provider_mod.Keys, are
pub fn restoreResumedSession(arena: Allocator, out: *Io.Writer, root: *agent_mod.Agent, keys: *provider_mod.Keys, flags: args.Flags, json_mode: bool, cwd_display: []const u8) !void {
if (!(flags.oneshot_prompt == null and flags.resume_flag != null and !flags.new_session_flag and !flags.no_resume_flag)) return;
const source = flags.resume_flag.?;
- if (session_branch.restore(root, keys, arena, source, flags.branch_flag)) |_| {
+ if (session_branch.restore(root, keys, arena, source, flags.branch_flag, if (flags.model_flag != null) root.provider else null)) |_| {
if (root.messages.items.len > 0) {
if (!json_mode) {
// Prefer the saved AI summary; fall back to the first user
diff --git a/src/tui_session.zig b/src/tui_session.zig
index 4775db1f..cc53885e 100644
--- a/src/tui_session.zig
+++ b/src/tui_session.zig
@@ -77,7 +77,7 @@ pub fn resumeCb(ctx_ptr: ?*anyopaque, gpa: Allocator, raw: []const u8, out: *tui
syncRoot(convo, root) catch |err| return failure(gpa, out, err);
session.saveSession(root, root.arena, root.session_name) catch |err| return failure(gpa, out, err);
}
- const resumed = session_branch.restore(root, &ctx.keys, root.arena, spec.source, spec.branch) catch |err| return failure(gpa, out, err);
+ const resumed = session_branch.restore(root, &ctx.keys, root.arena, spec.source, spec.branch, null) catch |err| return failure(gpa, out, err);
if (ctx.convo) |convo| seed(convo, root) catch |err| return failure(gpa, out, err);
ctx.provider = root.provider;
ctx.last_context_tokens = root.last_context_tokens;