🙌 OpenHands: AI-Driven Development
feat(agent-profiles): select secrets available to a profile (#17237)
simonrosenberg32cfcb2e053d
diff --git a/__tests__/api/agent-profiles-service/profile-field-support.test.ts b/__tests__/api/agent-profiles-service/profile-field-support.test.tsindex d2635197ab..10c6d86d32 100644--- a/__tests__/api/agent-profiles-service/profile-field-support.test.ts+++ b/__tests__/api/agent-profiles-service/profile-field-support.test.ts@@ -1,10 +1,17 @@import { beforeEach, describe, expect, it, vi } from "vitest";import {MIN_AGENT_SERVER_VERSION_FOR_PROFILE_SWITCH_LLM_TOOL,+ agentProfileSupportsSecretRefs,agentProfileSupportsSwitchLlmTool,} from "#/api/agent-profiles-service/profile-field-support";const mockGetCachedAgentServerVersion = vi.fn<() => string | null>();+const mockServerInfo = vi.fn<() => { capabilities?: string[] } | null>();+const mockBackendKind = vi.fn<() => string>(() => "local");++vi.mock("#/api/backend-registry/active-store", () => ({+ getActiveBackend: () => ({ backend: { kind: mockBackendKind() } }),+}));// Only the version *lookup* is mocked — the comparison stays the real one so// these cases exercise the same parser the boot-time compatibility check uses.@@ -14,6 +21,7 @@ vi.mock("#/api/agent-server-compatibility", async (importOriginal) => {return {...actual,getCachedAgentServerVersion: () => mockGetCachedAgentServerVersion(),+ getCachedAgentServerInfo: () => mockServerInfo(),};});@@ -57,3 +65,32 @@ describe("agentProfileSupportsSwitchLlmTool", () => {expect(agentProfileSupportsSwitchLlmTool()).toBe(true);});});++describe("agentProfileSupportsSecretRefs", () => {+ beforeEach(() => {+ mockBackendKind.mockReturnValue("local");+ });++ it.each([null, {}, { capabilities: [] }])(+ "hides an unadvertised scope: %j",+ (info) => {+ mockServerInfo.mockReturnValue(info);+ expect(agentProfileSupportsSecretRefs()).toBe(false);+ },+ );++ it("accepts enforcement advertised by a local development build", () => {+ mockServerInfo.mockReturnValue({+ capabilities: ["profile_secret_scope_v1"],+ });+ expect(agentProfileSupportsSecretRefs()).toBe(true);+ });++ it("does not promise enforcement through the Cloud profile launch path", () => {+ mockBackendKind.mockReturnValue("cloud");+ mockServerInfo.mockReturnValue({+ capabilities: ["profile_secret_scope_v1"],+ });+ expect(agentProfileSupportsSecretRefs()).toBe(false);+ });+});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.tsxindex d62f489027..1e281053ca 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@@ -10,6 +10,8 @@ import { displayErrorToast } from "#/utils/custom-toast-handlers";// 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";+const EDIT_PROFILE_LABEL = "edit";vi.mock("react-i18next", () => ({useTranslation: () => ({ t: (key: string) => key }),@@ -60,13 +62,13 @@ vi.mock(type="button"data-testid="add-agent-profile"onClick={onAddProfile}- aria-label="add"+ aria-label={ADD_PROFILE_LABEL}/><buttontype="button"data-testid="edit-agent-profile"onClick={() => onEditProfile?.({ name: "default" })}- aria-label="edit"+ aria-label={EDIT_PROFILE_LABEL}/></>),@@ -250,6 +252,7 @@ describe("AgentProfilesLocalView save mapping", () => {// Without this the picker opens on "all servers" and the save widens the// profile's scope back to every configured server.mcp_server_refs: ["github"],+ secret_refs: null,});await user.click(screen.getByTestId("save-agent-profile-btn"));@@ -279,6 +282,83 @@ describe("AgentProfilesLocalView save mapping", () => {expect(profile).not.toHaveProperty("revision");});+ it("seeds the editor with a stored secret scope", async () => {+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({+ name: "default",+ profile: {+ schema_version: 2,+ id: "p-1",+ name: "default",+ revision: 3,+ agent_kind: "openhands",+ llm_profile_ref: "default",+ enable_sub_agents: false,+ secret_refs: ["DATADOG_API_KEY"],+ },+ } as never);+ emitControl = {+ agentType: "openhands",+ isValid: true,+ isDirty: true,+ buildAgentProfileFields: () => ({+ agent_kind: "openhands",+ mcp_server_refs: null,+ enable_sub_agents: false,+ }),+ credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },+ };++ render(<AgentProfilesLocalView />);+ const user = userEvent.setup();+ await user.click(screen.getByTestId("edit-agent-profile"));+ await screen.findByTestId("mock-agent-settings");++ const seededOverride = JSON.parse(+ screen+ .getByTestId("mock-agent-settings")+ .getAttribute("data-override") as string,+ );+ expect(seededOverride.secret_refs).toEqual(["DATADOG_API_KEY"]);+ });++ it("edit-save persists an edited secret scope over the stored value", async () => {+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({+ name: "default",+ profile: {+ schema_version: 2,+ id: "p-1",+ name: "default",+ revision: 3,+ agent_kind: "openhands",+ llm_profile_ref: "default",+ enable_sub_agents: false,+ secret_refs: null,+ },+ } as never);+ emitControl = {+ agentType: "openhands",+ isValid: true,+ isDirty: true,+ buildAgentProfileFields: () => ({+ agent_kind: "openhands",+ mcp_server_refs: null,+ enable_sub_agents: false,+ secret_refs: ["DATADOG_API_KEY"],+ }),+ credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },+ };++ render(<AgentProfilesLocalView />);+ 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));+ const { profile } = saveMutate.mock.calls[0][0];+ expect(profile.secret_refs).toEqual(["DATADOG_API_KEY"]);+ });+it("edit-save persists an edited enable_switch_llm_tool over the stored value", async () => {// The stored profile has the tool disabled; the embedded form's builder// emits the edited value, which must win over the stored one in thediff --git a/__tests__/constants/profile-scope.test.ts b/__tests__/constants/profile-scope.test.tsindex 3741990c12..e373955fc0 100644--- a/__tests__/constants/profile-scope.test.ts+++ b/__tests__/constants/profile-scope.test.ts@@ -1,34 +1,34 @@import { describe, expect, it } from "vitest";import {- readProfileMcpRefs,+ readProfileScope,sameScopeSelection,} from "#/constants/profile-scope";-describe("readProfileMcpRefs", () => {+describe("readProfileScope", () => {it("reads an absent field as the server default", () => {- expect(readProfileMcpRefs(undefined)).toEqual({+ expect(readProfileScope(undefined)).toEqual({mode: "standard",selected: [],});- expect(readProfileMcpRefs(null)).toEqual({+ expect(readProfileScope(null)).toEqual({mode: "standard",selected: [],});});it("reads an empty array as an explicit no-servers scope", () => {- expect(readProfileMcpRefs([])).toEqual({ mode: "custom", selected: [] });+ expect(readProfileScope([])).toEqual({ mode: "custom", selected: [] });});it("reads a list as the selection", () => {- expect(readProfileMcpRefs(["github", "postgres"])).toEqual({+ expect(readProfileScope(["github", "postgres"])).toEqual({mode: "custom",selected: ["github", "postgres"],});});it("drops non-string entries rather than failing the editor", () => {- expect(readProfileMcpRefs(["github", 7, null])).toEqual({+ expect(readProfileScope(["github", 7, null])).toEqual({mode: "custom",selected: ["github"],});diff --git a/__tests__/hooks/mutation/use-create-conversation.test.tsx b/__tests__/hooks/mutation/use-create-conversation.test.tsxindex 4f0c13333a..6159e71f49 100644--- a/__tests__/hooks/mutation/use-create-conversation.test.tsx+++ b/__tests__/hooks/mutation/use-create-conversation.test.tsx@@ -8,6 +8,7 @@ import {getStoredConversationMetadata,removeStoredConversationMetadata,} from "#/api/conversation-metadata-store";+import { AGENT_PROFILES_QUERY_KEYS } from "#/hooks/query/query-keys";vi.mock("#/hooks/use-tracking", () => ({useTracking: () => ({@@ -53,18 +54,26 @@ 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.-const { listAgentProfilesMock } = vi.hoisted(() => ({+const { listAgentProfilesMock, getAgentProfileMock } = vi.hoisted(() => ({listAgentProfilesMock: vi.fn(),+ getAgentProfileMock: vi.fn(),}));vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({__esModule: true,- default: { listProfiles: listAgentProfilesMock },+ default: {+ listProfiles: listAgentProfilesMock,+ getProfile: getAgentProfileMock,+ },WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME: "default",}));listAgentProfilesMock.mockResolvedValue({profiles: [],active_agent_profile_id: null,});+getAgentProfileMock.mockResolvedValue({+ name: "default",+ profile: { secret_refs: null },+});// LLM-profile service: real listProfiles calls (the llmProfileExists// validation — see use-create-conversation.ts) so it can be asserted per-test.@@ -90,6 +99,11 @@ describe("useCreateConversation", () => {profiles: [],active_agent_profile_id: null,});+ getAgentProfileMock.mockReset();+ getAgentProfileMock.mockResolvedValue({+ name: "default",+ profile: { secret_refs: null },+ });listLlmProfilesMock.mockReset();listLlmProfilesMock.mockResolvedValue({profiles: [],@@ -420,6 +434,75 @@ describe("useCreateConversation", () => {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 andiff --git a/__tests__/routes/agent-settings.test.tsx b/__tests__/routes/agent-settings.test.tsxindex 19de58e7c7..10e520cf39 100644--- a/__tests__/routes/agent-settings.test.tsx+++ b/__tests__/routes/agent-settings.test.tsx@@ -12,7 +12,7 @@ import SettingsService from "#/api/settings-service/settings-service.api";import { SecretsService } from "#/api/secrets-service";import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";import { Settings } from "#/types/settings";-+import { ACP_PROVIDERS } from "#/constants/acp-providers";const CLAUDE_COMMAND = getClientAcpProvider("claude-code")!.default_command;const CODEX_COMMAND = getClientAcpProvider("codex")!.default_command;@@ -27,8 +27,19 @@ vi.mock("#/hooks/query/use-acp-auth-status", () => ({// model, which gained the field later than the settings schema did. Stub the// probe so both sides of that gate are reachable without a live server.const profileSupportsSwitchLlmToolMock = vi.hoisted(() => vi.fn(() => true));+const profileSupportsSecretRefsMock = vi.hoisted(() => vi.fn(() => true));vi.mock("#/api/agent-profiles-service/profile-field-support", () => ({agentProfileSupportsSwitchLlmTool: () => profileSupportsSwitchLlmToolMock(),+ agentProfileSupportsSecretRefs: () => profileSupportsSecretRefsMock(),+}));++// The secret picker lists the user's saved secrets; stub the query so these+// tests don't need a live secrets store.+const savedSecretsMock = vi.hoisted(() =>+ vi.fn<() => { name: string; description?: string }[]>(),+);+vi.mock("#/hooks/query/use-get-secrets", () => ({+ useSearchSecrets: () => ({ data: savedSecretsMock() }),}));// Observe save toasts so we can assert the single Save shows one confirmation,@@ -88,6 +99,12 @@ describe("AgentSettingsScreen", () => {toastMocks.error.mockClear();toastMocks.warning.mockClear();profileSupportsSwitchLlmToolMock.mockReturnValue(true);+ profileSupportsSecretRefsMock.mockReturnValue(true);+ savedSecretsMock.mockReturnValue([+ { name: "GITHUB_TOKEN", description: "repo access" },+ { name: "DATADOG_API_KEY" },+ { name: "PROD_DB_URL" },+ ]);});it("renders the agent type selector defaulting to OpenHands with sub-agents toggle", async () => {@@ -1286,4 +1303,400 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {const isDirty = await dirtyForStoredRefs(["postgres", "github"]);await waitFor(() => expect(isDirty()).toBe(false));});+ describe("secret scope", () => {+ beforeEach(() => {+ acpAuthStatusMock.mockReturnValue({+ status: "unknown",+ isChecking: false,+ isSupported: true,+ });+ profileSupportsSecretRefsMock.mockReturnValue(true);+ savedSecretsMock.mockReturnValue([+ { name: "GITHUB_TOKEN", description: "repo access" },+ { name: "DATADOG_API_KEY" },+ { name: "PROD_DB_URL" },+ ]);+ });+ function seedOpenHandsSettings() {+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettings({+ agent_settings: {+ ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,+ agent_kind: "openhands",+ },+ }),+ );+ }++ it("hides the control outside the profile editor", async () => {+ seedOpenHandsSettings();+ renderAgentSettingsScreen();+ await screen.findByTestId("agent-settings-screen");+ expect(+ screen.queryByTestId("agent-settings-secrets-mode"),+ ).not.toBeInTheDocument();+ });++ it("lists every saved secret read-only and persists null by default", async () => {+ seedOpenHandsSettings();+ let control: AgentSettingsSaveControl | null = null;+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_sub_agents: false,+ secret_refs: null,+ },+ onSaveControlChange: (next) => {+ control = next;+ },+ });+ await screen.findByTestId("agent-settings-screen");++ expect(+ screen.getByTestId("agent-settings-secret-list"),+ ).toBeInTheDocument();+ const github = screen.getByTestId("agent-settings-secret-GITHUB_TOKEN");+ expect(github).toBeChecked();+ expect(github).toBeDisabled();+ expect(+ screen.getByTestId("agent-settings-secret-PROD_DB_URL"),+ ).toBeChecked();+ expect(control!.buildAgentProfileFields()).toMatchObject({+ secret_refs: null,+ });+ });++ it("seeds from a stored scope and persists the selection", async () => {+ seedOpenHandsSettings();+ let control: AgentSettingsSaveControl | null = null;+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_sub_agents: false,+ secret_refs: ["DATADOG_API_KEY"],+ },+ onSaveControlChange: (next) => {+ control = next;+ },+ });+ await screen.findByTestId("agent-settings-screen");++ expect(+ screen.getByTestId("agent-settings-secret-DATADOG_API_KEY"),+ ).toBeChecked();+ expect(+ screen.getByTestId("agent-settings-secret-PROD_DB_URL"),+ ).not.toBeChecked();+ expect(control!.buildAgentProfileFields()).toMatchObject({+ secret_refs: ["DATADOG_API_KEY"],+ });+ });++ it("keeps a stored ref whose secret no longer exists", async () => {+ // The save is a whole-profile overwrite, so dropping it here would+ // silently rewrite the user's scope.+ seedOpenHandsSettings();+ let control: AgentSettingsSaveControl | null = null;+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_sub_agents: false,+ secret_refs: ["DELETED_SECRET"],+ },+ onSaveControlChange: (next) => {+ control = next;+ },+ });+ await screen.findByTestId("agent-settings-screen");++ expect(+ screen.getByTestId("agent-settings-secret-DELETED_SECRET"),+ ).toBeChecked();+ expect(control!.buildAgentProfileFields()).toMatchObject({+ secret_refs: ["DELETED_SECRET"],+ });+ });++ it.each([{ secretRefs: [] }, { secretRefs: ["PROD_DB_URL"] }])(+ "preserves an existing ACP secret scope $secretRefs through an unrelated edit",+ async ({ secretRefs }) => {+ savedSecretsMock.mockReturnValue([+ { name: "ANTHROPIC_API_KEY" },+ { name: "PROD_DB_URL" },+ ]);+ seedOpenHandsSettings();+ let control: AgentSettingsSaveControl | null = null;+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "acp",+ acp_server: "claude-code",+ acp_command: [...CLAUDE_COMMAND],+ acp_args: [],+ acp_model: "haiku",+ secret_refs: secretRefs,+ },+ onSaveControlChange: (next) => {+ control = next;+ },+ });+ await screen.findByTestId("agent-command-input");+ expect(control!.isDirty).toBe(false);+ expect(+ screen.getByTestId("agent-settings-secret-ANTHROPIC_API_KEY"),+ ).not.toBeChecked();++ const user = userEvent.setup();+ await user.click(screen.getByTestId("agent-settings-mcp-mode"));+ await user.click(+ await screen.findByRole("option", {+ name: "SETTINGS$AGENT_PROFILE_MCP_CHOOSE",+ }),+ );+ expect(control!.buildAgentProfileFields()).toMatchObject({+ mcp_server_refs: [],+ secret_refs: secretRefs,+ });+ },+ );++ it("keeps a provider credential deselected when the saved ACP profile is reopened", async () => {+ savedSecretsMock.mockReturnValue([+ { name: "ANTHROPIC_API_KEY" },+ { name: "PROD_DB_URL" },+ ]);+ seedOpenHandsSettings();+ let control: AgentSettingsSaveControl | null = null;+ const onSaveControlChange = (next: AgentSettingsSaveControl | null) => {+ control = next;+ };+ const view = renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "acp",+ acp_server: "claude-code",+ acp_command: [...CLAUDE_COMMAND],+ acp_args: [],+ acp_model: "haiku",+ secret_refs: ["ANTHROPIC_API_KEY", "PROD_DB_URL"],+ },+ onSaveControlChange,+ });+ await screen.findByTestId("agent-command-input");+ const user = userEvent.setup();+ await user.click(+ screen.getByTestId("agent-settings-secret-ANTHROPIC_API_KEY"),+ );+ const saved = control!.buildAgentProfileFields();+ expect(saved).toMatchObject({ secret_refs: ["PROD_DB_URL"] });+ view.unmount();+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: saved,+ onSaveControlChange,+ });+ await screen.findByTestId("agent-command-input");+ expect(+ screen.getByTestId("agent-settings-secret-ANTHROPIC_API_KEY"),+ ).not.toBeChecked();+ expect(control!.isDirty).toBe(false);+ expect(control!.buildAgentProfileFields()).toMatchObject({+ secret_refs: ["PROD_DB_URL"],+ });+ });++ it.each([true, false])(+ "selects provider credentials before saving (already stored: %s)",+ async (alreadyStored) => {+ // Scoping is strict server-side, so an ACP profile that omits its+ // credential cannot authenticate. Seed it visibly rather than re-adding+ // it behind the user's back.+ savedSecretsMock.mockReturnValue([+ ...(alreadyStored+ ? [{ name: "ANTHROPIC_API_KEY" }, { name: "ANTHROPIC_BASE_URL" }]+ : []),+ { name: "PROD_DB_URL" },+ ]);+ seedOpenHandsSettings();+ let control: AgentSettingsSaveControl | null = null;+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "acp",+ acp_server: "claude-code",+ // From the registry, not a literal: the pinned command carries a+ // version that moves, and a stale one detects as `custom` (no+ // provider credentials) instead of failing loudly.+ acp_command: [...CLAUDE_COMMAND],+ acp_args: [],+ acp_model: "",+ },+ onSaveControlChange: (next) => {+ control = next;+ },+ });+ await screen.findByTestId("agent-settings-screen");++ const user = userEvent.setup();+ await user.click(screen.getByTestId("agent-settings-secrets-mode"));+ await user.click(+ await screen.findByRole("option", {+ name: "SETTINGS$AGENT_PROFILE_SECRETS_CHOOSE",+ }),+ );++ await waitFor(() => {+ expect(+ screen.getByTestId("agent-settings-secret-ANTHROPIC_API_KEY"),+ ).toBeChecked();+ });+ // Seeded, not forced: an unrelated secret stays off.+ expect(+ screen.getByTestId("agent-settings-secret-PROD_DB_URL"),+ ).not.toBeChecked();++ await user.click(+ screen.getByTestId("agent-settings-secret-ANTHROPIC_API_KEY"),+ );+ expect(+ screen.getByTestId("agent-settings-secret-ANTHROPIC_API_KEY"),+ ).not.toBeChecked();+ expect(control!.buildAgentProfileFields()).toMatchObject({+ secret_refs: expect.not.arrayContaining(["ANTHROPIC_API_KEY"]),+ });+ await user.click(+ screen.getByTestId("agent-settings-secret-ANTHROPIC_API_KEY"),+ );+ const refs = (+ control!.buildAgentProfileFields() as { secret_refs?: string[] }+ ).secret_refs;+ expect(refs).toContain("ANTHROPIC_API_KEY");+ },+ );++ it.each(["preset", "command"])(+ "selects the new provider credential after an explicit %s change",+ async (input) => {+ savedSecretsMock.mockReturnValue([+ { name: "ANTHROPIC_API_KEY" },+ { name: "OPENAI_API_KEY" },+ ]);+ seedOpenHandsSettings();+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "acp",+ acp_server: "claude-code",+ acp_command: [...CLAUDE_COMMAND],+ acp_args: [],+ acp_model: "haiku",+ secret_refs: [],+ },+ });+ await screen.findByTestId("agent-command-input");+ const user = userEvent.setup();+ const codex = ACP_PROVIDERS.find(+ (provider) => provider.key === "codex",+ )!;+ if (input === "preset") {+ await user.click(screen.getByTestId("agent-preset-selector"));+ await user.click(+ await screen.findByRole("option", { name: codex.display_name }),+ );+ } else {+ const command = screen.getByTestId("agent-command-input");+ await user.clear(command);+ await user.type(command, codex.default_command.join(" "));+ }+ expect(+ screen.getByTestId("agent-settings-secret-OPENAI_API_KEY"),+ ).toBeChecked();+ expect(+ screen.getByTestId("agent-settings-secret-ANTHROPIC_API_KEY"),+ ).not.toBeChecked();+ },+ );++ it("leaves an OpenHands profile's scope empty when scoping starts", async () => {+ // Nothing an OpenHands agent needs rides this channel, so there is+ // nothing to seed.+ seedOpenHandsSettings();+ let control: AgentSettingsSaveControl | null = null;+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_sub_agents: false,+ },+ onSaveControlChange: (next) => {+ control = next;+ },+ });+ await screen.findByTestId("agent-settings-screen");++ const user = userEvent.setup();+ await user.click(screen.getByTestId("agent-settings-secrets-mode"));+ await user.click(+ await screen.findByRole("option", {+ name: "SETTINGS$AGENT_PROFILE_SECRETS_CHOOSE",+ }),+ );++ await waitFor(() => {+ expect(control!.buildAgentProfileFields()).toMatchObject({+ secret_refs: [],+ });+ });+ });++ it("omits the key on a backend whose profile model predates it", async () => {+ profileSupportsSecretRefsMock.mockReturnValue(false);+ seedOpenHandsSettings();+ let control: AgentSettingsSaveControl | null = null;+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_sub_agents: false,+ },+ onSaveControlChange: (next) => {+ control = next;+ },+ });+ await screen.findByTestId("agent-settings-screen");++ expect(+ screen.queryByTestId("agent-settings-secrets-mode"),+ ).not.toBeInTheDocument();+ expect(control!.buildAgentProfileFields()).not.toHaveProperty(+ "secret_refs",+ );+ });++ it("explains the empty state when nothing is saved", async () => {+ savedSecretsMock.mockReturnValue([]);+ seedOpenHandsSettings();+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_sub_agents: false,+ },+ });+ await screen.findByTestId("agent-settings-screen");+ expect(+ screen.queryByTestId("agent-settings-secret-list"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByText("SETTINGS$AGENT_PROFILE_SECRETS_NONE"),+ ).toBeInTheDocument();+ // The control itself stays, so the user can still see the scope mode.+ expect(+ screen.getByTestId("agent-settings-secrets-mode"),+ ).toBeInTheDocument();+ });+ });});diff --git a/__tests__/routes/build-agent-profile-fields.test.ts b/__tests__/routes/build-agent-profile-fields.test.tsindex e35a3f63be..0f0e93f534 100644--- a/__tests__/routes/build-agent-profile-fields.test.ts+++ b/__tests__/routes/build-agent-profile-fields.test.ts@@ -15,7 +15,10 @@ const baseAcp = {toolConcurrencyField: undefined,toolConcurrency: "",mcpMode: "standard" as const,- selectedMcpServers: [],+ selectedMcpServers: [] as string[],+ secretsMode: "standard" as const,+ selectedSecrets: [] as string[],+ secretRefsSupportedOnProfile: true,};const switchLlmToolField: SettingsFieldSchema = {@@ -55,6 +58,7 @@ describe("buildAgentProfileFields — ACP", () => {acp_model: "claude-opus-4-8",acp_command: null,acp_args: null,+ secret_refs: null,});});@@ -108,7 +112,10 @@ describe("buildAgentProfileFields — OpenHands", () => {toolConcurrencyField: undefined,toolConcurrency: "",mcpMode: "standard" as const,- selectedMcpServers: [],+ selectedMcpServers: [] as string[],+ secretsMode: "standard" as const,+ selectedSecrets: [] as string[],+ secretRefsSupportedOnProfile: true,};it("passes through enable_sub_agents and omits concurrency when the field is absent", () => {@@ -116,6 +123,7 @@ describe("buildAgentProfileFields — OpenHands", () => {agent_kind: "openhands",mcp_server_refs: null,enable_sub_agents: true,+ secret_refs: null,});});@@ -219,6 +227,9 @@ describe("buildAgentProfileFields — mcp_server_refs", () => {toolConcurrency: "",mcpMode: "standard" as const,selectedMcpServers: [],+ secretsMode: "standard" as const,+ selectedSecrets: [] as string[],+ secretRefsSupportedOnProfile: true,};it("emits null in standard mode, so the profile inherits every server", () => {@@ -256,3 +267,68 @@ describe("buildAgentProfileFields — mcp_server_refs", () => {expect(acp.mcp_server_refs).toEqual(["fetch"]);});});++describe("buildAgentProfileFields — secret scope", () => {+ const base = {+ isAcp: false,+ selectedPreset: "custom",+ isDefaultProviderCommand: false,+ commandTokens: [] as string[],+ acpModel: "",+ subAgentsEnabled: false,+ switchLlmToolField: undefined,+ switchLlmToolEnabled: false,+ switchLlmToolSupportedOnProfile: true,+ toolConcurrencyField: undefined,+ toolConcurrency: "",+ secretsMode: "standard" as const,+ selectedSecrets: [] as string[],+ secretRefsSupportedOnProfile: true,+ mcpMode: "standard" as const,+ selectedMcpServers: [] as string[],+ };++ it("persists null when every secret is allowed", () => {+ expect(buildAgentProfileFields(base)).toMatchObject({ secret_refs: null });+ });++ it("persists the selection when secrets are scoped", () => {+ const fields = buildAgentProfileFields({+ ...base,+ secretsMode: "custom",+ selectedSecrets: ["DATADOG_API_KEY"],+ });+ expect(fields).toMatchObject({ secret_refs: ["DATADOG_API_KEY"] });+ });++ it("persists an empty list when no secret is selected", () => {+ expect(+ buildAgentProfileFields({ ...base, secretsMode: "custom" }),+ ).toMatchObject({ secret_refs: [] });+ });++ it("rides the ACP variant too — it is a base-model field", () => {+ const fields = buildAgentProfileFields({+ ...base,+ isAcp: true,+ selectedPreset: "claude-code",+ commandTokens: ["npx", "claude-code-acp"],+ secretsMode: "custom",+ selectedSecrets: ["DATADOG_API_KEY"],+ });+ expect(fields).toMatchObject({+ agent_kind: "acp",+ secret_refs: ["DATADOG_API_KEY"],+ });+ });++ it("omits the key on a backend whose profile model predates it", () => {+ const fields = buildAgentProfileFields({+ ...base,+ secretsMode: "custom",+ selectedSecrets: ["DATADOG_API_KEY"],+ secretRefsSupportedOnProfile: false,+ });+ expect(fields).not.toHaveProperty("secret_refs");+ });+});diff --git a/src/api/agent-profiles-service/profile-field-support.ts b/src/api/agent-profiles-service/profile-field-support.tsindex 71e0c0b25e..1853b976d5 100644--- a/src/api/agent-profiles-service/profile-field-support.ts+++ b/src/api/agent-profiles-service/profile-field-support.ts@@ -1,7 +1,9 @@import {compareAgentServerVersions,getCachedAgentServerVersion,+ getCachedAgentServerInfo,} from "#/api/agent-server-compatibility";+import { getActiveBackend } from "#/api/backend-registry/active-store";/*** `enable_switch_llm_tool` reached `OpenHandsAgentProfile` in@@ -39,3 +41,13 @@ export function agentProfileSupportsSwitchLlmTool(): boolean {if (comparison === null) return true;return comparison >= 0;}++/** Only offer a scope when the serving backend advertises enforcement. */+export function agentProfileSupportsSecretRefs(): boolean {+ if (getActiveBackend().backend.kind === "cloud") return false;+ const capabilities = getCachedAgentServerInfo()?.capabilities;+ return (+ Array.isArray(capabilities) &&+ capabilities.includes("profile_secret_scope_v1")+ );+}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.tsxindex c0f305acf6..e6c92e4d00 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@@ -41,10 +41,14 @@ type ViewMode = "list" | "create" | "edit";function toAgentSettingsOverride(profile: AgentProfile,): Record<string, SettingsValue> {+ const secretRefs =+ ((profile as { secret_refs?: unknown }).secret_refs as SettingsValue) ??+ null;if (profile.agent_kind === "acp") {return {agent_kind: "acp",mcp_server_refs: profile.mcp_server_refs ?? null,+ secret_refs: secretRefs,acp_server: profile.acp_server,acp_command: profile.acp_command ? parseCommand(profile.acp_command) : [],acp_args: profile.acp_args ?? [],@@ -64,6 +68,7 @@ function toAgentSettingsOverride(enable_sub_agents: profile.enable_sub_agents,enable_switch_llm_tool: switchLlmToolEnabled,tool_concurrency_limit: profile.tool_concurrency_limit,+ secret_refs: secretRefs,};}diff --git a/src/constants/profile-scope.ts b/src/constants/profile-scope.tsindex d9a5aaeb47..bbb4bbb55f 100644--- a/src/constants/profile-scope.ts+++ b/src/constants/profile-scope.ts@@ -2,12 +2,12 @@export type ProfileScopeMode = "standard" | "custom";/**- * Read a stored profile's `mcp_server_refs` into picker state.+ * Read a stored profile's named scope (MCP servers or secrets) into picker state.** Tri-state on the wire: `null`/absent = every configured server, an array =* only those keys (`[]` = none).*/-export function readProfileMcpRefs(value: unknown): {+export function readProfileScope(value: unknown): {mode: ProfileScopeMode;selected: string[];} {diff --git a/src/hooks/mutation/use-create-conversation.ts b/src/hooks/mutation/use-create-conversation.tsindex cb62c8b9bf..225cd0227d 100644--- a/src/hooks/mutation/use-create-conversation.ts+++ b/src/hooks/mutation/use-create-conversation.ts@@ -129,7 +129,7 @@ export const useCreateConversation = () => {// `launched_agent_profile` stamped and the profile's config applied// (#1571 review).const isCloud = backend.kind === "cloud";- let effectiveAgentProfileId = requestedAgentProfileId;+ let prefersAgentSettingsFallback = false;// The account-wide active LLM profile from the launch-path fetch below// (null when that fetch didn't run or failed). Fresher than the// `useLlmProfiles()` render snapshot, which a fast send can outrun.@@ -157,7 +157,7 @@ export const useCreateConversation = () => {//// Scoped to local: cloud never writes agent_settings, so it always// resolves `default` server-side via agent_profile_id (validated below).- effectiveAgentProfileId = undefined;+ prefersAgentSettingsFallback = true;} else if (resolvedAgentProfile?.agent_kind === "openhands" &&resolvedAgentProfile.llm_profile_ref@@ -189,7 +189,7 @@ export const useCreateConversation = () => {`LLM profile "${resolvedAgentProfile.llm_profile_ref}"; ` +"launching from agent_settings instead.",);- effectiveAgentProfileId = undefined;+ prefersAgentSettingsFallback = true;} else if (!isCloud &&!agentProfileId &&@@ -210,10 +210,43 @@ export const useCreateConversation = () => {// apply to this launch; the start request has no per-launch LLM// override that could preserve it (AgentLaunchAdditions carries only// a system-message suffix).- effectiveAgentProfileId = undefined;+ prefersAgentSettingsFallback = true;}}+ // 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 even when one of the compatibility+ // fallbacks above would otherwise apply. If the detail cannot be read,+ // fail closed by preserving the profile id and letting Agent Server return+ // the underlying profile-resolution error.+ let profileAllowsAgentSettingsFallback = true;+ if (prefersAgentSettingsFallback && resolvedAgentProfile) {+ try {+ // Revalidate stale cached details: policy may have changed since the+ // profile editor or another client last populated this query.+ const detail = await queryClient.fetchQuery({+ queryKey: AGENT_PROFILES_QUERY_KEYS.detail(+ backend.id,+ orgId,+ resolvedAgentProfile.name,+ ),+ queryFn: () =>+ AgentProfilesService.getProfile(resolvedAgentProfile.name),+ ...AGENT_PROFILES_RETRY_OPTIONS,+ });+ const secretRefs = (detail.profile as { secret_refs?: unknown })+ .secret_refs;+ profileAllowsAgentSettingsFallback = !Array.isArray(secretRefs);+ } catch {+ profileAllowsAgentSettingsFallback = false;+ }+ }+ const effectiveAgentProfileId =+ prefersAgentSettingsFallback && profileAllowsAgentSettingsFallback+ ? undefined+ : requestedAgentProfileId;+// Only extend the call with the profile fields when launching from a// profile, so a plain create stays byte-identical to the legacy// agent_settings path (#3727). sandboxId is unused here.diff --git a/src/hooks/mutation/use-switch-acp-model.ts b/src/hooks/mutation/use-switch-acp-model.tsindex 396c4e0eeb..615027da3e 100644--- a/src/hooks/mutation/use-switch-acp-model.ts+++ b/src/hooks/mutation/use-switch-acp-model.ts@@ -11,7 +11,6 @@ import {AGENT_PROFILES_RETRY_OPTIONS,SETTINGS_QUERY_KEYS,} from "#/hooks/query/query-keys";-import { agentProfileDetailQueryKey } from "#/hooks/query/use-active-acp-profile-detail";import { invalidateConversationQueries } from "./conversation-mutation-utils";interface SwitchAcpModelVars {@@ -82,7 +81,7 @@ export const useSwitchAcpModel = () => {// Merge over the stored profile so a model-only pick can't wipe the// fields this surface doesn't model (command, session mode, …).const detail = await queryClient.ensureQueryData({- queryKey: agentProfileDetailQueryKey(+ queryKey: AGENT_PROFILES_QUERY_KEYS.detail(backend.id,orgId,activeProfile.name,diff --git a/src/hooks/query/query-keys.ts b/src/hooks/query/query-keys.tsindex 44edeeaf58..eb2c56033f 100644--- a/src/hooks/query/query-keys.ts+++ b/src/hooks/query/query-keys.ts@@ -24,6 +24,9 @@ export const LLM_PROFILES_QUERY_KEYS = {export const AGENT_PROFILES_QUERY_KEYS = {all: ["agent-profiles"] as const,+ // Nested under `all` so profile mutations invalidate cached details too.+ detail: (backendId: string, orgId: string | null | undefined, name: string) =>+ ["agent-profiles", backendId, orgId, "detail", name] as const,} as const;export const PROVIDER_CONNECTIONS_QUERY_KEYS = {diff --git a/src/hooks/query/use-active-acp-profile-detail.ts b/src/hooks/query/use-active-acp-profile-detail.tsindex c3933e5bbe..a700e7b3d4 100644--- a/src/hooks/query/use-active-acp-profile-detail.ts+++ b/src/hooks/query/use-active-acp-profile-detail.ts@@ -10,28 +10,6 @@ import {AGENT_PROFILES_RETRY_OPTIONS,} from "./query-keys";-/**- * Cache key for one profile's full detail. Lives under the agent-profiles- * prefix on purpose: activate/save/delete invalidate that prefix, so the- * detail refetches for free. (`useActivateAgentProfile.onMutate` also- * `setQueriesData`s the prefix, writing a stray `active_agent_profile_id`- * onto this entry — benign, consumers only read `.profile`.) Shared with- * `useSwitchAcpModel`, which `ensureQueryData`s the same entry.- */-export function agentProfileDetailQueryKey(- backendId: string,- orgId: string | null | undefined,- name: string,-) {- return [- ...AGENT_PROFILES_QUERY_KEYS.all,- backendId,- orgId,- "detail",- name,- ] as const;-}-/*** Full detail of the active AgentProfile when it is ACP and no conversation is* open. `AgentProfileSummary` carries no `acp_server`/`acp_model`, and profile@@ -51,7 +29,7 @@ export function useActiveAcpProfileDetail(): ACPAgentProfile | null {activeProfile?.agent_kind === "acp" ? activeProfile.name : null;const { data } = useQuery({- queryKey: agentProfileDetailQueryKey(+ queryKey: AGENT_PROFILES_QUERY_KEYS.detail(backend.id,orgId,activeAcpProfileName ?? "",diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 0177bf39c0..fe1b9edbda 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -41939,5 +41939,107 @@"uk": "Попередній перегляд зображення в повному розмірі","zh-CN": "原始尺寸图片预览","zh-TW": "原始尺寸圖片預覽"+ },+ "SETTINGS$AGENT_PROFILE_SECRETS": {+ "en": "Secrets",+ "ja": "シークレット",+ "zh-CN": "机密",+ "zh-TW": "機密",+ "ko-KR": "시크릿",+ "no": "Hemmeligheter",+ "it": "Segreti",+ "pt": "Segredos",+ "es": "Secretos",+ "ar": "الأسرار",+ "fr": "Secrets",+ "tr": "Gizli bilgiler",+ "de": "Geheimnisse",+ "uk": "Секрети",+ "ca": "Secrets"+ },+ "SETTINGS$AGENT_PROFILE_SECRETS_ALL": {+ "en": "No profile restriction",+ "ja": "プロファイルによる制限なし",+ "zh-CN": "不由配置文件限制",+ "zh-TW": "不由設定檔限制",+ "ko-KR": "프로필 제한 없음",+ "no": "Ingen profilbegrensning",+ "it": "Nessuna restrizione del profilo",+ "pt": "Sem restrição do perfil",+ "es": "Sin restricción del perfil",+ "ar": "بلا تقييد من الملف الشخصي",+ "fr": "Aucune restriction du profil",+ "tr": "Profil kısıtlaması yok",+ "de": "Keine Profileinschränkung",+ "uk": "Без обмежень профілю",+ "ca": "Sense restricció del perfil"+ },+ "SETTINGS$AGENT_PROFILE_SECRETS_CHOOSE": {+ "en": "Choose secrets",+ "ja": "シークレットを選択",+ "zh-CN": "自选机密",+ "zh-TW": "自選機密",+ "ko-KR": "시크릿 선택",+ "no": "Velg hemmeligheter",+ "it": "Scegli i segreti",+ "pt": "Escolher segredos",+ "es": "Elegir secretos",+ "ar": "اختيار الأسرار",+ "fr": "Choisir les secrets",+ "tr": "Gizli bilgileri seçin",+ "de": "Geheimnisse auswählen",+ "uk": "Вибрати секрети",+ "ca": "Tria els secrets"+ },+ "SETTINGS$AGENT_PROFILE_SECRETS_ALL_HINT": {+ "en": "Allows secrets supplied when the agent starts. For automations, choose secrets explicitly in this profile.",+ "ja": "エージェントの起動時に渡されたシークレットを許可します。自動化では、このプロファイルでシークレットを明示的に選択してください。",+ "zh-CN": "允许使用代理启动时提供的机密。用于自动化时,请在此配置文件中明确选择机密。",+ "zh-TW": "允許使用代理啟動時提供的機密。用於自動化時,請在此設定檔中明確選擇機密。",+ "ko-KR": "에이전트 시작 시 제공된 시크릿을 허용합니다. 자동화에서는 이 프로필에서 시크릿을 명시적으로 선택하세요.",+ "no": "Tillater hemmeligheter som oppgis når agenten starter. For automatiseringer må du velge hemmeligheter eksplisitt i denne profilen.",+ "it": "Consente i segreti forniti all’avvio dell’agente. Per le automazioni, scegli esplicitamente i segreti in questo profilo.",+ "pt": "Permite os segredos fornecidos quando o agente inicia. Para automações, escolha explicitamente os segredos neste perfil.",+ "es": "Permite los secretos proporcionados al iniciar el agente. Para las automatizaciones, elige los secretos explícitamente en este perfil.",+ "ar": "يسمح بالأسرار المقدمة عند بدء الوكيل. للأتمتة، اختر الأسرار صراحةً في هذا الملف الشخصي.",+ "fr": "Autorise les secrets fournis au démarrage de l’agent. Pour les automatisations, choisissez explicitement les secrets dans ce profil.",+ "tr": "Aracı başlatılırken sağlanan gizli bilgilere izin verir. Otomasyonlar için bu profilde gizli bilgileri açıkça seçin.",+ "de": "Erlaubt beim Start des Agenten übergebene Geheimnisse. Wählen Sie für Automatisierungen die Geheimnisse in diesem Profil ausdrücklich aus.",+ "uk": "Дозволяє секрети, передані під час запуску агента. Для автоматизацій явно виберіть секрети в цьому профілі.",+ "ca": "Permet els secrets proporcionats en iniciar l’agent. Per a les automatitzacions, tria explícitament els secrets en aquest perfil."+ },+ "SETTINGS$AGENT_PROFILE_SECRETS_CHOOSE_HINT": {+ "en": "This agent can use only the secrets you select — make sure it has everything it needs. An external agent needs its own provider credentials to sign in.",+ "ja": "このエージェントは選択したシークレットのみを使用できます。必要なものがすべて含まれているか確認してください。外部エージェントはサインインに自身のプロバイダー認証情報が必要です。",+ "zh-CN": "该代理只能使用你选择的机密,请确认它需要的都已包含。外部代理需要自身的提供方凭据才能登录。",+ "zh-TW": "該代理只能使用你選擇的機密,請確認它需要的都已包含。外部代理需要自身的供應商憑證才能登入。",+ "ko-KR": "이 에이전트는 선택한 시크릿만 사용할 수 있으므로 필요한 항목이 모두 포함되었는지 확인하세요. 외부 에이전트는 로그인하려면 자체 공급자 자격 증명이 필요합니다.",+ "no": "Denne agenten kan bare bruke hemmelighetene du velger – sørg for at den har alt den trenger. En ekstern agent trenger sine egne leverandørlegitimasjoner for å logge inn.",+ "it": "Questo agente può usare solo i segreti che selezioni: assicurati che abbia tutto ciò che gli serve. Un agente esterno ha bisogno delle proprie credenziali del provider per accedere.",+ "pt": "Este agente pode usar apenas os segredos que você selecionar — confirme que ele tem tudo o que precisa. Um agente externo precisa das próprias credenciais do provedor para entrar.",+ "es": "Este agente solo puede usar los secretos que selecciones; asegúrate de que tenga todo lo que necesita. Un agente externo necesita sus propias credenciales del proveedor para iniciar sesión.",+ "ar": "لا يمكن لهذا الوكيل استخدام سوى الأسرار التي تحددها، فتأكد من أنه يملك كل ما يحتاجه. ويحتاج الوكيل الخارجي إلى بيانات اعتماد مزوّده الخاصة لتسجيل الدخول.",+ "fr": "Cet agent ne peut utiliser que les secrets que vous sélectionnez : vérifiez qu'il dispose de tout ce dont il a besoin. Un agent externe a besoin de ses propres identifiants de fournisseur pour se connecter.",+ "tr": "Bu aracı yalnızca seçtiğiniz gizli bilgileri kullanabilir; ihtiyacı olan her şeyin bulunduğundan emin olun. Harici bir aracının oturum açmak için kendi sağlayıcı kimlik bilgilerine ihtiyacı vardır.",+ "de": "Dieser Agent kann nur die von Ihnen ausgewählten Geheimnisse verwenden – stellen Sie sicher, dass er alles Nötige hat. Ein externer Agent benötigt zum Anmelden seine eigenen Anbieter-Anmeldedaten.",+ "uk": "Цей агент може використовувати лише вибрані вами секрети — переконайтеся, що він має все потрібне. Зовнішньому агенту для входу потрібні власні облікові дані провайдера.",+ "ca": "Aquest agent només pot fer servir els secrets que seleccionis; assegura't que té tot el que necessita. Un agent extern necessita les seves pròpies credencials del proveïdor per iniciar la sessió."+ },+ "SETTINGS$AGENT_PROFILE_SECRETS_NONE": {+ "en": "You have not saved any secrets yet.",+ "ja": "シークレットはまだ保存されていません。",+ "zh-CN": "你还没有保存任何机密。",+ "zh-TW": "你還沒有儲存任何機密。",+ "ko-KR": "아직 저장된 시크릿이 없습니다.",+ "no": "Du har ikke lagret noen hemmeligheter ennå.",+ "it": "Non hai ancora salvato alcun segreto.",+ "pt": "Você ainda não salvou nenhum segredo.",+ "es": "Aún no has guardado ningún secreto.",+ "ar": "لم تحفظ أي أسرار بعد.",+ "fr": "Vous n'avez encore enregistré aucun secret.",+ "tr": "Henüz gizli bilgi kaydetmediniz.",+ "de": "Sie haben noch keine Geheimnisse gespeichert.",+ "uk": "Ви ще не зберегли жодного секрету.",+ "ca": "Encara no has desat cap secret."}}diff --git a/src/routes/agent-settings.tsx b/src/routes/agent-settings.tsxindex e13ff841da..539b18da95 100644--- a/src/routes/agent-settings.tsx+++ b/src/routes/agent-settings.tsx@@ -37,17 +37,22 @@ import {buildAcpAgentSettingsDiff,getAcpPreferredDefaultModel,getAcpProvider,+ getAcpProviderSecrets,type ACPProviderConfig,} from "#/constants/acp-providers";import { parseCommand, formatCommand } from "#/utils/acp-command";import {- readProfileMcpRefs,+ readProfileScope,sameScopeSelection,type ProfileScopeMode,} from "#/constants/profile-scope";import { flattenMcpConfig } from "#/utils/mcp-installed-servers";import { parseMcpConfig } from "#/utils/mcp-config";-import { agentProfileSupportsSwitchLlmTool } from "#/api/agent-profiles-service/profile-field-support";+import {+ agentProfileSupportsSecretRefs,+ agentProfileSupportsSwitchLlmTool,+} from "#/api/agent-profiles-service/profile-field-support";+import { useSearchSecrets } from "#/hooks/query/use-get-secrets";export const handle = { hideTitle: true };@@ -64,6 +69,7 @@ const ENABLE_SUB_AGENTS_FIELD_KEY = "enable_sub_agents";const ENABLE_SWITCH_LLM_TOOL_FIELD_KEY = "enable_switch_llm_tool";const TOOL_CONCURRENCY_FIELD_KEY = "tool_concurrency_limit";const MCP_SERVER_REFS_KEY = "mcp_server_refs";+const SECRET_REFS_KEY = "secret_refs";const COMMAND_PLACEHOLDER_FALLBACK = "npx -y <package-name>";const ACP_CUSTOM_MODEL_KEY = "__custom_model__";const EMPTY_AGENT_SETTINGS_SNAPSHOT: AgentSettingsSnapshot = {@@ -134,10 +140,12 @@ export type AgentProfileFieldsDraft =enable_sub_agents: boolean;enable_switch_llm_tool?: boolean;tool_concurrency_limit?: number;+ secret_refs?: string[] | null;}| {agent_kind: "acp";mcp_server_refs: string[] | null;+ secret_refs?: string[] | null;acp_server: string;acp_model: string | null;acp_command: string | null;@@ -167,6 +175,10 @@ export interface AgentProfileFieldsInput {toolConcurrency: string | boolean;mcpMode: ProfileScopeMode;selectedMcpServers: string[];+ secretsMode: ProfileScopeMode;+ selectedSecrets: string[];+ /** Whether the backend's *profile* model accepts `secret_refs`. */+ secretRefsSupportedOnProfile: boolean;}/**@@ -204,18 +216,26 @@ export function buildAgentProfileFields(toolConcurrency,mcpMode,selectedMcpServers,+ secretsMode,+ selectedSecrets,+ secretRefsSupportedOnProfile,} = input;- // A base-model field, so it rides both variants. No version gate: it has- // existed since agent profiles shipped, below the supported floor.+ // Both are base-model fields, so they ride both variants. `mcp_server_refs`+ // needs no version gate — it has existed since agent profiles shipped, below+ // the supported floor — while `secret_refs` does.const mcpRefs = {mcp_server_refs: mcpMode === "custom" ? selectedMcpServers : null,};+ const secretRefs = secretRefsSupportedOnProfile+ ? { secret_refs: secretsMode === "custom" ? selectedSecrets : null }+ : {};if (isAcp) {const isBuiltinDefault =isDefaultProviderCommand && selectedPreset !== ACP_CUSTOM_PRESET_KEY;return {agent_kind: "acp",...mcpRefs,+ ...secretRefs,acp_server: selectedPreset,acp_model: acpModel.trim() || null,acp_command: isBuiltinDefault@@ -229,6 +249,7 @@ export function buildAgentProfileFields(agent_kind: "openhands",...mcpRefs,enable_sub_agents: subAgentsEnabled,+ ...secretRefs,};if (switchLlmToolField && switchLlmToolSupportedOnProfile) {// Two conditions, two different questions. The schema tells us the field@@ -376,7 +397,7 @@ export function AgentSettingsScreen({// ``mcp_config`` itself.const showProfileScopeFields = embedded;const initialMcpRefs = React.useMemo(- () => readProfileMcpRefs(agentSettingsSource?.[MCP_SERVER_REFS_KEY]),+ () => readProfileScope(agentSettingsSource?.[MCP_SERVER_REFS_KEY]),[agentSettingsSource],);const [mcpMode, setMcpMode] = useState<ProfileScopeMode>(initialMcpRefs.mode);@@ -418,6 +439,39 @@ export function AgentSettingsScreen({.filter((name) => selectedMcpServers.includes(name)),[mcpCatalog, selectedMcpServers],);+ // --- Secret scope (both variants; a base-model field) ---+ const secretRefsSupportedOnProfile = agentProfileSupportsSecretRefs();+ const { data: savedSecrets } = useSearchSecrets({+ enabled: embedded && secretRefsSupportedOnProfile,+ });+ const initialSecretRefs = React.useMemo(+ () => readProfileScope(agentSettingsSource?.[SECRET_REFS_KEY]),+ [agentSettingsSource],+ );+ const [secretsMode, setSecretsMode] = useState<ProfileScopeMode>(+ initialSecretRefs.mode,+ );+ const [selectedSecrets, setSelectedSecrets] = useState<string[]>(+ initialSecretRefs.selected,+ );+ // Scoping is strict server-side — nothing is added back — so an ACP profile+ // that omits its provider credential simply fails to authenticate. Keep the+ // names selected by default rather than re-adding them behind the user's+ // back: a visible checkbox they can still clear, not a hidden rule.+ const addProviderSecrets = useCallback(+ (providerKey: string) =>+ setSelectedSecrets((prev) => {+ const names = getAcpProviderSecrets(providerKey).map(+ ({ name }) => name,+ );+ const missing = names.filter((name) => !prev.includes(name));+ return missing.length ? [...prev, ...missing] : prev;+ }),+ [],+ );++ // A ref to a server that no longer exists 422s the launch, so surface it+ // while the user can still fix it.const danglingMcpRefs = React.useMemo(() =>mcpMode === "custom"@@ -448,6 +502,34 @@ export function AgentSettingsScreen({: null,);+ // Available provider credentials must remain visible when deselected, even+ // before their values are saved. Stored references also survive deletion.+ const secretCatalog = React.useMemo(() => {+ const saved = (savedSecrets ?? []).map((secret) => ({+ name: secret.name,+ description: secret.description ?? null,+ }));+ const known = new Set(saved.map((secret) => secret.name));+ return [+ ...saved,+ ...[+ ...new Set([+ ...initialSecretRefs.selected,+ ...acpCredentialForm.fields.map(({ name }) => name),+ ]),+ ]+ .filter((name) => !known.has(name))+ .map((name) => ({ name, description: null as string | null })),+ ];+ }, [savedSecrets, initialSecretRefs, acpCredentialForm.fields]);+ const orderedSelectedSecrets = React.useMemo(+ () =>+ secretCatalog+ .map(({ name }) => name)+ .filter((name) => selectedSecrets.includes(name)),+ [secretCatalog, selectedSecrets],+ );+const lastInitializedSettingsRef = useRef<unknown>(null);const loadedAcpServerRef = useRef<string | null>(null);const loadedCommandTextRef = useRef<string>("");@@ -535,6 +617,12 @@ export function AgentSettingsScreen({setSelectedMcpServers(initialMcpRefs.selected);}, [initialMcpRefs]);+ // Sync the secret scope when settings reload+ useEffect(() => {+ setSecretsMode(initialSecretRefs.mode);+ setSelectedSecrets(initialSecretRefs.selected);+ }, [initialSecretRefs]);+// --- Embedded (Agent-profile editor) save control ---// Ref-backed so the exposed builder/credential fns read the freshest state at// call time without re-emitting the control on every keystroke (mirrors@@ -562,9 +650,14 @@ export function AgentSettingsScreen({const mcpScopeDirty =mcpMode !== initialMcpRefs.mode ||!sameScopeSelection(orderedSelectedMcpServers, initialMcpRefs.selected);+ // `secret_refs` is a base-model field too, so it is tracked for both variants.+ const secretScopeDirty =+ secretsMode !== initialSecretRefs.mode ||+ !sameScopeSelection(orderedSelectedSecrets, initialSecretRefs.selected);const settingsDirty =agentType !== loadedSnapshot.agentType ||mcpScopeDirty ||+ secretScopeDirty ||(agentType === "acp"? commandText !== loadedSnapshot.commandText ||acpModel !== loadedSnapshot.acpModel ||@@ -639,6 +732,9 @@ export function AgentSettingsScreen({toolConcurrency,mcpMode,selectedMcpServers: orderedSelectedMcpServers,+ secretsMode,+ selectedSecrets: orderedSelectedSecrets,+ secretRefsSupportedOnProfile,});const isSavingAny = isSaving || acpCredentialForm.isSaving;@@ -827,7 +923,14 @@ export function AgentSettingsScreen({setCommandText(formatCommand(preferred.default_command));setAcpModel(getAcpPreferredDefaultModel(preferred.key) ?? "");setIsCustomAcpModel(false);+ if (secretsMode === "custom") addProviderSecrets(preferred.key);}+ } else if (+ newType === "acp" &&+ agentType !== "acp" &&+ secretsMode === "custom"+ ) {+ addProviderSecrets(selectedPreset);} else if (newType === "openhands") {setIsCustomAcpModel(false);}@@ -969,6 +1072,68 @@ export function AgentSettingsScreen({</div>) : null}+ {showProfileScopeFields && secretRefsSupportedOnProfile ? (+ <div className="flex flex-col gap-2.5">+ <Typography.Text className="text-sm">+ {t(I18nKey.SETTINGS$AGENT_PROFILE_SECRETS)}+ </Typography.Text>+ <SettingsDropdownInput+ testId="agent-settings-secrets-mode"+ name="agent-secrets-mode"+ label=""+ items={[+ {+ key: "standard",+ label: t(I18nKey.SETTINGS$AGENT_PROFILE_SECRETS_ALL),+ },+ {+ key: "custom",+ label: t(I18nKey.SETTINGS$AGENT_PROFILE_SECRETS_CHOOSE),+ },+ ]}+ selectedKey={secretsMode}+ isDisabled={isSavingAny}+ onSelectionChange={(key) => {+ if (!key) return;+ const mode = key as ProfileScopeMode;+ setSecretsMode(mode);+ if (mode === "custom" && isAcp)+ addProviderSecrets(selectedPreset);+ }}+ />+ {secretCatalog.length > 0 ? (+ <ProfileScopeList+ testId="agent-settings-secret"+ items={secretCatalog}+ selected={+ secretsMode === "custom"+ ? orderedSelectedSecrets+ : secretCatalog.map(({ name }) => name)+ }+ isDisabled={isSavingAny || secretsMode === "standard"}+ onToggle={(name, checked) =>+ setSelectedSecrets((prev) =>+ checked+ ? [...prev, name]+ : prev.filter((entry) => entry !== name),+ )+ }+ />+ ) : (+ <Typography.Text className="text-xs text-tertiary-alt">+ {t(I18nKey.SETTINGS$AGENT_PROFILE_SECRETS_NONE)}+ </Typography.Text>+ )}+ <Typography.Text className="text-xs text-tertiary-alt">+ {t(+ secretsMode === "custom"+ ? I18nKey.SETTINGS$AGENT_PROFILE_SECRETS_CHOOSE_HINT+ : I18nKey.SETTINGS$AGENT_PROFILE_SECRETS_ALL_HINT,+ )}+ </Typography.Text>+ </div>+ ) : null}+{isAcp && (<><SettingsDropdownInput@@ -994,6 +1159,9 @@ export function AgentSettingsScreen({setCommandText(formatCommand(provider.default_command));setAcpModel(getAcpPreferredDefaultModel(preset) ?? "");setIsCustomAcpModel(false);+ if (secretsMode === "custom" && preset !== selectedPreset) {+ addProviderSecrets(preset);+ }} else if (preset === ACP_CUSTOM_PRESET_KEY) {// Clear command + model: the previous provider's default// command would otherwise make detectPreset(commandText)@@ -1034,6 +1202,7 @@ export function AgentSettingsScreen({if (nextPreset !== prevPreset) {setAcpModel(getAcpPreferredDefaultModel(nextPreset) ?? "");setIsCustomAcpModel(false);+ if (secretsMode === "custom") addProviderSecrets(nextPreset);}setCommandText(nextCommandText);}}