Skip to content

🙌 OpenHands: AI-Driven Development

feat(acp): containerized + cloud ACP — onboarding, secrets, and recycled-sandbox resume (#1013/#1014/#988) (#1102)

simonrosenbergec4616c1c735
diff --git a/.env.sample b/.env.sample
index 85d123192c..85b02596aa 100644
--- a/.env.sample
+++ b/.env.sample
@@ -5,6 +5,9 @@
# when you intentionally want to point at a separately managed backend.
VITE_BACKEND_HOST="127.0.0.1:8000" # Host:port used by the Vite dev proxy
VITE_BACKEND_BASE_URL="http://127.0.0.1:8000" # Base URL used by browser-side direct requests
+# To drive a containerized ACP agent-server, point this at the published port,
+# e.g. VITE_BACKEND_BASE_URL="http://localhost:8010" — see examples/acp-docker/
+# and docs/ACP_AGENTS.md → "Running ACP agents in a Docker container".
# VITE_SESSION_API_KEY="" # Set to the same value as backend SESSION_API_KEY or OH_SESSION_API_KEYS_0 when auth is enabled
# VITE_WORKING_DIR="/workspace/project/agent-canvas" # Base dir for per-conversation working_dirs. Each conversation's working_dir is <VITE_WORKING_DIR>/<id_hex>. Defaults to <OH_CANVAS_SAFE_STATE_DIR>/workspaces, which is the sibling of the agent server's <state_dir>/conversations/ persistence dir — both share the same <id_hex> per conversation.
# VITE_WORKER_URLS="" # Optional comma-separated worker URLs for the Browser tab
diff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.ts
index b55a828529..acd819bdc0 100644
--- a/__tests__/api/agent-server-adapter.test.ts
+++ b/__tests__/api/agent-server-adapter.test.ts
@@ -12,6 +12,7 @@ import {
removeStoredConversationMetadata,
setStoredConversationMetadata,
} from "#/api/conversation-metadata-store";
+import { ACP_VERTEX_SAFE_MODEL } from "#/constants/acp-providers";
import { DEFAULT_SETTINGS } from "#/services/settings";
const {
@@ -401,16 +402,12 @@ describe("buildStartConversationRequest", () => {
});
});
- it("mirrors conversation secrets onto agent_settings.agent_context.secrets for ACP", () => {
- // Until canvas pins to an agent-server build that includes
- // software-agent-sdk PR #3299, the bare ``payload.secrets`` channel
- // only reaches ``secret_registry`` server-side — ``ACPAgent``'s
- // spawn-time env loop reads from ``agent_context.secrets``, not
- // from the registry, so a Settings → Secrets entry like
- // ``ANTHROPIC_API_KEY`` would silently fail to land in the ACP
- // CLI's environment. Mirror the same LookupSecret map onto
- // ``agent_settings.agent_context.secrets`` so the existing SDK loop picks
- // it up. Mirrors OpenHands' app-server bridging.
+ it("does NOT mirror conversation secrets onto agent_context for ACP — request.secrets is the sole channel", () => {
+ // The pinned minimum agent-server (1.25.0) 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,
@@ -427,19 +424,13 @@ describe("buildStartConversationRequest", () => {
secrets: Record<string, unknown>;
};
- // Same LookupSecret object lands in both places — the bare-secrets
- // channel (for any non-ACP consumer / for SDK #3299 once it lands)
- // and the agent_context bridge (for current ACPAgent spawns).
expect(payload.secrets.ANTHROPIC_API_KEY).toBeDefined();
- expect(
- payload.agent_settings.agent_context?.secrets?.ANTHROPIC_API_KEY,
- ).toEqual(payload.secrets.ANTHROPIC_API_KEY);
+ 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 — the
- // bridge only fires when there's something to bridge.
+ // ``agent_context.secrets`` map on the ACPAgent payload.
const payload = buildStartConversationRequest({
settings: {
...DEFAULT_SETTINGS,
@@ -473,6 +464,66 @@ describe("buildStartConversationRequest", () => {
expect(payload.agent_settings.agent_context?.secrets).toBeUndefined();
});
+ 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.
+ const payload = buildStartConversationRequest({
+ settings: acpSettings(),
+ 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 }>;
+ };
+
+ 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
+ // (the ≥1.25.0 agent-server 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)", () => {
+ const payload = buildStartConversationRequest({
+ settings: DEFAULT_SETTINGS,
+ secretsEncrypted: true,
+ }) as { secrets_encrypted?: boolean };
+ expect(payload.secrets_encrypted).toBe(true);
+ });
+ });
+
describe("canvas_ui tool injection", () => {
it("always registers canvas_ui_tool in tool_module_qualnames, even when no user settings supply qualnames", () => {
const payload = buildStartConversationRequest({
@@ -1194,6 +1245,26 @@ describe("buildStartConversationRequest — ACP discriminator", () => {
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: {
diff --git a/__tests__/api/cloud/conversation-create.test.ts b/__tests__/api/cloud/conversation-create.test.ts
index 83ea6c1c5d..fc6a4399ed 100644
--- a/__tests__/api/cloud/conversation-create.test.ts
+++ b/__tests__/api/cloud/conversation-create.test.ts
@@ -117,4 +117,46 @@ describe("AgentServerConversationService cloud branch", () => {
expect(result?.status).toBe("READY");
expect(result?.app_conversation_id).toBe("conv-456");
});
+
+ it("wakeRecycledCloudConversation re-provisions under the same conversation id (bootstrap resume)", async () => {
+ const { wakeRecycledCloudConversation } =
+ await import("#/api/cloud/conversation-service.api");
+ vi.mocked(axios.request).mockResolvedValue({
+ data: {
+ id: "task-wake",
+ created_by_user_id: null,
+ status: "WORKING",
+ detail: null,
+ app_conversation_id: null,
+ agent_server_url: null,
+ request: {},
+ created_at: "2026-06-08T00:00:00Z",
+ updated_at: "2026-06-08T00:00:00Z",
+ },
+ });
+
+ const result = await wakeRecycledCloudConversation("conv-existing", {
+ selected_repository: "user/repo",
+ selected_branch: "main",
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ git_provider: "github" as any,
+ });
+
+ const [config] = vi.mocked(axios.request).mock.calls[0]!;
+ expect(config).toMatchObject({
+ url: `${cloudBackend.host}/api/v1/app-conversations`,
+ method: "POST",
+ });
+ const body = (config as { data: Record<string, unknown> }).data;
+ // The same conversation id is carried so the backend rebuilds (and, for
+ // ACP, bootstrap-resumes) the existing conversation rather than minting one.
+ expect(body.conversation_id).toBe("conv-existing");
+ // The repo selection rides along so the rebuilt working dir matches the
+ // original cwd — otherwise an ACP resume can't key off the same project dir.
+ expect(body.selected_repository).toBe("user/repo");
+ expect(body.selected_branch).toBe("main");
+ expect(body.git_provider).toBe("github");
+ expect(result.id).toBe("task-wake");
+ expect(result.status).toBe("WORKING");
+ });
});
diff --git a/__tests__/components/onboarding/choose-agent-step.test.tsx b/__tests__/components/onboarding/choose-agent-step.test.tsx
index fd16ae31fe..08451150da 100644
--- a/__tests__/components/onboarding/choose-agent-step.test.tsx
+++ b/__tests__/components/onboarding/choose-agent-step.test.tsx
@@ -9,7 +9,10 @@ import {
type OnboardingAgentId,
} from "#/components/features/onboarding/steps/choose-agent-step";
import SettingsService from "#/api/settings-service/settings-service.api";
-import { ACP_PROVIDERS } from "#/constants/acp-providers";
+import {
+ ACP_PROVIDERS,
+ getAcpPreferredDefaultModel,
+} from "#/constants/acp-providers";
import { I18nKey } from "#/i18n/declaration";
function renderStep(initial: OnboardingAgentId = "openhands") {
@@ -191,9 +194,13 @@ describe("ChooseAgentStep", () => {
expect(
(call.agent_settings_diff as Record<string, unknown>).acp_server,
).toBe(expected);
+ // Canvas preselects the *preferred* default model — the registry default
+ // for Codex, but the Vertex-safe override (gemini-2.5-pro) for Gemini:
+ // gemini-cli re-resolves flash ids to its own default, which 404s on many
+ // Vertex projects (software-agent-sdk#3532).
expect(
(call.agent_settings_diff as Record<string, unknown>).acp_model,
- ).toBe(ACP_PROVIDERS.find(({ key }) => key === expected)?.default_model);
+ ).toBe(getAcpPreferredDefaultModel(expected));
});
it("rebuilds the diff cleanly when the user flips between ACP providers", async () => {
diff --git a/__tests__/components/onboarding/setup-acp-secrets-step.test.tsx b/__tests__/components/onboarding/setup-acp-secrets-step.test.tsx
index eb8ebc573f..d1c0cd4c5d 100644
--- a/__tests__/components/onboarding/setup-acp-secrets-step.test.tsx
+++ b/__tests__/components/onboarding/setup-acp-secrets-step.test.tsx
@@ -4,9 +4,16 @@ import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
import { ActiveBackendProvider } from "#/contexts/active-backend-context";
-import { SetupAcpSecretsStep } from "#/components/features/onboarding/steps/setup-acp-secrets-step";
+import {
+ SetupAcpSecretsStep,
+ backendRequiresAcpCredentials,
+} from "#/components/features/onboarding/steps/setup-acp-secrets-step";
import { type OnboardingAgentId } from "#/components/features/onboarding/steps/choose-agent-step";
import { SecretsService } from "#/api/secrets-service";
@@ -74,6 +81,10 @@ beforeEach(() => {
vi.spyOn(SecretsService, "createSecret").mockResolvedValue();
});
afterEach(() => {
+ // setRegisteredBackends persists to localStorage, which
+ // __resetActiveStoreForTests re-reads — clear it so a test's backend
+ // registration (e.g. the cloud case) can't leak into the next test.
+ localStorage.clear();
__resetActiveStoreForTests();
});
@@ -265,4 +276,221 @@ describe("SetupAcpSecretsStep", () => {
screen.queryByTestId("onboarding-acp-auth-checking"),
).not.toBeInTheDocument();
});
+
+ it("renders the Codex subscription blob as a multiline textarea", () => {
+ renderStep("codex");
+
+ const blob = screen.getByTestId("onboarding-acp-secret-CODEX_AUTH_JSON");
+ expect(blob.tagName).toBe("TEXTAREA");
+ });
+
+ it("requires credentials (blocks Next) on a logged-out local backend, then unblocks once one is entered", async () => {
+ // local + "unauthenticated" = a fresh container with no host login → the
+ // step is required until the user provides a credential.
+ acpAuthStatusMock.mockReturnValue({
+ status: "unauthenticated",
+ isChecking: false,
+ isSupported: true,
+ });
+ const { onNext, user } = renderStep("claude-code");
+
+ expect(
+ screen.getByTestId("onboarding-acp-secrets-blocked"),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId("onboarding-acp-secrets-next")).toBeDisabled();
+
+ await user.type(
+ screen.getByTestId("onboarding-acp-secret-CLAUDE_CODE_OAUTH_TOKEN"),
+ "oauth-token",
+ );
+
+ expect(
+ screen.queryByTestId("onboarding-acp-secrets-blocked"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByTestId("onboarding-acp-secrets-next"),
+ ).not.toBeDisabled();
+
+ await user.click(screen.getByTestId("onboarding-acp-secrets-next"));
+ await waitFor(() => expect(onNext).toHaveBeenCalledTimes(1));
+ });
+
+ it("does not block Next when the login probe is unknown (permissive for native dev)", () => {
+ acpAuthStatusMock.mockReturnValue({
+ status: "unknown",
+ isChecking: false,
+ isSupported: false,
+ });
+ renderStep("claude-code");
+
+ expect(
+ screen.queryByTestId("onboarding-acp-secrets-blocked"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByTestId("onboarding-acp-secrets-next"),
+ ).not.toBeDisabled();
+ });
+
+ it("stays blocked when only a non-credential field is filled", async () => {
+ // GOOGLE_CLOUD_LOCATION (or a base URL) alone can't authenticate anything —
+ // only a masked ``secret`` field (blob / token / API key) satisfies a
+ // required credential step.
+ acpAuthStatusMock.mockReturnValue({
+ status: "unauthenticated",
+ isChecking: false,
+ isSupported: true,
+ });
+ const { user } = renderStep("gemini-cli");
+
+ await user.type(
+ screen.getByTestId("onboarding-acp-secret-GOOGLE_CLOUD_LOCATION"),
+ "us-central1",
+ );
+
+ expect(
+ screen.getByTestId("onboarding-acp-secrets-blocked"),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId("onboarding-acp-secrets-next")).toBeDisabled();
+
+ await user.type(
+ screen.getByTestId("onboarding-acp-secret-GEMINI_API_KEY"),
+ "AIza-key",
+ );
+
+ expect(
+ screen.queryByTestId("onboarding-acp-secrets-blocked"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("counts a Codex file blob toward the gate on cloud (cloud materialises file secrets)", async () => {
+ // Cloud materialises file-content credentials (Codex auth.json, Gemini
+ // Vertex SA) from the encrypted secret store via agent_context.secrets at
+ // conversation start, so a pasted blob satisfies a required step exactly
+ // like an env-var credential does.
+ setRegisteredBackends([
+ {
+ id: "cloud-1",
+ name: "Cloud",
+ host: "https://app.example.dev",
+ apiKey: "key",
+ kind: "cloud",
+ },
+ ]);
+ setActiveSelection({ backendId: "cloud-1", orgId: null });
+ const { user } = renderStep("codex");
+
+ // Required on cloud, so initially blocked until a credential is supplied.
+ expect(screen.getByTestId("onboarding-acp-secrets-next")).toBeDisabled();
+
+ await user.click(
+ screen.getByTestId("onboarding-acp-secret-CODEX_AUTH_JSON"),
+ );
+ await user.paste('{"tokens":{}}');
+
+ expect(
+ screen.queryByTestId("onboarding-acp-secrets-blocked"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByTestId("onboarding-acp-secrets-next"),
+ ).not.toBeDisabled();
+ });
+
+ it("holds Next while the login probe is still in flight, without the blocked note", async () => {
+ // A fast click must not slip past a gate the probe is about to raise; the
+ // "checking login status" banner already explains the wait. A credential
+ // typed meanwhile releases the hold.
+ acpAuthStatusMock.mockReturnValue({
+ status: "unknown",
+ isChecking: true,
+ isSupported: true,
+ });
+ const { user } = renderStep("claude-code");
+
+ expect(screen.getByTestId("onboarding-acp-secrets-next")).toBeDisabled();
+ // Not "blocked" — just pending classification.
+ expect(
+ screen.queryByTestId("onboarding-acp-secrets-blocked"),
+ ).not.toBeInTheDocument();
+
+ await user.type(
+ screen.getByTestId("onboarding-acp-secret-CLAUDE_CODE_OAUTH_TOKEN"),
+ "oauth-token",
+ );
+
+ expect(
+ screen.getByTestId("onboarding-acp-secrets-next"),
+ ).not.toBeDisabled();
+ });
+
+ it("warns when the Claude OAuth token and base URL are both set (bearer-auth conflict)", async () => {
+ const { user } = renderStep("claude-code");
+
+ expect(
+ screen.queryByTestId("acp-credential-conflict-warning"),
+ ).not.toBeInTheDocument();
+
+ await user.type(
+ screen.getByTestId("onboarding-acp-secret-CLAUDE_CODE_OAUTH_TOKEN"),
+ "oauth-token",
+ );
+ await user.type(
+ screen.getByTestId("onboarding-acp-secret-ANTHROPIC_BASE_URL"),
+ "https://proxy.example.com",
+ );
+
+ expect(
+ screen.getByTestId("acp-credential-conflict-warning"),
+ ).toBeInTheDocument();
+ });
+
+ it("counts an already-saved secret toward the conflict warning", async () => {
+ // A previously saved ANTHROPIC_BASE_URL conflicts just the same as a typed
+ // one — the warning must consider the secret store, not just the form.
+ vi.spyOn(SecretsService, "getSecrets").mockResolvedValue([
+ { name: "ANTHROPIC_BASE_URL" },
+ ]);
+ const { user } = renderStep("claude-code");
+ await waitFor(() =>
+ expect(
+ (
+ screen.getByTestId(
+ "onboarding-acp-secret-ANTHROPIC_BASE_URL",
+ ) as HTMLInputElement
+ ).placeholder.length,
+ ).toBeGreaterThan(0),
+ );
+
+ await user.type(
+ screen.getByTestId("onboarding-acp-secret-CLAUDE_CODE_OAUTH_TOKEN"),
+ "oauth-token",
+ );
+
+ expect(
+ screen.getByTestId("acp-credential-conflict-warning"),
+ ).toBeInTheDocument();
+ });
+});
+
+describe("backendRequiresAcpCredentials", () => {
+ it("never requires credentials when a login is already detected", () => {
+ expect(backendRequiresAcpCredentials("local", "authenticated")).toBe(false);
+ expect(backendRequiresAcpCredentials("cloud", "authenticated")).toBe(false);
+ });
+
+ it("always requires credentials on a cloud backend (no host login)", () => {
+ expect(backendRequiresAcpCredentials("cloud", "unauthenticated")).toBe(
+ true,
+ );
+ expect(backendRequiresAcpCredentials("cloud", "unknown")).toBe(true);
+ });
+
+ it("requires credentials on a logged-out local backend (a fresh container)", () => {
+ expect(backendRequiresAcpCredentials("local", "unauthenticated")).toBe(
+ true,
+ );
+ });
+
+ it("stays permissive on a local backend the probe can't classify", () => {
+ expect(backendRequiresAcpCredentials("local", "unknown")).toBe(false);
+ });
});
diff --git a/__tests__/components/settings/acp-credentials-section.test.tsx b/__tests__/components/settings/acp-credentials-section.test.tsx
new file mode 100644
index 0000000000..9f364bb074
--- /dev/null
+++ b/__tests__/components/settings/acp-credentials-section.test.tsx
@@ -0,0 +1,158 @@
+import React from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import { ActiveBackendProvider } from "#/contexts/active-backend-context";
+import { AcpCredentialsSection } from "#/components/features/settings/acp-credentials-section";
+import { SecretsService } from "#/api/secrets-service";
+
+// Observe the save outcome (success vs orphaned-credential warning) without
+// rendering real toasts.
+const toastMocks = vi.hoisted(() => ({
+ success: vi.fn(),
+ warning: vi.fn(),
+ error: vi.fn(),
+}));
+vi.mock("#/utils/custom-toast-handlers", () => ({
+ displaySuccessToast: toastMocks.success,
+ displayWarningToast: toastMocks.warning,
+ displayErrorToast: toastMocks.error,
+}));
+
+function renderSection(providerKey: string) {
+ const user = userEvent.setup();
+ render(
+ <QueryClientProvider
+ client={
+ new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ }
+ >
+ <ActiveBackendProvider>
+ <AcpCredentialsSection providerKey={providerKey} />
+ </ActiveBackendProvider>
+ </QueryClientProvider>,
+ );
+ return { user };
+}
+
+function useCloudBackend() {
+ setRegisteredBackends([
+ {
+ id: "cloud-1",
+ name: "Cloud",
+ host: "https://app.example.dev",
+ apiKey: "key",
+ kind: "cloud",
+ },
+ ]);
+ setActiveSelection({ backendId: "cloud-1", orgId: null });
+}
+
+beforeEach(() => {
+ vi.restoreAllMocks();
+ toastMocks.success.mockClear();
+ toastMocks.warning.mockClear();
+ toastMocks.error.mockClear();
+ __resetActiveStoreForTests();
+ vi.spyOn(SecretsService, "getSecrets").mockResolvedValue([]);
+ vi.spyOn(SecretsService, "createSecret").mockResolvedValue();
+});
+afterEach(() => {
+ __resetActiveStoreForTests();
+});
+
+describe("AcpCredentialsSection", () => {
+ it("renders the provider's credential fields (blob as textarea, key as password)", () => {
+ renderSection("codex");
+
+ const blob = screen.getByTestId("settings-acp-secret-CODEX_AUTH_JSON");
+ expect(blob.tagName).toBe("TEXTAREA");
+ expect(
+ screen.getByTestId("settings-acp-secret-OPENAI_API_KEY"),
+ ).toHaveAttribute("type", "password");
+ // Pristine form — nothing to save yet.
+ expect(screen.getByTestId("acp-credentials-save-button")).toBeDisabled();
+ });
+
+ it("renders nothing for a provider without credential fields", () => {
+ renderSection("custom");
+ expect(
+ screen.queryByTestId("acp-credentials-save-button"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("saves the filled fields as secrets and resets the form", async () => {
+ const { user } = renderSection("claude-code");
+
+ await user.type(
+ screen.getByTestId("settings-acp-secret-ANTHROPIC_API_KEY"),
+ "sk-ant-123",
+ );
+ await user.click(screen.getByTestId("acp-credentials-save-button"));
+
+ await waitFor(() => {
+ expect(SecretsService.createSecret).toHaveBeenCalledWith(
+ "ANTHROPIC_API_KEY",
+ "sk-ant-123",
+ undefined,
+ );
+ expect(toastMocks.success).toHaveBeenCalledTimes(1);
+ });
+ expect(
+ (
+ screen.getByTestId(
+ "settings-acp-secret-ANTHROPIC_API_KEY",
+ ) as HTMLInputElement
+ ).value,
+ ).toBe("");
+ });
+
+ it("warns when the Claude OAuth token and base URL are both set", async () => {
+ const { user } = renderSection("claude-code");
+
+ await user.type(
+ screen.getByTestId("settings-acp-secret-CLAUDE_CODE_OAUTH_TOKEN"),
+ "oauth-token",
+ );
+ expect(
+ screen.queryByTestId("acp-credential-conflict-warning"),
+ ).not.toBeInTheDocument();
+
+ await user.type(
+ screen.getByTestId("settings-acp-secret-ANTHROPIC_BASE_URL"),
+ "https://proxy.example.com",
+ );
+ expect(
+ screen.getByTestId("acp-credential-conflict-warning"),
+ ).toBeInTheDocument();
+ });
+
+ it("toasts success when a file credential is saved on a cloud backend (cloud materialises file secrets)", async () => {
+ // Cloud materialises file-content credentials from the encrypted secret
+ // store via agent_context.secrets at conversation start, so a saved blob is
+ // consumable — no orphaned-credential warning.
+ useCloudBackend();
+ const { user } = renderSection("codex");
+
+ await user.click(screen.getByTestId("settings-acp-secret-CODEX_AUTH_JSON"));
+ await user.paste('{"tokens":{}}');
+ await user.click(screen.getByTestId("acp-credentials-save-button"));
+
+ await waitFor(() => {
+ expect(SecretsService.createSecret).toHaveBeenCalledWith(
+ "CODEX_AUTH_JSON",
+ '{"tokens":{}}',
+ undefined,
+ );
+ expect(toastMocks.success).toHaveBeenCalled();
+ });
+ expect(toastMocks.warning).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/constants/acp-providers.test.ts b/__tests__/constants/acp-providers.test.ts
index fb61c78cdb..769d559239 100644
--- a/__tests__/constants/acp-providers.test.ts
+++ b/__tests__/constants/acp-providers.test.ts
@@ -2,8 +2,13 @@ import { describe, expect, it } from "vitest";
import {
ACP_CUSTOM_PRESET_KEY,
ACP_PROVIDERS,
+ ACP_VERTEX_SAFE_MODEL,
buildAcpAgentSettingsDiff,
+ getAcpCredentialConflicts,
+ getAcpPreferredDefaultModel,
+ getAcpProvider,
getAcpProviderDisplayName,
+ getAcpProviderSecrets,
} from "#/constants/acp-providers";
describe("getAcpProviderDisplayName", () => {
@@ -57,14 +62,21 @@ describe("ACP provider registry", () => {
}
});
- it("seeds built-in ACP diffs with the provider default model", () => {
+ it("seeds built-in ACP diffs with the provider's preferred default model", () => {
+ // Preferred default = registry default everywhere except Gemini, where
+ // the Vertex-safe override applies (see getAcpPreferredDefaultModel) —
+ // EVERY default-model surface must agree on this, including this diff
+ // builder's fallback.
for (const provider of ACP_PROVIDERS) {
expect(buildAcpAgentSettingsDiff(provider.key)).toMatchObject({
agent_kind: "acp",
acp_server: provider.key,
- acp_model: provider.default_model,
+ acp_model: getAcpPreferredDefaultModel(provider.key),
});
}
+ expect(buildAcpAgentSettingsDiff("gemini-cli")).toMatchObject({
+ acp_model: ACP_VERTEX_SAFE_MODEL,
+ });
});
it("keeps custom ACP diffs model-optional", () => {
@@ -75,3 +87,143 @@ describe("ACP provider registry", () => {
});
});
});
+
+describe("getAcpProviderSecrets — containerized credentials", () => {
+ // These are the credentials a fresh container (no host login) needs, sourced
+ // from the validated container contract (agent-canvas#1013/#1014) — if a
+ // refactor drops one, ACP auth in a container silently breaks, so assert
+ // each provider's exact field set.
+ it("collects the subscription cred, api key, then base URL — in that order — for Codex", () => {
+ const names = getAcpProviderSecrets("codex").map((f) => f.name);
+ expect(names).toEqual([
+ "CODEX_AUTH_JSON",
+ "OPENAI_API_KEY",
+ "OPENAI_BASE_URL",
+ ]);
+ });
+
+ it("collects the OAuth token + api key for Claude Code", () => {
+ const names = getAcpProviderSecrets("claude-code").map((f) => f.name);
+ expect(names).toEqual([
+ "CLAUDE_CODE_OAUTH_TOKEN",
+ "ANTHROPIC_API_KEY",
+ "ANTHROPIC_BASE_URL",
+ ]);
+ });
+
+ it("collects the Vertex SA JSON + project/location/flag for Gemini CLI", () => {
+ const names = getAcpProviderSecrets("gemini-cli").map((f) => f.name);
+ expect(names).toEqual([
+ "GOOGLE_APPLICATION_CREDENTIALS_JSON",
+ "GOOGLE_CLOUD_PROJECT",
+ "GOOGLE_CLOUD_LOCATION",
+ "GOOGLE_GENAI_USE_VERTEXAI",
+ "GEMINI_API_KEY",
+ "GEMINI_BASE_URL",
+ ]);
+ });
+
+ it("renders file-content blobs as multiline secret fields", () => {
+ // ``multiline`` also drives the orphaned-credential warning on backends
+ // that can't materialise file secrets (cloud, agent-canvas#1016).
+ const codexBlob = getAcpProviderSecrets("codex").find(
+ (f) => f.name === "CODEX_AUTH_JSON",
+ );
+ expect(codexBlob).toMatchObject({ multiline: true, secret: true });
+
+ const geminiBlob = getAcpProviderSecrets("gemini-cli").find(
+ (f) => f.name === "GOOGLE_APPLICATION_CREDENTIALS_JSON",
+ );
+ expect(geminiBlob).toMatchObject({ multiline: true, secret: true });
+ });
+
+ it("never marks the base URL as a credential (not secret, not multiline)", () => {
+ // ``secret`` is what a required credential step counts as an actual
+ // credential — a base URL alone can't authenticate, and ANTHROPIC_BASE_URL
+ // alongside a Claude OAuth token actively breaks bearer auth.
+ for (const key of ["codex", "claude-code", "gemini-cli"]) {
+ const baseUrl = getAcpProviderSecrets(key).find((f) =>
+ f.name.endsWith("_BASE_URL"),
+ );
+ expect(baseUrl?.secret, key).toBeFalsy();
+ expect(baseUrl?.multiline, key).toBeFalsy();
+ }
+ });
+
+ it("returns [] for OpenHands / custom / unknown / empty", () => {
+ expect(getAcpProviderSecrets("openhands")).toEqual([]);
+ expect(getAcpProviderSecrets(ACP_CUSTOM_PRESET_KEY)).toEqual([]);
+ expect(getAcpProviderSecrets("future-acp-server")).toEqual([]);
+ expect(getAcpProviderSecrets(null)).toEqual([]);
+ });
+});
+
+describe("getAcpPreferredDefaultModel", () => {
+ it("overrides Gemini with the Vertex-safe model rather than the registry default", () => {
+ // gemini-cli's own default 404s on many Vertex projects; canvas preselects
+ // a broadly-available model instead.
+ expect(getAcpPreferredDefaultModel("gemini-cli")).toBe(
+ ACP_VERTEX_SAFE_MODEL,
+ );
+ expect(getAcpPreferredDefaultModel("gemini-cli")).not.toBe(
+ getAcpProvider("gemini-cli")?.default_model,
+ );
+ });
+
+ it("pins a NON-flash Gemini model", () => {
+ // gemini-cli 0.45.x re-resolves any *-flash id at generation time to its
+ // current default flash (software-agent-sdk#3532), so a flash pin is not
+ // honored — only a non-flash id (e.g. gemini-2.5-pro) sticks.
+ expect(ACP_VERTEX_SAFE_MODEL).not.toMatch(/flash/);
+ });
+
+ it("keeps the registry default for the other providers", () => {
+ expect(getAcpPreferredDefaultModel("codex")).toBe(
+ getAcpProvider("codex")?.default_model,
+ );
+ expect(getAcpPreferredDefaultModel("claude-code")).toBe(
+ getAcpProvider("claude-code")?.default_model,
+ );
+ });
+
+ it("returns null for OpenHands / custom / unknown", () => {
+ expect(getAcpPreferredDefaultModel("openhands")).toBeNull();
+ expect(getAcpPreferredDefaultModel(ACP_CUSTOM_PRESET_KEY)).toBeNull();
+ expect(getAcpPreferredDefaultModel("future-acp-server")).toBeNull();
+ });
+});
+
+describe("getAcpCredentialConflicts", () => {
+ const has =
+ (...names: string[]) =>
+ (name: string) =>
+ names.includes(name);
+
+ it("flags the Claude OAuth token + base URL pair when both are set", () => {
+ expect(
+ getAcpCredentialConflicts(
+ "claude-code",
+ has("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL"),
+ ),
+ ).toEqual([["CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL"]]);
+ });
+
+ it("stays quiet when only one side is set", () => {
+ expect(
+ getAcpCredentialConflicts("claude-code", has("CLAUDE_CODE_OAUTH_TOKEN")),
+ ).toEqual([]);
+ expect(
+ getAcpCredentialConflicts("claude-code", has("ANTHROPIC_BASE_URL")),
+ ).toEqual([]);
+ });
+
+ it("has no conflicts for other providers / null", () => {
+ expect(
+ getAcpCredentialConflicts(
+ "codex",
+ has("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL"),
+ ),
+ ).toEqual([]);
+ expect(getAcpCredentialConflicts(null, () => true)).toEqual([]);
+ });
+});
diff --git a/docs/ACP_AGENTS.md b/docs/ACP_AGENTS.md
index 8ca5c95338..1baf017ae1 100644
--- a/docs/ACP_AGENTS.md
+++ b/docs/ACP_AGENTS.md
@@ -100,15 +100,26 @@ First-time users get a four-step onboarding modal. To onboard an ACP agent:
1. **Choose agent** — pick Claude Code, Codex, or Gemini CLI instead of
OpenHands. The choice is saved immediately to your backend's settings.
2. **Check backend** — confirms Agent Canvas can reach the Agent Server.
-3. **Set up credentials** — enter the provider's API key (and, optionally, a
- custom base URL for a proxy or gateway). All three providers — Claude Code,
- Codex, and Gemini CLI — collect these here, and every field is optional.
+3. **Set up credentials** — enter the provider's credentials. Beyond the API
+ key (+ optional base URL), this step also collects the credentials a
+ *containerized* backend needs, since a fresh container has no host login:
+ - **Codex** — `CODEX_AUTH_JSON` (the contents of `~/.codex/auth.json`).
+ - **Claude Code** — `CLAUDE_CODE_OAUTH_TOKEN` (a Pro/Max OAuth token).
+ - **Gemini CLI** — `GOOGLE_APPLICATION_CREDENTIALS_JSON` (Vertex SA / ADC JSON)
+ plus `GOOGLE_CLOUD_PROJECT`, `GOOGLE_CLOUD_LOCATION`, and
+ `GOOGLE_GENAI_USE_VERTEXAI`.
+
+ On a **local** backend the step is optional (a host login is reused
+ automatically); on a **Docker / cloud** backend it's **required**, because
+ there's no host login to fall back on. When the login probe detects an
+ existing session, the step shows a "you're already signed in" banner and
+ stays skippable.
4. **Say hello** — creates your first conversation and closes the modal.
> [!NOTE]
-> Every credential field is optional and the step is skippable. Leave a field
-> blank to reuse a key already set on the backend, or to authenticate the agent
-> through a subscription / OAuth login instead.
+> On a local backend every credential field is optional and the step is
+> skippable. Leave a field blank to reuse a key already set on the backend, or to
+> authenticate the agent through a subscription / OAuth login instead.
### How credentials reach the agent
@@ -119,6 +130,87 @@ under **Settings → Secrets**, where you can edit or remove it anytime. Keeping
the secret name equal to the env var is what makes a saved key actually reach the
provider CLI.
+## Running ACP agents in a Docker container
+
+The walkthrough above assumes the Agent Server runs on your own machine, where
+the provider CLIs reuse a host login. You can also run the Agent Server **in a
+container** — Canvas drives it the same way, but since a fresh container has no
+host login, you supply credentials through the UI and Canvas sends them inline
+on the conversation start request.
+
+A ready-to-run setup lives in
+[`examples/acp-docker/`](../examples/acp-docker/) (`docker compose up`, then
+point Canvas at it). In short:
+
+```bash
+# 1. Agent Server in a container (CORS allows localhost, so the browser talks
+# to it directly). The image pre-installs the ACP CLI wrappers. The
+# canvas_ui tool is mounted so the agent-server can import the module Canvas
+# references in every start request.
+# Minimum image: 1.25.0-python (first release with software-agent-sdk#3510;
+# older images deadlock the first ACP turn). Override SHA with a newer build.
+docker run -d --name oh-acp -p 8010:8000 -v acp-data:/workspace \
+ -v "$(pwd)/tools:/canvas-tools:ro" -e OH_EXTRA_PYTHON_PATH=/canvas-tools \
+ ghcr.io/openhands/agent-server:1.25.0-python
+
+# 2. Canvas pointed at the container.
+VITE_BACKEND_BASE_URL=http://localhost:8010 npm run dev:frontend
+```
+
+### How credentials reach a containerized agent
+
+In onboarding's **Set up credentials** step, the credentials you enter are saved
+as global secrets in the agent-server's secret store (as usual). The start
+request then references each as a **`LookupSecret`** — uniformly for ACP and
+non-ACP — and the agent-server resolves the value back from its own store at
+spawn time. For ACP this resolution runs **off the event loop**
+(software-agent-sdk#3510), so the loopback fetch does not self-deadlock. The
+SDK's `acp_file_secrets` defaults then:
+
+- materialise `CODEX_AUTH_JSON` back to `auth.json` under `CODEX_HOME` and point
+ Codex at it;
+- materialise `GOOGLE_APPLICATION_CREDENTIALS_JSON` to a file referenced by
+ `GOOGLE_APPLICATION_CREDENTIALS` and route Gemini through Vertex AI;
+- export the rest (`CLAUDE_CODE_OAUTH_TOKEN`, project/location, API keys) as env
+ vars for the CLI.
+
+Canvas just sends the secrets — it does **not** hand-roll the file
+materialisation. The `npx -y <pkg>` command is rewritten to the pinned
+pre-installed binary inside the container by the SDK, so no command change is
+needed.
+
+> [!IMPORTANT]
+> **Do not set `ANTHROPIC_BASE_URL` alongside the Claude OAuth token.** An
+> inherited LiteLLM base URL silently breaks the token's bearer auth (it routes
+> the request away from Anthropic). Canvas never derives a base-URL secret from
+> your LLM settings — but a base URL you save yourself rides along on every
+> start request like any other saved secret, which is why the credential forms
+> warn when both are set. Only set it deliberately, and not with the OAuth path.
+
+> [!IMPORTANT]
+> **Gemini Vertex needs a fresh ADC.** Run `gcloud auth application-default login`
+> before copying `~/.config/gcloud/application_default_credentials.json` — a stale
+> token surfaces as `invalid_rapt`, which is a credential problem, not a Canvas
+> bug.
+
+> [!NOTE]
+> **Pick a non-flash Gemini model.** gemini-cli 0.45.x re-resolves any `*-flash`
+> model id at generation time to its *current default* flash (e.g.
+> `gemini-2.5-flash` silently ran `gemini-3-flash`, which 404s on projects that
+> don't serve it — software-agent-sdk#3532). Only a non-flash id sticks, so
+> Canvas preselects `gemini-2.5-pro`. If a Gemini turn fails with
+> `Publisher Model … was not found`, check the selected model isn't a flash id.
+
+### Per-conversation isolation
+
+Concurrent same-provider conversations in one container share a HOME, so they can
+race on the CLI's auth/config/lock files. The SDK supports opting into a
+per-conversation data dir (`acp_isolate_data_dir`, software-agent-sdk#3492), but
+the released `@openhands/typescript-client` does not yet expose it on
+`ACPAgentSettings`, so Canvas can't send it without risking a validation error on
+older servers. This is tracked as a follow-up (agent-canvas#1019); cloud
+grouping isolation is separate (agent-canvas#1016).
+
## Switching agent or model later
Open **Settings → Agent** at any time:
diff --git a/examples/acp-docker/.env.example b/examples/acp-docker/.env.example
new file mode 100644
index 0000000000..e129a73beb
--- /dev/null
+++ b/examples/acp-docker/.env.example
@@ -0,0 +1,37 @@
+# Example environment for examples/acp-docker/docker-compose.yml.
+# Copy to `.env` in this directory. Everything here is OPTIONAL — the
+# recommended path is to enter credentials in Canvas's onboarding "Set up
+# credentials" step (they ride the conversation start request as secrets).
+# Set values here only if you want them baked into the container instead.
+
+# Pin the agent-server image. Default in docker-compose.yml is 1.25.0-python,
+# the first release that includes software-agent-sdk#3510 (required — Canvas
+# delivers ACP creds as loopback LookupSecrets that only #3510 resolves without
+# deadlocking). Bump to a newer release, or a post-#3510 main commit:
+# gh api repos/OpenHands/software-agent-sdk/commits/main --jq '.sha[0:7]'
+# AGENT_SERVER_IMAGE=ghcr.io/openhands/agent-server:1.25.0-python
+
+# --- Claude Code ---
+# A Pro/Max OAuth token, OR an API key. Do NOT set ANTHROPIC_BASE_URL with the
+# OAuth token — an inherited base URL breaks bearer auth (see docs/ACP_AGENTS.md).
+# CLAUDE_CODE_OAUTH_TOKEN=
+# ANTHROPIC_API_KEY=
+
+# --- Codex ---
+# Subscription auth.json is supplied via Canvas (CODEX_AUTH_JSON); for an API
+# key instead:
+# OPENAI_API_KEY=
+
+# --- Gemini CLI (Vertex AI) ---
+# The service-account / ADC JSON is supplied via Canvas
+# (GOOGLE_APPLICATION_CREDENTIALS_JSON). These scalars can live here or in Canvas:
+# GOOGLE_CLOUD_PROJECT=
+# GOOGLE_CLOUD_LOCATION=us-central1
+# GOOGLE_GENAI_USE_VERTEXAI=true
+# Or the API-key path:
+# GEMINI_API_KEY=
+
+# --- Auth (optional) ---
+# Require a session key on the backend; mirror it into Canvas as
+# VITE_SESSION_API_KEY. Leave unset for an open local backend.
+# SESSION_API_KEY=
diff --git a/examples/acp-docker/README.md b/examples/acp-docker/README.md
new file mode 100644
index 0000000000..538f619e4b
--- /dev/null
+++ b/examples/acp-docker/README.md
@@ -0,0 +1,86 @@
+# Containerized ACP agent-server for Agent Canvas
+
+Run an ACP agent (Codex / Claude Code / Gemini CLI) against a **containerized**
+Agent Server and drive it from Agent Canvas, with credentials supplied through
+the Canvas UI. This is the local-Docker counterpart of the cloud path — a fresh
+container has no host CLI login, so credentials come from you instead.
+
+See [`../../docs/ACP_AGENTS.md`](../../docs/ACP_AGENTS.md#running-acp-agents-in-a-docker-container)
+for the full walkthrough; this is the quick start.
+
+## 1. Bring up the agent-server
+
+```bash
+cd examples/acp-docker
+cp .env.example .env # optional — only if baking creds into the container
+docker compose up
+```
+
+This starts `ghcr.io/openhands/agent-server:1.25.0-python` on
+`http://localhost:8010` with a persistent `acp-data` volume. The image
+pre-installs the ACP CLI wrappers and the SDK rewrites `npx -y <pkg>` to those
+pinned binaries in-pod, so Canvas can keep sending the default `npx` command
+unchanged.
+
+> **Minimum version:** `1.25.0-python`. Canvas delivers every ACP credential as
+> a loopback `LookupSecret`; only software-agent-sdk#3510 (first released in
+> v1.25.0) resolves it off the event loop. An older image deadlocks the first
+> ACP turn with `Failed to start ACP server: timed out`.
+
+To pin a newer release or a post-#3510 main build:
+
+```bash
+AGENT_SERVER_IMAGE=ghcr.io/openhands/agent-server:$(gh api repos/OpenHands/software-agent-sdk/commits/main --jq '.sha[0:7]')-python docker compose up
+```
+
+## 2. Point Canvas at it
+
+```bash
+cd ../.. # repo root
+VITE_BACKEND_BASE_URL=http://localhost:8010 npm run dev:frontend
+```
+
+The image's CORS allows `localhost`, so the browser talks to the container
+directly. (You can also add it as a backend in the Canvas backend selector with
+host `http://localhost:8010`.)
+
+## 3. Onboard with credentials
+
+Pick the ACP provider in onboarding and fill in the **Set up credentials** step.
+On a containerized backend this step is **required** (there's no host login to
+fall back on):
+
+| Provider | What to paste |
+|---|---|
+| **Codex** (subscription) | `CODEX_AUTH_JSON` — the full contents of `~/.codex/auth.json` |
+| **Claude Code** (subscription) | `CLAUDE_CODE_OAUTH_TOKEN` — your Pro/Max OAuth token |
+| **Gemini CLI** (Vertex) | `GOOGLE_APPLICATION_CREDENTIALS_JSON` (SA / ADC JSON) + `GOOGLE_CLOUD_PROJECT` + `GOOGLE_CLOUD_LOCATION` + `GOOGLE_GENAI_USE_VERTEXAI=true` |
+
+Each provider also accepts an API-key path (`OPENAI_API_KEY` / `ANTHROPIC_API_KEY` /
+`GEMINI_API_KEY`). Canvas saves these to the agent-server's secret store and the
+start request references them as `LookupSecret`s; the SDK resolves each value at
+spawn time (off the event loop, per #3510), materialises the `*_JSON` blobs to
+disk, and points the CLI's data-dir env at them automatically.
+
+> ⚠️ **Do not set `ANTHROPIC_BASE_URL` with the Claude OAuth token.** An inherited
+> LiteLLM base URL silently breaks bearer auth. Canvas never sets it for you, but
+> a *saved* `ANTHROPIC_BASE_URL` secret rides along on every start request — the
+> credential form warns about the pair.
+
+> ⚠️ **Gemini Vertex ADC must be freshly logged in.** Run
+> `gcloud auth application-default login` — a stale token returns `invalid_rapt`.
+
+> ℹ️ **Baked creds in `.env` may not satisfy the onboarding gate.** The login
+> probe checks CLI login state (`claude auth status` / `codex login status` /
+> Gemini's OAuth credentials file), not container env vars — a container with
+> only e.g. `GEMINI_API_KEY` baked via `.env` typically still probes as
+> logged-out, and the credentials step then blocks "Next". Enter (or re-enter)
+> a credential in the UI to proceed; the baked env var still works for the
+> agent itself.
+
+## Tear down
+
+```bash
+docker compose down # keep the volume
+docker compose down -v # also drop credentials/conversations
+```
diff --git a/examples/acp-docker/docker-compose.yml b/examples/acp-docker/docker-compose.yml
new file mode 100644
index 0000000000..aa6ac30601
--- /dev/null
+++ b/examples/acp-docker/docker-compose.yml
@@ -0,0 +1,80 @@
+# Containerized ACP agent-server for Agent Canvas (agent-canvas#1014).
+#
+# Brings up the OpenHands Agent Server image — which pre-installs the ACP CLI
+# wrappers (claude-agent-acp / codex-acp / gemini) — with a persistent volume so
+# conversations and materialised credential files survive restarts. Point Canvas
+# at it with VITE_BACKEND_BASE_URL=http://localhost:8010 (the image's CORS allows
+# localhost, so the browser talks to it directly).
+#
+# 1. Copy .env.example to .env and fill in the credentials for the provider(s)
+# you want to run (see that file + ../../docs/ACP_AGENTS.md → "Running ACP
+# agents in a Docker container").
+# 2. `docker compose up` (from this directory)
+# 3. Run Canvas pointed at it: VITE_BACKEND_BASE_URL=http://localhost:8010 npm run dev:frontend
+#
+# The credentials below are read from your shell/.env and handed to Canvas via
+# the onboarding "Set up credentials" step; this file only needs them if you
+# prefer to bake host logins into the container instead of entering them in the
+# UI. Leave them unset to supply everything through Canvas.
+
+services:
+ agent-server:
+ # Pin to a software-agent-sdk release that includes the containerized ACP
+ # merges (#1020 file-secret materialisation, #3490 npx→pinned-binary, #3492
+ # per-conversation data-dir) AND #3510 (ACP cold-start off the event loop),
+ # which is REQUIRED: Canvas now delivers every ACP credential as a loopback
+ # LookupSecret, and only #3510 resolves it without self-deadlocking the
+ # conversation ("Failed to start ACP server: timed out"). #3510 first ships
+ # in v1.25.0, so 1.25.0-python is the minimum. Override with a newer release
+ # or a post-#3510 main sha:
+ # AGENT_SERVER_IMAGE=ghcr.io/openhands/agent-server:<sha>-python docker compose up
+ # gh api repos/OpenHands/software-agent-sdk/commits/main --jq '.sha[0:7]'
+ image: ${AGENT_SERVER_IMAGE:-ghcr.io/openhands/agent-server:1.25.0-python}
+ container_name: oh-acp
+ ports:
+ # host:container — Canvas points VITE_BACKEND_BASE_URL at http://localhost:8010.
+ - "8010:8000"
+ environment:
+ # Canvas's start request always references the bundled ``canvas_ui`` tool
+ # via ``tool_module_qualnames``; the agent-server imports that module from
+ # OH_EXTRA_PYTHON_PATH at conversation creation. Without the mount below +
+ # this var, conversation creation fails to import ``canvas_ui_tool``.
+ - OH_EXTRA_PYTHON_PATH=/canvas-tools
+ # Optional cipher key. ACP conversations work without it (Canvas sends ACP
+ # provider credentials as loopback LookupSecrets resolved from the
+ # agent-server's own secret store, and does NOT flag the request
+ # secrets_encrypted). Set it to (a) persist saved secrets across
+ # container restarts and (b) enable the encrypted-settings path used by
+ # OpenHands-agent (non-ACP) conversations. Generate one with
+ # `python -c "import secrets;print(secrets.token_urlsafe(32))"`.
+ # - OH_SECRET_KEY=${OH_SECRET_KEY}
+ #
+ # The agent-server's CORS already allows localhost origins, so no extra
+ # config is needed for the browser to reach it directly.
+ #
+ # Optionally bake provider logins into the container instead of entering
+ # them in the Canvas onboarding step. These are passed through from .env;
+ # unset values are simply not exported. NOTE: the recommended path is to
+ # enter credentials in Canvas (they ride the start request as secrets) —
+ # this is here for non-interactive / CI setups.
+ - ANTHROPIC_API_KEY
+ - CLAUDE_CODE_OAUTH_TOKEN
+ - OPENAI_API_KEY
+ - GEMINI_API_KEY
+ - GOOGLE_CLOUD_PROJECT
+ - GOOGLE_CLOUD_LOCATION
+ - GOOGLE_GENAI_USE_VERTEXAI
+ # Set a session key to require auth; mirror it into Canvas via
+ # VITE_SESSION_API_KEY. Leave unset for an open local backend.
+ # - SESSION_API_KEY
+ volumes:
+ # Persist conversations AND the credential files the SDK materialises
+ # (Codex auth.json under CODEX_HOME, Gemini ADC/SA JSON) across restarts.
+ - acp-data:/workspace
+ # Canvas-specific Python tools (the canvas_ui tool) the agent-server loads
+ # via OH_EXTRA_PYTHON_PATH. Path is relative to this compose file.
+ - ../../tools:/canvas-tools:ro
+ restart: unless-stopped
+
+volumes:
+ acp-data:
diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.ts
index b08b782e41..2e06ec0d7d 100644
--- a/src/api/agent-server-adapter.ts
+++ b/src/api/agent-server-adapter.ts
@@ -4,6 +4,7 @@ import { DEFAULT_SETTINGS } from "#/services/settings";
import { ExecutionStatus } from "#/types/agent-server/core";
import { Settings, SettingsValue } from "#/types/settings";
import {
+ getAcpPreferredDefaultModel,
getAcpProvider,
resolveEffectiveAcpModel,
} from "#/constants/acp-providers";
@@ -638,11 +639,18 @@ function buildConfiguredAcpAgentSettings(
agent_context: buildAgentContext(agentSettings),
};
+ // 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 agent_context.secrets.
+ // ``acp_env`` is deprecated — provider creds now route via ``request.secrets``.
if (key === "acp_env") continue;
const value =
key === "acp_command"
@@ -664,18 +672,17 @@ function buildConfiguredAcpAgentSettings(
// Saved settings may carry ``acp_model: null`` (existing users predating
// the default-model registry, or saved fields the agent-server stripped).
- // Fall back to the provider's ``default_model`` so the conversation starts
- // with whatever the Settings → Agent UI shows — without that, the form's
- // displayed default would silently not take effect at runtime until the
- // user re-saved the page.
+ // Fall back to the *preferred* default (Vertex-safe for Gemini) so the
+ // conversation starts with whatever the Settings → Agent UI shows — without
+ // that, the form's displayed default would silently not take effect at
+ // runtime until the user re-saved the page.
const serverKey =
typeof agentSettings.acp_server === "string"
? agentSettings.acp_server
: undefined;
- const provider = getAcpProvider(serverKey);
const effectiveModel = resolveEffectiveAcpModel({
configured: agentSettings.acp_model as string | null | undefined,
- providerDefault: provider?.default_model,
+ providerDefault: getAcpPreferredDefaultModel(serverKey),
});
if (effectiveModel) {
payload.acp_model = effectiveModel;
@@ -858,7 +865,14 @@ export function buildStartConversationRequest(
payload.tags = { [ACP_SERVER_TAG_KEY]: acpServerTag };
}
- if (options.secretsEncrypted) {
+ // ``secrets_encrypted`` makes the agent-server run every request secret through
+ // ``cipher.decrypt()`` at conversation start. Suppress it for ACP: an ACP agent
+ // carries no encrypted payload (no LLM api_key, and credentials ride as
+ // LookupSecrets whose values are fetched at resolution time, not decrypted), so
+ // there is nothing to decrypt. Claiming otherwise hard-fails ("cipher not
+ // configured") on a backend without ``OH_SECRET_KEY`` (e.g. a fresh ACP
+ // container). Non-ACP conversations still need it for their encrypted LLM key.
+ if (options.secretsEncrypted && !acpMode) {
payload.secrets_encrypted = true;
}
@@ -895,6 +909,11 @@ export function buildStartConversationRequest(
payload.agent_definitions = conversationSettings.agent_definitions;
}
+ // Every saved secret rides as a LookupSecret the agent-server resolves back
+ // from its own store at spawn time — ``request.secrets`` is the sole channel,
+ // uniform for ACP and non-ACP (agent-canvas#1039). For ACP the resolution
+ // runs off the event loop (software-agent-sdk#3510, ≥1.25.0), so the loopback
+ // fetch can't deadlock.
if (options.customSecrets && options.customSecrets.length > 0) {
const backend = getEffectiveLocalBackend();
const headers = backend ? buildAuthHeaders(backend) : {};
@@ -915,13 +934,6 @@ export function buildStartConversationRequest(
}
payload.secrets = secrets;
-
- if (acpMode) {
- payload.agent_settings.agent_context = {
- ...payload.agent_settings.agent_context,
- secrets,
- };
- }
}
return payload;
diff --git a/src/api/cloud/conversation-service.api.ts b/src/api/cloud/conversation-service.api.ts
index 894e54b5ca..44f837afcc 100644
--- a/src/api/cloud/conversation-service.api.ts
+++ b/src/api/cloud/conversation-service.api.ts
@@ -220,6 +220,43 @@ export async function resumeCloudSandbox(sandboxId: string): Promise<void> {
});
}
+/**
+ * Wake a conversation whose sandbox was recycled (STOPPED/MISSING, not just
+ * PAUSED). Unlike `resumeCloudSandbox`, a recycled sandbox no longer exists, so
+ * a fresh one must be provisioned by re-issuing the conversation-start with the
+ * SAME `conversation_id`. The backend rebuilds the conversation keyed on that
+ * id and, for ACP, resumes it from the durable event store via a bootstrap
+ * prompt (OpenHands#14640) so the agent continues with prior context rather
+ * than starting over. Returns a WORKING task the caller polls to READY (same
+ * lifecycle as a fresh create).
+ *
+ * The repo selection is carried so the rebuilt sandbox's working dir matches
+ * the original conversation's cwd — an ACP resume keys off cwd, so a repo-backed
+ * conversation woken without it would resolve a different project dir.
+ */
+export async function wakeRecycledCloudConversation(
+ conversationId: string,
+ repoSelection?: {
+ selected_repository?: string | null;
+ selected_branch?: string | null;
+ git_provider?: AppConversationStartRequest["git_provider"];
+ },
+): Promise<AppConversationStartTask> {
+ const backend = getActiveCloudBackend();
+ const body: AppConversationStartRequest = {
+ conversation_id: conversationId,
+ selected_repository: repoSelection?.selected_repository ?? null,
+ selected_branch: repoSelection?.selected_branch ?? null,
+ git_provider: repoSelection?.git_provider ?? null,
+ };
+ return callCloudProxy<AppConversationStartTask>({
+ backend,
+ method: "POST",
+ path: "/api/v1/app-conversations",
+ body: body as unknown as Record<string, unknown>,
+ });
+}
+
/**
* Read a file from a cloud conversation's sandbox workspace. Mirrors
* OpenHands' `AgentServerConversationService.readConversationFile` — hits
diff --git a/src/api/conversation-service/agent-server-conversation-service.types.ts b/src/api/conversation-service/agent-server-conversation-service.types.ts
index a8b9274de2..4db37da000 100644
--- a/src/api/conversation-service/agent-server-conversation-service.types.ts
+++ b/src/api/conversation-service/agent-server-conversation-service.types.ts
@@ -60,6 +60,11 @@ export interface SendMessageRequest {
}
export interface AppConversationStartRequest {
+ // Re-provision an EXISTING conversation (waking a recycled sandbox) instead
+ // of minting a new one. The backend keys the rebuilt conversation on this id
+ // and, for ACP, resumes it from the durable event store with a bootstrap
+ // prompt (OpenHands#14640). Omit/null to create a fresh conversation.
+ conversation_id?: string | null;
initial_message?: SendMessageRequest | null;
processors?: unknown[]; // EventCallbackProcessor - keeping as unknown for now
llm_model?: string | null;
diff --git a/src/components/features/chat/acp-resume-archived-button.tsx b/src/components/features/chat/acp-resume-archived-button.tsx
new file mode 100644
index 0000000000..26e932df74
--- /dev/null
+++ b/src/components/features/chat/acp-resume-archived-button.tsx
@@ -0,0 +1,54 @@
+import { useTranslation } from "react-i18next";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { I18nKey } from "#/i18n/declaration";
+import { useWakeConversation } from "#/hooks/mutation/use-wake-conversation";
+import { displayErrorToast } from "#/utils/custom-toast-handlers";
+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+
+interface AcpResumeArchivedButtonProps {
+ conversation: AppConversation;
+}
+
+/**
+ * Resume affordance shown in place of the read-only "archived" notice for an
+ * ACP conversation whose cloud sandbox was recycled. Waking re-provisions a
+ * fresh sandbox under the same conversation id; the backend resumes the
+ * conversation from the durable event store with a bootstrap prompt
+ * (OpenHands#14640). The active-conversation poll then reconnects once the
+ * fresh sandbox is RUNNING.
+ */
+export function AcpResumeArchivedButton({
+ conversation,
+}: AcpResumeArchivedButtonProps) {
+ const { t } = useTranslation();
+ const { mutate: wake, isPending } = useWakeConversation();
+
+ return (
+ <div className="flex flex-col gap-2">
+ <p className="text-xs text-[var(--oh-muted)]">
+ {t(I18nKey.CHAT_INTERFACE$ACP_RESUME_SANDBOX_DESCRIPTION)}
+ </p>
+ <BrandButton
+ type="button"
+ variant="primary"
+ isDisabled={isPending}
+ onClick={() =>
+ wake(
+ { conversationId: conversation.id, conversation },
+ {
+ onError: (error) =>
+ displayErrorToast(
+ error instanceof Error ? error.message : String(error),
+ ),
+ },
+ )
+ }
+ testId="acp-resume-conversation-button"
+ >
+ {isPending
+ ? t(I18nKey.CHAT_INTERFACE$ACP_RESUME_STARTING)
+ : t(I18nKey.CHAT_INTERFACE$ACP_RESUME_BUTTON)}
+ </BrandButton>
+ </div>
+ );
+}
diff --git a/src/components/features/chat/chat-interface.tsx b/src/components/features/chat/chat-interface.tsx
index 7f2ab7a03b..41b4c667b0 100644
--- a/src/components/features/chat/chat-interface.tsx
+++ b/src/components/features/chat/chat-interface.tsx
@@ -39,6 +39,7 @@ import { useTaskPolling } from "#/hooks/query/use-task-polling";
import { matchesPendingConversationId } from "#/utils/pending-task-message-link";
import { useConversationWebSocket } from "#/contexts/conversation-websocket-context";
import ChatStatusIndicator from "./chat-status-indicator";
+import { AcpResumeArchivedButton } from "./acp-resume-archived-button";
import { getStatusColor, getStatusText } from "#/utils/utils";
import { useNewConversationCommand } from "#/hooks/mutation/use-new-conversation-command";
import { useOptionalConversationId } from "#/hooks/use-conversation-id";
@@ -107,6 +108,11 @@ export function ChatInterface() {
const sandboxStatus = activeConversation?.sandbox_status ?? null;
const isArchivedConversation =
sandboxStatus === "MISSING" || sandboxStatus === "ERROR";
+ // A recycled (MISSING) sandbox for an ACP conversation can be re-provisioned:
+ // the backend resumes it from the durable event store with a bootstrap prompt
+ // (OpenHands#14640). ERROR is a genuine failure, so it stays read-only.
+ const isRecycledAcpConversation =
+ sandboxStatus === "MISSING" && activeConversation?.agent_kind === "acp";
// Block sending in a resumed conversation that has no usable LLM, and show
// the same setup banner as the home screen so the dead end is explained.
@@ -561,11 +567,20 @@ export function ChatInterface() {
? t(I18nKey.CHAT_INTERFACE$ERROR_SANDBOX_TITLE)
: t(I18nKey.CHAT_INTERFACE$ARCHIVED_SANDBOX_TITLE)}
</p>
- <p className="text-xs text-[var(--oh-muted)] mt-0.5">
- {sandboxStatus === "ERROR"
- ? t(I18nKey.CHAT_INTERFACE$ERROR_SANDBOX_DESCRIPTION)
- : t(I18nKey.CHAT_INTERFACE$ARCHIVED_SANDBOX_DESCRIPTION)}
- </p>
+ {isRecycledAcpConversation && activeConversation ? (
+ // ACP conversations resume from a recycled sandbox via a
+ // bootstrap prompt (OpenHands#14640): offer to re-provision
+ // instead of dead-ending.
+ <div className="mt-2">
+ <AcpResumeArchivedButton conversation={activeConversation} />
+ </div>
+ ) : (
+ <p className="text-xs text-[var(--oh-muted)] mt-0.5">
+ {sandboxStatus === "ERROR"
+ ? t(I18nKey.CHAT_INTERFACE$ERROR_SANDBOX_DESCRIPTION)
+ : t(I18nKey.CHAT_INTERFACE$ARCHIVED_SANDBOX_DESCRIPTION)}
+ </p>
+ )}
</div>
) : (
<div className="relative">
diff --git a/src/components/features/onboarding/steps/choose-agent-step.tsx b/src/components/features/onboarding/steps/choose-agent-step.tsx
index fc2e1659c9..d8d52a6932 100644
--- a/src/components/features/onboarding/steps/choose-agent-step.tsx
+++ b/src/components/features/onboarding/steps/choose-agent-step.tsx
@@ -105,6 +105,8 @@ export function ChooseAgentStep({
const { mutate: saveSettings, isPending: isSaving } = useSaveSettings();
const handleNext = () => {
+ // The diff builder seeds the preferred default model (Vertex-safe for
+ // Gemini) when none is passed.
const diff = buildAcpAgentSettingsDiff(selectedAgentId);
if (!diff) {
// Unknown id (shouldn't be reachable through the UI). Advance
diff --git a/src/components/features/onboarding/steps/setup-acp-secrets-step.tsx b/src/components/features/onboarding/steps/setup-acp-secrets-step.tsx
index 60a7d745e1..e6864b198a 100644
--- a/src/components/features/onboarding/steps/setup-acp-secrets-step.tsx
+++ b/src/components/features/onboarding/steps/setup-acp-secrets-step.tsx
@@ -1,24 +1,15 @@
import React from "react";
import { useTranslation } from "react-i18next";
-import { useQueryClient } from "@tanstack/react-query";
-import { AxiosError } from "axios";
import { Check, Loader2 } from "lucide-react";
import { BrandButton } from "#/components/features/settings/brand-button";
-import { SettingsInput } from "#/components/features/settings/settings-input";
+import { AcpConflictWarnings } from "#/components/features/settings/acp-conflict-warnings";
+import { AcpSecretField } from "#/components/features/settings/acp-secret-field";
import { I18nKey } from "#/i18n/declaration";
-import { useCreateSecret } from "#/hooks/mutation/use-create-secret";
-import { useSearchSecrets } from "#/hooks/query/use-get-secrets";
import { useAcpAuthStatus } from "#/hooks/query/use-acp-auth-status";
-import {
- getAcpProviderDisplayName,
- getAcpProviderSecrets,
-} from "#/constants/acp-providers";
+import { useAcpCredentialForm } from "#/hooks/use-acp-credential-form";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { getAcpProviderDisplayName } from "#/constants/acp-providers";
import { type OnboardingAgentId } from "./choose-agent-step";
-import {
- displayErrorToast,
- displaySuccessToast,
-} from "#/utils/custom-toast-handlers";
-import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
interface SetupAcpSecretsStepProps {
/** ACP provider whose credentials we're collecting (e.g. ``"claude-code"``).
@@ -39,18 +30,24 @@ interface SetupAcpSecretsStepProps {
}
/**
- * Onboarding credentials step for ACP providers that expose an env-var API key
- * (Claude Code, Codex, Gemini CLI). The fields are derived from
- * {@link getAcpProviderSecrets}; each one maps 1:1 to a **global secret**
- * whose name equals the env var the agent-server exports into the provider
- * subprocess. Saving here is therefore the same as adding the secret under
- * Settings → Secrets — it shows up there afterwards.
+ * Onboarding credentials step for ACP providers (Claude Code, Codex, Gemini
+ * CLI). The fields are derived from {@link getAcpProviderSecrets}: the API key
+ * + optional base URL (from the SDK registry) plus the per-provider
+ * credentials a *containerized* agent-server needs (Codex ``auth.json``, the
+ * Claude OAuth token, the Gemini Vertex service-account JSON + project/location).
+ * Each field maps 1:1 to a **global secret** whose name equals the env var the
+ * agent-server exports into the provider subprocess, so saving here is the same
+ * as adding the secret under Settings → Secrets.
*
- * The step is intentionally skippable: a user may authenticate via a
- * subscription / OAuth login (a Claude login, or Gemini's Google login), or
- * already have the env var set on the backend, so we never block "Next" on a
- * value — and the login probe shows a "you're already signed in" banner when it
- * detects one. Empty fields are simply not written; a field whose secret
+ * The step is **optional on a backend that can fall back to a host login** (a
+ * native agent-server where the user has already run ``claude``/``codex``/
+ * ``gcloud`` login) and **required otherwise** — a fresh Docker container or a
+ * cloud backend has no host login, so the agent can't authenticate without
+ * credentials. Required-ness is capability-driven (see {@link backendRequiresAcpCredentials}):
+ * we never block "Next" when the login probe detects an existing session, and
+ * we never block a native dev whose host login we just can't classify.
+ *
+ * Empty fields are never written (a deliberate skip), and a field whose secret
* already exists shows an "already saved" placeholder and is left untouched
* unless the user types a replacement.
*/
@@ -61,9 +58,7 @@ export function SetupAcpSecretsStep({
onNext,
}: SetupAcpSecretsStepProps) {
const { t } = useTranslation("openhands");
- const queryClient = useQueryClient();
- const { mutateAsync: createSecret } = useCreateSecret();
- const { data: existingSecrets } = useSearchSecrets();
+ const activeBackend = useActiveBackend();
// Login detection via AcpService (provider status commands run through the
// agent-server bash endpoint) — see issue #964.
const { status: authStatus, isChecking: isCheckingAuth } = useAcpAuthStatus(
@@ -71,51 +66,53 @@ export function SetupAcpSecretsStep({
{ enabled: isActive },
);
- const fields = React.useMemo(
- () => getAcpProviderSecrets(providerKey),
- [providerKey],
- );
- const [values, setValues] = React.useState<Record<string, string>>({});
- const [isSaving, setIsSaving] = React.useState(false);
+ const {
+ fields,
+ values,
+ setValue,
+ secretExists,
+ hasValueFor,
+ conflicts,
+ consumesFileCredentials,
+ save,
+ isSaving,
+ } = useAcpCredentialForm(providerKey);
const providerName = getAcpProviderDisplayName(providerKey) ?? providerKey;
- const secretExists = React.useCallback(
- (name: string) =>
- (existingSecrets ?? []).some((secret) => secret.name === name),
- [existingSecrets],
+ const isAuthenticated = authStatus === "authenticated";
+ // Required when the backend can't fall back to a host login (see component
+ // docstring). Cloud never has one; a local backend that probes as logged-out
+ // is a fresh container — require credentials there, but stay permissive when
+ // the probe resolves "unknown" so a native dev is never blocked.
+ const required = backendRequiresAcpCredentials(
+ activeBackend.backend.kind,
+ authStatus,
);
+ // Satisfied once the user has an actual credential for the provider — a
+ // masked ``secret`` field (blob, OAuth token, or API key), typed now or
+ // previously saved. A base URL or GCP project/location alone can't
+ // authenticate anything, so it doesn't count — and neither does a file blob
+ // on a backend that can't materialise it (cloud, agent-canvas#1016): the
+ // save flow warns it's orphaned, so it can't be what satisfies the gate.
+ // An existing login also satisfies it.
+ const satisfied =
+ isAuthenticated ||
+ fields.some(
+ (field) =>
+ field.secret &&
+ (!field.multiline || consumesFileCredentials) &&
+ hasValueFor(field.name),
+ );
+ const blockNext = required && !satisfied;
+ // While the probe is still classifying a local backend, hold Next: the gate
+ // may be about to come up "unauthenticated", and the checking banner is
+ // already showing. A probe that *completes* as "unknown" stays permissive.
+ const nextDisabled = isSaving || blockNext || (isCheckingAuth && !satisfied);
const handleNext = async () => {
- // Only persist fields the user actually filled in — empty inputs are a
- // deliberate skip, not a request to clear an existing secret.
- const toSave = fields
- .map((field) => ({ name: field.name, value: values[field.name]?.trim() }))
- .filter((entry): entry is { name: string; value: string } =>
- Boolean(entry.value),
- );
-
- if (toSave.length === 0) {
- onNext();
- return;
- }
-
- setIsSaving(true);
- try {
- // Sequential so a mid-list failure leaves the earlier secrets saved and
- // surfaces a single, specific error rather than a race of toasts.
- for (const { name, value } of toSave) {
- await createSecret({ name, value });
- }
- await queryClient.invalidateQueries({ queryKey: ["secrets-search"] });
- await queryClient.invalidateQueries({ queryKey: ["secrets"] });
- displaySuccessToast(t(I18nKey.SETTINGS$SAVED));
+ if (await save()) {
onNext();
- } catch (error) {
- const message = retrieveAxiosErrorMessage(error as AxiosError);
- displayErrorToast(message || t(I18nKey.ERROR$GENERIC));
- } finally {
- setIsSaving(false);
}
};
@@ -133,12 +130,23 @@ export function SetupAcpSecretsStep({
provider: providerName,
})}
</p>
- {authStatus !== "authenticated" && (
- // When already signed in, the success banner below already says to
- // leave the fields blank, so this general reminder would be redundant.
- <p className="text-sm text-[var(--oh-muted)]">
- {t(I18nKey.ONBOARDING$ACP_SECRETS_SUBSCRIPTION_NOTE)}
+ {required && !isAuthenticated ? (
+ <p
+ data-testid="onboarding-acp-secrets-required-note"
+ className="text-sm text-[var(--oh-muted)]"
+ >
+ {t(I18nKey.ONBOARDING$ACP_SECRETS_REQUIRED_NOTE, {
+ provider: providerName,
+ })}
</p>
+ ) : (
+ authStatus !== "authenticated" && (
+ // When already signed in, the success banner below already says to
+ // leave the fields blank, so this general reminder would be redundant.
+ <p className="text-sm text-[var(--oh-muted)]">
+ {t(I18nKey.ONBOARDING$ACP_SECRETS_SUBSCRIPTION_NOTE)}
+ </p>
+ )
)}
</header>
@@ -174,36 +182,30 @@ export function SetupAcpSecretsStep({
) : null}
<div className="flex flex-col gap-5">
- {fields.map((field) => {
- const alreadySet = secretExists(field.name);
- return (
- <div key={field.name} className="flex flex-col gap-1.5">
- <SettingsInput
- testId={`onboarding-acp-secret-${field.name}`}
- name={field.name}
- // The env-var name is the canonical label here; rendering it
- // monospace makes clear it's a literal key, not prose.
- label={field.name}
- labelClassName="font-mono"
- type={field.secret ? "password" : "text"}
- value={values[field.name] ?? ""}
- onChange={(value) =>
- setValues((prev) => ({ ...prev, [field.name]: value }))
- }
- // Every field is optional — the whole step is skippable.
- showOptionalTag
- placeholder={
- alreadySet ? t(I18nKey.ONBOARDING$ACP_SECRET_ALREADY_SET) : ""
- }
- />
- <span className="text-xs text-[var(--oh-muted)]">
- {t(field.hint_key)}
- </span>
- </div>
- );
- })}
+ {fields.map((field) => (
+ <AcpSecretField
+ key={field.name}
+ field={field}
+ value={values[field.name] ?? ""}
+ onChange={(value) => setValue(field.name, value)}
+ alreadySet={secretExists(field.name)}
+ testId={`onboarding-acp-secret-${field.name}`}
+ showOptionalTag
+ />
+ ))}
</div>
+ <AcpConflictWarnings conflicts={conflicts} />
+
+ {blockNext ? (
+ <p
+ data-testid="onboarding-acp-secrets-blocked"
+ className="text-sm text-amber-300"
+ >
+ {t(I18nKey.ONBOARDING$ACP_SECRETS_REQUIRED_BLOCKED)}
+ </p>
+ ) : null}
+
<div className="sticky bottom-0 flex items-center justify-between gap-2 bg-base-secondary pt-4 pb-7">
<BrandButton
testId="onboarding-acp-secrets-back"
@@ -218,7 +220,7 @@ export function SetupAcpSecretsStep({
testId="onboarding-acp-secrets-next"
type="button"
variant="primary"
- isDisabled={isSaving}
+ isDisabled={nextDisabled}
onClick={handleNext}
>
{isSaving ? t(I18nKey.SETTINGS$SAVING) : t(I18nKey.ONBOARDING$NEXT)}
@@ -227,3 +229,26 @@ export function SetupAcpSecretsStep({
</div>
);
}
+
+/**
+ * Whether the credential step must be satisfied before advancing, given the
+ * active backend kind and the ACP login-probe result.
+ *
+ * - **cloud** → always required: a remote backend has no host CLI login to fall
+ * back on.
+ * - **local + ``"unauthenticated"``** → required: the probe ran and found no
+ * login, i.e. a fresh containerized agent-server.
+ * - **local + ``"authenticated"`` / ``"unknown"``** → optional: either a login
+ * exists, or the probe couldn't classify it (CLI missing, odd output) — in
+ * which case we stay permissive rather than block a working native dev.
+ *
+ * Exported for unit testing the matrix without rendering the modal.
+ */
+export function backendRequiresAcpCredentials(
+ backendKind: "local" | "cloud",
+ authStatus: "authenticated" | "unauthenticated" | "unknown",
+): boolean {
+ if (authStatus === "authenticated") return false;
+ if (backendKind === "cloud") return true;
+ return authStatus === "unauthenticated";
+}
diff --git a/src/components/features/settings/acp-conflict-warnings.tsx b/src/components/features/settings/acp-conflict-warnings.tsx
new file mode 100644
index 0000000000..d90e03c382
--- /dev/null
+++ b/src/components/features/settings/acp-conflict-warnings.tsx
@@ -0,0 +1,33 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+
+/**
+ * Warning lines for credential pairs that break each other at runtime (see
+ * ``getAcpCredentialConflicts``). Rendered identically by the onboarding
+ * credentials step and the Settings → Agent credentials section.
+ */
+export function AcpConflictWarnings({
+ conflicts,
+}: {
+ conflicts: Array<[string, string]>;
+}) {
+ const { t } = useTranslation("openhands");
+
+ return (
+ <>
+ {conflicts.map(([credential, conflicting]) => (
+ <p
+ key={`${credential}:${conflicting}`}
+ data-testid="acp-credential-conflict-warning"
+ className="text-sm text-amber-300"
+ >
+ {t(I18nKey.SETTINGS$ACP_CREDENTIAL_CONFLICT_WARNING, {
+ credential,
+ conflicting,
+ })}
+ </p>
+ ))}
+ </>
+ );
+}
diff --git a/src/components/features/settings/acp-credentials-section.tsx b/src/components/features/settings/acp-credentials-section.tsx
new file mode 100644
index 0000000000..b35acedffb
--- /dev/null
+++ b/src/components/features/settings/acp-credentials-section.tsx
@@ -0,0 +1,82 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { AcpConflictWarnings } from "#/components/features/settings/acp-conflict-warnings";
+import { AcpSecretField } from "#/components/features/settings/acp-secret-field";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { Typography } from "#/ui/typography";
+import { I18nKey } from "#/i18n/declaration";
+import { useAcpCredentialForm } from "#/hooks/use-acp-credential-form";
+
+/**
+ * Settings → Agent credentials section for a built-in ACP provider: the same
+ * fields the onboarding step collects, saved through the same flow
+ * ({@link useAcpCredentialForm}), so credentials can be added or rotated after
+ * onboarding. Renders nothing for providers without credential fields.
+ */
+export function AcpCredentialsSection({
+ providerKey,
+}: {
+ providerKey: string;
+}) {
+ const { t } = useTranslation("openhands");
+ const {
+ fields,
+ values,
+ setValue,
+ secretExists,
+ conflicts,
+ isDirty,
+ save,
+ reset,
+ isSaving,
+ } = useAcpCredentialForm(providerKey);
+
+ if (fields.length === 0) return null;
+
+ const handleSave = async () => {
+ if (await save()) {
+ reset();
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-col gap-1">
+ <Typography.Text className="text-sm font-medium text-white">
+ {t(I18nKey.SETTINGS$ACP_CREDENTIALS_TITLE)}
+ </Typography.Text>
+ <Typography.Text className="text-xs text-[#717888]">
+ {t(I18nKey.SETTINGS$ACP_CREDENTIALS_DESCRIPTION)}
+ </Typography.Text>
+ </div>
+
+ <div className="flex flex-col gap-5">
+ {fields.map((field) => (
+ <AcpSecretField
+ key={field.name}
+ field={field}
+ value={values[field.name] ?? ""}
+ onChange={(value) => setValue(field.name, value)}
+ alreadySet={secretExists(field.name)}
+ testId={`settings-acp-secret-${field.name}`}
+ showOptionalTag
+ />
+ ))}
+ </div>
+
+ <AcpConflictWarnings conflicts={conflicts} />
+
+ <BrandButton
+ testId="acp-credentials-save-button"
+ type="button"
+ variant="primary"
+ isDisabled={isSaving || !isDirty}
+ onClick={handleSave}
+ >
+ {isSaving
+ ? t(I18nKey.SETTINGS$SAVING)
+ : t(I18nKey.SETTINGS$SAVE_CHANGES)}
+ </BrandButton>
+ </div>
+ );
+}
diff --git a/src/components/features/settings/acp-secret-field.tsx b/src/components/features/settings/acp-secret-field.tsx
new file mode 100644
index 0000000000..feaa37ec82
--- /dev/null
+++ b/src/components/features/settings/acp-secret-field.tsx
@@ -0,0 +1,81 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { cn } from "#/utils/utils";
+import { formControlMultilineFieldClassName } from "#/utils/form-control-classes";
+import { SettingsInput } from "#/components/features/settings/settings-input";
+import { OptionalTag } from "#/components/features/settings/optional-tag";
+import { I18nKey } from "#/i18n/declaration";
+import { type ACPProviderSecretField } from "#/constants/acp-providers";
+
+interface AcpSecretFieldProps {
+ field: ACPProviderSecretField;
+ value: string;
+ onChange: (value: string) => void;
+ alreadySet: boolean;
+ testId: string;
+ showOptionalTag?: boolean;
+}
+
+/**
+ * Renders a single ACP credential field — a multiline textarea for file-content
+ * blobs (Codex auth.json, Gemini SA JSON) or a masked/plain {@link SettingsInput}
+ * for everything else — plus its hint text. Used by both the onboarding
+ * credentials step and the Settings → Agent credentials section.
+ */
+export function AcpSecretField({
+ field,
+ value,
+ onChange,
+ alreadySet,
+ testId,
+ showOptionalTag,
+}: AcpSecretFieldProps) {
+ const { t } = useTranslation("openhands");
+ const placeholder = alreadySet
+ ? t(I18nKey.ONBOARDING$ACP_SECRET_ALREADY_SET)
+ : "";
+
+ return (
+ <div className="flex flex-col gap-1.5">
+ {field.multiline ? (
+ <label className="flex flex-col gap-2.5">
+ <span className="flex items-center gap-2">
+ <span className="text-sm font-mono text-white">{field.name}</span>
+ {showOptionalTag && <OptionalTag />}
+ </span>
+ <textarea
+ data-testid={testId}
+ name={field.name}
+ rows={4}
+ spellCheck={false}
+ autoCapitalize="off"
+ autoComplete="off"
+ autoCorrect="off"
+ value={value}
+ placeholder={placeholder}
+ onChange={(e) => onChange(e.target.value)}
+ className={cn(
+ formControlMultilineFieldClassName,
+ "font-mono text-xs",
+ )}
+ />
+ </label>
+ ) : (
+ <SettingsInput
+ testId={testId}
+ name={field.name}
+ label={field.name}
+ labelClassName="font-mono"
+ type={field.secret ? "password" : "text"}
+ value={value}
+ onChange={onChange}
+ showOptionalTag={showOptionalTag}
+ placeholder={placeholder}
+ />
+ )}
+ <span className="text-xs text-[var(--oh-muted)]">
+ {t(field.hint_key, field.hint_values)}
+ </span>
+ </div>
+ );
+}
diff --git a/src/constants/acp-providers.ts b/src/constants/acp-providers.ts
index b25eeb43af..641ec3d7bb 100644
--- a/src/constants/acp-providers.ts
+++ b/src/constants/acp-providers.ts
@@ -190,28 +190,170 @@ export interface ACPProviderSecretField {
/** Secret name and env var (e.g. ``"ANTHROPIC_API_KEY"``). Must satisfy the
* secret-name pattern ``^[a-zA-Z][a-zA-Z0-9_]{0,63}$``. */
name: string;
- /** Render as a masked password input (API keys) rather than a plain-text
- * input (base URLs). Every field is optional regardless — the whole step is
- * skippable — so this only controls masking, not whether the field gates. */
+ /** Render as a masked password input (API keys, OAuth tokens, credential
+ * blobs) rather than a plain-text input (base URLs, project IDs). Doubles as
+ * "this is an actual credential": when the onboarding step is required, only
+ * a ``secret`` field satisfies it — a base URL or GCP scalar alone can't
+ * authenticate anything. */
secret?: boolean;
+ /** Render as a multi-line textarea rather than a single-line input. Set for
+ * file-content credentials the user pastes verbatim (Codex ``auth.json``,
+ * Gemini Vertex service-account / ADC JSON) — the ones the SDK materialises
+ * to disk, which a cloud backend can't consume yet (agent-canvas#1016). */
+ multiline?: boolean;
/** i18n key for the one-line helper text under the field. */
hint_key: I18nKey;
+ /**
+ * Interpolation values for {@link hint_key} (e.g. ``{ file: "~/.codex/auth.json" }``
+ * for the shared "paste the file contents" hint). Omitted for hints that
+ * take no parameters.
+ */
+ hint_values?: Record<string, string>;
+}
+
+/**
+ * Container credentials — beyond the registry's API key / base URL — that
+ * canvas collects per provider so a *containerized* agent-server (no host login
+ * state) can authenticate the ACP CLI: subscription tokens plus the file-content
+ * blobs and Vertex config the SDK's ``acp_file_secrets`` materialisation
+ * consumes (agent-canvas#1013/#1014). They have no registry env-var entry
+ * because they're a deployment concern, not a model registry field. The Gemini
+ * project/location/flag are plain config, not secrets — grouped here because
+ * they travel with the SA blob.
+ *
+ * The blob *names* (``CODEX_AUTH_JSON`` / ``GOOGLE_APPLICATION_CREDENTIALS_JSON``)
+ * duplicate the SDK registry's ``file_secrets`` specs; derive them from the
+ * client registry once the pinned ``@openhands/typescript-client`` mirrors that
+ * field (same bump that unblocks ``acp_isolate_data_dir``, see #1019).
+ */
+const ACP_RESERVED_CREDENTIALS: Record<string, ACPProviderSecretField[]> = {
+ codex: [
+ {
+ name: "CODEX_AUTH_JSON",
+ secret: true,
+ multiline: true,
+ hint_key: I18nKey.ONBOARDING$ACP_SECRET_FILE_BLOB_HINT,
+ hint_values: { file: "~/.codex/auth.json" },
+ },
+ ],
+ "claude-code": [
+ {
+ name: "CLAUDE_CODE_OAUTH_TOKEN",
+ secret: true,
+ hint_key: I18nKey.ONBOARDING$ACP_SECRET_OAUTH_TOKEN_HINT,
+ },
+ ],
+ "gemini-cli": [
+ {
+ name: "GOOGLE_APPLICATION_CREDENTIALS_JSON",
+ secret: true,
+ multiline: true,
+ hint_key: I18nKey.ONBOARDING$ACP_SECRET_FILE_BLOB_HINT,
+ hint_values: {
+ file: "~/.config/gcloud/application_default_credentials.json",
+ },
+ },
+ {
+ name: "GOOGLE_CLOUD_PROJECT",
+ hint_key: I18nKey.ONBOARDING$ACP_SECRET_GCP_PROJECT_HINT,
+ },
+ {
+ name: "GOOGLE_CLOUD_LOCATION",
+ hint_key: I18nKey.ONBOARDING$ACP_SECRET_GCP_LOCATION_HINT,
+ },
+ {
+ name: "GOOGLE_GENAI_USE_VERTEXAI",
+ hint_key: I18nKey.ONBOARDING$ACP_SECRET_VERTEXAI_FLAG_HINT,
+ },
+ ],
+};
+
+/**
+ * Credential pairs that break each other at runtime, keyed by provider.
+ * Claude's OAuth token authenticates against Anthropic directly; an
+ * ``ANTHROPIC_BASE_URL`` set alongside it silently routes requests elsewhere
+ * and breaks the token's bearer auth (see docs/ACP_AGENTS.md).
+ */
+const ACP_CREDENTIAL_CONFLICTS: Record<string, Array<[string, string]>> = {
+ "claude-code": [["CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL"]],
+};
+
+/**
+ * The ``[credential, conflicting]`` pairs the user currently has set for
+ * ``providerKey``. ``hasValue`` should cover both typed and already-saved
+ * values, since a previously saved secret conflicts just the same.
+ */
+export function getAcpCredentialConflicts(
+ key: string | null | undefined,
+ hasValue: (name: string) => boolean,
+): Array<[string, string]> {
+ if (!key) return [];
+ return (ACP_CREDENTIAL_CONFLICTS[key] ?? []).filter(
+ ([credential, conflicting]) =>
+ hasValue(credential) && hasValue(conflicting),
+ );
+}
+
+/**
+ * Vertex AI-safe ``acp_model`` for Gemini.
+ *
+ * Left unset, gemini-cli falls back to its own internal default — a preview
+ * flash model that 404s on Google Cloud projects without preview access. And a
+ * ``*-flash`` id is no safer to pin: gemini-cli re-resolves flash ids at
+ * generation time to its *current default* flash (software-agent-sdk#3532), so
+ * a pinned ``gemini-2.5-flash`` still ran ``gemini-3-flash``. Only a non-flash
+ * id sticks; ``gemini-2.5-pro`` is broadly available on Vertex and the
+ * API-key / Google-login paths, so canvas preselects it. Kept as a named
+ * constant so every model-default consumer agrees.
+ */
+export const ACP_VERTEX_SAFE_MODEL = "gemini-2.5-pro";
+
+/**
+ * The default ``acp_model`` canvas substitutes for ``providerKey`` wherever no
+ * concrete model is configured — settings seeding (onboarding, Settings →
+ * Agent), the {@link buildAcpAgentSettingsDiff} fallback, and the start-request
+ * fallback for a saved ``null``. Overrides only Gemini (→
+ * {@link ACP_VERTEX_SAFE_MODEL}, see why above); every other provider keeps its
+ * registry {@link ACPProviderConfig.default_model}. Returns ``null`` when
+ * there's no override and no registry default, letting the ACP server pick its
+ * own.
+ *
+ * Distinct from {@link ACPProviderConfig.default_model} (which mirrors the SDK
+ * registry verbatim, closing agent-canvas#740): this is the *preferred* default,
+ * deliberately diverging for Gemini where the registry value isn't safe on
+ * every backend — so every default-model surface must route through this, not
+ * read ``default_model`` directly.
+ */
+export function getAcpPreferredDefaultModel(
+ key: string | null | undefined,
+): string | null {
+ if (key === "gemini-cli") return ACP_VERTEX_SAFE_MODEL;
+ return getAcpProvider(key)?.default_model ?? null;
}
/**
* List the credentials Canvas should prompt for when onboarding the given ACP
- * provider, derived from the SDK registry's ``api_key_env_var`` /
- * ``base_url_env_var`` (mirrored via ``@openhands/typescript-client``) rather
- * than a hand-maintained per-provider list — so the field names track the SDK
- * as providers are added or renamed, with no parallel copy to drift. Each field
+ * provider. The API-key and base-URL field *names* track the SDK registry's
+ * ``api_key_env_var`` / ``base_url_env_var`` (mirrored via
+ * ``@openhands/typescript-client``) so they can't drift as providers are added
+ * or renamed; the per-provider container credentials (subscription / Vertex
+ * blobs) come from {@link ACP_RESERVED_CREDENTIALS}, since those are a
+ * containerized-deployment concern with no model-registry entry. Each field
* name equals the env var the agent-server exports into the provider subprocess
- * (which is what makes a saved secret reach the CLI); the API key renders
- * masked, the base URL plain-text. All three built-ins (Claude Code, Codex,
- * Gemini CLI) expose an API key + optional base URL.
+ * (which is what makes a saved secret reach the CLI). On the wire none of this
+ * is special — every saved credential travels uniformly as a ``LookupSecret``.
+ *
+ * Field order is: container subscription/Vertex credentials → API key →
+ * optional base URL. Every field is optional at the UI level — the step is
+ * skippable, and a subscription / OAuth login on the backend takes precedence
+ * over a key at runtime. (Whether the *step* is required is a
+ * backend-capability decision the onboarding modal makes; see
+ * ``backendRequiresAcpCredentials``.)
*
- * Every field is optional — the step is skippable — and a subscription / OAuth
- * login takes precedence over a key at runtime (most relevant for Gemini, whose
- * Google login is the common local path).
+ * NB: the base URL is rendered plain-text (not ``secret``), so it never counts
+ * toward a required credential step — setting ``ANTHROPIC_BASE_URL`` alongside
+ * a ``CLAUDE_CODE_OAUTH_TOKEN`` breaks the token's bearer auth, which the forms
+ * surface via {@link getAcpCredentialConflicts}.
*
* Returns ``[]`` for OpenHands, the ``"custom"`` preset, any unknown key, and a
* future OAuth-only provider whose registry entry has no ``api_key_env_var`` —
@@ -220,9 +362,15 @@ export interface ACPProviderSecretField {
export function getAcpProviderSecrets(
key: string | null | undefined,
): ACPProviderSecretField[] {
- const info = key ? getClientAcpProvider(key) : null;
+ if (!key) return [];
+ const info = getClientAcpProvider(key);
if (!info) return [];
- const fields: ACPProviderSecretField[] = [];
+ // Subscription / Vertex credentials first — they're the primary auth path for
+ // ACP providers (Claude Pro/Max OAuth token, Codex ChatGPT auth.json), with
+ // the API key as the fallback below.
+ const fields: ACPProviderSecretField[] = [
+ ...(ACP_RESERVED_CREDENTIALS[key] ?? []),
+ ];
if (info.api_key_env_var) {
fields.push({
name: info.api_key_env_var,
@@ -358,9 +506,11 @@ export function buildAcpAgentSettingsDiff(
return null;
}
+ // Undefined model → the *preferred* default (Vertex-safe for Gemini), not
+ // the raw registry default — see getAcpPreferredDefaultModel.
const model =
options.model === undefined
- ? (provider?.default_model ?? null)
+ ? getAcpPreferredDefaultModel(providerKey)
: options.model;
// ``acp_args: []`` resets any API-set ``acp_args`` that would
diff --git a/src/hooks/mutation/use-wake-conversation.ts b/src/hooks/mutation/use-wake-conversation.ts
new file mode 100644
index 0000000000..522812ac67
--- /dev/null
+++ b/src/hooks/mutation/use-wake-conversation.ts
@@ -0,0 +1,37 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { wakeRecycledCloudConversation } from "#/api/cloud/conversation-service.api";
+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+
+/**
+ * Wake a recycled (STOPPED/MISSING) cloud conversation by re-provisioning its
+ * sandbox under the same conversation id. For ACP this triggers bootstrap-prompt
+ * resume on the backend (OpenHands#14640) — the agent continues from the durable
+ * event store. Invalidating the conversation queries drops the cached
+ * MISSING/archived view; the active-conversation poll then picks up the new
+ * `conversation_url` once the fresh sandbox is RUNNING and the chat reconnects.
+ */
+export const useWakeConversation = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: (variables: {
+ conversationId: string;
+ conversation?: AppConversation | null;
+ }) =>
+ wakeRecycledCloudConversation(variables.conversationId, {
+ selected_repository:
+ variables.conversation?.selected_repository ?? null,
+ selected_branch: variables.conversation?.selected_branch ?? null,
+ git_provider: variables.conversation?.git_provider ?? null,
+ }),
+ onSettled: (_, __, variables) => {
+ queryClient.invalidateQueries({
+ queryKey: ["user", "conversation", variables.conversationId],
+ });
+ queryClient.invalidateQueries({ queryKey: ["user", "conversations"] });
+ queryClient.invalidateQueries({
+ queryKey: ["v1-batch-get-app-conversations"],
+ });
+ },
+ });
+};
diff --git a/src/hooks/use-acp-credential-form.ts b/src/hooks/use-acp-credential-form.ts
new file mode 100644
index 0000000000..2afdf0feef
--- /dev/null
+++ b/src/hooks/use-acp-credential-form.ts
@@ -0,0 +1,99 @@
+import React from "react";
+import { useSearchSecrets } from "#/hooks/query/use-get-secrets";
+import { useSaveAcpSecrets } from "#/hooks/use-save-acp-secrets";
+import {
+ getAcpCredentialConflicts,
+ getAcpProviderSecrets,
+ type ACPProviderSecretField,
+} from "#/constants/acp-providers";
+
+export interface AcpCredentialForm {
+ /** Credential fields for ``providerKey`` (see {@link getAcpProviderSecrets}). */
+ fields: ACPProviderSecretField[];
+ /** Current (unsaved) input values, keyed by field name. */
+ values: Record<string, string>;
+ setValue: (name: string, value: string) => void;
+ /** Whether a secret with this name is already saved on the backend. */
+ secretExists: (name: string) => boolean;
+ /** Typed now (non-blank) or previously saved. */
+ hasValueFor: (name: string) => boolean;
+ /** ``[credential, conflicting]`` pairs currently both set (typed or saved). */
+ conflicts: Array<[string, string]>;
+ /** Whether the active backend can materialise file-content (``multiline``)
+ * credentials to disk. False on cloud (agent-canvas#1016), where such a
+ * credential would be orphaned. */
+ consumesFileCredentials: boolean;
+ /** At least one field has a non-blank typed value. */
+ isDirty: boolean;
+ /** Persist the filled fields; resolves ``true`` when everything saved. */
+ save: () => Promise<boolean>;
+ reset: () => void;
+ isSaving: boolean;
+}
+
+/**
+ * Shared state + derived values for the ACP credential forms (the onboarding
+ * step and the Settings → Agent section): the provider's field list, the typed
+ * values, existing-secret lookups, the credential-conflict pairs, and the save
+ * flow ({@link useSaveAcpSecrets}). Values reset when ``providerKey`` changes —
+ * typed-but-unsaved input belongs to the previous provider's fields.
+ */
+export function useAcpCredentialForm(
+ providerKey: string | null | undefined,
+): AcpCredentialForm {
+ const { data: existingSecrets } = useSearchSecrets();
+ const fields = React.useMemo(
+ () => getAcpProviderSecrets(providerKey),
+ [providerKey],
+ );
+ const [values, setValues] = React.useState<Record<string, string>>({});
+
+ // Both local and cloud agent-servers materialise file-content credentials
+ // (Codex auth.json, Gemini Vertex SA) via the SDK's acp_file_secrets: locally
+ // from the user's machine, on cloud from the per-user encrypted secret store
+ // routed through agent_context.secrets at conversation start (the cloud
+ // backend pins an SDK that materialises reserved file secrets). So a pasted
+ // file blob is consumable on every supported backend.
+ const consumesFileCredentials = true;
+ const { saveFilled, isSaving } = useSaveAcpSecrets(
+ fields,
+ consumesFileCredentials,
+ );
+
+ React.useEffect(() => {
+ setValues({});
+ }, [providerKey]);
+
+ const secretExists = React.useCallback(
+ (name: string) =>
+ (existingSecrets ?? []).some((secret) => secret.name === name),
+ [existingSecrets],
+ );
+
+ const hasValueFor = React.useCallback(
+ (name: string) => Boolean(values[name]?.trim()) || secretExists(name),
+ [values, secretExists],
+ );
+
+ const setValue = React.useCallback(
+ (name: string, value: string) =>
+ setValues((prev) => ({ ...prev, [name]: value })),
+ [],
+ );
+
+ const reset = React.useCallback(() => setValues({}), []);
+
+ return {
+ fields,
+ values,
+ setValue,
+ secretExists,
+ hasValueFor,
+ conflicts: getAcpCredentialConflicts(providerKey, hasValueFor),
+ consumesFileCredentials,
+ isDirty: fields.some((field) => Boolean(values[field.name]?.trim())),
+ save: () => saveFilled(values),
+ reset,
+ isSaving,
+ };
+}
diff --git a/src/hooks/use-chat-input-model-state.ts b/src/hooks/use-chat-input-model-state.ts
index 6a23bbc07c..dfe33180e0 100644
--- a/src/hooks/use-chat-input-model-state.ts
+++ b/src/hooks/use-chat-input-model-state.ts
@@ -4,6 +4,7 @@ import { useSettings } from "#/hooks/query/use-settings";
import { useAcpModelContext } from "#/hooks/use-acp-model-context";
import { useOptionalConversationId } from "#/hooks/use-conversation-id";
import {
+ getAcpPreferredDefaultModel,
getAcpProvider,
labelForAcpModel,
resolveEffectiveAcpModel,
@@ -52,7 +53,9 @@ export function useChatInputModelState(): ChatInputModelState {
typeof settings?.agent_settings?.acp_model === "string"
? settings.agent_settings.acp_model
: null,
- providerDefault: acpProvider?.default_model,
+ // Preferred default (Vertex-safe for Gemini) — must match what the
+ // start request would substitute for an unconfigured model.
+ providerDefault: getAcpPreferredDefaultModel(acpServerKey),
});
} else {
currentModelId = conversation?.llm_model ?? settings?.llm_model ?? null;
diff --git a/src/hooks/use-save-acp-secrets.ts b/src/hooks/use-save-acp-secrets.ts
new file mode 100644
index 0000000000..24ed1464d1
--- /dev/null
+++ b/src/hooks/use-save-acp-secrets.ts
@@ -0,0 +1,79 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { useQueryClient } from "@tanstack/react-query";
+import { AxiosError } from "axios";
+import { I18nKey } from "#/i18n/declaration";
+import { useCreateSecret } from "#/hooks/mutation/use-create-secret";
+import { type ACPProviderSecretField } from "#/constants/acp-providers";
+import {
+ displayErrorToast,
+ displaySuccessToast,
+ displayWarningToast,
+} from "#/utils/custom-toast-handlers";
+import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
+
+/**
+ * Shared save flow for the ACP credential forms (the onboarding step and the
+ * Settings → Agent section): persists each filled field as a global secret,
+ * refreshes the secret queries, and toasts the outcome — a warning instead of
+ * "Saved" when a file-content credential landed on a backend that can't
+ * materialise it to disk (cloud, pending agent-canvas#1016), so we don't claim
+ * success for an orphaned credential.
+ *
+ * ``saveFilled`` resolves ``true`` when every filled field saved (or nothing
+ * needed saving) and ``false`` on failure, so callers can gate navigation /
+ * form resets on it. Empty fields are never written — a blank input is a
+ * deliberate skip, not a request to clear an existing secret.
+ *
+ * ``consumesFileCredentials`` — whether the backend materialises ``multiline``
+ * credentials to disk — comes from the caller (``useAcpCredentialForm``
+ * computes it), so the save warning and the form's required-gate can't
+ * disagree on the capability.
+ */
+export function useSaveAcpSecrets(
+ fields: ACPProviderSecretField[],
+ consumesFileCredentials: boolean,
+) {
+ const { t } = useTranslation("openhands");
+ const queryClient = useQueryClient();
+ const { mutateAsync: createSecret } = useCreateSecret();
+ const [isSaving, setIsSaving] = React.useState(false);
+
+ const saveFilled = async (values: Record<string, string>) => {
+ const toSave = fields
+ .map((field) => ({ field, value: values[field.name]?.trim() }))
+ .filter(
+ (entry): entry is { field: ACPProviderSecretField; value: string } =>
+ Boolean(entry.value),
+ );
+ if (toSave.length === 0) return true;
+
+ setIsSaving(true);
+ try {
+ // Sequential so a mid-list failure leaves the earlier secrets saved and
+ // surfaces a single, specific error rather than a race of toasts.
+ for (const { field, value } of toSave) {
+ await createSecret({ name: field.name, value });
+ }
+ await queryClient.invalidateQueries({ queryKey: ["secrets-search"] });
+ await queryClient.invalidateQueries({ queryKey: ["secrets"] });
+
+ const savedOrphanedFileCredential =
+ !consumesFileCredentials && toSave.some(({ field }) => field.multiline);
+ if (savedOrphanedFileCredential) {
+ displayWarningToast(t(I18nKey.ONBOARDING$ACP_SECRETS_ORPHANED_WARNING));
+ } else {
+ displaySuccessToast(t(I18nKey.SETTINGS$SAVED));
+ }
+ return true;
+ } catch (error) {
+ const message = retrieveAxiosErrorMessage(error as AxiosError);
+ displayErrorToast(message || t(I18nKey.ERROR$GENERIC));
+ return false;
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ return { saveFilled, isSaving };
+}
diff --git a/src/i18n/index.ts b/src/i18n/index.ts
index 6e201530f6..188e82354d 100644
--- a/src/i18n/index.ts
+++ b/src/i18n/index.ts
@@ -48,6 +48,15 @@ const initializeI18n = (instance: I18nInstance) => {
backend: {
loadPath: "/locales/{{lng}}/{{ns}}.json",
},
+ // React escapes interpolated values at render time; leaving i18next's
+ // default escaping on double-escapes them, turning paths like
+ // "~/.codex/auth.json" into "~&#x2F;.codex&#x2F;auth.json".
+ // Safe to disable globally: every translation renders through React
+ // (no dangerouslySetInnerHTML on translated strings), which is the
+ // standard react-i18next setup.
+ interpolation: {
+ escapeValue: false,
+ },
});
initializationPromises.set(instance, initPromise);
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 59fe00ae48..b7a1f350d3 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -5320,6 +5320,57 @@
"uk": "Виберіть рекомендовану модель ACP або введіть користувацьке перевизначення моделі. Вбудовані постачальники зберігають конкретну модель замість того, щоб залишати поле порожнім.",
"ca": "Tria un model ACP suggerit o introdueix una substitució de model personalitzada. Els proveïdors integrats desen un model concret en lloc de deixar-lo en blanc."
},
+ "SETTINGS$ACP_CREDENTIAL_CONFLICT_WARNING": {
+ "en": "Setting {{conflicting}} alongside {{credential}} breaks its authentication — leave one of them blank.",
+ "ja": "{{credential}} と一緒に {{conflicting}} を設定すると認証が壊れます。どちらか一方は空欄のままにしてください。",
+ "zh-CN": "在设置 {{credential}} 的同时设置 {{conflicting}} 会破坏其身份验证——请将其中一项留空。",
+ "zh-TW": "在設定 {{credential}} 的同時設定 {{conflicting}} 會破壞其身分驗證——請將其中一項留空。",
+ "ko-KR": "{{credential}}과 함께 {{conflicting}}을 설정하면 인증이 깨집니다. 둘 중 하나는 비워 두세요.",
+ "no": "Å sette {{conflicting}} sammen med {{credential}} ødelegger autentiseringen — la én av dem stå tom.",
+ "ar": "تعيين {{conflicting}} مع {{credential}} يعطّل المصادقة — اترك أحدهما فارغًا.",
+ "de": "Wird {{conflicting}} zusammen mit {{credential}} gesetzt, schlägt die Authentifizierung fehl — lass eines davon leer.",
+ "fr": "Définir {{conflicting}} en même temps que {{credential}} casse son authentification — laissez l'un des deux vide.",
+ "it": "Impostare {{conflicting}} insieme a {{credential}} ne compromette l'autenticazione: lascia vuoto uno dei due.",
+ "pt": "Definir {{conflicting}} junto com {{credential}} quebra a autenticação — deixe um deles em branco.",
+ "es": "Configurar {{conflicting}} junto con {{credential}} rompe su autenticación: deja uno de los dos en blanco.",
+ "ca": "Configurar {{conflicting}} juntament amb {{credential}} en trenca l'autenticació: deixa'n un en blanc.",
+ "tr": "{{credential}} ile birlikte {{conflicting}} ayarlamak kimlik doğrulamasını bozar — birini boş bırakın.",
+ "uk": "Встановлення {{conflicting}} разом із {{credential}} ламає автентифікацію — залиште одне з них порожнім."
+ },
+ "SETTINGS$ACP_CREDENTIALS_TITLE": {
+ "en": "Credentials",
+ "ja": "認証情報",
+ "zh-CN": "凭据",
+ "zh-TW": "憑證",
+ "ko-KR": "자격 증명",
+ "no": "Legitimasjon",
+ "it": "Credenziali",
+ "pt": "Credenciais",
+ "es": "Credenciales",
+ "ar": "بيانات الاعتماد",
+ "fr": "Identifiants",
+ "tr": "Kimlik Bilgileri",
+ "de": "Zugangsdaten",
+ "uk": "Облікові дані",
+ "ca": "Credencials"
+ },
+ "SETTINGS$ACP_CREDENTIALS_DESCRIPTION": {
+ "en": "Saved as secrets and injected into the agent at runtime. Leave a field blank to keep the existing value.",
+ "ja": "シークレットとして保存され、実行時にエージェントに注入されます。既存の値を保持するにはフィールドを空白のままにしてください。",
+ "zh-CN": "保存为密钥并在运行时注入到代理中。将字段留空以保留现有值。",
+ "zh-TW": "儲存為密鑰並在執行時注入代理。將欄位留空以保留現有值。",
+ "ko-KR": "시크릿으로 저장되어 런타임에 에이전트에 주입됩니다. 기존 값을 유지하려면 필드를 비워두세요.",
+ "no": "Lagret som hemmeligheter og injisert i agenten ved kjøretid. La et felt stå tomt for å beholde den eksisterende verdien.",
+ "it": "Salvate come segreti e iniettate nell'agente in fase di esecuzione. Lascia un campo vuoto per mantenere il valore esistente.",
+ "pt": "Salvas como segredos e injetadas no agente em tempo de execução. Deixe um campo em branco para manter o valor existente.",
+ "es": "Guardadas como secretos e inyectadas en el agente en tiempo de ejecución. Deja un campo en blanco para conservar el valor existente.",
+ "ar": "محفوظة كأسرار ويتم حقنها في العميل أثناء وقت التشغيل. اترك الحقل فارغًا للاحتفاظ بالقيمة الحالية.",
+ "fr": "Enregistrées en tant que secrets et injectées dans l'agent à l'exécution. Laissez un champ vide pour conserver la valeur existante.",
+ "tr": "Sırlar olarak kaydedilir ve çalışma zamanında aracıya enjekte edilir. Mevcut değeri korumak için bir alanı boş bırakın.",
+ "de": "Als Secrets gespeichert und zur Laufzeit in den Agenten injiziert. Lass ein Feld leer, um den vorhandenen Wert beizubehalten.",
+ "uk": "Зберігаються як секрети та вводяться в агент під час виконання. Залиште поле порожнім, щоб зберегти наявне значення.",
+ "ca": "Desades com a secrets i injectades a l'agent en temps d'execució. Deixa un camp en blanc per conservar el valor existent."
+ },
"SETTINGS$AGENT_DISABLED_TOOLTIP": {
"en": "Disabled while {{agentName}} is the active agent",
"ja": "Disabled while {{agentName}} is the active agent",
@@ -22881,6 +22932,15 @@
"tr": "Bu konuşmanın sandbox'ı kaldırıldı. Yukarıdaki geçmiş salt okunur modundadır.",
"uk": "Пісочницю цієї розмови видалено. Наведена вище історія доступна лише для читання."
},
+ "CHAT_INTERFACE$ACP_RESUME_SANDBOX_DESCRIPTION": {
+ "en": "This conversation's sandbox was recycled. Resume to continue where you left off."
+ },
+ "CHAT_INTERFACE$ACP_RESUME_BUTTON": {
+ "en": "Resume conversation"
+ },
+ "CHAT_INTERFACE$ACP_RESUME_STARTING": {
+ "en": "Resuming…"
+ },
"CHAT_INTERFACE$ERROR_SANDBOX_TITLE": {
"en": "Sandbox error",
"ja": "サンドボックスエラー",
@@ -29493,5 +29553,141 @@
"uk": "No Backend Available",
"zh-CN": "No Backend Available",
"zh-TW": "No Backend Available"
+ },
+ "ONBOARDING$ACP_SECRET_FILE_BLOB_HINT": {
+ "en": "Paste the full contents of {{file}}. Run `cat {{file}}` to get it. Saved as a secret and written to disk for the agent at runtime.",
+ "ja": "{{file}} の内容全体を貼り付けてください。`cat {{file}}` を実行して取得できます。シークレットとして保存され、実行時にエージェント用にディスクへ書き出されます。",
+ "zh-CN": "粘贴 {{file}} 的完整内容。运行 `cat {{file}}` 获取。它会作为密钥保存,并在运行时写入磁盘供智能体使用。",
+ "zh-TW": "貼上 {{file}} 的完整內容。執行 `cat {{file}}` 取得。將以密鑰形式儲存,並在執行時寫入磁碟供代理使用。",
+ "ko-KR": "{{file}}의 전체 내용을 붙여넣으세요. `cat {{file}}`을 실행해 가져올 수 있습니다. 비밀로 저장되며 실행 시 에이전트를 위해 디스크에 기록됩니다.",
+ "no": "Lim inn hele innholdet i {{file}}. Kjør `cat {{file}}` for å hente det. Lagres som en hemmelighet og skrives til disk for agenten ved kjøretid.",
+ "ar": "الصق المحتوى الكامل لـ {{file}}. شغّل `cat {{file}}` للحصول عليه. يُحفظ كسرّ ويُكتب على القرص للوكيل عند التشغيل.",
+ "de": "Füge den vollständigen Inhalt von {{file}} ein. Führe `cat {{file}}` aus, um ihn zu erhalten. Wird als Secret gespeichert und zur Laufzeit für den Agenten auf die Festplatte geschrieben.",
+ "fr": "Collez le contenu complet de {{file}}. Exécutez `cat {{file}}` pour l'obtenir. Enregistré comme secret et écrit sur le disque pour l'agent à l'exécution.",
+ "it": "Incolla l'intero contenuto di {{file}}. Esegui `cat {{file}}` per ottenerlo. Salvato come secret e scritto su disco per l'agente in fase di esecuzione.",
+ "pt": "Cole o conteúdo completo de {{file}}. Execute `cat {{file}}` para obtê-lo. Salvo como secret e gravado em disco para o agente em tempo de execução.",
+ "es": "Pega el contenido completo de {{file}}. Ejecuta `cat {{file}}` para obtenerlo. Se guarda como secreto y se escribe en disco para el agente en tiempo de ejecución.",
+ "ca": "Enganxa el contingut complet de {{file}}. Executa `cat {{file}}` per obtenir-lo. Es desa com a secret i s'escriu al disc per a l'agent en temps d'execució.",
+ "tr": "{{file}} dosyasının tüm içeriğini yapıştırın. Almak için `cat {{file}}` çalıştırın. Bir secret olarak kaydedilir ve çalışma zamanında aracı için diske yazılır.",
+ "uk": "Вставте повний вміст {{file}}. Виконайте `cat {{file}}`, щоб отримати його. Зберігається як секрет і записується на диск для агента під час виконання."
+ },
+ "ONBOARDING$ACP_SECRET_OAUTH_TOKEN_HINT": {
+ "en": "Subscription OAuth token for Claude Pro/Max. Run `claude setup-token` in your terminal to get it.",
+ "ja": "Claude Pro/Max のサブスクリプション OAuth トークン。ターミナルで `claude setup-token` を実行して取得してください。",
+ "zh-CN": "Claude Pro/Max 的订阅 OAuth 令牌。在终端运行 `claude setup-token` 获取。",
+ "zh-TW": "Claude Pro/Max 的訂閱 OAuth 權杖。在終端機執行 `claude setup-token` 取得。",
+ "ko-KR": "Claude Pro/Max 구독 OAuth 토큰입니다. 터미널에서 `claude setup-token`을 실행해 받으세요.",
+ "no": "OAuth-token for Claude Pro/Max-abonnement. Kjør `claude setup-token` i terminalen for å hente det.",
+ "ar": "رمز OAuth لاشتراك Claude Pro/Max. شغّل `claude setup-token` في الطرفية للحصول عليه.",
+ "de": "OAuth-Token des Claude-Pro/Max-Abonnements. Führe `claude setup-token` im Terminal aus, um es zu erhalten.",
+ "fr": "Jeton OAuth d'abonnement Claude Pro/Max. Exécutez `claude setup-token` dans votre terminal pour l'obtenir.",
+ "it": "Token OAuth dell'abbonamento Claude Pro/Max. Esegui `claude setup-token` nel terminale per ottenerlo.",
+ "pt": "Token OAuth da assinatura Claude Pro/Max. Execute `claude setup-token` no terminal para obtê-lo.",
+ "es": "Token OAuth de la suscripción Claude Pro/Max. Ejecuta `claude setup-token` en tu terminal para obtenerlo.",
+ "ca": "Token OAuth de la subscripció Claude Pro/Max. Executa `claude setup-token` al terminal per obtenir-lo.",
+ "tr": "Claude Pro/Max abonelik OAuth belirteci. Almak için terminalde `claude setup-token` çalıştırın.",
+ "uk": "OAuth-токен передплати Claude Pro/Max. Виконайте `claude setup-token` у терміналі, щоб отримати його."
+ },
+ "ONBOARDING$ACP_SECRET_GCP_PROJECT_HINT": {
+ "en": "Google Cloud project ID for Vertex AI (e.g. the output of `gcloud config get-value project`).",
+ "ja": "Vertex AI 用の Google Cloud プロジェクト ID(例: `gcloud config get-value project` の出力)。",
+ "zh-CN": "用于 Vertex AI 的 Google Cloud 项目 ID(例如 `gcloud config get-value project` 的输出)。",
+ "zh-TW": "用於 Vertex AI 的 Google Cloud 專案 ID(例如 `gcloud config get-value project` 的輸出)。",
+ "ko-KR": "Vertex AI용 Google Cloud 프로젝트 ID(예: `gcloud config get-value project`의 출력).",
+ "no": "Google Cloud-prosjekt-ID for Vertex AI (f.eks. utdata fra `gcloud config get-value project`).",
+ "ar": "معرّف مشروع Google Cloud لـ Vertex AI (مثل ناتج `gcloud config get-value project`).",
+ "de": "Google-Cloud-Projekt-ID für Vertex AI (z. B. die Ausgabe von `gcloud config get-value project`).",
+ "fr": "ID de projet Google Cloud pour Vertex AI (par ex. la sortie de `gcloud config get-value project`).",
+ "it": "ID progetto Google Cloud per Vertex AI (ad es. l'output di `gcloud config get-value project`).",
+ "pt": "ID do projeto Google Cloud para o Vertex AI (por ex. a saída de `gcloud config get-value project`).",
+ "es": "ID de proyecto de Google Cloud para Vertex AI (p. ej. la salida de `gcloud config get-value project`).",
+ "ca": "ID de projecte de Google Cloud per a Vertex AI (p. ex. la sortida de `gcloud config get-value project`).",
+ "tr": "Vertex AI için Google Cloud proje kimliği (örn. `gcloud config get-value project` çıktısı).",
+ "uk": "Ідентифікатор проєкту Google Cloud для Vertex AI (напр. вивід `gcloud config get-value project`)."
+ },
+ "ONBOARDING$ACP_SECRET_GCP_LOCATION_HINT": {
+ "en": "Vertex AI region, for example us-central1.",
+ "ja": "Vertex AI のリージョン(例: us-central1)。",
+ "zh-CN": "Vertex AI 区域,例如 us-central1。",
+ "zh-TW": "Vertex AI 區域,例如 us-central1。",
+ "ko-KR": "Vertex AI 리전입니다(예: us-central1).",
+ "no": "Vertex AI-region, for eksempel us-central1.",
+ "ar": "منطقة Vertex AI، على سبيل المثال us-central1.",
+ "de": "Vertex-AI-Region, zum Beispiel us-central1.",
+ "fr": "Région Vertex AI, par exemple us-central1.",
+ "it": "Regione Vertex AI, ad esempio us-central1.",
+ "pt": "Região do Vertex AI, por exemplo us-central1.",
+ "es": "Región de Vertex AI, por ejemplo us-central1.",
+ "ca": "Regió de Vertex AI, per exemple us-central1.",
+ "tr": "Vertex AI bölgesi, örneğin us-central1.",
+ "uk": "Регіон Vertex AI, наприклад us-central1."
+ },
+ "ONBOARDING$ACP_SECRET_VERTEXAI_FLAG_HINT": {
+ "en": "Set to true to route Gemini through Vertex AI using the credentials above.",
+ "ja": "上記の認証情報を使って Gemini を Vertex AI 経由で利用する場合は true に設定します。",
+ "zh-CN": "设置为 true 可使用上述凭据通过 Vertex AI 调用 Gemini。",
+ "zh-TW": "設定為 true 可使用上述憑證透過 Vertex AI 呼叫 Gemini。",
+ "ko-KR": "위 자격 증명을 사용해 Gemini를 Vertex AI로 라우팅하려면 true로 설정하세요.",
+ "no": "Sett til true for å rute Gemini gjennom Vertex AI med legitimasjonen ovenfor.",
+ "ar": "اضبطه على true لتوجيه Gemini عبر Vertex AI باستخدام بيانات الاعتماد أعلاه.",
+ "de": "Auf true setzen, um Gemini mit den obigen Anmeldedaten über Vertex AI zu leiten.",
+ "fr": "Définissez sur true pour acheminer Gemini via Vertex AI avec les identifiants ci-dessus.",
+ "it": "Imposta su true per instradare Gemini tramite Vertex AI usando le credenziali sopra.",
+ "pt": "Defina como true para encaminhar o Gemini pelo Vertex AI usando as credenciais acima.",
+ "es": "Ponlo en true para enrutar Gemini a través de Vertex AI con las credenciales anteriores.",
+ "ca": "Posa'l a true per encaminar Gemini a través de Vertex AI amb les credencials anteriors.",
+ "tr": "Yukarıdaki kimlik bilgilerini kullanarak Gemini'yi Vertex AI üzerinden yönlendirmek için true yapın.",
+ "uk": "Установіть true, щоб спрямувати Gemini через Vertex AI з наведеними вище обліковими даними."
+ },
+ "ONBOARDING$ACP_SECRETS_REQUIRED_NOTE": {
+ "en": "This backend has no host login, so credentials are required to run {{provider}}.",
+ "ja": "このバックエンドにはホストログインがないため、{{provider}} を実行するには認証情報が必要です。",
+ "zh-CN": "此后端没有主机登录,因此运行 {{provider}} 需要提供凭据。",
+ "zh-TW": "此後端沒有主機登入,因此執行 {{provider}} 需要提供憑證。",
+ "ko-KR": "이 백엔드에는 호스트 로그인이 없으므로 {{provider}}을(를) 실행하려면 자격 증명이 필요합니다.",
+ "no": "Denne backend-en har ingen vertspålogging, så legitimasjon kreves for å kjøre {{provider}}.",
+ "ar": "لا يحتوي هذا الخادم الخلفي على تسجيل دخول للمضيف، لذا تلزم بيانات الاعتماد لتشغيل {{provider}}.",
+ "de": "Dieses Backend hat keine Host-Anmeldung, daher sind Anmeldedaten erforderlich, um {{provider}} auszuführen.",
+ "fr": "Ce backend n'a pas de connexion hôte ; des identifiants sont donc requis pour exécuter {{provider}}.",
+ "it": "Questo backend non ha un login host, quindi sono necessarie le credenziali per eseguire {{provider}}.",
+ "pt": "Este backend não tem login no host, então são necessárias credenciais para executar o {{provider}}.",
+ "es": "Este backend no tiene inicio de sesión en el host, por lo que se requieren credenciales para ejecutar {{provider}}.",
+ "ca": "Aquest backend no té inici de sessió a l'amfitrió, així que calen credencials per executar {{provider}}.",
+ "tr": "Bu arka uçta ana makine girişi yok, bu yüzden {{provider}} çalıştırmak için kimlik bilgileri gerekir.",
+ "uk": "Цей бекенд не має входу на хост, тому для запуску {{provider}} потрібні облікові дані."
+ },
+ "ONBOARDING$ACP_SECRETS_REQUIRED_BLOCKED": {
+ "en": "Add the credentials above to continue, or sign in on the backend.",
+ "ja": "続行するには上記の認証情報を入力するか、バックエンドでサインインしてください。",
+ "zh-CN": "请填写上述凭据以继续,或在后端登录。",
+ "zh-TW": "請填寫上述憑證以繼續,或在後端登入。",
+ "ko-KR": "계속하려면 위 자격 증명을 입력하거나 백엔드에서 로그인하세요.",
+ "no": "Legg til legitimasjonen ovenfor for å fortsette, eller logg inn på backend-en.",
+ "ar": "أضف بيانات الاعتماد أعلاه للمتابعة، أو سجّل الدخول على الخادم الخلفي.",
+ "de": "Gib die obigen Anmeldedaten ein, um fortzufahren, oder melde dich im Backend an.",
+ "fr": "Ajoutez les identifiants ci-dessus pour continuer, ou connectez-vous sur le backend.",
+ "it": "Aggiungi le credenziali sopra per continuare oppure accedi sul backend.",
+ "pt": "Adicione as credenciais acima para continuar ou faça login no backend.",
+ "es": "Añade las credenciales anteriores para continuar, o inicia sesión en el backend.",
+ "ca": "Afegeix les credencials anteriors per continuar, o inicia la sessió al backend.",
+ "tr": "Devam etmek için yukarıdaki kimlik bilgilerini ekleyin veya arka uçta oturum açın.",
+ "uk": "Додайте облікові дані вище, щоб продовжити, або увійдіть на бекенді."
+ },
+ "ONBOARDING$ACP_SECRETS_ORPHANED_WARNING": {
+ "en": "Saved, but this backend can't use these credentials yet — they'll apply once it supports ACP file credentials.",
+ "ja": "保存しました。ただし、このバックエンドはまだこれらの認証情報を使用できません。ACP ファイル認証情報に対応すると適用されます。",
+ "zh-CN": "已保存,但此后端尚无法使用这些凭据——一旦支持 ACP 文件凭据即会生效。",
+ "zh-TW": "已儲存,但此後端尚無法使用這些憑證——一旦支援 ACP 檔案憑證即會生效。",
+ "ko-KR": "저장했지만 이 백엔드는 아직 이러한 자격 증명을 사용할 수 없습니다. ACP 파일 자격 증명을 지원하면 적용됩니다.",
+ "no": "Lagret, men denne backend-en kan ikke bruke disse legitimasjonene ennå – de gjelder så snart den støtter ACP-fillegitimasjoner.",
+ "ar": "تم الحفظ، لكن هذا الخادم الخلفي لا يمكنه استخدام بيانات الاعتماد هذه بعد — ستُطبَّق بمجرد دعمه لبيانات اعتماد ملفات ACP.",
+ "de": "Gespeichert, aber dieses Backend kann diese Anmeldedaten noch nicht verwenden – sie greifen, sobald es ACP-Datei-Anmeldedaten unterstützt.",
+ "fr": "Enregistré, mais ce backend ne peut pas encore utiliser ces identifiants — ils s'appliqueront dès qu'il prendra en charge les identifiants de fichier ACP.",
+ "it": "Salvato, ma questo backend non può ancora usare queste credenziali: si applicheranno quando supporterà le credenziali file ACP.",
+ "pt": "Salvo, mas este backend ainda não pode usar essas credenciais — elas serão aplicadas assim que ele suportar credenciais de arquivo ACP.",
+ "es": "Guardado, pero este backend aún no puede usar estas credenciales: se aplicarán cuando admita credenciales de archivo ACP.",
+ "ca": "Desat, però aquest backend encara no pot fer servir aquestes credencials: s'aplicaran quan admeti credencials de fitxer ACP.",
+ "tr": "Kaydedildi, ancak bu arka uç bu kimlik bilgilerini henüz kullanamıyor — ACP dosya kimlik bilgilerini desteklediğinde geçerli olacaklar.",
+ "uk": "Збережено, але цей бекенд поки не може використовувати ці облікові дані — вони застосуються, щойно він підтримає файлові облікові дані ACP."
}
}
diff --git a/src/routes/agent-settings.tsx b/src/routes/agent-settings.tsx
index f2668be7ab..5a3cc07d79 100644
--- a/src/routes/agent-settings.tsx
+++ b/src/routes/agent-settings.tsx
@@ -7,6 +7,7 @@ import { useAgentSettingsSchema } from "#/hooks/query/use-agent-settings-schema"
import { SettingsDropdownInput } from "#/components/features/settings/settings-dropdown-input";
import { SettingsInput } from "#/components/features/settings/settings-input";
import { SettingsSwitch } from "#/components/features/settings/settings-switch";
+import { AcpCredentialsSection } from "#/components/features/settings/acp-credentials-section";
import { BrandButton } from "#/components/features/settings/brand-button";
import { Typography } from "#/ui/typography";
import { I18nKey } from "#/i18n/declaration";
@@ -26,6 +27,7 @@ import {
ACP_PROVIDERS,
ACP_CUSTOM_PRESET_KEY,
buildAcpAgentSettingsDiff,
+ getAcpPreferredDefaultModel,
getAcpProvider,
type ACPProviderConfig,
} from "#/constants/acp-providers";
@@ -150,7 +152,9 @@ function AgentSettingsScreen() {
const savedModel = settings.agent_settings?.acp_model;
const normalizedSavedModel =
typeof savedModel === "string" ? savedModel.trim() : "";
- setAcpModel(normalizedSavedModel || provider?.default_model || "");
+ setAcpModel(
+ normalizedSavedModel || getAcpPreferredDefaultModel(acpServer) || "",
+ );
setIsCustomAcpModel(
!!normalizedSavedModel &&
(!provider || !isKnownAcpModel(provider, normalizedSavedModel)),
@@ -213,9 +217,9 @@ function AgentSettingsScreen() {
: selectedProvider && isDefaultProviderCommand
? selectedProvider.key
: ACP_CUSTOM_PRESET_KEY;
- // ``model: undefined`` lets buildAcpAgentSettingsDiff seed the provider's
- // ``default_model`` for built-in keys; for the custom preset it falls
- // through to ``null`` since custom has no default.
+ // ``model: undefined`` lets buildAcpAgentSettingsDiff seed the
+ // provider's preferred default for built-in keys; for the custom preset
+ // it falls through to ``null`` since custom has no default.
const agentSettingsDiff = buildAcpAgentSettingsDiff(providerKey, {
command: useDefault ? [] : commandTokens,
model: acpModel.trim() || undefined,
@@ -306,7 +310,7 @@ function AgentSettingsScreen() {
const preferred = ACP_PROVIDERS[0];
if (preferred) {
setCommandText(formatCommand(preferred.default_command));
- setAcpModel(preferred.default_model ?? "");
+ setAcpModel(getAcpPreferredDefaultModel(preferred.key) ?? "");
setIsCustomAcpModel(false);
}
} else if (newType === "openhands") {
@@ -363,7 +367,7 @@ function AgentSettingsScreen() {
const provider = getAcpProvider(preset);
if (provider) {
setCommandText(formatCommand(provider.default_command));
- setAcpModel(provider.default_model ?? "");
+ setAcpModel(getAcpPreferredDefaultModel(preset) ?? "");
setIsCustomAcpModel(false);
} else if (preset === ACP_CUSTOM_PRESET_KEY) {
// Clear command + model: the previous provider's default
@@ -404,8 +408,7 @@ function AgentSettingsScreen() {
const prevPreset = detectPreset(commandText, ACP_PROVIDERS);
const nextPreset = detectPreset(nextCommandText, ACP_PROVIDERS);
if (nextPreset !== prevPreset) {
- const nextProvider = getAcpProvider(nextPreset);
- setAcpModel(nextProvider?.default_model ?? "");
+ setAcpModel(getAcpPreferredDefaultModel(nextPreset) ?? "");
setIsCustomAcpModel(false);
}
setCommandText(nextCommandText);
@@ -473,6 +476,13 @@ function AgentSettingsScreen() {
</>
)}
+ {isAcp && selectedPreset !== ACP_CUSTOM_PRESET_KEY && (
+ <>
+ <hr className="border-[#3D4046]" />
+ <AcpCredentialsSection providerKey={selectedPreset} />
+ </>
+ )}
+
<div>
<BrandButton
testId="agent-save-button"
diff --git a/src/types/settings.ts b/src/types/settings.ts
index c11344a3e9..61b4a5b6d2 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -119,8 +119,7 @@ export type SettingsScope = "personal";
* (Claude Code / Codex / Gemini CLI / Custom). The LLM / condenser / MCP
* settings are inert; ``acp_command`` / ``acp_args`` / ``acp_model`` /
* ``acp_server`` apply instead. Provider credentials are supplied through the
- * Secrets panel (``request.secrets`` / ``agent_context.secrets``), never
- * through a per-agent env channel.
+ * Secrets panel (``request.secrets``), never through a per-agent env channel.
*/
export type AgentKind = "openhands" | "acp";
diff --git a/src/utils/custom-toast-handlers.tsx b/src/utils/custom-toast-handlers.tsx
index 64a8ce86f2..4f97657d5a 100644
--- a/src/utils/custom-toast-handlers.tsx
+++ b/src/utils/custom-toast-handlers.tsx
@@ -106,3 +106,18 @@ export const displaySuccessToast = (message: string) => {
{ ...TOAST_OPTIONS, duration },
);
};
+
+/**
+ * Neutral, non-success notice — used when an action completed but the outcome
+ * is qualified (e.g. a secret was saved but the active backend can't consume it
+ * yet). Renders without the success checkmark so it doesn't read as "all good".
+ */
+export const displayWarningToast = (message: string) => {
+ const duration = calculateToastDuration(message, 6000);
+ toast(
+ <span className="[word-break:break-word] [overflow-wrap:anywhere]">
+ {message}
+ </span>,
+ { ...TOAST_OPTIONS, icon: "⚠️", duration },
+ );
+};
diff --git a/tests/e2e/live-acp/README.md b/tests/e2e/live-acp/README.md
new file mode 100644
index 0000000000..68016aeadd
--- /dev/null
+++ b/tests/e2e/live-acp/README.md
@@ -0,0 +1,76 @@
+# Live ACP-in-Docker e2e
+
+Proves the containerized ACP credential path **through Canvas's own code** —
+each credential is saved to the agent-server's secret store (as onboarding does)
+and `buildStartConversationRequest` references it as a `LookupSecret` the server
+resolves at spawn time — against a real agent-server container, with real
+provider API calls. It's the "it actually works" companion to the unit tests in
+`__tests__/api/agent-server-adapter.test.ts` — those assert the request shape;
+this asserts a real agent reply.
+
+> **Requires `agent-server:1.25.0-python` or newer** (software-agent-sdk#3510):
+> the ACP credentials ride as loopback LookupSecrets, and only #3510 resolves
+> them off the event loop. An older image deadlocks the first turn.
+
+It is **not** part of `npm test` (it lives under `tests/`, which Vitest excludes,
+and needs a running container + real host credentials).
+
+## Run it
+
+```bash
+# 1. Agent-server container with the canvas_ui tool mounted (as the dev stack does).
+# Minimum 1.25.0-python (software-agent-sdk#3510); override for a newer build.
+docker run -d --name oh-acp -p 8010:8000 \
+ -v oh-acp-data:/workspace \
+ -v "$(pwd)/tools:/canvas-tools:ro" -e OH_EXTRA_PYTHON_PATH=/canvas-tools \
+ ghcr.io/openhands/agent-server:1.25.0-python
+
+# 2. Run the e2e (all providers, or a subset).
+npx vite-node -c tests/e2e/live-acp/vite-node.config.mts \
+ tests/e2e/live-acp/acp-docker-e2e.mts -- codex claude gemini
+
+# 3. Tear down (holds real creds).
+docker rm -f oh-acp
+```
+
+Credentials are read from the host and **never printed**: Codex `~/.codex/auth.json`,
+the Claude Code OAuth token from the macOS keychain, and the gcloud ADC for Gemini
+Vertex (`gcloud auth application-default login` first). A provider whose creds
+aren't present is skipped.
+
+The provider plans (models, credential collectors) and the HTTP/poll helpers are
+shared between both scripts via `harness.mts` — change a model default or
+credential knob there, not per script.
+
+## Last validated result (agent-server `1.25.0-python`, unified LookupSecret path)
+
+Re-validated 2026-06-07 against `ghcr.io/openhands/agent-server:1.25.0-python`
+(the first release with software-agent-sdk#3510), on a **fresh volume** — every
+credential seeded from the secret store, no leftover state. Each credential
+rides as a loopback `LookupSecret`; the logs confirm the agent-server resolved
+it (`GET /api/settings/secrets/<name>` 200) during ACP cold-start — **no
+deadlock, no "Failed to start ACP server: timed out"**, which is exactly what
+#3510 fixes. Codex and Claude also passed the app-orchestrator script
+(`acp-docker-app-e2e.mts`).
+
+| Provider | Result | Evidence (agent-server logs) |
+|---|---|---|
+| **Codex** | ✅ real reply `ACPOK-CODEX` (both scripts) | `Materialised ACP file-secret 'CODEX_AUTH_JSON' -> …/acp/codex/auth.json`; codex-acp 0.15.0; `Authenticating with ACP method: chatgpt` |
+| **Claude Code** | ✅ real reply `ACPOK-CLAUDE` (both scripts) | claude-agent-acp 0.30.0; `CLAUDE_CODE_OAUTH_TOKEN` env path (no `ANTHROPIC_BASE_URL`) |
+| **Gemini CLI** | ✅ real reply `ACPOK-GEMINI`¹ | `Materialised ACP file-secret 'GOOGLE_APPLICATION_CREDENTIALS_JSON' -> …/acp/gemini-cli/gcloud-credentials.json`; gemini-cli 0.45.1; `Authenticating with ACP method: vertex-ai` → real Vertex inference on `gemini-2.5-pro` |
+
+¹ **Gemini prerequisites.** The full turn passes with: a **fresh** host ADC
+(`gcloud auth application-default login` — a stale one fails as `invalid_rapt`,
+a credential problem, not a Canvas one), the **non-flash** `gemini-2.5-pro`
+model (gemini-cli 0.45.x re-resolves any `*-flash` id at generation time to its
+current default flash, which 404s on projects that don't serve it —
+software-agent-sdk#3532; this is why Canvas preselects `gemini-2.5-pro`), and
+`ACP_E2E_GEMINI_SESSION_MODE=default` to clear the separate gemini-cli ≥0.43
+`set_session_mode("yolo")` headless-init blocker.
+
+## Knobs
+
+- `ACP_E2E_BASE_URL` (default `http://localhost:8010`)
+- `ACP_E2E_CODEX_MODEL` / `ACP_E2E_CLAUDE_MODEL` / `ACP_E2E_GEMINI_MODEL`
+- `ACP_E2E_GEMINI_SESSION_MODE` (set `default` to bypass the SDK `yolo` blocker)
+- `GOOGLE_CLOUD_PROJECT` / `GOOGLE_CLOUD_LOCATION` (else read from gcloud / `us-central1`)
diff --git a/tests/e2e/live-acp/acp-docker-app-e2e.mts b/tests/e2e/live-acp/acp-docker-app-e2e.mts
new file mode 100644
index 0000000000..3e419558b6
--- /dev/null
+++ b/tests/e2e/live-acp/acp-docker-app-e2e.mts
@@ -0,0 +1,134 @@
+/**
+ * Live e2e through the APPLICATION's own conversation-start path (not the
+ * isolated request builder). Drives the same functions the running app calls:
+ *
+ * onboarding "Set up credentials" -> SecretsService.createSecret(name, value)
+ * choose-agent step -> buildAcpAgentSettingsDiff(...) PATCH /api/settings
+ * conversation start -> buildStartConversationRequestWithEncryptedSettings(...)
+ * (reads settings + the saved secret NAMES,
+ * emits each as a LookupSecret the
+ * agent-server resolves from its store)
+ *
+ * This is the piece the request-builder script can't cover: it proves the saved
+ * credentials round-trip through the backend store and the orchestrator emits
+ * the right LookupSecrets, end-to-end, against a real container.
+ *
+ * Requires an agent-server with software-agent-sdk#3510 (first in v1.25.0) —
+ * ACP credentials resolve off the event loop; an older image deadlocks.
+ *
+ * npx vite-node -c tests/e2e/live-acp/vite-node.config.mts \
+ * tests/e2e/live-acp/acp-docker-app-e2e.mts -- codex
+ *
+ * One provider per process (settings are global on the backend; a fresh process
+ * avoids the SettingsService cache bleeding between providers).
+ *
+ * The provider plans, host credential collectors, and HTTP/poll helpers are
+ * shared with the request-builder script — see ./harness.mts.
+ */
+import { SecretsService } from "#/api/secrets-service";
+import { buildStartConversationRequestWithEncryptedSettings } from "#/api/agent-server-adapter";
+import { buildAcpAgentSettingsDiff } from "#/constants/acp-providers";
+import { SettingsClient } from "@openhands/typescript-client/clients";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
+import {
+ BASE,
+ fetchFinalReply,
+ getProviderPlan,
+ pollUntilTerminal,
+ postJson,
+ registerDockerBackend,
+ type ProviderPlan,
+} from "./harness.mts";
+
+registerDockerBackend();
+
+async function run(plan: ProviderPlan): Promise<boolean> {
+ const secrets = plan.collectSecrets();
+ if (!secrets) {
+ console.log(`⏭️ ${plan.id}: SKIP — credentials not present on host`);
+ return true;
+ }
+
+ const settingsClient = new SettingsClient(getAgentServerClientOptions());
+
+ // 1) onboarding "Set up credentials" — save each container cred as a global
+ // secret via the SAME service call the SetupAcpSecretsStep makes.
+ console.log(
+ `▶️ ${plan.id}: saving container creds via SecretsService.createSecret [${Object.keys(
+ secrets,
+ ).join(", ")}]`,
+ );
+ for (const [name, value] of Object.entries(secrets)) {
+ await SecretsService.createSecret(name, value);
+ }
+
+ // 2) choose-agent step — persist ACP agent settings via the app's diff builder.
+ const diff = buildAcpAgentSettingsDiff(plan.acpServer, { model: plan.model });
+ if (!diff) throw new Error(`no settings diff for ${plan.acpServer}`);
+ if (plan.sessionMode) diff.acp_session_mode = plan.sessionMode;
+ await settingsClient.updateSettings({ agent_settings_diff: diff });
+ console.log(
+ ` PATCHed agent settings: ${JSON.stringify({
+ acp_server: diff.acp_server,
+ acp_model: diff.acp_model,
+ ...(plan.sessionMode ? { acp_session_mode: plan.sessionMode } : {}),
+ })}`,
+ );
+
+ // 3) conversation start — the app's own orchestrator. It re-reads settings +
+ // the saved secret names and emits each as a LookupSecret.
+ const workingDir = `/workspace/app-e2e/${plan.id}-${Date.now()}`;
+ const payload = (await buildStartConversationRequestWithEncryptedSettings({
+ settings: undefined as any, // base settings come from the backend fetch
+ query: `Reply with exactly: ${plan.expectedToken}`,
+ workingDir,
+ })) as any;
+
+ const emitted = payload.secrets ?? {};
+ console.log(
+ ` orchestrator emitted secrets: ${Object.entries(emitted)
+ .map(([k, v]: any) => `${k}=${v.kind}`)
+ .join(", ")}`,
+ );
+ // Assert the orchestrator emitted a LookupSecret for each saved credential.
+ const missing = Object.keys(secrets).filter(
+ (n) => emitted[n]?.kind !== "LookupSecret",
+ );
+ if (missing.length > 0) {
+ console.log(
+ ` ❌ ${plan.id}: orchestrator did NOT emit a LookupSecret for: ${missing.join(", ")}`,
+ );
+ return false;
+ }
+
+ const created = await postJson(`${BASE}/api/conversations`, payload);
+ const id = created.id;
+ console.log(` conversation ${id} created; polling…`);
+
+ const status = await pollUntilTerminal(id);
+ const reply = await fetchFinalReply(id);
+ const ok = reply.includes(plan.expectedToken);
+ console.log(
+ ` status=${status} reply=${JSON.stringify(reply.slice(0, 160))}`,
+ );
+ console.log(` ${ok ? "✅ PASS" : "❌ FAIL"} (expected "${plan.expectedToken}")`);
+ return ok;
+}
+
+async function main() {
+ const args = process.argv.slice(2).filter((a) => a !== "--");
+ const plan = args[0] ? getProviderPlan(args[0]) : undefined;
+ if (!plan) {
+ console.error(`usage: ... acp-docker-app-e2e.mts -- <codex|claude|gemini>`);
+ process.exit(2);
+ }
+ console.log(`App-path e2e against ${BASE} — provider: ${plan.id}`);
+ const ok = await run(plan).catch((e) => {
+ console.error(` ❌ ${plan.id} errored: ${(e as Error).message}`);
+ return false;
+ });
+ console.log(ok ? "\nPASS" : "\nFAIL");
+ process.exit(ok ? 0 : 1);
+}
+
+main();
diff --git a/tests/e2e/live-acp/acp-docker-e2e.mts b/tests/e2e/live-acp/acp-docker-e2e.mts
new file mode 100644
index 0000000000..f2858119e0
--- /dev/null
+++ b/tests/e2e/live-acp/acp-docker-e2e.mts
@@ -0,0 +1,185 @@
+/**
+ * Live e2e for the containerized ACP path (agent-canvas#1013/#1014).
+ *
+ * Exercises CANVAS'S OWN code path — it saves each credential to the
+ * agent-server's secret store via {@link SecretsService.createSecret} (exactly
+ * as onboarding does), then imports {@link buildStartConversationRequest} and
+ * builds each provider's start request as the app does, POSTs it to a real
+ * agent-server container, and asserts a real agent reply. This is the
+ * "it actually works" check the unit tests can't give: it proves the
+ * LookupSecrets Canvas emits resolve back from the store and authenticate the
+ * CLI end-to-end (including the SDK's acp_file_secrets materialisation).
+ *
+ * Requires an agent-server with software-agent-sdk#3510 (first in v1.25.0): the
+ * ACP credentials ride as loopback LookupSecrets, and only #3510 resolves them
+ * off the event loop — an older image deadlocks ("Failed to start ACP server:
+ * timed out").
+ *
+ * Excluded from `npm test` (lives under tests/). Run it by hand against a
+ * running container:
+ *
+ * docker run -d --name oh-acp -p 8010:8000 -v oh-acp-data:/workspace \
+ * -v "$(pwd)/tools:/canvas-tools:ro" -e OH_EXTRA_PYTHON_PATH=/canvas-tools \
+ * ghcr.io/openhands/agent-server:1.25.0-python
+ * npx vite-node -c tests/e2e/live-acp/vite-node.config.mts \
+ * tests/e2e/live-acp/acp-docker-e2e.mts -- codex claude gemini
+ *
+ * The provider plans, host credential collectors, and HTTP/poll helpers are
+ * shared with the app-path script — see ./harness.mts. A provider whose
+ * credentials aren't present on the host is skipped.
+ */
+import { SecretsService } from "#/api/secrets-service";
+import { buildStartConversationRequest } from "#/api/agent-server-adapter";
+import { DEFAULT_SETTINGS } from "#/services/settings";
+import {
+ BASE,
+ PROVIDER_PLANS,
+ fetchFinalReply,
+ pollUntilTerminal,
+ postJson,
+ registerDockerBackend,
+ type ProviderId,
+ type ProviderPlan,
+} from "./harness.mts";
+
+registerDockerBackend();
+
+// Canvas gives every conversation its OWN working_dir (<base>/<id_hex>) so the
+// agent-server can init a fresh git repo + worktree per conversation. Mirror
+// that here with a unique dir per run/provider — sharing one dir makes the
+// second `git worktree add` collide on the same repo.
+const WORKING_DIR_BASE =
+ process.env.ACP_E2E_WORKING_DIR_BASE ?? "/workspace/acp-e2e";
+
+function buildRequest(
+ plan: ProviderPlan,
+ secretNames: string[],
+ workingDir: string,
+) {
+ // Build via the same function the app uses — this is the whole point of the
+ // exercise. Each saved credential is referenced by name as a LookupSecret; the
+ // agent-server resolves the value back from its own store (where the
+ // SecretsService.createSecret calls above put it) at spawn time.
+ return buildStartConversationRequest({
+ settings: {
+ ...DEFAULT_SETTINGS,
+ agent_settings: {
+ ...DEFAULT_SETTINGS.agent_settings,
+ agent_kind: "acp",
+ acp_server: plan.acpServer,
+ acp_model: plan.model,
+ ...(plan.sessionMode ? { acp_session_mode: plan.sessionMode } : {}),
+ },
+ conversation_settings: {
+ ...DEFAULT_SETTINGS.conversation_settings,
+ max_iterations: 8,
+ },
+ },
+ query: `Reply with exactly: ${plan.expectedToken}`,
+ workingDir,
+ customSecrets: secretNames.map((name) => ({ name })),
+ });
+}
+
+async function runProvider(plan: ProviderPlan): Promise<boolean> {
+ const secrets = plan.collectSecrets();
+ if (!secrets) {
+ console.log(`\n⏭️ ${plan.id}: SKIP — credentials not present on host`);
+ return true; // skip is not a failure
+ }
+ console.log(
+ `\n▶️ ${plan.id}: building request via buildStartConversationRequest ` +
+ `(acp_server=${plan.acpServer}, acp_model=${plan.model}, ` +
+ `secrets=[${Object.keys(secrets).join(", ")}])`,
+ );
+
+ // Onboarding step: save each credential to the agent-server's secret store so
+ // the LookupSecret the start request emits can be resolved back.
+ for (const [name, value] of Object.entries(secrets)) {
+ await SecretsService.createSecret(name, value);
+ }
+
+ const workingDir = `${WORKING_DIR_BASE}/${plan.id}-${Date.now()}`;
+ const payload = buildRequest(plan, Object.keys(secrets), workingDir);
+ // Sanity-check the request the app would send, without leaking values.
+ const emitted = payload.secrets as Record<string, { kind: string }>;
+ console.log(
+ ` emitted secret kinds: ${Object.entries(emitted ?? {})
+ .map(([k, v]) => `${k}=${v.kind}`)
+ .join(", ")}`,
+ );
+ const notLookup = Object.entries(emitted ?? {}).filter(
+ ([, v]) => v.kind !== "LookupSecret",
+ );
+ if (notLookup.length > 0) {
+ console.log(
+ ` ❌ ${plan.id}: expected all secrets as LookupSecret, got ${notLookup
+ .map(([k, v]) => `${k}=${v.kind}`)
+ .join(", ")}`,
+ );
+ return false;
+ }
+
+ const created = await postJson(`${BASE}/api/conversations`, payload);
+ const id = created.id;
+ console.log(` conversation ${id} created; polling…`);
+
+ const status = await pollUntilTerminal(id);
+ console.log(` execution_status=${status}`);
+
+ const reply = await fetchFinalReply(id);
+ const ok = reply.includes(plan.expectedToken);
+ console.log(
+ ` reply: ${JSON.stringify(reply.slice(0, 200))}\n ${
+ ok ? "✅ PASS" : "❌ FAIL"
+ } (expected to contain "${plan.expectedToken}")`,
+ );
+ if (!ok && plan.id === "gemini" && !plan.sessionMode && status === "error") {
+ // The credential path (materialise ADC → vertex-ai auth) is what this PR
+ // proves; gemini-cli ≥0.43 rejects the registry default session mode
+ // ("yolo") during headless init — an SDK/gemini-cli issue, not a credential
+ // one. Re-run with the override to confirm the full turn.
+ console.log(
+ " ℹ️ Likely the SDK/gemini-cli set_session_mode('yolo') blocker, not a " +
+ "credential problem. Re-run with ACP_E2E_GEMINI_SESSION_MODE=default to " +
+ "confirm the credential path end-to-end.",
+ );
+ }
+ return ok;
+}
+
+async function main() {
+ const args = process.argv.slice(2).filter((a) => a !== "--");
+ const selected =
+ args.length > 0
+ ? PROVIDER_PLANS.filter((p) => args.includes(p.id))
+ : PROVIDER_PLANS;
+
+ console.log(`ACP Docker e2e against ${BASE} — providers: ${selected
+ .map((p) => p.id)
+ .join(", ")}`);
+
+ const results: Array<{ id: ProviderId; ok: boolean }> = [];
+ for (const plan of selected) {
+ try {
+ results.push({ id: plan.id, ok: await runProvider(plan) });
+ } catch (error) {
+ console.log(` ❌ ${plan.id} errored: ${(error as Error).message}`);
+ results.push({ id: plan.id, ok: false });
+ }
+ }
+
+ console.log("\n=== summary ===");
+ for (const r of results) console.log(` ${r.ok ? "✅" : "❌"} ${r.id}`);
+ const failed = results.filter((r) => !r.ok);
+ if (failed.length > 0) {
+ console.log(`\n${failed.length} provider(s) failed.`);
+ process.exit(1);
+ }
+ console.log("\nAll selected providers passed.");
+}
+
+main().catch((error) => {
+ console.error(error);
+ process.exit(1);
+});
diff --git a/tests/e2e/live-acp/harness.mts b/tests/e2e/live-acp/harness.mts
new file mode 100644
index 0000000000..2020bfc8c7
--- /dev/null
+++ b/tests/e2e/live-acp/harness.mts
@@ -0,0 +1,212 @@
+/**
+ * Shared plumbing for the live ACP-in-Docker e2e scripts
+ * (`acp-docker-e2e.mts` — request-builder path; `acp-docker-app-e2e.mts` —
+ * full app-orchestrator path): the per-provider plans + host credential
+ * collectors, the backend registration, and the HTTP/poll helpers. Keeping the
+ * plans in one place means a model default or credential knob can't drift
+ * between the two scripts.
+ *
+ * Credentials are read from the host and never printed: Codex
+ * ~/.codex/auth.json, the Claude Code OAuth token from the macOS keychain, and
+ * the gcloud ADC for Gemini Vertex.
+ */
+import { execFileSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { homedir } from "node:os";
+import path from "node:path";
+
+import {
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+
+export const BASE = process.env.ACP_E2E_BASE_URL ?? "http://localhost:8010";
+export const POLL_TIMEOUT_MS = Number(
+ process.env.ACP_E2E_TIMEOUT_MS ?? 180_000,
+);
+
+/**
+ * Point the app's backend registry at the container, exactly as if the user
+ * had added it in the backend selector. Everything downstream (SecretsService,
+ * SettingsService, buildStartConversationRequest's LookupSecret auth headers)
+ * resolves the host through this.
+ */
+export function registerDockerBackend(): void {
+ setRegisteredBackends([
+ {
+ id: "acp-docker",
+ name: "ACP Docker",
+ host: BASE,
+ apiKey: "",
+ kind: "local",
+ },
+ ]);
+ setActiveSelection({ backendId: "acp-docker", orgId: null });
+}
+
+export type ProviderId = "codex" | "claude" | "gemini";
+
+export interface ProviderPlan {
+ id: ProviderId;
+ /** ACP registry key sent as acp_server. */
+ acpServer: string;
+ /** acp_model to send (a model the account/Vertex project supports). */
+ model: string;
+ expectedToken: string;
+ /** Container-credential map (name -> value) or null when creds are missing. */
+ collectSecrets: () => Record<string, string> | null;
+ /**
+ * Optional ``acp_session_mode`` override (env-driven). Canvas itself sends
+ * none — the SDK then uses the provider's registry default. For Gemini that
+ * default (``yolo``) makes gemini-cli ≥0.43 error on ``set_session_mode``
+ * during headless init (an SDK/gemini-cli issue, not a credential one); set
+ * ``ACP_E2E_GEMINI_SESSION_MODE=default`` to confirm the credential path
+ * end-to-end past that blocker.
+ */
+ sessionMode?: string;
+}
+
+function readFileTrimmed(file: string): string | null {
+ try {
+ const value = readFileSync(file, "utf-8");
+ return value.trim().length > 0 ? value : null;
+ } catch {
+ return null;
+ }
+}
+
+function claudeOAuthToken(): string | null {
+ // macOS keychain entry written by Claude Code on login. On other platforms
+ // (no `security` binary) this throws into the catch → null → the runner
+ // reports the provider as "SKIP — credentials not present on host".
+ try {
+ const raw = execFileSync(
+ "security",
+ ["find-generic-password", "-s", "Claude Code-credentials", "-w"],
+ { encoding: "utf-8" },
+ );
+ const token = JSON.parse(raw)?.claudeAiOauth?.accessToken;
+ return typeof token === "string" && token.length > 0 ? token : null;
+ } catch {
+ return null;
+ }
+}
+
+function gcloudProject(): string | null {
+ try {
+ return (
+ execFileSync("gcloud", ["config", "get-value", "project"], {
+ encoding: "utf-8",
+ }).trim() || null
+ );
+ } catch {
+ return null;
+ }
+}
+
+export const PROVIDER_PLANS: ProviderPlan[] = [
+ {
+ id: "codex",
+ acpServer: "codex",
+ model: process.env.ACP_E2E_CODEX_MODEL ?? "gpt-5.5/medium",
+ expectedToken: "ACPOK-CODEX",
+ collectSecrets: () => {
+ const auth = readFileTrimmed(path.join(homedir(), ".codex", "auth.json"));
+ return auth ? { CODEX_AUTH_JSON: auth } : null;
+ },
+ },
+ {
+ id: "claude",
+ acpServer: "claude-code",
+ model: process.env.ACP_E2E_CLAUDE_MODEL ?? "claude-opus-4-7",
+ expectedToken: "ACPOK-CLAUDE",
+ collectSecrets: () => {
+ const token = claudeOAuthToken();
+ // NB: deliberately NOT setting ANTHROPIC_BASE_URL — an inherited base URL
+ // breaks the OAuth token's bearer auth.
+ return token ? { CLAUDE_CODE_OAUTH_TOKEN: token } : null;
+ },
+ },
+ {
+ id: "gemini",
+ acpServer: "gemini-cli",
+ model: process.env.ACP_E2E_GEMINI_MODEL ?? "gemini-2.5-pro",
+ expectedToken: "ACPOK-GEMINI",
+ collectSecrets: () => {
+ const adc = readFileTrimmed(
+ path.join(
+ homedir(),
+ ".config",
+ "gcloud",
+ "application_default_credentials.json",
+ ),
+ );
+ const project = process.env.GOOGLE_CLOUD_PROJECT ?? gcloudProject();
+ if (!adc || !project) return null;
+ return {
+ GOOGLE_APPLICATION_CREDENTIALS_JSON: adc,
+ GOOGLE_CLOUD_PROJECT: project,
+ GOOGLE_CLOUD_LOCATION:
+ process.env.GOOGLE_CLOUD_LOCATION ?? "us-central1",
+ GOOGLE_GENAI_USE_VERTEXAI: "true",
+ };
+ },
+ sessionMode: process.env.ACP_E2E_GEMINI_SESSION_MODE,
+ },
+];
+
+export function getProviderPlan(id: string): ProviderPlan | undefined {
+ return PROVIDER_PLANS.find((plan) => plan.id === id);
+}
+
+export async function postJson(url: string, body: unknown): Promise<any> {
+ const res = await fetch(url, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ const text = await res.text();
+ if (!res.ok) {
+ throw new Error(`POST ${url} -> ${res.status}: ${text.slice(0, 800)}`);
+ }
+ return text ? JSON.parse(text) : null;
+}
+
+export async function getJson(url: string): Promise<any> {
+ const res = await fetch(url);
+ const text = await res.text();
+ if (!res.ok) {
+ throw new Error(`GET ${url} -> ${res.status}: ${text.slice(0, 400)}`);
+ }
+ return text ? JSON.parse(text) : null;
+}
+
+// Terminal states for a single-turn run. NB: "idle" is deliberately NOT here —
+// a freshly-created conversation reports "idle" before the agent starts, so
+// treating it as terminal bails out before the reply exists. Wait for the run
+// to actually finish (or error/stuck).
+const TERMINAL = new Set(["finished", "error", "stuck", "stopped"]);
+
+/** Poll the conversation until a terminal state (or timeout); returns the last
+ * observed ``execution_status``. */
+export async function pollUntilTerminal(conversationId: string): Promise<string> {
+ const deadline = Date.now() + POLL_TIMEOUT_MS;
+ let status = "";
+ while (Date.now() < deadline) {
+ const info = await getJson(`${BASE}/api/conversations/${conversationId}`);
+ status = String(info.execution_status ?? "").toLowerCase();
+ if (TERMINAL.has(status)) break;
+ await new Promise((r) => setTimeout(r, 2500));
+ }
+ return status;
+}
+
+/** Fetch the agent's final response as a plain string. */
+export async function fetchFinalReply(conversationId: string): Promise<string> {
+ const final = await getJson(
+ `${BASE}/api/conversations/${conversationId}/agent_final_response`,
+ );
+ return typeof final === "string"
+ ? final
+ : String(final?.response ?? final?.content ?? JSON.stringify(final));
+}
diff --git a/tests/e2e/live-acp/vite-node.config.mts b/tests/e2e/live-acp/vite-node.config.mts
new file mode 100644
index 0000000000..1e0ea24608
--- /dev/null
+++ b/tests/e2e/live-acp/vite-node.config.mts
@@ -0,0 +1,18 @@
+import { fileURLToPath } from "node:url";
+import { defineConfig } from "vite";
+
+// Minimal config so `vite-node` can run the live ACP e2e script outside the
+// app's full Vite/React-Router pipeline. We only need the `#/*` → `src/*` path
+// alias (the app resolves it via tsconfig-paths, which vite-node doesn't load)
+// and to inline the typescript-client so its ESM resolves the same way Vitest
+// configures it.
+const srcDir = fileURLToPath(new URL("../../../src", import.meta.url));
+
+export default defineConfig({
+ resolve: {
+ alias: [{ find: /^#\//, replacement: `${srcDir}/` }],
+ },
+ ssr: {
+ noExternal: ["@openhands/typescript-client"],
+ },
+});