Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
11.9 KB
Raw Blame
import type { ReactNode } from "react";
import { fireEvent, screen, within } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";
import { renderWithI18n } from "../test/i18n";
import { RailWorkspaces } from "./rail-workspaces";

type Ws = { id: string; name: string; slug: string; avatar_url: string | null; pinned_at?: string | null };

const state = vi.hoisted(() => ({
  workspaces: [] as Ws[],
  invitations: [] as { id: string; workspace_id: string; workspace_name?: string; inviter_name?: string }[],
  summary: [] as { workspace_id: string; count: number }[],
  setPinned: vi.fn(),
  workspaceCreationDisabled: false,
  openWorkspaceInNewWindow: undefined as undefined | Mock<(slug: string) => void>,
  workspacesInOtherWindows: undefined as undefined | (() => string[]),
}));

vi.mock("@multica/core/workspace/mutations", () => ({
  useSetWorkspacePinned: () => ({ mutate: state.setPinned }),
}));

vi.mock("@multica/core/config", () => ({
  useConfigStore: (selector: (s: { workspaceCreationDisabled: boolean }) => unknown) =>
    selector({ workspaceCreationDisabled: state.workspaceCreationDisabled }),
}));

vi.mock("../navigation", () => ({
  AppLink: ({ children, href, ...props }: { children: ReactNode; href: string } & React.ComponentProps<"a">) => (
    <a href={href} {...props}>
      {children}
    </a>
  ),
  useNavigation: () => ({
    pathname: "/active/issues",
    push: vi.fn(),
    openWorkspaceInNewWindow: state.openWorkspaceInNewWindow,
    workspacesInOtherWindows: state.workspacesInOtherWindows,
  }),
}));
vi.mock("@multica/core/paths", async (importOriginal) => ({
  ...(await importOriginal<typeof import("@multica/core/paths")>()),
  useCurrentWorkspace: () => ({ id: "ws-1", name: "Active WS", slug: "active" }),
}));
vi.mock("@multica/core/api", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@multica/core/api")>();
  return {
    ...actual,
    api: {
      ...actual.api,
      getBaseUrl: () => "http://127.0.0.1:8080",
    },
  };
});
vi.mock("@multica/core/inbox/queries", () => ({
  inboxUnreadSummaryOptions: () => ({ queryKey: ["inbox", "unread-summary"] }),
  inboxUnreadSummaryEnabled: () => true,
  unreadWorkspaceIds: (entries: { workspace_id: string; count: number }[]) =>
    new Set(entries.filter((s) => s.count > 0).map((s) => s.workspace_id)),
}));
vi.mock("@multica/core/workspace/queries", () => ({
  myInvitationListOptions: () => ({ queryKey: ["invitations"] }),
  workspaceListOptions: () => ({ queryKey: ["workspaces"] }),
}));
vi.mock("@tanstack/react-query", async (importOriginal) => ({
  ...(await importOriginal<typeof import("@tanstack/react-query")>()),
  useQuery: ({ queryKey }: { queryKey: readonly unknown[] }) => {
    if (queryKey[0] === "workspaces") return { data: state.workspaces };
    if (queryKey[0] === "invitations") return { data: state.invitations };
    if (queryKey[0] === "inbox") return { data: state.summary };
    return { data: undefined };
  },
}));
vi.mock("@multica/ui/components/common/tooltip-hint", () => ({
  TooltipHint: ({ children }: { children: ReactNode }) => <>{children}</>,
}));

const ws = (n: number): Ws => ({ id: `ws-${n}`, name: n === 1 ? "Active WS" : `WS ${n}`, slug: n === 1 ? "active" : `ws${n}`, avatar_url: null });
const trigger = () => screen.getByRole("button", { name: "Switch workspace" });
const triggerHasDot = () => !!trigger().querySelector(".bg-brand");
const openMenu = async () => {
  fireEvent.click(trigger());
  return screen.findByRole("menu");
};

beforeEach(() => {
  state.workspaces = [ws(1), ws(2)];
  state.invitations = [];
  state.summary = [];
  state.setPinned.mockClear();
  state.workspaceCreationDisabled = false;
  state.openWorkspaceInNewWindow = undefined;
  state.workspacesInOtherWindows = undefined;
});

describe("RailWorkspaces", () => {
  it("shows only the current workspace on the rail, however many there are", async () => {
    state.workspaces = [ws(2), ws(3), ws(4), ws(5), ws(6), ws(1)];
    renderWithI18n(<RailWorkspaces />);
    expect(screen.queryAllByRole("link")).toHaveLength(0);

    const menu = await openMenu();
    const items = within(menu).getAllByRole("menuitem").filter((el) => el.getAttribute("href") !== "/workspaces/new");
    expect(items.map((el) => el.textContent?.slice(1))).toEqual(["WS 2", "WS 3", "WS 4", "WS 5", "WS 6", "Active WS"]);
    expect(within(menu).getByRole("menuitem", { name: /Active WS$/ })).toHaveAttribute("aria-current", "page");
    expect(within(menu).getByRole("menuitem", { name: /WS 3$/ })).toHaveAttribute("href", "/ws3/issues");
  });

  it("marks pinned workspaces and offers a pin control without navigating", async () => {
    state.workspaces = [{ ...ws(2), pinned_at: "2026-04-01T00:00:00Z" }, ws(1), ws(3)];
    state.summary = [{ workspace_id: "ws-2", count: 1 }];
    renderWithI18n(<RailWorkspaces />);
    const menu = await openMenu();
    const rows = within(menu).getAllByRole("menuitem").filter((item) => item.getAttribute("href")?.endsWith("/issues"));
    expect(rows.map((item) => item.getAttribute("href"))).toEqual(["/ws2/issues", "/active/issues", "/ws3/issues"]);
    const pinned = within(menu).getByRole("menuitem", { name: /WS 2/ });
    expect(pinned.querySelector(".text-brand")).toBeInTheDocument();
    const button = within(pinned).getByRole("button", { name: "Unpin workspace" });
    fireEvent.mouseOver(pinned);
    expect(fireEvent.click(button)).toBe(false);
    expect(state.setPinned).toHaveBeenCalledWith({ workspaceId: "ws-2", pinned: false });
    expect(within(screen.getByRole("menu")).getByRole("menuitem", { name: /WS 2/ })).toBeInTheDocument();
    expect(within(menu).getAllByRole("button", { name: "Pin workspace" })).toHaveLength(2);
  });

  it("uses unread tone for pins and keeps the current check beside its pin", async () => {
    state.workspaces = [{ ...ws(1), pinned_at: "2026-03-01T00:00:00Z" }, { ...ws(2), pinned_at: "2026-02-01T00:00:00Z" }, ws(3)];
    state.summary = [{ workspace_id: "ws-3", count: 2 }];
    renderWithI18n(<RailWorkspaces />);
    const menu = await openMenu();
    const current = within(menu).getByRole("menuitem", { name: /Active WS/ });
    expect(current.querySelector(".icon-check")).toBeInTheDocument();
    expect(current.querySelector(".icon-pin.fill-current.text-muted-foreground")).toBeInTheDocument();
    const pinned = within(menu).getByRole("menuitem", { name: /WS 2/ });
    expect(pinned.querySelector(".icon-pin.fill-current.text-muted-foreground")).toBeInTheDocument();
    const unread = within(menu).getByRole("menuitem", { name: /WS 3/ });
    expect(unread.querySelector(".bg-brand")).toBeInTheDocument();
    const button = within(unread).getByRole("button", { name: "Pin workspace" });
    expect(button).toHaveClass("text-brand");
    expect(button.querySelector(".fill-current")).toBeNull();
    fireEvent.mouseOver(unread);
    expect(button).toHaveClass("group-hover/workspace:opacity-100");
  });

  it("dots the switcher while another workspace has unread inbox items", async () => {
    state.summary = [{ workspace_id: "ws-2", count: 3 }];
    renderWithI18n(<RailWorkspaces />);
    expect(triggerHasDot()).toBe(true);
    const menu = await openMenu();
    expect(within(menu).getByRole("menuitem", { name: /WS 2$/ }).querySelector(".bg-brand")).not.toBeNull();
  });

  // The current workspace's unread is the Inbox space's count.
  it("does not dot the switcher for the current workspace or zero counts", () => {
    state.summary = [
      { workspace_id: "ws-1", count: 5 },
      { workspace_id: "ws-2", count: 0 },
    ];
    renderWithI18n(<RailWorkspaces />);
    expect(triggerHasDot()).toBe(false);
  });

  it("links pending invitations to the invitations page and dots the switcher", async () => {
    state.invitations = [
      { id: "inv-1", workspace_id: "ws-8", workspace_name: "Copilot Hub" },
      { id: "inv-2", workspace_id: "ws-9", workspace_name: "Lumen Labs" },
    ];
    renderWithI18n(<RailWorkspaces />);
    expect(triggerHasDot()).toBe(true);
    const menu = await openMenu();
    const entry = within(menu).getByRole("menuitem", { name: /Pending invitations/ });
    expect(entry).toHaveAttribute("href", "/invitations");
    expect(entry).toHaveTextContent("2");
    expect(within(menu).queryByText("Copilot Hub")).toBeNull();
  });

  it("offers no invitations entry when none are pending", async () => {
    renderWithI18n(<RailWorkspaces />);
    const menu = await openMenu();
    expect(within(menu).queryByRole("menuitem", { name: /Pending invitations/ })).toBeNull();
  });

  it("offers workspace creation unless the instance disables it", async () => {
    const { unmount } = renderWithI18n(<RailWorkspaces />);
    expect(within(await openMenu()).getByRole("menuitem", { name: "Create workspace" })).toBeInTheDocument();
    unmount();

    state.workspaceCreationDisabled = true;
    renderWithI18n(<RailWorkspaces />);
    expect(within(await openMenu()).queryByRole("menuitem", { name: "Create workspace" })).toBeNull();
  });

  describe("new windows", () => {
    const row = (menu: HTMLElement, name: RegExp) => within(menu).getByRole("menuitem", { name });

    beforeEach(() => {
      state.openWorkspaceInNewWindow = vi.fn();
      state.workspaces = [ws(1), ws(2), ws(3)];
    });

    it("keeps pin and new-window actions separate without following the row link", async () => {
      renderWithI18n(<RailWorkspaces />);
      const menu = await openMenu();
      const target = row(menu, /WS 3/);
      fireEvent.click(within(target).getByRole("button", { name: "Pin workspace" }));
      expect(state.setPinned).toHaveBeenCalledWith({ workspaceId: "ws-3", pinned: true });
      expect(state.openWorkspaceInNewWindow).not.toHaveBeenCalled();
      expect(menu).toBeInTheDocument();
      const button = within(target).getByRole("button", { name: "Open in new window" });
      const notPrevented = fireEvent.click(button);

      expect(state.openWorkspaceInNewWindow).toHaveBeenCalledWith("ws3");
      expect(notPrevented).toBe(false);
    });

    it("opens a workspace in a new window on shift-click", async () => {
      renderWithI18n(<RailWorkspaces />);
      const menu = await openMenu();
      const target = row(menu, /WS 2/);
      const notPrevented = fireEvent.click(target, { shiftKey: true });

      expect(state.openWorkspaceInNewWindow).toHaveBeenCalledWith("ws2");
      expect(notPrevented).toBe(false);
    });

    it("leaves a plain or cmd+shift click to the row link", async () => {
      renderWithI18n(<RailWorkspaces />);
      const menu = await openMenu();
      fireEvent.click(row(menu, /WS 2/));
      fireEvent.click(row(menu, /WS 2/), { shiftKey: true, metaKey: true });
      expect(state.openWorkspaceInNewWindow).not.toHaveBeenCalled();
    });

    it("marks a workspace another window shows instead of offering a new window for it", async () => {
      state.workspacesInOtherWindows = () => ["ws2"];
      renderWithI18n(<RailWorkspaces />);
      const menu = await openMenu();

      const shown = row(menu, /WS 2/);
      expect(within(shown).getByText("Other window")).toBeInTheDocument();
      expect(within(row(menu, /WS 3/)).queryByText("Other window")).toBeNull();
      expect(within(shown).queryByRole("button", { name: "Open in new window" })).toBeNull();
      expect(within(row(menu, /WS 3/)).getByRole("button", { name: "Open in new window" })).toBeInTheDocument();
      fireEvent.click(shown, { shiftKey: true });
      expect(state.openWorkspaceInNewWindow).not.toHaveBeenCalled();
    });

    it("offers no new window for the current workspace", async () => {
      renderWithI18n(<RailWorkspaces />);
      const menu = await openMenu();
      expect(within(row(menu, /Active WS/)).queryByRole("button", { name: "Open in new window" })).toBeNull();
    });

    it("offers no new windows on web", async () => {
      state.openWorkspaceInNewWindow = undefined;
      renderWithI18n(<RailWorkspaces />);
      const menu = await openMenu();
      expect(within(menu).queryByRole("button", { name: "Open in new window" })).toBeNull();
    });
  });
});