π OpenHands: AI-Driven Development
fix(static-server): expose runtime session key via window global (#1091)
chuckbutkus578589af7fce
diff --git a/AGENTS.md b/AGENTS.mdindex 05462fd0ea..01fdcd44e5 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -180,7 +180,7 @@ you are running inside of β NOT the automation backend.## Additional Notes-- **Published binary auth fix**: When users install the npm package globally (`npm install -g @openhands/agent-canvas`) and run `agent-canvas`, the pre-built static frontend has a `VITE_SESSION_API_KEY` baked in at publish time that differs from the user's persisted runtime key (`~/.openhands/agent-canvas/session-api-key.txt`). The fix is to inject the runtime session key into `index.html` responses at serve time (not build time). `scripts/static-server.mjs` accepts a `--session-api-key <key>` flag and injects a tiny inline `<script>` before `</head>` that seeds the key into `localStorage['openhands-agent-server-config'].sessionApiKey` β only if no key is already stored (preserving user-set overrides). `scripts/dev-with-automation.mjs` and `scripts/dev-static.mjs` both pass `--session-api-key ${config.sessionApiKey}` when starting the static server.+- **Published binary auth fix**: When users install the npm package globally (`npm install -g @openhands/agent-canvas`) and run `agent-canvas`, the pre-built static frontend has NO `VITE_SESSION_API_KEY` baked in (npm publish runs `npm run build` with no such env var). The runtime session key is generated when the CLI launches and reaches the frontend via `scripts/static-server.mjs --session-api-key <key>`, which injects a `<head>` script that does two things: (a) sets `window.__AGENT_CANVAS_SESSION_API_KEY__ = <key>` β read by `getBakedSessionApiKey()` in `src/api/agent-server-config.ts` as a fallback when the env var is empty, symmetric with `__AGENT_CANVAS_AUTH_REQUIRED__` / `isAuthRequired()`; (b) writes the same key into `localStorage['openhands-agent-server-config'].sessionApiKey`, always overwriting when the value differs, so any code path that still reads the legacy storage key (e.g. e2e fixtures) sees the live key. The window-global path is the load-bearing one β without it, `makeDefaultLocalBackend()` returns null on a fresh install, the backend registry seeds empty, and `root.tsx` traps the user behind the Manage Backends modal instead of onboarding. `scripts/dev-with-automation.mjs` and `scripts/dev-static.mjs` both pass `--session-api-key ${config.sessionApiKey}` when starting the static server.- Direct `dependencies` and `devDependencies` in `package.json` are exact-pinned (no caret ranges); reproducible installs should use the committed `package-lock.json` plus `npm ci`, and targeted transitive fixes still belong in `overrides`.- `package-lock.json` must also retain the optional peer entry for `node_modules/vite-tsconfig-paths/node_modules/[email protected]`; without that nested lock entry, clean `npm ci` installs on CI fail with `Missing: [email protected] from lock file`.@@ -427,7 +427,7 @@ When adding code that needs a new string, decide up front which rule it falls un- 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`.+ - **Key rotation resilience (non-public):** Stale registry entries are reconciled in two places. (1) `syncLauncherDefaultLocalBackend()` in `src/api/backend-registry/storage.ts` re-runs at module init: for any stored backend whose id is `default-local` and whose host matches (or is loopback-equivalent to) the launcher's default, its `apiKey` is overwritten with the current `makeDefaultLocalBackend().apiKey` (sourced from `VITE_SESSION_API_KEY` or, in the published-binary path, `window.__AGENT_CANVAS_SESSION_API_KEY__`). (2) `scripts/static-server.mjs`'s injection script always overwrites `localStorage['openhands-agent-server-config'].sessionApiKey` when it differs from the runtime key, keeping any code that still reads that legacy storage in sync. E2E coverage: `tests/e2e/mock-llm/mock-llm-auth-modes.spec.ts` (fresh-install, key-rotation, and public-mode scenarios).- 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-config.test.ts b/__tests__/api/agent-server-config.test.tsindex c85ef43b2e..c895261446 100644--- a/__tests__/api/agent-server-config.test.ts+++ b/__tests__/api/agent-server-config.test.ts@@ -23,6 +23,8 @@ function mockWindowLocation(url: string) {afterEach(() => {window.localStorage.clear();vi.unstubAllEnvs();+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__;Object.defineProperty(window, "location", {configurable: true,value: ORIGINAL_LOCATION,@@ -161,3 +163,59 @@ describe("isAuthRequiredAndMissing", () => {expect(isAuthRequiredAndMissing()).toBe(false);});});++// Covers the published `agent-canvas` binary path: the prebuilt bundle has+// no VITE_SESSION_API_KEY baked in, but `scripts/static-server.mjs` injects+// the runtime key into `window.__AGENT_CANVAS_SESSION_API_KEY__`. Without+// this fallback, `makeDefaultLocalBackend()` returns null on a fresh install+// and the user sees the Manage Backends modal instead of the onboarding flow.+describe("getAgentServerSessionApiKey runtime-injection fallback", () => {+ function setInjectedKey(value: unknown) {+ (+ window as unknown as Record<string, unknown>+ ).__AGENT_CANVAS_SESSION_API_KEY__ = value;+ }++ it("returns the env-baked key when VITE_SESSION_API_KEY is set", () => {+ vi.stubEnv("VITE_SESSION_API_KEY", "env-key");+ setInjectedKey("window-key");++ expect(getAgentServerSessionApiKey()).toBe("env-key");+ });++ it("falls back to the runtime-injected window global when no env key is baked in", () => {+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ setInjectedKey("runtime-injected-key");++ expect(getAgentServerSessionApiKey()).toBe("runtime-injected-key");+ });++ it("includes the injected key in form defaults so the registry can seed", () => {+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ setInjectedKey("runtime-injected-key");++ expect(getAgentServerFormDefaults().sessionApiKey).toBe(+ "runtime-injected-key",+ );+ });++ it("returns null when neither env nor window provides a key", () => {+ vi.stubEnv("VITE_SESSION_API_KEY", "");++ expect(getAgentServerSessionApiKey()).toBeNull();+ });++ it("treats a whitespace-only injected key as missing", () => {+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ setInjectedKey(" ");++ expect(getAgentServerSessionApiKey()).toBeNull();+ });++ it("ignores non-string injected values", () => {+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ setInjectedKey(12345);++ expect(getAgentServerSessionApiKey()).toBeNull();+ });+});diff --git a/__tests__/scripts/static-server.test.ts b/__tests__/scripts/static-server.test.tsindex 324177b096..c24298ddbc 100644--- a/__tests__/scripts/static-server.test.ts+++ b/__tests__/scripts/static-server.test.ts@@ -97,6 +97,36 @@ describe("static-server.mjs", () => {expect(body).toContain("sessionApiKey");});+ // Regression test: the published `agent-canvas` binary builds without+ // VITE_SESSION_API_KEY baked in, so the React app reads the key from+ // `window.__AGENT_CANVAS_SESSION_API_KEY__` (see+ // `getBakedSessionApiKey()` in `src/api/agent-server-config.ts`).+ // Without this assignment, `makeDefaultLocalBackend()` returns null+ // on a fresh install and the user gets the Manage Backends modal+ // instead of onboarding.+ it("exposes the session key on window.__AGENT_CANVAS_SESSION_API_KEY__", async () => {+ const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));+ tempDirs.push(buildDir);+ writeFileSync(+ path.join(buildDir, "index.html"),+ "<html><head></head><body>app</body></html>",+ );++ const origin = await startServerWithKey(buildDir, "runtime-key");+ const response = await fetch(`${origin}/`);+ const body = await response.text();++ expect(body).toContain("window.__AGENT_CANVAS_SESSION_API_KEY__");+ expect(body).toContain('"runtime-key"');+ // The window assignment must precede the localStorage write so the+ // global is set even if storage access throws (private mode, etc.).+ const windowIdx = body.indexOf("__AGENT_CANVAS_SESSION_API_KEY__");+ const localStorageIdx = body.indexOf("openhands-agent-server-config");+ expect(windowIdx).toBeGreaterThan(-1);+ expect(localStorageIdx).toBeGreaterThan(-1);+ expect(windowIdx).toBeLessThan(localStorageIdx);+ });+it("injects session key into SPA fallback index.html", async () => {const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));tempDirs.push(buildDir);@@ -171,6 +201,7 @@ describe("static-server.mjs", () => {const response = await fetch(`${origin}/`);const body = await response.text();expect(body).not.toContain("openhands-agent-server-config");+ expect(body).not.toContain("__AGENT_CANVAS_SESSION_API_KEY__");});it("injects session key into HTML without </head> tag (falls back to </body>)", async () => {diff --git a/scripts/static-server.mjs b/scripts/static-server.mjsindex 556326f808..89335a766e 100644--- a/scripts/static-server.mjs+++ b/scripts/static-server.mjs@@ -192,9 +192,18 @@ ROUTING:/*** 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.+ * - `sessionApiKey`: exposed to the app two ways so a fresh-localStorage+ * browser can authenticate even though the published bundle has no+ * VITE_SESSION_API_KEY baked in:+ * 1. `window.__AGENT_CANVAS_SESSION_API_KEY__` β read by+ * `getBakedSessionApiKey()` in `agent-server-config.ts` as a fallback+ * when the env var is empty. This is symmetric with how+ * `__AGENT_CANVAS_AUTH_REQUIRED__` works for the auth-required flag.+ * 2. Written to `openhands-agent-server-config.sessionApiKey` in+ * localStorage for compatibility with the legacy storage key. Useful+ * for any code path that still reads it (e.g. e2e test fixtures).+ * Always overwrites when the stored value differs so a rotated key+ * is not shadowed by a stale one.** - `authRequired`: sets `window.__AGENT_CANVAS_AUTH_REQUIRED__ = true` so the* pre-built frontend shows the API key entry screen (public mode) without@@ -205,6 +214,9 @@ function makeConfigInjectionScript(sessionApiKey, authRequired) {if (sessionApiKey) {const keyLiteral = JSON.stringify(sessionApiKey);+ // Window global β read at module init by getBakedSessionApiKey().+ // Set first so it's available even if the localStorage write throws.+ parts.push(`window.__AGENT_CANVAS_SESSION_API_KEY__=${keyLiteral};`);// 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.diff --git a/src/api/agent-server-config.ts b/src/api/agent-server-config.tsindex 816d2f3c64..06c33d8216 100644--- a/src/api/agent-server-config.ts+++ b/src/api/agent-server-config.ts@@ -30,8 +30,36 @@ function getConfiguredBaseUrl(): string | null {return normalizeBaseUrl(import.meta.env.VITE_BACKEND_BASE_URL);}+/**+ * Return the session API key supplied by the deployment host.+ *+ * Two sources are consulted, in order:+ * 1. `VITE_SESSION_API_KEY` β baked into the bundle at build time (used by+ * `npm run dev` so the dev server has the key without a round-trip).+ * 2. `window.__AGENT_CANVAS_SESSION_API_KEY__` β injected into `index.html`+ * at serve time by `scripts/static-server.mjs --session-api-key <key>`.+ * This is the path used by the published `agent-canvas` binary, where+ * `VITE_SESSION_API_KEY` is empty in the prebuilt bundle and the+ * runtime key is generated when the user launches the CLI.+ *+ * Without the window-global fallback, the published binary cannot construct a+ * default local backend (`makeDefaultLocalBackend()` returns null), the+ * registry is left empty, and the user sees the Manage Backends modal+ * instead of the onboarding flow.+ */export function getBakedSessionApiKey(): string | null {- return trimToNull(import.meta.env.VITE_SESSION_API_KEY);+ const envKey = trimToNull(import.meta.env.VITE_SESSION_API_KEY);+ if (envKey) return envKey;++ if (typeof window !== "undefined") {+ const injected = (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__;+ if (typeof injected === "string") {+ return trimToNull(injected);+ }+ }++ return null;}export function getAgentServerFormDefaults(): AgentServerFormDefaults {diff --git a/tests/e2e/mock-llm/mock-llm-auth-modes.spec.ts b/tests/e2e/mock-llm/mock-llm-auth-modes.spec.tsindex eda09ab310..a1eed79d98 100644--- a/tests/e2e/mock-llm/mock-llm-auth-modes.spec.ts+++ b/tests/e2e/mock-llm/mock-llm-auth-modes.spec.ts@@ -1,13 +1,20 @@/*** Mock-LLM E2E tests for authentication modes.*- * Tests two scenarios using the same backend (agent-server) started by the- * main mock-LLM stack:+ * Tests three scenarios using the same backend (agent-server) started by+ * the main mock-LLM stack:+ *+ * 0. **Fresh install with runtime-injected key:** No pre-seeded+ * localStorage β the static-server's `<head>` injection must be the+ * only mechanism that gets the runtime session key into the app.+ * Verifies the user reaches the onboarding modal, not the Manage+ * Backends "trap" modal that v1.0.0-beta.7 showed.** 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.+ * Verifies that `syncLauncherDefaultLocalBackend()` and the+ * static-server's localStorage overwrite clear 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@@ -16,7 +23,7 @@* - Submitting the correct key lets the app through.* - Submitting a wrong key shows an inline error.*- * @spec BM-002 β Key rotation recovery via syncBakedSessionApiKey+ * @spec BM-002 β Key rotation recovery via syncLauncherDefaultLocalBackend*/import { test, expect } from "@playwright/test";@@ -32,6 +39,66 @@ import {test.describe.configure({ mode: "serial" });+// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+// 0. Fresh-install path (the published `agent-canvas` binary case)+// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++test.describe("auth mode: fresh install with runtime-injected key", () => {+ // Regression for the bug a user hit on v1.0.0-beta.7:+ //+ // `npm install -g @openhands/agent-canvas && agent-canvas`+ //+ // landed on the Manage Backends modal ("No extra backends added yet.")+ // with no way out, because the prebuilt bundle has no+ // VITE_SESSION_API_KEY baked in. The runtime key reaches the bundle via+ // `window.__AGENT_CANVAS_SESSION_API_KEY__` injected by+ // `scripts/static-server.mjs`; without that fallback the backend+ // registry seeds empty and `MissingAgentServerScreen` traps the user.+ test("reaches the onboarding modal without pre-seeded localStorage", async ({+ page,+ request,+ }) => {+ // No `addInitScript` here on purpose: we want a fresh browser context+ // that exactly mirrors the first-launch user experience.++ // Skip the analytics consent modal so it doesn't sit on top of the+ // onboarding modal in CI screenshots/timeouts.+ await page.addInitScript(() => {+ window.localStorage.setItem("analytics-consent", "false");+ window.localStorage.setItem("openhands-telemetry-consent", "denied");+ });++ await routeSessionApiKey(page);+ await page.goto("/", { waitUntil: "domcontentloaded" });++ // The static-server injected the runtime key into+ // `window.__AGENT_CANVAS_SESSION_API_KEY__`; the React app reads it,+ // seeds the default-local backend, and lands on the home page where+ // OnboardingHost mounts the first onboarding step.+ await waitForTestId(page, "onboarding-step-choose-agent");++ // The Manage Backends "trap" modal must NOT be the screen the user+ // sees on first launch.+ await expect(+ page.getByTestId("agent-server-onboarding-screen"),+ ).not.toBeVisible({ timeout: 1_000 });++ // Sanity check: the backend is actually reachable with the runtime key.+ const settingsResp = await request.get(`${BACKEND_URL}/api/settings`, {+ headers: { "X-Session-API-Key": SESSION_API_KEY },+ });+ expect(settingsResp.ok()).toBe(true);++ // Sanity check: the runtime key landed on the window global.+ const injected = await page.evaluate(+ () =>+ (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__,+ );+ expect(injected).toBe(SESSION_API_KEY);+ });+});+// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ// 1. Key rotation (non-public mode)// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -81,9 +148,11 @@ test.describe("auth mode: non-public key rotation", () => {{ 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.+ // The runtime session key (injected by static-server) should be the+ // CORRECT key. `syncLauncherDefaultLocalBackend()` overwrites the+ // stale apiKey on the registry's default-local entry on boot, and the+ // static-server's localStorage write overwrites the legacy stored+ // sessionApiKey so the next read produces the live key.await routeSessionApiKey(page);await page.goto("/", { waitUntil: "domcontentloaded" });await dismissAnalyticsModal(page);diff --git a/tests/e2e/mock-llm/utils/mock-llm-helpers.ts b/tests/e2e/mock-llm/utils/mock-llm-helpers.tsindex 5e35fee283..28073137f6 100644--- a/tests/e2e/mock-llm/utils/mock-llm-helpers.ts+++ b/tests/e2e/mock-llm/utils/mock-llm-helpers.ts@@ -43,10 +43,20 @@ export const SESSION_API_KEY = (() => {})();/** Seed localStorage with flags that skip onboarding / analytics modals- * and a default local backend so the app doesn't show the manage-backends- * modal. The backend registry must be seeded because the static build has- * no baked VITE_SESSION_API_KEY β makeDefaultLocalBackend() returns null- * and readLegacyBackend() can't infer a host from the injected config. */+ * and a default local backend so the app boots straight into the home+ * page. The backend registry is seeded explicitly for two reasons:+ *+ * 1. It guarantees a deterministic backend entry across tests even+ * when key rotation or stale-state scenarios are exercised.+ * 2. It avoids depending on the runtime injection ordering between+ * `page.addInitScript` and the static-server's `<head>` script.+ *+ * As of the published-binary session-key fix, the static-server also+ * exposes the runtime key via `window.__AGENT_CANVAS_SESSION_API_KEY__`,+ * which `getBakedSessionApiKey()` reads β so a real user with an empty+ * localStorage no longer needs this seeding to reach onboarding. See+ * `auth mode: fresh install with runtime-injected key` in+ * `mock-llm-auth-modes.spec.ts` for the test that covers that path. */export async function seedLocalStorage(page: Page) {await page.addInitScript(({ apiKey }) => {