π OpenHands: AI-Driven Development
fix(backends): pin backend identity on sidebar conversation links (#16243)
Rishav Naskar947d9a0358a4
diff --git a/.gitignore b/.gitignoreindex 5d7ccc3b40..40ca897911 100644--- a/.gitignore+++ b/.gitignore@@ -6,6 +6,10 @@ src/i18n/declaration.tsnode_modules/build/logs/+/.tmp/live-e2e-state/+# Scratch space for local E2E runs. Ignore the whole directory: besides the+# mock-llm state dirs, the suite also drops an automation DB and an unignored+# `secrets.json` here, which should never be committable./.tmp/dist/__pycache__diff --git a/__tests__/api/backend-registry/active-store.test.ts b/__tests__/api/backend-registry/active-store.test.tsindex 06a3fb9a54..5c8e06db69 100644--- a/__tests__/api/backend-registry/active-store.test.ts+++ b/__tests__/api/backend-registry/active-store.test.ts@@ -14,6 +14,14 @@ import {__resetHealthStoreForTests,recordBackendFailure,} from "#/api/backend-registry/health-store";+import {+ ACTIVE_BACKEND_STORAGE_KEY,+ BACKENDS_STORAGE_KEY,+} from "#/api/backend-registry/storage";+import {+ BACKEND_QUERY_PARAM,+ ORG_QUERY_PARAM,+} from "#/api/backend-registry/url-selection";import type { Backend } from "#/api/backend-registry/types";beforeEach(() => {@@ -182,3 +190,74 @@ describe("active-store", () => {expect(listener).not.toHaveBeenCalled();});});++describe("backend pinned in the URL", () => {+ function seedRegistry(backends: Backend[], selection: string) {+ window.localStorage.setItem(BACKENDS_STORAGE_KEY, JSON.stringify(backends));+ window.localStorage.setItem(+ ACTIVE_BACKEND_STORAGE_KEY,+ JSON.stringify({ backendId: selection, orgId: null }),+ );+ }++ function bootAt(search: string) {+ window.history.replaceState({}, "", `/conversations/abc${search}`);+ __resetActiveStoreForTests();+ }++ afterEach(() => {+ window.history.replaceState({}, "", "/");+ });++ it("boots on the backend named in the URL instead of the stored one", () => {+ seedRegistry([localBackend, secondLocalBackend], localBackend.id);++ bootAt(`?${BACKEND_QUERY_PARAM}=${secondLocalBackend.id}`);++ expect(getActiveBackend().backend).toEqual(secondLocalBackend);+ });++ it("persists the pinned selection so later in-tab navigation keeps it", () => {+ seedRegistry([localBackend, secondLocalBackend], localBackend.id);++ bootAt(`?${BACKEND_QUERY_PARAM}=${secondLocalBackend.id}`);++ expect(+ JSON.parse(+ window.sessionStorage.getItem(ACTIVE_BACKEND_STORAGE_KEY) ?? "null",+ ),+ ).toEqual({ backendId: secondLocalBackend.id, orgId: null });+ });++ it("carries the org id for a cloud backend", () => {+ seedRegistry([localBackend, cloudBackend], localBackend.id);++ bootAt(+ `?${BACKEND_QUERY_PARAM}=${cloudBackend.id}&${ORG_QUERY_PARAM}=org-9`,+ );++ const { backend, orgId } = getActiveBackend();+ expect(backend).toEqual(cloudBackend);+ expect(orgId).toBe("org-9");+ });++ it("falls back to the stored selection when the URL names an unknown backend", () => {+ seedRegistry([localBackend, secondLocalBackend], secondLocalBackend.id);++ bootAt(`?${BACKEND_QUERY_PARAM}=removed-backend`);++ expect(getActiveBackend().backend).toEqual(secondLocalBackend);+ });++ it("prefers the URL over a tab-scoped sessionStorage selection", () => {+ seedRegistry([localBackend, secondLocalBackend], localBackend.id);+ window.sessionStorage.setItem(+ ACTIVE_BACKEND_STORAGE_KEY,+ JSON.stringify({ backendId: localBackend.id, orgId: null }),+ );++ bootAt(`?${BACKEND_QUERY_PARAM}=${secondLocalBackend.id}`);++ expect(getActiveBackend().backend).toEqual(secondLocalBackend);+ });+});diff --git a/__tests__/api/backend-registry/url-selection.test.ts b/__tests__/api/backend-registry/url-selection.test.tsnew file mode 100644index 0000000000..bc00fd2739--- /dev/null+++ b/__tests__/api/backend-registry/url-selection.test.ts@@ -0,0 +1,99 @@+import { describe, expect, it } from "vitest";+import {+ BACKEND_QUERY_PARAM,+ ORG_QUERY_PARAM,+ readBackendSelectionFromUrl,+ withBackendSelectionParams,+} from "#/api/backend-registry/url-selection";+import type { Backend } from "#/api/backend-registry/types";++const localBackend: Backend = {+ id: "local-1",+ name: "Local 1",+ host: "http://localhost:9000",+ apiKey: "k",+ kind: "local",+};++const cloudBackend: Backend = {+ id: "prod",+ name: "Production",+ host: "https://app.all-hands.dev",+ apiKey: "bearer-key",+ kind: "cloud",+};++const backends = [localBackend, cloudBackend];++describe("withBackendSelectionParams", () => {+ it("pins the active backend id onto the path", () => {+ const path = withBackendSelectionParams("/conversations/abc", {+ backend: localBackend,+ orgId: null,+ });++ expect(path).toBe(`/conversations/abc?${BACKEND_QUERY_PARAM}=local-1`);+ });++ it("includes the org id for a cloud backend", () => {+ const path = withBackendSelectionParams("/conversations/abc", {+ backend: cloudBackend,+ orgId: "org-7",+ });++ expect(path).toBe(+ `/conversations/abc?${BACKEND_QUERY_PARAM}=prod&${ORG_QUERY_PARAM}=org-7`,+ );+ });++ it("omits the org id when there is none", () => {+ const path = withBackendSelectionParams("/conversations/abc", {+ backend: cloudBackend,+ orgId: null,+ });++ expect(path).not.toContain(ORG_QUERY_PARAM);+ });++ it("preserves query parameters already on the path", () => {+ const path = withBackendSelectionParams("/conversations/abc?tab=files", {+ backend: localBackend,+ orgId: null,+ });++ expect(path).toBe(+ `/conversations/abc?tab=files&${BACKEND_QUERY_PARAM}=local-1`,+ );+ });+});++describe("readBackendSelectionFromUrl", () => {+ it("reads a registered backend id", () => {+ expect(+ readBackendSelectionFromUrl(backends, `?${BACKEND_QUERY_PARAM}=local-1`),+ ).toEqual({ backendId: "local-1", orgId: null });+ });++ it("reads the org id alongside the backend id", () => {+ expect(+ readBackendSelectionFromUrl(+ backends,+ `?${BACKEND_QUERY_PARAM}=prod&${ORG_QUERY_PARAM}=org-7`,+ ),+ ).toEqual({ backendId: "prod", orgId: "org-7" });+ });++ it("ignores a backend id that is not registered", () => {+ expect(+ readBackendSelectionFromUrl(backends, `?${BACKEND_QUERY_PARAM}=gone`),+ ).toBeNull();+ });++ it("ignores an empty or absent parameter", () => {+ expect(readBackendSelectionFromUrl(backends, "")).toBeNull();+ expect(readBackendSelectionFromUrl(backends, "?tab=files")).toBeNull();+ expect(+ readBackendSelectionFromUrl(backends, `?${BACKEND_QUERY_PARAM}=`),+ ).toBeNull();+ });+});diff --git a/__tests__/components/features/conversation-panel/conversation-panel.test.tsx b/__tests__/components/features/conversation-panel/conversation-panel.test.tsxindex a7fef6733a..599dc7848f 100644--- a/__tests__/components/features/conversation-panel/conversation-panel.test.tsx+++ b/__tests__/components/features/conversation-panel/conversation-panel.test.tsx@@ -23,6 +23,8 @@ import AgentServerConversationService from "#/api/conversation-service/agent-serimport { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";import { ExecutionStatus } from "#/types/agent-server/core";import { displayErrorToast } from "#/utils/custom-toast-handlers";+import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";+import { SEEDED_DEFAULT_BACKEND_ID } from "#/api/backend-registry/default-backend";// Mock the unified stop conversation hookconst mockStopConversationMutate = vi.fn();@@ -124,6 +126,21 @@ describe("ConversationPanel", () => {afterEach(() => {vi.useRealTimers();+ window.localStorage.clear();+ window.sessionStorage.clear();+ __resetActiveStoreForTests();+ });++ it("pins the active backend onto each conversation link", async () => {+ // A tab opened with cmd/ctrl-click does not reliably inherit the opener's+ // sessionStorage, so the link has to carry the backend it belongs to or+ // the new tab resolves the conversation against whichever backend+ // localStorage happens to hold.+ renderConversationPanel();+ const cards = await screen.findAllByTestId("conversation-card");++ const href = cards[0].closest("a")?.getAttribute("href");+ expect(href).toBe(`/conversations/1?backend=${SEEDED_DEFAULT_BACKEND_ID}`);});it("should render the conversations", async () => {diff --git a/__tests__/components/shared/navigation-link.test.tsx b/__tests__/components/shared/navigation-link.test.tsxindex 2a18628d56..ddaa3edb21 100644--- a/__tests__/components/shared/navigation-link.test.tsx+++ b/__tests__/components/shared/navigation-link.test.tsx@@ -9,6 +9,7 @@ import { NavigationLink } from "#/components/shared/navigation-link";function renderNavigationLink(currentPath = "/",overrides: Partial<NavigationContextValue> = {},+ to = "/settings/mcp",) {const value: NavigationContextValue = {currentPath,@@ -20,7 +21,7 @@ function renderNavigationLink(const result = render(<NavigationProvider value={value}>- <NavigationLink to="/settings/mcp">MCP</NavigationLink>+ <NavigationLink to={to}>MCP</NavigationLink></NavigationProvider>,);@@ -54,4 +55,28 @@ describe("NavigationLink", () => {replace: false,});});++ it("stays active when the destination carries a query string", () => {+ renderNavigationLink(+ "/conversations/abc",+ {},+ "/conversations/abc?backend=local-1",+ );++ const link = screen.getByRole("link", { name: "MCP" });+ expect(link).toHaveAttribute("href", "/conversations/abc?backend=local-1");+ expect(link).toHaveAttribute("aria-current", "page");+ });++ it("does not mark a sibling path active because of a query string", () => {+ renderNavigationLink(+ "/conversations/other",+ {},+ "/conversations/abc?backend=local-1",+ );++ expect(screen.getByRole("link", { name: "MCP" })).not.toHaveAttribute(+ "aria-current",+ );+ });});diff --git a/__tests__/hooks/use-backend-scoped-path.test.tsx b/__tests__/hooks/use-backend-scoped-path.test.tsxnew file mode 100644index 0000000000..e783c0a528--- /dev/null+++ b/__tests__/hooks/use-backend-scoped-path.test.tsx@@ -0,0 +1,87 @@+import { renderHook } from "@testing-library/react";+import React from "react";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import {+ __resetActiveStoreForTests,+ NO_BACKEND_ID,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import { BACKEND_QUERY_PARAM } from "#/api/backend-registry/url-selection";+import type { Backend } from "#/api/backend-registry/types";+import { ActiveBackendProvider } from "#/contexts/active-backend-context";+import { useBackendScopedPath } from "#/hooks/use-backend-scoped-path";++const localBackend: Backend = {+ id: "local-1",+ name: "Local 1",+ host: "http://localhost:9000",+ apiKey: "k",+ kind: "local",+};++const cloudBackend: Backend = {+ id: "prod",+ name: "Production",+ host: "https://app.all-hands.dev",+ apiKey: "bearer-key",+ kind: "cloud",+};++function wrapper({ children }: React.PropsWithChildren) {+ return <ActiveBackendProvider>{children}</ActiveBackendProvider>;+}++const renderScopedPath = () =>+ renderHook(() => useBackendScopedPath(), { wrapper });++beforeEach(() => {+ window.localStorage.clear();+ window.sessionStorage.clear();+ __resetActiveStoreForTests();+});++afterEach(() => {+ window.localStorage.clear();+ window.sessionStorage.clear();+ __resetActiveStoreForTests();+});++describe("useBackendScopedPath", () => {+ it("pins the active backend onto a conversation path", () => {+ setRegisteredBackends([localBackend, cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-3" });++ const { result } = renderScopedPath();++ expect(result.current("/conversations/abc")).toBe(+ `/conversations/abc?${BACKEND_QUERY_PARAM}=prod&org=org-3`,+ );+ });++ it("tracks the backend the user switches to", () => {+ setRegisteredBackends([localBackend, cloudBackend]);+ setActiveSelection({ backendId: localBackend.id });++ const { result, rerender } = renderScopedPath();+ expect(result.current("/conversations/abc")).toContain(+ `${BACKEND_QUERY_PARAM}=local-1`,+ );++ setActiveSelection({ backendId: cloudBackend.id });+ rerender();++ expect(result.current("/conversations/abc")).toContain(+ `${BACKEND_QUERY_PARAM}=prod`,+ );+ });++ it("leaves the path untouched when no backend is registered", () => {+ setRegisteredBackends([]);++ const { result } = renderScopedPath();++ expect(result.current("/conversations/abc")).toBe("/conversations/abc");+ expect(result.current("/conversations/abc")).not.toContain(NO_BACKEND_ID);+ });+});diff --git a/src/api/backend-registry/active-store.ts b/src/api/backend-registry/active-store.tsindex 70909053ad..8373cbdb87 100644--- a/src/api/backend-registry/active-store.ts+++ b/src/api/backend-registry/active-store.ts@@ -6,6 +6,10 @@ import {writeStoredBackends,} from "./storage";import type { Backend, BackendSelection, ResolvedActiveBackend } from "./types";+import {+ currentLocationSearch,+ readBackendSelectionFromUrl,+} from "./url-selection";type Listener = () => void;@@ -88,9 +92,31 @@ function computeSnapshot(};}+/**+ * Resolve the selection this tab boots with. A backend pinned in the URL wins+ * over stored state so a link opened in a new tab (cmd/ctrl-click, middle+ * click, "Open in new tab") lands on the backend that owns the linked+ * conversation, even when the new tab starts with an empty `sessionStorage`+ * and would otherwise adopt the `localStorage` fallback. The honoured+ * selection is persisted so later in-tab navigation β which drops the query+ * parameters β keeps the same backend.+ */+function readInitialSelection(backends: Backend[]): BackendSelection | null {+ const fromUrl = readBackendSelectionFromUrl(+ backends,+ currentLocationSearch(),+ );+ if (fromUrl) {+ writeStoredActiveBackend(fromUrl);+ return fromUrl;+ }+ return readStoredActiveBackend();+}++const initialBackends = readStoredBackends();let snapshot: Snapshot = computeSnapshot(- readStoredBackends(),- readStoredActiveBackend(),+ initialBackends,+ readInitialSelection(initialBackends),);const listeners = new Set<Listener>();@@ -161,6 +187,7 @@ export function subscribeActiveBackend(listener: Listener): () => void {/** Test-only: re-read storage and clear listeners. */export function __resetActiveStoreForTests(): void {- snapshot = computeSnapshot(readStoredBackends(), readStoredActiveBackend());+ const backends = readStoredBackends();+ snapshot = computeSnapshot(backends, readInitialSelection(backends));listeners.clear();}diff --git a/src/api/backend-registry/url-selection.ts b/src/api/backend-registry/url-selection.tsnew file mode 100644index 0000000000..5c7a53a316--- /dev/null+++ b/src/api/backend-registry/url-selection.ts@@ -0,0 +1,70 @@+import type { Backend, BackendSelection, ResolvedActiveBackend } from "./types";++/**+ * Query parameters that pin a link to the backend (and cloud org) that owns+ * the linked resource.+ *+ * The active backend is tab-scoped: `readStoredActiveBackend()` prefers+ * `sessionStorage` and only falls back to `localStorage`. A tab opened with+ * cmd/ctrl-click or middle-click does not reliably inherit the opener's+ * `sessionStorage`, so it can boot from the `localStorage` fallback β which+ * holds whichever backend was selected *last in any tab*, not the one the+ * sidebar we were just looking at belongs to. The new tab then resolves the+ * conversation id against the wrong backend and shows "conversation not+ * found". Carrying the identity in the URL makes the link self-describing so+ * the new tab pins to the right backend regardless of what storage holds.+ */+export const BACKEND_QUERY_PARAM = "backend";+export const ORG_QUERY_PARAM = "org";++/**+ * Append the active backend identity to an in-app path so opening it in a new+ * browsing context resolves against the same backend.+ */+export function withBackendSelectionParams(+ path: string,+ active: ResolvedActiveBackend,+): string {+ const { backend, orgId } = active;+ if (!backend.id) return path;++ const [pathname, existingSearch = ""] = path.split("?");+ const params = new URLSearchParams(existingSearch);+ params.set(BACKEND_QUERY_PARAM, backend.id);+ if (orgId) params.set(ORG_QUERY_PARAM, orgId);++ return `${pathname}?${params.toString()}`;+}++/**+ * Read a backend selection off the current URL, keeping it only when it names+ * a registered backend. An unknown id (a link from another machine, or a+ * backend that has since been removed) is ignored so the caller falls back to+ * the stored selection.+ */+export function readBackendSelectionFromUrl(+ backends: Backend[],+ search: string,+): BackendSelection | null {+ if (!search) return null;++ let params: URLSearchParams;+ try {+ params = new URLSearchParams(search);+ } catch {+ return null;+ }++ const backendId = params.get(BACKEND_QUERY_PARAM);+ if (!backendId) return null;+ if (!backends.some((backend) => backend.id === backendId)) return null;++ const orgId = params.get(ORG_QUERY_PARAM);+ return { backendId, orgId: orgId || null };+}++/** The current tab's query string, or "" outside a browser. */+export function currentLocationSearch(): string {+ if (typeof window === "undefined") return "";+ return window.location.search;+}diff --git a/src/components/features/conversation-panel/compact-conversation-row.tsx b/src/components/features/conversation-panel/compact-conversation-row.tsxindex 07c9f8e5f8..b856175380 100644--- a/src/components/features/conversation-panel/compact-conversation-row.tsx+++ b/src/components/features/conversation-panel/compact-conversation-row.tsx@@ -9,6 +9,7 @@ import { cn } from "#/utils/utils";import { ConversationStatusDot } from "./conversation-status-dot";import { ConversationCardFooter } from "./conversation-card/conversation-card-footer";import { I18nKey } from "#/i18n/declaration";+import { useBackendScopedPath } from "#/hooks/use-backend-scoped-path";interface CompactConversationRowProps {conversationId: string;@@ -55,6 +56,7 @@ export function CompactConversationRow({showTags = false,}: CompactConversationRowProps) {const { t } = useTranslation("openhands");+ const backendScopedPath = useBackendScopedPath();const disableAnimation = import.meta.env.MODE === "test";const preview = (@@ -95,7 +97,7 @@ export function CompactConversationRow({disableAnimation={disableAnimation}><NavigationLink- to={`/conversations/${conversationId}`}+ to={backendScopedPath(`/conversations/${conversationId}`)}onClick={onClose}data-testid="compact-conversation-row"data-conversation-id={conversationId}diff --git a/src/components/features/conversation-panel/conversation-panel.tsx b/src/components/features/conversation-panel/conversation-panel.tsxindex 4b60340f75..42e1bee8a4 100644--- a/src/components/features/conversation-panel/conversation-panel.tsx+++ b/src/components/features/conversation-panel/conversation-panel.tsx@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";import { I18nKey } from "#/i18n/declaration";import { useNavigation } from "#/context/navigation-context";import { useActiveBackend } from "#/contexts/active-backend-context";+import { useBackendScopedPath } from "#/hooks/use-backend-scoped-path";import { usePaginatedConversations } from "#/hooks/query/use-paginated-conversations";import { useStartTasks } from "#/hooks/query/use-start-tasks";import { useDeleteConversation } from "#/hooks/mutation/use-delete-conversation";@@ -88,6 +89,7 @@ export function ConversationPanel({const { t } = useTranslation("openhands");const { conversationId: currentConversationId, navigate } = useNavigation();const { backend: activeBackend } = useActiveBackend();+ const backendScopedPath = useBackendScopedPath();// Click-outside is only relevant in the legacy drawer mode where an// onClose handler is provided. When the panel is rendered inline (e.g.// as the always-visible conversation list pane), clicking outside should@@ -640,7 +642,7 @@ export function ConversationPanel({}><NavigationLink- to={`/conversations/${conversation.id}`}+ to={backendScopedPath(`/conversations/${conversation.id}`)}onClick={onClose}className={cn("block rounded-md transition-colors",@@ -832,7 +834,7 @@ export function ConversationPanel({startTasks?.map((task) => (<NavigationLinkkey={task.id}- to={`/conversations/task-${task.id}`}+ to={backendScopedPath(`/conversations/task-${task.id}`)}onClick={onClose}className="block">diff --git a/src/components/shared/navigation-link.tsx b/src/components/shared/navigation-link.tsxindex 7e551f5906..5ec90b6666 100644--- a/src/components/shared/navigation-link.tsx+++ b/src/components/shared/navigation-link.tsx@@ -24,16 +24,27 @@ function isModifiedEvent(event: React.MouseEvent<HTMLAnchorElement>) {return event.metaKey || event.altKey || event.ctrlKey || event.shiftKey;}+/**+ * `currentPath` is a pathname, so compare against the pathname portion of+ * `to`. Links may carry a query string (e.g. the backend identity pinned on+ * sidebar conversation links) that must not defeat the active check.+ */+function toPathname(to: string) {+ return to.split(/[?#]/)[0];+}+function isPathActive(currentPath: string, to: string, end: boolean) {- if (to === "/") {- return currentPath === to;+ const path = toPathname(to);++ if (path === "/") {+ return currentPath === path;}if (end) {- return currentPath === to;+ return currentPath === path;}- return currentPath === to || currentPath.startsWith(`${to}/`);+ return currentPath === path || currentPath.startsWith(`${path}/`);}export const NavigationLink = React.forwardRef<diff --git a/src/hooks/use-backend-scoped-path.ts b/src/hooks/use-backend-scoped-path.tsnew file mode 100644index 0000000000..c0368b9cc9--- /dev/null+++ b/src/hooks/use-backend-scoped-path.ts@@ -0,0 +1,27 @@+import React from "react";+import { isNoBackend } from "#/api/backend-registry/active-store";+import { withBackendSelectionParams } from "#/api/backend-registry/url-selection";+import { useActiveBackend } from "#/contexts/active-backend-context";++/**+ * Build in-app paths that carry the active backend identity.+ *+ * Use it for links a user can plausibly open in a *new* browsing context+ * (cmd/ctrl-click, middle click, "Open link in new tab"). Such a tab does not+ * reliably inherit the opener's `sessionStorage`, so without the pinned+ * identity it can boot on whichever backend `localStorage` last recorded and+ * fail to resolve the linked conversation.+ */+export function useBackendScopedPath(): (path: string) => string {+ const active = useActiveBackend();++ return React.useCallback(+ (path: string) => {+ // The sentinel isn't a real backend and must never be pinned onto a+ // link β a new tab would only ignore it and fall back to storage.+ if (isNoBackend(active.backend)) return path;+ return withBackendSelectionParams(path, active);+ },+ [active],+ );+}diff --git a/tests/e2e/mock-llm/backends/mock-llm-cross-connect.spec.ts b/tests/e2e/mock-llm/backends/mock-llm-cross-connect.spec.tsindex f151d76cdc..ffb00f1b53 100644--- a/tests/e2e/mock-llm/backends/mock-llm-cross-connect.spec.ts+++ b/tests/e2e/mock-llm/backends/mock-llm-cross-connect.spec.ts@@ -12,6 +12,11 @@* 2. **Multiple backends**: A frontend-only instance connects to* two separate backend-only instances and switches between them.*+ * 3. **Pinned backend on sidebar links**: cmd/ctrl-clicking a sidebar+ * conversation opens the new tab on the backend that owns the+ * conversation, not on whichever backend localStorage happens to+ * name (#15573).+ ** These tests spawn their own child processes (not the webServer* entries in playwright.mock-llm.config.ts) so each test controls* exactly which partial-stack flags and ports are used.@@ -171,6 +176,119 @@ async function seedBackendAnalyticsConsent(backendUrl: string, apiKey: string) {).toBe(true);}+/**+ * Create a conversation directly on a backend, bypassing the UI.+ *+ * `POST /api/conversations` requires an agent config but never contacts the+ * LLM at creation time, so a placeholder `base_url` is enough β this seeds a+ * sidebar row without any LLM traffic or credentials.+ */+async function seedConversation(+ backendUrl: string,+ apiKey: string,+): Promise<string> {+ const response = await fetch(`${backendUrl}/api/conversations`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "X-Session-API-Key": apiKey,+ },+ body: JSON.stringify({+ workspace: { kind: "LocalWorkspace", working_dir: tmpdir() },+ agent_settings: {+ llm: {+ model: "openai/mock-test-model",+ api_key: "mock-api-key-for-testing",+ base_url: "http://127.0.0.1:9/v1",+ },+ },+ }),+ });++ expect(+ response.ok,+ `failed to seed conversation on ${backendUrl}: ${response.status}`,+ ).toBe(true);++ const { id } = (await response.json()) as { id: string };+ return id;+}++/** Add a backend through the sidebar dropdown (post-onboarding path). */+async function addBackendViaDropdown(+ page: Page,+ opts: { name: string; host: string; apiKey: string },+) {+ await page.getByTestId("backend-selector").click();+ await page.getByTestId("add-backend-menu-item").click();++ await expect(page.getByTestId("add-backend-modal")).toBeVisible({+ timeout: 5_000,+ });++ // The modal defaults to the Cloud tab; switch to the manual form.+ await page.getByTestId("add-backend-option-agent-server").click();+ await expect(page.getByTestId("add-backend-agent-server-panel")).toBeVisible({+ timeout: 5_000,+ });++ const nameInput = page.getByTestId("add-backend-name");+ await nameInput.click();+ await nameInput.fill(opts.name);++ const hostInput = page.getByTestId("add-backend-host");+ await hostInput.click();+ await hostInput.fill(opts.host);++ const keyInput = page.getByTestId("add-backend-api-key");+ await keyInput.click();+ await keyInput.fill(opts.apiKey);++ await page.getByTestId("add-backend-submit").click();++ await expect(page.getByTestId("add-backend-modal")).not.toBeVisible({+ timeout: 15_000,+ });+}++/** Switch the active backend through the sidebar selector. */+async function switchBackendViaSelector(page: Page, name: string) {+ await page.getByTestId("backend-selector").click();+ await page.getByRole("option", { name: new RegExp(name, "i") }).click();+ await page.waitForLoadState("domcontentloaded", { timeout: 20_000 });+ await dismissAnalyticsModal(page);+}++/**+ * Read the active backend id a tab would resolve from a given storage.+ * `session` is what the current tab uses; `local` is the fallback a+ * brand-new tab inherits.+ */+async function readActiveBackendId(+ page: Page,+ scope: "session" | "local",+): Promise<string | null> {+ return page.evaluate((which) => {+ const store =+ which === "session" ? window.sessionStorage : window.localStorage;+ const raw = store.getItem("openhands-active-backend");+ return raw ? (JSON.parse(raw) as { backendId: string }).backendId : null;+ }, scope);+}++/** Read the registry id the frontend assigned to a backend, by host. */+async function readBackendIdByHost(+ page: Page,+ host: string,+): Promise<string | undefined> {+ return page.evaluate((wanted) => {+ const raw = window.localStorage.getItem("openhands-backends");+ if (!raw) return undefined;+ const parsed = JSON.parse(raw) as { id: string; host: string }[];+ return parsed.find((b) => b.host === wanted)?.id;+ }, host);+}+async function addBackendViaOnboarding(page: Page,opts: { name: string; host: string; apiKey: string },@@ -528,3 +646,205 @@ test.describe("cross-connect: frontend-only β multiple backends", () => {await expect(list.getByText("Backend B")).toBeVisible({ timeout: 5_000 });});});++// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+// 3. Sidebar links pin the backend that owns the conversation (#15573)+// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++test.describe("cross-connect: sidebar links pin their backend", () => {+ const children: ChildProcess[] = [];+ const stateDirs: string[] = [];++ test.afterEach(async () => {+ await Promise.all(children.map(killChild));+ children.length = 0;+ for (const dir of stateDirs) rmSync(dir, { recursive: true, force: true });+ stateDirs.length = 0;+ });++ test("cmd-clicking a sidebar conversation opens it on the owning backend", async ({+ page,+ context,+ }) => {+ // Two backend-only instances via uvx β very slow+ test.setTimeout(360_000);++ test.skip(+ !existsSync(join(PROJECT_ROOT, "build/index.html")),+ "build/index.html missing β skipped (run `npm run build:app` or use the npm e2e config)",+ );++ // ββ 1. Spawn both backends and the frontend βββββββββββββββββββββββ+ const beEnvA = createIsolatedEnv(CROSS_BE_A_PORT);+ const beEnvB = createIsolatedEnv(CROSS_BE_B_PORT);+ const feEnv = createIsolatedEnv(CROSS_FE_PORT);+ stateDirs.push(beEnvA.stateDir, beEnvB.stateDir, feEnv.stateDir);++ const beOutputA = collectOutput(+ (() => {+ const child = spawnAgentCanvas(["--backend-only"], beEnvA.env);+ children.push(child);+ return child;+ })(),+ );+ const beOutputB = collectOutput(+ (() => {+ const child = spawnAgentCanvas(["--backend-only"], beEnvB.env);+ children.push(child);+ return child;+ })(),+ );+ const feOutput = collectOutput(+ (() => {+ const child = spawnAgentCanvas(["--frontend-only"], feEnv.env);+ children.push(child);+ return child;+ })(),+ );++ const feUrl = `http://localhost:${CROSS_FE_PORT}`;+ const beUrlA = `http://localhost:${CROSS_BE_A_PORT}`;+ const beUrlB = `http://localhost:${CROSS_BE_B_PORT}`;++ const [feStatus, beStatusA, beStatusB] = await Promise.all([+ pollUrl(`${feUrl}/`, 60_000),+ pollUrl(`${beUrlA}/server_info`, 180_000),+ pollUrl(`${beUrlB}/server_info`, 180_000),+ ]);++ expect(+ feStatus,+ `Frontend-only never ready.\nOutput: ${feOutput.get().slice(-500)}`,+ ).toBe(200);+ expect(+ beStatusA,+ `Backend A never ready.\nOutput: ${beOutputA.get().slice(-800)}`,+ ).not.toBeNull();+ expect(+ beStatusB,+ `Backend B never ready.\nOutput: ${beOutputB.get().slice(-800)}`,+ ).not.toBeNull();++ await Promise.all([+ seedBackendAnalyticsConsent(beUrlA, beEnvA.sessionKey),+ seedBackendAnalyticsConsent(beUrlB, beEnvB.sessionKey),+ ]);++ // ββ 2. Seed a conversation that exists ONLY on backend A ββββββββββ+ const conversationId = await seedConversation(beUrlA, beEnvA.sessionKey);++ // The whole bug depends on this id being unresolvable on B.+ const onB = await fetch(`${beUrlB}/api/conversations/${conversationId}`, {+ headers: { "X-Session-API-Key": beEnvB.sessionKey },+ });+ expect(onB.status, "seeded conversation must not exist on backend B").toBe(+ 404,+ );++ // ββ 3. Onboard the frontend onto backend A ββββββββββββββββββββββββ+ await suppressAnalytics(page);+ await page.goto(feUrl, { waitUntil: "domcontentloaded" });++ await addBackendViaOnboarding(page, {+ name: "Backend A",+ host: beUrlA,+ apiKey: beEnvA.sessionKey,+ });+ await page.getByTestId("onboarding-skip").click();+ await page.reload({ waitUntil: "domcontentloaded" });+ await dismissAnalyticsModal(page);+ await expect(page.getByTestId("home-chat-launcher")).toBeVisible({+ timeout: 20_000,+ });++ // ββ 4. Register backend B too βββββββββββββββββββββββββββββββββββββ+ await addBackendViaDropdown(page, {+ name: "Backend B",+ host: beUrlB,+ apiKey: beEnvB.sessionKey,+ });++ const backendAId = await readBackendIdByHost(page, beUrlA);+ expect(backendAId, "backend A should be in the registry").toBeTruthy();++ // Adding a backend auto-switches to it (@spec BM-001), so put tab 1+ // back on A β that is the tab the user cmd-clicks from.+ await switchBackendViaSelector(page, "Backend A");+ await expect+ .poll(() => readActiveBackendId(page, "session"), {+ message: "tab 1 should be back on backend A",+ timeout: 20_000,+ })+ .toBe(backendAId);++ // ββ 5. Reproduce the cross-tab precondition βββββββββββββββββββββββ+ // The active backend is tab-scoped: reads prefer sessionStorage and+ // fall back to localStorage. Selecting B in a second tab leaves+ // localStorage naming B while tab 1's sessionStorage still says A β+ // and a cmd-clicked tab starts with empty sessionStorage, so it+ // boots from that localStorage fallback.+ const otherTab = await context.newPage();+ await suppressAnalytics(otherTab);+ await otherTab.goto(feUrl, { waitUntil: "domcontentloaded" });+ await dismissAnalyticsModal(otherTab);++ await switchBackendViaSelector(otherTab, "Backend B");++ await expect+ .poll(() => readActiveBackendId(otherTab, "local"), {+ message: "localStorage should now point at backend B",+ timeout: 20_000,+ })+ .not.toBe(backendAId);++ // Tab 1 must be unaffected β that asymmetry is the whole bug.+ expect(+ await readActiveBackendId(page, "session"),+ "tab 1's session-scoped backend should still be A",+ ).toBe(backendAId);++ // ββ 6. Cmd-click the conversation in tab 1's sidebar ββββββββββββββ+ await page.bringToFront();+ // Match on the conversation id in the href rather than the title: the+ // agent-server assigns its own generated title.+ const card = page+ .getByTestId("conversation-panel")+ .locator(`a[href*="${conversationId}"]`)+ .first();+ await expect(card).toBeVisible({ timeout: 20_000 });++ const href = await card.getAttribute("href");++ const newTabPromise = context.waitForEvent("page");+ await card.click({ modifiers: ["ControlOrMeta"] });+ const newTab = await newTabPromise;++ // ββ 7. The new tab must resolve the conversation on backend A βββββ+ // A freshly opened tab starts at about:blank, so wait for the real+ // navigation before reading the URL.+ await newTab.waitForURL(/\/conversations\//, { timeout: 30_000 });+ await newTab.waitForLoadState("domcontentloaded", { timeout: 20_000 });+ await dismissAnalyticsModal(newTab);++ // The user-visible symptom: resolved against B the id 404s, so the+ // route toasts CONVERSATION$NOT_EXIST_OR_NO_PERMISSION and redirects+ // to /conversations. Staying put means it resolved against A.+ await expect+ .poll(() => new URL(newTab.url()).pathname, {+ message:+ "new tab should open the conversation on its owning backend, not bounce home",+ timeout: 20_000,+ })+ .toBe(`/conversations/${conversationId}`);++ await expect(newTab.getByTestId("chat-interface")).toBeVisible({+ timeout: 30_000,+ });++ // ββ 8. And the mechanism: the link named the owning backend βββββββ+ expect(+ new URL(href ?? "", feUrl).searchParams.get("backend"),+ "sidebar link should pin backend A",+ ).toBe(backendAId);+ });+});