π OpenHands: AI-Driven Development
feat(frontend): persist local workspaces on the agent-server (#653)
Hiep Leb3d5a61fe482
diff --git a/__tests__/api/workspaces-service.test.ts b/__tests__/api/workspaces-service.test.tsnew file mode 100644index 0000000000..3d124fe530--- /dev/null+++ b/__tests__/api/workspaces-service.test.ts@@ -0,0 +1,115 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import type { Backend } from "#/api/backend-registry/types";+import WorkspacesService from "#/api/workspaces-service/workspaces-service.api";++const { mockGet, mockPost, mockDelete } = vi.hoisted(() => ({+ mockGet: vi.fn(),+ mockPost: vi.fn(),+ mockDelete: vi.fn(),+}));++vi.mock("@openhands/typescript-client/client/http-client", () => ({+ HttpClient: vi.fn(function HttpClientMock() {+ return { get: mockGet, post: mockPost, delete: mockDelete };+ }),+}));++const localBackend: Backend = {+ id: "local",+ name: "Local",+ host: "http://127.0.0.1:8000",+ apiKey: "",+ kind: "local",+};++beforeEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ setRegisteredBackends([localBackend]);+ setActiveSelection({ backendId: localBackend.id });+ mockGet.mockReset();+ mockPost.mockReset();+ mockDelete.mockReset();+});++afterEach(() => {+ __resetActiveStoreForTests();+});++describe("WorkspacesService", () => {+ it("listWorkspaces unwraps the response body returned by HttpClient.get", async () => {+ // Arrange+ const body = {+ workspaces: [{ id: "/a", name: "a", path: "/a" }],+ workspaceParents: [{ id: "/p", name: "p", path: "/p" }],+ };+ mockGet.mockResolvedValue({ data: body, status: 200 });++ // Act+ const result = await WorkspacesService.listWorkspaces();++ // Assert+ expect(mockGet).toHaveBeenCalledWith("/api/workspaces");+ expect(result).toEqual(body);+ });++ it("addWorkspaces POSTs the items wrapped in a workspaces envelope", async () => {+ // Arrange+ mockPost.mockResolvedValue({ data: { workspaces: [], workspaceParents: [] } });+ const items = [{ id: "/a", name: "a", path: "/a", parentPath: "/p" }];++ // Act+ await WorkspacesService.addWorkspaces(items);++ // Assert+ expect(mockPost).toHaveBeenCalledWith("/api/workspaces", {+ workspaces: items,+ });+ });++ it("addWorkspaceParents POSTs the items wrapped in a parents envelope", async () => {+ // Arrange+ mockPost.mockResolvedValue({ data: { workspaces: [], workspaceParents: [] } });+ const parents = [{ id: "/p", name: "p", path: "/p" }];++ // Act+ await WorkspacesService.addWorkspaceParents(parents);++ // Assert+ expect(mockPost).toHaveBeenCalledWith("/api/workspaces/parents", {+ parents,+ });+ });++ it("removeWorkspace URL-encodes the path so slashes survive the query string", async () => {+ // Arrange+ mockDelete.mockResolvedValue({ data: { deleted: true } });++ // Act+ await WorkspacesService.removeWorkspace("/Users/me/dev/repo 1");++ // Assert+ expect(mockDelete).toHaveBeenCalledWith(+ "/api/workspaces?path=%2FUsers%2Fme%2Fdev%2Frepo%201",+ );+ });++ it("removeWorkspaceParent targets the parents endpoint", async () => {+ // Arrange+ mockDelete.mockResolvedValue({ data: { deleted: true } });++ // Act+ await WorkspacesService.removeWorkspaceParent("/parents/root");++ // Assert+ expect(mockDelete).toHaveBeenCalledWith(+ "/api/workspaces/parents?path=%2Fparents%2Froot",+ );+ });+});diff --git a/__tests__/components/features/conversation-panel/new-conversation-button.test.tsx b/__tests__/components/features/conversation-panel/local-new-conversation-menu.test.tsxsimilarity index 65%rename from __tests__/components/features/conversation-panel/new-conversation-button.test.tsxrename to __tests__/components/features/conversation-panel/local-new-conversation-menu.test.tsxindex d443741e28..9f2da33f70 100644--- a/__tests__/components/features/conversation-panel/new-conversation-button.test.tsx+++ b/__tests__/components/features/conversation-panel/local-new-conversation-menu.test.tsx@@ -4,8 +4,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { renderWithProviders } from "test-utils";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";-import { NewConversationButton } from "#/components/features/conversation-panel/new-conversation-button";-import { useWorkspacesStore } from "#/stores/workspaces-store";+import WorkspacesService from "#/api/workspaces-service/workspaces-service.api";+import { LocalNewConversationMenu } from "#/components/features/conversation-panel/local-new-conversation-menu";+import { LocalWorkspace, LocalWorkspaceParent } from "#/types/workspace";++const { mockSearchSubdirectories } = vi.hoisted(() => ({+ mockSearchSubdirectories: vi.fn(),+}));vi.mock("#/hooks/use-tracking", () => ({useTracking: () => ({@@ -13,6 +18,18 @@ vi.mock("#/hooks/use-tracking", () => ({}),}));+vi.mock("@openhands/typescript-client/clients", async () => {+ const actual = await vi.importActual<+ typeof import("@openhands/typescript-client/clients")+ >("@openhands/typescript-client/clients");+ return {+ ...actual,+ FileClient: vi.fn(function FileClientMock() {+ return { searchSubdirectories: mockSearchSubdirectories };+ }),+ };+});+vi.mock("#/components/features/home/workspace-dropdown/folder-browser-modal",() => ({@@ -54,21 +71,45 @@ const makeStartTask = (conversationId: string) => ({updated_at: new Date().toISOString(),});-describe("NewConversationButton", () => {+const renderMenu = ({+ workspaces = [],+ workspaceParents = [],+ navigate,+}: {+ workspaces?: LocalWorkspace[];+ workspaceParents?: LocalWorkspaceParent[];+ navigate?: (to: string) => void;+} = {}) => {+ vi.spyOn(WorkspacesService, "listWorkspaces").mockResolvedValue({+ workspaces,+ workspaceParents,+ });+ return renderWithProviders(+ <LocalNewConversationMenu+ popoverClassName="left-0 right-0"+ trigger={(tp) => (+ <button type="button" data-testid="new-conversation-button" {...tp}>+ + New conversation+ </button>+ )}+ />,+ { navigation: { navigate, currentPath: "/conversations" } },+ );+};++describe("LocalNewConversationMenu", () => {beforeEach(() => {- window.localStorage.clear();- useWorkspacesStore.getState().clearAll();+ mockSearchSubdirectories.mockReset();+ mockSearchSubdirectories.mockResolvedValue({ items: [], next_page_id: null });});afterEach(() => {vi.restoreAllMocks();- window.localStorage.clear();- useWorkspacesStore.getState().clearAll();});it("shows a divider above the workspace footer actions", async () => {const user = userEvent.setup();- renderWithProviders(<NewConversationButton />);+ renderMenu();await user.click(screen.getByTestId("new-conversation-button"));@@ -78,12 +119,15 @@ describe("NewConversationButton", () => {});it("toggles the popover and dismisses it on outside click", async () => {+ // Arrange+ renderMenu();const user = userEvent.setup();- renderWithProviders(<NewConversationButton />);+ // Act + Assert: openawait user.click(screen.getByTestId("new-conversation-button"));expect(screen.getByTestId("new-conversation-popover")).toBeInTheDocument();+ // Act + Assert: outside click closesawait user.click(document.body);await waitFor(() => {expect(@@ -93,13 +137,16 @@ describe("NewConversationButton", () => {});it("dismisses the popover on Escape", async () => {+ // Arrange+ renderMenu();const user = userEvent.setup();- renderWithProviders(<NewConversationButton />);-await user.click(screen.getByTestId("new-conversation-button"));expect(screen.getByTestId("new-conversation-popover")).toBeInTheDocument();+ // Actawait user.keyboard("{Escape}");++ // Assertawait waitFor(() => {expect(screen.queryByTestId("new-conversation-popover"),@@ -108,26 +155,28 @@ describe("NewConversationButton", () => {});it("launches a conversation for the selected workspace", async () => {- useWorkspacesStore.getState().addWorkspaces([- {- id: "/workspace/project/repo1",- name: "repo1",- path: "/workspace/project/repo1",- },- ]);+ // Arrangeconst navigate = vi.fn();const createSpy = vi.spyOn(AgentServerConversationService, "createConversation").mockResolvedValue(makeStartTask("conv-123"));-- const user = userEvent.setup();- renderWithProviders(<NewConversationButton />, {- navigation: { navigate, currentPath: "/conversations" },+ renderMenu({+ workspaces: [+ {+ id: "/workspace/project/repo1",+ name: "repo1",+ path: "/workspace/project/repo1",+ },+ ],+ navigate,});+ const user = userEvent.setup();+ // Actawait user.click(screen.getByTestId("new-conversation-button"));- await user.click(screen.getByRole("button", { name: "repo1" }));+ await user.click(await screen.findByRole("button", { name: "repo1" }));+ // Assertawait waitFor(() => {expect(createSpy).toHaveBeenCalledWith(undefined,@@ -145,81 +194,69 @@ describe("NewConversationButton", () => {});it("disables launch actions while a conversation is being created", async () => {- useWorkspacesStore.getState().addWorkspaces([- {- id: "/workspace/project/repo1",- name: "repo1",- path: "/workspace/project/repo1",- },- ]);- vi.spyOn(AgentServerConversationService, "createConversation").mockImplementation(- () => new Promise(() => {}),- );-+ // Arrange+ vi.spyOn(+ AgentServerConversationService,+ "createConversation",+ ).mockImplementation(() => new Promise(() => {}));+ renderMenu({+ workspaces: [+ {+ id: "/workspace/project/repo1",+ name: "repo1",+ path: "/workspace/project/repo1",+ },+ ],+ });const user = userEvent.setup();- renderWithProviders(<NewConversationButton />);+ // Actawait user.click(screen.getByTestId("new-conversation-button"));await user.click(screen.getByTestId("launch-no-workspace"));+ // Assertawait waitFor(() => {expect(screen.getByTestId("launch-no-workspace")).toBeDisabled();expect(screen.getByTestId("launch-workspace")).toBeDisabled();});});- it("keeps the popover open while the add workspace modal is open", async () => {+ it("keeps the popover open while a workspace modal is open", async () => {+ // Arrange β add-modal exercises the shared `keepPopoverOpenOnMouseDown`+ // handler; manage-modal uses the same handler so we don't duplicate.+ renderMenu();const user = userEvent.setup();- renderWithProviders(<NewConversationButton />);-await user.click(screen.getByTestId("new-conversation-button"));++ // Actawait user.click(screen.getByTestId("add-workspaces-button"));+ // Assertexpect(screen.getByTestId("folder-browser-modal")).toBeInTheDocument();await user.click(document.body);expect(screen.getByTestId("new-conversation-popover")).toBeInTheDocument();});- it("keeps the popover open while the manage workspaces modal is open", async () => {- useWorkspacesStore.getState().addWorkspaces([- {- id: "/workspace/project/repo1",- name: "repo1",- path: "/workspace/project/repo1",- },- ]);- const user = userEvent.setup();- renderWithProviders(<NewConversationButton />);-- await user.click(screen.getByTestId("new-conversation-button"));- await user.click(screen.getByTestId("manage-workspaces-button"));-- expect(screen.getByTestId("manage-workspaces-modal")).toBeInTheDocument();- await user.click(document.body);- expect(screen.getByTestId("new-conversation-popover")).toBeInTheDocument();- });-it("keeps the popover open when conversation creation fails", async () => {+ // Arrangeconst navigate = vi.fn();const createSpy = vi.spyOn(AgentServerConversationService, "createConversation").mockRejectedValue(new Error("create failed"));-+ renderMenu({ navigate });const user = userEvent.setup();- renderWithProviders(<NewConversationButton />, {- navigation: { navigate, currentPath: "/conversations" },- });+ // Actawait user.click(screen.getByTestId("new-conversation-button"));await user.click(screen.getByTestId("launch-no-workspace"));+ // Assertawait waitFor(() => {expect(createSpy).toHaveBeenCalledTimes(1);});await waitFor(() => {expect(screen.getByTestId("launch-no-workspace")).not.toBeDisabled();});-expect(navigate).not.toHaveBeenCalled();expect(screen.getByTestId("new-conversation-popover")).toBeInTheDocument();});diff --git a/__tests__/components/features/home/workspace-selection-form.test.tsx b/__tests__/components/features/home/workspace-selection-form.test.tsxindex 9a81d25c3a..546166507f 100644--- a/__tests__/components/features/home/workspace-selection-form.test.tsx+++ b/__tests__/components/features/home/workspace-selection-form.test.tsx@@ -2,10 +2,10 @@ import { render, screen, waitFor, within } from "@testing-library/react";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 AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";-import { useWorkspacesStore } from "#/stores/workspaces-store";-import { LocalWorkspace } from "#/types/workspace";+import WorkspacesService from "#/api/workspaces-service/workspaces-service.api";+import { LocalWorkspace, LocalWorkspaceParent } from "#/types/workspace";const mockNavigate = vi.fn();const mockUseIsCreatingConversation = vi.fn();@@ -56,31 +56,18 @@ vi.mock("@openhands/typescript-client/clients", async () => {mockUseIsCreatingConversation.mockReturnValue(false);-function makeStartTask(overrides: Record<string, unknown> = {}) {- return {- id: "conv-abc",- created_by_user_id: null,- status: "READY",- detail: null,- app_conversation_id: "conv-abc",- agent_server_url: "http://agent-server.local",- request: { initial_message: undefined, plugins: null },- created_at: new Date().toISOString(),- updated_at: new Date().toISOString(),- ...overrides,- } as never;-}--function renderForm(- initialWorkspaces: LocalWorkspace[] = [],- initialParents: { id: string; name: string; path: string }[] = [],- props: { onConfirm?: (workspace: LocalWorkspace) => void } = {},-) {- useWorkspacesStore.setState({- workspaces: initialWorkspaces,- workspaceParents: initialParents,- });- return render(<WorkspaceSelectionForm {...props} />, {+function renderForm({+ workspaces = [],+ workspaceParents = [],+}: {+ workspaces?: LocalWorkspace[];+ workspaceParents?: LocalWorkspaceParent[];+} = {}) {+ vi.spyOn(WorkspacesService, "listWorkspaces").mockResolvedValue({+ workspaces,+ workspaceParents,+ });+ return render(<WorkspaceSelectionForm />, {wrapper: ({ children }) => (<QueryClientProviderclient={@@ -98,323 +85,107 @@ function renderForm(});}-describe("WorkspaceSelectionForm", () => {+describe("WorkspaceSelectionForm (server-backed workspaces)", () => {beforeEach(() => {- vi.clearAllMocks();+ vi.restoreAllMocks();mockSearchSubdirectories.mockReset();mockGetHome.mockReset();mockUseIsCreatingConversation.mockReturnValue(false);mockGetHome.mockResolvedValue({ home: "/Users/me" });- useWorkspacesStore.setState({ workspaces: [], workspaceParents: [] });- // `useResolvedWorkspaces` always queries an implicit `/projects` parent- // in dev mode. Default it to empty so tests that don't care about it- // don't hit a real network call. Tests that need specific behavior can- // replace this with their own spy.+ // useResolvedWorkspaces always queries an implicit `/projects` parent in+ // dev mode β return empty so it doesn't influence tests that don't care.mockSearchSubdirectories.mockResolvedValue({items: [],next_page_id: null,});});- it("Add Workspace adds only the chosen folder (not its subfolders) and dedupes on repeat", async () => {- mockGetHome.mockResolvedValue({ home: "/Users/me" });- const searchSpy = mockSearchSubdirectories;-- mockSearchSubdirectories.mockImplementation(async (path: string) => {- if (path === "/Users/me") {- return {- items: [{ name: "dev", path: "/Users/me/dev" }],- next_page_id: null,- };- }- if (path === "/Users/me/dev") {- return {- items: [- { name: "repo1", path: "/Users/me/dev/repo1" },- { name: "repo2", path: "/Users/me/dev/repo2" },- { name: "repo3", path: "/Users/me/dev/repo3" },- ],- next_page_id: null,- };- }- throw new Error(`unexpected path ${path}`);+ it("renders workspaces returned by the agent-server in the dropdown", async () => {+ // Arrange+ renderForm({+ workspaces: [+ {+ id: "/Users/me/dev/repo1",+ name: "repo1",+ path: "/Users/me/dev/repo1",+ },+ ],});-- // Pre-seed one workspace to verify dedup- renderForm([{ id: "/Users/me/dev", name: "dev", path: "/Users/me/dev" }]);const user = userEvent.setup();- // First pass: navigate into "dev" then click "Use this folder"- await user.click(screen.getByTestId("workspace-dropdown"));- await user.click(await screen.findByTestId("add-workspaces-button"));-- await screen.findByTestId("folder-browser-modal");- expect(- screen.queryByTestId("add-workspaces-button"),- ).not.toBeInTheDocument();-- await user.click(await screen.findByTestId("folder-browser-entry-dev"));- await screen.findByTestId("folder-browser-entry-repo2");- await user.click(screen.getByTestId("folder-browser-use"));-- await waitFor(() =>- expect(- screen.queryByTestId("folder-browser-modal"),- ).not.toBeInTheDocument(),- );-- // The same /Users/me/dev folder should be deduped, not duplicated, and- // its children should NOT have been imported as workspaces.- expect(- useWorkspacesStore- .getState()- .workspaces.map((w) => w.path)- .sort(),- ).toEqual(["/Users/me/dev"]);-- // Second pass: pick a child folder; it should be added as a single- // workspace (still no recursion into its subfolders).- await user.click(screen.getByTestId("workspace-dropdown"));- await user.click(await screen.findByTestId("add-workspaces-button"));- await screen.findByTestId("folder-browser-modal");- await user.click(await screen.findByTestId("folder-browser-entry-dev"));- await user.click(await screen.findByTestId("folder-browser-entry-repo1"));- await user.click(screen.getByTestId("folder-browser-use"));+ // Act+ await user.click(await screen.findByTestId("workspace-dropdown"));+ const menu = await screen.findByTestId("workspace-dropdown-menu");- await waitFor(() =>- expect(- screen.queryByTestId("folder-browser-modal"),- ).not.toBeInTheDocument(),- );-- expect(- useWorkspacesStore- .getState()- .workspaces.map((w) => w.path)- .sort(),- ).toEqual(["/Users/me/dev", "/Users/me/dev/repo1"]);- expect(searchSpy).toHaveBeenCalledWith("/Users/me/dev");+ // Assert+ expect(await within(menu).findByText("repo1")).toBeInTheDocument();});- it("Manage Workspaces lets you remove individual workspaces and clears the current selection", async () => {- const workspaces: LocalWorkspace[] = [- { id: "/Users/me/dev/repo1", name: "repo1", path: "/Users/me/dev/repo1" },- { id: "/Users/me/dev/repo2", name: "repo2", path: "/Users/me/dev/repo2" },- ];- renderForm(workspaces);- const user = userEvent.setup();- const launchButton = screen.getByTestId("workspace-launch-button");-- await user.click(screen.getByTestId("workspace-dropdown"));- const dropdownMenu = await screen.findByTestId("workspace-dropdown-menu");- await user.click(within(dropdownMenu).getByText("repo1"));- expect(launchButton).toBeEnabled();-- await user.click(screen.getByTestId("workspace-dropdown"));- await user.click(await screen.findByTestId("manage-workspaces-button"));-- await screen.findByTestId("manage-workspaces-modal");- await user.click(screen.getByTestId("manage-workspaces-remove-repo1"));-- expect(useWorkspacesStore.getState().workspaces.map((w) => w.path)).toEqual(- ["/Users/me/dev/repo1", "/Users/me/dev/repo2"],- );-- await screen.findByTestId("confirmation-modal");- await user.click(screen.getByTestId("confirm-button"));-- expect(useWorkspacesStore.getState().workspaces.map((w) => w.path)).toEqual(- ["/Users/me/dev/repo2"],- );- expect(launchButton).toBeDisabled();-- await user.click(screen.getByTestId("manage-workspaces-done"));- await waitFor(() =>- expect(- screen.queryByTestId("manage-workspaces-modal"),- ).not.toBeInTheDocument(),- );- });-- it("Manage Workspaces button is hidden when there are no workspaces", async () => {- renderForm([]);- const user = userEvent.setup();-- await user.click(screen.getByTestId("workspace-dropdown"));- await screen.findByTestId("add-workspaces-button");- expect(- screen.queryByTestId("manage-workspaces-button"),- ).not.toBeInTheDocument();- });-- it("Implicit /projects parent surfaces workspaces automatically", async () => {- const searchSpy = mockSearchSubdirectories;-+ it("Add Workspace dispatches addWorkspaces to the agent-server", async () => {+ // Arrange+ const addSpy = vi+ .spyOn(WorkspacesService, "addWorkspaces")+ .mockResolvedValue({ workspaces: [], workspaceParents: [] });mockSearchSubdirectories.mockImplementation(async (path: string) => {- if (path === "/projects") {- return {- items: [- { name: "demo-app", path: "/projects/demo-app" },- { name: "sample-tools", path: "/projects/sample-tools" },- ],- next_page_id: null,- };- }- return { items: [], next_page_id: null };- });-- renderForm();- const user = userEvent.setup();-- await user.click(screen.getByTestId("workspace-dropdown"));- const dropdownMenu = await screen.findByTestId("workspace-dropdown-menu");- await within(dropdownMenu).findByText("demo-app");- await within(dropdownMenu).findByText("sample-tools");-- expect(searchSpy).toHaveBeenCalledWith("/projects");- });-- it("Add Workspace starts at the /projects path and can save nested folders", async () => {- mockGetHome.mockResolvedValue({- home: "/home/openhands",- favorites: [{ label: "Downloads", path: "/home/openhands/Downloads" }],- locations: [],- });- mockSearchSubdirectories.mockImplementation(async (path: string) => {- if (path === "/projects") {- return {- items: [{ name: "demo-app", path: "/projects/demo-app" }],- next_page_id: null,- };- }- if (path === "/projects/demo-app") {+ if (path === "/Users/me") {return {- items: [- {- name: "web-client",- path: "/projects/demo-app/web-client",- },- ],+ items: [{ name: "dev", path: "/Users/me/dev" }],next_page_id: null,};}- if (path === "/projects/demo-app/web-client") {- return { items: [], next_page_id: null };- }return { items: [], next_page_id: null };});-renderForm();const user = userEvent.setup();- await user.click(screen.getByTestId("workspace-dropdown"));+ // Act+ await user.click(await screen.findByTestId("workspace-dropdown"));await user.click(await screen.findByTestId("add-workspaces-button"));-await screen.findByTestId("folder-browser-modal");- expect(- await screen.findByTestId("folder-browser-current-path"),- ).toHaveTextContent("/projects");- expect(- await screen.findByTestId("folder-browser-sidebar-/projects"),- ).toBeInTheDocument();- await user.click(- await screen.findByTestId("folder-browser-entry-demo-app"),- );- await user.click(- await screen.findByTestId("folder-browser-entry-web-client"),- );+ await user.click(await screen.findByTestId("folder-browser-entry-dev"));await user.click(screen.getByTestId("folder-browser-use"));- await waitFor(() =>- expect(- screen.queryByTestId("folder-browser-modal"),- ).not.toBeInTheDocument(),- );- expect(useWorkspacesStore.getState().workspaces.map((w) => w.path)).toEqual(- ["/projects/demo-app/web-client"],- );+ // Assert+ await waitFor(() => expect(addSpy).toHaveBeenCalledTimes(1));+ expect(addSpy).toHaveBeenCalledWith([+ { id: "/Users/me/dev", name: "dev", path: "/Users/me/dev" },+ ]);});- it("A stored /projects parent suppresses the implicit duplicate query", async () => {- const searchSpy = mockSearchSubdirectories.mockResolvedValue({- items: [],- next_page_id: null,+ it("Remove Workspace dispatches removeWorkspace to the agent-server", async () => {+ // Arrange+ const removeSpy = vi+ .spyOn(WorkspacesService, "removeWorkspace")+ .mockResolvedValue();+ renderForm({+ workspaces: [+ {+ id: "/Users/me/dev/repo1",+ name: "repo1",+ path: "/Users/me/dev/repo1",+ },+ ],});-- renderForm(- [],- [{ id: "custom-projects", name: "My Projects", path: "/projects" }],- );-- await waitFor(() => expect(searchSpy).toHaveBeenCalledTimes(1));- expect(searchSpy).toHaveBeenCalledWith("/projects");- });-- it("Launch creates a v1 conversation with the selected workspace path as working_dir", async () => {- const workspaces: LocalWorkspace[] = [- { id: "/Users/me/dev/repo1", name: "repo1", path: "/Users/me/dev/repo1" },- { id: "/Users/me/dev/repo2", name: "repo2", path: "/Users/me/dev/repo2" },- ];- const createSpy = vi- .spyOn(AgentServerConversationService, "createConversation")- .mockResolvedValue(makeStartTask({ app_conversation_id: "conv-xyz" }));-- renderForm(workspaces);const user = userEvent.setup();- await user.click(screen.getByTestId("workspace-dropdown"));- const items = await screen.findAllByText(/repo[12]/);- await user.click(items.find((el) => el.textContent === "repo2")!);- await user.click(screen.getByTestId("workspace-launch-button"));-- await waitFor(() => expect(createSpy).toHaveBeenCalledTimes(1));- expect(createSpy).toHaveBeenCalledWith(- undefined,- undefined,- undefined,- null,- "/Users/me/dev/repo2",- undefined,- undefined,- );- await waitFor(() =>- expect(mockNavigate).toHaveBeenCalledWith("/conversations/conv-xyz"),- );- });-- it("Launch button is disabled until a workspace is selected", async () => {- renderForm([- { id: "/Users/me/dev/repo1", name: "repo1", path: "/Users/me/dev/repo1" },- ]);-- const launchButton = screen.getByTestId("workspace-launch-button");- expect(launchButton).toBeDisabled();-- const user = userEvent.setup();- await user.click(screen.getByTestId("workspace-dropdown"));- await user.click(await screen.findByText("repo1"));-- expect(launchButton).toBeEnabled();- });-- it("disables the workspace dropdown while parent workspaces are loading", async () => {- mockSearchSubdirectories.mockReturnValue(new Promise(() => {}) as never);-- renderForm(- [],- [{ id: "/Users/me/dev", name: "dev", path: "/Users/me/dev" }],- );+ // Act+ await user.click(await screen.findByTestId("workspace-dropdown"));+ await user.click(await screen.findByTestId("manage-workspaces-button"));+ await screen.findByTestId("manage-workspaces-modal");+ await user.click(screen.getByTestId("manage-workspaces-remove-repo1"));+ await screen.findByTestId("confirmation-modal");+ await user.click(screen.getByTestId("confirm-button"));- await waitFor(() => {- expect(screen.getByTestId("workspace-dropdown")).toBeDisabled();- });- expect(screen.getByTestId("workspace-status-message")).toBeInTheDocument();+ // Assert+ await waitFor(() => expect(removeSpy).toHaveBeenCalledTimes(1));+ expect(removeSpy).toHaveBeenCalledWith("/Users/me/dev/repo1");});- it("Add all subdirectories saves a workspace parent and lists its children dynamically", async () => {- mockGetHome.mockResolvedValue({ home: "/Users/me" });- const searchSpy = mockSearchSubdirectories;-+ it("Add all subdirectories dispatches addWorkspaceParents to the agent-server", async () => {+ // Arrange+ const addParentsSpy = vi+ .spyOn(WorkspacesService, "addWorkspaceParents")+ .mockResolvedValue({ workspaces: [], workspaceParents: [] });mockSearchSubdirectories.mockImplementation(async (path: string) => {if (path === "/Users/me") {return {@@ -422,189 +193,22 @@ describe("WorkspaceSelectionForm", () => {next_page_id: null,};}- if (path === "/Users/me/dev") {- return {- items: [- { name: "repo1", path: "/Users/me/dev/repo1" },- { name: "repo2", path: "/Users/me/dev/repo2" },- ],- next_page_id: null,- };- }- throw new Error(`unexpected path ${path}`);+ return { items: [], next_page_id: null };});-renderForm();const user = userEvent.setup();- await user.click(screen.getByTestId("workspace-dropdown"));+ // Act+ await user.click(await screen.findByTestId("workspace-dropdown"));await user.click(await screen.findByTestId("add-workspaces-button"));-await screen.findByTestId("folder-browser-modal");await user.click(await screen.findByTestId("folder-browser-entry-dev"));- await screen.findByTestId("folder-browser-entry-repo1");-- // Click the "Add all subdirectories" button.await user.click(screen.getByTestId("folder-browser-add-all-subdirs"));- await waitFor(() =>- expect(- screen.queryByTestId("folder-browser-modal"),- ).not.toBeInTheDocument(),- );-- // The directory itself becomes a workspace parent, not a workspace.- expect(useWorkspacesStore.getState().workspaces).toEqual([]);- expect(- useWorkspacesStore.getState().workspaceParents.map((p) => p.path),- ).toEqual(["/Users/me/dev"]);-- // ...and its subdirectories surface as workspaces dynamically.- await user.click(screen.getByTestId("workspace-dropdown"));- const dynamicDropdown = await screen.findByTestId(- "workspace-dropdown-menu",- );- await within(dynamicDropdown).findByText("repo1");- await within(dynamicDropdown).findByText("repo2");-- expect(searchSpy).toHaveBeenCalledWith("/Users/me/dev");- });-- it("Removing a workspace parent stops listing its children", async () => {- // Scope the mock to the user-added parent so the implicit `/projects`- // parent (always queried by `useResolvedWorkspaces`) doesn't also get- // these entries.- const searchSpy = mockSearchSubdirectories;-- mockSearchSubdirectories.mockImplementation(async (path: string) => {- if (path === "/Users/me/dev") {- return {- items: [- { name: "repoA", path: "/Users/me/dev/repoA" },- { name: "repoB", path: "/Users/me/dev/repoB" },- ],- next_page_id: null,- };- }- return { items: [], next_page_id: null };- });-- renderForm(- [],- [{ id: "/Users/me/dev", name: "dev", path: "/Users/me/dev" }],- );-- const user = userEvent.setup();-- // Children should appear in the dropdown.- await user.click(screen.getByTestId("workspace-dropdown"));- const dropdownMenu = await screen.findByTestId("workspace-dropdown-menu");- await within(dropdownMenu).findByText("repoA");- await within(dropdownMenu).findByText("repoB");-- // Manage modal should expose a remove button for the parent.- await user.click(screen.getByTestId("manage-workspaces-button"));- await screen.findByTestId("manage-workspaces-modal");- expect(- screen.getByTestId("manage-workspaces-parent-row-dev"),- ).toBeInTheDocument();-- await user.click(screen.getByTestId("manage-workspaces-remove-parent-dev"));-- expect(useWorkspacesStore.getState().workspaceParents).toEqual([+ // Assert+ await waitFor(() => expect(addParentsSpy).toHaveBeenCalledTimes(1));+ expect(addParentsSpy).toHaveBeenCalledWith([{ id: "/Users/me/dev", name: "dev", path: "/Users/me/dev" },]);-- await screen.findByTestId("confirmation-modal");- await user.click(screen.getByTestId("confirm-button"));-- expect(useWorkspacesStore.getState().workspaceParents).toEqual([]);- expect(searchSpy).toHaveBeenCalledWith("/Users/me/dev");-- await user.click(screen.getByTestId("manage-workspaces-done"));- await waitFor(() =>- expect(- screen.queryByTestId("manage-workspaces-modal"),- ).not.toBeInTheDocument(),- );-- await user.click(screen.getByTestId("workspace-dropdown"));- const refreshedDropdown = await screen.findByTestId(- "workspace-dropdown-menu",- );- expect(- within(refreshedDropdown).queryByText("repoA"),- ).not.toBeInTheDocument();- expect(- within(refreshedDropdown).queryByText("repoB"),- ).not.toBeInTheDocument();- });-- it("invokes onConfirm with the selected workspace instead of creating a conversation when used in dialog mode", async () => {- const onConfirm = vi.fn();- const createSpy = vi.spyOn(- AgentServerConversationService,- "createConversation",- );-- renderForm(- [{ id: "/Users/me/dev/repo1", name: "repo1", path: "/Users/me/dev/repo1" }],- [],- { onConfirm },- );- const user = userEvent.setup();-- await user.click(screen.getByTestId("workspace-dropdown"));- await user.click(await screen.findByText("repo1"));- await user.click(screen.getByTestId("workspace-launch-button"));-- expect(onConfirm).toHaveBeenCalledTimes(1);- expect(onConfirm).toHaveBeenCalledWith({- id: "/Users/me/dev/repo1",- name: "repo1",- path: "/Users/me/dev/repo1",- });- expect(createSpy).not.toHaveBeenCalled();- expect(mockNavigate).not.toHaveBeenCalled();- });-- it("Add Workspace sidebar renders backend-provided favorites dynamically and navigates into them on click", async () => {- // Arrange: backend reports a home with a custom favorite that did NOT- // exist in the old hardcoded list (Documents / Desktop / Downloads).- // This is the regression guard for the original 404-on-navigate bug.- mockGetHome.mockResolvedValue({- home: "/Users/me",- favorites: [{ label: "projects", path: "/Users/me/projects" }],- locations: [{ label: "/", path: "/" }],- });- const searchSpy = mockSearchSubdirectories;- mockSearchSubdirectories.mockImplementation(async (path: string) => {- if (path === "/Users/me/projects") {- return {- items: [{ name: "repo1", path: "/Users/me/projects/repo1" }],- next_page_id: null,- };- }- return { items: [], next_page_id: null };- });-- renderForm();- const user = userEvent.setup();-- // Act: open the modal and click the dynamic favorite.- await user.click(screen.getByTestId("workspace-dropdown"));- await user.click(await screen.findByTestId("add-workspaces-button"));- await screen.findByTestId("folder-browser-modal");- await user.click(- await screen.findByTestId("folder-browser-sidebar-projects"),- );-- // Assert: the dynamic favorite drove the navigation, and the previously- // hardcoded names are no longer present in the sidebar.- await screen.findByTestId("folder-browser-entry-repo1");- expect(searchSpy).toHaveBeenCalledWith("/Users/me/projects");- expect(- screen.queryByTestId("folder-browser-sidebar-documents"),- ).not.toBeInTheDocument();});});diff --git a/src/api/workspaces-service/workspaces-service.api.ts b/src/api/workspaces-service/workspaces-service.api.tsnew file mode 100644index 0000000000..e17dea616d--- /dev/null+++ b/src/api/workspaces-service/workspaces-service.api.ts@@ -0,0 +1,63 @@+/**+ * WorkspacesService talks to the agent-server's /api/workspaces endpoints,+ * which persist the user's saved workspaces and workspace parents on the+ * server (workspace/.openhands/workspaces.json). All clients pointed at+ * the same agent-server see the same list.+ *+ * No SDK client exists for this resource yet, so we call HttpClient directly+ * β the same pattern used elsewhere (e.g. switch_llm in the conversation+ * service). The lint test at src/api/no-direct-agent-server-calls.test.ts+ * allows HttpClient and only rejects raw axios / createHttpClient.+ */+import { HttpClient } from "@openhands/typescript-client/client/http-client";++import { LocalWorkspace, LocalWorkspaceParent } from "#/types/workspace";++import { getAgentServerHttpClientOptions } from "../agent-server-client-options";++export interface WorkspacesListResponse {+ workspaces: LocalWorkspace[];+ workspaceParents: LocalWorkspaceParent[];+}++function client() {+ return new HttpClient(getAgentServerHttpClientOptions());+}++class WorkspacesService {+ static async listWorkspaces(): Promise<WorkspacesListResponse> {+ const res = await client().get<WorkspacesListResponse>("/api/workspaces");+ return res.data;+ }++ static async addWorkspaces(+ items: LocalWorkspace[],+ ): Promise<WorkspacesListResponse> {+ const res = await client().post<WorkspacesListResponse>("/api/workspaces", {+ workspaces: items,+ });+ return res.data;+ }++ static async removeWorkspace(path: string): Promise<void> {+ await client().delete(`/api/workspaces?path=${encodeURIComponent(path)}`);+ }++ static async addWorkspaceParents(+ items: LocalWorkspaceParent[],+ ): Promise<WorkspacesListResponse> {+ const res = await client().post<WorkspacesListResponse>(+ "/api/workspaces/parents",+ { parents: items },+ );+ return res.data;+ }++ static async removeWorkspaceParent(path: string): Promise<void> {+ await client().delete(+ `/api/workspaces/parents?path=${encodeURIComponent(path)}`,+ );+ }+}++export default WorkspacesService;diff --git a/src/components/features/conversation-panel/local-new-conversation-menu.tsx b/src/components/features/conversation-panel/local-new-conversation-menu.tsxindex 1e18f0c39a..dc47d68107 100644--- a/src/components/features/conversation-panel/local-new-conversation-menu.tsx+++ b/src/components/features/conversation-panel/local-new-conversation-menu.tsx@@ -4,7 +4,13 @@ import { useTranslation } from "react-i18next";import { useCreateConversation } from "#/hooks/mutation/use-create-conversation";import { useNavigation } from "#/context/navigation-context";import { useIsCreatingConversation } from "#/hooks/use-is-creating-conversation";-import { useWorkspacesStore } from "#/stores/workspaces-store";+import {+ useAddWorkspaces,+ useAddWorkspaceParents,+ useRemoveWorkspace,+ useRemoveWorkspaceParent,+} from "#/hooks/mutation/use-local-workspaces-mutations";+import { useLocalWorkspaces } from "#/hooks/query/use-local-workspaces";import { useResolvedWorkspaces } from "#/hooks/query/use-resolved-workspaces";import { I18nKey } from "#/i18n/declaration";import { cn } from "#/utils/utils";@@ -62,13 +68,12 @@ export function LocalNewConversationMenu({enabled: useFixedPlacement,});- const {- workspaceParents,- addWorkspaces,- removeWorkspace,- addWorkspaceParents,- removeWorkspaceParent,- } = useWorkspacesStore();+ const { data: workspacesData } = useLocalWorkspaces();+ const workspaceParents = workspacesData?.workspaceParents ?? [];+ const { mutate: addWorkspaces } = useAddWorkspaces();+ const { mutate: removeWorkspace } = useRemoveWorkspace();+ const { mutate: addWorkspaceParents } = useAddWorkspaceParents();+ const { mutate: removeWorkspaceParent } = useRemoveWorkspaceParent();const { workspaces } = useResolvedWorkspaces();const [browserOpen, setBrowserOpen] = React.useState(false);const [manageOpen, setManageOpen] = React.useState(false);diff --git a/src/components/features/home/workspace-selection-form.tsx b/src/components/features/home/workspace-selection-form.tsxindex 90fe49a245..2ae5d34bc2 100644--- a/src/components/features/home/workspace-selection-form.tsx+++ b/src/components/features/home/workspace-selection-form.tsx@@ -4,7 +4,13 @@ import { useTranslation } from "react-i18next";import { useCreateConversation } from "#/hooks/mutation/use-create-conversation";import { useNavigation } from "#/context/navigation-context";import { useIsCreatingConversation } from "#/hooks/use-is-creating-conversation";-import { useWorkspacesStore } from "#/stores/workspaces-store";+import {+ useAddWorkspaces,+ useAddWorkspaceParents,+ useRemoveWorkspace,+ useRemoveWorkspaceParent,+} from "#/hooks/mutation/use-local-workspaces-mutations";+import { useLocalWorkspaces } from "#/hooks/query/use-local-workspaces";import { useResolvedWorkspaces } from "#/hooks/query/use-resolved-workspaces";import { LocalWorkspace } from "#/types/workspace";import { I18nKey } from "#/i18n/declaration";@@ -34,13 +40,12 @@ export function WorkspaceSelectionForm({const { t } = useTranslation("openhands");const { navigate } = useNavigation();- const {- workspaceParents,- addWorkspaces,- removeWorkspace,- addWorkspaceParents,- removeWorkspaceParent,- } = useWorkspacesStore();+ const { data: workspacesData } = useLocalWorkspaces();+ const workspaceParents = workspacesData?.workspaceParents ?? [];+ const { mutate: addWorkspaces } = useAddWorkspaces();+ const { mutate: removeWorkspace } = useRemoveWorkspace();+ const { mutate: addWorkspaceParents } = useAddWorkspaceParents();+ const { mutate: removeWorkspaceParent } = useRemoveWorkspaceParent();const {workspaces,isLoading: isLoadingWorkspaces,diff --git a/src/hooks/mutation/use-local-workspaces-mutations.ts b/src/hooks/mutation/use-local-workspaces-mutations.tsnew file mode 100644index 0000000000..7f8d51884e--- /dev/null+++ b/src/hooks/mutation/use-local-workspaces-mutations.ts@@ -0,0 +1,51 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";++import WorkspacesService from "#/api/workspaces-service/workspaces-service.api";+import { LOCAL_WORKSPACES_QUERY_KEYS } from "#/hooks/query/query-keys";+import { LocalWorkspace, LocalWorkspaceParent } from "#/types/workspace";++export function useAddWorkspaces() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (items: LocalWorkspace[]) =>+ WorkspacesService.addWorkspaces(items),+ onSuccess: () =>+ queryClient.invalidateQueries({+ queryKey: LOCAL_WORKSPACES_QUERY_KEYS.all,+ }),+ });+}++export function useRemoveWorkspace() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (path: string) => WorkspacesService.removeWorkspace(path),+ onSuccess: () =>+ queryClient.invalidateQueries({+ queryKey: LOCAL_WORKSPACES_QUERY_KEYS.all,+ }),+ });+}++export function useAddWorkspaceParents() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (items: LocalWorkspaceParent[]) =>+ WorkspacesService.addWorkspaceParents(items),+ onSuccess: () =>+ queryClient.invalidateQueries({+ queryKey: LOCAL_WORKSPACES_QUERY_KEYS.all,+ }),+ });+}++export function useRemoveWorkspaceParent() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (path: string) => WorkspacesService.removeWorkspaceParent(path),+ onSuccess: () =>+ queryClient.invalidateQueries({+ queryKey: LOCAL_WORKSPACES_QUERY_KEYS.all,+ }),+ });+}diff --git a/src/hooks/query/query-keys.ts b/src/hooks/query/query-keys.tsindex 6b45f8f899..2cf1a5ad07 100644--- a/src/hooks/query/query-keys.ts+++ b/src/hooks/query/query-keys.ts@@ -20,6 +20,10 @@ export const LLM_PROFILES_QUERY_KEYS = {all: ["llm-profiles"] as const,} as const;+export const LOCAL_WORKSPACES_QUERY_KEYS = {+ all: ["local-workspaces"] as const,+} as const;+/** Cache configuration shared across all config-related queries */export const CONFIG_CACHE_OPTIONS = {staleTime: 1000 * 60 * 5, // 5 minutesdiff --git a/src/hooks/query/use-local-workspaces.ts b/src/hooks/query/use-local-workspaces.tsnew file mode 100644index 0000000000..aa5e59245b--- /dev/null+++ b/src/hooks/query/use-local-workspaces.ts@@ -0,0 +1,14 @@+import { useQuery } from "@tanstack/react-query";++import WorkspacesService, {+ WorkspacesListResponse,+} from "#/api/workspaces-service/workspaces-service.api";+import { LOCAL_WORKSPACES_QUERY_KEYS } from "#/hooks/query/query-keys";++export function useLocalWorkspaces() {+ return useQuery<WorkspacesListResponse>({+ queryKey: LOCAL_WORKSPACES_QUERY_KEYS.all,+ queryFn: () => WorkspacesService.listWorkspaces(),+ staleTime: 60_000,+ });+}diff --git a/src/hooks/query/use-resolved-workspaces.ts b/src/hooks/query/use-resolved-workspaces.tsindex d886065470..c9860c7300 100644--- a/src/hooks/query/use-resolved-workspaces.ts+++ b/src/hooks/query/use-resolved-workspaces.ts@@ -3,7 +3,7 @@ import { useQueries } from "@tanstack/react-query";import { FileClient } from "@openhands/typescript-client/clients";import { getAgentServerClientOptions } from "#/api/agent-server-client-options";-import { useWorkspacesStore } from "#/stores/workspaces-store";+import { useLocalWorkspaces } from "#/hooks/query/use-local-workspaces";import { LocalWorkspace, LocalWorkspaceParent } from "#/types/workspace";interface UseResolvedWorkspacesResult {@@ -41,8 +41,13 @@ const IMPLICIT_WORKSPACE_PARENTS: LocalWorkspaceParent[] = [* same path so that user-selected names/ids are preserved.*/export function useResolvedWorkspaces(): UseResolvedWorkspacesResult {- const workspaces = useWorkspacesStore((s) => s.workspaces);- const storedParents = useWorkspacesStore((s) => s.workspaceParents);+ const {+ data,+ isLoading: isLoadingList,+ isError: isErrorList,+ } = useLocalWorkspaces();+ const workspaces = data?.workspaces ?? [];+ const storedParents = data?.workspaceParents ?? [];// Merge stored parents with the implicit ones, deduping on path so a// user-added `/projects` doesn't trigger a second query.@@ -69,8 +74,8 @@ export function useResolvedWorkspaces(): UseResolvedWorkspacesResult {})),});- const isLoading = parentQueries.some((q) => q.isLoading);- const isError = parentQueries.some((q) => q.isError);+ const isLoading = isLoadingList || parentQueries.some((q) => q.isLoading);+ const isError = isErrorList || parentQueries.some((q) => q.isError);// Stable string fingerprint that changes whenever any parent's subdir// results change. Avoids spreading timestamps into the `useMemo` deps,diff --git a/src/stores/workspaces-store.ts b/src/stores/workspaces-store.tsdeleted file mode 100644index 4cbd0d140e..0000000000--- a/src/stores/workspaces-store.ts+++ /dev/null@@ -1,75 +0,0 @@-import { create } from "zustand";-import { persist, createJSONStorage } from "zustand/middleware";-import { LocalWorkspace, LocalWorkspaceParent } from "#/types/workspace";--interface WorkspacesState {- workspaces: LocalWorkspace[];- workspaceParents: LocalWorkspaceParent[];-}--interface WorkspacesActions {- addWorkspaces: (items: LocalWorkspace[]) => void;- removeWorkspace: (path: string) => void;- clearWorkspaces: () => void;- addWorkspaceParents: (items: LocalWorkspaceParent[]) => void;- removeWorkspaceParent: (path: string) => void;- clearWorkspaceParents: () => void;- clearAll: () => void;-}--type WorkspacesStore = WorkspacesState & WorkspacesActions;--const initialState: WorkspacesState = {- workspaces: [],- workspaceParents: [],-};--export const useWorkspacesStore = create<WorkspacesStore>()(- persist(- (set) => ({- ...initialState,-- addWorkspaces: (items: LocalWorkspace[]) =>- set((state) => {- const existingPaths = new Set(state.workspaces.map((w) => w.path));- const newOnes = items.filter((item) => !existingPaths.has(item.path));- if (newOnes.length === 0) return state;- return { workspaces: [...state.workspaces, ...newOnes] };- }),-- removeWorkspace: (path: string) =>- set((state) => ({- workspaces: state.workspaces.filter((w) => w.path !== path),- })),-- clearWorkspaces: () => set(() => ({ workspaces: [] })),-- addWorkspaceParents: (items: LocalWorkspaceParent[]) =>- set((state) => {- const existingPaths = new Set(- state.workspaceParents.map((p) => p.path),- );- const newOnes = items.filter((item) => !existingPaths.has(item.path));- if (newOnes.length === 0) return state;- return {- workspaceParents: [...state.workspaceParents, ...newOnes],- };- }),-- removeWorkspaceParent: (path: string) =>- set((state) => ({- workspaceParents: state.workspaceParents.filter(- (p) => p.path !== path,- ),- })),-- clearWorkspaceParents: () => set(() => ({ workspaceParents: [] })),-- clearAll: () => set(() => ({ workspaces: [], workspaceParents: [] })),- }),- {- name: "workspaces-store",- storage: createJSONStorage(() => localStorage),- },- ),-);