Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(backends): remember most recent conversation per backend (#354)

Robert Brennan18c45316a5e9
diff --git a/__tests__/api/backend-registry/last-conversation-store.test.ts b/__tests__/api/backend-registry/last-conversation-store.test.ts
new file mode 100644
index 0000000000..dbede7ef7e
--- /dev/null
+++ b/__tests__/api/backend-registry/last-conversation-store.test.ts
@@ -0,0 +1,67 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ clearLastConversationId,
+ getLastConversationId,
+ LAST_CONVERSATION_STORAGE_KEY,
+ setLastConversationId,
+} from "#/api/backend-registry/last-conversation-store";
+
+beforeEach(() => {
+ window.localStorage.clear();
+});
+
+afterEach(() => {
+ window.localStorage.clear();
+});
+
+describe("last-conversation-store", () => {
+ it("returns null when nothing has been remembered for a backend", () => {
+ expect(getLastConversationId("backend-a", null)).toBeNull();
+ });
+
+ it("remembers and reads back the most recently selected conversation per backend", () => {
+ setLastConversationId("backend-a", null, "convo-a-1");
+ setLastConversationId("backend-b", null, "convo-b-1");
+
+ expect(getLastConversationId("backend-a", null)).toBe("convo-a-1");
+ expect(getLastConversationId("backend-b", null)).toBe("convo-b-1");
+
+ // The most recent selection wins.
+ setLastConversationId("backend-a", null, "convo-a-2");
+ expect(getLastConversationId("backend-a", null)).toBe("convo-a-2");
+ // …without affecting other backends.
+ expect(getLastConversationId("backend-b", null)).toBe("convo-b-1");
+ });
+
+ it("keys cloud backends by (backendId, orgId) so each org gets its own slot", () => {
+ setLastConversationId("cloud-x", "org-1", "convo-org-1");
+ setLastConversationId("cloud-x", "org-2", "convo-org-2");
+
+ expect(getLastConversationId("cloud-x", "org-1")).toBe("convo-org-1");
+ expect(getLastConversationId("cloud-x", "org-2")).toBe("convo-org-2");
+ expect(getLastConversationId("cloud-x", null)).toBeNull();
+ });
+
+ it("clears a backend's slot without touching others", () => {
+ setLastConversationId("backend-a", null, "convo-a");
+ setLastConversationId("backend-b", null, "convo-b");
+
+ clearLastConversationId("backend-a", null);
+
+ expect(getLastConversationId("backend-a", null)).toBeNull();
+ expect(getLastConversationId("backend-b", null)).toBe("convo-b");
+ });
+
+ it("ignores empty conversation ids on write", () => {
+ setLastConversationId("backend-a", null, "");
+ expect(getLastConversationId("backend-a", null)).toBeNull();
+ });
+
+ it("survives malformed JSON in storage", () => {
+ window.localStorage.setItem(LAST_CONVERSATION_STORAGE_KEY, "not-json");
+ expect(getLastConversationId("backend-a", null)).toBeNull();
+ // A subsequent write recovers the storage shape.
+ setLastConversationId("backend-a", null, "convo-a");
+ expect(getLastConversationId("backend-a", null)).toBe("convo-a");
+ });
+});
diff --git a/__tests__/components/backends/backend-selector.test.tsx b/__tests__/components/backends/backend-selector.test.tsx
index 7af00f344b..0ff461d30d 100644
--- a/__tests__/components/backends/backend-selector.test.tsx
+++ b/__tests__/components/backends/backend-selector.test.tsx
@@ -8,7 +8,7 @@ import {
within,
} from "@testing-library/react";
import userEvent from "@testing-library/user-event";
-import { createRoutesStub, MemoryRouter } from "react-router";
+import { createRoutesStub, MemoryRouter, useParams } from "react-router";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createAxiosError } from "test-utils";
import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";
@@ -420,6 +420,127 @@ describe("BackendSelector", () => {
expect(await screen.findByTestId("home")).toBeInTheDocument();
});
+ it("jumps to the target backend's most recently selected conversation when switching from a conversation route", async () => {
+ // Pre-seed two local backends and the per-backend "last selected"
+ // slot for the target. The BackendSelector reads the remembered
+ // slot synchronously during `onChange`, so the localStorage write
+ // has to happen before the snapshot is rebuilt.
+ const sourceBackendId = "source-local";
+ const targetBackendId = "target-local";
+ window.localStorage.setItem(
+ "openhands-backends",
+ JSON.stringify([
+ {
+ id: sourceBackendId,
+ name: "Source Local",
+ host: "http://localhost:9000",
+ apiKey: "k",
+ kind: "local",
+ },
+ {
+ id: targetBackendId,
+ name: "Local 1",
+ host: "http://localhost:9001",
+ apiKey: "k",
+ kind: "local",
+ },
+ ]),
+ );
+ window.localStorage.setItem(
+ "openhands-active-backend",
+ JSON.stringify({ backendId: sourceBackendId, orgId: null }),
+ );
+ window.localStorage.setItem(
+ "openhands-last-conversation-by-backend",
+ JSON.stringify({ [targetBackendId]: "remembered-convo" }),
+ );
+ // Reset the in-memory snapshot so the seeded localStorage is read.
+ __resetActiveStoreForTests();
+
+ // One conversation route that renders the BackendSelector for the
+ // initial id and a probe div for the remembered id so we can
+ // observe the navigation target.
+ function ConversationRoute() {
+ const { conversationId } = useParams<{ conversationId: string }>();
+ if (conversationId === "remembered-convo") {
+ return <div data-testid="convo-route">{conversationId}</div>;
+ }
+ return <BackendSelector />;
+ }
+ function HomeRoute() {
+ return <div data-testid="home" />;
+ }
+ const RouterStub = createRoutesStub([
+ { path: "/conversations/:conversationId", Component: ConversationRoute },
+ { path: "/conversations", Component: HomeRoute },
+ ]);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ render(
+ <QueryClientProvider client={queryClient}>
+ <ActiveBackendProvider>
+ <RouterStub initialEntries={["/conversations/old-convo-on-A"]} />
+ </ActiveBackendProvider>
+ </QueryClientProvider>,
+ );
+
+ const user = await openDropdown();
+ await user.click(screen.getByText("Local 1"));
+
+ const convo = await screen.findByTestId("convo-route");
+ expect(convo).toHaveTextContent("remembered-convo");
+ // The home route should never have been visited.
+ expect(screen.queryByTestId("home")).not.toBeInTheDocument();
+ });
+
+ it("stays on the current page when switching backends from a non-conversation route", async () => {
+ function SettingsRoute() {
+ return (
+ <TestSeed
+ onMount={(ctx) => {
+ ctx.addBackend({
+ name: "Local 1",
+ host: "http://localhost:9000",
+ apiKey: "k",
+ kind: "local",
+ });
+ }}
+ >
+ <div data-testid="settings-route" />
+ <BackendSelector />
+ </TestSeed>
+ );
+ }
+ function HomeRoute() {
+ return <div data-testid="home" />;
+ }
+ const RouterStub = createRoutesStub([
+ { path: "/settings", Component: SettingsRoute },
+ { path: "/conversations", Component: HomeRoute },
+ ]);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ render(
+ <QueryClientProvider client={queryClient}>
+ <ActiveBackendProvider>
+ <RouterStub initialEntries={["/settings"]} />
+ </ActiveBackendProvider>
+ </QueryClientProvider>,
+ );
+
+ const user = await openDropdown();
+ await user.click(screen.getByText("Local 1"));
+
+ // The settings route is still in the DOM after the switch β€” no
+ // redirect to /conversations or anywhere else.
+ await waitFor(() => {
+ expect(screen.getByTestId("settings-route")).toBeInTheDocument();
+ });
+ expect(screen.queryByTestId("home")).not.toBeInTheDocument();
+ });
+
it("keeps the environment-switch overlay visible even after the selector unmounts mid-switch", async () => {
// Arrange β€” selector and overlay are rendered in independent trees
// so the selector can be torn down without taking the overlay with
diff --git a/src/api/backend-registry/last-conversation-store.ts b/src/api/backend-registry/last-conversation-store.ts
new file mode 100644
index 0000000000..ccf7bcf416
--- /dev/null
+++ b/src/api/backend-registry/last-conversation-store.ts
@@ -0,0 +1,76 @@
+// Per-(backend, org) memory of the most recently selected conversation.
+//
+// Used by `BackendSelector` so that flipping from backend A β†’ B while a
+// conversation was active in A jumps straight to B's most recent
+// conversation (if any) instead of dropping the user on the home page.
+// Plain `localStorage` is sufficient: reads happen synchronously during
+// the dropdown's onChange and the data is purely a UX shortcut β€” losing
+// it just falls back to the conversations list.
+
+export const LAST_CONVERSATION_STORAGE_KEY =
+ "openhands-last-conversation-by-backend";
+
+type StoredMap = Record<string, string>;
+
+function selectionKey(backendId: string, orgId: string | null): string {
+ return orgId ? `${backendId}::${orgId}` : backendId;
+}
+
+function readMap(): StoredMap {
+ if (typeof window === "undefined") return {};
+ try {
+ const raw = window.localStorage.getItem(LAST_CONVERSATION_STORAGE_KEY);
+ if (!raw) return {};
+ const parsed = JSON.parse(raw) as unknown;
+ if (typeof parsed !== "object" || parsed === null) return {};
+ const out: StoredMap = {};
+ for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
+ if (typeof v === "string" && v.length > 0) out[k] = v;
+ }
+ return out;
+ } catch {
+ return {};
+ }
+}
+
+function writeMap(map: StoredMap): void {
+ if (typeof window === "undefined") return;
+ try {
+ window.localStorage.setItem(
+ LAST_CONVERSATION_STORAGE_KEY,
+ JSON.stringify(map),
+ );
+ } catch {
+ /* ignore quota / serialization errors */
+ }
+}
+
+export function getLastConversationId(
+ backendId: string,
+ orgId: string | null,
+): string | null {
+ return readMap()[selectionKey(backendId, orgId)] ?? null;
+}
+
+export function setLastConversationId(
+ backendId: string,
+ orgId: string | null,
+ conversationId: string,
+): void {
+ if (!conversationId) return;
+ const map = readMap();
+ map[selectionKey(backendId, orgId)] = conversationId;
+ writeMap(map);
+}
+
+export function clearLastConversationId(
+ backendId: string,
+ orgId: string | null,
+): void {
+ const map = readMap();
+ const key = selectionKey(backendId, orgId);
+ if (key in map) {
+ delete map[key];
+ writeMap(map);
+ }
+}
diff --git a/src/components/features/backends/backend-selector.tsx b/src/components/features/backends/backend-selector.tsx
index 40da854773..6ce8ff9e1f 100644
--- a/src/components/features/backends/backend-selector.tsx
+++ b/src/components/features/backends/backend-selector.tsx
@@ -26,6 +26,7 @@ import {
} from "#/components/features/backends/environment-switch-store";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
+import { getLastConversationId } from "#/api/backend-registry/last-conversation-store";
import { AddBackendModal } from "./add-backend-modal";
import { BackendStatusDot } from "./backend-status-dot";
import { ManageBackendsModal } from "./manage-backends-modal";
@@ -294,8 +295,38 @@ export function BackendSelector({
}
}
- if (conversationMatch) navigate("/conversations");
- else if (automationDetailMatch) navigate("/automations");
+ // Compute where the user should land on the target backend.
+ // The rule:
+ // - on `/conversations/:id`: jump to the target backend's
+ // most recently selected conversation, or to
+ // `/conversations` if it has none. Either way the URL
+ // stops referring to the source backend's conversation
+ // id, which avoids a "conversation not available" 404
+ // once we re-key backend-scoped queries below.
+ // - on `/automations/:id`: jump to the automations list
+ // (automation ids are not portable across backends and
+ // we don't currently remember a per-backend selection).
+ // - on any other route (settings, /conversations,
+ // /skills, …): stay on the same path.
+ //
+ // `await navigate(...)` waits for the router transition to
+ // commit before `setActive` notifies its listeners. Without
+ // that wait, react-router defers the URL change as a
+ // transition while `useSyncExternalStore`-based backend
+ // listeners run at sync priority β€” the conversation route
+ // would re-render once with `(newBackendId, oldConvoId)` and
+ // `useUserConversation` would fire a 404 against the new
+ // backend before unmounting.
+ let destination: string | null = null;
+ if (conversationMatch) {
+ const remembered = getLastConversationId(target.id, orgId);
+ destination = remembered
+ ? `/conversations/${remembered}`
+ : "/conversations";
+ } else if (automationDetailMatch) {
+ destination = "/automations";
+ }
+ if (destination) await navigate(destination);
setActive(target.id, orgId);
}}
diff --git a/src/routes/conversation.tsx b/src/routes/conversation.tsx
index 46a982c08c..d779933482 100644
--- a/src/routes/conversation.tsx
+++ b/src/routes/conversation.tsx
@@ -7,6 +7,11 @@ import { useCommandStore } from "#/stores/command-store";
import { useConversationStore } from "#/stores/conversation-store";
import { useAgentStore } from "#/stores/agent-store";
import { useConversationStateStore } from "#/stores/conversation-state-store";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import {
+ clearLastConversationId,
+ setLastConversationId,
+} from "#/api/backend-registry/last-conversation-store";
import { AgentState } from "#/types/agent-state";
import { EventHandler } from "../wrapper/event-handler";
@@ -30,6 +35,20 @@ function AppContent() {
const { isTask, taskStatus, taskDetail } = useTaskPolling();
+ // The conversationId in the URL belongs to whichever backend was
+ // active when the route first mounted. If the user switches backends
+ // while this route is still mounted, the id is meaningless under the
+ // new backend β€” disable the active-conversation fetch (and its 404
+ // toast) so we don't fire a request that the BackendSelector's
+ // redirect will immediately navigate away from anyway. Mirrors the
+ // same guard in `routes/automation-detail.tsx`.
+ const active = useActiveBackend();
+ const mountedBackendId = React.useRef(active.backend.id);
+ const mountedOrgId = React.useRef(active.orgId);
+ const backendChanged =
+ mountedBackendId.current !== active.backend.id ||
+ mountedOrgId.current !== active.orgId;
+
const { data: conversation, isFetched } = useActiveConversation();
const { data: isAuthed } = useIsAuthed();
const { resetConversationState } = useConversationStore();
@@ -72,12 +91,40 @@ function AppContent() {
React.useEffect(() => {
if (!isFetched || !isAuthed) return;
+ // The BackendSelector is in the middle of redirecting us away from
+ // this route β€” don't toast/navigate based on a 404 that's just
+ // "this id doesn't exist on the new backend".
+ if (backendChanged) return;
if (!conversation) {
+ // Clear the per-backend "last selected" slot so the next switch
+ // to this backend doesn't try to revisit a stale id.
+ clearLastConversationId(active.backend.id, active.orgId);
displayErrorToast(t(I18nKey.CONVERSATION$NOT_EXIST_OR_NO_PERMISSION));
navigate("/conversations");
}
- }, [conversation, isFetched, isAuthed, navigate, t]);
+ }, [
+ conversation,
+ isFetched,
+ isAuthed,
+ navigate,
+ t,
+ backendChanged,
+ active.backend.id,
+ active.orgId,
+ ]);
+
+ // Remember the most recently selected conversation for the current
+ // (backend, org) so flipping back to this backend later restores the
+ // user to where they left off. Skip while a backend switch is in
+ // flight: the id in the URL is from the previous backend and would
+ // otherwise overwrite the new backend's memory.
+ React.useEffect(() => {
+ if (backendChanged) return;
+ if (!conversationId) return;
+ if (conversationId.startsWith("task-")) return;
+ setLastConversationId(active.backend.id, active.orgId, conversationId);
+ }, [conversationId, backendChanged, active.backend.id, active.orgId]);
const content = (
<EventHandler>