Skip to content

πŸ™Œ OpenHands: AI-Driven Development

test: cover conversation and workspace mock contracts (#17369)

aivong-openhandsf685a4511160
diff --git a/__tests__/api/mock-conversation-handlers.test.ts b/__tests__/api/mock-conversation-handlers.test.ts
index 6c95efe0a1..658ebd3014 100644
--- a/__tests__/api/mock-conversation-handlers.test.ts
+++ b/__tests__/api/mock-conversation-handlers.test.ts
@@ -1,14 +1,78 @@
-import { describe, expect, it } from "vitest";
+import { createServer } from "node:http";
+import { http, HttpResponse } from "msw";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
import AgentServerGitService from "#/api/git-service/agent-server-git-service.api";
import EventService from "#/api/event-service/event-service.api";
-import { TABLE_DEMO_CONVERSATION_ID } from "#/fixtures/table-demo-conversation";
import {
CANVAS_DEMO_CONVERSATION_ID,
CANVAS_DEMO_FILE_PATH,
+ CANVAS_DEMO_MARKDOWN,
} from "#/fixtures/canvas-demo-conversation";
+import { TABLE_DEMO_CONVERSATION_ID } from "#/fixtures/table-demo-conversation";
+import { server } from "#/mocks/node";
+import { ExecutionStatus } from "#/types/agent-server/core";
+
+const API_BASE = "http://localhost:3000";
+
+// Catch-all so any request the conversation handlers do not match surfaces as
+// an explicit 599 instead of falling through to the Vite proxy (ECONNREFUSED).
+const UNHANDLED_REQUESTS = [
+ http.all("*", () =>
+ HttpResponse.json({ error: "Unhandled request" }, { status: 599 }),
+ ),
+];
+
+type MockConversationResponse = {
+ agent: unknown | null;
+ created_at: string;
+ execution_status: string;
+ id: string;
+ metrics: unknown | null;
+ sandbox_status: string | null;
+ title: string | null;
+ updated_at: string;
+ workspace: { working_dir: string } | null;
+};
+
+const requestJson = async <T>(path: string, init?: RequestInit) => {
+ const response = await fetch(`${API_BASE}${path}`, init);
+ return {
+ body: (await response.json()) as T,
+ status: response.status,
+ };
+};
+
+const cloudProxy = <T>(path?: string) =>
+ requestJson<T>("/api/cloud-proxy", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(path === undefined ? {} : { method: "GET", path }),
+ });
describe("mock conversation handlers", () => {
+ // Re-import the handler module inside each test (mirroring the workspaces
+ // suite) so the MSW handler array is rebuilt in the test's runtime context.
+ // This resets the in-memory conversation store between tests and β€” because
+ // the resolver array is constructed here rather than once at module load β€”
+ // lets Stryker's per-test mutants actually take effect against these
+ // handlers. `resetHandlers` (replace, not append) drops the default base
+ // handlers so a mutated-away route has no unmutated duplicate to fall back
+ // to. The git-repository handlers are included for the git-changes case.
+ beforeEach(async () => {
+ vi.resetModules();
+ const [{ CONVERSATION_HANDLERS }, { GIT_REPOSITORY_HANDLERS }] =
+ await Promise.all([
+ import("#/mocks/conversation-handlers"),
+ import("#/mocks/git-repository-handlers"),
+ ]);
+ server.resetHandlers(
+ ...CONVERSATION_HANDLERS,
+ ...GIT_REPOSITORY_HANDLERS,
+ ...UNHANDLED_REQUESTS,
+ );
+ });
+
it("returns adapted conversations for batch lookups", async () => {
const [conversation] =
await AgentServerConversationService.batchGetAppConversations(["1"]);
@@ -55,6 +119,7 @@ describe("mock conversation handlers", () => {
expect(conversation?.id).toBe(TABLE_DEMO_CONVERSATION_ID);
expect(conversation?.title).toBe("Wide table demo");
+ expect(conversation?.workspace?.working_dir?.trim()).toBeTruthy();
});
it("returns table demo events sorted for conversation history", async () => {
@@ -70,6 +135,518 @@ describe("mock conversation handlers", () => {
expect(page.items[1]?.source).toBe("user");
});
+ it("lists conversations in update order and honors the requested limit", async () => {
+ const defaultPage = await requestJson<{
+ items: { id: string; updated_at: string }[];
+ next_page_id: string | null;
+ }>("/api/conversations/search");
+ const limitedPage = await requestJson<{
+ items: { id: string; updated_at: string }[];
+ next_page_id: string | null;
+ }>("/api/conversations/search?limit=2");
+
+ expect(defaultPage.status).toBe(200);
+ expect(defaultPage.body.items.length).toBeGreaterThan(2);
+ expect(defaultPage.body.items.map(({ updated_at }) => updated_at)).toEqual(
+ [...defaultPage.body.items]
+ .map(({ updated_at }) => updated_at)
+ .sort((a, b) => b.localeCompare(a)),
+ );
+ expect(defaultPage.body.next_page_id).toBeNull();
+ expect(limitedPage.body.items).toEqual(defaultPage.body.items.slice(0, 2));
+ });
+
+ it("supports unfiltered, plain, and bracketed batch conversation lookups", async () => {
+ const all =
+ await requestJson<MockConversationResponse[]>("/api/conversations");
+ for (const conversation of all.body) {
+ expect(Object.values(ExecutionStatus)).toContain(
+ conversation.execution_status,
+ );
+ }
+ const plainIds = await requestJson<(MockConversationResponse | null)[]>(
+ "/api/conversations?ids=1&ids=missing",
+ );
+ const bracketedIds = await requestJson<(MockConversationResponse | null)[]>(
+ "/api/conversations?ids%5B%5D=2&ids%5B%5D=missing",
+ );
+
+ expect(all.body).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: "4",
+ sandbox_status: "MISSING",
+ workspace: null,
+ }),
+ expect.objectContaining({
+ id: "pagination-local",
+ sandbox_status: null,
+ workspace: { working_dir: "/workspace/project" },
+ }),
+ ]),
+ );
+ expect(plainIds.body).toEqual([
+ {
+ agent: null,
+ created_at: expect.any(String),
+ execution_status: "waiting_for_confirmation",
+ id: "1",
+ metrics: null,
+ sandbox_status: null,
+ tags: { project: "vault", work: "" },
+ title: "My New Project",
+ updated_at: expect.any(String),
+ workspace: null,
+ },
+ null,
+ ]);
+ expect(bracketedIds.body).toEqual([
+ expect.objectContaining({ id: "2" }),
+ null,
+ ]);
+ });
+
+ it("returns a conversation by id and reports an unknown id", async () => {
+ const found = await requestJson<{
+ id: string;
+ title: string | null;
+ execution_status: string;
+ }>("/api/conversations/5");
+ const missing = await requestJson<null>(
+ "/api/conversations/does-not-exist",
+ );
+
+ expect(found).toEqual({
+ body: {
+ agent: null,
+ created_at: expect.any(String),
+ metrics: null,
+ id: "5",
+ title: "Errored Project",
+ execution_status: "idle",
+ sandbox_status: "ERROR",
+ tags: null,
+ updated_at: expect.any(String),
+ workspace: null,
+ },
+ status: 200,
+ });
+ expect(missing).toEqual({ body: null, status: 404 });
+ });
+
+ it("creates, renames, and deletes a conversation through its lifecycle", async () => {
+ const random = vi.spyOn(Math, "random").mockReturnValue(0.42424);
+
+ try {
+ const created = await requestJson<{
+ id: string;
+ title: string;
+ execution_status: string;
+ }>("/api/conversations", { method: "POST" });
+
+ expect(created).toEqual({
+ body: {
+ agent: null,
+ created_at: expect.any(String),
+ id: "42424",
+ metrics: null,
+ sandbox_status: null,
+ tags: null,
+ title: "New Conversation",
+ execution_status: "idle",
+ updated_at: expect.any(String),
+ workspace: null,
+ },
+ status: 201,
+ });
+
+ const renamed = await requestJson<null>("/api/conversations/42424", {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ title: "Renamed Conversation" }),
+ });
+ const afterRename = await requestJson<{ title: string }>(
+ "/api/conversations/42424",
+ );
+ const deleted = await requestJson<null>("/api/conversations/42424", {
+ method: "DELETE",
+ });
+ const afterDelete = await requestJson<null>("/api/conversations/42424");
+ const deletedAgain = await requestJson<null>("/api/conversations/42424", {
+ method: "DELETE",
+ });
+
+ expect(renamed).toEqual({ body: null, status: 200 });
+ expect(afterRename.body.title).toBe("Renamed Conversation");
+ expect(deleted).toEqual({ body: null, status: 200 });
+ expect(afterDelete).toEqual({ body: null, status: 404 });
+ expect(deletedAgain).toEqual({ body: null, status: 404 });
+ } finally {
+ random.mockRestore();
+ }
+ });
+
+ it("passes unrelated workspace files through to the backing server", async () => {
+ const backingServer = createServer((_request, response) => {
+ response.writeHead(200, { "Content-Type": "text/plain" });
+ response.end("unrelated workspace file");
+ });
+ await new Promise<void>((resolve) =>
+ backingServer.listen(0, "127.0.0.1", resolve),
+ );
+ try {
+ const address = backingServer.address();
+ if (!address || typeof address === "string")
+ throw new Error("Expected TCP address");
+ // Exercise the mock HTTP passthrough contract against a controlled local server.
+
+ for (const [conversationId, path] of [
+ ["1", "unrelated.txt"],
+ ["1", CANVAS_DEMO_FILE_PATH],
+ [CANVAS_DEMO_CONVERSATION_ID, "unrelated.txt"],
+ ]) {
+ // eslint-disable-next-line local/no-direct-agent-server-fetch -- Exercise HTTP passthrough against the controlled backing server.
+ const response = await fetch(
+ `http://127.0.0.1:${address.port}/api/conversations/${conversationId}/workspace/${path}`,
+ );
+ expect(response.status).toBe(200);
+ expect(await response.text()).toBe("unrelated workspace file");
+ }
+ } finally {
+ await new Promise<void>((resolve, reject) =>
+ backingServer.close((error) => (error ? reject(error) : resolve())),
+ );
+ }
+ });
+
+ it("replaces tags without changing the existing title", async () => {
+ const before = await requestJson<{ title: string }>("/api/conversations/1");
+ const updated = await requestJson<null>("/api/conversations/1", {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ tags: { owner: "alice" } }),
+ });
+ expect(updated.status).toBe(200);
+ const after = await requestJson<{
+ title: string;
+ tags: Record<string, string>;
+ }>("/api/conversations/1");
+ expect(after.body.title).toBe(before.body.title);
+ expect(after.body.tags).toEqual({ owner: "alice" });
+ });
+
+ it("rejects empty rename payloads without changing the conversation", async () => {
+ const nullPayload = await requestJson<null>("/api/conversations/2", {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: "null",
+ });
+ const emptyTitle = await requestJson<null>("/api/conversations/2", {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ title: "" }),
+ });
+ const missing = await requestJson<null>(
+ "/api/conversations/does-not-exist",
+ {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ title: "Ignored" }),
+ },
+ );
+ const unchanged = await requestJson<{ title: string }>(
+ "/api/conversations/2",
+ );
+
+ expect(nullPayload).toEqual({ body: null, status: 404 });
+ expect(emptyTitle).toEqual({ body: null, status: 404 });
+ expect(missing).toEqual({ body: null, status: 404 });
+ expect(unchanged.body.title).toBe("Repo Testing");
+ });
+
+ it("paginates local events in ascending and descending timestamp order", async () => {
+ const ascending = await requestJson<{
+ items: {
+ activated_skills: unknown[];
+ extended_content: unknown[];
+ id: string;
+ llm_message: {
+ content: { text: string; type: string }[];
+ role: string;
+ };
+ source: string;
+ timestamp: string;
+ }[];
+ next_page_id: string | null;
+ }>("/api/conversations/pagination-local/events/search");
+ const descending = await requestJson<{
+ items: { id: string; timestamp: string }[];
+ next_page_id: string | null;
+ }>(
+ "/api/conversations/pagination-local/events/search?limit=2&sort_order=TIMESTAMP_DESC",
+ );
+
+ expect(ascending.body.items).toHaveLength(100);
+ expect(ascending.body.items[0]).toEqual({
+ activated_skills: [],
+ extended_content: [],
+ id: "local-pagination-message-1",
+ llm_message: {
+ content: [{ text: "Local pagination message 1", type: "text" }],
+ role: "assistant",
+ },
+ source: "agent",
+ timestamp: "2026-05-13T00:01:00.000Z",
+ });
+ expect(ascending.body.items.at(-1)).toEqual({
+ activated_skills: [],
+ extended_content: [],
+ id: "local-pagination-message-100",
+ llm_message: {
+ content: [{ text: "Local pagination message 100", type: "text" }],
+ role: "assistant",
+ },
+ source: "agent",
+ timestamp: "2026-05-13T01:40:00.000Z",
+ });
+ expect(ascending.body.next_page_id).toBeNull();
+ expect(descending.body.items.map(({ id }) => id)).toEqual([
+ "local-pagination-message-100",
+ "local-pagination-message-99",
+ ]);
+ expect(descending.body.next_page_id).toBe("next-page");
+ });
+
+ it("returns only pagination events older than the requested timestamp", async () => {
+ const timer = vi.spyOn(globalThis, "setTimeout");
+
+ try {
+ await requestJson(
+ "/api/conversations/pagination-local/events/search?limit=1",
+ );
+ expect(timer).not.toHaveBeenCalledWith(expect.any(Function), 500);
+
+ timer.mockClear();
+ const page = await requestJson<{
+ items: { id: string }[];
+ next_page_id: string | null;
+ }>(
+ "/api/conversations/pagination-local/events/search?timestamp__lt=2026-05-13T00%3A03%3A00.000Z&limit=10&sort_order=TIMESTAMP_DESC",
+ );
+
+ expect(timer).toHaveBeenCalledWith(expect.any(Function), 500);
+ expect(page.body).toEqual({
+ items: [
+ expect.objectContaining({ id: "local-pagination-message-2" }),
+ expect.objectContaining({ id: "local-pagination-message-1" }),
+ ],
+ next_page_id: null,
+ });
+ } finally {
+ timer.mockRestore();
+ }
+ });
+
+ it("paginates static events and returns an empty page for unknown conversations", async () => {
+ const staticPage = await requestJson<{
+ items: { source: string }[];
+ next_page_id: string | null;
+ }>(
+ `/api/conversations/${TABLE_DEMO_CONVERSATION_ID}/events/search?limit=1`,
+ );
+ const unknownPage = await requestJson<{
+ items: unknown[];
+ next_page_id: string | null;
+ }>("/api/conversations/unknown/events/search");
+
+ expect(staticPage.body.items).toHaveLength(1);
+ expect(staticPage.body.next_page_id).toBe("next-page");
+ expect(unknownPage.body).toEqual({ items: [], next_page_id: null });
+ });
+
+ it("serves cloud conversations and their paginated events through the proxy", async () => {
+ const batch = await cloudProxy<
+ ({
+ agent?: unknown;
+ conversation_url: string | null;
+ created_at: string;
+ created_by_user_id: string | null;
+ execution_status: string;
+ git_provider: string | null;
+ id: string;
+ llm_model: string;
+ metrics: unknown | null;
+ pr_number: number[];
+ public: boolean;
+ sandbox_id: string | null;
+ selected_branch: string | null;
+ selected_repository: string | null;
+ session_api_key: string | null;
+ sub_conversation_ids: string[];
+ title: string;
+ trigger: unknown | null;
+ updated_at: string;
+ workspace: { working_dir: string };
+ } | null)[]
+ >("/api/v1/app-conversations?ids=pagination-cloud&ids=unknown");
+ const emptyBatch = await cloudProxy<Record<string, never>>(
+ "/api/v1/app-conversations",
+ );
+ const search = await cloudProxy<{
+ items: { id: string; execution_status: string }[];
+ next_page_id: string | null;
+ }>("/api/v1/app-conversations/search");
+ const events = await cloudProxy<{
+ items: { id: string }[];
+ next_page_id: string | null;
+ }>(
+ "/api/v1/conversation/pagination-cloud/events/search?limit=2&sort_order=TIMESTAMP_DESC",
+ );
+
+ expect(batch.body).toEqual([
+ {
+ conversation_url: null,
+ created_at: expect.any(String),
+ created_by_user_id: null,
+ execution_status: "idle",
+ git_provider: null,
+ id: "pagination-cloud",
+ llm_model: "openhands/claude-haiku-4-5-20251001",
+ metrics: null,
+ pr_number: [],
+ public: false,
+ sandbox_id: null,
+ selected_branch: null,
+ selected_repository: null,
+ session_api_key: null,
+ sub_conversation_ids: [],
+ title: "Cloud pagination fixture",
+ trigger: null,
+ updated_at: expect.any(String),
+ workspace: { working_dir: "/workspace/project" },
+ },
+ null,
+ ]);
+ expect(emptyBatch.body).toEqual({});
+ expect(search.body).toEqual({
+ items: [expect.objectContaining({ id: "pagination-cloud" })],
+ next_page_id: null,
+ });
+ expect(events.body.items.map(({ id }) => id)).toEqual([
+ "cloud-pagination-message-100",
+ "cloud-pagination-message-99",
+ ]);
+ expect(events.body.next_page_id).toBe("next-page");
+ });
+
+ it("serves cloud account bootstrap data through the proxy", async () => {
+ const settings = await cloudProxy<{
+ agent: string;
+ language: string;
+ llm_api_key: string | null;
+ llm_api_key_set: boolean;
+ llm_base_url: string;
+ llm_model: string;
+ search_api_key_set: boolean;
+ user_consents_to_analytics: boolean;
+ provider_tokens_set: Record<string, string>;
+ }>("/api/v1/settings");
+ const key = await cloudProxy<{
+ auth_type: string;
+ id: string;
+ name: string;
+ org_id: string;
+ user_id: string;
+ }>("/api/keys/current");
+ const organizations = await cloudProxy<{
+ items: { id: string; is_personal: boolean }[];
+ current_org_id: string;
+ }>("/api/organizations");
+ const membership = await cloudProxy<{ org_id: string; user_id: string }>(
+ "/api/organizations/org-1/me",
+ );
+ const authenticated = await cloudProxy<{ ok: boolean }>(
+ "/api/authenticate",
+ );
+ const missingPath = await cloudProxy<Record<string, never>>();
+ const unknownPathWithIds = await cloudProxy<Record<string, never>>(
+ "/api/not-implemented?ids=unknown",
+ );
+
+ expect(settings.body).toEqual({
+ agent: "CodeActAgent",
+ language: "en",
+ llm_api_key: null,
+ llm_api_key_set: false,
+ llm_base_url: "",
+ llm_model: "openhands/claude-haiku-4-5-20251001",
+ search_api_key_set: false,
+ user_consents_to_analytics: false,
+ provider_tokens_set: { github: "" },
+ });
+ expect(key.body).toEqual({
+ auth_type: "api_key",
+ id: "mock-key",
+ name: "Mock key",
+ org_id: "org-1",
+ user_id: "user-1",
+ });
+ expect(organizations.body).toEqual({
+ items: [{ id: "org-1", name: "Mock Org", is_personal: true }],
+ current_org_id: "org-1",
+ });
+ expect(membership.body).toEqual({ org_id: "org-1", user_id: "org-1" });
+ expect(authenticated.body).toEqual({ ok: true });
+ expect(missingPath.body).toEqual({});
+ expect(unknownPathWithIds.body).toEqual({});
+ });
+
+ it("supports conversation controls and auxiliary conversation resources", async () => {
+ const [
+ count,
+ event,
+ paused,
+ interrupted,
+ run,
+ agentAnswer,
+ vscode,
+ skills,
+ pendingMessage,
+ ] = await Promise.all([
+ requestJson<number>("/api/conversations/1/events/count"),
+ requestJson<{ ok: boolean }>("/api/conversations/1/events", {
+ method: "POST",
+ }),
+ requestJson<{ success: boolean }>("/api/conversations/1/pause", {
+ method: "POST",
+ }),
+ requestJson<{ success: boolean }>("/api/conversations/1/interrupt", {
+ method: "POST",
+ }),
+ requestJson<{ success: boolean }>("/api/conversations/1/run", {
+ method: "POST",
+ }),
+ requestJson<{ response: string }>("/api/conversations/1/ask_agent", {
+ method: "POST",
+ }),
+ requestJson<{ url: string | null }>("/api/vscode/url"),
+ requestJson<{ skills: unknown[] }>("/api/skills", { method: "POST" }),
+ requestJson<{ id: string; position: number }>(
+ "/api/v1/conversations/1/pending-messages",
+ { method: "POST" },
+ ),
+ ]);
+
+ expect(count.body).toBe(0);
+ expect(event.body).toEqual({ ok: true });
+ expect(paused.body).toEqual({ success: true });
+ expect(interrupted.body).toEqual({ success: true });
+ expect(run.body).toEqual({ success: true });
+ expect(agentAnswer.body).toEqual({ response: "Mock agent response" });
+ expect(vscode.body).toEqual({ url: null });
+ expect(skills.body).toEqual({ skills: [] });
+ expect(pendingMessage.body).toEqual({ id: "mock-pending-id", position: 0 });
+ });
it("returns the generated-canvas demo conversation and file event", async () => {
const [conversation] =
await AgentServerConversationService.batchGetAppConversations([
@@ -83,6 +660,7 @@ describe("mock conversation handlers", () => {
);
expect(conversation?.title).toBe("Generated canvas demo");
+ expect(conversation?.workspace?.working_dir?.trim()).toBeTruthy();
expect(page.items).toHaveLength(4);
expect(page.items).toEqual(
expect.arrayContaining([
@@ -95,4 +673,13 @@ describe("mock conversation handlers", () => {
]),
);
});
+ it("serves the generated canvas Markdown from the conversation workspace", async () => {
+ // eslint-disable-next-line local/no-direct-agent-server-fetch -- Verify the mock response bytes and MIME type at the HTTP boundary.
+ const response = await fetch(
+ `${API_BASE}/api/conversations/${CANVAS_DEMO_CONVERSATION_ID}/workspace/${CANVAS_DEMO_FILE_PATH}`,
+ );
+ expect(response.status).toBe(200);
+ expect(response.headers.get("content-type")).toContain("text/markdown");
+ await expect(response.text()).resolves.toBe(CANVAS_DEMO_MARKDOWN);
+ });
});
diff --git a/__tests__/api/mock-workspaces-handlers.test.ts b/__tests__/api/mock-workspaces-handlers.test.ts
index e81b65af12..4ea6b3882f 100644
--- a/__tests__/api/mock-workspaces-handlers.test.ts
+++ b/__tests__/api/mock-workspaces-handlers.test.ts
@@ -1,69 +1,242 @@
-import { afterEach, describe, expect, it } from "vitest";
+import { http, HttpResponse } from "msw";
+import { afterEach, describe, expect, it, vi } from "vitest";
-import WorkspacesService from "#/api/workspaces-service/workspaces-service.api";
-import { resetMockWorkspaces } from "#/mocks/handlers";
+import { server } from "#/mocks/node";
+
+const unhandledWorkspacesRequest = () =>
+ HttpResponse.json({ error: "Unhandled workspaces request" }, { status: 599 });
+
+const UNHANDLED_WORKSPACES_REQUESTS = [
+ http.all("*/api/workspaces", unhandledWorkspacesRequest),
+ http.all("*/api/workspaces/parents", unhandledWorkspacesRequest),
+ http.all("*/api/auth/workspace-session", unhandledWorkspacesRequest),
+];
+
+const installWorkspacesHandlers = async () => {
+ vi.resetModules();
+ const { WORKSPACES_HANDLERS, resetMockWorkspaces } =
+ await import("#/mocks/workspaces-handlers");
+ server.resetHandlers(
+ ...WORKSPACES_HANDLERS,
+ ...UNHANDLED_WORKSPACES_REQUESTS,
+ );
+ return resetMockWorkspaces;
+};
+
+const postJson = (path: string, body: unknown) =>
+ fetch(`http://localhost:3000${path}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+
+const listWorkspaces = () => fetch("http://localhost:3000/api/workspaces");
+
+const deleteByPath = (path: string, workspacePath: string) =>
+ fetch(
+ `http://localhost:3000${path}?path=${encodeURIComponent(workspacePath)}`,
+ { method: "DELETE" },
+ );
describe("mock workspaces handlers", () => {
afterEach(() => {
- resetMockWorkspaces();
+ server.resetHandlers();
});
it("starts with an empty workspaces list", async () => {
- const response = await WorkspacesService.listWorkspaces();
- expect(response.workspaces).toEqual([]);
- expect(response.workspaceParents).toEqual([]);
+ await installWorkspacesHandlers();
+ const response = await listWorkspaces();
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({
+ workspaces: [],
+ workspaceParents: [],
+ });
});
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" },
- ]);
+ await installWorkspacesHandlers();
+ await postJson("/api/workspaces", {
+ workspaces: [{ id: "w1", name: "Project", path: "/workspace/project" }],
+ });
+
+ const response = await listWorkspaces();
+ await expect(response.json()).resolves.toEqual({
+ workspaces: [{ id: "w1", name: "Project", path: "/workspace/project" }],
+ workspaceParents: [],
+ });
});
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");
+ await installWorkspacesHandlers();
+ await postJson("/api/workspaces", {
+ workspaces: [
+ { id: "w1", name: "Other", path: "/workspace/other" },
+ { id: "w2", name: "Old", path: "/workspace/project" },
+ ],
+ });
+ const response = await postJson("/api/workspaces", {
+ workspaces: [
+ { id: "w3", name: "New", path: "/workspace/project" },
+ { id: "w4", name: "Other updated", path: "/workspace/other" },
+ ],
+ });
+
+ await expect(response.json()).resolves.toEqual({
+ workspaces: [
+ { id: "w4", name: "Other updated", path: "/workspace/other" },
+ { id: "w3", name: "New", path: "/workspace/project" },
+ ],
+ workspaceParents: [],
+ });
+ });
+
+ it("treats omitted workspace and parent collections as no-op updates", async () => {
+ await installWorkspacesHandlers();
+ const workspacesResponse = await postJson("/api/workspaces", {});
+
+ expect(workspacesResponse.status).toBe(200);
+ await expect(workspacesResponse.json()).resolves.toEqual({
+ workspaces: [],
+ workspaceParents: [],
+ });
+
+ const parentsResponse = await postJson("/api/workspaces/parents", {});
+
+ expect(parentsResponse.status).toBe(200);
+ await expect(parentsResponse.json()).resolves.toEqual({
+ workspaces: [],
+ workspaceParents: [],
+ });
});
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 installWorkspacesHandlers();
+ await postJson("/api/workspaces", {
+ workspaces: [
+ { id: "w1", name: "Project", path: "/workspace/project" },
+ { id: "w2", name: "Other", path: "/workspace/other" },
+ ],
+ });
+
+ const deleted = await deleteByPath("/api/workspaces", "/workspace/project");
+
+ expect(deleted.status).toBe(200);
+ await expect(deleted.json()).resolves.toEqual({ deleted: true });
- await WorkspacesService.removeWorkspace("/workspace/project");
+ const missing = await deleteByPath("/api/workspaces", "/workspace/missing");
- const response = await WorkspacesService.listWorkspaces();
- expect(response.workspaces.map((w) => w.path)).toEqual([
- "/workspace/other",
- ]);
+ expect(missing.status).toBe(200);
+ await expect(missing.json()).resolves.toEqual({ deleted: false });
+
+ const response = await listWorkspaces();
+ await expect(response.json()).resolves.toEqual({
+ workspaces: [{ id: "w2", name: "Other", path: "/workspace/other" }],
+ workspaceParents: [],
+ });
});
it("persists workspace parents and removes them by path", async () => {
- await WorkspacesService.addWorkspaceParents([
- { id: "p1", name: "Repos", path: "/workspace/repos" },
- ]);
+ await installWorkspacesHandlers();
+ await postJson("/api/workspaces/parents", {
+ parents: [
+ { id: "p1", name: "Repos", path: "/workspace/repos" },
+ { id: "p2", name: "Other", path: "/workspace/other" },
+ ],
+ });
+
+ const afterAdd = await listWorkspaces();
+ await expect(afterAdd.json()).resolves.toEqual({
+ workspaces: [],
+ workspaceParents: [
+ { id: "p1", name: "Repos", path: "/workspace/repos" },
+ { id: "p2", name: "Other", path: "/workspace/other" },
+ ],
+ });
+
+ const deleted = await deleteByPath(
+ "/api/workspaces/parents",
+ "/workspace/repos",
+ );
+
+ expect(deleted.status).toBe(200);
+ await expect(deleted.json()).resolves.toEqual({ deleted: true });
+
+ const missing = await deleteByPath(
+ "/api/workspaces/parents",
+ "/workspace/missing",
+ );
+
+ expect(missing.status).toBe(200);
+ await expect(missing.json()).resolves.toEqual({ deleted: false });
+
+ const afterRemove = await listWorkspaces();
+ await expect(afterRemove.json()).resolves.toEqual({
+ workspaces: [],
+ workspaceParents: [{ id: "p2", name: "Other", path: "/workspace/other" }],
+ });
+ });
+
+ it("replaces a workspace parent when its path is already registered", async () => {
+ await installWorkspacesHandlers();
+ await postJson("/api/workspaces/parents", {
+ parents: [
+ { id: "p1", name: "Other", path: "/workspace/other" },
+ { id: "p2", name: "Old", path: "/workspace/repos" },
+ ],
+ });
- const afterAdd = await WorkspacesService.listWorkspaces();
- expect(afterAdd.workspaceParents).toEqual([
- { id: "p1", name: "Repos", path: "/workspace/repos" },
- ]);
+ const response = await postJson("/api/workspaces/parents", {
+ parents: [
+ { id: "p3", name: "New", path: "/workspace/repos" },
+ { id: "p4", name: "Other updated", path: "/workspace/other" },
+ ],
+ });
- await WorkspacesService.removeWorkspaceParent("/workspace/repos");
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({
+ workspaces: [],
+ workspaceParents: [
+ { id: "p4", name: "Other updated", path: "/workspace/other" },
+ { id: "p3", name: "New", path: "/workspace/repos" },
+ ],
+ });
+ });
+
+ it("acknowledges workspace session creation and deletion", async () => {
+ await installWorkspacesHandlers();
+ const createResponse = await fetch(
+ "http://localhost:3000/api/auth/workspace-session",
+ { method: "POST" },
+ );
+
+ expect(createResponse.status).toBe(200);
+ await expect(createResponse.json()).resolves.toEqual({ ok: true });
+
+ const deleteResponse = await fetch(
+ "http://localhost:3000/api/auth/workspace-session",
+ { method: "DELETE" },
+ );
+
+ expect(deleteResponse.status).toBe(204);
+ await expect(deleteResponse.text()).resolves.toBe("");
+ });
+
+ it("resets workspace and parent state together", async () => {
+ const resetMockWorkspaces = await installWorkspacesHandlers();
+ await postJson("/api/workspaces", {
+ workspaces: [{ id: "w1", name: "Project", path: "/workspace/project" }],
+ });
+ await postJson("/api/workspaces/parents", {
+ parents: [{ id: "p1", name: "Repos", path: "/workspace/repos" }],
+ });
+
+ resetMockWorkspaces();
- const afterRemove = await WorkspacesService.listWorkspaces();
- expect(afterRemove.workspaceParents).toEqual([]);
+ const response = await listWorkspaces();
+ await expect(response.json()).resolves.toEqual({
+ workspaces: [],
+ workspaceParents: [],
+ });
});
});