Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6961 feat(agent): discover Claude Code's model catalog from the CLI (#7917)
Bohan Jianga075e58b8089
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 419f243617..f5b7901d9d 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -1588,6 +1588,48 @@ describe("RuntimeModelListRequestSchema", () => {expect(parsed.cached).toBeUndefined();});+ // MUL-6961: models the runtime cannot run arrive in their OWN list. The+ // separation is the compatibility contract — a client that never learned the+ // field reads `models` and therefore cannot offer one — so the schema must+ // keep them apart rather than folding them together.+ it("parses unavailable models without letting them into the selectable list", () => {+ const parsed = parseWithFallback(+ {+ ...completed,+ unavailable_models: [+ {+ id: "cc-update-required-1",+ label: "Fable 5.1 (disabled)",+ reason: "Update to 2.1.255+ to use Fable 5.1",+ },+ ],+ },+ RuntimeModelListRequestSchema,+ MALFORMED_RUNTIME_MODEL_LIST_REQUEST,+ { endpoint: "test" },+ );+ expect(parsed.unavailable_models?.[0]?.id).toBe("cc-update-required-1");+ expect(parsed.unavailable_models?.[0]?.reason).toBe(+ "Update to 2.1.255+ to use Fable 5.1",+ );+ expect(parsed.models?.map((m) => m.id)).not.toContain(+ "cc-update-required-1",+ );+ });++ // An older daemon or server sends no such key. The picker then shows no+ // unavailable section, which is exactly the pre-MUL-6961 behaviour.+ it("tolerates a backend that omits unavailable models entirely", () => {+ const parsed = parseWithFallback(+ completed,+ RuntimeModelListRequestSchema,+ MALFORMED_RUNTIME_MODEL_LIST_REQUEST,+ { endpoint: "test" },+ );+ expect(parsed.unavailable_models).toBeUndefined();+ expect(parsed.models?.length).toBe(1);+ });+it("treats an older daemon that omits explicit-standard support as unsupported", () => {const model = completed.models[0]!;const {diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex a984734867..d0662a8d99 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2945,11 +2945,24 @@ const RuntimeModelSchema = z.object({supports_explicit_standard_service_tier: z.boolean().optional(),}).loose();+// A row the runtime named but will not run (MUL-6961). Parsed from its own+// top-level list, never from `models`, so nothing here can become a selectable+// value. `id` is required for the same reason it is on RuntimeModelSchema — a+// row without one cannot even be keyed in a list.+const RuntimeUnavailableModelSchema = z.object({+ id: z.string(),+ label: z.string().default(""),+ reason: z.string().optional(),+}).loose();+export const RuntimeModelListRequestSchema = z.object({id: z.string().default(""),runtime_id: z.string().default(""),status: z.string(),models: z.array(RuntimeModelSchema).optional(),+ // Absent on any daemon or server older than the field, which simply means+ // the picker shows no unavailable section.+ unavailable_models: z.array(RuntimeUnavailableModelSchema).optional(),supported: z.boolean().default(true),error: z.string().optional(),created_at: z.string().default(""),diff --git a/packages/core/runtimes/models.test.ts b/packages/core/runtimes/models.test.tsindex 9f56f14a26..6c4766c5cd 100644--- a/packages/core/runtimes/models.test.ts+++ b/packages/core/runtimes/models.test.ts@@ -67,6 +67,7 @@ describe("resolveRuntimeModels", () => {expect(result).toEqual({models: catalog,+ unavailableModels: [],supported: true,cached: true,cachedAt: "2026-07-29T00:00:00Z",@@ -74,6 +75,48 @@ describe("resolveRuntimeModels", () => {expect(getListModelsResult).not.toHaveBeenCalled();});+ // MUL-6961. This is the single guarantee three separate consumers depend on+ // — the create dropdown, the inspector picker, and the agent builder all read+ // `models` and would each have to be taught otherwise. Models the runtime+ // cannot run stay out of it, so none of them can offer one, and so can no+ // already-installed client that never heard of the second list.+ it("keeps unavailable models out of the selectable list", async () => {+ const unavailable = [+ {+ id: "cc-update-required-1",+ label: "Fable 5.1 (disabled)",+ reason: "Update to 2.1.255+ to use Fable 5.1",+ },+ ];+ initiateListModels.mockResolvedValue(+ request({+ status: "completed",+ models: catalog,+ unavailable_models: unavailable,+ }),+ );++ const result = await resolveRuntimeModels("rt-1");++ expect(result.models).toEqual(catalog);+ expect(result.models.map((m) => m.id)).not.toContain(+ "cc-update-required-1",+ );+ expect(result.unavailableModels).toEqual(unavailable);+ });++ // A daemon or server older than the field sends no key at all. That must read+ // as "nothing to warn about", never as a missing list the UI trips over.+ it("defaults unavailable models to empty when the backend omits them", async () => {+ initiateListModels.mockResolvedValue(+ request({ status: "completed", models: catalog }),+ );++ const result = await resolveRuntimeModels("rt-1");++ expect(result.unavailableModels).toEqual([]);+ });+it("marks a live discovery as not cached", async () => {initiateListModels.mockResolvedValue(request({ status: "completed", models: catalog }),@@ -209,14 +252,14 @@ describe("staleTimeFor", () => {// observable staleness would be server window + client window. Zero keeps the// bound at the server's window alone.it("treats a cached answer as immediately revalidatable", () => {- expect(staleTimeFor({ models: catalog, supported: true, cached: true })).toBe(0);+ expect(staleTimeFor({ models: catalog, unavailableModels: [], supported: true, cached: true })).toBe(0);});it("trusts a live answer for the full window", () => {- expect(staleTimeFor({ models: catalog, supported: true, cached: false })).toBe(+ expect(staleTimeFor({ models: catalog, unavailableModels: [], supported: true, cached: false })).toBe(LIVE_MODELS_STALE_TIME_MS,);- expect(staleTimeFor({ models: catalog, supported: true })).toBe(+ expect(staleTimeFor({ models: catalog, unavailableModels: [], supported: true })).toBe(LIVE_MODELS_STALE_TIME_MS,);});diff --git a/packages/core/runtimes/models.ts b/packages/core/runtimes/models.tsindex 4c166f2d3c..5c67b61ae3 100644--- a/packages/core/runtimes/models.ts+++ b/packages/core/runtimes/models.ts@@ -91,6 +91,7 @@ export async function resolveRuntimeModels(}return {models: current.models ?? [],+ unavailableModels: current.unavailable_models ?? [],supported: current.supported !== false,cached: current.cached === true,cachedAt: current.cached_at,diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 5aabb70c9e..b77e4deb62 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -1111,6 +1111,22 @@ export interface RuntimeModel {supports_explicit_standard_service_tier?: boolean;}+/**+ * A model the runtime named but will not run on that host — today only Claude+ * Code, reporting one that needs a newer CLI than the installed one.+ *+ * These arrive in their own list and never inside `models`, which is what keeps+ * an older client from offering one: it reads `models`, and they are not there.+ * The picker shows them greyed out with `reason` so the gap reads as "your CLI+ * is behind" rather than "Multica does not support this model" (MUL-6961).+ */+export interface RuntimeUnavailableModel {+ id: string;+ label: string;+ /** The runtime's own remedy, e.g. "Update to 2.1.255+ to use Fable 5.1". */+ reason?: string;+}+export interface RuntimeModelServiceTier {/** Catalog ID sent to the provider protocol unchanged. */id: string;@@ -1153,6 +1169,8 @@ export interface RuntimeModelListRequest {runtime_id: string;status: RuntimeModelListStatus;models?: RuntimeModel[];+ /** Advisory rows the runtime cannot run; never selectable. */+ unavailable_models?: RuntimeUnavailableModel[];supported: boolean;error?: string;created_at: string;@@ -1173,6 +1191,13 @@ export interface RuntimeModelListRequest {// from "provider does not honour per-agent model selection".export interface RuntimeModelsResult {models: RuntimeModel[];+ /**+ * Rows the runtime named but cannot run. Kept out of `models` on purpose —+ * see RuntimeUnavailableModel. Optional like `cached` beside it: the resolver+ * always sets it, but a backend older than the field contributes nothing, so+ * consumers read it defensively.+ */+ unavailableModels?: RuntimeUnavailableModel[];supported: boolean;/*** True when the server answered from its catalog cache rather than a livediff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 97e68f5720..0d2213e2a9 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -67,6 +67,7 @@ export type {RuntimeModel,RuntimeModelServiceTier,RuntimeModelThinking,+ RuntimeUnavailableModel,RuntimeModelThinkingLevel,RuntimeModelListRequest,RuntimeModelListStatus,diff --git a/packages/views/agents/components/inspector/model-capability.test.ts b/packages/views/agents/components/inspector/model-capability.test.tsindex 6628765ceb..73efccf6f8 100644--- a/packages/views/agents/components/inspector/model-capability.test.ts+++ b/packages/views/agents/components/inspector/model-capability.test.ts@@ -42,4 +42,26 @@ describe("model capability lookup", () => {),).toBeUndefined();});++ // MUL-6961: discovery reports what the CLI actually runs, so a catalog id can+ // now carry the tag itself. Both sides need normalizing — matching only the+ // query side would hide the effort picker for the model the user just picked.+ it("matches a tagged catalog entry from either spelling", () => {+ const TAGGED: RuntimeModel[] = [+ { id: "claude-opus-5[1m]", label: "Opus (1M context)", provider: "anthropic" },+ { id: "claude-sonnet-5", label: "Sonnet", provider: "anthropic" },+ ];+ expect(+ findModelCapabilityEntry(TAGGED, "claude-opus-5[1m]", "claude")?.id,+ ).toBe("claude-opus-5[1m]");+ // An agent pinned before discovery landed stores the untagged id, and must+ // still resolve to the tagged entry rather than losing its picker.+ expect(+ findModelCapabilityEntry(TAGGED, "claude-opus-5", "claude")?.id,+ ).toBe("claude-opus-5[1m]");+ // Untagged entries keep matching exactly.+ expect(+ findModelCapabilityEntry(TAGGED, "claude-sonnet-5", "claude")?.id,+ ).toBe("claude-sonnet-5");+ });});diff --git a/packages/views/agents/components/inspector/model-capability.ts b/packages/views/agents/components/inspector/model-capability.tsindex 84b12175b5..ce73f1f656 100644--- a/packages/views/agents/components/inspector/model-capability.ts+++ b/packages/views/agents/components/inspector/model-capability.ts@@ -26,5 +26,13 @@ export function findModelCapabilityEntry(): RuntimeModel | undefined {if (!model) return undefined;const lookupId = modelIdForCapabilityLookup(provider, model);- return models.find((entry) => entry.id === lookupId);+ // Normalize the catalog side too. Claude discovery reports what the CLI+ // would really run, tag included (`claude-opus-5[1m]`), so comparing a+ // stripped query against raw catalog ids would miss the entry for the very+ // model the user just picked — and hiding a model's own effort picker is how+ // that failure would show up (MUL-6961). Mirrors the daemon's lookup in+ // ValidateThinkingLevelWith.+ return models.find(+ (entry) => modelIdForCapabilityLookup(provider, entry.id) === lookupId,+ );}diff --git a/packages/views/agents/components/inspector/model-picker.test.tsx b/packages/views/agents/components/inspector/model-picker.test.tsxnew file mode 100644index 0000000000..4e9e886326--- /dev/null+++ b/packages/views/agents/components/inspector/model-picker.test.tsx@@ -0,0 +1,116 @@+// @vitest-environment jsdom++import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { render, screen, fireEvent, cleanup } from "@testing-library/react";+import { I18nProvider } from "@multica/core/i18n/react";+import type { RuntimeModelsResult } from "@multica/core/types";+import { afterEach, describe, expect, it, vi } from "vitest";+import enAgents from "../../../locales/en/agents.json";+import enCommon from "../../../locales/en/common.json";+import enIssues from "../../../locales/en/issues.json";+import { ModelPicker } from "./model-picker";++const TEST_RESOURCES = {+ en: { common: enCommon, agents: enAgents, issues: enIssues },+};++// MUL-6961. The create-agent dropdown and this inspector picker are two+// separate renderers over one catalog, and the first attempt at unavailable+// models only taught the dropdown about them — leaving the inspector, which is+// where an ALREADY configured agent gets edited, still offering a model whose+// every run 400s. That asymmetry is what this file exists to prevent.+const CLAUDE_CATALOG: RuntimeModelsResult = {+ models: [{ id: "claude-fable-5", label: "Fable", provider: "anthropic" }],+ unavailableModels: [+ {+ id: "cc-update-required-1",+ label: "Fable 5.1 (disabled)",+ reason: "Update to 2.1.255+ to use Fable 5.1",+ },+ ],+ supported: true,+};++let discovery: () => Promise<RuntimeModelsResult> = async () => CLAUDE_CATALOG;+let discoveryKey = 0;++vi.mock("@multica/core/runtimes", () => ({+ runtimeModelsOptions: (runtimeId: string | null) => ({+ enabled: Boolean(runtimeId),+ queryKey: ["runtime-models", runtimeId, discoveryKey],+ queryFn: () => discovery(),+ }),+}));++function renderPicker() {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const onChange = vi.fn(async () => {});+ const view = render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <QueryClientProvider client={queryClient}>+ <ModelPicker+ runtimeId="rt-claude"+ runtimeOnline+ value=""+ onChange={onChange}+ />+ </QueryClientProvider>+ </I18nProvider>,+ );+ return { ...view, onChange };+}++function openPicker(container: HTMLElement) {+ const trigger = container.querySelector<HTMLButtonElement>("button");+ if (!trigger) throw new Error("model picker trigger not rendered");+ fireEvent.click(trigger);+}++describe("ModelPicker (inspector)", () => {+ afterEach(() => {+ cleanup();+ discovery = async () => CLAUDE_CATALOG;+ discoveryKey += 1;+ });++ it("offers the runnable model", async () => {+ const { container, onChange } = renderPicker();+ openPicker(container);++ fireEvent.click(await screen.findByText("Fable"));+ expect(onChange).toHaveBeenCalledWith("claude-fable-5");+ });++ it("shows an unavailable model with its reason and no way to select it", async () => {+ const { container, onChange } = renderPicker();+ openPicker(container);++ const row = await screen.findByText("Fable 5.1 (disabled)");+ expect(+ screen.getByText("Update to 2.1.255+ to use Fable 5.1"),+ ).toBeTruthy();++ fireEvent.click(row);+ expect(onChange).not.toHaveBeenCalled();+ expect(row.closest("button")).toBeNull();+ });++ // A backend older than the field sends nothing, and the picker must simply+ // not render the section rather than break or show an empty heading.+ it("renders no unavailable section when the backend omits the field", async () => {+ discovery = async () => ({+ models: [{ id: "claude-fable-5", label: "Fable", provider: "anthropic" }],+ supported: true,+ });++ const { container } = renderPicker();+ openPicker(container);++ await screen.findByText("Fable");+ expect(+ screen.queryByText(enAgents.pickers.model_unavailable_heading),+ ).toBeNull();+ });+});diff --git a/packages/views/agents/components/inspector/model-picker.tsx b/packages/views/agents/components/inspector/model-picker.tsxindex 6dc8706910..4a267e1be8 100644--- a/packages/views/agents/components/inspector/model-picker.tsx+++ b/packages/views/agents/components/inspector/model-picker.tsx@@ -12,6 +12,7 @@ import {} from "../../../issues/components/pickers";import { CHIP_CLASS } from "./chip";import { useT } from "../../../i18n";+import { UnavailableModelsNote } from "../unavailable-models-note";/*** Inline model picker for the agent inspector. Lighter cousin of@@ -55,6 +56,11 @@ export function ModelPicker({// Memoise the model list so every downstream useMemo gets a stable// reference; `?? []` would mint a fresh array on every render and// invalidate filters needlessly.+ // Advisory only — never merged into `models`, so no row below can select one.+ const unavailableModels = useMemo(+ () => modelsQuery.data?.unavailableModels ?? [],+ [modelsQuery.data],+ );const models = useMemo(() => modelsQuery.data?.models ?? [],[modelsQuery.data],@@ -244,6 +250,13 @@ export function ModelPicker({</p>)}+ {!modelsQuery.isLoading && (+ <UnavailableModelsNote+ models={unavailableModels}+ title={t(($) => $.pickers.model_unavailable_heading)}+ />+ )}+{canCreate && (<PickerItemselected={false}diff --git a/packages/views/agents/components/model-dropdown.test.tsx b/packages/views/agents/components/model-dropdown.test.tsxindex 82532f6616..6d426ebaae 100644--- a/packages/views/agents/components/model-dropdown.test.tsx+++ b/packages/views/agents/components/model-dropdown.test.tsx@@ -136,4 +136,63 @@ describe("ModelDropdown", () => {fireEvent.click(await screen.findByText(/vertex\/gemini-3\.1-pro/));expect(onChange).toHaveBeenCalledWith("vertex/gemini-3.1-pro");});++ // MUL-6961: Claude Code reports a model its own version cannot run in a+ // separate list. It must be visible — a missing row reads as "Multica doesn't+ // support Fable 5.1" when the truth is the user's CLI is behind — and it must+ // be impossible to pick, because picking one is a guaranteed 400.+ describe("models the runtime cannot run", () => {+ const WITH_UNAVAILABLE: RuntimeModelsResult = {+ models: [{ id: "claude-fable-5", label: "Fable", provider: "anthropic" }],+ unavailableModels: [+ {+ id: "cc-update-required-1",+ label: "Fable 5.1 (disabled)",+ reason: "Update to 2.1.255+ to use Fable 5.1",+ },+ ],+ supported: true,+ };++ it("shows the row with the runtime's upgrade hint but renders no control for it", async () => {+ discovery = async () => WITH_UNAVAILABLE;+ const { container, onChange } = renderDropdown();+ openDropdown(container);++ const row = await screen.findByText("Fable 5.1 (disabled)");+ expect(+ screen.getByText("Update to 2.1.255+ to use Fable 5.1"),+ ).toBeTruthy();++ // Nothing clickable was rendered for it, so there is no path to select it.+ expect(row.closest("button")).toBeNull();+ fireEvent.click(row);+ expect(onChange).not.toHaveBeenCalled();++ // The model this CLI *can* run is still a normal pick.+ fireEvent.click(screen.getByText("Fable"));+ expect(onChange).toHaveBeenCalledWith("claude-fable-5");+ });++ it("keeps the unavailable id out of the selectable catalog", async () => {+ discovery = async () => WITH_UNAVAILABLE;+ const { container, onChange } = renderDropdown();+ openDropdown(container);+ await screen.findByText("Fable 5.1 (disabled)");++ // Searching the placeholder id must not surface a selectable row for it.+ // Manual entry stays available — that escape hatch accepts any string and+ // is not what this guards — but it must be the only way the text reaches+ // onChange, and only on an explicit second click.+ const input = screen.getByPlaceholderText(+ enAgents.pickers.model_search_placeholder,+ );+ fireEvent.change(input, { target: { value: "cc-update-required-1" } });++ expect(+ screen.queryByRole("button", { name: /cc-update-required-1$/ }),+ ).toBeNull();+ expect(onChange).not.toHaveBeenCalled();+ });+ });});diff --git a/packages/views/agents/components/model-dropdown.tsx b/packages/views/agents/components/model-dropdown.tsxindex 37a83872e4..aa00db9e68 100644--- a/packages/views/agents/components/model-dropdown.tsx+++ b/packages/views/agents/components/model-dropdown.tsx@@ -13,6 +13,7 @@ import {import { Input } from "@multica/ui/components/ui/input";import { Label } from "@multica/ui/components/ui/label";import { useT } from "../../i18n";+import { UnavailableModelsNote } from "./unavailable-models-note";// ModelDropdown renders a searchable, creatable model picker for an agent.// It fetches the supported-model catalog from the selected runtime — the@@ -57,6 +58,11 @@ export function ModelDropdown({[modelsQuery.data],);const grouped = useMemo(() => groupByProvider(models), [models]);+ // Advisory only — never merged into `models`, so nothing below can select one.+ const unavailableModels = useMemo(+ () => modelsQuery.data?.unavailableModels ?? [],+ [modelsQuery.data],+ );// resolveRuntimeModels throws the daemon's reported error text, so this is// the runtime's own message (plus any hint the daemon appended). It is only// ever read while isError is true.@@ -245,6 +251,13 @@ export function ModelDropdown({</div>)}+ {!modelsQuery.isLoading && !modelsQuery.isError && (+ <UnavailableModelsNote+ models={unavailableModels}+ title={t(($) => $.pickers.model_unavailable_heading)}+ />+ )}+{!modelsQuery.isLoading &&!modelsQuery.isError &&Object.keys(filtered).length === 0 &&diff --git a/packages/views/agents/components/unavailable-models-note.tsx b/packages/views/agents/components/unavailable-models-note.tsxnew file mode 100644index 0000000000..11ed3116a7--- /dev/null+++ b/packages/views/agents/components/unavailable-models-note.tsx@@ -0,0 +1,50 @@+"use client";++import type { RuntimeUnavailableModel } from "@multica/core/types";++/**+ * The "your CLI is behind" section both model pickers render under their+ * selectable rows.+ *+ * These rows exist so a missing model reads as what it is. Claude Code stops+ * offering a model its own version cannot run, and simply dropping it from the+ * list would tell the user Multica does not support the model when the truth is+ * that their CLI does not yet — with the fix one `claude update` away. The+ * reason is the runtime's own copy ("Update to 2.1.255+ to use Fable 5.1"), so+ * the guidance stays correct without Multica tracking version floors (MUL-6961).+ *+ * Rendered as plain text, never as a control: nothing here is selectable, and+ * the component takes no click handler so no caller can make it one. That is+ * also why these arrive in their own list rather than as flagged entries in the+ * model array — a flag has to be honoured by every consumer that renders a row,+ * and an already-installed client cannot honour a flag it has never heard of.+ */+export function UnavailableModelsNote({+ models,+ title,+}: {+ models: readonly RuntimeUnavailableModel[];+ title: string;+}) {+ if (models.length === 0) return null;++ return (+ <div className="mt-1 border-t border-border pt-2">+ <div className="px-3 pb-1 text-caption font-medium uppercase tracking-wide text-muted-foreground">+ {title}+ </div>+ {models.map((m) => (+ <div key={m.id} className="px-3 py-1.5">+ <div className="truncate text-body text-muted-foreground">+ {m.label}+ </div>+ {m.reason && (+ // Not truncated: the reason names the version to upgrade to, and a+ // clipped remedy is no remedy.+ <div className="text-caption text-muted-foreground">{m.reason}</div>+ )}+ </div>+ ))}+ </div>+ );+}diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 9b5db6ccf2..4302de2cf0 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -236,6 +236,7 @@"model_discovery_failed_hint": "Type a model ID above to enter one manually.","model_empty": "No models available","model_empty_with_dot": "No models available.",+ "model_unavailable_heading": "Needs a newer CLI","model_custom_tooltip": "Use \"{{value}}\" as a custom model id","model_custom_use": "Use \"{{value}}\"","model_clear": "Clear (use provider default)",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex d1f36c8e50..b62577e972 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -218,6 +218,7 @@"model_discovery_failed_hint": "上の入力欄にモデル ID を直接入力して手動で指定できます。","model_empty": "利用可能なモデルがありません","model_empty_with_dot": "利用可能なモデルがありません。",+ "model_unavailable_heading": "新しい CLI が必要","model_custom_tooltip": "\"{{value}}\" をカスタムモデル ID として使用","model_custom_use": "\"{{value}}\" を使用","model_clear": "クリア(プロバイダーのデフォルトを使用)",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex a5f6770c98..ff606c922b 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -226,6 +226,7 @@"model_discovery_failed_hint": "위 입력란에 모델 ID를 직접 입력해 수동으로 지정할 수 있습니다.","model_empty": "사용 가능한 모델이 없습니다","model_empty_with_dot": "사용 가능한 모델이 없습니다.",+ "model_unavailable_heading": "최신 CLI 필요","model_custom_tooltip": "\"{{value}}\"을(를) 사용자 지정 모델 ID로 사용","model_custom_use": "\"{{value}}\" 사용","model_clear": "지우기(제공자 기본값 사용)",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex 9da3aa608a..a69c3ec475 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -226,6 +226,7 @@"model_discovery_failed_hint": "可在上方输入框直接键入模型 ID 手动指定。","model_empty": "暂无可用模型","model_empty_with_dot": "暂无可用模型。",+ "model_unavailable_heading": "需要更新 CLI","model_custom_tooltip": "使用\"{{value}}\"作为自定义模型 ID","model_custom_use": "使用\"{{value}}\"","model_clear": "清除(使用提供方默认)",diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 992e81ed41..486f5e44ec 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -4449,6 +4449,16 @@ func (d *Daemon) handleModelList(ctx context.Context, rt Runtime, requestID striServiceTiers []modelServiceTierWire `json:"service_tiers,omitempty"`SupportsExplicitStandardServiceTier bool `json:"supports_explicit_standard_service_tier,omitempty"`}+ // Models the runtime named but will not run here (Claude Code reporting one+ // that needs a newer CLI). Reported in their own list, never inside+ // `models`: a client that does not know this field — an installed desktop+ // build predating it — then cannot offer one as a real model, which a flag+ // on the model itself could not guarantee (MUL-6961).+ type unavailableModelWire struct {+ ID string `json:"id"`+ Label string `json:"label"`+ Reason string `json:"reason,omitempty"`+ }wire := make([]modelWire, 0, len(models))for _, m := range models {entry := modelWire{@@ -4481,10 +4491,21 @@ func (d *Daemon) handleModelList(ctx context.Context, rt Runtime, requestID stri}wire = append(wire, entry)}+ unavailableWire := make([]unavailableModelWire, 0, len(catalog.Unavailable))+ for _, m := range catalog.Unavailable {+ unavailableWire = append(unavailableWire, unavailableModelWire{+ ID: m.ID,+ Label: m.Label,+ Reason: m.Reason,+ })+ }d.reportModelListResult(ctx, rt, requestID, map[string]any{"status": "completed","models": wire,"supported": agent.ModelSelectionSupported(rt.Provider),+ // Additive: an older server drops the key and the picker simply shows+ // no unavailable section, which is the pre-MUL-6961 behaviour.+ "unavailable_models": unavailableWire,// Additive field: the models are still worth rendering, but the server// must not persist them as this runtime's real catalog (MUL-5549).// Older servers ignore it and keep the previous behaviour.diff --git a/server/internal/handler/agent_thinking_test.go b/server/internal/handler/agent_thinking_test.goindex 2a0e6c2eca..bc4c057dca 100644--- a/server/internal/handler/agent_thinking_test.go+++ b/server/internal/handler/agent_thinking_test.go@@ -759,7 +759,7 @@ func TestAcpThinkingDecision(t *testing.T) {withCatalog := func(t *testing.T, models []ModelEntry) *Handler {t.Helper()cache := NewInMemoryModelCatalogCache()- if err := cache.Put(ctx, uuidToString(runtimeID), models, true); err != nil {+ if err := cache.Put(ctx, uuidToString(runtimeID), models, nil, true); err != nil {t.Fatalf("seed catalog: %v", err)}return &Handler{ModelCatalogCache: cache}diff --git a/server/internal/handler/runtime_model_catalog.go b/server/internal/handler/runtime_model_catalog.goindex 586fc179e5..93354ea64c 100644--- a/server/internal/handler/runtime_model_catalog.go+++ b/server/internal/handler/runtime_model_catalog.go@@ -62,8 +62,12 @@ const (type ModelCatalogSnapshot struct {RuntimeID string `json:"runtime_id"`Models []ModelEntry `json:"models"`- Supported bool `json:"supported"`- StoredAt time.Time `json:"stored_at"`+ // UnavailableModels rides along so a cache hit renders the same picker as+ // the live round trip. Without it the greyed-out "needs a newer CLI" rows+ // would blink out for 24h the moment the first snapshot was stored.+ UnavailableModels []UnavailableModelEntry `json:"unavailable_models,omitempty"`+ Supported bool `json:"supported"`+ StoredAt time.Time `json:"stored_at"`}// Age reports how long ago the snapshot was captured.@@ -82,7 +86,7 @@ func (s *ModelCatalogSnapshot) Age(now time.Time) time.Duration {// Implementations must be safe for concurrent use.type ModelCatalogCache interface {Get(ctx context.Context, runtimeID string) (*ModelCatalogSnapshot, error)- Put(ctx context.Context, runtimeID string, models []ModelEntry, supported bool) error+ Put(ctx context.Context, runtimeID string, models []ModelEntry, unavailable []UnavailableModelEntry, supported bool) error// Invalidate drops any snapshot for the runtime. Used when the cached// catalog can no longer be trusted (e.g. the runtime row was deleted).Invalidate(ctx context.Context, runtimeID string) error@@ -165,6 +169,15 @@ func cloneModelEntries(models []ModelEntry) []ModelEntry {return out}+// cloneUnavailableModelEntries mirrors cloneModelEntries for the advisory list.+// The entries hold no pointers, so a shallow element copy is a full one.+func cloneUnavailableModelEntries(models []UnavailableModelEntry) []UnavailableModelEntry {+ if models == nil {+ return nil+ }+ return append([]UnavailableModelEntry(nil), models...)+}+// InMemoryModelCatalogCache is the single-node implementation. Adequate for// self-hosted and tests; multi-node deploys should use the Redis backend so// every API replica shares one warm catalog.@@ -198,10 +211,11 @@ func (c *InMemoryModelCatalogCache) Get(_ context.Context, runtimeID string) (*M// Copy so a caller mutating the response cannot corrupt the cache.snapshot := entrysnapshot.Models = cloneModelEntries(entry.Models)+ snapshot.UnavailableModels = cloneUnavailableModelEntries(entry.UnavailableModels)return &snapshot, nil}-func (c *InMemoryModelCatalogCache) Put(_ context.Context, runtimeID string, models []ModelEntry, supported bool) error {+func (c *InMemoryModelCatalogCache) Put(_ context.Context, runtimeID string, models []ModelEntry, unavailable []UnavailableModelEntry, supported bool) error {// fallback=false: ReportModelListResult refuses to Put a fallback catalog// at all, so anything reaching a cache backend is a real discovery result.if runtimeID == "" || !cacheableModelCatalog(models, supported, false) {@@ -220,10 +234,11 @@ func (c *InMemoryModelCatalogCache) Put(_ context.Context, runtimeID string, mod}c.entries[runtimeID] = ModelCatalogSnapshot{- RuntimeID: runtimeID,- Models: cloneModelEntries(models),- Supported: supported,- StoredAt: now,+ RuntimeID: runtimeID,+ Models: cloneModelEntries(models),+ UnavailableModels: cloneUnavailableModelEntries(unavailable),+ Supported: supported,+ StoredAt: now,}return nil}diff --git a/server/internal/handler/runtime_model_catalog_redis_cache.go b/server/internal/handler/runtime_model_catalog_redis_cache.goindex eab81fe546..60f27d133a 100644--- a/server/internal/handler/runtime_model_catalog_redis_cache.go+++ b/server/internal/handler/runtime_model_catalog_redis_cache.go@@ -64,17 +64,18 @@ func (c *RedisModelCatalogCache) Get(ctx context.Context, runtimeID string) (*Moreturn &snapshot, nil}-func (c *RedisModelCatalogCache) Put(ctx context.Context, runtimeID string, models []ModelEntry, supported bool) error {+func (c *RedisModelCatalogCache) Put(ctx context.Context, runtimeID string, models []ModelEntry, unavailable []UnavailableModelEntry, supported bool) error {// fallback=false: ReportModelListResult refuses to Put a fallback catalog// at all, so anything reaching a cache backend is a real discovery result.if runtimeID == "" || !cacheableModelCatalog(models, supported, false) {return nil}snapshot := ModelCatalogSnapshot{- RuntimeID: runtimeID,- Models: models,- Supported: supported,- StoredAt: time.Now(),+ RuntimeID: runtimeID,+ Models: models,+ UnavailableModels: unavailable,+ Supported: supported,+ StoredAt: time.Now(),}data, err := json.Marshal(snapshot)if err != nil {diff --git a/server/internal/handler/runtime_model_catalog_redis_cache_test.go b/server/internal/handler/runtime_model_catalog_redis_cache_test.goindex 63bb112311..f920d744bb 100644--- a/server/internal/handler/runtime_model_catalog_redis_cache_test.go+++ b/server/internal/handler/runtime_model_catalog_redis_cache_test.go@@ -21,7 +21,7 @@ func TestRedisModelCatalogCache_RoundTrip(t *testing.T) {t.Fatalf("cold cache should miss: got=%+v err=%v", got, err)}- if err := cache.Put(ctx, "runtime-1", sampleCatalog(), true); err != nil {+ if err := cache.Put(ctx, "runtime-1", sampleCatalog(), nil, true); err != nil {t.Fatalf("put: %v", err)}@@ -58,14 +58,14 @@ func TestRedisModelCatalogCache_SkipsUncacheableResults(t *testing.T) {ctx := context.Background()cache := NewRedisModelCatalogCache(rdb)- if err := cache.Put(ctx, "runtime-empty", nil, true); err != nil {+ if err := cache.Put(ctx, "runtime-empty", nil, nil, true); err != nil {t.Fatalf("put empty: %v", err)}if got, _ := cache.Get(ctx, "runtime-empty"); got != nil {t.Fatalf("empty catalog must not be cached: %+v", got)}- if err := cache.Put(ctx, "runtime-unsupported", sampleCatalog(), false); err != nil {+ if err := cache.Put(ctx, "runtime-unsupported", sampleCatalog(), nil, false); err != nil {t.Fatalf("put unsupported: %v", err)}if got, _ := cache.Get(ctx, "runtime-unsupported"); got != nil {@@ -78,7 +78,7 @@ func TestRedisModelCatalogCache_InvalidateAndExpiry(t *testing.T) {ctx := context.Background()cache := NewRedisModelCatalogCache(rdb)- if err := cache.Put(ctx, "runtime-1", sampleCatalog(), true); err != nil {+ if err := cache.Put(ctx, "runtime-1", sampleCatalog(), nil, true); err != nil {t.Fatalf("put: %v", err)}if err := cache.Invalidate(ctx, "runtime-1"); err != nil {@@ -90,7 +90,7 @@ func TestRedisModelCatalogCache_InvalidateAndExpiry(t *testing.T) {// The key must carry a TTL so a runtime that never comes back cannot pin a// snapshot in Redis forever.- if err := cache.Put(ctx, "runtime-1", sampleCatalog(), true); err != nil {+ if err := cache.Put(ctx, "runtime-1", sampleCatalog(), nil, true); err != nil {t.Fatalf("re-put: %v", err)}ttl, err := rdb.TTL(ctx, modelCatalogKey("runtime-1")).Result()diff --git a/server/internal/handler/runtime_model_catalog_test.go b/server/internal/handler/runtime_model_catalog_test.goindex 6c3c87f881..01df6ec08e 100644--- a/server/internal/handler/runtime_model_catalog_test.go+++ b/server/internal/handler/runtime_model_catalog_test.go@@ -26,7 +26,7 @@ func TestInMemoryModelCatalogCache_RoundTrip(t *testing.T) {if got, err := cache.Get(ctx, "rt-1"); err != nil || got != nil {t.Fatalf("cold cache should miss: got=%+v err=%v", got, err)}- if err := cache.Put(ctx, "rt-1", sampleCatalog(), true); err != nil {+ if err := cache.Put(ctx, "rt-1", sampleCatalog(), nil, true); err != nil {t.Fatalf("put: %v", err)}@@ -62,7 +62,7 @@ func TestInMemoryModelCatalogCache_RoundTrip(t *testing.T) {func TestInMemoryModelCatalogCache_ReturnsIndependentCopies(t *testing.T) {ctx := context.Background()cache := NewInMemoryModelCatalogCache()- if err := cache.Put(ctx, "rt-1", sampleCatalog(), true); err != nil {+ if err := cache.Put(ctx, "rt-1", sampleCatalog(), nil, true); err != nil {t.Fatalf("put: %v", err)}@@ -99,7 +99,7 @@ func TestInMemoryModelCatalogCache_IsolatesNestedFields(t *testing.T) {},ServiceTiers: []ModelServiceTier{{ID: "fast", Name: "Fast"}},}}- if err := cache.Put(ctx, "rt-1", source, true); err != nil {+ if err := cache.Put(ctx, "rt-1", source, nil, true); err != nil {t.Fatalf("put: %v", err)}@@ -145,21 +145,21 @@ func TestInMemoryModelCatalogCache_SkipsUncacheableResults(t *testing.T) {ctx := context.Background()cache := NewInMemoryModelCatalogCache()- if err := cache.Put(ctx, "rt-empty", nil, true); err != nil {+ if err := cache.Put(ctx, "rt-empty", nil, nil, true); err != nil {t.Fatalf("put empty: %v", err)}if got, _ := cache.Get(ctx, "rt-empty"); got != nil {t.Fatalf("empty catalog must not be cached: %+v", got)}- if err := cache.Put(ctx, "rt-unsupported", sampleCatalog(), false); err != nil {+ if err := cache.Put(ctx, "rt-unsupported", sampleCatalog(), nil, false); err != nil {t.Fatalf("put unsupported: %v", err)}if got, _ := cache.Get(ctx, "rt-unsupported"); got != nil {t.Fatalf("unsupported runtime must not be cached: %+v", got)}- if err := cache.Put(ctx, "", sampleCatalog(), true); err != nil {+ if err := cache.Put(ctx, "", sampleCatalog(), nil, true); err != nil {t.Fatalf("put empty runtime id: %v", err)}if got, _ := cache.Get(ctx, ""); got != nil {@@ -174,7 +174,7 @@ func TestInMemoryModelCatalogCache_ExpiresAndInvalidates(t *testing.T) {cache := NewInMemoryModelCatalogCache()cache.retainFor = 20 * time.Millisecond- if err := cache.Put(ctx, "rt-1", sampleCatalog(), true); err != nil {+ if err := cache.Put(ctx, "rt-1", sampleCatalog(), nil, true); err != nil {t.Fatalf("put: %v", err)}time.Sleep(40 * time.Millisecond)@@ -183,7 +183,7 @@ func TestInMemoryModelCatalogCache_ExpiresAndInvalidates(t *testing.T) {}cache.retainFor = modelCatalogServeWindow- if err := cache.Put(ctx, "rt-1", sampleCatalog(), true); err != nil {+ if err := cache.Put(ctx, "rt-1", sampleCatalog(), nil, true); err != nil {t.Fatalf("re-put: %v", err)}if err := cache.Invalidate(ctx, "rt-1"); err != nil {@@ -280,8 +280,10 @@ type failingModelCatalogCache struct{}func (failingModelCatalogCache) Get(context.Context, string) (*ModelCatalogSnapshot, error) {return nil, errors.New("redis down")}-func (failingModelCatalogCache) Put(context.Context, string, []ModelEntry, bool) error { return nil }-func (failingModelCatalogCache) Invalidate(context.Context, string) error { return nil }+func (failingModelCatalogCache) Put(context.Context, string, []ModelEntry, []UnavailableModelEntry, bool) error {+ return nil+}+func (failingModelCatalogCache) Invalidate(context.Context, string) error { return nil }// TestCachedModelCatalog_DegradesToMiss proves the cache can never fail a// request: a nil cache, a backend error, or a snapshot that is no longer@@ -464,3 +466,48 @@ func TestCachedModelListResponse_WireShape(t *testing.T) {t.Error("live responses must omit cached_at")}}++// TestInMemoryModelCatalogCache_RoundTripsUnavailableModels covers the advisory+// list (MUL-6961). Without it, a warm cache hit would silently drop the greyed+// "needs a newer CLI" rows for the whole serve window, so the same runtime would+// explain the missing model on a cold open and stay silent on every open after.+func TestInMemoryModelCatalogCache_RoundTripsUnavailableModels(t *testing.T) {+ ctx := context.Background()+ cache := NewInMemoryModelCatalogCache()++ unavailable := []UnavailableModelEntry{{+ ID: "cc-update-required-1",+ Label: "Fable 5.1 (disabled)",+ Reason: "Update to 2.1.255+ to use Fable 5.1",+ }}+ if err := cache.Put(ctx, "rt-1", sampleCatalog(), unavailable, true); err != nil {+ t.Fatalf("put: %v", err)+ }++ got, err := cache.Get(ctx, "rt-1")+ if err != nil || got == nil {+ t.Fatalf("get: got=%+v err=%v", got, err)+ }+ if len(got.UnavailableModels) != 1 {+ t.Fatalf("unavailable models lost in the cache: %+v", got.UnavailableModels)+ }+ if got.UnavailableModels[0].Reason != "Update to 2.1.255+ to use Fable 5.1" {+ t.Errorf("reason = %q, want the runtime's upgrade hint", got.UnavailableModels[0].Reason)+ }+ // The selectable list must not have absorbed it on the way through.+ for _, m := range got.Models {+ if m.ID == "cc-update-required-1" {+ t.Fatal("an unavailable model leaked into the selectable catalog")+ }+ }++ // Mutating the returned slice must not corrupt the cache, same as Models.+ got.UnavailableModels[0].Label = "mutated"+ again, err := cache.Get(ctx, "rt-1")+ if err != nil || again == nil {+ t.Fatalf("second get: got=%+v err=%v", again, err)+ }+ if again.UnavailableModels[0].Label != "Fable 5.1 (disabled)" {+ t.Errorf("cache was corrupted by a caller mutation: %q", again.UnavailableModels[0].Label)+ }+}diff --git a/server/internal/handler/runtime_models.go b/server/internal/handler/runtime_models.goindex 840c84cee9..4685ebdcff 100644--- a/server/internal/handler/runtime_models.go+++ b/server/internal/handler/runtime_models.go@@ -57,15 +57,18 @@ const (// `json:"-"` because it's a server-side bookkeeping field — the UI only// needs Status / UpdatedAt to drive the polling loop.type ModelListRequest struct {- ID string `json:"id"`- RuntimeID string `json:"runtime_id"`- Status ModelListStatus `json:"status"`- Models []ModelEntry `json:"models,omitempty"`- Supported bool `json:"supported"`- Error string `json:"error,omitempty"`- CreatedAt time.Time `json:"created_at"`- UpdatedAt time.Time `json:"updated_at"`- RunStartedAt *time.Time `json:"-"`+ ID string `json:"id"`+ RuntimeID string `json:"runtime_id"`+ Status ModelListStatus `json:"status"`+ Models []ModelEntry `json:"models,omitempty"`+ // UnavailableModels is advisory display copy, never a source of pickable+ // values. Older daemons omit it and older clients ignore it.+ UnavailableModels []UnavailableModelEntry `json:"unavailable_models,omitempty"`+ Supported bool `json:"supported"`+ Error string `json:"error,omitempty"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at"`+ RunStartedAt *time.Time `json:"-"`// Cached marks a response answered from the server-side catalog cache// instead of a live daemon round trip (MUL-5444). Purely informational —// Status is already "completed" and Models is already populated, so a client@@ -88,6 +91,9 @@ type ModelListRequest struct {// thinking_level selector. Older daemons (pre-2026-05) won't send this// field, which is fine: the UI hides the selector and the agent runs// with the runtime default.+//+// Every entry here is selectable. Models the runtime named but will not run are+// carried separately in UnavailableModelEntry — see the invariant there.type ModelEntry struct {ID string `json:"id"`Label string `json:"label"`@@ -98,6 +104,22 @@ type ModelEntry struct {SupportsExplicitStandardServiceTier bool `json:"supports_explicit_standard_service_tier,omitempty"`}+// UnavailableModelEntry is a model the runtime named but will not run on that+// host — Claude Code reports one needing a newer CLI this way. `Reason` is the+// runtime's own upgrade hint, shown so the gap reads as "your CLI is behind"+// rather than "Multica does not support this model" (MUL-6961).+//+// INVARIANT: these never appear in `models`. A client that does not know this+// field is an installed desktop build predating it, and such a client must not+// be able to render one as a selectable model and persist an id its CLI+// rejects. Keeping the lists disjoint is what makes that true without the old+// client having to do anything.+type UnavailableModelEntry struct {+ ID string `json:"id"`+ Label string `json:"label"`+ Reason string `json:"reason,omitempty"`+}+type ModelServiceTier struct {ID string `json:"id"`Name string `json:"name"`@@ -155,7 +177,7 @@ type ModelListStore interface {// PopPending handles "queue empty after probe" by returning nil.HasPending(ctx context.Context, runtimeID string) (bool, error)PopPending(ctx context.Context, runtimeID string) (*ModelListRequest, error)- Complete(ctx context.Context, id string, models []ModelEntry, supported bool) error+ Complete(ctx context.Context, id string, models []ModelEntry, unavailable []UnavailableModelEntry, supported bool) errorFail(ctx context.Context, id string, errMsg string) error}@@ -273,13 +295,14 @@ func (s *InMemoryModelListStore) PopPending(_ context.Context, runtimeID string)return oldest, nil}-func (s *InMemoryModelListStore) Complete(_ context.Context, id string, models []ModelEntry, supported bool) error {+func (s *InMemoryModelListStore) Complete(_ context.Context, id string, models []ModelEntry, unavailable []UnavailableModelEntry, supported bool) error {s.mu.Lock()defer s.mu.Unlock()if req, ok := s.requests[id]; ok {req.Status = ModelListCompletedreq.Models = models+ req.UnavailableModels = unavailablereq.Supported = supportedreq.UpdatedAt = time.Now()}@@ -339,15 +362,16 @@ func (h *Handler) InitiateListModels(w http.ResponseWriter, r *http.Request) {// Synthetic ID: no store record backs a cache hit. Clients only poll// GET /models/{id} while status is pending/running, which this// response never is.- ID: randomID(),- RuntimeID: resolvedRuntimeID,- Status: ModelListCompleted,- Models: cached.Models,- Supported: cached.Supported,- CreatedAt: storedAt,- UpdatedAt: storedAt,- Cached: true,- CachedAt: &storedAt,+ ID: randomID(),+ RuntimeID: resolvedRuntimeID,+ Status: ModelListCompleted,+ Models: cached.Models,+ UnavailableModels: cached.UnavailableModels,+ Supported: cached.Supported,+ CreatedAt: storedAt,+ UpdatedAt: storedAt,+ Cached: true,+ CachedAt: &storedAt,})return}@@ -478,10 +502,13 @@ func (h *Handler) ReportModelListResult(w http.ResponseWriter, r *http.Request)}var body struct {- Status string `json:"status"` // "completed" or "failed"- Models []ModelEntry `json:"models"`- Supported *bool `json:"supported"`- Error string `json:"error"`+ Status string `json:"status"` // "completed" or "failed"+ Models []ModelEntry `json:"models"`+ // UnavailableModels is what the runtime named but will not run. Older+ // daemons omit it; absent simply means no advisory rows to show.+ UnavailableModels []UnavailableModelEntry `json:"unavailable_models"`+ Supported *bool `json:"supported"`+ Error string `json:"error"`// Fallback marks a completed report whose models are a static// stand-in the provider substituted after discovery failed, not the// runtime's real catalog. Older daemons omit it; absent means "this@@ -500,7 +527,7 @@ func (h *Handler) ReportModelListResult(w http.ResponseWriter, r *http.Request)if body.Supported != nil {supported = *body.Supported}- if err := h.ModelListStore.Complete(r.Context(), requestID, body.Models, supported); err != nil {+ if err := h.ModelListStore.Complete(r.Context(), requestID, body.Models, body.UnavailableModels, supported); err != nil {// Surface the store failure as 5xx so the daemon can retry instead// of swallowing the report (leaves the request stuck in running// until the server-side timeout, which is exactly the "looks OK@@ -527,7 +554,7 @@ func (h *Handler) ReportModelListResult(w http.ResponseWriter, r *http.Request)if h.ModelCatalogCache != nil {switch modelCatalogCacheDecision(body.Models, supported, body.Fallback) {case modelCatalogCacheStore:- if err := h.ModelCatalogCache.Put(r.Context(), runtimeID, body.Models, supported); err != nil {+ if err := h.ModelCatalogCache.Put(r.Context(), runtimeID, body.Models, body.UnavailableModels, supported); err != nil {slog.Warn("model catalog cache write failed", "error", err, "runtime_id", runtimeID)}case modelCatalogCacheDrop:diff --git a/server/internal/handler/runtime_models_redis_store.go b/server/internal/handler/runtime_models_redis_store.goindex 828dbfb2e9..23ad881c10 100644--- a/server/internal/handler/runtime_models_redis_store.go+++ b/server/internal/handler/runtime_models_redis_store.go@@ -227,7 +227,7 @@ func (s *RedisModelListStore) PopPending(ctx context.Context, runtimeID string)return nil, nil}-func (s *RedisModelListStore) Complete(ctx context.Context, id string, models []ModelEntry, supported bool) error {+func (s *RedisModelListStore) Complete(ctx context.Context, id string, models []ModelEntry, unavailable []UnavailableModelEntry, supported bool) error {req, err := s.loadRequest(ctx, id)if err != nil {return err@@ -237,6 +237,7 @@ func (s *RedisModelListStore) Complete(ctx context.Context, id string, models []}req.Status = ModelListCompletedreq.Models = models+ req.UnavailableModels = unavailablereq.Supported = supportedreq.UpdatedAt = time.Now()return s.persistRequest(ctx, req)diff --git a/server/internal/handler/runtime_models_redis_store_test.go b/server/internal/handler/runtime_models_redis_store_test.goindex 06ca241ba2..164ac352de 100644--- a/server/internal/handler/runtime_models_redis_store_test.go+++ b/server/internal/handler/runtime_models_redis_store_test.go@@ -76,7 +76,7 @@ func TestRedisModelListStore_CreateGetComplete(t *testing.T) {{ID: "claude-sonnet-4-6", Label: "Claude Sonnet 4.6", Provider: "anthropic", Default: true},{ID: "claude-opus-4-7", Label: "Claude Opus 4.7", Provider: "anthropic"},}- if err := store.Complete(ctx, req.ID, models, true); err != nil {+ if err := store.Complete(ctx, req.ID, models, nil, true); err != nil {t.Fatalf("complete: %v", err)}diff --git a/server/internal/handler/runtime_models_test.go b/server/internal/handler/runtime_models_test.goindex b9e5b33b08..b7705b152a 100644--- a/server/internal/handler/runtime_models_test.go+++ b/server/internal/handler/runtime_models_test.go@@ -91,7 +91,7 @@ func TestReportModelListResult_PreservesDefault(t *testing.T) {if err := json.Unmarshal(raw, &parsed); err != nil {t.Fatalf("unmarshal report body: %v", err)}- if err := store.Complete(ctx, req.ID, parsed.Models, true); err != nil {+ if err := store.Complete(ctx, req.ID, parsed.Models, nil, true); err != nil {t.Fatalf("complete: %v", err)}diff --git a/server/pkg/agent/claude_models.go b/server/pkg/agent/claude_models.gonew file mode 100644index 0000000000..b1ddc0f277--- /dev/null+++ b/server/pkg/agent/claude_models.go@@ -0,0 +1,457 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "strings"+ "sync"+ "time"+)++// ── Claude model discovery ───────────────────────────────────────────+//+// Claude Code has no `--list-models` flag and no models subcommand, which is+// why this package carried a hand-maintained claudeStaticModels() for so long.+// It does have a discovery hook, just not on the command line: the stream-json+// control protocol answers a `list_models` control request with the same+// ModelInfo rows the interactive /model picker renders.+//+// That distinction is the whole point of MUL-6961. A static catalog cannot know+// what the CLI in front of it can actually run, so every new Anthropic model+// opened a window where Multica offered a model that 400s ("Claude Code 2.1.246+// does not support this model; version 2.1.251 or newer is required"). The+// control protocol closes the window at the source: the answer is computed by+// the installed binary, against the logged-in account, so a model the local CLI+// cannot run is either absent or explicitly flagged disabled. Verified against+// 2.1.223 / 2.1.228 / 2.1.246 / 2.1.258 — the three older builds return Fable+// 5.1 as a disabled row carrying "Update to 2.1.255+ to use Fable 5.1", and+// 2.1.258 returns it as a normal selectable entry.+//+// This governs SELECTION, and only selection. An agent already configured with+// a model, whose CLI is downgraded afterwards, still starts and still gets the+// upstream 400 — discovery cannot reach a value already persisted. That is the+// accepted boundary, decided on MUL-6961 rather than assumed: the downgrade is+// a rare case, the upstream error is accurate, and a run that fails loudly at+// the moment it starts is a fine way to report it. Do not "improve" this by+// clearing the configured model or substituting a runnable one when the catalog+// no longer offers it. Clearing turns a legible error into a silent config+// change the user did not make, and substituting is worse — it succeeds, using+// a model nobody chose.+//+// No version gate guards the request, unlike codexSupportsDebugModels. It would+// buy nothing: an unsupported subtype is answered, not ignored — every build+// tested replies `Unsupported control request subtype: ...` in about two+// seconds and exits 0 — so an old CLI costs one cheap round trip and falls back,+// with no risk of hanging until the timeout. Gating instead on a version floor+// would mean hand-maintaining exactly the kind of number this change exists to+// stop hand-maintaining.+//+// "One round trip" is only true because that specific answer is remembered; see+// claudeListModelsUnsupported below for why it has to be.++// claudeListModelsArgs is the argv for a discovery-only Claude session.+//+// `--print` with stream-json on both ends is the control-protocol channel the+// daemon already speaks for task execution. No user message is ever written, so+// no model is invoked and nothing is billed: the process answers the control+// request, sees stdin close, and exits 0.+//+// `--strict-mcp-config` without any `--mcp-config` resolves to "no MCP servers+// at all". Discovery has no use for the user's servers and every reason not to+// boot them — a stdio server that spawns a container would make enumerating a+// model list arbitrarily slow and arbitrarily side-effecting.+//+// Kept as a package-level var rather than a literal at the call site so tests+// can pin the exact argv a real `claude` invocation receives; the argv shape is+// as much of the contract as the parser is.+var claudeListModelsArgs = []string{+ "--print",+ "--verbose",+ "--input-format", "stream-json",+ "--output-format", "stream-json",+ "--strict-mcp-config",+}++// claudeListModelsRequestID labels our control request so the reply can be+// picked out of the stream. Claude answers a discovery-only session in a single+// stdout line today, but matching on the id keeps that from being load-bearing.+const claudeListModelsRequestID = "multica-list-models"++// claudeListModelsTimeout bounds one discovery round trip.+//+// Measured on an M-series laptop over five runs each: 1.57–2.19s against 2.1.258+// and 1.64–1.79s against 2.1.246, plus ~0.2s against an empty config dir. The+// ceiling is ~10x the observed worst case because the failure it exists for is+// not a slow answer but no answer — a wrapper script that never execs, or a CLI+// wedged on a keychain prompt — and the machines that hit that are the loaded,+// cold-cache ones the measurements above do not represent. Nothing user-facing+// blocks on it: exceeding it degrades to the static catalog.+const claudeListModelsTimeout = 20 * time.Second++// errClaudeListModelsUnsupported marks the one discovery failure that is a+// property of the binary rather than a bad moment: the CLI answered, and its+// answer was that it does not know this control request. Distinguishing it is+// what lets discoverClaudeCatalog remember it, and remembering it is not an+// optimisation — every Claude task carrying a thinking_level reads the catalog+// before it starts (see the ValidateThinkingLevelWith call in the daemon), and+// cachedDiscovery deliberately refuses to memoise a fallback result (#3729,+// MUL-5549). Without this, "one cheap round trip" would mean one round trip per+// task, forever, on exactly the old installs that can never succeed.+var errClaudeListModelsUnsupported = errors.New("claude CLI does not support the list_models control request")++// claudeUnsupportedSubtypeMarker is the substring Claude Code uses to say a+// control request subtype is unknown to it ("Unsupported control request+// subtype: list_models"), verified on 2.1.223 and 2.1.258.+//+// Matching on upstream prose is not something to do lightly, and it is only+// safe here because of which way it fails. A miss means the negative cache does+// not engage and behaviour is exactly what it was before — correct, slower. It+// is the opposite mistake that would hurt, caching "unsupported" for a CLI that+// merely had a bad moment, and no wording drift can produce that.+const claudeUnsupportedSubtypeMarker = "unsupported control request subtype"++// claudeCapabilityKey scopes a remembered capability answer to the exact binary+// that gave it. The CLI version is part of the key so an upgrade invalidates the+// memo immediately rather than after a TTL — the whole point is that upgrading+// is the fix we are nudging people toward, so it must take effect at once.+// Detecting the version costs ~0.01s against the ~1.7s probe it avoids.+type claudeCapabilityKey struct {+ command string+ cliVersion string+}++const claudeCapabilityTTL = 10 * time.Minute++var (+ claudeCapabilityMu sync.Mutex+ // claudeListModelsUnsupported holds expiry times for binaries known not to+ // answer list_models. A TTL still bounds the memo for the case a version+ // string cannot distinguish — a dev build replaced in place.+ claudeListModelsUnsupported = map[claudeCapabilityKey]time.Time{}+)++func claudeListModelsKnownUnsupported(key claudeCapabilityKey) bool {+ if key.cliVersion == "" {+ // No version means no way to notice an upgrade, so nothing is+ // remembered and nothing is trusted.+ return false+ }+ claudeCapabilityMu.Lock()+ defer claudeCapabilityMu.Unlock()+ expiry, ok := claudeListModelsUnsupported[key]+ if !ok || time.Now().After(expiry) {+ return false+ }+ return true+}++func rememberClaudeListModelsUnsupported(key claudeCapabilityKey) {+ if key.cliVersion == "" {+ return+ }+ claudeCapabilityMu.Lock()+ defer claudeCapabilityMu.Unlock()+ claudeListModelsUnsupported[key] = time.Now().Add(claudeCapabilityTTL)+}++// resetClaudeCapabilityCacheForTests is exposed for tests only; production code+// relies on the TTL, the version key, or a process restart.+func resetClaudeCapabilityCacheForTests() {+ claudeCapabilityMu.Lock()+ claudeListModelsUnsupported = map[claudeCapabilityKey]time.Time{}+ claudeCapabilityMu.Unlock()+}++// claudeModelInfo is one row of the control protocol's model catalog.+//+// Value is the picker token (`sonnet`, `opus[1m]`, or the sentinel `default`);+// ResolvedModel is what that token actually runs and is what Multica persists.+// Disabled marks a row the CLI shows greyed out — visible on purpose, so the+// user learns the model exists and why it is out of reach, with Description+// carrying the runtime's own remedy.+type claudeModelInfo struct {+ Value string `json:"value"`+ ResolvedModel string `json:"resolvedModel"`+ DisplayName string `json:"displayName"`+ Description string `json:"description"`+ SupportsEffort bool `json:"supportsEffort"`+ SupportedEffortLevels []string `json:"supportedEffortLevels"`+ Disabled bool `json:"disabled"`+}++// claudeControlResponse is the control-protocol envelope. The doubled+// `response` nesting is Claude's shape, not a transcription slip: the outer one+// is the envelope (subtype/request_id/error), the inner one is the payload.+type claudeControlResponse struct {+ Type string `json:"type"`+ Response struct {+ Subtype string `json:"subtype"`+ RequestID string `json:"request_id"`+ Error string `json:"error"`+ Response struct {+ Models []claudeModelInfo `json:"models"`+ } `json:"response"`+ } `json:"response"`+}++// claudeDefaultModelValue is the picker row meaning "whatever this CLI resolves+// to", not a model in its own right. Multica already spells that "leave the+// agent's model empty", so the row is folded into the Default flag rather than+// offered as a pick.+const claudeDefaultModelValue = "default"++// discoverClaudeCatalog answers a model-listing round for claude, preferring+// the live catalog and degrading to the hand-maintained one.+//+// The fallback is flagged, which is a change in kind rather than a detail. The+// static list used to be returned as authoritative because there was nothing to+// fall back from; now that discovery exists, a static answer means discovery+// failed, and Catalog.Fallback is what stops the server pinning that failure in+// a day-long cache (MUL-5549). The cost is that a CLI too old to answer+// list_models never gets a cached catalog — correct, and the same deal every+// other fallback provider already takes.+func discoverClaudeCatalog(ctx context.Context, runtimeCmd Command) Catalog {+ if runtimeCmd.Path == "" {+ runtimeCmd.Path = "claude"+ }+ // Detected up front because the fallback below needs it anyway+ // (annotateClaudeThinking keys its own cache on the version), so the+ // capability memo rides along for free rather than adding a probe.+ version, _ := DetectVersion(ctx, runtimeCmd)+ key := claudeCapabilityKey{command: runtimeCmd.cacheKey(), cliVersion: version}++ if claudeListModelsKnownUnsupported(key) {+ return claudeStaticCatalog(ctx, runtimeCmd)+ }++ models, unavailable, err := discoverClaudeModels(ctx, runtimeCmd)+ if err == nil {+ return Catalog{Models: models, Unavailable: unavailable}+ }+ if errors.Is(err, errClaudeListModelsUnsupported) {+ rememberClaudeListModelsUnsupported(key)+ }+ if runtimeCmd.logger != nil {+ runtimeCmd.logger.Debug("claude model discovery failed, using static catalog", "error", err)+ }+ return claudeStaticCatalog(ctx, runtimeCmd)+}++func claudeStaticCatalog(ctx context.Context, runtimeCmd Command) Catalog {+ static := claudeStaticModels()+ annotateClaudeThinking(ctx, static, runtimeCmd)+ return Catalog{Models: static, Fallback: true}+}++// discoverClaudeModels enumerates the local Claude Code catalog over the+// control protocol. A failure at any stage — spawn, timeout, malformed reply,+// error subtype, empty list — is returned as an error so the caller can fall+// back to the static catalog; no partial result is ever reported as authoritative.+func discoverClaudeModels(ctx context.Context, runtimeCmd Command) ([]Model, []UnavailableModel, error) {+ if runtimeCmd.Path == "" {+ runtimeCmd.Path = "claude"+ }++ raw, err := runClaudeListModels(ctx, runtimeCmd)+ if err != nil {+ return nil, nil, err+ }+ infos, err := parseClaudeModelCatalog(raw)+ if err != nil {+ return nil, nil, err+ }+ models, unavailable := claudeModelsFromInfos(infos)+ if len(models) == 0 {+ // Unavailable rows alone are not a catalog: with nothing selectable the+ // picker has no answer, and the static list is a better one.+ return nil, nil, errors.New("claude list_models returned no usable models")+ }+ return models, unavailable, nil+}++func runClaudeListModels(ctx context.Context, runtimeCmd Command) ([]byte, error) {+ ctx, cancel := context.WithTimeout(ctx, claudeListModelsTimeout)+ defer cancel()++ request, err := json.Marshal(map[string]any{+ "type": "control_request",+ "request_id": claudeListModelsRequestID,+ "request": map[string]any{"subtype": "list_models"},+ })+ if err != nil {+ return nil, err+ }++ cmd := runtimeCmd.exec(ctx, claudeListModelsArgs...)+ // Feeding stdin from a reader rather than a pipe is what makes this a+ // one-shot probe: os/exec closes the pipe once the request is written, the+ // CLI takes that EOF as end of session and exits on its own. Nothing here+ // has to police a lingering process.+ cmd.Stdin = strings.NewReader(string(request) + "\n")+ hideAgentWindow(cmd)+ return outputOwned(cmd, runtimeCmd.logger)+}++// parseClaudeModelCatalog pulls our reply out of the stream-json stdout.+//+// Non-JSON and unrelated lines are skipped rather than treated as corruption:+// stdout is a stream shared with whatever else the session emits, and a+// discovery run that failed to find its own answer is already reported as an+// error below.+func parseClaudeModelCatalog(raw []byte) ([]claudeModelInfo, error) {+ for _, line := range strings.Split(string(raw), "\n") {+ line = strings.TrimSpace(line)+ if line == "" {+ continue+ }+ var resp claudeControlResponse+ if err := json.Unmarshal([]byte(line), &resp); err != nil {+ continue+ }+ if resp.Type != "control_response" || resp.Response.RequestID != claudeListModelsRequestID {+ continue+ }+ if resp.Response.Subtype != "success" {+ // An old CLI lands here with "Unsupported control request+ // subtype: list_models". Surfacing the runtime's own words keeps+ // the daemon log honest about which of the two failures it hit,+ // and tagging that one case lets the caller stop asking a binary+ // that has told us it cannot answer.+ reason := strings.TrimSpace(resp.Response.Error)+ if reason == "" {+ reason = resp.Response.Subtype+ }+ if strings.Contains(strings.ToLower(reason), claudeUnsupportedSubtypeMarker) {+ return nil, fmt.Errorf("%w: %s", errClaudeListModelsUnsupported, reason)+ }+ return nil, fmt.Errorf("claude list_models failed: %s", reason)+ }+ return resp.Response.Response.Models, nil+ }+ return nil, errors.New("claude list_models produced no control response")+}++// claudeModelsFromInfos projects the control-protocol rows onto the catalog.+//+// Rows are keyed by ResolvedModel, not by the picker token: two tokens+// routinely resolve to one model (`default` and `opus[1m]` both mean Opus 5+// with a 1M window), and it is the resolved name that gets persisted on the+// agent, passed to `--model`, and matched by the pricing table. The context+// window tag rides along on purpose — `claude-opus-5[1m]` is what the CLI would+// actually run for that row, so dropping the tag would quietly downgrade a user+// who picked "Opus (1M context)" to the default window.+func claudeModelsFromInfos(infos []claudeModelInfo) ([]Model, []UnavailableModel) {+ models := make([]Model, 0, len(infos))+ var unavailable []UnavailableModel+ index := make(map[string]int, len(infos))+ var defaultRow *claudeModelInfo++ for i := range infos {+ info := infos[i]+ id := claudeModelID(info)+ if id == "" {+ continue+ }+ if strings.TrimSpace(info.Value) == claudeDefaultModelValue {+ // Held back rather than emitted: Multica already spells "whatever+ // this CLI resolves to" as an empty model. Resolved after the loop,+ // once we know whether a real row carries the same model.+ defaultRow = &infos[i]+ continue+ }+ if info.Disabled {+ // Never enters models, so no capability lookup, no picker, and no+ // older client can offer it.+ unavailable = append(unavailable, UnavailableModel{+ ID: id,+ Label: claudeModelLabel(info, id),+ Reason: strings.TrimSpace(info.Description),+ })+ continue+ }+ if _, seen := index[id]; seen {+ continue+ }+ index[id] = len(models)+ models = append(models, Model{+ ID: id,+ Label: claudeModelLabel(info, id),+ Provider: "anthropic",+ Thinking: claudeThinkingFromInfo(info),+ })+ }++ if defaultRow != nil {+ if id := claudeModelID(*defaultRow); id != "" {+ if i, ok := index[id]; ok {+ models[i].Default = true+ } else if !defaultRow.Disabled {+ // The default resolves to a model no other row names — an+ // org-restricted install can look like this. Materialise it+ // instead of dropping it: without an entry flagged Default,+ // ValidateThinkingLevelWith cannot resolve an empty model and+ // fails closed, which silently discards the user's effort on+ // every default-model task.+ models = append(models, Model{+ ID: id,+ Label: claudeModelLabel(*defaultRow, id),+ Provider: "anthropic",+ Default: true,+ Thinking: claudeThinkingFromInfo(*defaultRow),+ })+ }+ }+ }+ return models, unavailable+}++// claudeModelID is the identity Multica persists and passes to `--model`:+// what the picker token resolves to, falling back to the token itself.+func claudeModelID(info claudeModelInfo) string {+ if id := strings.TrimSpace(info.ResolvedModel); id != "" {+ return id+ }+ return strings.TrimSpace(info.Value)+}++func claudeModelLabel(info claudeModelInfo, id string) string {+ if label := strings.TrimSpace(info.DisplayName); label != "" {+ return label+ }+ return id+}++// claudeThinkingFromInfo builds the per-model effort catalog from the row's own+// advertisement. This is the discovery path's clearest win over the static one:+// loadClaudeThinkingByModel has to scrape `claude --help` for a global superset+// and then narrow it through claudeModelEffortAllow, a hand-kept table of which+// models really take xhigh. Here each model states its own levels.+//+// DefaultLevel is deliberately left empty. The rows carry no default-effort+// field, and empty already means "the runtime picks, we don't know" — a more+// honest answer than the static path's assumed "medium".+func claudeThinkingFromInfo(info claudeModelInfo) *ModelThinking {+ if !info.SupportsEffort || len(info.SupportedEffortLevels) == 0 {+ return nil+ }+ levels := make([]ThinkingLevel, 0, len(info.SupportedEffortLevels))+ for _, value := range info.SupportedEffortLevels {+ value = strings.TrimSpace(value)+ if value == "" {+ continue+ }+ label, ok := claudeEffortLabel[value]+ if !ok {+ // A level this daemon has not been taught yet. Show it raw rather+ // than hide it — the CLI is the authority on what it accepts.+ label = strings.ToUpper(value[:1]) + value[1:]+ }+ levels = append(levels, ThinkingLevel{Value: value, Label: label})+ }+ if len(levels) == 0 {+ return nil+ }+ return &ModelThinking{SupportedLevels: levels}+}diff --git a/server/pkg/agent/claude_models_test.go b/server/pkg/agent/claude_models_test.gonew file mode 100644index 0000000000..227874bb95--- /dev/null+++ b/server/pkg/agent/claude_models_test.go@@ -0,0 +1,551 @@+package agent++import (+ "context"+ "os"+ "path/filepath"+ "reflect"+ "runtime"+ "strings"+ "testing"+)++// The two fixtures under testdata are verbatim stdout from a real+// `claude --print --input-format stream-json --output-format stream-json`+// answering our list_models control request. They are the whole point of+// MUL-6961 and are captured, not written by hand:+//+// - 2.1.258 offers Fable 5.1 as a normal selectable row.+// - 2.1.246 — the build whose 400 opened the issue — does not offer it at+// all. It reports a disabled row instead, carrying the upstream remedy+// ("Update to 2.1.255+ to use Fable 5.1"). That row is the reason Multica+// does not need a per-model minimum-version table: the CLI already knows.+func loadClaudeListModelsFixture(t *testing.T, version string) []byte {+ t.Helper()+ raw, err := os.ReadFile(filepath.Join("testdata", "claude-code-"+version+"-list-models.jsonl"))+ if err != nil {+ t.Fatalf("read fixture: %v", err)+ }+ return raw+}++// TestClaudeListModelsArgs_Pinned locks the discovery argv. Every element is+// load-bearing and none is obvious from the call site, which is exactly when a+// pin earns its keep — dropping --verbose or the input format silently turns+// the probe into a session that never answers.+func TestClaudeListModelsArgs_Pinned(t *testing.T) {+ t.Parallel()+ want := []string{+ "--print",+ "--verbose",+ "--input-format", "stream-json",+ "--output-format", "stream-json",+ "--strict-mcp-config",+ }+ if !reflect.DeepEqual(claudeListModelsArgs, want) {+ t.Fatalf("claudeListModelsArgs drifted: got %v, want %v", claudeListModelsArgs, want)+ }+ // A model flag here would make discovery report the catalog for one model+ // instead of the account's, and a prompt would bill a real API call.+ for _, arg := range claudeListModelsArgs {+ if arg == "--model" || arg == "-p" {+ t.Errorf("discovery argv must not pin a model or pass a prompt: %v", claudeListModelsArgs)+ }+ }+}++func TestParseClaudeModelCatalog_RealCLIOutput(t *testing.T) {+ t.Parallel()+ infos, err := parseClaudeModelCatalog(loadClaudeListModelsFixture(t, "2.1.258"))+ if err != nil {+ t.Fatalf("parseClaudeModelCatalog: %v", err)+ }+ if len(infos) != 5 {+ t.Fatalf("got %d rows, want 5", len(infos))+ }+ if infos[0].Value != claudeDefaultModelValue {+ t.Errorf("first row = %q, want the %q sentinel", infos[0].Value, claudeDefaultModelValue)+ }+ if infos[2].ResolvedModel != "claude-fable-5-1" {+ t.Errorf("fable row resolved to %q, want claude-fable-5-1", infos[2].ResolvedModel)+ }+}++// TestParseClaudeModelCatalog_SkipsUnrelatedLines proves the parser reads a+// stream rather than a single document: stdout is shared with whatever else the+// session prints, so noise before the answer must not be mistaken for failure.+func TestParseClaudeModelCatalog_SkipsUnrelatedLines(t *testing.T) {+ t.Parallel()+ answer := string(loadClaudeListModelsFixture(t, "2.1.258"))+ raw := "not json at all\n" ++ `{"type":"system","subtype":"init","session_id":"x"}` + "\n" ++ `{"type":"control_response","response":{"subtype":"success","request_id":"someone-else","response":{"models":[]}}}` + "\n" ++ answer+ infos, err := parseClaudeModelCatalog([]byte(raw))+ if err != nil {+ t.Fatalf("parseClaudeModelCatalog: %v", err)+ }+ if len(infos) != 5 {+ t.Fatalf("got %d rows, want 5 — the reply was not matched by request id", len(infos))+ }+}++// TestParseClaudeModelCatalog_ErrorSubtype covers the old-CLI path. This is the+// reply every build without list_models sends, and it is why discovery needs no+// version gate: the failure is explicit, immediate, and cheap.+func TestParseClaudeModelCatalog_ErrorSubtype(t *testing.T) {+ t.Parallel()+ raw := `{"type":"control_response","response":{"subtype":"error","request_id":"multica-list-models","error":"Unsupported control request subtype: list_models"}}`+ _, err := parseClaudeModelCatalog([]byte(raw))+ if err == nil {+ t.Fatal("expected an error for an error-subtype response")+ }+ if !strings.Contains(err.Error(), "Unsupported control request subtype") {+ t.Errorf("error should quote the runtime verbatim, got %q", err)+ }+}++func TestParseClaudeModelCatalog_NoResponse(t *testing.T) {+ t.Parallel()+ for name, raw := range map[string]string{+ "empty": "",+ "junk": "hello\nworld\n",+ "wrong id": `{"type":"control_response","response":{"subtype":"success","request_id":"other","response":{"models":[]}}}`,+ } {+ if _, err := parseClaudeModelCatalog([]byte(raw)); err == nil {+ t.Errorf("%s: expected an error, got nil", name)+ }+ }+}++// TestClaudeModelsFromInfos_CurrentCLI pins the whole projection against real+// 2.1.258 output: the `default` sentinel folds into a badge rather than+// becoming a pickable row, the two rows resolving to Opus collapse to one, and+// the context-window tag survives because `claude-opus-5[1m]` is what the CLI+// would actually run for that row.+func TestClaudeModelsFromInfos_CurrentCLI(t *testing.T) {+ t.Parallel()+ infos, err := parseClaudeModelCatalog(loadClaudeListModelsFixture(t, "2.1.258"))+ if err != nil {+ t.Fatalf("parseClaudeModelCatalog: %v", err)+ }+ models, unavailable := claudeModelsFromInfos(infos)+ if len(unavailable) != 0 {+ t.Errorf("a current CLI should report nothing unavailable, got %+v", unavailable)+ }++ wantIDs := []string{+ "claude-opus-5[1m]",+ "claude-fable-5-1",+ "claude-sonnet-5",+ "claude-haiku-4-5-20251001",+ }+ gotIDs := make([]string, 0, len(models))+ for _, m := range models {+ gotIDs = append(gotIDs, m.ID)+ }+ if !reflect.DeepEqual(gotIDs, wantIDs) {+ t.Fatalf("catalog ids = %v, want %v", gotIDs, wantIDs)+ }++ if models[0].Label != "Opus (1M context)" {+ t.Errorf("opus label = %q, want the row's own display name", models[0].Label)+ }+ if !models[0].Default {+ t.Error("the model the `default` row resolves to should carry the Default badge")+ }+ for _, m := range models[1:] {+ if m.Default {+ t.Errorf("%s must not be flagged default; only one entry may be", m.ID)+ }+ }+ for _, m := range models {+ if m.Provider != "anthropic" {+ t.Errorf("%s provider = %q, want anthropic", m.ID, m.Provider)+ }+ }++ // Effort levels come from the row itself, replacing the `claude --help`+ // scrape plus the hand-kept claudeModelEffortAllow table.+ opus := models[0]+ if opus.Thinking == nil {+ t.Fatal("opus should advertise a thinking catalog")+ }+ gotLevels := make([]string, 0, len(opus.Thinking.SupportedLevels))+ for _, l := range opus.Thinking.SupportedLevels {+ gotLevels = append(gotLevels, l.Value)+ }+ if want := []string{"low", "medium", "high", "xhigh", "max"}; !reflect.DeepEqual(gotLevels, want) {+ t.Errorf("opus levels = %v, want %v", gotLevels, want)+ }+ // The rows carry no default-effort field, and inventing one is what the+ // static path did. Empty means "the runtime decides".+ if opus.Thinking.DefaultLevel != "" {+ t.Errorf("DefaultLevel = %q, want empty", opus.Thinking.DefaultLevel)+ }+ // Haiku advertises no effort support at all, so it must get no picker.+ if haiku := models[3]; haiku.Thinking != nil {+ t.Errorf("haiku advertises no effort support; Thinking should be nil, got %+v", haiku.Thinking)+ }+}++// TestClaudeModelsFromInfos_OldCLIDisabledRow is the regression this whole+// change exists for. On 2.1.246 the catalog must NOT offer Fable 5.1 as+// selectable — that combination is the guaranteed 400 from the issue — and must+// still tell the user it exists and how to reach it.+func TestClaudeModelsFromInfos_OldCLIDisabledRow(t *testing.T) {+ t.Parallel()+ infos, err := parseClaudeModelCatalog(loadClaudeListModelsFixture(t, "2.1.246"))+ if err != nil {+ t.Fatalf("parseClaudeModelCatalog: %v", err)+ }+ models, unavailable := claudeModelsFromInfos(infos)++ // The selectable list is the one every consumer reads — the picker, the+ // builder, the capability lookups, and any client too old to know about+ // unavailable rows. Nothing unrunnable may be in it.+ for _, m := range models {+ if m.ID == "claude-fable-5-1" || m.ID == "cc-update-required-1" {+ t.Fatalf("%s must never be selectable on 2.1.246: the run 400s", m.ID)+ }+ }++ if len(unavailable) != 1 {+ t.Fatalf("got %d unavailable rows, want 1: %+v", len(unavailable), unavailable)+ }+ if unavailable[0].Label != "Fable 5.1 (disabled)" {+ t.Errorf("unavailable label = %q", unavailable[0].Label)+ }+ if unavailable[0].Reason != "Update to 2.1.255+ to use Fable 5.1" {+ t.Errorf("unavailable reason = %q, want the runtime's own upgrade hint", unavailable[0].Reason)+ }+ // Fable 5 is the model this CLI *can* run, and it stays selectable.+ found := false+ for _, m := range models {+ if m.ID == "claude-fable-5" {+ found = true+ }+ }+ if !found {+ t.Error("claude-fable-5 should remain selectable on 2.1.246")+ }+}++// TestClaudeModelsFromInfos_DefaultWithNoSiblingRow covers the org-restricted+// shape where `default` resolves to a model no other row names.+//+// Dropping it costs more than one picker entry. ValidateThinkingLevelWith+// resolves an empty model — "follow the CLI default", which is what most agents+// are configured with — by looking for the catalog entry flagged Default, and+// fails closed when there is none. With no such entry every default-model task+// would silently lose its configured effort.+func TestClaudeModelsFromInfos_DefaultWithNoSiblingRow(t *testing.T) {+ t.Parallel()+ models, unavailable := claudeModelsFromInfos([]claudeModelInfo{+ {+ Value: "default", ResolvedModel: "claude-sonnet-5",+ DisplayName: "Default (recommended)",+ SupportsEffort: true, SupportedEffortLevels: []string{"low", "high"},+ },+ {Value: "haiku", ResolvedModel: "claude-haiku-4-5-20251001", DisplayName: "Haiku"},+ })+ if len(unavailable) != 0 {+ t.Errorf("nothing here is unavailable, got %+v", unavailable)+ }++ var def *Model+ for i := range models {+ if models[i].Default {+ def = &models[i]+ }+ }+ if def == nil {+ t.Fatalf("the default model must survive as a real entry, got %+v", models)+ }+ if def.ID != "claude-sonnet-5" {+ t.Errorf("default entry id = %q, want claude-sonnet-5", def.ID)+ }+ // Materialised from the same row, so it keeps that row's capabilities+ // rather than becoming a bare id with no effort picker.+ if def.Thinking == nil || len(def.Thinking.SupportedLevels) != 2 {+ t.Errorf("materialised default lost its effort catalog: %+v", def.Thinking)+ }+ // And it does not displace the row that was already there.+ found := false+ for _, m := range models {+ if m.ID == "claude-haiku-4-5-20251001" {+ found = true+ if m.Default {+ t.Error("only the model the default row resolves to may be badged")+ }+ }+ }+ if !found {+ t.Error("haiku should still be selectable")+ }+}++// TestClaudeModelsFromInfos_DisabledDefaultIsNotMaterialised guards the one case+// where materialising would reintroduce the bug: a default row that is itself+// unrunnable must not be conjured into a selectable model.+func TestClaudeModelsFromInfos_DisabledDefaultIsNotMaterialised(t *testing.T) {+ t.Parallel()+ models, _ := claudeModelsFromInfos([]claudeModelInfo{+ {Value: "default", ResolvedModel: "cc-update-required-1", DisplayName: "Nope", Disabled: true},+ {Value: "haiku", ResolvedModel: "claude-haiku-4-5-20251001", DisplayName: "Haiku"},+ })+ for _, m := range models {+ if m.ID == "cc-update-required-1" {+ t.Fatal("an unrunnable default must never be materialised as selectable")+ }+ }+}++// TestDiscoverClaudeModels_ArgvAndStdin runs the real discovery path against a+// stand-in binary, checking both halves of the contract: the argv the process+// receives, and that the control request actually arrives on its stdin. A probe+// that spawns correctly but never writes the request would hang in production+// and pass a parser-only test.+func TestDiscoverClaudeModels_ArgvAndStdin(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fake binary requires a POSIX shell")+ }+ t.Parallel()++ dir := t.TempDir()+ argvFile := filepath.Join(dir, "argv.txt")+ stdinFile := filepath.Join(dir, "stdin.txt")+ fixture := filepath.Join(dir, "reply.jsonl")+ if err := os.WriteFile(fixture, loadClaudeListModelsFixture(t, "2.1.258"), 0o600); err != nil {+ t.Fatalf("stage fixture: %v", err)+ }+ fake := filepath.Join(dir, "claude")+ script := "#!/bin/sh\n" ++ "printf '%s\\n' \"$@\" > '" + argvFile + "'\n" ++ "cat > '" + stdinFile + "'\n" ++ "cat '" + fixture + "'\n"+ writeTestExecutable(t, fake, []byte(script))++ models, unavailable, err := discoverClaudeModels(context.Background(), Command{Path: fake})+ if err != nil {+ t.Fatalf("discoverClaudeModels: %v", err)+ }+ if len(models) != 4 {+ t.Fatalf("got %d models, want 4", len(models))+ }+ if len(unavailable) != 0 {+ t.Errorf("2.1.258 reports nothing unavailable, got %+v", unavailable)+ }++ gotArgv, err := os.ReadFile(argvFile)+ if err != nil {+ t.Fatalf("read argv: %v", err)+ }+ if got := splitNonEmptyLines(string(gotArgv)); !reflect.DeepEqual(got, claudeListModelsArgs) {+ t.Errorf("fake claude received argv %v, want %v", got, claudeListModelsArgs)+ }++ gotStdin, err := os.ReadFile(stdinFile)+ if err != nil {+ t.Fatalf("read stdin: %v", err)+ }+ if !strings.Contains(string(gotStdin), `"subtype":"list_models"`) {+ t.Errorf("control request never reached stdin, got %q", gotStdin)+ }+ if !strings.Contains(string(gotStdin), claudeListModelsRequestID) {+ t.Errorf("request id missing from stdin, got %q", gotStdin)+ }+ if !strings.HasSuffix(string(gotStdin), "\n") {+ t.Error("request must be newline-terminated or the CLI never parses the line")+ }+}++func TestDiscoverClaudeModels_ErrorPaths(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fake binary requires a POSIX shell")+ }+ t.Parallel()++ for name, body := range map[string]string{+ // The reply an old CLI without list_models sends.+ "unsupported subtype": `echo '{"type":"control_response","response":{"subtype":"error","request_id":"multica-list-models","error":"Unsupported control request subtype: list_models"}}'` + "\n",+ "no reply": "exit 0\n",+ "garbage": "echo 'not json'\n",+ // A well-formed reply with nothing usable must not pass as a catalog.+ "empty catalog": `echo '{"type":"control_response","response":{"subtype":"success","request_id":"multica-list-models","response":{"models":[]}}}'` + "\n",+ // Rows that exist but none of which can be run: the picker would have+ // nothing to offer, so the static list is the better answer.+ "only unavailable rows": `echo '{"type":"control_response","response":{"subtype":"success","request_id":"multica-list-models","response":{"models":[{"value":"cc-update-required-1","resolvedModel":"cc-update-required-1","displayName":"Nope","disabled":true}]}}}'` + "\n",+ } {+ t.Run(name, func(t *testing.T) {+ t.Parallel()+ fake := filepath.Join(t.TempDir(), "claude")+ writeTestExecutable(t, fake, []byte("#!/bin/sh\ncat > /dev/null\n"+body))+ if _, _, err := discoverClaudeModels(context.Background(), Command{Path: fake}); err == nil {+ t.Fatal("expected an error so the caller falls back to the static catalog")+ }+ })+ }+}++// TestDiscoverClaudeCatalog_FallsBackToStatic covers the degrade path. The+// Fallback flag is the load-bearing part: it is what stops the server caching a+// discovery failure as this runtime's catalog for a day (MUL-5549).+func TestDiscoverClaudeCatalog_FallsBackToStatic(t *testing.T) {+ t.Parallel()+ missing := filepath.Join(t.TempDir(), "definitely-not-installed")++ catalog := discoverClaudeCatalog(context.Background(), Command{Path: missing})+ if !catalog.Fallback {+ t.Error("a static answer after discovery failed must be flagged Fallback")+ }+ if len(catalog.Models) != len(claudeStaticModels()) {+ t.Errorf("got %d models, want the static catalog's %d",+ len(catalog.Models), len(claudeStaticModels()))+ }+}++func TestDiscoverClaudeCatalog_LiveResultIsAuthoritative(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fake binary requires a POSIX shell")+ }+ t.Parallel()++ dir := t.TempDir()+ fixture := filepath.Join(dir, "reply.jsonl")+ if err := os.WriteFile(fixture, loadClaudeListModelsFixture(t, "2.1.246"), 0o600); err != nil {+ t.Fatalf("stage fixture: %v", err)+ }+ fake := filepath.Join(dir, "claude")+ writeTestExecutable(t, fake, []byte("#!/bin/sh\ncat > /dev/null\ncat '"+fixture+"'\n"))++ catalog := discoverClaudeCatalog(context.Background(), Command{Path: fake})+ if catalog.Fallback {+ t.Error("a live catalog must not be flagged Fallback — the server should cache it")+ }+ for _, m := range catalog.Models {+ if m.ID == "claude-fable-5-1" {+ t.Fatal("2.1.246's live catalog must not contain claude-fable-5-1")+ }+ }+}++// TestDiscoverClaudeCatalog_RemembersUnsupported is the fix for the "one cheap+// round trip" claim that was not true.+//+// Every Claude task carrying a thinking_level loads the catalog before it+// starts, and cachedDiscovery refuses to memoise a fallback — so on a CLI too+// old to answer list_models, the probe ran once per task forever. Once the+// binary has said it does not know the request, we stop asking it.+func TestDiscoverClaudeCatalog_RemembersUnsupported(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fake binary requires a POSIX shell")+ }+ // Not parallel: mutates the package-level capability cache.+ resetClaudeCapabilityCacheForTests()+ t.Cleanup(resetClaudeCapabilityCacheForTests)++ dir := t.TempDir()+ countFile := filepath.Join(dir, "probes.txt")+ fake := filepath.Join(dir, "claude")+ // Counts only real probes: the static fallback also runs --version and+ // --help (for the effort superset), and those are not what is being bounded.+ script := "#!/bin/sh\n" ++ "if [ \"$1\" != \"--print\" ]; then echo '2.1.100 (Claude Code)'; exit 0; fi\n" ++ "cat > /dev/null\n" ++ "echo x >> '" + countFile + "'\n" ++ `echo '{"type":"control_response","response":{"subtype":"error","request_id":"multica-list-models",` ++ `"error":"Unsupported control request subtype: list_models"}}'` + "\n"+ writeTestExecutable(t, fake, []byte(script))++ cmd := Command{Path: fake}+ for i := 0; i < 3; i++ {+ catalog := discoverClaudeCatalog(context.Background(), cmd)+ if !catalog.Fallback {+ t.Fatalf("round %d: an old CLI must degrade to the flagged static catalog", i)+ }+ if len(catalog.Models) == 0 {+ t.Fatalf("round %d: the fallback must still be usable", i)+ }+ }++ probes := 0+ if data, err := os.ReadFile(countFile); err == nil {+ probes = len(splitNonEmptyLines(string(data)))+ }+ if probes != 1 {+ t.Errorf("probed %d times across 3 catalog loads, want 1 — the "++ "unsupported answer is a property of the binary, not a bad moment", probes)+ }+}++// TestDiscoverClaudeCatalog_DoesNotRememberTransientFailures is the other half+// of the contract. Caching a timeout or a crash would turn one bad moment into+// ten minutes of static catalog on a CLI that can actually answer.+func TestDiscoverClaudeCatalog_DoesNotRememberTransientFailures(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fake binary requires a POSIX shell")+ }+ resetClaudeCapabilityCacheForTests()+ t.Cleanup(resetClaudeCapabilityCacheForTests)++ dir := t.TempDir()+ countFile := filepath.Join(dir, "probes.txt")+ fake := filepath.Join(dir, "claude")+ script := "#!/bin/sh\n" ++ "if [ \"$1\" != \"--print\" ]; then echo '2.1.258 (Claude Code)'; exit 0; fi\n" ++ "cat > /dev/null\n" ++ "echo x >> '" + countFile + "'\n" ++ "echo 'garbage that is not a control response'\n"+ writeTestExecutable(t, fake, []byte(script))++ cmd := Command{Path: fake}+ for i := 0; i < 3; i++ {+ if catalog := discoverClaudeCatalog(context.Background(), cmd); !catalog.Fallback {+ t.Fatalf("round %d: expected a fallback catalog", i)+ }+ }++ data, err := os.ReadFile(countFile)+ if err != nil {+ t.Fatalf("read probe count: %v", err)+ }+ if probes := len(splitNonEmptyLines(string(data))); probes != 3 {+ t.Errorf("probed %d times, want 3 — a transient failure must stay retryable", probes)+ }+}++// TestValidateThinkingLevel_TaggedCatalogID guards the capability lookup against+// the context-window tag discovery now puts in catalog ids. Without normalising+// the catalog side, `claude-opus-5[1m]` never matches the stripped target and+// every effort level fails closed — the daemon would silently drop --effort.+func TestValidateThinkingLevel_TaggedCatalogID(t *testing.T) {+ t.Parallel()+ catalog := Catalog{Models: []Model{{+ ID: "claude-opus-5[1m]",+ Label: "Opus (1M context)",+ Provider: "anthropic",+ Thinking: &ModelThinking{SupportedLevels: []ThinkingLevel{+ {Value: "low"}, {Value: "medium"}, {Value: "high"}, {Value: "xhigh"}, {Value: "max"},+ }},+ }}}+ load := func() (Catalog, error) { return catalog, nil }++ for _, model := range []string{"claude-opus-5[1m]", "claude-opus-5"} {+ ok, err := ValidateThinkingLevelWith(load, "claude", model, "xhigh")+ if err != nil {+ t.Fatalf("%s: %v", model, err)+ }+ if !ok {+ t.Errorf("%s: xhigh should validate against the tagged catalog entry", model)+ }+ }++ ok, err := ValidateThinkingLevelWith(load, "claude", "claude-opus-5", "nonsense")+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if ok {+ t.Error("a level the catalog does not advertise must still fail closed")+ }+}diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.goindex ad8ebb907d..a90a964c7c 100644--- a/server/pkg/agent/models.go+++ b/server/pkg/agent/models.go@@ -46,6 +46,29 @@ type Model struct {Thinking *ModelThinking `json:"thinking,omitempty"`}+// UnavailableModel is a model the runtime named but will not run on this host —+// today only Claude Code, reporting one that needs a newer CLI than the+// installed one. Reason is the runtime's own remedy ("Update to 2.1.255+ to use+// Fable 5.1"), forwarded verbatim so the copy stays right without Multica+// tracking upstream version floors.+//+// It is a distinct type, and travels in a distinct list, precisely so it can+// never be mistaken for something selectable. Marking such a row with a flag+// inside the models list was the first attempt and it was wrong twice over:+// every consumer that did not learn the flag (the inspector picker, the agent+// builder) kept offering it, and — the part a flag cannot fix — an already+// installed desktop client does not know the field at all, so it would render+// the row as an ordinary model and persist a model id the CLI rejects. Keeping+// the two lists separate makes old clients correct by construction, since they+// only ever read `models` (MUL-6961).+type UnavailableModel struct {+ ID string `json:"id"`+ Label string `json:"label"`+ // Reason is display copy, not a machine contract: it comes from the+ // runtime and may be empty when it offered none.+ Reason string `json:"reason,omitempty"`+}+// ModelServiceTier is one runtime-native execution tier advertised for a// model. ID is sent back to the provider protocol unchanged; Name and// Description are display copy owned by the runtime catalog.@@ -84,6 +107,11 @@ type ThinkingLevel struct {// plus whether they were actually discovered.type Catalog struct {Models []Model+ // Unavailable carries models the runtime named but will not run here. It is+ // deliberately NOT part of Models: every capability lookup in this package+ // walks Models, so keeping these out is what makes an unrunnable model fail+ // closed everywhere without each lookup having to remember a flag.+ Unavailable []UnavailableModel// Fallback reports that discovery did not succeed and Models is a static// stand-in rather than the runtime's real catalog.//@@ -109,8 +137,9 @@ func discovered(models []Model, err error) (Catalog, error) {// modelCache memoizes dynamic discovery calls so repeated UI loads// don't re-shell the agent CLI. Entries expire after cacheTTL.type modelCacheEntry struct {- models []Model- expiresAt time.Time+ models []Model+ unavailable []UnavailableModel+ expiresAt time.Time}var (@@ -122,15 +151,14 @@ const modelCacheTTL = 60 * time.Second// ListModels returns the models supported by the given agent provider.// For providers with a known static catalog it returns the baked-in-// list; for providers with a CLI discovery mechanism (codex, opencode,-// pi, openclaw) it shells out with caching and falls back where the+// list; for providers with a CLI discovery mechanism (claude, codex,+// opencode, pi, openclaw) it shells out with caching and falls back where the// provider has a safe static catalog.//-// For claude, codex, opencode, pi, and kimi, the catalog is augmented with-// per-model thinking-level options discovered from the local CLI. Codex-// discovery failures fall back to a model + thinking snapshot; providers-// without a safe fallback leave Thinking nil, which makes the UI hide the-// thinking picker.+// For claude, codex, opencode, pi, and kimi, the catalog carries per-model+// thinking-level options taken from the local CLI. Claude and Codex discovery+// failures fall back to a model + thinking snapshot; providers without a safe+// fallback leave Thinking nil, which makes the UI hide the thinking picker.//// runtimeCmd lets the caller point at a non-default binary; pass the zero// Command to use the provider's default name on PATH. Its launch prefix — a@@ -156,11 +184,9 @@ func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (C}switch providerType {case "claude":- models := claudeStaticModels()- annotateClaudeThinking(ctx, models, runtimeCmd)- // Claude's catalog is static by design, not by failure: there is no- // discovery step to fall back from, so this is authoritative.- return Catalog{Models: models}, nil+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discoverClaudeCatalog(ctx, runtimeCmd), nil+ })case "codex":return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {return discovered(discoverCodexModels(ctx, runtimeCmd), nil)@@ -482,9 +508,9 @@ func modelHasKnownPrefix(model string) bool {func cachedDiscovery(key string, fn func() (Catalog, error)) (Catalog, error) {modelCacheMu.Lock()if entry, ok := modelCache[key]; ok && time.Now().Before(entry.expiresAt) {- out := entry.models+ out, unavailable := entry.models, entry.unavailablemodelCacheMu.Unlock()- return Catalog{Models: out}, nil+ return Catalog{Models: out, Unavailable: unavailable}, nil}modelCacheMu.Unlock()@@ -509,7 +535,11 @@ func cachedDiscovery(key string, fn func() (Catalog, error)) (Catalog, error) {}modelCacheMu.Lock()- modelCache[key] = modelCacheEntry{models: catalog.Models, expiresAt: time.Now().Add(modelCacheTTL)}+ modelCache[key] = modelCacheEntry{+ models: catalog.Models,+ unavailable: catalog.Unavailable,+ expiresAt: time.Now().Add(modelCacheTTL),+ }modelCacheMu.Unlock()return catalog, nil}diff --git a/server/pkg/agent/testdata/claude-code-2.1.246-list-models.jsonl b/server/pkg/agent/testdata/claude-code-2.1.246-list-models.jsonlnew file mode 100644index 0000000000..8858b387ea--- /dev/null+++ b/server/pkg/agent/testdata/claude-code-2.1.246-list-models.jsonl@@ -0,0 +1 @@+{"type":"control_response","response":{"subtype":"success","request_id":"multica-list-models","response":{"models":[{"value":"default","resolvedModel":"claude-opus-5[1m]","displayName":"Default (recommended)","description":"Opus 5 with 1M context · Best for everyday, complex tasks","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsFastMode":true,"supportsAutoMode":true},{"value":"opus[1m]","resolvedModel":"claude-opus-5[1m]","displayName":"Opus (1M context)","description":"Opus 5 with 1M context · Best for everyday, complex tasks","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsFastMode":true,"supportsAutoMode":true},{"value":"claude-fable-5[1m]","resolvedModel":"claude-fable-5","displayName":"Fable","description":"Fable 5 · Most capable for your hardest and longest-running tasks","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true},{"value":"sonnet","resolvedModel":"claude-sonnet-5","displayName":"Sonnet","description":"Sonnet 5 · Efficient for routine tasks","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true},{"value":"haiku","resolvedModel":"claude-haiku-4-5-20251001","displayName":"Haiku","description":"Haiku 4.5 · Fastest for quick answers"},{"value":"cc-update-required-1","resolvedModel":"cc-update-required-1","displayName":"Fable 5.1 (disabled)","description":"Update to 2.1.255+ to use Fable 5.1","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"disabled":true}]}}}diff --git a/server/pkg/agent/testdata/claude-code-2.1.258-list-models.jsonl b/server/pkg/agent/testdata/claude-code-2.1.258-list-models.jsonlnew file mode 100644index 0000000000..5c2449003b--- /dev/null+++ b/server/pkg/agent/testdata/claude-code-2.1.258-list-models.jsonl@@ -0,0 +1 @@+{"type":"control_response","response":{"subtype":"success","request_id":"multica-list-models","response":{"models":[{"value":"default","resolvedModel":"claude-opus-5[1m]","displayName":"Default (recommended)","description":"Opus 5 with 1M context · Best for everyday, complex tasks","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsFastMode":true,"supportsAutoMode":true},{"value":"opus[1m]","resolvedModel":"claude-opus-5[1m]","displayName":"Opus (1M context)","description":"Opus 5 with 1M context · Best for everyday, complex tasks","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsFastMode":true,"supportsAutoMode":true},{"value":"claude-fable-5-1[1m]","resolvedModel":"claude-fable-5-1","displayName":"Fable","description":"Fable 5.1 · Most capable for your hardest and longest-running tasks","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true},{"value":"sonnet","resolvedModel":"claude-sonnet-5","displayName":"Sonnet","description":"Sonnet 5 · Efficient for routine tasks","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true},{"value":"haiku","resolvedModel":"claude-haiku-4-5-20251001","displayName":"Haiku","description":"Haiku 4.5 · Fastest for quick answers"}]}}}diff --git a/server/pkg/agent/thinking.go b/server/pkg/agent/thinking.goindex b9a85f3a4c..80095e5ae2 100644--- a/server/pkg/agent/thinking.go+++ b/server/pkg/agent/thinking.go@@ -703,7 +703,13 @@ func ValidateThinkingLevelWith(loadCatalog func() (Catalog, error), providerType}}for _, m := range models {- if m.ID != target {+ // Normalise the catalog side too, not just the requested model. Claude+ // discovery reports what the CLI would really run, and that includes+ // the context-window tag (`claude-opus-5[1m]`), while target has+ // already had it stripped. Comparing raw IDs would miss every tagged+ // entry and fail the level closed, silently dropping the user's+ // --effort (MUL-6961).+ if modelIDForCapabilityLookup(providerType, m.ID) != target {continue}if m.Thinking == nil {