Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(mocks): stub /api/mcp/test so MCP install flow completes in mock … (#949)

chuckbutkus357e0c8b56d4
diff --git a/__tests__/api/mock-workspaces-handlers.test.ts b/__tests__/api/mock-workspaces-handlers.test.ts
new file mode 100644
index 0000000000..e81b65af12
--- /dev/null
+++ b/__tests__/api/mock-workspaces-handlers.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, describe, expect, it } from "vitest";
+
+import WorkspacesService from "#/api/workspaces-service/workspaces-service.api";
+import { resetMockWorkspaces } from "#/mocks/handlers";
+
+describe("mock workspaces handlers", () => {
+ afterEach(() => {
+ resetMockWorkspaces();
+ });
+
+ it("starts with an empty workspaces list", async () => {
+ const response = await WorkspacesService.listWorkspaces();
+ expect(response.workspaces).toEqual([]);
+ expect(response.workspaceParents).toEqual([]);
+ });
+
+ it("persists added workspaces across list calls", async () => {
+ await WorkspacesService.addWorkspaces([
+ { id: "w1", name: "Project", path: "/workspace/project" },
+ ]);
+
+ const response = await WorkspacesService.listWorkspaces();
+ expect(response.workspaces).toEqual([
+ { id: "w1", name: "Project", path: "/workspace/project" },
+ ]);
+ });
+
+ it("upserts a workspace when path already exists", async () => {
+ await WorkspacesService.addWorkspaces([
+ { id: "w1", name: "Old", path: "/workspace/project" },
+ ]);
+ await WorkspacesService.addWorkspaces([
+ { id: "w2", name: "New", path: "/workspace/project" },
+ ]);
+ const response = await WorkspacesService.listWorkspaces();
+ expect(response.workspaces).toHaveLength(1);
+ expect(response.workspaces[0].name).toBe("New");
+ });
+
+ it("removes a workspace by path", async () => {
+ await WorkspacesService.addWorkspaces([
+ { id: "w1", name: "Project", path: "/workspace/project" },
+ { id: "w2", name: "Other", path: "/workspace/other" },
+ ]);
+
+ await WorkspacesService.removeWorkspace("/workspace/project");
+
+ const response = await WorkspacesService.listWorkspaces();
+ expect(response.workspaces.map((w) => w.path)).toEqual([
+ "/workspace/other",
+ ]);
+ });
+
+ it("persists workspace parents and removes them by path", async () => {
+ await WorkspacesService.addWorkspaceParents([
+ { id: "p1", name: "Repos", path: "/workspace/repos" },
+ ]);
+
+ const afterAdd = await WorkspacesService.listWorkspaces();
+ expect(afterAdd.workspaceParents).toEqual([
+ { id: "p1", name: "Repos", path: "/workspace/repos" },
+ ]);
+
+ await WorkspacesService.removeWorkspaceParent("/workspace/repos");
+
+ const afterRemove = await WorkspacesService.listWorkspaces();
+ expect(afterRemove.workspaceParents).toEqual([]);
+ });
+});
diff --git a/src/mocks/handlers.ts b/src/mocks/handlers.ts
index bebb5edf92..6b074e3b76 100644
--- a/src/mocks/handlers.ts
+++ b/src/mocks/handlers.ts
@@ -18,6 +18,11 @@ import {
AUTOMATION_HANDLERS,
resetAutomationMockData,
} from "./automation-handlers";
+import { MCP_HANDLERS } from "./mcp-handlers";
+import {
+ WORKSPACES_HANDLERS,
+ resetMockWorkspaces,
+} from "./workspaces-handlers";
export const handlers = [
...FILE_SERVICE_HANDLERS,
@@ -30,11 +35,14 @@ export const handlers = [
...FEEDBACK_HANDLERS,
...ANALYTICS_HANDLERS,
...AUTOMATION_HANDLERS,
+ ...MCP_HANDLERS,
+ ...WORKSPACES_HANDLERS,
];
export {
MOCK_DEFAULT_USER_SETTINGS,
resetTestHandlersMockSettings,
resetAutomationMockData,
+ resetMockWorkspaces,
setMockGitChanges,
};
diff --git a/src/mocks/mcp-handlers.ts b/src/mocks/mcp-handlers.ts
new file mode 100644
index 0000000000..3ff92b1789
--- /dev/null
+++ b/src/mocks/mcp-handlers.ts
@@ -0,0 +1,24 @@
+import { http, HttpResponse } from "msw";
+import type { MCPTestResponse } from "@openhands/typescript-client";
+
+/**
+ * MSW handlers for the MCP API.
+ *
+ * Currently only the pre-flight connectivity check (`POST /api/mcp/test`)
+ * needs a mock β€” the install/save flow in `InstallServerModal` and
+ * `CustomServerEditor` calls it before persisting the new server via the
+ * existing settings PATCH. In mock mode there is no real MCP server to
+ * connect to, so we return a deterministic success response so the install
+ * flow can complete in both `npm run dev:mock` and the Playwright snapshot
+ * tests.
+ */
+const MOCK_MCP_TEST_SUCCESS: MCPTestResponse = {
+ ok: true,
+ tools: [],
+};
+
+export const MCP_HANDLERS = [
+ http.post("*/api/mcp/test", async () =>
+ HttpResponse.json(MOCK_MCP_TEST_SUCCESS),
+ ),
+];
diff --git a/src/mocks/workspaces-handlers.ts b/src/mocks/workspaces-handlers.ts
new file mode 100644
index 0000000000..f5048cf614
--- /dev/null
+++ b/src/mocks/workspaces-handlers.ts
@@ -0,0 +1,105 @@
+import { http, HttpResponse } from "msw";
+import type {
+ WorkspaceItem,
+ WorkspaceParentItem,
+ WorkspacesListResponse,
+} from "@openhands/typescript-client/clients";
+
+/**
+ * MSW handlers for the agent-server's `/api/workspaces` and
+ * `/api/auth/workspace-session` endpoints used by `useLocalWorkspaces`,
+ * `WorkspacesService`, and `useWorkspaceSession`.
+ *
+ * Without these handlers, mock-mode renders of the home / sidebar /
+ * conversation pages let those requests fall through to the Vite proxy
+ * (`127.0.0.1:8000` ECONNREFUSED), which spams the snapshot-test logs and
+ * surfaces global error toasts in the captured screenshots.
+ *
+ * The mock keeps an in-memory list so the install / remove flow round-trips
+ * cleanly within a single page load. State resets on every test reload.
+ */
+
+let workspaces: WorkspaceItem[] = [];
+let workspaceParents: WorkspaceParentItem[] = [];
+
+function snapshot(): WorkspacesListResponse {
+ return {
+ workspaces: workspaces.map((w) => ({ ...w })),
+ workspaceParents: workspaceParents.map((p) => ({ ...p })),
+ };
+}
+
+export function resetMockWorkspaces(): void {
+ workspaces = [];
+ workspaceParents = [];
+}
+
+export const WORKSPACES_HANDLERS = [
+ http.get("*/api/workspaces", async () => HttpResponse.json(snapshot())),
+
+ http.post("*/api/workspaces", async ({ request }) => {
+ // `workspaces` is the top-level key used by WorkspacesClient.addWorkspaces()
+ // in @openhands/typescript-client β€” aligns with the agent-server SDK contract.
+ const body = (await request.json()) as { workspaces?: WorkspaceItem[] };
+ for (const incoming of body.workspaces ?? []) {
+ const existingIndex = workspaces.findIndex(
+ (w) => w.path === incoming.path,
+ );
+ if (existingIndex >= 0) {
+ workspaces[existingIndex] = { ...incoming };
+ } else {
+ workspaces.push({ ...incoming });
+ }
+ }
+ return HttpResponse.json(snapshot());
+ }),
+
+ http.delete("*/api/workspaces", async ({ request }) => {
+ const url = new URL(request.url);
+ const path = url.searchParams.get("path");
+ const before = workspaces.length;
+ workspaces = workspaces.filter((w) => w.path !== path);
+ // WorkspacesService.removeWorkspace() discards the response body (returns
+ // void), so the shape here is mock-only and not coupled to the real contract.
+ return HttpResponse.json({ deleted: workspaces.length !== before });
+ }),
+
+ http.post("*/api/workspaces/parents", async ({ request }) => {
+ const body = (await request.json()) as { parents?: WorkspaceParentItem[] };
+ for (const incoming of body.parents ?? []) {
+ const existingIndex = workspaceParents.findIndex(
+ (p) => p.path === incoming.path,
+ );
+ if (existingIndex >= 0) {
+ workspaceParents[existingIndex] = { ...incoming };
+ } else {
+ workspaceParents.push({ ...incoming });
+ }
+ }
+ return HttpResponse.json(snapshot());
+ }),
+
+ http.delete("*/api/workspaces/parents", async ({ request }) => {
+ const url = new URL(request.url);
+ const path = url.searchParams.get("path");
+ const before = workspaceParents.length;
+ workspaceParents = workspaceParents.filter((p) => p.path !== path);
+ // WorkspacesService.removeWorkspaceParent() discards the response body
+ // (returns void), so the shape here is mock-only and not coupled to the
+ // real contract.
+ return HttpResponse.json({ deleted: workspaceParents.length !== before });
+ }),
+
+ // Workspace static-asset session: minted on conversation pages by
+ // `useWorkspaceSession`. The real endpoint sets an HttpOnly cookie; in
+ // mock mode we just acknowledge the POST/DELETE so the call doesn't fall
+ // through to the Vite proxy.
+ http.post("*/api/auth/workspace-session", async () =>
+ HttpResponse.json({ ok: true }),
+ ),
+
+ http.delete(
+ "*/api/auth/workspace-session",
+ async () => new HttpResponse(null, { status: 204 }),
+ ),
+];
diff --git a/tests/e2e/snapshots/skills-page.snapshot.spec.ts b/tests/e2e/snapshots/skills-page.snapshot.spec.ts
index ca55e91df4..7de576b121 100644
--- a/tests/e2e/snapshots/skills-page.snapshot.spec.ts
+++ b/tests/e2e/snapshots/skills-page.snapshot.spec.ts
@@ -89,17 +89,23 @@ async function setupMocks(page: Page) {
async function seedSkills(page: Page, skills = MOCK_SKILLS) {
await page.waitForFunction(
() =>
- !!(window as unknown as { __OH_QUERY_CLIENT__?: unknown }).__OH_QUERY_CLIENT__,
+ !!(window as unknown as { __OH_QUERY_CLIENT__?: unknown })
+ .__OH_QUERY_CLIENT__,
{ timeout: 10_000 },
);
await page.evaluate((skillsData) => {
+ // Matches the `useSkills` queryKey: `["skills", projectDir ?? null]`.
+ // The global Skills page calls `useSkills()` with no projectDir, so the
+ // key resolves to `["skills", null]`. Seeding with the bare `["skills"]`
+ // tuple (as the test originally did) misses the cache entry and the
+ // skill cards never render.
(
window as unknown as {
__OH_QUERY_CLIENT__: {
setQueryData: (key: unknown[], data: unknown) => void;
};
}
- ).__OH_QUERY_CLIENT__.setQueryData(["skills"], skillsData);
+ ).__OH_QUERY_CLIENT__.setQueryData(["skills", null], skillsData);
}, skills);
await page.waitForTimeout(200);
}