Skip to content

🙌 OpenHands: AI-Driven Development

feat(acp): take ACP model lists from the agent instead of hardcoding them (#18131)

simonrosenberg738b23d2d63c
diff --git a/__tests__/api/acp-service/acp-service.api.test.ts b/__tests__/api/acp-service/acp-service.api.test.ts
index 8bc8005a71..a309bf1c47 100644
--- a/__tests__/api/acp-service/acp-service.api.test.ts
+++ b/__tests__/api/acp-service/acp-service.api.test.ts
@@ -8,10 +8,14 @@ import AcpService from "#/api/acp-service/acp-service.api";
// Capture the command the service runs and control the BashOutput it sees.
const executeCommand = vi.hoisted(() => vi.fn());
+const discoverModels = vi.hoisted(() => vi.fn());
vi.mock("@openhands/typescript-client/clients", () => ({
BashClient: class {
executeCommand = executeCommand;
},
+ ACPClient: class {
+ discoverModels = discoverModels;
+ },
}));
vi.mock("#/api/agent-server-client-options", () => ({
getAgentServerClientOptions: () => ({
@@ -175,3 +179,23 @@ describe("AcpService.getAuthStatus", () => {
expect(executeCommand).not.toHaveBeenCalled();
});
});
+
+describe("AcpService.discoverModels", () => {
+ it("sends the built-in agent and the saved secrets by reference", async () => {
+ discoverModels.mockResolvedValue({ current_model_id: "default" });
+
+ await expect(
+ AcpService.discoverModels("claude-code", ["ANTHROPIC_API_KEY"]),
+ ).resolves.toEqual({ current_model_id: "default" });
+
+ expect(discoverModels).toHaveBeenCalledWith({
+ agent_settings: { agent_kind: "acp", acp_server: "claude-code" },
+ secrets: {
+ ANTHROPIC_API_KEY: expect.objectContaining({
+ kind: "LookupSecret",
+ url: "/api/settings/secrets/ANTHROPIC_API_KEY",
+ }),
+ },
+ });
+ });
+});
diff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.ts
index 19dd6192e1..344725514d 100644
--- a/__tests__/api/agent-server-adapter.test.ts
+++ b/__tests__/api/agent-server-adapter.test.ts
@@ -1995,37 +1995,32 @@ describe("buildStartConversationRequest — ACP discriminator", () => {
expect(payload.agent_settings.acp_command).toEqual([]);
});
- it("seeds the provider default when settings contains an empty acp_model", () => {
- // The form may carry an empty string after a user clears the model
- // input. Older behavior left ``acp_model`` absent and relied on the
- // agent-server's own default; the registry-default path
- // (resolveEffectiveAcpModel) is now authoritative on Canvas's side,
- // so an empty string resolves to the provider's ``default_model``
- // before the request leaves the client. Keeps the displayed Settings
- // → Agent default in sync with what the runtime actually starts.
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- schema_version: 1,
- agent_kind: "acp",
- acp_server: "claude-code",
- acp_command: [],
- acp_model: "",
+ it.each([
+ ["claude-code", undefined],
+ ["gemini-cli", ACP_VERTEX_SAFE_MODEL],
+ ])(
+ "leaves an empty %s acp_model to the agent unless Canvas prefers one",
+ (acpServer, expected) => {
+ const payload = buildStartConversationRequest({
+ settings: {
+ ...DEFAULT_SETTINGS,
+ agent_settings: {
+ schema_version: 1,
+ agent_kind: "acp",
+ acp_server: acpServer,
+ acp_command: [],
+ acp_model: "",
+ },
},
- },
- }) as {
- agent_settings: Record<string, unknown> & { acp_model?: unknown };
- };
+ }) as {
+ agent_settings: Record<string, unknown> & { acp_model?: unknown };
+ };
- expect(payload.agent_settings.acp_model).toBe("opus[1m]");
- });
+ expect(payload.agent_settings.acp_model).toBe(expected);
+ },
+ );
it("omits acp_model for the custom preset when none is configured", () => {
- // The Custom preset has no registered ``default_model``, so an empty
- // ``acp_model`` falls through to ``undefined`` — the agent-server then
- // applies its own default. Distinct from the built-in providers
- // which substitute their registry default.
const payload = buildStartConversationRequest({
settings: {
...DEFAULT_SETTINGS,
diff --git a/__tests__/api/agent-server-conversation-service-regressions.test.ts b/__tests__/api/agent-server-conversation-service-regressions.test.ts
index a1fab882f1..6869ebec05 100644
--- a/__tests__/api/agent-server-conversation-service-regressions.test.ts
+++ b/__tests__/api/agent-server-conversation-service-regressions.test.ts
@@ -751,6 +751,7 @@ describe("AgentServerConversationService", () => {
launched_agent_profile: {
agent_profile_id: "profile-1",
revision: 3,
+ secret_refs: ["OPENAI_API_KEY"],
},
},
],
@@ -764,9 +765,33 @@ describe("AgentServerConversationService", () => {
expect(conversation?.launched_agent_profile).toEqual({
agent_profile_id: "profile-1",
revision: 3,
+ secret_refs: ["OPENAI_API_KEY"],
});
});
+ it("reads a launched Agent Profile without a secret scope as unscoped", async () => {
+ mockHttpGet.mockResolvedValue({
+ data: [
+ {
+ id: "conv-profile",
+ created_at: "2024-01-01",
+ updated_at: "2024-01-01",
+ launched_agent_profile: {
+ agent_profile_id: "profile-1",
+ revision: 3,
+ },
+ },
+ ],
+ });
+
+ const [conversation] =
+ await AgentServerConversationService.batchGetAppConversations([
+ "conv-profile",
+ ]);
+
+ expect(conversation?.launched_agent_profile?.secret_refs).toBeNull();
+ });
+
it("carries well-formed wire tags through to AppConversation.tags", async () => {
mockHttpGet.mockResolvedValue({
data: [
diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.ts
index 44f0b2bb0a..9a179ffef7 100644
--- a/__tests__/api/agent-server-conversation-service.test.ts
+++ b/__tests__/api/agent-server-conversation-service.test.ts
@@ -1136,6 +1136,35 @@ describe("AgentServerConversationService", () => {
expect(conversation?.llm_model).toBe("Claude Opus 4.7");
});
+ it("carries the models an ACP session reported", async () => {
+ mockHttpGet.mockResolvedValue({
+ data: [
+ {
+ id: "conv-acp-live-models",
+ created_at: "2024-01-01",
+ updated_at: "2024-01-01",
+ agent: { kind: "ACPAgent", acp_server: "codex" },
+ current_model_id: "gpt-6-astra",
+ available_models: [
+ { model_id: "gpt-6-astra", name: "GPT-6 Astra" },
+ { model_id: "gpt-5.6-sol", name: null, description: "fast" },
+ { name: "no id" },
+ ],
+ },
+ ],
+ });
+
+ const [conversation] =
+ await AgentServerConversationService.batchGetAppConversations([
+ "conv-acp-live-models",
+ ]);
+
+ expect(conversation?.acp_available_models).toEqual([
+ { id: "gpt-6-astra", label: "GPT-6 Astra" },
+ { id: "gpt-5.6-sol", label: "gpt-5.6-sol" },
+ ]);
+ });
+
it("sources acp_server from the agent when the acpserver tag is absent", async () => {
// Profile launches don't stamp the ``acpserver`` tag client-side, so the
// provider identity must survive from ``agent.acp_server`` (SDK #3692)
diff --git a/__tests__/components/features/chat/components/chat-input-model.test.tsx b/__tests__/components/features/chat/components/chat-input-model.test.tsx
index 5153163380..936cb0f078 100644
--- a/__tests__/components/features/chat/components/chat-input-model.test.tsx
+++ b/__tests__/components/features/chat/components/chat-input-model.test.tsx
@@ -30,6 +30,21 @@ vi.mock("#/hooks/mutation/use-switch-acp-model", () => ({
useSwitchAcpModel: () => ({ mutate: switchAcpModelMutate }),
}));
+// What the session and the agent report; empty unless a test sets them.
+const sessionModelsMock = vi.fn();
+vi.mock("#/hooks/query/use-acp-session-models", () => ({
+ useAcpSessionModels: () => sessionModelsMock(),
+}));
+const discoveryMock = vi.fn();
+vi.mock("#/hooks/query/use-acp-model-discovery", () => ({
+ useAcpModelDiscovery: () => discoveryMock(),
+}));
+
+const CLAUDE_MODELS = [
+ { id: "opus[1m]", label: "Claude Opus (1M)" },
+ { id: "sonnet", label: "Claude Sonnet" },
+];
+
import { ChatInputModel } from "#/components/features/chat/components/chat-input-model";
describe("ChatInputModel", () => {
@@ -42,6 +57,8 @@ describe("ChatInputModel", () => {
// fallback): live ACP model switching is local-only.
useActiveBackendMock.mockReturnValue({ backend: { kind: "local" } });
switchAcpModelMutate.mockReset();
+ sessionModelsMock.mockReturnValue([]);
+ discoveryMock.mockReturnValue({ models: [], defaultModelId: null });
});
it("renders the active conversation's llm_model when present", () => {
@@ -84,6 +101,7 @@ describe("ChatInputModel", () => {
});
it("renders an ACP conversation model and links to Agent settings", () => {
+ sessionModelsMock.mockReturnValue(CLAUDE_MODELS);
useActiveConversationMock.mockReturnValue({
data: {
conversation_id: "test-conversation-id",
@@ -96,8 +114,7 @@ describe("ChatInputModel", () => {
renderWithProviders(<ChatInputModel />);
const model = screen.getByTestId("chat-input-llm-model");
- // ACP surfaces show the provider's human label (matching the conversation
- // list chip), resolved from ``acp_server`` + the raw ``acp_model`` id.
+ // ACP surfaces show the label the session gave the model.
expect(model).toHaveAttribute("title", "Claude Sonnet");
fireEvent.click(model);
expect(screen.getByRole("link")).toHaveAttribute(
@@ -125,6 +142,32 @@ describe("ChatInputModel", () => {
).not.toBeInTheDocument();
});
+ it("does not show another provider's saved model before an ACP conversation reports its own", () => {
+ useActiveConversationMock.mockReturnValue({
+ data: {
+ conversation_id: "test-conversation-id",
+ agent_kind: "acp",
+ acp_server: "codex",
+ llm_model: null,
+ },
+ });
+ useSettingsMock.mockReturnValue({
+ data: {
+ agent_settings: {
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ acp_model: "opus[1m]",
+ },
+ },
+ });
+
+ renderWithProviders(<ChatInputModel />);
+
+ expect(
+ screen.queryByTestId("chat-input-llm-model"),
+ ).not.toBeInTheDocument();
+ });
+
it("falls back to the user's default model from settings when there is no active conversation", () => {
// Arrange — home page render: no conversation yet, but the user has
// a default model configured. The switcher should still show.
@@ -202,13 +245,14 @@ describe("ChatInputModel", () => {
).not.toBeInTheDocument();
});
- it("shows the provider default on the home page when ACP is the default agent and no model is saved", () => {
- // Home-screen gating: no active conversation and no saved ``acp_model``.
- // The next-created conversation will inherit the provider's
- // ``default_model`` (see buildConfiguredAcpAgentSettings), so the picker
- // shows that same default — matching what the runtime will actually
- // start. Picker links to /settings/agent (not /settings) since
- // ``settings.llm_model`` doesn't apply to ACP.
+ it("shows the agent's own default on the home page when no model is saved", () => {
+ // The next conversation starts on the agent's default, so the picker
+ // shows it. It links to Agent settings since ``settings.llm_model``
+ // doesn't apply to ACP.
+ discoveryMock.mockReturnValue({
+ models: CLAUDE_MODELS,
+ defaultModelId: "opus[1m]",
+ });
useActiveConversationMock.mockReturnValue({ data: undefined });
useSettingsMock.mockReturnValue({
data: {
@@ -222,9 +266,6 @@ describe("ChatInputModel", () => {
renderWithProviders(<ChatInputModel />);
const model = screen.getByTestId("chat-input-llm-model");
- // Claude Code's registered default (``opus[1m]``), shown as its
- // human label to match the conversation list chip. See CLAUDE_MODELS in
- // acp-providers.ts.
expect(model).toHaveAttribute("title", "Claude Opus (1M)");
fireEvent.click(model);
expect(screen.getByRole("link")).toHaveAttribute(
@@ -233,7 +274,8 @@ describe("ChatInputModel", () => {
);
});
- it("renders the provider's available models as selectable rows for an ACP conversation", () => {
+ it("renders the session's models as selectable rows for an ACP conversation", () => {
+ sessionModelsMock.mockReturnValue(CLAUDE_MODELS);
useActiveConversationMock.mockReturnValue({
data: {
conversation_id: "test-conversation-id",
@@ -247,8 +289,8 @@ describe("ChatInputModel", () => {
fireEvent.click(screen.getByTestId("chat-input-llm-model"));
- // Every registered Claude Code model is offered as a row, and the running
- // one (sonnet) is marked selected.
+ // Every model the session reported is a row, and the running one
+ // (sonnet) is marked selected.
const selectedRow = screen.getByTestId(
"chat-input-acp-model-option-sonnet",
);
@@ -260,6 +302,7 @@ describe("ChatInputModel", () => {
});
it("live-switches the model when a row is selected in an active ACP conversation", () => {
+ sessionModelsMock.mockReturnValue(CLAUDE_MODELS);
useActiveConversationMock.mockReturnValue({
data: {
conversation_id: "test-conversation-id",
@@ -287,6 +330,10 @@ describe("ChatInputModel", () => {
});
it("persists the choice as the default (conversationId null) in the home ACP case", () => {
+ discoveryMock.mockReturnValue({
+ models: CLAUDE_MODELS,
+ defaultModelId: null,
+ });
useActiveConversationMock.mockReturnValue({ data: undefined });
useSettingsMock.mockReturnValue({
data: {
@@ -308,8 +355,118 @@ describe("ChatInputModel", () => {
});
});
+ it("offers Agent default on the home page and saves no model when it is picked", () => {
+ discoveryMock.mockReturnValue({
+ models: CLAUDE_MODELS,
+ defaultModelId: null,
+ });
+ useActiveConversationMock.mockReturnValue({ data: undefined });
+ useSettingsMock.mockReturnValue({
+ data: {
+ agent_settings: {
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ acp_model: "sonnet",
+ },
+ },
+ });
+
+ renderWithProviders(<ChatInputModel />);
+
+ fireEvent.click(screen.getByTestId("chat-input-llm-model"));
+ const agentDefault = screen.getByTestId(
+ "chat-input-acp-model-option-agent-default",
+ );
+ expect(agentDefault).toHaveTextContent(
+ "SETTINGS$AGENT_MODEL_AGENT_DEFAULT",
+ );
+ fireEvent.click(agentDefault);
+
+ expect(switchAcpModelMutate).toHaveBeenCalledWith({
+ conversationId: null,
+ model: null,
+ });
+ });
+
+ it("marks Agent default, not the model it resolves to, when no model is saved", () => {
+ discoveryMock.mockReturnValue({
+ models: CLAUDE_MODELS,
+ defaultModelId: "opus[1m]",
+ });
+ useActiveConversationMock.mockReturnValue({ data: undefined });
+ useSettingsMock.mockReturnValue({
+ data: {
+ agent_settings: { agent_kind: "acp", acp_server: "claude-code" },
+ },
+ });
+
+ renderWithProviders(<ChatInputModel />);
+
+ fireEvent.click(screen.getByTestId("chat-input-llm-model"));
+ const agentDefault = screen.getByTestId(
+ "chat-input-acp-model-option-agent-default",
+ );
+ expect(agentDefault).toHaveTextContent(
+ "SETTINGS$AGENT_MODEL_AGENT_DEFAULT_IS",
+ );
+ expect(agentDefault).toHaveClass("bg-interactive-hover");
+ const opus = screen.getByTestId("chat-input-acp-model-option-opus[1m]");
+ expect(opus).not.toHaveClass("bg-interactive-hover");
+
+ // Picking the default's model by name pins it.
+ fireEvent.click(opus);
+ expect(switchAcpModelMutate).toHaveBeenCalledWith({
+ conversationId: null,
+ model: "opus[1m]",
+ });
+ });
+
+ it("does not offer Agent default inside a conversation", () => {
+ sessionModelsMock.mockReturnValue(CLAUDE_MODELS);
+ useActiveConversationMock.mockReturnValue({
+ data: {
+ conversation_id: "test-conversation-id",
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ llm_model: "sonnet",
+ },
+ });
+
+ renderWithProviders(<ChatInputModel />);
+
+ fireEvent.click(screen.getByTestId("chat-input-llm-model"));
+ expect(
+ screen.getByTestId("chat-input-acp-model-option-sonnet"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("chat-input-acp-model-option-agent-default"),
+ ).toBeNull();
+ });
+
+ it("does not offer Agent default for Gemini, which keeps its Vertex-safe model", () => {
+ discoveryMock.mockReturnValue({
+ models: [{ id: "gemini-2.5-pro", label: "Gemini 2.5 Pro" }],
+ defaultModelId: "auto",
+ });
+ useActiveConversationMock.mockReturnValue({ data: undefined });
+ useSettingsMock.mockReturnValue({
+ data: { agent_settings: { agent_kind: "acp", acp_server: "gemini-cli" } },
+ });
+
+ renderWithProviders(<ChatInputModel />);
+
+ fireEvent.click(screen.getByTestId("chat-input-llm-model"));
+ expect(
+ screen.getByTestId("chat-input-acp-model-option-gemini-2.5-pro"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("chat-input-acp-model-option-agent-default"),
+ ).toBeNull();
+ });
+
it("offers selectable rows on a cloud backend for ACP conversations (mid-conversation model switching is supported)", () => {
useActiveBackendMock.mockReturnValue({ backend: { kind: "cloud" } });
+ sessionModelsMock.mockReturnValue(CLAUDE_MODELS);
useActiveConversationMock.mockReturnValue({
data: {
conversation_id: "test-conversation-id",
diff --git a/__tests__/components/features/conversation-panel/conversation-card.test.tsx b/__tests__/components/features/conversation-panel/conversation-card.test.tsx
index 18ebc5b573..915e121084 100644
--- a/__tests__/components/features/conversation-panel/conversation-card.test.tsx
+++ b/__tests__/components/features/conversation-panel/conversation-card.test.tsx
@@ -53,6 +53,13 @@ vi.mock("react-i18next", async () => {
};
});
+const useRememberedAcpModels = vi.hoisted(() =>
+ vi.fn((): { id: string; label: string }[] => []),
+);
+vi.mock("#/hooks/use-remembered-acp-models", () => ({
+ useRememberedAcpModels,
+}));
+
vi.mock("#/hooks/use-tracking", () => ({
useTracking: () => ({
trackDownloadVsCodeButtonClicked: vi.fn(),
@@ -1061,10 +1068,11 @@ describe("ConversationCard", () => {
).toBeInTheDocument();
});
- it("shows the provider's picker label for a known model ID", () => {
- // When ``llm_model`` is a registry-known ID, the chip renders the
- // human label ("Claude Opus (1M)") instead of the raw ID — matching
- // what the Settings → Agent picker shows for the same value.
+ it("labels a model with the name the agent last reported for it", () => {
+ useRememberedAcpModels.mockReturnValue([
+ { id: "opus[1m]", label: "Claude Opus (1M)" },
+ ]);
+
renderWithProviders(
<ConversationCard
title="Conversation 1"
@@ -1080,6 +1088,32 @@ describe("ConversationCard", () => {
const chip = screen.getByTestId("conversation-card-agent-chip");
expect(chip).toHaveTextContent("Claude Opus (1M)");
expect(chip).toHaveAttribute("title", "Claude Code · Claude Opus (1M)");
+ expect(useRememberedAcpModels).toHaveBeenCalledWith("claude-code");
+ useRememberedAcpModels.mockReturnValue([]);
+ });
+
+ it("prefers the models the conversation's own session reported", () => {
+ useRememberedAcpModels.mockReturnValue([
+ { id: "opus[1m]", label: "Stale label" },
+ ]);
+
+ renderWithProviders(
+ <ConversationCard
+ title="Conversation 1"
+ selectedRepository={null}
+ lastUpdatedAt="2021-10-01T12:00:00Z"
+ showLlmProfiles
+ agentKind="acp"
+ acpServer="claude-code"
+ llmModel="opus[1m]"
+ acpModels={[{ id: "opus[1m]", label: "Claude Opus (1M)" }]}
+ />,
+ );
+
+ expect(
+ screen.getByTestId("conversation-card-agent-chip"),
+ ).toHaveTextContent("Claude Opus (1M)");
+ useRememberedAcpModels.mockReturnValue([]);
});
it("falls back to the provider display name for an ACP conversation with no model", () => {
diff --git a/__tests__/components/onboarding/choose-agent-step.test.tsx b/__tests__/components/onboarding/choose-agent-step.test.tsx
index 32e81c5035..65295a2e5e 100644
--- a/__tests__/components/onboarding/choose-agent-step.test.tsx
+++ b/__tests__/components/onboarding/choose-agent-step.test.tsx
@@ -180,7 +180,7 @@ describe("ChooseAgentStep", () => {
expect(call.agent_settings_diff).toEqual({ agent_kind: "openhands" });
});
- it("persists an ACP diff matching the registry when Claude Code is selected", async () => {
+ it("persists an ACP diff for Claude Code that leaves the model to the agent", async () => {
const save = vi.spyOn(SettingsService, "saveSettings");
const { onNext } = renderStep("claude-code");
const user = userEvent.setup();
@@ -204,7 +204,8 @@ describe("ChooseAgentStep", () => {
// ``acp_args`` can't survive and concatenate onto the spawn
// command at conversation-create time.
acp_args: [],
- acp_model: "opus[1m]",
+ // No model: Claude Code starts on its own default.
+ acp_model: null,
});
});
diff --git a/__tests__/constants/acp-providers.test.ts b/__tests__/constants/acp-providers.test.ts
index eb47a29456..91f90f8187 100644
--- a/__tests__/constants/acp-providers.test.ts
+++ b/__tests__/constants/acp-providers.test.ts
@@ -7,7 +7,6 @@ import {
buildAcpAgentSettingsDiff,
getAcpCredentialConflicts,
getAcpPreferredDefaultModel,
- getAcpProvider,
getAcpProviderDisplayName,
getAcpProviderSecrets,
} from "#/constants/acp-providers";
@@ -43,7 +42,7 @@ describe("getAcpProviderDisplayName", () => {
});
describe("ACP provider registry", () => {
- it("sources display_name / default_command / models from the SDK, not a local mirror", () => {
+ it("sources display_name / default_command from the SDK, not a local mirror", () => {
// Core invariant of agent-canvas#678: the registry data fields must come
// straight from @openhands/typescript-client's getAcpProvider(), so the
// Python SDK stays the single source of truth. Only the UI-only overlay
@@ -53,52 +52,18 @@ describe("ACP provider registry", () => {
expect(sdk, provider.key).not.toBeNull();
expect(provider.display_name).toBe(sdk!.display_name);
expect(provider.default_command).toEqual([...sdk!.default_command]);
- expect(provider.available_models).toEqual(
- sdk!.available_models.map((m) => ({ id: m.id, label: m.label })),
- );
- expect(provider.default_model).toBe(sdk!.default_model ?? undefined);
+ // Models come from the agent itself, never from a hardcoded list.
+ expect(provider).not.toHaveProperty("available_models");
+ expect(provider).not.toHaveProperty("default_model");
// UI-only overlay stays local.
expect(provider.icon).toBeTruthy();
expect(provider.description_key).toBeTruthy();
}
});
- it("keeps every built-in default model in the UX suggestions", () => {
- // Pi has no default: it picks a model from whichever credential is set.
- for (const provider of ACP_PROVIDERS.filter(({ key }) => key !== "pi")) {
- expect(provider.default_model, provider.key).toBeTruthy();
- expect(provider.available_models, provider.key).toBeTruthy();
- expect(
- provider.available_models?.some(
- (model) => model.id === provider.default_model,
- ),
- provider.key,
- ).toBe(true);
- }
- });
-
- it("does not suggest generic default model placeholders", () => {
- // Model lists are SDK-owned (see ACP_PROVIDERS) — Canvas no longer hand-keeps
- // them. The claude-code registry intentionally offers an id ``default``
- // labeled "Default (recommended)", a legitimate, well-labeled choice. Guard
- // against genuinely empty ids and bare placeholder labels, not the qualified
- // "Default (recommended)" entry.
- for (const provider of ACP_PROVIDERS) {
- for (const model of provider.available_models ?? []) {
- expect(model.id.trim(), provider.key).toBeTruthy();
- expect(
- model.label.trim().toLowerCase(),
- `${provider.key}:${model.id}`,
- ).not.toBe("default");
- }
- }
- });
-
it("seeds built-in ACP diffs with the provider's preferred default model", () => {
- // Preferred default = registry default everywhere except Gemini, where
- // the Vertex-safe override applies (see getAcpPreferredDefaultModel) —
- // EVERY default-model surface must agree on this, including this diff
- // builder's fallback.
+ // EVERY default-model surface must agree with getAcpPreferredDefaultModel,
+ // including this diff builder's fallback.
for (const provider of ACP_PROVIDERS) {
expect(buildAcpAgentSettingsDiff(provider.key)).toMatchObject({
agent_kind: "acp",
@@ -201,15 +166,12 @@ describe("getAcpProviderSecrets — containerized credentials", () => {
});
describe("getAcpPreferredDefaultModel", () => {
- it("overrides Gemini with the Vertex-safe model rather than the registry default", () => {
+ it("overrides Gemini with the Vertex-safe model rather than its own default", () => {
// gemini-cli's own default 404s on many Vertex projects; canvas preselects
// a broadly-available model instead.
expect(getAcpPreferredDefaultModel("gemini-cli")).toBe(
ACP_VERTEX_SAFE_MODEL,
);
- expect(getAcpPreferredDefaultModel("gemini-cli")).not.toBe(
- getAcpProvider("gemini-cli")?.default_model,
- );
});
it("pins a NON-flash Gemini model", () => {
@@ -219,13 +181,10 @@ describe("getAcpPreferredDefaultModel", () => {
expect(ACP_VERTEX_SAFE_MODEL).not.toMatch(/flash/);
});
- it("keeps the registry default for the other providers", () => {
- expect(getAcpPreferredDefaultModel("codex")).toBe(
- getAcpProvider("codex")?.default_model,
- );
- expect(getAcpPreferredDefaultModel("claude-code")).toBe(
- getAcpProvider("claude-code")?.default_model,
- );
+ it("leaves the other providers on their own default", () => {
+ for (const key of ["claude-code", "codex", "pi", "opencode"]) {
+ expect(getAcpPreferredDefaultModel(key), key).toBeNull();
+ }
});
it("returns null for OpenHands / custom / unknown", () => {
diff --git a/__tests__/hooks/mutation/use-switch-acp-model.test.tsx b/__tests__/hooks/mutation/use-switch-acp-model.test.tsx
index a7fb3aa8f1..a7de8d7491 100644
--- a/__tests__/hooks/mutation/use-switch-acp-model.test.tsx
+++ b/__tests__/hooks/mutation/use-switch-acp-model.test.tsx
@@ -167,6 +167,41 @@ describe("useSwitchAcpModel", () => {
});
});
+ it("saves no model into the active ACP profile when Agent default is picked", async () => {
+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({
+ profiles: [{ id: "id-codex", name: "codex", agent_kind: "acp" }],
+ active_agent_profile_id: "id-codex",
+ } as never);
+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
+ profile: {
+ id: "id-codex",
+ name: "codex",
+ revision: 2,
+ agent_kind: "acp",
+ acp_server: "codex",
+ acp_model: "gpt-5.6-terra",
+ },
+ } as never);
+ vi.mocked(AgentProfilesService.saveProfile).mockResolvedValue({
+ name: "codex",
+ message: "saved",
+ } as never);
+
+ const { result } = renderSwitchHook();
+
+ result.current.mutate({ conversationId: null, model: null });
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledWith("codex", {
+ agent_kind: "acp",
+ acp_server: "codex",
+ acp_model: null,
+ });
+ });
+
it("does not persist to agent_settings when the profiles fetch fails", async () => {
// Discovery failure propagates instead of downgrading (#16523): an
// active-profile launch ignores agent_settings, so persisting the pick
diff --git a/__tests__/hooks/query/use-acp-model-discovery.test.tsx b/__tests__/hooks/query/use-acp-model-discovery.test.tsx
new file mode 100644
index 0000000000..2823bd34bb
--- /dev/null
+++ b/__tests__/hooks/query/use-acp-model-discovery.test.tsx
@@ -0,0 +1,261 @@
+import React from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { useAcpModelDiscovery } from "#/hooks/query/use-acp-model-discovery";
+import {
+ acpModelScope,
+ readRememberedAcpModels,
+ rememberAcpModels,
+} from "#/utils/remembered-acp-models";
+
+const backendMock = vi.hoisted(() => ({
+ current: {
+ backend: { id: "local-1", kind: "local" as "local" | "cloud" },
+ orgId: null as string | null,
+ },
+}));
+vi.mock("#/contexts/active-backend-context", () => ({
+ useActiveBackend: () => backendMock.current,
+}));
+
+vi.mock("#/hooks/query/use-get-secrets", () => ({
+ useSearchSecrets: () => ({
+ data: [{ name: "PI_AUTH_JSON" }, { name: "ANTHROPIC_API_KEY" }],
+ isLoading: false,
+ }),
+}));
+
+const discoverModels = vi.hoisted(() => vi.fn());
+vi.mock("#/api/acp-service/acp-service.api", () => ({
+ default: {
+ discoverModels: (...args: unknown[]) => discoverModels(...args),
+ },
+}));
+
+function wrapper({ children }: { children: React.ReactNode }) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
+}
+
+const PI_DISCOVERY = {
+ agent_name: "pi-acp",
+ agent_version: "0.0.33",
+ current_model_id: "anthropic/claude-opus-4-8",
+ available_models: [
+ { model_id: "anthropic/claude-opus-4-8", name: "Claude Opus 4.8" },
+ { model_id: "anthropic/claude-sonnet-5", name: null },
+ ],
+ supports_runtime_model_switch: true,
+ error: null,
+};
+
+const ALL = acpModelScope(null);
+
+const AUTH_REQUIRED = {
+ ...PI_DISCOVERY,
+ current_model_id: null,
+ available_models: [],
+ error: { code: "ACPAuthRequired", detail: "log in first" },
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ window.localStorage.clear();
+ backendMock.current = {
+ backend: { id: "local-1", kind: "local" },
+ orgId: null,
+ };
+});
+
+describe("useAcpModelDiscovery", () => {
+ it("asks the local agent-server with every saved secret", async () => {
+ discoverModels.mockResolvedValue(PI_DISCOVERY);
+
+ const { result } = renderHook(() => useAcpModelDiscovery("pi"), {
+ wrapper,
+ });
+
+ await waitFor(() =>
+ expect(result.current.defaultModelId).toBe("anthropic/claude-opus-4-8"),
+ );
+ expect(discoverModels).toHaveBeenCalledWith("pi", [
+ "ANTHROPIC_API_KEY",
+ "PI_AUTH_JSON",
+ ]);
+ const models = [
+ { id: "anthropic/claude-opus-4-8", label: "Claude Opus 4.8" },
+ { id: "anthropic/claude-sonnet-5", label: "anthropic/claude-sonnet-5" },
+ ];
+ expect(result.current.models).toEqual(models);
+ expect(result.current.source).toBe("live");
+ expect(readRememberedAcpModels("local-1", "pi", ALL)).toEqual(models);
+ });
+
+ it("asks with only the secrets the launch would receive", async () => {
+ discoverModels.mockResolvedValue(PI_DISCOVERY);
+
+ renderHook(
+ () =>
+ useAcpModelDiscovery("pi", { secretRefs: ["PI_AUTH_JSON", "GONE"] }),
+ { wrapper },
+ );
+
+ await waitFor(() =>
+ expect(discoverModels).toHaveBeenCalledWith("pi", ["PI_AUTH_JSON"]),
+ );
+ });
+
+ it("sends no secrets when the profile allows none", async () => {
+ discoverModels.mockResolvedValue(PI_DISCOVERY);
+
+ renderHook(() => useAcpModelDiscovery("pi", { secretRefs: [] }), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(discoverModels).toHaveBeenCalledWith("pi", []));
+ });
+
+ it("does not offer a list remembered with other secrets", async () => {
+ rememberAcpModels("local-1", "pi", ALL, [
+ { id: "anthropic/claude-opus-4-8", label: "Claude Opus 4.8" },
+ ]);
+ discoverModels.mockResolvedValue(AUTH_REQUIRED);
+
+ const { result } = renderHook(
+ () => useAcpModelDiscovery("pi", { secretRefs: [] }),
+ { wrapper },
+ );
+
+ await waitFor(() =>
+ expect(result.current.discovery?.error?.code).toBe("ACPAuthRequired"),
+ );
+ expect(result.current.models).toEqual([]);
+ expect(result.current.source).toBe("none");
+ });
+
+ it("offers the list remembered with the same secrets", async () => {
+ const models = [{ id: "anthropic/claude-sonnet-5", label: "Sonnet 5" }];
+ rememberAcpModels("local-1", "pi", acpModelScope(["PI_AUTH_JSON"]), models);
+ discoverModels.mockResolvedValue(AUTH_REQUIRED);
+
+ const { result } = renderHook(
+ () => useAcpModelDiscovery("pi", { secretRefs: ["PI_AUTH_JSON"] }),
+ { wrapper },
+ );
+
+ await waitFor(() =>
+ expect(result.current.discovery?.error?.code).toBe("ACPAuthRequired"),
+ );
+ expect(result.current.models).toEqual(models);
+ expect(result.current.source).toBe("remembered");
+ });
+
+ it("remembers a scoped lookup without replacing the unscoped list", async () => {
+ const unscoped = [{ id: "openai/gpt-6-astra", label: "GPT-6 Astra" }];
+ rememberAcpModels("local-1", "pi", ALL, unscoped);
+ discoverModels.mockResolvedValue(PI_DISCOVERY);
+
+ const { result } = renderHook(
+ () => useAcpModelDiscovery("pi", { secretRefs: ["PI_AUTH_JSON"] }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.source).toBe("live"));
+ expect(readRememberedAcpModels("local-1", "pi", ALL)).toEqual(unscoped);
+ expect(
+ readRememberedAcpModels("local-1", "pi", acpModelScope(["PI_AUTH_JSON"])),
+ ).toEqual(result.current.models);
+ });
+
+ it("offers nothing while disabled, even a lookup it already made", async () => {
+ discoverModels.mockResolvedValue(PI_DISCOVERY);
+
+ const { result, rerender } = renderHook(
+ ({ enabled }) => useAcpModelDiscovery("pi", { enabled }),
+ { wrapper, initialProps: { enabled: true } },
+ );
+ await waitFor(() => expect(result.current.source).toBe("live"));
+
+ rerender({ enabled: false });
+
+ expect(result.current.models).toEqual([]);
+ expect(result.current.source).toBe("none");
+ expect(result.current.defaultModelId).toBeNull();
+ });
+
+ it("has no models when the server cannot answer and none were seen", async () => {
+ discoverModels.mockRejectedValue(new Error("404"));
+
+ const { result } = renderHook(() => useAcpModelDiscovery("pi"), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(discoverModels).toHaveBeenCalled());
+ await waitFor(() => expect(result.current.isDiscovering).toBe(false));
+ expect(result.current.discovery).toBeNull();
+ expect(result.current.models).toEqual([]);
+ expect(result.current.source).toBe("none");
+ });
+
+ it("does not ask on a cloud backend", () => {
+ backendMock.current = {
+ backend: { id: "cloud-1", kind: "cloud" },
+ orgId: null,
+ };
+
+ const { result } = renderHook(() => useAcpModelDiscovery("claude-code"), {
+ wrapper,
+ });
+
+ expect(discoverModels).not.toHaveBeenCalled();
+ expect(result.current.models).toEqual([]);
+ expect(result.current.source).toBe("none");
+ });
+
+ it("offers the list the agent last reported on this backend", () => {
+ backendMock.current = {
+ backend: { id: "cloud-1", kind: "cloud" },
+ orgId: null,
+ };
+ const models = [{ id: "sonnet", label: "Sonnet" }];
+ rememberAcpModels("cloud-1", "claude-code", ALL, models);
+ rememberAcpModels("cloud-2", "codex", ALL, [
+ { id: "gpt-5.5", label: "GPT" },
+ ]);
+
+ const { result } = renderHook(() => useAcpModelDiscovery("claude-code"), {
+ wrapper,
+ });
+
+ expect(result.current.models).toEqual(models);
+ expect(result.current.source).toBe("remembered");
+ expect(result.current.defaultModelId).toBeNull();
+ });
+
+ it("picks up a list remembered after it mounted", () => {
+ backendMock.current = {
+ backend: { id: "cloud-1", kind: "cloud" },
+ orgId: null,
+ };
+ const { result } = renderHook(() => useAcpModelDiscovery("claude-code"), {
+ wrapper,
+ });
+ expect(result.current.models).toEqual([]);
+
+ const models = [{ id: "sonnet", label: "Sonnet" }];
+ act(() => rememberAcpModels("cloud-1", "claude-code", ALL, models));
+
+ expect(result.current.models).toEqual(models);
+ expect(result.current.source).toBe("remembered");
+ });
+
+ it("does not ask without a provider", () => {
+ renderHook(() => useAcpModelDiscovery(null), { wrapper });
+
+ expect(discoverModels).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/hooks/query/use-acp-session-models.test.tsx b/__tests__/hooks/query/use-acp-session-models.test.tsx
new file mode 100644
index 0000000000..3178b34147
--- /dev/null
+++ b/__tests__/hooks/query/use-acp-session-models.test.tsx
@@ -0,0 +1,144 @@
+import React from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { useAcpSessionModels } from "#/hooks/query/use-acp-session-models";
+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+import {
+ acpModelScope,
+ readRememberedAcpModels,
+} from "#/utils/remembered-acp-models";
+
+const backendMock = vi.hoisted(() => ({
+ current: { backend: { id: "cloud-1", kind: "cloud" as "local" | "cloud" } },
+}));
+vi.mock("#/contexts/active-backend-context", () => ({
+ useActiveBackend: () => backendMock.current,
+}));
+
+const getRuntimeConversation = vi.hoisted(() => vi.fn());
+vi.mock(
+ "#/api/conversation-service/agent-server-conversation-service.api",
+ () => ({ default: { getRuntimeConversation } }),
+);
+
+const ALL = acpModelScope(null);
+
+const MODELS = [
+ { id: "default", label: "Default (recommended)" },
+ { id: "sonnet", label: "Sonnet" },
+];
+
+function conversation(overrides: Partial<AppConversation> = {}) {
+ return {
+ id: "conv-1",
+ acp_server: "claude-code",
+ conversation_url: "https://runtime.example.com/api/conversations/conv-1",
+ session_api_key: "session-key",
+ sandbox_status: "RUNNING",
+ acp_available_models: null,
+ ...overrides,
+ } as AppConversation;
+}
+
+function wrapper({ children }: { children: React.ReactNode }) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ window.localStorage.clear();
+ backendMock.current = { backend: { id: "cloud-1", kind: "cloud" } };
+});
+
+describe("useAcpSessionModels", () => {
+ it("reads a cloud conversation's list from its sandbox and remembers it", async () => {
+ getRuntimeConversation.mockResolvedValue({ available_models: MODELS });
+
+ const { result } = renderHook(() => useAcpSessionModels(conversation()), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(result.current).toEqual(MODELS));
+ expect(getRuntimeConversation).toHaveBeenCalledWith(
+ "conv-1",
+ "https://runtime.example.com/api/conversations/conv-1",
+ "session-key",
+ );
+ expect(readRememberedAcpModels("cloud-1", "claude-code", ALL)).toEqual(
+ MODELS,
+ );
+ });
+
+ it("waits for the sandbox to run", () => {
+ const { result } = renderHook(
+ () => useAcpSessionModels(conversation({ sandbox_status: "PAUSED" })),
+ { wrapper },
+ );
+
+ expect(getRuntimeConversation).not.toHaveBeenCalled();
+ expect(result.current).toEqual([]);
+ });
+
+ it("uses a local conversation's own list without asking the runtime", () => {
+ backendMock.current = { backend: { id: "local-1", kind: "local" } };
+
+ const { result } = renderHook(
+ () => useAcpSessionModels(conversation({ acp_available_models: MODELS })),
+ { wrapper },
+ );
+
+ expect(result.current).toEqual(MODELS);
+ expect(getRuntimeConversation).not.toHaveBeenCalled();
+ expect(readRememberedAcpModels("local-1", "claude-code", ALL)).toEqual(
+ MODELS,
+ );
+ });
+
+ it("remembers a list under the secrets the conversation launched with", () => {
+ backendMock.current = { backend: { id: "local-1", kind: "local" } };
+ const launched_agent_profile = {
+ agent_profile_id: "id-claude",
+ revision: 2,
+ secret_refs: ["ANTHROPIC_API_KEY"],
+ };
+
+ renderHook(
+ () =>
+ useAcpSessionModels(
+ conversation({
+ acp_available_models: MODELS,
+ launched_agent_profile,
+ }),
+ ),
+ { wrapper },
+ );
+
+ expect(
+ readRememberedAcpModels(
+ "local-1",
+ "claude-code",
+ acpModelScope(["ANTHROPIC_API_KEY"]),
+ ),
+ ).toEqual(MODELS);
+ expect(readRememberedAcpModels("local-1", "claude-code", ALL)).toEqual([]);
+ });
+
+ it("does not remember a custom server's list", () => {
+ backendMock.current = { backend: { id: "local-1", kind: "local" } };
+
+ renderHook(
+ () =>
+ useAcpSessionModels(
+ conversation({ acp_server: "custom", acp_available_models: MODELS }),
+ ),
+ { wrapper },
+ );
+
+ expect(readRememberedAcpModels("local-1", "custom")).toEqual([]);
+ });
+});
diff --git a/__tests__/hooks/query/use-conversation-metrics.test.tsx b/__tests__/hooks/query/use-conversation-metrics.test.tsx
index d34df19afd..7b921fe9a9 100644
--- a/__tests__/hooks/query/use-conversation-metrics.test.tsx
+++ b/__tests__/hooks/query/use-conversation-metrics.test.tsx
@@ -20,6 +20,7 @@ const runtimeInfo = {
created_at: "2026-04-16T00:00:00Z",
updated_at: "2026-04-16T00:00:00Z",
status: ExecutionStatus.IDLE,
+ available_models: [],
stats: {
usage_to_metrics: {
agent: {
@@ -170,6 +171,7 @@ describe("useConversationMetrics", () => {
created_at: "2026-04-16T00:00:00Z",
updated_at: "2026-04-16T00:00:00Z",
status: ExecutionStatus.IDLE,
+ available_models: [],
stats: {
usage_to_metrics: {
agent: {
diff --git a/__tests__/hooks/use-chat-input-model-state.test.tsx b/__tests__/hooks/use-chat-input-model-state.test.tsx
index 0f4ad551f1..de58105202 100644
--- a/__tests__/hooks/use-chat-input-model-state.test.tsx
+++ b/__tests__/hooks/use-chat-input-model-state.test.tsx
@@ -1,7 +1,7 @@
import { renderHook } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { AcpModelContext } from "#/hooks/use-acp-model-context";
-import { getAcpProvider } from "#/constants/acp-providers";
+import { ACP_VERTEX_SAFE_MODEL } from "#/constants/acp-providers";
const useActiveConversationMock = vi.fn();
const useSettingsMock = vi.fn();
@@ -48,9 +48,23 @@ vi.mock("#/hooks/use-can-manage-org-profiles", () => ({
useCanManageOrgProfiles: () => useCanManageOrgProfilesMock(),
}));
-// `getAcpProvider`/`labelForAcpModel`/`resolveEffectiveAcpModel` are exercised
-// for real (not mocked) so the test pins the actual registry-sourced model
-// list the picker shows.
+const useAcpModelDiscoveryMock = vi.fn();
+vi.mock("#/hooks/query/use-acp-model-discovery", () => ({
+ useAcpModelDiscovery: (...args: unknown[]) =>
+ useAcpModelDiscoveryMock(...args),
+}));
+
+const useAcpSessionModelsMock = vi.fn();
+vi.mock("#/hooks/query/use-acp-session-models", () => ({
+ useAcpSessionModels: (...args: unknown[]) => useAcpSessionModelsMock(...args),
+}));
+
+const NO_LIVE_MODELS = { models: [], defaultModelId: null };
+const CLAUDE_MODELS = [
+ { id: "default", label: "Default (recommended)" },
+ { id: "sonnet", label: "Sonnet" },
+];
+
import { useChatInputModelState } from "#/hooks/use-chat-input-model-state";
// `useAcpModelContext` derives these booleans; here we drive them directly so
@@ -83,6 +97,164 @@ describe("useChatInputModelState", () => {
useActiveAcpProfileDetailMock.mockReturnValue(null);
useCanManageOrgProfilesMock.mockReset();
useCanManageOrgProfilesMock.mockReturnValue(true);
+ useAcpModelDiscoveryMock.mockReset();
+ useAcpModelDiscoveryMock.mockReturnValue(NO_LIVE_MODELS);
+ useAcpSessionModelsMock.mockReset();
+ useAcpSessionModelsMock.mockImplementation(
+ (conversation) => conversation?.acp_available_models ?? [],
+ );
+ });
+
+ it("active ACP: lists the models the conversation's session reported", () => {
+ const live = [
+ { id: "default", label: "Default (recommended)" },
+ { id: "claude-fable-5[1m]", label: "Fable 5 (1M)" },
+ ];
+ useActiveConversationMock.mockReturnValue({
+ data: {
+ conversation_id: "c1",
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ llm_model: "claude-fable-5[1m]",
+ acp_available_models: live,
+ },
+ });
+ useAcpModelContextMock.mockReturnValue(
+ acpContext({ isActiveAcpConversation: true, isAcpContext: true }),
+ );
+
+ const { result } = renderHook(() => useChatInputModelState());
+
+ expect(result.current.availableAcpModels).toEqual(live);
+ expect(result.current.displayModel).toBe("Fable 5 (1M)");
+ });
+
+ it("active ACP: a custom server's session list makes the picker selectable", () => {
+ const live = [
+ { id: "swe-2-high", label: "SWE-2 High" },
+ { id: "swe-2-low", label: "SWE-2 Low" },
+ ];
+ useActiveConversationMock.mockReturnValue({
+ data: {
+ conversation_id: "c1",
+ agent_kind: "acp",
+ acp_server: "custom",
+ llm_model: "swe-2-high",
+ acp_available_models: live,
+ },
+ });
+ useAcpModelContextMock.mockReturnValue(
+ acpContext({ isActiveAcpConversation: true, isAcpContext: true }),
+ );
+
+ const { result } = renderHook(() => useChatInputModelState());
+
+ expect(result.current.availableAcpModels).toEqual(live);
+ expect(result.current.displayModel).toBe("SWE-2 High");
+ expect(result.current.showAcpPicker).toBe(true);
+ expect(useAcpModelDiscoveryMock).toHaveBeenCalledWith(null, {
+ enabled: true,
+ secretRefs: null,
+ });
+ });
+
+ it("active ACP: uses the agent's reported list until the session reports its own", () => {
+ useActiveConversationMock.mockReturnValue({
+ data: {
+ conversation_id: "c1",
+ agent_kind: "acp",
+ acp_server: "codex",
+ llm_model: "gpt-5.6-terra",
+ acp_available_models: [],
+ },
+ });
+ useAcpModelContextMock.mockReturnValue(
+ acpContext({ isActiveAcpConversation: true, isAcpContext: true }),
+ );
+ const live = [
+ { id: "gpt-6-astra", label: "GPT-6 Astra" },
+ { id: "gpt-5.6-terra", label: "GPT-5.6 Terra" },
+ ];
+ useAcpModelDiscoveryMock.mockReturnValue({
+ models: live,
+ defaultModelId: "gpt-6-astra",
+ });
+
+ const { result } = renderHook(() => useChatInputModelState());
+
+ expect(useAcpModelDiscoveryMock).toHaveBeenCalledWith("codex", {
+ enabled: true,
+ secretRefs: null,
+ });
+ expect(result.current.availableAcpModels).toEqual(live);
+ expect(result.current.currentModelId).toBe("gpt-5.6-terra");
+ });
+
+ it("active ACP: asks for models with the secrets the conversation launched with", () => {
+ useActiveConversationMock.mockReturnValue({
+ data: {
+ conversation_id: "c1",
+ agent_kind: "acp",
+ acp_server: "codex",
+ llm_model: "gpt-5.6-terra",
+ launched_agent_profile: {
+ agent_profile_id: "id-codex",
+ revision: 3,
+ secret_refs: ["OPENAI_API_KEY"],
+ },
+ },
+ });
+ useAcpModelContextMock.mockReturnValue(
+ acpContext({ isActiveAcpConversation: true, isAcpContext: true }),
+ );
+ // The home page's active profile is not the one this conversation launched.
+ useActiveAcpProfileDetailMock.mockReturnValue({
+ id: "id-other",
+ name: "other",
+ agent_kind: "acp",
+ acp_server: "codex",
+ acp_model: null,
+ secret_refs: null,
+ });
+
+ renderHook(() => useChatInputModelState());
+
+ expect(useAcpModelDiscoveryMock).toHaveBeenCalledWith("codex", {
+ enabled: true,
+ secretRefs: ["OPENAI_API_KEY"],
+ });
+ });
+
+ it("home ACP: lists the models the agent reported and shows its own default", () => {
+ useActiveAcpProfileDetailMock.mockReturnValue({
+ id: "id-pi",
+ name: "pi",
+ agent_kind: "acp",
+ acp_server: "pi",
+ acp_model: null,
+ secret_refs: null,
+ });
+ useAcpModelContextMock.mockReturnValue(
+ acpContext({ isHomeAcp: true, isAcpContext: true }),
+ );
+ const live = [
+ { id: "anthropic/claude-opus-4-8", label: "Claude Opus 4.8" },
+ { id: "anthropic/claude-sonnet-5", label: "Claude Sonnet 5" },
+ ];
+ useAcpModelDiscoveryMock.mockReturnValue({
+ models: live,
+ defaultModelId: "anthropic/claude-opus-4-8",
+ });
+
+ const { result } = renderHook(() => useChatInputModelState());
+
+ expect(useAcpModelDiscoveryMock).toHaveBeenCalledWith("pi", {
+ enabled: true,
+ secretRefs: null,
+ });
+ expect(result.current.availableAcpModels).toEqual(live);
+ expect(result.current.currentModelId).toBe("anthropic/claude-opus-4-8");
+ expect(result.current.displayModel).toBe("Claude Opus 4.8");
});
it("non-ACP: shows the conversation/settings llm_model with no picker", () => {
@@ -112,13 +284,7 @@ describe("useChatInputModelState", () => {
expect(result.current.currentModelId).toBe("openai/gpt-4o");
});
- it("active ACP: resolves the provider's available models (getAcpProvider called for active contexts, not just home)", () => {
- // Regression guard: in the old ChatInputModel `getAcpProvider` ran only on
- // the home branch. The shared hook calls it for ANY ACP context so the
- // picker has a model list on active conversations too. Pin that contract.
- const provider = getAcpProvider("claude-code");
- expect(provider?.available_models?.length).toBeGreaterThan(0);
-
+ it("active ACP: offers no hardcoded models before the agent reports any", () => {
useActiveConversationMock.mockReturnValue({
data: {
conversation_id: "c1",
@@ -141,13 +307,9 @@ describe("useChatInputModelState", () => {
expect(result.current.isAcpContext).toBe(true);
expect(result.current.currentModelId).toBe("sonnet");
- // Human label resolved from the registry (matches the conversation chip).
- expect(result.current.displayModel).toBe("Claude Sonnet");
- expect(result.current.availableAcpModels).toEqual(
- provider?.available_models,
- );
- // Local backend + ACP + a non-empty model list → picker is enabled.
- expect(result.current.showAcpPicker).toBe(true);
+ expect(result.current.displayModel).toBe("sonnet");
+ expect(result.current.availableAcpModels).toEqual([]);
+ expect(result.current.showAcpPicker).toBe(false);
// Live switch targets the navigation conversation id.
expect(result.current.switchConversationId).toBe("c1");
expect(result.current.destinationPath).toBe("/settings/agents");
@@ -173,6 +335,10 @@ describe("useChatInputModelState", () => {
destinationLabel: "Agent",
}),
);
+ useAcpModelDiscoveryMock.mockReturnValue({
+ models: CLAUDE_MODELS,
+ defaultModelId: "default",
+ });
const { result } = renderHook(() => useChatInputModelState());
@@ -182,8 +348,29 @@ describe("useChatInputModelState", () => {
expect(result.current.switchConversationId).toBeNull();
});
- it("home ACP: falls back to the provider default when no acp_model is saved", () => {
- const provider = getAcpProvider("claude-code");
+ it("home ACP: shows the agent's own default when no acp_model is saved", () => {
+ useActiveConversationMock.mockReturnValue({ data: undefined });
+ useSettingsMock.mockReturnValue({
+ data: {
+ agent_settings: { agent_kind: "acp", acp_server: "claude-code" },
+ },
+ });
+ useAcpModelContextMock.mockReturnValue(
+ acpContext({ isHomeAcp: true, isAcpContext: true }),
+ );
+ useAcpModelDiscoveryMock.mockReturnValue({
+ models: CLAUDE_MODELS,
+ defaultModelId: "default",
+ });
+
+ const { result } = renderHook(() => useChatInputModelState());
+
+ expect(result.current.currentModelId).toBe("default");
+ expect(result.current.displayModel).toBe("Default (recommended)");
+ });
+
+ it("home ACP: names the agent's default when no one has reported it yet", () => {
+ useActiveBackendMock.mockReturnValue({ backend: { kind: "cloud" } });
useActiveConversationMock.mockReturnValue({ data: undefined });
useSettingsMock.mockReturnValue({
data: {
@@ -193,10 +380,38 @@ describe("useChatInputModelState", () => {
useAcpModelContextMock.mockReturnValue(
acpContext({ isHomeAcp: true, isAcpContext: true }),
);
+ useAcpModelDiscoveryMock.mockReturnValue({
+ models: CLAUDE_MODELS,
+ defaultModelId: null,
+ });
const { result } = renderHook(() => useChatInputModelState());
- expect(result.current.currentModelId).toBe(provider?.default_model);
+ expect(result.current.currentModelId).toBeNull();
+ expect(result.current.displayModel).toBe(
+ "SETTINGS$AGENT_MODEL_AGENT_DEFAULT",
+ );
+ expect(result.current.showAcpPicker).toBe(true);
+ });
+
+ it("home ACP: Gemini keeps its Vertex-safe model over the agent's default", () => {
+ useActiveConversationMock.mockReturnValue({ data: undefined });
+ useSettingsMock.mockReturnValue({
+ data: {
+ agent_settings: { agent_kind: "acp", acp_server: "gemini-cli" },
+ },
+ });
+ useAcpModelContextMock.mockReturnValue(
+ acpContext({ isHomeAcp: true, isAcpContext: true }),
+ );
+ useAcpModelDiscoveryMock.mockReturnValue({
+ models: [],
+ defaultModelId: "gemini-3-flash-preview",
+ });
+
+ const { result } = renderHook(() => useChatInputModelState());
+
+ expect(result.current.currentModelId).toBe(ACP_VERTEX_SAFE_MODEL);
});
it("home ACP: the active profile's detail overrides stale agent settings for provider and model", () => {
@@ -223,13 +438,57 @@ describe("useChatInputModelState", () => {
useAcpModelContextMock.mockReturnValue(
acpContext({ isHomeAcp: true, isAcpContext: true }),
);
+ const codexModels = [{ id: "gpt-5.5", label: "GPT-5.5" }];
+ useAcpModelDiscoveryMock.mockReturnValue({
+ models: codexModels,
+ defaultModelId: null,
+ });
const { result } = renderHook(() => useChatInputModelState());
expect(result.current.currentModelId).toBe("gpt-5.5");
- expect(result.current.availableAcpModels).toEqual(
- getAcpProvider("codex")?.available_models,
+ expect(useAcpModelDiscoveryMock).toHaveBeenCalledWith("codex", {
+ enabled: true,
+ secretRefs: null,
+ });
+ expect(result.current.availableAcpModels).toEqual(codexModels);
+ });
+
+ it("home ACP: asks for models with the active profile's secret scope", () => {
+ useActiveAcpProfileDetailMock.mockReturnValue({
+ id: "id-codex",
+ name: "codex-test",
+ agent_kind: "acp",
+ acp_server: "codex",
+ acp_model: null,
+ secret_refs: ["OPENAI_API_KEY"],
+ });
+ useAcpModelContextMock.mockReturnValue(
+ acpContext({ isHomeAcp: true, isAcpContext: true }),
);
+
+ renderHook(() => useChatInputModelState());
+
+ expect(useAcpModelDiscoveryMock).toHaveBeenCalledWith("codex", {
+ enabled: true,
+ secretRefs: ["OPENAI_API_KEY"],
+ });
+ });
+
+ it("home ACP: does not ask for models until the active profile loads", () => {
+ useSettingsMock.mockReturnValue({
+ data: { agent_settings: { acp_server: "codex", acp_model: null } },
+ });
+ useAcpModelContextMock.mockReturnValue(
+ acpContext({ isHomeAcp: true, isAcpContext: true }),
+ );
+
+ renderHook(() => useChatInputModelState());
+
+ expect(useAcpModelDiscoveryMock).toHaveBeenCalledWith("codex", {
+ enabled: false,
+ secretRefs: null,
+ });
});
it("home ACP on cloud: hides the selectable rows from members who cannot manage org profiles", () => {
@@ -246,6 +505,10 @@ describe("useChatInputModelState", () => {
useAcpModelContextMock.mockReturnValue(
acpContext({ isHomeAcp: true, isAcpContext: true }),
);
+ useAcpModelDiscoveryMock.mockReturnValue({
+ models: CLAUDE_MODELS,
+ defaultModelId: null,
+ });
const { result } = renderHook(() => useChatInputModelState());
@@ -253,25 +516,25 @@ describe("useChatInputModelState", () => {
expect(result.current.showAcpPicker).toBe(false);
});
- it("showAcpPicker: cloud backend shows the picker when a model list is present (cloud ACP supports mid-conversation switching)", () => {
+ it("showAcpPicker: a cloud conversation's session list enables the picker", () => {
useActiveBackendMock.mockReturnValue({ backend: { kind: "cloud" } });
- useActiveConversationMock.mockReturnValue({
- data: {
- conversation_id: "c1",
- agent_kind: "acp",
- acp_server: "claude-code",
- llm_model: "claude-sonnet-4-6",
- },
- });
+ const conversation = {
+ conversation_id: "c1",
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ llm_model: "sonnet",
+ };
+ useActiveConversationMock.mockReturnValue({ data: conversation });
+ useAcpSessionModelsMock.mockReturnValue(CLAUDE_MODELS);
useAcpModelContextMock.mockReturnValue(
acpContext({ isActiveAcpConversation: true, isAcpContext: true }),
);
const { result } = renderHook(() => useChatInputModelState());
- expect(result.current.availableAcpModels.length).toBeGreaterThan(0);
- // ACP + model list present → picker is enabled on all backends
- // (cloud ACP conversations support mid-conversation model switching).
+ expect(useAcpSessionModelsMock).toHaveBeenCalledWith(conversation);
+ expect(result.current.availableAcpModels).toEqual(CLAUDE_MODELS);
+ expect(result.current.displayModel).toBe("Sonnet");
expect(result.current.showAcpPicker).toBe(true);
});
@@ -292,7 +555,7 @@ describe("useChatInputModelState", () => {
expect(result.current.availableAcpModels).toEqual([]);
expect(result.current.showAcpPicker).toBe(false);
- // Unknown model id has no registry label → falls back to the raw id.
+ // No reported label → falls back to the raw id.
expect(result.current.displayModel).toBe("custom-model");
});
});
diff --git a/__tests__/routes/agent-settings.test.tsx b/__tests__/routes/agent-settings.test.tsx
index 0abe572602..81dce758f4 100644
--- a/__tests__/routes/agent-settings.test.tsx
+++ b/__tests__/routes/agent-settings.test.tsx
@@ -12,7 +12,10 @@ import SettingsService from "#/api/settings-service/settings-service.api";
import { SecretsService } from "#/api/secrets-service";
import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";
import { Settings } from "#/types/settings";
-import { ACP_PROVIDERS } from "#/constants/acp-providers";
+import {
+ ACP_PROVIDERS,
+ ACP_VERTEX_SAFE_MODEL,
+} from "#/constants/acp-providers";
import {
__resetActiveStoreForTests,
setActiveSelection,
@@ -31,6 +34,23 @@ vi.mock("#/hooks/query/use-acp-auth-status", () => ({
useAcpAuthStatus: (...args: unknown[]) => acpAuthStatusMock(...args),
}));
+// What the provider's own server reports; empty unless a test sets it.
+const acpModelDiscoveryMock = vi.hoisted(() => vi.fn());
+vi.mock("#/hooks/query/use-acp-model-discovery", () => ({
+ useAcpModelDiscovery: (...args: unknown[]) => acpModelDiscoveryMock(...args),
+}));
+const NO_DISCOVERY = {
+ discovery: null,
+ models: [],
+ source: "none",
+ defaultModelId: null,
+ isDiscovering: false,
+};
+const CLAUDE_MODELS = [
+ { id: "default", label: "Default (recommended)" },
+ { id: "haiku", label: "Haiku" },
+];
+
const profileSupportsSecretRefsMock = vi.hoisted(() => vi.fn(() => true));
const profileSupportsInstructionsMock = vi.hoisted(() => vi.fn(() => false));
vi.mock("#/api/agent-profiles-service/profile-field-support", () => ({
@@ -117,6 +137,7 @@ describe("AgentSettingsScreen", () => {
isChecking: false,
isSupported: true,
});
+ acpModelDiscoveryMock.mockReturnValue(NO_DISCOVERY);
toastMocks.success.mockClear();
toastMocks.error.mockClear();
toastMocks.warning.mockClear();
@@ -149,9 +170,7 @@ describe("AgentSettingsScreen", () => {
});
});
- it("opens a stored ACP profile on its command and custom model", async () => {
- // A model ID outside the provider's suggestions falls through to the
- // custom input; known IDs go through the dropdown instead.
+ it("opens a stored ACP profile on its command and saved model", async () => {
renderAgentSettingsScreen({
agentSettingsOverride: {
...CLAUDE_PROFILE,
@@ -166,22 +185,80 @@ describe("AgentSettingsScreen", () => {
expect(commandInput.value).toBe(
"npx -y @agentclientprotocol/claude-agent-acp",
);
- const modelInput = screen.getByTestId(
- "agent-model-input",
- ) as HTMLInputElement;
- expect(modelInput.value).toBe("my-pinned-fork-model");
+ expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue(
+ "my-pinned-fork-model",
+ );
+ expect(screen.queryByTestId("agent-model-input")).toBeNull();
});
- it("defaults built-in ACP providers to a suggested model when none is saved", async () => {
+ it("starts a built-in provider on the agent's own default before any model list", async () => {
+ const { control } = renderAgentSettingsScreen({
+ agentSettingsOverride: CLAUDE_PROFILE,
+ });
+
+ await screen.findByTestId("agent-command-input");
+ expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue(
+ "SETTINGS$AGENT_MODEL_AGENT_DEFAULT",
+ );
+ expect(
+ screen.getByTestId("agent-model-list-after-first-conversation"),
+ ).toBeInTheDocument();
+ expect(control().buildAgentProfileFields()).toMatchObject({
+ acp_model: null,
+ });
+ });
+
+ it("says when the models come from the last conversation", async () => {
+ acpModelDiscoveryMock.mockReturnValue({
+ ...NO_DISCOVERY,
+ models: CLAUDE_MODELS,
+ source: "remembered",
+ });
renderAgentSettingsScreen({ agentSettingsOverride: CLAUDE_PROFILE });
+ expect(
+ await screen.findByTestId("agent-model-list-remembered"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("agent-model-list-after-first-conversation"),
+ ).toBeNull();
+ });
+
+ it("keeps Gemini on its Vertex-safe model instead of offering its own default", async () => {
+ const user = userEvent.setup();
+ renderAgentSettingsScreen({
+ agentSettingsOverride: { ...CLAUDE_PROFILE, acp_server: "gemini-cli" },
+ });
+
await screen.findByTestId("agent-command-input");
expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue(
- "Claude Opus (1M)",
+ ACP_VERTEX_SAFE_MODEL,
);
+ await user.click(screen.getByLabelText("SETTINGS$AGENT_MODEL"));
+ expect(
+ screen.queryByRole("option", {
+ name: "SETTINGS$AGENT_MODEL_AGENT_DEFAULT",
+ }),
+ ).toBeNull();
+ });
+
+ it("puts the credentials before the model, since the models depend on them", async () => {
+ renderAgentSettingsScreen({ agentSettingsOverride: CLAUDE_PROFILE });
+
+ const model = await screen.findByTestId("agent-model-selector");
+ const credentials = screen.getByText("SETTINGS$ACP_CREDENTIALS_TITLE");
+ expect(
+ credentials.compareDocumentPosition(model) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
});
it("builds the selected built-in ACP model", async () => {
+ acpModelDiscoveryMock.mockReturnValue({
+ ...NO_DISCOVERY,
+ models: CLAUDE_MODELS,
+ source: "live",
+ });
const user = userEvent.setup();
const { control } = renderAgentSettingsScreen({
agentSettingsOverride: CLAUDE_PROFILE,
@@ -189,7 +266,7 @@ describe("AgentSettingsScreen", () => {
await screen.findByTestId("agent-command-input");
await user.click(screen.getByLabelText("SETTINGS$AGENT_MODEL"));
- await user.click(await screen.findByText("Claude Haiku"));
+ await user.click(await screen.findByText("Haiku"));
expect(control().buildAgentProfileFields()).toMatchObject({
acp_model: "haiku",
@@ -209,9 +286,7 @@ describe("AgentSettingsScreen", () => {
OPENCODE_PROVIDER.default_command.join(" "),
);
expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue(
- OPENCODE_PROVIDER.available_models.find(
- ({ id }) => id === OPENCODE_PROVIDER.default_model,
- )?.label,
+ "SETTINGS$AGENT_MODEL_AGENT_DEFAULT",
);
expect(control().buildAgentProfileFields()).toMatchObject({
@@ -219,7 +294,7 @@ describe("AgentSettingsScreen", () => {
acp_server: "opencode",
acp_command: null,
acp_args: null,
- acp_model: OPENCODE_PROVIDER.default_model,
+ acp_model: null,
});
});
@@ -231,7 +306,7 @@ describe("AgentSettingsScreen", () => {
agent_kind: "acp",
acp_server: "opencode",
acp_command: command,
- acp_model: OPENCODE_PROVIDER.default_model,
+ acp_model: "opencode/big-pickle",
},
});
@@ -242,16 +317,14 @@ describe("AgentSettingsScreen", () => {
OPENCODE_PROVIDER.default_command.join(" "),
);
expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue(
- OPENCODE_PROVIDER.available_models.find(
- ({ id }) => id === OPENCODE_PROVIDER.default_model,
- )?.label,
+ "opencode/big-pickle",
);
// Old explicit defaults are cleared on the next save; new profiles
// resolve the current registry command rather than pinning a CLI version.
expect(control().buildAgentProfileFields()).toMatchObject({
acp_server: "opencode",
acp_command: null,
- acp_model: OPENCODE_PROVIDER.default_model,
+ acp_model: "opencode/big-pickle",
});
},
);
@@ -272,16 +345,20 @@ describe("AgentSettingsScreen", () => {
expect(await screen.findByTestId("agent-preset-selector")).toHaveValue(
"OpenCode",
);
- expect(screen.getByTestId("agent-model-input")).toHaveValue(model);
+ expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue(model);
expect(control().buildAgentProfileFields()).toMatchObject({
acp_server: "opencode",
acp_command: null,
acp_model: model,
});
- // Go IDs need not be in the SDK's static model suggestions. Changing
- // the model must not turn the provider into a Custom ACP command.
- await user.clear(screen.getByTestId("agent-model-input"));
+ // Changing the model must not turn the provider into a Custom ACP command.
+ await user.click(screen.getByLabelText("SETTINGS$AGENT_MODEL"));
+ await user.click(
+ await screen.findByRole("option", {
+ name: "SETTINGS$AGENT_PRESET_CUSTOM",
+ }),
+ );
await user.type(
screen.getByTestId("agent-model-input"),
"opencode-go/deepseek-v4-flash",
@@ -303,7 +380,7 @@ describe("AgentSettingsScreen", () => {
});
await screen.findByTestId("agent-command-input");
expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue(
- "Claude Opus (1M)",
+ "SETTINGS$AGENT_MODEL_AGENT_DEFAULT",
);
await user.click(screen.getByTestId("agent-preset-selector"));
@@ -344,6 +421,156 @@ describe("AgentSettingsScreen", () => {
});
});
+ it("lists the models the agent reports and names its own default", async () => {
+ acpModelDiscoveryMock.mockReturnValue({
+ ...NO_DISCOVERY,
+ source: "live",
+ models: [
+ { id: "default", label: "Default (recommended)" },
+ { id: "claude-fable-5[1m]", label: "Fable 5 (1M)" },
+ { id: "sonnet", label: "Sonnet" },
+ ],
+ defaultModelId: "default",
+ });
+ const user = userEvent.setup();
+ const { control } = renderAgentSettingsScreen({
+ agentSettingsOverride: CLAUDE_PROFILE,
+ });
+ await screen.findByTestId("agent-command-input");
+ expect(acpModelDiscoveryMock).toHaveBeenLastCalledWith("claude-code", {
+ secretRefs: null,
+ });
+
+ await user.click(screen.getByLabelText("SETTINGS$AGENT_MODEL"));
+ await user.click(
+ await screen.findByRole("option", { name: "Fable 5 (1M)" }),
+ );
+ expect(control().buildAgentProfileFields()).toMatchObject({
+ acp_model: "claude-fable-5[1m]",
+ });
+
+ await user.click(screen.getByLabelText("SETTINGS$AGENT_MODEL"));
+ await user.click(
+ await screen.findByRole("option", {
+ name: "SETTINGS$AGENT_MODEL_AGENT_DEFAULT_IS",
+ }),
+ );
+ expect(control().buildAgentProfileFields()).toMatchObject({
+ acp_model: null,
+ });
+ });
+
+ it("keeps a saved model selectable when the agent no longer lists it", async () => {
+ acpModelDiscoveryMock.mockReturnValue({
+ ...NO_DISCOVERY,
+ source: "live",
+ models: [{ id: "gpt-6-astra", label: "GPT-6 Astra" }],
+ defaultModelId: "gpt-6-astra",
+ });
+ renderAgentSettingsScreen({
+ agentSettingsOverride: {
+ ...CLAUDE_PROFILE,
+ acp_server: "codex",
+ acp_model: "gpt-5.5",
+ },
+ });
+
+ await screen.findByTestId("agent-command-input");
+ expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue(
+ "gpt-5.5",
+ );
+ expect(screen.queryByTestId("agent-model-input")).toBeNull();
+ });
+
+ it("offers Pi's own default and saves no model for it", async () => {
+ acpModelDiscoveryMock.mockReturnValue({
+ ...NO_DISCOVERY,
+ models: [
+ { id: "anthropic/claude-opus-4-8", label: "Claude Opus 4.8" },
+ { id: "anthropic/claude-sonnet-5", label: "Claude Sonnet 5" },
+ ],
+ defaultModelId: "anthropic/claude-opus-4-8",
+ });
+ const user = userEvent.setup();
+ const { control } = renderAgentSettingsScreen({
+ agentSettingsOverride: { ...CLAUDE_PROFILE, acp_server: "pi" },
+ });
+
+ await screen.findByTestId("agent-command-input");
+ expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue(
+ "SETTINGS$AGENT_MODEL_AGENT_DEFAULT_IS",
+ );
+ expect(control().buildAgentProfileFields()).toMatchObject({
+ acp_server: "pi",
+ acp_model: null,
+ });
+
+ await user.click(screen.getByLabelText("SETTINGS$AGENT_MODEL"));
+ await user.click(
+ await screen.findByRole("option", { name: "Claude Sonnet 5" }),
+ );
+ expect(control().buildAgentProfileFields()).toMatchObject({
+ acp_model: "anthropic/claude-sonnet-5",
+ });
+ });
+
+ it("asks for models with only the secrets the profile allows", async () => {
+ renderAgentSettingsScreen({
+ agentSettingsOverride: {
+ ...CLAUDE_PROFILE,
+ secret_refs: ["ANTHROPIC_API_KEY"],
+ },
+ });
+
+ await screen.findByTestId("agent-command-input");
+ expect(acpModelDiscoveryMock).toHaveBeenLastCalledWith("claude-code", {
+ secretRefs: ["ANTHROPIC_API_KEY"],
+ });
+ });
+
+ it("does not ask a custom command for its models", async () => {
+ renderAgentSettingsScreen({
+ agentSettingsOverride: {
+ ...CLAUDE_PROFILE,
+ acp_server: "custom",
+ acp_command: ["my-acp-wrapper"],
+ },
+ });
+
+ await screen.findByTestId("agent-command-input");
+ expect(acpModelDiscoveryMock).toHaveBeenLastCalledWith(null, {
+ secretRefs: null,
+ });
+ });
+
+ it("asks for credentials when the agent needs a login to list models", async () => {
+ acpModelDiscoveryMock.mockReturnValue({
+ ...NO_DISCOVERY,
+ discovery: {
+ agent_name: null,
+ agent_version: null,
+ current_model_id: null,
+ available_models: [],
+ supports_runtime_model_switch: false,
+ error: { code: "ACPAuthRequired", detail: "log in" },
+ },
+ });
+ acpAuthStatusMock.mockReturnValue({
+ status: "authenticated",
+ isChecking: false,
+ isSupported: true,
+ });
+ renderAgentSettingsScreen({
+ agentSettingsOverride: { ...CLAUDE_PROFILE, acp_server: "gemini-cli" },
+ });
+
+ expect(
+ await screen.findByTestId("agent-model-discovery-needs-auth"),
+ ).toBeInTheDocument();
+ // The agent refused the login a local file check counted as signed in.
+ expect(screen.queryByTestId("settings-acp-auth-detected")).toBeNull();
+ });
+
it("hides the local-only presets on a cloud backend", async () => {
__resetActiveStoreForTests();
setRegisteredBackends([
@@ -399,7 +626,7 @@ describe("AgentSettingsScreen", () => {
// previous provider's model just like the preset dropdown does.
const user = userEvent.setup();
const { control } = renderAgentSettingsScreen({
- agentSettingsOverride: CLAUDE_PROFILE,
+ agentSettingsOverride: { ...CLAUDE_PROFILE, acp_model: "haiku" },
});
await screen.findByTestId("agent-command-input");
@@ -407,13 +634,10 @@ describe("AgentSettingsScreen", () => {
await user.clear(commandInput);
await user.type(commandInput, CODEX_COMMAND.join(" "));
- expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue(
- "GPT-5.5",
- );
expect(control().buildAgentProfileFields()).toMatchObject({
acp_server: "codex",
acp_command: null,
- acp_model: "gpt-5.5",
+ acp_model: null,
});
});
@@ -441,7 +665,7 @@ describe("AgentSettingsScreen", () => {
// The default command is left to the registry rather than pinned.
acp_command: null,
acp_args: null,
- acp_model: "opus[1m]",
+ acp_model: null,
});
});
diff --git a/__tests__/utils/remembered-acp-models.test.ts b/__tests__/utils/remembered-acp-models.test.ts
new file mode 100644
index 0000000000..1bd3c7de98
--- /dev/null
+++ b/__tests__/utils/remembered-acp-models.test.ts
@@ -0,0 +1,108 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ acpModelScope,
+ readRememberedAcpModels,
+ rememberAcpModels,
+ subscribeRememberedAcpModels,
+} from "#/utils/remembered-acp-models";
+
+const MODELS = [{ id: "sonnet", label: "Sonnet" }];
+const ALL = acpModelScope(null);
+
+beforeEach(() => {
+ window.localStorage.clear();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("remembered ACP models", () => {
+ it("notifies subscribers when a list changes, not when it is rewritten unchanged", () => {
+ const listener = vi.fn();
+ const unsubscribe = subscribeRememberedAcpModels(listener);
+
+ rememberAcpModels("cloud-1", "claude-code", ALL, MODELS);
+ rememberAcpModels("cloud-1", "claude-code", ALL, MODELS);
+ expect(listener).toHaveBeenCalledTimes(1);
+
+ unsubscribe();
+ rememberAcpModels("cloud-1", "claude-code", ALL, [
+ { id: "haiku", label: "Haiku" },
+ ]);
+ expect(listener).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps each backend's list per agent", () => {
+ rememberAcpModels("cloud-1", "claude-code", ALL, MODELS);
+
+ expect(readRememberedAcpModels("cloud-1", "claude-code", ALL)).toEqual(
+ MODELS,
+ );
+ expect(readRememberedAcpModels("cloud-2", "claude-code", ALL)).toEqual([]);
+ expect(readRememberedAcpModels("cloud-1", "codex", ALL)).toEqual([]);
+ });
+
+ it("keeps a list per secret scope", () => {
+ const narrow = acpModelScope(["OPENAI_API_KEY"]);
+ const haiku = [{ id: "haiku", label: "Haiku" }];
+ rememberAcpModels("cloud-1", "claude-code", ALL, MODELS);
+ rememberAcpModels("cloud-1", "claude-code", narrow, haiku);
+
+ expect(readRememberedAcpModels("cloud-1", "claude-code", ALL)).toEqual(
+ MODELS,
+ );
+ expect(readRememberedAcpModels("cloud-1", "claude-code", narrow)).toEqual(
+ haiku,
+ );
+ expect(
+ readRememberedAcpModels("cloud-1", "claude-code", acpModelScope([])),
+ ).toEqual([]);
+ });
+
+ it("names a scope by its secrets, whatever their order", () => {
+ expect(acpModelScope(["B", "A", "B"])).toBe(acpModelScope(["A", "B"]));
+ expect(acpModelScope([])).not.toBe(acpModelScope(null));
+ });
+
+ it("offers every scope's models when no scope is given", () => {
+ rememberAcpModels("cloud-1", "claude-code", ALL, MODELS);
+ rememberAcpModels("cloud-1", "claude-code", acpModelScope([]), [
+ { id: "sonnet", label: "Sonnet (again)" },
+ { id: "haiku", label: "Haiku" },
+ ]);
+
+ expect(readRememberedAcpModels("cloud-1", "claude-code")).toEqual([
+ ...MODELS,
+ { id: "haiku", label: "Haiku" },
+ ]);
+ });
+
+ it("does not replace a list with an empty one", () => {
+ rememberAcpModels("cloud-1", "claude-code", ALL, MODELS);
+ rememberAcpModels("cloud-1", "claude-code", ALL, []);
+
+ expect(readRememberedAcpModels("cloud-1", "claude-code", ALL)).toEqual(
+ MODELS,
+ );
+ });
+
+ it("drops entries that are not models", () => {
+ window.localStorage.setItem(
+ "openhands-acp-models:cloud-1:claude-code",
+ JSON.stringify({ "*": [...MODELS, { id: "" }, "haiku", null] }),
+ );
+
+ expect(readRememberedAcpModels("cloud-1", "claude-code", ALL)).toEqual(
+ MODELS,
+ );
+ });
+
+ it("returns nothing when storage cannot be read", () => {
+ vi.spyOn(window.localStorage, "getItem").mockImplementation(() => {
+ throw new Error("blocked");
+ });
+
+ expect(readRememberedAcpModels("cloud-1", "claude-code", ALL)).toEqual([]);
+ });
+});
diff --git a/docs/ACP_AGENTS.md b/docs/ACP_AGENTS.md
index fa5169ae03..aed79f6ba6 100644
--- a/docs/ACP_AGENTS.md
+++ b/docs/ACP_AGENTS.md
@@ -252,9 +252,28 @@ Open **Settings → Agent** at any time:
- **Command** — the command line used to spawn the subprocess. Selecting a preset
fills this in; editing it to match another preset re-detects that provider.
API keys are _not_ entered here — they live in the Secrets panel.
-- **Model** — choose a suggested model for the provider or enter a custom model
- override. Built-in providers save a concrete model rather than leaving it
- blank — except Pi, which picks its own from the configured credential.
+- **Credentials** — sign in or add the provider's keys. They come before the
+ model because the models a provider offers depend on them.
+- **Model** — **Agent default** (the provider picks, saving no model), one of
+ the provider's models, or a custom model ID. Gemini has no **Agent default**:
+ Canvas preselects `gemini-2.5-pro` (see the note above).
+
+Canvas keeps no list of models; the agent reports its own. On a local backend
+Canvas asks the agent-server (`POST /api/acp/models`) to start the provider with
+your saved credentials and report the models it offers and the one it uses by
+default, so account-dependent catalogues (a ChatGPT plan's Codex models, a Claude
+subscription's aliases, OpenCode's free tier versus a Zen key) show what you can
+actually run. The first lookup can take a few seconds while the provider starts;
+results are cached. If the agent rejects its login, Settings says so instead of
+showing a stale "signed in" banner.
+
+Cloud can't ask before a conversation starts, so until then the model field
+offers **Agent default** and a custom model ID. Each conversation's session
+reports its models, which the in-chat picker offers for switching mid-conversation;
+Canvas remembers the last list per backend, provider and secret scope in the
+browser and offers it in Settings and on the home page from then on, only to
+profiles that allow the same secrets (also the fallback for older agent-servers
+and failed lookups).
Saving writes an `agent_settings_diff` (`agent_kind`, `acp_server`,
`acp_command`, `acp_model`) to `PATCH /api/settings`. A running conversation
@@ -264,6 +283,8 @@ start afterward.
## Custom ACP servers
Any stdio ACP server works: choose **Custom** in Settings → Agent and enter its
-launch command. Custom servers have no curated model list, so enter the model ID
-the server expects (if any) as a custom model. Pass credentials by adding the
-env vars the server reads as global secrets under **Settings → Secrets**.
+launch command. Canvas can't ask a custom server for its models before a
+conversation, so enter the model ID the server expects (if any) as a custom
+model; inside a conversation the picker lists what the session reports. Pass
+credentials by adding the env vars the server reads as global secrets under
+**Settings → Secrets**.
diff --git a/src/api/acp-service/acp-service.api.ts b/src/api/acp-service/acp-service.api.ts
index 88dd9db3c7..643a64a9e3 100644
--- a/src/api/acp-service/acp-service.api.ts
+++ b/src/api/acp-service/acp-service.api.ts
@@ -1,5 +1,9 @@
-import { BashClient } from "@openhands/typescript-client/clients";
-import type { BashOutput } from "@openhands/typescript-client";
+import { ACPClient, BashClient } from "@openhands/typescript-client/clients";
+import type {
+ ACPModelDiscovery,
+ BashOutput,
+} from "@openhands/typescript-client";
+import { buildCustomSecrets } from "../agent-server-adapter";
import { getAgentServerClientOptions } from "../agent-server-client-options";
export type AcpAuthStatus = "authenticated" | "unauthenticated" | "unknown";
@@ -112,6 +116,21 @@ class AcpService {
).executeCommand(probe.command, undefined, PROBE_TIMEOUT_SECONDS);
return probe.classify(out);
}
+
+ /**
+ * Ask the (local) agent-server which models ``server`` offers and which one
+ * it picks by default, given the saved secrets named in ``secretNames``.
+ */
+ static async discoverModels(
+ server: string,
+ secretNames: readonly string[],
+ ): Promise<ACPModelDiscovery> {
+ const { host, apiKey } = getAgentServerClientOptions();
+ return new ACPClient({ host, apiKey }).discoverModels({
+ agent_settings: { agent_kind: "acp", acp_server: server },
+ secrets: buildCustomSecrets(secretNames.map((name) => ({ name }))),
+ });
+ }
}
export default AcpService;
diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.ts
index df604124e7..33902dd13b 100644
--- a/src/api/agent-server-adapter.ts
+++ b/src/api/agent-server-adapter.ts
@@ -4,6 +4,7 @@ import {
HookType,
} from "@openhands/typescript-client";
import type {
+ ACPModelInfo,
ConversationRuntimeInfo,
HookConfig,
} from "@openhands/typescript-client";
@@ -16,6 +17,7 @@ import {
getAcpPreferredDefaultModel,
getAcpProvider,
resolveEffectiveAcpModel,
+ toAcpModelOptions,
} from "#/constants/acp-providers";
import { getAgentServerClientOptions } from "./agent-server-client-options";
import {
@@ -128,6 +130,7 @@ export interface DirectConversationInfo {
} | null;
current_model_id?: string | null;
current_model_name?: string | null;
+ available_models?: ACPModelInfo[] | null;
workspace?: {
working_dir?: string | null;
} | null;
@@ -143,6 +146,7 @@ export interface DirectConversationInfo {
launched_agent_profile?: {
agent_profile_id: string;
revision: number;
+ secret_refs?: string[] | null;
} | null;
/**
* Server-owned, derived from the catalog's ``parent_conversation_id`` link
@@ -439,6 +443,9 @@ export function toAppConversation(
pr_number: [],
agent_kind: isAcp ? "acp" : "openhands",
acp_server: acpServer,
+ acp_available_models: isAcp
+ ? toAcpModelOptions(info.available_models)
+ : null,
tags: info.tags ?? null,
launched_agent_profile: info.launched_agent_profile ?? null,
// Chip path: omit ``providerDefault`` so that when no concrete model
@@ -1031,12 +1038,8 @@ function buildConfiguredAcpAgentSettings(
payload.mcp_config = mcpConfig;
}
- // Saved settings may carry ``acp_model: null`` (existing users predating
- // the default-model registry, or saved fields the agent-server stripped).
- // Fall back to the *preferred* default (Vertex-safe for Gemini) so the
- // conversation starts with whatever the Settings → Agent UI shows — without
- // that, the form's displayed default would silently not take effect at
- // runtime until the user re-saved the page.
+ // A saved ``acp_model: null`` leaves the agent on its own default, unless
+ // Canvas prefers another (see getAcpPreferredDefaultModel).
const serverKey =
typeof agentSettings.acp_server === "string"
? agentSettings.acp_server
@@ -1174,7 +1177,7 @@ interface LookupSecret {
}
/** A custom secret's public identity — name + optional description, no value. */
-type CustomSecretInput = { name: string; description?: string };
+export type CustomSecretInput = { name: string; description?: string };
type StartConversationPayloadBase = Record<string, unknown> & {
workspace: WorkspacePayload;
@@ -1262,7 +1265,7 @@ export interface StartConversationOptions {
* loopback fetch can't deadlock. Returns `undefined` when there are no custom
* secrets so callers can omit the field.
*/
-function buildCustomSecrets(
+export function buildCustomSecrets(
customSecrets: CustomSecretInput[] | undefined,
): Record<string, LookupSecret> | undefined {
if (!customSecrets?.length) return undefined;
diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.ts
index 1b7b2e1388..a90f3cf9c1 100644
--- a/src/api/conversation-service/agent-server-conversation-service.api.ts
+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts
@@ -1,4 +1,5 @@
import {
+ type ACPModelInfo,
ConversationSortOrder,
type ForkConversationRequest,
type LLMConfig,
@@ -65,6 +66,7 @@ import {
type WorkspaceMode,
} from "../conversation-metadata-store";
import { resolveTitleLlmProfile } from "#/utils/title-llm-profile";
+import { toAcpModelOptions } from "#/constants/acp-providers";
import { isPlannerConversationOf } from "#/utils/plan-file";
import { buildAutomationSetupModeTags } from "#/utils/automation-draft-tags";
import { AUTOMATION_FORM_UPDATE_CLIENT_TOOL } from "../automation-form-client-tool";
@@ -113,6 +115,20 @@ function stringOrNull(value: unknown): string | null {
return typeof value === "string" ? value : null;
}
+function normalizeAcpModels(value: unknown): ACPModelInfo[] {
+ if (!Array.isArray(value)) return [];
+ return value.flatMap((entry) => {
+ if (!isRecord(entry) || typeof entry.model_id !== "string") return [];
+ return [
+ {
+ model_id: entry.model_id,
+ name: stringOrNull(entry.name),
+ description: stringOrNull(entry.description),
+ },
+ ];
+ });
+}
+
function readTimestamp(
item: Record<string, unknown>,
snakeKey: "created_at" | "updated_at",
@@ -248,11 +264,21 @@ function normalizeLaunchedAgentProfile(
value: unknown,
): DirectConversationInfo["launched_agent_profile"] {
if (!isRecord(value)) return null;
- const { agent_profile_id: agentProfileId, revision } = value;
+ const {
+ agent_profile_id: agentProfileId,
+ revision,
+ secret_refs: secretRefs,
+ } = value;
if (typeof agentProfileId !== "string" || typeof revision !== "number") {
return null;
}
- return { agent_profile_id: agentProfileId, revision };
+ return {
+ agent_profile_id: agentProfileId,
+ revision,
+ secret_refs: Array.isArray(secretRefs)
+ ? secretRefs.filter((name): name is string => typeof name === "string")
+ : null,
+ };
}
function normalizeAbsolutePath(path: string): string | null {
@@ -319,6 +345,7 @@ function requireDirectConversationInfo(item: unknown): DirectConversationInfo {
// omit these — adapter handles ``undefined`` / ``null`` gracefully.
current_model_id: stringOrNull(item.current_model_id),
current_model_name: stringOrNull(item.current_model_name),
+ available_models: normalizeAcpModels(item.available_models),
};
}
@@ -943,6 +970,7 @@ class AgentServerConversationService {
updated_at: data.updated_at,
status: toRuntimeStatus(data.execution_status),
stats: data.stats ?? { usage_to_metrics: {} },
+ available_models: toAcpModelOptions(data.available_models),
};
}
diff --git a/src/api/conversation-service/agent-server-conversation-service.types.ts b/src/api/conversation-service/agent-server-conversation-service.types.ts
index 663e15d471..fe1d1cd17f 100644
--- a/src/api/conversation-service/agent-server-conversation-service.types.ts
+++ b/src/api/conversation-service/agent-server-conversation-service.types.ts
@@ -3,6 +3,7 @@ import type { ClientToolSpec } from "../canvas-ui-client-tool";
import { Provider } from "#/types/settings";
import { SuggestedTask } from "#/utils/types";
import { ExecutionStatus } from "#/types/agent-server/core";
+import type { ACPModelOption } from "#/constants/acp-providers";
/**
* Lifecycle state of a cloud sandbox. Mirrors OpenHands' V1SandboxStatus.
@@ -142,6 +143,8 @@ export interface ConversationWorkspace {
export interface LaunchedAgentProfile {
agent_profile_id: string;
revision: number;
+ /** The secrets the conversation may use; null is every saved secret. */
+ secret_refs?: string[] | null;
}
export interface AppConversation {
@@ -176,6 +179,11 @@ export interface AppConversation {
* "ACP" chip when the key is unknown or null.
*/
acp_server?: string | null;
+ /**
+ * Models the conversation's ACP session offers, as its server reported them.
+ * Empty before the session starts and on servers that don't report models.
+ */
+ acp_available_models?: ACPModelOption[] | null;
/**
* Server-side key-value tags from the agent-server's
* ``ConversationInfo.tags`` (settable at creation and via
@@ -310,4 +318,6 @@ export interface RuntimeConversationInfo {
updated_at: string;
status: ExecutionStatus;
stats: RuntimeConversationStats;
+ /** Models an ACP session reported; empty otherwise. */
+ available_models: ACPModelOption[];
}
diff --git a/src/components/features/chat/components/chat-input-model.tsx b/src/components/features/chat/components/chat-input-model.tsx
index bab1fbd78a..c4afd85bd3 100644
--- a/src/components/features/chat/components/chat-input-model.tsx
+++ b/src/components/features/chat/components/chat-input-model.tsx
@@ -56,8 +56,8 @@ export function ChatInputModelMenuContent({
// Locked-to-Cloud blocks the Canvas settings pages this links to (OHE-3457).
const showSettingsLink = getLockedCloudHost() === null;
- const handleSelectAcpModel = (modelId: string) => {
- if (modelId !== model.currentModelId) {
+ const handleSelectAcpModel = (modelId: string | null) => {
+ if (modelId !== model.selectedModelId) {
switchAcpModel.mutate({
conversationId: model.switchConversationId,
model: modelId,
@@ -78,12 +78,17 @@ export function ChatInputModelMenuContent({
{t(I18nKey.MODEL$AVAILABLE_MODELS)}
</Typography.Text>
</li>
- {model.availableAcpModels.map((option) => {
- const isSelected = option.id === model.currentModelId;
+ {[
+ ...(model.agentDefaultLabel
+ ? [{ id: null, label: model.agentDefaultLabel }]
+ : []),
+ ...model.availableAcpModels,
+ ].map((option) => {
+ const isSelected = option.id === model.selectedModelId;
return (
<ContextMenuListItem
- key={option.id}
- testId={`chat-input-acp-model-option-${option.id}`}
+ key={option.id ?? ""}
+ testId={`chat-input-acp-model-option-${option.id ?? "agent-default"}`}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
diff --git a/src/components/features/conversation-panel/compact-conversation-row.tsx b/src/components/features/conversation-panel/compact-conversation-row.tsx
index 1e44139d00..4ab3740dc7 100644
--- a/src/components/features/conversation-panel/compact-conversation-row.tsx
+++ b/src/components/features/conversation-panel/compact-conversation-row.tsx
@@ -1,6 +1,7 @@
import React from "react";
import { Tooltip } from "@heroui/react";
import { useTranslation } from "react-i18next";
+import type { ACPModelOption } from "#/constants/acp-providers";
import { NavigationLink } from "#/components/shared/navigation-link";
import { ExecutionStatus } from "#/types/agent-server/core/base/common";
import { SandboxStatus } from "#/api/conversation-service/agent-server-conversation-service.types";
@@ -27,6 +28,7 @@ interface CompactConversationRowProps {
showLlmProfiles?: boolean;
agentKind?: "openhands" | "acp" | null;
acpServer?: string | null;
+ acpModels?: readonly ACPModelOption[] | null;
tags?: Record<string, string> | null;
showTags?: boolean;
}
@@ -52,6 +54,7 @@ export function CompactConversationRow({
showLlmProfiles = false,
agentKind = null,
acpServer = null,
+ acpModels = null,
tags = null,
showTags = false,
}: CompactConversationRowProps) {
@@ -85,6 +88,7 @@ export function CompactConversationRow({
showAgentChip={showLlmProfiles}
agentKind={agentKind}
acpServer={acpServer}
+ acpModels={acpModels}
tags={tags}
showTags={showTags}
/>
diff --git a/src/components/features/conversation-panel/conversation-card/conversation-card-footer.tsx b/src/components/features/conversation-panel/conversation-card/conversation-card-footer.tsx
index 829340b2ff..81dcd380ea 100644
--- a/src/components/features/conversation-panel/conversation-card/conversation-card-footer.tsx
+++ b/src/components/features/conversation-panel/conversation-card/conversation-card-footer.tsx
@@ -6,11 +6,13 @@ import { RepositorySelection } from "#/api/open-hands.types";
import { ExecutionStatus } from "#/types/agent-server/core/base/common";
import { isExecutionPaused } from "#/utils/status";
import {
+ type ACPModelOption,
getAcpProviderDisplayName,
labelForAcpModel,
resolveAcpProviderIcon,
} from "#/constants/acp-providers";
import { useFreeModels } from "#/hooks/query/use-free-models";
+import { useRememberedAcpModels } from "#/hooks/use-remembered-acp-models";
import { formatNativeModelName } from "#/utils/format-model-name";
import {
AgentBrandIcon,
@@ -52,6 +54,8 @@ interface ConversationCardFooterProps {
* useful chip.
*/
acpServer?: string | null;
+ /** The models this conversation's session reported. */
+ acpModels?: readonly ACPModelOption[] | null;
/**
* Server-side conversation tags (``AppConversation.tags``). Non-reserved
* entries render as value-only chips so API-/automation-born
@@ -83,12 +87,14 @@ export function ConversationCardFooter({
showAgentChip = false,
agentKind = null,
acpServer = null,
+ acpModels = null,
tags = null,
showTags = false,
isArchived = false,
}: ConversationCardFooterProps) {
const { t } = useTranslation("openhands");
const freeModels = useFreeModels();
+ const rememberedModels = useRememberedAcpModels(acpServer);
const isPaused = isExecutionPaused(executionStatus);
@@ -108,10 +114,12 @@ export function ConversationCardFooter({
const providerName =
getAcpProviderDisplayName(acpServer) ??
t(I18nKey.CONVERSATION$ACP_AGENT_GENERIC);
- // Prefer the provider's picker label (e.g. "Claude Opus 4.7") over the
- // raw ``acp_model`` ID; falls back to the raw ID for custom overrides
- // and to the provider name when there's no model at all.
- const modelLabel = labelForAcpModel(acpServer, llmModel);
+ // Prefer the label the agent gave the model over its raw ID, and the
+ // provider name when there's no model at all.
+ const modelLabel = labelForAcpModel(
+ llmModel,
+ acpModels?.length ? acpModels : rememberedModels,
+ );
const text = modelLabel ?? providerName;
chip = {
kind: resolveAcpProviderIcon(acpServer),
diff --git a/src/components/features/conversation-panel/conversation-card/conversation-card.tsx b/src/components/features/conversation-panel/conversation-card/conversation-card.tsx
index 7410d6a8b1..7e37e920a0 100644
--- a/src/components/features/conversation-panel/conversation-card/conversation-card.tsx
+++ b/src/components/features/conversation-panel/conversation-card/conversation-card.tsx
@@ -1,6 +1,7 @@
import React from "react";
import { Pin } from "lucide-react";
import { useTranslation } from "react-i18next";
+import type { ACPModelOption } from "#/constants/acp-providers";
import { useTracking } from "#/hooks/use-tracking";
import { cn } from "#/utils/utils";
import { I18nKey } from "#/i18n/declaration";
@@ -58,6 +59,7 @@ interface ConversationCardProps {
showLlmProfiles?: boolean;
agentKind?: "openhands" | "acp" | null;
acpServer?: string | null;
+ acpModels?: readonly ACPModelOption[] | null;
tags?: Record<string, string> | null;
/** Gates the tag-chip row; wired to the panel's "Tags" metadata toggle. */
showTags?: boolean;
@@ -93,6 +95,7 @@ export function ConversationCard({
showLlmProfiles = false,
agentKind = null,
acpServer = null,
+ acpModels = null,
tags = null,
showTags = false,
isArchived = false,
@@ -378,6 +381,7 @@ export function ConversationCard({
showAgentChip={showLlmProfiles}
agentKind={agentKind}
acpServer={acpServer}
+ acpModels={acpModels}
tags={tags}
showTags={showTagChipRow}
isArchived={isArchived}
diff --git a/src/components/features/conversation-panel/conversation-panel.tsx b/src/components/features/conversation-panel/conversation-panel.tsx
index ca224cfc6a..165541a989 100644
--- a/src/components/features/conversation-panel/conversation-panel.tsx
+++ b/src/components/features/conversation-panel/conversation-panel.tsx
@@ -882,6 +882,7 @@ export function ConversationPanel({
showLlmProfiles={showLlmProfiles}
agentKind={conversation.agent_kind}
acpServer={conversation.acp_server}
+ acpModels={conversation.acp_available_models}
tags={conversation.tags}
showTags={showTagsMetadata}
/>
@@ -985,6 +986,7 @@ export function ConversationPanel({
showLlmProfiles={showLlmProfiles}
agentKind={conversation.agent_kind}
acpServer={conversation.acp_server}
+ acpModels={conversation.acp_available_models}
tags={conversation.tags}
showTags={showTagsMetadata}
isArchived={isArchived}
diff --git a/src/components/features/settings/acp-credentials-section.tsx b/src/components/features/settings/acp-credentials-section.tsx
index 6da74b7bb3..35c0ac7d5a 100644
--- a/src/components/features/settings/acp-credentials-section.tsx
+++ b/src/components/features/settings/acp-credentials-section.tsx
@@ -19,9 +19,12 @@ import type { AcpCredentialForm } from "#/hooks/use-acp-credential-form";
export function AcpCredentialsSection({
form,
providerKey,
+ loginRejected = false,
}: {
form: AcpCredentialForm;
providerKey: string;
+ /** The agent itself refused its login, whatever the local check found. */
+ loginRejected?: boolean;
}) {
const { t } = useTranslation("openhands");
const {
@@ -49,7 +52,7 @@ export function AcpCredentialsSection({
</div>
<AcpAuthStatusBanner
- status={authStatus}
+ status={loginRejected ? "unauthenticated" : authStatus}
isChecking={isChecking}
credentialsConfigured={credentialsConfigured}
providerName={providerName}
diff --git a/src/constants/acp-providers.test.ts b/src/constants/acp-providers.test.ts
index 8f5e81227a..d94f2389a8 100644
--- a/src/constants/acp-providers.test.ts
+++ b/src/constants/acp-providers.test.ts
@@ -10,25 +10,11 @@ import {
} from "./acp-providers";
describe("ACP_PROVIDERS", () => {
- it("passes every codex data field through from the pinned client registry", () => {
- // No local override may sit between the registry and the picker: a
- // hand-maintained model entry survives an upstream *removal*, so Canvas
- // would keep offering an id the live ACP server has started rejecting.
+ it("passes the codex launch command through from the pinned client registry", () => {
const codex = ACP_PROVIDERS.find(({ key }) => key === "codex");
- const client = CLIENT_ACP_PROVIDERS.codex;
- expect(codex?.default_command).toEqual([...client.default_command]);
- expect(codex?.available_models).toEqual(
- client.available_models.map(({ id, label }) => ({ id, label })),
- );
- });
-
- it("carries GPT-6 Astra, so the pin is new enough to launch it", () => {
- // Canary for the pin's freshness, not a catalog Canvas maintains: Astra
- // needs codex-acp >= 1.10.0, which only client >= 1.45.0 mirrors.
- const codex = ACP_PROVIDERS.find(({ key }) => key === "codex");
- expect(codex?.available_models?.map(({ id }) => id)).toContain(
- "gpt-6-astra",
- );
+ expect(codex?.default_command).toEqual([
+ ...CLIENT_ACP_PROVIDERS.codex.default_command,
+ ]);
});
});
diff --git a/src/constants/acp-providers.ts b/src/constants/acp-providers.ts
index f22d601e6c..524f3e0482 100644
--- a/src/constants/acp-providers.ts
+++ b/src/constants/acp-providers.ts
@@ -1,4 +1,7 @@
-import { getAcpProvider as getClientAcpProvider } from "@openhands/typescript-client";
+import {
+ getAcpProvider as getClientAcpProvider,
+ type ACPModelInfo,
+} from "@openhands/typescript-client";
import type { BackendKind } from "#/api/backend-registry/types";
import { I18nKey } from "#/i18n/declaration";
@@ -69,8 +72,8 @@ export function resolveEffectiveAcpModel(inputs: {
/**
* Shape of a built-in ACP (Agent Client Protocol) provider as Canvas consumes
- * it. The data fields (display name, launch command, model picker + default)
- * are sourced at module load from ``@openhands/typescript-client``'s ACP
+ * it. The data fields (display name, launch command) are sourced at module
+ * load from ``@openhands/typescript-client``'s ACP
* registry — the generated mirror of the Python source of truth
* ``openhands.sdk.settings.acp_providers``. This config only adds the
* Canvas-specific UI fields ({@link ACPProviderConfig.icon} +
@@ -93,14 +96,6 @@ export interface ACPProviderConfig {
* ``@agentclientprotocol/codex-acp`` (the codex ACP wrapper) instead.
*/
default_command: string[];
- /**
- * Suggested ACP model IDs for the provider's picker, sourced from the
- * typescript-client registry. Not authoritative access checks; users can
- * still enter a custom override in Settings -> Agent.
- */
- available_models?: ACPModelOption[];
- /** Model ID preselected for the provider; absent when it picks its own. */
- default_model?: string;
/**
* i18n key for the one-line provider description rendered under the
* onboarding tile. Stored on the registry so adding a new ACP
@@ -126,10 +121,10 @@ export interface ACPModelOption {
}
// Canvas-only UI metadata per built-in provider, keyed by the ACP registry
-// key. Everything else — display name, launch command, model picker list and
-// default — comes from the typescript-client registry below. Adding a model
-// or a provider happens upstream in the SDK; Canvas only owns the brand icon
-// and the onboarding-tile description here. Its keys are the harnesses Canvas
+// key. The display name and launch command come from the typescript-client
+// registry below; models come from the agent itself. Adding a provider
+// happens upstream in the SDK; Canvas only owns the brand icon and the
+// onboarding-tile description here. Its keys are the harnesses Canvas
// offers — see {@link SURFACED_ACP_PROVIDERS}.
const ACP_PROVIDER_UI: Record<
string,
@@ -159,13 +154,6 @@ const ACP_PROVIDER_UI: Record<
},
};
-function getAvailableModels(key: string): ACPModelOption[] | undefined {
- return getClientAcpProvider(key)?.available_models?.map((model) => ({
- id: model.id,
- label: model.label,
- }));
-}
-
/**
* The ACP harnesses Canvas surfaces — its own declaration of what it offers,
* independent of what the SDK registry happens to contain. Registering a
@@ -186,8 +174,6 @@ export const ACP_PROVIDERS: ACPProviderConfig[] = Object.entries(
key,
display_name: info?.display_name ?? key,
default_command: info ? [...info.default_command] : [],
- available_models: getAvailableModels(key),
- default_model: info?.default_model ?? undefined,
description_key: ui.description_key,
icon: ui.icon,
local_only: ui.local_only,
@@ -361,26 +347,16 @@ export function getAcpCredentialConflicts(
export const ACP_VERTEX_SAFE_MODEL = "gemini-2.5-pro";
/**
- * The default ``acp_model`` canvas substitutes for ``providerKey`` wherever no
- * concrete model is configured — settings seeding (onboarding, Settings →
- * Agent), the {@link buildAcpAgentSettingsDiff} fallback, and the start-request
- * fallback for a saved ``null``. Overrides only Gemini (→
- * {@link ACP_VERTEX_SAFE_MODEL}, see why above); every other provider keeps its
- * registry {@link ACPProviderConfig.default_model}. Returns ``null`` when
- * there's no override and no registry default, letting the ACP server pick its
- * own.
- *
- * Distinct from {@link ACPProviderConfig.default_model} (which mirrors the SDK
- * registry verbatim, closing agent-canvas#740): this is the *preferred* default,
- * deliberately diverging for Gemini where the registry value isn't safe on
- * every backend — so every default-model surface must route through this, not
- * read ``default_model`` directly.
+ * The ``acp_model`` canvas substitutes for ``providerKey`` wherever no concrete
+ * model is configured — settings seeding (onboarding, Settings → Agent), the
+ * {@link buildAcpAgentSettingsDiff} fallback, and the start-request fallback
+ * for a saved ``null``. ``null`` lets the agent use its own default; only
+ * Gemini's own default is unsafe (see {@link ACP_VERTEX_SAFE_MODEL}).
*/
export function getAcpPreferredDefaultModel(
key: string | null | undefined,
): string | null {
- if (key === "gemini-cli") return ACP_VERTEX_SAFE_MODEL;
- return getAcpProvider(key)?.default_model ?? null;
+ return key === "gemini-cli" ? ACP_VERTEX_SAFE_MODEL : null;
}
/**
@@ -498,23 +474,28 @@ export function resolveAcpProviderIcon(
}
/**
- * Resolve a raw ``acp_model`` ID to the human-readable label the provider's
- * picker shows for it (e.g. ``"claude-opus-4-7"`` → ``"Claude Opus 4.7"``).
- *
- * Falls back to the raw ID when the provider is unknown or the ID isn't one
- * of its registered {@link ACPModelOption}s — so a user's custom override
- * still renders something meaningful rather than nothing. Returns ``null``
- * only when there is no model to show, letting the conversation chip decide
- * to display the provider name instead.
+ * The label the agent gave ``modelId`` in ``models``, else the raw ID. Returns
+ * ``null`` only when there is no model to show, letting the conversation chip
+ * display the provider name instead.
*/
export function labelForAcpModel(
- serverKey: string | null | undefined,
modelId: string | null | undefined,
+ models: readonly ACPModelOption[] = [],
): string | null {
if (!modelId) return null;
- const provider = getAcpProvider(serverKey);
- const match = provider?.available_models?.find((m) => m.id === modelId);
- return match?.label ?? modelId;
+ return models.find(({ id }) => id === modelId)?.label ?? modelId;
+}
+
+/** Picker options for the models an ACP server reported. */
+export function toAcpModelOptions(
+ models: readonly ACPModelInfo[] | null | undefined,
+): ACPModelOption[] {
+ return (models ?? [])
+ .filter(({ model_id }) => model_id)
+ .map(({ model_id, name }) => ({
+ id: model_id,
+ label: name?.trim() || model_id,
+ }));
}
/**
@@ -549,8 +530,6 @@ export function buildAcpAgentSettingsDiff(
acp_server: providerKey,
acp_command: [],
acp_args: [],
- // The *preferred* default (Vertex-safe for Gemini), not the raw registry
- // default — see getAcpPreferredDefaultModel.
acp_model: getAcpPreferredDefaultModel(providerKey) ?? null,
};
}
diff --git a/src/hooks/mutation/use-switch-acp-model.ts b/src/hooks/mutation/use-switch-acp-model.ts
index 615027da3e..093fb8949f 100644
--- a/src/hooks/mutation/use-switch-acp-model.ts
+++ b/src/hooks/mutation/use-switch-acp-model.ts
@@ -21,7 +21,8 @@ interface SwitchAcpModelVars {
* is persisted as the default the next conversation launches with.
*/
conversationId: string | null;
- model: string;
+ /** Null saves no model, so the next conversation starts on the agent's own default. */
+ model: string | null;
}
/**
@@ -51,10 +52,12 @@ export const useSwitchAcpModel = () => {
return useMutation({
mutationFn: async ({ conversationId, model }: SwitchAcpModelVars) => {
if (conversationId) {
- await AgentServerConversationService.switchAcpModel(
- conversationId,
- model,
- );
+ if (model) {
+ await AgentServerConversationService.switchAcpModel(
+ conversationId,
+ model,
+ );
+ }
return;
}
diff --git a/src/hooks/query/query-keys.ts b/src/hooks/query/query-keys.ts
index d909e6ae3a..c7e276602c 100644
--- a/src/hooks/query/query-keys.ts
+++ b/src/hooks/query/query-keys.ts
@@ -26,6 +26,10 @@ export const META_PROFILES_QUERY_KEYS = {
all: ["meta-profiles"] as const,
} as const;
+export const ACP_MODEL_DISCOVERY_QUERY_KEYS = {
+ all: ["acp-model-discovery"] as const,
+} as const;
+
export const AGENT_PROFILES_QUERY_KEYS = {
all: ["agent-profiles"] as const,
// Nested under `all` so profile mutations invalidate cached details too.
diff --git a/src/hooks/query/use-acp-model-discovery.ts b/src/hooks/query/use-acp-model-discovery.ts
new file mode 100644
index 0000000000..fd88e8d26b
--- /dev/null
+++ b/src/hooks/query/use-acp-model-discovery.ts
@@ -0,0 +1,106 @@
+import { useEffect, useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import type { ACPModelDiscovery } from "@openhands/typescript-client";
+import AcpService from "#/api/acp-service/acp-service.api";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { useSearchSecrets } from "#/hooks/query/use-get-secrets";
+import { ACP_MODEL_DISCOVERY_QUERY_KEYS } from "#/hooks/query/query-keys";
+import {
+ toAcpModelOptions,
+ type ACPModelOption,
+} from "#/constants/acp-providers";
+import { useRememberedAcpModels } from "#/hooks/use-remembered-acp-models";
+import {
+ acpModelScope,
+ rememberAcpModels,
+} from "#/utils/remembered-acp-models";
+
+async function discover(
+ providerKey: string,
+ secretNames: string[],
+): Promise<ACPModelDiscovery | null> {
+ try {
+ return await AcpService.discoverModels(providerKey, secretNames);
+ } catch {
+ // Older agent-servers lack the endpoint.
+ return null;
+ }
+}
+
+/** Where {@link useAcpModelDiscovery}'s ``models`` came from. */
+export type AcpModelSource = "live" | "remembered" | "none";
+
+/**
+ * The models a built-in ACP provider offers on the active backend, and the one
+ * it uses by default, as its own server reports them for the saved
+ * credentials. Only local backends can ask before a conversation starts;
+ * otherwise ``models`` is the list the agent last reported with the same
+ * secrets. ``secretRefs`` limits the lookup to the secrets a launch would
+ * receive; null means every saved secret.
+ */
+export function useAcpModelDiscovery(
+ providerKey: string | null | undefined,
+ {
+ enabled = true,
+ secretRefs = null,
+ }: { enabled?: boolean; secretRefs?: readonly string[] | null } = {},
+) {
+ const { backend } = useActiveBackend();
+ const isLocal = backend.kind === "local";
+ const secrets = useSearchSecrets({ enabled: enabled && isLocal });
+ const secretNames = secrets.data
+ .map(({ name }) => name)
+ .filter((name) => !secretRefs || secretRefs.includes(name))
+ .sort();
+ const queryEnabled =
+ enabled && isLocal && !!providerKey && !secrets.isLoading;
+
+ const query = useQuery<ACPModelDiscovery | null, Error>({
+ queryKey: [
+ ...ACP_MODEL_DISCOVERY_QUERY_KEYS.all,
+ backend.id,
+ providerKey,
+ secretNames,
+ ],
+ queryFn: () => discover(providerKey as string, secretNames),
+ enabled: queryEnabled,
+ staleTime: 1000 * 60 * 5,
+ gcTime: 1000 * 60 * 15,
+ retry: false,
+ refetchOnWindowFocus: false,
+ });
+
+ const scope = acpModelScope(secretRefs);
+ const discovery = queryEnabled ? (query.data ?? null) : null;
+ const liveModels = useMemo(
+ () => toAcpModelOptions(discovery?.available_models),
+ [discovery],
+ );
+ useEffect(() => {
+ if (providerKey) {
+ rememberAcpModels(backend.id, providerKey, scope, liveModels);
+ }
+ }, [backend.id, providerKey, scope, liveModels]);
+
+ const remembered = useRememberedAcpModels(
+ enabled ? providerKey : null,
+ scope,
+ );
+ let models: ACPModelOption[] = [];
+ let source: AcpModelSource = "none";
+ if (liveModels.length) {
+ models = liveModels;
+ source = "live";
+ } else if (remembered.length) {
+ models = remembered;
+ source = "remembered";
+ }
+
+ return {
+ discovery,
+ models,
+ source,
+ defaultModelId: discovery?.current_model_id ?? null,
+ isDiscovering: queryEnabled && query.isFetching && !query.data,
+ };
+}
diff --git a/src/hooks/query/use-acp-session-models.ts b/src/hooks/query/use-acp-session-models.ts
new file mode 100644
index 0000000000..6234eab415
--- /dev/null
+++ b/src/hooks/query/use-acp-session-models.ts
@@ -0,0 +1,68 @@
+import { useEffect, useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { getAcpProvider, type ACPModelOption } from "#/constants/acp-providers";
+import {
+ acpModelScope,
+ rememberAcpModels,
+} from "#/utils/remembered-acp-models";
+
+const NO_MODELS: ACPModelOption[] = [];
+
+/**
+ * The models an ACP conversation's session reported. Cloud conversations
+ * carry no list, so it is read from the conversation's sandbox. Lists from
+ * built-in agents are remembered under the secrets the conversation may use.
+ */
+export function useAcpSessionModels(
+ conversation: AppConversation | null | undefined,
+): ACPModelOption[] {
+ const { backend } = useActiveBackend();
+ const isCloud = backend.kind === "cloud";
+ const id = conversation?.id;
+ const conversationUrl = conversation?.conversation_url;
+ const sessionApiKey = conversation?.session_api_key;
+ const enabled =
+ isCloud &&
+ !!id &&
+ !!conversationUrl &&
+ !!sessionApiKey &&
+ conversation?.sandbox_status === "RUNNING";
+
+ const runtime = useQuery({
+ queryKey: ["acp-session-models", id, conversationUrl, sessionApiKey],
+ queryFn: async () =>
+ (
+ await AgentServerConversationService.getRuntimeConversation(
+ id as string,
+ conversationUrl,
+ sessionApiKey,
+ )
+ ).available_models,
+ enabled,
+ // The session reports its list once it starts; stop asking after that.
+ refetchInterval: (query) => (query.state.data?.length ? false : 10_000),
+ staleTime: Infinity,
+ retry: false,
+ });
+
+ const models = useMemo(
+ () =>
+ (isCloud ? runtime.data : conversation?.acp_available_models) ??
+ NO_MODELS,
+ [isCloud, runtime.data, conversation?.acp_available_models],
+ );
+ const server = conversation?.acp_server;
+ const scope = acpModelScope(
+ conversation?.launched_agent_profile?.secret_refs,
+ );
+ useEffect(() => {
+ if (server && getAcpProvider(server)) {
+ rememberAcpModels(backend.id, server, scope, models);
+ }
+ }, [backend.id, server, scope, models]);
+
+ return models;
+}
diff --git a/src/hooks/use-chat-input-model-state.ts b/src/hooks/use-chat-input-model-state.ts
index 6a81e52505..d42b8de23d 100644
--- a/src/hooks/use-chat-input-model-state.ts
+++ b/src/hooks/use-chat-input-model-state.ts
@@ -1,3 +1,4 @@
+import { useTranslation } from "react-i18next";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { useSettings } from "#/hooks/query/use-settings";
import {
@@ -8,6 +9,8 @@ import { useActiveBackend } from "#/contexts/active-backend-context";
import { useCanManageOrgProfiles } from "#/hooks/use-can-manage-org-profiles";
import { useActiveAcpProfileDetail } from "#/hooks/query/use-active-acp-profile-detail";
import { useOptionalConversationId } from "#/hooks/use-conversation-id";
+import { useAcpModelDiscovery } from "#/hooks/query/use-acp-model-discovery";
+import { useAcpSessionModels } from "#/hooks/query/use-acp-session-models";
import {
getAcpPreferredDefaultModel,
getAcpProvider,
@@ -15,12 +18,17 @@ import {
resolveEffectiveAcpModel,
type ACPModelOption,
} from "#/constants/acp-providers";
+import { I18nKey } from "#/i18n/declaration";
export interface ChatInputModelState {
isAcpContext: boolean;
displayModel: string | null;
currentModelId: string | null;
+ /** The saved choice the picker marks; null is the agent's own default. */
+ selectedModelId: string | null;
availableAcpModels: ACPModelOption[];
+ /** The picker's Agent default row, or null when it isn't offered. */
+ agentDefaultLabel: string | null;
showAcpPicker: boolean;
switchConversationId: string | null;
destinationPath: AcpModelContext["destinationPath"];
@@ -28,6 +36,7 @@ export interface ChatInputModelState {
}
export function useChatInputModelState(): ChatInputModelState {
+ const { t } = useTranslation("openhands");
const { data: conversation } = useActiveConversation();
const { data: settings } = useSettings();
const { conversationId } = useOptionalConversationId();
@@ -57,6 +66,20 @@ export function useChatInputModelState(): ChatInputModelState {
? (activeAcpProfile?.acp_server ?? settingsAcpServerKey)
: null;
const acpProvider = isAcpContext ? getAcpProvider(acpServerKey) : undefined;
+ // The agent's models depend on the secrets it may use: the ones the
+ // conversation launched with, or the next launch's from the active profile.
+ const discovered = useAcpModelDiscovery(acpProvider ? acpServerKey : null, {
+ enabled: isActiveAcpConversation || !!activeAcpProfile,
+ secretRefs:
+ (isActiveAcpConversation
+ ? conversation?.launched_agent_profile?.secret_refs
+ : activeAcpProfile?.secret_refs) ?? null,
+ });
+ // The session's own list arrives only after it starts.
+ const sessionModels = useAcpSessionModels(
+ isActiveAcpConversation ? conversation : null,
+ );
+ const liveModels = sessionModels.length ? sessionModels : discovered.models;
const settingsAcpModel =
typeof settings?.agent_settings?.acp_model === "string"
@@ -71,32 +94,32 @@ export function useChatInputModelState(): ChatInputModelState {
: settingsAcpModel;
let currentModelId: string | null = null;
+ let selectedModelId: string | null = null;
if (isActiveAcpConversation) {
- // ACP conversations store llm_model as the acp_model (persisted at
- // creation time). Use it directly if available; fall back to the
- // settings-configured model or provider default so the chip stays visible.
+ // The settings may name another provider's model, so never fall back to them.
currentModelId =
- conversation?.llm_model ??
- resolveEffectiveAcpModel({
- configured: acpConfiguredModel,
- providerDefault: getAcpPreferredDefaultModel(acpServerKey),
- });
+ conversation?.llm_model ?? getAcpPreferredDefaultModel(acpServerKey);
+ selectedModelId = currentModelId;
} else if (isHomeAcp) {
- currentModelId = resolveEffectiveAcpModel({
+ selectedModelId = resolveEffectiveAcpModel({
configured: acpConfiguredModel,
// Preferred default (Vertex-safe for Gemini) — must match what the
// start request would substitute for an unconfigured model.
providerDefault: getAcpPreferredDefaultModel(acpServerKey),
});
+ currentModelId = selectedModelId ?? discovered.defaultModelId;
} else {
currentModelId = conversation?.llm_model ?? settings?.llm_model ?? null;
}
- const displayModel =
- currentModelId && isAcpContext
- ? (labelForAcpModel(acpServerKey, currentModelId) ?? currentModelId)
- : currentModelId;
- const availableAcpModels = acpProvider?.available_models ?? [];
+ let displayModel = currentModelId;
+ if (isAcpContext) {
+ displayModel =
+ labelForAcpModel(currentModelId, liveModels) ??
+ // The next conversation starts on a default no one has reported yet.
+ (isHomeAcp ? t(I18nKey.SETTINGS$AGENT_MODEL_AGENT_DEFAULT) : null);
+ }
+ const availableAcpModels = isAcpContext ? liveModels : [];
// A home-page pick persists into the active ACP profile, which on cloud is
// org-owned — hide the selectable rows from members who'd only get a 403.
// Conversation-scoped switches (blank or started) stay member-allowed.
@@ -104,6 +127,18 @@ export function useChatInputModelState(): ChatInputModelState {
!isHomeAcp || backend.kind !== "cloud" || canManageOrgProfiles;
const showAcpPicker =
isAcpContext && availableAcpModels.length > 0 && canPersistHomeAcpModel;
+ let agentDefaultLabel: string | null = null;
+ if (isHomeAcp && acpProvider && !getAcpPreferredDefaultModel(acpServerKey)) {
+ const defaultModelLabel = labelForAcpModel(
+ discovered.defaultModelId,
+ liveModels,
+ );
+ agentDefaultLabel = defaultModelLabel
+ ? t(I18nKey.SETTINGS$AGENT_MODEL_AGENT_DEFAULT_IS, {
+ model: defaultModelLabel,
+ })
+ : t(I18nKey.SETTINGS$AGENT_MODEL_AGENT_DEFAULT);
+ }
const switchConversationId = isActiveAcpConversation
? (conversationId ?? null)
: null;
@@ -112,7 +147,9 @@ export function useChatInputModelState(): ChatInputModelState {
isAcpContext,
displayModel,
currentModelId,
+ selectedModelId,
availableAcpModels,
+ agentDefaultLabel,
showAcpPicker,
switchConversationId,
destinationPath,
diff --git a/src/hooks/use-remembered-acp-models.ts b/src/hooks/use-remembered-acp-models.ts
new file mode 100644
index 0000000000..06f70d574c
--- /dev/null
+++ b/src/hooks/use-remembered-acp-models.ts
@@ -0,0 +1,24 @@
+import { useMemo, useSyncExternalStore } from "react";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import {
+ parseRememberedAcpModels,
+ readRememberedAcpModelsRaw,
+ subscribeRememberedAcpModels,
+} from "#/utils/remembered-acp-models";
+
+/**
+ * The models ``providerKey`` last reported on this backend under ``scope``, or
+ * under any scope when omitted.
+ */
+export function useRememberedAcpModels(
+ providerKey: string | null | undefined,
+ scope?: string,
+) {
+ const { backend } = useActiveBackend();
+ const raw = useSyncExternalStore(
+ subscribeRememberedAcpModels,
+ () => readRememberedAcpModelsRaw(backend.id, providerKey),
+ () => null,
+ );
+ return useMemo(() => parseRememberedAcpModels(raw, scope), [raw, scope]);
+}
diff --git a/src/hooks/use-save-acp-secrets.ts b/src/hooks/use-save-acp-secrets.ts
index b35d4e5400..5bdad2278f 100644
--- a/src/hooks/use-save-acp-secrets.ts
+++ b/src/hooks/use-save-acp-secrets.ts
@@ -4,6 +4,7 @@ import { useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { I18nKey } from "#/i18n/declaration";
import { useCreateSecret } from "#/hooks/mutation/use-create-secret";
+import { ACP_MODEL_DISCOVERY_QUERY_KEYS } from "#/hooks/query/query-keys";
import { type ACPProviderSecretField } from "#/constants/acp-providers";
import {
displayErrorToast,
@@ -64,6 +65,9 @@ export function useSaveAcpSecrets(
}
await queryClient.invalidateQueries({ queryKey: ["secrets-search"] });
await queryClient.invalidateQueries({ queryKey: ["secrets"] });
+ await queryClient.invalidateQueries({
+ queryKey: ACP_MODEL_DISCOVERY_QUERY_KEYS.all,
+ });
const savedOrphanedFileCredential =
!consumesFileCredentials && toSave.some(({ field }) => field.multiline);
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 91e6971c58..f47a86d85b 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -7123,21 +7123,140 @@
"ca": "Model personalitzat"
},
"SETTINGS$AGENT_MODEL_HINT": {
- "en": "Choose a suggested ACP model or enter a custom model override. Built-in providers save a concrete model instead of leaving the model blank.",
- "ja": "推奨される ACP モデルを選択するか、カスタムモデルの上書きを入力してください。組み込みプロバイダーはモデルを空白のままにせず、具体的なモデルを保存します。",
- "zh-CN": "选择一个建议的 ACP 模型,或输入自定义模型覆盖。内置提供商会保存一个具体的模型,而不是将模型留空。",
- "zh-TW": "選擇一個建議的 ACP 模型,或輸入自訂模型覆寫。內建供應商會儲存具體的模型,而不是將模型留空。",
- "ko-KR": "추천 ACP 모델을 선택하거나 사용자 정의 모델 재정의를 입력하세요. 기본 제공 공급자는 모델을 비워두지 않고 구체적인 모델을 저장합니다.",
- "no": "Velg en foreslått ACP-modell eller skriv inn en egendefinert modelloverstyring. Innebygde leverandører lagrer en konkret modell i stedet for å la modellen være tom.",
- "it": "Scegli un modello ACP suggerito o inserisci una sostituzione personalizzata. I provider integrati salvano un modello concreto invece di lasciarlo vuoto.",
- "pt": "Escolha um modelo ACP sugerido ou insira uma substituição de modelo personalizada. Os provedores integrados salvam um modelo concreto em vez de deixá-lo em branco.",
- "es": "Elige un modelo ACP sugerido o introduce una sustitución de modelo personalizada. Los proveedores integrados guardan un modelo concreto en lugar de dejarlo en blanco.",
- "ar": "اختر نموذج ACP مقترحًا أو أدخل تجاوزًا لنموذج مخصص. تقوم المزودات المدمجة بحفظ نموذج محدد بدلًا من ترك النموذج فارغًا.",
- "fr": "Choisissez un modèle ACP suggéré ou saisissez un remplacement de modèle personnalisé. Les fournisseurs intégrés enregistrent un modèle concret plutôt que de laisser le champ vide.",
- "tr": "Önerilen bir ACP modelini seçin veya özel bir model geçersiz kılma değeri girin. Yerleşik sağlayıcılar, modeli boş bırakmak yerine somut bir model kaydeder.",
- "de": "Wähle ein vorgeschlagenes ACP-Modell aus oder gib eine benutzerdefinierte Modellüberschreibung ein. Integrierte Anbieter speichern ein konkretes Modell, anstatt das Modellfeld leer zu lassen.",
- "uk": "Виберіть рекомендовану модель ACP або введіть користувацьке перевизначення моделі. Вбудовані постачальники зберігають конкретну модель замість того, щоб залишати поле порожнім.",
- "ca": "Tria un model ACP suggerit o introdueix una substitució de model personalitzada. Els proveïdors integrats desen un model concret en lloc de deixar-lo en blanc."
+ "en": "Choose one of the agent's models, or enter a custom model ID.",
+ "ja": "エージェントのモデルを選択するか、カスタムモデル ID を入力してください。",
+ "zh-CN": "选择代理的某个模型,或输入自定义模型 ID。",
+ "zh-TW": "選擇代理的某個模型,或輸入自訂模型 ID。",
+ "ko-KR": "에이전트의 모델 중 하나를 선택하거나 사용자 정의 모델 ID를 입력하세요.",
+ "no": "Velg en av agentens modeller, eller skriv inn en egendefinert modell-ID.",
+ "it": "Scegli uno dei modelli dell'agente o inserisci un ID modello personalizzato.",
+ "pt": "Escolha um dos modelos do agente ou insira um ID de modelo personalizado.",
+ "es": "Elige uno de los modelos del agente o introduce un ID de modelo personalizado.",
+ "ar": "اختر أحد نماذج الوكيل، أو أدخل معرّف نموذج مخصص.",
+ "fr": "Choisissez l'un des modèles de l'agent ou saisissez un identifiant de modèle personnalisé.",
+ "tr": "Ajanın modellerinden birini seçin veya özel bir model kimliği girin.",
+ "de": "Wähle eines der Modelle des Agenten oder gib eine eigene Modell-ID ein.",
+ "uk": "Виберіть одну з моделей агента або введіть власний ідентифікатор моделі.",
+ "ca": "Tria un dels models de l'agent o introdueix un identificador de model personalitzat."
+ },
+ "SETTINGS$AGENT_MODEL_IS_AGENT_DEFAULT": {
+ "en": "{{model}} (agent default)",
+ "ja": "{{model}}(エージェントの既定)",
+ "zh-CN": "{{model}}(代理默认)",
+ "zh-TW": "{{model}}(代理預設)",
+ "ko-KR": "{{model}} (에이전트 기본값)",
+ "no": "{{model}} (agentens standard)",
+ "it": "{{model}} (predefinito dell'agente)",
+ "pt": "{{model}} (padrão do agente)",
+ "es": "{{model}} (predeterminado del agente)",
+ "ar": "{{model}} (افتراضي الوكيل)",
+ "fr": "{{model}} (par défaut de l'agent)",
+ "tr": "{{model}} (ajan varsayılanı)",
+ "de": "{{model}} (Standard des Agenten)",
+ "uk": "{{model}} (типова для агента)",
+ "ca": "{{model}} (predeterminat de l'agent)"
+ },
+ "SETTINGS$AGENT_MODEL_AGENT_DEFAULT": {
+ "en": "Agent default",
+ "ja": "エージェントの既定",
+ "zh-CN": "代理默认",
+ "zh-TW": "代理預設",
+ "ko-KR": "에이전트 기본값",
+ "no": "Agentens standard",
+ "it": "Predefinito dell'agente",
+ "pt": "Padrão do agente",
+ "es": "Predeterminado del agente",
+ "ar": "افتراضي الوكيل",
+ "fr": "Par défaut de l'agent",
+ "tr": "Ajan varsayılanı",
+ "de": "Standard des Agenten",
+ "uk": "Типова для агента",
+ "ca": "Predeterminat de l'agent"
+ },
+ "SETTINGS$AGENT_MODEL_AGENT_DEFAULT_IS": {
+ "en": "Agent default ({{model}})",
+ "ja": "エージェントの既定({{model}})",
+ "zh-CN": "代理默认({{model}})",
+ "zh-TW": "代理預設({{model}})",
+ "ko-KR": "에이전트 기본값 ({{model}})",
+ "no": "Agentens standard ({{model}})",
+ "it": "Predefinito dell'agente ({{model}})",
+ "pt": "Padrão do agente ({{model}})",
+ "es": "Predeterminado del agente ({{model}})",
+ "ar": "افتراضي الوكيل ({{model}})",
+ "fr": "Par défaut de l'agent ({{model}})",
+ "tr": "Ajan varsayılanı ({{model}})",
+ "de": "Standard des Agenten ({{model}})",
+ "uk": "Типова для агента ({{model}})",
+ "ca": "Predeterminat de l'agent ({{model}})"
+ },
+ "SETTINGS$AGENT_MODEL_DISCOVERING": {
+ "en": "Asking {{agent}} which models it offers…",
+ "ja": "{{agent}} に利用可能なモデルを問い合わせています…",
+ "zh-CN": "正在向 {{agent}} 查询可用模型…",
+ "zh-TW": "正在向 {{agent}} 查詢可用模型…",
+ "ko-KR": "{{agent}}에 사용 가능한 모델을 확인하는 중…",
+ "no": "Spør {{agent}} hvilke modeller den tilbyr …",
+ "it": "Chiedo a {{agent}} quali modelli offre…",
+ "pt": "Perguntando ao {{agent}} quais modelos ele oferece…",
+ "es": "Preguntando a {{agent}} qué modelos ofrece…",
+ "ar": "جارٍ سؤال {{agent}} عن النماذج التي يوفرها…",
+ "fr": "Interrogation de {{agent}} sur les modèles proposés…",
+ "tr": "{{agent}} hangi modelleri sunduğu soruluyor…",
+ "de": "{{agent}} wird nach den angebotenen Modellen gefragt …",
+ "uk": "Запитуємо в {{agent}}, які моделі він пропонує…",
+ "ca": "Preguntant a {{agent}} quins models ofereix…"
+ },
+ "SETTINGS$AGENT_MODEL_DISCOVERY_NEEDS_AUTH": {
+ "en": "Sign in or add credentials above to see the models {{agent}} offers.",
+ "ja": "{{agent}} が提供するモデルを表示するには、サインインするか上に認証情報を追加してください。",
+ "zh-CN": "请登录或在上方添加凭据,以查看 {{agent}} 提供的模型。",
+ "zh-TW": "請登入或在上方新增憑證,以查看 {{agent}} 提供的模型。",
+ "ko-KR": "{{agent}}에서 제공하는 모델을 보려면 로그인하거나 위에 자격 증명을 추가하세요.",
+ "no": "Logg inn eller legg til legitimasjon ovenfor for å se modellene {{agent}} tilbyr.",
+ "it": "Accedi o aggiungi le credenziali qui sopra per vedere i modelli offerti da {{agent}}.",
+ "pt": "Entre ou adicione credenciais acima para ver os modelos que o {{agent}} oferece.",
+ "es": "Inicia sesión o añade credenciales arriba para ver los modelos que ofrece {{agent}}.",
+ "ar": "سجّل الدخول أو أضف بيانات الاعتماد أعلاه لرؤية النماذج التي يوفرها {{agent}}.",
+ "fr": "Connectez-vous ou ajoutez des identifiants ci-dessus pour voir les modèles proposés par {{agent}}.",
+ "tr": "{{agent}} tarafından sunulan modelleri görmek için oturum açın veya yukarıya kimlik bilgileri ekleyin.",
+ "de": "Melde dich an oder füge oben Zugangsdaten hinzu, um die Modelle von {{agent}} zu sehen.",
+ "uk": "Увійдіть або додайте облікові дані вище, щоб побачити моделі, які пропонує {{agent}}.",
+ "ca": "Inicia la sessió o afegeix credencials a dalt per veure els models que ofereix {{agent}}."
+ },
+ "SETTINGS$AGENT_MODEL_LIST_REMEMBERED": {
+ "en": "Models from your last conversation with {{agent}}.",
+ "ja": "{{agent}} との前回の会話で取得したモデルです。",
+ "zh-CN": "这些模型来自你与 {{agent}} 的上一次对话。",
+ "zh-TW": "這些模型來自你與 {{agent}} 的上一次對話。",
+ "ko-KR": "{{agent}}와의 마지막 대화에서 가져온 모델입니다.",
+ "no": "Modeller fra din siste samtale med {{agent}}.",
+ "it": "Modelli dalla tua ultima conversazione con {{agent}}.",
+ "pt": "Modelos da sua última conversa com o {{agent}}.",
+ "es": "Modelos de tu última conversación con {{agent}}.",
+ "ar": "نماذج من محادثتك الأخيرة مع {{agent}}.",
+ "fr": "Modèles issus de votre dernière conversation avec {{agent}}.",
+ "tr": "{{agent}} ile son konuşmanızdaki modeller.",
+ "de": "Modelle aus deiner letzten Unterhaltung mit {{agent}}.",
+ "uk": "Моделі з вашої останньої розмови з {{agent}}.",
+ "ca": "Models de la teva darrera conversa amb {{agent}}."
+ },
+ "SETTINGS$AGENT_MODEL_LIST_AFTER_FIRST_CONVERSATION": {
+ "en": "{{agent}}'s models appear here after your first conversation with it. You can also switch models from the chat.",
+ "ja": "{{agent}} のモデルは、最初の会話の後にここに表示されます。チャットからモデルを切り替えることもできます。",
+ "zh-CN": "与 {{agent}} 进行第一次对话后,其模型会显示在这里。你也可以在聊天中切换模型。",
+ "zh-TW": "與 {{agent}} 進行第一次對話後,其模型會顯示在這裡。你也可以在聊天中切換模型。",
+ "ko-KR": "{{agent}}의 모델은 첫 대화 후 여기에 표시됩니다. 채팅에서 모델을 전환할 수도 있습니다.",
+ "no": "Modellene til {{agent}} vises her etter din første samtale med den. Du kan også bytte modell fra chatten.",
+ "it": "I modelli di {{agent}} compaiono qui dopo la tua prima conversazione con esso. Puoi anche cambiare modello dalla chat.",
+ "pt": "Os modelos do {{agent}} aparecem aqui após sua primeira conversa com ele. Você também pode trocar de modelo pelo chat.",
+ "es": "Los modelos de {{agent}} aparecen aquí después de tu primera conversación con él. También puedes cambiar de modelo desde el chat.",
+ "ar": "تظهر نماذج {{agent}} هنا بعد محادثتك الأولى معه. يمكنك أيضًا تبديل النموذج من المحادثة.",
+ "fr": "Les modèles de {{agent}} apparaissent ici après votre première conversation avec lui. Vous pouvez aussi changer de modèle depuis le chat.",
+ "tr": "{{agent}} modelleri, onunla ilk konuşmanızdan sonra burada görünür. Modeli sohbetten de değiştirebilirsiniz.",
+ "de": "Die Modelle von {{agent}} erscheinen hier nach deiner ersten Unterhaltung damit. Du kannst das Modell auch im Chat wechseln.",
+ "uk": "Моделі {{agent}} з’являться тут після вашої першої розмови з ним. Ви також можете змінити модель у чаті.",
+ "ca": "Els models de {{agent}} apareixen aquí després de la teva primera conversa amb ell. També pots canviar de model des del xat."
},
"SETTINGS$ACP_CREDENTIAL_CONFLICT_WARNING": {
"en": "Setting {{conflicting}} alongside {{credential}} breaks its authentication — leave one of them blank.",
diff --git a/src/routes/agent-settings.tsx b/src/routes/agent-settings.tsx
index 6462e9fe1f..de58f93a3a 100644
--- a/src/routes/agent-settings.tsx
+++ b/src/routes/agent-settings.tsx
@@ -30,8 +30,11 @@ import {
getAcpProvider,
getAcpProvidersForBackend,
getAcpProviderSecrets,
+ labelForAcpModel,
+ type ACPModelOption,
type ACPProviderConfig,
} from "#/constants/acp-providers";
+import { useAcpModelDiscovery } from "#/hooks/query/use-acp-model-discovery";
import { useActiveBackend } from "#/contexts/active-backend-context";
import { parseCommand, formatCommand } from "#/utils/acp-command";
import {
@@ -69,6 +72,7 @@ const SYSTEM_MESSAGE_SUFFIX_KEY = "system_message_suffix";
const SYSTEM_PROMPT_MAX_LENGTH = 65536;
const COMMAND_PLACEHOLDER_FALLBACK = "npx -y <package-name>";
const ACP_CUSTOM_MODEL_KEY = "__custom_model__";
+const ACP_AGENT_DEFAULT_MODEL_KEY = "__agent_default_model__";
const EMPTY_AGENT_SETTINGS_SNAPSHOT: AgentSettingsSnapshot = {
agentType: "openhands",
commandText: "",
@@ -110,13 +114,14 @@ export function readSystemPromptSeed(
return { mode: "standard", text: "" };
}
-function isKnownAcpModel(
- provider: ACPProviderConfig | undefined,
- model: string,
-): boolean {
- return (
- provider?.available_models?.some(({ id }) => id === model.trim()) ?? false
- );
+/** The agent's models, keeping a saved model selectable when it isn't listed. */
+function buildModelSuggestions(
+ models: readonly ACPModelOption[],
+ selectedModel: string,
+): ACPModelOption[] {
+ const model = selectedModel.trim();
+ if (!model || models.some(({ id }) => id === model)) return [...models];
+ return [...models, { id: model, label: model }];
}
/**
@@ -574,9 +579,7 @@ export function AgentSettingsScreen({
typeof savedModel === "string" ? savedModel.trim() : "";
const nextAcpModel =
normalizedSavedModel || getAcpPreferredDefaultModel(acpServer) || "";
- const nextIsCustomAcpModel =
- !!normalizedSavedModel &&
- (!provider || !isKnownAcpModel(provider, normalizedSavedModel));
+ const nextIsCustomAcpModel = !!normalizedSavedModel && !provider;
setAcpModel(nextAcpModel);
setIsCustomAcpModel(nextIsCustomAcpModel);
setLoadedSnapshot({
@@ -723,22 +726,63 @@ export function AgentSettingsScreen({
stableCredReset,
]);
- if (isLoading) return null;
-
const isAcp = agentType === "acp";
const commandTokens = parseCommand(commandText);
const selectedPreset = detectPreset(commandText, acpProviders);
const selectedProvider = getAcpProvider(selectedPreset);
- const modelSuggestions = selectedProvider?.available_models ?? [];
- const hasModelSuggestions = modelSuggestions.length > 0;
- const selectedModelIsSuggestion = isKnownAcpModel(selectedProvider, acpModel);
- const selectedModelKey =
- isCustomAcpModel || !selectedModelIsSuggestion
- ? ACP_CUSTOM_MODEL_KEY
- : acpModel;
const isDefaultProviderCommand =
!!selectedProvider &&
commandTokens.join(" ") === selectedProvider.default_command.join(" ");
+ const liveModels = useAcpModelDiscovery(
+ isAcp && isDefaultProviderCommand ? selectedPreset : null,
+ {
+ secretRefs:
+ secretRefsSupportedOnProfile && secretsMode === "custom"
+ ? selectedSecrets
+ : null,
+ },
+ );
+
+ if (isLoading) return null;
+
+ const modelSuggestions = buildModelSuggestions(
+ liveModels.models,
+ isCustomAcpModel ? "" : acpModel,
+ );
+ const agentDefaultModelLabel = labelForAcpModel(
+ liveModels.defaultModelId,
+ liveModels.models,
+ );
+ // Without a preferred model the agent picks its own, so name that choice.
+ const offersAgentDefault =
+ !!selectedProvider && !getAcpPreferredDefaultModel(selectedPreset);
+ const showModelSelector = offersAgentDefault || modelSuggestions.length > 0;
+ const modelListHint = (() => {
+ if (!selectedProvider || liveModels.isDiscovering) return null;
+ if (liveModels.discovery?.error?.code === "ACPAuthRequired") return null;
+ if (liveModels.source === "remembered") {
+ return {
+ testId: "agent-model-list-remembered",
+ key: I18nKey.SETTINGS$AGENT_MODEL_LIST_REMEMBERED,
+ };
+ }
+ if (liveModels.source === "none") {
+ return {
+ testId: "agent-model-list-after-first-conversation",
+ key: I18nKey.SETTINGS$AGENT_MODEL_LIST_AFTER_FIRST_CONVERSATION,
+ };
+ }
+ return null;
+ })();
+ const selectedModelIsSuggestion = modelSuggestions.some(
+ ({ id }) => id === acpModel.trim(),
+ );
+ let selectedModelKey = acpModel;
+ if (offersAgentDefault && !isCustomAcpModel && !acpModel.trim()) {
+ selectedModelKey = ACP_AGENT_DEFAULT_MODEL_KEY;
+ } else if (isCustomAcpModel || !selectedModelIsSuggestion) {
+ selectedModelKey = ACP_CUSTOM_MODEL_KEY;
+ }
const commandPlaceholder =
formatCommand(acpProviders[0]?.default_command ?? []) ||
COMMAND_PLACEHOLDER_FALLBACK;
@@ -1219,58 +1263,6 @@ export function AgentSettingsScreen({
{t(I18nKey.SETTINGS$AGENT_COMMAND_HINT)}
</Typography.Text>
</div>
-
- <div className="flex flex-col gap-1.5">
- {hasModelSuggestions && (
- <SettingsDropdownInput
- testId="agent-model-selector"
- name="agent-model"
- label={t(I18nKey.SETTINGS$AGENT_MODEL)}
- items={[
- ...modelSuggestions.map((model) => ({
- key: model.id,
- label: model.label,
- })),
- {
- key: ACP_CUSTOM_MODEL_KEY,
- label: t(I18nKey.SETTINGS$AGENT_PRESET_CUSTOM),
- },
- ]}
- selectedKey={selectedModelKey}
- onSelectionChange={(key) => {
- if (!key) return;
- const modelKey = String(key);
- if (modelKey === ACP_CUSTOM_MODEL_KEY) {
- setIsCustomAcpModel(true);
- setAcpModel("");
- } else {
- setIsCustomAcpModel(false);
- setAcpModel(modelKey);
- }
- }}
- />
- )}
- {selectedModelKey === ACP_CUSTOM_MODEL_KEY && (
- <SettingsInput
- testId="agent-model-input"
- label={
- hasModelSuggestions
- ? t(I18nKey.SETTINGS$AGENT_CUSTOM_MODEL)
- : t(I18nKey.SETTINGS$AGENT_MODEL)
- }
- type="text"
- className="w-full"
- value={acpModel}
- showOptionalTag
- onChange={(value) => {
- setAcpModel(value);
- }}
- />
- )}
- <Typography.Text className="text-xs text-[#717888]">
- {t(I18nKey.SETTINGS$AGENT_MODEL_HINT)}
- </Typography.Text>
- </div>
</>
)}
@@ -1280,9 +1272,117 @@ export function AgentSettingsScreen({
<AcpCredentialsSection
form={acpCredentialForm}
providerKey={selectedPreset}
+ loginRejected={
+ liveModels.discovery?.error?.code === "ACPAuthRequired"
+ }
/>
+ <hr className="border-[#3D4046]" />
</>
)}
+
+ {isAcp && (
+ <div className="flex flex-col gap-1.5">
+ {showModelSelector && (
+ <SettingsDropdownInput
+ testId="agent-model-selector"
+ name="agent-model"
+ label={t(I18nKey.SETTINGS$AGENT_MODEL)}
+ items={[
+ ...(offersAgentDefault
+ ? [
+ {
+ key: ACP_AGENT_DEFAULT_MODEL_KEY,
+ label: agentDefaultModelLabel
+ ? t(I18nKey.SETTINGS$AGENT_MODEL_AGENT_DEFAULT_IS, {
+ model: agentDefaultModelLabel,
+ })
+ : t(I18nKey.SETTINGS$AGENT_MODEL_AGENT_DEFAULT),
+ },
+ ]
+ : []),
+ ...modelSuggestions.map((model) => ({
+ key: model.id,
+ label:
+ !offersAgentDefault &&
+ model.id === liveModels.defaultModelId
+ ? t(I18nKey.SETTINGS$AGENT_MODEL_IS_AGENT_DEFAULT, {
+ model: model.label,
+ })
+ : model.label,
+ })),
+ {
+ key: ACP_CUSTOM_MODEL_KEY,
+ label: t(I18nKey.SETTINGS$AGENT_PRESET_CUSTOM),
+ },
+ ]}
+ selectedKey={selectedModelKey}
+ onSelectionChange={(key) => {
+ if (!key) return;
+ const modelKey = String(key);
+ if (modelKey === ACP_CUSTOM_MODEL_KEY) {
+ setIsCustomAcpModel(true);
+ setAcpModel("");
+ } else if (modelKey === ACP_AGENT_DEFAULT_MODEL_KEY) {
+ setIsCustomAcpModel(false);
+ setAcpModel("");
+ } else {
+ setIsCustomAcpModel(false);
+ setAcpModel(modelKey);
+ }
+ }}
+ />
+ )}
+ {selectedModelKey === ACP_CUSTOM_MODEL_KEY && (
+ <SettingsInput
+ testId="agent-model-input"
+ label={
+ showModelSelector
+ ? t(I18nKey.SETTINGS$AGENT_CUSTOM_MODEL)
+ : t(I18nKey.SETTINGS$AGENT_MODEL)
+ }
+ type="text"
+ className="w-full"
+ value={acpModel}
+ showOptionalTag
+ onChange={(value) => {
+ setAcpModel(value);
+ }}
+ />
+ )}
+ {liveModels.isDiscovering && selectedProvider && (
+ <Typography.Text
+ testId="agent-model-discovering"
+ className="text-xs text-[#717888]"
+ >
+ {t(I18nKey.SETTINGS$AGENT_MODEL_DISCOVERING, {
+ agent: selectedProvider.display_name,
+ })}
+ </Typography.Text>
+ )}
+ {liveModels.discovery?.error?.code === "ACPAuthRequired" &&
+ selectedProvider && (
+ <Typography.Text
+ testId="agent-model-discovery-needs-auth"
+ className="text-xs text-[#717888]"
+ >
+ {t(I18nKey.SETTINGS$AGENT_MODEL_DISCOVERY_NEEDS_AUTH, {
+ agent: selectedProvider.display_name,
+ })}
+ </Typography.Text>
+ )}
+ {modelListHint && selectedProvider && (
+ <Typography.Text
+ testId={modelListHint.testId}
+ className="text-xs text-[#717888]"
+ >
+ {t(modelListHint.key, { agent: selectedProvider.display_name })}
+ </Typography.Text>
+ )}
+ <Typography.Text className="text-xs text-[#717888]">
+ {t(I18nKey.SETTINGS$AGENT_MODEL_HINT)}
+ </Typography.Text>
+ </div>
+ )}
</div>
);
}
diff --git a/src/utils/remembered-acp-models.ts b/src/utils/remembered-acp-models.ts
new file mode 100644
index 0000000000..478057f195
--- /dev/null
+++ b/src/utils/remembered-acp-models.ts
@@ -0,0 +1,115 @@
+import type { ACPModelOption } from "#/constants/acp-providers";
+
+const STORAGE_PREFIX = "openhands-acp-models";
+
+const listeners = new Set<() => void>();
+
+type RememberedLists = Record<string, ACPModelOption[]>;
+
+function storageKey(backendId: string, providerKey: string): string {
+ return `${STORAGE_PREFIX}:${backendId}:${providerKey}`;
+}
+
+function isModelOption(value: unknown): value is ACPModelOption {
+ if (typeof value !== "object" || value === null) return false;
+ const { id, label } = value as Record<string, unknown>;
+ return typeof id === "string" && !!id && typeof label === "string";
+}
+
+function parseLists(raw: string | null): RememberedLists {
+ if (!raw) return {};
+ try {
+ const stored = JSON.parse(raw);
+ if (typeof stored !== "object" || stored === null || Array.isArray(stored))
+ return {};
+ return Object.fromEntries(
+ Object.entries(stored).map(([scope, models]) => [
+ scope,
+ Array.isArray(models) ? models.filter(isModelOption) : [],
+ ]),
+ );
+ } catch {
+ return {};
+ }
+}
+
+/** The scope a list is remembered under: the secrets the agent could use. */
+export function acpModelScope(
+ secretRefs: readonly string[] | null | undefined,
+): string {
+ return secretRefs ? JSON.stringify([...new Set(secretRefs)].sort()) : "*";
+}
+
+/** The stored JSON for {@link readRememberedAcpModels}, or null. */
+export function readRememberedAcpModelsRaw(
+ backendId: string,
+ providerKey: string | null | undefined,
+): string | null {
+ if (typeof window === "undefined" || !providerKey) return null;
+ try {
+ return window.localStorage.getItem(storageKey(backendId, providerKey));
+ } catch {
+ return null;
+ }
+}
+
+/** The list remembered under ``scope``, or every remembered model when omitted. */
+export function parseRememberedAcpModels(
+ raw: string | null,
+ scope?: string,
+): ACPModelOption[] {
+ const lists = parseLists(raw);
+ if (scope !== undefined) return lists[scope] ?? [];
+ const byId = new Map<string, ACPModelOption>();
+ Object.values(lists)
+ .flat()
+ .forEach((model) => {
+ if (!byId.has(model.id)) byId.set(model.id, model);
+ });
+ return [...byId.values()];
+}
+
+/** The models a built-in ACP agent last reported on this backend, in this browser. */
+export function readRememberedAcpModels(
+ backendId: string,
+ providerKey: string | null | undefined,
+ scope?: string,
+): ACPModelOption[] {
+ return parseRememberedAcpModels(
+ readRememberedAcpModelsRaw(backendId, providerKey),
+ scope,
+ );
+}
+
+/** Call ``listener`` whenever a remembered list changes, in this tab or another. */
+export function subscribeRememberedAcpModels(listener: () => void) {
+ listeners.add(listener);
+ window.addEventListener("storage", listener);
+ return () => {
+ listeners.delete(listener);
+ window.removeEventListener("storage", listener);
+ };
+}
+
+export function rememberAcpModels(
+ backendId: string,
+ providerKey: string,
+ scope: string,
+ models: readonly ACPModelOption[],
+): void {
+ if (typeof window === "undefined" || !models.length) return;
+ const list = models.map(({ id, label }) => ({ id, label }));
+ try {
+ const key = storageKey(backendId, providerKey);
+ const lists = parseLists(window.localStorage.getItem(key));
+ if (JSON.stringify(lists[scope]) === JSON.stringify(list)) return;
+ window.localStorage.setItem(
+ key,
+ JSON.stringify({ ...lists, [scope]: list }),
+ );
+ } catch {
+ // Storage is unavailable; the list is only a convenience.
+ return;
+ }
+ listeners.forEach((listener) => listener());
+}