Skip to content

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

Python

Fix the desktop model pill to follow the live ACP model

Rachef19e4e0496e
diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsx
index fe7bbcd5..515c481a 100644
--- a/apps/native/components/primitives/PromptBar.tsx
+++ b/apps/native/components/primitives/PromptBar.tsx
@@ -6,6 +6,7 @@ import ModelPicker from "./ModelPicker";
import layout from "./PromptBar.module.css";
import ModelEffortButtons from "./ModelEffortButtons";
import type { ModelChoice } from "@/lib/acp-client";
+import { resolveComposerModel } from "@/lib/composer-model";
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import ComposerMenu from "./ComposerMenu";
import ComposerAttachments from "./ComposerAttachments";
@@ -97,16 +98,12 @@ export default function PromptBar({
const [dismissed, setDismissed] = useState(false);
const [plusOpen, setPlusOpen] = useState(false);
const [modelOpen, setModelOpen] = useState(false);
- const [model, setModel] = useState<PromptModel>(
- () => catalog.find((m) => m.key === modelKey) ?? catalog[0] ?? MODELS[1],
- );
+ const [model, setModel] = useState<PromptModel>(() => resolveComposerModel(catalog, modelKey));
/* Live surfaces load their catalog async (graff/models); once it lands, or
* the owner re-points modelKey, the picked entry must follow — the initial
- * useState snapshot is stale by then. */
+ * useState snapshot is stale by then. Unknown keys keep their own name. */
useEffect(() => {
- if (!modelKey) return;
- const found = catalog.find((m) => m.key === modelKey);
- if (found && found !== model) setModel(found);
+ setModel(resolveComposerModel(catalog, modelKey));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [modelKey, models]);
const [dragging, setDragging] = useState(false);
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index 06bdbeb0..ef2aae72 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -17,6 +17,7 @@ import HarnessChrome from "./HarnessChrome";
import ChatSplitLayout from "./ChatSplitLayout";
import { sidebarRecents } from "./harness-sidebar";
import { newPageToken, newSessionName, type Chat, type Msg } from "./harness-types";
+import { liveComposerKey } from "@/lib/composer-model";
import { useBrowserVisibility } from "./useBrowserVisibility";
import { useReferenceNavigation } from "./useReferenceNavigation";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -206,12 +207,7 @@ export default function GraffHarness() {
* `--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))
- // 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" })));
};
@@ -469,7 +465,7 @@ export default function GraffHarness() {
chatsRef.current = next; setChats(next);
}}
prompt={{ demo: false, models, commands: commands[thread.id] ?? catalogCommands,
- root: cwdOf(thread), modelKey: thread.model ?? model ?? undefined,
+ root: cwdOf(thread), modelKey: liveComposerKey(thread.model, model, sessionsRef.current.has(thread.id)),
onModelChange: key => changeModel(key, thread.id), onSend: text => void send(text, thread.id),
onSetting: text => settings.change(thread.id, text),
onSteerQueued: () => steerOrInterrupt(queuesRef.current[thread.id]?.[0], runningRef.current.has(thread.id), id => steerQueued(thread.id, id), () => {
diff --git a/apps/native/components/site/useHarnessSessions.ts b/apps/native/components/site/useHarnessSessions.ts
index 4092d557..e5713329 100644
--- a/apps/native/components/site/useHarnessSessions.ts
+++ b/apps/native/components/site/useHarnessSessions.ts
@@ -34,17 +34,14 @@ export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, work
});
};
const adoptCatalog = async (chatId: number) => {
- // Use the provider and model actually resolved by graff.
- try {
- const { models: live, current, commands: available } = await fetchModels(sessionsRef.current.has(chatId) ? handleOf(chatId) : undefined, activePathRef.current ?? undefined);
- if (live.length > 0) setModels(live);
- if (available?.length) { setCatalogCommands(available); setCommands(old => ({ ...old, [chatId]: available })); }
- if (current) {
- setChatModel(chatId, current);
- setModelKey((fallback) => fallback ?? current);
- }
- } catch {
- // Do not invent a selected model when the catalog is unavailable.
+ // Pill follows this chat's agent. A transient /api/models process is not that agent.
+ const handle = sessionsRef.current.has(chatId) ? handleOf(chatId) : undefined;
+ const { models: live, current, commands: available } = await fetchModels(handle, activePathRef.current ?? undefined);
+ if (live.length > 0) setModels(live);
+ if (available?.length) { setCatalogCommands(available); setCommands(old => ({ ...old, [chatId]: available })); }
+ if (current && handle) {
+ setChatModel(chatId, current);
+ setModelKey(current);
}
};
@@ -94,6 +91,10 @@ export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, work
// Populate the command menu from this agent's advertisement.
if (commands.length > 0) setCommands((current) => ({ ...current, [chatId]: commands }));
setHealth({ ok: true });
+ if (spawnModel) {
+ setChatModel(chatId, spawnModel);
+ setModelKey(spawnModel);
+ }
await adoptCatalog(chatId);
return id;
};
diff --git a/apps/native/lib/composer-model.test.ts b/apps/native/lib/composer-model.test.ts
new file mode 100644
index 00000000..30b0cac7
--- /dev/null
+++ b/apps/native/lib/composer-model.test.ts
@@ -0,0 +1,86 @@
+import { test, expect } from "bun:test";
+import { spawn } from "node:child_process";
+import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { modelChoices } from "./acp-client";
+import { liveComposerKey, pillFromAcp, resolveComposerModel } from "./composer-model";
+
+test("the pill keeps an unknown live key instead of catalog[0]", () => {
+ const decoy = { key: "catalog-zero", name: "catalog-zero" };
+ const pill = resolveComposerModel([decoy], "running-live");
+ expect(pill.key).toBe("running-live");
+ expect(pill.name).toBe("running-live");
+});
+
+test("a tab with an agent does not inherit another chat's global pick", () => {
+ expect(liveComposerKey(undefined, "catalog-zero", true)).toBeUndefined();
+ expect(liveComposerKey("running-live", "catalog-zero", true)).toBe("running-live");
+ expect(liveComposerKey(undefined, "catalog-zero", false)).toBe("catalog-zero");
+});
+
+function askAcpModels(binary: string, model: string): Promise<unknown> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(binary, ["acp", "--model", model], { stdio: ["pipe", "pipe", "ignore"] });
+ let output = "";
+ let settled = false;
+ const finish = (error?: Error, value?: unknown) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ child.stdin.end();
+ if (child.exitCode === null) child.kill("SIGTERM");
+ if (error) reject(error);
+ else resolve(value);
+ };
+ const timer = setTimeout(() => finish(new Error("ACP graff/models timed out")), 3500);
+ child.once("error", (error) => finish(error));
+ child.once("exit", () => finish(new Error("ACP exited before graff/models")));
+ child.stdout.on("data", (chunk) => {
+ output += chunk.toString();
+ let newline;
+ while ((newline = output.indexOf("\n")) >= 0) {
+ const line = output.slice(0, newline);
+ output = output.slice(newline + 1);
+ try {
+ const reply = JSON.parse(line);
+ if (reply.id === 2) finish(reply.error ? new Error(reply.error.message ?? "graff/models failed") : undefined, reply.result);
+ } catch { /* ACP diagnostics are not results. */ }
+ }
+ });
+ child.stdin.on("error", (error) => finish(error));
+ child.stdin.write('{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1}}\n{"jsonrpc":"2.0","id":2,"method":"graff/models"}\n');
+ });
+}
+
+test("the composer pill matches graff/models current from the ACP worker", async () => {
+ const temp = mkdtempSync(path.join(os.tmpdir(), "graff-acp-pill-"));
+ const binary = path.join(temp, "agent.cjs");
+ writeFileSync(binary, `#!/usr/bin/env node
+const readline = require('node:readline');
+const args = process.argv.slice(2);
+const model = args.includes('--model') ? args[args.indexOf('--model') + 1] : 'catalog-zero';
+const send = value => console.log(JSON.stringify(value));
+readline.createInterface({input:process.stdin}).on('line', line => {
+ const req = JSON.parse(line);
+ if (req.method === 'initialize') send({id:req.id,result:{}});
+ if (req.method === 'graff/models') send({id:req.id,result:{
+ models: [
+ {name:'catalog-zero',provider:'plan',authenticated:true,context:1,cost:'plan',current:false},
+ {name:model,provider:'local',authenticated:false,context:1,cost:'local',current:true}
+ ],
+ current: {model, provider:'local'}
+ }});
+}).on('close', () => process.exit(0));
+`, { mode: 0o700 });
+ try {
+ const result = await askAcpModels(binary, "running-live");
+ const { models, current } = modelChoices(result as Parameters<typeof modelChoices>[0]);
+ expect(current).toBe("running-live");
+ const pill = pillFromAcp(models, current, "catalog-zero", true);
+ expect(pill.key).toBe(current);
+ expect(pill.key).not.toBe("catalog-zero");
+ } finally {
+ rmSync(temp, { recursive: true, force: true });
+ }
+});
diff --git a/apps/native/lib/composer-model.ts b/apps/native/lib/composer-model.ts
new file mode 100644
index 00000000..b83bc2e7
--- /dev/null
+++ b/apps/native/lib/composer-model.ts
@@ -0,0 +1,28 @@
+import type { ModelChoice } from "./acp-client";
+
+/** Label the composer pill. A live key is never replaced by catalog[0]. */
+export function resolveComposerModel(catalog: ModelChoice[], modelKey?: string | null): ModelChoice {
+ if (modelKey) return catalog.find((m) => m.key === modelKey) ?? { key: modelKey, name: modelKey };
+ return catalog[0] ?? { key: "", name: "Loading graff models…" };
+}
+
+/** Display key: this chat's ACP model. Global inherit is only for a tab with no agent yet. */
+export function liveComposerKey(
+ threadModel: string | undefined,
+ globalModel: string | null | undefined,
+ hasAgent: boolean,
+): string | undefined {
+ if (threadModel) return threadModel;
+ if (hasAgent) return undefined;
+ return globalModel ?? undefined;
+}
+
+/** Pill after a `graff/models` reply. `current` is the agent; the catalog only prettifies it. */
+export function pillFromAcp(
+ models: ModelChoice[],
+ current: string | null,
+ globalKey?: string | null,
+ hasAgent = true,
+): ModelChoice {
+ return resolveComposerModel(models, liveComposerKey(current ?? undefined, globalKey, hasAgent));
+}