Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Persist dev session API key to disk and re-seed default backend (#240)

Robert Brennan5d16a6cbcfd3
diff --git a/__tests__/api/backend-registry/storage.test.ts b/__tests__/api/backend-registry/storage.test.ts
index df9f379baa..b02577eb11 100644
--- a/__tests__/api/backend-registry/storage.test.ts
+++ b/__tests__/api/backend-registry/storage.test.ts
@@ -42,6 +42,39 @@ describe("backend-registry storage", () => {
expect(readStoredBackends()).toEqual([]);
});
+ it("seeds the default Local backend when storage key is missing", () => {
+ expect(window.localStorage.getItem(BACKENDS_STORAGE_KEY)).toBeNull();
+
+ const result = readStoredBackends();
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({ id: "default-local", kind: "local" });
+ // Persists the seed so a subsequent read returns the same entry.
+ expect(window.localStorage.getItem(BACKENDS_STORAGE_KEY)).not.toBeNull();
+ expect(readStoredBackends()).toEqual(result);
+ });
+
+ it("re-seeds the default Local backend when storage holds an empty array", () => {
+ window.localStorage.setItem(BACKENDS_STORAGE_KEY, JSON.stringify([]));
+
+ const result = readStoredBackends();
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({ id: "default-local", kind: "local" });
+ });
+
+ it("re-seeds the default Local backend when every stored entry is invalid", () => {
+ window.localStorage.setItem(
+ BACKENDS_STORAGE_KEY,
+ JSON.stringify([{ kind: "cloud" }, "not-an-object"]),
+ );
+
+ const result = readStoredBackends();
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({ id: "default-local", kind: "local" });
+ });
+
it("filters out backends with invalid shape", () => {
window.localStorage.setItem(
BACKENDS_STORAGE_KEY,
diff --git a/__tests__/scripts/dev-extra-backend.test.ts b/__tests__/scripts/dev-extra-backend.test.ts
index 64853b39ee..fde467706b 100644
--- a/__tests__/scripts/dev-extra-backend.test.ts
+++ b/__tests__/scripts/dev-extra-backend.test.ts
@@ -1,8 +1,13 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
import path from "node:path";
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it } from "vitest";
import { buildExtraBackendConfig } from "../../scripts/dev-extra-backend.mjs";
-import { buildSafeDevConfig } from "../../scripts/dev-safe.mjs";
+import {
+ buildSafeDevConfig,
+ resetPersistedSessionApiKeyCache,
+} from "../../scripts/dev-safe.mjs";
const repoRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
@@ -10,9 +15,26 @@ const repoRoot = path.resolve(
);
describe("buildExtraBackendConfig", () => {
+ const keyDirs: string[] = [];
+
+ afterEach(() => {
+ while (keyDirs.length > 0) {
+ const dir = keyDirs.pop();
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ }
+ resetPersistedSessionApiKeyCache();
+ });
+
+ function isolatedKeyPath(): string {
+ const dir = mkdtempSync(path.join(tmpdir(), "extra-backend-key-"));
+ keyDirs.push(dir);
+ return path.join(dir, "session-api-key.txt");
+ }
+
it("defaults to ports 18002/18003 distinct from the bundled instance", () => {
- const bundled = buildSafeDevConfig(repoRoot, {});
- const extra = buildExtraBackendConfig(repoRoot, {});
+ const env = { OH_SESSION_API_KEY_PATH: isolatedKeyPath() };
+ const bundled = buildSafeDevConfig(repoRoot, env);
+ const extra = buildExtraBackendConfig(repoRoot, env);
expect(extra.backendPort).toBe(18002);
expect(extra.vscodePort).toBe(18003);
@@ -26,6 +48,7 @@ describe("buildExtraBackendConfig", () => {
const config = buildExtraBackendConfig(repoRoot, {
OH_CANVAS_EXTRA_BACKEND_PORT: "29000",
OH_CANVAS_EXTRA_VSCODE_PORT: "29001",
+ OH_SESSION_API_KEY_PATH: isolatedKeyPath(),
});
expect(config.backendPort).toBe(29000);
@@ -34,7 +57,10 @@ describe("buildExtraBackendConfig", () => {
});
it("shares state dir, conversations, bash events, and secret key with the bundled config", () => {
- const env = { OH_CANVAS_SAFE_STATE_DIR: "/tmp/canvas-state" };
+ const env = {
+ OH_CANVAS_SAFE_STATE_DIR: "/tmp/canvas-state",
+ OH_SESSION_API_KEY_PATH: isolatedKeyPath(),
+ };
const bundled = buildSafeDevConfig(repoRoot, env);
const extra = buildExtraBackendConfig(repoRoot, env);
@@ -49,6 +75,7 @@ describe("buildExtraBackendConfig", () => {
expect(() =>
buildExtraBackendConfig(repoRoot, {
OH_CANVAS_EXTRA_BACKEND_PORT: "not-a-port",
+ OH_SESSION_API_KEY_PATH: isolatedKeyPath(),
}),
).toThrow(/Invalid port/);
});
diff --git a/__tests__/scripts/dev-safe.test.ts b/__tests__/scripts/dev-safe.test.ts
index eaa7505191..d5f6c91298 100644
--- a/__tests__/scripts/dev-safe.test.ts
+++ b/__tests__/scripts/dev-safe.test.ts
@@ -16,8 +16,16 @@ import {
validateLocalAgentServerPath,
findFreePort,
findFreePorts,
+ getOrCreatePersistedSessionApiKey,
+ resetPersistedSessionApiKeyCache,
} from "../../scripts/dev-safe.mjs";
-import { mkdtempSync, mkdirSync, rmSync } from "node:fs";
+import {
+ mkdtempSync,
+ mkdirSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
const repoRoot = path.resolve(
@@ -153,16 +161,29 @@ describe("findFreePorts", () => {
describe("buildSafeDevConfigAsync", () => {
const servers: net.Server[] = [];
+ let keyTmp: string | null = null;
afterEach(() => {
for (const server of servers) {
server.close();
}
servers.length = 0;
+ if (keyTmp) {
+ rmSync(keyTmp, { recursive: true, force: true });
+ keyTmp = null;
+ }
+ resetPersistedSessionApiKeyCache();
});
+ function tempKeyPath(): string {
+ keyTmp = mkdtempSync(path.join(tmpdir(), "dev-safe-async-key-"));
+ return path.join(keyTmp, "session-api-key.txt");
+ }
+
it("returns config with dynamically allocated ports", async () => {
- const config = await buildSafeDevConfigAsync(repoRoot, {});
+ const config = await buildSafeDevConfigAsync(repoRoot, {
+ OH_SESSION_API_KEY_PATH: tempKeyPath(),
+ });
expect(typeof config.backendPort).toBe("number");
expect(config.backendPort).toBeGreaterThan(0);
@@ -187,6 +208,7 @@ describe("buildSafeDevConfigAsync", () => {
// Request the busy port via env var
const config = await buildSafeDevConfigAsync(repoRoot, {
OH_CANVAS_SAFE_BACKEND_PORT: busyPort.toString(),
+ OH_SESSION_API_KEY_PATH: tempKeyPath(),
});
// Backend port should NOT be busyPort since it's taken
@@ -390,10 +412,27 @@ describe("validateLocalAgentServerPath", () => {
});
describe("buildSafeDevConfig", () => {
+ let keyTmp: string | null = null;
+
+ afterEach(() => {
+ if (keyTmp) {
+ rmSync(keyTmp, { recursive: true, force: true });
+ keyTmp = null;
+ }
+ resetPersistedSessionApiKeyCache();
+ });
+
+ function tempKeyPath(): string {
+ keyTmp = mkdtempSync(path.join(tmpdir(), "dev-safe-key-"));
+ return path.join(keyTmp, "session-api-key.txt");
+ }
+
it("builds isolated default paths and ports", () => {
const cwd = "/workspace/project/agent-canvas";
- const config = buildSafeDevConfig(cwd, {});
+ const config = buildSafeDevConfig(cwd, {
+ OH_SESSION_API_KEY_PATH: tempKeyPath(),
+ });
expect(config.backendPort).toBe(18000);
expect(config.vscodePort).toBe(18001);
@@ -423,6 +462,7 @@ describe("buildSafeDevConfig", () => {
OH_CANVAS_SAFE_VSCODE_PORT: "19010",
OH_CANVAS_SAFE_STATE_DIR: ".tmp/dev-safe",
VITE_WORKING_DIR: "/workspace/custom-repo",
+ OH_SESSION_API_KEY_PATH: tempKeyPath(),
});
expect(config.backendPort).toBe(19000);
@@ -432,6 +472,105 @@ describe("buildSafeDevConfig", () => {
expect(config.stateDir).toBe(path.resolve(cwd, ".tmp", "dev-safe"));
expect(config.workingDir).toBe("/workspace/custom-repo");
});
+
+ it("falls back to the persisted session key file when no env override is set", () => {
+ const keyPath = tempKeyPath();
+ const config = buildSafeDevConfig("/workspace/project/agent-canvas", {
+ OH_SESSION_API_KEY_PATH: keyPath,
+ });
+
+ // A fresh hex key was generated and persisted.
+ expect(config.sessionApiKey).toMatch(/^[a-f0-9]{64}$/);
+ expect(readFileSync(keyPath, "utf8").trim()).toBe(config.sessionApiKey);
+ });
+
+ it("reuses the same key across config builds, simulating dev:docker / dev:dangerously-dockerless restarts", () => {
+ const keyPath = tempKeyPath();
+
+ const first = buildSafeDevConfig("/workspace/project/agent-canvas", {
+ OH_SESSION_API_KEY_PATH: keyPath,
+ });
+
+ // Simulate a fresh process by clearing the in-memory cache; the file
+ // on disk is what should make the key stable.
+ resetPersistedSessionApiKeyCache();
+
+ const second = buildSafeDevConfig("/workspace/project/agent-canvas", {
+ OH_SESSION_API_KEY_PATH: keyPath,
+ });
+
+ expect(second.sessionApiKey).toBe(first.sessionApiKey);
+ });
+
+ it("env-provided session keys take 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",
+ OH_SESSION_API_KEY_PATH: keyPath,
+ });
+
+ expect(config.sessionApiKey).toBe("env-key-wins");
+ // The file is left untouched.
+ expect(readFileSync(keyPath, "utf8").trim()).toBe("persisted-key-value");
+ });
+});
+
+describe("getOrCreatePersistedSessionApiKey", () => {
+ let dir: string | null = null;
+
+ afterEach(() => {
+ if (dir) {
+ rmSync(dir, { recursive: true, force: true });
+ dir = null;
+ }
+ resetPersistedSessionApiKeyCache();
+ });
+
+ function tempPath(): string {
+ dir = mkdtempSync(path.join(tmpdir(), "session-key-"));
+ return path.join(dir, "nested", "session-api-key.txt");
+ }
+
+ it("creates the file (and parent dirs) with a hex key on first call", () => {
+ const filePath = tempPath();
+ const key = getOrCreatePersistedSessionApiKey(filePath);
+
+ expect(key).toMatch(/^[a-f0-9]{64}$/);
+ expect(readFileSync(filePath, "utf8").trim()).toBe(key);
+ });
+
+ it("returns the existing key on subsequent calls (after cache reset)", () => {
+ const filePath = tempPath();
+ const first = getOrCreatePersistedSessionApiKey(filePath);
+
+ resetPersistedSessionApiKeyCache();
+
+ const second = getOrCreatePersistedSessionApiKey(filePath);
+ expect(second).toBe(first);
+ });
+
+ it("trims surrounding whitespace from the persisted file", () => {
+ const filePath = tempPath();
+ mkdirSync(path.dirname(filePath), { recursive: true });
+ writeFileSync(filePath, " abcdef1234 \n");
+
+ const key = getOrCreatePersistedSessionApiKey(filePath);
+ expect(key).toBe("abcdef1234");
+ });
+
+ it("regenerates and overwrites when the file is empty", () => {
+ const filePath = tempPath();
+ mkdirSync(path.dirname(filePath), { recursive: true });
+ writeFileSync(filePath, " \n");
+
+ const key = getOrCreatePersistedSessionApiKey(filePath);
+ expect(key).toMatch(/^[a-f0-9]{64}$/);
+ expect(readFileSync(filePath, "utf8").trim()).toBe(key);
+ });
});
describe("buildNpmScriptCommand", () => {
diff --git a/__tests__/scripts/dev-with-automation.test.ts b/__tests__/scripts/dev-with-automation.test.ts
index c47d034173..a994ae6a78 100644
--- a/__tests__/scripts/dev-with-automation.test.ts
+++ b/__tests__/scripts/dev-with-automation.test.ts
@@ -1,7 +1,8 @@
import net from "node:net";
import { spawn } from "node:child_process";
import { once } from "node:events";
-import { homedir } from "node:os";
+import { mkdtempSync, rmSync } from "node:fs";
+import { homedir, tmpdir } from "node:os";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";
@@ -15,6 +16,7 @@ import {
DEFAULT_BACKEND_PORT,
DEFAULT_AUTOMATION_PORT,
} from "../../scripts/dev-with-automation.mjs";
+import { resetPersistedSessionApiKeyCache } from "../../scripts/dev-safe.mjs";
const repoRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
@@ -114,16 +116,38 @@ describe("buildAutomationCommand", () => {
describe("buildConfig", () => {
const servers: net.Server[] = [];
+ const keyDirs: string[] = [];
afterEach(() => {
for (const server of servers) {
server.close();
}
servers.length = 0;
- });
+ while (keyDirs.length > 0) {
+ const dir = keyDirs.pop();
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ }
+ resetPersistedSessionApiKeyCache();
+ });
+
+ /**
+ * Build an env that points the persisted session-api-key file at a
+ * fresh temp dir, so tests don't write to the user's real
+ * ~/.openhands/agent-canvas/session-api-key.txt.
+ */
+ function envWithIsolatedKeyPath(
+ extra: Record<string, string> = {},
+ ): Record<string, string> {
+ const dir = mkdtempSync(path.join(tmpdir(), "buildconfig-key-"));
+ keyDirs.push(dir);
+ return {
+ OH_SESSION_API_KEY_PATH: path.join(dir, "session-api-key.txt"),
+ ...extra,
+ };
+ }
it("builds default config with correct ports", async () => {
- const config = await buildConfig({}, {});
+ const config = await buildConfig({}, envWithIsolatedKeyPath());
// Ports should be allocated (either defaults if free, or alternatives)
expect(typeof config.ingressPort).toBe("number");
@@ -149,7 +173,10 @@ describe("buildConfig", () => {
it("respects preferred port from args when available", async () => {
// Use a high port unlikely to be busy
const preferredPort = 19500;
- const config = await buildConfig({ port: preferredPort }, {});
+ const config = await buildConfig(
+ { port: preferredPort },
+ envWithIsolatedKeyPath(),
+ );
expect(config.ingressPort).toBe(preferredPort);
});
@@ -168,7 +195,10 @@ describe("buildConfig", () => {
});
// Request the busy port
- const config = await buildConfig({ port: busyPort }, {});
+ const config = await buildConfig(
+ { port: busyPort },
+ envWithIsolatedKeyPath(),
+ );
// Should get a different port since busyPort is taken
expect(config.ingressPort).not.toBe(busyPort);
@@ -176,7 +206,7 @@ describe("buildConfig", () => {
});
it("allocates valid ports for all services", async () => {
- const config = await buildConfig({}, {});
+ const config = await buildConfig({}, envWithIsolatedKeyPath());
// All service ports should be valid
expect(config.agentServerPort).toBeGreaterThan(0);
@@ -197,34 +227,40 @@ describe("buildConfig", () => {
it("respects preferred PORT from env when available", async () => {
// Use a high port unlikely to be busy
const preferredPort = "19501";
- const config = await buildConfig({}, { PORT: preferredPort });
+ const config = await buildConfig(
+ {},
+ envWithIsolatedKeyPath({ PORT: preferredPort }),
+ );
expect(config.ingressPort).toBe(19501);
});
it("args.port takes precedence over env.PORT", async () => {
// Use high ports unlikely to be busy
- const config = await buildConfig({ port: 19502 }, { PORT: "19599" });
+ const config = await buildConfig(
+ { port: 19502 },
+ envWithIsolatedKeyPath({ PORT: "19599" }),
+ );
expect(config.ingressPort).toBe(19502);
});
it("applies automationGitRef from args to env", async () => {
- const env: Record<string, string> = {};
+ const env = envWithIsolatedKeyPath();
await buildConfig({ automationGitRef: "my-branch" }, env);
expect(env.OH_AUTOMATION_GIT_REF).toBe("my-branch");
});
it("applies automationRepo from args to env", async () => {
- const env: Record<string, string> = {};
+ const env = envWithIsolatedKeyPath();
await buildConfig({ automationRepo: "https://example.com/repo" }, env);
expect(env.OH_AUTOMATION_REPO).toBe("https://example.com/repo");
});
it("uses correct state directory path", async () => {
- const config = await buildConfig({}, {});
+ const config = await buildConfig({}, envWithIsolatedKeyPath());
expect(config.stateDir).toBe(
path.join(homedir(), ".openhands", "agent-canvas"),
@@ -232,31 +268,48 @@ describe("buildConfig", () => {
});
it("passes verbose flag through", async () => {
- const config = await buildConfig({ verbose: true }, {});
+ const config = await buildConfig({ verbose: true }, envWithIsolatedKeyPath());
expect(config.verbose).toBe(true);
});
it("auto-generates random local API key by default", async () => {
- const config = await buildConfig({}, {});
+ const config = await buildConfig({}, envWithIsolatedKeyPath());
// Default is a 64-char hex string (256-bit random key)
expect(config.localApiKey).toMatch(/^[0-9a-f]{64}$/);
});
it("respects custom AUTOMATION_LOCAL_API_KEY from env", async () => {
- const config = await buildConfig({}, { AUTOMATION_LOCAL_API_KEY: "my-custom-key" });
+ const config = await buildConfig(
+ {},
+ envWithIsolatedKeyPath({ AUTOMATION_LOCAL_API_KEY: "my-custom-key" }),
+ );
expect(config.localApiKey).toBe("my-custom-key");
});
- it("auto-generates random session API key by default", async () => {
- const config = await buildConfig({}, {});
+ it("falls back to a freshly persisted session API key by default", async () => {
+ const config = await buildConfig({}, envWithIsolatedKeyPath());
- // Default is a 64-char hex string (256-bit random key)
+ // Default is a 64-char hex string (256-bit random key) read from /
+ // written to OH_SESSION_API_KEY_PATH.
expect(config.sessionApiKey).toMatch(/^[0-9a-f]{64}$/);
});
+ it("reuses the persisted session API key across calls (parity for dev:docker and dev:dangerously-dockerless restarts)", async () => {
+ const env = envWithIsolatedKeyPath();
+ const first = await buildConfig({}, env);
+
+ // Simulate a fresh process invocation (the file on disk should be
+ // what makes the key stable).
+ resetPersistedSessionApiKeyCache();
+
+ const second = await buildConfig({}, env);
+
+ expect(second.sessionApiKey).toBe(first.sessionApiKey);
+ });
+
it("reads sessionApiKey from SESSION_API_KEY", async () => {
const config = await buildConfig({}, { SESSION_API_KEY: "my-session-key" });
diff --git a/scripts/dev-safe.mjs b/scripts/dev-safe.mjs
index e91600a6b0..a1fe2337d9 100644
--- a/scripts/dev-safe.mjs
+++ b/scripts/dev-safe.mjs
@@ -4,8 +4,10 @@ import {
existsSync,
mkdirSync,
readdirSync,
+ readFileSync,
statSync,
unlinkSync,
+ writeFileSync,
} from "node:fs";
import net from "node:net";
import { homedir } from "node:os";
@@ -40,10 +42,81 @@ export function generateRandomApiKey() {
return randomBytes(32).toString("hex");
}
-// Auto-generate a random session API key for this dev session.
-// This ensures the agent-server API is authenticated even in local dev.
-// Set SESSION_API_KEY env var to use a consistent key across restarts.
-const DEFAULT_SESSION_API_KEY = generateRandomApiKey();
+// Where the auto-generated default session API key is persisted so it stays
+// stable across `npm run dev` / `npm run dev:dangerously-dockerless` /
+// `npm run dev:docker` 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(
+ homedir(),
+ ".openhands",
+ "agent-canvas",
+ "session-api-key.txt",
+);
+
+// Cache so repeated lookups within a single process return the same key,
+// keyed by file path so tests can use temp paths in isolation.
+const persistedSessionApiKeyCache = new Map();
+
+/**
+ * Load the persisted default session 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.
+ */
+export function getOrCreatePersistedSessionApiKey(
+ filePath = DEFAULT_SESSION_API_KEY_PATH,
+) {
+ const cached = persistedSessionApiKeyCache.get(filePath);
+ if (cached) return cached;
+
+ // Try to read an existing key.
+ try {
+ const existing = readFileSync(filePath, "utf8").trim();
+ if (existing) {
+ persistedSessionApiKeyCache.set(filePath, existing);
+ return existing;
+ }
+ // File exists but is empty -- treat as if missing and regenerate.
+ } catch (error) {
+ if (!isEnoentError(error)) {
+ console.warn(
+ `Could not read persisted session API key from ${filePath}: ${error.message}. Regenerating.`,
+ );
+ }
+ }
+
+ // Generate and persist a new key.
+ const newKey = generateRandomApiKey();
+ try {
+ mkdirSync(path.dirname(filePath), { recursive: true });
+ writeFileSync(filePath, `${newKey}\n`, { mode: 0o600 });
+ } catch (error) {
+ console.warn(
+ `Could not persist session API key to ${filePath}: ${error.message}. Falling back to in-memory key (will not survive restarts).`,
+ );
+ }
+ persistedSessionApiKeyCache.set(filePath, newKey);
+ return newKey;
+}
+
+/**
+ * Clear the in-memory cache used by {@link getOrCreatePersistedSessionApiKey}.
+ * Intended for tests that swap the persisted file path between cases.
+ */
+export function resetPersistedSessionApiKeyCache() {
+ persistedSessionApiKeyCache.clear();
+}
function isEnoentError(error) {
return Boolean(
@@ -400,16 +473,24 @@ function buildConfigFromPorts(ports, cwd, env) {
const workspacesPath = path.join(stateDir, "workspaces");
// Use provided secret key or default for local development
const secretKey = env.OH_SECRET_KEY || DEFAULT_SECRET_KEY;
- // Use provided session API key or auto-generated random key for this session
+ // 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
+ // `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
+ // 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 sessionApiKey =
env.SESSION_API_KEY ||
env.OH_SESSION_API_KEYS_0 ||
env.VITE_SESSION_API_KEY ||
- DEFAULT_SESSION_API_KEY;
+ getOrCreatePersistedSessionApiKey(persistedKeyPath);
return {
cwd,
@@ -565,7 +646,9 @@ async function main() {
process.env.OH_SESSION_API_KEYS_0 ||
process.env.VITE_SESSION_API_KEY
? "custom (from env)"
- : "auto-generated (random)";
+ : `persisted (${
+ process.env.OH_SESSION_API_KEY_PATH || DEFAULT_SESSION_API_KEY_PATH
+ })`;
console.log(`- agent-server: ${agentServerCmd.source}`);
console.log(`- backend: ${config.backendBaseUrl}`);
diff --git a/src/api/backend-registry/storage.ts b/src/api/backend-registry/storage.ts
index 473becbc9b..9a1231cdeb 100644
--- a/src/api/backend-registry/storage.ts
+++ b/src/api/backend-registry/storage.ts
@@ -38,9 +38,7 @@ export function readStoredBackends(): Backend[] {
// First install: the storage key has never been written. Seed the
// registry with one default local backend derived from the env /
// agent-server-config so the user has something to talk to out of
- // the box. Persist the seed immediately so a subsequent removal
- // doesn't get re-seeded β€” only a missing key triggers seeding,
- // not an empty array.
+ // the box.
if (raw === null) {
const seeded = [makeDefaultLocalBackend()];
writeStoredBackends(seeded);
@@ -49,7 +47,21 @@ export function readStoredBackends(): Backend[] {
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
- return parsed.filter(isValidBackend);
+ const valid = parsed.filter(isValidBackend);
+
+ // If the stored array is empty (or everything in it failed validation),
+ // re-seed with the default Local backend so the user always has a
+ // working entry pointing at VITE_SESSION_API_KEY. With the dev scripts
+ // persisting that key to ~/.openhands/agent-canvas/session-api-key.txt,
+ // re-seeding is safe β€” the seeded entry will keep working across
+ // restarts instead of going stale.
+ if (valid.length === 0) {
+ const seeded = [makeDefaultLocalBackend()];
+ writeStoredBackends(seeded);
+ return seeded;
+ }
+
+ return valid;
} catch {
return [];
}