/** * @file WorkspaceTree.test.tsx * @description Tests for the sidebar's workspace list: one flat row per * workspace in the stored order, a row expanding to its sessions (remembered), * a live session opening its pane and an ended one its transcript, the * workspace's OWN sessions only, a session's state dot, rename and archive, * selection * by URL, Alt+arrow reordering kept in localStorage, double-click rename, the * search, the row menu's items by kind and tool, and the status dot. * @author Nguyễn Ngọc Trí Vĩ */ import { describe, it, expect, vi, beforeEach } from "vitest"; import { act, render, screen, waitFor, within, fireEvent } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom"; import type { Lane, Session } from "../../lib/types"; function lane(id: number, cwd: string, extra: Partial = {}): Lane { return { id, title: "", cwd, branch: null, kind: "adopted", tool: "claude", router_profile: null, source_repo: null, pipeline: "default", session_id: null, run_id: null, stage: "idle", stage_since: null, status: "idle", needs_action: null, liveness: "idle", pipeline_nodes: [], ...extra, } as unknown as Lane; } const session = (id: string, name: string) => ({ id, name, cwd: "/r", status: "completed", started_at: "2026-09-30T10:00:00Z" }) as Session; let lanes: Lane[] = []; // Archiving a live session asks through the themed confirm (App's host): yes. vi.mock("../../lib/confirm", () => ({ confirmDialog: vi.fn(async () => true), confirmDiscard: vi.fn(async () => true), })); vi.mock("../../lib/api", async (importOriginal) => { const actual = await importOriginal>(); return { ...actual, api: { lanes: { list: vi.fn(async () => ({ lanes, counts: {} })), update: vi.fn(async () => ({ lane: lanes[0] })), action: vi.fn(async () => ({ ok: true })), removeSessionWorktree: vi.fn(async () => ({ removed: true, branch: "x", branchKept: false, })), routerList: vi.fn(async () => ({ routers: [] })), }, sessions: { list: vi.fn(async () => ({ sessions: [session("s-live", "Live one"), session("s-old", "Old one")], })), patch: vi.fn(async () => ({ session: {} })), // A tab's session with no row yet (a bare tab): 404. get: vi.fn(async () => { throw Object.assign(new Error("not found"), { status: 404 }); }), }, run: { list: vi.fn(async () => ({ items: [{ id: "agenthub-lane-1-2", laneId: 1, status: "running", sessionId: "s-live" }], })), cwds: vi.fn(async () => ({ items: [] })), kill: vi.fn(async () => ({ ok: true })), }, aiTools: { list: vi.fn(async () => ({ tools: [], default: "claude" })), iconUrl: () => "", }, aiProxies: { list: vi.fn(async () => ({ items: [] })) }, }, }; }); import { api } from "../../lib/api"; import { WorkspaceTree } from "../WorkspaceTree"; import { workspaceDot } from "../lanes/WorkspaceRow"; function Where() { const loc = useLocation(); return {loc.pathname + loc.search}; } function renderTree(at = "/") { return render( } /> ); } const rowIds = () => screen.getAllByTestId(/^workspace-row-\d+$/).map((el) => el.dataset.testid); beforeEach(() => { localStorage.clear(); vi.clearAllMocks(); vi.mocked(api.sessions.list).mockImplementation(async () => ({ sessions: [session("s-live", "Live one"), session("s-old", "Old one")], total: 2, limit: 20, offset: 0, })); lanes = [ lane(1, "/r", { title: "Repo" }), lane(2, "/r/sub", { title: "Sub" }), lane(3, "/tmp/plain", { kind: "managed", tool: "codex" }), ]; }); describe("WorkspaceTree", () => { it("lists every workspace on one flat level, collapsed", async () => { renderTree(); await screen.findByTestId("workspace-row-3"); expect(rowIds()).toEqual(["workspace-row-1", "workspace-row-2", "workspace-row-3"]); expect(screen.getByTestId("workspace-row-3")).toHaveTextContent("plain"); expect(screen.queryByTestId("workspace-sessions-1")).toBeNull(); expect(api.sessions.list).not.toHaveBeenCalled(); }); it("expands a workspace to its sessions and remembers it", async () => { const user = userEvent.setup(); renderTree(); await user.click(await screen.findByTestId("workspace-toggle-1")); const list = await screen.findByTestId("workspace-sessions-1"); expect(within(list).getByText("Live one")).toBeInTheDocument(); // Its OWN sessions only — never the rest of its folder. expect(api.sessions.list).toHaveBeenCalledTimes(1); expect(api.sessions.list).toHaveBeenCalledWith({ lane: 1, archived: false, limit: 6 }); expect(JSON.parse(localStorage.getItem("agenthub.sidebar.projects")!).expanded).toEqual({ "1": true, }); }); it("shows six sessions and loads the rest on See all", async () => { const all = Array.from({ length: 9 }, (_, i) => session(`s-${i}`, `Session ${i}`)); vi.mocked(api.sessions.list).mockImplementation(async (p) => ({ sessions: all.slice(0, p?.limit), total: all.length, limit: p?.limit ?? 50, offset: 0, })); const user = userEvent.setup(); renderTree(); await user.click(await screen.findByTestId("workspace-toggle-1")); const list = await screen.findByTestId("workspace-sessions-1"); expect(within(list).getAllByTestId(/^workspace-session-s-\d+$/)).toHaveLength(6); expect(screen.getByTestId("workspace-sessions-more-1")).toHaveTextContent("See all (3 more)"); await user.click(screen.getByTestId("workspace-sessions-more-1")); expect(api.sessions.list).toHaveBeenLastCalledWith({ lane: 1, archived: false, limit: 9 }); await screen.findByText("Session 8"); expect(screen.queryByTestId("workspace-sessions-more-1")).toBeNull(); }); it("renames a session on double-click + Enter, and archives one from its row", async () => { const user = userEvent.setup(); renderTree(); await user.click(await screen.findByTestId("workspace-toggle-1")); await user.dblClick(await screen.findByTestId("workspace-session-s-old")); const input = screen.getByTestId("workspace-session-rename-s-old"); await user.clear(input); await user.type(input, "Better name{Enter}"); expect(api.sessions.patch).toHaveBeenCalledWith("s-old", { name: "Better name" }); await user.click(screen.getByTestId("workspace-session-archive-s-live")); expect(api.sessions.patch).toHaveBeenCalledWith("s-live", { archived: true }); }); it("right-click on a session opens its menu: split, rename, archive, close its tab", async () => { const user = userEvent.setup(); renderTree(); await user.click(await screen.findByTestId("workspace-toggle-1")); const right = (target: Element) => user.pointer({ keys: "[MouseRight]", target }); await right(await screen.findByTestId("workspace-session-s-old")); let menu = screen.getByTestId("session-menu-s-old"); // Ended: no pane to split or close. expect(within(menu).queryByText("Open in split")).toBeNull(); expect(within(menu).queryByText("Close tab (stops its session)")).toBeNull(); await user.click(within(menu).getByText("Rename")); expect(screen.queryByTestId("session-menu-s-old")).toBeNull(); expect(screen.getByTestId("workspace-session-rename-s-old")).toBeInTheDocument(); await user.keyboard("{Escape}"); await right(screen.getByTestId("workspace-session-s-live")); menu = screen.getByTestId("session-menu-s-live"); await user.click(within(menu).getByText("Open in split")); expect(screen.getByTestId("where")).toHaveTextContent( "/workspace?lane=1&run=agenthub-lane-1-2" ); await right(screen.getByTestId("workspace-session-s-live")); await user.click(within(screen.getByTestId("session-menu-s-live")).getByText("Archive")); expect(api.sessions.patch).toHaveBeenCalledWith("s-live", { archived: true }); await right(screen.getByTestId("workspace-session-s-live")); await user.click( within(screen.getByTestId("session-menu-s-live")).getByText("Close tab (stops its session)") ); expect(api.run.kill).toHaveBeenCalledWith("agenthub-lane-1-2"); }); it("archiving a worktree session removes its worktree first, after asking", async () => { vi.mocked(api.sessions.list).mockImplementation(async () => ({ sessions: [ { ...session("s-wt", "In a worktree"), cwd: "/r/.claude/worktrees/ah-1-x" } as Session, ], total: 1, limit: 20, offset: 0, })); const user = userEvent.setup(); renderTree(); await user.click(await screen.findByTestId("workspace-toggle-1")); expect(await screen.findByTestId("workspace-session-worktree-s-wt")).toBeInTheDocument(); await user.click(screen.getByTestId("workspace-session-archive-s-wt")); expect(api.sessions.patch).not.toHaveBeenCalled(); expect(screen.getByRole("dialog")).toHaveTextContent(".claude/worktrees/ah-1-x"); await user.click(screen.getByRole("button", { name: "Archive and remove" })); await waitFor(() => expect(api.sessions.patch).toHaveBeenCalledWith("s-wt", { archived: true }) ); expect(api.lanes.removeSessionWorktree).toHaveBeenCalledWith(1, "s-wt"); }); it("keeps a worktree session when git refuses to remove its worktree", async () => { vi.mocked(api.sessions.list).mockImplementation(async () => ({ sessions: [ { ...session("s-wt", "In a worktree"), cwd: "/r/.claude/worktrees/ah-1-x" } as Session, ], total: 1, limit: 20, offset: 0, })); vi.mocked(api.lanes.removeSessionWorktree).mockRejectedValueOnce( Object.assign(new Error("contains modified or untracked files"), { code: "EGIT" }) ); const user = userEvent.setup(); renderTree(); await user.click(await screen.findByTestId("workspace-toggle-1")); await user.click(await screen.findByTestId("workspace-session-archive-s-wt")); await user.click(screen.getByRole("button", { name: "Archive and remove" })); expect(await screen.findByRole("alert")).toHaveTextContent("modified or untracked"); expect(api.sessions.patch).not.toHaveBeenCalled(); }); it("dots a session waiting for the user amber and a failed one red", async () => { vi.mocked(api.sessions.list).mockImplementation(async () => ({ sessions: [ { ...session("s-wait", "Waiting"), status: "active", awaiting_input_since: "2026-09-30T10:00:00Z", } as Session, { ...session("s-bad", "Broke"), status: "error" } as Session, ], total: 2, limit: 20, offset: 0, })); const user = userEvent.setup(); renderTree(); await user.click(await screen.findByTestId("workspace-toggle-1")); expect(await screen.findByTestId("workspace-session-dot-s-wait")).toHaveClass( "bg-status-warning" ); expect(screen.getByTestId("workspace-session-dot-s-bad")).toHaveClass("bg-status-danger"); }); it("opens a live session's pane and an ended session's conversation, resuming nothing", async () => { const user = userEvent.setup(); renderTree(); await user.click(await screen.findByTestId("workspace-toggle-1")); const live = await screen.findByTestId("workspace-session-s-live"); await waitFor(() => expect(live).toHaveAttribute("data-live", "true")); await user.click(live); expect(screen.getByTestId("where").textContent).toBe("/workspace?lane=1&run=agenthub-lane-1-2"); await user.click(screen.getByTestId("workspace-session-s-old")); expect(screen.getByTestId("where").textContent).toBe("/workspace?lane=1&session=s-old"); expect(api.lanes.action).not.toHaveBeenCalled(); }); it("lists live sessions above ended ones, even an ended one active more recently", async () => { vi.mocked(api.sessions.list).mockImplementation(async () => ({ sessions: [session("s-old", "Old one"), session("s-live", "Live one")], total: 2, limit: 20, offset: 0, })); const user = userEvent.setup(); renderTree(); await user.click(await screen.findByTestId("workspace-toggle-1")); await waitFor(() => expect(screen.getByTestId("workspace-session-s-live")).toHaveAttribute("data-live", "true") ); const ids = screen.getAllByTestId(/^workspace-session-s-/).map((el) => el.dataset.testid); expect(ids).toEqual(["workspace-session-s-live", "workspace-session-s-old"]); }); it("shows a live tab whose session has no row yet as a New session, and a shell as Terminal", async () => { vi.mocked(api.run.list).mockImplementation( async () => ({ items: [ { id: "agenthub-lane-1-2", laneId: 1, status: "running", sessionId: "s-live", tool: "claude", }, { id: "agenthub-lane-1", laneId: 1, status: "running", sessionId: "s-fresh", tool: "claude", }, { id: "agenthub-lane-1-3", laneId: 1, status: "running", sessionId: null, tool: "shell", }, ], }) as never ); const user = userEvent.setup(); renderTree(); await user.click(await screen.findByTestId("workspace-toggle-1")); const fresh = await screen.findByTestId("workspace-session-new-agenthub-lane-1"); expect(fresh).toHaveTextContent("New session"); expect(screen.getByTestId("workspace-session-new-agenthub-lane-1-3")).toHaveTextContent( "Terminal" ); expect(screen.queryByTestId("workspace-session-new-agenthub-lane-1-2")).toBeNull(); await user.click(fresh); expect(screen.getByTestId("where").textContent).toBe("/workspace?lane=1&run=agenthub-lane-1"); }); it("selects by URL, and a click selects and expands", async () => { const user = userEvent.setup(); renderTree("/workspace?lane=2"); expect(await screen.findByTestId("workspace-open-2")).toHaveAttribute("aria-current", "true"); // Lane 1 has a live tab: its row still opens the home. await waitFor(() => expect(api.run.list).toHaveBeenCalled()); await user.click(screen.getByTestId("workspace-open-1")); expect(screen.getByTestId("where").textContent).toBe("/workspace?lane=1"); expect(await screen.findByTestId("workspace-sessions-1")).toBeInTheDocument(); await user.click(screen.getByTestId("workspace-open-2")); expect(screen.getByTestId("where").textContent).toBe("/workspace?lane=2"); }); it("opens a workspace's home even while it has live tabs", async () => { vi.mocked(api.run.list).mockImplementation(async () => ({ items: [] }) as never); localStorage.setItem( "agenthub.workspace.paneLayout", JSON.stringify({ 1: { root: { type: "split", dir: "row", ratio: 0.5, a: { type: "pane", slot: 0 }, b: { type: "pane", slot: 2 }, }, focus: 2, }, }) ); const user = userEvent.setup(); renderTree(); await screen.findByTestId("workspace-open-1"); // The Workspace page's poll lands: two live tabs on lane 1. act(() => { window.dispatchEvent( new CustomEvent("agenthub:live-runs", { detail: [ { id: "agenthub-lane-1", laneId: 1, slot: 0, status: "running", tool: "claude" }, { id: "agenthub-lane-1-2", laneId: 1, slot: 2, status: "running", tool: "claude" }, ], }) ); }); await user.click(screen.getByTestId("workspace-open-1")); expect(screen.getByTestId("where").textContent).toBe("/workspace?lane=1"); }); it("reorders with Alt+ArrowUp and keeps the order in localStorage", async () => { renderTree(); fireEvent.keyDown(await screen.findByTestId("workspace-open-2"), { key: "ArrowUp", altKey: true, }); expect(JSON.parse(localStorage.getItem("agenthub.workspace.laneOrder")!)).toEqual([2, 1, 3]); expect(rowIds()).toEqual(["workspace-row-2", "workspace-row-1", "workspace-row-3"]); }); it("renames on double-click + Enter, and Escape cancels without a call", async () => { const user = userEvent.setup(); renderTree(); await user.dblClick(await screen.findByTestId("workspace-open-2")); const input = screen.getByTestId("workspace-rename-2"); await user.clear(input); await user.type(input, " Renamed {Enter}"); expect(api.lanes.update).toHaveBeenCalledWith(2, { title: "Renamed" }); vi.mocked(api.lanes.update).mockClear(); await user.dblClick(screen.getByTestId("workspace-open-2")); await user.type(screen.getByTestId("workspace-rename-2"), "x{Escape}"); expect(api.lanes.update).not.toHaveBeenCalled(); }); it("filters workspaces by search", async () => { const user = userEvent.setup(); renderTree(); await screen.findByTestId("workspace-row-1"); await user.click(screen.getByRole("button", { name: "Search workspaces and sessions" })); await user.type(screen.getByRole("searchbox"), "plain"); expect(rowIds()).toEqual(["workspace-row-3"]); }); it("filters by tool, remembered, and offers the filter only with two tools", async () => { const user = userEvent.setup(); const { unmount } = renderTree(); await screen.findByTestId("workspace-row-1"); await user.selectOptions(screen.getByLabelText("Filter by tool"), "codex"); expect(rowIds()).toEqual(["workspace-row-3"]); expect(JSON.parse(localStorage.getItem("agenthub.sidebar.projects")!).tool).toBe("codex"); await user.selectOptions(screen.getByLabelText("Filter by tool"), ""); expect(rowIds()).toEqual(["workspace-row-1", "workspace-row-2", "workspace-row-3"]); unmount(); // One tool only: no filter, and a stale stored one is ignored. localStorage.setItem("agenthub.sidebar.projects", JSON.stringify({ tool: "codex" })); lanes = lanes.filter((l) => l.tool === "claude"); renderTree(); await screen.findByTestId("workspace-row-1"); expect(screen.queryByLabelText("Filter by tool")).toBeNull(); expect(rowIds()).toEqual(["workspace-row-1", "workspace-row-2"]); }); it("reorders within a tool filter without losing the hidden workspaces' places", async () => { localStorage.setItem("agenthub.workspace.laneOrder", JSON.stringify([1, 3, 2])); localStorage.setItem("agenthub.sidebar.projects", JSON.stringify({ tool: "claude" })); renderTree(); fireEvent.keyDown(await screen.findByTestId("workspace-open-2"), { key: "ArrowUp", altKey: true, }); expect(JSON.parse(localStorage.getItem("agenthub.workspace.laneOrder")!)).toEqual([2, 3, 1]); expect(rowIds()).toEqual(["workspace-row-2", "workspace-row-1"]); }); it("finds a workspace by one of its session names, showing only the matches", async () => { vi.mocked(api.sessions.list).mockImplementation(async (params) => ({ sessions: (params as { lane?: number }).lane === 2 ? [session("s-x", "Fix login bug"), session("s-y", "Docs")] : [session("s-live", "Live one"), session("s-old", "Old one")], total: 2, limit: 20, offset: 0, })); const user = userEvent.setup(); renderTree(); await screen.findByTestId("workspace-row-1"); await user.click(screen.getByRole("button", { name: "Search workspaces and sessions" })); await user.type(screen.getByRole("searchbox"), "login"); await waitFor(() => expect(rowIds()).toEqual(["workspace-row-2"])); expect(screen.getByTestId("workspace-session-s-x")).toBeVisible(); expect(screen.queryByTestId("workspace-session-s-y")).toBeNull(); // A workspace whose NAME matches keeps all of its sessions. await user.clear(screen.getByRole("searchbox")); await user.type(screen.getByRole("searchbox"), "sub"); await waitFor(() => expect(rowIds()).toEqual(["workspace-row-2"])); expect(screen.getByTestId("workspace-session-s-y")).toBeInTheDocument(); }); it("offers Reset only on a managed workspace", async () => { const user = userEvent.setup(); renderTree(); await user.click(await screen.findByTestId("workspace-menu-1")); let menu = screen.getByTestId("workspace-row-menu-1"); expect(within(menu).queryByText("Reset worktree…")).toBeNull(); expect(within(menu).getByText("Delete workspace…")).toBeInTheDocument(); await user.keyboard("{Escape}"); await user.click(screen.getByTestId("workspace-menu-3")); menu = screen.getByTestId("workspace-row-menu-3"); expect(within(menu).getByText("Reset worktree…")).toBeInTheDocument(); }); }); describe("workspaceDot", () => { it("maps needs-you, dead/error, running, active and idle", () => { expect(workspaceDot(lane(1, "/a", { needs_action: "x", status: "running" }))).toBe( "bg-status-warning" ); expect(workspaceDot(lane(1, "/a", { liveness: "dead" }))).toBe("bg-status-danger"); expect(workspaceDot(lane(1, "/a", { status: "error" }))).toBe("bg-status-danger"); expect(workspaceDot(lane(1, "/a", { status: "running" }))).toContain("animate-pulse-slow"); expect(workspaceDot(lane(1, "/a", { liveness: "active" }))).toBe("bg-status-success"); expect(workspaceDot(lane(1, "/a"))).toBe("border border-fg-muted"); }); });