Skip to content

🙌 OpenHands: AI-Driven Development

feat(agent-profiles): launch `default` by id; profiles own their settings (#18720)

simonrosenberg61cd03c89ed7
diff --git a/.agents/skills/frontend-api-contracts/references/guide.md b/.agents/skills/frontend-api-contracts/references/guide.md
index 51901bfec4..2d85b7634d 100644
--- a/.agents/skills/frontend-api-contracts/references/guide.md
+++ b/.agents/skills/frontend-api-contracts/references/guide.md
@@ -190,7 +190,7 @@ return new ConversationClient(getAgentServerClientOptions()).someMethod(...);
- Collapsible thinking: `ThinkAction` events and LLM extended reasoning (`reasoning_content` / `thinking_blocks` on `ActionEvent`) are rendered as collapsible sections via `CollapsibleThinking` (`src/components/conversation-events/chat/event-message-components/collapsible-thinking.tsx`). Collapsed by default to keep the chat compact — the thinking is often in English regardless of the user's conversation language. The `getReasoningContent()` helper in `event-thought-helpers.ts` extracts the content, preferring `reasoning_content` (plain string) and falling back to Anthropic `thinking_blocks`. i18n keys: `THINKING$TITLE`, `THINKING$EXPAND`, `THINKING$COLLAPSE`. Tests: `__tests__/components/conversation-events/chat/event-message-think-action.test.tsx`.
-- Global tool selection: `getAgentTools()` in `agent-server-adapter.ts` sends `agent_settings.tools` exactly as stored (`[]` included) and omits it when unset/`null`, so the agent server resolves its standard set. There are no global tool toggles; tools are chosen per agent profile from the server's catalog. `GlobalToolsNotice` (`agent-profiles/global-tools-notice.tsx`) surfaces a custom global list and resets it with `agent_settings_diff: { tools: null }`.
+- Tool selection is per agent profile: every local launch sends `agent_profile_id`, and the server builds the agent from the profile's `tools` (`null` = its standard set). Global `agent_settings.tools` only seeds `default` through the one-time migration in `use-migrate-default-agent-profile.ts`.
- Settings naming is backend-aware today: local `/settings` is profile-oriented (`use-settings-nav-items.ts` renames the first settings item/title/subtitle to `LLM Profiles` and `chat-input-model.tsx` / `chat-input-actions.tsx` link there as `LLM Profiles`), while cloud keeps the generic `LLM Settings` copy because cloud still edits raw settings rather than saved profiles. The local profile editor (`llm-settings-local-view.tsx`) should keep explicit create/edit profile headings plus helper text so users know they are saving a profile, not mutating the current conversation directly.
diff --git a/.pr/default-by-id-after-default-editor-behavior.png b/.pr/default-by-id-after-default-editor-behavior.png
new file mode 100644
index 0000000000..9dfcae68bc
Binary files /dev/null and b/.pr/default-by-id-after-default-editor-behavior.png differ
diff --git a/.pr/default-by-id-after-router.png b/.pr/default-by-id-after-router.png
new file mode 100644
index 0000000000..87e0f2bd75
Binary files /dev/null and b/.pr/default-by-id-after-router.png differ
diff --git a/.pr/default-by-id-after-verification.png b/.pr/default-by-id-after-verification.png
new file mode 100644
index 0000000000..e92567f699
Binary files /dev/null and b/.pr/default-by-id-after-verification.png differ
diff --git a/.pr/default-by-id-before-default-editor-behavior.png b/.pr/default-by-id-before-default-editor-behavior.png
new file mode 100644
index 0000000000..c0ab322d13
Binary files /dev/null and b/.pr/default-by-id-before-default-editor-behavior.png differ
diff --git a/.pr/default-by-id-before-router.png b/.pr/default-by-id-before-router.png
new file mode 100644
index 0000000000..6cf63c408e
Binary files /dev/null and b/.pr/default-by-id-before-router.png differ
diff --git a/.pr/default-by-id-before-verification.png b/.pr/default-by-id-before-verification.png
new file mode 100644
index 0000000000..e62d9262a4
Binary files /dev/null and b/.pr/default-by-id-before-verification.png differ
diff --git a/.pr/default-by-id-default-mcp-secrets.png b/.pr/default-by-id-default-mcp-secrets.png
new file mode 100644
index 0000000000..ce830656ef
Binary files /dev/null and b/.pr/default-by-id-default-mcp-secrets.png differ
diff --git a/.pr/default-by-id-default-skills-llm.png b/.pr/default-by-id-default-skills-llm.png
new file mode 100644
index 0000000000..87c82f1351
Binary files /dev/null and b/.pr/default-by-id-default-skills-llm.png differ
diff --git a/.pr/default-by-id-new-profile.png b/.pr/default-by-id-new-profile.png
new file mode 100644
index 0000000000..efa5e9483b
Binary files /dev/null and b/.pr/default-by-id-new-profile.png differ
diff --git a/.pr/default-by-id-ux-agents-list.png b/.pr/default-by-id-ux-agents-list.png
new file mode 100644
index 0000000000..bac036be18
Binary files /dev/null and b/.pr/default-by-id-ux-agents-list.png differ
diff --git a/.pr/default-by-id-ux-default-editor.png b/.pr/default-by-id-ux-default-editor.png
new file mode 100644
index 0000000000..7d0b721682
Binary files /dev/null and b/.pr/default-by-id-ux-default-editor.png differ
diff --git a/.pr/default-by-id-ux-home-pills.png b/.pr/default-by-id-ux-home-pills.png
new file mode 100644
index 0000000000..30f6535ad6
Binary files /dev/null and b/.pr/default-by-id-ux-home-pills.png differ
diff --git a/.pr/default-by-id-ux-new-profile.png b/.pr/default-by-id-ux-new-profile.png
new file mode 100644
index 0000000000..0248fdbf5c
Binary files /dev/null and b/.pr/default-by-id-ux-new-profile.png differ
diff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.ts
index 124df62168..381682bbc2 100644
--- a/__tests__/api/agent-server-adapter.test.ts
+++ b/__tests__/api/agent-server-adapter.test.ts
@@ -1,6 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { MockInstance } from "vitest";
-import { getAcpProvider as getClientAcpProvider } from "@openhands/typescript-client";
import { CANVAS_UI_CLIENT_TOOL_NAME } from "#/constants/canvas-ui";
import { LAUNCH_CHILD_CONVERSATION_TOOL_NAME } from "#/constants/child-conversation";
import { REQUEST_SECRET_TOOL_NAME } from "#/constants/secret-request";
@@ -14,7 +13,6 @@ import {
buildStartConversationRequest,
buildStartConversationRequestWithEncryptedSettings,
fetchBackendExecutionRuntime,
- backendSupportsLaunchLlmOverride,
getDefaultConversationTitle,
parseRuntimeServicesInfo,
toAppConversation,
@@ -28,14 +26,10 @@ import {
setStoredConversationMetadata,
} from "#/api/conversation-metadata-store";
import { HookType } from "@openhands/typescript-client";
+import { SKILLS_CATALOG } from "@openhands/extensions/skills";
import type { HookConfig } from "@openhands/typescript-client";
-import { ACP_VERTEX_SAFE_MODEL } from "#/constants/acp-providers";
import { DEFAULT_SETTINGS } from "#/services/settings";
import type { SettingsValue } from "#/types/settings";
-import {
- LLM_AUTH_TYPE_SUBSCRIPTION,
- OPENAI_SUBSCRIPTION_VENDOR,
-} from "#/constants/llm-subscription";
const {
mockGetAgentServerWorkingDir,
@@ -44,7 +38,6 @@ const {
mockGetServerInfo,
mockGetActiveBackend,
mockLoadHooks,
- mockListMetaProfiles,
} = vi.hoisted(() => ({
mockGetAgentServerWorkingDir: vi.fn(() => "/workspace/project/agent-canvas"),
mockGetEffectiveLocalBackend: vi.fn(() => ({
@@ -66,7 +59,6 @@ const {
},
})),
mockLoadHooks: vi.fn(),
- mockListMetaProfiles: vi.fn(),
}));
vi.mock("@openhands/typescript-client/clients", () => ({
@@ -78,9 +70,6 @@ vi.mock("@openhands/typescript-client/clients", () => ({
HooksClient: vi.fn(function HooksClientMock() {
return { loadHooks: mockLoadHooks };
}),
- MetaProfilesClient: vi.fn(function MetaProfilesClientMock() {
- return { listMetaProfiles: mockListMetaProfiles };
- }),
}));
vi.mock("#/api/agent-server-config", () => ({
@@ -142,12 +131,18 @@ beforeEach(() => {
});
});
+const PROFILE = {
+ agentProfileId: "profile-1",
+ agentProfileKind: "openhands" as const,
+};
+
describe("buildStartConversationRequest", () => {
it.each([{ city: "Tokyo" }, { metric: false }, { days: 0 }])(
"rejects unsupported plugin parameters instead of silently stripping %o",
(parameters) => {
expect(() =>
buildStartConversationRequest({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
plugins: [{ source: "local-plugin", parameters }],
}),
@@ -167,7 +162,11 @@ describe("buildStartConversationRequest", () => {
JSON.stringify([{ source: "local-plugin", parameters }]),
);
expect(() =>
- buildStartConversationRequest({ settings: DEFAULT_SETTINGS, plugins }),
+ buildStartConversationRequest({
+ ...PROFILE,
+ settings: DEFAULT_SETTINGS,
+ plugins,
+ }),
).toThrow();
},
);
@@ -176,6 +175,7 @@ describe("buildStartConversationRequest", () => {
"keeps coordinate-only plugins when parameters are %o",
(parameters) => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
plugins: [
{
@@ -194,6 +194,7 @@ describe("buildStartConversationRequest", () => {
it("includes the resolved title LLM profile when configured", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
titleLlmProfile: "Titles",
});
@@ -203,215 +204,16 @@ describe("buildStartConversationRequest", () => {
it("omits the title LLM profile in automatic mode without a default", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
});
expect(payload).not.toHaveProperty("title_llm_profile");
});
- it("uses nested settings as the source of truth and lets the SDK create the agent", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- llm_model: "stale-top-level-model",
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- agent: "CodeActAgent",
- llm: {
- model: "nested-model",
- api_key: " nested-key ",
- base_url: " https://nested.example.com ",
- },
- condenser: {
- enabled: true,
- max_size: 120,
- },
- },
- conversation_settings: {
- ...DEFAULT_SETTINGS.conversation_settings,
- max_iterations: 123,
- },
- },
- query: "hello",
- }) as {
- agent?: unknown;
- agent_settings: Record<string, unknown> & {
- llm: Record<string, unknown>;
- tools: Array<{ name: string; params: Record<string, unknown> }>;
- agent_context: Record<string, unknown>;
- };
- workspace: { working_dir: string };
- initial_message: { content: Array<{ text: string }> };
- max_iterations: number;
- };
-
- expect(payload.agent).toBeUndefined();
- expect(payload.agent_settings.llm).toMatchObject({
- model: "nested-model",
- api_key: "nested-key",
- base_url: "https://nested.example.com",
- // Streaming is enabled so the OpenHands agent emits StreamingDeltaEvents.
- stream: true,
- });
- expect(payload.agent_settings.condenser).toEqual({
- enabled: true,
- max_size: 120,
- });
- expect(
- JSON.parse(JSON.stringify(payload.agent_settings)),
- ).not.toHaveProperty("tools");
- expect(payload.agent_settings.agent_context).toMatchObject({
- load_public_skills: false,
- load_user_skills: true,
- load_project_skills: true,
- });
- // Persistent memory is opt-in: the key must be absent (not false) so the
- // wire payload for un-opted users stays byte-identical to before.
- expect(payload.agent_settings.agent_context).not.toHaveProperty(
- "load_memory",
- );
- // Bundled public skills are injected into agent_context.skills so the
- // SDK can perform trigger matching without cloning the extensions repo.
- expect(Array.isArray(payload.agent_settings.agent_context.skills)).toBe(
- true,
- );
- const skills = payload.agent_settings.agent_context.skills as Record<
- string,
- unknown
- >[];
- expect(skills.length).toBeGreaterThan(0);
- // Every bundled skill must carry the fields the SDK needs for trigger
- // matching and system-prompt injection.
- for (const skill of skills) {
- expect(skill).toHaveProperty("name");
- expect(skill).toHaveProperty("content");
- // source must be an absolute path to the skill's SKILL.md so the
- // Python agent-server can resolve bundled resources (scripts/, references/).
- const source = skill.source as string;
- expect(source).toMatch(/^\//);
- expect(source).toMatch(
- new RegExp(`/${skill.name as string}/SKILL\\.md$`),
- );
- expect(skill).toHaveProperty("is_agentskills_format", true);
- // trigger is either null (always-active) or { type, keywords }
- if (skill.trigger !== null) {
- expect(skill.trigger).toMatchObject({
- type: "keyword",
- keywords: expect.arrayContaining([expect.any(String)]),
- });
- }
- }
- expect(payload.agent_settings.agent).toBe("CodeActAgent");
- expect(payload.workspace.working_dir).toBe(
- "/workspace/project/agent-canvas",
- );
- expect(payload.max_iterations).toBe(123);
- expect(payload.initial_message.content[0]?.text).toBe("hello");
- });
-
- it("preserves base_url for subscription auth while stripping api_key", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- llm: {
- model: "gpt-5.2-codex",
- api_key: "stale-api-key",
- base_url: "https://chatgpt.com/backend-api/codex",
- auth_type: LLM_AUTH_TYPE_SUBSCRIPTION,
- subscription_vendor: OPENAI_SUBSCRIPTION_VENDOR,
- },
- },
- },
- }) as { agent_settings: { llm: Record<string, unknown> } };
-
- expect(payload.agent_settings.llm).toEqual({
- model: "gpt-5.2-codex",
- stream: true,
- base_url: "https://chatgpt.com/backend-api/codex",
- auth_type: LLM_AUTH_TYPE_SUBSCRIPTION,
- subscription_vendor: OPENAI_SUBSCRIPTION_VENDOR,
- });
- });
-
- it("passes the stored model through unchanged for subscription auth", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- llm: {
- model: "openai/gpt-4o",
- auth_type: LLM_AUTH_TYPE_SUBSCRIPTION,
- subscription_vendor: OPENAI_SUBSCRIPTION_VENDOR,
- },
- },
- },
- }) as { agent_settings: { llm: Record<string, unknown> } };
-
- expect(payload.agent_settings.llm.model).toBe("openai/gpt-4o");
- });
-
- it("sends configured tools as given", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- tools: [
- { name: "glob", params: {} },
- { name: "task_tool_set", params: { x: 1 } },
- ],
- llm: { model: "nested-model" },
- },
- },
- }) as {
- agent_settings: {
- tools: Array<{ name: string; params: Record<string, unknown> }>;
- };
- };
-
- expect(payload.agent_settings.tools).toEqual([
- { name: "glob", params: {} },
- { name: "task_tool_set", params: { x: 1 } },
- ]);
- });
-
- it("leaves a null tool list to the server", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- tools: null,
- llm: { model: "nested-model" },
- },
- },
- }) as { agent_settings: Record<string, unknown> };
-
- expect(
- JSON.parse(JSON.stringify(payload.agent_settings)),
- ).not.toHaveProperty("tools");
- });
-
- it("keeps an explicitly empty tool list bare", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- tools: [],
- llm: { model: "nested-model" },
- },
- },
- }) as { agent_settings: { tools: unknown[] } };
-
- expect(payload.agent_settings.tools).toEqual([]);
- });
-
it("derives confirmation and security settings the same way as OpenHands", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: {
...DEFAULT_SETTINGS,
agent_settings: {
@@ -443,6 +245,7 @@ describe("buildStartConversationRequest", () => {
const conversationId = "11111111-1111-4111-8111-111111111111";
const workingDir = `/base/${conversationId}`;
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: {
...DEFAULT_SETTINGS,
agent_settings: {
@@ -463,6 +266,7 @@ describe("buildStartConversationRequest", () => {
it("requests a git worktree for new conversations by default", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: {
...DEFAULT_SETTINGS,
agent_settings: {
@@ -477,6 +281,7 @@ describe("buildStartConversationRequest", () => {
it("can start a conversation without requesting a git worktree", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: {
...DEFAULT_SETTINGS,
agent_settings: {
@@ -496,6 +301,7 @@ describe("buildStartConversationRequest", () => {
it("forwards supported conversation runtime fields from nested settings", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: {
...DEFAULT_SETTINGS,
agent_settings: {
@@ -536,6 +342,7 @@ describe("buildStartConversationRequest", () => {
it("uses workspaceHookConfig when conversation_settings.hook_config is omitted", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
workspaceHookConfig: WORKSPACE_HOOK_CONFIG,
}) as Record<string, unknown>;
@@ -545,6 +352,7 @@ describe("buildStartConversationRequest", () => {
it("prioritizes conversation_settings.hook_config over workspaceHookConfig", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: {
...DEFAULT_SETTINGS,
conversation_settings: {
@@ -560,6 +368,7 @@ describe("buildStartConversationRequest", () => {
it("serializes custom secrets as host-relative LookupSecret entries", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: {
...DEFAULT_SETTINGS,
agent_settings: {
@@ -599,249 +408,38 @@ describe("buildStartConversationRequest", () => {
});
});
- it("passes a stored agent_context.load_memory through on an inline launch", () => {
- // The persistent-memory toggle persists into
- // ``agent_settings.agent_context.load_memory``; buildAgentContext spreads
- // the stored context, so the flag needs no dedicated adapter wiring.
- //
- // This is the inline path only. A profile launch sends ``agent_profile_id``
- // and no ``agent_settings`` at all (pinned in
- // src/api/agent-server-adapter.test.ts), so there the agent-server reads the
- // same stored preference itself — covered by the SDK's
- // tests/agent_server/test_agent_profile_conv_start.py.
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- agent_context: { load_memory: true },
- },
- },
- }) as {
- agent_settings: { agent_context: Record<string, unknown> };
- };
-
- expect(payload.agent_settings.agent_context.load_memory).toBe(true);
- });
-
- it("passes a stored agent_context.load_memory through on an inline ACP launch", () => {
- // Inline ACP settings are the fallback used when no agent profile is
- // available; a normal ACP conversation launches from a profile (see
- // use-create-conversation.test.tsx) and never reaches this branch.
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- agent_kind: "acp",
- acp_server: "claude-code",
- acp_command: ["npx", "-y", "@agentclientprotocol/claude-agent-acp"],
- agent_context: { load_memory: true },
- },
- },
- }) as {
- agent_settings: { agent_context: Record<string, unknown> };
- };
-
- expect(payload.agent_settings.agent_context.load_memory).toBe(true);
- });
-
- it("does NOT mirror conversation secrets onto agent_context for ACP — request.secrets is the sole channel", () => {
- // The compatible agent-server line injects the ACP spawn env from
- // ``secret_registry``, which is seeded from ``request.secrets``
- // (sdk#3299/#3464; the agent_context drain is gone entirely in sdk#3528).
- // Mirroring the map onto ``agent_context.secrets`` would keep a second,
- // dead credential channel alive (agent-canvas#1039 wants exactly one).
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- agent_kind: "acp",
- acp_server: "claude-code",
- acp_command: ["npx", "-y", "@agentclientprotocol/claude-agent-acp"],
- },
- },
- customSecrets: [{ name: "ANTHROPIC_API_KEY" }],
- }) as {
- agent_settings: { agent_context?: { secrets?: Record<string, unknown> } };
- secrets: Record<string, unknown>;
- };
-
- expect(payload.secrets.ANTHROPIC_API_KEY).toBeDefined();
- expect(payload.agent_settings.agent_context?.secrets).toBeUndefined();
- });
-
- it("does not synthesize agent_context.secrets for ACP when no custom secrets are set", () => {
- // Empty/absent customSecrets must not introduce an empty
- // ``agent_context.secrets`` map on the ACPAgent payload.
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- agent_kind: "acp",
- acp_server: "claude-code",
- acp_command: ["npx", "-y", "@agentclientprotocol/claude-agent-acp"],
- },
- },
- }) as {
- agent_settings: { agent_context?: { secrets?: Record<string, unknown> } };
- };
-
- expect(payload.agent_settings.agent_context?.secrets).toBeUndefined();
- });
-
- it("does not mirror conversation secrets onto agent_context for non-ACP conversations", () => {
- // The OpenHands ``Agent`` reads secrets from ``secret_registry``
- // directly (no spawn-env bridging needed), so the LLM-driven path
- // must not get an extra ``agent_context.secrets`` map — that would
- // be both redundant and a surprise for any code that inspects
- // ``agent_context`` for non-secret payload (skills, suffixes, etc.).
- const payload = buildStartConversationRequest({
- settings: DEFAULT_SETTINGS,
- customSecrets: [{ name: "ANTHROPIC_API_KEY" }],
- }) as {
- agent_settings: { agent_context?: { secrets?: Record<string, unknown> } };
- };
-
- expect(payload.agent_settings.agent_context?.secrets).toBeUndefined();
- });
-
- it("appends the route-at-conversation-start suffix when the toggle is on and a meta-profile is active (OpenHands agent)", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- run_router_at_conversation_start: true,
- },
- hasActiveMetaProfile: true,
- }) as {
- agent_settings: { agent_context?: { system_message_suffix?: string } };
- };
-
- const suffix = payload.agent_settings.agent_context?.system_message_suffix;
- expect(suffix).toContain("ROUTE_AT_CONVERSATION_START");
- expect(suffix).toContain("route_task_to_model");
- });
-
- it("appends the route-at-conversation-start suffix for an inline ACP launch when the toggle is on and a meta-profile is active", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- agent_kind: "acp",
- acp_server: "claude-code",
- acp_command: ["npx", "-y", "@agentclientprotocol/claude-agent-acp"],
- },
- run_router_at_conversation_start: true,
- },
- hasActiveMetaProfile: true,
- }) as {
- agent_settings: { agent_context?: { system_message_suffix?: string } };
- };
-
- expect(
- payload.agent_settings.agent_context?.system_message_suffix,
- ).toContain("ROUTE_AT_CONVERSATION_START");
- });
-
- it("does not add the router suffix when the toggle is on but no meta-profile is active", () => {
- // With no active meta-profile the agent-server does not attach
- // `route_task_to_model`, so the instruction must not be emitted even if
- // the toggle was left on (e.g. the active profile was just deleted).
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- run_router_at_conversation_start: true,
- },
- hasActiveMetaProfile: false,
- }) as {
- agent_settings: { agent_context?: { system_message_suffix?: string } };
- };
-
- const suffix =
- payload.agent_settings.agent_context?.system_message_suffix ?? "";
- expect(suffix).not.toContain("ROUTE_AT_CONVERSATION_START");
- });
-
- it("does not add a system_message_suffix for the router when the toggle is off (default)", () => {
- const payload = buildStartConversationRequest({
- settings: DEFAULT_SETTINGS,
- }) as {
- agent_settings: { agent_context?: { system_message_suffix?: string } };
- };
-
- // The suffix may be undefined (no runtime-services block either); assert
- // specifically that the router sentinel is absent when present.
- const suffix =
- payload.agent_settings.agent_context?.system_message_suffix ?? "";
- expect(suffix).not.toContain("ROUTE_AT_CONVERSATION_START");
- });
-
- describe("ACP secret delivery", () => {
- // Settings factory for a containerized ACP conversation.
- const acpSettings = (overrides: Record<string, unknown> = {}) => ({
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- agent_kind: "acp",
- acp_server: "codex",
- acp_command: ["npx", "-y", "@zed-industries/codex-acp"],
- acp_model: "gpt-5.5/medium",
- ...overrides,
- },
- });
-
- it("delivers provider credentials and user secrets uniformly as LookupSecrets in request.secrets only", () => {
- // Provider credentials (e.g. a saved CODEX_AUTH_JSON) are no longer special
- // on the wire — they ride as LookupSecrets like any custom secret. The SDK
- // resolves them off the event loop at spawn, so the loopback fetch is safe
- // (software-agent-sdk#3510). "Reserved" is now only an onboarding concept.
+ describe("secret delivery", () => {
+ it("delivers provider credentials and user secrets as LookupSecrets for an ACP profile", () => {
+ // Provider credentials (e.g. a saved CODEX_AUTH_JSON) ride as
+ // LookupSecrets like any custom secret; the server keeps only the ones
+ // the profile's `secret_refs` allows.
const payload = buildStartConversationRequest({
- settings: acpSettings(),
+ settings: DEFAULT_SETTINGS,
+ agentProfileId: "profile-acp",
+ agentProfileKind: "acp",
customSecrets: [{ name: "CODEX_AUTH_JSON" }, { name: "MY_TOKEN" }],
- }) as {
- agent_settings: {
- acp_model?: string;
- agent_context?: { secrets?: Record<string, { kind: string }> };
- };
- secrets: Record<string, { kind: string }>;
- };
+ }) as unknown as { secrets: Record<string, { kind: string }> };
expect(payload.secrets.CODEX_AUTH_JSON?.kind).toBe("LookupSecret");
expect(payload.secrets.MY_TOKEN?.kind).toBe("LookupSecret");
- // ``request.secrets`` is the sole channel — no agent_context mirror
- // (agent-server >=1.25.0 injects the spawn env from secret_registry).
- expect(payload.agent_settings.agent_context?.secrets).toBeUndefined();
- // The configured model rides along unchanged.
- expect(payload.agent_settings.acp_model).toBe("gpt-5.5/medium");
- });
-
- it("does NOT set secrets_encrypted for ACP — there is no encrypted payload to decrypt", () => {
- // An ACP request carries no encrypted secret (no LLM api_key; credentials
- // are LookupSecrets resolved at runtime). Flagging it encrypted hard-fails
- // ("cipher not configured") on a fresh ACP container without OH_SECRET_KEY.
- const payload = buildStartConversationRequest({
- settings: acpSettings(),
- secretsEncrypted: true,
- customSecrets: [{ name: "CODEX_AUTH_JSON" }],
- }) as { secrets_encrypted?: boolean };
- expect(payload.secrets_encrypted).toBeUndefined();
});
- it("still sets secrets_encrypted for a non-ACP conversation (encrypted LLM key)", () => {
+ it("never asks the server to decrypt request secrets", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
- secretsEncrypted: true,
- }) as { secrets_encrypted?: boolean };
- expect(payload.secrets_encrypted).toBe(true);
+ customSecrets: [{ name: "MY_TOKEN" }],
+ });
+
+ expect(payload).not.toHaveProperty("secrets_encrypted");
+ expect(payload).not.toHaveProperty("agent_settings");
});
});
describe("client tool injection", () => {
it("sends canvas_ui as a client-defined JSON tool", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
});
@@ -863,28 +461,9 @@ describe("buildStartConversationRequest", () => {
openWorldHint: false,
},
});
- expect(
- payload.agent_settings?.tools?.map((tool) => tool.name) ?? [],
- ).not.toContain("canvas_ui");
expect(payload.tool_module_qualnames).toBeUndefined();
});
- it("omits the client tool for an inline ACP agent", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- agent_kind: "acp",
- acp_server: "custom",
- acp_command: ["custom-acp"],
- },
- },
- });
-
- expect(payload.client_tools).toEqual([]);
- });
-
it("omits the client tool for an ACP profile when global settings are stale", () => {
const payload = buildStartConversationRequest({
settings: DEFAULT_SETTINGS,
@@ -911,6 +490,7 @@ describe("buildStartConversationRequest", () => {
it("adds automation setup tags to local conversation requests", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
automationSetup: true,
automationSetupTags: {
@@ -951,6 +531,7 @@ describe("buildStartConversationRequest", () => {
"builds client tools for automationSetup=$automationSetup",
({ automationSetup, expectedTools }) => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
automationSetup,
});
@@ -963,6 +544,7 @@ describe("buildStartConversationRequest", () => {
it("sends the client tool when resuming a conversation", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
conversationId: "legacy-conversation-id",
}) as { conversation_id: string; client_tools: Array<{ name: string }> };
@@ -977,6 +559,7 @@ describe("buildStartConversationRequest", () => {
it("drops conflicting user-supplied Canvas module qualnames", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: {
...DEFAULT_SETTINGS,
conversation_settings: {
@@ -997,6 +580,7 @@ describe("buildStartConversationRequest", () => {
it("preserves non-Canvas custom tool modules", () => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: {
...DEFAULT_SETTINGS,
conversation_settings: {
@@ -1011,91 +595,6 @@ describe("buildStartConversationRequest", () => {
});
});
});
-
- // @spec LLD-001 — Frontend always sends its chosen default model
- describe("llm.model fallback — frontend always sends its chosen default", () => {
- type ModelPayload = {
- agent_settings: Record<string, unknown> & {
- llm: Record<string, unknown>;
- };
- };
-
- function getModelFrom(
- options: Parameters<typeof buildStartConversationRequest>[0],
- ): unknown {
- return (buildStartConversationRequest(options) as unknown as ModelPayload)
- .agent_settings.llm.model;
- }
-
- it("uses the configured model when one is set", () => {
- expect(
- getModelFrom({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- llm: { model: "anthropic/claude-opus-4-5" },
- },
- },
- }),
- ).toBe("anthropic/claude-opus-4-5");
- });
-
- // The agent-server returns '' when no model has been saved yet.
- // Without this guard the empty string passes the old typeof check and
- // the agent-server falls back to its own SDK default (gpt-5.5).
- // SettingsValue includes scalars so inline literals are type-safe here.
- it.each([
- ["undefined", { ...DEFAULT_SETTINGS.agent_settings, llm: {} }],
- [
- "an empty string",
- { ...DEFAULT_SETTINGS.agent_settings, llm: { model: "" } },
- ],
- [
- "whitespace only",
- { ...DEFAULT_SETTINGS.agent_settings, llm: { model: " " } },
- ],
- // No llm key at all — SettingsValue accepts plain scalars.
- [
- "absent (no llm block)",
- { schema_version: 1, agent_kind: "openhands", agent: "CodeActAgent" },
- ],
- // Mirrors a fresh user who skipped onboarding: server returns {}.
- ["entirely empty", {}],
- ])(
- "falls back to DEFAULT_SETTINGS.llm_model when agent_settings.llm.model is %s",
- (_, agentSettings) => {
- expect(
- getModelFrom({
- settings: {
- ...DEFAULT_SETTINGS,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- agent_settings: agentSettings as any,
- },
- }),
- ).toBe(DEFAULT_SETTINGS.llm_model);
- },
- );
-
- // encryptedAgentSettings overrides settings.agent_settings at conversation
- // start; if the encrypted payload has no model set the frontend default
- // must still be sent explicitly.
- it.each([
- ["carries an empty model", { llm: { model: "" } }],
- ["is empty", {}],
- ])(
- "falls back to DEFAULT_SETTINGS.llm_model when encryptedAgentSettings %s",
- (_, encryptedAgentSettings) => {
- expect(
- getModelFrom({
- settings: DEFAULT_SETTINGS,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- encryptedAgentSettings: encryptedAgentSettings as any,
- }),
- ).toBe(DEFAULT_SETTINGS.llm_model);
- },
- );
- });
});
describe("getDefaultConversationTitle", () => {
@@ -1564,207 +1063,47 @@ describe("buildRuntimeServicesSystemSuffix", () => {
expect(runtime).toBe("local");
expect(mockGetServerInfo).toHaveBeenCalledOnce();
});
+});
- it("reports the per-launch LLM override from server capabilities", async () => {
- mockGetCachedAgentServerInfo.mockReturnValue({
- version: "1.54.0",
- capabilities: ["tool_catalog_v1"],
+type LaunchAdditions = {
+ system_message_suffix_append?: string;
+ llm_profile_ref?: string;
+ skills?: Array<{ name: string; source: string; content: string }>;
+};
+
+const additionsOf = (payload: unknown): LaunchAdditions | undefined =>
+ (payload as { agent_launch_additions?: LaunchAdditions })
+ .agent_launch_additions;
+
+const RUNTIME_SERVICES = {
+ mode: "dev:automation",
+ services: {
+ agent_server: { url_from_agent: "http://localhost:18000" },
+ automation: { url_from_agent: "http://localhost:18001" },
+ },
+};
+
+describe("profile launch additions", () => {
+ it("carries runtime services and leaves the saved global suffix to the profile", () => {
+ const payload = buildStartConversationRequest({
+ ...PROFILE,
+ settings: {
+ ...DEFAULT_SETTINGS,
+ agent_settings: {
+ ...DEFAULT_SETTINGS.agent_settings,
+ agent_context: { system_message_suffix: "MARKER-GLOBAL-RULES" },
+ },
+ },
+ query: "hello",
+ runtimeServicesInfo: RUNTIME_SERVICES,
});
- await expect(backendSupportsLaunchLlmOverride()).resolves.toBe(false);
- mockGetCachedAgentServerInfo.mockReturnValue({
- version: "1.54.0",
- capabilities: ["tool_catalog_v1", "agent_launch_pipeline_v1"],
- });
- await expect(backendSupportsLaunchLlmOverride()).resolves.toBe(true);
- });
-});
-
-describe("agent_settings runtime services suffix", () => {
- it("does not set system_message_suffix when no runtime info is provided", () => {
- const payload = buildStartConversationRequest({
- settings: DEFAULT_SETTINGS,
- query: "hello",
- }) as {
- agent_settings: { agent_context: Record<string, unknown> };
- };
- expect(payload.agent_settings.agent_context).toMatchObject({
- load_public_skills: false,
- load_user_skills: true,
- load_project_skills: true,
- });
- expect(Array.isArray(payload.agent_settings.agent_context.skills)).toBe(
- true,
- );
- });
-
- it("sets system_message_suffix when backend runtime info is provided", () => {
- const payload = buildStartConversationRequest({
- settings: DEFAULT_SETTINGS,
- query: "hello",
- runtimeServicesInfo: {
- mode: "dev:automation",
- services: {
- agent_server: { url_from_agent: "http://localhost:18000" },
- automation: {
- url_from_agent: "http://localhost:18001",
- },
- },
- },
- }) as {
- agent_settings: { agent_context: Record<string, unknown> };
- };
- expect(payload.agent_settings.agent_context).toMatchObject({
- load_public_skills: false,
- load_user_skills: true,
- });
- expect(
- payload.agent_settings.agent_context.system_message_suffix as string,
- ).toContain("<RUNTIME_SERVICES>");
- });
-
- it("preserves a saved system_message_suffix when runtime services are advertised", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- agent_context: {
- system_message_suffix: "MARKER-GLOBAL-RULES",
- },
- },
- },
- query: "hello",
- runtimeServicesInfo: {
- mode: "dev:automation",
- services: {
- agent_server: { url_from_agent: "http://localhost:18000" },
- automation: {
- url_from_agent: "http://localhost:18001",
- },
- },
- },
- }) as {
- agent_settings: { agent_context: Record<string, unknown> };
- };
- const suffix = payload.agent_settings.agent_context
- .system_message_suffix as string;
- expect(suffix).toMatch(/^MARKER-GLOBAL-RULES\n\n<RUNTIME_SERVICES>/);
- });
-
- it("keeps a saved suffix when no runtime services are advertised", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- agent_context: { system_message_suffix: "MARKER-GLOBAL-RULES" },
- },
- },
- query: "hello",
- }) as { agent_settings: { agent_context: Record<string, unknown> } };
-
- expect(payload.agent_settings.agent_context.system_message_suffix).toBe(
- "MARKER-GLOBAL-RULES",
- );
- });
-
- it("omits the suffix when neither a saved suffix nor runtime services exist", () => {
- const payload = buildStartConversationRequest({
- settings: DEFAULT_SETTINGS,
- query: "hello",
- }) as { agent_settings: { agent_context: Record<string, unknown> } };
-
- expect(payload.agent_settings.agent_context).not.toHaveProperty(
- "system_message_suffix",
- );
- });
-
- it("combines saved and runtime suffixes on the profile path", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- agent_context: { system_message_suffix: "MARKER-GLOBAL-RULES" },
- },
- },
- query: "hello",
- agentProfileId: "profile-openhands",
- agentProfileKind: "openhands",
- runtimeServicesInfo: {
- mode: "dev:automation",
- services: {
- agent_server: { url_from_agent: "http://localhost:18000" },
- automation: { url_from_agent: "http://localhost:18001" },
- },
- },
- }) as {
- agent_profile_id?: string;
- agent_settings?: unknown;
- agent_launch_additions?: { system_message_suffix_append?: string };
- };
-
- expect(payload.agent_profile_id).toBe("profile-openhands");
- expect(payload.agent_settings).toBeUndefined();
- expect(
- payload.agent_launch_additions?.system_message_suffix_append,
- ).toMatch(/^MARKER-GLOBAL-RULES\n\n<RUNTIME_SERVICES>/);
- expect(
- payload.agent_launch_additions?.system_message_suffix_append,
- ).toContain("http://localhost:18001");
- });
-
- it("carries runtime services on the profile path", () => {
- const payload = buildStartConversationRequest({
- settings: DEFAULT_SETTINGS,
- query: "hello",
- agentProfileId: "profile-openhands",
- agentProfileKind: "openhands",
- runtimeServicesInfo: {
- mode: "dev:automation",
- services: {
- agent_server: { url_from_agent: "http://localhost:18000" },
- automation: { url_from_agent: "http://localhost:18001" },
- },
- },
- }) as {
- agent_profile_id?: string;
- agent_settings?: unknown;
- agent_launch_additions?: { system_message_suffix_append?: string };
- };
-
- expect(payload.agent_profile_id).toBe("profile-openhands");
- expect(payload.agent_settings).toBeUndefined();
- expect(
- payload.agent_launch_additions?.system_message_suffix_append,
- ).toContain("<RUNTIME_SERVICES>");
- expect(
- payload.agent_launch_additions?.system_message_suffix_append,
- ).toContain("http://localhost:18001");
- });
-
- it("keeps the route-at-conversation-start suffix off the profile path", () => {
- const payload = buildStartConversationRequest({
- settings: { ...DEFAULT_SETTINGS, run_router_at_conversation_start: true },
- hasActiveMetaProfile: true,
- query: "hello",
- agentProfileId: "profile-openhands",
- agentProfileKind: "openhands",
- runtimeServicesInfo: {
- mode: "dev:automation",
- services: {
- automation: { url_from_agent: "http://localhost:18001" },
- },
- },
- }) as {
- agent_launch_additions?: { system_message_suffix_append?: string };
- };
-
- const appended =
- payload.agent_launch_additions?.system_message_suffix_append;
- expect(appended).toContain("<RUNTIME_SERVICES>");
- expect(appended).not.toContain("ROUTE_AT_CONVERSATION_START");
+ const appended = additionsOf(payload)?.system_message_suffix_append;
+ expect(payload.agent_profile_id).toBe("profile-1");
+ expect(payload).not.toHaveProperty("agent_settings");
+ expect(appended).toMatch(/^<RUNTIME_SERVICES>/);
+ expect(appended).toContain("http://localhost:18001");
+ expect(appended).not.toContain("MARKER-GLOBAL-RULES");
});
it("carries runtime services on an ACP profile launch too", () => {
@@ -1773,385 +1112,81 @@ describe("agent_settings runtime services suffix", () => {
query: "hello",
agentProfileId: "profile-acp",
agentProfileKind: "acp",
- runtimeServicesInfo: {
- mode: "dev:automation",
- services: {
- automation: { url_from_agent: "http://localhost:18001" },
- },
- },
- }) as {
- agent_profile_id?: string;
- agent_launch_additions?: { system_message_suffix_append?: string };
- };
-
- expect(payload.agent_profile_id).toBe("profile-acp");
- expect(
- payload.agent_launch_additions?.system_message_suffix_append,
- ).toContain("<RUNTIME_SERVICES>");
- });
-
- it("omits profile additions without a saved suffix or runtime services", () => {
- const payload = buildStartConversationRequest({
- settings: DEFAULT_SETTINGS,
- query: "hello",
- agentProfileId: "profile-openhands",
- agentProfileKind: "openhands",
- }) as { agent_launch_additions?: unknown };
-
- expect(payload.agent_launch_additions).toBeUndefined();
- });
-});
-
-describe("buildStartConversationRequest — ACP discriminator", () => {
- it("builds ACP agent settings when agent_kind is 'acp'", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- schema_version: 1,
- agent_kind: "acp",
- acp_server: "claude-code",
- acp_command: [],
- acp_model: "claude-opus-4-5",
- // These fields are LLM-only and must NOT leak into ACP settings.
- // (mcp_config is handled separately — it IS forwarded for ACP; see
- // the dedicated tests below.)
- agent: "CodeActAgent",
- llm: { model: "gpt-4", api_key: "should-not-appear" },
- condenser: { enabled: true, max_size: 240 },
- },
- },
- }) as {
- agent?: unknown;
- agent_settings: Record<string, unknown> & {
- acp_command?: string[];
- acp_model?: string | null;
- agent_context?: unknown;
- };
- tags?: Record<string, string>;
- };
-
- expect(payload.agent).toBeUndefined();
- expect(payload.agent_settings.agent_kind).toBe("acp");
- expect(payload.agent_settings.acp_command).toEqual([
- ...getClientAcpProvider("claude-code")!.default_command,
- ]);
- expect(payload.agent_settings.acp_model).toBe("claude-opus-4-5");
- // LLM-only fields must not leak into the ACP settings payload.
- expect(payload.agent_settings.llm).toBeUndefined();
- expect(payload.agent_settings.condenser).toBeUndefined();
- expect(payload.agent_settings.tools).toBeUndefined();
- const acpAgentContext = payload.agent_settings.agent_context as Record<
- string,
- unknown
- >;
- expect(acpAgentContext).toMatchObject({
- load_public_skills: false,
- load_user_skills: true,
- load_project_skills: true,
- });
- expect(Array.isArray(acpAgentContext.skills)).toBe(true);
- expect(payload.tags).toEqual({
- [ACP_SERVER_TAG_KEY]: "claude-code",
- [CLIENT_SOURCE_TAG_KEY]: AGENT_CANVAS_SOURCE,
+ runtimeServicesInfo: RUNTIME_SERVICES,
});
- });
-
- it("forwards mcp_config to the ACP subprocess when servers are configured", () => {
- // mcp_config is a shared field: the SDK's ACPAgent forwards these servers
- // to the ACP subprocess at session creation, so the start payload must
- // carry it (it is intentionally NOT one of the stripped ACP-only fields).
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- schema_version: 1,
- agent_kind: "acp",
- acp_server: "claude-code",
- acp_command: ["npx", "-y", "@agentclientprotocol/claude-agent-acp"],
- mcp_config: {
- fetch: { command: "uvx", args: ["mcp-server-fetch"] },
- },
- },
- },
- }) as { agent_settings: { mcp_config?: unknown } };
-
- expect(payload.agent_settings.mcp_config).toEqual({
- fetch: { command: "uvx", args: ["mcp-server-fetch"] },
- });
- });
-
- it("omits mcp_config from the ACP payload when it carries no servers", () => {
- // An empty / serverless mcp_config must not be sent as ``mcp_config: {}``.
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- schema_version: 1,
- agent_kind: "acp",
- acp_server: "claude-code",
- acp_command: ["npx", "-y", "@agentclientprotocol/claude-agent-acp"],
- mcp_config: {},
- },
- },
- }) as { agent_settings: { mcp_config?: unknown } };
- expect(payload.agent_settings.mcp_config).toBeUndefined();
- });
-
- it("does not include ACP-only fields in OpenHands agent settings", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- ...DEFAULT_SETTINGS.agent_settings,
- agent_kind: "openhands",
- llm: { model: "gpt-4" },
- acp_command: ["npx", "leftover"],
- acp_server: "claude-code",
- },
- },
- }) as {
- agent?: unknown;
- agent_settings: Record<string, unknown> & {
- llm: Record<string, unknown>;
- };
- tags?: Record<string, string>;
- };
-
- expect(payload.agent).toBeUndefined();
- expect(payload.agent_settings.agent_kind).toBe("openhands");
- expect(payload.agent_settings.acp_command).toBeUndefined();
- expect(payload.agent_settings.acp_server).toBeUndefined();
- expect(payload.agent_settings.llm.model).toBe("gpt-4");
- expect(payload.tags).toEqual({
- [CLIENT_SOURCE_TAG_KEY]: AGENT_CANVAS_SOURCE,
- });
- });
-
- it("omits acp_model when the user clears it (null)", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- schema_version: 1,
- agent_kind: "acp",
- acp_server: "custom",
- acp_command: ["./bin/my-agent"],
- acp_model: null,
- },
- },
- }) as { agent_settings: Record<string, unknown> };
-
- expect(payload.agent_settings.agent_kind).toBe("acp");
- expect(payload.agent_settings.acp_model).toBeUndefined();
- });
-
- it("falls back to the preferred (Vertex-safe) default for a null Gemini acp_model", () => {
- // The start-request fallback is the third default-model surface (after
- // onboarding and Settings → Agent) — all three must substitute the same
- // Vertex-safe model, or a saved ``null`` would silently run gemini-cli's
- // 404-prone default on Vertex (software-agent-sdk#3532).
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- schema_version: 1,
- agent_kind: "acp",
- acp_server: "gemini-cli",
- acp_model: null,
- },
- },
- }) as { agent_settings: Record<string, unknown> };
-
- expect(payload.agent_settings.acp_model).toBe(ACP_VERTEX_SAFE_MODEL);
- });
-
- it("resolves an empty acp_command from the registry by acp_server", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- schema_version: 1,
- agent_kind: "acp",
- acp_server: "claude-code",
- acp_command: [],
- acp_model: null,
- },
- },
- }) as {
- agent_settings: Record<string, unknown> & { acp_command?: unknown[] };
- };
-
- expect(payload.agent_settings.acp_command).toEqual([
- ...getClientAcpProvider("claude-code")!.default_command,
- ]);
- });
-
- it("resolves an absent acp_command for built-in providers too", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- schema_version: 1,
- agent_kind: "acp",
- acp_server: "codex",
- acp_model: null,
- },
- },
- }) as {
- agent_settings: Record<string, unknown> & { acp_command?: unknown[] };
- };
-
- expect(payload.agent_settings.acp_command).toEqual([
- ...getClientAcpProvider("codex")!.default_command,
- ]);
- });
-
- it("leaves acp_command alone when acp_server is 'custom'", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- schema_version: 1,
- agent_kind: "acp",
- acp_server: "custom",
- acp_command: [],
- acp_model: null,
- },
- },
- }) as {
- agent_settings: Record<string, unknown> & { acp_command?: unknown[] };
- };
-
- expect(payload.agent_settings.acp_command).toEqual([]);
- });
-
- it("leaves acp_command alone for an unknown acp_server key", () => {
- const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- schema_version: 1,
- agent_kind: "acp",
- acp_server: "future-provider-not-yet-mirrored",
- acp_command: [],
- acp_model: null,
- },
- },
- }) as {
- agent_settings: Record<string, unknown> & { acp_command?: unknown[] };
- };
-
- expect(payload.agent_settings.acp_command).toEqual([]);
+ expect(payload.agent_profile_id).toBe("profile-acp");
+ expect(additionsOf(payload)?.system_message_suffix_append).toContain(
+ "<RUNTIME_SERVICES>",
+ );
});
it.each([
- ["claude-code", undefined],
- ["gemini-cli", ACP_VERTEX_SAFE_MODEL],
+ ["the toggle is on and the profile carries a router", true, true, true],
+ ["the profile carries no router", true, false, false],
+ ["the toggle is off", false, true, false],
])(
- "leaves an empty %s acp_model to the agent unless Canvas prefers one",
- (acpServer, expected) => {
+ "routes the first message only when %s",
+ (_case, runAtStart, profileHasRouter, expected) => {
const payload = buildStartConversationRequest({
+ ...PROFILE,
settings: {
...DEFAULT_SETTINGS,
- agent_settings: {
- schema_version: 1,
- agent_kind: "acp",
- acp_server: acpServer,
- acp_command: [],
- acp_model: "",
- },
+ run_router_at_conversation_start: runAtStart,
},
- }) as {
- agent_settings: Record<string, unknown> & { acp_model?: unknown };
- };
+ profileHasRouter,
+ query: "hello",
+ });
- expect(payload.agent_settings.acp_model).toBe(expected);
+ const appended = additionsOf(payload)?.system_message_suffix_append;
+ if (expected) {
+ expect(appended).toContain("<ROUTE_AT_CONVERSATION_START>");
+ } else {
+ expect(appended ?? "").not.toContain("ROUTE_AT_CONVERSATION_START");
+ }
},
);
- it("omits acp_model for the custom preset when none is configured", () => {
+ it("adds a catalog skill the opening message invokes", () => {
+ const [entry] = SKILLS_CATALOG;
const payload = buildStartConversationRequest({
- settings: {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- schema_version: 1,
- agent_kind: "acp",
- acp_server: "custom",
- acp_command: ["my-custom-acp"],
- acp_model: "",
- },
- },
- }) as {
- agent_settings: Record<string, unknown> & { acp_model?: unknown };
- };
+ ...PROFILE,
+ settings: DEFAULT_SETTINGS,
+ query: `/${entry.name} please`,
+ });
- expect(payload.agent_settings.acp_model).toBeUndefined();
+ const skills = additionsOf(payload)?.skills ?? [];
+ expect(skills.map((skill) => skill.name)).toEqual([entry.name]);
+ expect(skills[0].content).toBe(entry.content);
+ expect(skills[0].source).toMatch(new RegExp(`/${entry.name}/SKILL\\.md$`));
});
- it("ACP → OpenHands → ACP round trip leaves no field leakage", () => {
- const baseAcpSettings = {
- ...DEFAULT_SETTINGS,
- agent_settings: {
- schema_version: 1,
- agent_kind: "acp",
- acp_server: "claude-code",
- acp_command: [],
- // Legacy persisted value: provider creds no longer ride acp_env —
- // they flow through the Secrets panel (request.secrets). A stale
- // acp_env left on saved settings must be dropped, not forwarded.
- acp_env: { ANTHROPIC_API_KEY: "user-set-via-api" },
- acp_model: "claude-opus-4-5",
- agent: "CodeActAgent",
- llm: { model: "gpt-4o", api_key: "stale-from-prior-oh-run" },
- condenser: { enabled: true, max_size: 200 },
- },
- };
-
- const ohPayload = buildStartConversationRequest({
- settings: {
- ...baseAcpSettings,
- agent_settings: {
- ...baseAcpSettings.agent_settings,
- agent_kind: "openhands",
- },
- },
- }) as {
- agent_settings: Record<string, unknown> & {
- llm: Record<string, unknown>;
- };
- };
+ it.each([
+ ["an ACP profile", "acp" as const, (name: string) => `/${name} please`],
+ [
+ "a message that invokes no catalog skill",
+ "openhands" as const,
+ () => "/not-a-catalog-skill please",
+ ],
+ ])("adds no skills for %s", (_case, kind, query) => {
+ const payload = buildStartConversationRequest({
+ settings: DEFAULT_SETTINGS,
+ agentProfileId: "profile-1",
+ agentProfileKind: kind,
+ query: query(SKILLS_CATALOG[0].name),
+ });
- expect(ohPayload.agent_settings.agent_kind).toBe("openhands");
- expect(ohPayload.agent_settings.acp_command).toBeUndefined();
- expect(ohPayload.agent_settings.acp_env).toBeUndefined();
- expect(ohPayload.agent_settings.acp_model).toBeUndefined();
- expect(ohPayload.agent_settings.acp_server).toBeUndefined();
- expect(ohPayload.agent_settings.llm.model).toBe("gpt-4o");
+ expect(additionsOf(payload)?.skills).toBeUndefined();
+ });
- const acpPayload = buildStartConversationRequest({
- settings: baseAcpSettings,
- }) as {
- agent_settings: Record<string, unknown> & {
- acp_command?: unknown;
- acp_env?: unknown;
- acp_model?: unknown;
- llm?: unknown;
- condenser?: unknown;
- };
- };
+ it("omits additions when there is nothing to add", () => {
+ const payload = buildStartConversationRequest({
+ ...PROFILE,
+ settings: DEFAULT_SETTINGS,
+ query: "hello",
+ });
- expect(acpPayload.agent_settings.agent_kind).toBe("acp");
- expect(acpPayload.agent_settings.acp_command).toEqual([
- ...getClientAcpProvider("claude-code")!.default_command,
- ]);
- expect(acpPayload.agent_settings.acp_model).toBe("claude-opus-4-5");
- // acp_env is no longer a forwarded ACP setting — a stale value on saved
- // settings is dropped rather than leaked into the conversation request.
- expect(acpPayload.agent_settings.acp_env).toBeUndefined();
- expect(acpPayload.agent_settings.llm).toBeUndefined();
- expect(acpPayload.agent_settings.condenser).toBeUndefined();
+ expect(additionsOf(payload)).toBeUndefined();
});
});
@@ -2175,12 +1210,6 @@ describe("buildStartConversationRequestWithEncryptedSettings", () => {
skillEnablement: { disabledSkills: [] },
});
secretsSpy = vi.spyOn(SecretsService, "getSecrets").mockResolvedValue([]);
- // Default: no active meta-profile so the route-at-start suffix is off.
- mockListMetaProfiles.mockReset();
- mockListMetaProfiles.mockResolvedValue({
- meta_profiles: [],
- active_meta_profile: null,
- });
});
// vitest is not configured with `restoreMocks`, so restore explicitly.
@@ -2193,6 +1222,7 @@ describe("buildStartConversationRequestWithEncryptedSettings", () => {
mockLoadHooks.mockResolvedValue({ hook_config: WORKSPACE_HOOK_CONFIG });
const payload = await buildStartConversationRequestWithEncryptedSettings({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
workingDir: "/workspace/my-project/0f1e2d3c",
hooksProjectDir: "/workspace/my-project",
@@ -2208,6 +1238,7 @@ describe("buildStartConversationRequestWithEncryptedSettings", () => {
mockLoadHooks.mockResolvedValue({ hook_config: null });
await buildStartConversationRequestWithEncryptedSettings({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
workingDir: "/workspace/my-project/0f1e2d3c",
});
@@ -2221,6 +1252,7 @@ describe("buildStartConversationRequestWithEncryptedSettings", () => {
mockLoadHooks.mockResolvedValue({ hook_config: null });
const payload = await buildStartConversationRequestWithEncryptedSettings({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
hooksProjectDir: "/workspace/my-project",
});
@@ -2232,86 +1264,29 @@ describe("buildStartConversationRequestWithEncryptedSettings", () => {
mockLoadHooks.mockRejectedValue(new Error("500 Internal Server Error"));
const payload = await buildStartConversationRequestWithEncryptedSettings({
+ ...PROFILE,
settings: DEFAULT_SETTINGS,
hooksProjectDir: "/workspace/my-project",
});
expect(payload.hook_config).toBeUndefined();
- expect(payload.agent_settings).toBeDefined();
+ expect(payload.agent_profile_id).toBe("profile-1");
});
- it("stamps the route-at-start suffix when the toggle is on and a meta-profile is active", async () => {
- mockListMetaProfiles.mockResolvedValue({
- meta_profiles: [],
- active_meta_profile: {
- llm_router_profile_id: "router-1",
- name: "Model Router",
- routing_strategy: "classification",
- routing_models: [],
- router_model: null,
- fallback_model: null,
- },
- });
-
- const payload = (await buildStartConversationRequestWithEncryptedSettings({
- settings: {
- ...DEFAULT_SETTINGS,
- run_router_at_conversation_start: true,
- },
- hooksProjectDir: "/workspace/my-project",
- })) as {
- agent_settings: {
- agent_context?: { system_message_suffix?: string };
- };
- };
-
- expect(
- payload.agent_settings?.agent_context?.system_message_suffix,
- ).toContain("ROUTE_AT_CONVERSATION_START");
- });
-
- it("omits the route-at-start suffix when the toggle is on but no meta-profile is active", async () => {
- // active_meta_profile is null by default (see beforeEach). Even with the
- // toggle on, no suffix should be emitted since the agent-server won't
- // attach `route_task_to_model` without an active profile.
- const payload = (await buildStartConversationRequestWithEncryptedSettings({
+ it("routes the first message for a profile that carries a router", async () => {
+ const payload = await buildStartConversationRequestWithEncryptedSettings({
+ ...PROFILE,
settings: {
...DEFAULT_SETTINGS,
run_router_at_conversation_start: true,
},
+ profileHasRouter: true,
hooksProjectDir: "/workspace/my-project",
- })) as {
- agent_settings: {
- agent_context?: { system_message_suffix?: string };
- };
- };
-
- expect(
- payload.agent_settings?.agent_context?.system_message_suffix ?? "",
- ).not.toContain("ROUTE_AT_CONVERSATION_START");
- });
+ });
- it("omits the route-at-start suffix when the meta-profiles endpoint fails (fails closed)", async () => {
- mockListMetaProfiles.mockRejectedValue(
- new Error("503 Service Unavailable"),
+ expect(additionsOf(payload)?.system_message_suffix_append).toContain(
+ "ROUTE_AT_CONVERSATION_START",
);
-
- const payload = (await buildStartConversationRequestWithEncryptedSettings({
- settings: {
- ...DEFAULT_SETTINGS,
- run_router_at_conversation_start: true,
- },
- hooksProjectDir: "/workspace/my-project",
- })) as {
- agent_settings: {
- agent_context?: { system_message_suffix?: string };
- };
- };
-
- // If we can't confirm a router is active, fail closed: no instruction.
- expect(
- payload.agent_settings?.agent_context?.system_message_suffix ?? "",
- ).not.toContain("ROUTE_AT_CONVERSATION_START");
});
});
diff --git a/__tests__/api/agent-server-conversation-service-regressions.test.ts b/__tests__/api/agent-server-conversation-service-regressions.test.ts
index 6869ebec05..fc40078eca 100644
--- a/__tests__/api/agent-server-conversation-service-regressions.test.ts
+++ b/__tests__/api/agent-server-conversation-service-regressions.test.ts
@@ -195,7 +195,9 @@ describe("AgentServerConversationService", () => {
},
});
- await AgentServerConversationService.createConversation();
+ await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
+ });
expect(mockHttpPost).toHaveBeenCalledWith(
"/api/conversations",
@@ -222,7 +224,9 @@ describe("AgentServerConversationService", () => {
},
});
- await AgentServerConversationService.createConversation();
+ await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
+ });
const payload = mockHttpPost.mock.calls[0][1] as Record<string, unknown>;
expect(payload).not.toHaveProperty("user_id");
@@ -258,7 +262,9 @@ describe("AgentServerConversationService", () => {
},
});
- await AgentServerConversationService.createConversation();
+ await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
+ });
expect(mockHttpPost).toHaveBeenCalledWith(
"/api/conversations",
@@ -286,7 +292,9 @@ describe("AgentServerConversationService", () => {
},
});
- await AgentServerConversationService.createConversation();
+ await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
+ });
const [payloadCall] = mockHttpPost.mock.calls;
const payload = payloadCall[1] as {
@@ -320,6 +328,7 @@ describe("AgentServerConversationService", () => {
});
await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
workingDirOverride: "/Users/jane/projects/foo",
});
@@ -347,6 +356,7 @@ describe("AgentServerConversationService", () => {
});
await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
workingDirOverride: "/Users/jane/projects/foo",
workspaceMode: "new_worktree",
parentConversationId: "parent-conversation-id",
diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.ts
index 2f3fdd08fa..714c4b4cd4 100644
--- a/__tests__/api/agent-server-conversation-service.test.ts
+++ b/__tests__/api/agent-server-conversation-service.test.ts
@@ -600,6 +600,7 @@ describe("AgentServerConversationService", () => {
});
await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
agentLlmProfileRef: "powerful",
});
@@ -646,6 +647,7 @@ describe("AgentServerConversationService", () => {
});
await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
agentLlmProfileRef: "powerful",
});
@@ -689,6 +691,7 @@ describe("AgentServerConversationService", () => {
// must degrade to the account-wide active profile instead of sending an
// unresolvable name.
await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
agentLlmProfileRef: "powerful",
});
@@ -716,8 +719,12 @@ describe("AgentServerConversationService", () => {
},
});
- await AgentServerConversationService.createConversation();
- await AgentServerConversationService.createConversation();
+ await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
+ });
+ await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
+ });
// The first conversation on a cold agent-server can exceed the client's
// default timeout, so createConversation constructs its ConversationClient
@@ -789,7 +796,9 @@ describe("AgentServerConversationService", () => {
},
});
- await AgentServerConversationService.createConversation();
+ await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
+ });
const [payloadCall] = mockHttpPost.mock.calls;
const payload = payloadCall[1] as {
@@ -823,6 +832,7 @@ describe("AgentServerConversationService", () => {
});
await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
workingDirOverride: "/Users/jane/projects/foo",
});
@@ -854,6 +864,7 @@ describe("AgentServerConversationService", () => {
});
await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
workingDirOverride: "/Users/jane/projects/foo",
workspaceMode: "new_worktree",
});
@@ -2444,6 +2455,7 @@ describe("AgentServerConversationService", () => {
});
await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
initialUserMsg: "Inspect the repository",
metadata: {
selected_repository: "OpenHands/agent-canvas",
@@ -2483,7 +2495,9 @@ describe("AgentServerConversationService", () => {
});
await expect(
- AgentServerConversationService.createConversation(),
+ AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
+ }),
).rejects.toThrow("No backend is configured");
});
@@ -3113,6 +3127,7 @@ describe("AgentServerConversationService", () => {
];
const result = await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
initialUserMsg: "Inspect the repository",
plugins,
workingDirOverride: "/Users/jane/projects/canvas",
@@ -3148,7 +3163,9 @@ describe("AgentServerConversationService", () => {
it("does not persist empty metadata for a conversation without a selected source", async () => {
arrangeLocalCreate("conv-unselected");
- await AgentServerConversationService.createConversation();
+ await AgentServerConversationService.createConversation({
+ agentProfileId: "profile-1",
+ });
expect(getStoredConversationMetadata("conv-unselected")).toBeNull();
expect(window.localStorage.getItem(metadataStorageKey)).toBeNull();
diff --git a/__tests__/api/use-create-conversation-metadata.test.ts b/__tests__/api/use-create-conversation-metadata.test.ts
index 542905025c..351e1967b5 100644
--- a/__tests__/api/use-create-conversation-metadata.test.ts
+++ b/__tests__/api/use-create-conversation-metadata.test.ts
@@ -30,6 +30,16 @@ const {
mockGetTelemetryDistinctId: vi.fn(),
}));
+vi.mock(
+ "#/hooks/use-migrate-default-agent-profile",
+ async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/use-migrate-default-agent-profile")
+ >()),
+ ensureDefaultAgentProfileMigrated: vi.fn().mockResolvedValue(true),
+ }),
+);
+
vi.mock("@openhands/typescript-client/clients", async () => {
const actual = await vi.importActual<
typeof import("@openhands/typescript-client/clients")
@@ -165,6 +175,7 @@ describe("useCreateConversation persists selected repository metadata", () => {
git_provider: "github",
selected_workspace: null,
workspace_mode: "new_worktree",
+ active_profile: "default",
});
});
@@ -186,17 +197,23 @@ describe("useCreateConversation persists selected repository metadata", () => {
git_provider: null,
selected_workspace: "/home/me/code/some-project",
workspace_mode: "local_repo",
+ active_profile: "default",
});
});
- it("does not write metadata when neither a repository nor a workspace is attached", async () => {
+ it("writes no source metadata when neither a repository nor a workspace is attached", async () => {
const { result } = renderHook(() => useCreateConversation(), { wrapper });
result.current.mutate({ query: "scratch session" });
await waitFor(() => expect(result.current.isSuccess).toBe(true));
- expect(getStoredConversationMetadata("conv-new")).toBeNull();
+ expect(getStoredConversationMetadata("conv-new")).toEqual({
+ selected_repository: null,
+ selected_branch: null,
+ git_provider: null,
+ active_profile: "default",
+ });
});
it("stamps the active LLM profile even when no repo or workspace is attached (#1082)", async () => {
diff --git a/__tests__/components/features/chat/components/chat-input-actions.test.tsx b/__tests__/components/features/chat/components/chat-input-actions.test.tsx
index 37eea70d0e..d934775d96 100644
--- a/__tests__/components/features/chat/components/chat-input-actions.test.tsx
+++ b/__tests__/components/features/chat/components/chat-input-actions.test.tsx
@@ -43,6 +43,9 @@ vi.mock(
ChatInputProfileMenuContent: () => (
<div data-testid="agent-profile-menu-stub" />
),
+ ChatInputAgentProfilePicker: () => (
+ <div data-testid="agent-profile-pill-stub" />
+ ),
}),
);
@@ -339,6 +342,16 @@ describe("ChatInputActions — Switch agent profile gate (OSS-5735)", () => {
).toBeInTheDocument();
});
+ it("names the agent profile on the home page", async () => {
+ renderWithProviders(<ChatInputActions disabled={false} />, {
+ navigation: { conversationId: null },
+ });
+
+ expect(
+ await screen.findByTestId("agent-profile-pill-stub"),
+ ).toBeInTheDocument();
+ });
+
it("offers Switch agent profile in a blank (unstarted) conversation", async () => {
useActiveConversationMock.mockReturnValue({
data: { conversation_id: "conv-blank", llm_model: null },
@@ -372,6 +385,9 @@ describe("ChatInputActions — Switch agent profile gate (OSS-5735)", () => {
expect(
screen.queryByTestId("switch-agent-profile-button"),
).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("agent-profile-pill-stub"),
+ ).not.toBeInTheDocument();
});
it("does not offer Switch agent profile when the backend has no profiles", async () => {
diff --git a/__tests__/components/features/chat/components/chat-input-profile-picker.test.tsx b/__tests__/components/features/chat/components/chat-input-profile-picker.test.tsx
index 80fb301b17..6b986d62c8 100644
--- a/__tests__/components/features/chat/components/chat-input-profile-picker.test.tsx
+++ b/__tests__/components/features/chat/components/chat-input-profile-picker.test.tsx
@@ -29,7 +29,10 @@ vi.mock("#/hooks/mutation/use-activate-agent-profile", () => ({
ACTIVATE_AGENT_PROFILE_MUTATION_KEY: ["activate-agent-profile"],
}));
-import { ChatInputProfileMenuContent } from "#/components/features/chat/components/chat-input-profile-picker";
+import {
+ ChatInputAgentProfilePicker,
+ ChatInputProfileMenuContent,
+} from "#/components/features/chat/components/chat-input-profile-picker";
const PROFILES = [
{ id: "id-default", name: "Default", agent_kind: "openhands" },
@@ -213,3 +216,45 @@ describe("ChatInputProfileMenuContent", () => {
);
});
});
+
+describe("ChatInputAgentProfilePicker", () => {
+ beforeEach(() => {
+ useAgentProfilesMock.mockReset();
+ useActiveConversationMock.mockReset();
+ useActiveConversationMock.mockReturnValue({ data: undefined });
+ activateProfileMutate.mockReset();
+ });
+
+ it("names the active profile and switches it from its menu", async () => {
+ useAgentProfilesMock.mockReturnValue({
+ data: { profiles: PROFILES, active_agent_profile_id: "id-default" },
+ isLoading: false,
+ });
+ renderWithProviders(<ChatInputAgentProfilePicker />, {
+ navigation: { conversationId: null },
+ });
+
+ const pill = screen.getByTestId("chat-input-agent-profile");
+ expect(pill).toHaveTextContent("Default");
+ fireEvent.click(pill);
+ fireEvent.click(
+ await screen.findByTestId("chat-input-agent-profile-option-Codex"),
+ );
+
+ expect(activateProfileMutate).toHaveBeenCalledWith("id-codex");
+ });
+
+ it("stays hidden without an active profile", () => {
+ useAgentProfilesMock.mockReturnValue({
+ data: { profiles: PROFILES, active_agent_profile_id: null },
+ isLoading: false,
+ });
+ renderWithProviders(<ChatInputAgentProfilePicker />, {
+ navigation: { conversationId: null },
+ });
+
+ expect(
+ screen.queryByTestId("chat-input-agent-profile"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/__tests__/components/features/chat/skill-install-restart-banner.test.tsx b/__tests__/components/features/chat/skill-install-restart-banner.test.tsx
index b97cc2ac13..76b8177012 100644
--- a/__tests__/components/features/chat/skill-install-restart-banner.test.tsx
+++ b/__tests__/components/features/chat/skill-install-restart-banner.test.tsx
@@ -18,16 +18,35 @@ import type {
} from "#/types/agent-server/core";
// The restart mutation resolves the launch profile through these services
-// before creating the conversation; stub them so it deterministically takes
-// the legacy agent_settings path (no active agent profile).
+// before creating the conversation; stub them with the seeded `default`.
+vi.mock(
+ "#/hooks/use-migrate-default-agent-profile",
+ async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/use-migrate-default-agent-profile")
+ >()),
+ ensureDefaultAgentProfileMigrated: vi.fn().mockResolvedValue(true),
+ }),
+);
+
vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({
__esModule: true,
default: {
- listProfiles: vi
- .fn()
- .mockResolvedValue({ profiles: [], active_agent_profile_id: null }),
+ listProfiles: vi.fn().mockResolvedValue({
+ profiles: [
+ {
+ id: "profile-default",
+ name: "default",
+ agent_kind: "openhands",
+ revision: 1,
+ llm_profile_ref: "default",
+ mcp_server_refs: null,
+ },
+ ],
+ active_agent_profile_id: "profile-default",
+ }),
+ getProfile: vi.fn().mockRejectedValue(new Error("not needed")),
},
- WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME: "default",
}));
vi.mock("#/api/profiles-service/profiles-service.api", () => ({
__esModule: true,
diff --git a/__tests__/components/features/command-menu/command-menu-items.test.tsx b/__tests__/components/features/command-menu/command-menu-items.test.tsx
index bff3cb1f61..0d10d56651 100644
--- a/__tests__/components/features/command-menu/command-menu-items.test.tsx
+++ b/__tests__/components/features/command-menu/command-menu-items.test.tsx
@@ -48,7 +48,6 @@ describe("the command menu settings group", () => {
"agent-settings",
"llm-settings",
"meta-llm-settings",
- "condenser-settings",
"agent-context-settings",
"verification-settings",
"app-settings",
@@ -62,9 +61,13 @@ describe("the command menu settings group", () => {
(item) => item.to,
);
- // Assert
+ // Assert — Condenser is per agent profile on the default local backend.
expect(routes).toEqual(
- expect.arrayContaining(OSS_NAV_ITEMS.map((navItem) => navItem.to)),
+ expect.arrayContaining(
+ OSS_NAV_ITEMS.map((navItem) => navItem.to).filter(
+ (to) => to !== "/settings/condenser",
+ ),
+ ),
);
});
diff --git a/__tests__/components/features/command-menu/command-menu.test.tsx b/__tests__/components/features/command-menu/command-menu.test.tsx
index c3b555e654..52cd5349b7 100644
--- a/__tests__/components/features/command-menu/command-menu.test.tsx
+++ b/__tests__/components/features/command-menu/command-menu.test.tsx
@@ -476,7 +476,7 @@ describe("CommandMenu", () => {
name: SEARCH_LABEL_KEY,
});
expect(reopenedInput).toHaveValue("");
- expect(screen.getAllByRole("option")).toHaveLength(14);
+ expect(screen.getAllByRole("option")).toHaveLength(13);
expect(screen.getAllByRole("option")[0]).toHaveAttribute(
"aria-selected",
"true",
diff --git a/__tests__/components/features/conversation-panel/local-new-conversation-menu.test.tsx b/__tests__/components/features/conversation-panel/local-new-conversation-menu.test.tsx
index cf7808a61e..80110e8534 100644
--- a/__tests__/components/features/conversation-panel/local-new-conversation-menu.test.tsx
+++ b/__tests__/components/features/conversation-panel/local-new-conversation-menu.test.tsx
@@ -221,10 +221,12 @@ describe("LocalNewConversationMenu", () => {
// Assert
await waitFor(() => {
- expect(createSpy).toHaveBeenCalledWith({
- metadata: null,
- workingDirOverride: "/workspace/project/repo1",
- });
+ expect(createSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: null,
+ workingDirOverride: "/workspace/project/repo1",
+ }),
+ );
});
await waitFor(() => {
expect(navigate).toHaveBeenCalledWith("/conversations/conv-123");
diff --git a/__tests__/components/features/home/home-chat-launcher.test.tsx b/__tests__/components/features/home/home-chat-launcher.test.tsx
index d91bf02e3c..eea877c775 100644
--- a/__tests__/components/features/home/home-chat-launcher.test.tsx
+++ b/__tests__/components/features/home/home-chat-launcher.test.tsx
@@ -871,7 +871,12 @@ describe("HomeChatLauncher", () => {
}),
);
if (marksAutomationSetup) {
- expect(mockMarkAutomationSetupHandoff).toHaveBeenCalledWith("conv-abc");
+ // Marked once the create mutation settles, after the call above.
+ await waitFor(() =>
+ expect(mockMarkAutomationSetupHandoff).toHaveBeenCalledWith(
+ "conv-abc",
+ ),
+ );
} else {
expect(mockMarkAutomationSetupHandoff).not.toHaveBeenCalled();
}
diff --git a/__tests__/components/modals/skills/skill-modal.test.tsx b/__tests__/components/modals/skills/skill-modal.test.tsx
index 3661c71ce5..2a884e786e 100644
--- a/__tests__/components/modals/skills/skill-modal.test.tsx
+++ b/__tests__/components/modals/skills/skill-modal.test.tsx
@@ -6,6 +6,12 @@ import { SkillsModal } from "#/components/features/conversation-panel/skills-mod
import SkillsService from "#/api/skills-service";
import SettingsService from "#/api/settings-service/settings-service.api";
import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";
+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";
+import { useActiveConversation } from "#/hooks/query/use-active-conversation";
+
+vi.mock("#/hooks/query/use-active-conversation", () => ({
+ useActiveConversation: vi.fn(() => ({ data: undefined })),
+}));
describe("SkillsModal", () => {
const mockOnClose = vi.fn();
@@ -71,6 +77,43 @@ describe("SkillsModal", () => {
expect(await screen.findByText(CATALOG_ON)).toBeInTheDocument();
expect(screen.queryByText(CATALOG_OFF)).not.toBeInTheDocument();
});
+
+ it("lists what the conversation's agent profile selects, not the Skills page", async () => {
+ vi.spyOn(SkillsService, "getSkills").mockResolvedValue([
+ catalogSkill(CATALOG_ON),
+ catalogSkill(CATALOG_OFF),
+ ]);
+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue({
+ ...MOCK_DEFAULT_USER_SETTINGS,
+ enabled_skills: [CATALOG_ON],
+ disabled_skills: [],
+ });
+ vi.mocked(useActiveConversation).mockReturnValue({
+ data: { launched_agent_profile: { agent_profile_id: "p-reviewer" } },
+ } as never);
+ vi.spyOn(AgentProfilesService, "listProfiles").mockResolvedValue({
+ profiles: [
+ { id: "p-reviewer", name: "reviewer", agent_kind: "openhands" },
+ ],
+ active_agent_profile_id: null,
+ } as never);
+ vi.spyOn(AgentProfilesService, "getProfile").mockResolvedValue({
+ name: "reviewer",
+ profile: {
+ id: "p-reviewer",
+ name: "reviewer",
+ revision: 1,
+ agent_kind: "openhands",
+ public_skills: [CATALOG_OFF],
+ disabled_skills: [],
+ },
+ } as never);
+
+ renderWithProviders(<SkillsModal {...defaultProps} />);
+
+ expect(await screen.findByText(CATALOG_OFF)).toBeInTheDocument();
+ expect(screen.queryByText(CATALOG_ON)).not.toBeInTheDocument();
+ });
});
describe("Refresh Button Rendering", () => {
diff --git a/__tests__/components/onboarding/setup-llm-step.test.tsx b/__tests__/components/onboarding/setup-llm-step.test.tsx
index d333e13aef..baceec8d67 100644
--- a/__tests__/components/onboarding/setup-llm-step.test.tsx
+++ b/__tests__/components/onboarding/setup-llm-step.test.tsx
@@ -115,9 +115,17 @@ vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({
default: {
listProfiles: listAgentProfiles,
saveProfile: applyAgentProfile,
- getProfile: vi
- .fn()
- .mockResolvedValue({ profile: { id: "onboarding-agent" } }),
+ // The stored `default` already carries the migrated skill selection.
+ getProfile: vi.fn().mockResolvedValue({
+ profile: {
+ id: "onboarding-agent",
+ name: "default",
+ revision: 1,
+ agent_kind: "openhands",
+ llm_profile_ref: "default",
+ public_skills: ["github"],
+ },
+ }),
activateProfile: vi.fn().mockResolvedValue(undefined),
},
}));
@@ -269,6 +277,7 @@ describe("SetupLlmStep", () => {
expect(applyAgentProfile).toHaveBeenCalledWith("default", {
agent_kind: "openhands",
llm_profile_ref: "mock-onboarding-model",
+ public_skills: ["github"],
});
});
@@ -402,6 +411,7 @@ describe("SetupLlmStep", () => {
expect(applyAgentProfile).toHaveBeenCalledWith("default", {
agent_kind: "openhands",
llm_profile_ref: "my-deepseek",
+ public_skills: ["github"],
});
});
@@ -641,6 +651,7 @@ describe("SetupLlmStep", () => {
expect(applyAgentProfile).toHaveBeenLastCalledWith("default", {
agent_kind: "openhands",
llm_profile_ref: "gpt-4o-mini",
+ public_skills: ["github"],
});
});
});
diff --git a/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx b/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx
index 44e9ed7b07..f35d9f2a9b 100644
--- a/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx
+++ b/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx
@@ -1,4 +1,6 @@
+import { DEFAULT_ENABLED_SKILL_NAMES } from "@openhands/extensions/skills";
import { render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, expect, it, vi, beforeEach } from "vitest";
import userEvent from "@testing-library/user-event";
import { useEffect } from "react";
@@ -6,11 +8,13 @@ import type { AgentSettingsSaveControl } from "#/routes/agent-settings";
import { AgentProfilesLocalView } from "#/components/features/settings/agent-profiles/agent-profiles-local-view";
import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
+import { ensureDefaultAgentProfileMigrated } from "#/hooks/use-migrate-default-agent-profile";
// The embedded Agent settings form is stubbed to emit a caller-provided
// control, so the tests exercise the view's mapping to AgentProfileSaveInput.
let emitControl: AgentSettingsSaveControl | null = null;
const ADD_PROFILE_LABEL = "add";
+let editTarget = "my-agent";
const EDIT_PROFILE_LABEL = "edit";
vi.mock("react-i18next", () => ({
@@ -25,10 +29,12 @@ vi.mock("#/routes/agent-settings", () => {
agentSettingsOverride,
onSaveControlChange,
isDefaultProfile,
+ llmPicker,
}: {
agentSettingsOverride?: Record<string, unknown> | null;
onSaveControlChange?: (c: AgentSettingsSaveControl) => void;
isDefaultProfile?: boolean;
+ llmPicker?: React.ReactNode;
}) => {
useEffect(() => {
if (emitControl) onSaveControlChange?.(emitControl);
@@ -40,7 +46,9 @@ vi.mock("#/routes/agent-settings", () => {
data-testid="mock-agent-settings"
data-override={JSON.stringify(agentSettingsOverride)}
data-default-profile={String(Boolean(isDefaultProfile))}
- />
+ >
+ {emitControl?.agentType === "acp" ? null : llmPicker}
+ </div>
);
};
return {
@@ -70,7 +78,7 @@ vi.mock(
<button
type="button"
data-testid="edit-agent-profile"
- onClick={() => onEditProfile?.({ name: "default" })}
+ onClick={() => onEditProfile?.({ name: editTarget })}
aria-label={EDIT_PROFILE_LABEL}
/>
</>
@@ -78,11 +86,6 @@ vi.mock(
}),
);
-vi.mock(
- "#/components/features/settings/agent-profiles/global-tools-notice",
- () => ({ GlobalToolsNotice: () => null }),
-);
-
const saveMutate = vi.fn().mockResolvedValue({ name: "x", message: "ok" });
vi.mock("#/hooks/mutation/use-save-agent-profile", () => ({
useSaveAgentProfile: () => ({ mutateAsync: saveMutate }),
@@ -109,7 +112,11 @@ vi.mock("#/hooks/query/use-llm-profiles", () => ({
useLlmProfiles: () => ({ data: llmProfilesData }),
}));
-let settingsData: { enabled_skills?: string[]; disabled_skills?: string[] };
+let settingsData: {
+ enabled_skills?: string[];
+ disabled_skills?: string[];
+ mcp_config?: Record<string, Record<string, unknown>>;
+};
vi.mock("#/hooks/query/use-settings", () => ({
useSettings: () => ({ data: settingsData }),
}));
@@ -125,6 +132,28 @@ vi.mock("#/api/agent-profiles-service/profile-field-support", () => ({
agentProfileSupportsSkills: () => profileSupportsSkillsMock(),
}));
+const applyToGlobalMock = vi.hoisted(() => vi.fn(async () => undefined));
+vi.mock("#/hooks/mutation/sync-agent-profiles", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/mutation/sync-agent-profiles")
+ >()),
+ applyDefaultAgentProfileToGlobal: applyToGlobalMock,
+}));
+
+vi.mock("#/hooks/use-migrate-default-agent-profile", () => ({
+ ensureDefaultAgentProfileMigrated: vi.fn(),
+}));
+
+function renderView() {
+ return render(<AgentProfilesLocalView />, {
+ wrapper: ({ children }) => (
+ <QueryClientProvider client={new QueryClient()}>
+ {children}
+ </QueryClientProvider>
+ ),
+ });
+}
+
vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({
__esModule: true,
default: { getProfile: vi.fn(), renameProfile: vi.fn() },
@@ -144,6 +173,7 @@ async function openCreateAndName(name: string) {
describe("AgentProfilesLocalView save mapping", () => {
beforeEach(() => {
vi.clearAllMocks();
+ vi.mocked(ensureDefaultAgentProfileMigrated).mockResolvedValue(true);
emitControl = null;
agentProfilesData = { profiles: [], active_agent_profile_id: null };
llmProfilesData = {
@@ -151,13 +181,14 @@ describe("AgentProfilesLocalView save mapping", () => {
active_profile: "default",
};
settingsData = {};
+ editTarget = "my-agent";
profileSupportsSkillsMock.mockReturnValue(true);
});
- it("opens a new profile on the skills selected on the Skills page", async () => {
+ it("opens a new profile on the settings lists when there is no OpenHands default", async () => {
settingsData = { enabled_skills: ["add-skill"], disabled_skills: ["mine"] };
- render(<AgentProfilesLocalView />);
+ renderView();
await openCreateAndName("my-agent");
const override = JSON.parse(
@@ -176,7 +207,7 @@ describe("AgentProfilesLocalView save mapping", () => {
profileSupportsSkillsMock.mockReturnValue(false);
settingsData = { enabled_skills: ["add-skill"], disabled_skills: ["mine"] };
- render(<AgentProfilesLocalView />);
+ renderView();
await openCreateAndName("my-agent");
expect(
@@ -188,8 +219,137 @@ describe("AgentProfilesLocalView save mapping", () => {
).toEqual({ agent_kind: "openhands" });
});
+ it("starts a new profile from default, skills included, with every server and secret", async () => {
+ settingsData = { enabled_skills: ["add-skill"], disabled_skills: [] };
+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
+ name: "default",
+ profile: {
+ id: "p-default",
+ name: "default",
+ revision: 4,
+ agent_kind: "openhands",
+ llm_profile_ref: "other-llm",
+ tools: [{ name: "terminal", params: {} }],
+ tool_concurrency_limit: 3,
+ system_message_suffix: "Be terse.",
+ condenser: { kind: "NoOpCondenserSettings" },
+ verification: { critic_enabled: true },
+ enable_classify_and_switch_llm_tool: true,
+ meta_profile_ref: "fast-router",
+ mcp_server_refs: ["github"],
+ secret_refs: ["GITHUB_TOKEN"],
+ public_skills: ["only-in-default"],
+ disabled_skills: ["off-in-default"],
+ },
+ } as never);
+ emitControl = {
+ agentType: "openhands",
+ isValid: true,
+ isDirty: true,
+ buildAgentProfileFields: () => ({
+ agent_kind: "openhands",
+ mcp_server_refs: null,
+ public_skills: ["only-in-default"],
+ disabled_skills: ["off-in-default"],
+ }),
+ credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
+ };
+
+ renderView();
+ const user = await openCreateAndName("my-agent");
+
+ expect(AgentProfilesService.getProfile).toHaveBeenCalledWith("default");
+ const override = JSON.parse(
+ screen
+ .getByTestId("mock-agent-settings")
+ .getAttribute("data-override") as string,
+ );
+ expect(override).toMatchObject({
+ agent_kind: "openhands",
+ tools: [{ name: "terminal", params: {} }],
+ tool_concurrency_limit: 3,
+ system_message_suffix: "Be terse.",
+ condenser: { kind: "NoOpCondenserSettings" },
+ verification: { critic_enabled: true },
+ enable_classify_and_switch_llm_tool: true,
+ meta_profile_ref: "fast-router",
+ mcp_server_refs: null,
+ secret_refs: null,
+ public_skills: ["only-in-default"],
+ disabled_skills: ["off-in-default"],
+ });
+
+ await user.click(screen.getByTestId("save-agent-profile-btn"));
+ await waitFor(() => expect(saveMutate).toHaveBeenCalledTimes(1));
+ const { profile } = saveMutate.mock.calls[0][0];
+ expect(profile).toEqual({
+ agent_kind: "openhands",
+ llm_profile_ref: "default",
+ tools: [{ name: "terminal", params: {} }],
+ tool_concurrency_limit: 3,
+ system_message_suffix: "Be terse.",
+ condenser: { kind: "NoOpCondenserSettings" },
+ verification: { critic_enabled: true },
+ enable_classify_and_switch_llm_tool: true,
+ meta_profile_ref: "fast-router",
+ mcp_server_refs: null,
+ public_skills: ["only-in-default"],
+ disabled_skills: ["off-in-default"],
+ });
+ });
+
+ it("starts a new profile without default's settings when default is an ACP agent", async () => {
+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
+ name: "default",
+ profile: {
+ id: "p-default",
+ name: "default",
+ revision: 1,
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ },
+ } as never);
+
+ renderView();
+ await openCreateAndName("my-agent");
+
+ expect(
+ JSON.parse(
+ screen
+ .getByTestId("mock-agent-settings")
+ .getAttribute("data-override") as string,
+ ),
+ ).toEqual({
+ agent_kind: "openhands",
+ public_skills: [...DEFAULT_ENABLED_SKILL_NAMES],
+ disabled_skills: [],
+ });
+ });
+
+ it("waits for typing before calling a new profile's empty name invalid", async () => {
+ renderView();
+ const user = await openCreateAndName("x");
+ const input = screen.getByTestId("agent-profile-name-input");
+ await user.clear(input);
+
+ expect(input).toHaveAttribute("aria-invalid", "true");
+ });
+
+ it("starts a new profile without flagging its empty name", async () => {
+ renderView();
+ const user = userEvent.setup();
+ await user.click(screen.getByTestId("add-agent-profile"));
+ await screen.findByTestId("mock-agent-settings");
+
+ expect(screen.getByTestId("agent-profile-name-input")).toHaveAttribute(
+ "aria-invalid",
+ "false",
+ );
+ expect(screen.getByTestId("save-agent-profile-btn")).toBeDisabled();
+ });
+
it("describes the add editor with agent copy, not the LLM-profile hint", async () => {
- render(<AgentProfilesLocalView />);
+ renderView();
await openCreateAndName("my-agent");
expect(
@@ -209,7 +369,7 @@ describe("AgentProfilesLocalView save mapping", () => {
credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
};
- render(<AgentProfilesLocalView />);
+ renderView();
const user = await openCreateAndName("my-oh");
await user.click(screen.getByTestId("save-agent-profile-btn"));
@@ -220,6 +380,7 @@ describe("AgentProfilesLocalView save mapping", () => {
agent_kind: "openhands",
mcp_server_refs: null,
llm_profile_ref: "default",
+ public_skills: [...DEFAULT_ENABLED_SKILL_NAMES],
},
});
});
@@ -240,7 +401,7 @@ describe("AgentProfilesLocalView save mapping", () => {
credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
};
- render(<AgentProfilesLocalView />);
+ renderView();
const user = await openCreateAndName("my-claude");
await user.click(screen.getByTestId("save-agent-profile-btn"));
@@ -265,7 +426,7 @@ describe("AgentProfilesLocalView save mapping", () => {
const storedProfile = {
schema_version: 1,
id: "p-1",
- name: "default",
+ name: "my-agent",
revision: 3,
agent_kind: "openhands",
llm_profile_ref: "default",
@@ -281,7 +442,7 @@ describe("AgentProfilesLocalView save mapping", () => {
meta_profile_ref: "fast-router",
};
vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
- name: "default",
+ name: "my-agent",
profile: storedProfile,
} as never);
emitControl = {
@@ -298,7 +459,7 @@ describe("AgentProfilesLocalView save mapping", () => {
credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
};
- render(<AgentProfilesLocalView />);
+ renderView();
const user = userEvent.setup();
await user.click(screen.getByTestId("edit-agent-profile"));
await screen.findByTestId("mock-agent-settings");
@@ -332,7 +493,7 @@ describe("AgentProfilesLocalView save mapping", () => {
// Profiles are secret-free now (no embedded skills), so exposeSecrets is a
// server-side no-op; canvas still passes "encrypted" for signature parity.
expect(AgentProfilesService.getProfile).toHaveBeenCalledWith(
- "default",
+ "my-agent",
"encrypted",
);
const { profile } = saveMutate.mock.calls[0][0];
@@ -352,15 +513,231 @@ describe("AgentProfilesLocalView save mapping", () => {
expect(profile).not.toHaveProperty("id");
expect(profile).not.toHaveProperty("name");
expect(profile).not.toHaveProperty("revision");
+ expect(applyToGlobalMock).not.toHaveBeenCalled();
+ });
+
+ describe("the default profile", () => {
+ const OPTIONAL = "add-javadoc";
+ const storedDefault = {
+ id: "p-default",
+ name: "default",
+ revision: 2,
+ agent_kind: "openhands",
+ llm_profile_ref: "stale",
+ mcp_server_refs: ["github"],
+ secret_refs: ["GITHUB_TOKEN"],
+ public_skills: ["github"],
+ disabled_skills: [],
+ };
+
+ beforeEach(() => {
+ editTarget = "default";
+ llmProfilesData = {
+ profiles: [
+ { name: "stale", model: "gpt-4" },
+ { name: "fast", model: "gpt-5" },
+ ],
+ active_profile: "fast",
+ };
+ settingsData = {
+ enabled_skills: [OPTIONAL],
+ disabled_skills: ["mine"],
+ mcp_config: {
+ github: { transport: "http", url: "https://github.example/mcp" },
+ slack: { transport: "stdio", command: "npx", enabled: false },
+ },
+ };
+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
+ name: "default",
+ profile: storedDefault,
+ } as never);
+ emitControl = {
+ agentType: "openhands",
+ isValid: true,
+ isDirty: true,
+ buildAgentProfileFields: () => ({
+ agent_kind: "openhands",
+ mcp_server_refs: ["slack"],
+ secret_refs: null,
+ public_skills: [OPTIONAL],
+ disabled_skills: [],
+ }),
+ credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
+ };
+ });
+
+ it("opens on the MCP servers switched on, every secret, and its own skills", async () => {
+ renderView();
+ const user = userEvent.setup();
+ await user.click(screen.getByTestId("edit-agent-profile"));
+ const form = await screen.findByTestId("mock-agent-settings");
+
+ expect(form).toHaveAttribute("data-default-profile", "true");
+ expect(
+ JSON.parse(form.getAttribute("data-override") as string),
+ ).toMatchObject({
+ mcp_server_refs: ["github"],
+ secret_refs: null,
+ public_skills: ["github"],
+ disabled_skills: [],
+ });
+ expect(
+ screen.getByTestId("agent-profile-llm-default-note"),
+ ).toBeInTheDocument();
+ });
+
+ it("writes its edits to the global pages and stores every server and secret", async () => {
+ renderView();
+ const user = userEvent.setup();
+ await user.click(screen.getByTestId("edit-agent-profile"));
+ await screen.findByTestId("mock-agent-settings");
+ await user.click(screen.getByTestId("save-agent-profile-btn"));
+
+ await waitFor(() => expect(saveMutate).toHaveBeenCalledTimes(1));
+ expect(applyToGlobalMock).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ llm_profile_ref: "fast",
+ mcp_server_refs: ["slack"],
+ public_skills: [OPTIONAL],
+ }),
+ );
+ const { name, profile } = saveMutate.mock.calls[0][0];
+ expect(name).toBe("default");
+ expect(profile).toMatchObject({
+ llm_profile_ref: "fast",
+ mcp_server_refs: null,
+ secret_refs: null,
+ });
+ // The profile saves first, so a rejected save changes no global page.
+ expect(saveMutate.mock.invocationCallOrder[0]).toBeLessThan(
+ applyToGlobalMock.mock.invocationCallOrder[0],
+ );
+ });
+
+ it("changes no global page when the profile save fails", async () => {
+ saveMutate.mockRejectedValueOnce(new Error("conflict"));
+ renderView();
+ const user = userEvent.setup();
+ await user.click(screen.getByTestId("edit-agent-profile"));
+ await screen.findByTestId("mock-agent-settings");
+ await user.click(screen.getByTestId("save-agent-profile-btn"));
+
+ await waitFor(() => expect(displayErrorToast).toHaveBeenCalled());
+ expect(applyToGlobalMock).not.toHaveBeenCalled();
+ });
+
+ it("treats an ACP default switched to OpenHands as the shared default", async () => {
+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
+ name: "default",
+ profile: {
+ ...storedDefault,
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ acp_command: "claude",
+ },
+ } as never);
+ emitControl = {
+ agentType: "openhands",
+ isValid: true,
+ isDirty: true,
+ buildAgentProfileFields: () => ({
+ agent_kind: "openhands",
+ mcp_server_refs: ["github"],
+ secret_refs: ["GITHUB_TOKEN"],
+ }),
+ credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
+ };
+
+ renderView();
+ const user = userEvent.setup();
+ await user.click(screen.getByTestId("edit-agent-profile"));
+ const form = await screen.findByTestId("mock-agent-settings");
+
+ expect(form).toHaveAttribute("data-default-profile", "true");
+ expect(
+ screen.getByTestId("agent-profile-llm-default-note"),
+ ).toBeInTheDocument();
+ await user.click(screen.getByTestId("save-agent-profile-btn"));
+ await waitFor(() => expect(applyToGlobalMock).toHaveBeenCalled());
+ expect(saveMutate.mock.calls[0][0].profile).toMatchObject({
+ agent_kind: "openhands",
+ llm_profile_ref: "fast",
+ mcp_server_refs: null,
+ secret_refs: null,
+ });
+ });
+
+ it("leaves an ACP default's own servers and secrets alone", async () => {
+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
+ name: "default",
+ profile: {
+ ...storedDefault,
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ acp_command: "claude",
+ },
+ } as never);
+ emitControl = {
+ agentType: "acp",
+ isValid: true,
+ isDirty: true,
+ buildAgentProfileFields: () => ({
+ agent_kind: "acp",
+ mcp_server_refs: ["github"],
+ secret_refs: ["GITHUB_TOKEN"],
+ acp_server: "claude-code",
+ acp_model: null,
+ acp_command: "claude",
+ acp_args: null,
+ }),
+ credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
+ };
+
+ renderView();
+ const user = userEvent.setup();
+ await user.click(screen.getByTestId("edit-agent-profile"));
+ const form = await screen.findByTestId("mock-agent-settings");
+
+ // The editor hides the shared controls only for an OpenHands agent.
+ expect(form).toHaveAttribute("data-default-profile", "true");
+ expect(
+ JSON.parse(form.getAttribute("data-override") as string),
+ ).toMatchObject({
+ mcp_server_refs: ["github"],
+ secret_refs: ["GITHUB_TOKEN"],
+ });
+ expect(
+ screen.queryByTestId("agent-profile-llm-default-note"),
+ ).not.toBeInTheDocument();
+ await user.click(screen.getByTestId("save-agent-profile-btn"));
+ await waitFor(() => expect(saveMutate).toHaveBeenCalledTimes(1));
+ expect(applyToGlobalMock).not.toHaveBeenCalled();
+ expect(saveMutate.mock.calls[0][0].profile).toMatchObject({
+ secret_refs: ["GITHUB_TOKEN"],
+ });
+ });
+
+ it("locks default's name, which the server would otherwise reseed", async () => {
+ renderView();
+ const user = userEvent.setup();
+ await user.click(screen.getByTestId("edit-agent-profile"));
+ await screen.findByTestId("mock-agent-settings");
+
+ expect(screen.getByTestId("agent-profile-name-input")).toBeDisabled();
+ expect(
+ screen.getByTestId("agent-profile-default-locked-note"),
+ ).toHaveTextContent("SETTINGS$AGENT_PROFILE_DEFAULT_LOCKED");
+ });
});
it("seeds tools from a stored profile", async () => {
vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
- name: "default",
+ name: "my-agent",
profile: {
schema_version: 3,
id: "p-1",
- name: "default",
+ name: "my-agent",
revision: 3,
agent_kind: "openhands",
llm_profile_ref: "default",
@@ -378,7 +755,7 @@ describe("AgentProfilesLocalView save mapping", () => {
credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
};
- render(<AgentProfilesLocalView />);
+ renderView();
const user = userEvent.setup();
await user.click(screen.getByTestId("edit-agent-profile"));
await screen.findByTestId("mock-agent-settings");
@@ -395,11 +772,11 @@ describe("AgentProfilesLocalView save mapping", () => {
it("seeds the editor with a stored secret scope", async () => {
vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
- name: "default",
+ name: "my-agent",
profile: {
schema_version: 2,
id: "p-1",
- name: "default",
+ name: "my-agent",
revision: 3,
agent_kind: "openhands",
llm_profile_ref: "default",
@@ -417,7 +794,7 @@ describe("AgentProfilesLocalView save mapping", () => {
credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
};
- render(<AgentProfilesLocalView />);
+ renderView();
const user = userEvent.setup();
await user.click(screen.getByTestId("edit-agent-profile"));
await screen.findByTestId("mock-agent-settings");
@@ -428,20 +805,15 @@ describe("AgentProfilesLocalView save mapping", () => {
.getAttribute("data-override") as string,
);
expect(seededOverride.secret_refs).toEqual(["DATADOG_API_KEY"]);
- expect(
- screen
- .getByTestId("mock-agent-settings")
- .getAttribute("data-default-profile"),
- ).toBe("true");
});
it("seeds the editor with a stored persona and instructions", async () => {
vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
- name: "default",
+ name: "my-agent",
profile: {
schema_version: 2,
id: "p-1",
- name: "default",
+ name: "my-agent",
revision: 3,
agent_kind: "openhands",
llm_profile_ref: "default",
@@ -460,7 +832,7 @@ describe("AgentProfilesLocalView save mapping", () => {
credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
};
- render(<AgentProfilesLocalView />);
+ renderView();
const user = userEvent.setup();
await user.click(screen.getByTestId("edit-agent-profile"));
await screen.findByTestId("mock-agent-settings");
@@ -474,25 +846,13 @@ describe("AgentProfilesLocalView save mapping", () => {
expect(seededOverride.system_message_suffix).toBe("Be terse.");
});
- it("does not flag a named profile as the default", async () => {
- emitControl = null;
- render(<AgentProfilesLocalView />);
- await openCreateAndName("triage");
-
- expect(
- screen
- .getByTestId("mock-agent-settings")
- .getAttribute("data-default-profile"),
- ).toBe("false");
- });
-
it("edit-save persists an edited secret scope over the stored value", async () => {
vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
- name: "default",
+ name: "my-agent",
profile: {
schema_version: 2,
id: "p-1",
- name: "default",
+ name: "my-agent",
revision: 3,
agent_kind: "openhands",
llm_profile_ref: "default",
@@ -511,7 +871,7 @@ describe("AgentProfilesLocalView save mapping", () => {
credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
};
- render(<AgentProfilesLocalView />);
+ renderView();
const user = userEvent.setup();
await user.click(screen.getByTestId("edit-agent-profile"));
await screen.findByTestId("mock-agent-settings");
@@ -524,11 +884,11 @@ describe("AgentProfilesLocalView save mapping", () => {
it("kind-switch edit-save sends a clean variant payload", async () => {
vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
- name: "default",
+ name: "my-agent",
profile: {
schema_version: 1,
id: "p-1",
- name: "default",
+ name: "my-agent",
revision: 3,
agent_kind: "openhands",
llm_profile_ref: "default",
@@ -551,7 +911,7 @@ describe("AgentProfilesLocalView save mapping", () => {
credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
};
- render(<AgentProfilesLocalView />);
+ renderView();
const user = userEvent.setup();
await user.click(screen.getByTestId("edit-agent-profile"));
await screen.findByTestId("mock-agent-settings");
@@ -561,7 +921,7 @@ describe("AgentProfilesLocalView save mapping", () => {
// No stored openhands fields may leak into the acp payload — the server's
// extra="forbid" union would 422 on a mongrel profile.
expect(saveMutate).toHaveBeenCalledWith({
- name: "default",
+ name: "my-agent",
profile: {
agent_kind: "acp",
mcp_server_refs: null,
@@ -578,11 +938,11 @@ describe("AgentProfilesLocalView save mapping", () => {
// the editor must validate against the live list and self-heal to the
// active default rather than saving the stale ref straight back.
vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
- name: "default",
+ name: "my-agent",
profile: {
schema_version: 1,
id: "p-1",
- name: "default",
+ name: "my-agent",
revision: 3,
agent_kind: "openhands",
llm_profile_ref: "deleted-profile",
@@ -599,7 +959,7 @@ describe("AgentProfilesLocalView save mapping", () => {
credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
};
- render(<AgentProfilesLocalView />);
+ renderView();
const user = userEvent.setup();
await user.click(screen.getByTestId("edit-agent-profile"));
await screen.findByTestId("mock-agent-settings");
@@ -636,7 +996,7 @@ describe("AgentProfilesLocalView save mapping", () => {
credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
};
- render(<AgentProfilesLocalView />);
+ renderView();
const user = userEvent.setup();
await user.click(screen.getByTestId("edit-agent-profile"));
await screen.findByTestId("mock-agent-settings");
@@ -656,7 +1016,7 @@ describe("AgentProfilesLocalView save mapping", () => {
credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },
};
- render(<AgentProfilesLocalView />);
+ renderView();
const user = await openCreateAndName("my-oh");
await user.click(screen.getByTestId("save-agent-profile-btn"));
@@ -668,10 +1028,42 @@ describe("AgentProfilesLocalView save mapping", () => {
expect(saveMutate).not.toHaveBeenCalled();
});
+ it("reads a profile to edit only after the default migration", async () => {
+ let finishMigration: (value: true) => void = () => {};
+ vi.mocked(ensureDefaultAgentProfileMigrated).mockReturnValue(
+ new Promise((resolve) => {
+ finishMigration = resolve;
+ }),
+ );
+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
+ name: "my-agent",
+ profile: {
+ id: "p-1",
+ name: "my-agent",
+ revision: 1,
+ agent_kind: "openhands",
+ llm_profile_ref: "default",
+ },
+ } as never);
+
+ renderView();
+ const user = userEvent.setup();
+ await user.click(screen.getByTestId("edit-agent-profile"));
+
+ expect(ensureDefaultAgentProfileMigrated).toHaveBeenCalled();
+ expect(AgentProfilesService.getProfile).not.toHaveBeenCalled();
+ finishMigration(true);
+ await screen.findByTestId("mock-agent-settings");
+ expect(AgentProfilesService.getProfile).toHaveBeenCalledWith(
+ "my-agent",
+ "encrypted",
+ );
+ });
+
describe("duplicate profile name", () => {
beforeEach(() => {
agentProfilesData = {
- profiles: [{ name: "default" }, { name: "triage" }],
+ profiles: [{ name: "my-agent" }, { name: "triage" }],
active_agent_profile_id: null,
};
emitControl = {
@@ -687,8 +1079,8 @@ describe("AgentProfilesLocalView save mapping", () => {
});
it("tells the user a new profile's name is taken until it is unique", async () => {
- render(<AgentProfilesLocalView />);
- const user = await openCreateAndName("default");
+ renderView();
+ const user = await openCreateAndName("my-agent");
const input = screen.getByTestId("agent-profile-name-input");
expect(input).toHaveAttribute("aria-invalid", "true");
@@ -709,24 +1101,24 @@ describe("AgentProfilesLocalView save mapping", () => {
it("flags a rename to another profile's name but not the profile's own name", async () => {
vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
- name: "default",
+ name: "my-agent",
profile: {
schema_version: 3,
id: "p-1",
- name: "default",
+ name: "my-agent",
revision: 1,
agent_kind: "openhands",
llm_profile_ref: "default",
},
} as never);
- render(<AgentProfilesLocalView />);
+ renderView();
const user = userEvent.setup();
await user.click(screen.getByTestId("edit-agent-profile"));
await screen.findByTestId("mock-agent-settings");
const input = screen.getByTestId("agent-profile-name-input");
- expect(input).toHaveValue("default");
+ expect(input).toHaveValue("my-agent");
expect(input).toHaveAttribute("aria-invalid", "false");
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
diff --git a/__tests__/components/settings/agent-profiles/agent-profiles-manager.test.tsx b/__tests__/components/settings/agent-profiles/agent-profiles-manager.test.tsx
index 9be86e4a37..87884ed349 100644
--- a/__tests__/components/settings/agent-profiles/agent-profiles-manager.test.tsx
+++ b/__tests__/components/settings/agent-profiles/agent-profiles-manager.test.tsx
@@ -127,7 +127,25 @@ describe("AgentProfilesManager", () => {
renderManager();
const badge = await screen.findByTestId("agent-profile-active-badge");
- expect(badge).toHaveTextContent("Default");
+ expect(badge).toHaveTextContent("Active");
+ });
+
+ it("keeps the default profile from being deleted", async () => {
+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({
+ profiles: [{ ...mockProfiles[0], id: "id-default", name: "default" }],
+ active_agent_profile_id: "id-default",
+ });
+
+ renderManager();
+ const user = userEvent.setup();
+ await user.click(await screen.findByTestId("agent-profile-menu-trigger"));
+
+ const remove = screen.getByTestId("agent-profile-delete");
+ expect(remove).toBeDisabled();
+ expect(remove).toHaveAttribute(
+ "title",
+ "SETTINGS$AGENT_PROFILE_DEFAULT_LOCKED",
+ );
});
it("shows the Add button and fires onAddProfile", async () => {
diff --git a/__tests__/components/settings/agent-profiles/global-tools-notice.test.tsx b/__tests__/components/settings/agent-profiles/global-tools-notice.test.tsx
deleted file mode 100644
index 7fa87721e1..0000000000
--- a/__tests__/components/settings/agent-profiles/global-tools-notice.test.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { GlobalToolsNotice } from "#/components/features/settings/agent-profiles/global-tools-notice";
-
-vi.mock("react-i18next", () => ({
- useTranslation: () => ({
- t: (key: string, options?: { names?: string }) =>
- options?.names ? `${key}:${options.names}` : key,
- }),
-}));
-
-let agentSettings: Record<string, unknown> | undefined;
-vi.mock("#/hooks/query/use-settings", () => ({
- useSettings: () => ({ data: { agent_settings: agentSettings } }),
-}));
-
-const saveSettings = vi.fn();
-vi.mock("#/hooks/mutation/use-save-settings", () => ({
- useSaveSettings: () => ({ mutate: saveSettings, isPending: false }),
-}));
-
-vi.mock("#/utils/custom-toast-handlers");
-
-describe("GlobalToolsNotice", () => {
- beforeEach(() => {
- saveSettings.mockReset();
- });
-
- it.each([
- ["unset", { agent_kind: "openhands" }],
- ["null", { agent_kind: "openhands", tools: null }],
- ["an ACP agent", { agent_kind: "acp", tools: [{ name: "terminal" }] }],
- ])("stays hidden when global tools are %s", (_label, settings) => {
- agentSettings = settings;
- render(<GlobalToolsNotice />);
- expect(screen.queryByTestId("global-tools-notice")).toBeNull();
- });
-
- it("lists a custom global tool list and resets it to the standard set", async () => {
- agentSettings = {
- agent_kind: "openhands",
- tools: [
- { name: "terminal", params: {} },
- { name: "task_tool_set", params: {} },
- ],
- };
- render(<GlobalToolsNotice />);
-
- expect(screen.getByTestId("global-tools-notice")).toHaveTextContent(
- "terminal, task_tool_set",
- );
- await userEvent.setup().click(screen.getByTestId("global-tools-reset"));
-
- expect(saveSettings).toHaveBeenCalledWith(
- { agent_settings_diff: { tools: null } },
- expect.any(Object),
- );
- });
-
- it("shows an explicitly bare global tool list", () => {
- agentSettings = { agent_kind: "openhands", tools: [] };
- render(<GlobalToolsNotice />);
- expect(screen.getByTestId("global-tools-notice")).toBeInTheDocument();
- });
-});
diff --git a/__tests__/components/settings/agent-profiles/merge-agent-profile-save-input.test.ts b/__tests__/components/settings/agent-profiles/merge-agent-profile-save-input.test.ts
index da0a57a4e9..42d7550b3f 100644
--- a/__tests__/components/settings/agent-profiles/merge-agent-profile-save-input.test.ts
+++ b/__tests__/components/settings/agent-profiles/merge-agent-profile-save-input.test.ts
@@ -1,3 +1,4 @@
+import { DEFAULT_ENABLED_SKILL_NAMES } from "@openhands/extensions/skills";
import { describe, expect, it } from "vitest";
import type {
AgentProfile,
@@ -124,13 +125,54 @@ describe("mergeAgentProfileSaveInput", () => {
expect(mergeAgentProfileSaveInput(storedOpenHands, edited)).toEqual(edited);
});
- it("passes the edited fields through on create (no stored profile)", () => {
+ it("starts a new OpenHands profile on the recommended catalog skills", () => {
const edited: AgentProfileSaveInput = {
agent_kind: "openhands",
llm_profile_ref: "default",
};
- expect(mergeAgentProfileSaveInput(null, edited)).toEqual(edited);
+ expect(mergeAgentProfileSaveInput(null, edited)).toEqual({
+ ...edited,
+ public_skills: [...DEFAULT_ENABLED_SKILL_NAMES],
+ });
+ });
+
+ it("gives a profile switched to OpenHands the recommended catalog skills", () => {
+ const storedAcp = {
+ id: "p-2",
+ name: "agent",
+ revision: 1,
+ agent_kind: "acp",
+ acp_server: "codex",
+ } as unknown as AgentProfile;
+
+ expect(
+ mergeAgentProfileSaveInput(storedAcp, {
+ agent_kind: "openhands",
+ llm_profile_ref: "default",
+ }),
+ ).toMatchObject({ public_skills: [...DEFAULT_ENABLED_SKILL_NAMES] });
+ });
+
+ it("keeps a stored or explicit skill selection", () => {
+ const stored = {
+ ...storedOpenHands,
+ public_skills: ["github"],
+ } as unknown as AgentProfile;
+
+ expect(
+ mergeAgentProfileSaveInput(stored, {
+ agent_kind: "openhands",
+ llm_profile_ref: "x",
+ }),
+ ).toMatchObject({ public_skills: ["github"] });
+ expect(
+ mergeAgentProfileSaveInput(null, {
+ agent_kind: "openhands",
+ llm_profile_ref: "x",
+ public_skills: [],
+ } as AgentProfileSaveInput),
+ ).toMatchObject({ public_skills: [] });
});
});
diff --git a/__tests__/components/settings/meta-llm-profiles/meta-llm-settings-view.test.tsx b/__tests__/components/settings/meta-llm-profiles/meta-llm-settings-view.test.tsx
index 5b8f9dafc1..af446b784b 100644
--- a/__tests__/components/settings/meta-llm-profiles/meta-llm-settings-view.test.tsx
+++ b/__tests__/components/settings/meta-llm-profiles/meta-llm-settings-view.test.tsx
@@ -40,6 +40,10 @@ vi.mock("#/utils/custom-toast-handlers", () => ({
displayErrorToast: vi.fn(),
displaySuccessToast: vi.fn(),
}));
+const routerPerProfileMock = vi.hoisted(() => vi.fn(() => false));
+vi.mock("#/api/agent-profiles-service/profile-field-support", () => ({
+ agentProfileSupportsRouter: () => routerPerProfileMock(),
+}));
const mockMetaProfiles = [
{
@@ -97,6 +101,7 @@ describe("MetaLlmSettingsView", () => {
beforeEach(() => {
vi.clearAllMocks();
+ routerPerProfileMock.mockReturnValue(false);
vi.mocked(useMetaProfilesHook.useMetaProfiles).mockReturnValue({
data: {
@@ -436,7 +441,10 @@ describe("MetaLlmSettingsView", () => {
const user = userEvent.setup();
// A router already exists (and is active), so this is not a 0 → 1 create.
vi.mocked(useMetaProfilesHook.useMetaProfiles).mockReturnValue({
- data: { meta_profiles: mockMetaProfiles, active_meta_profile: "balanced" },
+ data: {
+ meta_profiles: mockMetaProfiles,
+ active_meta_profile: "balanced",
+ },
isLoading: false,
error: null,
} as unknown as ReturnType<typeof useMetaProfilesHook.useMetaProfiles>);
@@ -701,4 +709,68 @@ describe("MetaLlmSettingsView", () => {
screen.getByTestId("meta-profile-run-at-conversation-start-switch"),
).toBeChecked();
});
+
+ describe("when each agent profile picks its router", () => {
+ beforeEach(() => {
+ routerPerProfileMock.mockReturnValue(true);
+ });
+
+ it("lists routers without an active one or a Set active action", async () => {
+ const user = userEvent.setup();
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ expect(
+ screen.queryByTestId("meta-profile-active-badge"),
+ ).not.toBeInTheDocument();
+ await user.click(
+ screen.getByTestId("meta-profile-menu-trigger-balanced"),
+ );
+ expect(screen.getByTestId("meta-profile-edit")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("meta-profile-set-active"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByTestId("meta-profile-delete")).toBeInTheDocument();
+ });
+
+ it("does not activate the first router after creating it", async () => {
+ const user = userEvent.setup();
+ vi.mocked(useMetaProfilesHook.useMetaProfiles).mockReturnValue({
+ data: { meta_profiles: [], active_meta_profile: null },
+ isLoading: false,
+ error: null,
+ } as unknown as ReturnType<typeof useMetaProfilesHook.useMetaProfiles>);
+ saveMutateAsync.mockResolvedValue({ name: "pareto" });
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ await openRouterProTemplate(user);
+ await user.clear(screen.getByTestId("meta-profile-name-input"));
+ await user.type(screen.getByTestId("meta-profile-name-input"), "pareto");
+ fireEvent.change(screen.getByTestId("meta-profile-model-table"), {
+ target: { value: "" },
+ });
+ await user.click(screen.getByTestId("meta-profile-save"));
+
+ await waitFor(() => expect(saveMutateAsync).toHaveBeenCalled());
+ expect(activateMutateAsync).not.toHaveBeenCalled();
+ });
+
+ it("enables Run on first message once any router exists", () => {
+ vi.mocked(useMetaProfilesHook.useMetaProfiles).mockReturnValue({
+ data: { meta_profiles: mockMetaProfiles, active_meta_profile: null },
+ isLoading: false,
+ error: null,
+ } as unknown as ReturnType<typeof useMetaProfilesHook.useMetaProfiles>);
+
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ expect(
+ screen.getByTestId("meta-profile-run-at-conversation-start-switch"),
+ ).not.toBeDisabled();
+ expect(
+ screen.getByText(
+ "SETTINGS$META_PROFILE_RUN_AT_CONVERSATION_START_HELP_PROFILE",
+ ),
+ ).toBeInTheDocument();
+ });
+ });
});
diff --git a/__tests__/hooks/mutation/resolve-conversation-launch.test.ts b/__tests__/hooks/mutation/resolve-conversation-launch.test.ts
index b10684e9d3..3c1a89cebb 100644
--- a/__tests__/hooks/mutation/resolve-conversation-launch.test.ts
+++ b/__tests__/hooks/mutation/resolve-conversation-launch.test.ts
@@ -1,29 +1,47 @@
import { QueryClient } from "@tanstack/react-query";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { resolveConversationLaunch } from "#/hooks/mutation/resolve-conversation-launch";
+import {
+ launchConversation,
+ resolveConversationLaunch,
+} from "#/hooks/mutation/resolve-conversation-launch";
+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import { SUBSCRIPTION_LOGIN_REQUIRED_ERROR } from "#/api/agent-server-adapter";
-const { listAgentProfiles, listLlmProfiles, supportsOverride } = vi.hoisted(
- () => ({
- listAgentProfiles: vi.fn(),
- listLlmProfiles: vi.fn(),
- supportsOverride: vi.fn(),
- }),
-);
+const {
+ listAgentProfiles,
+ getAgentProfile,
+ listLlmProfiles,
+ getLlmProfile,
+ getOpenAIStatus,
+ migrate,
+} = vi.hoisted(() => ({
+ listAgentProfiles: vi.fn(),
+ getAgentProfile: vi.fn(),
+ listLlmProfiles: vi.fn(),
+ getLlmProfile: vi.fn(),
+ getOpenAIStatus: vi.fn(),
+ migrate: vi.fn(),
+}));
+
+vi.mock("#/hooks/use-migrate-default-agent-profile", () => ({
+ ensureDefaultAgentProfileMigrated: migrate,
+}));
vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({
__esModule: true,
- default: { listProfiles: listAgentProfiles, getProfile: vi.fn() },
+ default: { listProfiles: listAgentProfiles, getProfile: getAgentProfile },
WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME: "default",
}));
vi.mock("#/api/profiles-service/profiles-service.api", () => ({
__esModule: true,
- default: { listProfiles: listLlmProfiles },
+ default: { listProfiles: listLlmProfiles, getProfile: getLlmProfile },
}));
-vi.mock("#/api/agent-server-adapter", () => ({
- backendSupportsLaunchLlmOverride: supportsOverride,
+vi.mock("#/api/llm-subscription-service", () => ({
+ __esModule: true,
+ default: { getOpenAIStatus },
}));
-const PARENT_PROFILE = {
+const REVIEWER = {
id: "profile-1",
name: "reviewer",
agent_kind: "openhands",
@@ -31,56 +49,276 @@ const PARENT_PROFILE = {
llm_profile_ref: "slow",
mcp_server_refs: null,
};
+const DEFAULT = {
+ id: "profile-default",
+ name: "default",
+ agent_kind: "openhands",
+ revision: 1,
+ llm_profile_ref: "slow",
+ mcp_server_refs: null,
+};
+const CLAUDE = {
+ id: "profile-2",
+ name: "claude",
+ agent_kind: "acp",
+ revision: 1,
+ llm_profile_ref: null,
+ mcp_server_refs: null,
+};
+
+function arrange({
+ activeId = null as string | null,
+ activeLlm = "slow" as string | null,
+ detail = {} as Record<string, unknown>,
+} = {}) {
+ listAgentProfiles.mockResolvedValue({
+ profiles: [REVIEWER, CLAUDE, DEFAULT],
+ active_agent_profile_id: activeId,
+ });
+ listLlmProfiles.mockResolvedValue({
+ profiles: [{ name: "slow" }, { name: "fast" }],
+ active_profile: activeLlm,
+ });
+ migrate.mockResolvedValue(true);
+ getAgentProfile.mockImplementation(async (name: string) => ({
+ name,
+ profile: {
+ ...[REVIEWER, CLAUDE, DEFAULT].find((p) => p.name === name),
+ ...detail,
+ },
+ }));
+}
-function launchWithParentModel() {
+function launch(
+ options: {
+ agentProfileId?: string;
+ llmProfile?: string;
+ isCloud?: boolean;
+ } = {},
+) {
return resolveConversationLaunch({
queryClient: new QueryClient(),
backendId: "local-1",
orgId: null,
isCloud: false,
- agentProfileId: "profile-1",
- llmProfile: "fast",
+ ...options,
});
}
-describe("resolveConversationLaunch with a requested LLM profile", () => {
+describe("resolveConversationLaunch", () => {
afterEach(() => vi.resetAllMocks());
it("runs the requested LLM on the picked profile", async () => {
- listAgentProfiles.mockResolvedValue({
- profiles: [PARENT_PROFILE],
- active_agent_profile_id: null,
- });
- listLlmProfiles.mockResolvedValue({
- profiles: [{ name: "slow" }, { name: "fast" }],
- active_profile: "slow",
+ arrange();
+
+ await expect(
+ launch({ agentProfileId: "profile-1", llmProfile: "fast" }),
+ ).resolves.toMatchObject({
+ agentProfileId: "profile-1",
+ llmProfileOverride: "fast",
+ llmProfile: "fast",
});
- supportsOverride.mockResolvedValue(true);
+ });
+
+ it("runs the active agent profile's own LLM on an implicit launch", async () => {
+ arrange({ activeId: "profile-1", activeLlm: "fast" });
- await expect(launchWithParentModel()).resolves.toMatchObject({
+ const result = await launch();
+
+ expect(result).toMatchObject({
agentProfileId: "profile-1",
+ llmProfile: "slow",
+ });
+ expect(result.llmProfileOverride).toBeUndefined();
+ });
+
+ it("runs default on the active LLM profile on an implicit launch", async () => {
+ arrange({ activeId: "profile-default", activeLlm: "fast" });
+
+ await expect(launch()).resolves.toMatchObject({
llmProfileOverride: "fast",
llmProfile: "fast",
});
});
- it("keeps the profile on its own LLM when the server has no override", async () => {
- listAgentProfiles.mockResolvedValue({
- profiles: [PARENT_PROFILE],
- active_agent_profile_id: null,
+ it("keeps an explicit pick on its own LLM", async () => {
+ arrange({ activeLlm: "fast" });
+
+ const result = await launch({ agentProfileId: "profile-1" });
+
+ expect(result).toMatchObject({ llmProfile: "slow" });
+ expect(result.llmProfileOverride).toBeUndefined();
+ });
+
+ it("runs default on the active LLM profile even when picked", async () => {
+ arrange({ activeLlm: "fast" });
+
+ await expect(
+ launch({ agentProfileId: "profile-default" }),
+ ).resolves.toMatchObject({
+ llmProfileOverride: "fast",
+ llmProfile: "fast",
});
+ });
+
+ it("refuses a local launch when no profile is active", async () => {
+ arrange();
+
+ await expect(launch()).rejects.toThrow(
+ "CONVERSATION$NO_ACTIVE_AGENT_PROFILE",
+ );
+ });
+
+ it("lets Cloud launch its own default when no profile is active", async () => {
+ arrange();
+
+ await expect(launch({ isCloud: true })).resolves.toEqual({});
+ expect(getAgentProfile).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [
+ "enabled with a router",
+ { enable_classify_and_switch_llm_tool: true, meta_profile_ref: "router" },
+ true,
+ ],
+ [
+ "enabled without a name, so the first router",
+ { enable_classify_and_switch_llm_tool: true, meta_profile_ref: null },
+ true,
+ ],
+ [
+ "disabled",
+ {
+ enable_classify_and_switch_llm_tool: false,
+ meta_profile_ref: "router",
+ },
+ false,
+ ],
+ ])(
+ "reports the profile's router when the routing tool is %s",
+ async (_case, detail, expected) => {
+ arrange({ activeId: "profile-1", detail });
+
+ await expect(launch()).resolves.toMatchObject({
+ profileHasRouter: expected,
+ });
+ },
+ );
+
+ it("reports the ACP profile's server for the conversation tag", async () => {
+ arrange({ activeId: "profile-2", detail: { acp_server: "claude-code" } });
+
+ await expect(launch()).resolves.toMatchObject({
+ agentProfileId: "profile-2",
+ agentProfileKind: "acp",
+ acpServer: "claude-code",
+ profileHasRouter: false,
+ });
+ });
+
+ it("reads the profiles only after the default-profile migration settles", async () => {
+ arrange({ activeId: "profile-1" });
+ let finishMigration = () => {};
+ migrate.mockReturnValue(
+ new Promise<true>((resolve) => {
+ finishMigration = () => resolve(true);
+ }),
+ );
+
+ const pending = launch();
+ await Promise.resolve();
+ expect(listAgentProfiles).not.toHaveBeenCalled();
+
+ finishMigration();
+ await expect(pending).resolves.toMatchObject({
+ agentProfileId: "profile-1",
+ });
+ });
+
+ it("fails a local launch when the migration fails, and skips it on Cloud", async () => {
+ arrange({ activeId: "profile-1" });
+ migrate.mockRejectedValue(new Error("offline"));
+
+ await expect(launch()).rejects.toThrow("offline");
+ expect(listAgentProfiles).not.toHaveBeenCalled();
+
+ migrate.mockClear();
+ await launch({ isCloud: true });
+ expect(migrate).not.toHaveBeenCalled();
+ });
+
+ it("still launches the profile when its detail cannot be read", async () => {
+ arrange({ activeId: "profile-1" });
+ getAgentProfile.mockRejectedValue(new Error("boom"));
+
+ await expect(launch()).resolves.toMatchObject({
+ agentProfileId: "profile-1",
+ profileHasRouter: false,
+ });
+ });
+
+ it("launches Cloud's own default when the profile's LLM profile is gone", async () => {
+ arrange({ activeId: "profile-1" });
+ listLlmProfiles.mockResolvedValue({
+ profiles: [{ name: "fast" }],
+ active_profile: "fast",
+ });
+
+ await expect(launch({ isCloud: true })).resolves.toEqual({});
+ });
+
+ it("keeps a secret-restricted profile on Cloud even when its LLM profile is gone", async () => {
+ arrange({ activeId: "profile-1", detail: { secret_refs: [] } });
listLlmProfiles.mockResolvedValue({
- profiles: [{ name: "slow" }, { name: "fast" }],
- active_profile: "slow",
+ profiles: [{ name: "fast" }],
+ active_profile: "fast",
});
- supportsOverride.mockResolvedValue(false);
- const launch = await launchWithParentModel();
+ await expect(launch({ isCloud: true })).resolves.toMatchObject({
+ agentProfileId: "profile-1",
+ });
+ });
- expect(launch).toMatchObject({
+ it("launches the profile on Cloud when its LLM profile exists", async () => {
+ arrange({ activeId: "profile-1" });
+
+ await expect(launch({ isCloud: true })).resolves.toEqual({
agentProfileId: "profile-1",
+ agentProfileKind: "openhands",
llmProfile: "slow",
});
- expect(launch.llmProfileOverride).toBeUndefined();
+ expect(getAgentProfile).not.toHaveBeenCalled();
+ });
+});
+
+describe("launchConversation", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("refuses to launch on a subscription LLM that isn't connected", async () => {
+ arrange({ activeId: "profile-1", activeLlm: "slow" });
+ getLlmProfile.mockResolvedValue({
+ name: "slow",
+ config: { model: "openai/gpt-5", auth_type: "subscription" },
+ });
+ getOpenAIStatus.mockResolvedValue({ connected: false });
+ const create = vi.spyOn(
+ AgentServerConversationService,
+ "createConversation",
+ );
+
+ await expect(
+ launchConversation(
+ {
+ queryClient: new QueryClient(),
+ backendId: "local-1",
+ orgId: null,
+ isCloud: false,
+ },
+ {},
+ ),
+ ).rejects.toThrow(SUBSCRIPTION_LOGIN_REQUIRED_ERROR);
+ expect(getLlmProfile).toHaveBeenCalledWith("slow");
+ expect(create).not.toHaveBeenCalled();
});
});
diff --git a/__tests__/hooks/mutation/sync-agent-profiles.test.ts b/__tests__/hooks/mutation/sync-agent-profiles.test.ts
new file mode 100644
index 0000000000..d2ca18d927
--- /dev/null
+++ b/__tests__/hooks/mutation/sync-agent-profiles.test.ts
@@ -0,0 +1,384 @@
+import { QueryClient } from "@tanstack/react-query";
+import { HttpError } from "@openhands/typescript-client";
+import { DEFAULT_ENABLED_SKILL_NAMES } from "@openhands/extensions/skills";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";
+import { getActiveBackend } from "#/api/backend-registry/active-store";
+import ProfilesService from "#/api/profiles-service/profiles-service.api";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import {
+ applyDefaultAgentProfileToGlobal,
+ enabledMcpServerRefs,
+ sharedDefaultProfileFields,
+ llmProfileMirrored,
+ mcpServerRemoved,
+ mcpServerRenamed,
+ routerDetached,
+ withSkillSelection,
+ updateDefaultAgentProfile,
+ updateEveryAgentProfile,
+} from "#/hooks/mutation/sync-agent-profiles";
+import { settleRunningDefaultAgentProfileMigration } from "#/hooks/use-migrate-default-agent-profile";
+import type { Settings } from "#/types/settings";
+import { displayErrorToast } from "#/utils/custom-toast-handlers";
+import { CATALOG_SKILL_NAMES } from "#/utils/skill-enablement";
+
+vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({
+ __esModule: true,
+ default: { listProfiles: vi.fn(), getProfile: vi.fn(), saveProfile: vi.fn() },
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME: "default",
+}));
+vi.mock("#/api/profiles-service/profiles-service.api", () => ({
+ __esModule: true,
+ default: { listProfiles: vi.fn(), activateProfile: vi.fn() },
+}));
+vi.mock("#/api/settings-service/settings-service.api", () => ({
+ __esModule: true,
+ default: {
+ getSettings: vi.fn(),
+ saveSettings: vi.fn(),
+ patchMcpServer: vi.fn(),
+ invalidateCache: vi.fn(),
+ },
+}));
+vi.mock("#/api/backend-registry/active-store", () => ({
+ getActiveBackend: vi.fn(),
+ isNoBackend: (backend: { id: string }) => backend.id === "no-backend",
+}));
+vi.mock("#/hooks/use-migrate-default-agent-profile", () => ({
+ settleRunningDefaultAgentProfileMigration: vi.fn(),
+}));
+vi.mock("#/utils/custom-toast-handlers", () => ({
+ displayErrorToast: vi.fn(),
+}));
+
+const OPTIONAL = CATALOG_SKILL_NAMES.find(
+ (name) => !DEFAULT_ENABLED_SKILL_NAMES.includes(name),
+)!;
+
+const openHands = (name: string, overrides: Record<string, unknown> = {}) => ({
+ id: `id-${name}`,
+ name,
+ revision: 3,
+ agent_kind: "openhands",
+ llm_profile_ref: "llm",
+ mcp_server_refs: null,
+ public_skills: [...DEFAULT_ENABLED_SKILL_NAMES],
+ disabled_skills: [],
+ ...overrides,
+});
+
+const useBackend = (kind: "local" | "cloud") =>
+ vi.mocked(getActiveBackend).mockReturnValue({
+ backend: { id: "local-1", kind },
+ } as never);
+
+const storeProfiles = (...profiles: ReturnType<typeof openHands>[]) => {
+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({
+ profiles,
+ } as never);
+ vi.mocked(AgentProfilesService.getProfile).mockImplementation(
+ async (name) => {
+ const profile = profiles.find((entry) => entry.name === name);
+ if (!profile) throw new HttpError(404, "Not Found", {}, "missing");
+ return { name, profile } as never;
+ },
+ );
+};
+
+const MCP_SERVERS = {
+ github: { transport: "http", url: "https://github.example/mcp" },
+ slack: { transport: "stdio", command: "npx", enabled: false },
+};
+
+const settingsWith = (overrides: Partial<Settings>): Settings =>
+ ({
+ enabled_skills: [...DEFAULT_ENABLED_SKILL_NAMES],
+ disabled_skills: [],
+ mcp_config: MCP_SERVERS,
+ ...overrides,
+ }) as unknown as Settings;
+
+describe("profile changes", () => {
+ it("renames and drops an MCP server only where a profile lists it", () => {
+ const restricted = openHands("p", {
+ mcp_server_refs: ["github", "slack"],
+ }) as never;
+ expect(mcpServerRenamed("github", "gh")(restricted)).toEqual({
+ mcp_server_refs: ["gh", "slack"],
+ });
+ expect(mcpServerRemoved("github")(restricted)).toEqual({
+ mcp_server_refs: ["slack"],
+ });
+ expect(mcpServerRemoved("linear")(restricted)).toBeNull();
+ expect(mcpServerRemoved("github")(openHands("all") as never)).toBeNull();
+ });
+
+ it("sets default's whole skill list", () => {
+ const selection = { enabledSkills: [OPTIONAL], disabledSkills: ["mine"] };
+ expect(
+ withSkillSelection(selection)(openHands("default") as never),
+ ).toEqual({
+ public_skills: [OPTIONAL],
+ disabled_skills: ["mine"],
+ });
+ expect(
+ withSkillSelection(selection)(
+ openHands("default", {
+ public_skills: [OPTIONAL],
+ disabled_skills: ["mine"],
+ }) as never,
+ ),
+ ).toBeNull();
+ expect(
+ withSkillSelection(selection)({
+ ...openHands("default"),
+ agent_kind: "acp",
+ } as never),
+ ).toBeNull();
+ });
+
+ it("points default at the active LLM profile", () => {
+ expect(llmProfileMirrored("fast")(openHands("default") as never)).toEqual({
+ llm_profile_ref: "fast",
+ });
+ expect(llmProfileMirrored("llm")(openHands("default") as never)).toBeNull();
+ });
+
+ it("reads the servers switched on, or null when all are", () => {
+ expect(enabledMcpServerRefs(settingsWith({}))).toEqual(["github"]);
+ expect(
+ enabledMcpServerRefs(
+ settingsWith({
+ mcp_config: { github: { transport: "http", url: "u" } },
+ } as never),
+ ),
+ ).toBeNull();
+ });
+});
+
+describe("profile writes", () => {
+ let queryClient: QueryClient;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ queryClient = new QueryClient();
+ useBackend("local");
+ vi.mocked(settleRunningDefaultAgentProfileMigration).mockResolvedValue(
+ undefined,
+ );
+ vi.mocked(AgentProfilesService.saveProfile).mockResolvedValue({} as never);
+ });
+
+ it("saves a change over the stored default after a running migration", async () => {
+ storeProfiles(openHands("default"));
+
+ await updateDefaultAgentProfile(queryClient, llmProfileMirrored("fast"));
+
+ expect(settleRunningDefaultAgentProfileMigration).toHaveBeenCalledWith(
+ queryClient,
+ "local-1",
+ );
+ const [name, saved] = vi.mocked(AgentProfilesService.saveProfile).mock
+ .calls[0];
+ expect(name).toBe("default");
+ expect(saved).toMatchObject({
+ agent_kind: "openhands",
+ llm_profile_ref: "fast",
+ public_skills: [...DEFAULT_ENABLED_SKILL_NAMES],
+ });
+ expect(saved).not.toHaveProperty("revision");
+ });
+
+ it("updates every profile that lists a removed MCP server", async () => {
+ storeProfiles(
+ openHands("default"),
+ openHands("uses-it", { mcp_server_refs: ["github", "slack"] }),
+ openHands("other", { mcp_server_refs: ["slack"] }),
+ );
+
+ await updateEveryAgentProfile(queryClient, mcpServerRemoved("github"));
+
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledTimes(1);
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledWith(
+ "uses-it",
+ expect.objectContaining({ mcp_server_refs: ["slack"] }),
+ );
+ });
+
+ it("does nothing on Cloud, without a default, or when nothing changes", async () => {
+ useBackend("cloud");
+ await updateDefaultAgentProfile(queryClient, llmProfileMirrored("fast"));
+ expect(AgentProfilesService.getProfile).not.toHaveBeenCalled();
+
+ useBackend("local");
+ storeProfiles();
+ await updateDefaultAgentProfile(queryClient, llmProfileMirrored("fast"));
+ storeProfiles(openHands("default"));
+ await updateDefaultAgentProfile(queryClient, llmProfileMirrored("llm"));
+
+ expect(AgentProfilesService.saveProfile).not.toHaveBeenCalled();
+ expect(displayErrorToast).not.toHaveBeenCalled();
+ });
+
+ it("runs writes one at a time, so the second reads the first's save", async () => {
+ let stored = openHands("default", { mcp_server_refs: ["a", "b", "c"] });
+ vi.mocked(AgentProfilesService.getProfile).mockImplementation(
+ async () => ({ name: "default", profile: stored }) as never,
+ );
+ vi.mocked(AgentProfilesService.saveProfile).mockImplementation(
+ async (_name, profile) => {
+ await new Promise((resolve) => {
+ setTimeout(resolve, 5);
+ });
+ stored = { ...stored, ...(profile as typeof stored) };
+ return {} as never;
+ },
+ );
+
+ await Promise.all([
+ updateDefaultAgentProfile(queryClient, mcpServerRemoved("a")),
+ updateDefaultAgentProfile(queryClient, mcpServerRemoved("b")),
+ ]);
+
+ expect(stored.mcp_server_refs).toEqual(["c"]);
+ });
+
+ it("toasts a failed save and keeps later writes running", async () => {
+ storeProfiles(openHands("default"));
+ vi.mocked(AgentProfilesService.saveProfile).mockRejectedValueOnce(
+ new Error("boom"),
+ );
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+
+ await updateDefaultAgentProfile(queryClient, llmProfileMirrored("fast"));
+ await updateDefaultAgentProfile(queryClient, llmProfileMirrored("slow"));
+
+ expect(displayErrorToast).toHaveBeenCalledTimes(1);
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledTimes(2);
+ });
+
+ it("detaches a deleted router, and can reject so the delete stops", async () => {
+ storeProfiles(
+ openHands("default"),
+ openHands("routed", {
+ meta_profile_ref: "fast",
+ enable_classify_and_switch_llm_tool: true,
+ }),
+ );
+
+ await updateEveryAgentProfile(queryClient, routerDetached("fast"), {
+ throwOnError: true,
+ });
+
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledTimes(1);
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledWith(
+ "routed",
+ expect.objectContaining({
+ meta_profile_ref: null,
+ enable_classify_and_switch_llm_tool: false,
+ }),
+ );
+
+ vi.mocked(AgentProfilesService.saveProfile).mockRejectedValueOnce(
+ new Error("boom"),
+ );
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ await expect(
+ updateEveryAgentProfile(queryClient, routerDetached("fast"), {
+ throwOnError: true,
+ }),
+ ).rejects.toThrow("boom");
+ expect(displayErrorToast).not.toHaveBeenCalled();
+ });
+
+ it("lets the caller report a failure instead of the default toast", async () => {
+ storeProfiles(openHands("default"));
+ vi.mocked(AgentProfilesService.saveProfile).mockRejectedValueOnce(
+ new Error("boom"),
+ );
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ const onError = vi.fn();
+
+ await updateDefaultAgentProfile(queryClient, llmProfileMirrored("fast"), {
+ onError,
+ });
+
+ expect(onError).toHaveBeenCalledWith(new Error("boom"));
+ expect(displayErrorToast).not.toHaveBeenCalled();
+ });
+});
+
+describe("applyDefaultAgentProfileToGlobal", () => {
+ let queryClient: QueryClient;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ queryClient = new QueryClient();
+ // As the server sends it: servers under `agent_settings`, a stale flat map.
+ vi.mocked(SettingsService.getSettings).mockResolvedValue(
+ settingsWith({
+ mcp_config: {},
+ agent_settings: { mcp_config: MCP_SERVERS },
+ } as never),
+ );
+ vi.mocked(ProfilesService.listProfiles).mockResolvedValue({
+ profiles: [],
+ active_profile: "llm",
+ } as never);
+ });
+
+ it("writes default's LLM and MCP servers to the global pages, not its skills", async () => {
+ const input = {
+ agent_kind: "openhands",
+ llm_profile_ref: "fast",
+ public_skills: [OPTIONAL],
+ disabled_skills: ["mine"],
+ mcp_server_refs: ["slack"],
+ secret_refs: ["GITHUB_TOKEN"],
+ } as never;
+ await applyDefaultAgentProfileToGlobal(queryClient, input);
+ const saved = sharedDefaultProfileFields(input);
+
+ expect(SettingsService.saveSettings).not.toHaveBeenCalled();
+ expect(ProfilesService.activateProfile).toHaveBeenCalledWith("fast");
+ expect(SettingsService.patchMcpServer).toHaveBeenCalledWith("github", {
+ enabled: false,
+ });
+ expect(SettingsService.patchMcpServer).toHaveBeenCalledWith("slack", {
+ enabled: true,
+ });
+ expect(saved).toMatchObject({ mcp_server_refs: null, secret_refs: null });
+ });
+
+ it("writes nothing when default already matches the global pages", async () => {
+ const input = {
+ agent_kind: "openhands",
+ llm_profile_ref: "llm",
+ public_skills: [...DEFAULT_ENABLED_SKILL_NAMES],
+ disabled_skills: [],
+ mcp_server_refs: ["github"],
+ } as never;
+ await applyDefaultAgentProfileToGlobal(queryClient, input);
+ const saved = sharedDefaultProfileFields(input);
+
+ expect(SettingsService.saveSettings).not.toHaveBeenCalled();
+ expect(ProfilesService.activateProfile).not.toHaveBeenCalled();
+ expect(SettingsService.patchMcpServer).not.toHaveBeenCalled();
+ expect(saved).toMatchObject({ mcp_server_refs: null });
+ expect(saved).not.toHaveProperty("secret_refs");
+ });
+
+ it("switches every server on when default takes all of them", async () => {
+ await applyDefaultAgentProfileToGlobal(queryClient, {
+ agent_kind: "acp",
+ mcp_server_refs: null,
+ } as never);
+
+ expect(SettingsService.patchMcpServer).toHaveBeenCalledTimes(1);
+ expect(SettingsService.patchMcpServer).toHaveBeenCalledWith("slack", {
+ enabled: true,
+ });
+ expect(SettingsService.saveSettings).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/hooks/mutation/use-activate-llm-profile.test.tsx b/__tests__/hooks/mutation/use-activate-llm-profile.test.tsx
index 8183742954..bdc5f944f5 100644
--- a/__tests__/hooks/mutation/use-activate-llm-profile.test.tsx
+++ b/__tests__/hooks/mutation/use-activate-llm-profile.test.tsx
@@ -15,6 +15,21 @@ vi.mock("#/api/profiles-service/profiles-service.api", () => ({
},
}));
+const updateDefaultAgentProfileMock = vi.hoisted(() => vi.fn());
+vi.mock("#/hooks/mutation/sync-agent-profiles", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/mutation/sync-agent-profiles")
+ >()),
+ updateDefaultAgentProfile: updateDefaultAgentProfileMock,
+}));
+
+/** The `default` fields the sync would change, from a stored LLM ref. */
+const mirroredFrom = (llmProfileRef: string) => {
+ expect(updateDefaultAgentProfileMock).toHaveBeenCalledOnce();
+ const [, change] = updateDefaultAgentProfileMock.mock.calls[0];
+ return change({ agent_kind: "openhands", llm_profile_ref: llmProfileRef });
+};
+
describe("useActivateLlmProfile", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -58,6 +73,7 @@ describe("useActivateLlmProfile", () => {
// Verify activateProfile was called with the correct name
expect(mockActivateProfile).toHaveBeenCalledWith("my-profile");
+ expect(mirroredFrom("old")).toEqual({ llm_profile_ref: "my-profile" });
// Verify all cache invalidations occur on success
expect(invalidateCacheSpy).toHaveBeenCalled();
diff --git a/__tests__/hooks/mutation/use-add-mcp-server.test.ts b/__tests__/hooks/mutation/use-add-mcp-server.test.ts
index 5d953edcad..1c0c023d5b 100644
--- a/__tests__/hooks/mutation/use-add-mcp-server.test.ts
+++ b/__tests__/hooks/mutation/use-add-mcp-server.test.ts
@@ -7,6 +7,17 @@ import { SUPER_ADMIN_SETUP_STEP_EVENT } from "#/components/features/setup-guide/
import { useAddMcpServer } from "#/hooks/mutation/use-add-mcp-server";
import { SUPER_ADMIN_SETUP_QUERY_KEYS } from "#/hooks/query/query-keys";
+const syncMocks = vi.hoisted(() => ({
+ updateDefaultAgentProfile: vi.fn(),
+ updateEveryAgentProfile: vi.fn(),
+}));
+vi.mock("#/hooks/mutation/sync-agent-profiles", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/mutation/sync-agent-profiles")
+ >()),
+ ...syncMocks,
+}));
+
const useSettingsMock = vi.fn();
vi.mock("#/hooks/query/use-settings", () => ({
useSettings: () => useSettingsMock(),
@@ -37,6 +48,24 @@ describe("useAddMcpServer", () => {
});
});
+ it("leaves agent profiles alone: default loads every switched-on server", async () => {
+ vi.clearAllMocks();
+ vi.spyOn(SettingsService, "createMcpServer").mockResolvedValue(true);
+ const { result } = renderHook(() => useAddMcpServer(), {
+ wrapper: createWrapper(),
+ });
+
+ await result.current.mutateAsync({
+ id: "",
+ type: "shttp",
+ name: "docs",
+ url: "https://docs.example/mcp",
+ });
+
+ expect(syncMocks.updateDefaultAgentProfile).not.toHaveBeenCalled();
+ expect(syncMocks.updateEveryAgentProfile).not.toHaveBeenCalled();
+ });
+
it("adds only one named entry and leaves siblings out of the mutation", async () => {
const createSpy = vi
.spyOn(SettingsService, "createMcpServer")
diff --git a/__tests__/hooks/mutation/use-apply-onboarding-agent-profile.test.tsx b/__tests__/hooks/mutation/use-apply-onboarding-agent-profile.test.tsx
new file mode 100644
index 0000000000..f26074f5b0
--- /dev/null
+++ b/__tests__/hooks/mutation/use-apply-onboarding-agent-profile.test.tsx
@@ -0,0 +1,163 @@
+import { renderHook } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { HttpError } from "@openhands/typescript-client";
+import { DEFAULT_ENABLED_SKILL_NAMES } from "@openhands/extensions/skills";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";
+import * as activeBackendContext from "#/contexts/active-backend-context";
+import { useApplyOnboardingAgentProfile } from "#/hooks/mutation/use-apply-onboarding-agent-profile";
+import { ensureDefaultAgentProfileMigrated } from "#/hooks/use-migrate-default-agent-profile";
+
+vi.mock("#/hooks/use-migrate-default-agent-profile", () => ({
+ ensureDefaultAgentProfileMigrated: vi.fn(),
+}));
+
+vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({
+ __esModule: true,
+ default: {
+ getProfile: vi.fn(),
+ saveProfile: vi.fn(),
+ activateProfile: vi.fn(),
+ },
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME: "default",
+}));
+
+const STORED_DEFAULT = {
+ id: "profile-default",
+ name: "default",
+ revision: 2,
+ agent_kind: "openhands",
+ llm_profile_ref: "old-llm",
+ mcp_server_refs: ["linear"],
+ public_skills: ["github"],
+};
+
+function renderApply() {
+ const queryClient = new QueryClient();
+ return renderHook(() => useApplyOnboardingAgentProfile(), {
+ wrapper: ({ children }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ ),
+ }).result.current;
+}
+
+describe("useApplyOnboardingAgentProfile", () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.spyOn(activeBackendContext, "useActiveBackend").mockReturnValue({
+ backend: {
+ id: "local-1",
+ name: "Local",
+ host: "http://127.0.0.1:18000",
+ apiKey: "",
+ kind: "local",
+ },
+ orgId: null,
+ });
+ vi.mocked(ensureDefaultAgentProfileMigrated).mockResolvedValue(true);
+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
+ name: "default",
+ profile: STORED_DEFAULT,
+ } as never);
+ vi.mocked(AgentProfilesService.saveProfile).mockResolvedValue({} as never);
+ vi.mocked(AgentProfilesService.activateProfile).mockResolvedValue(
+ {} as never,
+ );
+ });
+
+ it("keeps the stored `default` settings when onboarding picks an LLM", async () => {
+ await renderApply()({
+ agent_kind: "openhands",
+ llm_profile_ref: "new-llm",
+ });
+
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledWith("default", {
+ agent_kind: "openhands",
+ llm_profile_ref: "new-llm",
+ mcp_server_refs: ["linear"],
+ public_skills: ["github"],
+ });
+ expect(AgentProfilesService.activateProfile).toHaveBeenCalledWith(
+ "profile-default",
+ );
+ });
+
+ it("replaces `default` when onboarding picks an ACP agent", async () => {
+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
+ name: "default",
+ profile: {
+ id: "profile-default",
+ name: "default",
+ revision: 2,
+ agent_kind: "acp",
+ acp_server: "custom",
+ acp_command: "my-acp --flag",
+ },
+ } as never);
+
+ await renderApply()({
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ acp_model: null,
+ });
+
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledWith("default", {
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ acp_model: null,
+ });
+ });
+
+ it("configures `default` only after the default migration", async () => {
+ let finishMigration: (value: true) => void = () => {};
+ vi.mocked(ensureDefaultAgentProfileMigrated).mockReturnValue(
+ new Promise((resolve) => {
+ finishMigration = resolve;
+ }),
+ );
+
+ const applied = renderApply()({
+ agent_kind: "openhands",
+ llm_profile_ref: "new-llm",
+ });
+ await Promise.resolve();
+ expect(AgentProfilesService.getProfile).not.toHaveBeenCalled();
+
+ finishMigration(true);
+ await applied;
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledWith(
+ "default",
+ expect.objectContaining({ llm_profile_ref: "new-llm" }),
+ );
+ });
+
+ it("creates `default` fresh when none is stored", async () => {
+ vi.mocked(AgentProfilesService.getProfile)
+ .mockRejectedValueOnce(new HttpError(404, "Not Found"))
+ .mockResolvedValue({ name: "default", profile: STORED_DEFAULT } as never);
+
+ await renderApply()({
+ agent_kind: "openhands",
+ llm_profile_ref: "new-llm",
+ });
+
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledWith("default", {
+ agent_kind: "openhands",
+ llm_profile_ref: "new-llm",
+ public_skills: [...DEFAULT_ENABLED_SKILL_NAMES],
+ });
+ });
+
+ it("leaves `default` untouched when it can't be read", async () => {
+ vi.mocked(AgentProfilesService.getProfile).mockRejectedValue(
+ new HttpError(500, "Internal Server Error"),
+ );
+
+ await renderApply()({
+ agent_kind: "openhands",
+ llm_profile_ref: "new-llm",
+ });
+
+ expect(AgentProfilesService.saveProfile).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/hooks/mutation/use-create-conversation.test.tsx b/__tests__/hooks/mutation/use-create-conversation.test.tsx
index 195f35f6f1..de41090ab6 100644
--- a/__tests__/hooks/mutation/use-create-conversation.test.tsx
+++ b/__tests__/hooks/mutation/use-create-conversation.test.tsx
@@ -53,7 +53,15 @@ vi.mock("#/hooks/query/use-agent-profiles", () => ({
// The launch path resolves the active AgentProfile by awaiting
// `AgentProfilesService.listProfiles` through the query cache (#3727).
-// Default: no active profile, so a plain create stays on the legacy path.
+// Default: the seeded `default` profile is active, as a server keeps it.
+const DEFAULT_PROFILE = {
+ id: "profile-default",
+ name: "default",
+ agent_kind: "openhands",
+ revision: 1,
+ llm_profile_ref: "default",
+ mcp_server_refs: null,
+};
const { listAgentProfilesMock, getAgentProfileMock } = vi.hoisted(() => ({
listAgentProfilesMock: vi.fn(),
getAgentProfileMock: vi.fn(),
@@ -67,14 +75,24 @@ vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({
WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME: "default",
}));
listAgentProfilesMock.mockResolvedValue({
- profiles: [],
- active_agent_profile_id: null,
+ profiles: [DEFAULT_PROFILE],
+ active_agent_profile_id: DEFAULT_PROFILE.id,
});
getAgentProfileMock.mockResolvedValue({
name: "default",
- profile: { secret_refs: null },
+ profile: DEFAULT_PROFILE,
});
+vi.mock(
+ "#/hooks/use-migrate-default-agent-profile",
+ async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/use-migrate-default-agent-profile")
+ >()),
+ ensureDefaultAgentProfileMigrated: vi.fn().mockResolvedValue(true),
+ }),
+);
+
// LLM-profile service: real listProfiles calls (the llmProfileExists
// validation — see use-create-conversation.ts) so it can be asserted per-test.
const listLlmProfilesMock = vi.fn();
@@ -86,33 +104,23 @@ vi.mock("#/api/profiles-service/profiles-service.api", () => ({
}));
listLlmProfilesMock.mockResolvedValue({ profiles: [], active_profile: null });
-// Without `agent_launch_pipeline_v1` the launch keeps its agent_settings
-// fallbacks; the override block below turns it on.
-const { supportsLaunchLlmOverrideMock } = vi.hoisted(() => ({
- supportsLaunchLlmOverrideMock: vi.fn(async () => false),
-}));
-vi.mock("#/api/agent-server-adapter", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#/api/agent-server-adapter")>()),
- backendSupportsLaunchLlmOverride: () => supportsLaunchLlmOverrideMock(),
-}));
-
describe("useCreateConversation", () => {
afterEach(() => {
- // Restore the default (no active AgentProfile) so the overrides below
- // don't leak into the other create-call assertions.
+ // Restore the default (`default` active) so the overrides below don't
+ // leak into the other create-call assertions.
mockUseActiveBackend.mockReturnValue({
backend: { id: "local-1", kind: "local" as const },
orgId: null,
});
listAgentProfilesMock.mockReset();
listAgentProfilesMock.mockResolvedValue({
- profiles: [],
- active_agent_profile_id: null,
+ profiles: [DEFAULT_PROFILE],
+ active_agent_profile_id: DEFAULT_PROFILE.id,
});
getAgentProfileMock.mockReset();
getAgentProfileMock.mockResolvedValue({
name: "default",
- profile: { secret_refs: null },
+ profile: DEFAULT_PROFILE,
});
listLlmProfilesMock.mockReset();
listLlmProfilesMock.mockResolvedValue({
@@ -197,6 +205,9 @@ describe("useCreateConversation", () => {
workspaceMode: undefined,
parentConversationId: undefined,
agentType: undefined,
+ agentProfileId: DEFAULT_PROFILE.id,
+ agentProfileKind: "openhands",
+ agentLlmProfileRef: "default",
});
});
});
@@ -399,120 +410,6 @@ describe("useCreateConversation", () => {
);
});
- it("launches the seeded `default` profile via agent_settings so canvas enrichments survive", async () => {
- // The active profile IS the well-known default → it's the enriched baseline
- // (mirrors agent_settings), not a deliberate profile pick, so the launch
- // stays on the agent_settings path (no profile tail) even though its
- // llm_profile_ref resolves. Keeps <RUNTIME_SERVICES> and project skills,
- // which the profile-resolution path drops.
- listAgentProfilesMock.mockResolvedValue({
- profiles: [
- {
- id: "profile-default",
- name: "default",
- agent_kind: "openhands",
- revision: 1,
- llm_profile_ref: "gpt",
- mcp_server_refs: null,
- },
- ],
- active_agent_profile_id: "profile-default",
- });
- listLlmProfilesMock.mockResolvedValue({
- profiles: [{ name: "gpt" }],
- active_profile: "gpt",
- });
- const createConversationSpy = vi
- .spyOn(AgentServerConversationService, "createConversation")
- .mockResolvedValue({
- id: "task-id",
- app_conversation_id: "conv-1",
- agent_server_url: "http://agent-server.local",
- } as never);
-
- const { result } = renderHook(() => useCreateConversation(), {
- wrapper: ({ children }) => (
- <QueryClientProvider client={new QueryClient()}>
- {children}
- </QueryClientProvider>
- ),
- });
-
- await result.current.mutateAsync({ query: "hello" });
-
- const call = createConversationSpy.mock.lastCall;
- expect(call?.[0]?.agentProfileId).toBeUndefined();
- });
-
- it.each([
- ["the local default profile", "default", "gpt", ["gpt"], "gpt"],
- ["a missing LLM profile", "missing-llm", "missing", [], null],
- [
- "an implicit active-LLM override",
- "pinned",
- "pinned",
- ["pinned", "selected"],
- "selected",
- ],
- ] as const)(
- "keeps a secret-scoped profile for %s",
- async (
- _fallback,
- profileName,
- llmProfileRef,
- llmProfileNames,
- activeLlmProfile,
- ) => {
- const profile = {
- id: `profile-${profileName}`,
- name: profileName,
- agent_kind: "openhands",
- revision: 1,
- llm_profile_ref: llmProfileRef,
- mcp_server_refs: null,
- };
- listAgentProfilesMock.mockResolvedValue({
- profiles: [profile],
- active_agent_profile_id: profile.id,
- });
- getAgentProfileMock.mockResolvedValue({
- name: profile.name,
- profile: { ...profile, secret_refs: [] },
- });
- listLlmProfilesMock.mockResolvedValue({
- profiles: llmProfileNames.map((name) => ({ name })),
- active_profile: activeLlmProfile,
- });
- const createConversationSpy = vi
- .spyOn(AgentServerConversationService, "createConversation")
- .mockResolvedValue({
- id: "task-id",
- app_conversation_id: "conv-1",
- agent_server_url: "http://agent-server.local",
- } as never);
- const queryClient = new QueryClient();
- queryClient.setQueryData(
- AGENT_PROFILES_QUERY_KEYS.detail("local-1", null, profile.name),
- { profile: { ...profile, secret_refs: null } },
- { updatedAt: 1 },
- );
-
- const { result } = renderHook(() => useCreateConversation(), {
- wrapper: ({ children }) => (
- <QueryClientProvider client={queryClient}>
- {children}
- </QueryClientProvider>
- ),
- });
-
- await result.current.mutateAsync({ query: "hello" });
-
- expect(createConversationSpy.mock.lastCall?.[0]?.agentProfileId).toBe(
- profile.id,
- );
- },
- );
-
it("keeps the profile path for an ACP `default` profile (agent_settings can't carry ACP config)", async () => {
// The default→agent_settings shortcut is OpenHands-only: activation is
// pointer-only, so global agent_settings is stale (still OpenHands) for an
@@ -656,55 +553,6 @@ describe("useCreateConversation", () => {
);
});
- it("honors the home LLM dropdown selection over a named profile's pinned ref (#16539)", async () => {
- // The home pill shows the account-wide active LLM profile, so when it
- // differs from the active named profile's pinned llm_profile_ref the
- // launch must run the selection: downgrade to the agent_settings path
- // (which the dropdown activation syncs) and stamp the selected profile.
- listAgentProfilesMock.mockResolvedValue({
- profiles: [
- {
- id: "profile-luna",
- name: "openhands-luna",
- agent_kind: "openhands",
- revision: 1,
- llm_profile_ref: "pinned-model",
- mcp_server_refs: null,
- },
- ],
- active_agent_profile_id: "profile-luna",
- });
- listLlmProfilesMock.mockResolvedValue({
- profiles: [{ name: "pinned-model" }, { name: "selected-model" }],
- active_profile: "selected-model",
- });
- const createConversationSpy = vi
- .spyOn(AgentServerConversationService, "createConversation")
- .mockResolvedValue({
- id: "task-id",
- app_conversation_id: "conv-dropdown-override",
- agent_server_url: "http://agent-server.local",
- } as never);
-
- const { result } = renderHook(() => useCreateConversation(), {
- wrapper: ({ children }) => (
- <QueryClientProvider client={new QueryClient()}>
- {children}
- </QueryClientProvider>
- ),
- });
-
- await result.current.mutateAsync({ query: "hello" });
-
- const call = createConversationSpy.mock.lastCall;
- expect(call?.[0]?.agentProfileId).toBeUndefined();
- await waitFor(() =>
- expect(
- getStoredConversationMetadata("conv-dropdown-override")?.active_profile,
- ).toBe("selected-model"),
- );
- });
-
it("keeps the named profile path when the dropdown selection matches its pinned ref (#16539)", async () => {
listAgentProfilesMock.mockResolvedValue({
profiles: [
@@ -837,7 +685,7 @@ describe("useCreateConversation", () => {
expect(call?.[0]?.agentProfileId).toBe("profile-luna");
});
- describe("on an agent-server with per-launch LLM overrides", () => {
+ describe("the home LLM selection", () => {
const luna = {
id: "profile-luna",
name: "openhands-luna",
@@ -866,14 +714,7 @@ describe("useCreateConversation", () => {
return createConversationSpy.mock.lastCall?.[0];
}
- beforeEach(() => {
- supportsLaunchLlmOverrideMock.mockResolvedValue(true);
- });
- afterEach(() => {
- supportsLaunchLlmOverrideMock.mockResolvedValue(false);
- });
-
- it("keeps the named profile and runs the home LLM selection (#16539)", async () => {
+ it("runs a named profile's own LLM over the active LLM profile", async () => {
listAgentProfilesMock.mockResolvedValue({
profiles: [luna],
active_agent_profile_id: "profile-luna",
@@ -886,14 +727,13 @@ describe("useCreateConversation", () => {
const call = await launch();
expect(call?.agentProfileId).toBe("profile-luna");
- expect(call?.agentLlmProfileOverride).toBe("selected-model");
- expect(call?.agentLlmProfileRef).toBe("selected-model");
- expect(getAgentProfileMock).not.toHaveBeenCalled();
+ expect(call?.agentLlmProfileOverride).toBeUndefined();
+ expect(call?.agentLlmProfileRef).toBe("pinned-model");
await waitFor(() =>
expect(
getStoredConversationMetadata("conv-dropdown-override")
?.active_profile,
- ).toBe("selected-model"),
+ ).toBe("pinned-model"),
);
});
@@ -946,20 +786,16 @@ describe("useCreateConversation", () => {
expect(call?.agentLlmProfileRef).toBe("pinned-model");
});
- it("still launches the OpenHands `default` via agent_settings", async () => {
- listAgentProfilesMock.mockResolvedValue({
- profiles: [{ ...luna, id: "profile-default", name: "default" }],
- active_agent_profile_id: "profile-default",
- });
+ it("launches the seeded `default` by id like any other profile", async () => {
listLlmProfilesMock.mockResolvedValue({
- profiles: [{ name: "pinned-model" }, { name: "selected-model" }],
+ profiles: [{ name: "default" }, { name: "selected-model" }],
active_profile: "selected-model",
});
const call = await launch();
- expect(call?.agentProfileId).toBeUndefined();
- expect(call).not.toHaveProperty("agentLlmProfileOverride");
+ expect(call?.agentProfileId).toBe(DEFAULT_PROFILE.id);
+ expect(call?.agentLlmProfileOverride).toBe("selected-model");
});
it("sends no override to cloud", async () => {
diff --git a/__tests__/hooks/mutation/use-delete-llm-profile.test.tsx b/__tests__/hooks/mutation/use-delete-llm-profile.test.tsx
index 2be1623e08..12cea26cb4 100644
--- a/__tests__/hooks/mutation/use-delete-llm-profile.test.tsx
+++ b/__tests__/hooks/mutation/use-delete-llm-profile.test.tsx
@@ -12,6 +12,13 @@ import {
vi.mock("#/api/profiles-service/profiles-service.api");
vi.mock("#/api/settings-service/settings-service.api");
+const updateDefaultAgentProfileMock = vi.hoisted(() => vi.fn());
+vi.mock("#/hooks/mutation/sync-agent-profiles", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/mutation/sync-agent-profiles")
+ >()),
+ updateDefaultAgentProfile: updateDefaultAgentProfileMock,
+}));
describe("useDeleteLlmProfile", () => {
let queryClient: QueryClient;
@@ -34,6 +41,45 @@ describe("useDeleteLlmProfile", () => {
{ client: queryClient },
children,
);
+ vi.mocked(ProfilesService.listProfiles).mockResolvedValue({
+ profiles: [],
+ active_profile: null,
+ } as never);
+ updateDefaultAgentProfileMock.mockResolvedValue(undefined);
+ });
+
+ it("moves default to the profile that will become active, then deletes", async () => {
+ vi.mocked(ProfilesService.listProfiles).mockResolvedValue({
+ profiles: [
+ { name: "old", api_key_set: true },
+ { name: "keyless", api_key_set: false },
+ { name: "keyed", api_key_set: true },
+ ],
+ active_profile: "old",
+ } as never);
+ vi.mocked(ProfilesService.deleteProfile).mockResolvedValue({
+ name: "old",
+ message: "Profile deleted",
+ });
+
+ const { result } = renderHook(() => useDeleteLlmProfile(), { wrapper });
+ await act(async () => {
+ await result.current.mutateAsync("old");
+ });
+
+ const [, change, options] = updateDefaultAgentProfileMock.mock.calls[0];
+ expect(options).toEqual({ throwOnError: true });
+ expect(change({ agent_kind: "openhands", llm_profile_ref: "old" })).toEqual(
+ { llm_profile_ref: "keyed" },
+ );
+ expect(
+ change({ agent_kind: "openhands", llm_profile_ref: "keyless" }),
+ ).toBeNull();
+ expect(
+ updateDefaultAgentProfileMock.mock.invocationCallOrder[0],
+ ).toBeLessThan(
+ vi.mocked(ProfilesService.deleteProfile).mock.invocationCallOrder[0],
+ );
});
afterEach(() => {
diff --git a/__tests__/hooks/mutation/use-delete-mcp-server.test.ts b/__tests__/hooks/mutation/use-delete-mcp-server.test.ts
index 83780d9bd2..2975baac90 100644
--- a/__tests__/hooks/mutation/use-delete-mcp-server.test.ts
+++ b/__tests__/hooks/mutation/use-delete-mcp-server.test.ts
@@ -12,6 +12,24 @@ import { useDeleteMcpServer } from "#/hooks/mutation/use-delete-mcp-server";
import type { MCPServerConfig } from "#/types/mcp-server";
import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";
+const syncMocks = vi.hoisted(() => ({
+ updateDefaultAgentProfile: vi.fn(),
+ updateEveryAgentProfile: vi.fn(),
+}));
+vi.mock("#/hooks/mutation/sync-agent-profiles", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/mutation/sync-agent-profiles")
+ >()),
+ ...syncMocks,
+}));
+
+/** The `mcp_server_refs` the sync gives a profile restricted to these servers. */
+const syncedRefs = (refs: string[]) => {
+ expect(syncMocks.updateEveryAgentProfile).toHaveBeenCalledOnce();
+ const [, change] = syncMocks.updateEveryAgentProfile.mock.calls[0];
+ return change({ agent_kind: "openhands", mcp_server_refs: refs });
+};
+
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
@@ -54,6 +72,25 @@ describe("useDeleteMcpServer", () => {
expect(fetchSpy).not.toHaveBeenCalled();
});
+ it("drops the deleted server from every profile that lists it", async () => {
+ vi.clearAllMocks();
+ vi.spyOn(SettingsService, "deleteMcpServer").mockResolvedValue(true);
+ const { result } = renderHook(() => useDeleteMcpServer(), {
+ wrapper: createWrapper(),
+ });
+
+ await result.current.mutateAsync({
+ id: "github",
+ type: "shttp",
+ name: "github",
+ url: "https://github.example/mcp",
+ });
+
+ expect(syncedRefs(["github", "docs"])).toEqual({
+ mcp_server_refs: ["docs"],
+ });
+ });
+
it("drops the deleted server's health verdict after success", async () => {
vi.spyOn(SettingsService, "deleteMcpServer").mockResolvedValue(true);
const target: MCPServerConfig = {
diff --git a/__tests__/hooks/mutation/use-delete-meta-profile.test.tsx b/__tests__/hooks/mutation/use-delete-meta-profile.test.tsx
index 333d769f68..ec8c0010db 100644
--- a/__tests__/hooks/mutation/use-delete-meta-profile.test.tsx
+++ b/__tests__/hooks/mutation/use-delete-meta-profile.test.tsx
@@ -4,6 +4,7 @@ import { renderHook, waitFor, act } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useDeleteMetaProfile } from "#/hooks/mutation/use-delete-meta-profile";
import MetaProfilesService from "#/api/meta-profiles-service/meta-profiles-service.api";
+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";
import SettingsService from "#/api/settings-service/settings-service.api";
import {
META_PROFILES_QUERY_KEYS,
@@ -12,6 +13,21 @@ import {
vi.mock("#/api/meta-profiles-service/meta-profiles-service.api");
vi.mock("#/api/settings-service/settings-service.api");
+vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({
+ __esModule: true,
+ default: { listProfiles: vi.fn(), getProfile: vi.fn(), saveProfile: vi.fn() },
+}));
+
+const openHands = (name: string, router: string | null) => ({
+ id: `id-${name}`,
+ name,
+ revision: 1,
+ agent_kind: "openhands",
+ llm_profile_ref: "llm",
+ mcp_server_refs: null,
+ meta_profile_ref: router,
+ enable_classify_and_switch_llm_tool: router !== null,
+});
describe("useDeleteMetaProfile", () => {
let queryClient: QueryClient;
@@ -22,6 +38,10 @@ describe("useDeleteMetaProfile", () => {
}) => React.ReactElement;
beforeEach(() => {
+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({
+ profiles: [],
+ active_agent_profile_id: null,
+ } as never);
queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
@@ -41,6 +61,50 @@ describe("useDeleteMetaProfile", () => {
vi.clearAllMocks();
});
+ it("detaches the router from the local agent profiles that use it, first", async () => {
+ const profiles = [
+ openHands("uses-it", "balanced"),
+ openHands("other-router", "cheap"),
+ ];
+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({
+ profiles: [
+ ...profiles,
+ { id: "id-acp", name: "acp", agent_kind: "acp", revision: 1 },
+ ],
+ active_agent_profile_id: "id-uses-it",
+ } as never);
+ vi.mocked(AgentProfilesService.getProfile).mockImplementation(
+ async (name) =>
+ ({
+ name,
+ profile: profiles.find((profile) => profile.name === name),
+ }) as never,
+ );
+ vi.mocked(MetaProfilesService.deleteMetaProfile).mockImplementation(
+ async () => {
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledTimes(1);
+ return { name: "balanced", message: "deleted" };
+ },
+ );
+
+ const { result } = renderHook(() => useDeleteMetaProfile(), { wrapper });
+ await act(async () => {
+ await result.current.mutateAsync("balanced");
+ });
+
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledWith(
+ "uses-it",
+ expect.objectContaining({
+ meta_profile_ref: null,
+ enable_classify_and_switch_llm_tool: false,
+ llm_profile_ref: "llm",
+ }),
+ );
+ expect(MetaProfilesService.deleteMetaProfile).toHaveBeenCalledWith(
+ "balanced",
+ );
+ });
+
it("calls MetaProfilesService.deleteMetaProfile with name", async () => {
vi.mocked(MetaProfilesService.deleteMetaProfile).mockResolvedValue({
name: "balanced",
diff --git a/__tests__/hooks/mutation/use-new-conversation-command.test.tsx b/__tests__/hooks/mutation/use-new-conversation-command.test.tsx
index 9927a3ba4c..7d9a4471d7 100644
--- a/__tests__/hooks/mutation/use-new-conversation-command.test.tsx
+++ b/__tests__/hooks/mutation/use-new-conversation-command.test.tsx
@@ -223,10 +223,13 @@ describe("useNewConversationCommand", () => {
// Assert — only sandbox_id travels; parent_conversation_id and agent_type
// stay undefined because /new is NOT a sub-conversation.
await waitFor(() => {
- expect(createSpy).toHaveBeenCalledWith({
- sandboxId: "sandbox-abc",
- });
+ expect(createSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ sandboxId: "sandbox-abc" }),
+ );
});
+ const [options] = createSpy.mock.lastCall ?? [];
+ expect(options).not.toHaveProperty("parentConversationId");
+ expect(options).not.toHaveProperty("agentType");
});
it("launches the active agent profile rather than the global settings", async () => {
diff --git a/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx b/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx
index 33b552bf18..889de195b7 100644
--- a/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx
+++ b/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx
@@ -45,6 +45,21 @@ vi.mock("#/hooks/chat/model-command-event-anchor", () => ({
getLastRenderableEventId: () => "evt-9",
}));
+const updateDefaultAgentProfileMock = vi.hoisted(() => vi.fn());
+vi.mock("#/hooks/mutation/sync-agent-profiles", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/mutation/sync-agent-profiles")
+ >()),
+ updateDefaultAgentProfile: updateDefaultAgentProfileMock,
+}));
+
+/** The `default` fields the sync would change, from a stored LLM ref. */
+const mirroredFrom = (llmProfileRef: string) => {
+ expect(updateDefaultAgentProfileMock).toHaveBeenCalledOnce();
+ const [, change] = updateDefaultAgentProfileMock.mock.calls[0];
+ return change({ agent_kind: "openhands", llm_profile_ref: llmProfileRef });
+};
+
const renderSwitchHook = () => {
const queryClient = new QueryClient({
defaultOptions: {
@@ -95,6 +110,7 @@ describe("useSwitchLlmProfile", () => {
expect(invalidateQueriesSpy).toHaveBeenCalledWith({
queryKey: SETTINGS_QUERY_KEYS.personal(),
});
+ expect(mirroredFrom("old")).toEqual({ llm_profile_ref: "my-profile" });
invalidateCacheSpy.mockRestore();
});
@@ -126,6 +142,7 @@ describe("useSwitchLlmProfile", () => {
expect(invalidateQueriesSpy).not.toHaveBeenCalledWith({
queryKey: SETTINGS_QUERY_KEYS.personal(),
});
+ expect(updateDefaultAgentProfileMock).not.toHaveBeenCalled();
invalidateCacheSpy.mockRestore();
});
diff --git a/__tests__/hooks/mutation/use-update-mcp-server.test.ts b/__tests__/hooks/mutation/use-update-mcp-server.test.ts
index e86ae1c166..c5f4182f02 100644
--- a/__tests__/hooks/mutation/use-update-mcp-server.test.ts
+++ b/__tests__/hooks/mutation/use-update-mcp-server.test.ts
@@ -13,6 +13,24 @@ import type { MCPServerConfig } from "#/types/mcp-server";
import { REDACTED_MCP_SECRET_VALUE } from "#/utils/mcp-config";
import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";
+const syncMocks = vi.hoisted(() => ({
+ updateDefaultAgentProfile: vi.fn(),
+ updateEveryAgentProfile: vi.fn(),
+}));
+vi.mock("#/hooks/mutation/sync-agent-profiles", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/mutation/sync-agent-profiles")
+ >()),
+ ...syncMocks,
+}));
+
+/** The `mcp_server_refs` the sync gives a profile restricted to these servers. */
+const syncedRefs = (refs: string[]) => {
+ expect(syncMocks.updateEveryAgentProfile).toHaveBeenCalledOnce();
+ const [, change] = syncMocks.updateEveryAgentProfile.mock.calls[0];
+ return change({ agent_kind: "openhands", mcp_server_refs: refs });
+};
+
const useSettingsMock = vi.fn();
vi.mock("#/hooks/query/use-settings", () => ({
useSettings: () => useSettingsMock(),
@@ -154,6 +172,48 @@ describe("useUpdateMcpServer", () => {
expect(serverSpy).not.toHaveBeenCalled();
});
+ it("renames the server in every profile that lists it", async () => {
+ vi.clearAllMocks();
+ vi.spyOn(SettingsService, "patchMcpConfig").mockResolvedValue(true);
+ const { result } = renderHook(() => useUpdateMcpServer(), {
+ wrapper: createWrapper(),
+ });
+
+ await result.current.mutateAsync({
+ serverId: "docs",
+ server: {
+ id: "docs",
+ type: "shttp",
+ name: "reference",
+ url: "https://docs.example/mcp",
+ },
+ });
+
+ expect(syncedRefs(["docs", "github"])).toEqual({
+ mcp_server_refs: ["reference", "github"],
+ });
+ });
+
+ it("leaves the default agent profile alone when the name stays", async () => {
+ vi.clearAllMocks();
+ vi.spyOn(SettingsService, "patchMcpServer").mockResolvedValue(true);
+ const { result } = renderHook(() => useUpdateMcpServer(), {
+ wrapper: createWrapper(),
+ });
+
+ await result.current.mutateAsync({
+ serverId: "docs",
+ server: {
+ id: "docs",
+ type: "shttp",
+ name: "docs",
+ url: "https://docs.example/v2/mcp",
+ },
+ });
+
+ expect(syncMocks.updateEveryAgentProfile).not.toHaveBeenCalled();
+ });
+
it("rejects a rename collision before issuing a request", async () => {
const configSpy = vi.spyOn(SettingsService, "patchMcpConfig");
const serverSpy = vi.spyOn(SettingsService, "patchMcpServer");
diff --git a/__tests__/hooks/use-active-agent-profile.test.tsx b/__tests__/hooks/use-active-agent-profile.test.tsx
index b57290d6d5..f38e9af77b 100644
--- a/__tests__/hooks/use-active-agent-profile.test.tsx
+++ b/__tests__/hooks/use-active-agent-profile.test.tsx
@@ -7,9 +7,10 @@ import { useAcpModelContext } from "#/hooks/use-acp-model-context";
import { resolveConversationLaunch } from "#/hooks/mutation/resolve-conversation-launch";
import { AGENT_PROFILES_QUERY_KEYS } from "#/hooks/query/query-keys";
-const { listProfilesMock, settingsKind } = vi.hoisted(() => ({
+const { listProfilesMock, settingsKind, backendKind } = vi.hoisted(() => ({
listProfilesMock: vi.fn(),
settingsKind: { value: "openhands" as "openhands" | "acp" },
+ backendKind: { value: "local" as "local" | "cloud" },
}));
vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({
@@ -26,12 +27,9 @@ vi.mock("#/api/profiles-service/profiles-service.api", () => ({
}),
},
}));
-vi.mock("#/api/agent-server-adapter", () => ({
- backendSupportsLaunchLlmOverride: vi.fn().mockResolvedValue(true),
-}));
vi.mock("#/contexts/active-backend-context", () => ({
useActiveBackend: () => ({
- backend: { id: "local-1", kind: "local" },
+ backend: { id: "local-1", kind: backendKind.value },
orgId: null,
}),
}));
@@ -40,6 +38,10 @@ vi.mock("#/hooks/query/use-settings", () => ({
data: { agent_settings: { agent_kind: settingsKind.value } },
}),
}));
+// Covered by its own tests; here the launch only needs it resolved.
+vi.mock("#/hooks/use-migrate-default-agent-profile", () => ({
+ ensureDefaultAgentProfileMigrated: vi.fn().mockResolvedValue(true),
+}));
vi.mock("#/hooks/query/use-active-conversation", () => ({
useActiveConversation: () => ({ data: undefined }),
}));
@@ -80,13 +82,14 @@ const launch = (queryClient: QueryClient) =>
queryClient,
backendId: "local-1",
orgId: null,
- isCloud: false,
+ isCloud: backendKind.value === "cloud",
});
describe("active agent profile after a failed refetch", () => {
afterEach(() => {
listProfilesMock.mockReset();
settingsKind.value = "openhands";
+ backendKind.value = "local";
});
it("keeps cached data across a failed refetch, and the launch agrees", async () => {
@@ -138,8 +141,24 @@ describe("active agent profile after a failed refetch", () => {
await expect(launch(queryClient)).rejects.toThrow("network down");
});
- it("uses global settings when no profile is active", async () => {
+ it("leaves the agent kind unknown when a local server has no active profile", async () => {
+ const queryClient = new QueryClient();
+ settingsKind.value = "acp";
+ listProfilesMock.mockResolvedValue({
+ profiles: [OPENHANDS],
+ active_agent_profile_id: null,
+ });
+ const { result } = renderActiveAgent(queryClient);
+
+ await waitFor(() => expect(result.current.active.isLoading).toBe(false));
+ expect(result.current.active.agentKind).toBeUndefined();
+ expect(result.current.acp.isHomeAcp).toBe(false);
+ await expect(launch(queryClient)).rejects.toThrow();
+ });
+
+ it("uses global settings on Cloud when no profile is active", async () => {
const queryClient = new QueryClient();
+ backendKind.value = "cloud";
settingsKind.value = "acp";
listProfilesMock.mockResolvedValue({
profiles: [OPENHANDS],
@@ -147,7 +166,6 @@ describe("active agent profile after a failed refetch", () => {
});
const { result } = renderActiveAgent(queryClient);
- await waitFor(() => expect(listProfilesMock).toHaveBeenCalled());
await waitFor(() => expect(result.current.active.isLoading).toBe(false));
expect(result.current.active.agentKind).toBe("acp");
expect(result.current.acp.isHomeAcp).toBe(true);
diff --git a/__tests__/hooks/use-chat-input-llm-profile-state.test.tsx b/__tests__/hooks/use-chat-input-llm-profile-state.test.tsx
index 0799144ffc..9d1a5f3549 100644
--- a/__tests__/hooks/use-chat-input-llm-profile-state.test.tsx
+++ b/__tests__/hooks/use-chat-input-llm-profile-state.test.tsx
@@ -34,6 +34,21 @@ vi.mock("#/hooks/use-can-manage-org-profiles", () => ({
useCanManageOrgProfiles: () => useCanManageOrgProfilesMock(),
}));
+const useAgentProfilesMock = vi.fn();
+vi.mock("#/hooks/query/use-agent-profiles", () => ({
+ useAgentProfiles: () => useAgentProfilesMock(),
+}));
+vi.mock("#/contexts/active-backend-context", () => ({
+ useActiveBackend: () => ({ backend: { id: "b1", kind: "local" } }),
+}));
+const updateAgentProfileMock = vi.hoisted(() => vi.fn());
+vi.mock("#/hooks/mutation/sync-agent-profiles", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/mutation/sync-agent-profiles")
+ >()),
+ updateAgentProfile: updateAgentProfileMock,
+}));
+
// eslint-disable-next-line import/first
import { useChatInputLlmProfileState } from "#/hooks/use-chat-input-llm-profile-state";
@@ -68,6 +83,58 @@ describe("useChatInputLlmProfileState", () => {
useCanManageOrgProfilesMock.mockReset();
// Local backends always own their profiles.
useCanManageOrgProfilesMock.mockReturnValue(true);
+ useAgentProfilesMock.mockReturnValue({ data: undefined });
+ updateAgentProfileMock.mockReset();
+ });
+
+ const activeAgent = (name: string, llmProfileRef: string) =>
+ useAgentProfilesMock.mockReturnValue({
+ data: {
+ profiles: [
+ {
+ id: `id-${name}`,
+ name,
+ agent_kind: "openhands",
+ llm_profile_ref: llmProfileRef,
+ },
+ ],
+ active_agent_profile_id: `id-${name}`,
+ },
+ });
+
+ it("shows the active agent profile's own LLM on the home page", () => {
+ useOptionalConversationIdMock.mockReturnValue({ conversationId: null });
+ activeAgent("reviewer", "Smart");
+
+ const { result } = renderState();
+
+ expect(result.current.currentProfileName).toBe("Smart");
+ });
+
+ it("saves a home pick as a named agent profile's own LLM", () => {
+ useOptionalConversationIdMock.mockReturnValue({ conversationId: null });
+ activeAgent("reviewer", "Smart");
+
+ const { result } = renderState();
+ result.current.selectProfile("Fast");
+
+ expect(switchAndLog).not.toHaveBeenCalled();
+ const [, name, change] = updateAgentProfileMock.mock.calls[0];
+ expect(name).toBe("reviewer");
+ expect(
+ change({ agent_kind: "openhands", llm_profile_ref: "Smart" }),
+ ).toEqual({ llm_profile_ref: "Fast" });
+ });
+
+ it("activates a home pick account-wide while default is active", () => {
+ useOptionalConversationIdMock.mockReturnValue({ conversationId: null });
+ activeAgent("default", "Fast");
+
+ const { result } = renderState();
+ result.current.selectProfile("Smart");
+
+ expect(updateAgentProfileMock).not.toHaveBeenCalled();
+ expect(switchAndLog).toHaveBeenCalledWith(null, "Smart");
});
it("prefers the profile stamped on the conversation over a model match", () => {
diff --git a/__tests__/hooks/use-llm-configured.test.tsx b/__tests__/hooks/use-llm-configured.test.tsx
index 372220eb1b..9975e11240 100644
--- a/__tests__/hooks/use-llm-configured.test.tsx
+++ b/__tests__/hooks/use-llm-configured.test.tsx
@@ -70,29 +70,9 @@ describe("useLlmConfigured (local, agent-profile-driven)", () => {
},
});
- it("is configured when the LLM profile the AGENT profile references has a key", () => {
- useLlmProfilesMock.mockReturnValue(
- llmProfiles("default", [
- { name: "default", api_key_set: false },
- { name: "sonnet", api_key_set: true },
- ]),
- );
- useActiveAgentProfileMock.mockReturnValue({
- activeProfile: {
- agent_kind: "openhands",
- llm_profile_ref: "sonnet",
- name: "MyOH",
- },
- });
-
- const { result } = renderHook(() => useLlmConfigured(), { wrapper });
- expect(result.current.isConfigured).toBe(true);
- });
-
- it("is NOT configured when the referenced profile has no key, even if the active LLM profile has one", () => {
- // Discriminating case: the standalone active LLM profile ("default") HAS a
- // key, but the active agent profile references "sonnet", which does not.
- // Conversations launch from the agent profile, so the ref is what matters.
+ it("is NOT configured when the agent profile's own LLM, which a home launch runs, has no key", () => {
+ // Discriminating case: the active LLM profile ("default") has a key, but
+ // the launch runs the agent profile's own ref ("sonnet"), which has none.
useLlmProfilesMock.mockReturnValue(
llmProfiles("default", [
{ name: "default", api_key_set: true },
@@ -110,21 +90,17 @@ describe("useLlmConfigured (local, agent-profile-driven)", () => {
const { result } = renderHook(() => useLlmConfigured(), { wrapper });
expect(result.current.isConfigured).toBe(false);
});
-
- it("falls back to the active LLM profile when the ref is stale (matches the launch fallback)", () => {
- // The agent profile references "ghost", which no longer exists in the list
- // (deleted profile / seed ref pointing at a named profile that was never
- // created). The launch path drops a stale-ref profile launch to an
- // agent_settings launch on the active LLM ("default", which HAS a key), so
- // this hook must report configured too — otherwise the composer is
- // spuriously disabled even though launch succeeds (VascoSch92 review #1571).
+ it("is configured when the agent profile's own LLM has a key, even if the active LLM profile has none", () => {
useLlmProfilesMock.mockReturnValue(
- llmProfiles("default", [{ name: "default", api_key_set: true }]),
+ llmProfiles("default", [
+ { name: "default", api_key_set: false },
+ { name: "sonnet", api_key_set: true },
+ ]),
);
useActiveAgentProfileMock.mockReturnValue({
activeProfile: {
agent_kind: "openhands",
- llm_profile_ref: "ghost",
+ llm_profile_ref: "sonnet",
name: "MyOH",
},
});
@@ -132,48 +108,65 @@ describe("useLlmConfigured (local, agent-profile-driven)", () => {
const { result } = renderHook(() => useLlmConfigured(), { wrapper });
expect(result.current.isConfigured).toBe(true);
});
-
- it("is configured for the local seeded `default` agent profile when its ref is unauthenticated (matches the agent_settings launch)", () => {
- // #16193: "B" EXISTS (so the stale-ref fallback above doesn't fire) but has
- // no key. `default` launches via `agent_settings` on the active LLM "A".
+ it("checks the active LLM profile for `default`, which a local launch runs", () => {
useLlmProfilesMock.mockReturnValue(
- llmProfiles("A", [
- { name: "A", api_key_set: true },
- { name: "B", api_key_set: false },
+ llmProfiles("active", [
+ { name: "active", api_key_set: false },
+ { name: "sonnet", api_key_set: true },
]),
);
useActiveAgentProfileMock.mockReturnValue({
activeProfile: {
agent_kind: "openhands",
- llm_profile_ref: "B",
+ llm_profile_ref: "sonnet",
name: "default",
},
});
const { result } = renderHook(() => useLlmConfigured(), { wrapper });
- expect(result.current.isConfigured).toBe(true);
+ expect(result.current.isConfigured).toBe(false);
});
-
- it("is NOT configured for the local seeded `default` profile when the active LLM profile has no key either", () => {
- // The fallback must still validate: nothing here is usable.
+ it("checks the active LLM profile when the agent profile's ref is stale", () => {
+ // The agent profile references "ghost", which no longer exists; the launch
+ // runs the active LLM profile ("default", which HAS a key) instead.
useLlmProfilesMock.mockReturnValue(
- llmProfiles("A", [
- { name: "A", api_key_set: false },
- { name: "B", api_key_set: false },
- ]),
+ llmProfiles("default", [{ name: "default", api_key_set: true }]),
);
useActiveAgentProfileMock.mockReturnValue({
activeProfile: {
agent_kind: "openhands",
- llm_profile_ref: "B",
- name: "default",
+ llm_profile_ref: "ghost",
+ name: "MyOH",
},
});
const { result } = renderHook(() => useLlmConfigured(), { wrapper });
- expect(result.current.isConfigured).toBe(false);
+ expect(result.current.isConfigured).toBe(true);
});
-
+ it.each([
+ [true, true],
+ [false, false],
+ ])(
+ "falls back to the agent profile's ref when no LLM profile is active (key set: %s)",
+ (keySet, expected) => {
+ useLlmProfilesMock.mockReturnValue({
+ data: {
+ active_profile: null,
+ profiles: [{ name: "B", model: "m", api_key_set: keySet }],
+ },
+ });
+ useActiveAgentProfileMock.mockReturnValue({
+ activeProfile: {
+ agent_kind: "openhands",
+ llm_profile_ref: "B",
+ name: "default",
+ },
+ });
+
+ const { result } = renderHook(() => useLlmConfigured(), { wrapper });
+ expect(result.current.isConfigured).toBe(expected);
+ },
+ );
it("is configured for an ACP agent profile regardless of LLM keys", () => {
useLlmProfilesMock.mockReturnValue(
llmProfiles("default", [{ name: "default", api_key_set: false }]),
diff --git a/__tests__/hooks/use-migrate-default-agent-profile.test.ts b/__tests__/hooks/use-migrate-default-agent-profile.test.ts
new file mode 100644
index 0000000000..4dd33e03d5
--- /dev/null
+++ b/__tests__/hooks/use-migrate-default-agent-profile.test.ts
@@ -0,0 +1,262 @@
+import { QueryClient } from "@tanstack/react-query";
+import { DEFAULT_ENABLED_SKILL_NAMES } from "@openhands/extensions/skills";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";
+import ProfilesService from "#/api/profiles-service/profiles-service.api";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import {
+ buildDefaultProfileMigration,
+ ensureDefaultAgentProfileMigrated,
+ settleRunningDefaultAgentProfileMigration,
+} from "#/hooks/use-migrate-default-agent-profile";
+import { DEFAULT_SETTINGS } from "#/services/settings";
+import type { Settings } from "#/types/settings";
+import { CATALOG_SKILL_NAMES } from "#/utils/skill-enablement";
+
+vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({
+ __esModule: true,
+ default: {
+ listProfiles: vi.fn(),
+ getProfile: vi.fn(),
+ saveProfile: vi.fn(),
+ },
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME: "default",
+}));
+vi.mock("#/api/profiles-service/profiles-service.api", () => ({
+ __esModule: true,
+ default: { listProfiles: vi.fn() },
+}));
+vi.mock("#/api/settings-service/settings-service.api", () => ({
+ __esModule: true,
+ default: {
+ getSettings: vi.fn(),
+ saveSettings: vi.fn(),
+ invalidateCache: vi.fn(),
+ },
+}));
+
+const GLOBAL_AGENT = {
+ agent_kind: "openhands",
+ agent: "CodeActAgent",
+ persona: "You review code.",
+ tools: [{ name: "terminal", params: {} }],
+ tool_concurrency_limit: 3,
+ agent_context: { system_message_suffix: "Be terse.", load_memory: true },
+ condenser: {
+ condenser_kind: "llm_summarizing",
+ enabled: false,
+ max_size: 80,
+ },
+ verification: {
+ critic_enabled: true,
+ critic_mode: "all_actions",
+ enable_iterative_refinement: false,
+ critic_threshold: 0.7,
+ max_refinement_iterations: 2,
+ critic_server_url: null,
+ critic_model_name: null,
+ critic_api_key: "**********",
+ },
+ enable_classify_and_switch_llm_tool: true,
+ active_meta_profile: "router",
+};
+
+const settingsWith = (overrides: Partial<Settings> = {}): Settings => ({
+ ...DEFAULT_SETTINGS,
+ agent_settings: GLOBAL_AGENT,
+ enabled_skills: ["github", "docker"],
+ disabled_skills: ["my-user-skill"],
+ ...overrides,
+});
+
+const STORED_DEFAULT = {
+ id: "profile-default",
+ name: "default",
+ revision: 4,
+ agent_kind: "openhands",
+ llm_profile_ref: "my-llm",
+ mcp_server_refs: ["linear"],
+ secret_refs: ["GITHUB_TOKEN"],
+ persona: null,
+ tools: null,
+};
+
+describe("buildDefaultProfileMigration", () => {
+ it("copies the global behavior the inline launch used, without the critic key", () => {
+ expect(buildDefaultProfileMigration(settingsWith())).toEqual({
+ public_skills: ["github", "docker"],
+ disabled_skills: ["my-user-skill"],
+ condenser: GLOBAL_AGENT.condenser,
+ verification: {
+ critic_enabled: true,
+ critic_mode: "all_actions",
+ enable_iterative_refinement: false,
+ critic_threshold: 0.7,
+ max_refinement_iterations: 2,
+ critic_server_url: null,
+ critic_model_name: null,
+ },
+ tools: GLOBAL_AGENT.tools,
+ persona: "You review code.",
+ agent: "CodeActAgent",
+ tool_concurrency_limit: 3,
+ system_message_suffix: "Be terse.",
+ enable_classify_and_switch_llm_tool: true,
+ meta_profile_ref: "router",
+ });
+ });
+
+ it("turns a pre-allow-list deny-list into the skill selection it meant", () => {
+ const migrated = buildDefaultProfileMigration(
+ settingsWith({
+ enabled_skills: undefined,
+ disabled_skills: [CATALOG_SKILL_NAMES[0], "my-user-skill"],
+ }),
+ );
+
+ expect(migrated.public_skills).toEqual(CATALOG_SKILL_NAMES.slice(1));
+ expect(migrated.disabled_skills).toEqual(["my-user-skill"]);
+ });
+
+ it("gives a fresh workspace the recommended skills", () => {
+ const migrated = buildDefaultProfileMigration(
+ settingsWith({ enabled_skills: undefined, disabled_skills: [] }),
+ );
+
+ expect(migrated.public_skills).toEqual([...DEFAULT_ENABLED_SKILL_NAMES]);
+ });
+
+ it("carries only the skills when global settings are left on ACP", () => {
+ const migrated = buildDefaultProfileMigration(
+ settingsWith({
+ agent_settings: { agent_kind: "acp", acp_server: "codex" },
+ }),
+ );
+
+ expect(migrated).toEqual({
+ public_skills: ["github", "docker"],
+ disabled_skills: ["my-user-skill"],
+ });
+ });
+});
+
+describe("ensureDefaultAgentProfileMigrated", () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(SettingsService.getSettings).mockResolvedValue(settingsWith());
+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({
+ profiles: [STORED_DEFAULT],
+ active_agent_profile_id: STORED_DEFAULT.id,
+ } as never);
+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
+ name: "default",
+ profile: STORED_DEFAULT,
+ } as never);
+ vi.mocked(ProfilesService.listProfiles).mockResolvedValue({
+ profiles: [],
+ active_profile: "active-llm",
+ } as never);
+ });
+
+ it("merges the global behavior into `default` and records it once", async () => {
+ const queryClient = new QueryClient();
+
+ await ensureDefaultAgentProfileMigrated(queryClient, "local-1");
+ await ensureDefaultAgentProfileMigrated(queryClient, "local-1");
+
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledTimes(1);
+ const [name, saved] = vi.mocked(AgentProfilesService.saveProfile).mock
+ .calls[0];
+ expect(name).toBe("default");
+ expect(saved).toMatchObject({
+ // `default` shares these with the global pages.
+ llm_profile_ref: "active-llm",
+ mcp_server_refs: null,
+ secret_refs: null,
+ // What `default` used to take from global settings moves onto it.
+ persona: "You review code.",
+ tools: GLOBAL_AGENT.tools,
+ public_skills: ["github", "docker"],
+ meta_profile_ref: "router",
+ });
+ expect(saved).not.toHaveProperty("id");
+ expect(SettingsService.saveSettings).toHaveBeenCalledWith({
+ default_profile_migrated: true,
+ });
+ });
+
+ it("does nothing once the backend is marked migrated", async () => {
+ vi.mocked(SettingsService.getSettings).mockResolvedValue(
+ settingsWith({ default_profile_migrated: true }),
+ );
+
+ await ensureDefaultAgentProfileMigrated(new QueryClient(), "local-1");
+
+ expect(AgentProfilesService.listProfiles).not.toHaveBeenCalled();
+ expect(AgentProfilesService.saveProfile).not.toHaveBeenCalled();
+ });
+
+ it("leaves an ACP `default`, which already launched as stored, alone", async () => {
+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({
+ profiles: [{ ...STORED_DEFAULT, agent_kind: "acp" }],
+ active_agent_profile_id: STORED_DEFAULT.id,
+ } as never);
+
+ await ensureDefaultAgentProfileMigrated(new QueryClient(), "local-1");
+
+ expect(AgentProfilesService.saveProfile).not.toHaveBeenCalled();
+ expect(SettingsService.saveSettings).toHaveBeenCalledWith({
+ default_profile_migrated: true,
+ });
+ });
+
+ it("leaves the marker unset when the save fails, so a later call retries", async () => {
+ const queryClient = new QueryClient();
+ vi.mocked(AgentProfilesService.saveProfile).mockRejectedValueOnce(
+ new Error("boom"),
+ );
+
+ await expect(
+ ensureDefaultAgentProfileMigrated(queryClient, "local-1"),
+ ).rejects.toThrow("boom");
+ expect(SettingsService.saveSettings).not.toHaveBeenCalled();
+
+ await ensureDefaultAgentProfileMigrated(queryClient, "local-1");
+ expect(SettingsService.saveSettings).toHaveBeenCalledTimes(1);
+ });
+
+ it("never starts the migration when only waiting on it", async () => {
+ await settleRunningDefaultAgentProfileMigration(
+ new QueryClient(),
+ "local-1",
+ );
+
+ expect(SettingsService.getSettings).not.toHaveBeenCalled();
+ });
+
+ it("waits for a migration already running", async () => {
+ const queryClient = new QueryClient();
+ let release: (settings: Settings) => void = () => undefined;
+ vi.mocked(SettingsService.getSettings).mockReturnValueOnce(
+ new Promise((resolve) => {
+ release = resolve;
+ }),
+ );
+ const running = ensureDefaultAgentProfileMigrated(queryClient, "local-1");
+ let settled = false;
+ const waiting = settleRunningDefaultAgentProfileMigration(
+ queryClient,
+ "local-1",
+ ).then(() => {
+ settled = true;
+ });
+
+ await new Promise((resolve) => {
+ setTimeout(resolve, 10);
+ });
+ expect(settled).toBe(false);
+ release(settingsWith({ default_profile_migrated: true }));
+ await Promise.all([running, waiting]);
+ expect(settled).toBe(true);
+ });
+});
diff --git a/__tests__/hooks/use-settings-nav-items.test.tsx b/__tests__/hooks/use-settings-nav-items.test.tsx
index 2b95fc2b1a..6ff7842ba7 100644
--- a/__tests__/hooks/use-settings-nav-items.test.tsx
+++ b/__tests__/hooks/use-settings-nav-items.test.tsx
@@ -168,11 +168,7 @@ describe("useSettingsNavItems", () => {
),
);
- for (const path of [
- "/settings/llm",
- "/settings/condenser",
- "/settings/verification",
- ]) {
+ for (const path of ["/settings/llm", "/settings/verification"]) {
const renderedItem = byPath.get(path);
expect(renderedItem).toEqual({
type: "item",
@@ -181,6 +177,22 @@ describe("useSettingsNavItems", () => {
}
});
+ it("lists the Condenser page only on cloud backends", () => {
+ useConfigMock.mockReturnValue({ data: createConfig() });
+ const paths = () =>
+ renderHook(() => useSettingsNavItems()).result.current.map((item) =>
+ item.type === "item" ? item.item.to : null,
+ );
+
+ expect(paths()).not.toContain("/settings/condenser");
+
+ useActiveBackendMock.mockReturnValue({
+ backend: { kind: "cloud" },
+ orgId: null,
+ });
+ expect(paths()).toContain("/settings/condenser");
+ });
+
it("lists only the Application page when the canvas is locked to a Cloud host", () => {
// Arrange — SaaS / self-hosted OHE serve the canvas with `--lock-to-cloud`;
// the OHE settings shell ("All Cloud Settings") owns every other page.
diff --git a/__tests__/routes/agent-settings-tool-selection.test.tsx b/__tests__/routes/agent-settings-tool-selection.test.tsx
index 4dbfd97bf0..2a00a24538 100644
--- a/__tests__/routes/agent-settings-tool-selection.test.tsx
+++ b/__tests__/routes/agent-settings-tool-selection.test.tsx
@@ -279,36 +279,3 @@ it("hides tools on a cloud backend and leaves the stored selection alone", async
expect(ToolCatalogService.getCatalog).not.toHaveBeenCalled();
expect(control!.buildAgentProfileFields()).not.toHaveProperty("tools");
});
-
-it("points the default profile to a named profile instead of offering tools", async () => {
- let control: AgentSettingsSaveControl | null = null;
- render(
- <MemoryRouter>
- <QueryClientProvider
- client={
- new QueryClient({ defaultOptions: { queries: { retry: false } } })
- }
- >
- <AgentSettingsScreen
- agentSettingsOverride={{
- agent_kind: "openhands",
- tools: [{ name: "terminal", params: {} }],
- }}
- onSaveControlChange={(next) => {
- control = next;
- }}
- isDefaultProfile
- />
- </QueryClientProvider>
- </MemoryRouter>,
- );
-
- expect(
- await screen.findByTestId("agent-settings-tools-default-profile"),
- ).toHaveTextContent("SETTINGS$AGENT_PROFILE_TOOLS_DEFAULT_PROFILE");
- expect(
- screen.queryByTestId("agent-settings-tools-mode"),
- ).not.toBeInTheDocument();
- expect(ToolCatalogService.getCatalog).not.toHaveBeenCalled();
- expect(control!.buildAgentProfileFields()).not.toHaveProperty("tools");
-});
diff --git a/__tests__/routes/agent-settings.test.tsx b/__tests__/routes/agent-settings.test.tsx
index 604977afdf..14db7fe4e9 100644
--- a/__tests__/routes/agent-settings.test.tsx
+++ b/__tests__/routes/agent-settings.test.tsx
@@ -1419,6 +1419,118 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {
screen.getByTestId("agent-settings-secrets-mode"),
).toBeInTheDocument();
});
+
+ it("keeps the secrets picker on an ACP default", async () => {
+ seedOpenHandsSettings();
+ renderAgentSettingsScreen({
+ agentSettingsOverride: {
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ acp_command: [...CLAUDE_COMMAND],
+ acp_args: [],
+ acp_model: "",
+ secret_refs: ["PROD_DB_URL"],
+ },
+ isDefaultProfile: true,
+ });
+ await screen.findByTestId("agent-settings-screen");
+
+ expect(
+ screen.getByTestId("agent-settings-secrets-mode"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("agent-settings-secrets-default-note"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("agent-settings-mcp-default-note"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("moves an ACP default switched to OpenHands onto the MCP page's switches", async () => {
+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
+ buildSettings({
+ agent_settings: {
+ ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,
+ agent_kind: "openhands",
+ mcp_config: {
+ github: { transport: "http", url: "https://github.example/mcp" },
+ slack: {
+ transport: "http",
+ url: "https://slack.example/mcp",
+ enabled: false,
+ },
+ },
+ },
+ }),
+ );
+ let control: AgentSettingsSaveControl | null = null;
+ renderAgentSettingsScreen({
+ agentSettingsOverride: {
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ acp_command: [...CLAUDE_COMMAND],
+ acp_args: [],
+ acp_model: "",
+ mcp_server_refs: ["slack"],
+ secret_refs: ["PROD_DB_URL"],
+ },
+ isDefaultProfile: true,
+ onSaveControlChange: (next) => {
+ control = next;
+ },
+ });
+ await screen.findByTestId("agent-command-input");
+ expect(control!.buildAgentProfileFields()).toMatchObject({
+ mcp_server_refs: ["slack"],
+ });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByTestId("agent-type-selector"));
+ await user.click(
+ await screen.findByRole("option", {
+ name: "SETTINGS$AGENT_TYPE_OPENHANDS",
+ }),
+ );
+
+ await waitFor(() =>
+ expect(control!.buildAgentProfileFields()).toMatchObject({
+ agent_kind: "openhands",
+ mcp_server_refs: ["github"],
+ }),
+ );
+ expect(
+ screen.queryByTestId("agent-settings-secrets-mode"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByTestId("agent-settings-mcp-default-note"),
+ ).toBeInTheDocument();
+ });
+
+ it("gives the default profile every secret, with no picker", async () => {
+ seedOpenHandsSettings();
+ let control: AgentSettingsSaveControl | null = null;
+ renderAgentSettingsScreen({
+ agentSettingsOverride: { agent_kind: "openhands", secret_refs: null },
+ isDefaultProfile: true,
+ onSaveControlChange: (next) => {
+ control = next;
+ },
+ });
+ await screen.findByTestId("agent-settings-screen");
+
+ expect(
+ screen.queryByTestId("agent-settings-secrets-mode"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByTestId("agent-settings-secrets-default-note"),
+ ).toHaveTextContent("SETTINGS$AGENT_PROFILE_DEFAULT_SECRETS_NOTE");
+ expect(
+ screen.getByTestId("agent-settings-mcp-default-note"),
+ ).toHaveTextContent("SETTINGS$AGENT_PROFILE_DEFAULT_MCP_NOTE");
+ expect(control!.buildAgentProfileFields()).toMatchObject({
+ secret_refs: null,
+ });
+ });
});
});
@@ -1471,6 +1583,81 @@ describe("AgentSettingsScreen — skills", () => {
});
});
+ it("filters a long skill list by name, description or trigger", async () => {
+ const many: SkillInfo[] = Array.from({ length: 12 }, (_, i) => ({
+ name: `skill-${i}`,
+ type: "knowledge" as const,
+ source: null,
+ origin: "public" as const,
+ description: i === 3 ? "Reviews pull requests" : null,
+ triggers: i === 7 ? ["deploy"] : [],
+ }));
+ vi.spyOn(SkillsService, "getSkillCatalog").mockResolvedValue(many);
+ renderAgentSettingsScreen({
+ agentSettingsOverride: {
+ agent_kind: "openhands",
+ public_skills: [],
+ disabled_skills: [],
+ },
+ });
+ const search = await screen.findByTestId("agent-settings-skills-search");
+ const user = userEvent.setup();
+
+ await user.type(search, "review");
+ expect(screen.getByTestId("agent-settings-skills-skill-3")).toBeVisible();
+ expect(
+ screen.queryByTestId("agent-settings-skills-skill-1"),
+ ).not.toBeInTheDocument();
+
+ await user.clear(search);
+ await user.type(search, "deploy");
+ expect(screen.getByTestId("agent-settings-skills-skill-7")).toBeVisible();
+ });
+
+ it("shows the LLM picker under the agent type for OpenHands only", async () => {
+ renderAgentSettingsScreen({
+ agentSettingsOverride: CLAUDE_PROFILE,
+ llmPicker: <div data-testid="llm-picker-slot" />,
+ });
+ await screen.findByTestId("agent-command-input");
+ expect(screen.queryByTestId("llm-picker-slot")).not.toBeInTheDocument();
+ });
+
+ it("puts the LLM picker right after the agent type", async () => {
+ renderAgentSettingsScreen({
+ agentSettingsOverride: { agent_kind: "openhands" },
+ llmPicker: <div data-testid="llm-picker-slot" />,
+ });
+ const slot = await screen.findByTestId("llm-picker-slot");
+ const agentType = screen.getByTestId("agent-type-selector");
+
+ expect(
+ agentType.compareDocumentPosition(slot) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(
+ slot.compareDocumentPosition(
+ screen.getByTestId("agent-settings-mcp-mode"),
+ ) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ it("tells the default profile its list is the Skills page", async () => {
+ renderAgentSettingsScreen({
+ agentSettingsOverride: {
+ agent_kind: "openhands",
+ public_skills: ["alpha"],
+ disabled_skills: [],
+ },
+ isDefaultProfile: true,
+ });
+ await screen.findByTestId("agent-settings-skills-alpha");
+
+ expect(
+ screen.getByTestId("agent-settings-skills-default-note"),
+ ).toHaveTextContent("SETTINGS$AGENT_PROFILE_DEFAULT_SKILLS_NOTE");
+ });
+
it("keeps a profile without a list unset until the user edits it", async () => {
let control: AgentSettingsSaveControl | null = null;
renderAgentSettingsScreen({
@@ -1518,31 +1705,6 @@ describe("AgentSettingsScreen — skills", () => {
"public_skills",
);
});
-
- it("points the default profile to the Skills page", async () => {
- let control: AgentSettingsSaveControl | null = null;
- renderAgentSettingsScreen({
- agentSettingsOverride: {
- agent_kind: "openhands",
- public_skills: ["alpha"],
- disabled_skills: [],
- },
- isDefaultProfile: true,
- onSaveControlChange: (next) => {
- control = next;
- },
- });
-
- expect(
- await screen.findByTestId("agent-settings-skills-default-profile"),
- ).toHaveTextContent("SETTINGS$AGENT_PROFILE_SKILLS_DEFAULT_PROFILE");
- expect(
- screen.queryByTestId("agent-settings-skills-list"),
- ).not.toBeInTheDocument();
- expect(control!.buildAgentProfileFields()).not.toHaveProperty(
- "public_skills",
- );
- });
});
describe("AgentSettingsScreen — condenser and verification", () => {
@@ -1607,69 +1769,6 @@ describe("AgentSettingsScreen — condenser and verification", () => {
screen.queryByTestId("sdk-settings-verification.critic_api_key"),
).not.toBeInTheDocument();
});
-
- it("points the default profile to the global pages", async () => {
- const { control } = renderAgentSettingsScreen({
- agentSettingsOverride: STORED,
- isDefaultProfile: true,
- });
-
- expect(
- await screen.findByTestId("agent-settings-condenser-default-profile"),
- ).toHaveTextContent("SETTINGS$AGENT_PROFILE_BEHAVIOR_DEFAULT_PROFILE");
- expect(
- screen.queryByTestId("sdk-settings-condenser.condenser_max_size"),
- ).not.toBeInTheDocument();
- expect(control().buildAgentProfileFields()).not.toHaveProperty("condenser");
- });
-
- it("lets the default profile edit its own values on a cloud backend", async () => {
- __resetActiveStoreForTests();
- setRegisteredBackends([
- {
- id: "cloud-1",
- name: "Cloud",
- host: "https://app.example.com",
- apiKey: "key",
- kind: "cloud",
- },
- ]);
- setActiveSelection({ backendId: "cloud-1", orgId: null });
- try {
- render(
- <AgentSettingsScreen
- agentSettingsOverride={STORED}
- isDefaultProfile
- onSaveControlChange={() => {}}
- />,
- {
- wrapper: ({ children }) => (
- <MemoryRouter>
- <QueryClientProvider
- client={
- new QueryClient({
- defaultOptions: { queries: { retry: false } },
- })
- }
- >
- <ActiveBackendProvider>{children}</ActiveBackendProvider>
- </QueryClientProvider>
- </MemoryRouter>
- ),
- },
- );
-
- expect(
- await screen.findByTestId("sdk-settings-condenser.condenser_max_size"),
- ).toHaveValue(100);
- expect(
- screen.queryByTestId("agent-settings-condenser-default-profile"),
- ).not.toBeInTheDocument();
- } finally {
- window.localStorage.clear();
- __resetActiveStoreForTests();
- }
- });
});
describe("AgentSettingsScreen — Model Router", () => {
@@ -1801,23 +1900,6 @@ describe("AgentSettingsScreen — Model Router", () => {
await screen.findByTestId("agent-settings-router-dangling"),
).toHaveTextContent("SETTINGS$AGENT_PROFILE_ROUTER_DANGLING");
});
-
- it("points the default profile to the Model Router page", async () => {
- const { control } = renderAgentSettingsScreen({
- agentSettingsOverride: WITH_ROUTER,
- isDefaultProfile: true,
- });
-
- expect(
- await screen.findByTestId("agent-settings-router-default-profile"),
- ).toHaveTextContent("SETTINGS$AGENT_PROFILE_ROUTER_DEFAULT_PROFILE");
- expect(
- screen.queryByTestId("agent-settings-router-select"),
- ).not.toBeInTheDocument();
- expect(control().buildAgentProfileFields()).not.toHaveProperty(
- "meta_profile_ref",
- );
- });
});
describe("AgentSettingsScreen — system prompt", () => {
@@ -1962,25 +2044,4 @@ describe("AgentSettingsScreen — system prompt", () => {
system_message_suffix: null,
});
});
-
- it("explains instead of editing on the default profile, and leaves both fields alone", async () => {
- const { control } = renderAgentSettingsScreen({
- agentSettingsOverride: {
- ...OPENHANDS_PROFILE,
- persona: "Set through the API.",
- system_message_suffix: "Also set through the API.",
- },
- isDefaultProfile: true,
- });
-
- expect(
- await screen.findByTestId("agent-settings-system-prompt-default-profile"),
- ).toBeInTheDocument();
- expect(
- screen.queryByTestId("agent-settings-system-prompt-mode"),
- ).not.toBeInTheDocument();
- const fields = control().buildAgentProfileFields();
- expect(fields).not.toHaveProperty("persona");
- expect(fields).not.toHaveProperty("system_message_suffix");
- });
});
diff --git a/__tests__/routes/root-layout.test.tsx b/__tests__/routes/root-layout.test.tsx
index 8a21933188..4d82e3d415 100644
--- a/__tests__/routes/root-layout.test.tsx
+++ b/__tests__/routes/root-layout.test.tsx
@@ -12,6 +12,7 @@ const useSettingsMock = vi.fn();
const changeLanguageMock = vi.fn();
const ensureActiveProfileMock = vi.fn();
const migrateEnabledSkillsMock = vi.fn();
+const migrateDefaultAgentProfileMock = vi.fn();
const syncTelemetryConsentMock = vi.fn();
const syncAutomationTelemetryConsentMock = vi.fn();
const telemetryIdentityMock = vi.fn();
@@ -29,6 +30,10 @@ vi.mock("#/hooks/use-migrate-enabled-skills", () => ({
useMigrateEnabledSkills: () => migrateEnabledSkillsMock(),
}));
+vi.mock("#/hooks/use-migrate-default-agent-profile", () => ({
+ useMigrateDefaultAgentProfile: () => migrateDefaultAgentProfileMock(),
+}));
+
vi.mock("#/hooks/use-sync-telemetry-consent", () => ({
useSyncTelemetryConsent: () => syncTelemetryConsentMock(),
}));
@@ -259,6 +264,7 @@ describe("root layout", () => {
expect(changeLanguageMock).toHaveBeenCalledWith("en");
expect(migrateEnabledSkillsMock).toHaveBeenCalledOnce();
+ expect(migrateDefaultAgentProfileMock).toHaveBeenCalledOnce();
expect(syncTelemetryConsentMock).toHaveBeenCalledOnce();
expect(syncAutomationTelemetryConsentMock).toHaveBeenCalledOnce();
expect(telemetryIdentityMock).toHaveBeenCalledOnce();
diff --git a/__tests__/routes/skills-settings.test.tsx b/__tests__/routes/skills-settings.test.tsx
index 180b2e1836..14dc533e7d 100644
--- a/__tests__/routes/skills-settings.test.tsx
+++ b/__tests__/routes/skills-settings.test.tsx
@@ -13,6 +13,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import SkillsSettingsScreen from "#/routes/skills-settings";
import SettingsService from "#/api/settings-service/settings-service.api";
import SkillsService from "#/api/skills-service";
+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";
+import { HttpError } from "@openhands/typescript-client";
import {
ADD_SKILL_DOCS_URL,
ADD_SKILL_EXAMPLE_COMMAND,
@@ -22,6 +24,27 @@ import { Settings, SkillInfo } from "#/types/settings";
import { ActiveBackendProvider } from "#/contexts/active-backend-context";
const navigateMock = vi.fn();
+let migrationState: {
+ isFetching: boolean;
+ isSuccess: boolean;
+ error: unknown;
+} = { isFetching: false, isSuccess: true, error: null };
+vi.mock(
+ "#/hooks/use-migrate-default-agent-profile",
+ async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/use-migrate-default-agent-profile")
+ >()),
+ useMigrateDefaultAgentProfile: () => migrationState,
+ }),
+);
+const updateDefaultAgentProfileMock = vi.hoisted(() => vi.fn());
+vi.mock("#/hooks/mutation/sync-agent-profiles", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/mutation/sync-agent-profiles")
+ >()),
+ updateDefaultAgentProfile: updateDefaultAgentProfileMock,
+}));
vi.mock("#/context/navigation-context", () => ({
useNavigation: () => ({
@@ -44,6 +67,12 @@ function buildSettings(overrides: Partial<Settings> = {}): Settings {
};
}
+// The local page lists the server catalog; Cloud lists its own skills.
+function mockSkillList(skills: SkillInfo[]) {
+ vi.spyOn(SkillsService, "getSkills").mockResolvedValue(skills);
+ vi.spyOn(SkillsService, "getSkillCatalog").mockResolvedValue(skills);
+}
+
function buildSkill(overrides: Partial<SkillInfo> = {}): SkillInfo {
return {
name: "deno",
@@ -64,7 +93,12 @@ function buildSkill(overrides: Partial<SkillInfo> = {}): SkillInfo {
};
}
-function renderSkillsSettingsScreen(initialEntry = "/skills") {
+function renderSkillsSettingsScreen(
+ initialEntry = "/skills",
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ }),
+) {
const router = createMemoryRouter(
[
{
@@ -81,15 +115,7 @@ function renderSkillsSettingsScreen(initialEntry = "/skills") {
render(<RouterProvider router={router} />, {
wrapper: ({ children }) => (
- <QueryClientProvider
- client={
- new QueryClient({
- defaultOptions: { queries: { retry: false } },
- })
- }
- >
- {children}
- </QueryClientProvider>
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
),
});
@@ -101,10 +127,15 @@ describe("SkillsSettingsScreen", () => {
vi.restoreAllMocks();
navigateMock.mockReset();
vi.spyOn(SettingsService, "getSettings").mockResolvedValue(buildSettings());
+ migrationState = { isFetching: false, isSuccess: true, error: null };
+ // No OpenHands `default`: the page keeps its lists in settings.
+ vi.spyOn(AgentProfilesService, "getProfile").mockRejectedValue(
+ new HttpError(404, "Not Found", {}, "missing"),
+ );
});
it("renders the description text inside the description badge", async () => {
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([]);
+ mockSkillList([]);
renderSkillsSettingsScreen();
@@ -136,7 +167,7 @@ description: Connect and run commands on remote machines over SSH.
Full skill body.`,
triggers: ["ssh"],
});
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([skill]);
+ mockSkillList([skill]);
renderSkillsSettingsScreen();
const card = await screen.findByTestId(`skill-card-${skill.name}`);
@@ -150,7 +181,7 @@ Full skill body.`,
it("surfaces the YAML description under the card title with the source path beneath it", async () => {
const skill = buildSkill();
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([skill]);
+ mockSkillList([skill]);
renderSkillsSettingsScreen();
const card = await screen.findByTestId(`skill-card-${skill.name}`);
@@ -174,7 +205,7 @@ Full skill body.`,
const skill = buildSkill();
const writeText = vi.fn().mockResolvedValue(undefined);
vi.spyOn(navigator.clipboard, "writeText").mockImplementation(writeText);
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([skill]);
+ mockSkillList([skill]);
renderSkillsSettingsScreen();
const card = await screen.findByTestId(`skill-card-${skill.name}`);
@@ -188,7 +219,7 @@ Full skill body.`,
it("hides the copy button when the source is a scope label instead of a path", async () => {
const skill = buildSkill({ name: "add_repo_inst", source: "global" });
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([skill]);
+ mockSkillList([skill]);
renderSkillsSettingsScreen();
const card = await screen.findByTestId(`skill-card-${skill.name}`);
@@ -202,7 +233,7 @@ Full skill body.`,
});
it("filters skills by name, description, or trigger via the search input", async () => {
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([
+ mockSkillList([
buildSkill({ name: "deno", description: "Deno runtime helper" }),
buildSkill({
name: "vercel",
@@ -225,7 +256,7 @@ Full skill body.`,
it("narrows the visible skills when a facet row is selected", async () => {
const user = userEvent.setup();
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([
+ mockSkillList([
buildSkill({ name: "deno", type: "knowledge" }),
buildSkill({
name: "global-rules",
@@ -246,7 +277,7 @@ Full skill body.`,
});
it("seeds the filter state from the URL on load", async () => {
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([
+ mockSkillList([
buildSkill({ name: "deno", category: "environment" }),
buildSkill({ name: "prd", category: "writing", triggers: [] }),
]);
@@ -259,7 +290,7 @@ Full skill body.`,
it("restores the search text when history navigation changes the query", async () => {
const user = userEvent.setup();
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([
+ mockSkillList([
buildSkill({ name: "deno", type: "knowledge", description: "A helper" }),
buildSkill({
name: "global-rules",
@@ -289,7 +320,7 @@ Full skill body.`,
it("filters through the mobile filters modal", async () => {
const user = userEvent.setup();
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([
+ mockSkillList([
buildSkill({ name: "deno", type: "knowledge" }),
buildSkill({
name: "global-rules",
@@ -319,7 +350,7 @@ Full skill body.`,
allowed_tools: ["bash", "execute_bash"],
source: "/skills/rich/SKILL.md",
});
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([skill]);
+ mockSkillList([skill]);
renderSkillsSettingsScreen();
const card = await screen.findByTestId(`skill-card-${skill.name}`);
@@ -350,7 +381,7 @@ Full skill body.`,
it("toggles a skill from the detail modal", async () => {
const user = userEvent.setup();
const skill = buildSkill({ name: "toggle-me" });
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([skill]);
+ mockSkillList([skill]);
renderSkillsSettingsScreen();
const card = await screen.findByTestId(`skill-card-${skill.name}`);
@@ -379,7 +410,7 @@ Full skill body.`,
// causing hasHydratedInitialSettings to never become true and the save to be silently skipped.
const user = userEvent.setup();
const skill = buildSkill({ name: "save-me" });
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([skill]);
+ mockSkillList([skill]);
vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
buildSettings({ disabled_skills: undefined }),
);
@@ -403,7 +434,7 @@ Full skill body.`,
it("saves an updated disabled list when a skill is toggled off and settings already has disabled_skills", async () => {
const user = userEvent.setup();
const skill = buildSkill({ name: "another-skill" });
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([skill]);
+ mockSkillList([skill]);
vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
buildSettings({ disabled_skills: [] }),
);
@@ -427,7 +458,7 @@ Full skill body.`,
it("toggles a skill from the card without opening the modal", async () => {
const user = userEvent.setup();
const skill = buildSkill({ name: "card-toggle" });
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([skill]);
+ mockSkillList([skill]);
renderSkillsSettingsScreen();
const card = await screen.findByTestId(`skill-card-${skill.name}`);
@@ -443,7 +474,7 @@ Full skill body.`,
it("shows an empty-state message when no skills match the current filters", async () => {
const skill = buildSkill();
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([skill]);
+ mockSkillList([skill]);
renderSkillsSettingsScreen();
await screen.findByTestId(`skill-card-${skill.name}`);
@@ -457,7 +488,7 @@ Full skill body.`,
it("opens the add skill modal with docs link and closes it", async () => {
const user = userEvent.setup();
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([]);
+ mockSkillList([]);
renderSkillsSettingsScreen();
await screen.findByTestId("skills-add-skill-button");
@@ -483,7 +514,7 @@ Full skill body.`,
const user = userEvent.setup();
const writeText = vi.fn().mockResolvedValue(undefined);
vi.spyOn(navigator.clipboard, "writeText").mockImplementation(writeText);
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([]);
+ mockSkillList([]);
renderSkillsSettingsScreen();
await user.click(await screen.findByTestId("skills-add-skill-button"));
@@ -498,18 +529,36 @@ Full skill body.`,
const CATALOG_RECOMMENDED = "add-skill";
const CATALOG_OPTIONAL = "add-javadoc";
- it("shows the notice that skill changes only reach new conversations", async () => {
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([]);
+ it("lists the skills agent profiles can select on a local backend", async () => {
+ vi.spyOn(SkillsService, "getSkills").mockResolvedValue([
+ buildSkill({ name: "repo-only" }),
+ ]);
+ vi.spyOn(SkillsService, "getSkillCatalog").mockResolvedValue([
+ buildSkill({ name: "from-catalog" }),
+ ]);
+
+ renderSkillsSettingsScreen();
+
+ expect(
+ await screen.findByTestId("skill-card-from-catalog"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("skill-card-repo-only"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("says the selection is the default list for new agent profiles", async () => {
+ mockSkillList([]);
renderSkillsSettingsScreen();
expect(
- await screen.findByTestId("skills-new-conversation-notice"),
- ).toHaveTextContent("SETTINGS$SKILLS_NEW_CONVERSATION_NOTICE");
+ await screen.findByTestId("skills-default-list-notice"),
+ ).toHaveTextContent("SETTINGS$SKILLS_DEFAULT_LIST_NOTICE");
});
it("badges a catalog skill the catalog recommends", async () => {
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([
+ mockSkillList([
buildSkill({ name: CATALOG_RECOMMENDED }),
buildSkill({ name: CATALOG_OPTIONAL }),
]);
@@ -527,9 +576,7 @@ Full skill body.`,
it("renders an unlisted catalog skill as off without it being denied", async () => {
// The reported bug: everything in the catalog arrived switched on.
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([
- buildSkill({ name: CATALOG_OPTIONAL }),
- ]);
+ mockSkillList([buildSkill({ name: CATALOG_OPTIONAL })]);
vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
buildSettings({ enabled_skills: undefined, disabled_skills: [] }),
);
@@ -545,9 +592,7 @@ Full skill body.`,
it("writes nothing back when the user toggles nothing", async () => {
// Persisting the hydrated state on mount would race the one-shot migration
// and could narrow a workspace it had just preserved.
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([
- buildSkill({ name: CATALOG_OPTIONAL }),
- ]);
+ mockSkillList([buildSkill({ name: CATALOG_OPTIONAL })]);
vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
buildSettings({ enabled_skills: undefined, disabled_skills: [] }),
);
@@ -566,9 +611,7 @@ Full skill body.`,
it("saves a catalog toggle to enabled_skills rather than the deny-list", async () => {
const user = userEvent.setup();
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([
- buildSkill({ name: CATALOG_RECOMMENDED }),
- ]);
+ mockSkillList([buildSkill({ name: CATALOG_RECOMMENDED })]);
vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
buildSettings({ enabled_skills: [CATALOG_RECOMMENDED] }),
);
@@ -593,13 +636,165 @@ Full skill body.`,
);
});
+ it("shows and saves the default agent profile's own list", async () => {
+ const user = userEvent.setup();
+ updateDefaultAgentProfileMock.mockReset().mockResolvedValue(undefined);
+ mockSkillList([
+ buildSkill({ name: CATALOG_RECOMMENDED }),
+ buildSkill({ name: CATALOG_OPTIONAL }),
+ ]);
+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
+ buildSettings({ enabled_skills: [CATALOG_RECOMMENDED] }),
+ );
+ vi.spyOn(AgentProfilesService, "getProfile").mockResolvedValue({
+ name: "default",
+ profile: {
+ id: "p-default",
+ name: "default",
+ revision: 1,
+ agent_kind: "openhands",
+ llm_profile_ref: "llm",
+ public_skills: [CATALOG_OPTIONAL],
+ disabled_skills: [],
+ },
+ } as never);
+ const saveSpy = vi
+ .spyOn(SettingsService, "saveSettings")
+ .mockResolvedValue(true);
+
+ renderSkillsSettingsScreen();
+ const optional = await screen.findByTestId(
+ `skill-card-${CATALOG_OPTIONAL}`,
+ );
+ await waitFor(() =>
+ expect(
+ within(optional).getByTestId(`skill-toggle-${CATALOG_OPTIONAL}`),
+ ).toHaveAttribute("aria-checked", "true"),
+ );
+ expect(
+ screen.getByTestId(`skill-toggle-${CATALOG_RECOMMENDED}`),
+ ).toHaveAttribute("aria-checked", "false");
+
+ await user.click(
+ within(optional).getByTestId(`skill-toggle-${CATALOG_OPTIONAL}`),
+ );
+
+ await waitFor(() =>
+ expect(updateDefaultAgentProfileMock).toHaveBeenCalledOnce(),
+ );
+ const [, change] = updateDefaultAgentProfileMock.mock.calls[0];
+ expect(
+ change({
+ agent_kind: "openhands",
+ public_skills: [CATALOG_OPTIONAL],
+ disabled_skills: [],
+ }),
+ ).toEqual({ public_skills: [], disabled_skills: [] });
+ expect(saveSpy).not.toHaveBeenCalled();
+ });
+
+ it("keeps a second quick toggle while the first write's refetch lands", async () => {
+ const user = userEvent.setup();
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const releases: (() => void)[] = [];
+ updateDefaultAgentProfileMock.mockReset().mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ releases.push(resolve);
+ }),
+ );
+ mockSkillList([
+ buildSkill({ name: CATALOG_RECOMMENDED }),
+ buildSkill({ name: CATALOG_OPTIONAL }),
+ ]);
+ const stored = (publicSkills: string[]) =>
+ ({
+ name: "default",
+ profile: {
+ id: "p-default",
+ name: "default",
+ revision: 1,
+ agent_kind: "openhands",
+ llm_profile_ref: "llm",
+ public_skills: publicSkills,
+ disabled_skills: [],
+ },
+ }) as never;
+ const getProfile = vi
+ .spyOn(AgentProfilesService, "getProfile")
+ .mockResolvedValue(stored([]));
+
+ renderSkillsSettingsScreen("/skills", queryClient);
+ const first = await screen.findByTestId(
+ `skill-toggle-${CATALOG_RECOMMENDED}`,
+ );
+ await waitFor(() => expect(first).toHaveAttribute("aria-checked", "false"));
+ await user.click(first);
+ await user.click(screen.getByTestId(`skill-toggle-${CATALOG_OPTIONAL}`));
+
+ // The first write lands and its refetch returns only the first toggle.
+ getProfile.mockResolvedValue(stored([CATALOG_RECOMMENDED]));
+ await act(() => queryClient.invalidateQueries());
+
+ expect(
+ screen.getByTestId(`skill-toggle-${CATALOG_OPTIONAL}`),
+ ).toHaveAttribute("aria-checked", "true");
+ await act(async () => releases.forEach((release) => release()));
+ });
+
+ it("writes nowhere when the default profile cannot be read", async () => {
+ const user = userEvent.setup();
+ updateDefaultAgentProfileMock.mockReset().mockResolvedValue(undefined);
+ mockSkillList([buildSkill({ name: CATALOG_RECOMMENDED })]);
+ vi.spyOn(AgentProfilesService, "getProfile").mockRejectedValue(
+ new HttpError(500, "Server Error", {}, "boom"),
+ );
+ const saveSpy = vi
+ .spyOn(SettingsService, "saveSettings")
+ .mockResolvedValue(true);
+
+ renderSkillsSettingsScreen();
+ const toggle = await screen.findByTestId(
+ `skill-toggle-${CATALOG_RECOMMENDED}`,
+ );
+ await waitFor(() => expect(toggle).toBeDisabled());
+ await user.click(toggle);
+
+ expect(saveSpy).not.toHaveBeenCalled();
+ expect(updateDefaultAgentProfileMock).not.toHaveBeenCalled();
+ });
+
+ it("locks the switches while the default profile's migration has failed", async () => {
+ const user = userEvent.setup();
+ updateDefaultAgentProfileMock.mockReset().mockResolvedValue(undefined);
+ migrationState = {
+ isFetching: false,
+ isSuccess: false,
+ error: new Error("offline"),
+ };
+ mockSkillList([buildSkill({ name: CATALOG_RECOMMENDED })]);
+ const saveSpy = vi
+ .spyOn(SettingsService, "saveSettings")
+ .mockResolvedValue(true);
+
+ renderSkillsSettingsScreen();
+ const toggle = await screen.findByTestId(
+ `skill-toggle-${CATALOG_RECOMMENDED}`,
+ );
+ await waitFor(() => expect(toggle).toBeDisabled());
+ await user.click(toggle);
+
+ expect(saveSpy).not.toHaveBeenCalled();
+ expect(updateDefaultAgentProfileMock).not.toHaveBeenCalled();
+ });
+
it("drops a re-enabled catalog skill from an unmigrated deny-list", async () => {
// A stale deny entry would otherwise veto the allow-list entry we just
// wrote, leaving the toggle on and the skill still absent.
const user = userEvent.setup();
- vi.spyOn(SkillsService, "getSkills").mockResolvedValue([
- buildSkill({ name: CATALOG_RECOMMENDED }),
- ]);
+ mockSkillList([buildSkill({ name: CATALOG_RECOMMENDED })]);
vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
buildSettings({
enabled_skills: undefined,
diff --git a/__tests__/routes/verification-settings.test.tsx b/__tests__/routes/verification-settings.test.tsx
index ae8f886604..892f53b40f 100644
--- a/__tests__/routes/verification-settings.test.tsx
+++ b/__tests__/routes/verification-settings.test.tsx
@@ -3,7 +3,9 @@ import { render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import SettingsService from "#/api/settings-service/settings-service.api";
import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";
-import VerificationSettingsScreen from "#/routes/verification-settings";
+import VerificationSettingsRoute, {
+ VerificationSettingsScreen,
+} from "#/routes/verification-settings";
import { Settings } from "#/types/settings";
function buildSettings(overrides: Partial<Settings> = {}): Settings {
@@ -27,14 +29,16 @@ function buildSettings(overrides: Partial<Settings> = {}): Settings {
};
}
-function renderVerificationSettingsScreen() {
+function renderVerificationSettingsScreen(
+ Screen: React.ComponentType = VerificationSettingsScreen,
+) {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
});
- return render(<VerificationSettingsScreen />, {
+ return render(<Screen />, {
wrapper: ({ children }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
),
@@ -228,3 +232,56 @@ describe("VerificationSettingsScreen", () => {
).not.toBeInTheDocument();
});
});
+
+describe("VerificationSettingsRoute on a local backend", () => {
+ it("keeps the critic API key and leaves the critic's behavior to agent profiles", async () => {
+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
+ buildSettings({
+ agent_settings: {
+ ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,
+ verification: {
+ critic_enabled: false,
+ enable_iterative_refinement: false,
+ },
+ },
+ }),
+ );
+
+ renderVerificationSettingsScreen(VerificationSettingsRoute);
+
+ expect(
+ await screen.findByTestId("sdk-settings-verification.critic_api_key"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("sdk-settings-verification.critic_enabled"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId(
+ "sdk-settings-verification.enable_iterative_refinement",
+ ),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByTestId("verification-critic-per-profile-note"),
+ ).toBeInTheDocument();
+ });
+
+ it("keeps the confirmation controls", async () => {
+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
+ buildSettings({
+ conversation_settings: {
+ ...MOCK_DEFAULT_USER_SETTINGS.conversation_settings,
+ confirmation_mode: true,
+ },
+ }),
+ );
+
+ renderVerificationSettingsScreen(VerificationSettingsRoute);
+
+ expect(
+ await screen.findByTestId("sdk-settings-confirmation_mode"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByTestId("sdk-settings-security_analyzer"),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/__tests__/services/child-conversation-launch.test.ts b/__tests__/services/child-conversation-launch.test.ts
index 363c6400e6..2a8e79a83e 100644
--- a/__tests__/services/child-conversation-launch.test.ts
+++ b/__tests__/services/child-conversation-launch.test.ts
@@ -50,6 +50,16 @@ const {
mockSupportsLaunchLlmOverride: vi.fn(),
}));
+vi.mock(
+ "#/hooks/use-migrate-default-agent-profile",
+ async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/hooks/use-migrate-default-agent-profile")
+ >()),
+ ensureDefaultAgentProfileMigrated: vi.fn().mockResolvedValue(true),
+ }),
+);
+
vi.mock(
"#/api/conversation-service/agent-server-conversation-service.api",
() => ({
@@ -186,9 +196,20 @@ describe("handleLaunchChildConversationAction", () => {
});
mockBatchGetAppConversations.mockResolvedValue([]);
getQueryClient().clear();
+ // A parent without a recorded profile launches its child from the active
+ // one, the seeded `default` here.
mockListAgentProfiles.mockResolvedValue({
- profiles: [],
- active_agent_profile_id: null,
+ profiles: [
+ {
+ id: "profile-default",
+ name: "default",
+ agent_kind: "openhands",
+ revision: 1,
+ llm_profile_ref: "default",
+ mcp_server_refs: null,
+ },
+ ],
+ active_agent_profile_id: "profile-default",
});
mockListLlmProfiles.mockResolvedValue({
profiles: [],
@@ -264,6 +285,9 @@ describe("handleLaunchChildConversationAction", () => {
);
expect(mockCreateConversation).toHaveBeenCalledWith({
+ agentProfileId: "profile-default",
+ agentProfileKind: "openhands",
+ agentLlmProfileRef: "default",
initialUserMsg: "Add a regression test for the parser",
metadata: PARENT_REPO_METADATA,
workingDirOverride: "/Users/jane/projects/foo",
@@ -362,6 +386,9 @@ describe("handleLaunchChildConversationAction", () => {
);
expect(mockCreateConversation).toHaveBeenCalledWith({
+ agentProfileId: "profile-default",
+ agentProfileKind: "openhands",
+ agentLlmProfileRef: "default",
initialUserMsg: expect.anything(),
metadata: null,
workingDirOverride: "/Users/jane/projects/foo",
@@ -416,6 +443,9 @@ describe("handleLaunchChildConversationAction", () => {
expect(mockCreateConversation).toHaveBeenCalledTimes(1);
expect(mockCreateConversation).toHaveBeenCalledWith({
+ agentProfileId: "profile-default",
+ agentProfileKind: "openhands",
+ agentLlmProfileRef: "default",
initialUserMsg: expect.anything(),
metadata: null,
workingDirOverride: "/Users/jane/projects/foo",
@@ -446,6 +476,9 @@ describe("handleLaunchChildConversationAction", () => {
expect(mockCreateConversation).toHaveBeenCalledTimes(2);
expect(mockCreateConversation).toHaveBeenLastCalledWith({
+ agentProfileId: "profile-default",
+ agentProfileKind: "openhands",
+ agentLlmProfileRef: "default",
initialUserMsg: expect.anything(),
metadata: PARENT_REPO_METADATA,
workingDirOverride: "/Users/jane/projects/foo",
diff --git a/specs/llm-defaults.md b/specs/llm-defaults.md
index a5acdc1095..ac520d02e6 100644
--- a/specs/llm-defaults.md
+++ b/specs/llm-defaults.md
@@ -4,7 +4,7 @@
### LLD-001: Frontend always sends its chosen default model
-- [x] When the agent-server returns an absent or empty `llm.model` (e.g. because the user has never saved settings), the frontend adapter shall substitute `DEFAULT_SETTINGS.llm_model` (`"openai/gpt-5.6-sol"`) before sending the conversation-start request.
+- [x] When the agent-server returns an absent or empty `llm.model` (e.g. because the user has never saved settings), the frontend adapter shall substitute `DEFAULT_SETTINGS.llm_model` (`"openai/gpt-5.6-sol"`) before sending a conversation-start request that carries a raw agent spec (the local planner). Agent Profile launches take the model from the referenced LLM profile.
- [x] The frontend shall never rely on the agent-server SDK's own default model (`gpt-5.5`); it shall always send an explicit model value.
- [x] Whitespace-only model strings shall be treated as absent and fall back to the default.
-- [x] The same guard applies when LLM settings arrive via `encryptedAgentSettings` (the conversation-start encrypted payload path).
+- [x] The same guard applies when LLM settings arrive via `encryptedAgentSettings` (the planner's encrypted payload path).
diff --git a/src/api/agent-profiles-service/agent-profiles-service.api.ts b/src/api/agent-profiles-service/agent-profiles-service.api.ts
index 530d96f772..568d38605a 100644
--- a/src/api/agent-profiles-service/agent-profiles-service.api.ts
+++ b/src/api/agent-profiles-service/agent-profiles-service.api.ts
@@ -43,9 +43,7 @@ function isCloud(): boolean {
/**
* The seeded, well-known baseline agent profile. The backend lazily seeds it to
* mirror the user's global config (#3719), and onboarding configures it from the
- * user's choice. It stands in for global `agent_settings`, so the home-launch
- * path treats it as the enriched baseline rather than a deliberate profile
- * selection (see `useCreateConversation`).
+ * user's choice. It launches like any other profile.
*/
export const WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME = "default";
diff --git a/src/api/agent-profiles-service/profile-behavior.ts b/src/api/agent-profiles-service/profile-behavior.ts
new file mode 100644
index 0000000000..1935cb5020
--- /dev/null
+++ b/src/api/agent-profiles-service/profile-behavior.ts
@@ -0,0 +1,25 @@
+import type { OpenHandsAgentProfile } from "@openhands/typescript-client";
+
+/** OpenHands profile fields the agent-server stores that the ts-client types omit. */
+export interface OpenHandsProfileBehavior {
+ /** Deny-list over every skill the profile would load. */
+ disabled_skills?: string[];
+ /** Allow-list over the public catalog; `null` loads all of it. */
+ public_skills?: string[] | null;
+ meta_profile_ref?: string | null;
+ enable_classify_and_switch_llm_tool?: boolean;
+}
+
+export type StoredOpenHandsProfile = OpenHandsAgentProfile &
+ OpenHandsProfileBehavior;
+
+/**
+ * Whether launching the profile attaches the Model Router's routing tool. On
+ * without a name, the server picks the alphabetically first router.
+ */
+export function profileHasRouter(profile: OpenHandsAgentProfile): boolean {
+ return (
+ (profile as StoredOpenHandsProfile).enable_classify_and_switch_llm_tool ===
+ true
+ );
+}
diff --git a/src/api/agent-server-adapter.test.ts b/src/api/agent-server-adapter.test.ts
index d3cc048fe5..eea1b2fbe8 100644
--- a/src/api/agent-server-adapter.test.ts
+++ b/src/api/agent-server-adapter.test.ts
@@ -5,6 +5,7 @@ import { REQUEST_SECRET_TOOL_NAME } from "#/constants/secret-request";
import { DEFAULT_SETTINGS } from "#/services/settings";
import type { Settings } from "#/types/settings";
import {
+ ACP_SERVER_TAG_KEY,
AGENT_CANVAS_SOURCE,
CLIENT_SOURCE_TAG_KEY,
buildStartConversationRequest,
@@ -23,14 +24,12 @@ vi.mock("./secrets-service", () => ({
SecretsService: { getSecrets: vi.fn().mockResolvedValue([]) },
}));
vi.mock("./agent-profiles-service/agent-profiles-service.api", () => ({
- default: { listProfiles: vi.fn() },
+ default: { listProfiles: vi.fn(), getProfile: vi.fn() },
}));
vi.mock("./profiles-service/profiles-service.api", () => ({
default: { getProfile: vi.fn() },
}));
-const encryptedValue = "gAAAAAencrypted-mcp-header";
-
function makeSettings(agentSettings: Settings["agent_settings"]): Settings {
return {
...DEFAULT_SETTINGS,
@@ -43,19 +42,6 @@ function makeSettings(agentSettings: Settings["agent_settings"]): Settings {
};
}
-function getAgentContextSkillNames(
- payload: ReturnType<typeof buildStartConversationRequest>,
-): Array<string | undefined> {
- const agentSettings = payload.agent_settings as
- | {
- agent_context?: {
- skills?: Array<{ name?: string }>;
- };
- }
- | undefined;
- return agentSettings?.agent_context?.skills?.map((skill) => skill.name) ?? [];
-}
-
function getPlannerAgentContextSkillNames(payload: {
agent: { agent_context?: { skills?: Array<{ name?: string }> } };
}): Array<string | undefined> {
@@ -63,71 +49,6 @@ function getPlannerAgentContextSkillNames(payload: {
}
describe("buildStartConversationRequest", () => {
- it("marks OpenHands start requests as encrypted when MCP headers are encrypted", () => {
- const agentSettings = {
- agent_kind: "openhands",
- llm: {
- model: "litellm_proxy/openai/gpt-5.5",
- api_key: "gAAAAAencrypted-llm-api-key",
- },
- mcp_config: {
- linear: {
- url: "https://mcp.linear.app/mcp",
- transport: "http",
- headers: {
- Authorization: encryptedValue,
- },
- },
- },
- };
- const settings = makeSettings(agentSettings);
-
- const payload = buildStartConversationRequest({
- settings,
- encryptedAgentSettings: agentSettings,
- encryptedConversationSettings: settings.conversation_settings!,
- secretsEncrypted: true,
- });
-
- expect(payload.agent_settings!.agent_kind).toBe("openhands");
- expect(payload.agent_settings!.mcp_config).toEqual(
- agentSettings.mcp_config,
- );
- expect(payload.secrets_encrypted).toBe(true);
- });
-
- it("marks ACP start requests as encrypted when MCP headers are encrypted", () => {
- const agentSettings = {
- agent_kind: "acp",
- acp_server: "codex",
- acp_command: ["codex-acp"],
- acp_model: "gpt-5.5/medium",
- mcp_config: {
- linear: {
- url: "https://mcp.linear.app/mcp",
- transport: "http",
- headers: {
- Authorization: encryptedValue,
- },
- },
- },
- };
- const settings = makeSettings(agentSettings);
-
- const payload = buildStartConversationRequest({
- settings,
- encryptedAgentSettings: agentSettings,
- encryptedConversationSettings: settings.conversation_settings!,
- secretsEncrypted: true,
- });
-
- expect(payload.agent_settings!.agent_kind).toBe("acp");
- expect(payload.agent_settings!.mcp_config).toEqual(
- agentSettings.mcp_config,
- );
- expect(payload.secrets_encrypted).toBe(true);
- });
-
it("builds a raw planning agent request for local Planner", () => {
const agentSettings = {
agent_kind: "openhands",
@@ -183,6 +104,41 @@ describe("buildStartConversationRequest", () => {
expect(payload.secrets).toHaveProperty("CUSTOM_TOKEN");
});
+ // @spec LLD-001 — Frontend always sends its chosen default model
+ it.each([
+ [
+ "configured",
+ { model: "anthropic/claude-opus-4-5" },
+ "anthropic/claude-opus-4-5",
+ ],
+ ["undefined", {}, DEFAULT_SETTINGS.llm_model],
+ ["an empty string", { model: "" }, DEFAULT_SETTINGS.llm_model],
+ ["whitespace only", { model: " " }, DEFAULT_SETTINGS.llm_model],
+ ])(
+ "sends the planner an explicit model when it is %s",
+ (_case, llm, model) => {
+ const payload = buildStartPlanningConversationRequest({
+ encryptedAgentSettings: { llm },
+ workingDir: "/workspace/project/agent-canvas",
+ parentConversationId: "parent-1",
+ });
+
+ expect(payload.agent.llm).toMatchObject({ model });
+ },
+ );
+
+ it("sends the planner the default model when settings carry no LLM", () => {
+ const payload = buildStartPlanningConversationRequest({
+ encryptedAgentSettings: {},
+ workingDir: "/workspace/project/agent-canvas",
+ parentConversationId: "parent-1",
+ });
+
+ expect(payload.agent.llm).toMatchObject({
+ model: DEFAULT_SETTINGS.llm_model,
+ });
+ });
+
it("links the local planner to its parent server-side so the relationship survives storage loss", () => {
const payload = buildStartPlanningConversationRequest({
encryptedAgentSettings: {
@@ -281,158 +237,31 @@ describe("buildStartConversationRequest", () => {
expect(page.items.map((item) => item.id)).toEqual(["main-1"]);
});
- it("keeps ACP start requests unencrypted when no encrypted MCP values are present", () => {
- const agentSettings = {
- agent_kind: "acp",
- acp_server: "codex",
- acp_command: ["codex-acp"],
- acp_model: "gpt-5.5/medium",
- mcp_config: {
- publicDocs: {
- url: "https://docs.example.com/mcp",
- transport: "http",
- },
- },
- };
- const settings = makeSettings(agentSettings);
-
- const payload = buildStartConversationRequest({
- settings,
- encryptedAgentSettings: agentSettings,
- encryptedConversationSettings: settings.conversation_settings!,
- secretsEncrypted: true,
- });
-
- expect(payload.agent_settings!.agent_kind).toBe("acp");
- expect(payload.secrets_encrypted).toBeUndefined();
- });
-
- it("ships only allow-listed catalog skills to a OpenHands conversation context", () => {
- const settings = makeSettings({
- agent_kind: "openhands",
- llm: {
- model: "litellm_proxy/openai/gpt-5.5",
- api_key: "sk-test",
- },
- agent_context: {
- skills: [
- { name: "disabled-custom", content: "disabled" },
- { name: "enabled-custom", content: "enabled" },
- ],
- },
- });
- settings.disabled_skills = ["agent-memory", "disabled-custom"];
-
- const payload = buildStartConversationRequest({ settings });
- const skillNames = getAgentContextSkillNames(payload);
-
- // `agent-memory` is default-enabled, so this asserts the deny-list still
- // wins over the allow-list — the case that matters before the one-shot
- // migration has run.
- expect(skillNames).not.toContain("agent-memory");
- expect(skillNames).not.toContain("disabled-custom");
- // Skills already on the agent context are user-authored and stay opt-out.
- expect(skillNames).toContain("enabled-custom");
- // No `enabled_skills` on the settings means the curated default applies:
- // `add-skill` is flagged `defaultEnabled` in the catalog, `add-javadoc` is
- // not, and shipping every catalog skill is what OpenHands#16302 reported.
- expect(skillNames).toContain("add-skill");
- expect(skillNames).not.toContain("add-javadoc");
-
- expect(payload.agent_settings?.agent_context?.disabled_skills).toEqual([
- "agent-memory",
- "disabled-custom",
- ]);
- });
-
- it("ships only allow-listed catalog skills to a ACP conversation context", () => {
- const settings = makeSettings({
- agent_kind: "acp",
- acp_server: "codex",
- acp_command: ["codex-acp"],
- acp_model: "gpt-5.5/medium",
- agent_context: {
- skills: [
- { name: "disabled-custom", content: "disabled" },
- { name: "enabled-custom", content: "enabled" },
- ],
- },
- });
- settings.disabled_skills = ["agent-memory", "disabled-custom"];
-
- const payload = buildStartConversationRequest({ settings });
- const skillNames = getAgentContextSkillNames(payload);
-
- // `agent-memory` is default-enabled, so this asserts the deny-list still
- // wins over the allow-list — the case that matters before the one-shot
- // migration has run.
- expect(skillNames).not.toContain("agent-memory");
- expect(skillNames).not.toContain("disabled-custom");
- // Skills already on the agent context are user-authored and stay opt-out.
- expect(skillNames).toContain("enabled-custom");
- // No `enabled_skills` on the settings means the curated default applies:
- // `add-skill` is flagged `defaultEnabled` in the catalog, `add-javadoc` is
- // not, and shipping every catalog skill is what OpenHands#16302 reported.
- expect(skillNames).toContain("add-skill");
- expect(skillNames).not.toContain("add-javadoc");
-
- expect(payload.agent_settings?.agent_context?.disabled_skills).toEqual([
- "agent-memory",
- "disabled-custom",
- ]);
- });
-
it("loads a catalog skill the opening slash command invokes", () => {
// An automation card fills the chat input with the skill's own command
- // (`findAutomationCommand`), and 18 of the catalog's 24 slash commands
- // belong to skills that are off by default — without this the card would
- // silently do nothing.
- const settings = makeSettings({
- agent_kind: "openhands",
- llm: { model: "litellm_proxy/openai/gpt-5.5", api_key: "sk-test" },
- });
-
+ // (`findAutomationCommand`), and most of the catalog's slash commands
+ // belong to skills a profile does not select — without this the card
+ // would silently do nothing.
const payload = buildStartConversationRequest({
- settings,
+ settings: makeSettings({ agent_kind: "openhands" }),
+ agentProfileId: "profile-xyz",
+ agentProfileKind: "openhands",
query: "/standup-digest:setup",
});
- expect(getAgentContextSkillNames(payload)).toContain(
- "slack-standup-digest",
- );
+ expect(
+ payload.agent_launch_additions?.skills?.map((skill) => skill.name),
+ ).toEqual(["slack-standup-digest"]);
});
-
it("does not admit a skill named mid-sentence rather than invoked", () => {
- const settings = makeSettings({
- agent_kind: "openhands",
- llm: { model: "litellm_proxy/openai/gpt-5.5", api_key: "sk-test" },
- });
-
const payload = buildStartConversationRequest({
- settings,
+ settings: makeSettings({ agent_kind: "openhands" }),
+ agentProfileId: "profile-xyz",
+ agentProfileKind: "openhands",
query: "tell me what /standup-digest:setup would do",
});
- expect(getAgentContextSkillNames(payload)).not.toContain(
- "slack-standup-digest",
- );
- });
-
- it("lets an invoked skill override a stored deny entry for that conversation", () => {
- const settings = makeSettings({
- agent_kind: "openhands",
- llm: { model: "litellm_proxy/openai/gpt-5.5", api_key: "sk-test" },
- });
- settings.disabled_skills = ["slack-standup-digest"];
-
- const payload = buildStartConversationRequest({
- settings,
- query: "/standup-digest:setup",
- });
-
- expect(getAgentContextSkillNames(payload)).toContain(
- "slack-standup-digest",
- );
+ expect(payload.agent_launch_additions).toBeUndefined();
});
});
@@ -440,6 +269,7 @@ describe("buildStartConversationRequest — execution runtime", () => {
it("requests DockerExecutionWorkspace from Docker execution servers", () => {
const payload = buildStartConversationRequest({
settings: makeSettings({ agent_kind: "openhands" }),
+ agentProfileId: "profile-xyz",
workingDir: "/host/workspace",
executionRuntime: "docker",
});
@@ -454,6 +284,7 @@ describe("buildStartConversationRequest — execution runtime", () => {
it("keeps LocalWorkspace for local and older servers", () => {
const payload = buildStartConversationRequest({
settings: makeSettings({ agent_kind: "openhands" }),
+ agentProfileId: "profile-xyz",
workingDir: "/host/workspace",
});
@@ -535,7 +366,7 @@ describe("buildStartPlanningConversationRequestWithEncryptedSettings", () => {
parentAgentProfileId: null,
});
- expect(AgentProfilesService.listProfiles).not.toHaveBeenCalled();
+ expect(ProfilesService.getProfile).not.toHaveBeenCalled();
expect(payload.agent.llm).toMatchObject({
model: "openhands/globally-active-model",
});
@@ -581,7 +412,7 @@ describe("buildStartPlanningConversationRequestWithEncryptedSettings", () => {
);
// The launched agent profile must not even be consulted once
// active_profile resolves successfully.
- expect(AgentProfilesService.listProfiles).not.toHaveBeenCalled();
+ expect(ProfilesService.getProfile).toHaveBeenCalledTimes(1);
expect(payload.agent.llm).toMatchObject({
model: "openhands/switched-model",
api_key: "gAAAAAswitched-key",
@@ -684,6 +515,36 @@ describe("buildStartPlanningConversationRequestWithEncryptedSettings", () => {
expect(skillNames).toContain("add-javadoc");
});
+ it("gives the planner the parent profile's skill selection over the global lists", async () => {
+ vi.mocked(SettingsService.getSettingsForConversation).mockResolvedValue({
+ ...globallyActiveSettings,
+ skillEnablement: { enabledSkills: ["agent-memory"], disabledSkills: [] },
+ });
+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
+ name: "parent-profile",
+ profile: {
+ id: "profile-parent",
+ name: "parent-profile",
+ revision: 1,
+ agent_kind: "openhands",
+ llm_profile_ref: "parent-llm",
+ public_skills: ["add-javadoc"],
+ disabled_skills: [],
+ },
+ } as never);
+
+ const payload =
+ await buildStartPlanningConversationRequestWithEncryptedSettings({
+ workingDir: "/workspace/project",
+ parentConversationId: "parent-1",
+ parentAgentProfileId: "profile-parent",
+ });
+
+ const skillNames = getPlannerAgentContextSkillNames(payload);
+ expect(skillNames).toContain("add-javadoc");
+ expect(skillNames).not.toContain("agent-memory");
+ });
+
it("threads executionRuntime through to DockerExecutionWorkspace selection", async () => {
const payload =
await buildStartPlanningConversationRequestWithEncryptedSettings({
@@ -713,22 +574,6 @@ describe("buildStartPlanningConversationRequestWithEncryptedSettings", () => {
});
describe("buildStartConversationRequest — agentProfileId path", () => {
- it("appends the saved global suffix to a profile launch", () => {
- const payload = buildStartConversationRequest({
- settings: makeSettings({
- agent_kind: "openhands",
- agent_context: { system_message_suffix: "MARKER-GLOBAL-RULES" },
- }),
- agentProfileId: "profile-xyz",
- agentProfileKind: "openhands",
- });
-
- expect(payload.agent_launch_additions).toEqual({
- system_message_suffix_append: "MARKER-GLOBAL-RULES",
- });
- expect(payload.agent_settings).toBeUndefined();
- });
-
it("sends agent_profile_id and omits agent_settings (mutually exclusive)", () => {
const settings = makeSettings({
agent_kind: "openhands",
@@ -751,85 +596,37 @@ describe("buildStartConversationRequest — agentProfileId path", () => {
]);
});
- it("carries a per-launch LLM override only on a profile launch", () => {
- const settings = makeSettings({
- agent_kind: "openhands",
- llm: { model: "litellm_proxy/openai/gpt-5.5", api_key: "sk-test" },
- });
-
- const profileLaunch = buildStartConversationRequest({
- settings,
+ it("carries a per-launch LLM override", () => {
+ const payload = buildStartConversationRequest({
+ settings: makeSettings({ agent_kind: "openhands" }),
agentProfileId: "profile-xyz",
agentProfileKind: "openhands",
llmProfileOverride: "fast",
});
- expect(profileLaunch.agent_launch_additions).toEqual({
- llm_profile_ref: "fast",
- });
- const settingsLaunch = buildStartConversationRequest({
- settings,
- llmProfileOverride: "fast",
+ expect(payload.agent_launch_additions).toEqual({
+ llm_profile_ref: "fast",
});
- expect(settingsLaunch.agent_launch_additions).toBeUndefined();
- expect(settingsLaunch.agent_settings).toBeDefined();
});
-
- it("suppresses the ACP server tag when launching from a profile", () => {
- const agentSettings = {
- agent_kind: "acp",
- acp_server: "codex",
- acp_command: ["codex-acp"],
- acp_model: "gpt-5.5/medium",
- };
-
- // Without a profile the ACP server tag is stamped from settings...
- expect(
- buildStartConversationRequest({ settings: makeSettings(agentSettings) })
- .tags,
- ).toBeDefined();
-
- // ...but a profile launch resolves the server server-side, so the tag
- // (which may not match the launched profile) is omitted while the client
- // source telemetry tag is still stamped.
- const payload = buildStartConversationRequest({
- settings: makeSettings(agentSettings),
- agentProfileId: "profile-xyz",
- });
- expect(payload.tags).toEqual({
+ it("stamps the launched ACP profile's server as the ACP server tag", () => {
+ const tagsFor = (
+ agentProfileKind: "acp" | "openhands",
+ acpServer?: string,
+ ) =>
+ buildStartConversationRequest({
+ // Global settings name another ACP server; the profile decides.
+ settings: makeSettings({ agent_kind: "acp", acp_server: "codex" }),
+ agentProfileId: "profile-xyz",
+ agentProfileKind,
+ acpServer,
+ }).tags;
+
+ expect(tagsFor("acp", "claude-code")).toEqual({
+ [ACP_SERVER_TAG_KEY]: "claude-code",
[CLIENT_SOURCE_TAG_KEY]: AGENT_CANVAS_SOURCE,
});
- });
-
- it("suppresses secrets_encrypted when launching from a profile", () => {
- const agentSettings = {
- agent_kind: "openhands",
- llm: {
- model: "litellm_proxy/openai/gpt-5.5",
- api_key: "gAAAAAencrypted-llm-api-key",
- },
- mcp_config: {
- mcpServers: {
- linear: {
- url: "https://mcp.linear.app/mcp",
- transport: "http",
- headers: { Authorization: encryptedValue },
- },
- },
- },
- };
- const settings = makeSettings(agentSettings);
-
- // Same inputs without a profile would set secrets_encrypted (covered
- // above); the profile path defers secret resolution to the server.
- const payload = buildStartConversationRequest({
- settings,
- encryptedAgentSettings: agentSettings,
- encryptedConversationSettings: settings.conversation_settings!,
- secretsEncrypted: true,
- agentProfileId: "profile-xyz",
+ expect(tagsFor("openhands")).toEqual({
+ [CLIENT_SOURCE_TAG_KEY]: AGENT_CANVAS_SOURCE,
});
-
- expect(payload.secrets_encrypted).toBeUndefined();
});
});
diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.ts
index ce10a738e4..85927be874 100644
--- a/src/api/agent-server-adapter.ts
+++ b/src/api/agent-server-adapter.ts
@@ -1,11 +1,7 @@
import i18n, { OPENHANDS_I18N_NAMESPACE } from "#/i18n";
import { I18nKey } from "#/i18n/declaration";
import { hasPluginParameters } from "#/utils/plugin-parameters";
-import {
- ACP_SETTINGS_KEYS,
- HOOK_EVENT_FIELDS,
- HookType,
-} from "@openhands/typescript-client";
+import { HOOK_EVENT_FIELDS, HookType } from "@openhands/typescript-client";
import type {
ACPModelInfo,
ConversationRuntimeInfo,
@@ -17,8 +13,6 @@ import { DEFAULT_SETTINGS } from "#/services/settings";
import { ExecutionStatus } from "#/types/agent-server/core";
import { AgentKind, Settings, SettingsValue } from "#/types/settings";
import {
- getAcpPreferredDefaultModel,
- getAcpProvider,
resolveEffectiveAcpModel,
toAcpModelOptions,
} from "#/constants/acp-providers";
@@ -49,11 +43,11 @@ import {
import {
buildSkillEnablementFilter,
findInvokedCatalogSkill,
- toSkillEnablement,
+ profileSkillEnablement,
type SkillEnablement,
} from "#/utils/skill-enablement";
+import type { StoredOpenHandsProfile } from "./agent-profiles-service/profile-behavior";
import SettingsService from "./settings-service/settings-service.api";
-import MetaProfilesService from "./meta-profiles-service/meta-profiles-service.api";
import { getStoredConversationMetadata } from "./conversation-metadata-store";
import LLMSubscriptionService from "./llm-subscription-service";
import {
@@ -244,14 +238,6 @@ async function fetchBackendServerInfo(): Promise<AgentServerInfo | null> {
}
}
-/** Whether start requests accept `agent_launch_additions.llm_profile_ref`. */
-export async function backendSupportsLaunchLlmOverride(): Promise<boolean> {
- const serverInfo = await fetchBackendServerInfo();
- return (
- serverInfo?.capabilities?.includes("agent_launch_pipeline_v1") ?? false
- );
-}
-
export async function fetchBackendExecutionRuntime(): Promise<
AgentServerInfo["execution_runtime"]
> {
@@ -522,17 +508,6 @@ export function toConversationPage(data: {
type SettingsRecord = Record<string, unknown>;
-interface AgentToolSpec {
- name: string;
- params: SettingsRecord;
-}
-
-type AgentSettingsPayload = SettingsRecord & {
- llm?: SettingsRecord;
- agent_context: SettingsRecord;
- tools?: AgentToolSpec[];
-};
-
interface LocalWorkspacePayload {
kind: "LocalWorkspace";
working_dir: string;
@@ -677,8 +652,6 @@ export function getDisplayConversationTags(
});
}
-const FERNET_TOKEN_PREFIX = "gAAAAA";
-
const CONVERSATION_SETTINGS_METADATA_KEYS = new Set([
"schema_version",
"agent_settings",
@@ -743,27 +716,6 @@ function isPlainRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === "object" && !Array.isArray(value);
}
-function hasEncryptedString(value: unknown): boolean {
- if (typeof value === "string") {
- return value.startsWith(FERNET_TOKEN_PREFIX);
- }
- if (Array.isArray(value)) {
- return value.some(hasEncryptedString);
- }
- if (isPlainRecord(value)) {
- return Object.values(value).some(hasEncryptedString);
- }
- return false;
-}
-
-function hasEncryptedMcpSecrets(mcpConfig: unknown): boolean {
- if (!isPlainRecord(mcpConfig)) {
- return false;
- }
-
- return Object.values(mcpConfig).some(hasEncryptedString);
-}
-
function getConversationConfirmationPolicy(
conversationSettings: SettingsRecord,
) {
@@ -791,34 +743,6 @@ function getConversationSecurityAnalyzer(conversationSettings: SettingsRecord) {
}
}
-function isToolRecord(
- value: unknown,
-): value is { name: string; params?: unknown } {
- return (
- !!value &&
- typeof value === "object" &&
- !Array.isArray(value) &&
- typeof (value as { name?: unknown }).name === "string"
- );
-}
-
-/** Unset `tools` is left to the server; a list is sent as given. */
-function getAgentTools(
- agentSettings: SettingsRecord,
-): AgentToolSpec[] | undefined {
- const configuredTools = agentSettings.tools;
- if (
- !Array.isArray(configuredTools) ||
- !configuredTools.every((tool) => isToolRecord(tool))
- ) {
- return undefined;
- }
- return configuredTools.map((tool) => ({
- name: tool.name,
- params: toRecord(tool.params),
- }));
-}
-
function buildInitialMessage(
query?: string,
conversationInstructions?: string,
@@ -891,18 +815,8 @@ function buildBundledSkills(): BundledSkill[] {
function buildAgentContext(
agentSettings: SettingsRecord,
- runtimeServicesInfo?: RuntimeServicesInfo | null,
enablement: SkillEnablement = {},
- invokedCatalogSkill?: string,
- runRouterAtStart?: boolean,
- hasActiveRouter?: boolean,
): SettingsRecord {
- const runtimeServicesSuffix =
- buildRuntimeServicesSystemSuffix(runtimeServicesInfo);
- const routerAtStartSuffix = buildRouterAtStartSystemSuffix(
- runRouterAtStart ?? false,
- hasActiveRouter ?? false,
- );
const existingContext = toRecord(agentSettings.agent_context);
// Merge bundled public skills with any skills already present in the
@@ -917,17 +831,13 @@ function buildAgentContext(
// The bundled catalog is allow-listed, not deny-listed: it is a build-time
// snapshot of ~60 skills, so a deny-list puts every future addition into
// every system prompt (OpenHands#16302). Skills the agent context already
- // carries are user-authored and stay opt-out. A skill the opening message
- // invokes by name overrides both, for this conversation only.
+ // carries are user-authored and stay opt-out.
const mergedSkills = [
...existingSkills.filter(
(skill) =>
typeof skill.name !== "string" || !disabledSkillNames.has(skill.name),
),
- ...buildBundledSkills().filter(
- (skill) =>
- skill.name === invokedCatalogSkill || isSkillEnabled(skill.name),
- ),
+ ...buildBundledSkills().filter((skill) => isSkillEnabled(skill.name)),
];
return {
@@ -950,179 +860,9 @@ function buildAgentContext(
// prompt too. The allow-list has no counterpart to send: the backend
// loads no catalog skills of its own (`load_public_skills` is false).
disabled_skills: disabledSkills,
- ...(runtimeServicesSuffix || routerAtStartSuffix
- ? {
- system_message_suffix: [
- typeof existingContext.system_message_suffix === "string"
- ? existingContext.system_message_suffix
- : undefined,
- runtimeServicesSuffix,
- routerAtStartSuffix,
- ]
- .filter((s): s is string => Boolean(s))
- .join("\n\n"),
- }
- : {}),
- };
-}
-
-function isAcpAgent(settings: Settings): boolean {
- const agentSettings = toRecord(settings.agent_settings);
- return agentSettings.agent_kind === "acp";
-}
-
-function getAcpServerTag(settings: Settings): string | undefined {
- const agentSettings = toRecord(settings.agent_settings);
- const value = agentSettings.acp_server;
- return typeof value === "string" && value.length > 0 ? value : undefined;
-}
-
-function resolveAcpCommand(agentSettings: SettingsRecord): unknown {
- const cmd = agentSettings.acp_command;
- const isEmpty = Array.isArray(cmd) && cmd.length === 0;
- const noCommand = cmd === undefined;
- if (!isEmpty && !noCommand) {
- return cmd;
- }
-
- const serverKey =
- typeof agentSettings.acp_server === "string"
- ? agentSettings.acp_server
- : undefined;
- const provider = getAcpProvider(serverKey);
- return provider ? [...provider.default_command] : cmd;
-}
-
-function buildConfiguredAcpAgentSettings(
- settings: Settings,
- runtimeServicesInfo?: RuntimeServicesInfo | null,
- query?: string,
- hasActiveMetaProfile?: boolean,
-): AgentSettingsPayload {
- const agentSettings = toRecord(settings.agent_settings);
- const payload: AgentSettingsPayload = {
- agent_kind: "acp",
- agent_context: buildAgentContext(
- agentSettings,
- runtimeServicesInfo,
- toSkillEnablement(settings),
- findInvokedCatalogSkill(query),
- settings.run_router_at_conversation_start,
- hasActiveMetaProfile,
- ),
- };
-
- // TODO(#1019): set ``acp_isolate_data_dir: true`` here for a containerized
- // backend so concurrent same-provider conversations don't race on a shared
- // HOME. The SDK supports it (software-agent-sdk#3492), but the released
- // ``@openhands/typescript-client`` (1.24.3) doesn't surface it on
- // ``ACPAgentSettings`` yet, so sending it risks a validation error on older
- // servers. Cloud grouping isolation is separate (agent-canvas#1016).
-
- for (const key of ACP_SETTINGS_KEYS) {
- // ``acp_model`` is resolved separately below so a saved ``null`` still
- // falls back to the provider's default rather than being dropped.
- if (key === "acp_model") continue;
- // ``acp_env`` is deprecated — provider creds now route via ``request.secrets``.
- if (key === "acp_env") continue;
- const value =
- key === "acp_command"
- ? resolveAcpCommand(agentSettings)
- : agentSettings[key];
- if (value !== undefined && value !== null) {
- payload[key] = value;
- }
- }
-
- // ``mcp_config`` is a shared field (not in ACP_SETTINGS_KEYS): forward it
- // so the ACP subprocess connects to the configured MCP servers at session
- // creation. Only include it when it actually carries servers — an empty or
- // malformed value is dropped rather than sending ``mcp_config: {}``.
- const mcpConfig = toRecord(agentSettings.mcp_config);
- if (Object.keys(mcpConfig).length > 0) {
- payload.mcp_config = mcpConfig;
- }
-
- // 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
- : undefined;
- const effectiveModel = resolveEffectiveAcpModel({
- configured: agentSettings.acp_model as string | null | undefined,
- providerDefault: getAcpPreferredDefaultModel(serverKey),
- });
- if (effectiveModel) {
- payload.acp_model = effectiveModel;
- }
-
- return payload;
-}
-
-function buildConfiguredOpenHandsAgentSettings(
- settings: Settings,
- runtimeServicesInfo?: RuntimeServicesInfo | null,
- query?: string,
- hasActiveMetaProfile?: boolean,
-): AgentSettingsPayload {
- const agentSettings = toRecord(settings.agent_settings);
- const llm = buildNormalizedLlmSettings(agentSettings.llm);
-
- // Stream assistant tokens (parity with ACP agents). The agent-server only
- // emits StreamingDeltaEvents for SDK LLM agents when an LLM has stream=True.
- llm.stream = true;
-
- const mcpConfig = toRecord(agentSettings.mcp_config);
- if (Object.keys(mcpConfig).length === 0) {
- delete agentSettings.mcp_config;
- }
-
- delete agentSettings.acp_server;
- for (const key of ACP_SETTINGS_KEYS) {
- delete agentSettings[key];
- }
- // ``acp_env`` is no longer a forwarded ACP setting (provider creds ride the
- // Secrets panel), but a legacy value may linger on persisted settings —
- // scrub it so it never leaks onto the OpenHands payload.
- delete agentSettings.acp_env;
-
- return {
- ...agentSettings,
- llm,
- agent_context: buildAgentContext(
- agentSettings,
- runtimeServicesInfo,
- toSkillEnablement(settings),
- findInvokedCatalogSkill(query),
- settings.run_router_at_conversation_start,
- hasActiveMetaProfile,
- ),
- tools: getAgentTools(agentSettings),
};
}
-function buildConfiguredAgentSettings(
- settings: Settings,
- runtimeServicesInfo?: RuntimeServicesInfo | null,
- query?: string,
- hasActiveMetaProfile?: boolean,
-): AgentSettingsPayload {
- return isAcpAgent(settings)
- ? buildConfiguredAcpAgentSettings(
- settings,
- runtimeServicesInfo,
- query,
- hasActiveMetaProfile,
- )
- : buildConfiguredOpenHandsAgentSettings(
- settings,
- runtimeServicesInfo,
- query,
- hasActiveMetaProfile,
- );
-}
-
function buildConfiguredConversationSettings(options: {
settings: Settings;
query?: string;
@@ -1210,18 +950,18 @@ type StartConversationPayloadBase = Record<string, unknown> & {
tool_module_qualnames?: Record<string, string>;
};
-type AgentSettingsStartConversationPayload = StartConversationPayloadBase & {
- // Omitted when launching via ``agent_profile_id`` — the two are mutually
- // exclusive agent sources; the server resolves the profile server-side.
- agent_settings?: AgentSettingsPayload;
- agent_profile_id?: string;
+type ProfileStartConversationPayload = StartConversationPayloadBase & {
+ agent_profile_id: string;
agent_launch_additions?: {
// Appended to the profile-resolved agent's system-message suffix.
system_message_suffix_append?: string;
// Runs the profile with this LLM profile instead of its own.
llm_profile_ref?: string;
+ // Merged into the profile-resolved agent's skills by name.
+ skills?: BundledSkill[];
};
agent?: never;
+ agent_settings?: never;
};
// The local planner bypasses agent assembly entirely and sends a raw agent
@@ -1248,30 +988,21 @@ export interface StartConversationOptions {
parentConversationId?: string;
workingDir?: string;
worktree?: boolean;
- encryptedAgentSettings?: Record<string, SettingsValue>;
encryptedConversationSettings?: Record<string, SettingsValue>;
- secretsEncrypted?: boolean;
customSecrets?: CustomSecretInput[];
- // When set, the conversation launches from this AgentProfile (resolved
- // server-side) instead of an inline ``agent_settings`` dump (#3727).
- agentProfileId?: string;
+ /** The AgentProfile the server builds the agent from (#3727). */
+ agentProfileId: string;
agentProfileKind?: AgentKind;
/** LLM profile the agent profile runs with instead of its own. */
llmProfileOverride?: string;
+ /** The profile carries a Model Router, so router-at-start can apply. */
+ profileHasRouter?: boolean;
+ /** The ACP profile's server, stamped as the `acpserver` tag. */
+ acpServer?: string;
titleLlmProfile?: string;
runtimeServicesInfo?: RuntimeServicesInfo | null;
executionRuntime?: AgentServerInfo["execution_runtime"];
workspaceHookConfig?: HookConfig | null;
- /**
- * Whether a Model Router meta-profile is currently active. The
- * route-at-conversation-start system-message suffix is only emitted when
- * this is true AND ``settings.run_router_at_conversation_start`` is on —
- * without an active meta-profile the agent-server does not attach the
- * ``route_task_to_model`` tool, so the instruction would be a no-op (or
- * worse, tell the agent to call a tool it lacks). Defaults to false so a
- * sync caller that omits it never emits the suffix.
- */
- hasActiveMetaProfile?: boolean;
}
/**
@@ -1308,45 +1039,32 @@ export function buildCustomSecrets(
export function buildStartConversationRequest(
options: StartConversationOptions,
-): AgentSettingsStartConversationPayload {
- const sourceAgentSettings = options.encryptedAgentSettings
- ? { ...options.settings, agent_settings: options.encryptedAgentSettings }
- : options.settings;
-
- const acpMode = isAcpAgent(sourceAgentSettings);
- const launchAgentKind = options.agentProfileId
- ? options.agentProfileKind
- : acpMode
- ? "acp"
- : "openhands";
- const agentSettings = buildConfiguredAgentSettings(
- sourceAgentSettings,
- options.runtimeServicesInfo,
- options.query,
- options.hasActiveMetaProfile,
- );
- const savedSuffix = toRecord(
- toRecord(sourceAgentSettings.agent_settings).agent_context,
- ).system_message_suffix;
- // Router-at-start stays inline-only because profile-resolved agents do not
- // have the route_task_to_model tool.
- const profileLaunchSuffix = [
- typeof savedSuffix === "string" ? savedSuffix : undefined,
+): ProfileStartConversationPayload {
+ const launchSuffix = [
buildRuntimeServicesSystemSuffix(options.runtimeServicesInfo),
+ buildRouterAtStartSystemSuffix(
+ options.settings.run_router_at_conversation_start ?? false,
+ options.profileHasRouter ?? false,
+ ),
]
.filter((suffix): suffix is string => Boolean(suffix))
.join("\n\n");
+ // A catalog skill the opening message invokes loads for this conversation
+ // even when the profile does not select it.
+ const invokedSkillName =
+ options.agentProfileKind === "openhands"
+ ? findInvokedCatalogSkill(options.query)
+ : undefined;
+ const invokedSkill = invokedSkillName
+ ? buildBundledSkills().find((skill) => skill.name === invokedSkillName)
+ : undefined;
const launchAdditions = {
- ...(profileLaunchSuffix
- ? { system_message_suffix_append: profileLaunchSuffix }
- : {}),
+ ...(launchSuffix ? { system_message_suffix_append: launchSuffix } : {}),
...(options.llmProfileOverride
? { llm_profile_ref: options.llmProfileOverride }
: {}),
+ ...(invokedSkill ? { skills: [invokedSkill] } : {}),
};
- const acpServerTag = acpMode
- ? getAcpServerTag(sourceAgentSettings)
- : undefined;
const sourceConversationOptions = options.encryptedConversationSettings
? {
@@ -1363,39 +1081,11 @@ export function buildStartConversationRequest(
executionRuntime: options.executionRuntime,
});
- const payload: AgentSettingsStartConversationPayload = {
- // ``agent_profile_id`` and ``agent_settings`` are mutually exclusive agent
- // sources; the profile path lets the server resolve the profile (#3727).
- //
- // Enrichment boundary: on the profile path the server rebuilds the agent
- // purely from the stored profile fields, so the client-owned enrichments
- // this adapter folds into ``agent_settings`` do NOT apply. The exec toolset
- // (terminal/file_editor/task_tracker) and public-skill loading are the
- // server/SDK's responsibility to restore on the profile path — tracked in
- // software-agent-sdk#3967 (profile resolution must attach the default
- // toolset + public skills, else a profile-launched OpenHands agent has only
- // Finish/Think). The Canvas UI tool is a top-level client tool and
- // therefore works on both inline-agent and profile launch paths.
- //
- // The saved global suffix and ``RUNTIME_SERVICES`` are not part of the
- // stored profile, so the profile path sends them as
- // ``agent_launch_additions``.
- //
- // Persistent memory is NOT on that boundary: ``load_memory`` is a global
- // user preference, so the agent-server stamps the stored
- // ``agent_settings.agent_context.load_memory`` onto the profile-resolved
- // agent the same way it already applies the global ``mcp_config``. The
- // toggle therefore applies to both launch paths, and the client must not
- // re-send it here (``agent_profile_id`` and ``agent_settings`` are
- // mutually exclusive).
- ...(options.agentProfileId
- ? {
- agent_profile_id: options.agentProfileId,
- ...(Object.keys(launchAdditions).length > 0
- ? { agent_launch_additions: launchAdditions }
- : {}),
- }
- : { agent_settings: agentSettings }),
+ const payload: ProfileStartConversationPayload = {
+ agent_profile_id: options.agentProfileId,
+ ...(Object.keys(launchAdditions).length > 0
+ ? { agent_launch_additions: launchAdditions }
+ : {}),
workspace: conversationSettings.workspace,
// The agent-server caches each client tool's schema per tool *name* for the
// life of the process and rejects a re-registration with a different schema
@@ -1403,7 +1093,7 @@ export function buildStartConversationRequest(
// requires restarting a long-running dev agent-server before new
// conversations can start.
client_tools:
- launchAgentKind === "openhands"
+ options.agentProfileKind === "openhands"
? [
CANVAS_UI_CLIENT_TOOL,
LAUNCH_CHILD_CONVERSATION_CLIENT_TOOL,
@@ -1429,37 +1119,15 @@ export function buildStartConversationRequest(
// Stamp the client source tag so the agent-server can attribute the
// conversation to Canvas in telemetry (conversation_source = "canvas").
- // A profile launch resolves the ACP server server-side, so don't stamp the
- // tag from current settings (it may not match the launched profile).
- const baseTags = options.automationSetup
- ? buildAutomationSetupModeTags(options.automationSetupTags)
- : {};
- if (!options.agentProfileId && acpServerTag) {
- payload.tags = {
- ...baseTags,
- [ACP_SERVER_TAG_KEY]: acpServerTag,
- [CLIENT_SOURCE_TAG_KEY]: AGENT_CANVAS_SOURCE,
- };
- } else {
- payload.tags = {
- ...baseTags,
- [CLIENT_SOURCE_TAG_KEY]: AGENT_CANVAS_SOURCE,
- };
- }
-
- // ``secrets_encrypted`` makes the agent-server decrypt request secrets at
- // conversation start. Non-ACP conversations need it for encrypted LLM keys.
- // ACP normally carries provider credentials as LookupSecrets, so avoid
- // forcing a cipher on fresh ACP-only backends. The exception is MCP:
- // encrypted settings round-trip mcp_config secrets as Fernet tokens,
- // and ACP forwards mcp_config directly to the subprocess.
- if (
- !options.agentProfileId &&
- options.secretsEncrypted &&
- (!acpMode || hasEncryptedMcpSecrets(agentSettings.mcp_config))
- ) {
- payload.secrets_encrypted = true;
- }
+ payload.tags = {
+ ...(options.automationSetup
+ ? buildAutomationSetupModeTags(options.automationSetupTags)
+ : {}),
+ ...(options.agentProfileKind === "acp" && options.acpServer
+ ? { [ACP_SERVER_TAG_KEY]: options.acpServer }
+ : {}),
+ [CLIENT_SOURCE_TAG_KEY]: AGENT_CANVAS_SOURCE,
+ };
if (options.conversationId) {
payload.conversation_id = options.conversationId;
@@ -1522,7 +1190,7 @@ export function buildStartPlanningConversationRequest(options: {
customSecrets?: CustomSecretInput[];
/** Mirrors the parent's configured `conversation_settings.max_iterations` — see DEFAULT_MAX_ITERATIONS. */
maxIterations?: number;
- /** Mirrors the code agent's skill filtering — see buildConfiguredOpenHandsAgentSettings. */
+ /** The skills the parent's agent profile selects. */
skillEnablement?: SkillEnablement;
/** Mirrors the main conversation's workspace selection — see buildConfiguredConversationSettings. */
executionRuntime?: AgentServerInfo["execution_runtime"];
@@ -1538,11 +1206,10 @@ export function buildStartPlanningConversationRequest(options: {
const planPath = buildPlanPath(options.workingDir);
// Put the planner's directive + boundaries in the system prompt (matching the
- // OpenHands app-server's PLANNING_AGENT_INSTRUCTION), preserving any suffix
- // buildAgentContext already set (e.g. the runtime-services block).
+ // OpenHands app-server's PLANNING_AGENT_INSTRUCTION), preserving any saved
+ // suffix.
const agentContext = buildAgentContext(
agentSettings,
- undefined,
options.skillEnablement,
);
const existingSuffix = agentContext.system_message_suffix;
@@ -1693,6 +1360,36 @@ async function resolveAgentProfileLlmSettings(
}
}
+/**
+ * The skill selection of the parent's agent profile, or of the active one when
+ * the parent recorded none. `null` — caller falls back to the global lists —
+ * for an ACP profile or a failed lookup.
+ */
+async function resolveAgentProfileSkillEnablement(
+ agentProfileId: string | null | undefined,
+): Promise<SkillEnablement | null> {
+ try {
+ const { default: AgentProfilesService } =
+ await import("./agent-profiles-service/agent-profiles-service.api");
+ const { profiles, active_agent_profile_id: activeId } =
+ await AgentProfilesService.listProfiles();
+ const summary = profiles.find(
+ (profile) => profile.id === (agentProfileId ?? activeId),
+ );
+ if (summary?.agent_kind !== "openhands") return null;
+ const { profile } = await AgentProfilesService.getProfile(summary.name);
+ return profile.agent_kind === "openhands"
+ ? profileSkillEnablement(profile as StoredOpenHandsProfile)
+ : null;
+ } catch (error) {
+ console.warn(
+ "Falling back to global skill settings for the planner",
+ error,
+ );
+ return null;
+ }
+}
+
export async function buildStartPlanningConversationRequestWithEncryptedSettings(options: {
workingDir: string;
parentConversationId: string;
@@ -1717,10 +1414,12 @@ export async function buildStartPlanningConversationRequestWithEncryptedSettings
}): Promise<RawAgentStartConversationPayload> {
const { SecretsService } = await import("./secrets-service");
- const [settingsResult, customSecrets] = await Promise.all([
- SettingsService.getSettingsForConversation(),
- SecretsService.getSecrets(),
- ]);
+ const [settingsResult, customSecrets, profileSkillSelection] =
+ await Promise.all([
+ SettingsService.getSettingsForConversation(),
+ SecretsService.getSecrets(),
+ resolveAgentProfileSkillEnablement(options.parentAgentProfileId),
+ ]);
const profileLlm =
(options.parentActiveProfileName
@@ -1747,7 +1446,7 @@ export async function buildStartPlanningConversationRequestWithEncryptedSettings
secretsEncrypted: settingsResult.secretsEncrypted,
customSecrets,
maxIterations,
- skillEnablement: settingsResult.skillEnablement,
+ skillEnablement: profileSkillSelection ?? settingsResult.skillEnablement,
});
}
@@ -1785,9 +1484,11 @@ export async function buildStartConversationRequestWithEncryptedSettings(options
/** Workspace root for the hooks lookup, not the per-conversation `workingDir` (#16907). */
hooksProjectDir?: string | null;
worktree?: boolean;
- agentProfileId?: string;
+ agentProfileId: string;
agentProfileKind?: AgentKind;
llmProfileOverride?: string;
+ profileHasRouter?: boolean;
+ acpServer?: string;
titleLlmProfile?: string;
}): Promise<Record<string, unknown>> {
const [{ SecretsService }, { default: HooksService }] = await Promise.all([
@@ -1795,48 +1496,25 @@ export async function buildStartConversationRequestWithEncryptedSettings(options
import("./hooks-service"),
]);
- const [
- settingsResult,
- customSecrets,
- serverInfo,
- workspaceHookConfig,
- metaProfiles,
- ] = await Promise.all([
- SettingsService.getSettingsForConversation(),
- SecretsService.getSecrets(),
- fetchBackendServerInfo(),
- options.hooksProjectDir === null
- ? Promise.resolve(null)
- : HooksService.loadWorkspaceHooks(options.hooksProjectDir),
- // Best-effort: if the meta-profiles endpoint is unreachable we cannot
- // confirm a router is active, so fail closed (no route-at-start suffix).
- MetaProfilesService.listMetaProfiles().catch(() => null),
- ]);
-
- const { agentSettings, conversationSettings, secretsEncrypted } =
- settingsResult;
- const runtimeServicesInfo = parseRuntimeServicesInfo(
- (serverInfo as { runtime_services?: unknown } | null)?.runtime_services,
- );
- const executionRuntime = serverInfo?.execution_runtime;
- const hasActiveMetaProfile = !!metaProfiles?.active_meta_profile;
-
- // A profile launch resolves the LLM server-side, so the current-settings
- // subscription check doesn't apply (and can't see the profile's LLM).
- if (!options.agentProfileId) {
- await assertSubscriptionAuthReady(agentSettings);
- }
+ const [settingsResult, customSecrets, serverInfo, workspaceHookConfig] =
+ await Promise.all([
+ SettingsService.getSettingsForConversation(),
+ SecretsService.getSecrets(),
+ fetchBackendServerInfo(),
+ options.hooksProjectDir === null
+ ? Promise.resolve(null)
+ : HooksService.loadWorkspaceHooks(options.hooksProjectDir),
+ ]);
return buildStartConversationRequest({
...options,
- encryptedAgentSettings: agentSettings,
- encryptedConversationSettings: conversationSettings,
- secretsEncrypted,
+ encryptedConversationSettings: settingsResult.conversationSettings,
customSecrets,
- runtimeServicesInfo,
- executionRuntime,
+ runtimeServicesInfo: parseRuntimeServicesInfo(
+ (serverInfo as { runtime_services?: unknown } | null)?.runtime_services,
+ ),
+ executionRuntime: serverInfo?.execution_runtime,
workspaceHookConfig,
- hasActiveMetaProfile,
});
}
diff --git a/src/api/agent-server-compatibility.ts b/src/api/agent-server-compatibility.ts
index 78f3682321..7ad8a9e0d5 100644
--- a/src/api/agent-server-compatibility.ts
+++ b/src/api/agent-server-compatibility.ts
@@ -36,7 +36,6 @@ export interface AgentServerInfo extends BaseServerInfo {
sdk_version?: string;
runtime_services?: unknown;
execution_runtime?: "local" | "docker";
- capabilities?: string[];
}
let cachedAgentServerInfo: AgentServerInfo | null = null;
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 817ae41705..32b73bb42b 100644
--- a/src/api/conversation-service/agent-server-conversation-service.api.ts
+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts
@@ -441,22 +441,19 @@ export interface CreateConversationOptions {
parentConversationId?: string;
agentType?: "default" | "plan";
sandboxId?: string;
- // Launch from a saved AgentProfile (resolved server-side) instead of the
- // current encrypted agent_settings (#3727). Supported on both local and the
- // cloud app-server (OpenHands #15060): local threads it through the
- // encrypted-settings builder; cloud sends it as a flat request field.
+ // The saved AgentProfile the server builds the agent from (#3727). Required
+ // on local; cloud without one launches the org's default (OpenHands #15060).
agentProfileId?: string;
agentProfileKind?: AgentKind;
/**
- * Whether the first message should be routed through the active Model
- * Router. Only consumed on the cloud path — the local path reads the
- * toggle from its own settings fetch. Threaded in by the caller from the
- * warmed settings query to avoid a settings round-trip on the cloud hot
- * path.
+ * Cloud only: whether the first message should be routed through the
+ * active Model Router. The local path reads the toggle from its own
+ * settings fetch. Threaded in by the caller from the warmed settings query
+ * to avoid a settings round-trip on the cloud hot path.
*/
runRouterAtConversationStart?: boolean;
/**
- * Whether a Model Router meta-profile is currently active. The
+ * Cloud only: whether a Model Router meta-profile is currently active. The
* route-at-start suffix is only emitted when this is true AND
* ``runRouterAtConversationStart`` is on — without an active meta-profile
* the agent-server does not attach ``route_task_to_model``, so the
@@ -464,6 +461,10 @@ export interface CreateConversationOptions {
* by the caller from the warmed meta-profiles query.
*/
hasActiveMetaProfile?: boolean;
+ /** Local only: the launched profile carries a Model Router. */
+ profileHasRouter?: boolean;
+ /** Local only: the launched ACP profile's server, for the conversation tag. */
+ acpServer?: string;
// The LLM profile the launched agent profile runs. When set and no explicit
// title_llm_profile preference exists, title generation uses this profile so
// both the agent and its title use the same model.
@@ -529,6 +530,8 @@ class AgentServerConversationService {
agentProfileKind,
agentLlmProfileRef,
agentLlmProfileOverride,
+ profileHasRouter,
+ acpServer,
} = options;
if (getActiveBackend().backend.kind === "cloud") {
@@ -586,6 +589,9 @@ class AgentServerConversationService {
return createCloudAppConversation(request);
}
+ if (!agentProfileId) {
+ throw new Error("A local conversation needs an agent profile.");
+ }
const [settings, profiles] = await Promise.all([
SettingsService.getSettings(),
ProfilesService.listProfiles().catch(() => undefined),
@@ -626,6 +632,8 @@ class AgentServerConversationService {
agentProfileId,
agentProfileKind,
llmProfileOverride: agentLlmProfileOverride,
+ profileHasRouter,
+ acpServer,
titleLlmProfile,
});
diff --git a/src/api/settings-service/settings-service.api.ts b/src/api/settings-service/settings-service.api.ts
index bed02805ce..6366d60aff 100644
--- a/src/api/settings-service/settings-service.api.ts
+++ b/src/api/settings-service/settings-service.api.ts
@@ -42,6 +42,7 @@ export const APP_PREFERENCE_FIELDS = [
"enabled_skills",
"run_router_at_conversation_start",
"workspace_file_discovery",
+ "default_profile_migrated",
] as const;
export type AppPreferenceField = (typeof APP_PREFERENCE_FIELDS)[number];
diff --git a/src/components/features/chat/components/chat-input-actions.tsx b/src/components/features/chat/components/chat-input-actions.tsx
index de7765686a..54c94ba39a 100644
--- a/src/components/features/chat/components/chat-input-actions.tsx
+++ b/src/components/features/chat/components/chat-input-actions.tsx
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { Cpu } from "lucide-react";
import { AgentStatus } from "#/components/features/controls/agent-status";
import { ChangeAgentButton } from "../change-agent-button";
+import { ChatInputAgentProfilePicker } from "./chat-input-profile-picker";
import { ChatInputModel, ChatInputModelMenuContent } from "./chat-input-model";
import {
ChatInputLlmProfilePicker,
@@ -104,6 +105,7 @@ export function ChatInputActions({
const addFileRef = React.useRef<HTMLDivElement>(null);
const codeRef = React.useRef<HTMLDivElement>(null);
const modelRef = React.useRef<HTMLDivElement>(null);
+ const agentProfileRef = React.useRef<HTMLDivElement>(null);
const overflowTriggerRef = React.useRef<HTMLButtonElement>(null);
const [actionsRowWidth, setActionsRowWidth] = React.useState<number>(
Number.POSITIVE_INFINITY,
@@ -112,6 +114,7 @@ export function ChatInputActions({
const [addFileWidth, setAddFileWidth] = React.useState(32);
const [codeWidth, setCodeWidth] = React.useState(96);
const [modelWidth, setModelWidth] = React.useState(120);
+ const [agentProfileWidth, setAgentProfileWidth] = React.useState(110);
const [isOverflowOpen, setIsOverflowOpen] = React.useState(false);
const [activeSubmenu, setActiveSubmenu] = React.useState<
"agent" | "model" | null
@@ -125,6 +128,7 @@ export function ChatInputActions({
const addEl = addFileRef.current;
const codeEl = codeRef.current;
const modelEl = modelRef.current;
+ const agentProfileEl = agentProfileRef.current;
if (
!rowEl ||
@@ -152,6 +156,10 @@ export function ChatInputActions({
const nextCodeWidth = codeEl.getBoundingClientRect().width;
if (nextCodeWidth > 0) setCodeWidth(nextCodeWidth);
}
+ if (agentProfileEl) {
+ const nextAgentWidth = agentProfileEl.getBoundingClientRect().width;
+ if (nextAgentWidth > 0) setAgentProfileWidth(nextAgentWidth);
+ }
};
const observer = new ResizeObserver(() => {
@@ -165,11 +173,14 @@ export function ChatInputActions({
if (codeEl) {
observer.observe(codeEl);
}
+ if (agentProfileEl) {
+ observer.observe(agentProfileEl);
+ }
syncWidths();
return () => observer.disconnect();
- }, [showChangeAgentButton]);
+ }, [showChangeAgentButton, showAgentProfileSwitch]);
const handlePauseAgent = () => {
if (!conversationId) return;
@@ -194,6 +205,7 @@ export function ChatInputActions({
const next = {
showCodeInline: false,
showModelInline: false,
+ showAgentProfileInline: false,
};
if (showChangeAgentButton && remaining >= codeWidth) {
@@ -203,11 +215,23 @@ export function ChatInputActions({
if (remaining >= modelWidth) {
next.showModelInline = true;
+ remaining -= modelWidth + INLINE_GAP;
+ }
+
+ // Drops first: the "+" menu also switches the agent profile.
+ if (showAgentProfileSwitch && remaining >= agentProfileWidth) {
+ next.showAgentProfileInline = true;
}
return next;
},
- [showChangeAgentButton, codeWidth, modelWidth],
+ [
+ showChangeAgentButton,
+ codeWidth,
+ modelWidth,
+ showAgentProfileSwitch,
+ agentProfileWidth,
+ ],
);
const leftBaseWidth =
@@ -226,6 +250,7 @@ export function ChatInputActions({
? false
: fitWithOverflow.showCodeInline;
const showModelInline = fitWithOverflow.showModelInline;
+ const showAgentProfileInline = fitWithOverflow.showAgentProfileInline;
const showAddFileInline = true;
const showAgentStatusInline = actionsRowWidth >= 360;
@@ -496,6 +521,14 @@ export function ChatInputActions({
<ChangeAgentButton />
</div>
)}
+ {showAgentProfileSwitch && (
+ <div
+ ref={agentProfileRef}
+ className={cn(!showAgentProfileInline && "hidden")}
+ >
+ <ChatInputAgentProfilePicker />
+ </div>
+ )}
<div ref={modelRef} className={cn(!showModelInline && "hidden")}>
{/* Picker depends on backend + ACP context; see the `pickerKind`
cases above. */}
diff --git a/src/components/features/chat/components/chat-input-profile-picker.tsx b/src/components/features/chat/components/chat-input-profile-picker.tsx
index 1484a8b4ab..f2d1cd5b4a 100644
--- a/src/components/features/chat/components/chat-input-profile-picker.tsx
+++ b/src/components/features/chat/components/chat-input-profile-picker.tsx
@@ -1,5 +1,11 @@
+import React from "react";
import { useTranslation } from "react-i18next";
import { useChatInputProfileState } from "#/hooks/use-chat-input-profile-state";
+import { useClickOutsideElement } from "#/hooks/use-click-outside-element";
+import RobotIcon from "#/icons/u-robot.svg?react";
+import { ContextMenu } from "#/ui/context-menu";
+import { ComboboxCaretInline } from "#/ui/combobox-caret";
+import { chatInputPillButtonClassName } from "#/utils/form-control-classes";
import SettingsGearIcon from "#/icons/settings-gear.svg?react";
import CheckIcon from "#/icons/checkmark.svg?react";
import { NavigationLink } from "#/components/shared/navigation-link";
@@ -22,8 +28,8 @@ interface ChatInputProfileMenuContentProps {
* profile" submenu, offered only while starting a new conversation (OSS-5735 —
* the profile is locked once a conversation starts). Selecting a profile
* activates it (home) or recreates the blank conversation with it (see
- * `useChatInputProfileState`). The chat-input pill itself is always an LLM
- * selector; the former `ChatInputProfilePicker` pill is gone.
+ * `useChatInputProfileState`). Also the menu of the
+ * {@link ChatInputAgentProfilePicker} pill.
*/
export function ChatInputProfileMenuContent({
onClose,
@@ -133,3 +139,56 @@ export function ChatInputProfileMenuContent({
</>
);
}
+
+/** Names the agent profile a new conversation will run, and switches it. */
+export function ChatInputAgentProfilePicker() {
+ const { t } = useTranslation("openhands");
+ const { currentProfileName, isLoading, isSwitching } =
+ useChatInputProfileState();
+ const [isOpen, setIsOpen] = React.useState(false);
+ const triggerRef = React.useRef<HTMLButtonElement>(null);
+ const popoverRef = useClickOutsideElement<HTMLUListElement>(
+ () => setIsOpen(false),
+ triggerRef,
+ );
+
+ if (isLoading || !currentProfileName) return null;
+
+ return (
+ <div className="relative min-w-0">
+ <button
+ ref={triggerRef}
+ type="button"
+ className={cn(chatInputPillButtonClassName, "max-w-40")}
+ title={t(I18nKey.CHAT$SWITCH_AGENT_PROFILE)}
+ aria-label={`${t(I18nKey.CHAT$SWITCH_AGENT_PROFILE)}: ${currentProfileName}`}
+ data-testid="chat-input-agent-profile"
+ aria-expanded={isOpen}
+ aria-haspopup="dialog"
+ disabled={isSwitching}
+ aria-busy={isSwitching}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setIsOpen((open) => !open);
+ }}
+ >
+ <RobotIcon width={14} height={14} className="shrink-0" aria-hidden />
+ <span className="truncate">{currentProfileName}</span>
+ <ComboboxCaretInline isOpen={isOpen} />
+ </button>
+ {isOpen && (
+ <ContextMenu
+ ref={popoverRef}
+ testId="chat-input-agent-profile-popover"
+ position="top"
+ alignment="left"
+ spacing="none"
+ className="z-[60] mb-2 min-w-50 max-w-80 max-h-[60vh] overflow-y-auto"
+ >
+ <ChatInputProfileMenuContent onClose={() => setIsOpen(false)} />
+ </ContextMenu>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/features/command-menu/command-menu-items.tsx b/src/components/features/command-menu/command-menu-items.tsx
index ab6dea1c4b..6c73b94ded 100644
--- a/src/components/features/command-menu/command-menu-items.tsx
+++ b/src/components/features/command-menu/command-menu-items.tsx
@@ -22,6 +22,7 @@ import {
hasAutomationInterface,
} from "#/manifests/automation-interface";
import { getLockedCloudHost } from "#/api/agent-server-config";
+import { getActiveBackend } from "#/api/backend-registry/active-store";
import { LOCKED_CLOUD_SETTINGS_NAV_PATH } from "#/constants/settings-nav";
import { isApplePlatform } from "#/utils/utils";
@@ -254,12 +255,15 @@ export const createCommandMenuItems = ({
// Locked-to-Cloud (SaaS / self-hosted OHE) lists only the Application page;
// the OHE settings shell owns the rest (OHE-3168).
const isLockedToCloud = getLockedCloudHost() !== null;
+ // Locally each agent profile has its own condenser.
+ const isCloud = getActiveBackend().backend.kind === "cloud";
return items.filter(
(item) =>
- !isLockedToCloud ||
- item.group !== "settings" ||
- item.to === COMMAND_MENU_ROUTE.settings ||
- item.to === LOCKED_CLOUD_SETTINGS_NAV_PATH,
+ (isCloud || item.to !== COMMAND_MENU_ROUTE.condenserSettings) &&
+ (!isLockedToCloud ||
+ item.group !== "settings" ||
+ item.to === COMMAND_MENU_ROUTE.settings ||
+ item.to === LOCKED_CLOUD_SETTINGS_NAV_PATH),
);
};
diff --git a/src/components/features/conversation-panel/skills-modal.tsx b/src/components/features/conversation-panel/skills-modal.tsx
index f3c0506fa2..f4f898cd87 100644
--- a/src/components/features/conversation-panel/skills-modal.tsx
+++ b/src/components/features/conversation-panel/skills-modal.tsx
@@ -8,6 +8,7 @@ import {
import { I18nKey } from "#/i18n/declaration";
import { getAgentServerWorkingDir } from "#/api/agent-server-config";
import { useConversationSkills } from "#/hooks/query/use-conversation-skills";
+import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { useSkillEnabledFilter } from "#/hooks/use-skill-enablement";
import {
groupSkillsByScope,
@@ -46,7 +47,10 @@ export function SkillsModal({ onClose }: SkillsModalProps) {
refetch,
isRefetching,
} = useConversationSkills();
- const isSkillEnabled = useSkillEnabledFilter();
+ const { data: conversation } = useActiveConversation();
+ const isSkillEnabled = useSkillEnabledFilter(
+ conversation?.launched_agent_profile?.agent_profile_id,
+ );
// The modal reports what the conversation actually has, so it lists the
// enabled set rather than the whole catalog.
diff --git a/src/components/features/settings/agent-profiles/agent-profile-actions-menu.tsx b/src/components/features/settings/agent-profiles/agent-profile-actions-menu.tsx
index beca508dd8..5a7d0425a1 100644
--- a/src/components/features/settings/agent-profiles/agent-profile-actions-menu.tsx
+++ b/src/components/features/settings/agent-profiles/agent-profile-actions-menu.tsx
@@ -26,6 +26,8 @@ interface AgentProfileActionsMenuProps {
onEdit: () => void;
onSetActive: () => void;
onDelete: () => void;
+ /** Disables Delete and explains why. */
+ deleteDisabledReason?: string;
isActive: boolean;
isActivating: boolean;
onClose: () => void;
@@ -41,6 +43,7 @@ export function AgentProfileActionsMenu({
onEdit,
onSetActive,
onDelete,
+ deleteDisabledReason,
isActive,
isActivating,
onClose,
@@ -178,6 +181,8 @@ export function AgentProfileActionsMenu({
onClick={() => handleAction(onDelete)}
onKeyDown={handleKeyDown}
menuItemsRef={menuItemsRef}
+ disabled={Boolean(deleteDisabledReason)}
+ title={deleteDisabledReason}
testId="agent-profile-delete"
/>
</div>
diff --git a/src/components/features/settings/agent-profiles/agent-profile-row.tsx b/src/components/features/settings/agent-profiles/agent-profile-row.tsx
index cbcfdc31a7..42cabd4fc5 100644
--- a/src/components/features/settings/agent-profiles/agent-profile-row.tsx
+++ b/src/components/features/settings/agent-profiles/agent-profile-row.tsx
@@ -1,7 +1,11 @@
import { useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { AgentProfileActionsMenu } from "./agent-profile-actions-menu";
-import { type AgentProfileSummary } from "#/api/agent-profiles-service/agent-profiles-service.api";
+import {
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,
+ type AgentProfileSummary,
+} from "#/api/agent-profiles-service/agent-profiles-service.api";
+import { useActiveBackend } from "#/contexts/active-backend-context";
import { I18nKey } from "#/i18n/declaration";
import { EllipsisButton } from "#/components/features/conversation-panel/ellipsis-button";
import { BrandBadge } from "#/components/shared/badge";
@@ -32,6 +36,12 @@ export function AgentProfileRow({
isActivating,
}: AgentProfileRowProps) {
const { t } = useTranslation("openhands");
+ const { backend } = useActiveBackend();
+ // The server reseeds a deleted `default`, which would reset what it shares
+ // with the global pages.
+ const isProtected =
+ backend.kind === "local" &&
+ profile.name === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME;
const [menuOpen, setMenuOpen] = useState(false);
const triggerRef = useRef<HTMLButtonElement>(null);
@@ -66,7 +76,7 @@ export function AgentProfileRow({
className="shrink-0 whitespace-nowrap px-2.5 py-1 text-xs"
data-testid="agent-profile-active-badge"
>
- {t(I18nKey.SETTINGS$PROFILE_DEFAULT)}
+ {t(I18nKey.SETTINGS$PROFILE_ACTIVE)}
</BrandBadge>
)}
</div>
@@ -85,6 +95,11 @@ export function AgentProfileRow({
onEdit={() => onEdit(profile)}
onSetActive={() => onActivate(profile)}
onDelete={() => onDelete(profile)}
+ deleteDisabledReason={
+ isProtected
+ ? t(I18nKey.SETTINGS$AGENT_PROFILE_DEFAULT_LOCKED)
+ : undefined
+ }
isActive={isActive}
isActivating={isActivating}
onClose={() => setMenuOpen(false)}
diff --git a/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx b/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx
index e54648fc7b..763bf84c69 100644
--- a/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx
+++ b/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx
@@ -1,8 +1,11 @@
import { useCallback, useEffect, useMemo, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { ensureDefaultAgentProfileMigrated } from "#/hooks/use-migrate-default-agent-profile";
import { useTranslation } from "react-i18next";
import { AgentProfilesManager } from "./agent-profiles-manager";
-import { GlobalToolsNotice } from "./global-tools-notice";
import { mergeAgentProfileSaveInput } from "./merge-agent-profile-save-input";
+import { newProfileSeed } from "./new-profile-seed";
import { ProfileNameInput } from "#/components/features/settings/llm-profiles/profile-name-input";
import { BrandButton } from "#/components/features/settings/brand-button";
import { SettingsDropdownInput } from "#/components/features/settings/settings-dropdown-input";
@@ -38,6 +41,12 @@ import {
defaultSkillEnablement,
toProfileSkillFields,
} from "#/utils/skill-enablement";
+import {
+ applyDefaultAgentProfileToGlobal,
+ enabledMcpServerRefs,
+ sharedDefaultProfileFields,
+} from "#/hooks/mutation/sync-agent-profiles";
+import type { Settings } from "#/types/settings";
type ViewMode = "list" | "create" | "edit";
@@ -85,6 +94,18 @@ function toAgentSettingsOverride(
};
}
+/** An OpenHands `default` opens on the MCP servers switched on and every secret. */
+function defaultProfileOverride(
+ profile: AgentProfile,
+ settings: Settings | undefined,
+): Record<string, SettingsValue> {
+ return {
+ ...toAgentSettingsOverride(profile),
+ mcp_server_refs: enabledMcpServerRefs(settings),
+ secret_refs: null,
+ };
+}
+
/**
* AgentProfilesLocalView mirrors {@link LlmSettingsLocalView}: a list of the
* user's Agent profiles, with a create/edit view that reuses the existing Agent
@@ -100,12 +121,24 @@ export function AgentProfilesLocalView() {
const { data: llmProfilesData, isLoading: isLlmProfilesLoading } =
useLlmProfiles();
const { data: settings } = useSettings();
+ const queryClient = useQueryClient();
+ const { backend } = useActiveBackend();
+ // Edits must build on, and land after, the one-time `default` migration.
+ const waitForMigration = useCallback(
+ () =>
+ backend.kind === "local"
+ ? ensureDefaultAgentProfileMigrated(queryClient, backend.id)
+ : Promise.resolve(true as const),
+ [backend.kind, backend.id, queryClient],
+ );
const [viewMode, setViewMode] = useState<ViewMode>("list");
const [profileName, setProfileName] = useState("");
+ const [nameTouched, setNameTouched] = useState(false);
const [editingProfile, setEditingProfile] = useState<AgentProfile | null>(
null,
);
+ const [seedProfile, setSeedProfile] = useState<AgentProfile | null>(null);
const [override, setOverride] = useState<Record<
string,
SettingsValue
@@ -140,24 +173,41 @@ export function AgentProfilesLocalView() {
(viewMode === "edit" && profileName !== editingProfile?.name));
const isNameValid = isNameFormatValid && !isDuplicateName;
- const handleAddProfile = useCallback(() => {
+ const handleAddProfile = useCallback(async () => {
+ let seed: AgentProfile | null = null;
+ if (backend.kind === "local") {
+ try {
+ await waitForMigration();
+ const { profile } = await AgentProfilesService.getProfile(
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,
+ );
+ seed = newProfileSeed(profile);
+ } catch {
+ // Without a readable `default`, the editor starts from its own values.
+ }
+ }
setProfileName("");
+ setNameTouched(false);
setEditingProfile(null);
- // A new profile starts from the skills selected on the Skills page.
+ setSeedProfile(seed);
+ // A new profile copies an OpenHands `default`, skills included.
setOverride({
+ ...(seed
+ ? toAgentSettingsOverride(seed)
+ : agentProfileSupportsSkills()
+ ? toProfileSkillFields(defaultSkillEnablement(settings ?? {}))
+ : {}),
agent_kind: "openhands",
- ...(agentProfileSupportsSkills()
- ? toProfileSkillFields(defaultSkillEnablement(settings ?? {}))
- : {}),
});
setLlmProfileRef(defaultLlmProfileRef);
setSaveControl(null);
setViewMode("create");
- }, [defaultLlmProfileRef, settings]);
+ }, [backend.kind, waitForMigration, defaultLlmProfileRef, settings]);
const handleEditProfile = useCallback(
async (summary: AgentProfileSummary) => {
try {
+ await waitForMigration();
// Fetch with encrypted secret exposure so any `skills[].mcp_tools`
// values arrive as Fernet tokens rather than masks — the save below
// round-trips the stored profile, and posting back a mask would
@@ -167,9 +217,22 @@ export function AgentProfilesLocalView() {
"encrypted",
);
const profile = detail.profile;
+ const isDefault =
+ profile.name === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME;
setEditingProfile(profile);
- setOverride(toAgentSettingsOverride(profile));
- if (profile.agent_kind === "openhands") {
+ setOverride(
+ isDefault && profile.agent_kind === "openhands"
+ ? defaultProfileOverride(profile, settings)
+ : toAgentSettingsOverride(profile),
+ );
+ if (isDefault) {
+ setLlmProfileRef(
+ defaultLlmProfileRef ||
+ (profile.agent_kind === "openhands"
+ ? profile.llm_profile_ref
+ : ""),
+ );
+ } else if (profile.agent_kind === "openhands") {
// A profile can reference an LLM profile that's since been deleted
// (or renamed): the dropdown would render nothing selected while
// `llmProfileRef` still holds the stale name and saves it straight
@@ -194,13 +257,22 @@ export function AgentProfilesLocalView() {
displayErrorToast(t(I18nKey.ERROR$GENERIC));
}
},
- [t, llmProfiles, isLlmProfilesLoading, defaultLlmProfileRef],
+ [
+ t,
+ llmProfiles,
+ isLlmProfilesLoading,
+ defaultLlmProfileRef,
+ waitForMigration,
+ settings,
+ ],
);
const handleBackToList = useCallback(() => {
setViewMode("list");
setEditingProfile(null);
+ setSeedProfile(null);
setProfileName("");
+ setNameTouched(false);
setOverride(null);
setSaveControl(null);
}, []);
@@ -236,9 +308,15 @@ export function AgentProfilesLocalView() {
const originalName = editingProfile?.name;
const isRename =
viewMode === "edit" && originalName && originalName !== trimmedName;
+ const savesDefault =
+ viewMode === "edit" &&
+ originalName === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME &&
+ trimmedName === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME &&
+ input.agent_kind === "openhands";
setIsSaving(true);
try {
+ await waitForMigration();
// Persist ACP credentials (global secrets) before the profile spec.
if (saveControl.credentials.isDirty) {
const ok = await saveControl.credentials.save({ silent: true });
@@ -259,10 +337,12 @@ export function AgentProfilesLocalView() {
// the edited fields so the fields this editor doesn't model survive an
// edit (kind-aware — a kind switch stays a clean variant replacement).
const profile = mergeAgentProfileSaveInput(
- viewMode === "edit" ? editingProfile : null,
- input,
+ viewMode === "edit" ? editingProfile : seedProfile,
+ savesDefault ? sharedDefaultProfileFields(input) : input,
);
await saveProfile.mutateAsync({ name: trimmedName, profile });
+ if (savesDefault)
+ await applyDefaultAgentProfileToGlobal(queryClient, input);
displaySuccessToast(
viewMode === "create"
@@ -283,16 +363,18 @@ export function AgentProfilesLocalView() {
profileName,
viewMode,
editingProfile,
+ seedProfile,
saveProfile,
renameProfile,
t,
handleBackToList,
+ waitForMigration,
+ queryClient,
]);
if (viewMode === "list") {
return (
<div className="flex flex-col gap-4">
- <GlobalToolsNotice />
<AgentProfilesManager
onAddProfile={handleAddProfile}
onEditProfile={handleEditProfile}
@@ -310,6 +392,13 @@ export function AgentProfilesLocalView() {
? t(I18nKey.SETTINGS$PROFILE_LOADED, { name: editingProfile.name })
: t(I18nKey.SETTINGS$AGENT_PROFILE_SAVE_HINT);
const isOpenHands = saveControl?.agentType !== "acp";
+ const isDefaultLocked =
+ viewMode === "edit" &&
+ editingProfile?.name === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME;
+ const isEditingDefault =
+ viewMode === "edit" &&
+ editingProfile?.name === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME &&
+ profileName.trim() === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME;
const nameDirty = viewMode === "edit" && profileName !== editingProfile?.name;
const loadedLlmRef =
editingProfile?.agent_kind === "openhands"
@@ -323,6 +412,40 @@ export function AgentProfilesLocalView() {
nameDirty ||
llmRefDirty;
+ // @spec FF-001 — Profile validation feedback follows the host error role
+ // OpenHands profiles reference an LLM profile (required).
+ const llmPicker =
+ llmProfiles.length > 0 ? (
+ <div className="flex flex-col gap-2">
+ <SettingsDropdownInput
+ testId="agent-profile-llm-selector"
+ name="agent-profile-llm"
+ label={t(I18nKey.SETTINGS$AGENT_PROFILE_LLM_LABEL)}
+ items={llmProfiles.map((p) => ({
+ key: p.name,
+ label: p.model ? `${p.name} (${p.model})` : p.name,
+ }))}
+ selectedKey={llmProfileRef}
+ onSelectionChange={(key) => key && setLlmProfileRef(String(key))}
+ />
+ {isEditingDefault ? (
+ <p
+ data-testid="agent-profile-llm-default-note"
+ className="text-xs text-tertiary-alt"
+ >
+ {t(I18nKey.SETTINGS$AGENT_PROFILE_DEFAULT_LLM_NOTE)}
+ </p>
+ ) : null}
+ </div>
+ ) : (
+ <p
+ data-testid="agent-profile-no-llm"
+ className="text-sm text-feedback-error"
+ >
+ {t(I18nKey.SETTINGS$AGENT_PROFILE_NO_LLM)}
+ </p>
+ );
+
return (
<div className="flex flex-col gap-6">
<div className="flex flex-col gap-2">
@@ -343,52 +466,42 @@ export function AgentProfilesLocalView() {
</p>
</div>
- <ProfileNameInput
- testId="agent-profile-name-input"
- value={profileName}
- onChange={setProfileName}
- isRequired
- error={
- isDuplicateName
- ? t(I18nKey.SETTINGS$AGENT_PROFILE_NAME_TAKEN)
- : undefined
- }
- />
+ <div className="flex flex-col gap-2">
+ <ProfileNameInput
+ testId="agent-profile-name-input"
+ value={profileName}
+ onChange={(name) => {
+ setNameTouched(true);
+ setProfileName(name);
+ }}
+ // A new profile's empty name isn't an error until the user types.
+ isRequired={viewMode === "edit" || nameTouched}
+ isDisabled={isDefaultLocked}
+ error={
+ isDuplicateName
+ ? t(I18nKey.SETTINGS$AGENT_PROFILE_NAME_TAKEN)
+ : undefined
+ }
+ />
+ {isDefaultLocked ? (
+ <p
+ data-testid="agent-profile-default-locked-note"
+ className="text-xs text-tertiary-alt"
+ >
+ {t(I18nKey.SETTINGS$AGENT_PROFILE_DEFAULT_LOCKED)}
+ </p>
+ ) : null}
+ </div>
{/* Reuse the existing Agent settings form to define the agent. */}
<AgentSettingsScreen
key={viewMode === "edit" ? `edit-${editingProfile?.id}` : "new-profile"}
agentSettingsOverride={override}
onSaveControlChange={setSaveControl}
- isDefaultProfile={
- profileName.trim() === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME
- }
+ isDefaultProfile={isEditingDefault}
+ llmPicker={llmPicker}
/>
- {/* @spec FF-001 — Profile validation feedback follows the host error role */}
- {/* OpenHands profiles reference an LLM profile (required). */}
- {isOpenHands &&
- (llmProfiles.length > 0 ? (
- <SettingsDropdownInput
- testId="agent-profile-llm-selector"
- name="agent-profile-llm"
- label={t(I18nKey.SETTINGS$AGENT_PROFILE_LLM_LABEL)}
- items={llmProfiles.map((p) => ({
- key: p.name,
- label: p.model ? `${p.name} (${p.model})` : p.name,
- }))}
- selectedKey={llmProfileRef}
- onSelectionChange={(key) => key && setLlmProfileRef(String(key))}
- />
- ) : (
- <p
- data-testid="agent-profile-no-llm"
- className="text-sm text-feedback-error"
- >
- {t(I18nKey.SETTINGS$AGENT_PROFILE_NO_LLM)}
- </p>
- ))}
-
<div className="flex justify-start gap-3 pt-4">
<BrandButton
testId="cancel-agent-profile-btn"
diff --git a/src/components/features/settings/agent-profiles/delete-agent-profile-modal.tsx b/src/components/features/settings/agent-profiles/delete-agent-profile-modal.tsx
index 92e8327f3e..d070bc23c0 100644
--- a/src/components/features/settings/agent-profiles/delete-agent-profile-modal.tsx
+++ b/src/components/features/settings/agent-profiles/delete-agent-profile-modal.tsx
@@ -85,7 +85,7 @@ export function DeleteAgentProfileModal({
onClose={handleClose}
initialFocusRef={cancelButtonRef}
>
- <p className="text-sm break-all">
+ <p className="text-sm break-words">
{t(I18nKey.SETTINGS$PROFILE_DELETE_CONFIRMATION, {
name: profile.name,
})}
diff --git a/src/components/features/settings/agent-profiles/global-tools-notice.tsx b/src/components/features/settings/agent-profiles/global-tools-notice.tsx
deleted file mode 100644
index c9ca785508..0000000000
--- a/src/components/features/settings/agent-profiles/global-tools-notice.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { AxiosError } from "axios";
-import { BrandButton } from "#/components/features/settings/brand-button";
-import { useSettings } from "#/hooks/query/use-settings";
-import { useSaveSettings } from "#/hooks/mutation/use-save-settings";
-import { readProfileTools } from "#/constants/profile-tools";
-import { agentProfileSupportsTools } from "#/api/agent-profiles-service/profile-field-support";
-import { Typography } from "#/ui/typography";
-import { I18nKey } from "#/i18n/declaration";
-import { cn } from "#/utils/utils";
-import { settingsListContainerClassName } from "#/utils/settings-list-classes";
-import {
- displayErrorToast,
- displaySuccessToast,
-} from "#/utils/custom-toast-handlers";
-import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
-
-/** Surface a custom global `tools` list, which no editor shows, and reset it. */
-export function GlobalToolsNotice() {
- const { t } = useTranslation("openhands");
- const { data: settings } = useSettings();
- const { mutate: saveSettings, isPending } = useSaveSettings();
-
- const agentSettings = settings?.agent_settings;
- if (!agentProfileSupportsTools()) return null;
- if (!agentSettings || agentSettings.agent_kind === "acp") return null;
- const tools = readProfileTools(agentSettings.tools);
- if (tools.mode !== "custom") return null;
-
- const handleReset = () =>
- saveSettings(
- { agent_settings_diff: { tools: null } },
- {
- onError: (error) => {
- const message = retrieveAxiosErrorMessage(error as AxiosError);
- displayErrorToast(message || t(I18nKey.ERROR$GENERIC));
- },
- onSuccess: () => displaySuccessToast(t(I18nKey.SETTINGS$SAVED)),
- },
- );
-
- return (
- <div
- data-testid="global-tools-notice"
- className={cn(
- settingsListContainerClassName,
- "flex flex-wrap items-center justify-between gap-3 p-3",
- )}
- >
- <Typography.Text className="text-sm">
- {t(I18nKey.SETTINGS$GLOBAL_TOOLS_CUSTOM, {
- names: tools.selected.join(", ") || "—",
- })}
- </Typography.Text>
- <BrandButton
- testId="global-tools-reset"
- type="button"
- variant="secondary"
- isDisabled={isPending}
- onClick={handleReset}
- >
- {t(I18nKey.SETTINGS$GLOBAL_TOOLS_RESET)}
- </BrandButton>
- </div>
- );
-}
diff --git a/src/components/features/settings/agent-profiles/merge-agent-profile-save-input.ts b/src/components/features/settings/agent-profiles/merge-agent-profile-save-input.ts
index 788540da83..40208c78e4 100644
--- a/src/components/features/settings/agent-profiles/merge-agent-profile-save-input.ts
+++ b/src/components/features/settings/agent-profiles/merge-agent-profile-save-input.ts
@@ -1,3 +1,4 @@
+import { DEFAULT_ENABLED_SKILL_NAMES } from "@openhands/extensions/skills";
import type {
AgentProfile,
AgentProfileSaveInput,
@@ -6,14 +7,16 @@ import type {
/**
* Merge the minimal editor's fields over the stored profile so an edit-save
* doesn't wipe the fields the editor doesn't model (condenser, verification,
- * mcp_server_refs, the disabled_skills deny-list, ACP session mode/timeout,
+ * mcp_server_refs, the skill lists, ACP session mode/timeout,
* …) — `POST /api/agent-profiles/{name}` is a
* whole-profile overwrite, and unset fields fall back to server-side defaults.
*
* Kind-aware: when the editor switched `agent_kind`, the stored variant's
* fields must NOT be carried over — the server's `extra="forbid"` profile
* union rejects a payload mixing openhands and acp fields — so a kind switch
- * stays a clean variant replacement built from the edited fields alone.
+ * stays a clean variant replacement built from the edited fields alone. A new
+ * OpenHands variant selects the recommended catalog skills, not the server's
+ * default of all of them (OpenHands#16302).
*
* Identity (`id` / `name` / `revision`) is stripped from the merge: the path
* name is authoritative on save, and the server preserves the namesake's id
@@ -23,8 +26,15 @@ export function mergeAgentProfileSaveInput(
stored: AgentProfile | null,
edited: AgentProfileSaveInput,
): AgentProfileSaveInput {
- if (!stored) return edited;
- if (stored.agent_kind !== edited.agent_kind) return edited;
- const { id, name, revision, ...preserved } = stored;
- return { ...preserved, ...edited } as AgentProfileSaveInput;
+ if (stored?.agent_kind === edited.agent_kind) {
+ const { id, name, revision, ...preserved } = stored;
+ return { ...preserved, ...edited } as AgentProfileSaveInput;
+ }
+ if (edited.agent_kind === "openhands" && !("public_skills" in edited)) {
+ return {
+ ...edited,
+ public_skills: [...DEFAULT_ENABLED_SKILL_NAMES],
+ } as AgentProfileSaveInput;
+ }
+ return edited;
}
diff --git a/src/components/features/settings/agent-profiles/new-profile-seed.ts b/src/components/features/settings/agent-profiles/new-profile-seed.ts
new file mode 100644
index 0000000000..f86a98ebcc
--- /dev/null
+++ b/src/components/features/settings/agent-profiles/new-profile-seed.ts
@@ -0,0 +1,18 @@
+import type { AgentProfile } from "#/api/agent-profiles-service/agent-profiles-service.api";
+
+/** A new profile starts with every MCP server and secret, on the LLM picker's pick. */
+const NOT_COPIED_FROM_DEFAULT = [
+ "llm_profile_ref",
+ "mcp_server_refs",
+ "secret_refs",
+] as const;
+
+/** The settings a new profile copies from an OpenHands `default`. */
+export function newProfileSeed(
+ defaultProfile: AgentProfile | null | undefined,
+): AgentProfile | null {
+ if (defaultProfile?.agent_kind !== "openhands") return null;
+ const seed: Record<string, unknown> = { ...defaultProfile };
+ NOT_COPIED_FROM_DEFAULT.forEach((key) => delete seed[key]);
+ return seed as unknown as AgentProfile;
+}
diff --git a/src/components/features/settings/agent-profiles/profile-behavior-form.ts b/src/components/features/settings/agent-profiles/profile-behavior-form.ts
index 15ebea5e93..51f4e8c17f 100644
--- a/src/components/features/settings/agent-profiles/profile-behavior-form.ts
+++ b/src/components/features/settings/agent-profiles/profile-behavior-form.ts
@@ -30,6 +30,14 @@ function profileFields(
);
}
+/** Keys of the section's fields each profile stores. */
+export function profileBehaviorFieldKeys(
+ schema: SettingsSchema | null | undefined,
+ section: ProfileBehaviorSection,
+): string[] {
+ return profileFields(schema, section).map((field) => field.key);
+}
+
/** A stored profile section as form values; fields it lacks take the schema default. */
export function toBehaviorFormValues(
schema: SettingsSchema | null | undefined,
diff --git a/src/components/features/settings/llm-profiles/llm-settings-local-view.tsx b/src/components/features/settings/llm-profiles/llm-settings-local-view.tsx
index f43526044d..533ff516ae 100644
--- a/src/components/features/settings/llm-profiles/llm-settings-local-view.tsx
+++ b/src/components/features/settings/llm-profiles/llm-settings-local-view.tsx
@@ -406,9 +406,9 @@ export function LlmSettingsLocalView() {
},
});
- // Conversation start uses agent_settings.llm, not the profile row
- // directly. Re-applying an active profile keeps those settings in sync
- // after editing or recreating a profile with the active profile name.
+ // Activation copies the profile into agent_settings.llm, which the
+ // planner falls back to. Re-applying an active profile keeps that copy
+ // in sync after editing or recreating a profile with its name.
if (shouldReapplyActiveProfile) {
await activateProfile.mutateAsync(trimmedName);
}
diff --git a/src/components/features/settings/llm-profiles/profile-actions-menu-item.tsx b/src/components/features/settings/llm-profiles/profile-actions-menu-item.tsx
index 5faddd063a..f0b97fb9a5 100644
--- a/src/components/features/settings/llm-profiles/profile-actions-menu-item.tsx
+++ b/src/components/features/settings/llm-profiles/profile-actions-menu-item.tsx
@@ -9,6 +9,7 @@ interface MenuItemProps {
onKeyDown: (e: React.KeyboardEvent, index: number) => void;
menuItemsRef: React.MutableRefObject<(HTMLButtonElement | null)[]>;
disabled?: boolean;
+ title?: string;
testId: string;
}
@@ -20,6 +21,7 @@ export function MenuItem({
onKeyDown,
menuItemsRef,
disabled,
+ title,
testId,
}: MenuItemProps) {
return (
@@ -32,6 +34,7 @@ export function MenuItem({
onClick={onClick}
onKeyDown={(e) => onKeyDown(e, index)}
disabled={disabled}
+ title={title}
className={cn(
"group w-full cursor-pointer rounded px-2 py-2 text-start text-nowrap text-sm font-normal",
"text-foreground hover:bg-interactive-hover",
diff --git a/src/components/features/settings/meta-llm-profiles/meta-llm-settings-view.tsx b/src/components/features/settings/meta-llm-profiles/meta-llm-settings-view.tsx
index 593d0b9108..20efc1f788 100644
--- a/src/components/features/settings/meta-llm-profiles/meta-llm-settings-view.tsx
+++ b/src/components/features/settings/meta-llm-profiles/meta-llm-settings-view.tsx
@@ -10,6 +10,7 @@ import { useProviderConnections } from "#/hooks/query/use-provider-connections";
import { useSaveMetaProfile } from "#/hooks/mutation/use-save-meta-profile";
import { useSaveLlmProfile } from "#/hooks/mutation/use-save-llm-profile";
import { useActivateMetaProfile } from "#/hooks/mutation/use-activate-meta-profile";
+import { agentProfileSupportsRouter } from "#/api/agent-profiles-service/profile-field-support";
import { useSettings } from "#/hooks/query/use-settings";
import { useSaveSettings } from "#/hooks/mutation/use-save-settings";
import { SettingsSwitch } from "#/components/features/settings/settings-switch";
@@ -83,7 +84,9 @@ export function MetaLlmSettingsView() {
>([]);
const metaProfiles = data?.meta_profiles ?? [];
- const active = data?.active_meta_profile ?? null;
+ // Locally each agent profile picks its router, so none is active here.
+ const routerPerProfile = agentProfileSupportsRouter();
+ const active = routerPerProfile ? null : (data?.active_meta_profile ?? null);
const availableProfiles = (llmProfilesData?.profiles ?? []).map(
(p) => p.name,
);
@@ -203,7 +206,8 @@ export function MetaLlmSettingsView() {
config: MetaProfile,
providerConnectionId: string | null,
) => {
- const shouldActivateAfterCreate = view === "create" && active === null;
+ const shouldActivateAfterCreate =
+ view === "create" && active === null && !routerPerProfile;
// Creating the first router (0 → 1) is the moment "Run on first message"
// becomes useful, so flip it on by default — but only if the user hasn't
// already enabled it. Subsequent router creations leave the preference
@@ -272,8 +276,11 @@ export function MetaLlmSettingsView() {
// meta-profiles response can prove a router is active. Instead the launch
// paths gate on the active meta-profile at the single suffix-emission
// point (``buildRouterAtStartSystemSuffix``), so a stale ``true`` with no
- // router can never emit the ``route_task_to_model`` instruction.
- const canRunRouterAtStart = active !== null;
+ // router can never emit the ``route_task_to_model`` instruction. Locally
+ // that gate is the launched profile's router, so any router enables it.
+ const canRunRouterAtStart = routerPerProfile
+ ? metaProfiles.length > 0
+ : active !== null;
const handleToggleRunAtConversationStart = (value: boolean) => {
saveSettings({ run_router_at_conversation_start: value });
};
@@ -368,7 +375,7 @@ export function MetaLlmSettingsView() {
key={info.name}
info={info}
isActive={info.name === active}
- onActivate={handleActivate}
+ onActivate={routerPerProfile ? undefined : handleActivate}
onEdit={handleEdit}
onDelete={setNameToDelete}
isActivating={activateMetaProfile.isPending}
@@ -392,7 +399,11 @@ export function MetaLlmSettingsView() {
{t(I18nKey.SETTINGS$META_PROFILE_RUN_AT_CONVERSATION_START)}
</SettingsSwitch>
<p className="text-xs leading-4 text-tertiary-light">
- {t(I18nKey.SETTINGS$META_PROFILE_RUN_AT_CONVERSATION_START_HELP)}
+ {t(
+ routerPerProfile
+ ? I18nKey.SETTINGS$META_PROFILE_RUN_AT_CONVERSATION_START_HELP_PROFILE
+ : I18nKey.SETTINGS$META_PROFILE_RUN_AT_CONVERSATION_START_HELP,
+ )}
</p>
</div>
</div>
diff --git a/src/components/features/settings/meta-llm-profiles/meta-profile-actions-menu.tsx b/src/components/features/settings/meta-llm-profiles/meta-profile-actions-menu.tsx
index 7aa95515ec..e2da1e84a2 100644
--- a/src/components/features/settings/meta-llm-profiles/meta-profile-actions-menu.tsx
+++ b/src/components/features/settings/meta-llm-profiles/meta-profile-actions-menu.tsx
@@ -61,7 +61,7 @@ function MenuItem({
interface MetaProfileActionsMenuProps {
onEdit: () => void;
- onSetActive: () => void;
+ onSetActive?: () => void;
onDelete: () => void;
isActive: boolean;
isActivating: boolean;
@@ -194,18 +194,20 @@ export function MetaProfileActionsMenu({
menuItemsRef={menuItemsRef}
testId="meta-profile-edit"
/>
+ {onSetActive ? (
+ <MenuItem
+ index={1}
+ icon={<CheckCircleIcon width={16} height={16} />}
+ label={t(I18nKey.SETTINGS$META_PROFILE_ACTIVATE)}
+ onClick={() => handleAction(onSetActive)}
+ onKeyDown={handleKeyDown}
+ menuItemsRef={menuItemsRef}
+ disabled={setActiveDisabled}
+ testId="meta-profile-set-active"
+ />
+ ) : null}
<MenuItem
- index={1}
- icon={<CheckCircleIcon width={16} height={16} />}
- label={t(I18nKey.SETTINGS$META_PROFILE_ACTIVATE)}
- onClick={() => handleAction(onSetActive)}
- onKeyDown={handleKeyDown}
- menuItemsRef={menuItemsRef}
- disabled={setActiveDisabled}
- testId="meta-profile-set-active"
- />
- <MenuItem
- index={2}
+ index={onSetActive ? 2 : 1}
icon={<DeleteIcon width={16} height={16} />}
label={t(I18nKey.BUTTON$DELETE)}
onClick={() => handleAction(onDelete)}
diff --git a/src/components/features/settings/meta-llm-profiles/meta-profile-row.tsx b/src/components/features/settings/meta-llm-profiles/meta-profile-row.tsx
index f6b97efcdd..aa0c9a0a85 100644
--- a/src/components/features/settings/meta-llm-profiles/meta-profile-row.tsx
+++ b/src/components/features/settings/meta-llm-profiles/meta-profile-row.tsx
@@ -14,7 +14,8 @@ import {
interface MetaProfileRowProps {
info: MetaProfileInfo;
isActive: boolean;
- onActivate: (name: string) => void;
+ /** Omitted when routers aren't activated here. */
+ onActivate?: (name: string) => void;
onEdit: (name: string) => void;
onDelete: (name: string) => void;
isActivating: boolean;
@@ -78,7 +79,7 @@ export function MetaProfileRow({
<MetaProfileActionsMenu
anchorRef={triggerRef}
onEdit={() => onEdit(info.name)}
- onSetActive={() => onActivate(info.name)}
+ onSetActive={onActivate ? () => onActivate(info.name) : undefined}
onDelete={() => onDelete(info.name)}
isActive={isActive}
isActivating={isActivating}
diff --git a/src/components/features/skills/skill-card.tsx b/src/components/features/skills/skill-card.tsx
index 2a692092a5..6f19324ea0 100644
--- a/src/components/features/skills/skill-card.tsx
+++ b/src/components/features/skills/skill-card.tsx
@@ -21,6 +21,7 @@ interface SkillCardProps {
enabled: boolean;
onOpen: () => void;
onToggle: (enabled: boolean) => void;
+ isToggleDisabled?: boolean;
}
export function SkillCard({
@@ -28,6 +29,7 @@ export function SkillCard({
enabled,
onOpen,
onToggle,
+ isToggleDisabled = false,
}: SkillCardProps) {
const { t } = useTranslation("openhands");
const [sourceCopied, setSourceCopied] = React.useState(false);
@@ -122,6 +124,7 @@ export function SkillCard({
testId={`skill-toggle-${skill.name}`}
isSelected={enabled}
onToggle={onToggle}
+ isDisabled={isToggleDisabled}
disableTooltipKey={I18nKey.COMMON$DISABLE}
/>
</header>
diff --git a/src/components/features/skills/skill-detail-modal.tsx b/src/components/features/skills/skill-detail-modal.tsx
index ffe54c7fe8..765cf93bb4 100644
--- a/src/components/features/skills/skill-detail-modal.tsx
+++ b/src/components/features/skills/skill-detail-modal.tsx
@@ -24,6 +24,7 @@ interface SkillDetailModalProps {
enabled: boolean;
onToggle: (enabled: boolean) => void;
onClose: () => void;
+ isToggleDisabled?: boolean;
}
function ReadonlyTextArea({
@@ -57,6 +58,7 @@ export function SkillDetailModal({
enabled,
onToggle,
onClose,
+ isToggleDisabled = false,
}: SkillDetailModalProps) {
const { t } = useTranslation("openhands");
const launchSkillInChat = useLaunchSkillInChat();
@@ -158,6 +160,7 @@ export function SkillDetailModal({
testId={`skill-modal-toggle-${skill.name}`}
isToggled={enabled}
onToggle={onToggle}
+ isDisabled={isToggleDisabled}
togglePosition="right"
>
{t(
diff --git a/src/constants/settings-nav.tsx b/src/constants/settings-nav.tsx
index 2a3ae7f1d0..e991474533 100644
--- a/src/constants/settings-nav.tsx
+++ b/src/constants/settings-nav.tsx
@@ -44,10 +44,8 @@ export const OSS_NAV_ITEMS: SettingsNavItem[] = [
{
// The agent's ``agent_context`` section, whatever the schema exposes in it
// — today only persistent memory (``agent_context.load_memory``). Not
- // ``disabledByAcp``: the stored flag rides the shared agent_settings
- // record into ACP conversations too — inline launches spread it into
- // ``agent_context``, and profile launches (the normal ACP path) have the
- // agent-server stamp it onto the profile-resolved agent.
+ // ``disabledByAcp``: the agent-server stamps the stored flag onto every
+ // profile-resolved agent, ACP included.
icon: <Brain className="size-4" strokeWidth={2} aria-hidden />,
to: "/settings/agent-context",
text: "SETTINGS$NAV_AGENT_CONTEXT",
diff --git a/src/hooks/mutation/resolve-conversation-launch.ts b/src/hooks/mutation/resolve-conversation-launch.ts
index 789d615f07..856e0eafc6 100644
--- a/src/hooks/mutation/resolve-conversation-launch.ts
+++ b/src/hooks/mutation/resolve-conversation-launch.ts
@@ -3,9 +3,11 @@ import type { AgentKind } from "@openhands/typescript-client";
import AgentProfilesService, {
WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,
type AgentProfileListResponse,
+ type AgentProfileSummary,
} from "#/api/agent-profiles-service/agent-profiles-service.api";
+import { profileHasRouter } from "#/api/agent-profiles-service/profile-behavior";
import ProfilesService from "#/api/profiles-service/profiles-service.api";
-import { backendSupportsLaunchLlmOverride } from "#/api/agent-server-adapter";
+import { assertSubscriptionAuthReady } from "#/api/agent-server-adapter";
import AgentServerConversationService, {
type CreateConversationOptions,
} from "#/api/conversation-service/agent-server-conversation-service.api";
@@ -16,15 +18,22 @@ import {
AGENT_PROFILES_RETRY_OPTIONS,
LLM_PROFILES_QUERY_KEYS,
} from "#/hooks/query/query-keys";
+import { ensureDefaultAgentProfileMigrated } from "#/hooks/use-migrate-default-agent-profile";
+import i18n from "#/i18n";
+import { I18nKey } from "#/i18n/declaration";
export interface ConversationLaunch {
- /** Unset when the launch sends the global `agent_settings` instead. */
+ /** Unset only on cloud, which launches its own default without one. */
agentProfileId?: string;
agentProfileKind?: AgentKind;
/** Runs the agent profile with this LLM profile instead of its own. */
llmProfileOverride?: string;
/** The LLM profile the launch runs, when Canvas can tell. */
llmProfile?: string;
+ /** Local only: the launched profile carries a Model Router. */
+ profileHasRouter?: boolean;
+ /** Local only: the launched ACP profile's server, for the conversation tag. */
+ acpServer?: string;
}
export interface ResolveConversationLaunchOptions {
@@ -38,19 +47,19 @@ export interface ResolveConversationLaunchOptions {
llmProfile?: string | null;
}
-/** Decide which agent source and LLM a new conversation launches with. */
-export async function resolveConversationLaunch({
- queryClient,
- backendId,
- orgId,
- isCloud,
- agentProfileId,
- llmProfile,
-}: ResolveConversationLaunchOptions): Promise<ConversationLaunch> {
+/** Decide which agent profile and LLM a new conversation launches with. */
+export async function resolveConversationLaunch(
+ options: ResolveConversationLaunchOptions,
+): Promise<ConversationLaunch> {
+ const { queryClient, backendId, orgId, isCloud, agentProfileId, llmProfile } =
+ options;
+ if (!isCloud) {
+ // `default` must carry the global settings it used to launch from before
+ // it launches by id; a failed migration fails the launch and retries next time.
+ await ensureDefaultAgentProfileMigrated(queryClient, backendId);
+ }
// Await the list from the shared query cache: a send fired before the home
- // query resolves must still launch from the active profile. Do not fall back
- // to the global agent_settings when profile discovery fails: activation is
- // pointer-only, so those settings may describe a different agent.
+ // query resolves must still launch from the active profile.
const agentProfiles: AgentProfileListResponse =
await queryClient.ensureQueryData({
queryKey: [...AGENT_PROFILES_QUERY_KEYS.all, backendId, orgId],
@@ -60,10 +69,32 @@ export async function resolveConversationLaunch({
meta: { disableToast: true },
});
- // Await the list rather than a render snapshot: a send fired before the
- // LLM-profile query loads must still validate the ref.
- const readLlmProfiles = () =>
- queryClient
+ const requestedAgentProfileId =
+ agentProfileId ?? agentProfiles.active_agent_profile_id ?? undefined;
+ if (!requestedAgentProfileId) {
+ if (isCloud) return {};
+ throw new Error(i18n.t(I18nKey.CONVERSATION$NO_ACTIVE_AGENT_PROFILE));
+ }
+ const profile = agentProfiles.profiles?.find(
+ (p) => p.id === requestedAgentProfileId,
+ );
+ if (isCloud) {
+ if (await cloudFallsBackToDefault(options, profile)) return {};
+ return {
+ agentProfileId: requestedAgentProfileId,
+ agentProfileKind: profile?.agent_kind,
+ llmProfile:
+ profile?.agent_kind === "openhands"
+ ? (profile.llm_profile_ref ?? undefined)
+ : undefined,
+ };
+ }
+
+ let llmProfileOverride: string | undefined;
+ if (profile?.agent_kind === "openhands" && profile.llm_profile_ref) {
+ // Await the list rather than a render snapshot: a send fired before the
+ // LLM-profile query loads must still validate the ref.
+ const llm = await queryClient
.ensureQueryData({
queryKey: [...LLM_PROFILES_QUERY_KEYS.all, backendId, orgId],
queryFn: ProfilesService.listProfiles,
@@ -71,103 +102,41 @@ export async function resolveConversationLaunch({
meta: { disableToast: true },
})
.catch(() => null);
-
- const requestedAgentProfileId =
- agentProfileId ?? agentProfiles.active_agent_profile_id ?? undefined;
- const profile = requestedAgentProfileId
- ? agentProfiles.profiles?.find((p) => p.id === requestedAgentProfileId)
- : undefined;
-
- let prefersAgentSettings = false;
- let activeLlmProfile: string | null = null;
- let llmProfileOverride: string | undefined;
- if (
- !isCloud &&
- profile?.name === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME &&
- profile.agent_kind === "openhands"
- ) {
- // The seeded OpenHands `default` launches via agent_settings so the Skills
- // page selection (buildAgentContext) applies: a profile launch gets the
- // server's whole skill catalog minus a deny-list. Per-profile fields saved
- // on `default` therefore don't apply on local launches.
- //
- // Scoped to OpenHands: global agent_settings is stale when an ACP profile
- // is active. Scoped to local: cloud always resolves `default` server-side.
- prefersAgentSettings = true;
- } else if (profile?.agent_kind === "openhands" && profile.llm_profile_ref) {
- const llm = await readLlmProfiles();
- // An unreadable list leaves the ref unvalidated; handled below.
const llmProfileExists =
llm?.profiles.some((p) => p.name === profile.llm_profile_ref) ?? false;
- activeLlmProfile = llm?.active_profile ?? null;
- // The home LLM pill shows and activates the account-wide active LLM
- // profile, never the pinned ref (#16539), so an implicit launch runs that
- // selection. An explicit pick keeps its pinned ref unless the ref is gone.
+ // A profile runs its own LLM, which the home pill shows; `default`'s is the
+ // active LLM profile. A ref that's gone falls back to the active profile.
const preferredLlmProfile =
llmProfile ||
- (!agentProfileId || !llmProfileExists ? activeLlmProfile : null);
- const selectedLlmProfile =
- !isCloud &&
+ (!llmProfileExists ||
+ profile.name === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME
+ ? llm?.active_profile
+ : null);
+ if (
preferredLlmProfile &&
preferredLlmProfile !== profile.llm_profile_ref
- ? preferredLlmProfile
- : undefined;
- if (!llmProfileExists || selectedLlmProfile) {
- if (!isCloud && (await backendSupportsLaunchLlmOverride())) {
- // A dangling ref with nothing selected reaches the server, which
- // rejects it with an error the user can act on.
- llmProfileOverride = selectedLlmProfile;
- } else if (!llmProfileExists || !llmProfile) {
- // No per-launch override on this server: run agent_settings at the
- // cost of the profile's other fields. A requested LLM is dropped
- // instead, keeping the profile.
- if (!llmProfileExists) {
- console.warn(
- `Agent profile "${profile.name}" references missing ` +
- `LLM profile "${profile.llm_profile_ref}"; ` +
- "launching from agent_settings instead.",
- );
- }
- prefersAgentSettings = true;
- }
+ ) {
+ llmProfileOverride = preferredLlmProfile;
}
}
- // A legacy agent_settings launch carries no profile identity, so Agent
- // Server cannot enforce that profile's secret allow-list. Keep restricted
- // profiles on the server-resolved path; if the detail cannot be read, fail
- // closed and let Agent Server report the underlying error.
- let profileAllowsAgentSettings = true;
- if (prefersAgentSettings && profile) {
- try {
- const detail = await queryClient.fetchQuery({
- queryKey: AGENT_PROFILES_QUERY_KEYS.detail(
- backendId,
- orgId,
- profile.name,
- ),
- queryFn: () => AgentProfilesService.getProfile(profile.name),
- ...AGENT_PROFILES_RETRY_OPTIONS,
- meta: { disableToast: true },
- });
- const secretRefs = (detail.profile as { secret_refs?: unknown })
- .secret_refs;
- profileAllowsAgentSettings = !Array.isArray(secretRefs);
- } catch {
- profileAllowsAgentSettings = false;
- }
- }
+ const detail = profile
+ ? await queryClient
+ .fetchQuery({
+ queryKey: AGENT_PROFILES_QUERY_KEYS.detail(
+ backendId,
+ orgId,
+ profile.name,
+ ),
+ queryFn: () => AgentProfilesService.getProfile(profile.name),
+ ...AGENT_PROFILES_RETRY_OPTIONS,
+ meta: { disableToast: true },
+ })
+ // Router and tag are extras: the server still launches the profile.
+ .catch(() => null)
+ : null;
+ const stored = detail?.profile;
- if (
- !requestedAgentProfileId ||
- (prefersAgentSettings && profileAllowsAgentSettings)
- ) {
- // An agent_settings launch runs the active LLM profile.
- if (!activeLlmProfile && !isCloud) {
- activeLlmProfile = (await readLlmProfiles())?.active_profile ?? null;
- }
- return { llmProfile: activeLlmProfile ?? undefined };
- }
return {
agentProfileId: requestedAgentProfileId,
agentProfileKind: profile?.agent_kind,
@@ -176,9 +145,65 @@ export async function resolveConversationLaunch({
profile?.agent_kind === "openhands"
? (llmProfileOverride ?? profile.llm_profile_ref ?? undefined)
: undefined,
+ profileHasRouter:
+ stored?.agent_kind === "openhands" && profileHasRouter(stored),
+ acpServer: stored?.agent_kind === "acp" ? stored.acp_server : undefined,
};
}
+/**
+ * Cloud launches its own default instead of an OpenHands profile whose LLM
+ * profile is gone, unless the profile restricts secrets, which only a profile
+ * launch enforces.
+ */
+async function cloudFallsBackToDefault(
+ { queryClient, backendId, orgId }: ResolveConversationLaunchOptions,
+ profile: AgentProfileSummary | undefined,
+): Promise<boolean> {
+ if (profile?.agent_kind !== "openhands" || !profile.llm_profile_ref) {
+ return false;
+ }
+ const llm = await queryClient
+ .ensureQueryData({
+ queryKey: [...LLM_PROFILES_QUERY_KEYS.all, backendId, orgId],
+ queryFn: ProfilesService.listProfiles,
+ retry: false,
+ meta: { disableToast: true },
+ })
+ .catch(() => null);
+ if (llm?.profiles.some((p) => p.name === profile.llm_profile_ref)) {
+ return false;
+ }
+ try {
+ const detail = await queryClient.fetchQuery({
+ queryKey: AGENT_PROFILES_QUERY_KEYS.detail(
+ backendId,
+ orgId,
+ profile.name,
+ ),
+ queryFn: () => AgentProfilesService.getProfile(profile.name),
+ ...AGENT_PROFILES_RETRY_OPTIONS,
+ meta: { disableToast: true },
+ });
+ return !Array.isArray(
+ (detail.profile as { secret_refs?: unknown }).secret_refs,
+ );
+ } catch {
+ return false;
+ }
+}
+
+/** Fail before creating a conversation whose subscription LLM isn't connected. */
+async function assertLaunchLlmReady(llmProfile: string): Promise<void> {
+ let config: unknown;
+ try {
+ ({ config } = await ProfilesService.getProfile(llmProfile));
+ } catch {
+ return;
+ }
+ await assertSubscriptionAuthReady({ llm: config });
+}
+
/** Create a conversation from the resolved launch and record the LLM it runs. */
export async function launchConversation(
{ agentProfileId, llmProfile, ...context }: ResolveConversationLaunchOptions,
@@ -189,6 +214,9 @@ export async function launchConversation(
agentProfileId,
llmProfile,
});
+ if (!context.isCloud && launch.llmProfile) {
+ await assertLaunchLlmReady(launch.llmProfile);
+ }
const task = await AgentServerConversationService.createConversation({
...options,
...launchProfileOptions(launch),
@@ -215,5 +243,7 @@ function launchProfileOptions(
...(launch.llmProfileOverride
? { agentLlmProfileOverride: launch.llmProfileOverride }
: {}),
+ ...(launch.profileHasRouter ? { profileHasRouter: true } : {}),
+ ...(launch.acpServer ? { acpServer: launch.acpServer } : {}),
};
}
diff --git a/src/hooks/mutation/sync-agent-profiles.ts b/src/hooks/mutation/sync-agent-profiles.ts
new file mode 100644
index 0000000000..f360155dc3
--- /dev/null
+++ b/src/hooks/mutation/sync-agent-profiles.ts
@@ -0,0 +1,270 @@
+import type { QueryClient } from "@tanstack/react-query";
+import { HttpError } from "@openhands/typescript-client";
+import AgentProfilesService, {
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,
+ type AgentProfile,
+ type AgentProfileSaveInput,
+} from "#/api/agent-profiles-service/agent-profiles-service.api";
+import {
+ getActiveBackend,
+ isNoBackend,
+} from "#/api/backend-registry/active-store";
+import ProfilesService from "#/api/profiles-service/profiles-service.api";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import { mergeAgentProfileSaveInput } from "#/components/features/settings/agent-profiles/merge-agent-profile-save-input";
+import {
+ AGENT_PROFILES_QUERY_KEYS,
+ LLM_PROFILES_QUERY_KEYS,
+ SETTINGS_QUERY_KEYS,
+} from "#/hooks/query/query-keys";
+import { getSettingsQueryFn } from "#/hooks/query/use-settings";
+import { settleRunningDefaultAgentProfileMigration } from "#/hooks/use-migrate-default-agent-profile";
+import i18n from "#/i18n";
+import { I18nKey } from "#/i18n/declaration";
+import type { Settings } from "#/types/settings";
+import { displayErrorToast } from "#/utils/custom-toast-handlers";
+import { getMcpServerEnabled, parseMcpConfig } from "#/utils/mcp-config";
+import {
+ profileSkillEnablement,
+ sameSkillSelection,
+ toProfileSkillFields,
+ type SkillEnablement,
+} from "#/utils/skill-enablement";
+
+/** The fields to change on a profile, or `null` when it already matches. */
+export type ProfileChange = (
+ profile: AgentProfile,
+) => Partial<AgentProfileSaveInput> | null;
+
+let queue: Promise<void> = Promise.resolve();
+
+async function readProfile(name: string): Promise<AgentProfile | null> {
+ return AgentProfilesService.getProfile(name)
+ .then((detail) => detail.profile)
+ .catch((error: unknown) => {
+ if (error instanceof HttpError && error.status === 404) return null;
+ throw error;
+ });
+}
+
+async function saveChange(
+ name: string,
+ stored: AgentProfile | null,
+ change: ProfileChange,
+): Promise<boolean> {
+ const patch = stored ? change(stored) : null;
+ if (!stored || !patch) return false;
+ await AgentProfilesService.saveProfile(
+ name,
+ mergeAgentProfileSaveInput(stored, {
+ agent_kind: stored.agent_kind,
+ ...patch,
+ } as AgentProfileSaveInput),
+ );
+ return true;
+}
+
+interface WriteOptions {
+ /** Replaces the default failure toast, which says the global edit saved. */
+ onError?: (error: unknown) => void;
+ /** Reject instead, for a caller that must not go on after a failed write. */
+ throwOnError?: boolean;
+}
+
+/** Run profile writes one at a time on a local backend, so each reads the previous one's result. */
+function enqueue(
+ queryClient: QueryClient,
+ write: () => Promise<boolean>,
+ { onError, throwOnError = false }: WriteOptions = {},
+): Promise<void> {
+ const run = queue.then(async () => {
+ const { backend } = getActiveBackend();
+ if (backend.kind !== "local" || isNoBackend(backend)) return;
+ await settleRunningDefaultAgentProfileMigration(
+ queryClient,
+ backend.id,
+ ).catch(() => undefined);
+ if (await write()) {
+ await queryClient.invalidateQueries({
+ queryKey: AGENT_PROFILES_QUERY_KEYS.all,
+ });
+ }
+ });
+ queue = run.catch(() => undefined);
+ return run.catch((error: unknown) => {
+ console.error("Failed to update agent profiles:", error);
+ if (throwOnError) throw error;
+ if (onError) onError(error);
+ else
+ displayErrorToast(i18n.t(I18nKey.SETTINGS$DEFAULT_PROFILE_NOT_UPDATED));
+ });
+}
+
+/** Change one local profile. */
+export function updateAgentProfile(
+ queryClient: QueryClient,
+ name: string,
+ change: ProfileChange,
+ options?: WriteOptions,
+): Promise<void> {
+ return enqueue(
+ queryClient,
+ async () => saveChange(name, await readProfile(name), change),
+ options,
+ );
+}
+
+/** Change the local `default` profile. */
+export function updateDefaultAgentProfile(
+ queryClient: QueryClient,
+ change: ProfileChange,
+ options?: WriteOptions,
+): Promise<void> {
+ return enqueue(
+ queryClient,
+ async () =>
+ saveChange(
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,
+ await readProfile(WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME),
+ change,
+ ),
+ options,
+ );
+}
+
+/** Apply a global page edit to every local profile. */
+export function updateEveryAgentProfile(
+ queryClient: QueryClient,
+ change: ProfileChange,
+ options?: WriteOptions,
+): Promise<void> {
+ return enqueue(
+ queryClient,
+ async () => {
+ const { profiles } = await AgentProfilesService.listProfiles();
+ const saved = await Promise.all(
+ profiles.map(async ({ name }) =>
+ saveChange(name, await readProfile(name), change),
+ ),
+ );
+ return saved.some(Boolean);
+ },
+ options,
+ );
+}
+
+export const routerDetached =
+ (name: string): ProfileChange =>
+ (profile) =>
+ profile.agent_kind === "openhands" &&
+ (profile as { meta_profile_ref?: string | null }).meta_profile_ref === name
+ ? ({
+ meta_profile_ref: null,
+ enable_classify_and_switch_llm_tool: false,
+ } as Partial<AgentProfileSaveInput>)
+ : null;
+
+type McpRefs = { mcp_server_refs?: string[] | null };
+
+export const mcpServerRenamed =
+ (from: string, to: string): ProfileChange =>
+ (profile) => {
+ const refs = (profile as McpRefs).mcp_server_refs;
+ return refs?.includes(from)
+ ? { mcp_server_refs: refs.map((ref) => (ref === from ? to : ref)) }
+ : null;
+ };
+
+export const mcpServerRemoved =
+ (name: string): ProfileChange =>
+ (profile) => {
+ const refs = (profile as McpRefs).mcp_server_refs;
+ return refs?.includes(name)
+ ? { mcp_server_refs: refs.filter((ref) => ref !== name) }
+ : null;
+ };
+
+export const withSkillSelection =
+ (selection: SkillEnablement): ProfileChange =>
+ (profile) => {
+ if (profile.agent_kind !== "openhands") return null;
+ return sameSkillSelection(profileSkillEnablement(profile), selection)
+ ? null
+ : toProfileSkillFields(selection);
+ };
+
+export const llmProfileMovedOff =
+ (from: string, to: string): ProfileChange =>
+ (profile) =>
+ profile.agent_kind === "openhands" && profile.llm_profile_ref === from
+ ? { llm_profile_ref: to }
+ : null;
+
+export const llmProfileMirrored =
+ (name: string): ProfileChange =>
+ (profile) =>
+ profile.agent_kind === "openhands" && profile.llm_profile_ref !== name
+ ? { llm_profile_ref: name }
+ : null;
+
+function mcpConfigOf(settings: Settings | undefined) {
+ return (
+ settings?.mcp_config ?? parseMcpConfig(settings?.agent_settings?.mcp_config)
+ );
+}
+
+/** `default`'s MCP servers as the editor shows them: the ones switched on in MCP Servers. */
+export function enabledMcpServerRefs(
+ settings: Settings | undefined,
+): string[] | null {
+ const config = mcpConfigOf(settings);
+ const enabled = Object.keys(config).filter(
+ (key) => getMcpServerEnabled(config[key]) !== false,
+ );
+ return enabled.length === Object.keys(config).length ? null : enabled;
+}
+
+/** What an OpenHands `default` stores: every switched-on MCP server and every secret. */
+export function sharedDefaultProfileFields(
+ input: AgentProfileSaveInput,
+): AgentProfileSaveInput {
+ return {
+ ...input,
+ mcp_server_refs: null,
+ ...("secret_refs" in input ? { secret_refs: null } : {}),
+ } as AgentProfileSaveInput;
+}
+
+/** Make the active LLM profile and the MCP page's switches match an edited OpenHands `default`. */
+export async function applyDefaultAgentProfileToGlobal(
+ queryClient: QueryClient,
+ input: AgentProfileSaveInput,
+): Promise<void> {
+ const settings = await getSettingsQueryFn();
+ const writes: Promise<unknown>[] = [];
+
+ if (input.agent_kind === "openhands" && input.llm_profile_ref) {
+ const { active_profile: active } = await ProfilesService.listProfiles();
+ if (active !== input.llm_profile_ref) {
+ writes.push(ProfilesService.activateProfile(input.llm_profile_ref));
+ }
+ }
+
+ const refs = (input as McpRefs).mcp_server_refs ?? null;
+ const config = mcpConfigOf(settings);
+ Object.keys(config).forEach((key) => {
+ const enabled = refs === null || refs.includes(key);
+ if ((getMcpServerEnabled(config[key]) !== false) !== enabled) {
+ writes.push(SettingsService.patchMcpServer(key, { enabled }));
+ }
+ });
+
+ await Promise.all(writes);
+ if (writes.length > 0) {
+ SettingsService.invalidateCache();
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: SETTINGS_QUERY_KEYS.all }),
+ queryClient.invalidateQueries({ queryKey: LLM_PROFILES_QUERY_KEYS.all }),
+ ]);
+ }
+}
diff --git a/src/hooks/mutation/use-activate-llm-profile.ts b/src/hooks/mutation/use-activate-llm-profile.ts
index 710912953d..f9aea77b10 100644
--- a/src/hooks/mutation/use-activate-llm-profile.ts
+++ b/src/hooks/mutation/use-activate-llm-profile.ts
@@ -5,13 +5,18 @@ import {
LLM_PROFILES_QUERY_KEYS,
SETTINGS_QUERY_KEYS,
} from "#/hooks/query/query-keys";
+import {
+ llmProfileMirrored,
+ updateDefaultAgentProfile,
+} from "#/hooks/mutation/sync-agent-profiles";
export function useActivateLlmProfile() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (name: string) => ProfilesService.activateProfile(name),
- onSuccess: async () => {
+ onSuccess: async (_data, name) => {
+ updateDefaultAgentProfile(queryClient, llmProfileMirrored(name));
// Invalidate the SettingsService internal cache so getSettingsForConversation
// fetches fresh settings with the newly activated profile's LLM config
SettingsService.invalidateCache();
diff --git a/src/hooks/mutation/use-apply-onboarding-agent-profile.ts b/src/hooks/mutation/use-apply-onboarding-agent-profile.ts
index 51f20cbd41..49d503cafc 100644
--- a/src/hooks/mutation/use-apply-onboarding-agent-profile.ts
+++ b/src/hooks/mutation/use-apply-onboarding-agent-profile.ts
@@ -1,10 +1,16 @@
import { useCallback } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { HttpError } from "@openhands/typescript-client";
import AgentProfilesService, {
WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,
type AgentProfileSaveInput,
} from "#/api/agent-profiles-service/agent-profiles-service.api";
+import { mergeAgentProfileSaveInput } from "#/components/features/settings/agent-profiles/merge-agent-profile-save-input";
import { useSaveAgentProfile } from "#/hooks/mutation/use-save-agent-profile";
import { useActivateAgentProfile } from "#/hooks/mutation/use-activate-agent-profile";
+import { isNoBackend } from "#/api/backend-registry/active-store";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { ensureDefaultAgentProfileMigrated } from "#/hooks/use-migrate-default-agent-profile";
/**
* The well-known agent profile onboarding configures. Conversations launch from
@@ -22,26 +28,45 @@ export const ONBOARDING_AGENT_PROFILE_NAME =
* an OpenHands profile pointing at the LLM profile onboarding just created, or
* an ACP profile for the chosen provider (which owns its own LLM — no key).
*
- * Best-effort: a failure (e.g. an older backend without `/api/agent-profiles`)
- * is swallowed so onboarding is never blocked — the global agent_settings the
- * setup steps already wrote remain the fallback.
+ * Best-effort: a failure is swallowed so onboarding is never blocked; the
+ * error shows when the user starts a conversation.
*/
export function useApplyOnboardingAgentProfile() {
+ const queryClient = useQueryClient();
+ const { backend } = useActiveBackend();
const saveProfile = useSaveAgentProfile();
const activateProfile = useActivateAgentProfile();
return useCallback(
async (profile: AgentProfileSaveInput) => {
try {
- // Overwrite (not merge) is intentional: the `default` profile is the
- // baseline that mirrors the current onboarding choice, not a durable
- // store of per-profile customizations (home-launch resolves it via
- // agent_settings — see `useCreateConversation`). Re-onboarding resets it
- // to the fresh choice; users wanting durable custom config create a
- // named profile, which the editor saves via `mergeAgentProfileSaveInput`.
+ if (backend.kind === "local" && !isNoBackend(backend)) {
+ // A failed migration retries later and merges over this save.
+ await ensureDefaultAgentProfileMigrated(
+ queryClient,
+ backend.id,
+ ).catch(() => undefined);
+ }
+ // An OpenHands choice merges over the stored `default`: it carries the
+ // user's migrated skills, condenser and verification, which
+ // re-onboarding must keep. An ACP choice replaces the profile, so a
+ // previous provider's command never runs under the new one.
+ const stored =
+ profile.agent_kind === "openhands"
+ ? await AgentProfilesService.getProfile(
+ ONBOARDING_AGENT_PROFILE_NAME,
+ )
+ .then((detail) => detail.profile)
+ .catch((error: unknown) => {
+ if (error instanceof HttpError && error.status === 404) {
+ return null;
+ }
+ throw error;
+ })
+ : null;
await saveProfile.mutateAsync({
name: ONBOARDING_AGENT_PROFILE_NAME,
- profile,
+ profile: mergeAgentProfileSaveInput(stored, profile),
});
// activate needs the stable id; the save response only echoes the name.
const detail = await AgentProfilesService.getProfile(
@@ -53,6 +78,6 @@ export function useApplyOnboardingAgentProfile() {
console.error("Failed to configure onboarding agent profile:", error);
}
},
- [saveProfile, activateProfile],
+ [queryClient, backend, saveProfile, activateProfile],
);
}
diff --git a/src/hooks/mutation/use-create-conversation.ts b/src/hooks/mutation/use-create-conversation.ts
index bf7b8ed97c..8f0488d38e 100644
--- a/src/hooks/mutation/use-create-conversation.ts
+++ b/src/hooks/mutation/use-create-conversation.ts
@@ -131,11 +131,11 @@ export const useCreateConversation = ({
workspaceMode,
parentConversationId,
agentType,
- // Only stamp the toggle when it's on so the default path stays
- // byte-identical to the legacy launch (and the e2e snapshot tests
- // that assert the exact createConversation payload). The active
- // meta-profile gates the suffix: no router attached means no
- // route-at-start instruction, even if the toggle was left on.
+ // Cloud only; a local launch reads the toggle itself and gates it
+ // on the launched profile's router. Only stamped when on, so the
+ // e2e snapshot tests that assert the exact createConversation
+ // payload stay stable. The active meta-profile gates the suffix:
+ // no router attached means no route-at-start instruction.
...(settings?.run_router_at_conversation_start
? {
runRouterAtConversationStart: true,
diff --git a/src/hooks/mutation/use-delete-llm-profile.ts b/src/hooks/mutation/use-delete-llm-profile.ts
index fca34b1b04..e5e44d0011 100644
--- a/src/hooks/mutation/use-delete-llm-profile.ts
+++ b/src/hooks/mutation/use-delete-llm-profile.ts
@@ -6,12 +6,47 @@ import {
SETTINGS_QUERY_KEYS,
} from "#/hooks/query/query-keys";
import { getActiveBackend } from "#/api/backend-registry/active-store";
+import {
+ llmProfileMovedOff,
+ updateDefaultAgentProfile,
+} from "#/hooks/mutation/sync-agent-profiles";
+
+/**
+ * `default` follows the active LLM profile, and the server refuses to delete
+ * one an agent profile still uses: move `default` to the profile that will
+ * become active first. The only profile left stays, since `default` needs one.
+ */
+async function moveDefaultOffLlmProfile(
+ queryClient: ReturnType<typeof useQueryClient>,
+ name: string,
+): Promise<void> {
+ if (getActiveBackend().backend.kind !== "local") return;
+ let profiles: Awaited<
+ ReturnType<typeof ProfilesService.listProfiles>
+ >["profiles"] = [];
+ try {
+ profiles = (await ProfilesService.listProfiles())?.profiles ?? [];
+ } catch {
+ // Without the list the delete still runs; the server explains a refusal.
+ }
+ const remaining = profiles.filter((profile) => profile.name !== name);
+ const next = remaining.find((profile) => profile.api_key_set) ?? remaining[0];
+ if (!next) return;
+ await updateDefaultAgentProfile(
+ queryClient,
+ llmProfileMovedOff(name, next.name),
+ { throwOnError: true },
+ );
+}
export function useDeleteLlmProfile() {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: (name: string) => ProfilesService.deleteProfile(name),
+ mutationFn: async (name: string) => {
+ await moveDefaultOffLlmProfile(queryClient, name);
+ return ProfilesService.deleteProfile(name);
+ },
onSuccess: async (_response, name) => {
if (getActiveBackend().backend.kind === "local") {
const settings = await SettingsService.getSettings();
diff --git a/src/hooks/mutation/use-delete-mcp-server.ts b/src/hooks/mutation/use-delete-mcp-server.ts
index 3c62dee839..c4a283db5e 100644
--- a/src/hooks/mutation/use-delete-mcp-server.ts
+++ b/src/hooks/mutation/use-delete-mcp-server.ts
@@ -2,6 +2,10 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import SettingsService from "#/api/settings-service/settings-service.api";
import { MCPServerConfig } from "#/types/mcp-server";
import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";
+import {
+ mcpServerRemoved,
+ updateEveryAgentProfile,
+} from "#/hooks/mutation/sync-agent-profiles";
import { clearMcpServerHealth } from "#/api/mcp-health/mcp-health-store";
import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";
@@ -21,6 +25,7 @@ export function useDeleteMcpServer() {
meta: { disableToast: true },
mutationFn: async (target: MCPServerConfig): Promise<void> => {
await SettingsService.deleteMcpServer(target.id);
+ await updateEveryAgentProfile(queryClient, mcpServerRemoved(target.id));
},
onSuccess: (_data, target) => {
// Drop the deleted server's health entry so a later server that
diff --git a/src/hooks/mutation/use-delete-meta-profile.ts b/src/hooks/mutation/use-delete-meta-profile.ts
index 709d307d01..32105fe5d1 100644
--- a/src/hooks/mutation/use-delete-meta-profile.ts
+++ b/src/hooks/mutation/use-delete-meta-profile.ts
@@ -2,6 +2,11 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import MetaProfilesService from "#/api/meta-profiles-service/meta-profiles-service.api";
import SettingsService from "#/api/settings-service/settings-service.api";
import {
+ routerDetached,
+ updateEveryAgentProfile,
+} from "#/hooks/mutation/sync-agent-profiles";
+import {
+ AGENT_PROFILES_QUERY_KEYS,
META_PROFILES_QUERY_KEYS,
SETTINGS_QUERY_KEYS,
} from "#/hooks/query/query-keys";
@@ -10,19 +15,28 @@ export function useDeleteMetaProfile() {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: (name: string) => MetaProfilesService.deleteMetaProfile(name),
+ mutationFn: async (name: string) => {
+ // A launch refuses a missing router, so detach it first.
+ await updateEveryAgentProfile(queryClient, routerDetached(name), {
+ throwOnError: true,
+ });
+ return MetaProfilesService.deleteMetaProfile(name);
+ },
onSuccess: async () => {
// Deleting the *active* meta-profile clears ``active_meta_profile`` in
- // settings (and detaches the route_task_to_model tool from new
- // conversations), so refresh the settings caches too — mirroring
- // activation. Without this, settings can stay stale until reload.
+ // settings, so refresh the settings caches too — mirroring activation.
SettingsService.invalidateCache();
- await queryClient.invalidateQueries({
- queryKey: META_PROFILES_QUERY_KEYS.all,
- });
- await queryClient.invalidateQueries({
- queryKey: SETTINGS_QUERY_KEYS.personal(),
- });
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: META_PROFILES_QUERY_KEYS.all,
+ }),
+ queryClient.invalidateQueries({
+ queryKey: SETTINGS_QUERY_KEYS.personal(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: AGENT_PROFILES_QUERY_KEYS.all,
+ }),
+ ]);
},
// Consumers handle errors with try-catch and manual toasts; disable global toast
meta: { disableToast: true },
diff --git a/src/hooks/mutation/use-new-conversation-command.ts b/src/hooks/mutation/use-new-conversation-command.ts
index 205c1fc896..833a902583 100644
--- a/src/hooks/mutation/use-new-conversation-command.ts
+++ b/src/hooks/mutation/use-new-conversation-command.ts
@@ -43,10 +43,10 @@ export const useNewConversationCommand = () => {
},
{
sandboxId: conversation.sandbox_id ?? undefined,
- // Only stamp the toggle when it's on so the default /new path
- // stays byte-identical to the legacy launch. The active
- // meta-profile gates the suffix: no router attached means no
- // route-at-start instruction.
+ // Cloud only; a local launch reads the toggle itself and gates it
+ // on the launched profile's router. The active meta-profile gates
+ // the suffix: no router attached means no route-at-start
+ // instruction.
...(settings?.run_router_at_conversation_start
? {
runRouterAtConversationStart: true,
diff --git a/src/hooks/mutation/use-switch-acp-model.ts b/src/hooks/mutation/use-switch-acp-model.ts
index 093fb8949f..2ce0ddde18 100644
--- a/src/hooks/mutation/use-switch-acp-model.ts
+++ b/src/hooks/mutation/use-switch-acp-model.ts
@@ -37,8 +37,8 @@ interface SwitchAcpModelVars {
* (``agent_profile_id`` and ``agent_settings`` are mutually exclusive launch
* sources), so writing ``agent_settings.acp_model`` would not affect them.
* Only when the profile list resolves with no active ACP profile does the
- * write fall back to the ``agent_settings_diff`` the legacy launch path
- * reads. A failed profile discovery propagates instead of downgrading
+ * write fall back to the ``agent_settings_diff`` a Cloud launch without a
+ * profile reads. A failed profile discovery propagates instead of downgrading
* (#16523): an active-profile launch ignores agent_settings, so persisting
* the pick there would silently drop it.
*
@@ -102,8 +102,8 @@ export const useSwitchAcpModel = () => {
return;
}
- // No active ACP profile: persist as the agent-settings default the
- // legacy launch path reads. The backend deep-merges
+ // No active ACP profile: persist as the agent-settings default a Cloud
+ // launch without a profile reads. The backend deep-merges
// ``agent_settings_diff`` into the existing ``agent_settings`` dict, so
// a scalar ``acp_model`` diff updates only the model and preserves the
// selected provider + command.
diff --git a/src/hooks/mutation/use-switch-llm-profile.ts b/src/hooks/mutation/use-switch-llm-profile.ts
index b00da3e2af..3eb9de915e 100644
--- a/src/hooks/mutation/use-switch-llm-profile.ts
+++ b/src/hooks/mutation/use-switch-llm-profile.ts
@@ -15,6 +15,10 @@ import { displayErrorToast } from "#/utils/custom-toast-handlers";
import { getApiOrConnectionErrorMessage } from "#/utils/api-error-message";
import { I18nKey } from "#/i18n/declaration";
import { invalidateConversationQueries } from "./conversation-mutation-utils";
+import {
+ llmProfileMirrored,
+ updateDefaultAgentProfile,
+} from "./sync-agent-profiles";
interface SwitchLlmProfileVars {
/**
@@ -91,6 +95,7 @@ export const useSwitchLlmProfile = () => {
queryClient.invalidateQueries({
queryKey: SETTINGS_QUERY_KEYS.personal(),
});
+ updateDefaultAgentProfile(queryClient, llmProfileMirrored(profileName));
}
},
});
diff --git a/src/hooks/mutation/use-update-mcp-server.ts b/src/hooks/mutation/use-update-mcp-server.ts
index 508db10ec6..b32107bc33 100644
--- a/src/hooks/mutation/use-update-mcp-server.ts
+++ b/src/hooks/mutation/use-update-mcp-server.ts
@@ -8,6 +8,10 @@ import {
parseMcpConfig,
} from "#/utils/mcp-config";
import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";
+import {
+ mcpServerRenamed,
+ updateEveryAgentProfile,
+} from "#/hooks/mutation/sync-agent-profiles";
import { clearMcpServerHealth } from "#/api/mcp-health/mcp-health-store";
import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";
import { toMcpServerName } from "#/utils/mcp-server-name";
@@ -64,6 +68,10 @@ export function useUpdateMcpServer() {
await SettingsService.patchMcpConfig(
buildRenameMcpConfigPatch(serverId, nextKey, previous, server),
);
+ await updateEveryAgentProfile(
+ queryClient,
+ mcpServerRenamed(serverId, nextKey),
+ );
return previousHealthKey;
}
diff --git a/src/hooks/query/use-skills.ts b/src/hooks/query/use-skills.ts
index 95d634d7e0..d4e3388890 100644
--- a/src/hooks/query/use-skills.ts
+++ b/src/hooks/query/use-skills.ts
@@ -7,10 +7,14 @@ import { SkillInfo } from "#/types/settings";
* views pass the conversation's own workspace so the catalog matches the
* skills loaded into that conversation; the global Skills page omits it.
*/
-export const useSkills = (projectDir?: string) =>
+export const useSkills = (
+ projectDir?: string,
+ options: { enabled?: boolean } = {},
+) =>
useQuery<SkillInfo[]>({
queryKey: ["skills", projectDir ?? null],
queryFn: () => SkillsService.getSkills(projectDir),
+ enabled: options.enabled ?? true,
staleTime: 1000 * 60 * 10, // 10 minutes – skill list rarely changes
refetchOnWindowFocus: false,
});
diff --git a/src/hooks/use-active-agent-profile.ts b/src/hooks/use-active-agent-profile.ts
index cf9fbb635a..1efc89f2d8 100644
--- a/src/hooks/use-active-agent-profile.ts
+++ b/src/hooks/use-active-agent-profile.ts
@@ -2,6 +2,7 @@ import type { AgentKind } from "@openhands/typescript-client";
import type { AgentProfileSummary } from "#/api/agent-profiles-service/agent-profiles-service.api";
import { useAgentProfiles } from "#/hooks/query/use-agent-profiles";
import { useSettings } from "#/hooks/query/use-settings";
+import { useActiveBackend } from "#/contexts/active-backend-context";
/**
* The agent profile the user has activated — the authoritative "current agent"
@@ -13,8 +14,8 @@ import { useSettings } from "#/hooks/query/use-settings";
* Cached profile data survives a failed refetch; `isError` is set only when a
* failed fetch left nothing to decide from, and `agentKind` is then
* `undefined`. Without an active profile `agentKind` comes from the global
- * agent settings: briefly while the list loads, and for good when no profile
- * is active, the one case a launch sends them.
+ * agent settings only while the list loads, and on Cloud, which can launch
+ * without one. A local server always keeps a profile active.
*/
export function useActiveAgentProfile(): {
activeProfile: AgentProfileSummary | null;
@@ -24,6 +25,7 @@ export function useActiveAgentProfile(): {
} {
const { data, isLoading, isError: queryError } = useAgentProfiles();
const { data: settings } = useSettings();
+ const { backend } = useActiveBackend();
const activeId = data?.active_agent_profile_id ?? null;
const activeProfile =
data?.profiles?.find((p) => p.id != null && p.id === activeId) ?? null;
@@ -31,7 +33,11 @@ export function useActiveAgentProfile(): {
const settingsKind = settings?.agent_settings?.agent_kind;
let agentKind: AgentKind | undefined;
if (activeProfile) agentKind = activeProfile.agent_kind;
- else if (!isError && (settingsKind === "acp" || settingsKind === "openhands"))
+ else if (
+ !isError &&
+ (isLoading || backend.kind === "cloud") &&
+ (settingsKind === "acp" || settingsKind === "openhands")
+ )
agentKind = settingsKind;
return { activeProfile, agentKind, isLoading, isError };
}
diff --git a/src/hooks/use-chat-input-llm-profile-state.ts b/src/hooks/use-chat-input-llm-profile-state.ts
index e986e95987..a74300271a 100644
--- a/src/hooks/use-chat-input-llm-profile-state.ts
+++ b/src/hooks/use-chat-input-llm-profile-state.ts
@@ -1,5 +1,12 @@
import { useCallback } from "react";
-import { useIsMutating } from "@tanstack/react-query";
+import { useIsMutating, useQueryClient } from "@tanstack/react-query";
+import { WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME } from "#/api/agent-profiles-service/agent-profiles-service.api";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import {
+ llmProfileMirrored,
+ updateAgentProfile,
+} from "#/hooks/mutation/sync-agent-profiles";
+import { useAgentProfiles } from "#/hooks/query/use-agent-profiles";
import type { ProfileInfo } from "@openhands/typescript-client";
import { useOptionalConversationId } from "#/hooks/use-conversation-id";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
@@ -24,17 +31,17 @@ export interface ChatInputLlmProfileState {
*/
canSwitchProfile: boolean;
/**
- * Switch the LLM profile: live via `/switch_profile` when inside a
- * conversation, or activate it globally when on the home page (no
- * conversation) — see {@link useSwitchLlmProfile}.
+ * Switch the LLM profile: live via `/switch_profile` inside a conversation.
+ * On the home page it becomes the active agent profile's LLM, which for
+ * `default` means activating it (see {@link useSwitchLlmProfile}).
*/
selectProfile: (profileName: string) => void;
}
/**
* Backs the OpenHands LLM-profile switcher pill, both on the home page (where
- * a pick activates the profile globally so the next conversation launches
- * with it) and inside a conversation (live swap). The ACP analog is
+ * it shows and sets the LLM the active agent profile launches with) and
+ * inside a conversation (live swap). The ACP analog is
* {@link useChatInputModelState}. Mirrors the former SwitchProfileButton's
* resolution priority so a switch is reflected instantly.
*/
@@ -42,6 +49,11 @@ export function useChatInputLlmProfileState(): ChatInputLlmProfileState {
const { conversationId } = useOptionalConversationId();
const { data: conversation } = useActiveConversation();
const { data, isLoading } = useLlmProfiles();
+ const queryClient = useQueryClient();
+ const { backend } = useActiveBackend();
+ const { data: agentProfiles } = useAgentProfiles({
+ enabled: !conversationId && backend.kind === "local",
+ });
const canManageOrgProfiles = useCanManageOrgProfiles();
const { switchAndLog } = useSwitchLlmProfileAndLog();
// Read the switch's pending state globally by mutation key: the pill button
@@ -64,18 +76,35 @@ export function useChatInputLlmProfileState(): ChatInputLlmProfileState {
// 2. Profile stamped on the conversation, validated against the live list
// so a since-deleted/renamed profile falls through.
// 3. Profile whose model matches the running llm_model.
- // 4. User-level active_profile (fallback before the first message).
+ // 4. Before the first message, the active agent profile's own LLM, which
+ // the launch runs, else the user-level active_profile.
const stampedProfile = conversation?.active_profile ?? null;
const conversationProfile =
stampedProfile && profiles.some((p) => p.name === stampedProfile)
? stampedProfile
: null;
+ const activeAgentProfile = agentProfiles?.profiles?.find(
+ (profile) =>
+ profile.id != null &&
+ profile.id === agentProfiles.active_agent_profile_id,
+ );
+ const agentLlmProfile =
+ activeAgentProfile?.agent_kind === "openhands" &&
+ profiles.some((p) => p.name === activeAgentProfile.llm_profile_ref)
+ ? activeAgentProfile.llm_profile_ref
+ : null;
+ // `default` runs the active LLM profile, so a home pick activates it; any
+ // other profile keeps the pick as its own LLM.
+ const ownsHomeLlm =
+ !conversationId &&
+ agentLlmProfile !== null &&
+ activeAgentProfile?.name !== WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME;
const currentProfileName =
optimisticActiveProfile ??
conversationProfile ??
(conversationModel
? (profiles.find((p) => p.model === conversationModel)?.name ?? null)
- : (data?.active_profile ?? null));
+ : (agentLlmProfile ?? data?.active_profile ?? null));
const currentProfileModel =
profiles.find((p) => p.name === currentProfileName)?.model ??
conversationModel ??
@@ -93,9 +122,25 @@ export function useChatInputLlmProfileState(): ChatInputLlmProfileState {
const selectProfile = useCallback(
(profileName: string) => {
if (!canSwitchProfile || profileName === currentProfileName) return;
+ if (ownsHomeLlm && activeAgentProfile) {
+ updateAgentProfile(
+ queryClient,
+ activeAgentProfile.name,
+ llmProfileMirrored(profileName),
+ );
+ return;
+ }
switchAndLog(conversationId, profileName);
},
- [canSwitchProfile, conversationId, currentProfileName, switchAndLog],
+ [
+ canSwitchProfile,
+ conversationId,
+ currentProfileName,
+ switchAndLog,
+ ownsHomeLlm,
+ activeAgentProfile,
+ queryClient,
+ ],
);
return {
diff --git a/src/hooks/use-llm-configured.ts b/src/hooks/use-llm-configured.ts
index fe1b886a13..fee8424f52 100644
--- a/src/hooks/use-llm-configured.ts
+++ b/src/hooks/use-llm-configured.ts
@@ -2,11 +2,11 @@ import { useQuery } from "@tanstack/react-query";
import { useSettings } from "#/hooks/query/use-settings";
import { useConfig } from "#/hooks/query/use-config";
import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";
+import { WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME } from "#/api/agent-profiles-service/agent-profiles-service.api";
import { useActiveBackend } from "#/contexts/active-backend-context";
import { useActiveAgentProfile } from "#/hooks/use-active-agent-profile";
import { isSettingsPageHidden } from "#/utils/settings-utils";
import ProfilesService from "#/api/profiles-service/profiles-service.api";
-import { WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME } from "#/api/agent-profiles-service/agent-profiles-service.api";
import {
CONFIG_CACHE_OPTIONS,
LLM_PROFILES_QUERY_KEYS,
@@ -66,34 +66,25 @@ export function useLlmConfigured(): LlmConfiguredResult {
} = useActiveAgentProfile();
const isAcpAgent = activeAgentKind === "acp";
const hasApiKey = settings?.llm_api_key_set === true;
- // The LLM that will actually power the next conversation is the profile the
- // active AGENT profile references (`llm_profile_ref`) — conversations launch
- // from the agent profile, not the standalone "active LLM profile".
- // Except the local seeded `default` profile: `useCreateConversation` launches
- // it via `agent_settings` on the ACTIVE LLM, not the seed's ref, so gating on
- // that ref blocks launches that would have succeeded (#16193).
- const referencedLlmProfileName =
- activeAgentProfile?.agent_kind === "openhands" &&
- !(
- isLocal &&
- activeAgentProfile.name === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME
- )
- ? activeAgentProfile.llm_profile_ref
+ // Check the LLM profile the next home launch runs: the agent profile's own
+ // `llm_profile_ref`, except a local `default`, which runs the active LLM
+ // profile. Either falls back to the other when it names no saved profile.
+ const findLlmProfile = (name: string | null | undefined) =>
+ name
+ ? profilesData?.profiles.find((profile) => profile.name === name)
: undefined;
- const referencedProfile = referencedLlmProfileName
- ? profilesData?.profiles.find(
- (profile) => profile.name === referencedLlmProfileName,
- )
- : undefined;
- // Fall back to the active LLM profile when the ref is absent (list loading,
- // or an agent profile without a ref) OR stale (names a profile that no longer
- // exists): a launch runs the active LLM profile for a stale ref, so gating on
- // the ref would disable a composer whose launch succeeds.
- const activeProfile =
- referencedProfile ??
- profilesData?.profiles.find(
- (profile) => profile.name === profilesData?.active_profile,
- );
+ const referencedProfile = findLlmProfile(
+ activeAgentProfile?.agent_kind === "openhands"
+ ? activeAgentProfile.llm_profile_ref
+ : undefined,
+ );
+ const selectedProfile = findLlmProfile(profilesData?.active_profile);
+ const runsActiveLlmProfile =
+ isLocal &&
+ activeAgentProfile?.name === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME;
+ const activeProfile = runsActiveLlmProfile
+ ? (selectedProfile ?? referencedProfile)
+ : (referencedProfile ?? selectedProfile);
const hasActiveProfileApiKey = activeProfile?.api_key_set === true;
const shouldLoadActiveProfileDetail =
isLocal && !!activeProfile && !hasActiveProfileApiKey;
diff --git a/src/hooks/use-migrate-default-agent-profile.ts b/src/hooks/use-migrate-default-agent-profile.ts
new file mode 100644
index 0000000000..92b49d7b26
--- /dev/null
+++ b/src/hooks/use-migrate-default-agent-profile.ts
@@ -0,0 +1,194 @@
+import {
+ useQuery,
+ useQueryClient,
+ type QueryClient,
+} from "@tanstack/react-query";
+import AgentProfilesService, {
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,
+} from "#/api/agent-profiles-service/agent-profiles-service.api";
+import ProfilesService from "#/api/profiles-service/profiles-service.api";
+import type { StoredOpenHandsProfile } from "#/api/agent-profiles-service/profile-behavior";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import { isNoBackend } from "#/api/backend-registry/active-store";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { mergeAgentProfileSaveInput } from "#/components/features/settings/agent-profiles/merge-agent-profile-save-input";
+import {
+ AGENT_PROFILES_QUERY_KEYS,
+ SETTINGS_QUERY_KEYS,
+} from "#/hooks/query/query-keys";
+import type { Settings } from "#/types/settings";
+import {
+ migrateSkillEnablement,
+ resolveEnabledCatalogSkills,
+ toSkillEnablement,
+} from "#/utils/skill-enablement";
+
+const PROFILE_VERIFICATION_FIELDS = [
+ "critic_enabled",
+ "critic_mode",
+ "enable_iterative_refinement",
+ "critic_threshold",
+ "max_refinement_iterations",
+ "critic_server_url",
+ "critic_model_name",
+] as const;
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ !!value && typeof value === "object" && !Array.isArray(value);
+
+/**
+ * The `default` profile fields that reproduce the global settings it used to
+ * launch from. Skills come from the Skills page lists; the critic API key
+ * stays global.
+ */
+export function buildDefaultProfileMigration(
+ settings: Settings,
+): Partial<StoredOpenHandsProfile> {
+ const enablement = toSkillEnablement(settings);
+ const skills = migrateSkillEnablement(enablement) ?? {
+ enabled_skills: resolveEnabledCatalogSkills(enablement),
+ disabled_skills: enablement.disabledSkills ?? [],
+ };
+ const migrated: Partial<StoredOpenHandsProfile> = {
+ public_skills: skills.enabled_skills,
+ disabled_skills: skills.disabled_skills,
+ };
+
+ // Global settings left on an ACP agent carry no OpenHands behavior.
+ const agent: Record<string, unknown> = settings.agent_settings ?? {};
+ if (agent.agent_kind === "acp") return migrated;
+
+ const context = isRecord(agent.agent_context) ? agent.agent_context : {};
+ const globalVerification = isRecord(agent.verification)
+ ? agent.verification
+ : null;
+ // The secret-free subset; the critic API key stays global.
+ const verification = globalVerification
+ ? (Object.fromEntries(
+ PROFILE_VERIFICATION_FIELDS.filter(
+ (key) => key in globalVerification,
+ ).map((key) => [key, globalVerification[key]]),
+ ) as unknown as StoredOpenHandsProfile["verification"])
+ : undefined;
+
+ return {
+ ...migrated,
+ ...(isRecord(agent.condenser) ? { condenser: agent.condenser } : {}),
+ ...(verification ? { verification } : {}),
+ ...("tools" in agent
+ ? { tools: (agent.tools ?? null) as StoredOpenHandsProfile["tools"] }
+ : {}),
+ ...(typeof agent.persona === "string" || agent.persona === null
+ ? { persona: agent.persona }
+ : {}),
+ ...(typeof agent.agent === "string" ? { agent: agent.agent } : {}),
+ ...(typeof agent.tool_concurrency_limit === "number"
+ ? { tool_concurrency_limit: agent.tool_concurrency_limit }
+ : {}),
+ system_message_suffix:
+ typeof context.system_message_suffix === "string"
+ ? context.system_message_suffix
+ : null,
+ enable_classify_and_switch_llm_tool:
+ agent.enable_classify_and_switch_llm_tool === true,
+ meta_profile_ref:
+ typeof agent.active_meta_profile === "string"
+ ? agent.active_meta_profile
+ : null,
+ };
+}
+
+/**
+ * Copy global agent behavior into an OpenHands `default`, once. It also gets
+ * every MCP server switched on, every secret, and the active LLM profile. An
+ * ACP `default` already launched as stored, so it is left alone.
+ */
+async function migrateDefaultAgentProfile(): Promise<true> {
+ // Read the marker fresh: another tab may have migrated and then edited
+ // `default` since this one cached its settings.
+ SettingsService.invalidateCache();
+ const settings = await SettingsService.getSettings();
+ if (settings.default_profile_migrated) return true;
+
+ const { profiles } = await AgentProfilesService.listProfiles();
+ const hasOpenHandsDefault = profiles.some(
+ (profile) =>
+ profile.name === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME &&
+ profile.agent_kind === "openhands",
+ );
+ if (hasOpenHandsDefault) {
+ const { profile } = await AgentProfilesService.getProfile(
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,
+ );
+ if (profile.agent_kind === "openhands") {
+ const activeLlm = await ProfilesService.listProfiles()
+ .then((list) => list.active_profile)
+ .catch(() => null);
+ await AgentProfilesService.saveProfile(
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,
+ mergeAgentProfileSaveInput(profile, {
+ agent_kind: "openhands",
+ ...buildDefaultProfileMigration(settings),
+ mcp_server_refs: null,
+ secret_refs: null,
+ ...(activeLlm ? { llm_profile_ref: activeLlm } : {}),
+ }),
+ );
+ }
+ }
+ await SettingsService.saveSettings({ default_profile_migrated: true });
+ return true;
+}
+
+function migrationQuery(queryClient: QueryClient, backendId: string) {
+ return {
+ queryKey: ["default-profile-migration", backendId] as const,
+ queryFn: async () => {
+ await migrateDefaultAgentProfile();
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: AGENT_PROFILES_QUERY_KEYS.all,
+ }),
+ queryClient.invalidateQueries({ queryKey: SETTINGS_QUERY_KEYS.all }),
+ ]);
+ return true as const;
+ },
+ staleTime: Infinity,
+ retry: false,
+ meta: { disableToast: true },
+ };
+}
+
+/**
+ * Resolve once the local backend's `default` profile carries its migrated
+ * settings. A failure is left for the next caller to retry.
+ */
+export function ensureDefaultAgentProfileMigrated(
+ queryClient: QueryClient,
+ backendId: string,
+): Promise<true> {
+ return queryClient.ensureQueryData(migrationQuery(queryClient, backendId));
+}
+
+/** Wait for a migration already in flight; never start one. */
+export async function settleRunningDefaultAgentProfileMigration(
+ queryClient: QueryClient,
+ backendId: string,
+): Promise<void> {
+ const { queryKey } = migrationQuery(queryClient, backendId);
+ if (queryClient.getQueryState(queryKey)?.fetchStatus !== "fetching") return;
+ await ensureDefaultAgentProfileMigrated(queryClient, backendId);
+}
+
+/**
+ * Run the migration as soon as a local backend is active. Anything that edits
+ * `default` waits for it, or the migration could overwrite the edit.
+ */
+export function useMigrateDefaultAgentProfile() {
+ const queryClient = useQueryClient();
+ const { backend } = useActiveBackend();
+ return useQuery({
+ ...migrationQuery(queryClient, backend.id),
+ enabled: backend.kind === "local" && !isNoBackend(backend),
+ });
+}
diff --git a/src/hooks/use-settings-nav-items.ts b/src/hooks/use-settings-nav-items.ts
index ce863ba439..f2312383d6 100644
--- a/src/hooks/use-settings-nav-items.ts
+++ b/src/hooks/use-settings-nav-items.ts
@@ -17,6 +17,9 @@ export type SettingsNavRenderedItem =
| { type: "header"; text: I18nKey }
| { type: "divider" };
+// Locally each agent profile owns these settings.
+const PROFILE_OWNED_SETTINGS_PATHS = new Set(["/settings/condenser"]);
+
export function useSettingsNavItems(): SettingsNavRenderedItem[] {
const { data: config } = useConfig();
const { backend } = useActiveBackend();
@@ -28,7 +31,8 @@ export function useSettingsNavItems(): SettingsNavRenderedItem[] {
return OSS_NAV_ITEMS.filter(
(item) =>
!isSettingsPageHidden(item.to, featureFlags) &&
- (!isLockedToCloud || item.to === LOCKED_CLOUD_SETTINGS_NAV_PATH),
+ (!isLockedToCloud || item.to === LOCKED_CLOUD_SETTINGS_NAV_PATH) &&
+ (backend.kind === "cloud" || !PROFILE_OWNED_SETTINGS_PATHS.has(item.to)),
).map((item) => {
const renamedItem =
item.to === "/settings"
diff --git a/src/hooks/use-skill-enablement.ts b/src/hooks/use-skill-enablement.ts
index 02734bc17e..eac5e2fabc 100644
--- a/src/hooks/use-skill-enablement.ts
+++ b/src/hooks/use-skill-enablement.ts
@@ -1,8 +1,26 @@
import React from "react";
-import { useTranslation } from "react-i18next";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { HttpError } from "@openhands/typescript-client";
+import AgentProfilesService, {
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,
+} from "#/api/agent-profiles-service/agent-profiles-service.api";
+import type { StoredOpenHandsProfile } from "#/api/agent-profiles-service/profile-behavior";
+import { isNoBackend } from "#/api/backend-registry/active-store";
import { useActiveBackend } from "#/contexts/active-backend-context";
import { useSaveSettings } from "#/hooks/mutation/use-save-settings";
+import {
+ updateDefaultAgentProfile,
+ withSkillSelection,
+} from "#/hooks/mutation/sync-agent-profiles";
+import { useMigrateDefaultAgentProfile } from "#/hooks/use-migrate-default-agent-profile";
+import { useAgentProfiles } from "#/hooks/query/use-agent-profiles";
+import {
+ AGENT_PROFILES_QUERY_KEYS,
+ AGENT_PROFILES_RETRY_OPTIONS,
+ CONFIG_CACHE_OPTIONS,
+} from "#/hooks/query/query-keys";
import { useSettings } from "#/hooks/query/use-settings";
+import i18n from "#/i18n";
import { I18nKey } from "#/i18n/declaration";
import type { Settings, SkillInfo } from "#/types/settings";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
@@ -11,6 +29,7 @@ import {
buildSkillEnablementFilter,
CATALOG_SKILL_NAMES,
isCatalogSkill,
+ profileSkillEnablement,
resolveEnabledCatalogSkills,
type SkillEnablement,
} from "#/utils/skill-enablement";
@@ -32,18 +51,107 @@ function readSkillEnablement(
};
}
-/** Read-only view of the rule, for surfaces that list skills without toggling. */
-export function useSkillEnabledFilter(): (skill: SkillInfo) => boolean {
+/** The stored OpenHands profile with this id, read only on a local backend. */
+function useLocalOpenHandsProfile(
+ agentProfileId: string | null | undefined,
+): StoredOpenHandsProfile | null {
+ const { backend, orgId } = useActiveBackend();
+ const isLocal = backend.kind !== "cloud" && !!agentProfileId;
+ const { data: list } = useAgentProfiles({ enabled: isLocal });
+ const name = isLocal
+ ? (list?.profiles?.find((profile) => profile.id === agentProfileId)?.name ??
+ null)
+ : null;
+ const { data: detail } = useQuery({
+ queryKey: AGENT_PROFILES_QUERY_KEYS.detail(backend.id, orgId, name ?? ""),
+ queryFn: () => AgentProfilesService.getProfile(name!),
+ enabled: name !== null,
+ ...CONFIG_CACHE_OPTIONS,
+ ...AGENT_PROFILES_RETRY_OPTIONS,
+ meta: { disableToast: true },
+ });
+ return detail?.profile.agent_kind === "openhands"
+ ? (detail.profile as StoredOpenHandsProfile)
+ : null;
+}
+
+/**
+ * A local OpenHands `default`'s lists, which the Skills page edits; `null`
+ * where there is none and the page keeps the lists in settings.
+ */
+function useDefaultProfileSkills(): {
+ ready: boolean;
+ failed: boolean;
+ selection: SkillEnablement | null;
+} {
+ const { backend, orgId } = useActiveBackend();
+ const isLocal = backend.kind === "local" && !isNoBackend(backend);
+ const migration = useMigrateDefaultAgentProfile();
+ const { data, isLoading, error } = useQuery({
+ queryKey: AGENT_PROFILES_QUERY_KEYS.detail(
+ backend.id,
+ orgId,
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,
+ ),
+ queryFn: () =>
+ AgentProfilesService.getProfile(WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME),
+ enabled: isLocal && migration.isSuccess,
+ ...CONFIG_CACHE_OPTIONS,
+ ...AGENT_PROFILES_RETRY_OPTIONS,
+ meta: { disableToast: true },
+ });
+ const profile =
+ data?.profile.agent_kind === "openhands"
+ ? (data.profile as StoredOpenHandsProfile)
+ : null;
+ const hasProfile = profile !== null;
+ const selection = React.useMemo(
+ () => (profile ? profileSkillEnablement(profile) : null),
+ [hasProfile, profile?.public_skills, profile?.disabled_skills],
+ );
+ // Without `default`'s lists the page would show and write settings, which
+ // no launch reads; only a missing `default` falls back to them.
+ const failure =
+ (isLocal && migration.error) ||
+ (error && !(error instanceof HttpError && error.status === 404)
+ ? error
+ : null);
+ React.useEffect(() => {
+ if (failure) {
+ displayErrorToast(
+ retrieveAxiosErrorMessage(failure) || i18n.t(I18nKey.ERROR$GENERIC),
+ );
+ }
+ }, [failure]);
+ return {
+ ready: !isLocal || (migration.isSuccess && !isLoading && !failure),
+ failed: !!failure,
+ selection,
+ };
+}
+
+/**
+ * Read-only view of the rule, for surfaces that list skills without toggling.
+ * Locally a conversation loads its agent profile's selection, so pass the
+ * profile it launched with.
+ */
+export function useSkillEnabledFilter(
+ agentProfileId?: string | null,
+): (skill: SkillInfo) => boolean {
const { backend } = useActiveBackend();
const { data: settings } = useSettings();
const usesCatalogAllowList = backend.kind !== "cloud";
+ const profile = useLocalOpenHandsProfile(agentProfileId);
return React.useMemo(() => {
const isEnabled = buildSkillEnablementFilter(
- readSkillEnablement(settings, usesCatalogAllowList),
+ profile
+ ? profileSkillEnablement(profile)
+ : readSkillEnablement(settings, usesCatalogAllowList),
);
return (skill: SkillInfo) => isEnabled(skill.name);
}, [
+ profile,
settings?.enabled_skills,
settings?.disabled_skills,
usesCatalogAllowList,
@@ -53,6 +161,8 @@ export function useSkillEnabledFilter(): (skill: SkillInfo) => boolean {
export interface SkillEnablementController {
isEnabled: (skill: SkillInfo) => boolean;
setEnabled: (skillName: string, enabled: boolean) => void;
+ /** The list couldn't be read, so switching a skill would save nothing. */
+ isUnavailable: boolean;
}
/** Stable form of both lists, so an unchanged set can skip the save. */
@@ -80,18 +190,29 @@ function withMembership(
* surface cannot write a preference another cannot see.
*/
export function useSkillEnablement(): SkillEnablementController {
- const { t } = useTranslation("openhands");
const { backend } = useActiveBackend();
const usesCatalogAllowList = backend.kind !== "cloud";
+ const queryClient = useQueryClient();
const { data: settings, isLoading: settingsLoading } = useSettings();
- const { mutate: saveSettings } = useSaveSettings();
+ const { mutateAsync: saveSettings } = useSaveSettings();
+ const defaultSkills = useDefaultProfileSkills();
+ // Read at save time: a dependency would re-run the save with the
+ // pre-hydration selection when `default` finishes loading.
+ const ownedByDefaultRef = React.useRef(false);
+ ownedByDefaultRef.current = defaultSkills.selection !== null;
const [enablement, setEnablement] = React.useState<SkillEnablement>({});
const savedRef = React.useRef<string | null>(null);
+ // While writes to `default` are queued, its refetched lists lag the page.
+ const pendingWrites = React.useRef(0);
+ const [writesSettled, setWritesSettled] = React.useState(0);
React.useEffect(() => {
- if (settingsLoading || !settings) return;
- const hydrated = readSkillEnablement(settings, usesCatalogAllowList);
+ if (settingsLoading || !settings || !defaultSkills.ready) return;
+ if (pendingWrites.current > 0) return;
+ const hydrated =
+ defaultSkills.selection ??
+ readSkillEnablement(settings, usesCatalogAllowList);
savedRef.current = snapshot(hydrated);
setEnablement(hydrated);
}, [
@@ -99,6 +220,9 @@ export function useSkillEnablement(): SkillEnablementController {
settings?.enabled_skills,
settings?.disabled_skills,
usesCatalogAllowList,
+ defaultSkills.ready,
+ defaultSkills.selection,
+ writesSettled,
]);
React.useEffect(() => {
@@ -108,6 +232,20 @@ export function useSkillEnablement(): SkillEnablementController {
if (savedRef.current === null || savedRef.current === next) return;
savedRef.current = next;
+ const reportFailure = (error: unknown) =>
+ displayErrorToast(
+ retrieveAxiosErrorMessage(error) || i18n.t(I18nKey.ERROR$GENERIC),
+ );
+ if (ownedByDefaultRef.current) {
+ pendingWrites.current += 1;
+ updateDefaultAgentProfile(queryClient, withSkillSelection(enablement), {
+ onError: reportFailure,
+ }).finally(() => {
+ pendingWrites.current -= 1;
+ if (pendingWrites.current === 0) setWritesSettled((n) => n + 1);
+ });
+ return;
+ }
const disabledSkills = enablement.disabledSkills ?? [];
saveSettings(
usesCatalogAllowList
@@ -116,15 +254,8 @@ export function useSkillEnablement(): SkillEnablementController {
disabled_skills: disabledSkills,
}
: { disabled_skills: disabledSkills },
- {
- onError: (error) => {
- displayErrorToast(
- retrieveAxiosErrorMessage(error) || t(I18nKey.ERROR$GENERIC),
- );
- },
- },
- );
- }, [enablement, usesCatalogAllowList, saveSettings, t]);
+ ).catch(reportFailure);
+ }, [enablement, usesCatalogAllowList, saveSettings, queryClient]);
const isEnabled = React.useMemo(() => {
const enabled = buildSkillEnablementFilter(enablement);
@@ -156,5 +287,5 @@ export function useSkillEnablement(): SkillEnablementController {
[usesCatalogAllowList],
);
- return { isEnabled, setEnabled };
+ return { isEnabled, setEnabled, isUnavailable: defaultSkills.failed };
}
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 50b2477f3c..3d52eda96c 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -503,60 +503,6 @@
"ca": "Aquest agent rep les eines que el servidor considera estàndard, mostrades a dalt. La llista depèn del servidor, així que pot canviar quan s'actualitzi.",
"id": "Agen ini mendapatkan alat yang dianggap standar oleh server, yang ditampilkan di atas. Daftarnya mengikuti server, sehingga dapat berubah saat server ditingkatkan."
},
- "SETTINGS$AGENT_PROFILE_TOOLS_DEFAULT_PROFILE": {
- "en": "The default profile always launches with the global tool set. Create a named profile to choose its tools.",
- "ja": "デフォルトのプロファイルは常にグローバルなツールセットで起動します。ツールを選ぶには、名前付きのプロファイルを作成してください。",
- "zh-CN": "默认配置文件始终使用全局工具集启动。如需选择工具,请创建一个命名配置文件。",
- "zh-TW": "預設設定檔一律以全域工具集啟動。若要選擇工具,請建立具名設定檔。",
- "ko-KR": "기본 프로필은 항상 전역 도구 세트로 시작됩니다. 도구를 선택하려면 이름이 있는 프로필을 만드세요.",
- "no": "Standardprofilen starter alltid med det globale verktøysettet. Opprett en navngitt profil for å velge verktøyene.",
- "it": "Il profilo predefinito si avvia sempre con il set di strumenti globale. Crea un profilo con nome per sceglierne gli strumenti.",
- "pt": "O perfil padrão sempre inicia com o conjunto global de ferramentas. Crie um perfil com nome para escolher as ferramentas.",
- "es": "El perfil predeterminado siempre se inicia con el conjunto de herramientas global. Crea un perfil con nombre para elegir sus herramientas.",
- "ar": "يبدأ الملف الشخصي الافتراضي دائمًا بمجموعة الأدوات العامة. أنشئ ملفًا شخصيًا باسم لاختيار أدواته.",
- "fr": "Le profil par défaut démarre toujours avec les outils globaux. Créez un profil nommé pour choisir ses outils.",
- "tr": "Varsayılan profil her zaman genel araç setiyle başlar. Araçlarını seçmek için adlandırılmış bir profil oluşturun.",
- "de": "Das Standardprofil startet immer mit den globalen Werkzeugen. Erstellen Sie ein benanntes Profil, um seine Werkzeuge auszuwählen.",
- "uk": "Типовий профіль завжди запускається з глобальним набором інструментів. Щоб вибрати інструменти, створіть іменований профіль.",
- "ca": "El perfil predeterminat sempre s’inicia amb el conjunt d’eines global. Crea un perfil amb nom per triar-ne les eines.",
- "id": "Profil default selalu diluncurkan dengan kumpulan alat global. Buat profil bernama untuk memilih alatnya."
- },
- "SETTINGS$GLOBAL_TOOLS_CUSTOM": {
- "en": "Conversations started without an agent profile use a custom tool list: {{names}}.",
- "ja": "エージェントプロファイルなしで開始した会話は、カスタムのツール一覧を使用します: {{names}}。",
- "zh-CN": "未使用代理配置文件启动的对话将使用自定义工具列表:{{names}}。",
- "zh-TW": "未使用代理設定檔啟動的對話會使用自訂工具清單:{{names}}。",
- "ko-KR": "에이전트 프로필 없이 시작한 대화는 사용자 지정 도구 목록을 사용합니다: {{names}}.",
- "no": "Samtaler som startes uten en agentprofil bruker en egendefinert verktøyliste: {{names}}.",
- "it": "Le conversazioni avviate senza un profilo agente usano un elenco di strumenti personalizzato: {{names}}.",
- "pt": "As conversas iniciadas sem um perfil de agente usam uma lista de ferramentas personalizada: {{names}}.",
- "es": "Las conversaciones iniciadas sin un perfil de agente usan una lista de herramientas personalizada: {{names}}.",
- "ar": "تستخدم المحادثات التي تبدأ دون ملف تعريف وكيل قائمة أدوات مخصصة: {{names}}.",
- "fr": "Les conversations démarrées sans profil d'agent utilisent une liste d'outils personnalisée : {{names}}.",
- "tr": "Aracı profili olmadan başlatılan konuşmalar özel bir araç listesi kullanır: {{names}}.",
- "de": "Unterhaltungen, die ohne Agentenprofil gestartet werden, verwenden eine benutzerdefinierte Werkzeugliste: {{names}}.",
- "uk": "Розмови, розпочаті без профілю агента, використовують власний список інструментів: {{names}}.",
- "ca": "Les converses iniciades sense un perfil d'agent fan servir una llista d'eines personalitzada: {{names}}.",
- "id": "Percakapan yang dimulai tanpa profil agen menggunakan daftar alat khusus: {{names}}."
- },
- "SETTINGS$GLOBAL_TOOLS_RESET": {
- "en": "Reset to standard tools",
- "ja": "標準ツールに戻す",
- "zh-CN": "重置为标准工具",
- "zh-TW": "重設為標準工具",
- "ko-KR": "표준 도구로 재설정",
- "no": "Tilbakestill til standardverktøy",
- "it": "Ripristina gli strumenti standard",
- "pt": "Redefinir para as ferramentas padrão",
- "es": "Restablecer las herramientas estándar",
- "ar": "إعادة التعيين إلى الأدوات القياسية",
- "fr": "Rétablir les outils standard",
- "tr": "Standart araçlara sıfırla",
- "de": "Auf Standardwerkzeuge zurücksetzen",
- "uk": "Скинути до стандартних інструментів",
- "ca": "Restableix les eines estàndard",
- "id": "Reset ke alat standar"
- },
"TASK$SUBAGENT": {
"en": "Subagent:",
"ja": "サブエージェント:",
@@ -2627,6 +2573,42 @@
"ca": "Perfil LLM",
"id": "Profil LLM"
},
+ "SETTINGS$AGENT_PROFILE_DEFAULT_LLM_NOTE": {
+ "en": "The default profile uses the active LLM profile. Picking another one here makes it active.",
+ "ja": "デフォルトのプロファイルはアクティブな LLM プロファイルを使います。ここで別のものを選ぶとそれがアクティブになります。",
+ "zh-CN": "默认配置文件使用当前启用的 LLM 配置文件。在此处选择其他配置文件会将其设为启用。",
+ "zh-TW": "預設設定檔使用目前啟用的 LLM 設定檔。在此處選擇其他設定檔會將其設為啟用。",
+ "ko-KR": "기본 프로필은 활성 LLM 프로필을 사용합니다. 여기에서 다른 것을 고르면 그것이 활성화됩니다.",
+ "no": "Standardprofilen bruker den aktive LLM-profilen. Velger du en annen her, blir den aktiv.",
+ "it": "Il profilo predefinito usa il profilo LLM attivo. Sceglierne un altro qui lo rende attivo.",
+ "pt": "O perfil padrão usa o perfil LLM ativo. Escolher outro aqui torna-o ativo.",
+ "es": "El perfil predeterminado usa el perfil LLM activo. Elegir otro aquí lo activa.",
+ "ar": "يستخدم الملف الافتراضي ملف LLM النشط. اختيار ملف آخر هنا يجعله نشطًا.",
+ "fr": "Le profil par défaut utilise le profil LLM actif. En choisir un autre ici le rend actif.",
+ "tr": "Varsayılan profil etkin LLM profilini kullanır. Burada başka birini seçmek onu etkin yapar.",
+ "de": "Das Standardprofil nutzt das aktive LLM-Profil. Wählst du hier ein anderes, wird es aktiv.",
+ "uk": "Типовий профіль використовує активний профіль LLM. Вибір іншого тут робить його активним.",
+ "ca": "El perfil per defecte fa servir el perfil LLM actiu. Triar-ne un altre aquí el fa actiu.",
+ "id": "Profil bawaan memakai profil LLM yang aktif. Memilih yang lain di sini membuatnya aktif."
+ },
+ "SETTINGS$AGENT_PROFILE_DEFAULT_LOCKED": {
+ "en": "The default profile can't be renamed or deleted.",
+ "ja": "デフォルトのプロファイルは名前の変更や削除ができません。",
+ "zh-CN": "默认配置文件不能重命名或删除。",
+ "zh-TW": "預設設定檔無法重新命名或刪除。",
+ "ko-KR": "기본 프로필은 이름을 바꾸거나 삭제할 수 없습니다.",
+ "no": "Standardprofilen kan ikke gis nytt navn eller slettes.",
+ "it": "Il profilo predefinito non può essere rinominato né eliminato.",
+ "pt": "O perfil padrão não pode ser renomeado nem excluído.",
+ "es": "El perfil predeterminado no se puede renombrar ni eliminar.",
+ "ar": "لا يمكن إعادة تسمية الملف الافتراضي أو حذفه.",
+ "fr": "Le profil par défaut ne peut pas être renommé ni supprimé.",
+ "tr": "Varsayılan profil yeniden adlandırılamaz veya silinemez.",
+ "de": "Das Standardprofil kann nicht umbenannt oder gelöscht werden.",
+ "uk": "Типовий профіль не можна перейменувати чи видалити.",
+ "ca": "El perfil per defecte no es pot reanomenar ni suprimir.",
+ "id": "Profil bawaan tidak dapat diganti namanya atau dihapus."
+ },
"SETTINGS$AGENT_PROFILE_LLM_REQUIRED": {
"en": "Select an LLM profile for this agent.",
"ja": "このエージェントのLLMプロファイルを選択してください。",
@@ -7307,6 +7289,24 @@
"ca": "Encamina el primer missatge de cada nova conversa a través de l'encaminador de models actiu abans que l'agent continú.",
"id": "Rutekan pesan pertama setiap percakapan baru melalui Model Router aktif sebelum agen melanjutkan."
},
+ "SETTINGS$META_PROFILE_RUN_AT_CONVERSATION_START_HELP_PROFILE": {
+ "en": "Route the first message of every new conversation through its agent profile's Model Router before the agent proceeds. Each agent profile picks its router in Settings → Agent.",
+ "ja": "エージェントが処理を始める前に、新しい会話の最初のメッセージをそのエージェントプロファイルのモデルルーターに振り分けます。ルーターは設定 → エージェントでエージェントプロファイルごとに選択します。",
+ "zh-CN": "在代理继续之前,将每个新对话的第一条消息通过其代理配置文件的模型路由器进行路由。每个代理配置文件在“设置 → 代理”中选择自己的路由器。",
+ "zh-TW": "在代理繼續之前,將每個新對話的第一則訊息透過其代理設定檔的模型路由器進行路由。每個代理設定檔在「設定 → 代理」中選擇自己的路由器。",
+ "ko-KR": "에이전트가 진행하기 전에 모든 새 대화의 첫 메시지를 해당 에이전트 프로필의 모델 라우터로 라우팅합니다. 각 에이전트 프로필의 라우터는 설정 → 에이전트에서 선택합니다.",
+ "no": "Ruter den første meldingen i hver ny samtale gjennom agentprofilens modellruter før agenten fortsetter. Hver agentprofil velger sin ruter under Innstillinger → Agent.",
+ "it": "Instrada il primo messaggio di ogni nuova conversazione attraverso il router dei modelli del suo profilo agente prima che l'agente proceda. Ogni profilo agente sceglie il proprio router in Impostazioni → Agente.",
+ "pt": "Encaminha a primeira mensagem de cada nova conversa pelo roteador de modelos do seu perfil de agente antes que o agente prossiga. Cada perfil de agente escolhe o seu roteador em Configurações → Agente.",
+ "es": "Enruta el primer mensaje de cada nueva conversación a través del enrutador de modelos de su perfil de agente antes de que el agente continúe. Cada perfil de agente elige su enrutador en Configuración → Agente.",
+ "ar": "وجّه أول رسالة من كل محادثة جديدة عبر موجّه النماذج الخاص بملف تعريف الوكيل قبل أن يكمل الوكيل. يختار كل ملف تعريف وكيل موجّهه من الإعدادات ← الوكيل.",
+ "fr": "Achemine le premier message de chaque nouvelle conversation via le routeur de modèles de son profil d'agent avant que l'agent ne continue. Chaque profil d'agent choisit son routeur dans Paramètres → Agent.",
+ "tr": "Aracı devam etmeden önce her yeni konuşmanın ilk mesajını ajan profilinin model yönlendiricisi üzerinden yönlendirir. Her ajan profili yönlendiricisini Ayarlar → Ajan bölümünden seçer.",
+ "de": "Leitet die erste Nachricht jeder neuen Konversation über den Modell-Router ihres Agentenprofils, bevor der Agent fortfährt. Jedes Agentenprofil wählt seinen Router unter Einstellungen → Agent.",
+ "uk": "Спрямовує перше повідомлення кожної нової розмови через маршрутизатор моделей її профілю агента, перш ніж агент продовжить. Кожен профіль агента вибирає свій маршрутизатор у Налаштування → Агент.",
+ "ca": "Encamina el primer missatge de cada nova conversa a través de l'encaminador de models del seu perfil d'agent abans que l'agent continuï. Cada perfil d'agent tria el seu encaminador a Configuració → Agent.",
+ "id": "Rutekan pesan pertama setiap percakapan baru melalui Model Router dari profil agennya sebelum agen melanjutkan. Setiap profil agen memilih router-nya di Pengaturan → Agen."
+ },
"SETTINGS$AGENT_PAGE_DESCRIPTION": {
"en": "Choose between the built-in OpenHands agent and an external ACP (Agent Client Protocol) subprocess such as Claude Code, Codex, or Gemini CLI.",
"ja": "組み込みのOpenHandsエージェントと、Claude Code、Codex、Gemini CLIなどの外部ACP(Agent Client Protocol)サブプロセスのどちらかを選択します。",
@@ -7433,6 +7433,24 @@
"ca": "Aquest agent pot fer servir tots els servidors MCP que has configurat, inclosos els que poden fer canvis.",
"id": "Agen ini dapat menggunakan setiap server MCP yang Anda konfigurasi, termasuk yang dapat membuat perubahan."
},
+ "SETTINGS$AGENT_PROFILE_DEFAULT_MCP_NOTE": {
+ "en": "The default profile uses the servers switched on in MCP Servers. Changing them here switches them there, for every profile.",
+ "ja": "デフォルトのプロファイルは、MCP サーバーでオンになっているサーバーを使います。ここで変更すると、すべてのプロファイルに対してそちらも変わります。",
+ "zh-CN": "默认配置文件使用在 MCP 服务器中开启的服务器。在此处更改会同时更改那里,对所有配置文件生效。",
+ "zh-TW": "預設設定檔使用在 MCP 伺服器中開啟的伺服器。在此處變更也會變更那裡,對所有設定檔生效。",
+ "ko-KR": "기본 프로필은 MCP 서버에서 켜진 서버를 사용합니다. 여기에서 바꾸면 모든 프로필에 대해 그곳도 바뀝니다.",
+ "no": "Standardprofilen bruker serverne som er slått på i MCP-servere. Endrer du dem her, endres de der, for alle profiler.",
+ "it": "Il profilo predefinito usa i server attivati in Server MCP. Modificarli qui li modifica anche lì, per tutti i profili.",
+ "pt": "O perfil padrão usa os servidores ativados em Servidores MCP. Alterá-los aqui altera-os lá, para todos os perfis.",
+ "es": "El perfil predeterminado usa los servidores activados en Servidores MCP. Cambiarlos aquí los cambia allí, para todos los perfiles.",
+ "ar": "يستخدم الملف الافتراضي الخوادم المفعّلة في خوادم MCP. تغييرها هنا يغيّرها هناك، لكل الملفات.",
+ "fr": "Le profil par défaut utilise les serveurs activés dans Serveurs MCP. Les modifier ici les modifie là-bas, pour tous les profils.",
+ "tr": "Varsayılan profil, MCP Sunucuları'nda açık olan sunucuları kullanır. Burada değiştirmek, tüm profiller için orayı da değiştirir.",
+ "de": "Das Standardprofil nutzt die in MCP-Server aktivierten Server. Änderungen hier gelten auch dort, für alle Profile.",
+ "uk": "Типовий профіль використовує сервери, увімкнені в розділі MCP-сервери. Зміни тут змінюють їх і там, для всіх профілів.",
+ "ca": "El perfil per defecte fa servir els servidors activats a Servidors MCP. Canviar-los aquí els canvia allà, per a tots els perfils.",
+ "id": "Profil bawaan memakai server yang aktif di Server MCP. Mengubahnya di sini juga mengubahnya di sana, untuk semua profil."
+ },
"SETTINGS$AGENT_PROFILE_MCP_CHOOSE_HINT": {
"en": "This agent can use only the servers you select. Every other MCP server stays hidden from it.",
"ja": "このエージェントは選択したサーバーのみを使用できます。ほかのMCPサーバーは表示されません。",
@@ -7919,6 +7937,24 @@
"ca": "Sol·licituds de confirmació i comprovacions de seguretat sobre les accions.",
"id": "Prompt konfirmasi dan pemeriksaan keamanan pada tindakan."
},
+ "SETTINGS$VERIFICATION_CRITIC_PER_PROFILE": {
+ "en": "Each agent profile turns the critic on or off in Settings → Agent.",
+ "ja": "クリティックのオン・オフは、設定 → エージェントでエージェントプロファイルごとに切り替えます。",
+ "zh-CN": "每个代理配置文件在“设置 → 代理”中开启或关闭评审器。",
+ "zh-TW": "每個代理設定檔在「設定 → 代理」中開啟或關閉評審器。",
+ "ko-KR": "크리틱은 설정 → 에이전트에서 에이전트 프로필마다 켜거나 끕니다.",
+ "no": "Hver agentprofil slår kritikeren av eller på under Innstillinger → Agent.",
+ "it": "Ogni profilo agente attiva o disattiva il critico in Impostazioni → Agente.",
+ "pt": "Cada perfil de agente ativa ou desativa o crítico em Configurações → Agente.",
+ "es": "Cada perfil de agente activa o desactiva el crítico en Configuración → Agente.",
+ "ar": "يشغّل كل ملف تعريف وكيل الناقد أو يوقفه من الإعدادات ← الوكيل.",
+ "fr": "Chaque profil d'agent active ou désactive le critique dans Paramètres → Agent.",
+ "tr": "Her ajan profili eleştirmeni Ayarlar → Ajan bölümünden açar veya kapatır.",
+ "de": "Jedes Agentenprofil schaltet den Kritiker unter Einstellungen → Agent ein oder aus.",
+ "uk": "Кожен профіль агента вмикає чи вимикає критика в Налаштування → Агент.",
+ "ca": "Cada perfil d'agent activa o desactiva el crític a Configuració → Agent.",
+ "id": "Setiap profil agen menyalakan atau mematikan critic di Pengaturan → Agen."
+ },
"SETTINGS$PAGE_APPLICATION_SUBLINE": {
"en": "Language, theme, notifications, and Git identity.",
"ja": "言語、テーマ、通知、およびGitアイデンティティ。",
@@ -38771,6 +38807,42 @@
"zh-TW": "技能變更僅對新對話生效。",
"id": "Perubahan skill hanya berlaku untuk percakapan baru."
},
+ "SETTINGS$SKILLS_DEFAULT_LIST_NOTICE": {
+ "ar": "هذه مهارات ملف تعريف الوكيل الافتراضي، وتبدأ ملفات تعريف الوكلاء الجديدة من هذه القائمة. تحتفظ ملفات التعريف الأخرى بقوائمها الخاصة.",
+ "ca": "Aquestes són les habilitats del perfil d'agent per defecte, i els perfils d'agent nous parteixen d'aquesta llista. Els altres perfils conserven la seva pròpia llista.",
+ "de": "Das sind die Fähigkeiten des Standard-Agentenprofils, und neue Agentenprofile beginnen mit dieser Liste. Andere Profile behalten ihre eigene Liste.",
+ "en": "These are the default agent profile's skills, and new agent profiles start from this list. Other profiles keep their own list.",
+ "es": "Estas son las habilidades del perfil de agente predeterminado, y los nuevos perfiles de agente parten de esta lista. Los demás perfiles conservan su propia lista.",
+ "fr": "Voici les compétences du profil d'agent par défaut, et les nouveaux profils d'agent partent de cette liste. Les autres profils conservent leur propre liste.",
+ "it": "Queste sono le competenze del profilo agente predefinito, e i nuovi profili agente partono da questo elenco. Gli altri profili mantengono il proprio elenco.",
+ "ja": "これはデフォルトのエージェントプロファイルのスキルで、新しいエージェントプロファイルはこのリストから始まります。他のプロファイルは独自のリストを保持します。",
+ "ko-KR": "기본 에이전트 프로필의 스킬이며, 새 에이전트 프로필은 이 목록으로 시작합니다. 다른 프로필은 자체 목록을 유지합니다.",
+ "no": "Dette er ferdighetene til standard agentprofil, og nye agentprofiler starter med denne listen. Andre profiler beholder sin egen liste.",
+ "pt": "Estas são as habilidades do perfil de agente padrão, e os novos perfis de agente começam com esta lista. Os outros perfis mantêm a sua própria lista.",
+ "tr": "Bunlar varsayılan ajan profilinin yetenekleridir ve yeni ajan profilleri bu listeyle başlar. Diğer profiller kendi listelerini korur.",
+ "uk": "Це навички типового профілю агента, і нові профілі агента починаються з цього списку. Інші профілі зберігають власний список.",
+ "zh-CN": "这些是默认代理配置文件的技能,新代理配置文件将从此列表开始。其他配置文件保留自己的列表。",
+ "zh-TW": "這些是預設代理設定檔的技能,新代理設定檔會從此清單開始。其他設定檔會保留自己的清單。",
+ "id": "Ini adalah skill profil agen bawaan, dan profil agen baru dimulai dari daftar ini. Profil lain menyimpan daftarnya sendiri."
+ },
+ "SETTINGS$DEFAULT_PROFILE_NOT_UPDATED": {
+ "ar": "تم الحفظ، لكن تعذّر تحديث ملفات تعريف الوكلاء لتتطابق.",
+ "ca": "S'ha desat, però no s'han pogut actualitzar els perfils d'agent perquè hi coincideixin.",
+ "de": "Gespeichert, aber deine Agentenprofile konnten nicht angepasst werden.",
+ "en": "Saved, but your agent profiles couldn't be updated to match.",
+ "es": "Guardado, pero no se pudieron actualizar tus perfiles de agente para que coincidan.",
+ "fr": "Enregistré, mais vos profils d'agent n'ont pas pu être mis à jour en conséquence.",
+ "it": "Salvato, ma non è stato possibile aggiornare i tuoi profili agente di conseguenza.",
+ "ja": "保存しましたが、エージェントプロファイルを合わせて更新できませんでした。",
+ "ko-KR": "저장했지만 에이전트 프로필을 맞춰 업데이트하지 못했습니다.",
+ "no": "Lagret, men agentprofilene dine kunne ikke oppdateres tilsvarende.",
+ "pt": "Salvo, mas não foi possível atualizar os seus perfis de agente para corresponder.",
+ "tr": "Kaydedildi, ancak ajan profilleriniz buna göre güncellenemedi.",
+ "uk": "Збережено, але не вдалося відповідно оновити ваші профілі агента.",
+ "zh-CN": "已保存,但无法相应更新你的代理配置文件。",
+ "zh-TW": "已儲存,但無法相應更新你的代理設定檔。",
+ "id": "Tersimpan, tetapi profil agen Anda tidak dapat diperbarui agar sesuai."
+ },
"SETTINGS$SKILLS_SOURCE_PROJECT": {
"en": "This project",
"ja": "このプロジェクト",
@@ -47807,6 +47879,24 @@
"ca": "Permet els secrets proporcionats en iniciar l’agent. Per a les automatitzacions, tria explícitament els secrets en aquest perfil.",
"id": "Mengizinkan rahasia yang disediakan saat agen dimulai. Untuk otomatisasi, pilih rahasia secara eksplisit di profil ini."
},
+ "SETTINGS$AGENT_PROFILE_DEFAULT_SECRETS_NOTE": {
+ "en": "The default profile always has every secret.",
+ "ja": "デフォルトのプロファイルは常にすべてのシークレットを使えます。",
+ "zh-CN": "默认配置文件始终拥有所有密钥。",
+ "zh-TW": "預設設定檔一律擁有所有密鑰。",
+ "ko-KR": "기본 프로필은 항상 모든 시크릿을 가집니다.",
+ "no": "Standardprofilen har alltid alle hemmeligheter.",
+ "it": "Il profilo predefinito ha sempre tutti i segreti.",
+ "pt": "O perfil padrão tem sempre todos os segredos.",
+ "es": "El perfil predeterminado siempre tiene todos los secretos.",
+ "ar": "يملك الملف الافتراضي دائمًا كل الأسرار.",
+ "fr": "Le profil par défaut a toujours tous les secrets.",
+ "tr": "Varsayılan profil her zaman tüm gizli anahtarlara sahiptir.",
+ "de": "Das Standardprofil hat immer alle Geheimnisse.",
+ "uk": "Типовий профіль завжди має всі секрети.",
+ "ca": "El perfil per defecte sempre té tots els secrets.",
+ "id": "Profil bawaan selalu memiliki semua rahasia."
+ },
"SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT": {
"en": "System prompt",
"ja": "システムプロンプト",
@@ -47915,24 +48005,6 @@
"ca": "Substitueix la persona integrada d’OpenHands i el flux de treball de programació. La memòria, les pautes de seguretat i d’eines, les habilitats, les instruccions del repositori i el context d’execució s’hi continuen incloent.",
"id": "Menggantikan persona dan alur kerja coding bawaan OpenHands. Panduan memori, keamanan, dan alat, skill, instruksi repositori, serta konteks runtime tetap disertakan."
},
- "SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_DEFAULT_PROFILE": {
- "en": "The default profile always uses the OpenHands system prompt. Create a named profile to customize it.",
- "ja": "デフォルトのプロファイルでは常に OpenHands のシステムプロンプトが使われます。カスタマイズするには、名前付きのプロファイルを作成してください。",
- "zh-CN": "默认配置文件始终使用 OpenHands 系统提示词。如需自定义,请创建一个命名配置文件。",
- "zh-TW": "預設設定檔一律使用 OpenHands 系統提示詞。若要自訂,請建立具名設定檔。",
- "ko-KR": "기본 프로필은 항상 OpenHands 시스템 프롬프트를 사용합니다. 사용자 지정하려면 이름이 있는 프로필을 만드세요.",
- "no": "Standardprofilen bruker alltid OpenHands-systemprompten. Opprett en navngitt profil for å tilpasse den.",
- "it": "Il profilo predefinito usa sempre il prompt di sistema di OpenHands. Crea un profilo con nome per personalizzarlo.",
- "pt": "O perfil padrão sempre usa o prompt do sistema do OpenHands. Crie um perfil com nome para personalizá-lo.",
- "es": "El perfil predeterminado siempre usa el prompt del sistema de OpenHands. Crea un perfil con nombre para personalizarlo.",
- "ar": "يستخدم الملف الشخصي الافتراضي دائمًا موجّه نظام OpenHands. أنشئ ملفًا شخصيًا باسم لتخصيصه.",
- "fr": "Le profil par défaut utilise toujours le prompt système d’OpenHands. Créez un profil nommé pour le personnaliser.",
- "tr": "Varsayılan profil her zaman OpenHands sistem istemini kullanır. Özelleştirmek için adlandırılmış bir profil oluşturun.",
- "de": "Das Standardprofil verwendet immer den OpenHands-System-Prompt. Erstellen Sie ein benanntes Profil, um ihn anzupassen.",
- "uk": "Типовий профіль завжди використовує системний промпт OpenHands. Щоб налаштувати його, створіть іменований профіль.",
- "ca": "El perfil predeterminat sempre fa servir la indicació del sistema d’OpenHands. Crea un perfil amb nom per personalitzar-la.",
- "id": "Profil default selalu menggunakan prompt sistem OpenHands. Buat profil bernama untuk menyesuaikannya."
- },
"SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_PLACEHOLDER": {
"en": "Describe who this agent is and how it should work.",
"ja": "このエージェントの役割と作業の進め方を説明してください。",
@@ -52379,41 +52451,23 @@
"ca": "Aquest agent carrega les habilitats activades aquí. Els perfils nous parteixen de les habilitats seleccionades a la pàgina Habilitats. Les habilitats d'un repositori sempre es carreguen.",
"id": "Agen ini memuat skill yang diaktifkan di sini. Profil baru dimulai dari skill yang dipilih di halaman Skill. Skill dari repositori selalu dimuat."
},
- "SETTINGS$AGENT_PROFILE_SKILLS_DEFAULT_PROFILE": {
- "en": "The default profile always launches with the skills selected on the Skills page. Create a named profile to choose its own.",
- "ja": "デフォルトのプロファイルは常にスキルページで選択したスキルで起動します。独自に選ぶには、名前付きのプロファイルを作成してください。",
- "zh-CN": "默认配置文件始终使用技能页面上选择的技能启动。如需单独选择,请创建一个命名配置文件。",
- "zh-TW": "預設設定檔一律以技能頁面上選取的技能啟動。若要單獨選擇,請建立具名設定檔。",
- "ko-KR": "기본 프로필은 항상 스킬 페이지에서 선택한 스킬로 시작됩니다. 따로 선택하려면 이름이 있는 프로필을 만드세요.",
- "no": "Standardprofilen starter alltid med ferdighetene som er valgt på Ferdigheter-siden. Opprett en navngitt profil for å velge egne.",
- "it": "Il profilo predefinito si avvia sempre con le competenze selezionate nella pagina Competenze. Crea un profilo con nome per sceglierne di proprie.",
- "pt": "O perfil padrão sempre inicia com as habilidades selecionadas na página Habilidades. Crie um perfil com nome para escolher as suas.",
- "es": "El perfil predeterminado siempre se inicia con las habilidades seleccionadas en la página Habilidades. Crea un perfil con nombre para elegir las suyas.",
- "ar": "يبدأ الملف الشخصي الافتراضي دائمًا بالمهارات المحددة في صفحة المهارات. أنشئ ملفًا شخصيًا باسم لاختيار مهاراته الخاصة.",
- "fr": "Le profil par défaut démarre toujours avec les compétences sélectionnées sur la page Compétences. Créez un profil nommé pour choisir les siennes.",
- "tr": "Varsayılan profil her zaman Yetenekler sayfasında seçilen yeteneklerle başlar. Kendi yeteneklerini seçmek için adlandırılmış bir profil oluşturun.",
- "de": "Das Standardprofil startet immer mit den auf der Seite „Fähigkeiten“ ausgewählten Fähigkeiten. Erstellen Sie ein benanntes Profil, um eigene auszuwählen.",
- "uk": "Типовий профіль завжди запускається з навичками, вибраними на сторінці «Навички». Щоб вибрати власні, створіть іменований профіль.",
- "ca": "El perfil predeterminat sempre s'inicia amb les habilitats seleccionades a la pàgina Habilitats. Crea un perfil amb nom per triar-ne les seves.",
- "id": "Profil default selalu diluncurkan dengan skill yang dipilih di halaman Skill. Buat profil bernama untuk memilih skill-nya sendiri."
- },
- "SETTINGS$AGENT_PROFILE_BEHAVIOR_DEFAULT_PROFILE": {
- "en": "The default profile always launches with the global Condenser and Verification settings. Create a named profile to choose its own.",
- "ja": "デフォルトのプロファイルは常にグローバルなコンデンサーと検証の設定で起動します。独自の設定を選ぶには、名前付きのプロファイルを作成してください。",
- "zh-CN": "默认配置文件始终使用全局的压缩器和验证设置启动。如需单独设置,请创建一个命名配置文件。",
- "zh-TW": "預設設定檔一律以全域的壓縮器和驗證設定啟動。若要單獨設定,請建立具名設定檔。",
- "ko-KR": "기본 프로필은 항상 전역 압축기 및 검증 설정으로 시작됩니다. 별도로 설정하려면 이름이 있는 프로필을 만드세요.",
- "no": "Standardprofilen starter alltid med de globale innstillingene for kondensator og verifisering. Opprett en navngitt profil for å velge egne.",
- "it": "Il profilo predefinito si avvia sempre con le impostazioni globali di condensatore e verifica. Crea un profilo con nome per sceglierne di proprie.",
- "pt": "O perfil padrão sempre inicia com as configurações globais de condensador e verificação. Crie um perfil com nome para escolher as suas.",
- "es": "El perfil predeterminado siempre se inicia con la configuración global de condensador y verificación. Crea un perfil con nombre para elegir la suya.",
- "ar": "يبدأ الملف الشخصي الافتراضي دائمًا بإعدادات المكثف والتحقق العامة. أنشئ ملفًا شخصيًا باسم لاختيار إعداداته الخاصة.",
- "fr": "Le profil par défaut démarre toujours avec les paramètres globaux du condenseur et de la vérification. Créez un profil nommé pour choisir les siens.",
- "tr": "Varsayılan profil her zaman genel yoğunlaştırıcı ve doğrulama ayarlarıyla başlar. Kendi ayarlarını seçmek için adlandırılmış bir profil oluşturun.",
- "de": "Das Standardprofil startet immer mit den globalen Einstellungen für Kondensator und Verifizierung. Erstellen Sie ein benanntes Profil, um eigene festzulegen.",
- "uk": "Типовий профіль завжди запускається з глобальними налаштуваннями конденсатора та верифікації. Щоб вибрати власні, створіть іменований профіль.",
- "ca": "El perfil predeterminat sempre s’inicia amb la configuració global del condensador i la verificació. Crea un perfil amb nom per triar-ne la seva.",
- "id": "Profil default selalu diluncurkan dengan pengaturan Condenser dan Verifikasi global. Buat profil bernama untuk memilih pengaturannya sendiri."
+ "SETTINGS$AGENT_PROFILE_DEFAULT_SKILLS_NOTE": {
+ "en": "The default profile's skills are the Skills page list. Changing them here changes that page.",
+ "ja": "デフォルトのプロファイルのスキルは、スキルページのリストです。ここで変更するとそのページも変わります。",
+ "zh-CN": "默认配置文件的技能就是技能页面的列表。在此处更改会同时更改该页面。",
+ "zh-TW": "預設設定檔的技能就是技能頁面的清單。在此處變更也會變更該頁面。",
+ "ko-KR": "기본 프로필의 스킬은 스킬 페이지 목록입니다. 여기에서 바꾸면 그 페이지도 바뀝니다.",
+ "no": "Ferdighetene til standardprofilen er listen på Ferdigheter-siden. Endrer du dem her, endres den siden.",
+ "it": "Le competenze del profilo predefinito sono l'elenco della pagina Competenze. Modificarle qui modifica quella pagina.",
+ "pt": "As habilidades do perfil padrão são a lista da página Habilidades. Alterá-las aqui altera essa página.",
+ "es": "Las habilidades del perfil predeterminado son la lista de la página Habilidades. Cambiarlas aquí cambia esa página.",
+ "ar": "مهارات الملف الافتراضي هي قائمة صفحة المهارات. تغييرها هنا يغيّر تلك الصفحة.",
+ "fr": "Les compétences du profil par défaut sont la liste de la page Compétences. Les modifier ici modifie cette page.",
+ "tr": "Varsayılan profilin yetenekleri, Yetenekler sayfasındaki listedir. Burada değiştirmek o sayfayı da değiştirir.",
+ "de": "Die Fähigkeiten des Standardprofils sind die Liste der Seite Fähigkeiten. Änderungen hier ändern diese Seite.",
+ "uk": "Навички типового профілю — це список на сторінці «Навички». Зміни тут змінюють ту сторінку.",
+ "ca": "Les habilitats del perfil per defecte són la llista de la pàgina Habilitats. Canviar-les aquí canvia aquella pàgina.",
+ "id": "Skill profil bawaan adalah daftar di halaman Skill. Mengubahnya di sini juga mengubah halaman itu."
},
"SETTINGS$AGENT_PROFILE_ROUTER_OFF": {
"en": "Off",
@@ -52469,24 +52523,6 @@
"ca": "{{name}} ja no existeix. Desar-lo seleccionat impedirà que aquest agent s'iniciï. Tria un altre encaminador o desactiva'l.",
"id": "{{name}} sudah tidak ada. Menyimpan dengan pilihan ini akan membuat agen gagal dimulai. Pilih router lain atau matikan."
},
- "SETTINGS$AGENT_PROFILE_ROUTER_DEFAULT_PROFILE": {
- "en": "The default profile always launches with the router chosen on the Model Router page. Create a named profile to choose its own.",
- "ja": "デフォルトのプロファイルは常にモデルルーターのページで選んだルーターで起動します。独自に選ぶには、名前付きのプロファイルを作成してください。",
- "zh-CN": "默认配置文件始终使用在“模型路由器”页面中选择的路由器启动。如需单独选择,请创建一个命名配置文件。",
- "zh-TW": "預設設定檔一律以「模型路由器」頁面中選擇的路由器啟動。若要單獨選擇,請建立具名設定檔。",
- "ko-KR": "기본 프로필은 항상 모델 라우터 페이지에서 선택한 라우터로 시작됩니다. 따로 선택하려면 이름이 있는 프로필을 만드세요.",
- "no": "Standardprofilen starter alltid med ruteren som er valgt på siden Modellruter. Opprett en navngitt profil for å velge en egen.",
- "it": "Il profilo predefinito si avvia sempre con il router scelto nella pagina Router dei modelli. Crea un profilo con nome per sceglierne uno proprio.",
- "pt": "O perfil padrão sempre inicia com o roteador escolhido na página Roteador de modelos. Crie um perfil com nome para escolher o seu.",
- "es": "El perfil predeterminado siempre se inicia con el enrutador elegido en la página Enrutador de modelos. Crea un perfil con nombre para elegir el suyo.",
- "ar": "يبدأ الملف الشخصي الافتراضي دائمًا بالموجّه المختار في صفحة موجّه النماذج. أنشئ ملفًا شخصيًا باسم لاختيار موجّهه الخاص.",
- "fr": "Le profil par défaut démarre toujours avec le routeur choisi sur la page Routeur de modèles. Créez un profil nommé pour choisir le sien.",
- "tr": "Varsayılan profil her zaman Model yönlendirici sayfasında seçilen yönlendiriciyle başlar. Kendi yönlendiricisini seçmek için adlandırılmış bir profil oluşturun.",
- "de": "Das Standardprofil startet immer mit dem Router, der auf der Seite Modell-Router ausgewählt ist. Erstellen Sie ein benanntes Profil, um einen eigenen zu wählen.",
- "uk": "Типовий профіль завжди запускається з маршрутизатором, вибраним на сторінці «Маршрутизатор моделей». Щоб вибрати власний, створіть іменований профіль.",
- "ca": "El perfil predeterminat sempre s'inicia amb l'encaminador triat a la pàgina Encaminador de models. Crea un perfil amb nom per triar-ne un de propi.",
- "id": "Profil default selalu diluncurkan dengan router yang dipilih di halaman Model Router. Buat profil bernama untuk memilih router sendiri."
- },
"SETTINGS$AGENT_PROFILE_ROUTER_FIRST": {
"en": "Alphabetically first router",
"ja": "名前順で最初のルーター",
@@ -52504,5 +52540,23 @@
"uk": "Перший маршрутизатор за алфавітом",
"ca": "Primer encaminador per ordre alfabètic",
"id": "Router pertama menurut abjad"
+ },
+ "CONVERSATION$NO_ACTIVE_AGENT_PROFILE": {
+ "en": "No agent profile is active. Choose one in Settings → Agent.",
+ "ja": "有効なエージェントプロファイルがありません。設定 → エージェントで選択してください。",
+ "zh-CN": "没有启用的智能体配置文件。请在“设置 → 智能体”中选择一个。",
+ "zh-TW": "沒有啟用的代理設定檔。請在「設定 → 代理」中選擇一個。",
+ "ko-KR": "활성화된 에이전트 프로필이 없습니다. 설정 → 에이전트에서 선택하세요.",
+ "no": "Ingen agentprofil er aktiv. Velg en under Innstillinger → Agent.",
+ "it": "Nessun profilo agente è attivo. Scegline uno in Impostazioni → Agente.",
+ "pt": "Nenhum perfil de agente está ativo. Escolha um em Configurações → Agente.",
+ "es": "No hay ningún perfil de agente activo. Elige uno en Configuración → Agente.",
+ "ar": "لا يوجد ملف تعريف وكيل نشط. اختر واحدًا من الإعدادات ← الوكيل.",
+ "fr": "Aucun profil d'agent n'est actif. Choisissez-en un dans Paramètres → Agent.",
+ "tr": "Etkin bir ajan profili yok. Ayarlar → Ajan bölümünden birini seçin.",
+ "de": "Kein Agentenprofil ist aktiv. Wählen Sie eines unter Einstellungen → Agent.",
+ "uk": "Немає активного профілю агента. Виберіть його в Налаштування → Агент.",
+ "ca": "No hi ha cap perfil d'agent actiu. Trieu-ne un a Configuració → Agent.",
+ "id": "Tidak ada profil agen yang aktif. Pilih satu di Pengaturan → Agen."
}
}
diff --git a/src/routes/agent-settings.tsx b/src/routes/agent-settings.tsx
index 87b157cbf4..a241adbba8 100644
--- a/src/routes/agent-settings.tsx
+++ b/src/routes/agent-settings.tsx
@@ -54,6 +54,7 @@ import {
import { useAcpModelDiscovery } from "#/hooks/query/use-acp-model-discovery";
import { useActiveBackend } from "#/contexts/active-backend-context";
import { parseCommand, formatCommand } from "#/utils/acp-command";
+import { enabledMcpServerRefs } from "#/hooks/mutation/sync-agent-profiles";
import {
readProfileScope,
sameScopeSelection,
@@ -105,6 +106,7 @@ const TOOL_CONCURRENCY_FIELD_KEY = "tool_concurrency_limit";
// Not valid meta-profile names, so they can't collide with one.
const ROUTER_OFF_KEY = "__off__";
const ROUTER_FIRST_KEY = "__first__";
+const SKILL_SEARCH_MIN_ITEMS = 10;
const MCP_SERVER_REFS_KEY = "mcp_server_refs";
const SECRET_REFS_KEY = "secret_refs";
const TOOLS_KEY = "tools";
@@ -371,14 +373,17 @@ interface AgentSettingsScreenProps {
/** `agent_settings`-shaped profile fields the form opens on. */
agentSettingsOverride?: Record<string, SettingsValue> | null;
onSaveControlChange: (control: AgentSettingsSaveControl) => void;
- /** Local launches route the `default` profile around its stored prompt and tools. */
+ /** `default` shares its MCP servers and skills with the global pages and keeps every secret. */
isDefaultProfile?: boolean;
+ /** Shown under the agent type for an OpenHands agent. */
+ llmPicker?: React.ReactNode;
}
export function AgentSettingsScreen({
agentSettingsOverride = null,
onSaveControlChange,
isDefaultProfile = false,
+ llmPicker = null,
}: AgentSettingsScreenProps) {
const { t } = useTranslation("openhands");
const { data: settings, isLoading } = useSettings();
@@ -420,12 +425,11 @@ export function AgentSettingsScreen({
initialTools.mode === "custom" ? initialTools.selected : null,
);
const toolsSupported = agentProfileSupportsTools();
- const toolsEditable = toolsSupported && !isDefaultProfile;
const {
data: toolCatalog,
isError: toolCatalogFailed,
refetch: refetchToolCatalog,
- } = useToolCatalog({ enabled: toolsEditable });
+ } = useToolCatalog({ enabled: toolsSupported });
// Only a loaded catalog may write `tools`.
const toolCatalogLoaded = toolCatalog !== undefined;
const standardToolNames = React.useMemo(
@@ -465,7 +469,6 @@ export function AgentSettingsScreen({
// --- System prompt (OpenHands path) ---
const instructionsSupported = agentProfileSupportsInstructions();
- const showSystemPrompt = instructionsSupported && !isDefaultProfile;
const initialSystemPrompt = React.useMemo(
() => readSystemPromptSeed(agentSettingsOverride),
[agentSettingsOverride],
@@ -522,18 +525,26 @@ export function AgentSettingsScreen({
[mcpCatalog, selectedMcpServers],
);
// --- Skills (OpenHands; the selection a profile launch loads) ---
- // `default` launches with the Skills page selection instead.
const skillsSupported = agentProfileSupportsSkills();
- const skillsEditable = skillsSupported && !isDefaultProfile;
const {
data: skillCatalog,
isError: skillCatalogFailed,
refetch: refetchSkillCatalog,
- } = useSkillCatalog({ enabled: skillsEditable });
+ } = useSkillCatalog({ enabled: skillsSupported });
const isPublicSkill = React.useMemo(
() => publicSkillTest(skillCatalog),
[skillCatalog],
);
+ const [skillQuery, setSkillQuery] = useState("");
+ const visibleSkills = React.useMemo(() => {
+ const query = skillQuery.trim().toLowerCase();
+ if (!skillCatalog || !query) return skillCatalog;
+ return skillCatalog.filter((skill) =>
+ [skill.name, skill.description ?? "", ...(skill.triggers ?? [])].some(
+ (text) => text.toLowerCase().includes(query),
+ ),
+ );
+ }, [skillCatalog, skillQuery]);
const storedPublicSkills = agentSettingsOverride?.public_skills;
const hasStoredSkillList = Array.isArray(storedPublicSkills);
const initialSkills = React.useMemo<SkillEnablement | undefined>(() => {
@@ -581,7 +592,7 @@ export function AgentSettingsScreen({
[initialSkills, isPublicSkill],
);
// A seeded or stored list is written back; an unset one only once edited.
- const skillsToSave = skillsEditable
+ const skillsToSave = skillsSupported
? (editedSkills ?? (hasStoredSkillList ? initialSkills : undefined))
: undefined;
const skillsDirty =
@@ -774,8 +785,6 @@ export function AgentSettingsScreen({
}, [initialSecretRefs]);
// --- Condenser and verification (OpenHands; stored on the profile) ---
- // A local `default` launches from the global settings, so its own copy would be ignored.
- const behaviorEditable = !isDefaultProfile || backendKind === "cloud";
const [behaviorControls, setBehaviorControls] = useState<
Partial<Record<ProfileBehaviorSection, SdkSectionSaveControl>>
>({});
@@ -852,24 +861,20 @@ export function AgentSettingsScreen({
>,
[storedBehavior],
);
- const behaviorDirty =
- behaviorEditable &&
- Boolean(
- behaviorControls.condenser?.isDirty ||
- behaviorControls.verification?.isDirty,
- );
+ const behaviorDirty = Boolean(
+ behaviorControls.condenser?.isDirty ||
+ behaviorControls.verification?.isDirty,
+ );
const behaviorToSave = (section: ProfileBehaviorSection) => {
const control = behaviorControls[section];
- if (!behaviorEditable || !control) return undefined;
+ if (!control) return undefined;
if (!control.isDirty && storedBehavior[section]) return undefined;
return fromBehaviorFormValues(schema, section, control.values);
};
// --- Model Router (OpenHands; stored on the profile) ---
- // `default` launches with the router chosen on the Model Router page instead.
const routerSupported = agentProfileSupportsRouter();
- const routerEditable = routerSupported && !isDefaultProfile;
const { data: metaProfilesData } = useMetaProfiles({
- enabled: routerEditable,
+ enabled: routerSupported,
});
// On without a name means the server picks the alphabetically first router.
let initialRouter: string | null = null;
@@ -923,19 +928,19 @@ export function AgentSettingsScreen({
const secretScopeDirty =
secretsMode !== initialSecretRefs.mode ||
!sameScopeSelection(orderedSelectedSecrets, initialSecretRefs.selected);
- const routerDirty = routerEditable && router !== initialRouter;
+ const routerDirty = routerSupported && router !== initialRouter;
const toolSelectionDirty =
toolsMode !== initialTools.mode ||
(toolsMode === "custom" &&
!sameScopeSelection(orderedSelectedTools, initialTools.selected));
const systemPromptDirty =
- showSystemPrompt &&
+ instructionsSupported &&
(systemPromptMode !== initialSystemPrompt.mode ||
(systemPromptMode !== "standard" &&
systemPromptText !== initialSystemPrompt.text));
const systemPromptMissing =
agentType === "openhands" &&
- showSystemPrompt &&
+ instructionsSupported &&
systemPromptMode !== "standard" &&
!systemPromptText.trim();
const settingsDirty =
@@ -987,6 +992,20 @@ export function AgentSettingsScreen({
]);
const isAcp = agentType === "acp";
+ // An OpenHands `default` shares its MCP servers, secrets and skills with the global pages.
+ const sharesGlobalPages = isDefaultProfile && !isAcp;
+ // Switching `default`'s agent type moves its MCP servers onto or off the
+ // MCP page's switches.
+ const sharedRef = React.useRef(sharesGlobalPages);
+ React.useEffect(() => {
+ if (sharedRef.current === sharesGlobalPages) return;
+ sharedRef.current = sharesGlobalPages;
+ const scope = sharesGlobalPages
+ ? readProfileScope(enabledMcpServerRefs(settings))
+ : initialMcpRefs;
+ setMcpMode(scope.mode);
+ setSelectedMcpServers(scope.selected);
+ }, [sharesGlobalPages, settings, initialMcpRefs]);
const commandTokens = parseCommand(commandText);
const selectedPreset = detectPreset(commandText, acpProviders);
const selectedProvider = getAcpProvider(selectedPreset);
@@ -1073,7 +1092,7 @@ export function AgentSettingsScreen({
router: routerDirty ? router : undefined,
systemPromptMode,
systemPromptText,
- systemPromptEditable: showSystemPrompt,
+ systemPromptEditable: instructionsSupported,
condenser: behaviorToSave("condenser"),
verification: behaviorToSave("verification"),
});
@@ -1121,95 +1140,80 @@ export function AgentSettingsScreen({
}}
/>
+ {isAcp ? null : llmPicker}
+
{!isAcp && instructionsSupported ? (
<div className="flex flex-col gap-2.5">
<Typography.Text className="text-sm">
{t(I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT)}
</Typography.Text>
- {isDefaultProfile ? (
+ <SettingsDropdownInput
+ testId="agent-settings-system-prompt-mode"
+ name="agent-system-prompt-mode"
+ label=""
+ items={[
+ {
+ key: "standard",
+ label: t(I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_STANDARD),
+ },
+ {
+ key: "append",
+ label: t(I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_APPEND),
+ },
+ {
+ key: "custom",
+ label: t(I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_CUSTOM),
+ },
+ ]}
+ selectedKey={systemPromptMode}
+ isDisabled={isSaving}
+ onSelectionChange={(key) => {
+ if (key) setSystemPromptMode(key as SystemPromptMode);
+ }}
+ />
+ {systemPromptMode !== "standard" ? (
+ <textarea
+ data-testid="agent-settings-system-prompt"
+ aria-label={t(I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT)}
+ className={cn(
+ formControlMultilineFieldClassName,
+ "min-h-48 font-mono placeholder:italic",
+ "disabled:bg-surface-raised disabled:border-border-subtle",
+ )}
+ value={systemPromptText}
+ maxLength={SYSTEM_PROMPT_MAX_LENGTH}
+ placeholder={t(
+ systemPromptMode === "custom"
+ ? I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_PLACEHOLDER
+ : I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_APPEND_PLACEHOLDER,
+ )}
+ disabled={isSaving}
+ onChange={(e) => setSystemPromptText(e.target.value)}
+ />
+ ) : null}
+ {systemPromptMissing ? (
<Typography.Text
- testId="agent-settings-system-prompt-default-profile"
- className="text-xs text-tertiary-alt"
+ testId="agent-settings-system-prompt-required"
+ className="text-xs text-danger"
>
- {t(I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_DEFAULT_PROFILE)}
+ {t(I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_REQUIRED)}
</Typography.Text>
- ) : (
- <>
- <SettingsDropdownInput
- testId="agent-settings-system-prompt-mode"
- name="agent-system-prompt-mode"
- label=""
- items={[
- {
- key: "standard",
- label: t(
- I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_STANDARD,
- ),
- },
- {
- key: "append",
- label: t(
- I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_APPEND,
- ),
- },
- {
- key: "custom",
- label: t(
- I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_CUSTOM,
- ),
- },
- ]}
- selectedKey={systemPromptMode}
- isDisabled={isSaving}
- onSelectionChange={(key) => {
- if (key) setSystemPromptMode(key as SystemPromptMode);
- }}
- />
- {systemPromptMode !== "standard" ? (
- <textarea
- data-testid="agent-settings-system-prompt"
- aria-label={t(I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT)}
- className={cn(
- formControlMultilineFieldClassName,
- "min-h-48 font-mono placeholder:italic",
- "disabled:bg-surface-raised disabled:border-border-subtle",
- )}
- value={systemPromptText}
- maxLength={SYSTEM_PROMPT_MAX_LENGTH}
- placeholder={t(
- systemPromptMode === "custom"
- ? I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_PLACEHOLDER
- : I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_APPEND_PLACEHOLDER,
- )}
- disabled={isSaving}
- onChange={(e) => setSystemPromptText(e.target.value)}
- />
- ) : null}
- {systemPromptMissing ? (
- <Typography.Text
- testId="agent-settings-system-prompt-required"
- className="text-xs text-danger"
- >
- {t(I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_REQUIRED)}
- </Typography.Text>
- ) : null}
- <Typography.Text
- testId="agent-settings-system-prompt-hint"
- className="text-xs text-tertiary-alt"
- >
- {t(
- {
- standard:
- I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_STANDARD_HINT,
- append:
- I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_APPEND_HINT,
- custom:
- I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_CUSTOM_HINT,
- }[systemPromptMode],
- )}
- </Typography.Text>
- </>
- )}
+ ) : null}
+ <Typography.Text
+ testId="agent-settings-system-prompt-hint"
+ className="text-xs text-tertiary-alt"
+ >
+ {t(
+ {
+ standard:
+ I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_STANDARD_HINT,
+ append:
+ I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_APPEND_HINT,
+ custom:
+ I18nKey.SETTINGS$AGENT_PROFILE_SYSTEM_PROMPT_CUSTOM_HINT,
+ }[systemPromptMode],
+ )}
+ </Typography.Text>
</div>
) : null}
@@ -1221,59 +1225,48 @@ export function AgentSettingsScreen({
<Typography.Text className="text-sm">
{t(I18nKey.SETTINGS$NAV_META_LLM)}
</Typography.Text>
- {routerEditable ? (
- <>
- <SettingsDropdownInput
- testId="agent-settings-router-select"
- name="agent-router"
- label=""
- items={[
- {
- key: ROUTER_OFF_KEY,
- label: t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_OFF),
- },
- ...(initialRouter === ROUTER_FIRST_KEY
- ? [
- {
- key: ROUTER_FIRST_KEY,
- label: t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_FIRST),
- },
- ]
- : []),
- ...[
- ...routerNames,
- ...(routerDangling && router ? [router] : []),
- ].map((name) => ({ key: name, label: name })),
- ]}
- selectedKey={router ?? ROUTER_OFF_KEY}
- isDisabled={isSaving}
- onSelectionChange={(key) => {
- if (key === null || key === undefined) return;
- setRouter(key === ROUTER_OFF_KEY ? null : String(key));
- }}
- />
- {routerDangling ? (
- <Typography.Text
- testId="agent-settings-router-dangling"
- className="text-xs text-danger"
- >
- {t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_DANGLING, {
- name: router,
- })}
- </Typography.Text>
- ) : null}
- <Typography.Text className="text-xs text-tertiary-alt">
- {t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_HINT)}
- </Typography.Text>
- </>
- ) : (
+ <SettingsDropdownInput
+ testId="agent-settings-router-select"
+ name="agent-router"
+ label=""
+ items={[
+ {
+ key: ROUTER_OFF_KEY,
+ label: t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_OFF),
+ },
+ ...(initialRouter === ROUTER_FIRST_KEY
+ ? [
+ {
+ key: ROUTER_FIRST_KEY,
+ label: t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_FIRST),
+ },
+ ]
+ : []),
+ ...[
+ ...routerNames,
+ ...(routerDangling && router ? [router] : []),
+ ].map((name) => ({ key: name, label: name })),
+ ]}
+ selectedKey={router ?? ROUTER_OFF_KEY}
+ isDisabled={isSaving}
+ onSelectionChange={(key) => {
+ if (key === null || key === undefined) return;
+ setRouter(key === ROUTER_OFF_KEY ? null : String(key));
+ }}
+ />
+ {routerDangling ? (
<Typography.Text
- testId="agent-settings-router-default-profile"
- className="text-xs text-tertiary-alt"
+ testId="agent-settings-router-dangling"
+ className="text-xs text-danger"
>
- {t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_DEFAULT_PROFILE)}
+ {t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_DANGLING, {
+ name: router,
+ })}
</Typography.Text>
- )}
+ ) : null}
+ <Typography.Text className="text-xs text-tertiary-alt">
+ {t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_HINT)}
+ </Typography.Text>
</div>
) : null}
{!isAcp && toolConcurrencyField ? (
@@ -1284,20 +1277,7 @@ export function AgentSettingsScreen({
onChange={setToolConcurrency}
/>
) : null}
- {!isAcp && toolsSupported && isDefaultProfile ? (
- <div className="flex flex-col gap-2.5">
- <Typography.Text className="text-sm">
- {t(I18nKey.SETTINGS$AGENT_PROFILE_TOOLS)}
- </Typography.Text>
- <Typography.Text
- testId="agent-settings-tools-default-profile"
- className="text-xs text-tertiary-alt"
- >
- {t(I18nKey.SETTINGS$AGENT_PROFILE_TOOLS_DEFAULT_PROFILE)}
- </Typography.Text>
- </div>
- ) : null}
- {!isAcp && toolsEditable ? (
+ {!isAcp && toolsSupported ? (
<div className="flex flex-col gap-2.5">
<Typography.Text className="text-sm">
{t(I18nKey.SETTINGS$AGENT_PROFILE_TOOLS)}
@@ -1442,11 +1422,18 @@ export function AgentSettingsScreen({
})}
</Typography.Text>
) : null}
- <Typography.Text className="text-xs text-tertiary-alt">
+ <Typography.Text
+ testId={
+ sharesGlobalPages ? "agent-settings-mcp-default-note" : undefined
+ }
+ className="text-xs text-tertiary-alt"
+ >
{t(
- mcpMode === "custom"
- ? I18nKey.SETTINGS$AGENT_PROFILE_MCP_CHOOSE_HINT
- : I18nKey.SETTINGS$AGENT_PROFILE_MCP_ALL_HINT,
+ sharesGlobalPages
+ ? I18nKey.SETTINGS$AGENT_PROFILE_DEFAULT_MCP_NOTE
+ : mcpMode === "custom"
+ ? I18nKey.SETTINGS$AGENT_PROFILE_MCP_CHOOSE_HINT
+ : I18nKey.SETTINGS$AGENT_PROFILE_MCP_ALL_HINT,
)}
</Typography.Text>
</div>
@@ -1461,36 +1448,41 @@ export function AgentSettingsScreen({
<Typography.Text className="text-sm">
{t(titleKey)}
</Typography.Text>
- {behaviorEditable ? (
- <SdkSectionPage
- settingsSources={[
- {
- settingsSource: "agent_settings",
- sectionKeys: [section],
- excludeKeys: GLOBAL_BEHAVIOR_FIELD_KEYS,
- },
- ]}
- embedded
- hideSaveButton
- markInitialOverridesDirty={false}
- initialValueOverrides={behaviorInitialValues[section]}
- getInitialView={behaviorInitialView[section]}
- onSaveControlChange={behaviorControlHandlers[section]}
- testId={`agent-settings-${section}-fields`}
- />
- ) : (
- <Typography.Text
- testId={`agent-settings-${section}-default-profile`}
- className="text-xs text-tertiary-alt"
- >
- {t(I18nKey.SETTINGS$AGENT_PROFILE_BEHAVIOR_DEFAULT_PROFILE)}
- </Typography.Text>
- )}
+ <SdkSectionPage
+ settingsSources={[
+ {
+ settingsSource: "agent_settings",
+ sectionKeys: [section],
+ excludeKeys: GLOBAL_BEHAVIOR_FIELD_KEYS,
+ },
+ ]}
+ embedded
+ hideSaveButton
+ markInitialOverridesDirty={false}
+ initialValueOverrides={behaviorInitialValues[section]}
+ getInitialView={behaviorInitialView[section]}
+ onSaveControlChange={behaviorControlHandlers[section]}
+ testId={`agent-settings-${section}-fields`}
+ />
</div>
))
: null}
- {secretRefsSupportedOnProfile ? (
+ {secretRefsSupportedOnProfile && sharesGlobalPages ? (
+ <div className="flex flex-col gap-2.5">
+ <Typography.Text className="text-sm">
+ {t(I18nKey.SETTINGS$AGENT_PROFILE_SECRETS)}
+ </Typography.Text>
+ <Typography.Text
+ testId="agent-settings-secrets-default-note"
+ className="text-xs text-tertiary-alt"
+ >
+ {t(I18nKey.SETTINGS$AGENT_PROFILE_DEFAULT_SECRETS_NOTE)}
+ </Typography.Text>
+ </div>
+ ) : null}
+
+ {secretRefsSupportedOnProfile && !sharesGlobalPages ? (
<div className="flex flex-col gap-2.5">
<Typography.Text className="text-sm">
{t(I18nKey.SETTINGS$AGENT_PROFILE_SECRETS)}
@@ -1560,56 +1552,67 @@ export function AgentSettingsScreen({
<Typography.Text className="text-sm">
{t(I18nKey.SETTINGS$AGENT_PROFILE_SKILLS)}
</Typography.Text>
- {!skillsEditable ? (
- <Typography.Text
- testId="agent-settings-skills-default-profile"
- className="text-xs text-tertiary-alt"
+ {skillCatalog && skillCatalog.length > SKILL_SEARCH_MIN_ITEMS ? (
+ <SettingsInput
+ testId="agent-settings-skills-search"
+ label=""
+ type="search"
+ className="w-full"
+ value={skillQuery}
+ placeholder={t(I18nKey.SETTINGS$SKILLS_SEARCH_PLACEHOLDER)}
+ onChange={setSkillQuery}
+ />
+ ) : null}
+ {visibleSkills && currentSkills ? (
+ <div className="max-h-80 overflow-y-auto pr-1">
+ <ProfileScopeList
+ testId="agent-settings-skills"
+ items={visibleSkills.map((skill) => ({
+ name: skill.name,
+ description: t(
+ skill.origin === "public"
+ ? I18nKey.SETTINGS$SKILL_ORIGIN_PUBLIC
+ : I18nKey.SETTINGS$SKILL_ORIGIN_USER,
+ ),
+ }))}
+ selected={enabledSkillNames}
+ isDisabled={isSaving}
+ onToggle={toggleProfileSkill}
+ />
+ </div>
+ ) : null}
+ {skillCatalogFailed ? (
+ <div
+ className="flex items-center gap-2"
+ data-testid="agent-settings-skills-load-failed"
>
- {t(I18nKey.SETTINGS$AGENT_PROFILE_SKILLS_DEFAULT_PROFILE)}
- </Typography.Text>
- ) : (
- <>
- {skillCatalog && currentSkills ? (
- <div className="max-h-80 overflow-y-auto pr-1">
- <ProfileScopeList
- testId="agent-settings-skills"
- items={skillCatalog.map((skill) => ({
- name: skill.name,
- description: t(
- skill.origin === "public"
- ? I18nKey.SETTINGS$SKILL_ORIGIN_PUBLIC
- : I18nKey.SETTINGS$SKILL_ORIGIN_USER,
- ),
- }))}
- selected={enabledSkillNames}
- isDisabled={isSaving}
- onToggle={toggleProfileSkill}
- />
- </div>
- ) : null}
- {skillCatalogFailed ? (
- <div
- className="flex items-center gap-2"
- data-testid="agent-settings-skills-load-failed"
- >
- <Typography.Text className="text-xs text-feedback-error">
- {t(I18nKey.SETTINGS$AGENT_PROFILE_SKILLS_LOAD_FAILED)}
- </Typography.Text>
- <BrandButton
- testId="agent-settings-skills-retry"
- type="button"
- variant="secondary"
- onClick={() => refetchSkillCatalog()}
- >
- {t(I18nKey.SETTINGS$AGENT_PROFILE_TOOLS_RETRY)}
- </BrandButton>
- </div>
- ) : null}
- <Typography.Text className="text-xs text-tertiary-alt">
- {t(I18nKey.SETTINGS$AGENT_PROFILE_SKILLS_HINT)}
+ <Typography.Text className="text-xs text-feedback-error">
+ {t(I18nKey.SETTINGS$AGENT_PROFILE_SKILLS_LOAD_FAILED)}
</Typography.Text>
- </>
- )}
+ <BrandButton
+ testId="agent-settings-skills-retry"
+ type="button"
+ variant="secondary"
+ onClick={() => refetchSkillCatalog()}
+ >
+ {t(I18nKey.SETTINGS$AGENT_PROFILE_TOOLS_RETRY)}
+ </BrandButton>
+ </div>
+ ) : null}
+ <Typography.Text
+ testId={
+ sharesGlobalPages
+ ? "agent-settings-skills-default-note"
+ : undefined
+ }
+ className="text-xs text-tertiary-alt"
+ >
+ {t(
+ sharesGlobalPages
+ ? I18nKey.SETTINGS$AGENT_PROFILE_DEFAULT_SKILLS_NOTE
+ : I18nKey.SETTINGS$AGENT_PROFILE_SKILLS_HINT,
+ )}
+ </Typography.Text>
</div>
) : null}
diff --git a/src/routes/condenser-settings.tsx b/src/routes/condenser-settings.tsx
index b81d52d862..3c80712d24 100644
--- a/src/routes/condenser-settings.tsx
+++ b/src/routes/condenser-settings.tsx
@@ -1,6 +1,13 @@
+import { Navigate } from "react-router";
import { SdkSectionPage } from "#/components/features/settings/sdk-settings/sdk-section-page";
+import { useActiveBackend } from "#/contexts/active-backend-context";
function CondenserSettingsScreen() {
+ const { backend } = useActiveBackend();
+ // Locally each agent profile has its own condenser.
+ if (backend.kind !== "cloud") {
+ return <Navigate to="/settings/agents" replace />;
+ }
return (
<SdkSectionPage
settingsSources={[
diff --git a/src/routes/root-layout.tsx b/src/routes/root-layout.tsx
index cb1470face..0e1228a3b0 100644
--- a/src/routes/root-layout.tsx
+++ b/src/routes/root-layout.tsx
@@ -14,6 +14,7 @@ import { SidebarMobileNavProvider } from "#/components/features/sidebar/sidebar-
import { SidebarMobileMenuBar } from "#/components/features/sidebar/sidebar-mobile-menu-bar";
import { useSettings } from "#/hooks/query/use-settings";
import { useEnsureActiveProfile } from "#/hooks/use-ensure-active-profile";
+import { useMigrateDefaultAgentProfile } from "#/hooks/use-migrate-default-agent-profile";
import { useMigrateEnabledSkills } from "#/hooks/use-migrate-enabled-skills";
import { useSyncTelemetryConsent } from "#/hooks/use-sync-telemetry-consent";
import { useSyncAutomationTelemetryConsent } from "#/hooks/use-sync-automation-telemetry-consent";
@@ -136,6 +137,8 @@ function MainAppContent() {
useEnsureActiveProfile();
// One-shot move from the catalog deny-list to an explicit allow-list.
useMigrateEnabledSkills();
+ // One-shot move of global agent behavior into the `default` profile.
+ useMigrateDefaultAgentProfile();
React.useEffect(() => {
if (settings?.language) {
diff --git a/src/routes/skills-settings.tsx b/src/routes/skills-settings.tsx
index f4c578ff78..dccc499fea 100644
--- a/src/routes/skills-settings.tsx
+++ b/src/routes/skills-settings.tsx
@@ -24,7 +24,9 @@ import {
type SkillFilterState,
} from "#/components/features/skills/skill-filter";
import { SkillsToolbar } from "#/components/features/skills/skills-toolbar";
+import { useActiveBackend } from "#/contexts/active-backend-context";
import { useSettings } from "#/hooks/query/use-settings";
+import { useSkillCatalog } from "#/hooks/query/use-skill-catalog";
import { useSkills } from "#/hooks/query/use-skills";
import { useSkillEnablement } from "#/hooks/use-skill-enablement";
import { I18nKey } from "#/i18n/declaration";
@@ -42,9 +44,16 @@ const SEARCH_URL_SYNC_DELAY_MS = 300;
function SkillsSettingsScreen() {
const { t } = useTranslation("openhands");
+ const { backend } = useActiveBackend();
+ const isCloud = backend.kind === "cloud";
const { data: settings, isLoading: settingsLoading } = useSettings();
- const { data: skills, isLoading: skillsLoading } = useSkills();
- const { isEnabled, setEnabled } = useSkillEnablement();
+ // Locally the page lists what agent profiles can select; Cloud lists its own skills.
+ const catalog = useSkillCatalog();
+ const cloudSkills = useSkills(undefined, { enabled: isCloud });
+ const { data: skills, isLoading: skillsLoading } = isCloud
+ ? cloudSkills
+ : catalog;
+ const { isEnabled, setEnabled, isUnavailable } = useSkillEnablement();
const [searchParams, setSearchParams] = useSearchParams();
const [queryInput, setQueryInput] = React.useState(
@@ -150,12 +159,21 @@ function SkillsSettingsScreen() {
>
{t(I18nKey.SETTINGS$SKILLS_PAGE_DESCRIPTION)}
</div>
- <div
- data-testid="skills-new-conversation-notice"
- className="max-w-2xl text-xs text-tertiary-alt"
- >
- {t(I18nKey.SETTINGS$SKILLS_NEW_CONVERSATION_NOTICE)}
- </div>
+ {isCloud ? (
+ <div
+ data-testid="skills-new-conversation-notice"
+ className="max-w-2xl text-xs text-tertiary-alt"
+ >
+ {t(I18nKey.SETTINGS$SKILLS_NEW_CONVERSATION_NOTICE)}
+ </div>
+ ) : (
+ <div
+ data-testid="skills-default-list-notice"
+ className="max-w-2xl text-xs text-tertiary-alt"
+ >
+ {t(I18nKey.SETTINGS$SKILLS_DEFAULT_LIST_NOTICE)}
+ </div>
+ )}
</div>
<BrandButton
type="button"
@@ -250,6 +268,7 @@ function SkillsSettingsScreen() {
onToggle={(enabled) =>
setEnabled(skill.name, enabled)
}
+ isToggleDisabled={isUnavailable}
/>
))}
</div>
@@ -277,6 +296,7 @@ function SkillsSettingsScreen() {
enabled={isEnabled(selectedSkill)}
onToggle={(enabled) => setEnabled(selectedSkill.name, enabled)}
onClose={() => setSelectedSkill(null)}
+ isToggleDisabled={isUnavailable}
/>
)}
diff --git a/src/routes/verification-settings.tsx b/src/routes/verification-settings.tsx
index 996f270043..5c9095d535 100644
--- a/src/routes/verification-settings.tsx
+++ b/src/routes/verification-settings.tsx
@@ -1,4 +1,12 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { Typography } from "#/ui/typography";
+import { I18nKey } from "#/i18n/declaration";
import { SdkSectionPage } from "#/components/features/settings/sdk-settings/sdk-section-page";
+import { profileBehaviorFieldKeys } from "#/components/features/settings/agent-profiles/profile-behavior-form";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { useAgentSettingsSchema } from "#/hooks/query/use-agent-settings-schema";
+import { useSettings } from "#/hooks/query/use-settings";
import { SettingsScope } from "#/types/settings";
// Defensive de-dup: agent_settings.verification still carries
@@ -11,6 +19,9 @@ const CONVERSATION_OWNED_AGENT_VERIFICATION_FIELD_KEYS = new Set([
"verification.security_analyzer",
]);
+// The critic API key depends on `critic_enabled`, which each profile sets.
+const SHOW_CRITIC_API_KEY = { "verification.critic_enabled": true };
+
export function VerificationSettingsScreen({
scope = "personal",
renderTopContent,
@@ -40,4 +51,59 @@ export function VerificationSettingsScreen({
);
}
-export default VerificationSettingsScreen;
+/** Locally each agent profile owns the critic's behavior; its API key stays here. */
+function GlobalVerificationSettingsScreen() {
+ const { t } = useTranslation("openhands");
+ const { data: settings } = useSettings();
+ const { data: schema } = useAgentSettingsSchema(
+ settings?.agent_settings_schema,
+ );
+ const settingsSources = React.useMemo(
+ () =>
+ schema
+ ? [
+ {
+ settingsSource: "agent_settings" as const,
+ sectionKeys: ["verification"],
+ excludeKeys: new Set([
+ ...CONVERSATION_OWNED_AGENT_VERIFICATION_FIELD_KEYS,
+ ...profileBehaviorFieldKeys(schema, "verification"),
+ ]),
+ },
+ {
+ settingsSource: "conversation_settings" as const,
+ sectionKeys: ["verification"],
+ },
+ ]
+ : null,
+ [schema],
+ );
+ if (!settingsSources) return null;
+ return (
+ <div className="flex flex-col gap-4">
+ <Typography.Text
+ testId="verification-critic-per-profile-note"
+ className="text-xs text-tertiary-alt"
+ >
+ {t(I18nKey.SETTINGS$VERIFICATION_CRITIC_PER_PROFILE)}
+ </Typography.Text>
+ <SdkSectionPage
+ settingsSources={settingsSources}
+ initialValueOverrides={SHOW_CRITIC_API_KEY}
+ markInitialOverridesDirty={false}
+ testId="verification-settings-screen"
+ />
+ </div>
+ );
+}
+
+function VerificationSettingsRoute() {
+ const { backend } = useActiveBackend();
+ return backend.kind === "cloud" ? (
+ <VerificationSettingsScreen />
+ ) : (
+ <GlobalVerificationSettingsScreen />
+ );
+}
+
+export default VerificationSettingsRoute;
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 419626d126..8f7e75c3dd 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -155,6 +155,8 @@ export type Settings = {
* it is deliberately absent from `DEFAULT_SETTINGS`.
*/
enabled_skills?: string[];
+ /** Global agent behavior has been copied into the `default` agent profile. */
+ default_profile_migrated?: boolean;
max_budget_per_task: number | null;
email?: string;
email_verified?: boolean;
diff --git a/tests/e2e/mock-llm/settings/mock-llm-profile-management.spec.ts b/tests/e2e/mock-llm/settings/mock-llm-profile-management.spec.ts
index 2679318ef9..e31a1a52c8 100644
--- a/tests/e2e/mock-llm/settings/mock-llm-profile-management.spec.ts
+++ b/tests/e2e/mock-llm/settings/mock-llm-profile-management.spec.ts
@@ -192,8 +192,11 @@ test.describe("active profile deletion + reconciliation", () => {
await waitForTestId(page, "profile-actions-menu");
await page.getByTestId("profile-delete").click();
- // Confirm in the delete modal.
- await page.getByTestId("delete-profile-confirm").click();
+ // Confirm in the delete modal, and let the delete finish: it first moves
+ // the `default` agent profile off this LLM profile.
+ const confirm = page.getByTestId("delete-profile-confirm");
+ await confirm.click();
+ await expect(confirm).toBeHidden({ timeout: 30_000 });
// useEnsureActiveProfile re-activates the only remaining profile. Poll
// with reload — the delete + activate mutations may take a moment on CI.