Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: persist selected workspace across navigation in the new-chat view (#1118)

Matt Van Hornbc595cc8e303
diff --git a/__tests__/components/features/home/workspace-selection-form.test.tsx b/__tests__/components/features/home/workspace-selection-form.test.tsx
index 19b643f54b..92636aa48c 100644
--- a/__tests__/components/features/home/workspace-selection-form.test.tsx
+++ b/__tests__/components/features/home/workspace-selection-form.test.tsx
@@ -3,7 +3,10 @@ import userEvent from "@testing-library/user-event";
import { describe, expect, vi, beforeEach, it } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { WorkspaceSelectionForm } from "../../../../src/components/features/home/workspace-selection-form";
+import {
+ HOME_SELECTED_WORKSPACE_PATH_KEY,
+ WorkspaceSelectionForm,
+} from "../../../../src/components/features/home/workspace-selection-form";
import WorkspacesService from "#/api/workspaces-service/workspaces-service.api";
import { LocalWorkspace, LocalWorkspaceParent } from "#/types/workspace";
@@ -85,11 +88,20 @@ function renderForm({
});
}
+async function openWorkspaceDropdown(user: ReturnType<typeof userEvent.setup>) {
+ const dropdown = await screen.findByTestId("workspace-dropdown");
+ await waitFor(() => expect(dropdown).not.toBeDisabled());
+ await user.click(dropdown);
+ return screen.findByTestId("workspace-dropdown-menu");
+}
+
describe("WorkspaceSelectionForm (server-backed workspaces)", () => {
beforeEach(() => {
vi.restoreAllMocks();
+ mockNavigate.mockReset();
mockSearchSubdirectories.mockReset();
mockGetHome.mockReset();
+ window.sessionStorage.clear();
mockUseIsCreatingConversation.mockReturnValue(false);
mockGetHome.mockResolvedValue({ home: "/Users/me" });
// useResolvedWorkspaces always queries an implicit `/projects` parent in
@@ -100,6 +112,27 @@ describe("WorkspaceSelectionForm (server-backed workspaces)", () => {
});
});
+ it("renders the default empty selection when no workspace path is persisted", async () => {
+ renderForm({
+ workspaces: [
+ {
+ id: "/Users/me/dev/repo1",
+ name: "repo1",
+ path: "/Users/me/dev/repo1",
+ },
+ ],
+ });
+
+ const dropdown = await screen.findByTestId("workspace-dropdown");
+ await waitFor(() => expect(dropdown).not.toBeDisabled());
+
+ expect(dropdown).toHaveValue("");
+ expect(screen.getByTestId("workspace-launch-button")).toBeDisabled();
+ expect(
+ window.sessionStorage.getItem(HOME_SELECTED_WORKSPACE_PATH_KEY),
+ ).toBeNull();
+ });
+
it("renders workspaces returned by the agent-server in the dropdown", async () => {
// Arrange
renderForm({
@@ -114,13 +147,65 @@ describe("WorkspaceSelectionForm (server-backed workspaces)", () => {
const user = userEvent.setup();
// Act
- await user.click(await screen.findByTestId("workspace-dropdown"));
- const menu = await screen.findByTestId("workspace-dropdown-menu");
+ const menu = await openWorkspaceDropdown(user);
// Assert
expect(await within(menu).findByText("repo1")).toBeInTheDocument();
});
+ it("restores the selected workspace after unmounting and remounting", async () => {
+ const workspace = {
+ id: "/Users/me/dev/repo1",
+ name: "repo1",
+ path: "/Users/me/dev/repo1",
+ };
+ const user = userEvent.setup();
+
+ const { unmount } = renderForm({ workspaces: [workspace] });
+ const firstMenu = await openWorkspaceDropdown(user);
+ await user.click(await within(firstMenu).findByText("repo1"));
+
+ await waitFor(() =>
+ expect(
+ window.sessionStorage.getItem(HOME_SELECTED_WORKSPACE_PATH_KEY),
+ ).toBe(workspace.path),
+ );
+ expect(screen.getByTestId("workspace-launch-button")).not.toBeDisabled();
+
+ unmount();
+ renderForm({ workspaces: [workspace] });
+
+ await waitFor(() =>
+ expect(screen.getByTestId("workspace-dropdown")).toHaveValue("repo1"),
+ );
+ expect(screen.getByTestId("workspace-launch-button")).not.toBeDisabled();
+ });
+
+ it("clears a persisted workspace path that is no longer resolved", async () => {
+ window.sessionStorage.setItem(
+ HOME_SELECTED_WORKSPACE_PATH_KEY,
+ "/Users/me/dev/missing",
+ );
+
+ renderForm({
+ workspaces: [
+ {
+ id: "/Users/me/dev/repo1",
+ name: "repo1",
+ path: "/Users/me/dev/repo1",
+ },
+ ],
+ });
+
+ await waitFor(() =>
+ expect(
+ window.sessionStorage.getItem(HOME_SELECTED_WORKSPACE_PATH_KEY),
+ ).toBeNull(),
+ );
+ expect(screen.getByTestId("workspace-dropdown")).toHaveValue("");
+ expect(screen.getByTestId("workspace-launch-button")).toBeDisabled();
+ });
+
it("shows a version-specific workspace message for old agent servers", async () => {
vi.spyOn(WorkspacesService, "listWorkspaces").mockRejectedValue({
code: "AGENT_SERVER_VERSION_TOO_OLD",
@@ -191,24 +276,31 @@ describe("WorkspaceSelectionForm (server-backed workspaces)", () => {
]);
});
- it("Remove Workspace dispatches removeWorkspace to the agent-server", async () => {
+ it("Remove Workspace dispatches removeWorkspace and clears the selected workspace", async () => {
// Arrange
const removeSpy = vi
.spyOn(WorkspacesService, "removeWorkspace")
.mockResolvedValue();
+ const workspace = {
+ id: "/Users/me/dev/repo1",
+ name: "repo1",
+ path: "/Users/me/dev/repo1",
+ };
renderForm({
- workspaces: [
- {
- id: "/Users/me/dev/repo1",
- name: "repo1",
- path: "/Users/me/dev/repo1",
- },
- ],
+ workspaces: [workspace],
});
const user = userEvent.setup();
// Act
- await user.click(await screen.findByTestId("workspace-dropdown"));
+ const selectionMenu = await openWorkspaceDropdown(user);
+ await user.click(await within(selectionMenu).findByText("repo1"));
+ await waitFor(() =>
+ expect(
+ window.sessionStorage.getItem(HOME_SELECTED_WORKSPACE_PATH_KEY),
+ ).toBe(workspace.path),
+ );
+
+ await openWorkspaceDropdown(user);
await user.click(await screen.findByTestId("manage-workspaces-button"));
await screen.findByTestId("manage-workspaces-modal");
await user.click(screen.getByTestId("manage-workspaces-remove-repo1"));
@@ -218,6 +310,57 @@ describe("WorkspaceSelectionForm (server-backed workspaces)", () => {
// Assert
await waitFor(() => expect(removeSpy).toHaveBeenCalledTimes(1));
expect(removeSpy).toHaveBeenCalledWith("/Users/me/dev/repo1");
+ expect(
+ window.sessionStorage.getItem(HOME_SELECTED_WORKSPACE_PATH_KEY),
+ ).toBeNull();
+ expect(screen.getByTestId("workspace-dropdown")).toHaveValue("");
+ expect(screen.getByTestId("workspace-launch-button")).toBeDisabled();
+ });
+
+ it("clears the selected parent-derived workspace when its parent is removed", async () => {
+ const removeParentSpy = vi
+ .spyOn(WorkspacesService, "removeWorkspaceParent")
+ .mockResolvedValue();
+ const workspaceParent = {
+ id: "/Users/me/dev",
+ name: "dev",
+ path: "/Users/me/dev",
+ };
+ const workspacePath = "/Users/me/dev/repo1";
+ mockSearchSubdirectories.mockImplementation(async (path: string) => {
+ if (path === workspaceParent.path) {
+ return {
+ items: [{ name: "repo1", path: workspacePath }],
+ next_page_id: null,
+ };
+ }
+ return { items: [], next_page_id: null };
+ });
+ renderForm({ workspaceParents: [workspaceParent] });
+ const user = userEvent.setup();
+
+ const selectionMenu = await openWorkspaceDropdown(user);
+ await user.click(await within(selectionMenu).findByText("repo1"));
+ await waitFor(() =>
+ expect(
+ window.sessionStorage.getItem(HOME_SELECTED_WORKSPACE_PATH_KEY),
+ ).toBe(workspacePath),
+ );
+
+ await openWorkspaceDropdown(user);
+ await user.click(await screen.findByTestId("manage-workspaces-button"));
+ await screen.findByTestId("manage-workspaces-modal");
+ await user.click(screen.getByTestId("manage-workspaces-remove-parent-dev"));
+ await screen.findByTestId("confirmation-modal");
+ await user.click(screen.getByTestId("confirm-button"));
+
+ await waitFor(() => expect(removeParentSpy).toHaveBeenCalledTimes(1));
+ expect(removeParentSpy).toHaveBeenCalledWith(workspaceParent.path);
+ expect(
+ window.sessionStorage.getItem(HOME_SELECTED_WORKSPACE_PATH_KEY),
+ ).toBeNull();
+ expect(screen.getByTestId("workspace-dropdown")).toHaveValue("");
+ expect(screen.getByTestId("workspace-launch-button")).toBeDisabled();
});
it("Add all subdirectories dispatches addWorkspaceParents to the agent-server", async () => {
diff --git a/src/components/features/home/workspace-selection-form.tsx b/src/components/features/home/workspace-selection-form.tsx
index 322445378c..84d6a28455 100644
--- a/src/components/features/home/workspace-selection-form.tsx
+++ b/src/components/features/home/workspace-selection-form.tsx
@@ -34,6 +34,36 @@ interface WorkspaceSelectionFormProps {
onConfirm?: (workspace: LocalWorkspace) => void;
}
+export const HOME_SELECTED_WORKSPACE_PATH_KEY =
+ "oh:home-selected-workspace-path";
+
+function getStoredSelectedWorkspacePath(): string | null {
+ if (typeof window === "undefined") return null;
+
+ try {
+ const path = window.sessionStorage.getItem(
+ HOME_SELECTED_WORKSPACE_PATH_KEY,
+ );
+ return path && path.length > 0 ? path : null;
+ } catch {
+ return null;
+ }
+}
+
+function setStoredSelectedWorkspacePath(path: string | null): void {
+ if (typeof window === "undefined") return;
+
+ try {
+ if (path) {
+ window.sessionStorage.setItem(HOME_SELECTED_WORKSPACE_PATH_KEY, path);
+ } else {
+ window.sessionStorage.removeItem(HOME_SELECTED_WORKSPACE_PATH_KEY);
+ }
+ } catch {
+ // sessionStorage may be unavailable in private browsing contexts.
+ }
+}
+
export function WorkspaceSelectionForm({
isLoadingSettings = false,
onConfirm,
@@ -71,6 +101,43 @@ export function WorkspaceSelectionForm({
const isCreatingConversation =
isPending || isSuccess || isCreatingConversationElsewhere;
+ const handleWorkspaceChange = React.useCallback(
+ (workspace: LocalWorkspace | null) => {
+ setSelectedWorkspace(workspace);
+ setStoredSelectedWorkspacePath(workspace?.path ?? null);
+ },
+ [],
+ );
+
+ React.useEffect(() => {
+ const storedPath = getStoredSelectedWorkspacePath();
+ if (!storedPath) return;
+
+ const restoredWorkspace = workspaces.find((w) => w.path === storedPath);
+ if (restoredWorkspace) {
+ setSelectedWorkspace((current) =>
+ current?.path === restoredWorkspace.path ? current : restoredWorkspace,
+ );
+ return;
+ }
+
+ if (
+ !isLoadingWorkspaces &&
+ !hasWorkspaceError &&
+ !workspacesUnsupportedMessage
+ ) {
+ setStoredSelectedWorkspacePath(null);
+ setSelectedWorkspace((current) =>
+ current?.path === storedPath ? null : current,
+ );
+ }
+ }, [
+ hasWorkspaceError,
+ isLoadingWorkspaces,
+ workspaces,
+ workspacesUnsupportedMessage,
+ ]);
+
const showWorkspaceStatus =
workspaceParents.length > 0 || Boolean(workspacesUnsupportedMessage);
let workspaceStatusText: string | null = null;
@@ -127,10 +194,11 @@ export function WorkspaceSelectionForm({
disabled={isDropdownDisabled}
disabledTooltip={workspacesUnsupportedMessage}
showManage={workspaces.length > 0 || workspaceParents.length > 0}
- onChange={setSelectedWorkspace}
+ onChange={handleWorkspaceChange}
onAddClick={() => setIsBrowserOpen(true)}
onManageClick={() => setIsManageOpen(true)}
className="max-w-auto"
+ key={selectedWorkspace?.path ?? "empty-workspace-selection"}
/>
{showWorkspaceStatus && workspaceStatusText && (
@@ -178,13 +246,13 @@ export function WorkspaceSelectionForm({
onClose={() => setIsManageOpen(false)}
onRemove={(path) => {
if (selectedWorkspace?.path === path) {
- setSelectedWorkspace(null);
+ handleWorkspaceChange(null);
}
removeWorkspace(path);
}}
onRemoveParent={(path) => {
if (selectedWorkspace?.parentPath === path) {
- setSelectedWorkspace(null);
+ handleWorkspaceChange(null);
}
removeWorkspaceParent(path);
}}
diff --git a/tests/e2e/regressions/workspace-selection-persistence.spec.ts b/tests/e2e/regressions/workspace-selection-persistence.spec.ts
new file mode 100644
index 0000000000..8ab6912dcf
--- /dev/null
+++ b/tests/e2e/regressions/workspace-selection-persistence.spec.ts
@@ -0,0 +1,144 @@
+import test, { expect, Page } from "@playwright/test";
+
+/**
+ * Regression test for issue #1076: selected workspace should persist across
+ * navigation in the new-chat view.
+ *
+ * The workspace-selection-form now backs the selected workspace path in
+ * sessionStorage so it survives unmount/remount cycles caused by navigating
+ * away from the home page and returning.
+ *
+ * The dev-mode MSW mock seeds implicit workspace parents under /projects,
+ * giving us "demo-app", "sample-tools", "notes-service" in the dropdown
+ * without any additional API setup.
+ */
+
+const WORKSPACE_NAME = "demo-app";
+
+async function seedLocalStorage(page: Page) {
+ await page.addInitScript(() => {
+ window.localStorage.setItem("openhands-onboarded", "1");
+ window.localStorage.setItem("openhands-telemetry-consent", "denied");
+ window.localStorage.setItem("analytics-consent", "true");
+ window.localStorage.setItem("openhands-telemetry-first-use", "true");
+ if (!window.localStorage.getItem("openhands-backends")) {
+ window.localStorage.setItem(
+ "openhands-backends",
+ JSON.stringify([
+ {
+ id: "default-local",
+ name: "Local",
+ host: window.location.origin,
+ apiKey: "test-session-key",
+ kind: "local",
+ },
+ ]),
+ );
+ }
+ if (!window.localStorage.getItem("openhands-active-backend")) {
+ window.localStorage.setItem(
+ "openhands-active-backend",
+ JSON.stringify({ backendId: "default-local", orgId: null }),
+ );
+ }
+ });
+}
+
+async function dismissConsentModal(page: Page) {
+ const consentDialog = page.getByRole("dialog", {
+ name: "Help improve OpenHands",
+ });
+ await page
+ .getByRole("button", { name: "Confirm preferences" })
+ .click({ timeout: 5000 })
+ .catch(() => undefined);
+ await expect(consentDialog).toHaveCount(0, { timeout: 5000 });
+}
+
+async function openWorkspaceDialog(page: Page) {
+ const openWorkspaceButton = page.getByTestId("open-workspace-button");
+ await expect(openWorkspaceButton).toBeEnabled({ timeout: 15_000 });
+ await openWorkspaceButton.click();
+ await expect(page.getByTestId("open-workspace-dialog-body")).toBeVisible();
+}
+
+async function selectWorkspaceInDropdown(page: Page, workspaceName: string) {
+ const dropdown = page.getByTestId("workspace-dropdown");
+ await expect(dropdown).toBeEnabled({ timeout: 15_000 });
+ await dropdown.click();
+
+ const menu = page.getByTestId("workspace-dropdown-menu");
+ await expect(menu).toBeVisible();
+
+ const option = menu.getByText(workspaceName, { exact: true });
+ await expect(option).toBeVisible();
+ await option.click();
+}
+
+test.describe("Workspace selection persistence (#1076)", () => {
+ test("selected workspace persists after navigating away and returning", async ({
+ page,
+ }) => {
+ test.setTimeout(60_000);
+
+ await seedLocalStorage(page);
+ await page.goto("/conversations", { waitUntil: "domcontentloaded" });
+ await dismissConsentModal(page);
+
+ // Step 1: Open workspace dialog and select a workspace
+ await openWorkspaceDialog(page);
+ await selectWorkspaceInDropdown(page, WORKSPACE_NAME);
+
+ // Verify the dropdown now shows the selected workspace
+ const dropdown = page.getByTestId("workspace-dropdown");
+ await expect(dropdown).toHaveValue(WORKSPACE_NAME);
+
+ // Close the dialog
+ await page.getByTestId("close-open-workspace-dialog").click();
+ await expect(
+ page.getByTestId("open-workspace-dialog-body"),
+ ).not.toBeVisible();
+
+ // Step 2: Navigate to settings and back
+ await page.goto("/settings", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("home-screen")).not.toBeVisible({
+ timeout: 5000,
+ });
+
+ await page.goto("/conversations", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("home-screen")).toBeVisible({
+ timeout: 10_000,
+ });
+
+ // Step 3: Open workspace dialog again and verify persistence
+ await openWorkspaceDialog(page);
+
+ const restoredDropdown = page.getByTestId("workspace-dropdown");
+ await expect(restoredDropdown).toBeEnabled({ timeout: 15_000 });
+ await expect(restoredDropdown).toHaveValue(WORKSPACE_NAME);
+ });
+
+ test("cleared sessionStorage results in empty workspace selection on fresh visit", async ({
+ page,
+ }) => {
+ test.setTimeout(60_000);
+
+ await seedLocalStorage(page);
+
+ // Ensure no persisted workspace path
+ await page.addInitScript(() => {
+ window.sessionStorage.removeItem("oh:home-selected-workspace-path");
+ });
+
+ await page.goto("/conversations", { waitUntil: "domcontentloaded" });
+ await dismissConsentModal(page);
+
+ await openWorkspaceDialog(page);
+
+ const dropdown = page.getByTestId("workspace-dropdown");
+ await expect(dropdown).toBeEnabled({ timeout: 15_000 });
+
+ // The dropdown should be empty (no pre-selected workspace)
+ await expect(dropdown).toHaveValue("");
+ });
+});