๐ OpenHands: AI-Driven Development
feat: two auth modes โ local (auto-key) and public (paste-key) (#790)
Rohit Malhotra14b1b1e8ad43
diff --git a/AGENTS.md b/AGENTS.mdindex 7ea9dcfb73..52100f1daa 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -406,6 +406,14 @@ When adding code that needs a new string, decide up front which rule it falls un2. **localStorage** (`openhands-agent-server-git-provider-tokens`) - for frontend git API calls (repo search, branches, etc.)The `addGitProvider` method stores to server FIRST (must succeed), then updates localStorage. This ensures server-side persistence is the source of truth.- Agent server connection settings now live at `Settings > Agent Server` (`/settings/agent-server`). The page reads deployment defaults from `VITE_BACKEND_BASE_URL` / `VITE_SESSION_API_KEY`, saves user overrides in the `openhands-agent-server-config` localStorage key, and must stay reachable even when the backend compatibility probe fails so users can recover from missing or wrong backend configuration.+- Auth modes for `agent-canvas` (dev and production):+ - **Local mode** (default, no `--public` flag): A session API key is auto-generated and persisted to `~/.openhands/agent-canvas/session-api-key.txt`. The key is baked into the Vite dev server via `VITE_SESSION_API_KEY` or injected into static builds via `static-server.mjs --session-api-key`. Users never need to paste a key.+ - **Public mode** (`--public` flag): Requires `LOCAL_BACKEND_API_KEY` env var. The key is used as the agent-server session key (`OH_SESSION_API_KEYS_0`) but is NOT baked into the frontend (no `VITE_SESSION_API_KEY`, no `--session-api-key` to static-server). The frontend detects a 401 from `/server_info` via `isAgentServerAuthError()` and shows `ApiKeyEntryScreen` (`src/components/features/backends/api-key-entry-screen.tsx`). The screen reuses `BackendForm` with the host pre-filled (read-only) and prompts for the API key. On submit, the key is persisted to `localStorage['openhands-agent-server-config']` and the page reloads.+ - Dev usage: `LOCAL_BACKEND_API_KEY=my-secret npm run dev -- --public`+ - Production usage: `LOCAL_BACKEND_API_KEY=my-secret npx @openhands/agent-canvas --public`+ - The `--public` flag is supported by both `scripts/dev-with-automation.mjs` (parsed in `parseArgs()`, propagated via `config.isPublic`) and `bin/agent-canvas.mjs` (passed as `isPublic` to `main()`).+ - The 401 detection lives in `src/api/agent-server-compatibility.ts` (`isAgentServerAuthError()`), and the gate is in `src/root.tsx`'s `App` component, between the `AgentServerUnavailableError` check and the `<Outlet />` render.+ - **Key rotation resilience (non-public):** When `VITE_SESSION_API_KEY` is baked in and differs from the stored key in `openhands-agent-server-config.sessionApiKey` (localStorage), `syncBakedSessionApiKey()` (called from `readStoredBackends()` at module init) overwrites the stale stored key. Without this sync, `getConfiguredSessionApiKey()` returns the stale localStorage value (which takes priority over the env fallback), poisoning the backend registry seed via `makeDefaultLocalBackend()` and causing 401s from `loadAgentServerInfo()`. The `static-server.mjs` injection script also always overwrites when the key differs (changed from `if(!_c.sessionApiKey)` to `if(_c.sessionApiKey!==<runtime_key>)`). E2E coverage: `tests/e2e/mock-llm/mock-llm-auth-modes.spec.ts`.- Backend/footer actions that launch modals from inside a dropdown or popover should intercept `onMouseDown` to keep the menu mounted, then perform the actual open on `onClick`. Current examples: `Add backend` / `Manage backends` in `src/components/features/backends/backend-selector.tsx`, plus the mirrored workspace-footer buttons in `src/components/features/conversation-panel/new-conversation-button.tsx`.- `BackendSelector`'s cloud-org switch paths should never rethrow from the dropdown `onChange` handler: unexpected non-Axios failures need a generic error toast instead of an unhandled promise rejection, and the malformed `(cloud backend, null org)` self-heal path should fall back to the bundled backend if `/switch` fails.- `NewConversationButton` should support keyboard dismissal (`Escape`) for its inline popover, while still keeping the popover open when its modal children (`FolderBrowserModal`, `ManageWorkspacesModal`) are active.diff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.tsindex 15ac2fc08d..c82028b565 100644--- a/__tests__/api/agent-server-adapter.test.ts+++ b/__tests__/api/agent-server-adapter.test.ts@@ -36,6 +36,7 @@ vi.mock("#/api/agent-server-config", () => ({getAgentServerWorkingDir: mockGetAgentServerWorkingDir,getConfiguredWorkerUrls: vi.fn(() => []),shouldLoadPublicSkills: vi.fn(() => true),+ syncBakedSessionApiKey: vi.fn(),}));vi.mock("#/api/agent-server-compatibility", () => ({diff --git a/__tests__/api/agent-server-config.test.ts b/__tests__/api/agent-server-config.test.tsindex 953cbe1f06..7813a29783 100644--- a/__tests__/api/agent-server-config.test.ts+++ b/__tests__/api/agent-server-config.test.ts@@ -7,8 +7,11 @@ import {getAgentServerFormDefaults,getAgentServerSessionApiKey,getAgentServerWorkingDir,+ isAuthRequired,+ isAuthRequiredAndMissing,saveAgentServerConfig,shouldLoadPublicSkills,+ syncBakedSessionApiKey,} from "#/api/agent-server-config";const ORIGINAL_LOCATION = window.location;@@ -118,3 +121,153 @@ describe("agent server config", () => {expect(shouldLoadPublicSkills()).toBe(false);});});++describe("isAuthRequired", () => {+ afterEach(() => {+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_AUTH_REQUIRED__;+ });++ it("returns false when neither env var nor window flag is set", () => {+ expect(isAuthRequired()).toBe(false);+ });++ it("returns true when VITE_AUTH_REQUIRED is 'true'", () => {+ vi.stubEnv("VITE_AUTH_REQUIRED", "true");+ expect(isAuthRequired()).toBe(true);+ });++ it("returns true when window.__AGENT_CANVAS_AUTH_REQUIRED__ is set (static binary path)", () => {+ (+ window as unknown as Record<string, unknown>+ ).__AGENT_CANVAS_AUTH_REQUIRED__ = true;+ expect(isAuthRequired()).toBe(true);+ });++ it("returns false when window flag is a non-true value", () => {+ (+ window as unknown as Record<string, unknown>+ ).__AGENT_CANVAS_AUTH_REQUIRED__ = "true";+ expect(isAuthRequired()).toBe(false);+ });+});++describe("isAuthRequiredAndMissing", () => {+ afterEach(() => {+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_AUTH_REQUIRED__;+ });++ it("returns false when VITE_AUTH_REQUIRED is not set", () => {+ expect(isAuthRequiredAndMissing()).toBe(false);+ });++ it("returns true when VITE_AUTH_REQUIRED is true and no key is configured", () => {+ vi.stubEnv("VITE_AUTH_REQUIRED", "true");++ expect(isAuthRequiredAndMissing()).toBe(true);+ });++ it("returns true via window flag when no key is configured", () => {+ (+ window as unknown as Record<string, unknown>+ ).__AGENT_CANVAS_AUTH_REQUIRED__ = true;++ expect(isAuthRequiredAndMissing()).toBe(true);+ });++ it("returns false when VITE_AUTH_REQUIRED is true but a key exists in localStorage", () => {+ vi.stubEnv("VITE_AUTH_REQUIRED", "true");+ saveAgentServerConfig({+ baseUrl: "http://localhost:8000",+ sessionApiKey: "stored-key",+ });++ expect(isAuthRequiredAndMissing()).toBe(false);+ });++ it("returns false when window flag is set but a key exists in localStorage", () => {+ (+ window as unknown as Record<string, unknown>+ ).__AGENT_CANVAS_AUTH_REQUIRED__ = true;+ saveAgentServerConfig({+ baseUrl: "http://localhost:8000",+ sessionApiKey: "stored-key",+ });++ expect(isAuthRequiredAndMissing()).toBe(false);+ });++ it("returns false when VITE_AUTH_REQUIRED is true but VITE_SESSION_API_KEY is baked in", () => {+ vi.stubEnv("VITE_AUTH_REQUIRED", "true");+ vi.stubEnv("VITE_SESSION_API_KEY", "baked-key");++ expect(isAuthRequiredAndMissing()).toBe(false);+ });++ it("returns false for non-'true' values of VITE_AUTH_REQUIRED", () => {+ vi.stubEnv("VITE_AUTH_REQUIRED", "false");++ expect(isAuthRequiredAndMissing()).toBe(false);+ });+});++describe("syncBakedSessionApiKey", () => {+ it("overwrites a stale stored key when VITE_SESSION_API_KEY differs", () => {+ // Simulate Run 1: the onboarding or settings page stored the old key.+ saveAgentServerConfig({+ baseUrl: "http://localhost:8000",+ sessionApiKey: "old-key",+ });++ // Run 2: dev scripts restart with a new key.+ vi.stubEnv("VITE_SESSION_API_KEY", "new-key");++ syncBakedSessionApiKey();++ // The stored config must reflect the new baked key.+ expect(getAgentServerSessionApiKey()).toBe("new-key");+ const raw = JSON.parse(+ window.localStorage.getItem(AGENT_SERVER_CONFIG_STORAGE_KEY) ?? "{}",+ );+ expect(raw.sessionApiKey).toBe("new-key");+ });++ it("does nothing when the stored key already matches the baked key", () => {+ saveAgentServerConfig({+ baseUrl: "http://localhost:8000",+ sessionApiKey: "same-key",+ });+ vi.stubEnv("VITE_SESSION_API_KEY", "same-key");++ syncBakedSessionApiKey();++ expect(getAgentServerSessionApiKey()).toBe("same-key");+ });++ it("does nothing when no key is stored (empty localStorage)", () => {+ vi.stubEnv("VITE_SESSION_API_KEY", "baked-key");++ syncBakedSessionApiKey();++ // Falls through to VITE_SESSION_API_KEY as before.+ expect(getAgentServerSessionApiKey()).toBe("baked-key");+ // Should NOT have written to localStorage since there was nothing stale.+ expect(+ window.localStorage.getItem(AGENT_SERVER_CONFIG_STORAGE_KEY),+ ).toBeNull();+ });++ it("does nothing in public mode (no VITE_SESSION_API_KEY)", () => {+ saveAgentServerConfig({+ baseUrl: "http://localhost:8000",+ sessionApiKey: "user-pasted-key",+ });++ // No VITE_SESSION_API_KEY โ public mode or static build without injection.+ syncBakedSessionApiKey();++ // The user-pasted key must be preserved.+ expect(getAgentServerSessionApiKey()).toBe("user-pasted-key");+ });+});diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.tsindex 4c7d2c573d..e8a4f0ae40 100644--- a/__tests__/api/agent-server-conversation-service.test.ts+++ b/__tests__/api/agent-server-conversation-service.test.ts@@ -82,6 +82,7 @@ vi.mock("#/api/agent-server-config", () => ({getConfiguredWorkerUrls: vi.fn(() => []),getAgentServerHeaders: vi.fn(() => ({ "X-Session-API-Key": "test-api-key" })),shouldLoadPublicSkills: vi.fn(() => true),+ syncBakedSessionApiKey: vi.fn(),}));vi.mock("#/api/settings-service/settings-service.api", () => ({diff --git a/__tests__/api/use-create-conversation-metadata.test.ts b/__tests__/api/use-create-conversation-metadata.test.tsindex 029e11aec1..d87cf88142 100644--- a/__tests__/api/use-create-conversation-metadata.test.ts+++ b/__tests__/api/use-create-conversation-metadata.test.ts@@ -51,6 +51,7 @@ vi.mock("#/api/agent-server-config", () => ({),getConfiguredWorkerUrls: vi.fn(() => []),shouldLoadPublicSkills: vi.fn(() => true),+ syncBakedSessionApiKey: vi.fn(),}));vi.mock("#/api/settings-service/settings-service.api", () => ({diff --git a/__tests__/components/backends/api-key-entry-screen.test.tsx b/__tests__/components/backends/api-key-entry-screen.test.tsxnew file mode 100644index 0000000000..8a4bc522df--- /dev/null+++ b/__tests__/components/backends/api-key-entry-screen.test.tsx@@ -0,0 +1,329 @@+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 {+ AGENT_SERVER_CONFIG_STORAGE_KEY,+ saveAgentServerConfig,+} from "#/api/agent-server-config";+import { BACKENDS_STORAGE_KEY } from "#/api/backend-registry/storage";+import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";+import { ActiveBackendProvider } from "#/contexts/active-backend-context";+import ApiKeyEntryScreen from "#/components/features/backends/api-key-entry-screen";++// โโ Mocks โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++const getSettingsMock = vi.fn();++vi.mock("@openhands/typescript-client/clients", () => ({+ SettingsClient: vi.fn(function SettingsClientMock() {+ return { getSettings: getSettingsMock };+ }),+ // ServerClient needed by useBackendsHealth (imported transitively)+ ServerClient: vi.fn(function ServerClientMock() {+ return { getServerInfo: vi.fn().mockResolvedValue({ version: "1.0.0" }) };+ }),+}));++// Stub cloud org service used by ActiveBackendProvider+vi.mock("#/api/cloud/organization-service.api", () => ({+ getCurrentCloudApiKey: vi.fn().mockResolvedValue({+ orgId: null,+ isLegacyKey: true,+ }),+}));++// Capture reload calls without crashing jsdom+const reloadMock = vi.fn();++// โโ Helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++function renderScreen() {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={queryClient}>+ <ActiveBackendProvider>+ <ApiKeyEntryScreen />+ </ActiveBackendProvider>+ </QueryClientProvider>,+ );+}++/** Fill the required fields: name and api key. */+async function fillRequiredFields(+ user: ReturnType<typeof userEvent.setup>,+ { name = "My Server", apiKey = "some-key" } = {},+) {+ await user.type(screen.getByTestId("api-key-entry-name"), name);+ await user.type(screen.getByTestId("api-key-entry-api-key"), apiKey);+}++// โโ Setup / teardown โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++const ORIGINAL_LOCATION = window.location;++beforeEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ getSettingsMock.mockReset();++ // Replace window.location with a spy-able version+ Object.defineProperty(window, "location", {+ configurable: true,+ value: {+ ...ORIGINAL_LOCATION,+ origin: "http://localhost:8000",+ hostname: "localhost",+ reload: reloadMock,+ },+ });+ reloadMock.mockReset();+});++afterEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ vi.unstubAllEnvs();+ Object.defineProperty(window, "location", {+ configurable: true,+ value: ORIGINAL_LOCATION,+ });+});++// โโ Tests โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++describe("ApiKeyEntryScreen", () => {+ // @spec โ UI: name + host (disabled) + api key + connect+ it("renders name, host (disabled), api key, and connect button", () => {+ renderScreen();++ // Name field+ const nameInput = screen.getByTestId("api-key-entry-name");+ expect(nameInput).toBeInTheDocument();+ expect(nameInput).toHaveValue("");++ // Host field โ pre-filled from window.location.origin, disabled+ const hostInput = screen.getByTestId("api-key-entry-host");+ expect(hostInput).toBeInTheDocument();+ expect(hostInput).toBeDisabled();+ expect(hostInput).toHaveValue("http://localhost:8000");++ // API key field+ expect(screen.getByTestId("api-key-entry-api-key")).toBeInTheDocument();++ // Connect button+ expect(screen.getByTestId("api-key-entry-submit")).toBeInTheDocument();+ });++ // @spec โ API key field always starts empty (stale key wipe)+ it("starts with an empty api key even when localStorage has a stale key", () => {+ // Seed localStorage with a stale key from a previous session+ saveAgentServerConfig({+ baseUrl: "http://localhost:8000",+ sessionApiKey: "old-stale-key-from-previous-session",+ });++ // Also seed the backend registry with the stale key+ window.localStorage.setItem(+ BACKENDS_STORAGE_KEY,+ JSON.stringify([+ {+ id: "default-local",+ name: "Local",+ host: "http://localhost:8000",+ apiKey: "old-stale-key-from-previous-session",+ kind: "local",+ },+ ]),+ );++ renderScreen();++ expect(screen.getByTestId("api-key-entry-api-key")).toHaveValue("");+ });++ // @spec โ Connect button requires both name and api key+ it("disables Connect when name or api key is empty", async () => {+ renderScreen();+ const user = userEvent.setup();+ const submit = screen.getByTestId("api-key-entry-submit");++ // Both empty+ expect(submit).toBeDisabled();++ // Only api key filled โ still disabled+ await user.type(screen.getByTestId("api-key-entry-api-key"), "key");+ expect(submit).toBeDisabled();++ // Name also filled โ enabled+ await user.type(screen.getByTestId("api-key-entry-name"), "Server");+ expect(submit).not.toBeDisabled();+ });++ // @spec โ Valid key: validates against GET /api/settings, persists, reloads+ it("validates the key before persisting and reloading", async () => {+ getSettingsMock.mockResolvedValueOnce({ llm_model: "test" });++ renderScreen();+ const user = userEvent.setup();++ await fillRequiredFields(user, { apiKey: "correct-key" });+ await user.click(screen.getByTestId("api-key-entry-submit"));++ await waitFor(() => {+ expect(getSettingsMock).toHaveBeenCalledTimes(1);+ });++ // Key persisted to agent-server-config storage+ const stored = JSON.parse(+ window.localStorage.getItem(AGENT_SERVER_CONFIG_STORAGE_KEY) ?? "{}",+ );+ expect(stored.sessionApiKey).toBe("correct-key");++ // Page reloaded+ expect(reloadMock).toHaveBeenCalled();+ });++ // @spec โ 401 shows "Invalid API key", does NOT persist or reload+ it("shows 'Invalid API key' when the key is rejected with 401", async () => {+ getSettingsMock.mockRejectedValueOnce(+ Object.assign(new Error("Unauthorized"), {+ name: "HttpError",+ status: 401,+ }),+ );++ renderScreen();+ const user = userEvent.setup();++ await fillRequiredFields(user, { apiKey: "wrong-key" });+ await user.click(screen.getByTestId("api-key-entry-submit"));++ // Error status appears with "Invalid" text+ await waitFor(() => {+ expect(screen.getByTestId("api-key-entry-status")).toBeInTheDocument();+ });+ expect(screen.getByTestId("api-key-entry-status")).toHaveClass(+ "text-red-400",+ );+ expect(screen.getByTestId("api-key-entry-status").textContent).toContain(+ "AUTH$INVALID_KEY",+ );++ // Key NOT persisted+ expect(+ window.localStorage.getItem(AGENT_SERVER_CONFIG_STORAGE_KEY),+ ).toBeNull();++ // Page NOT reloaded+ expect(reloadMock).not.toHaveBeenCalled();+ });++ // @spec โ Non-401 errors show the actual error message, not "Invalid key"+ it("shows 'Connection failed' with detail for non-auth errors (e.g. 500)", async () => {+ getSettingsMock.mockRejectedValueOnce(+ Object.assign(new Error("HTTP 500: Internal Server Error"), {+ name: "HttpError",+ status: 500,+ }),+ );++ renderScreen();+ const user = userEvent.setup();++ await fillRequiredFields(user, { apiKey: "correct-key" });+ await user.click(screen.getByTestId("api-key-entry-submit"));++ await waitFor(() => {+ expect(screen.getByTestId("api-key-entry-status")).toBeInTheDocument();+ });++ const statusText =+ screen.getByTestId("api-key-entry-status").textContent ?? "";+ // Shows "Connection failed" prefix, NOT "Invalid API key"+ expect(statusText).toContain("AUTH$CONNECTION_FAILED");+ expect(statusText).toContain("500");+ expect(statusText).not.toContain("AUTH$INVALID_KEY");++ // Key NOT persisted+ expect(+ window.localStorage.getItem(AGENT_SERVER_CONFIG_STORAGE_KEY),+ ).toBeNull();++ expect(reloadMock).not.toHaveBeenCalled();+ });++ // @spec โ Retry flow: wrong key โ error โ correct key โ success+ it("allows retry after a failed attempt", async () => {+ getSettingsMock+ .mockRejectedValueOnce(+ Object.assign(new Error("Unauthorized"), {+ name: "HttpError",+ status: 401,+ }),+ )+ .mockResolvedValueOnce({ llm_model: "test" });++ renderScreen();+ const user = userEvent.setup();+ const apiKeyInput = screen.getByTestId("api-key-entry-api-key");++ // First attempt โ wrong key+ await fillRequiredFields(user, { apiKey: "wrong-key" });+ await user.click(screen.getByTestId("api-key-entry-submit"));+ await waitFor(() => {+ expect(screen.getByTestId("api-key-entry-status")).toHaveClass(+ "text-red-400",+ );+ });++ // Retry โ correct key+ await user.clear(apiKeyInput);+ await user.type(apiKeyInput, "correct-key");+ await user.click(screen.getByTestId("api-key-entry-submit"));++ await waitFor(() => {+ expect(reloadMock).toHaveBeenCalled();+ });++ const stored = JSON.parse(+ window.localStorage.getItem(AGENT_SERVER_CONFIG_STORAGE_KEY) ?? "{}",+ );+ expect(stored.sessionApiKey).toBe("correct-key");+ });++ // @spec โ Stale key in localStorage does not contaminate the new key+ it("persists only the freshly-entered key, not the stale one", async () => {+ // Seed a stale key from a previous session+ saveAgentServerConfig({+ baseUrl: "http://localhost:8000",+ sessionApiKey: "stale-key-AAAA",+ });++ getSettingsMock.mockResolvedValueOnce({ llm_model: "test" });++ renderScreen();+ const user = userEvent.setup();++ // API key field is empty โ stale key not visible+ const apiKeyInput = screen.getByTestId("api-key-entry-api-key");+ expect(apiKeyInput).toHaveValue("");++ // Enter fresh key+ await fillRequiredFields(user, { apiKey: "fresh-key-BBBB" });+ await user.click(screen.getByTestId("api-key-entry-submit"));++ await waitFor(() => {+ expect(reloadMock).toHaveBeenCalled();+ });++ // Stored key is the NEW one, not old + new concatenated+ const stored = JSON.parse(+ window.localStorage.getItem(AGENT_SERVER_CONFIG_STORAGE_KEY) ?? "{}",+ );+ expect(stored.sessionApiKey).toBe("fresh-key-BBBB");+ });+});diff --git a/__tests__/scripts/dev-safe.test.ts b/__tests__/scripts/dev-safe.test.tsindex 90e4247fa3..b52f1f1249 100644--- a/__tests__/scripts/dev-safe.test.ts+++ b/__tests__/scripts/dev-safe.test.ts@@ -653,14 +653,14 @@ describe("buildSafeDevConfig", () => {expect(second.sessionApiKey).toBe(first.sessionApiKey);});- it("env-provided session keys take precedence over the persisted file", () => {+ it("LOCAL_BACKEND_API_KEY takes precedence over the persisted file", () => {const keyPath = tempKeyPath();// Pre-seed the file with one key.mkdirSync(path.dirname(keyPath), { recursive: true });writeFileSync(keyPath, "persisted-key-value\n");const config = buildSafeDevConfig("/workspace/project/agent-canvas", {- SESSION_API_KEY: "env-key-wins",+ LOCAL_BACKEND_API_KEY: "env-key-wins",OH_SESSION_API_KEY_PATH: keyPath,});diff --git a/__tests__/scripts/dev-with-automation.test.ts b/__tests__/scripts/dev-with-automation.test.tsindex 9cdef379b5..43a4c15e22 100644--- a/__tests__/scripts/dev-with-automation.test.ts+++ b/__tests__/scripts/dev-with-automation.test.ts@@ -318,71 +318,13 @@ describe("buildConfig", () => {expect(second.sessionApiKey).toBe(first.sessionApiKey);});- it("reads sessionApiKey from SESSION_API_KEY", async () => {+ it("reads sessionApiKey from LOCAL_BACKEND_API_KEY", async () => {const config = await buildConfig({},- { ...envWithIsolatedKeyPath(), SESSION_API_KEY: "my-session-key" },+ { ...envWithIsolatedKeyPath(), LOCAL_BACKEND_API_KEY: "my-api-key" },);- expect(config.sessionApiKey).toBe("my-session-key");- });-- it("reads sessionApiKey from VITE_SESSION_API_KEY as fallback", async () => {- const config = await buildConfig(- {},- { ...envWithIsolatedKeyPath(), VITE_SESSION_API_KEY: "vite-session-key" },- );-- expect(config.sessionApiKey).toBe("vite-session-key");- });-- it("SESSION_API_KEY takes precedence over VITE_SESSION_API_KEY", async () => {- const config = await buildConfig(- {},- {- ...envWithIsolatedKeyPath(),- SESSION_API_KEY: "session-key",- VITE_SESSION_API_KEY: "vite-key",- },- );-- expect(config.sessionApiKey).toBe("session-key");- });-- it("reads sessionApiKey from OH_SESSION_API_KEYS_0 (agent-server V1 env)", async () => {- const config = await buildConfig(- {},- { ...envWithIsolatedKeyPath(), OH_SESSION_API_KEYS_0: "v1-session-key" },- );-- expect(config.sessionApiKey).toBe("v1-session-key");- });-- it("SESSION_API_KEY takes precedence over OH_SESSION_API_KEYS_0", async () => {- const config = await buildConfig(- {},- {- ...envWithIsolatedKeyPath(),- SESSION_API_KEY: "v0-key",- OH_SESSION_API_KEYS_0: "v1-key",- },- );-- expect(config.sessionApiKey).toBe("v0-key");- });-- it("SESSION_API_KEY takes precedence over all other session key env vars", async () => {- const config = await buildConfig(- {},- {- ...envWithIsolatedKeyPath(),- SESSION_API_KEY: "v0-key",- OH_SESSION_API_KEYS_0: "v1-key",- VITE_SESSION_API_KEY: "vite-key",- },- );-- expect(config.sessionApiKey).toBe("v0-key");+ expect(config.sessionApiKey).toBe("my-api-key");});});diff --git a/bin/agent-canvas.mjs b/bin/agent-canvas.mjsindex f785f6aed3..b9aab7d264 100755--- a/bin/agent-canvas.mjs+++ b/bin/agent-canvas.mjs@@ -22,7 +22,7 @@ const BUILD_DIR = join(__dirname, "..", "build");const DEFAULTS_JSON = join(__dirname, "..", "config", "defaults.json");-// Check for version/help/info flags first+// Check for version/help/info/public flags firstconst args = process.argv.slice(2);if (args.includes("-v") || args.includes("--version")) {const { version } = JSON.parse(readFileSync(PKG_JSON, "utf-8"));@@ -49,6 +49,7 @@ Override versions via environment variables:OH_AUTOMATION_VERSION, OH_AUTOMATION_GIT_REF`);process.exit(0);}+const isPublic = args.includes("--public");if (args.includes("-h") || args.includes("--help")) {console.log(`@openhands/agent-canvas - Run the Agent Canvas UI with agent-server@@ -59,13 +60,25 @@ and serves pre-built static frontend assets.USAGE:npx @openhands/agent-canvas [options]+AUTH MODES:+ By default the server auto-generates an API key that is injected into+ the frontend at startup โ no login required.++ --public Enable public mode. Requires LOCAL_BACKEND_API_KEY env var.+ The key protects the server but is NOT injected into the+ frontend. Users must paste it when the UI loads.+OPTIONS:-p, --port <port> Ingress port (default: 8000)+ --public Enable public mode (see above)-v, --version Show version number--info Show version and default stack configuration-h, --help Show this help messageENVIRONMENT VARIABLES:+ LOCAL_BACKEND_API_KEY API key for the server. Required in --public+ mode; optional otherwise (auto-generated if+ omitted, persisted across restarts).OH_SECRET_KEY Secret key for encrypting settingsOH_AGENT_SERVER_GIT_REF Git ref for agent-serverOH_AGENT_SERVER_LOCAL_PATH Path to local SDK checkout (for development)@@ -75,9 +88,15 @@ Note: LLM settings are configured through the web UI settings page,not environment variables.EXAMPLES:- # Start full stack+ # Start full stack (local mode, auto-generated key)npx @openhands/agent-canvas+ # Pin a specific key (local mode, key auto-injected into frontend)+ LOCAL_BACKEND_API_KEY=my-key npx @openhands/agent-canvas++ # Public mode โ users must enter the API key in the browser+ LOCAL_BACKEND_API_KEY=my-secret npx @openhands/agent-canvas --public+# Use a specific portnpx @openhands/agent-canvas --port 3000@@ -119,6 +138,7 @@ main({staticMode: true,staticDir: BUILD_DIR,mode: "agent-canvas",+ isPublic,}).catch((err) => {console.error(`Fatal error: ${err.message}`);if (err.stack) {diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex cd8e74c61b..e02a28557c 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -67,26 +67,28 @@ if [ -z "${OH_SECRET_KEY:-}" ]; thenfiexport OH_SECRET_KEY-# Session API key โ generate one if not provided so the image doesn't run-# wide-open by default. Persisted so restarts reuse the same key.-SESSION_KEY_FILE="${STATE_DIR}/session-api-key.txt"-if [ -z "${OH_SESSION_API_KEYS_0:-}" ] && [ -z "${SESSION_API_KEY:-}" ]; then- if [ -f "$SESSION_KEY_FILE" ]; then- SESSION_API_KEY="$(cat "$SESSION_KEY_FILE")"+# API key โ generate one if not provided so the image doesn't run wide-open+# by default. LOCAL_BACKEND_API_KEY is the single user-facing env var.+# Persisted so restarts reuse the same key.+API_KEY_FILE="${STATE_DIR}/api-key.txt"++if [ -z "${LOCAL_BACKEND_API_KEY:-}" ] && [ -z "${OH_SESSION_API_KEYS_0:-}" ]; then+ if [ -f "$API_KEY_FILE" ]; then+ LOCAL_BACKEND_API_KEY="$(cat "$API_KEY_FILE")"else- SESSION_API_KEY="$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')"- mkdir -p "$(dirname "$SESSION_KEY_FILE")"- printf '%s' "$SESSION_API_KEY" > "$SESSION_KEY_FILE"- chmod 600 "$SESSION_KEY_FILE"- log "Generated session API key (persisted to $SESSION_KEY_FILE)"+ LOCAL_BACKEND_API_KEY="$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')"+ mkdir -p "$(dirname "$API_KEY_FILE")"+ printf '%s' "$LOCAL_BACKEND_API_KEY" > "$API_KEY_FILE"+ chmod 600 "$API_KEY_FILE"+ log "Generated API key (persisted to $API_KEY_FILE)"fi- export OH_SESSION_API_KEYS_0="$SESSION_API_KEY"+ export OH_SESSION_API_KEYS_0="$LOCAL_BACKEND_API_KEY"fi# Both backends share the same API key value and the same `X-Session-API-Key`# header for authentication. Default OPENHANDS_AUTOMATION_API_KEY to the-# session key so a single credential secures the whole stack.-EFFECTIVE_SESSION_KEY="${OH_SESSION_API_KEYS_0:-${SESSION_API_KEY:-}}"+# API key so a single credential secures the whole stack.+EFFECTIVE_SESSION_KEY="${OH_SESSION_API_KEYS_0:-${LOCAL_BACKEND_API_KEY:-}}"if [ -z "$EFFECTIVE_SESSION_KEY" ]; thenlog "ERROR: No session API key available โ cannot configure automation auth"exit 1@@ -193,7 +195,7 @@ wait "$WAIT_PID1" "$WAIT_PID2"# โโ 4. Start static server (frontend + proxy) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโlog "Starting frontend + proxy on port $PORT..."-# EFFECTIVE_SESSION_KEY is set above from ~/.openhands/agent-canvas/session-api-key.txt (or $SESSION_API_KEY)+# EFFECTIVE_SESSION_KEY is set above from LOCAL_BACKEND_API_KEY or the persisted api-key.txtnode /opt/agent-canvas/static-server.mjs \--port "$PORT" \--host 0.0.0.0 \diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.mdindex a68e03de99..554a9a6784 100644--- a/docs/DEVELOPMENT.md+++ b/docs/DEVELOPMENT.md@@ -24,11 +24,11 @@ sessions.### Environment Variables-| Variable | Description | Default |-|----------|-------------|---------|-| `PORT` | Ingress port | `8000` |-| `OH_AUTOMATION_GIT_REF` | Git ref for automation backend | `main` |-| `OH_AGENT_SERVER_GIT_REF` | Git ref for agent-server | `main` |+| Variable | Description | Default |+| ------------------------- | ------------------------------ | ------- |+| `PORT` | Ingress port | `8000` |+| `OH_AUTOMATION_GIT_REF` | Git ref for automation backend | `main` |+| `OH_AGENT_SERVER_GIT_REF` | Git ref for agent-server | `main` |### Alternative: Minimal Mode (without Automation)@@ -86,7 +86,7 @@ npm run dev:frontendThe frontend-only workflow expects the backend at `127.0.0.1:8000` by default.-If you start the backend with `SESSION_API_KEY` or `OH_SESSION_API_KEYS_0`, every `/api/*` route is authenticated with `X-Session-API-Key`. In that case the frontend must send the same key via `VITE_SESSION_API_KEY`.+If you set `LOCAL_BACKEND_API_KEY`, it is used as the API key for the agent-server (mapped internally to `OH_SESSION_API_KEYS_0`). The launcher auto-generates and persists a key when `LOCAL_BACKEND_API_KEY` is not set.### Mock mode@@ -142,15 +142,15 @@ If you want Tailwind layout utilities on the inner themed container, pass `conteYou can create a `.env` file in the project directory with these variables based on `.env.sample`.-| Variable | Description | Default Value |-| --------------------------- | ---------------------------------------------------------------------------------- | ---------------------- |-| `VITE_BACKEND_BASE_URL` | Full base URL for the agent server used by direct browser requests | current browser origin |-| `VITE_BACKEND_HOST` | Backend host used by the Vite dev proxy | `127.0.0.1:8000` |-| `VITE_SESSION_API_KEY` | Optional `X-Session-API-Key` header value for authenticated agent_server instances | - |-| `VITE_WORKING_DIR` | Workspace path sent when starting new conversations | `workspace/project` |-| `VITE_WORKER_URLS` | Optional comma-separated worker/app URLs for the Browser tab | - |-| `VITE_ENABLE_BROWSER_TOOLS` | Set to `false` to omit `BrowserToolSet` from new conversation payloads | `true` |-| `VITE_MOCK_API` | Enable/disable API mocking with MSW | `false` |-| `VITE_USE_TLS` | Use HTTPS/WSS for the Vite proxy target | `false` |-| `VITE_FRONTEND_PORT` | Port to run the frontend application | `3001` |-| `VITE_INSECURE_SKIP_VERIFY` | Skip TLS certificate verification for proxied backend requests | `false` |+| Variable | Description | Default Value |+| --------------------------- | ----------------------------------------------------------------------------------------- | ---------------------- |+| `VITE_BACKEND_BASE_URL` | Full base URL for the agent server used by direct browser requests | current browser origin |+| `VITE_BACKEND_HOST` | Backend host used by the Vite dev proxy | `127.0.0.1:8000` |+| `VITE_SESSION_API_KEY` | (Internal) Session API key injected by the launcher โ set `LOCAL_BACKEND_API_KEY` instead | - |+| `VITE_WORKING_DIR` | Workspace path sent when starting new conversations | `workspace/project` |+| `VITE_WORKER_URLS` | Optional comma-separated worker/app URLs for the Browser tab | - |+| `VITE_ENABLE_BROWSER_TOOLS` | Set to `false` to omit `BrowserToolSet` from new conversation payloads | `true` |+| `VITE_MOCK_API` | Enable/disable API mocking with MSW | `false` |+| `VITE_USE_TLS` | Use HTTPS/WSS for the Vite proxy target | `false` |+| `VITE_FRONTEND_PORT` | Port to run the frontend application | `3001` |+| `VITE_INSECURE_SKIP_VERIFY` | Skip TLS certificate verification for proxied backend requests | `false` |diff --git a/playwright.live.config.ts b/playwright.live.config.tsindex b1093663ac..4312430f01 100644--- a/playwright.live.config.ts+++ b/playwright.live.config.ts@@ -60,10 +60,8 @@ export default defineConfig({"node -e \"const fs=require('node:fs'); for (const p of ['.tmp/live-e2e-state','node_modules/.vite']) fs.rmSync(p,{recursive:true,force:true});\" && " +["OH_CANVAS_SAFE_STATE_DIR=.tmp/live-e2e-state",- envAssignment("SESSION_API_KEY", liveE2ESessionApiKey),- envAssignment("OH_SESSION_API_KEYS_0", liveE2ESessionApiKey),+ envAssignment("LOCAL_BACKEND_API_KEY", liveE2ESessionApiKey),envAssignment("OH_CANVAS_SAFE_BACKEND_PORT", liveE2EBackendPort),- envAssignment("VITE_SESSION_API_KEY", liveE2ESessionApiKey),"VITE_DO_NOT_TRACK=1","VITE_ENABLE_BROWSER_TOOLS=false",envAssignment("VITE_FRONTEND_PORT", liveE2EFrontendPort),diff --git a/playwright.mock-llm.config.ts b/playwright.mock-llm.config.tsindex 00aa5fa93f..f129354975 100644--- a/playwright.mock-llm.config.ts+++ b/playwright.mock-llm.config.ts@@ -1,11 +1,14 @@/*** Playwright config for mock-LLM E2E tests.*- * Starts two processes:+ * Starts three processes:* 1. Mock LLM server (Python, using openhands-sdk TestLLM)* 2. Full agent-canvas stack via bin/agent-canvas.mjs (agent-server +* automation backend + static frontend + ingress proxy), matching the* production npm-published binary.+ * 3. A second static-server instance with `--auth-required` (public mode)+ * on a separate port, proxying to the same backend. Used by the+ * auth-mode E2E tests.** The test creates an LLM profile via the UI that points at the mock server,* so no real LLM credentials are needed.@@ -30,6 +33,11 @@ const MOCK_LLM_PORT = process.env.MOCK_LLM_PORT ?? "9999";// calls (the ingress proxies /api/* transparently).const INGRESS_PORT = process.env.MOCK_LLM_INGRESS_PORT ?? "18300";+// A second static-server instance for public-mode auth tests. It serves+// the same build/ directory with --auth-required (no baked session key)+// and proxies to the same backend.+const PUBLIC_MODE_PORT = process.env.MOCK_LLM_PUBLIC_MODE_PORT ?? "18301";+// โโ Session API key โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโconst sessionApiKey =process.env.MOCK_LLM_SESSION_API_KEY?.trim() ||@@ -55,7 +63,7 @@ const MOCK_LLM_PYTHON = process.env.MOCK_LLM_PYTHON ?? "python3";// calls are proxied to the agent-server, so no direct backend port needed).process.env.MOCK_LLM_BACKEND_URL = `http://localhost:${INGRESS_PORT}`;process.env.MOCK_LLM_PORT = MOCK_LLM_PORT;-process.env.VITE_SESSION_API_KEY = sessionApiKey;+process.env.MOCK_LLM_PUBLIC_MODE_URL = `http://localhost:${PUBLIC_MODE_PORT}`;function shellQuote(value: string) {return `'${value.replaceAll("'", "'\\''")}'`;@@ -119,14 +127,12 @@ export default defineConfig({// Clean state dir to avoid stale profile/conversation data between runs`node -e "const fs=require('node:fs'); fs.rmSync('${STATE_DIR}',{recursive:true,force:true});" && ` +// Build frontend if not already built (CI should pre-build for caching)- '[ -f build/index.html ] || npm run build:app && ' ++ "[ -f build/index.html ] || npm run build:app && " +["exec env",envAssignment("OH_CANVAS_SAFE_STATE_DIR", STATE_DIR),envAssignment("PORT", INGRESS_PORT),- envAssignment("SESSION_API_KEY", sessionApiKey),- envAssignment("OH_SESSION_API_KEYS_0", sessionApiKey),- envAssignment("VITE_SESSION_API_KEY", sessionApiKey),+ envAssignment("LOCAL_BACKEND_API_KEY", sessionApiKey),"VITE_DO_NOT_TRACK=1","VITE_ENABLE_BROWSER_TOOLS=false",// Bypass npm โ exec directly into node so SIGTERM reaches@@ -145,5 +151,24 @@ export default defineConfig({timeout: 180_000, // allow extra time for build + agent-server + automation startupreuseExistingServer: !process.env.CI,},+ // 3. Public-mode static server โ same build/, same backend, but with+ // --auth-required (no session key injected). The agent-server's+ // internal ports are the defaults from config/defaults.json (18000+ // for agent-server, 18001 for automation).+ {+ command: [+ "exec node scripts/static-server.mjs",+ "--dir build",+ "--host 0.0.0.0",+ `--port ${PUBLIC_MODE_PORT}`,+ "--auth-required",+ "--route /api/automation=http://localhost:18001",+ "--route /api=http://localhost:18000",+ "--route /sockets=http://localhost:18000",+ ].join(" "),+ url: `http://localhost:${PUBLIC_MODE_PORT}/`,+ timeout: 15_000,+ reuseExistingServer: !process.env.CI,+ },],});diff --git a/scripts/dev-safe.mjs b/scripts/dev-safe.mjsindex dd98b2d382..322a63d1eb 100644--- a/scripts/dev-safe.mjs+++ b/scripts/dev-safe.mjs@@ -53,22 +53,24 @@ export function generateRandomApiKey() {return randomBytes(32).toString("hex");}-// Where the auto-generated default session API key is persisted so it stays-// stable across `npm run dev` restarts. Keeping the key stable means the value-// baked into the frontend (VITE_SESSION_API_KEY) and the persisted-// backend-registry entry (`openhands-backends` localStorage) stay in sync-// without users needing to set anything in `.env`.+// Where the auto-generated API key is persisted so it stays stable across+// `npm run dev` restarts. Keeping the key stable means the value baked into+// the frontend (VITE_SESSION_API_KEY) and the persisted backend-registry entry+// (`openhands-backends` localStorage) stay in sync without users needing to+// set anything in `.env`.//// To rotate the key, delete this file. To pin a key explicitly, export-// SESSION_API_KEY (or OH_SESSION_API_KEYS_0 / VITE_SESSION_API_KEY) -- those-// take precedence over the persisted file.-export const DEFAULT_SESSION_API_KEY_PATH = path.join(+// LOCAL_BACKEND_API_KEY โ it takes precedence over the persisted file.+export const DEFAULT_API_KEY_PATH = path.join(homedir(),".openhands","agent-canvas",- "session-api-key.txt",+ "api-key.txt",);+/** @deprecated Use DEFAULT_API_KEY_PATH */+export const DEFAULT_SESSION_API_KEY_PATH = DEFAULT_API_KEY_PATH;+// Where the OH_SECRET_KEY is persisted so dev mode and Docker mode share the// same encryption key when both use ~/.openhands as their state directory.// docker/entrypoint.sh reads and writes this same file, so whichever mode runs@@ -88,22 +90,29 @@ export const DEFAULT_SECRET_KEY_PATH = path.join(const persistedApiKeyCache = new Map();/**- * Load the persisted default session API key, generating + persisting one if- * the file doesn't exist yet.+ * Load the persisted default API key, generating + persisting one if the file+ * doesn't exist yet.** Best-effort: if the file can't be written (e.g. read-only home dir), we* fall back to an in-memory key for this process so dev still works -- the* key just won't survive a restart.** @param {string} filePath - Where to read/write the key.- * @returns {string} The (hex) session API key.+ * @returns {string} The (hex) API key.*/-export function getOrCreatePersistedSessionApiKey(- filePath = DEFAULT_SESSION_API_KEY_PATH,+export function getOrCreatePersistedApiKeyFile(+ filePath = DEFAULT_API_KEY_PATH,) {return getOrCreatePersistedApiKey(filePath, "session");}+/** @deprecated Use getOrCreatePersistedApiKeyFile */+export function getOrCreatePersistedSessionApiKey(+ filePath = DEFAULT_API_KEY_PATH,+) {+ return getOrCreatePersistedApiKeyFile(filePath);+}+/*** Load a persisted default API key, generating + persisting one if the file* doesn't exist yet.@@ -589,24 +598,18 @@ function buildConfigFromPorts(ports, cwd, env) {env.OH_SECRET_KEY_PATH || DEFAULT_SECRET_KEY_PATH;const secretKey =env.OH_SECRET_KEY || getOrCreatePersistedApiKey(secretKeyPath, "secret");- // Use provided session API key or fall back to a key persisted to- // ~/.openhands/agent-canvas/session-api-key.txt. Persisting on disk keeps- // the agent-server, the Vite-baked VITE_SESSION_API_KEY, and any+ // Use the user-provided LOCAL_BACKEND_API_KEY or fall back to a key+ // persisted to ~/.openhands/agent-canvas/api-key.txt. Persisting on disk+ // keeps the agent-server, the Vite-baked VITE_SESSION_API_KEY, and any// `openhands-backends` localStorage entries the frontend has cached all// pointing at the same value across dev restarts.//- // Check multiple env vars that may be used:- // - SESSION_API_KEY: Common name- // - OH_SESSION_API_KEYS_0: Used by agent-server V1 config- // - VITE_SESSION_API_KEY: Used by frontend config+ // LOCAL_BACKEND_API_KEY is the single user-facing env var for the API key.// OH_SESSION_API_KEY_PATH overrides the persisted file path (used by tests).- const persistedKeyPath =- env.OH_SESSION_API_KEY_PATH || DEFAULT_SESSION_API_KEY_PATH;+ const persistedKeyPath = env.OH_SESSION_API_KEY_PATH || DEFAULT_API_KEY_PATH;const sessionApiKey =- env.SESSION_API_KEY ||- env.OH_SESSION_API_KEYS_0 ||- env.VITE_SESSION_API_KEY ||- getOrCreatePersistedSessionApiKey(persistedKeyPath);+ env.LOCAL_BACKEND_API_KEY ||+ getOrCreatePersistedApiKeyFile(persistedKeyPath);// Host directory containing Agent-Canvas-specific Python tools (e.g. the// canvas_ui tool). Added to OH_EXTRA_PYTHON_PATH below so the agent-server@@ -920,14 +923,11 @@ async function main() {? "custom (from OH_SECRET_KEY)": `persisted (${process.env.OH_SECRET_KEY_PATH || DEFAULT_SECRET_KEY_PATH})`;- const sessionKeySource =- process.env.SESSION_API_KEY ||- process.env.OH_SESSION_API_KEYS_0 ||- process.env.VITE_SESSION_API_KEY- ? "custom (from env)"- : `persisted (${- process.env.OH_SESSION_API_KEY_PATH || DEFAULT_SESSION_API_KEY_PATH- })`;+ const sessionKeySource = process.env.LOCAL_BACKEND_API_KEY+ ? "custom (from LOCAL_BACKEND_API_KEY)"+ : `persisted (${+ process.env.OH_SESSION_API_KEY_PATH || DEFAULT_API_KEY_PATH+ })`;console.log(`- agent-server: ${agentServerCmd.source}`);console.log(`- backend: ${config.backendBaseUrl}`);diff --git a/scripts/dev-static.mjs b/scripts/dev-static.mjsindex 5abfe9fcb0..3d017fe4e8 100644--- a/scripts/dev-static.mjs+++ b/scripts/dev-static.mjs@@ -388,9 +388,8 @@ function startStaticServer(config) {"0.0.0.0","--port",String(config.vitePort),- // Inject the runtime session key so the pre-built frontend can- // authenticate to agent-server without VITE_SESSION_API_KEY being baked- // into the bundle at publish time.+ // Inject the API key so the pre-built frontend can authenticate+ // to the agent-server without a baked-in VITE_SESSION_API_KEY....(config.sessionApiKey? ["--session-api-key", config.sessionApiKey]: []),diff --git a/scripts/dev-with-automation.mjs b/scripts/dev-with-automation.mjsindex 72581d8abd..b91a97cb52 100644--- a/scripts/dev-with-automation.mjs+++ b/scripts/dev-with-automation.mjs@@ -134,6 +134,7 @@ function parseArgs() {dynamic: false,staticDir: null,skipBuild: false,+ public: false,};for (let i = 0; i < args.length; i++) {@@ -164,6 +165,9 @@ function parseArgs() {case "--skip-build":config.skipBuild = true;break;+ case "--public":+ config.public = true;+ break;case "-h":case "--help":showHelp();@@ -281,6 +285,18 @@ async function buildConfig(args, env = process.env) {env.OH_AUTOMATION_REPO = args.automationRepo;}+ const isPublic = args.public;++ // In public mode, LOCAL_BACKEND_API_KEY is required โ without it the+ // auth screen has nothing to validate against.+ if (isPublic && !env.LOCAL_BACKEND_API_KEY) {+ logError(+ "PUBLIC MODE requires LOCAL_BACKEND_API_KEY environment variable.\n" ++ " Example: LOCAL_BACKEND_API_KEY=my-secret npm run dev -- --public",+ );+ process.exit(1);+ }+// Preferred ports (from env or defaults).// OH_CANVAS_SAFE_BACKEND_PORT / OH_CANVAS_SAFE_AUTOMATION_PORT /// OH_CANVAS_SAFE_VITE_PORT allow tests (and advanced users) to redirect@@ -303,11 +319,14 @@ async function buildConfig(args, env = process.env) {const vscodePort = preferredBackendPort + 1000;- // Session API key โ shared by both agent-server and automation backend.+ // API key โ shared by both agent-server and automation backend.// Both validate it via the `X-Session-API-Key` header.+ // LOCAL_BACKEND_API_KEY is the single user-facing env var: if set it's+ // used directly; otherwise one is auto-generated and persisted.const stateDir =env.OH_CANVAS_SAFE_STATE_DIR ||join(homedir(), ".openhands", "agent-canvas");+const safeConfig = buildSafeDevConfig(projectRoot, {...env,OH_CANVAS_SAFE_STATE_DIR: stateDir,@@ -316,6 +335,19 @@ async function buildConfig(args, env = process.env) {});const sessionApiKey = safeConfig.sessionApiKey;+ if (isPublic) {+ logService(+ "auth",+ "PUBLIC MODE โ key will NOT be injected into the frontend",+ c.yellow,+ );+ logService(+ "auth",+ "Users must paste the LOCAL_BACKEND_API_KEY in the browser",+ c.dim,+ );+ }+return {// Ingress port (main entry point)ingressPort: preferredIngressPort,@@ -335,6 +367,9 @@ async function buildConfig(args, env = process.env) {// Auth โ single key for both backendssessionApiKey,+ // Public mode โ the session key should NOT be baked into the frontend+ isPublic,+verbose: args.verbose,};}@@ -517,6 +552,9 @@ function startAgentServer(config) {const agentServerEnv = {...buildAgentServerEnv(safeConfig),...buildAgentServerAutomationEnv(config),+ // Ensure the agent-server uses the resolved key from config. This is+ // LOCAL_BACKEND_API_KEY when set, or the auto-generated persisted key.+ OH_SESSION_API_KEYS_0: config.sessionApiKey,};spawnService(@@ -726,22 +764,31 @@ function startVite(config) {const frontendCommand = buildNpmScriptCommand("dev:frontend");const runtimeServicesInfo = buildAutomationRuntimeServicesInfo(config);+ const viteEnv = {+ // Point Vite at the ingress (so client-side fetches work)+ VITE_BACKEND_HOST: `127.0.0.1:${config.ingressPort}`,+ VITE_BACKEND_BASE_URL: `http://127.0.0.1:${config.ingressPort}`,+ VITE_WORKING_DIR:+ config.viteWorkingDir ?? join(config.stateDir, "workspaces"),+ VITE_FRONTEND_PORT: config.vitePort.toString(),+ // Inform the frontend (and downstream, the agent's system prompt) about+ // which services are available in this dev stack.+ VITE_RUNTIME_SERVICES_INFO: JSON.stringify(runtimeServicesInfo),+ };++ // In local mode, bake the session key into the frontend so the user+ // never has to paste it. In public mode, omit the key and set+ // VITE_AUTH_REQUIRED so the frontend shows the API key entry screen+ // immediately (no network round-trip needed).+ if (config.isPublic) {+ viteEnv.VITE_AUTH_REQUIRED = "true";+ } else {+ viteEnv.VITE_SESSION_API_KEY = config.sessionApiKey;+ }+spawnService("vite", frontendCommand.command, frontendCommand.args, {cwd: config.canvasPath,- env: {- // Point Vite at the ingress (so client-side fetches work)- VITE_BACKEND_HOST: `127.0.0.1:${config.ingressPort}`,- VITE_BACKEND_BASE_URL: `http://127.0.0.1:${config.ingressPort}`,- VITE_WORKING_DIR:- config.viteWorkingDir ?? join(config.stateDir, "workspaces"),- VITE_FRONTEND_PORT: config.vitePort.toString(),- // Session API key โ used by the frontend for both agent-server and- // automation auth via the `X-Session-API-Key` header.- VITE_SESSION_API_KEY: config.sessionApiKey,- // Inform the frontend (and downstream, the agent's system prompt) about- // which services are available in this dev stack.- VITE_RUNTIME_SERVICES_INFO: JSON.stringify(runtimeServicesInfo),- },+ env: viteEnv,color: c.magenta,});}@@ -905,10 +952,18 @@ async function main(options = {}) {// Human-readable label for the dev mode, surfaced in the agent's// <RUNTIME_SERVICES> system-prompt block.mode = "dev:automation",+ // When true, enable public mode (require LOCAL_BACKEND_API_KEY,+ // don't bake session key into frontend).+ isPublic: isPublicOverride,} = options;const args = parseArgs();+ // Allow options to override CLI args for public mode+ if (isPublicOverride != null) {+ args.public = isPublicOverride;+ }+// Allow options to override CLI args (for bin/agent-canvas.mjs)const useStaticMode =staticModeOverride ??@@ -1041,12 +1096,13 @@ function startStaticFrontend(config, staticDir) {"0.0.0.0","--port",String(config.vitePort),- // Inject the runtime session key so the pre-built frontend can- // authenticate to agent-server without VITE_SESSION_API_KEY being baked- // into the bundle at publish time.- ...(config.sessionApiKey+ // In local mode, inject the API key so the pre-built frontend can+ // authenticate transparently. In public mode, pass --auth-required+ // so the frontend shows the API key entry screen instead.+ ...(!config.isPublic && config.sessionApiKey? ["--session-api-key", config.sessionApiKey]: []),+ ...(config.isPublic ? ["--auth-required"] : []),// Proxy routes to backends (same as ingress but for direct access to vitePort)"--route",`/api/automation=http://localhost:${config.autoBackendPort}`,diff --git a/scripts/static-server.mjs b/scripts/static-server.mjsindex 238196c04c..da96d0c4a1 100644--- a/scripts/static-server.mjs+++ b/scripts/static-server.mjs@@ -73,6 +73,7 @@ export function parseArgs(argv = process.argv.slice(2)) {dir: "build",routes: {},sessionApiKey: null,+ authRequired: false,};for (let i = 0; i < argv.length; i++) {@@ -108,6 +109,9 @@ export function parseArgs(argv = process.argv.slice(2)) {case "--session-api-key":config.sessionApiKey = argv[++i] || null;break;+ case "--auth-required":+ config.authRequired = true;+ break;case "-h":case "--help":showHelp();@@ -117,6 +121,19 @@ export function parseArgs(argv = process.argv.slice(2)) {}}+ // Guard: --session-api-key and --auth-required are semantically+ // mutually exclusive. The first auto-injects the key (local mode);+ // the second forces the user to paste it (public mode). Combining+ // both is a misconfiguration.+ if (config.sessionApiKey && config.authRequired) {+ console.error(+ "ERROR: --session-api-key and --auth-required are mutually exclusive.\n" ++ " Use --session-api-key for local mode (key auto-injected).\n" ++ " Use --auth-required for public mode (user pastes key).",+ );+ process.exit(1);+ }+return config;}@@ -136,6 +153,9 @@ OPTIONS:--session-api-key <key> Inject session API key into index.html so thepre-built frontend authenticates to agent-serverwithout needing VITE_SESSION_API_KEY baked in.+ --auth-required Inject authRequired flag into index.html so the+ pre-built frontend shows the API key entry screen+ (public mode) without VITE_AUTH_REQUIRED baked in.-h, --help Show this helpROUTING:@@ -152,39 +172,55 @@ ROUTING:// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ/**- * Build a tiny inline script that seeds the session API key into the- * `openhands-agent-server-config` localStorage entry the first time the page- * loads. Only writes if no key is already stored โ explicit user overrides- * (set via Settings > Agent Server in the UI) are always preserved.+ * Build a tiny inline script that seeds runtime config into the page.+ *+ * - `sessionApiKey`: written to `openhands-agent-server-config` in localStorage+ * so the pre-built frontend authenticates without VITE_SESSION_API_KEY baked in.+ * Only writes if no key is already stored โ explicit user overrides are preserved.*- * This lets the pre-built static binary work without needing VITE_SESSION_API_KEY- * baked into the bundle at publish time: the runtime key is injected here instead.+ * - `authRequired`: sets `window.__AGENT_CANVAS_AUTH_REQUIRED__ = true` so the+ * pre-built frontend shows the API key entry screen (public mode) without+ * VITE_AUTH_REQUIRED baked in.*/-function makeConfigInjectionScript(sessionApiKey) {- if (!sessionApiKey) return "";- // JSON.stringify produces a properly escaped JS string literal.- const keyLiteral = JSON.stringify(sessionApiKey);- return (- `<script>` +- `(function(){` +- `try{` +- `var _k='openhands-agent-server-config',` +- `_c=JSON.parse(localStorage.getItem(_k)||'{}');` +- `if(!_c.sessionApiKey){` +- `_c.sessionApiKey=${keyLiteral};` +- `localStorage.setItem(_k,JSON.stringify(_c));` +- `}` +- `}catch(e){}` +- `}());` +- `</script>`- );+function makeConfigInjectionScript(sessionApiKey, authRequired) {+ const parts = [];++ if (sessionApiKey) {+ const keyLiteral = JSON.stringify(sessionApiKey);+ // Always overwrite when the stored key differs from the runtime key.+ // A previous session may have persisted a now-stale key; the runtime+ // value (from --session-api-key) is the server's truth.+ parts.push(+ `try{` ++ `var _k='openhands-agent-server-config',` ++ `_c=JSON.parse(localStorage.getItem(_k)||'{}');` ++ `if(_c.sessionApiKey!==${keyLiteral}){` ++ `_c.sessionApiKey=${keyLiteral};` ++ `localStorage.setItem(_k,JSON.stringify(_c));` ++ `}` ++ `}catch(e){}`,+ );+ }++ if (authRequired) {+ parts.push(`window.__AGENT_CANVAS_AUTH_REQUIRED__=true;`);+ }++ if (parts.length === 0) return "";++ return `<script>(function(){${parts.join("")}}());</script>`;}/**- * Serve index.html with the runtime session key injected into <head>.+ * Serve index.html with runtime config injected into <head>.* Returns true if the response was written, false if the file was not found.*/-async function serveInjectedIndexHtml(req, res, indexPath, sessionApiKey) {+async function serveInjectedIndexHtml(+ req,+ res,+ indexPath,+ { sessionApiKey, authRequired } = {},+) {let content;try {content = await readFile(indexPath, "utf8");@@ -192,7 +228,7 @@ async function serveInjectedIndexHtml(req, res, indexPath, sessionApiKey) {return false;}- const script = makeConfigInjectionScript(sessionApiKey);+ const script = makeConfigInjectionScript(sessionApiKey, authRequired);// Inject right before </head> so the key is available before any app code runs.// replace() targets the first (and only) </head> in well-formed HTML.const injected = content.includes("</head>")@@ -393,7 +429,7 @@ async function serveFile(req, res, filePath, urlPath) {return true;}-async function handleStatic(req, res, dirAbs, sessionApiKey = null) {+async function handleStatic(req, res, dirAbs, injectionOpts = {}) {const rawPath = req.url.split("?")[0];let urlPath;try {@@ -417,9 +453,12 @@ async function handleStatic(req, res, dirAbs, sessionApiKey = null) {filePath = resolve(filePath, "index.html");}- // Serve index.html with runtime key injection when a session key is configured.- if (sessionApiKey && filePath.endsWith("index.html")) {- if (await serveInjectedIndexHtml(req, res, filePath, sessionApiKey)) return;+ const needsInjection =+ injectionOpts.sessionApiKey || injectionOpts.authRequired;++ // Serve index.html with runtime config injection when configured.+ if (needsInjection && filePath.endsWith("index.html")) {+ if (await serveInjectedIndexHtml(req, res, filePath, injectionOpts)) return;// Fall through to regular serveFile (handles 404 path correctly).}@@ -431,8 +470,8 @@ async function handleStatic(req, res, dirAbs, sessionApiKey = null) {!looksLikeAssetRequest(urlPath)) {const indexPath = resolve(dirAbs, "index.html");- if (sessionApiKey) {- if (await serveInjectedIndexHtml(req, res, indexPath, sessionApiKey))+ if (needsInjection) {+ if (await serveInjectedIndexHtml(req, res, indexPath, injectionOpts))return;} else if (await serveFile(req, res, indexPath, "/")) return;}@@ -448,7 +487,10 @@ async function handleStatic(req, res, dirAbs, sessionApiKey = null) {export function startStaticServer(config) {const route = createRouter(config.routes);const dirAbs = resolve(config.dir);- const sessionApiKey = config.sessionApiKey || null;+ const injectionOpts = {+ sessionApiKey: config.sessionApiKey || null,+ authRequired: config.authRequired || false,+ };const server = createServer((req, res) => {const backend = route(req.url);@@ -456,7 +498,7 @@ export function startStaticServer(config) {proxyRequest(req, res, backend);return;}- handleStatic(req, res, dirAbs, sessionApiKey).catch((err) => {+ handleStatic(req, res, dirAbs, injectionOpts).catch((err) => {console.error(`Static handler error for ${req.url}:`, err);if (!res.headersSent) {res.writeHead(500);diff --git a/src/api/agent-server-compatibility.ts b/src/api/agent-server-compatibility.tsindex 57d1606b4b..d3710df381 100644--- a/src/api/agent-server-compatibility.ts+++ b/src/api/agent-server-compatibility.ts@@ -1,6 +1,10 @@-import { ServerClient } from "@openhands/typescript-client/clients";+import {+ ServerClient,+ SettingsClient,+} from "@openhands/typescript-client/clients";import type { ServerInfo as BaseServerInfo } from "@openhands/typescript-client";import { getAgentServerClientOptions } from "#/api/agent-server-client-options";+import { isAuthRequired } from "#/api/agent-server-config";import { getEffectiveLocalBackend } from "#/api/backend-registry/active-store";const AGENT_SERVER_INFO_TIMEOUT_MS = 5000;@@ -39,6 +43,18 @@ export const isAgentServerUnavailableError = ("name" in error &&error.name === "AgentServerUnavailableError");+/**+ * Returns true when the agent-server probe failed with HTTP 401.+ * In public mode this means the stored key is stale (server restarted+ * with a different `LOCAL_BACKEND_API_KEY`). Only meaningful when+ * auth is required โ a 401 in local mode is a misconfiguration, not a+ * key-rotation event. Uses {@link isAuthRequired} so both the build-time+ * `VITE_AUTH_REQUIRED` flag and the runtime `window.__AGENT_CANVAS_AUTH_REQUIRED__`+ * injection (used by pre-built static binaries) are honoured.+ */+export const isAgentServerAuthError = (error: unknown): boolean =>+ isAuthRequired() && isSdkHttpStatusError(error, 401);+export function clearCachedAgentServerInfo() {cachedAgentServerInfo = null;}@@ -51,7 +67,7 @@ export function isAgentServerToolAvailable(toolName: string) {return availableTools.includes(toolName);}-function isSdkHttpError(error: unknown) {+export function isSdkHttpError(error: unknown) {return (error instanceof Error &&error.name === "HttpError" &&@@ -60,21 +76,32 @@ function isSdkHttpError(error: unknown) {);}+/**+ * Narrows an SDK HTTP error to a specific status code.+ * Use instead of manually casting `(err as { status: number }).status`.+ */+export function isSdkHttpStatusError(error: unknown, status: number): boolean {+ return (+ isSdkHttpError(error) && (error as { status: number }).status === status+ );+}+export async function loadAgentServerInfo() {// The probe is a *local* agent-server concern โ it verifies the runtime// hosting the GUI is reachable. It must NEVER run against the active// backend when that backend is cloud, because cloud hosts don't// expose /api/server_info and would fail with a CORS error besides.const local = getEffectiveLocalBackend();+ const clientOptions = getAgentServerClientOptions({+ host: local.host,+ sessionApiKey: local.apiKey || null,+ timeout: AGENT_SERVER_INFO_TIMEOUT_MS,+ });let serverInfo: AgentServerInfo;try {serverInfo = (await new ServerClient(- getAgentServerClientOptions({- host: local.host,- sessionApiKey: local.apiKey || null,- timeout: AGENT_SERVER_INFO_TIMEOUT_MS,- }),+ clientOptions,).getServerInfo()) as AgentServerInfo;} catch (error) {clearCachedAgentServerInfo();@@ -86,6 +113,35 @@ export async function loadAgentServerInfo() {throw new AgentServerUnavailableError(details);}+ // /server_info is unprotected, so a stale session key still gets 200.+ // In public mode, validate the key against a protected endpoint so a+ // server restart with a new LOCAL_BACKEND_API_KEY surfaces immediately+ // instead of letting the app load and fail on every subsequent call.+ if (isAuthRequired()) {+ try {+ await new SettingsClient(clientOptions).getSettings();+ } catch (error) {+ // Only rethrow 401 โ that means the stored key is invalid /+ // rotated. Other HTTP errors (403, 5xx) and non-HTTP errors+ // (network, timeout) are swallowed: the server *is* up (we just+ // reached /server_info), so let the app proceed with an+ // unvalidated key rather than blocking the UI.+ // NOTE: If the connection drops between the /server_info and+ // getSettings() probes, the app loads with an unvalidated key and+ // subsequent 401s won't trigger the auth screen (they come from+ // React Query hooks, not this bootstrap path). Acceptable for now+ // since the window is narrow and a page refresh recovers.+ if (isSdkHttpStatusError(error, 401)) {+ throw error;+ }++ console.warn(+ "[agent-server] getSettings() probe failed (non-401):",+ error,+ );+ }+ }+cachedAgentServerInfo = serverInfo;return serverInfo;}diff --git a/src/api/agent-server-config.ts b/src/api/agent-server-config.tsindex 2e54d1a741..648d2f224d 100644--- a/src/api/agent-server-config.ts+++ b/src/api/agent-server-config.ts@@ -78,11 +78,51 @@ function getConfiguredBaseUrl(): string | null {return normalizeBaseUrl(import.meta.env.VITE_BACKEND_BASE_URL);}+/**+ * Return the baked-in session API key from the Vite env or the runtime+ * injection by static-server.mjs. This represents the *server's* truth+ * and is only set in non-public (local) mode.+ */+export function getBakedSessionApiKey(): string | null {+ return trimToNull(import.meta.env.VITE_SESSION_API_KEY);+}+function getConfiguredSessionApiKey(): string | null {const storedKey = trimToNull(readStoredConfig().sessionApiKey);if (storedKey) return storedKey;- return trimToNull(import.meta.env.VITE_SESSION_API_KEY);+ return getBakedSessionApiKey();+}++/**+ * Sync the baked-in session API key into `openhands-agent-server-config`+ * localStorage when the stored value has drifted.+ *+ * In non-public (local) mode the dev scripts bake the session key into+ * `VITE_SESSION_API_KEY` (Vite dev) or inject it via `static-server.mjs`+ * (`--session-api-key`). That key represents the *server's* truth โ the+ * agent-server was started with the same value as `OH_SESSION_API_KEYS_0`.+ *+ * If a user restarts the stack with a different `LOCAL_BACKEND_API_KEY`,+ * the baked-in key changes but the old value may still be persisted in+ * localStorage (written by the onboarding form, the Settings page, or a+ * previous key injection). Without this sync the stale stored key would+ * shadow the new baked key everywhere (`getConfiguredSessionApiKey()`+ * reads localStorage first), causing 401s.+ *+ * Must run **before** any call to `getConfiguredSessionApiKey()` or+ * `makeDefaultLocalBackend()` โ called from `readStoredBackends()` in+ * `storage.ts` which is evaluated at module init time.+ */+export function syncBakedSessionApiKey(): void {+ const bakedKey = getBakedSessionApiKey();+ if (!bakedKey) return; // public mode or no key baked in++ const storedConfig = readStoredConfig();+ const storedKey = trimToNull(storedConfig.sessionApiKey);+ if (storedKey && storedKey !== bakedKey) {+ writeStoredConfig({ ...storedConfig, sessionApiKey: bakedKey });+ }}function shouldUseProxyOrigin(baseUrl: string): boolean {@@ -189,3 +229,33 @@ export function getAgentServerHeaders(): Record<string, string> {export function shouldLoadPublicSkills(): boolean {return import.meta.env.VITE_LOAD_PUBLIC_SKILLS !== "false";}++/**+ * Whether the deployment requires an API key from the user (public mode).+ *+ * Checks both the Vite build-time env var (`VITE_AUTH_REQUIRED`) and the+ * runtime flag injected by static-server.mjs (`window.__AGENT_CANVAS_AUTH_REQUIRED__`).+ * The runtime flag is needed for pre-built static binaries where+ * `VITE_AUTH_REQUIRED` was not set at build time.+ */+export function isAuthRequired(): boolean {+ return (+ import.meta.env.VITE_AUTH_REQUIRED === "true" ||+ (typeof window !== "undefined" &&+ (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_AUTH_REQUIRED__ === true)+ );+}++/**+ * Returns true when the server was started in public mode and the user+ * has not yet pasted an API key (nothing in localStorage, nothing baked+ * in via `VITE_SESSION_API_KEY`).+ *+ * Used by `root.tsx` to gate the app behind {@link ApiKeyEntryScreen}+ * before any network request is attempted.+ */+export function isAuthRequiredAndMissing(): boolean {+ if (!isAuthRequired()) return false;+ return !getConfiguredSessionApiKey();+}diff --git a/src/api/backend-registry/storage.ts b/src/api/backend-registry/storage.tsindex cb89f9b545..dfe89298b7 100644--- a/src/api/backend-registry/storage.ts+++ b/src/api/backend-registry/storage.ts@@ -1,3 +1,4 @@+import { syncBakedSessionApiKey } from "../agent-server-config";import { makeDefaultLocalBackend } from "./default-backend";import type { Backend, BackendKind, BackendSelection } from "./types";@@ -63,6 +64,16 @@ export function writeStoredBackends(backends: Backend[]): void {export function readStoredBackends(): Backend[] {if (typeof window === "undefined") return [];++ // Ensure the baked-in session API key (VITE_SESSION_API_KEY) is synced+ // into the legacy `openhands-agent-server-config` localStorage entry+ // BEFORE we read the backend registry. This matters when the user+ // restarts the stack with a different LOCAL_BACKEND_API_KEY โ without+ // this call the stale key in `openhands-agent-server-config` shadows+ // the new baked key, making `makeDefaultLocalBackend()` (and the+ // downstream `syncDefaultLocalBackendAuth`) read the wrong value.+ syncBakedSessionApiKey();+try {const raw = window.localStorage.getItem(BACKENDS_STORAGE_KEY);diff --git a/src/components/features/backends/api-key-entry-screen.tsx b/src/components/features/backends/api-key-entry-screen.tsxnew file mode 100644index 0000000000..21c39d6abd--- /dev/null+++ b/src/components/features/backends/api-key-entry-screen.tsx@@ -0,0 +1,150 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { SettingsClient } from "@openhands/typescript-client/clients";+import { I18nKey } from "#/i18n/declaration";+import { saveAgentServerConfig } from "#/api/agent-server-config";+import { isSdkHttpStatusError } from "#/api/agent-server-compatibility";+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";+import { useActiveBackendContext } from "#/contexts/active-backend-context";+import { BrandButton } from "#/components/features/settings/brand-button";+import {+ MODAL_MAX_WIDTH_VIEWPORT,+ modalWidthClassName,+} from "#/components/shared/modals/modal-body";+import { cn } from "#/utils/utils";+import { BackendStatusDot } from "./backend-status-dot";+import {+ BackendForm,+ type BackendFormSubmitPayload,+} from "./backend-form-modal";++/**+ * Full-screen prompt shown when the server is in public mode+ * (`VITE_AUTH_REQUIRED=true`) and no valid API key has been configured.+ *+ * Reuses {@link BackendForm} with `hostReadOnly` + `onSubmitOverride`+ * to render the standard name / host / API-key inputs while adding+ * server-side validation (calls `GET /api/settings` before persisting)+ * and a connection status indicator.+ */+export default function ApiKeyEntryScreen() {+ const { t } = useTranslation("openhands");+ const { active, updateBackend } = useActiveBackendContext();++ const host = window.location.origin;++ const [isValidating, setIsValidating] = React.useState(false);+ const [connectionStatus, setConnectionStatus] = React.useState<+ "idle" | "success" | "error"+ >("idle");+ const [errorMessage, setErrorMessage] = React.useState<string | null>(null);++ const handleSubmitOverride = React.useCallback(+ async (payload: BackendFormSubmitPayload) => {+ setIsValidating(true);+ setConnectionStatus("idle");+ setErrorMessage(null);++ try {+ await new SettingsClient(+ getAgentServerClientOptions({+ host: payload.host,+ sessionApiKey: payload.apiKey,+ timeout: 5000,+ }),+ ).getSettings();++ setConnectionStatus("success");++ updateBackend(active.backend.id, payload);+ saveAgentServerConfig({+ baseUrl: payload.host,+ sessionApiKey: payload.apiKey,+ });++ window.location.reload();+ } catch (err: unknown) {+ setConnectionStatus("error");++ if (isSdkHttpStatusError(err, 401)) {+ setErrorMessage(t(I18nKey.AUTH$INVALID_KEY));+ } else {+ const detail = err instanceof Error ? err.message : String(err);+ setErrorMessage(+ `${t(I18nKey.AUTH$CONNECTION_FAILED)}${detail ? `: ${detail}` : ""}`,+ );+ }+ setIsValidating(false);+ }+ },+ [active.backend.id, updateBackend, t],+ );++ return (+ <div+ data-testid="api-key-entry-screen"+ className="flex min-h-screen items-center justify-center bg-base px-6"+ >+ <div+ className={cn(+ "relative rounded-xl border border-[var(--oh-border)] bg-base-secondary",+ modalWidthClassName("md"),+ MODAL_MAX_WIDTH_VIEWPORT,+ )}+ >+ <div className="px-6 pt-6 pb-2 pr-12">+ <h2 className="text-lg font-semibold">+ {t(I18nKey.BACKEND$ADD_TITLE)}+ </h2>+ </div>++ <div className="px-6 pb-6 pt-2">+ <BackendForm+ mode="add"+ backend={{ ...active.backend, host, apiKey: "", name: "" }}+ onSubmitted={() => {}}+ testIdRoot="api-key-entry"+ hostReadOnly+ requireApiKey+ onSubmitOverride={handleSubmitOverride}+ renderActions={({ canSubmit, testIdRoot }) => (+ <>+ {connectionStatus !== "idle" && (+ <div className="flex items-center gap-3 text-sm">+ <BackendStatusDot+ isConnected={connectionStatus === "success"}+ />+ <span+ data-testid={`${testIdRoot}-status`}+ className={+ connectionStatus === "error"+ ? "text-red-400"+ : "text-green-400"+ }+ >+ {connectionStatus === "error"+ ? errorMessage+ : t(I18nKey.ONBOARDING$BACKEND_STATUS_CONNECTED)}+ </span>+ </div>+ )}++ <BrandButton+ type="submit"+ variant="secondary"+ isDisabled={!canSubmit || isValidating}+ testId={`${testIdRoot}-submit`}+ className="w-full text-center"+ >+ {isValidating+ ? t(I18nKey.ONBOARDING$BACKEND_STATUS_CHECKING)+ : t(I18nKey.BACKEND$CONNECT)}+ </BrandButton>+ </>+ )}+ />+ </div>+ </div>+ </div>+ );+}diff --git a/src/components/features/backends/backend-form-modal.tsx b/src/components/features/backends/backend-form-modal.tsxindex 1bcdfb1753..a4792e605d 100644--- a/src/components/features/backends/backend-form-modal.tsx+++ b/src/components/features/backends/backend-form-modal.tsx@@ -215,6 +215,13 @@ function BackendStatusBadge({);}+export interface BackendFormSubmitPayload {+ name: string;+ host: string;+ apiKey: string;+ kind: BackendKind;+}+export interface BackendFormProps {mode: BackendFormMode;/** Required when `mode === "edit"`. */@@ -238,6 +245,21 @@ export interface BackendFormProps {}) => React.ReactNode;/** Used to disambiguate test ids across the same screen. */testIdRoot?: string;+ /** When true, the host field is pre-filled and disabled. */+ hostReadOnly?: boolean;+ /**+ * When true, a non-empty API key is required for submission regardless+ * of the inferred backend kind. The standard add form allows empty+ * keys for local backends; the auth-gate screen needs to enforce one.+ */+ requireApiKey?: boolean;+ /**+ * Replace the default synchronous add/update-and-close submit with a+ * custom async handler. The form builds the payload, validates+ * client-side, then hands it to this callback. If the callback throws,+ * the form remains open so the caller can surface errors.+ */+ onSubmitOverride?: (payload: BackendFormSubmitPayload) => Promise<void>;}/**@@ -256,6 +278,9 @@ export function BackendForm({onSubmitted,renderActions,testIdRoot: explicitTestIdRoot,+ hostReadOnly,+ requireApiKey,+ onSubmitOverride,}: BackendFormProps) {const { t } = useTranslation("openhands");const { addBackend, updateBackend } = useActiveBackendContext();@@ -274,10 +299,11 @@ export function BackendForm({const testIdRoot =explicitTestIdRoot ?? (mode === "edit" ? "edit-backend" : "add-backend");+ const needsApiKey = requireApiKey || kind !== "local";const canSubmit =name.trim().length > 0 &&isValidHostUrl(host) &&- (kind === "local" || apiKey.trim().length > 0);+ (!needsApiKey || apiKey.trim().length > 0);// Error messages โ only surfaced after the user has blurred the field.const nameError =@@ -290,7 +316,7 @@ export function BackendForm({: undefined: undefined;- const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {+ const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {event.preventDefault();if (!canSubmit) {// Mark all validated fields as touched so inline errors become visible@@ -300,13 +326,18 @@ export function BackendForm({return;}- const payload = {+ const payload: BackendFormSubmitPayload = {name: name.trim(),host: normalizeHost(host),apiKey: apiKey.trim(),kind,};+ if (onSubmitOverride) {+ await onSubmitOverride(payload);+ return;+ }+if (mode === "edit" && backend) {updateBackend(backend.id, payload);} else {@@ -342,12 +373,13 @@ export function BackendForm({type="text"label={t(I18nKey.BACKEND$HOST_LABEL)}value={host}- onChange={setHost}+ onChange={hostReadOnly ? undefined : setHost}onBlur={() => setHostTouched(true)}placeholder={DEFAULT_OPENHANDS_CLOUD_HOST}className="w-full"showRequiredTagerror={hostError}+ isDisabled={hostReadOnly}/><SettingsInputdiff --git a/src/hooks/query/use-config.ts b/src/hooks/query/use-config.tsindex 39e121e051..995064df20 100644--- a/src/hooks/query/use-config.ts+++ b/src/hooks/query/use-config.ts@@ -1,5 +1,8 @@import { useQuery } from "@tanstack/react-query";-import { isAgentServerUnavailableError } from "#/api/agent-server-compatibility";+import {+ isAgentServerUnavailableError,+ isAgentServerAuthError,+} from "#/api/agent-server-compatibility";import OptionService from "#/api/option-service/option-service.api";import { QUERY_KEYS, CONFIG_CACHE_OPTIONS } from "./query-keys";@@ -12,7 +15,9 @@ export const useConfig = (options?: UseConfigOptions) =>queryKey: QUERY_KEYS.WEB_CLIENT_CONFIG,queryFn: OptionService.getConfig,retry: (failureCount, error) =>- !isAgentServerUnavailableError(error) && failureCount < 3,+ !isAgentServerUnavailableError(error) &&+ !isAgentServerAuthError(error) &&+ failureCount < 3,meta: { disableToast: true },...CONFIG_CACHE_OPTIONS,enabled: options?.enabled,diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 3a60b4152f..9d8de6c0e1 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -594,6 +594,40 @@"uk": "ะะพะฒัะพัะฝะธะน ะฒั ัะด ะดะพ OpenHands...","ca": "Tornant a iniciar sessiรณ a OpenHands..."},+ "AUTH$INVALID_KEY": {+ "en": "Invalid API key. Please check the key and try again.",+ "ja": "็กๅนใชAPIใญใผใงใใใญใผใ็ขบ่ชใใฆๅ่ฉฆ่กใใฆใใ ใใใ",+ "zh-CN": "ๆ ๆ็APIๅฏ้ฅใ่ฏทๆฃๆฅๅฏ้ฅๅ้่ฏใ",+ "zh-TW": "็กๆ็API้้ฐใ่ซๆชขๆฅ้้ฐๅพ้่ฉฆใ",+ "ko-KR": "์๋ชป๋ API ํค์ ๋๋ค. ํค๋ฅผ ํ์ธํ๊ณ ๋ค์ ์๋ํ์ธ์.",+ "no": "Ugyldig API-nรธkkel. Sjekk nรธkkelen og prรธv igjen.",+ "it": "Chiave API non valida. Controlla la chiave e riprova.",+ "pt": "Chave de API invรกlida. Verifique a chave e tente novamente.",+ "es": "Clave de API no vรกlida. Verifique la clave e intente de nuevo.",+ "ar": "ู ูุชุงุญ API ุบูุฑ ุตุงูุญ. ูุฑุฌู ุงูุชุญูู ู ู ุงูู ูุชุงุญ ูุงูู ุญุงููุฉ ู ุฑุฉ ุฃุฎุฑู.",+ "fr": "Clรฉ API invalide. Veuillez vรฉrifier la clรฉ et rรฉessayer.",+ "tr": "Geรงersiz API anahtarฤฑ. Lรผtfen anahtarฤฑ kontrol edin ve tekrar deneyin.",+ "de": "Ungรผltiger API-Schlรผssel. Bitte รผberprรผfen Sie den Schlรผssel und versuchen Sie es erneut.",+ "uk": "ะะตะดัะนัะฝะธะน ะบะปัั API. ะะตัะตะฒัััะต ะบะปัั ั ัะฟัะพะฑัะนัะต ัะต ัะฐะท.",+ "ca": "Clau d'API no vร lida. Comproveu la clau i torneu-ho a provar."+ },+ "AUTH$CONNECTION_FAILED": {+ "en": "Connection failed",+ "ja": "ๆฅ็ถใซๅคฑๆใใพใใ",+ "zh-CN": "่ฟๆฅๅคฑ่ดฅ",+ "zh-TW": "้ฃ็ทๅคฑๆ",+ "ko-KR": "์ฐ๊ฒฐ ์คํจ",+ "no": "Tilkobling mislyktes",+ "it": "Connessione fallita",+ "pt": "Falha na conexรฃo",+ "es": "Error de conexiรณn",+ "ar": "ูุดู ุงูุงุชุตุงู",+ "fr": "รchec de la connexion",+ "tr": "Baฤlantฤฑ baลarฤฑsฤฑz",+ "de": "Verbindung fehlgeschlagen",+ "uk": "ะะพะผะธะปะบะฐ ะท'ัะดะฝะฐะฝะฝั",+ "ca": "Error de connexiรณ"+ },"SECURITY$LOW_RISK": {"en": "Risk: Low","ja": "ใชในใฏ: ไฝ",diff --git a/src/root.tsx b/src/root.tsxindex d0e9fcf331..7fd8c5365a 100644--- a/src/root.tsx+++ b/src/root.tsx@@ -11,7 +11,11 @@ import "./tailwind.css";import "./index.css";import React from "react";import { Toaster } from "react-hot-toast";-import { isAgentServerUnavailableError } from "#/api/agent-server-compatibility";+import {+ isAgentServerUnavailableError,+ isAgentServerAuthError,+} from "#/api/agent-server-compatibility";+import { isAuthRequiredAndMissing } from "#/api/agent-server-config";import { TOAST_OPTIONS } from "#/utils/custom-toast-handlers";import { TelemetryConsentBanner } from "#/components/features/analytics/telemetry-consent-banner";import { LoadingSpinner } from "#/components/shared/loading-spinner";@@ -38,6 +42,11 @@ const ManageBackendsModal = React.lazy(() =>})),);+// Rendered when the backend returns 401 (public mode โ user must paste key).+const ApiKeyEntryScreen = React.lazy(+ () => import("#/components/features/backends/api-key-entry-screen"),+);+export function Layout({ children }: { children: React.ReactNode }) {return (<html lang="en">@@ -105,7 +114,24 @@ export const meta: MetaFunction = () => [];export default function App() {- const config = useConfig();+ // Flag-based gate: in public mode (VITE_AUTH_REQUIRED=true) with no+ // session key yet, show the auth screen immediately โ no network+ // round-trip needed.+ const authMissing = isAuthRequiredAndMissing();++ // Skip the /server_info probe entirely when we already know auth is+ // required and missing โ it would just 401 and waste time.+ const config = useConfig({ enabled: !authMissing });++ // No key at all โ instant auth screen (no network).+ // Stale key โ /server_info 401 โ auth screen (public mode only).+ if (authMissing || isAgentServerAuthError(config.error)) {+ return (+ <React.Suspense fallback={<AgentServerBootstrapLoading />}>+ <ApiKeyEntryScreen />+ </React.Suspense>+ );+ }if (config.isPending || config.isLoading) {return <AgentServerBootstrapLoading />;diff --git a/tests/e2e/live/utils/agent-server-conversation.ts b/tests/e2e/live/utils/agent-server-conversation.tsindex 291e4bc5e4..bcc3418503 100644--- a/tests/e2e/live/utils/agent-server-conversation.ts+++ b/tests/e2e/live/utils/agent-server-conversation.ts@@ -43,9 +43,7 @@ const llmModel =: "anthropic/claude-haiku-4-5-20251001");export const sessionApiKey = firstNonEmpty(process.env.LIVE_E2E_SESSION_API_KEY,- process.env.SESSION_API_KEY,- process.env.OH_SESSION_API_KEYS_0,- process.env.VITE_SESSION_API_KEY,+ process.env.LOCAL_BACKEND_API_KEY,);if (!sessionApiKey) {@@ -83,7 +81,7 @@ export function getLiveArtifactMask(page: Page): Locator[] {page.locator('[data-testid*="token" i]'),page.locator('[data-testid*="api-key" i]'),page.getByText(- /(?:OPENAI_API_KEY|ANTHROPIC_API_KEY|LIVE_E2E_LLM_API_KEY|LLM_API_KEY|SESSION_API_KEY|X-Session-API-Key)\s*[:=]\s*\S+/i,+ /(?:OPENAI_API_KEY|ANTHROPIC_API_KEY|LIVE_E2E_LLM_API_KEY|LLM_API_KEY|LOCAL_BACKEND_API_KEY|SESSION_API_KEY|X-Session-API-Key)\s*[:=]\s*\S+/i,),page.getByText(/(?:sk-[A-Za-z0-9_-]{8,}|gh[pousr]_[A-Za-z0-9_]{8,}|xox[baprs]-[A-Za-z0-9-]{8,}|(?:api[_ -]?key|secret|password|token)\s*[:=]\s*\S+)/i,diff --git a/tests/e2e/mock-llm/mock-llm-auth-modes.spec.ts b/tests/e2e/mock-llm/mock-llm-auth-modes.spec.tsnew file mode 100644index 0000000000..eda09ab310--- /dev/null+++ b/tests/e2e/mock-llm/mock-llm-auth-modes.spec.ts@@ -0,0 +1,259 @@+/**+ * Mock-LLM E2E tests for authentication modes.+ *+ * Tests two scenarios using the same backend (agent-server) started by the+ * main mock-LLM stack:+ *+ * 1. **Key rotation (non-public):** The stack runs with key A, but+ * localStorage still holds a stale key B from a previous session.+ * Verifies that the boot-time sync in `syncBakedSessionApiKey()`+ * clears the stale key so the app loads and can talk to the backend.+ *+ * 2. **Public-mode auth gate:** A separate static-server instance+ * serves the same build with `--auth-required` (no baked session+ * key). Verifies:+ * - The `ApiKeyEntryScreen` is shown when no key is configured.+ * - Submitting the correct key lets the app through.+ * - Submitting a wrong key shows an inline error.+ *+ * @spec BM-002 โ Key rotation recovery via syncBakedSessionApiKey+ */++import { test, expect } from "@playwright/test";+import {+ BACKEND_URL,+ SESSION_API_KEY,+ PUBLIC_MODE_URL,+ seedLocalStorage,+ routeSessionApiKey,+ dismissAnalyticsModal,+ waitForTestId,+} from "./utils/mock-llm-helpers";++test.describe.configure({ mode: "serial" });++// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+// 1. Key rotation (non-public mode)+// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test.describe("auth mode: non-public key rotation", () => {+ test("recovers when localStorage has a stale session API key", async ({+ page,+ request,+ }) => {+ // Seed localStorage with a STALE key (different from the real SESSION_API_KEY+ // that the agent-server was started with). This simulates a user who ran+ // `LOCAL_BACKEND_API_KEY=old-key npm run dev` previously and now restarts+ // with `LOCAL_BACKEND_API_KEY=<new-key> npm run dev`.+ const STALE_KEY = "this-is-a-stale-key-from-previous-session";++ await page.addInitScript(+ ({ staleKey }) => {+ // 1. Seed the legacy agent-server-config with the stale key+ window.localStorage.setItem(+ "openhands-agent-server-config",+ JSON.stringify({+ baseUrl: window.location.origin,+ sessionApiKey: staleKey,+ }),+ );++ // 2. Seed the backend registry with the stale key+ window.localStorage.setItem(+ "openhands-backends",+ JSON.stringify([+ {+ id: "default-local",+ name: "Local",+ host: window.location.origin,+ apiKey: staleKey,+ kind: "local",+ },+ ]),+ );++ // 3. Mark onboarding as done, opt out of analytics+ window.localStorage.setItem("openhands-onboarded", "1");+ window.localStorage.setItem("analytics-consent", "false");+ window.localStorage.setItem("openhands-telemetry-consent", "denied");+ window.localStorage.setItem("openhands-telemetry-first-use", "true");+ },+ { staleKey: STALE_KEY },+ );++ // The baked-in VITE_SESSION_API_KEY (from the stack) should be the+ // CORRECT key. The syncBakedSessionApiKey() function should overwrite+ // the stale localStorage key on boot.+ await routeSessionApiKey(page);+ await page.goto("/", { waitUntil: "domcontentloaded" });+ await dismissAnalyticsModal(page);++ // Verify the app loads โ the home chat launcher should be visible.+ // If the stale key wasn't synced, we'd see the "agent server+ // unavailable" screen instead.+ await waitForTestId(page, "home-chat-launcher");++ // Verify the backend is reachable with a direct API call.+ // This confirms the synced key is actually used for API requests.+ const settingsResp = await request.get(`${BACKEND_URL}/api/settings`, {+ headers: { "X-Session-API-Key": SESSION_API_KEY },+ });+ expect(+ settingsResp.ok(),+ `GET /api/settings should succeed but returned ${settingsResp.status()}`,+ ).toBe(true);++ // Verify localStorage was updated: the stale key should have been+ // replaced by the baked key.+ const storedConfig = await page.evaluate(() => {+ const raw = window.localStorage.getItem("openhands-agent-server-config");+ return raw ? JSON.parse(raw) : null;+ });+ expect(storedConfig?.sessionApiKey).not.toBe(STALE_KEY);+ });+});++// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+// 2. Public-mode auth gate+// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test.describe("auth mode: public gate", () => {+ // The analytics consent modal overlays the auth screen and intercepts+ // pointer events, so suppress it for every public-mode test.+ test.beforeEach(async ({ page }) => {+ await page.addInitScript(() => {+ window.localStorage.setItem("analytics-consent", "false");+ window.localStorage.setItem("openhands-telemetry-consent", "denied");+ });+ });++ test("shows the auth screen when no key is configured", async ({ page }) => {+ // Navigate to the public-mode static server (--auth-required, no+ // baked session key). The browser has a clean context (no localStorage)+ // so isAuthRequiredAndMissing() should return true.+ await page.goto(PUBLIC_MODE_URL, { waitUntil: "domcontentloaded" });++ // The ApiKeyEntryScreen should be visible.+ await waitForTestId(page, "api-key-entry-screen");++ // The main app UI should NOT be visible.+ const homeLauncher = page.getByTestId("home-chat-launcher");+ await expect(homeLauncher).not.toBeVisible({ timeout: 2_000 });+ });++ test("rejects an incorrect key with an inline error", async ({ page }) => {+ await page.goto(PUBLIC_MODE_URL, { waitUntil: "domcontentloaded" });+ await waitForTestId(page, "api-key-entry-screen");++ // Focus โ fill pattern needed for React controlled inputs (see+ // mock-llm-conversation.spec.ts for the established pattern).+ const nameInput = page.getByTestId("api-key-entry-name");+ await nameInput.click();+ await nameInput.fill("Test Server");++ const keyInput = page.getByTestId("api-key-entry-api-key");+ await keyInput.click();+ await keyInput.fill("wrong-key-12345");++ // Submit+ await page.getByTestId("api-key-entry-submit").click();++ // Should show an error status (not navigate away).+ const statusEl = page.getByTestId("api-key-entry-status");+ await expect(statusEl).toBeVisible({ timeout: 10_000 });+ await expect(statusEl).toHaveClass(/text-red/);+ });++ test("allows access after pasting the correct key", async ({ page }) => {+ await page.goto(PUBLIC_MODE_URL, { waitUntil: "domcontentloaded" });+ await waitForTestId(page, "api-key-entry-screen");++ // Focus โ fill pattern needed for React controlled inputs.+ const nameInput = page.getByTestId("api-key-entry-name");+ await nameInput.click();+ await nameInput.fill("Test Server");++ const keyInput = page.getByTestId("api-key-entry-api-key");+ await keyInput.click();+ await keyInput.fill(SESSION_API_KEY);++ // Submit โ this validates against GET /api/settings, persists the key,+ // and triggers a page reload.+ await page.getByTestId("api-key-entry-submit").click();++ // After reload, the app should load normally. The onboarding modal+ // may appear (fresh localStorage), so we dismiss it. The key+ // indicator is that we do NOT see the auth screen anymore and the+ // page eventually shows app UI (home launcher or onboarding).+ //+ // Wait for the page to reload and settle.+ await page.waitForLoadState("domcontentloaded", { timeout: 15_000 });++ // After the reload, the auth screen should NOT reappear.+ // We may see onboarding or the home page โ either is acceptable.+ const authScreen = page.getByTestId("api-key-entry-screen");+ await expect(authScreen).not.toBeVisible({ timeout: 10_000 });+ });++ test("re-prompts when the server rotates its key (stale localStorage)", async ({+ page,+ }) => {+ // Simulate the state after a key rotation:+ // - The user previously authenticated with key A (now stale)+ // - The server restarted with key B (SESSION_API_KEY)+ // - localStorage still holds key A+ //+ // On load the app detects auth is required, finds a stored key, so+ // it skips the instant gate (isAuthRequiredAndMissing โ false) and+ // proceeds to probe /server_info with the stale key. The agent-server+ // returns 401, isAgentServerAuthError fires, and the auth screen+ // appears โ giving the user a chance to paste the new key.+ const STALE_KEY = "rotated-out-old-key-from-previous-deploy";++ // The beforeEach already seeds analytics consent. Layer on the stale+ // backend credentials.+ await page.addInitScript(+ ({ staleKey, host }) => {+ window.localStorage.setItem(+ "openhands-agent-server-config",+ JSON.stringify({ baseUrl: host, sessionApiKey: staleKey }),+ );+ window.localStorage.setItem(+ "openhands-backends",+ JSON.stringify([+ {+ id: "default-local",+ name: "Public Server",+ host,+ apiKey: staleKey,+ kind: "local",+ },+ ]),+ );+ },+ { staleKey: STALE_KEY, host: PUBLIC_MODE_URL },+ );++ await page.goto(PUBLIC_MODE_URL, { waitUntil: "domcontentloaded" });++ // The app tries to probe with the stale key โ 401 โ auth screen.+ await waitForTestId(page, "api-key-entry-screen");++ // Enter the new (correct) key.+ const nameInput = page.getByTestId("api-key-entry-name");+ await nameInput.click();+ await nameInput.fill("Rotated Server");++ const keyInput = page.getByTestId("api-key-entry-api-key");+ await keyInput.click();+ await keyInput.fill(SESSION_API_KEY);++ await page.getByTestId("api-key-entry-submit").click();++ // After submitting the correct key, the page reloads and the auth+ // screen should not reappear.+ await page.waitForLoadState("domcontentloaded", { timeout: 15_000 });+ const authScreen = page.getByTestId("api-key-entry-screen");+ await expect(authScreen).not.toBeVisible({ timeout: 10_000 });+ });+});diff --git a/tests/e2e/mock-llm/utils/mock-llm-helpers.ts b/tests/e2e/mock-llm/utils/mock-llm-helpers.tsindex e8f6ce7c0c..2bcbfdcee8 100644--- a/tests/e2e/mock-llm/utils/mock-llm-helpers.ts+++ b/tests/e2e/mock-llm/utils/mock-llm-helpers.ts@@ -5,11 +5,7 @@* shorter timeouts (responses are instant), no real credential handling.*/-import {- expect,- type APIRequestContext,- type Page,-} from "@playwright/test";+import { expect, type APIRequestContext, type Page } from "@playwright/test";// Tokens that the mock LLM server uses โ must match mock-llm-server.py.export const BASH_TOKEN = "MOCK_LLM_E2E_BASH_OK";@@ -19,17 +15,18 @@ export const BASH_COMMAND = `printf '${BASH_TOKEN}\\n'`;// Ports / URLs โ set via env or defaults matching playwright.mock-llm.config.ts.// The agent-canvas binary exposes a single ingress port; API calls are proxied// through it, so BACKEND_URL = ingress URL (no separate backend port).-export const MOCK_LLM_PORT =- process.env.MOCK_LLM_PORT ?? "9999";+export const MOCK_LLM_PORT = process.env.MOCK_LLM_PORT ?? "9999";export const MOCK_LLM_BASE_URL = `http://127.0.0.1:${MOCK_LLM_PORT}`;export const BACKEND_URL =process.env.MOCK_LLM_BACKEND_URL ?? "http://localhost:18300";+// Public-mode static server (--auth-required, no session key injected).+export const PUBLIC_MODE_URL =+ process.env.MOCK_LLM_PUBLIC_MODE_URL ?? "http://localhost:18301";export const SESSION_API_KEY = (() => {const key =process.env.MOCK_LLM_SESSION_API_KEY ??+ process.env.LOCAL_BACKEND_API_KEY ??process.env.LIVE_E2E_SESSION_API_KEY ??- process.env.SESSION_API_KEY ??- process.env.VITE_SESSION_API_KEY ??"";if (!key) throw new Error("Session API key is required for mock-LLM E2E.");return key;@@ -66,10 +63,9 @@ export async function waitForPath(timeout = 30_000,) {await expect- .poll(- () => page.evaluate(() => window.location.pathname).catch(() => ""),- { timeout },- )+ .poll(() => page.evaluate(() => window.location.pathname).catch(() => ""), {+ timeout,+ }).toMatch(pattern);}