๐ OpenHands: AI-Driven Development
Add lock-to-cloud backend setup mode (#1389)
Graham Neubiga1c68313b290
diff --git a/.github/workflows/mock-llm-docker-e2e.yml b/.github/workflows/mock-llm-docker-e2e.ymlindex 0f2781fad5..8218fa0e61 100644--- a/.github/workflows/mock-llm-docker-e2e.yml+++ b/.github/workflows/mock-llm-docker-e2e.yml@@ -70,7 +70,7 @@ jobs:SHOULD_RUN=falsewhile IFS= read -r file; docase "$file" in- src/*|public/*|scripts/*|bin/*|config/*|docker/*|tests/e2e/mock-llm/*|tests/e2e/support/*|package.json|package-lock.json|vite.config.ts|tsconfig.json|react-router.config.ts|playwright.mock-llm.config.ts|playwright.mock-llm-docker.config.ts|tailwind.config.js|hero.ts|.github/workflows/mock-llm-docker-e2e.yml)+ src/*|public/*|scripts/*|bin/*|config/*|docker/*|tests/e2e/mock-llm/*|tests/e2e/support/*|package.json|package-lock.json|vite.config.ts|tsconfig.json|react-router.config.ts|playwright.mock-llm.config.ts|playwright.mock-llm-docker.config.ts|tailwind.config.js|hero.ts|.github/workflows/docker.yml|.github/workflows/mock-llm-docker-e2e.yml)SHOULD_RUN=truebreak;;diff --git a/.github/workflows/mock-llm-e2e.yml b/.github/workflows/mock-llm-e2e.ymlindex e58a9b0400..1532fa6225 100644--- a/.github/workflows/mock-llm-e2e.yml+++ b/.github/workflows/mock-llm-e2e.yml@@ -49,7 +49,11 @@ jobs:needs: detect-pr-changesif: github.event_name != 'pull_request' || needs.detect-pr-changes.outputs.should_run == 'true'runs-on: ubuntu-24.04- timeout-minutes: 15+ # Full-suite runs can spend several minutes on dependency, browser, uv,+ # and frontend setup before Playwright starts. Keep Playwright's own+ # 10-minute test deadline below, but give the job enough wall-clock room+ # for setup plus reporting so GitHub does not terminate it mid-suite.+ timeout-minutes: 30env:MOCK_LLM_REPORT_PATH: mock-llm-report.mddiff --git a/.gitignore b/.gitignoreindex dca7671654..182f1ca650 100644--- a/.gitignore+++ b/.gitignore@@ -28,3 +28,7 @@ __pycache__ralph/.vercel*.tgz++# Local runtime artifacts produced by static-server / agent-server runs+workspace/+build-fresh/diff --git a/__tests__/api/agent-server-config.test.ts b/__tests__/api/agent-server-config.test.tsindex c80db9d33e..303db69edb 100644--- a/__tests__/api/agent-server-config.test.ts+++ b/__tests__/api/agent-server-config.test.ts@@ -6,6 +6,7 @@ import {getAgentServerFormDefaults,getAgentServerSessionApiKey,getAgentServerWorkingDir,+ getLockedCloudHost,isAuthRequired,isAuthRequiredAndMissing,} from "#/api/agent-server-config";@@ -24,6 +25,8 @@ afterEach(() => {vi.unstubAllEnvs();delete (window as unknown as Record<string, unknown>).__AGENT_CANVAS_SESSION_API_KEY__;+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_LOCK_TO_CLOUD__;Object.defineProperty(window, "location", {configurable: true,value: ORIGINAL_LOCATION,@@ -75,6 +78,45 @@ describe("agent server config", () => {});});+describe("getLockedCloudHost", () => {+ function setInjectedCloudHost(value: unknown) {+ (+ window as unknown as Record<string, unknown>+ ).__AGENT_CANVAS_LOCK_TO_CLOUD__ = value;+ }++ it("returns null when no Cloud lock is configured", () => {+ expect(getLockedCloudHost()).toBeNull();+ });++ it("uses VITE_LOCK_TO_CLOUD when it is provided", () => {+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://cloud.example.com/");+ setInjectedCloudHost("https://runtime.example.com");++ expect(getLockedCloudHost()).toBe("https://cloud.example.com");+ });++ it("falls back to the runtime-injected Cloud URL", () => {+ setInjectedCloudHost("https://runtime.example.com/");++ expect(getLockedCloudHost()).toBe("https://runtime.example.com");+ });++ it("adds https:// to hostnames without an explicit scheme", () => {+ setInjectedCloudHost("cloud.example.com/");++ expect(getLockedCloudHost()).toBe("https://cloud.example.com");+ });++ it("ignores blank and non-string runtime values", () => {+ setInjectedCloudHost(" ");+ expect(getLockedCloudHost()).toBeNull();++ setInjectedCloudHost(12345);+ expect(getLockedCloudHost()).toBeNull();+ });+});+describe("isAuthRequired", () => {afterEach(() => {delete (window as unknown as Record<string, unknown>)diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.tsindex b5d8e906e9..22fa9305fa 100644--- a/__tests__/api/agent-server-conversation-service.test.ts+++ b/__tests__/api/agent-server-conversation-service.test.ts@@ -82,6 +82,7 @@ vi.mock("#/api/agent-server-config", () => ({getAgentServerHeaders: vi.fn(() => ({ "X-Session-API-Key": "test-api-key" })),shouldLoadPublicSkills: vi.fn(() => true),syncBakedSessionApiKey: vi.fn(),+ getLockedCloudHost: vi.fn(() => null),}));vi.mock("#/api/settings-service/settings-service.api", () => ({diff --git a/__tests__/api/use-create-conversation-metadata.test.ts b/__tests__/api/use-create-conversation-metadata.test.tsindex 5c4c45fb3f..1033df95fd 100644--- a/__tests__/api/use-create-conversation-metadata.test.ts+++ b/__tests__/api/use-create-conversation-metadata.test.ts@@ -54,6 +54,7 @@ vi.mock("#/api/agent-server-config", () => ({),shouldLoadPublicSkills: vi.fn(() => true),syncBakedSessionApiKey: vi.fn(),+ getLockedCloudHost: vi.fn(() => null),}));vi.mock("#/api/settings-service/settings-service.api", () => ({diff --git a/__tests__/components/backends/backend-form-modal.test.tsx b/__tests__/components/backends/backend-form-modal.test.tsxindex 88a1f9026c..494d51c831 100644--- a/__tests__/components/backends/backend-form-modal.test.tsx+++ b/__tests__/components/backends/backend-form-modal.test.tsx@@ -69,6 +69,9 @@ beforeEach(() => {afterEach(() => {window.localStorage.clear();+ vi.unstubAllEnvs();+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_LOCK_TO_CLOUD__;__resetActiveStoreForTests();});@@ -128,14 +131,12 @@ describe("BackendFormModal โ edit mode (BackendForm entry point)", () => {renderWithProviders(<TestSeedonMount={(ctx) => {- backendId = ctx- .addBackend({- name: "Local Seed",- host: "http://localhost:9000",- apiKey: "sk-old",- kind: "local",- })- .id;+ backendId = ctx.addBackend({+ name: "Local Seed",+ host: "http://localhost:9000",+ apiKey: "sk-old",+ kind: "local",+ }).id;}}><BackendFormModal@@ -153,9 +154,7 @@ describe("BackendFormModal โ edit mode (BackendForm entry point)", () => {);await waitFor(() => {- expect(screen.getByTestId("edit-backend-name")).toHaveValue(- "Local Seed",- );+ expect(screen.getByTestId("edit-backend-name")).toHaveValue("Local Seed");});const user = userEvent.setup();@@ -187,14 +186,12 @@ describe("BackendFormModal โ edit mode (BackendForm entry point)", () => {renderWithProviders(<TestSeedonMount={(ctx) => {- backendId = ctx- .addBackend({- name: "Offline Server",- host: "http://localhost:9999",- apiKey: "sk-key",- kind: "local",- })- .id;+ backendId = ctx.addBackend({+ name: "Offline Server",+ host: "http://localhost:9999",+ apiKey: "sk-key",+ kind: "local",+ }).id;}}><BackendFormModal@@ -227,9 +224,9 @@ describe("BackendFormModal โ edit mode (BackendForm entry point)", () => {await user.click(screen.getByTestId("edit-backend-submit"));- expect(- await screen.findByTestId("edit-backend-error"),- ).toHaveTextContent("Connection refused");+ expect(await screen.findByTestId("edit-backend-error")).toHaveTextContent(+ "Connection refused",+ );});it("preserves cloud kind when editing a cloud backend", async () => {@@ -238,14 +235,12 @@ describe("BackendFormModal โ edit mode (BackendForm entry point)", () => {renderWithProviders(<TestSeedonMount={(ctx) => {- backendId = ctx- .addBackend({- name: "OpenHands Cloud",- host: "https://app.all-hands.dev",- apiKey: "sk-cloud",- kind: "cloud",- })- .id;+ backendId = ctx.addBackend({+ name: "OpenHands Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "sk-cloud",+ kind: "cloud",+ }).id;}}><BackendFormModal@@ -290,4 +285,21 @@ describe("BackendFormModal โ edit mode (BackendForm entry point)", () => {kind: "cloud",});});++ it("locks add mode to Cloud login when VITE_LOCK_TO_CLOUD is set", () => {+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://cloud.example.com");++ renderWithProviders(<BackendFormModal mode="add" onClose={vi.fn()} />);++ expect(screen.getByTestId("add-backend-cloud-title")).toBeVisible();+ expect(screen.getByTestId("add-backend-login-button")).toBeVisible();+ expect(screen.queryByTestId("add-backend-host")).not.toBeInTheDocument();+ expect(screen.queryByTestId("add-backend-api-key")).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("add-backend-advanced-toggle"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("add-backend-cloud-host"),+ ).not.toBeInTheDocument();+ });});diff --git a/__tests__/components/onboarding/onboarding-host.test.tsx b/__tests__/components/onboarding/onboarding-host.test.tsxnew file mode 100644index 0000000000..90627ac267--- /dev/null+++ b/__tests__/components/onboarding/onboarding-host.test.tsx@@ -0,0 +1,252 @@+import React from "react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { render, screen, waitFor } from "@testing-library/react";+import { MemoryRouter } from "react-router";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { OnboardingHost } from "#/components/features/onboarding/onboarding-host";+import { ONBOARDING_COMPLETED_STORAGE_KEY } from "#/components/features/onboarding/use-onboarding-completion";+import SettingsService from "#/api/settings-service/settings-service.api";+import { DEFAULT_SETTINGS } from "#/services/settings";+import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import { ActiveBackendProvider } from "#/contexts/active-backend-context";+import { NavigationProvider } from "#/context/navigation-context";++// We don't need to exercise the modal's internals here; just verify+// whether OnboardingHost mounts it at all.+vi.mock("#/components/features/onboarding/onboarding-modal", () => ({+ OnboardingModal: () => (+ <div data-testid="onboarding-modal-stub">onboarding modal</div>+ ),+}));++function renderHost() {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const navigationValue = {+ currentPath: "/",+ conversationId: null,+ isNavigating: false,+ navigate: vi.fn(),+ };+ return render(+ <QueryClientProvider client={queryClient}>+ <MemoryRouter initialEntries={["/"]}>+ <ActiveBackendProvider>+ <NavigationProvider value={navigationValue}>+ <OnboardingHost />+ </NavigationProvider>+ </ActiveBackendProvider>+ </MemoryRouter>+ </QueryClientProvider>,+ );+}++function seedCloudBackend() {+ const backend = {+ id: "cloud-backend",+ name: "OpenHands Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "cloud-session-key",+ kind: "cloud" as const,+ };+ setRegisteredBackends([backend]);+ setActiveSelection({ backendId: backend.id, orgId: null });+ return backend;+}++function seedUserAddedLocalBackend() {+ // A Local backend the user explicitly added via "Add Backend" โ its id+ // is NOT the launcher-seeded SEEDED_DEFAULT_BACKEND_ID, so the+ // "pre-configured server" skip is allowed to fire for it.+ const backend = {+ id: "user-added-local",+ name: "My Agent Server",+ host: "http://localhost:9000",+ apiKey: "session-key",+ kind: "local" as const,+ };+ setRegisteredBackends([backend]);+ setActiveSelection({ backendId: backend.id, orgId: null });+ return backend;+}++beforeEach(() => {+ window.localStorage.clear();+ vi.stubEnv("VITE_BACKEND_BASE_URL", "http://localhost:9000");+ vi.stubEnv("VITE_SESSION_API_KEY", "session-key");+ __resetActiveStoreForTests();+ vi.clearAllMocks();+});++afterEach(() => {+ window.localStorage.clear();+ vi.unstubAllEnvs();+ __resetActiveStoreForTests();+});++describe("OnboardingHost", () => {+ it("renders the onboarding modal for a fresh install with no configured LLM", async () => {+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue({+ ...DEFAULT_SETTINGS,+ llm_api_key_set: false,+ agent_settings: {+ ...DEFAULT_SETTINGS.agent_settings,+ llm: { model: "" },+ },+ });++ renderHost();++ expect(+ await screen.findByTestId("onboarding-modal-stub"),+ ).toBeInTheDocument();+ });++ it("skips the modal and marks completion for a returning Cloud user with a configured LLM", async () => {+ seedCloudBackend();+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue({+ ...DEFAULT_SETTINGS,+ llm_api_key_set: true,+ agent_settings: {+ ...DEFAULT_SETTINGS.agent_settings,+ llm: { model: "anthropic/claude-sonnet-4-5", api_key: "stored" },+ },+ });++ renderHost();++ await waitFor(() => {+ expect(+ window.localStorage.getItem(ONBOARDING_COMPLETED_STORAGE_KEY),+ ).not.toBeNull();+ });+ expect(screen.queryByTestId("onboarding-modal-stub")).toBeNull();+ });++ it("skips the modal when the active Cloud LLM uses subscription auth (no API key)", async () => {+ seedCloudBackend();+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue({+ ...DEFAULT_SETTINGS,+ llm_api_key_set: false,+ agent_settings: {+ ...DEFAULT_SETTINGS.agent_settings,+ llm: { model: "openai/gpt-5.5", auth_type: "subscription" },+ },+ });++ renderHost();++ await waitFor(() => {+ expect(+ window.localStorage.getItem(ONBOARDING_COMPLETED_STORAGE_KEY),+ ).not.toBeNull();+ });+ expect(screen.queryByTestId("onboarding-modal-stub")).toBeNull();+ });++ it("still shows the modal for a Cloud user when an API key is set but no model is configured", async () => {+ seedCloudBackend();+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue({+ ...DEFAULT_SETTINGS,+ llm_api_key_set: true,+ agent_settings: {+ ...DEFAULT_SETTINGS.agent_settings,+ llm: { model: "" },+ },+ });++ renderHost();++ expect(+ await screen.findByTestId("onboarding-modal-stub"),+ ).toBeInTheDocument();+ expect(+ window.localStorage.getItem(ONBOARDING_COMPLETED_STORAGE_KEY),+ ).toBeNull();+ });++ it("skips the modal for a user-added Local backend that already has an LLM configured (llm_api_key_is_set)", async () => {+ // When the user connects via Add Backend to an existing+ // agent-server that already has an LLM saved, walking them+ // through "Set up your LLM" would just overwrite the stored+ // value with a copy. Skip and persist completion. This only+ // applies to Local backends the user explicitly added (not the+ // launcher-seeded default-local โ see the next test).+ seedUserAddedLocalBackend();+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue({+ ...DEFAULT_SETTINGS,+ llm_api_key_is_set: true,+ agent_settings: {+ ...DEFAULT_SETTINGS.agent_settings,+ llm: { model: "openai/zai-org/GLM-5.2", api_key: "**********" },+ },+ });++ renderHost();++ await waitFor(() => {+ expect(+ window.localStorage.getItem(ONBOARDING_COMPLETED_STORAGE_KEY),+ ).not.toBeNull();+ });+ expect(screen.queryByTestId("onboarding-modal-stub")).toBeNull();+ });++ it("still shows the modal for a launcher-seeded default-local backend even when the agent-server reports a configured LLM", async () => {+ // Regression for the mock-LLM E2E fresh-install / happy-path tests:+ // the shared agent-server retains a previously-configured LLM across+ // browser sessions, so keying first-run onboarding off the server's+ // LLM state would suppress the modal for a genuinely fresh browser+ // install. The launcher-seeded default-local backend (id+ // SEEDED_DEFAULT_BACKEND_ID) must not trigger the skip โ the+ // `openhands-onboarded` localStorage flag stays the source of truth+ // for first-run detection there.+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue({+ ...DEFAULT_SETTINGS,+ llm_api_key_is_set: true,+ agent_settings: {+ ...DEFAULT_SETTINGS.agent_settings,+ llm: { model: "openai/zai-org/GLM-5.2", api_key: "**********" },+ },+ });++ renderHost();++ expect(+ await screen.findByTestId("onboarding-modal-stub"),+ ).toBeInTheDocument();+ expect(+ window.localStorage.getItem(ONBOARDING_COMPLETED_STORAGE_KEY),+ ).toBeNull();+ });++ it("still shows the modal for a fresh Local agent-server with no API key set", async () => {+ // The default agent-server schema returns a model name (e.g.+ // "gpt-5.5") but llm_api_key_is_set === false until the user+ // configures one. The modal must keep running the LLM step.+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue({+ ...DEFAULT_SETTINGS,+ llm_api_key_is_set: false,+ llm_api_key_set: false,+ agent_settings: {+ ...DEFAULT_SETTINGS.agent_settings,+ llm: { model: "gpt-5.5", api_key: null },+ },+ });++ renderHost();++ expect(+ await screen.findByTestId("onboarding-modal-stub"),+ ).toBeInTheDocument();+ expect(+ window.localStorage.getItem(ONBOARDING_COMPLETED_STORAGE_KEY),+ ).toBeNull();+ });+});diff --git a/__tests__/components/onboarding/onboarding-modal.test.tsx b/__tests__/components/onboarding/onboarding-modal.test.tsxindex 04bf53a812..8550abf507 100644--- a/__tests__/components/onboarding/onboarding-modal.test.tsx+++ b/__tests__/components/onboarding/onboarding-modal.test.tsx@@ -4,13 +4,19 @@ import { render, screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";+import {+ __resetActiveStoreForTests,+ getActiveSelection,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";import { ActiveBackendProvider } from "#/contexts/active-backend-context";import { OnboardingModal } from "#/components/features/onboarding/onboarding-modal";import { ONBOARDING_DEFAULT_LLM_MODEL } from "#/components/features/onboarding/steps/setup-llm-step";import { NavigationProvider } from "#/context/navigation-context";import SettingsService from "#/api/settings-service/settings-service.api";import { SecretsService } from "#/api/secrets-service";+import { DEFAULT_SETTINGS } from "#/services/settings";const llmSettingsScreenMock = vi.hoisted(() => vi.fn());const getServerInfoMock = vi.hoisted(() => vi.fn());@@ -59,6 +65,29 @@ vi.mock("#/routes/llm-settings", async () => {};});+vi.mock("#/components/features/backends/device-flow-auth", async () => {+ const React = await import("react");++ return {+ DeviceFlowAuth: ({+ onSuccess,+ testIdRoot,+ }: {+ onSuccess: (apiKey: string) => void;+ testIdRoot: string;+ }) =>+ React.createElement(+ "button",+ {+ type: "button",+ "data-testid": `${testIdRoot}-login-button`,+ onClick: () => onSuccess("cloud-session-key"),+ },+ "Login with OpenHands Cloud",+ ),+ };+});+vi.mock("#/components/features/automations/recommended-automations-launcher",() => ({@@ -99,19 +128,20 @@ vi.mock("#/hooks/query/use-acp-auth-status", () => ({}),}));-async function completeBackendStep(user: ReturnType<typeof userEvent.setup>) {+async function waitForConfiguredBackendToBeSkipped() {await waitFor(- () =>- expect(screen.getByTestId("onboarding-backend-connected")).toBeVisible(),- { timeout: 3000 },- );- await user.click(screen.getByTestId("onboarding-backend-next"));- await waitFor(- () =>+ () => {+ expect(screen.queryByTestId("onboarding-step-check-backend")).toBeNull();expect(screen.getByTestId("onboarding-modal")).toHaveAttribute("data-current-step",- "1",- ),+ "0",+ );+ expect(+ within(screen.getByTestId("onboarding-slide-0")).getByTestId(+ "onboarding-step-choose-agent",+ ),+ ).toBeInTheDocument();+ },{ timeout: 3000 },);}@@ -122,12 +152,25 @@ async function completeAgentStep(user: ReturnType<typeof userEvent.setup>) {() =>expect(screen.getByTestId("onboarding-modal")).toHaveAttribute("data-current-step",- "2",+ "1",),{ timeout: 3000 },);}+function seedCloudBackend() {+ const backend = {+ id: "cloud-backend",+ name: "OpenHands Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "cloud-session-key",+ kind: "cloud" as const,+ };+ setRegisteredBackends([backend]);+ setActiveSelection({ backendId: backend.id, orgId: null });+ return backend;+}+function renderModal(onClose = vi.fn()) {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },@@ -168,6 +211,13 @@ beforeEach(() => {// ChooseAgentStep's Next button now persists the selection via// saveSettings before advancing. Stub it so the rest of the flow// (which these tests focus on) isn't gated on a real HTTP call.+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue({+ ...DEFAULT_SETTINGS,+ agent_settings: {+ ...DEFAULT_SETTINGS.agent_settings,+ llm: {},+ },+ });vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);// The ACP secrets step lists existing secrets to flag "already saved"// fields. Stub the fetch so it doesn't reach a real client (none is@@ -183,7 +233,14 @@ afterEach(() => {});describe("OnboardingModal", () => {- it("starts on the backend step with each slide offset by its index", () => {+ it("starts no-backend first-run users on the backend step with each slide offset by its index", () => {+ window.localStorage.clear();+ vi.stubEnv("VITE_BACKEND_BASE_URL", "");+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__;+ __resetActiveStoreForTests();+renderModal();expect(screen.getByTestId("onboarding-modal")).toHaveAttribute(@@ -210,6 +267,23 @@ describe("OnboardingModal", () => {);});+ it("skips backend setup when the configured backend is already healthy", async () => {+ renderModal();++ await waitForConfiguredBackendToBeSkipped();+ expect(screen.getByTestId("onboarding-progress-bar")).toHaveAttribute(+ "aria-valuemax",+ "3",+ );+ expect(screen.getByTestId("onboarding-progress-step-2")).toHaveAttribute(+ "data-state",+ "upcoming",+ );+ expect(screen.queryByTestId("onboarding-progress-step-3")).toBeNull();+ expect(screen.queryByTestId("onboarding-agent-back")).toBeNull();+ expect(getServerInfoMock).toHaveBeenCalled();+ });+it("starts first-run no-backend onboarding as Add a backend without an error banner", () => {window.localStorage.clear();vi.stubEnv("VITE_BACKEND_BASE_URL", "");@@ -222,8 +296,8 @@ describe("OnboardingModal", () => {expect(screen.getByText("BACKEND$ADD_TITLE")).toBeInTheDocument();expect(- screen.getByText("ONBOARDING$ADD_BACKEND_SUBTITLE"),- ).toBeInTheDocument();+ screen.queryByTestId("onboarding-backend-subtitle"),+ ).not.toBeInTheDocument();expect(screen.queryByTestId("onboarding-backend-disconnected"),).not.toBeInTheDocument();@@ -234,16 +308,312 @@ describe("OnboardingModal", () => {expect(screen.getByTestId("onboarding-backend-login-button")).toBeVisible();});- it("shows a connection error when saving an unreachable backend", async () => {+ it("locks no-backend onboarding to Cloud login when VITE_LOCK_TO_CLOUD is set", () => {+ window.localStorage.clear();+ vi.stubEnv("VITE_BACKEND_BASE_URL", "");+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://cloud.example.com");+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__;+ __resetActiveStoreForTests();+renderModal();++ expect(+ screen.getByText("ONBOARDING$LOGIN_TO_CLOUD_TITLE"),+ ).toBeInTheDocument();+ expect(screen.queryByText("BACKEND$ADD_TITLE")).not.toBeInTheDocument();+ expect(screen.getByTestId("onboarding-backend-cloud-title")).toBeVisible();+ expect(screen.getByTestId("onboarding-backend-login-button")).toBeVisible();+ expect(+ screen.queryByTestId("onboarding-backend-host"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("onboarding-backend-api-key"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("onboarding-backend-advanced-toggle"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("onboarding-backend-cloud-host"),+ ).not.toBeInTheDocument();+ expect(screen.queryByTestId("onboarding-skip")).not.toBeInTheDocument();+ });++ it("dismisses the onboarding modal immediately after Cloud login in locked-to-Cloud mode without showing the next step", async () => {+ // Regression for hieptl's flicker report on PR #1389: after logging+ // into OpenHands Cloud in locked-to-Cloud mode, the onboarding modal+ // used to advance to the Choose Agent slide (the "next window"),+ // then get torn down by the root first-run gate, then briefly+ // remounted by OnboardingHost โ producing a visible flicker. Cloud+ // login IS the onboarding completion in locked mode, so the modal+ // must call `onClose` (dismiss) immediately instead of advancing,+ // so the next slide never shows.+ window.localStorage.clear();+ vi.stubEnv("VITE_BACKEND_BASE_URL", "");+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__;+ __resetActiveStoreForTests();++ const onClose = vi.fn();+ renderModal(onClose);const user = userEvent.setup();- await waitFor(() =>- expect(screen.getByTestId("onboarding-backend-connected")).toBeVisible(),+ await user.click(screen.getByTestId("onboarding-backend-login-button"));++ // Cloud login must dismiss the modal (not advance to Choose Agent).+ expect(onClose).toHaveBeenCalledTimes(1);+ // The stale-org reset still runs when replacing a mismatched host;+ // here there was no prior backend, so nothing to assert beyond+ // dismissal. The key contract: no slide advancement happened via+ // the Cloud login path. The backend step is what was visible at+ // click time, and the modal is now dismissing.+ });++ it("keeps the backend step visible for a reachable stale Local backend in locked-to-Cloud mode", async () => {+ // Regression for PR #1389 review: in locked-to-Cloud mode a reachable+ // stale Local backend (one persisted from a previous non-locked+ // session) must NOT skip `CheckBackendStep`. The user has to stay on+ // the backend slide so they can log into the locked Cloud host and+ // replace the stale backend, rather than continuing as Local.+ window.localStorage.clear();+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ const staleLocal = {+ id: "stale-local",+ name: "Local",+ host: "http://127.0.0.1:8000",+ apiKey: "stale-key",+ kind: "local" as const,+ };+ setRegisteredBackends([staleLocal]);+ setActiveSelection({ backendId: staleLocal.id, orgId: null });+ __resetActiveStoreForTests();++ renderModal();++ // The health probe succeeds for the stale Local backend, but the+ // backend slide must remain the active step (not skipped to agent+ // selection) because the backend is not the locked Cloud host.+ await waitFor(() => {+ expect(+ screen.getByTestId("onboarding-step-check-backend"),+ ).toBeInTheDocument();+ });+ expect(screen.getByTestId("onboarding-modal")).toHaveAttribute(+ "data-current-step",+ "0",);- await user.click(- screen.getByTestId("onboarding-backend-show-configuration"),+ expect(screen.getByTestId("onboarding-progress-step-0")).toHaveAttribute(+ "data-state",+ "current",+ );+ // Progress bar keeps all 4 steps (backend slide still in the flow).+ expect(screen.getByTestId("onboarding-progress-bar")).toHaveAttribute(+ "aria-valuemax",+ "4",+ );+ // The locked Cloud login UI must be presented for replacement, and+ // the connected-backend "Next" shortcut (which would let the user+ // advance with the stale Local backend still active) must NOT be+ // offered. Keeping the slide mounted is not enough on its own.+ expect(+ screen.getByText("ONBOARDING$LOGIN_TO_CLOUD_TITLE"),+ ).toBeInTheDocument();+ expect(screen.getByTestId("onboarding-backend-cloud-title")).toBeVisible();+ expect(screen.getByTestId("onboarding-backend-login-button")).toBeVisible();+ expect(+ screen.queryByTestId("onboarding-backend-show-configuration"),+ ).toBeNull();+ expect(screen.queryByTestId("onboarding-backend-next")).toBeNull();+ // The misleading "Connected" banner for the stale backend should+ // not render either; the user is being told to log into Cloud.+ expect(screen.queryByTestId("onboarding-backend-subtitle")).toBeNull();+ });++ it("keeps the backend step visible for a reachable Cloud backend on a different host in locked-to-Cloud mode", async () => {+ // A Cloud backend pointing at a host other than the locked Cloud host+ // must also keep `CheckBackendStep` visible โ `kind === "cloud"` alone+ // is not enough; the host must match the locked host (normalized).+ window.localStorage.clear();+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ const otherCloud = {+ id: "other-cloud",+ name: "Other Cloud",+ host: "https://other-cloud.example.com",+ apiKey: "other-token",+ kind: "cloud" as const,+ };+ setRegisteredBackends([otherCloud]);+ setActiveSelection({ backendId: otherCloud.id, orgId: null });+ __resetActiveStoreForTests();++ renderModal();++ await waitFor(() => {+ expect(+ screen.getByTestId("onboarding-step-check-backend"),+ ).toBeInTheDocument();+ });+ expect(screen.getByTestId("onboarding-modal")).toHaveAttribute(+ "data-current-step",+ "0",+ );+ expect(screen.getByTestId("onboarding-progress-bar")).toHaveAttribute(+ "aria-valuemax",+ "4",+ );+ });++ it("clears the stale active org_id when Cloud login replaces a mismatched Cloud backend", async () => {+ // Regression for PR #1389 review: replacing a mismatched Cloud+ // backend updates the backend row's host/apiKey, but the persisted+ // active org_id is keyed to the OLD host's org list. Leaving it in+ // place causes subsequent Cloud API calls to send an invalid+ // X-Org-Id to the locked Cloud host. After Cloud login completes,+ // active.orgId must be reset to null.+ window.localStorage.clear();+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ const otherCloud = {+ id: "other-cloud",+ name: "Other Cloud",+ host: "https://other-cloud.example.com",+ apiKey: "other-token",+ kind: "cloud" as const,+ };+ setRegisteredBackends([otherCloud]);+ setActiveSelection({+ backendId: otherCloud.id,+ orgId: "stale-org-from-other-host",+ });+ __resetActiveStoreForTests();+ expect(getActiveSelection()?.orgId).toBe("stale-org-from-other-host");++ renderModal();+ const user = userEvent.setup();++ await waitFor(() => {+ expect(+ screen.getByTestId("onboarding-backend-login-button"),+ ).toBeInTheDocument();+ });++ await user.click(screen.getByTestId("onboarding-backend-login-button"));++ await waitFor(() => {+ expect(getActiveSelection()?.orgId).toBeNull();+ });+ // The backend row was updated rather than added: still a single+ // entry, but now pointed at the locked Cloud host.+ expect(getActiveSelection()?.backendId).toBe(otherCloud.id);+ });++ it("skips the backend step in locked-to-Cloud mode when the active backend IS the locked Cloud host", async () => {+ // Positive control: when the active backend is the locked Cloud host+ // (and healthy), the backend slide is skipped exactly as before.+ window.localStorage.clear();+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ const lockedCloud = {+ id: "locked-cloud",+ name: "OpenHands Cloud",+ host: "https://app.all-hands.dev/",+ apiKey: "cloud-token",+ kind: "cloud" as const,+ };+ setRegisteredBackends([lockedCloud]);+ setActiveSelection({ backendId: lockedCloud.id, orgId: null });+ __resetActiveStoreForTests();++ renderModal();++ // Trailing slash on the stored host must normalize-match the locked+ // host, so the backend slide is skipped.+ await waitForConfiguredBackendToBeSkipped();+ expect(screen.getByTestId("onboarding-progress-bar")).toHaveAttribute(+ "aria-valuemax",+ "3",);+ });++ it("keeps users on Choose Agent after Cloud login in standard (non-locked) mode", async () => {+ // Regression for #1389 review feedback: in standard mode (no+ // VITE_LOCK_TO_CLOUD), the onboarding backend slide shows both the+ // manual column and the Cloud column. Completing Cloud login from+ // there used to land the user on the Set Up LLM slide because the+ // slide-rail renumbered when `skipBackendStep` flipped before the+ // post-flip step-decrement effect ran. Phase-based state must keep+ // them on Choose Agent regardless of the renumber.+ window.localStorage.clear();+ vi.stubEnv("VITE_BACKEND_BASE_URL", "");+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "");+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__;+ __resetActiveStoreForTests();++ renderModal();+ const user = userEvent.setup();++ // Both columns should be visible in standard mode.+ expect(screen.getByTestId("onboarding-backend-host")).toBeInTheDocument();+ expect(+ screen.getByTestId("onboarding-backend-login-button"),+ ).toBeInTheDocument();++ await user.click(screen.getByTestId("onboarding-backend-login-button"));++ await waitFor(() => {+ expect(screen.getByTestId("onboarding-modal")).toHaveAttribute(+ "data-current-step",+ "0",+ );+ expect(+ within(screen.getByTestId("onboarding-slide-0")).getByTestId(+ "onboarding-step-choose-agent",+ ),+ ).toBeInTheDocument();+ });+ expect(screen.getByTestId("onboarding-slide-0")).toHaveAttribute(+ "data-active",+ "true",+ );+ // The Set Up LLM slide is always mounted (transform-translated off-screen),+ // but it must not be the active slide after Cloud login completes.+ expect(screen.getByTestId("onboarding-slide-1")).toHaveAttribute(+ "data-active",+ "false",+ );+ });++ it("does not render an 'Or' divider between manual and Cloud columns", () => {+ // Regression for #1389 review feedback: the "Or" label between+ // BackendConnectionOptions' manual and Cloud columns is visually+ // redundant given the columns are already clearly separated and+ // both have prominent titles. It must not render.+ window.localStorage.clear();+ vi.stubEnv("VITE_BACKEND_BASE_URL", "");+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "");+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__;+ __resetActiveStoreForTests();++ renderModal();++ expect(screen.queryByText("BACKEND$LOGIN_OR")).toBeNull();+ });++ it("shows a connection error when saving an unreachable backend", async () => {+ window.localStorage.clear();+ vi.stubEnv("VITE_BACKEND_BASE_URL", "");+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__;+ __resetActiveStoreForTests();++ renderModal();+ const user = userEvent.setup();await user.clear(screen.getByTestId("onboarding-backend-host"));await user.type(@@ -278,60 +648,41 @@ describe("OnboardingModal", () => {);});- it("collapses backend configuration fields once connected until Show configuration is toggled", async () => {+ it("does not show backend configuration when the configured backend is healthy", async () => {renderModal();- const user = userEvent.setup();-- await waitFor(() =>- expect(screen.getByTestId("onboarding-backend-connected")).toBeVisible(),- );+ await waitForConfiguredBackendToBeSkipped();+ expect(screen.queryByTestId("onboarding-backend-connected")).toBeNull();expect(- within(- screen.getByTestId("onboarding-backend-configuration-fields"),- ).queryByTestId("onboarding-backend-connection-options"),- ).not.toBeInTheDocument();- expect(- screen.getByTestId("onboarding-backend-show-configuration"),- ).toBeInTheDocument();-- await user.click(- screen.getByTestId("onboarding-backend-show-configuration"),- );- expect(- within(- screen.getByTestId("onboarding-backend-configuration-fields"),- ).getByTestId("onboarding-backend-connection-options"),- ).toBeInTheDocument();- expect(screen.getByTestId("onboarding-backend-cloud-title")).toBeVisible();- expect(screen.getByTestId("onboarding-backend-login-button")).toBeVisible();+ screen.queryByTestId("onboarding-backend-configuration-fields"),+ ).toBeNull();});it("advances each step via the per-step Next button and reframes slide offsets", async () => {renderModal();const user = userEvent.setup();- // Step 0 โ 1. Once the backend health probe resolves, step 0's Next is enabled.- await completeBackendStep(user);- expect(screen.getByTestId("onboarding-slide-1")).toHaveAttribute(+ // Healthy configured backends are skipped, so agent selection is step 0.+ await waitForConfiguredBackendToBeSkipped();+ expect(screen.getByTestId("onboarding-slide-0")).toHaveAttribute("data-active","true",);- // Step 1 โ 2. ChooseAgentStep does an async save before advancing.+ // Step 0 โ 1. ChooseAgentStep does an async save before advancing.await completeAgentStep(user);- expect(screen.getByTestId("onboarding-slide-2")).toHaveAttribute(+ expect(screen.getByTestId("onboarding-slide-1")).toHaveAttribute("data-active","true",);- // Step 2 โ 3+ // Step 1 โ 2await user.click(screen.getByTestId("onboarding-llm-next"));expect(screen.getByTestId("onboarding-modal")).toHaveAttribute("data-current-step",- "3",+ "2",);- expect(screen.getByTestId("onboarding-slide-3")).toHaveAttribute(+ expect(screen.getByTestId("onboarding-slide-2")).toHaveAttribute("data-active","true",);@@ -383,7 +734,7 @@ describe("OnboardingModal", () => {// Arrange: render the modal and walk through to the LLM step.renderModal();const user = userEvent.setup();- await completeBackendStep(user);+ await waitForConfiguredBackendToBeSkipped();await completeAgentStep(user);// Wait for the LLM slide to become the active one before querying// by role โ otherwise the heading is `aria-hidden` from inside a@@ -392,7 +743,7 @@ describe("OnboardingModal", () => {() =>expect(screen.getByTestId("onboarding-modal")).toHaveAttribute("data-current-step",- "2",+ "1",),{ timeout: 3000 },);@@ -407,6 +758,7 @@ describe("OnboardingModal", () => {// Assert: heading and footer buttons are siblings of the settings// body, not descendants. Anything moved inside the settings wrapper+// would scroll out of view on the All tab โ this is the invariant// the fix relies on.expect(settings.contains(heading)).toBe(false);@@ -414,26 +766,37 @@ describe("OnboardingModal", () => {expect(settings.contains(next)).toBe(false);});- it("shows slide 2 with Gemini's credential fields", async () => {+ it("hides the Say Hello OR separator when recommended automations are unavailable on Cloud", () => {+ seedCloudBackend();++ renderModal();++ expect(screen.queryByTestId("onboarding-hello-or-separator")).toBeNull();+ expect(+ screen.queryByTestId("onboarding-recommended-automations"),+ ).toBeNull();+ });++ it("shows the setup slide with Gemini's credential fields", async () => {renderModal();const user = userEvent.setup();// Pick Gemini CLI: its key/base-URL come from the SDK registry like the// other providers, so the slide shows the GEMINI_API_KEY field.- await completeBackendStep(user);+ await waitForConfiguredBackendToBeSkipped();await user.click(screen.getByTestId("onboarding-agent-option-gemini-cli"));await completeAgentStep(user);- // Lands on slide 2 (the ACP step) โ not jumped past to Say Hello.+ // Lands on the setup slide (the ACP step) โ not jumped past to Say Hello.await waitFor(() =>expect(screen.getByTestId("onboarding-modal")).toHaveAttribute("data-current-step",- "2",+ "1",),{ timeout: 3000 },);- expect(screen.getByTestId("onboarding-slide-2")).toHaveAttribute(+ expect(screen.getByTestId("onboarding-slide-1")).toHaveAttribute("data-active","true",);@@ -446,36 +809,37 @@ describe("OnboardingModal", () => {screen.getByTestId("onboarding-acp-secret-GEMINI_API_KEY"),).toBeInTheDocument();- // The flow keeps all four progress segments (nothing is skipped).+ // The flow skips backend setup and keeps three progress segments.expect(- screen.getByTestId("onboarding-progress-step-3"),+ screen.getByTestId("onboarding-progress-step-2"),).toBeInTheDocument();- expect(screen.getByTestId("onboarding-progress-step-2")).toHaveAttribute(+ expect(screen.queryByTestId("onboarding-progress-step-3")).toBeNull();+ expect(screen.getByTestId("onboarding-progress-step-1")).toHaveAttribute("data-state","current",);});- it("shows the ACP credentials step on slide 2 for Claude Code and saves entered keys as secrets", async () => {+ it("shows the ACP credentials step for Claude Code and saves entered keys as secrets", async () => {renderModal();const user = userEvent.setup();// Pick Claude Code after configuring the backend.- await completeBackendStep(user);+ await waitForConfiguredBackendToBeSkipped();await user.click(screen.getByTestId("onboarding-agent-option-claude-code"));await completeAgentStep(user);- // Slide 2 is the ACP credentials step (not skipped), so the flow keeps- // all 4 progress segments and slide 2 โ not Say Hello โ is now active.+ // The setup slide is the ACP credentials step โ not Say Hello โ after+ // skipping the already healthy backend.await waitFor(() =>expect(screen.getByTestId("onboarding-modal")).toHaveAttribute("data-current-step",- "2",+ "1",),{ timeout: 3000 },);- expect(screen.getByTestId("onboarding-slide-2")).toHaveAttribute(+ expect(screen.getByTestId("onboarding-slide-1")).toHaveAttribute("data-active","true",);@@ -483,8 +847,9 @@ describe("OnboardingModal", () => {screen.getByTestId("onboarding-step-setup-acp-secrets"),).toBeInTheDocument();expect(- screen.getByTestId("onboarding-progress-step-3"),+ screen.getByTestId("onboarding-progress-step-2"),).toBeInTheDocument();+ expect(screen.queryByTestId("onboarding-progress-step-3")).toBeNull();// Both Anthropic credentials are offered; the optional base URL too.const apiKeyField = screen.getByTestId(@@ -511,7 +876,7 @@ describe("OnboardingModal", () => {() =>expect(screen.getByTestId("onboarding-modal")).toHaveAttribute("data-current-step",- "3",+ "2",),{ timeout: 3000 },);@@ -521,14 +886,14 @@ describe("OnboardingModal", () => {renderModal();const user = userEvent.setup();- await completeBackendStep(user);+ await waitForConfiguredBackendToBeSkipped();await user.click(screen.getByTestId("onboarding-agent-option-codex"));await completeAgentStep(user);await waitFor(() =>expect(screen.getByTestId("onboarding-modal")).toHaveAttribute("data-current-step",- "2",+ "1",),{ timeout: 3000 },);@@ -540,18 +905,18 @@ describe("OnboardingModal", () => {() =>expect(screen.getByTestId("onboarding-modal")).toHaveAttribute("data-current-step",- "3",+ "2",),{ timeout: 3000 },);expect(SecretsService.createSecret).not.toHaveBeenCalled();});- it("pre-fills the say-hello input with the default greeting on step 3", async () => {+ it("pre-fills the say-hello input with the default greeting on the final step", async () => {renderModal();const user = userEvent.setup();- await completeBackendStep(user);+ await waitForConfiguredBackendToBeSkipped();await completeAgentStep(user);await user.click(screen.getByTestId("onboarding-llm-next"));@@ -570,17 +935,17 @@ describe("OnboardingModal", () => {renderModal(onClose);const user = userEvent.setup();- await completeBackendStep(user);+ await waitForConfiguredBackendToBeSkipped();await completeAgentStep(user);await waitFor(() =>- expect(screen.getByTestId("onboarding-slide-2")).toHaveAttribute(+ expect(screen.getByTestId("onboarding-slide-1")).toHaveAttribute("data-active","true",),);await user.click(screen.getByTestId("onboarding-llm-next"));await waitFor(() =>- expect(screen.getByTestId("onboarding-slide-3")).toHaveAttribute(+ expect(screen.getByTestId("onboarding-slide-2")).toHaveAttribute("data-active","true",),diff --git a/__tests__/root.test.tsx b/__tests__/root.test.tsxindex a591a3ed3f..f44ba0bc32 100644--- a/__tests__/root.test.tsx+++ b/__tests__/root.test.tsx@@ -76,6 +76,8 @@ describe("App root agent-server availability guard", () => {vi.unstubAllEnvs();delete (window as unknown as Record<string, unknown>).__AGENT_CANVAS_AUTH_REQUIRED__;+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_LOCK_TO_CLOUD__;(window as unknown as Record<string, unknown>).__AGENT_CANVAS_SESSION_API_KEY__ = "test-session-key";@@ -106,6 +108,247 @@ describe("App root agent-server availability guard", () => {).not.toBeInTheDocument();});+ it("shows first-run onboarding before the recovery modal when locked to Cloud with no backend", async () => {+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__;+ window.localStorage.clear();+ __resetActiveStoreForTests();++ renderApp(["/"]);++ await waitFor(() => {+ expect(+ screen.getByTestId("first-run-onboarding-screen"),+ ).toBeInTheDocument();+ });+ expect(await screen.findByTestId("onboarding-modal")).toBeInTheDocument();+ expect(+ screen.queryByTestId("agent-server-onboarding-screen"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("manage-backends-modal"),+ ).not.toBeInTheDocument();+ });++ it("shows first-run onboarding when locked to Cloud even if a session API key is baked in", async () => {+ // Reproduces Hiep's report on PR #1389: a pre-built bundle with a baked-in+ // VITE_SESSION_API_KEY plus --lock-to-cloud used to seed a disconnected+ // Local backend, which skipped onboarding and landed on the Manage Backends+ // recovery modal. Locked mode must not seed a Local backend, so onboarding+ // still owns the first-run Cloud login.+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ vi.stubEnv("VITE_SESSION_API_KEY", "baked-session-key");+ (+ window as unknown as Record<string, unknown>+ ).__AGENT_CANVAS_SESSION_API_KEY__ = "baked-session-key";+ window.localStorage.clear();+ __resetActiveStoreForTests();++ renderApp(["/"]);++ await waitFor(() => {+ expect(+ screen.getByTestId("first-run-onboarding-screen"),+ ).toBeInTheDocument();+ });+ expect(await screen.findByTestId("onboarding-modal")).toBeInTheDocument();+ expect(+ screen.queryByTestId("agent-server-onboarding-screen"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("manage-backends-modal"),+ ).not.toBeInTheDocument();+ // No Local backend should have been seeded into the registry.+ expect(window.localStorage.getItem("openhands-backends")).toBeNull();+ });++ it("shows first-run onboarding when locked to Cloud with a stale persisted Local backend", async () => {+ // A Local backend persisted from a previous non-locked session must not+ // bypass onboarding once the deployment is locked to Cloud.+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__;+ window.localStorage.setItem(+ "openhands-backends",+ JSON.stringify([+ {+ id: "default-local",+ name: "Local",+ host: "http://127.0.0.1:8000",+ apiKey: "stale-key",+ kind: "local",+ },+ ]),+ );+ window.localStorage.setItem(+ "openhands-active-backend",+ JSON.stringify({ backendId: "default-local", orgId: null }),+ );+ __resetActiveStoreForTests();++ renderApp(["/"]);++ await waitFor(() => {+ expect(+ screen.getByTestId("first-run-onboarding-screen"),+ ).toBeInTheDocument();+ });+ expect(await screen.findByTestId("onboarding-modal")).toBeInTheDocument();+ expect(+ screen.queryByTestId("manage-backends-modal"),+ ).not.toBeInTheDocument();+ });++ it("forces first-run onboarding in locked mode even when a stale Local backend reports a configured LLM", async () => {+ // Critical regression for PR #1389 review: in locked-to-Cloud mode the+ // ready-backend fast-path must NOT skip onboarding for a reachable+ // stale Local backend that happens to report a configured LLM. The+ // fast-path may only fire when the active backend IS the locked Cloud+ // host; otherwise the user must be routed through the Cloud login /+ // replacement flow. Here the agent-server (stale Local backend) reports+ // `llm_api_key_is_set: true` and a configured model, which previously+ // made `isBackendLlmReady` true and bypassed onboarding entirely.+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__;+ window.localStorage.setItem(+ "openhands-backends",+ JSON.stringify([+ {+ id: "user-added-local",+ name: "My agent-server",+ host: "http://127.0.0.1:8000",+ apiKey: "stale-key",+ kind: "local",+ },+ ]),+ );+ window.localStorage.setItem(+ "openhands-active-backend",+ JSON.stringify({ backendId: "user-added-local", orgId: null }),+ );+ __resetActiveStoreForTests();+ server.use(+ http.get("*/api/settings", () =>+ HttpResponse.json({+ llm_api_key_is_set: true,+ agent_settings: {+ llm: { model: "openai/gpt-5.5", api_key: "stored" },+ },+ }),+ ),+ http.get("*/server_info", () =>+ HttpResponse.json({ uptime: 0, idle_time: 0, version: "1.28.1" }),+ ),+ );++ renderApp(["/"]);++ await waitFor(() => {+ expect(+ screen.getByTestId("first-run-onboarding-screen"),+ ).toBeInTheDocument();+ });+ expect(await screen.findByTestId("onboarding-modal")).toBeInTheDocument();+ expect(+ screen.queryByTestId("manage-backends-modal"),+ ).not.toBeInTheDocument();+ // The ready-backend fast-path must NOT have persisted completion.+ expect(+ window.localStorage.getItem(ONBOARDING_COMPLETED_STORAGE_KEY),+ ).toBeNull();+ });++ it("forces first-run onboarding in locked mode when a Cloud backend points at a different host with a configured LLM", async () => {+ // Companion to the stale-Local test: a Cloud backend on a *different*+ // host than the locked Cloud host must also be forced through+ // onboarding, even if it reports a configured LLM. `kind === "cloud"`+ // alone is not enough โ the host must match the locked host.+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__;+ const otherCloud = {+ id: "other-cloud",+ name: "Other Cloud",+ host: "https://other-cloud.example.com",+ apiKey: "other-token",+ kind: "cloud",+ };+ window.localStorage.setItem(+ "openhands-backends",+ JSON.stringify([otherCloud]),+ );+ window.localStorage.setItem(+ "openhands-active-backend",+ JSON.stringify({ backendId: otherCloud.id, orgId: null }),+ );+ __resetActiveStoreForTests();+ server.use(+ http.get("*/api/settings", () =>+ HttpResponse.json({+ llm_api_key_set: true,+ agent_settings: {+ llm: { model: "openai/gpt-5.5" },+ },+ }),+ ),+ http.get("*/server_info", () =>+ HttpResponse.json({ uptime: 0, idle_time: 0, version: "1.28.1" }),+ ),+ );++ renderApp(["/"]);++ await waitFor(() => {+ expect(+ screen.getByTestId("first-run-onboarding-screen"),+ ).toBeInTheDocument();+ });+ expect(await screen.findByTestId("onboarding-modal")).toBeInTheDocument();+ expect(+ window.localStorage.getItem(ONBOARDING_COMPLETED_STORAGE_KEY),+ ).toBeNull();+ });++ it("shows first-run onboarding when locked to Cloud even if onboarding was previously completed", async () => {+ // Reproduces hieptl's report on PR #1389: the user had previously+ // completed onboarding in a non-locked session (so the+ // `openhands-onboarded` localStorage flag is set), then relaunched the+ // static server with --lock-to-cloud. The stale completion flag used to+ // suppress first-run onboarding, so the app fell through to the Manage+ // Backends recovery modal ("Add Backend") instead of going straight to+ // Cloud login. In locked-to-Cloud mode the completion flag must not+ // bypass onboarding when the active backend is not a connected Cloud+ // backend.+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ 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");+ __resetActiveStoreForTests();++ renderApp(["/"]);++ await waitFor(() => {+ expect(+ screen.getByTestId("first-run-onboarding-screen"),+ ).toBeInTheDocument();+ });+ expect(await screen.findByTestId("onboarding-modal")).toBeInTheDocument();+ expect(+ screen.queryByTestId("agent-server-onboarding-screen"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("manage-backends-modal"),+ ).not.toBeInTheDocument();+ });+it("shows the auth gate after onboarding was already completed", async () => {vi.stubEnv("VITE_AUTH_REQUIRED", "true");vi.stubEnv("VITE_SESSION_API_KEY", "");@@ -246,6 +489,112 @@ describe("App root agent-server availability guard", () => {screen.queryByTestId("agent-server-onboarding-screen"),).not.toBeInTheDocument();});++ it("does not mark onboarding complete for the launcher-seeded default-local backend even when the agent-server reports a configured LLM", async () => {+ // Regression for mock-llm-onboarding-regressions.spec.ts:16+ // ("keeps the modal open on backdrop click and Escape") and+ // mock-llm-auth-modes.spec.ts:57 ("reaches the onboarding modal+ // without pre-seeded localStorage"). The shared mock-LLM+ // agent-server retains a previously-configured LLM across browser+ // sessions, so a genuinely fresh browser install (launcher-seeded+ // default-local backend, no `openhands-onboarded` flag) must NOT+ // have onboarding auto-marked complete by the returning-user+ // fast-path. The settings-based LLM-ready signal is unreliable for+ // the launcher-seeded default backend and must be suppressed there.+ vi.stubEnv("VITE_BACKEND_BASE_URL", "http://127.0.0.1:8000");+ vi.stubEnv("VITE_SESSION_API_KEY", "test-session-key");+ // The launcher-seeded default-local backend (id+ // SEEDED_DEFAULT_BACKEND_ID) is created from these env stubs by+ // readStoredBackends().+ __resetActiveStoreForTests();+ server.use(+ http.get("*/api/settings", () =>+ HttpResponse.json({+ llm_api_key_is_set: true,+ agent_settings: {+ llm: { model: "openai/gpt-5.5", api_key: "stored" },+ },+ }),+ ),+ http.get("*/server_info", () =>+ HttpResponse.json({ uptime: 0, idle_time: 0, version: "1.28.1" }),+ ),+ );++ renderApp(["/"]);++ await waitFor(() => {+ expect(screen.getByTestId("app-outlet")).toBeInTheDocument();+ });++ // The returning-user fast-path must NOT have persisted completion.+ expect(+ window.localStorage.getItem(ONBOARDING_COMPLETED_STORAGE_KEY),+ ).toBeNull();+ });++ it("hides first-run onboarding immediately after Cloud login completes in locked-to-Cloud mode (no flicker)", async () => {+ // Regression for hieptl's flicker report on PR #1389: after Cloud+ // login succeeds in locked-to-Cloud mode, the onboarding modal's+ // onClose marks onboarding complete. The root first-run gate must+ // honor that completion IMMEDIATELY โ without waiting for the Cloud+ // settings probe to confirm a configured LLM โ so the first-run+ // screen disappears and the routed app renders, rather than the+ // modal flickering back via OnboardingHost. This test simulates the+ // post-login state (active locked Cloud backend + completion flag+ // set by the modal's onClose) with the Cloud settings probe+ // reporting NO configured LLM, which is exactly the window where+ // the old gate (`!isActiveLockedCloudBackend || !backendLlmReady`)+ // kept the first-run screen mounted and caused the reopen.+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ vi.stubEnv("VITE_SESSION_API_KEY", "");+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_SESSION_API_KEY__;+ const lockedCloud = {+ id: "locked-cloud",+ name: "OpenHands Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "cloud-session-key",+ kind: "cloud",+ };+ window.localStorage.setItem(+ "openhands-backends",+ JSON.stringify([lockedCloud]),+ );+ window.localStorage.setItem(+ "openhands-active-backend",+ JSON.stringify({ backendId: lockedCloud.id, orgId: null }),+ );+ // The onboarding modal's onClose (markCompleted) sets this right+ // after Cloud login succeeds โ before the Cloud settings probe+ // resolves. Seed it to reproduce the post-login moment.+ window.localStorage.setItem(ONBOARDING_COMPLETED_STORAGE_KEY, "1");+ __resetActiveStoreForTests();+ // Cloud settings probe reports no configured LLM. This is the+ // critical condition: the old gate treated `!backendLlmReady` as+ // "keep showing first-run onboarding" even though the user had+ // just finished Cloud login, so the modal reappeared.+ server.use(+ http.get("https://app.all-hands.dev/api/v1/settings", () =>+ HttpResponse.json({ llm_api_key_set: false }),+ ),+ http.get("https://app.all-hands.dev/api/keys/current", () =>+ HttpResponse.json({ org_id: "org-1" }),+ ),+ );++ renderApp(["/"]);++ // The first-run onboarding screen must NOT be mounted (no reopen),+ // and the routed app must render instead.+ await waitFor(() => {+ expect(screen.getByTestId("app-outlet")).toBeInTheDocument();+ });+ expect(+ screen.queryByTestId("first-run-onboarding-screen"),+ ).not.toBeInTheDocument();+ expect(screen.queryByTestId("onboarding-modal")).not.toBeInTheDocument();+ });});describe("App root document links", () => {diff --git a/__tests__/scripts/static-server.test.ts b/__tests__/scripts/static-server.test.tsindex 6548aa4284..4b8e52313c 100644--- a/__tests__/scripts/static-server.test.ts+++ b/__tests__/scripts/static-server.test.ts@@ -4,10 +4,7 @@ import { tmpdir } from "node:os";import path from "node:path";import { afterEach, describe, expect, it } from "vitest";-import {- parseArgs,- startStaticServer,-} from "../../scripts/static-server.mjs";+import { parseArgs, startStaticServer } from "../../scripts/static-server.mjs";describe("static-server.mjs", () => {const servers: Server[] = [];@@ -66,6 +63,24 @@ describe("static-server.mjs", () => {expect(config.runtimeServicesInfo).toBeNull();});+ it("defaults lockToCloud to null", () => {+ const config = parseArgs([]);+ expect(config.lockToCloud).toBeNull();+ });++ it("parses --lock-to-cloud", () => {+ const config = parseArgs([+ "--lock-to-cloud",+ "https://cloud.example.com",+ ]);+ expect(config.lockToCloud).toBe("https://cloud.example.com");+ });++ it("treats empty string as null for lockToCloud", () => {+ const config = parseArgs(["--lock-to-cloud", ""]);+ expect(config.lockToCloud).toBeNull();+ });+it("parses --runtime-services-info", () => {const json = '{"mode":"docker"}';const config = parseArgs(["--runtime-services-info", json]);@@ -151,6 +166,61 @@ describe("static-server.mjs", () => {});});+ describe("lock-to-cloud injection", () => {+ async function startServerLockedToCloud(dir: string, lockToCloud: string) {+ const server = await startStaticServer({+ port: 0,+ host: "127.0.0.1",+ dir,+ routes: {},+ lockToCloud,+ });+ servers.push(server);+ const address = server.address();+ if (!address || typeof address === "string") {+ throw new Error("Static server did not bind to a TCP port");+ }+ return `http://127.0.0.1:${address.port}`;+ }++ it("exposes the locked Cloud URL on window.__AGENT_CANVAS_LOCK_TO_CLOUD__", 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 startServerLockedToCloud(+ buildDir,+ "https://cloud.example.com",+ );+ const body = await (await fetch(`${origin}/`)).text();++ expect(body).toContain("window.__AGENT_CANVAS_LOCK_TO_CLOUD__");+ expect(body).toContain('"https://cloud.example.com"');+ });++ it("injects lock-to-cloud into SPA fallback index.html", 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 startServerLockedToCloud(+ buildDir,+ "https://cloud.example.com",+ );+ const response = await fetch(`${origin}/some/deep/route`);+ const body = await response.text();++ expect(response.status).toBe(200);+ expect(body).toContain("__AGENT_CANVAS_LOCK_TO_CLOUD__");+ });+ });+describe("session key injection", () => {async function startServerWithKey(dir: string, sessionApiKey: string) {const server = await startStaticServer({diff --git a/scripts/static-server.mjs b/scripts/static-server.mjsindex 5f7997755f..1582852e1e 100644--- a/scripts/static-server.mjs+++ b/scripts/static-server.mjs@@ -76,6 +76,7 @@ export function parseArgs(argv = process.argv.slice(2)) {sessionApiKey: null,authRequired: false,runtimeServicesInfo: null,+ lockToCloud: null,};for (let i = 0; i < argv.length; i++) {@@ -114,6 +115,10 @@ export function parseArgs(argv = process.argv.slice(2)) {case "--runtime-services-info":config.runtimeServicesInfo = argv[++i] || null;break;+ case "--lock-to-cloud":+ config.lockToCloud = argv[++i] || null;+ break;+case "--auth-required":config.authRequired = true;break;@@ -177,6 +182,9 @@ OPTIONS:frontend can populate the agent's<RUNTIME_SERVICES> system-prompt block withoutVITE_RUNTIME_SERVICES_INFO baked in.+ --lock-to-cloud <cloud-url> Lock backend setup to a single OpenHands Cloud+ URL. Hides manual/local backend setup and the+ custom Cloud URL field in the pre-built frontend.--reject-prefix <prefix> Return 503 for requests matching <prefix>instead of SPA-fallbacking to index.html;may be repeated. Useful in --frontend-only@@ -225,11 +233,17 @@ ROUTING:* `parseRuntimeServicesInfo()` in `agent-server-adapter.ts` as a fallback* when `VITE_RUNTIME_SERVICES_INFO` is empty, so static builds (Docker /* published binary) still populate the agent's `<RUNTIME_SERVICES>` block.+ *+ * - `lockToCloud`: an OpenHands Cloud URL exposed as+ * `window.__AGENT_CANVAS_LOCK_TO_CLOUD__`. Read by `getLockedCloudHost()` in+ * `agent-server-config.ts` so pre-built frontend bundles can hide manual+ * backend setup and the custom Cloud URL field at runtime.*/function makeConfigInjectionScript(sessionApiKey,authRequired,runtimeServicesInfo,+ lockToCloud,) {const parts = [];@@ -267,6 +281,12 @@ function makeConfigInjectionScript();}+ if (lockToCloud) {+ parts.push(+ `window.__AGENT_CANVAS_LOCK_TO_CLOUD__=${JSON.stringify(lockToCloud)};`,+ );+ }+if (parts.length === 0) return "";return `<script>(function(){${parts.join("")}}());</script>`;@@ -280,7 +300,7 @@ async function serveInjectedIndexHtml(req,res,indexPath,- { sessionApiKey, authRequired, runtimeServicesInfo } = {},+ { sessionApiKey, authRequired, runtimeServicesInfo, lockToCloud } = {},) {let content;try {@@ -293,6 +313,7 @@ async function serveInjectedIndexHtml(sessionApiKey,authRequired,runtimeServicesInfo,+ lockToCloud,);// Inject right before </head> so the key is available before any app code runs.// replace() targets the first (and only) </head> in well-formed HTML.@@ -417,11 +438,17 @@ function proxyWebSocket(req, socket, head, backendUrl) {// EPIPE) during test cleanup doesn't crash the process with an// uncaught 'error' event.proxySocket.on("error", (err) => {- console.error(`WebSocket proxy backend socket error (${req.url}):`, err.message);+ console.error(+ `WebSocket proxy backend socket error (${req.url}):`,+ err.message,+ );socket.destroy();});socket.on("error", (err) => {- console.error(`WebSocket proxy client socket error (${req.url}):`, err.message);+ console.error(+ `WebSocket proxy client socket error (${req.url}):`,+ err.message,+ );proxySocket.destroy();});proxySocket.pipe(socket, { end: true });@@ -548,7 +575,8 @@ async function handleStatic(const needsInjection =injectionOpts.sessionApiKey ||injectionOpts.authRequired ||- injectionOpts.runtimeServicesInfo;+ injectionOpts.runtimeServicesInfo ||+ injectionOpts.lockToCloud;// Serve index.html with runtime config injection when configured.if (needsInjection && filePath.endsWith("index.html")) {@@ -602,6 +630,7 @@ export function startStaticServer(config) {sessionApiKey: config.sessionApiKey || null,authRequired: config.authRequired || false,runtimeServicesInfo: config.runtimeServicesInfo || null,+ lockToCloud: config.lockToCloud || null,};const rejectPrefixes = config.rejectPrefixes ?? [];@@ -611,13 +640,15 @@ export function startStaticServer(config) {proxyRequest(req, res, backend);return;}- handleStatic(req, res, dirAbs, injectionOpts, rejectPrefixes).catch((err) => {- console.error(`Static handler error for ${req.url}:`, err);- if (!res.headersSent) {- res.writeHead(500);- res.end("Internal Server Error");- }- });+ handleStatic(req, res, dirAbs, injectionOpts, rejectPrefixes).catch(+ (err) => {+ console.error(`Static handler error for ${req.url}:`, err);+ if (!res.headersSent) {+ res.writeHead(500);+ res.end("Internal Server Error");+ }+ },+ );});server.on("upgrade", (req, socket, head) => {@@ -647,6 +678,9 @@ export function startStaticServer(config) {console.log(` ${prefix} -> 503 (rejected)`);}}+ if (config.lockToCloud) {+ console.log(` Backend setup locked to Cloud: ${config.lockToCloud}`);+ }console.log(" * (default) -> static files + SPA fallback");console.log("");resolveListen(server);diff --git a/src/api/agent-server-config.ts b/src/api/agent-server-config.tsindex bfd0aa35b8..fba4d7c518 100644--- a/src/api/agent-server-config.ts+++ b/src/api/agent-server-config.ts@@ -5,6 +5,12 @@ export interface AgentServerFormDefaults {sessionApiKey: string;}+// Window-global key the static server injects `--lock-to-cloud` into; kept+// module-private because only `getLockedCloudHost()` reads it. The static+// server (`scripts/static-server.mjs`) and its tests reference the literal+// string directly, not this constant.+const LOCK_TO_CLOUD_WINDOW_KEY = "__AGENT_CANVAS_LOCK_TO_CLOUD__";+function trimToNull(value?: string | null): string | null {return value?.trim() || null;}@@ -26,6 +32,19 @@ function normalizeBaseUrl(value?: string | null): string | null {return `http://${trimmed}`;}+function normalizeCloudHost(value?: string | null): string | null {+ if (!value) return null;++ const trimmed = value.trim().replace(/\/+$/, "");+ if (!trimmed) return null;++ if (/^https?:\/\//i.test(trimmed)) {+ return trimmed;+ }++ return `https://${trimmed}`;+}+function getConfiguredBaseUrl(): string | null {return normalizeBaseUrl(import.meta.env.VITE_BACKEND_BASE_URL);}@@ -69,6 +88,42 @@ export function getAgentServerFormDefaults(): AgentServerFormDefaults {};}+export function getLockedCloudHost(): string | null {+ const envHost = normalizeCloudHost(import.meta.env.VITE_LOCK_TO_CLOUD);+ if (envHost) return envHost;++ if (typeof window !== "undefined") {+ const injected = (window as unknown as Record<string, unknown>)[+ LOCK_TO_CLOUD_WINDOW_KEY+ ];+ if (typeof injected === "string") {+ return normalizeCloudHost(injected);+ }+ }++ return null;+}++/**+ * Compare a backend host against the locked Cloud host, normalizing+ * trailing slashes, protocol, and case so that e.g.+ * `https://app.all-hands.dev/` matches `https://app.all-hands.dev`.+ *+ * Used by the locked-to-Cloud gates (`root.tsx`,+ * `onboarding-modal.tsx`) to decide whether the active backend is the+ * configured locked Cloud host โ a Cloud backend on a *different* host+ * (or a stale Local backend) must not be treated as the locked backend.+ */+export function isSameCloudHost(+ host: string | null | undefined,+ lockedHost: string | null | undefined,+): boolean {+ const a = normalizeCloudHost(host);+ const b = normalizeCloudHost(lockedHost);+ if (!a || !b) return false;+ return a.toLowerCase() === b.toLowerCase();+}+export function getAgentServerBaseUrl(): string | null {const configuredUrl = getConfiguredBaseUrl();if (configuredUrl) return configuredUrl;diff --git a/src/api/backend-registry/default-backend.ts b/src/api/backend-registry/default-backend.tsindex 77b7f1fad0..a9a6ba4890 100644--- a/src/api/backend-registry/default-backend.ts+++ b/src/api/backend-registry/default-backend.ts@@ -1,6 +1,7 @@import {getAgentServerBaseUrl,getAgentServerSessionApiKey,+ getLockedCloudHost,} from "../agent-server-config";import type { Backend } from "./types";@@ -22,8 +23,19 @@ export const DEFAULT_LOCAL_BACKEND_NAME = "Local";* Used as the seed entry written to `openhands-backends` on first load;* if it returns null, onboarding is responsible for collecting backend* connection details from the user.+ *+ * Returns null when the deployment is locked to a single OpenHands Cloud+ * host (`VITE_LOCK_TO_CLOUD` / `--lock-to-cloud`). In locked mode the user+ * can only authenticate against the configured Cloud URL, so seeding a+ * Local backend from a baked/injected session key would short-circuit the+ * first-run onboarding gate and strand the user on the Manage Backends+ * recovery modal with a disconnected Local entry.*/export function makeDefaultLocalBackend(): Backend | null {+ // Locked-to-Cloud deployments must never auto-seed a Local backend โ+ // see the docblock above.+ if (getLockedCloudHost()) return null;+const host = getAgentServerBaseUrl();const apiKey = getAgentServerSessionApiKey();diff --git a/src/components/features/backends/backend-form-modal.tsx b/src/components/features/backends/backend-form-modal.tsxindex 10166284dc..72e75490b5 100644--- a/src/components/features/backends/backend-form-modal.tsx+++ b/src/components/features/backends/backend-form-modal.tsx@@ -15,6 +15,7 @@ import { useActiveBackendContext } from "#/contexts/active-backend-context";import { useNavigation } from "#/context/navigation-context";import { useBackendsHealth } from "#/hooks/query/use-backends-health";import { getAgentServerClientOptions } from "#/api/agent-server-client-options";+import { getLockedCloudHost } from "#/api/agent-server-config";import {assertAgentServerVersionIsSupported,getDisplayAgentServerVersion,@@ -688,6 +689,24 @@ export function BackendConnectionOptions({manualSubmitTestId,}: BackendConnectionOptionsProps) {const { t } = useTranslation("openhands");+ const lockedCloudHost = getLockedCloudHost();++ if (lockedCloudHost) {+ return (+ <div+ data-testid={`${testIdRoot}-connection-options`}+ className="flex justify-center"+ >+ <div className="w-full">+ <CloudLoginColumn+ onConnected={onConnected}+ testIdRoot={testIdRoot}+ lockedHost={lockedCloudHost}+ />+ </div>+ </div>+ );+ }return (<div@@ -709,14 +728,6 @@ export function BackendConnectionOptions({/></div>- <div className="flex shrink-0 flex-row items-center md:flex-col">- <div className="h-px flex-1 bg-[var(--oh-border)] md:h-auto md:w-px" />- <span className="px-3 py-0 text-xs uppercase text-[var(--oh-muted)] md:px-0 md:py-3">- {t(I18nKey.BACKEND$LOGIN_OR)}- </span>- <div className="h-px flex-1 bg-[var(--oh-border)] md:h-auto md:w-px" />- </div>-<div className="flex-1 min-w-0"><CloudLoginColumn onConnected={onConnected} testIdRoot={testIdRoot} /></div>@@ -870,6 +881,7 @@ function ManualConnectionColumn({interface CloudLoginColumnProps {onConnected: (payload: BackendFormSubmitPayload) => void;testIdRoot: string;+ lockedHost?: string;}/**@@ -877,13 +889,18 @@ interface CloudLoginColumnProps {* disclosure for users who self-host OpenHands Cloud and need to override the* host.*/-function CloudLoginColumn({ onConnected, testIdRoot }: CloudLoginColumnProps) {+function CloudLoginColumn({+ onConnected,+ testIdRoot,+ lockedHost,+}: CloudLoginColumnProps) {const { t } = useTranslation("openhands");const [advancedOpen, setAdvancedOpen] = React.useState(false);const [customHost, setCustomHost] = React.useState("");- const effectiveHost = customHost.trim() || DEFAULT_OPENHANDS_CLOUD_HOST;+ const effectiveHost =+ lockedHost ?? (customHost.trim() || DEFAULT_OPENHANDS_CLOUD_HOST);const handleLoginSuccess = (apiKey: string) => {onConnected({@@ -917,45 +934,47 @@ function CloudLoginColumn({ onConnected, testIdRoot }: CloudLoginColumnProps) {testIdRoot={testIdRoot}/>- <div className="w-full">- <button- type="button"- onClick={() => setAdvancedOpen((open) => !open)}- aria-expanded={advancedOpen}- data-testid={`${testIdRoot}-advanced-toggle`}- className="flex w-full cursor-pointer items-center justify-center gap-1 text-center text-xs text-[var(--oh-muted)] transition-colors hover:text-content-2"- >- <span>{t(I18nKey.BACKEND$ADVANCED)}</span>- <ChevronDownSmallIcon+ {lockedHost ? null : (+ <div className="w-full">+ <button+ type="button"+ onClick={() => setAdvancedOpen((open) => !open)}+ aria-expanded={advancedOpen}+ data-testid={`${testIdRoot}-advanced-toggle`}+ className="flex w-full cursor-pointer items-center justify-center gap-1 text-center text-xs text-[var(--oh-muted)] transition-colors hover:text-content-2"+ >+ <span>{t(I18nKey.BACKEND$ADVANCED)}</span>+ <ChevronDownSmallIcon+ className={cn(+ "h-4 w-4 shrink-0 text-muted transition-transform",+ advancedOpen && "rotate-180",+ )}+ aria-hidden+ />+ </button>+ <divclassName={cn(- "h-4 w-4 shrink-0 text-muted transition-transform",- advancedOpen && "rotate-180",+ "pt-2",+ !advancedOpen && "pointer-events-none invisible",)}- aria-hidden- />- </button>- <div- className={cn(- "pt-2",- !advancedOpen && "pointer-events-none invisible",- )}- aria-hidden={!advancedOpen}- >- <SettingsInput- testId={`${testIdRoot}-cloud-host`}- name={`${testIdRoot}-cloud-host`}- type="text"- label={t(I18nKey.BACKEND$HOST_LABEL)}- value={customHost}- onChange={setCustomHost}- placeholder={DEFAULT_OPENHANDS_CLOUD_HOST}- className="w-full"- />- <p className="mt-1 text-xs text-[var(--oh-muted)]">- {t(I18nKey.BACKEND$LOGIN_CLOUD_HINT)}- </p>+ aria-hidden={!advancedOpen}+ >+ <SettingsInput+ testId={`${testIdRoot}-cloud-host`}+ name={`${testIdRoot}-cloud-host`}+ type="text"+ label={t(I18nKey.BACKEND$HOST_LABEL)}+ value={customHost}+ onChange={setCustomHost}+ placeholder={DEFAULT_OPENHANDS_CLOUD_HOST}+ className="w-full"+ />+ <p className="mt-1 text-xs text-[var(--oh-muted)]">+ {t(I18nKey.BACKEND$LOGIN_CLOUD_HINT)}+ </p>+ </div></div>- </div>+ )}</div>);}diff --git a/src/components/features/onboarding/is-backend-llm-ready.ts b/src/components/features/onboarding/is-backend-llm-ready.tsnew file mode 100644index 0000000000..50b7594368--- /dev/null+++ b/src/components/features/onboarding/is-backend-llm-ready.ts@@ -0,0 +1,49 @@+import { SEEDED_DEFAULT_BACKEND_ID } from "#/api/backend-registry/default-backend";+import type { Backend } from "#/api/backend-registry/types";+import type { Settings } from "#/types/settings";++/**+ * `true` when the active backend already has a ready-to-use LLM:+ * * `agent_settings.llm.model` is a non-empty string, AND+ * * the backend reports an API key on file OR the model uses+ * subscription auth (no key required).+ *+ * Cloud surfaces this via `llm_api_key_set`; the agent-server+ * surfaces it via `llm_api_key_is_set` โ we accept either, so the+ * same skip rule applies in both modes. A truly fresh agent-server+ * with no key configured reports both flags as `false` and the+ * modal continues to show.+ *+ * For Local backends the skip is intentionally suppressed for the+ * launcher-seeded default backend (`SEEDED_DEFAULT_BACKEND_ID`). The+ * agent-server can be started with an env-injected LLM key, and in+ * shared-server deployments (e.g. the mock-LLM E2E stack) a+ * previously-configured LLM persists across browser sessions โ so+ * keying the first-run onboarding modal off the server's LLM state+ * would suppress onboarding for a genuinely fresh browser install.+ * The skip still fires for Local backends the user explicitly added+ * via "Add Backend" (which carry a different id), preserving the+ * "don't walk a pre-configured server through Set Up LLM" behavior.+ *+ * Extracted into its own module (no UI imports) so `root.tsx` can+ * reuse the exact same rule for its first-run gate without pulling+ * the onboarding modal graph into the root's eager bundle.+ */+export function isBackendLlmReady(+ backend: Backend,+ settings: Settings | undefined,+): boolean {+ const llm = settings?.agent_settings?.llm as+ | { model?: unknown; auth_type?: unknown }+ | undefined;+ const hasModel = typeof llm?.model === "string" && llm.model.length > 0;+ const isAuthed =+ settings?.llm_api_key_set === true ||+ settings?.llm_api_key_is_set === true ||+ llm?.auth_type === "subscription";+ if (!hasModel || !isAuthed) return false;+ if (backend.kind === "local" && backend.id === SEEDED_DEFAULT_BACKEND_ID) {+ return false;+ }+ return true;+}diff --git a/src/components/features/onboarding/onboarding-host.tsx b/src/components/features/onboarding/onboarding-host.tsxindex 355be02c1e..3cf147c81f 100644--- a/src/components/features/onboarding/onboarding-host.tsx+++ b/src/components/features/onboarding/onboarding-host.tsx@@ -6,6 +6,9 @@ import {readOnboardingPreviewStep,} from "./onboarding-preview";import { useOnboardingCompletion } from "./use-onboarding-completion";+import { useSettings } from "#/hooks/query/use-settings";+import { useActiveBackend } from "#/contexts/active-backend-context";+import { isBackendLlmReady } from "./is-backend-llm-ready";/*** Mounts the onboarding modal automatically the first time the user@@ -13,6 +16,20 @@ import { useOnboardingCompletion } from "./use-onboarding-completion";* isn't set yet). Closing or completing the flow marks it done so the* modal won't re-appear on subsequent visits.*+ * Returning Cloud users are detected via the live settings query: if+ * Cloud already reports a configured LLM (api key + model, or a+ * subscription model with no key), onboarding is skipped and the+ * completion flag is persisted so the same user keeps skipping across+ * tabs and devices.+ *+ * Local backends fall through to the existing localStorage-based+ * gating โ env-injected keys make the settings-based signal unreliable+ * there.+ *+ * Stale or unreachable backends fall through to the modal so the+ * existing backend-check / manage-backends recovery path still kicks+ * in for those users.+ ** With `?previewOnboardingStep=<0-3>` the modal opens on that slide for* design review without persisting completion (works on any route when* mounted from the root layout).@@ -22,8 +39,20 @@ export function OnboardingHost() {const previewStep = readOnboardingPreviewStep(location.search);const isPreview = isOnboardingPreviewActive(location.search);const { isCompleted, markCompleted } = useOnboardingCompletion();+ const { backend } = useActiveBackend();+ const { data: settings } = useSettings();+ const skipForReadyBackend = isBackendLlmReady(backend, settings);++ React.useEffect(() => {+ if (!isPreview && !isCompleted && skipForReadyBackend) {+ markCompleted();+ }+ }, [isPreview, isCompleted, skipForReadyBackend, markCompleted]);- if (!isPreview && isCompleted) return null;+ if (!isPreview) {+ if (isCompleted) return null;+ if (skipForReadyBackend) return null;+ }const handleClose = () => {if (isPreview) return;diff --git a/src/components/features/onboarding/onboarding-modal.tsx b/src/components/features/onboarding/onboarding-modal.tsxindex 2737d90ebc..facf9d516a 100644--- a/src/components/features/onboarding/onboarding-modal.tsx+++ b/src/components/features/onboarding/onboarding-modal.tsx@@ -1,5 +1,7 @@import React from "react";import { useTranslation } from "react-i18next";+import { isNoBackend } from "#/api/backend-registry/active-store";+import { getLockedCloudHost, isSameCloudHost } from "#/api/agent-server-config";import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";import {MODAL_MAX_WIDTH_VIEWPORT,@@ -7,6 +9,8 @@ import {} from "#/components/shared/modals/modal-body";import { I18nKey } from "#/i18n/declaration";import { cn } from "#/utils/utils";+import { useActiveBackendContext } from "#/contexts/active-backend-context";+import { useBackendsHealth } from "#/hooks/query/use-backends-health";import { OnboardingProgressBar } from "./onboarding-progress-bar";import {ChooseAgentStep,@@ -17,13 +21,29 @@ import { SetupLlmStep } from "./steps/setup-llm-step";import { SetupAcpSecretsStep } from "./steps/setup-acp-secrets-step";import { SayHelloStep } from "./steps/say-hello-step";-const TOTAL_STEPS = 4;+/**+ * Logical onboarding phases.+ *+ * State is tracked as a phase (not a numeric step) so that the slide+ * indices renumbering when ``skipBackendStep`` flips โ e.g. a returning+ * Cloud user finishes the backend slide and the carousel collapses from+ * 4 slides to 3 โ cannot accidentally drag the user from "agent" onto+ * the slide that used to live at the agent index ("setup"). See the+ * regression test `onboarding-modal` covering this transition.+ */+type OnboardingPhase = "backend" | "agent" | "setup" | "hello";-// Index of the per-provider setup slide (LLM form for OpenHands, ACP-// credentials for Claude Code / Codex). Named so the slide and the-// ``isActive`` gate that drives the ACP login probe move together โ inserting-// a slide before it can't silently fire the probe on the wrong step.-const SETUP_SLIDE_INDEX = 2;+const PHASE_ORDER_WITH_BACKEND: readonly OnboardingPhase[] = [+ "backend",+ "agent",+ "setup",+ "hello",+];+const PHASE_ORDER_WITHOUT_BACKEND: readonly OnboardingPhase[] = [+ "agent",+ "setup",+ "hello",+];interface SlideProps {/** Index of this slide in the step sequence. */@@ -81,15 +101,22 @@ interface OnboardingModalProps {/*** Top-level onboarding modal for first-time users.*- * The flow is a fixed sequence of four steps:- * 0. Check backend+ * The flow starts with backend setup only when the active backend is missing+ * or cannot be reached. If an already configured backend is healthy, the user+ * starts directly on agent selection:+ * 0. Check/add backend (only when needed)* 1. Choose agent* 2. Set up LLM* 3. Say hello (creates a fresh conversation, then closes)*- * Each step lives in its own slide; all four are mounted at once and- * the rail is translated horizontally by step index, so transitioning- * between steps animates the new step in from the right.+ * Internally we track the user's *phase* โ "backend" | "agent" | "setup" |+ * "hello" โ rather than a numeric step, because the slide indices renumber+ * when the backend slide is skipped and we must never accidentally drop the+ * user onto whatever slide *used to* live at their numeric position.+ *+ * Each visible step lives in its own slide and the rail is translated+ * horizontally by step index, so transitioning between steps animates the new+ * step in from the right.*/export function OnboardingModal({onClose,@@ -97,25 +124,75 @@ export function OnboardingModal({isPreview = false,}: OnboardingModalProps) {const { t } = useTranslation("openhands");- const [currentStep, setCurrentStep] = React.useState(() =>- Math.min(Math.max(initialStep, 0), TOTAL_STEPS - 1),+ const { active } = useActiveBackendContext();+ const { backend } = active;+ const noBackendSelected = isNoBackend(backend);+ const healthByBackendId = useBackendsHealth(+ noBackendSelected ? [] : [backend],+ );+ // In locked-to-Cloud mode the backend slide may only be skipped when the+ // active backend IS the configured locked Cloud host. A reachable stale+ // Local backend (or a Cloud backend on a different host) must keep+ // `CheckBackendStep` visible so the user can log into Cloud and replace+ // the stale backend โ otherwise they would continue as Local despite+ // `VITE_LOCK_TO_CLOUD`. Outside locked mode the existing behavior+ // (skip once the active backend is healthy) is unchanged.+ const lockedCloudHost = getLockedCloudHost();+ const isActiveLockedCloudBackend =+ lockedCloudHost !== null &&+ backend.kind === "cloud" &&+ isSameCloudHost(backend.host, lockedCloudHost);+ const skipBackendStep =+ !noBackendSelected &&+ healthByBackendId[backend.id]?.isConnected === true &&+ (lockedCloudHost === null || isActiveLockedCloudBackend);++ const slideOrder = skipBackendStep+ ? PHASE_ORDER_WITHOUT_BACKEND+ : PHASE_ORDER_WITH_BACKEND;++ const [phase, setPhase] = React.useState<OnboardingPhase>(+ () =>+ PHASE_ORDER_WITH_BACKEND[+ Math.min(Math.max(initialStep, 0), PHASE_ORDER_WITH_BACKEND.length - 1)+ ],);const [selectedAgentId, setSelectedAgentId] =React.useState<OnboardingAgentId>("openhands");- // Slide index 2 is the "provider credentials" slot:- // * OpenHands โ the LLM-setup form (its own LLM config).- // * Any ACP provider (Claude Code / Codex / Gemini) โ the ACP credentials- // form: API key + optional base URL, with a login-detection banner.+ // When the backend slide drops out of the flow (skipBackendStep flips+ // true), a user still parked on "backend" must be moved forward to the+ // first remaining phase. Doing this with the *phase* rather than a numeric+ // step keeps every other phase pinned to itself, so the user never lands+ // on the slide that used to live at the next index ("setup").+ React.useEffect(() => {+ if (!slideOrder.includes(phase)) setPhase(slideOrder[0]);+ }, [phase, slideOrder]);++ const totalSteps = slideOrder.length;+ const currentPhase = slideOrder.includes(phase) ? phase : slideOrder[0];+ const currentStep = slideOrder.indexOf(currentPhase);+const isOpenHands = selectedAgentId === "openhands";- const goNext = React.useCallback(- () => setCurrentStep((step) => Math.min(step + 1, TOTAL_STEPS - 1)),- [],- );- const goBack = React.useCallback(- () => setCurrentStep((step) => Math.max(step - 1, 0)),- [],- );+ const hideSkip = currentStep === 0 && getLockedCloudHost() !== null;+ const goNext = React.useCallback(() => {+ setPhase((prev) => {+ const order = slideOrder;+ const idx = order.indexOf(prev);+ // If `prev` isn't in the current order (e.g. "backend" after the+ // backend slide just collapsed), start from the first slot.+ const safeIdx = idx === -1 ? 0 : idx;+ return order[Math.min(safeIdx + 1, order.length - 1)];+ });+ }, [slideOrder]);+ const goBack = React.useCallback(() => {+ setPhase((prev) => {+ const order = slideOrder;+ const idx = order.indexOf(prev);+ const safeIdx = idx === -1 ? 0 : idx;+ return order[Math.max(safeIdx - 1, 0)];+ });+ }, [slideOrder]);return (// No `onClose`: the flow must only be dismissed via explicit actions@@ -137,43 +214,57 @@ export function OnboardingModal({<header className="flex flex-col gap-3 px-7 pt-7 shrink-0"><OnboardingProgressBarcurrentStep={currentStep}- totalSteps={TOTAL_STEPS}+ totalSteps={totalSteps}/></header><divdata-testid="onboarding-scroll-area"- className="flex-1 min-h-0 overflow-y-auto custom-scrollbar-always px-7"+ className="flex-1 min-h-0 overflow-y-auto custom-scrollbar-always px-7 pb-7"><divdata-testid="onboarding-slide-rail"data-current-step={currentStep}className="relative overflow-clip">- <Slide index={0} currentStep={currentStep}>- <CheckBackendStep onNext={goNext} />- </Slide>- <Slide index={1} currentStep={currentStep}>+ {skipBackendStep ? null : (+ <Slide+ index={slideOrder.indexOf("backend")}+ currentStep={currentStep}+ >+ <CheckBackendStep onNext={goNext} onClose={onClose} />+ </Slide>+ )}+ <Slide+ index={slideOrder.indexOf("agent")}+ currentStep={currentStep}+ ><ChooseAgentStepselectedAgentId={selectedAgentId}onSelect={setSelectedAgentId}- onBack={goBack}+ onBack={skipBackendStep ? undefined : goBack}onNext={goNext}/></Slide>- <Slide index={SETUP_SLIDE_INDEX} currentStep={currentStep}>+ <Slide+ index={slideOrder.indexOf("setup")}+ currentStep={currentStep}+ >{isOpenHands ? (<SetupLlmStep onBack={goBack} onNext={goNext} />) : (<SetupAcpSecretsStepproviderKey={selectedAgentId}- isActive={currentStep === SETUP_SLIDE_INDEX}+ isActive={currentPhase === "setup"}onBack={goBack}onNext={goNext}/>)}</Slide>- <Slide index={3} currentStep={currentStep}>+ <Slide+ index={slideOrder.indexOf("hello")}+ currentStep={currentStep}+ ><SayHelloSteponBack={goBack}onClose={onClose}@@ -184,7 +275,7 @@ export function OnboardingModal({</div></section>- {currentStep < TOTAL_STEPS - 1 ? (+ {currentStep < totalSteps - 1 && !hideSkip ? (<buttontype="button"data-testid="onboarding-skip"diff --git a/src/components/features/onboarding/steps/check-backend-step.tsx b/src/components/features/onboarding/steps/check-backend-step.tsxindex b98977fc36..0d3ea8f7aa 100644--- a/src/components/features/onboarding/steps/check-backend-step.tsx+++ b/src/components/features/onboarding/steps/check-backend-step.tsx@@ -5,7 +5,9 @@ import { isNoBackend } from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import {getAgentServerFormDefaults,+ getLockedCloudHost,isAuthRequired,+ isSameCloudHost,} from "#/api/agent-server-config";import { DEFAULT_LOCAL_BACKEND_NAME } from "#/api/backend-registry/default-backend";import {@@ -23,6 +25,15 @@ import { getBackendStatusLabel } from "#/components/features/backends/backend-stinterface CheckBackendStepProps {onBack?: () => void;onNext: () => void;+ /**+ * Dismisses the entire onboarding modal. Called when Cloud login succeeds+ * in locked-to-Cloud mode: there the Cloud login IS the onboarding+ * completion, so the modal must disappear immediately rather than+ * advancing to the next slide (which previously flickered โ the next+ * slide flashed before the root gate tore the modal down). Standard mode+ * still walks the user through agent/LLM setup via `onNext`.+ */+ onClose?: () => void;}function ConnectionBanner({@@ -100,13 +111,35 @@ function ConnectionBanner({* First onboarding step: add the initial backend when none is selected,* or edit/check the active backend with a contextual health banner.*/-export function CheckBackendStep({ onBack, onNext }: CheckBackendStepProps) {+export function CheckBackendStep({+ onBack,+ onNext,+ onClose,+}: CheckBackendStepProps) {const { t } = useTranslation("openhands");- const { active, addBackend, updateBackend } = useActiveBackendContext();+ const { active, addBackend, setActive, updateBackend } =+ useActiveBackendContext();const { backend } = active;const noBackendSelected = isNoBackend(backend);+ const lockedCloudHost = getLockedCloudHost();++ // In locked-Cloud mode, a reachable backend that is NOT the locked+ // Cloud host (e.g. a stale Local backend from localStorage) must be+ // forced through Cloud login replacement. Treat it as if no backend+ // were selected for render purposes so the Cloud login UI shows and+ // the connected-backend "Next" shortcut is suppressed. The real+ // `noBackendSelected` still controls whether handleConnected calls+ // `addBackend` or `updateBackend`, so the stale backend gets replaced.+ const lockedCloudHostMismatch =+ lockedCloudHost !== null &&+ !noBackendSelected &&+ !(+ backend.kind === "cloud" && isSameCloudHost(backend.host, lockedCloudHost)+ );+ const treatAsNoBackend = noBackendSelected || lockedCloudHostMismatch;+const defaults = React.useMemo(() => getAgentServerFormDefaults(), []);- const backendForForm = noBackendSelected+ const backendForForm = treatAsNoBackend? {id: "onboarding-local-backend-draft",name: DEFAULT_LOCAL_BACKEND_NAME,@@ -118,10 +151,10 @@ export function CheckBackendStep({ onBack, onNext }: CheckBackendStepProps) {const healthByBackendId = useBackendsHealth(noBackendSelected ? [] : [backend],);- const isConnected = noBackendSelected+ const isConnected = treatAsNoBackend? null: (healthByBackendId[backend.id]?.isConnected ?? null);- const lastError = noBackendSelected+ const lastError = treatAsNoBackend? null: (healthByBackendId[backend.id]?.lastError ?? null);const [configurationOpen, setConfigurationOpen] = React.useState(false);@@ -139,23 +172,53 @@ export function CheckBackendStep({ onBack, onNext }: CheckBackendStepProps) {if (noBackendSelected) {addBackend(payload);} else {+ // When the host changes (e.g. replacing a stale Cloud backend+ // with the locked Cloud host), the persisted active org_id is+ // keyed to the OLD host's org list and would be sent as an+ // invalid X-Org-Id to the new host. Clear it so the new+ // backend starts org-less; the user picks an org on the new+ // host. (Local-only edits are no-ops here since active.orgId+ // is already null for Local backends.)+ const hostChanged = payload.host !== backend.host;updateBackend(backend.id, payload);+ if (hostChanged && active.orgId !== null) {+ setActive(backend.id, null);+ }+ }+ // In locked-to-Cloud mode, Cloud login IS the onboarding+ // completion: dismiss the modal immediately so the user never+ // sees the next slide (Choose Agent) flash before the root gate+ // tears the modal down โ the flicker reported on PR #1389.+ // Standard mode still walks the user through agent/LLM setup.+ if (lockedCloudHost !== null && payload.kind === "cloud" && onClose) {+ onClose();+ } else {+ onNext();}- onNext();},- [addBackend, backend.id, noBackendSelected, onNext, updateBackend],+ [+ active.orgId,+ addBackend,+ backend.host,+ backend.id,+ lockedCloudHost,+ noBackendSelected,+ onClose,+ onNext,+ setActive,+ updateBackend,+ ],);const actionRowClassName = cn("sticky bottom-0 mt-2 flex items-center gap-2 bg-base-secondary pt-4 pb-7",onBack ? "justify-between" : "justify-end",);- const titleKey = noBackendSelected- ? I18nKey.BACKEND$ADD_TITLE+ const titleKey = treatAsNoBackend+ ? lockedCloudHost+ ? I18nKey.ONBOARDING$LOGIN_TO_CLOUD_TITLE+ : I18nKey.BACKEND$ADD_TITLE: I18nKey.ONBOARDING$BACKEND_TITLE;- const subtitleKey = noBackendSelected- ? I18nKey.ONBOARDING$ADD_BACKEND_SUBTITLE- : I18nKey.ONBOARDING$BACKEND_SUBTITLE;return (<div@@ -164,10 +227,17 @@ export function CheckBackendStep({ onBack, onNext }: CheckBackendStepProps) {><header className="flex flex-col gap-2"><h2 className="text-2xl font-medium text-white">{t(titleKey)}</h2>- <p className="text-sm text-[var(--oh-muted)]">{t(subtitleKey)}</p>+ {treatAsNoBackend ? null : (+ <p+ data-testid="onboarding-backend-subtitle"+ className="text-sm text-[var(--oh-muted)]"+ >+ {t(I18nKey.ONBOARDING$BACKEND_SUBTITLE)}+ </p>+ )}</header>- {noBackendSelected ? null : (+ {treatAsNoBackend ? null : (<ConnectionBannerbackend={backendForForm}isConnected={isConnected}diff --git a/src/components/features/onboarding/steps/say-hello-step.tsx b/src/components/features/onboarding/steps/say-hello-step.tsxindex 6d0365d2c7..63674fea3f 100644--- a/src/components/features/onboarding/steps/say-hello-step.tsx+++ b/src/components/features/onboarding/steps/say-hello-step.tsx@@ -4,6 +4,7 @@ import { ChatSendButton } from "#/components/features/chat/chat-send-button";import { RecommendedAutomationsLauncher } from "#/components/features/automations/recommended-automations-launcher";import { BrandButton } from "#/components/features/settings/brand-button";import { useNavigation } from "#/context/navigation-context";+import { useActiveBackend } from "#/contexts/active-backend-context";import { useCreateConversation } from "#/hooks/mutation/use-create-conversation";import { useIsCreatingConversation } from "#/hooks/use-is-creating-conversation";import { I18nKey } from "#/i18n/declaration";@@ -29,6 +30,8 @@ export function SayHelloStep({}: SayHelloStepProps) {const { t } = useTranslation("openhands");const { navigate } = useNavigation();+ const { backend } = useActiveBackend();+ const showRecommendedAutomations = backend.kind !== "cloud";const defaultMessage = t(I18nKey.ONBOARDING$HELLO_DEFAULT_MESSAGE);const [message, setMessage] = React.useState(defaultMessage);@@ -117,26 +120,30 @@ export function SayHelloStep({</div></form>- <div- data-testid="onboarding-hello-or-separator"- className="mt-6 flex w-full items-center gap-3"- >- <div className="h-px flex-1 bg-[var(--oh-border)]" />- <span className="text-xs uppercase text-[var(--oh-muted)]">- {t(I18nKey.LANDING$OR)}- </span>- <div className="h-px flex-1 bg-[var(--oh-border)]" />- </div>+ {showRecommendedAutomations ? (+ <>+ <div+ data-testid="onboarding-hello-or-separator"+ className="mt-6 flex w-full items-center gap-3"+ >+ <div className="h-px flex-1 bg-[var(--oh-border)]" />+ <span className="text-xs uppercase text-[var(--oh-muted)]">+ {t(I18nKey.LANDING$OR)}+ </span>+ <div className="h-px flex-1 bg-[var(--oh-border)]" />+ </div>- <div- data-testid="onboarding-recommended-automations"- className="flex min-h-0 flex-1 flex-col"- >- <RecommendedAutomationsLauncher- onLaunched={onLaunched}- scrollableGrid- />- </div>+ <div+ data-testid="onboarding-recommended-automations"+ className="flex min-h-0 flex-1 flex-col"+ >+ <RecommendedAutomationsLauncher+ onLaunched={onLaunched}+ scrollableGrid+ />+ </div>+ </>+ ) : null}<div className="flex shrink-0 items-center justify-between gap-2 bg-base-secondary pt-7 pb-7"><BrandButtondiff --git a/src/components/features/onboarding/steps/setup-llm-step.tsx b/src/components/features/onboarding/steps/setup-llm-step.tsxindex dda6ce765e..52b2778087 100644--- a/src/components/features/onboarding/steps/setup-llm-step.tsx+++ b/src/components/features/onboarding/steps/setup-llm-step.tsx@@ -23,10 +23,6 @@ interface SetupLlmStepProps {*/export const ONBOARDING_DEFAULT_LLM_MODEL = "openai/gpt-5.5";-const ONBOARDING_LLM_OVERRIDES = {- "llm.model": ONBOARDING_DEFAULT_LLM_MODEL,-} as const;-/*** Step 2: embed the LLM settings form. The screen runs in `embedded`* mode (so it doesn't render its own sticky Save bar) and with@@ -38,6 +34,11 @@ const ONBOARDING_LLM_OVERRIDES = {* If the form happens to be untouched (no dirty fields), Next falls* through to advancing without a save call, so users with already-* configured settings aren't blocked.+ *+ * Note: returning Cloud users who already have an LLM configured are+ * intercepted upstream by `OnboardingHost`, so they never reach this+ * step. Users who do reach it are first-time installs (Cloud or Local)+ * who want the OpenAI/GPT-5.5 default pre-filled.*/export function SetupLlmStep({ onBack, onNext }: SetupLlmStepProps) {const { t } = useTranslation("openhands");@@ -125,7 +126,9 @@ export function SetupLlmStep({ onBack, onNext }: SetupLlmStepProps) {embeddedhideSaveButtonsuppressSuccessToast- initialValueOverrides={ONBOARDING_LLM_OVERRIDES}+ initialValueOverrides={{+ "llm.model": ONBOARDING_DEFAULT_LLM_MODEL,+ }}onSaveSuccess={handleSaveSuccess}onSaveControlChange={setSaveControl}/>diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex fb1549e12e..1ecbba3304 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -28508,22 +28508,22 @@"tr": "Sunucu tarafฤฑnฤฑ kontrol edin","uk": "ะะตัะตะฒัััะต ะฑะตะบะตะฝะด"},- "ONBOARDING$ADD_BACKEND_SUBTITLE": {- "en": "Connect OpenHands to an agent server or OpenHands Cloud to get started.",- "ja": "้ๅงใใใซใฏใOpenHands ใใจใผใธใงใณใใตใผใใผใพใใฏ OpenHands Cloud ใซๆฅ็ถใใฆใใ ใใใ",- "zh-CN": "ๅฐ OpenHands ่ฟๆฅๅฐๆบ่ฝไฝๆๅกๅจๆ OpenHands Cloud ๅณๅฏๅผๅงใ",- "zh-TW": "ๅฐ OpenHands ้ฃ็ทๅฐไปฃ็ไผบๆๅจๆ OpenHands Cloud ๅณๅฏ้ๅงใ",- "ko-KR": "์์ํ๋ ค๋ฉด OpenHands๋ฅผ ์์ด์ ํธ ์๋ฒ ๋๋ OpenHands Cloud์ ์ฐ๊ฒฐํ์ธ์.",- "no": "Koble OpenHands til en agentserver eller OpenHands Cloud for รฅ komme i gang.",- "ar": "ูุตูู OpenHands ุจุฎุงุฏู ูููู ุฃู OpenHands Cloud ููุจุฏุก.",- "de": "Verbinden Sie OpenHands mit einem Agent-Server oder OpenHands Cloud, um zu starten.",- "fr": "Connectez OpenHands ร un serveur dโagent ou ร OpenHands Cloud pour commencer.",- "it": "Collega OpenHands a un server agente o a OpenHands Cloud per iniziare.",- "pt": "Conecte o OpenHands a um servidor de agente ou ao OpenHands Cloud para comeรงar.",- "es": "Conecta OpenHands a un servidor de agente o a OpenHands Cloud para empezar.",- "ca": "Connecteu OpenHands a un servidor dโagent o a OpenHands Cloud per comenรงar.",- "tr": "Baลlamak iรงin OpenHandsโi bir aracฤฑ sunucusuna veya OpenHands Cloudโa baฤlayฤฑn.",- "uk": "ะัะดะบะปััััั OpenHands ะดะพ ัะตัะฒะตัะฐ ะฐะณะตะฝัะฐ ะฐะฑะพ OpenHands Cloud, ัะพะฑ ะฟะพัะฐัะธ."+ "ONBOARDING$LOGIN_TO_CLOUD_TITLE": {+ "en": "Login to cloud",+ "ja": "ใฏใฉใฆใใซใญใฐใคใณ",+ "zh-CN": "็ปๅฝไบ็ซฏ",+ "zh-TW": "็ปๅ ฅ้ฒ็ซฏ",+ "ko-KR": "ํด๋ผ์ฐ๋์ ๋ก๊ทธ์ธ",+ "no": "Logg inn pรฅ skyen",+ "ar": "ุชุณุฌูู ุงูุฏุฎูู ุฅูู ุงูุณุญุงุจุฉ",+ "de": "Bei der Cloud anmelden",+ "fr": "Se connecter au cloud",+ "it": "Accedi al cloud",+ "pt": "Entrar na nuvem",+ "es": "Iniciar sesiรณn en la nube",+ "ca": "Inicia sessiรณ al nรบvol",+ "tr": "Buluta giriล yap",+ "uk": "ะฃะฒัะนัะธ ะฒ ั ะผะฐัั"},"ONBOARDING$BACKEND_SUBTITLE": {"en": "OpenHands talks to an agent server. Make sure the default backend is reachable.",diff --git a/src/root.tsx b/src/root.tsxindex bae8773c25..ab1055a73a 100644--- a/src/root.tsx+++ b/src/root.tsx@@ -17,7 +17,11 @@ import {isAgentServerUnavailableError,isAgentServerAuthError,} from "#/api/agent-server-compatibility";-import { isAuthRequiredAndMissing } from "#/api/agent-server-config";+import {+ getLockedCloudHost,+ isAuthRequiredAndMissing,+ isSameCloudHost,+} from "#/api/agent-server-config";import { getEffectiveLocalBackend } from "#/api/backend-registry/active-store";import { useActiveBackendContext } from "#/contexts/active-backend-context";import {@@ -28,9 +32,11 @@ import { TOAST_OPTIONS } from "#/utils/custom-toast-handlers";import { TelemetryConsentBanner } from "#/components/features/analytics/telemetry-consent-banner";import { LoadingSpinner } from "#/components/shared/loading-spinner";import { useConfig } from "#/hooks/query/use-config";+import { useSettings } from "#/hooks/query/use-settings";import { QUERY_KEYS } from "#/hooks/query/query-keys";import { AgentServerUIRoot } from "#/components/providers";import { useOnboardingCompletion } from "#/components/features/onboarding/use-onboarding-completion";+import { isBackendLlmReady } from "#/components/features/onboarding/is-backend-llm-ready";import {applyColorTheme,readPersistedColorTheme,@@ -171,22 +177,117 @@ export default function App() {const bakedKeyMissing = isAuthRequiredAndMissing();const hasRegisteredKey = Boolean(getEffectiveLocalBackend()?.apiKey);const authMissing = bakedKeyMissing && !hasRegisteredKey;+ const { active } = useActiveBackendContext();+ // In locked-to-Cloud mode the only valid backend is a Cloud backend whose+ // host matches the configured locked Cloud host. A missing backend, a stale+ // Local backend (e.g. one persisted from a previous non-locked session), or+ // a Cloud backend pointing at a *different* host must all trigger first-run+ // onboarding instead of the Manage Backends recovery modal โ the onboarding+ // flow owns the Cloud login that replaces the stale backend.+ const lockedCloudHost = getLockedCloudHost();+ const isLockedToCloud = lockedCloudHost !== null;+ // True only when the active backend IS the configured locked Cloud host+ // (normalized comparison so trailing slash / case / protocol differences+ // don't cause false negatives). This is the single signal the locked-mode+ // gates key off of: a reachable stale Local backend or a Cloud backend on+ // another host must never be treated as the locked backend.+ const isActiveLockedCloudBackend =+ isLockedToCloud &&+ active.backend.kind === "cloud" &&+ isSameCloudHost(active.backend.host, lockedCloudHost);const { isCompleted: onboardingCompleted, markCompleted } =useOnboardingCompletion();++ // Returning-user fast-path: when the active backend already reports a+ // ready-to-use LLM (model + key, or subscription auth), skip first-run+ // onboarding entirely. Covers two cases:+ // * Cloud (settings.llm_api_key_set) โ same Cloud account on a new+ // origin/browser would otherwise re-trigger the modal because the+ // `openhands-onboarded` flag is origin-scoped and starts empty.+ // * Local (settings.llm_api_key_is_set) โ when the user connects via+ // Add Backend to an existing agent-server that already has an LLM+ // configured, walking them through Set Up LLM is redundant.+ // A truly fresh agent-server (no env-injected key, no saved settings)+ // reports both flags as false and the modal still shows normally.+ //+ // The skip is intentionally suppressed for the launcher-seeded default+ // Local backend (`SEEDED_DEFAULT_BACKEND_ID`): the agent-server can be+ // started with an env-injected LLM key, and shared-server deployments+ // (e.g. the mock-LLM E2E stack) retain configured LLMs across browser+ // sessions, so keying first-run onboarding off the server's LLM state+ // would suppress the modal (and persist `openhands-onboarded`) for a+ // genuinely fresh browser install. The shared helper is the same one+ // `OnboardingHost` uses, so the two gates stay in sync.+ const { data: activeBackendSettings } = useSettings();+ const backendLlmReady = isBackendLlmReady(+ active.backend,+ activeBackendSettings,+ );++ // In locked-to-Cloud mode the `openhands-onboarded` localStorage flag is+ // not trustworthy: it may have been set during a previous non-locked+ // session on the same origin, and origin-scoped localStorage cannot tell+ // the two deployments apart. So when the active backend is not the locked+ // Cloud host we ignore the completion flag and force first-run onboarding+ // (which owns the Cloud login). A stale completion flag must never strand+ // the user on the Manage Backends recovery modal ("Add Backend") in locked+ // mode.+ //+ // The ready-backend fast-path is additionally restricted in locked mode:+ // it may only skip onboarding when the active backend IS the locked Cloud+ // host. A reachable stale Local backend (or a Cloud backend on a different+ // host) that happens to report a configured LLM must NOT bypass the Cloud+ // login/replacement flow โ otherwise the user continues as Local despite+ // `VITE_LOCK_TO_CLOUD`.+ //+ // Once the active backend IS the locked Cloud host, a Cloud login that+ // just succeeded (markCompleted fired via the onboarding modal's onClose)+ // must hide first-run onboarding immediately โ without waiting for the+ // Cloud settings probe to confirm a configured LLM. Waiting caused the+ // PR #1389 flicker: the modal advanced to Choose Agent, then the root+ // gate tore it down, then OnboardingHost remounted it. Treating+ // `onboardingCompleted` as authoritative once the locked Cloud backend is+ // active suppresses the reopen. (The flag is only honored when the active+ // backend really is the locked Cloud host, so the stale-flag bypass+ // concerns above don't apply here.)+ const shouldShowFirstRunOnboarding = isLockedToCloud+ ? !isActiveLockedCloudBackend || (!backendLlmReady && !onboardingCompleted)+ : authMissing && !onboardingCompleted && !backendLlmReady;const [showFirstRunOnboarding, setShowFirstRunOnboarding] = React.useState(- () => authMissing && !onboardingCompleted,+ () => shouldShowFirstRunOnboarding,);React.useEffect(() => {- if (authMissing && !onboardingCompleted) {+ if (shouldShowFirstRunOnboarding) {setShowFirstRunOnboarding(true);return;}- if (onboardingCompleted) {+ if (onboardingCompleted || backendLlmReady) {setShowFirstRunOnboarding(false);}- }, [authMissing, onboardingCompleted]);+ }, [onboardingCompleted, shouldShowFirstRunOnboarding, backendLlmReady]);++ // Persist completion once we observe a returning user with a ready LLM,+ // so future first renders short-circuit immediately (before settings+ // load) and the modal never flashes on a reload.+ //+ // In locked-to-Cloud mode this must only fire for the legitimate locked+ // Cloud host: a stale Local backend (or a Cloud backend on a different+ // host) that happens to report a configured LLM must NOT be treated as+ // "onboarding complete" โ the user is being routed through the Cloud+ // login/replacement flow, not skipped past it.+ React.useEffect(() => {+ if (!backendLlmReady || onboardingCompleted) return;+ if (isLockedToCloud && !isActiveLockedCloudBackend) return;+ markCompleted();+ }, [+ backendLlmReady,+ onboardingCompleted,+ markCompleted,+ isLockedToCloud,+ isActiveLockedCloudBackend,+ ]);// Skip the /server_info probe entirely when we already know auth is// required and missing โ it would just 401 and waste time. Also keep the@@ -195,7 +296,6 @@ export default function App() {const config = useConfig({enabled: !authMissing && !showFirstRunOnboarding,});- const { active } = useActiveBackendContext();const activeCloudHealth = useBackendsHealth(active.backend.kind === "cloud" ? [active.backend] : [],)[active.backend.id];diff --git a/src/types/settings.ts b/src/types/settings.tsindex 8f4cc7b804..373b8952d7 100644--- a/src/types/settings.ts+++ b/src/types/settings.ts@@ -133,7 +133,15 @@ export type Settings = {agent: string;language: string;llm_api_key: string | null;+ /** Cloud-shape "an LLM key is on file for this user". */llm_api_key_set: boolean;+ /**+ * Agent-server-shape "an LLM key is on file". The local agent-server+ * uses `_is_set` in its `/api/settings` payload; Cloud uses `_set`.+ * Surfacing both so onboarding-skip logic can treat the two backends+ * uniformly.+ */+ llm_api_key_is_set?: boolean;search_api_key_set: boolean;confirmation_mode: boolean;security_analyzer: string | null;diff --git a/tests/e2e/mock-llm/onboarding/mock-llm-onboarding-happy-path.spec.ts b/tests/e2e/mock-llm/onboarding/mock-llm-onboarding-happy-path.spec.tsindex 70eb7b7893..f9ffcc500e 100644--- a/tests/e2e/mock-llm/onboarding/mock-llm-onboarding-happy-path.spec.ts+++ b/tests/e2e/mock-llm/onboarding/mock-llm-onboarding-happy-path.spec.ts@@ -37,10 +37,8 @@ import {waitForOnboardingStep,waitForOnboardingBackendConnected,clickOnboardingStepButton,- ONBOARDING_BACKEND_STEP,- ONBOARDING_AGENT_STEP,- ONBOARDING_LLM_STEP,- ONBOARDING_HELLO_STEP,+ getOnboardingStepLayout,+ type OnboardingStepLayout,} from "../../support/onboarding-helpers";const MOCK_MODEL = "openai/mock-onboarding-model";@@ -94,31 +92,32 @@ test.describe("onboarding happy path", () => {beforeGoto: () => routeSessionApiKey(page),});- // โโ Step 0: Choose Agent โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ let layout!: OnboardingStepLayout;- await test.step("step 0: choose agent โ advance past it", async () => {- await waitForOnboardingStep(page, ONBOARDING_BACKEND_STEP);+ // โโ Backend / agent setup โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ await test.step("backend setup if needed, then choose agent", async () => {+ layout = await getOnboardingStepLayout(page);// Verify the skip button is visible on non-final stepsawait expect(page.getByTestId("onboarding-skip"),- "Skip button should be visible on step 0",+ "Skip button should be visible before the final step",).toBeVisible({ timeout: 5_000 });- // Advance โ the helper clicks any button's onNext, which- // increments the step regardless of which slide owns the button.- await clickOnboardingStepButton(page, "onboarding-backend-next");- });-- // โโ Step 1: Check Backend โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ-- await test.step("step 1: check backend โ wait for connected, advance", async () => {- await waitForOnboardingStep(page, ONBOARDING_AGENT_STEP);- await waitForOnboardingBackendConnected(page);+ if (layout.hasBackendStep) {+ await waitForOnboardingBackendConnected(page);+ await clickOnboardingStepButton(page, "onboarding-backend-next");+ await waitForOnboardingStep(page, layout.agentStep);+ } else {+ await expect(+ page.getByTestId("onboarding-step-choose-agent"),+ "healthy configured backends should start at agent selection",+ ).toBeVisible({ timeout: 10_000 });+ }await expect(page.getByTestId("onboarding-skip"),- "Skip button should be visible on step 1",+ "Skip button should be visible on agent selection",).toBeVisible();await clickOnboardingStepButton(page, "onboarding-agent-next");@@ -127,7 +126,7 @@ test.describe("onboarding happy path", () => {// โโ Step 2: Setup LLM โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโawait test.step("step 2: setup LLM โ fill mock LLM details, advance", async () => {- await waitForOnboardingStep(page, ONBOARDING_LLM_STEP);+ await waitForOnboardingStep(page, layout.llmStep);await expect(page.getByTestId("onboarding-step-setup-llm"),@@ -170,7 +169,7 @@ test.describe("onboarding happy path", () => {// โโ Step 3: Say Hello โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโawait test.step("step 3: say hello โ verify skip hidden, launch conversation", async () => {- await waitForOnboardingStep(page, ONBOARDING_HELLO_STEP);+ await waitForOnboardingStep(page, layout.helloStep);await expect(page.getByTestId("onboarding-step-say-hello"),diff --git a/tests/e2e/support/onboarding-helpers.ts b/tests/e2e/support/onboarding-helpers.tsindex 0a0d0a31fe..d35949c343 100644--- a/tests/e2e/support/onboarding-helpers.ts+++ b/tests/e2e/support/onboarding-helpers.ts@@ -5,6 +5,13 @@ export const ONBOARDING_AGENT_STEP = 1;export const ONBOARDING_LLM_STEP = 2;export const ONBOARDING_HELLO_STEP = 3;+export type OnboardingStepLayout = {+ hasBackendStep: boolean;+ agentStep: number;+ llmStep: number;+ helloStep: number;+};+export async function routeOnboardingLlmCatalog(page: Page) {await page.route("**/api/llm/models/verified", async (route) => {await route.fulfill({@@ -123,15 +130,47 @@ export async function clickOnboardingStepButton(page: Page, testId: string) {await page.getByTestId(testId).dispatchEvent("click");}-export async function advanceOnboardingToLlmStep(page: Page) {+export async function getOnboardingStepLayout(+ page: Page,+): Promise<OnboardingStepLayout> {await waitForOnboardingStep(page, ONBOARDING_BACKEND_STEP);- await waitForOnboardingBackendConnected(page);- await clickOnboardingStepButton(page, "onboarding-backend-next");+ const hasBackendStep = await page+ .getByTestId("onboarding-step-check-backend")+ .isVisible()+ .catch(() => false);++ return hasBackendStep+ ? {+ hasBackendStep: true,+ agentStep: ONBOARDING_AGENT_STEP,+ llmStep: ONBOARDING_LLM_STEP,+ helloStep: ONBOARDING_HELLO_STEP,+ }+ : {+ hasBackendStep: false,+ agentStep: ONBOARDING_BACKEND_STEP,+ llmStep: ONBOARDING_AGENT_STEP,+ helloStep: ONBOARDING_LLM_STEP,+ };+}++export async function advanceOnboardingToLlmStep(page: Page) {+ const layout = await getOnboardingStepLayout(page);++ if (layout.hasBackendStep) {+ await waitForOnboardingBackendConnected(page);+ await clickOnboardingStepButton(page, "onboarding-backend-next");+ await waitForOnboardingStep(page, layout.agentStep);+ } else {+ await expect(+ page.getByTestId("onboarding-step-choose-agent"),+ "onboarding should start on agent selection when backend is healthy",+ ).toBeVisible({ timeout: 10_000 });+ }- await waitForOnboardingStep(page, ONBOARDING_AGENT_STEP);await clickOnboardingStepButton(page, "onboarding-agent-next");- await waitForOnboardingStep(page, ONBOARDING_LLM_STEP);+ await waitForOnboardingStep(page, layout.llmStep);await expect(page.getByTestId("onboarding-step-setup-llm"),"onboarding LLM setup step should be visible after advancing",