π OpenHands: AI-Driven Development
Replace bundled backend with seeded default local backend (#235)
Robert Brennan7509bbbe7146
diff --git a/AGENTS.md b/AGENTS.mdindex 3eefc7c7fc..518c8a50c0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -49,6 +49,9 @@- runtime git panels: `/api/git/changes`, `/api/git/diff`- Static mock verification needs a build created with `VITE_MOCK_API=true` (use `npm run build:mock`); the client must start MSW whenever that flag is enabled, even in production/static builds, otherwise routes like `/settings` and the conversations pane fall through to the static server and crash on undefined `.filter`/`.map` assumptions.- No frontend version guard: `OptionService.getConfig()` calls `loadAgentServerInfo()` which fetches `/server_info` only to (a) detect an unreachable agent server (renders the onboarding screen via `AgentServerUnavailableError`) and (b) cache `usable_tools` for tool gating. All advertised versions are accepted. The "manage backends" modal displays each local backend's `/server_info.version` in light text via the `BACKEND$VERSION_LABEL` translation key.+- Backend registry: there is no longer a separate "bundled" backend. On first read of the `openhands-backends` localStorage key (`raw === null`), `readStoredBackends()` seeds the registry with one default local backend (`makeDefaultLocalBackend()`, id `BUNDLED_BACKEND_ID = "default-local"`, host/api-key from `agent-server-config`). After that the seed is just an ordinary registered backend β users can rename or remove it like any other. `getEffectiveLocalBackend()` returns the first registered local, falling back to a synthesized default if the registry has no locals (used by API clients that need a baseline `local` target). The "Manage backends" modal and the BackendSelector dropdown both read from the single registered list, so the seeded default appears in both without any special-casing.+- Shared `Dropdown` open behavior: when the menu opens, it clears the input/search text so callers can show the current selection via `placeholder` while still rendering the full option list. Generic dropdown tests should not expect the selected label to remain in the input after reopening unless the parent explicitly controls that display.+- `/server_info` tool capability metadata from `software-agent-sdk` PR #3028 ended up shipping as `usable_tools` (not `available_tools`). Frontend browser-tool gating should key off `usable_tools`, and still default to allowing tools when the server does not advertise tool metadata.- Useful regression tests for mock mode live in `__tests__/api/option-service.test.ts`, `__tests__/api/mock-conversation-handlers.test.ts`, and `__tests__/api/mock-settings-handlers.test.ts`.diff --git a/__tests__/api/backend-registry/active-store.test.ts b/__tests__/api/backend-registry/active-store.test.tsindex 41df68c1ba..3ca0c251a8 100644--- a/__tests__/api/backend-registry/active-store.test.ts+++ b/__tests__/api/backend-registry/active-store.test.ts@@ -6,7 +6,7 @@ import {setRegisteredBackends,subscribeActiveBackend,} from "#/api/backend-registry/active-store";-import { BUNDLED_BACKEND_ID } from "#/api/backend-registry/types";+import { DEFAULT_LOCAL_BACKEND_ID } from "#/api/backend-registry/default-backend";import type { Backend } from "#/api/backend-registry/types";beforeEach(() => {@@ -28,10 +28,18 @@ const cloudBackend: Backend = {kind: "cloud",};+const localBackend: Backend = {+ id: "local-1",+ name: "Local 1",+ host: "http://localhost:9000",+ apiKey: "k",+ kind: "local",+};+describe("active-store", () => {- it("falls back to the bundled backend when nothing is selected", () => {+ it("seeds the registry with a default local backend on first read and uses it as the active backend", () => {const { backend, orgId } = getActiveBackend();- expect(backend.id).toBe(BUNDLED_BACKEND_ID);+ expect(backend.id).toBe(DEFAULT_LOCAL_BACKEND_ID);expect(backend.kind).toBe("local");expect(orgId).toBeNull();});@@ -45,12 +53,22 @@ describe("active-store", () => {expect(orgId).toBe("org-2");});- it("falls back to bundled when the active backend was removed", () => {- setRegisteredBackends([cloudBackend]);+ it("falls back to the first local backend when the active selection points at a removed entry", () => {+ setRegisteredBackends([cloudBackend, localBackend]);setActiveSelection({ backendId: cloudBackend.id, orgId: null });- setRegisteredBackends([]);+ setRegisteredBackends([localBackend]);++ expect(getActiveBackend().backend).toEqual(localBackend);+ expect(getActiveBackend().orgId).toBeNull();+ });- expect(getActiveBackend().backend.id).toBe(BUNDLED_BACKEND_ID);+ it("falls back to a synthetic env-derived backend when the registry has no local entry", () => {+ setRegisteredBackends([cloudBackend]);+ setActiveSelection(null);++ const { backend } = getActiveBackend();+ expect(backend.kind).toBe("local");+ expect(backend.id).toBe(DEFAULT_LOCAL_BACKEND_ID);});it("notifies subscribers when selection changes", () => {diff --git a/__tests__/components/backends/add-backend-modal.test.tsx b/__tests__/components/backends/add-backend-modal.test.tsxindex 19e3c73001..f2690f29bd 100644--- a/__tests__/components/backends/add-backend-modal.test.tsx+++ b/__tests__/components/backends/add-backend-modal.test.tsx@@ -104,14 +104,17 @@ describe("AddBackendModal", () => {const stored = JSON.parse(window.localStorage.getItem("openhands-backends") ?? "[]",);- expect(stored).toMatchObject([- {- name: "Local Extra",- host: "http://127.0.0.1:18002",- apiKey: "",- kind: "local",- },- ]);+ // The seeded default ("Local") is in the list alongside the new+ // entry. Find the user-added one to assert its shape.+ const added = stored.find(+ (b: { name: string }) => b.name === "Local Extra",+ );+ expect(added).toMatchObject({+ name: "Local Extra",+ host: "http://127.0.0.1:18002",+ apiKey: "",+ kind: "local",+ });});it("keeps submit disabled for cloud backends until an API key is entered", async () => {@@ -153,8 +156,11 @@ describe("AddBackendModal", () => {const stored = JSON.parse(window.localStorage.getItem("openhands-backends") ?? "[]",);- expect(stored).toHaveLength(1);- expect(stored[0]).toMatchObject({+ // The seeded default ("Local") is in the list alongside the new+ // entry. Find the user-added one to assert its shape.+ expect(stored).toHaveLength(2);+ const added = stored.find((b: { name: string }) => b.name === "Local 1");+ expect(added).toMatchObject({name: "Local 1",host: "http://localhost:9000",apiKey: "k",diff --git a/__tests__/components/backends/backend-selector.test.tsx b/__tests__/components/backends/backend-selector.test.tsxindex 38a77f5861..2f63870a97 100644--- a/__tests__/components/backends/backend-selector.test.tsx+++ b/__tests__/components/backends/backend-selector.test.tsx@@ -105,11 +105,11 @@ afterEach(() => {});describe("BackendSelector", () => {- it("uses the bundled Local label by default", () => {+ it("shows the seeded default Local backend's name by default", () => {renderWithProviders(<BackendSelector />);const wrapper = screen.getByTestId("backend-selector");const input = wrapper.querySelector("input") as HTMLInputElement;- expect(input.value).toBe("BACKEND$LOCAL_ROW");+ expect(input.value).toBe("Local");});it("lists all registered backends in the dropdown", async () => {@@ -136,7 +136,9 @@ describe("BackendSelector", () => {await openDropdown();- expect(screen.getByText("BACKEND$LOCAL_ROW")).toBeInTheDocument();+ // The seeded default ("Local") is rendered as a normal row alongside+ // the user-added backends.+ expect(screen.getByText("Local")).toBeInTheDocument();expect(screen.getByText("Local 1")).toBeInTheDocument();expect(screen.getByText("Production")).toBeInTheDocument();});@@ -560,7 +562,7 @@ describe("BackendSelector", () => {consoleErrorSpy.mockRestore();});- it("falls back to the bundled backend when malformed cloud self-heal fails", async () => {+ it("falls back to the first registered local backend when malformed cloud self-heal fails", async () => {vi.mocked(getCloudOrganizations).mockResolvedValue({items: [{ id: "org-2", name: "Acme Inc" }],currentOrgId: "org-2",@@ -589,7 +591,8 @@ describe("BackendSelector", () => {const stored = JSON.parse(window.localStorage.getItem("openhands-active-backend") ?? "null",);- expect(stored?.backendId).toBe("__bundled__");+ // The seeded default-local backend is the first registered local.+ expect(stored?.backendId).toBe("default-local");expect(stored?.orgId ?? null).toBeNull();});});@@ -610,6 +613,23 @@ describe("BackendSelector", () => {});});+ it("includes the seeded default Local backend in the manage backends modal as a removable entry", async () => {+ renderWithProviders(<BackendSelector />);++ const user = await openDropdown();+ await user.click(screen.getByTestId("manage-backends-menu-item"));++ expect(+ await screen.findByTestId("manage-backends-modal"),+ ).toBeInTheDocument();+ // The default backend is just a regular registered entry β same row+ // shape and a remove button identical to any other backend.+ expect(screen.getByTestId("manage-backends-row-Local")).toBeInTheDocument();+ expect(+ screen.getByTestId("manage-backends-remove-Local"),+ ).toBeInTheDocument();+ });+it("opens the manage backends modal and removes a backend", async () => {renderWithProviders(<TestSeed@@ -646,12 +666,14 @@ describe("BackendSelector", () => {screen.queryByTestId("manage-backends-row-Local 1"),).not.toBeInTheDocument();});- expect(- JSON.parse(window.localStorage.getItem("openhands-backends") ?? "[]"),- ).toEqual([]);+ // The seeded default ("Local") survives removing only "Local 1".+ const remaining = JSON.parse(+ window.localStorage.getItem("openhands-backends") ?? "[]",+ );+ expect(remaining.map((b: { name: string }) => b.name)).toEqual(["Local"]);});- it("falls back to the bundled backend when removing the active backend from manage backends", async () => {+ it("falls back to the seeded default backend when removing the active backend from manage backends", async () => {renderWithProviders(<TestSeedonMount={(ctx) => {@@ -685,6 +707,8 @@ describe("BackendSelector", () => {).not.toBeInTheDocument();});+ // The active selection is cleared because its target was removed;+ // the active store then falls back to the seeded default backend.const stored = JSON.parse(window.localStorage.getItem("openhands-active-backend") ?? "null",);@@ -692,7 +716,7 @@ describe("BackendSelector", () => {wrapper = screen.getByTestId("backend-selector");input = wrapper.querySelector("input") as HTMLInputElement;- expect(input.value).toBe("BACKEND$LOCAL_ROW");+ expect(input.value).toBe("Local");});it("redirects to the automations list when switching backends from an automation detail route", async () => {diff --git a/__tests__/components/features/settings/backend-synced-settings-badge.test.tsx b/__tests__/components/features/settings/backend-synced-settings-badge.test.tsxindex 7d29ac1781..672b0734ba 100644--- a/__tests__/components/features/settings/backend-synced-settings-badge.test.tsx+++ b/__tests__/components/features/settings/backend-synced-settings-badge.test.tsx@@ -88,18 +88,19 @@ describe("BackendSyncedSettingsBadge", () => {__resetActiveStoreForTests();});- it("renders the bundled local backend label and host URL without HTML-escaping", () => {- // Arrange β no registered backends; resolved active falls back to bundled.+ it("renders the seeded default local backend label and host URL without HTML-escaping", () => {+ // Arrange β no explicit setRegisteredBackends() in this test; the+ // active store auto-seeds a default local backend named "Local".// ActrenderBadge();- // Assert β the bundled name slot resolves to BACKEND$LOCAL_ROW and the- // host URL is preserved literally (no `/` from i18next escape).+ // Assert β the default name slot resolves to "Local" and the host+ // URL is preserved literally (no `/` from i18next escape).const text = screen.getByTestId("backend-synced-settings-badge",).textContent;expect(text).toMatch(- /These settings are synced from BACKEND\$LOCAL_ROW backend \(https?:\/\/.+\)/,+ /These settings are synced from Local backend \(https?:\/\/.+\)/,);expect(text).not.toContain("/");});diff --git a/__tests__/components/ui/dropdown.test.tsx b/__tests__/components/ui/dropdown.test.tsxindex 55a1fa767a..edec8ba496 100644--- a/__tests__/components/ui/dropdown.test.tsx+++ b/__tests__/components/ui/dropdown.test.tsx@@ -155,7 +155,7 @@ describe("Dropdown", () => {expect(selectedOption).toHaveAttribute("aria-selected", "true");});- it("should preserve selected value in input and show all options when reopening dropdown", async () => {+ it("should clear the search input and show all options when reopening dropdown", async () => {const user = userEvent.setup();render(<Dropdown options={mockOptions} />);@@ -167,7 +167,7 @@ describe("Dropdown", () => {await user.click(trigger);const input = screen.getByRole("combobox");- expect(input).toHaveValue("Option 1");+ expect(input).toHaveValue("");expect(screen.getByRole("option", { name: "Option 1" }),).toBeInTheDocument();diff --git a/__tests__/contexts/active-backend-context.test.tsx b/__tests__/contexts/active-backend-context.test.tsxindex 4c3708caca..3e67a88fdd 100644--- a/__tests__/contexts/active-backend-context.test.tsx+++ b/__tests__/contexts/active-backend-context.test.tsx@@ -3,7 +3,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { act, render, renderHook } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";-import { BUNDLED_BACKEND_ID } from "#/api/backend-registry/types";+import { DEFAULT_LOCAL_BACKEND_ID } from "#/api/backend-registry/default-backend";import {ActiveBackendProvider,useActiveBackendContext,@@ -31,16 +31,20 @@ afterEach(() => {});describe("ActiveBackendProvider", () => {- it("exposes the bundled backend by default", () => {+ it("seeds the default local backend on first read and treats it as active", () => {const { result } = renderHook(() => useActiveBackendContext(), {wrapper: makeWrapper(),});- expect(result.current.active.backend.id).toBe(BUNDLED_BACKEND_ID);- expect(result.current.backends).toEqual([]);+ expect(result.current.active.backend.id).toBe(DEFAULT_LOCAL_BACKEND_ID);+ expect(result.current.backends).toHaveLength(1);+ expect(result.current.backends[0]).toMatchObject({+ id: DEFAULT_LOCAL_BACKEND_ID,+ kind: "local",+ });});- it("addBackend persists and exposes the new backend", () => {+ it("addBackend persists and exposes the new backend alongside the seeded default", () => {const { result } = renderHook(() => useActiveBackendContext(), {wrapper: makeWrapper(),});@@ -54,8 +58,11 @@ describe("ActiveBackendProvider", () => {});});- expect(result.current.backends).toHaveLength(1);- expect(result.current.backends[0]).toMatchObject({+ // Seed entry plus the new one.+ expect(result.current.backends).toHaveLength(2);+ expect(+ result.current.backends.find((b) => b.name === "Production"),+ ).toMatchObject({name: "Production",kind: "cloud",});@@ -92,7 +99,7 @@ describe("ActiveBackendProvider", () => {expect(queryClient.getQueryData(["dummy"])).toEqual({ value: 1 });});- it("removeBackend falls back to bundled if the active was removed", () => {+ it("removeBackend falls back to the seeded default when the active backend is removed", () => {const { result } = renderHook(() => useActiveBackendContext(), {wrapper: makeWrapper(),});@@ -115,8 +122,28 @@ describe("ActiveBackendProvider", () => {act(() => {result.current.removeBackend(id);});- expect(result.current.active.backend.id).toBe(BUNDLED_BACKEND_ID);+ expect(result.current.active.backend.id).toBe(DEFAULT_LOCAL_BACKEND_ID);+ expect(result.current.backends).toHaveLength(1);+ expect(result.current.backends[0].id).toBe(DEFAULT_LOCAL_BACKEND_ID);+ });++ it("removeBackend allows removing the seeded default and falls back to a synthesized env-derived backend", () => {+ const { result } = renderHook(() => useActiveBackendContext(), {+ wrapper: makeWrapper(),+ });++ expect(result.current.backends).toHaveLength(1);++ act(() => {+ result.current.removeBackend(DEFAULT_LOCAL_BACKEND_ID);+ });+expect(result.current.backends).toEqual([]);+ // No registered backend remains, so the active store synthesizes+ // an env-derived local backend (with the well-known default id) so+ // synchronous call sites never have to handle a null backend.+ expect(result.current.active.backend.id).toBe(DEFAULT_LOCAL_BACKEND_ID);+ expect(result.current.active.backend.kind).toBe("local");});it("throws if used outside the provider", () => {diff --git a/src/api/agent-server-compatibility.ts b/src/api/agent-server-compatibility.tsindex 30d76b9e46..e3ee6b1e0d 100644--- a/src/api/agent-server-compatibility.ts+++ b/src/api/agent-server-compatibility.ts@@ -1,5 +1,5 @@import { HttpError } from "@openhands/typescript-client/client/http-client";-import { getBundledBackend } from "#/api/backend-registry/bundled";+import { getEffectiveLocalBackend } from "#/api/backend-registry/active-store";import {createServerClient,type ServerInfo as BaseServerInfo,@@ -56,15 +56,15 @@ export function isAgentServerToolAvailable(toolName: string) {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, because cloud SaaS hosts don't expose /api/server_info and- // would fail with a CORS error besides.- const bundled = getBundledBackend();+ // backend when that backend is cloud, because cloud SaaS hosts don't+ // expose /api/server_info and would fail with a CORS error besides.+ const local = getEffectiveLocalBackend();let serverInfo: AgentServerInfo;try {serverInfo = (await createServerClient({- host: bundled.host,- sessionApiKey: bundled.apiKey || null,+ host: local.host,+ sessionApiKey: local.apiKey || null,timeout: AGENT_SERVER_INFO_TIMEOUT_MS,}).getServerInfo()) as AgentServerInfo;} catch (error) {diff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.tsindex 75adaba858..fe27e82583 100644--- a/src/api/automation-service/automation-service.api.ts+++ b/src/api/automation-service/automation-service.api.ts@@ -4,8 +4,10 @@ import type {AutomationsResponse,AutomationRunsResponse,} from "#/types/automation";-import { getAgentServerBaseUrl } from "../agent-server-config";-import { getActiveBackend } from "../backend-registry/active-store";+import {+ getActiveBackend,+ getEffectiveLocalBackend,+} from "../backend-registry/active-store";import { callCloudProxy } from "../cloud/proxy";const AUTOMATION_BASE_PATH = "/api/automation";@@ -16,15 +18,20 @@ export interface AutomationHealthResponse {}// Local automation calls go to the automation sidecar that-// `scripts/dev-with-automation.mjs` mounts behind the bundled agent-server.+// `scripts/dev-with-automation.mjs` mounts behind the local agent-server.// That sidecar authenticates via its own `VITE_AUTOMATION_API_KEY` Bearer// token β NOT the agent-server's `X-Session-API-Key` β so we cannot reuse// the shared `openHands` axios for these calls.-const localAutomationAxios = axios.create({- baseURL: getAgentServerBaseUrl(),-});+const localAutomationAxios = axios.create();localAutomationAxios.interceptors.request.use((config) => {+ // Resolve the local backend host on every call so it tracks the+ // currently-active local backend (and any host edits made via the+ // manage-backends UI), rather than freezing whatever value the+ // agent-server-config produced at module load time.+ // eslint-disable-next-line no-param-reassign+ if (!config.baseURL) config.baseURL = getEffectiveLocalBackend().host;+const apiKey = import.meta.env.VITE_AUTOMATION_API_KEY?.trim();if (apiKey) {config.headers.set("Authorization", `Bearer ${apiKey}`);diff --git a/src/api/backend-registry/active-store.ts b/src/api/backend-registry/active-store.tsindex 9d9345da25..15df90e71e 100644--- a/src/api/backend-registry/active-store.ts+++ b/src/api/backend-registry/active-store.ts@@ -1,16 +1,11 @@-import { getBundledBackend } from "./bundled";+import { makeDefaultLocalBackend } from "./default-backend";import {readStoredActiveBackend,readStoredBackends,writeStoredActiveBackend,writeStoredBackends,} from "./storage";-import {- BUNDLED_BACKEND_ID,- type Backend,- type BackendSelection,- type ResolvedActiveBackend,-} from "./types";+import type { Backend, BackendSelection, ResolvedActiveBackend } from "./types";type Listener = () => void;@@ -20,25 +15,40 @@ interface Snapshot {active: ResolvedActiveBackend;}+/**+ * Pick the local backend the GUI should talk to for local-protocol calls+ * (settings, conversations, secrets, β¦). Prefers the user's first+ * registered local backend. As a last resort β when the registry has no+ * local entry at all β synthesize one from env/agent-server-config so+ * synchronous call sites never have to handle a `null` backend; the+ * synthesized entry is never persisted.+ */+function pickLocalBackend(backends: Backend[]): Backend {+ const firstLocal = backends.find((b) => b.kind === "local");+ return firstLocal ?? makeDefaultLocalBackend();+}+function computeSnapshot(backends: Backend[],selection: BackendSelection | null,): Snapshot {- const bundled = getBundledBackend();-- let activeBackend: Backend = bundled;+ let activeBackend: Backend | null = null;let activeOrgId: string | null = null;if (selection) {- activeOrgId = selection.orgId ?? null;- if (selection.backendId !== BUNDLED_BACKEND_ID) {- const found = backends.find((b) => b.id === selection.backendId);- if (found) {- activeBackend = found;- } else {- activeOrgId = null; // selection points at a removed backend- }+ const found = backends.find((b) => b.id === selection.backendId);+ if (found) {+ activeBackend = found;+ activeOrgId = selection.orgId ?? null;}+ // If the selection points at a removed backend, fall through to+ // the unselected case below; we also drop the orgId since it only+ // makes sense in the context of a specific cloud backend.+ }++ if (!activeBackend) {+ activeBackend = pickLocalBackend(backends);+ activeOrgId = null;}return {@@ -69,13 +79,14 @@ export function getActiveBackend(): ResolvedActiveBackend {* Most of the GUI's services (settings reads/writes, conversation CRUD,* skills/MCP/secrets, etc.) speak the local agent-server's protocol β* they would fail against a cloud SaaS host. When the user has chosen a- * cloud backend as active, those calls fall back to the bundled local- * agent-server. Cloud-only call sites import `getActiveBackend` directly.+ * cloud backend as active, those calls fall back to the first registered+ * local backend (or the env-derived default if none exists). Cloud-only+ * call sites import `getActiveBackend` directly.*/export function getEffectiveLocalBackend(): Backend {const active = snapshot.active.backend;- if (active.kind === "cloud") return getBundledBackend();- return active;+ if (active.kind === "local") return active;+ return pickLocalBackend(snapshot.backends);}export function getRegisteredBackends(): Backend[] {@@ -102,7 +113,6 @@ export function setRegisteredBackends(backends: Backend[]): void {let nextSelection = snapshot.selection;if (nextSelection &&- nextSelection.backendId !== BUNDLED_BACKEND_ID &&!backends.some((b) => b.id === nextSelection!.backendId)) {nextSelection = null;diff --git a/src/api/backend-registry/bundled.ts b/src/api/backend-registry/bundled.tsdeleted file mode 100644index d21cba4d2d..0000000000--- a/src/api/backend-registry/bundled.ts+++ /dev/null@@ -1,17 +0,0 @@-import {- getAgentServerBaseUrl,- getAgentServerSessionApiKey,-} from "../agent-server-config";-import { BUNDLED_BACKEND_ID, type Backend } from "./types";--export const BUNDLED_BACKEND_NAME = "Local";--export function getBundledBackend(): Backend {- return {- id: BUNDLED_BACKEND_ID,- name: BUNDLED_BACKEND_NAME,- host: getAgentServerBaseUrl(),- apiKey: getAgentServerSessionApiKey() ?? "",- kind: "local",- };-}diff --git a/src/api/backend-registry/default-backend.ts b/src/api/backend-registry/default-backend.tsnew file mode 100644index 0000000000..7a1db147c4--- /dev/null+++ b/src/api/backend-registry/default-backend.ts@@ -0,0 +1,40 @@+import {+ getAgentServerBaseUrl,+ getAgentServerSessionApiKey,+} from "../agent-server-config";+import type { Backend } from "./types";++/**+ * Stable id for the default local backend that is auto-seeded into the+ * registry on a fresh install. After seeding, this backend is a normal+ * registered entry β the user can rename it, edit its host/api key, or+ * remove it like any other backend.+ *+ * The id is also used by `saveAgentServerConfig` to keep the registry+ * entry in sync with the legacy `openhands-agent-server-config` storage+ * that the recovery / agent-server settings page edits.+ */+export const DEFAULT_LOCAL_BACKEND_ID = "default-local";++export const DEFAULT_LOCAL_BACKEND_NAME = "Local";++/**+ * Construct the default local backend from environment / agent-server+ * config (`VITE_BACKEND_BASE_URL`, `VITE_SESSION_API_KEY`, plus the+ * `openhands-agent-server-config` localStorage overrides).+ *+ * Used in two places:+ * 1. As the seed entry written to `openhands-backends` on first load.+ * 2. As a last-resort fallback inside the active store when the+ * registry has no local backend at all (e.g. the user removed+ * every entry). The synthetic fallback is never persisted.+ */+export function makeDefaultLocalBackend(): Backend {+ return {+ id: DEFAULT_LOCAL_BACKEND_ID,+ name: DEFAULT_LOCAL_BACKEND_NAME,+ host: getAgentServerBaseUrl(),+ apiKey: getAgentServerSessionApiKey() ?? "",+ kind: "local",+ };+}diff --git a/src/api/backend-registry/index.ts b/src/api/backend-registry/index.tsindex b1e01a58ce..f3e94281c1 100644--- a/src/api/backend-registry/index.ts+++ b/src/api/backend-registry/index.ts@@ -1,5 +1,5 @@export * from "./types";export * from "./storage";-export * from "./bundled";+export * from "./default-backend";export * from "./active-store";export * from "./auth";diff --git a/src/api/backend-registry/storage.ts b/src/api/backend-registry/storage.tsindex 7b74677b27..473becbc9b 100644--- a/src/api/backend-registry/storage.ts+++ b/src/api/backend-registry/storage.ts@@ -1,3 +1,4 @@+import { makeDefaultLocalBackend } from "./default-backend";import type { Backend, BackendKind, BackendSelection } from "./types";export const BACKENDS_STORAGE_KEY = "openhands-backends";@@ -20,11 +21,32 @@ function isValidBackend(value: unknown): value is Backend {);}+export function writeStoredBackends(backends: Backend[]): void {+ if (typeof window === "undefined") return;+ try {+ window.localStorage.setItem(BACKENDS_STORAGE_KEY, JSON.stringify(backends));+ } catch {+ /* ignore quota / serialization errors */+ }+}+export function readStoredBackends(): Backend[] {if (typeof window === "undefined") return [];try {const raw = window.localStorage.getItem(BACKENDS_STORAGE_KEY);- if (!raw) return [];++ // 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.+ if (raw === null) {+ const seeded = [makeDefaultLocalBackend()];+ writeStoredBackends(seeded);+ return seeded;+ }+const parsed = JSON.parse(raw);if (!Array.isArray(parsed)) return [];return parsed.filter(isValidBackend);@@ -33,15 +55,6 @@ export function readStoredBackends(): Backend[] {}}-export function writeStoredBackends(backends: Backend[]): void {- if (typeof window === "undefined") return;- try {- window.localStorage.setItem(BACKENDS_STORAGE_KEY, JSON.stringify(backends));- } catch {- /* ignore quota / serialization errors */- }-}-export function readStoredActiveBackend(): BackendSelection | null {if (typeof window === "undefined") return null;try {diff --git a/src/api/backend-registry/types.ts b/src/api/backend-registry/types.tsindex 045936d1be..fb50708dff 100644--- a/src/api/backend-registry/types.ts+++ b/src/api/backend-registry/types.ts@@ -17,5 +17,3 @@ export interface ResolvedActiveBackend {backend: Backend;orgId: string | null;}--export const BUNDLED_BACKEND_ID = "__bundled__";diff --git a/src/api/cloud/proxy.ts b/src/api/cloud/proxy.tsindex ba5e609e29..0346c0475d 100644--- a/src/api/cloud/proxy.ts+++ b/src/api/cloud/proxy.ts@@ -1,6 +1,6 @@import axios from "axios";+import { getEffectiveLocalBackend } from "../backend-registry/active-store";import { buildAuthHeaders } from "../backend-registry/auth";-import { getBundledBackend } from "../backend-registry/bundled";import type { Backend } from "../backend-registry/types";interface CloudProxyRequest {@@ -58,10 +58,10 @@ function buildUpstreamAuthHeaders(}/**- * POST a cloud-proxy envelope to the bundled local agent-server. The local- * server forwards the request to the upstream host server-side, which- * sidesteps the cross-origin restrictions that would block a direct- * browser β SaaS or browser β runtime-sandbox call.+ * POST a cloud-proxy envelope to the local agent-server. The local server+ * forwards the request to the upstream host server-side, which sidesteps+ * the cross-origin restrictions that would block a direct browser β SaaS+ * or browser β runtime-sandbox call.** Auth headers (bearer or session-api-key) are attached server-side; they* never cross an origin boundary in the browser.@@ -69,18 +69,18 @@ function buildUpstreamAuthHeaders(export async function callCloudProxy<TResponse = unknown>(req: CloudProxyRequest,): Promise<TResponse> {- const bundled = getBundledBackend();+ const local = getEffectiveLocalBackend();const upstreamHeaders = {...buildUpstreamAuthHeaders(req),...(req.headers ?? {}),};const upstreamHost = req.hostOverride ?? req.backend.host;- // Talk directly to the bundled local agent-server, bypassing the global+ // Talk directly to the local agent-server, bypassing the global// openHands axios interceptor (which would otherwise read host + auth// from the active backend β wrong for this call).const response = await axios.post<TResponse>(- `${bundled.host.replace(/\/+$/, "")}/api/cloud-proxy`,+ `${local.host.replace(/\/+$/, "")}/api/cloud-proxy`,{host: upstreamHost,method: req.method,@@ -90,7 +90,7 @@ export async function callCloudProxy<TResponse = unknown>(...(req.timeoutSeconds ? { timeout_seconds: req.timeoutSeconds } : {}),},{- headers: buildAuthHeaders(bundled),+ headers: buildAuthHeaders(local),timeout: 30_000,...(req.responseType ? { responseType: req.responseType } : {}),},diff --git a/src/api/open-hands-axios.ts b/src/api/open-hands-axios.tsindex 9437906e75..09bef75248 100644--- a/src/api/open-hands-axios.ts+++ b/src/api/open-hands-axios.ts@@ -3,9 +3,11 @@ import axios, {AxiosResponse,InternalAxiosRequestConfig,} from "axios";-import { getActiveBackend } from "./backend-registry/active-store";+import {+ getActiveBackend,+ getEffectiveLocalBackend,+} from "./backend-registry/active-store";import { buildAuthHeaders } from "./backend-registry/auth";-import { getBundledBackend } from "./backend-registry/bundled";function serializeParams(params: Record<string, unknown> | URLSearchParams,@@ -43,11 +45,11 @@ export const openHands = axios.create({openHands.interceptors.request.use((config: InternalAxiosRequestConfig) => {// The default openHands axios speaks the *local agent-server's* protocol// (X-Session-API-Key auth, /api/* paths). When the active backend is- // cloud, fall back to the bundled local agent-server β cloud-specific- // calls go through `callCloudProxy` (which uses axios directly) and- // never hit this interceptor.+ // cloud, fall back to the first registered local backend β cloud-+ // specific calls go through `callCloudProxy` (which uses axios directly)+ // and never hit this interceptor.const active = getActiveBackend().backend;- const backend = active.kind === "cloud" ? getBundledBackend() : active;+ const backend = active.kind === "cloud" ? getEffectiveLocalBackend() : active;// Mutating the per-request config is the canonical axios interceptor pattern.// eslint-disable-next-line no-param-reassigndiff --git a/src/api/typescript-client.ts b/src/api/typescript-client.tsindex 9f73539602..a3a0e4b20b 100644--- a/src/api/typescript-client.ts+++ b/src/api/typescript-client.ts@@ -9,8 +9,10 @@ import { HttpClient } from "@openhands/typescript-client/client/http-client";import { RemoteEventsList } from "@openhands/typescript-client/events/remote-events-list";import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";import { buildHttpBaseUrl } from "#/utils/websocket-url";-import { getActiveBackend } from "./backend-registry/active-store";-import { getBundledBackend } from "./backend-registry/bundled";+import {+ getActiveBackend,+ getEffectiveLocalBackend,+} from "./backend-registry/active-store";import { getAgentServerWorkingDir } from "./agent-server-config";export type { ServerInfo } from "@openhands/typescript-client";@@ -36,12 +38,12 @@ interface ResolvedClientOptions {* speak the *local agent-server's* protocol β `X-Session-API-Key` auth and* paths like `/api/conversations`, `/api/skills`, etc. The cloud SaaS* exposes neither, so when the active backend is cloud, fall back to the- * bundled local agent-server for these calls. Cloud-specific calls go+ * first registered local backend for these calls. Cloud-specific calls go* through `callCloudProxy` separately and never touch this resolver.*/function resolveDefaultBackend() {const active = getActiveBackend().backend;- if (active.kind === "cloud") return getBundledBackend();+ if (active.kind === "cloud") return getEffectiveLocalBackend();return active;}diff --git a/src/components/features/backends/backend-selector.tsx b/src/components/features/backends/backend-selector.tsxindex ff6c21781c..8b11767f8d 100644--- a/src/components/features/backends/backend-selector.tsx+++ b/src/components/features/backends/backend-selector.tsx@@ -36,16 +36,12 @@ function parseOptionValue(value: string): {}function buildOptions(- bundled: Backend,registered: Backend[],- bundledLabel: string,personalWorkspaceLabel: string,cloudOrgs: ReturnType<typeof useAllCloudOrganizations>,currentUserIds: ReturnType<typeof useCloudCurrentUserId>,): DropdownOption[] {- const options: DropdownOption[] = [- { value: makeOptionValue(bundled.id, null), label: bundledLabel },- ];+ const options: DropdownOption[] = [];const locals = registered.filter((b) => b.kind === "local");const clouds = registered.filter((b) => b.kind === "cloud");@@ -88,8 +84,7 @@ export function BackendSelector({openUpward = false,}: BackendSelectorProps = {}) {const { t } = useTranslation("openhands");- const { backends, bundledBackend, active, setActive } =- useActiveBackendContext();+ const { backends, active, setActive } = useActiveBackendContext();const cloudOrgs = useAllCloudOrganizations();const currentUserIds = useCloudCurrentUserId();const { mutateAsync: switchOrg, isPending: isSwitching } =@@ -101,27 +96,17 @@ export function BackendSelector({const [manageBackendsModalOpen, setManageBackendsModalOpen] =React.useState(false);- const bundledLabel = t(I18nKey.BACKEND$LOCAL_ROW);const personalWorkspaceLabel = t(I18nKey.BACKEND$PERSONAL_WORKSPACE);+ const firstLocalBackendId = React.useMemo(+ () => backends.find((b) => b.kind === "local")?.id ?? null,+ [backends],+ );+const options = React.useMemo(() =>- buildOptions(- bundledBackend,- backends,- bundledLabel,- personalWorkspaceLabel,- cloudOrgs,- currentUserIds,- ),- [- bundledBackend,- backends,- bundledLabel,- personalWorkspaceLabel,- cloudOrgs,- currentUserIds,- ],+ buildOptions(backends, personalWorkspaceLabel, cloudOrgs, currentUserIds),+ [backends, personalWorkspaceLabel, cloudOrgs, currentUserIds],);const activeValue = makeOptionValue(active.backend.id, active.orgId);@@ -161,8 +146,8 @@ export function BackendSelector({setActive(backend.id, target.id);}} catch {- if (!cancelled) {- setActive(bundledBackend.id, null);+ if (!cancelled && firstLocalBackendId) {+ setActive(firstLocalBackendId, null);}}};@@ -177,7 +162,7 @@ export function BackendSelector({};}, [active,- bundledBackend.id,+ firstLocalBackendId,cloudOrgs,currentUserIds,setActive,@@ -231,17 +216,14 @@ export function BackendSelector({testId="backend-selector"key={`${activeValue}-${activeOption?.label ?? ""}`}defaultValue={- activeOption ?? { value: activeValue, label: bundledLabel }+ activeOption ?? { value: activeValue, label: active.backend.name }}footer={addBackendFooter}openUpward={openUpward}onChange={async (item) => {if (!item || item.value === activeValue) return;const { backendId, orgId } = parseOptionValue(item.value);- const target =- backendId === bundledBackend.id- ? bundledBackend- : backends.find((b) => b.id === backendId);+ const target = backends.find((b) => b.id === backendId);if (!target) return;triggerEnvironmentSwitch(item.label);@@ -273,7 +255,7 @@ export function BackendSelector({setActive(target.id, orgId);}}- placeholder={bundledLabel}+ placeholder={active.backend.name}loading={someCloudLoading || isSwitching}options={options}className="bg-[#1F1F1F66] border-[#242424]"diff --git a/src/components/features/settings/agent-server-onboarding.tsx b/src/components/features/settings/agent-server-onboarding.tsxindex db9ab123b1..2970c44d0c 100644--- a/src/components/features/settings/agent-server-onboarding.tsx+++ b/src/components/features/settings/agent-server-onboarding.tsx@@ -5,6 +5,15 @@ import {getAgentServerFormDefaults,saveAgentServerConfig,} from "#/api/agent-server-config";+import {+ getRegisteredBackends,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import {+ DEFAULT_LOCAL_BACKEND_ID,+ DEFAULT_LOCAL_BACKEND_NAME,+} from "#/api/backend-registry/default-backend";+import type { Backend } from "#/api/backend-registry/types";import { cn } from "#/utils/utils";import { BrandButton } from "./brand-button";import { SettingsInput } from "./settings-input";@@ -40,14 +49,51 @@ export function AgentServerConnectionForm({window.location.assign("/");};+ const syncDefaultBackendInRegistry = () => {+ const trimmedHost = baseUrl.trim();+ if (!trimmedHost) return;++ const trimmedKey = sessionApiKey.trim();+ const current = getRegisteredBackends();+ const defaultEntry: Backend = {+ id: DEFAULT_LOCAL_BACKEND_ID,+ name: DEFAULT_LOCAL_BACKEND_NAME,+ host: trimmedHost,+ apiKey: trimmedKey,+ kind: "local",+ };++ const existingIndex = current.findIndex(+ (b) => b.id === DEFAULT_LOCAL_BACKEND_ID,+ );+ if (existingIndex === -1) {+ setRegisteredBackends([defaultEntry, ...current]);+ return;+ }++ const next = current.slice();+ next[existingIndex] = {+ ...current[existingIndex],+ host: trimmedHost,+ apiKey: trimmedKey,+ };+ setRegisteredBackends(next);+ };+const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {event.preventDefault();+ // Persist to the legacy config so the next-session seed and any+ // module-level fallbacks pick up the new values β¦saveAgentServerConfig({baseUrl,sessionApiKey,});+ // β¦ and propagate the change into the registry so the active-store+ // snapshot reflects the new host/api key on this session too.+ syncDefaultBackendInRegistry();+reconnect();};diff --git a/src/components/features/settings/backend-synced-settings-badge.tsx b/src/components/features/settings/backend-synced-settings-badge.tsxindex b03c69b278..71f45843e2 100644--- a/src/components/features/settings/backend-synced-settings-badge.tsx+++ b/src/components/features/settings/backend-synced-settings-badge.tsx@@ -3,7 +3,6 @@ import { Typography } from "#/ui/typography";import { I18nKey } from "#/i18n/declaration";import InfoCircleIcon from "#/icons/info-circle.svg?react";import { useActiveBackend } from "#/contexts/active-backend-context";-import { BUNDLED_BACKEND_ID } from "#/api/backend-registry/types";import { useAllCloudOrganizations } from "#/hooks/query/use-cloud-organizations";import { useCloudCurrentUserId } from "#/hooks/query/use-cloud-current-user-id";@@ -13,9 +12,6 @@ function useActiveBackendDisplayName(): string {const cloudOrgs = useAllCloudOrganizations();const userIds = useCloudCurrentUserId();- if (active.backend.id === BUNDLED_BACKEND_ID) {- return t(I18nKey.BACKEND$LOCAL_ROW);- }if (active.backend.kind !== "cloud" || !active.orgId) {return active.backend.name;}diff --git a/src/contexts/active-backend-context.tsx b/src/contexts/active-backend-context.tsxindex 40ab7ec323..2b4798b3f4 100644--- a/src/contexts/active-backend-context.tsx+++ b/src/contexts/active-backend-context.tsx@@ -7,17 +7,15 @@ import {setRegisteredBackends,subscribeActiveBackend,} from "#/api/backend-registry/active-store";-import { getBundledBackend } from "#/api/backend-registry/bundled";+import { makeDefaultLocalBackend } from "#/api/backend-registry/default-backend";import {type Backend,type BackendSelection,type ResolvedActiveBackend,- BUNDLED_BACKEND_ID,} from "#/api/backend-registry/types";interface ActiveBackendContextValue {backends: Backend[];- bundledBackend: Backend;active: ResolvedActiveBackend;setActive: (backendId: string, orgId?: string | null) => void;addBackend: (backend: Omit<Backend, "id">) => Backend;@@ -51,8 +49,7 @@ export function ActiveBackendProvider({const setActive = React.useCallback((backendId: string, orgId?: string | null) => {- const prevBackendId =- getActiveSelection()?.backendId ?? BUNDLED_BACKEND_ID;+ const prevBackendId = getActiveSelection()?.backendId ?? null;const prevOrgId = getActiveSelection()?.orgId ?? null;const nextOrgId = orgId ?? null;@@ -93,19 +90,17 @@ export function ActiveBackendProvider({);const removeBackend = React.useCallback((id: string) => {- if (id === BUNDLED_BACKEND_ID) return;const list = getRegisteredBackends().filter((b) => b.id !== id);setRegisteredBackends(list);// If the active selection pointed at this backend, the active- // store falls back to bundled; consumer hooks re-key by the new- // active backend identity and refetch automatically. No blanket- // invalidate needed.+ // store falls back to the first remaining local backend (or the+ // env-derived default if no locals exist); consumer hooks re-key+ // by the new active backend identity and refetch automatically.}, []);const value = React.useMemo<ActiveBackendContextValue>(() => ({backends: snapshot.backends,- bundledBackend: getBundledBackend(),active: snapshot.active,setActive,addBackend,@@ -135,11 +130,10 @@ export function useActiveBackendContext(): ActiveBackendContextValue {/*** Read the resolved active backend.*- * Falls back to the bundled local backend when called outside an- * `<ActiveBackendProvider>` (e.g. from a unit test that mounts a- * narrow component without the full provider stack). The bundled- * backend is a pure function of env vars + window.location, so this- * fallback is identical to what an empty active selection resolves to.+ * Falls back to a synthesized env-derived local backend when called+ * outside an `<ActiveBackendProvider>` (e.g. from a unit test that+ * mounts a narrow component without the full provider stack). That+ * synthesized backend is identical to the seed used on first install.** Components that need to mutate state (`setActive`, `addBackend`,* etc.) must use `useActiveBackendContext()` directly β that throws if@@ -148,5 +142,5 @@ export function useActiveBackendContext(): ActiveBackendContextValue {export function useActiveBackend(): ResolvedActiveBackend {const ctx = React.useContext(ActiveBackendContext);if (ctx) return ctx.active;- return { backend: getBundledBackend(), orgId: null };+ return { backend: makeDefaultLocalBackend(), orgId: null };}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex c16e6c3982..15aaba9857 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -22410,23 +22410,6 @@"uk": "Π₯ΠΌΠ°ΡΠ°","ca": "NΓΊvol"},- "BACKEND$LOCAL_ROW": {- "en": "Local",- "ja": "γγΌγ«γ«",- "zh-CN": "ζ¬ε°",- "zh-TW": "ζ¬ζ©",- "ko-KR": "λ‘컬",- "no": "Lokal",- "it": "Locale",- "pt": "Local",- "es": "Local",- "ar": "Ω ΨΩΩ",- "fr": "Local",- "tr": "Yerel",- "de": "Lokal",- "uk": "ΠΠΎΠΊΠ°Π»ΡΠ½ΠΈΠΉ",- "ca": "Local"- },"BACKEND$VERSION_LABEL": {"en": "v{{version}}","ja": "v{{version}}",diff --git a/src/ui/dropdown/dropdown.tsx b/src/ui/dropdown/dropdown.tsxindex 6046af9d53..90e48b1741 100644--- a/src/ui/dropdown/dropdown.tsx+++ b/src/ui/dropdown/dropdown.tsx@@ -74,6 +74,11 @@ export function Dropdown({selectedItem: currentSelectedItem,}) => {if (newIsOpen) {+ // Clear the input on open so the user sees an empty search box+ // (with the placeholder reminding them of the current value)+ // and the full options list. Otherwise the active label would+ // appear both in the trigger AND as the highlighted menu row.+ setInputValue("");setSearchTerm("");} else {setInputValue(currentSelectedItem?.label ?? "");