Skip to content

🙌 OpenHands: AI-Driven Development

fix(mars): preserve DigitalOcean sessions through auth recovery (#18604)

🐾 smolpaws4533ab2480cd
diff --git a/.agents/skills/frontend-api-contracts/references/guide.md b/.agents/skills/frontend-api-contracts/references/guide.md
index 2d85b7634d..50c10010ab 100644
--- a/.agents/skills/frontend-api-contracts/references/guide.md
+++ b/.agents/skills/frontend-api-contracts/references/guide.md
@@ -167,7 +167,7 @@ return new ConversationClient(getAgentServerClientOptions()).someMethod(...);
- App-level user preferences (language, sound notifications, analytics consent, git identity, disabled skills) are persisted server-side under `PersistedSettings.misc_settings.app_preferences` since agent-server 1.27. `misc_settings` is a generic container for frontend-owned settings the agent doesn't interpret; `app_preferences` is currently its only nested category, but additional categories (e.g. a future `ui_preferences` for sidebar layout / view modes) drop in as additional siblings without churning the top-level wire shape. `GET /api/settings` returns the block under `misc_settings.app_preferences`, and `PATCH /api/settings` accepts a `misc_settings_diff` that is **deep-merged** into the persisted block (same semantics as `agent_settings_diff` / `conversation_settings_diff`). Partial diffs like `{"misc_settings_diff": {"app_preferences": {"language": "fr"}}}` update only the named nested field; sibling `app_preferences` fields are left untouched. Lists (`disabled_skills`) are replaced wholesale by the deep-merge. `SettingsService.transformApiResponse` hoists the nested fields onto the flat `Settings` shape so the rest of the GUI keeps reading them as top-level keys (`settings.language`, `settings.disabled_skills`, …). Do NOT reintroduce a localStorage fallback for these fields — `disabled_skills` and the rest belong in `misc_settings_diff.app_preferences`. The previous flat `app_preferences` / `app_preferences_diff` API (introduced in SDK PR #3539, never shipped to users) was replaced by the `misc_settings` container before either side reached a stable release; on-disk v2 settings files written by the flat shape are migrated automatically on first read by the agent-server. The legacy localStorage migration (`src/api/settings-service/legacy-app-preferences-migration.ts`) was removed in issue #1337 after a one-release drain period — it is no longer needed.
- 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.
+ - **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. After validation, the form updates or creates the ordinary local backend at the actual page origin in the backend registry (the record `getMarsBridgeHeaders` reads the key from). A live DigitalOcean guest (`/mars/sessions/<id>`) stays selected with its host/key/session metadata untouched; any other active backend gives way to that hosting record, or the gate would return after the reload. It must not treat a same-origin session proxy path or a foreign backend as the hosting Canvas. The page then reloads to reconnect using the refreshed hosting credentials.
- 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()`).
diff --git a/.github/pr-assets/pr-18604-01-before-real-do-api-key-gate.png b/.github/pr-assets/pr-18604-01-before-real-do-api-key-gate.png
new file mode 100644
index 0000000000..3a5bed0d06
Binary files /dev/null and b/.github/pr-assets/pr-18604-01-before-real-do-api-key-gate.png differ
diff --git a/.github/pr-assets/pr-18604-02-after-real-do-session.png b/.github/pr-assets/pr-18604-02-after-real-do-session.png
new file mode 100644
index 0000000000..68113a02bf
Binary files /dev/null and b/.github/pr-assets/pr-18604-02-after-real-do-session.png differ
diff --git a/.github/pr-assets/pr-18604-03-after-reload-retained-no-gate.png b/.github/pr-assets/pr-18604-03-after-reload-retained-no-gate.png
new file mode 100644
index 0000000000..160f407d3e
Binary files /dev/null and b/.github/pr-assets/pr-18604-03-after-reload-retained-no-gate.png differ
diff --git a/.pr/recovery-18604/after-outcome.json b/.pr/recovery-18604/after-outcome.json
new file mode 100644
index 0000000000..33cdd6cf0b
--- /dev/null
+++ b/.pr/recovery-18604/after-outcome.json
@@ -0,0 +1,100 @@
+{
+ "label": "after",
+ "guestPreserved": true,
+ "rootRecovered": true,
+ "activeGuest": true,
+ "guestKeyEmpty": true,
+ "guestHost": "http://127.0.0.1:18640/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12",
+ "guestName": "openhands-do-test-9l71qg",
+ "backendCount": 2,
+ "events": [
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 200
+ },
+ {
+ "path": "/server_info",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 401
+ },
+ {
+ "path": "/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/server_info",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 200
+ }
+ ]
+}
\ No newline at end of file
diff --git a/.pr/recovery-18604/after-recovery.webm b/.pr/recovery-18604/after-recovery.webm
new file mode 100644
index 0000000000..c18bd0a9fa
Binary files /dev/null and b/.pr/recovery-18604/after-recovery.webm differ
diff --git a/.pr/recovery-18604/after-result.png b/.pr/recovery-18604/after-result.png
new file mode 100644
index 0000000000..c078cd8b23
Binary files /dev/null and b/.pr/recovery-18604/after-result.png differ
diff --git a/.pr/recovery-18604/before-outcome.json b/.pr/recovery-18604/before-outcome.json
new file mode 100644
index 0000000000..0d52155e96
--- /dev/null
+++ b/.pr/recovery-18604/before-outcome.json
@@ -0,0 +1,88 @@
+{
+ "label": "before",
+ "guestPreserved": false,
+ "rootRecovered": false,
+ "activeGuest": true,
+ "guestKeyEmpty": false,
+ "guestHost": "http://127.0.0.1:18640",
+ "guestName": "Canvas recovered",
+ "backendCount": 2,
+ "events": [
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/server_info",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 200
+ },
+ {
+ "path": "/mars/sessions/01a16026-ecf4-7e1d-b214-addaf61b2e12/server_info",
+ "status": 401
+ },
+ {
+ "path": "/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/server_info",
+ "status": 200
+ },
+ {
+ "path": "/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/server_info",
+ "status": 200
+ },
+ {
+ "path": "/api/settings",
+ "status": 401
+ },
+ {
+ "path": "/api/settings",
+ "status": 200
+ },
+ {
+ "path": "/server_info",
+ "status": 200
+ }
+ ]
+}
\ No newline at end of file
diff --git a/.pr/recovery-18604/before-recovery.webm b/.pr/recovery-18604/before-recovery.webm
new file mode 100644
index 0000000000..94ad13e1ae
Binary files /dev/null and b/.pr/recovery-18604/before-recovery.webm differ
diff --git a/.pr/recovery-18604/before-result.png b/.pr/recovery-18604/before-result.png
new file mode 100644
index 0000000000..ce324f7403
Binary files /dev/null and b/.pr/recovery-18604/before-result.png differ
diff --git a/.pr/recovery-18604/verification.md b/.pr/recovery-18604/verification.md
new file mode 100644
index 0000000000..7ffcc00a9b
--- /dev/null
+++ b/.pr/recovery-18604/verification.md
@@ -0,0 +1,42 @@
+# Live credential recovery verification — PR 18604
+
+Date: 2026-10-21. Real DigitalOcean VM reused; no VM creation, pause, destruction or LLM message was performed.
+
+## Exact sources and topology
+
+- Before: `7b9fbcda38e916fba87c11f1cd9f3bf34f7a5ada`.
+- After: `a17cc2a7115540b0ef097a92401d63866bb8fc05`. The recovery form source in the temporary after build is byte-identical to this commit.
+- Both copies used the production `npm run build` output, served with `scripts/static-server.mjs --auth-required --disable-telemetry` on isolated `http://127.0.0.1:18640`.
+- The real `/mars`, `/api`, `/server_info`, `/health`, `/sockets`, `/alive` and `/ready` routes were proxied to the existing localhost:8000 stack. It was neither restarted nor changed for this check. Its saved DigitalOcean OAuth connection and existing READY session were reused.
+- **Shared verification prerequisite:** both temporary copies applied only the frontend bridge-key forwarding source diff from [PR 18465](https://github.com/OpenHands/OpenHands/pull/18465) at head `09336296e70766963ed2f635e5ec9b066ccfaf15`, so typed hosting keys can authenticate real bridge RPCs. Patch SHA-256: `fa18937ecf0b1c8a7595cc7afc936f0d6e9c5d4817a1edbd39e69302fcd5b1ee`. This prerequisite is not part of the recovery implementation commit.
+- **Shared topology adjustment:** both temporary copies set the reverse proxy's `changeOrigin` to false, preserving the browser Host so the real bridge's same-origin checks work behind the extra localhost proxy. This is verification infrastructure only, not a product change or mock.
+- Browser: repository-pinned Playwright Chromium, 1280×900. No routes or API responses were mocked. Trace recording was disabled. Analytics destinations were blocked.
+
+## Procedure
+
+1. Complete ordinary backend onboarding through the UI with the real hosting Canvas key; skip model setup.
+2. In Add Backend → Providers → DigitalOcean, select the existing `openhands-do-test` agent. Its existing `openhands-do-test-9l71qg` session connects and opens its existing conversation. No new conversation is submitted.
+3. Save this UI-created browser state privately for equivalent before/after starting states.
+4. **Explicit fault injection:** replace only the saved hosting-root key with a known invalid string, clear this isolated context's bridge cookie, and reload. This simulates stale hosting credentials plus an expired bridge cookie. The guest record and active selection remain unchanged. The real guest `/server_info` request returns 401 and the production recovery form appears.
+5. Enter a name and the real hosting key in the recovery form. Its actual `GET /api/settings` validation returns 200. Observe reload and inspect the real persisted registry.
+
+## Results
+
+| Assertion | Before | After |
+| --- | --- | --- |
+| Hosting root receives recovered key | No | Yes |
+| Existing guest id/name/host/kind/key/session fields preserved | No | Yes |
+| Guest key stays empty | No | Yes |
+| Guest remains selected and reaches its real `/server_info` after recovery | No: saved guest host becomes Canvas root | Yes: 200 from the same VM |
+| Registry contains original root and guest (2 records) | 2, but guest overwritten | 2, both correct |
+
+Before, the selected guest is renamed “Canvas recovered”, its host becomes the Canvas root and its key becomes the hosting key, while the actual root still has stale credentials. The app displays the local Canvas conversations. After, the hosting root is updated, the original DigitalOcean guest remains unchanged and reconnects to the same session.
+
+The focused unit tests separately cover absent-root creation and cloud-looking Canvas origins; this live run intentionally covers the existing-root recovery flow only.
+
+## Media and privacy
+
+- `before-result.png` / `after-result.png`: actual final browser screens with backend menu open.
+- `before-recovery.webm` / `after-recovery.webm`: continuous real-browser recording through stale-key recovery and reload. No simulated UI or stitched outcome frames.
+- A fixed black rectangle redacts unrelated sidebar conversation titles in the published images/videos. API-key inputs remain password-masked. There are no account panels, emails, token values, raw request bodies or storage snapshots in the published assets.
+- `before-outcome.json` / `after-outcome.json` retain only boolean registry comparisons, guest host/name and response paths/statuses; no credentials.
diff --git a/__tests__/components/backends/api-key-entry-screen.test.tsx b/__tests__/components/backends/api-key-entry-screen.test.tsx
index ac509314cf..11cb0a0974 100644
--- a/__tests__/components/backends/api-key-entry-screen.test.tsx
+++ b/__tests__/components/backends/api-key-entry-screen.test.tsx
@@ -1,9 +1,15 @@
import React from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { SettingsClient } from "@openhands/typescript-client/clients";
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 { BACKENDS_STORAGE_KEY } from "#/api/backend-registry/storage";
+import {
+ BACKENDS_STORAGE_KEY,
+ readStoredActiveBackend,
+ writeStoredActiveBackend,
+} from "#/api/backend-registry/storage";
+import type { Backend } from "#/api/backend-registry/types";
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";
@@ -63,6 +69,8 @@ const ORIGINAL_LOCATION = window.location;
beforeEach(() => {
window.localStorage.clear();
+ window.sessionStorage.clear();
+ window.localStorage.setItem(BACKENDS_STORAGE_KEY, "[]");
__resetActiveStoreForTests();
getSettingsMock.mockReset();
@@ -81,6 +89,7 @@ beforeEach(() => {
afterEach(() => {
window.localStorage.clear();
+ window.sessionStorage.clear();
__resetActiveStoreForTests();
vi.unstubAllEnvs();
Object.defineProperty(window, "location", {
@@ -171,12 +180,246 @@ describe("ApiKeyEntryScreen", () => {
const stored = JSON.parse(
window.localStorage.getItem(BACKENDS_STORAGE_KEY) ?? "[]",
);
- expect(stored[0].apiKey).toBe("correct-key");
+ expect(
+ stored.find((backend: Backend) => backend.host === window.location.origin)
+ ?.apiKey,
+ ).toBe("correct-key");
// Page reloaded
expect(reloadMock).toHaveBeenCalled();
});
+ it.each([
+ { hasRootBackend: true, origin: "http://localhost:8000" },
+ {
+ hasRootBackend: false,
+ origin: "https://work-1.prod-runtime.all-hands.dev",
+ },
+ ])(
+ "recovers the hosting key at $origin and preserves the active DigitalOcean session (root exists: $hasRootBackend)",
+ async ({ hasRootBackend, origin }) => {
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ value: { ...window.location, origin },
+ });
+ const guest: Backend = {
+ id: "mars-session",
+ name: "My DigitalOcean agent",
+ host: `${window.location.origin}/mars/sessions/test-session`,
+ apiKey: "",
+ kind: "local",
+ marsSessionId: "test-session",
+ marsConfigId: "test-config",
+ connectionRevision: 3,
+ };
+ const otherBackends: Backend[] = [
+ {
+ id: "remote-server",
+ name: "Remote server",
+ host: "https://other.example.test",
+ apiKey: "remote-key",
+ kind: "local",
+ },
+ {
+ id: "path-backend",
+ name: "Another service",
+ host: `${window.location.origin}/other-service`,
+ apiKey: "service-key",
+ kind: "local",
+ },
+ ];
+ const root: Backend = {
+ id: "canvas",
+ name: "Canvas",
+ host: `${window.location.origin}/`,
+ apiKey: "stale-key",
+ kind: "local",
+ };
+ window.localStorage.setItem(
+ BACKENDS_STORAGE_KEY,
+ JSON.stringify([
+ guest,
+ ...otherBackends,
+ ...(hasRootBackend ? [root] : []),
+ ]),
+ );
+ writeStoredActiveBackend({ backendId: guest.id });
+ __resetActiveStoreForTests();
+ getSettingsMock.mockResolvedValueOnce({});
+ renderScreen();
+ const user = userEvent.setup();
+
+ await fillRequiredFields(user, { name: "My Canvas", apiKey: "new-key" });
+ await user.click(screen.getByTestId("api-key-entry-submit"));
+ await waitFor(() => expect(reloadMock).toHaveBeenCalled());
+
+ const stored: Backend[] = JSON.parse(
+ window.localStorage.getItem(BACKENDS_STORAGE_KEY) ?? "[]",
+ );
+ expect(SettingsClient).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ host: window.location.origin,
+ apiKey: "new-key",
+ }),
+ );
+ expect(stored).toHaveLength(4);
+ expect(readStoredActiveBackend()?.backendId).toBe(guest.id);
+ for (const unchanged of [guest, ...otherBackends]) {
+ expect(stored.find((backend) => backend.id === unchanged.id)).toEqual(
+ unchanged,
+ );
+ }
+ expect(
+ stored.find((backend) => backend.host === window.location.origin),
+ ).toMatchObject({
+ ...(hasRootBackend ? { id: root.id } : {}),
+ name: "My Canvas",
+ apiKey: "new-key",
+ kind: "local",
+ });
+ },
+ );
+
+ it("preserves the registry and selection when a recovery key is rejected", async () => {
+ const guest: Backend = {
+ id: "mars-session",
+ name: "DigitalOcean",
+ host: `${window.location.origin}/mars/sessions/test-session`,
+ apiKey: "",
+ kind: "local",
+ marsSessionId: "test-session",
+ };
+ window.localStorage.setItem(BACKENDS_STORAGE_KEY, JSON.stringify([guest]));
+ writeStoredActiveBackend({ backendId: guest.id });
+ __resetActiveStoreForTests();
+ 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"));
+ await waitFor(() =>
+ expect(screen.getByTestId("api-key-entry-status")).toHaveTextContent(
+ "AUTH$INVALID_KEY",
+ ),
+ );
+
+ expect(
+ JSON.parse(window.localStorage.getItem(BACKENDS_STORAGE_KEY) ?? "[]"),
+ ).toEqual([guest]);
+ expect(readStoredActiveBackend()?.backendId).toBe(guest.id);
+ expect(reloadMock).not.toHaveBeenCalled();
+ });
+
+ async function recoverWith(records: Backend[], activeId: string) {
+ window.localStorage.setItem(BACKENDS_STORAGE_KEY, JSON.stringify(records));
+ writeStoredActiveBackend({ backendId: activeId });
+ __resetActiveStoreForTests();
+ getSettingsMock.mockResolvedValueOnce({});
+ renderScreen();
+ const user = userEvent.setup();
+ await fillRequiredFields(user, { name: "My Canvas", apiKey: "new-key" });
+ await user.click(screen.getByTestId("api-key-entry-submit"));
+ await waitFor(() => expect(reloadMock).toHaveBeenCalled());
+ const stored: Backend[] = JSON.parse(
+ window.localStorage.getItem(BACKENDS_STORAGE_KEY) ?? "[]",
+ );
+ const activeAfter = stored.find(
+ (backend) => backend.id === readStoredActiveBackend()?.backendId,
+ );
+ return { stored, activeAfter };
+ }
+
+ it.each([{ hasRootBackend: true }, { hasRootBackend: false }])(
+ "selects the Canvas root instead of a remote agent-server that tripped the gate (root exists: $hasRootBackend)",
+ async ({ hasRootBackend }) => {
+ const remote: Backend = {
+ id: "remote-server",
+ name: "Remote server",
+ host: "https://other.example.test",
+ apiKey: "",
+ kind: "local",
+ };
+ const root: Backend = {
+ id: "canvas",
+ name: "Canvas",
+ host: `${window.location.origin}/`,
+ apiKey: "stale-key",
+ kind: "local",
+ };
+
+ const { stored, activeAfter } = await recoverWith(
+ hasRootBackend ? [remote, root] : [remote],
+ remote.id,
+ );
+
+ expect(activeAfter).toMatchObject({
+ ...(hasRootBackend ? { id: root.id } : {}),
+ apiKey: "new-key",
+ kind: "local",
+ });
+ expect(new URL(activeAfter!.host).origin).toBe(window.location.origin);
+ expect(stored.find((backend) => backend.id === remote.id)).toEqual(
+ remote,
+ );
+ },
+ );
+
+ it("updates the active root when the origin has more than one root entry", async () => {
+ const first: Backend = {
+ id: "root-a",
+ name: "Root A",
+ host: window.location.origin,
+ apiKey: "stale-a",
+ kind: "local",
+ };
+ const active: Backend = {
+ id: "root-b",
+ name: "Root B",
+ host: `${window.location.origin}/`,
+ apiKey: "stale-b",
+ kind: "local",
+ };
+
+ const { stored, activeAfter } = await recoverWith(
+ [first, active],
+ active.id,
+ );
+
+ expect(activeAfter).toMatchObject({ id: active.id, apiKey: "new-key" });
+ expect(stored.find((backend) => backend.id === first.id)).toEqual(first);
+ });
+
+ it("selects the root when the active record is a DigitalOcean entry an older recovery rewrote to the origin", async () => {
+ // Before this screen kept the hosting key on its own record, recovery
+ // overwrote the active guest's host and key but kept its marsSessionId.
+ const rewritten: Backend = {
+ id: "mars-session",
+ name: "My DigitalOcean agent",
+ host: window.location.origin,
+ apiKey: "stale-key",
+ kind: "local",
+ marsSessionId: "test-session",
+ };
+
+ const { stored, activeAfter } = await recoverWith(
+ [rewritten],
+ rewritten.id,
+ );
+
+ expect(activeAfter).toMatchObject({ apiKey: "new-key", kind: "local" });
+ expect(activeAfter?.marsSessionId).toBeUndefined();
+ expect(new URL(activeAfter!.host).origin).toBe(window.location.origin);
+ expect(stored.find((backend) => backend.id === rewritten.id)).toEqual(
+ rewritten,
+ );
+ });
+
// @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(
@@ -279,7 +522,10 @@ describe("ApiKeyEntryScreen", () => {
const stored = JSON.parse(
window.localStorage.getItem(BACKENDS_STORAGE_KEY) ?? "[]",
);
- expect(stored[0].apiKey).toBe("correct-key");
+ expect(
+ stored.find((backend: Backend) => backend.host === window.location.origin)
+ ?.apiKey,
+ ).toBe("correct-key");
});
// @spec — Stale key in localStorage does not contaminate the new key
@@ -305,6 +551,9 @@ describe("ApiKeyEntryScreen", () => {
const stored = JSON.parse(
window.localStorage.getItem(BACKENDS_STORAGE_KEY) ?? "[]",
);
- expect(stored[0].apiKey).toBe("fresh-key-BBBB");
+ expect(
+ stored.find((backend: Backend) => backend.host === window.location.origin)
+ ?.apiKey,
+ ).toBe("fresh-key-BBBB");
});
});
diff --git a/__tests__/root.test.tsx b/__tests__/root.test.tsx
index 342eae61b9..bdf13f5648 100644
--- a/__tests__/root.test.tsx
+++ b/__tests__/root.test.tsx
@@ -494,6 +494,84 @@ describe("App root agent-server availability guard", () => {
expect(screen.queryByTestId("onboarding-modal")).not.toBeInTheDocument();
});
+ it("opens a ready DO session without the local API-key form when the backend carries a marsSessionId", async () => {
+ // A DigitalOcean MARS session is an ordinary `kind: "local"` backend with
+ // an intentionally empty guest key (the session's own agent-server key is
+ // set by the sandbox template, not us). On a page with no baked session
+ // key the auth gate must not treat it as an unkeyed local backend and show
+ // the full-screen local API-key form.
+ vi.stubEnv("VITE_AUTH_REQUIRED", "true");
+ vi.stubEnv("VITE_SESSION_API_KEY", "");
+ delete (window as unknown as Record<string, unknown>)
+ .__AGENT_CANVAS_SESSION_API_KEY__;
+ window.localStorage.clear();
+ window.localStorage.setItem(ONBOARDING_COMPLETED_STORAGE_KEY, "1");
+ window.localStorage.setItem(
+ "openhands-backends",
+ JSON.stringify([
+ {
+ id: "mars-session-1",
+ name: "DO session",
+ host: "http://127.0.0.1:8000",
+ apiKey: "",
+ kind: "local",
+ marsSessionId: "sess_1",
+ marsConfigId: "cfg_1",
+ },
+ ]),
+ );
+ window.localStorage.setItem(
+ "openhands-active-backend",
+ JSON.stringify({ backendId: "mars-session-1", orgId: null }),
+ );
+ __resetActiveStoreForTests();
+
+ renderApp(["/"]);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("app-outlet")).toBeInTheDocument();
+ });
+ expect(
+ screen.queryByTestId("api-key-entry-screen"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("still shows the API-key form for an ordinary keyless local backend", async () => {
+ // The marsSessionId exemption is scoped: an unrelated local backend with
+ // no key on a page with no baked key must still land on the local
+ // API-key form, not silently bypass the auth gate.
+ vi.stubEnv("VITE_AUTH_REQUIRED", "true");
+ vi.stubEnv("VITE_SESSION_API_KEY", "");
+ delete (window as unknown as Record<string, unknown>)
+ .__AGENT_CANVAS_SESSION_API_KEY__;
+ window.localStorage.clear();
+ window.localStorage.setItem(ONBOARDING_COMPLETED_STORAGE_KEY, "1");
+ window.localStorage.setItem(
+ "openhands-backends",
+ JSON.stringify([
+ {
+ id: "plain-local",
+ name: "Local server",
+ host: "http://127.0.0.1:8000",
+ apiKey: "",
+ kind: "local",
+ },
+ ]),
+ );
+ window.localStorage.setItem(
+ "openhands-active-backend",
+ JSON.stringify({ backendId: "plain-local", orgId: null }),
+ );
+ __resetActiveStoreForTests();
+
+ renderApp(["/"]);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("api-key-entry-screen")).toBeInTheDocument();
+ });
+ expect(screen.queryByTestId("app-outlet")).not.toBeInTheDocument();
+ });
+
it("shows the manage-backends modal when the connected server reports an old version", async () => {
window.localStorage.setItem(ONBOARDING_COMPLETED_STORAGE_KEY, "1");
server.use(
diff --git a/src/components/features/backends/api-key-entry-screen.tsx b/src/components/features/backends/api-key-entry-screen.tsx
index b5326023f6..2c55d2b495 100644
--- a/src/components/features/backends/api-key-entry-screen.tsx
+++ b/src/components/features/backends/api-key-entry-screen.tsx
@@ -4,7 +4,8 @@ import { SettingsClient } from "@openhands/typescript-client/clients";
import { I18nKey } from "#/i18n/declaration";
import { isSdkHttpStatusError } from "#/api/agent-server-compatibility";
import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
-import { isNoBackend } from "#/api/backend-registry/active-store";
+import { isServedOriginHost } from "#/api/agent-server-config";
+import type { Backend } from "#/api/backend-registry/types";
import { useActiveBackendContext } from "#/contexts/active-backend-context";
import { BrandButton } from "#/components/features/settings/brand-button";
import {
@@ -18,6 +19,28 @@ import {
type BackendFormSubmitPayload,
} from "./backend-form-modal";
+/**
+ * The record holding the hosting Canvas key: the same served-origin match the
+ * MARS web bridge reads it back with (`getMarsBridgeHeaders`).
+ */
+function isCanvasRoot(backend: Backend): boolean {
+ return (
+ backend.kind === "local" &&
+ !backend.marsSessionId &&
+ isServedOriginHost(backend.host)
+ );
+}
+
+/** A DigitalOcean guest the web build proxies under `/mars/sessions/<id>`. */
+function isLiveMarsGuest(backend: Backend): boolean {
+ if (!backend.marsSessionId) return false;
+ try {
+ return new URL(backend.host).pathname.startsWith("/mars/sessions/");
+ } catch {
+ return false;
+ }
+}
+
/**
* Full-screen prompt shown when the server is in public mode
* (`VITE_AUTH_REQUIRED=true`) and no valid API key has been configured.
@@ -29,9 +52,16 @@ import {
*/
export default function ApiKeyEntryScreen() {
const { t } = useTranslation("openhands");
- const { active, addBackend, updateBackend } = useActiveBackendContext();
+ const { active, backends, addBackend, updateBackend, setActive } =
+ useActiveBackendContext();
const host = window.location.origin;
+ // Prefer the active record when it is a root, so a duplicate earlier in the
+ // list cannot take the key while the selected one stays stale.
+ const rootBackend = isCanvasRoot(active.backend)
+ ? active.backend
+ : backends.find(isCanvasRoot);
+ const keepGuest = isLiveMarsGuest(active.backend);
const [isValidating, setIsValidating] = React.useState(false);
const [connectionStatus, setConnectionStatus] = React.useState<
@@ -56,10 +86,23 @@ export default function ApiKeyEntryScreen() {
setConnectionStatus("success");
- if (isNoBackend(active.backend)) {
- addBackend(payload);
+ // This form authenticates the serving Canvas, so the key goes on the
+ // Canvas root's own record. A live DigitalOcean guest stays selected so
+ // a reload reconnects to the same session; any other backend that
+ // tripped the gate is left as it is and the root is selected, or the
+ // gate would come straight back.
+ // Validation above uses the local Agent Server protocol even when
+ // the Canvas hostname resembles an OpenHands Cloud deployment.
+ const rootPayload = { ...payload, kind: "local" as const };
+ if (rootBackend) {
+ updateBackend(rootBackend.id, rootPayload);
+ if (!keepGuest && rootBackend.id !== active.backend.id) {
+ setActive(rootBackend.id);
+ }
} else {
- updateBackend(active.backend.id, payload);
+ // addBackend selects the new root (BM-001).
+ addBackend(rootPayload);
+ if (keepGuest) setActive(active.backend.id, active.orgId);
}
window.location.reload();
@@ -77,7 +120,7 @@ export default function ApiKeyEntryScreen() {
setIsValidating(false);
}
},
- [active.backend, addBackend, updateBackend, t],
+ [active, rootBackend, keepGuest, addBackend, updateBackend, setActive, t],
);
return (
diff --git a/src/root.tsx b/src/root.tsx
index f26e93ccad..1059fb50b9 100644
--- a/src/root.tsx
+++ b/src/root.tsx
@@ -250,8 +250,18 @@ export default function App() {
// the cloud backend uses its own bearer token. Skip the API-key entry screen
// in that case so Docker/public mode doesn't block cloud-only sessions.
const isActiveCloudBackend = active.backend.kind === "cloud";
+ // A DigitalOcean MARS session is registered as an ordinary `kind: "local"`
+ // backend whose guest key is intentionally empty (the in-guest agent-server
+ // key is set by the sandbox template, not us; the DigitalOcean token is the
+ // authorization boundary). On a page with no baked session key it must not
+ // be mistaken for an unkeyed local backend: the same-origin `/mars/sessions/*`
+ // proxy is authenticated by the bridge cookie, not by a per-backend key.
+ const isActiveMarsSession = Boolean(active.backend.marsSessionId);
const authMissing =
- bakedKeyMissing && !hasRegisteredKey && !isActiveCloudBackend;
+ bakedKeyMissing &&
+ !hasRegisteredKey &&
+ !isActiveCloudBackend &&
+ !isActiveMarsSession;
const restoringMarsTunnel = useRestoreMarsTunnels();
const queryClient = useQueryClient();
// In locked-to-Cloud mode the only valid backend is a Cloud backend whose