Skip to content

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

Go
23.4 KB
Raw Blame
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { ReactNode } from "react";
import { act, render, renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ApiError, setApiInstance, type ApiClient } from "@multica/core/api";
import { createQueryClient } from "@multica/core/query-client";
import type { Issue, ListIssueStatusesResponse } from "@multica/core/types";
import { onIssueUpdated } from "@multica/core/issues";
import { issueDetailOptions } from "@multica/core/issues/queries";
import { issueStatusListOptions } from "@multica/core/issue-statuses/queries";
import { projectDetailOptions } from "@multica/core/projects/queries";
import { chatSessionsOptions } from "@multica/core/chat/queries";
import {
  inboxListOptions,
  archivedInboxPagesOptions,
  archivedInboxLookupOptions,
} from "@multica/core/inbox/queries";
import { EMPTY_INBOX_FILTERS } from "@multica/core/inbox/filter-store";
import { agentListOptions } from "@multica/core/workspace/queries";
import { runtimeListOptions } from "@multica/core/runtimes/queries";

// Mutable workspace stub so a test can simulate "workspace not resolved yet".
const ws = vi.hoisted(() => ({ current: { id: "ws1", slug: "acme" } as { id: string; slug: string } | null }));

vi.mock("@multica/core/paths", async (importOriginal) => ({
  ...(await importOriginal<typeof import("@multica/core/paths")>()),
  useCurrentWorkspace: () => ws.current,
}));

vi.mock("../i18n", async () => {
  const layout = (await import("../locales/en/layout.json")).default;
  const chat = (await import("../locales/en/chat.json")).default;
  const bundles: Record<string, unknown> = { layout, chat };
  return {
    useT: (ns: string) => ({
      t: (select: (b: Record<string, unknown>) => string) =>
        select(bundles[ns] as Record<string, unknown>),
    }),
  };
});

// ActorAvatar reaches into workspace directory queries; the hook returns a
// descriptor (not the rendered avatar), so the render test stubs it.
vi.mock("../common/actor-avatar", () => ({
  ActorAvatar: ({ actorType, actorId }: { actorType: string; actorId: string }) => (
    <span data-testid="actor-avatar" data-actor={`${actorType}:${actorId}`} />
  ),
}));

import { useTabPresentation, ResourceLeadingVisual } from "./tab-presentation";

function makeClient() {
  return new QueryClient({ defaultOptions: { queries: { retry: false } } });
}

function seed(qc: QueryClient) {
  qc.setQueryData(issueDetailOptions("ws1", "i1").queryKey, {
    id: "i1",
    identifier: "MUL-1",
    title: "Fix login",
    status: "in_progress",
  } as never);
  qc.setQueryData(issueDetailOptions("ws1", "i9").queryKey, {
    id: "i9",
    identifier: "MUL-9",
    title: "Crash",
    status: "todo",
  } as never);
  qc.setQueryData(projectDetailOptions("ws1", "p1").queryKey, {
    id: "p1",
    icon: "🚀",
    title: "Apollo",
  } as never);
  qc.setQueryData(chatSessionsOptions("ws1").queryKey, [
    { id: "s1", title: "Deploy plan", status: "active" },
    { id: "s2", title: "  ", status: "active" },
  ] as never);
  qc.setQueryData(inboxListOptions("ws1").queryKey, [
    { id: "n1", issue_id: "i9", title: "Assigned to you", type: "issue_assigned" },
    { id: "n2", issue_id: null, title: "Quick create failed", type: "quick_create_failed" },
  ] as never);
  const archiveRow = {
    workspace_id: "ws1", recipient_type: "member" as const, recipient_id: "user",
    actor_type: null, actor_id: null, severity: "info" as const, body: null,
    issue_status: null, read: true, archived: true, created_at: "2026-09-01T00:00:00Z", details: null,
  };
  // Archived list is a distinct cache; these items are NOT in the main list.
  qc.setQueryData(archivedInboxPagesOptions("ws1", EMPTY_INBOX_FILTERS).queryKey, {
    pages: [{ items: [
      { ...archiveRow, id: "a1", issue_id: "i1", title: "Old assignment", type: "issue_assigned" },
      { ...archiveRow, id: "a2", issue_id: null, title: "Archived note", type: "quick_create_failed" },
    ], hasMore: false, nextCursor: null }], pageParams: [null],
  });
  qc.setQueryData(archivedInboxLookupOptions("ws1", "a3").queryKey, {
    items: [{ ...archiveRow, id: "a3", issue_id: null, title: "Deep archived note", type: "quick_create_failed" }],
    hasMore: false, nextCursor: null,
  });
  qc.setQueryData(agentListOptions("ws1").queryKey, [
    { id: "ag1", name: "Robby", avatar_url: null },
  ] as never);
  qc.setQueryData(runtimeListOptions("ws1").queryKey, [
    { id: "rt1", name: "Claude (host)", custom_name: "Prod Box", provider: "claude", status: "online" },
    { id: "rt2", name: "Codex (host)", custom_name: null, provider: "codex", status: "online" },
  ] as never);
}

function presentationOf(url: string, fallback?: string) {
  const qc = makeClient();
  seed(qc);
  const wrapper = ({ children }: { children: ReactNode }) => (
    <QueryClientProvider client={qc}>{children}</QueryClientProvider>
  );
  const { visual, title } = renderHook(() => useTabPresentation(url, fallback), { wrapper }).result.current;
  return { visual, title };
}

beforeEach(() => {
  ws.current = { id: "ws1", slug: "acme" };
});

it("updates a tab's custom icon from the shared catalog cache without fetching", () => {
  const qc = makeClient();
  seed(qc);
  qc.setQueryData(issueDetailOptions("ws1", "i1").queryKey, {
    id: "i1", identifier: "MUL-1", title: "QA", status: "qa", status_category: "started",
  } as never);
  qc.setQueryData(issueStatusListOptions("ws1").queryKey, {
    statuses: [{
      id: "qa", workspace_id: "ws1", key: "qa", name: "QA", description: "",
      category: "started", color: "#123456", icon: "slash", is_system: false,
      position: 0, archived_at: null, created_at: "", updated_at: "",
    }],
    categories: ["unstarted", "started", "done", "closed"],
    total: 1,
  });
  const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
  const { result } = renderHook(() => useTabPresentation("/acme/issues/i1"), { wrapper });
  expect(result.current.visual).toMatchObject({ kind: "issue-status", status: "qa", icon: "slash", color: "#123456" });
  const { container } = render(<ResourceLeadingVisual visual={result.current.visual} />);
  expect(container.querySelector("svg line")).not.toBeNull();
});

describe("useTabPresentation — live from cache", () => {
  it("page: page icon + localized page name", () => {
    expect(presentationOf("/acme/issues")).toEqual({
      visual: { kind: "icon", icon: "ListTodo" },
      title: "Issues",
    });
  });

  it("issue: live status glyph + identifier:title", () => {
    expect(presentationOf("/acme/issues/i1")).toEqual({
      // `category` travels with the visual so the tab strip never resolves a
      // custom status key itself. (MUL-6243)
      visual: { kind: "issue-status", status: "in_progress", category: "started" },
      title: "MUL-1: Fix login",
    });
  });

  it("project: own icon + title", () => {
    expect(presentationOf("/acme/projects/p1")).toEqual({
      visual: { kind: "project-icon", icon: "🚀" },
      title: "Apollo",
    });
  });

  it("actor: avatar visual + resolved name", () => {
    expect(presentationOf("/acme/agents/ag1")).toEqual({
      visual: { kind: "actor", actorType: "agent", id: "ag1" },
      title: "Robby",
    });
  });

  it("machine tab shows the runtime's alias with its provider", () => {
    expect(presentationOf("/acme/runtimes/rt1")).toEqual({
      visual: { kind: "icon", icon: "Monitor" },
      title: "Prod Box (Claude)",
    });
  });

  it("runtime tab without an alias keeps the daemon name", () => {
    expect(presentationOf("/acme/runtimes/m1/runtime/rt2").title).toBe("Codex (host)");
  });

  it("runtime tab with an alias shows the provider", () => {
    expect(presentationOf("/acme/runtimes/m1/runtime/rt1").title).toBe("Prod Box (Claude)");
  });

  it("chat container: MessageSquare icon + session title", () => {
    expect(presentationOf("/acme/chat?session=s1")).toEqual({
      visual: { kind: "icon", icon: "MessageSquare" },
      title: "Deploy plan",
    });
  });

  it("chat container: blank session title uses the New chat fallback", () => {
    expect(presentationOf("/acme/chat?session=s2").title).toBe("New chat");
  });

  it("chat container: no session stays Chat", () => {
    expect(presentationOf("/acme/chat")).toEqual({
      visual: { kind: "icon", icon: "MessageSquare" },
      title: "Chat",
    });
  });

  it("inbox container: selected issue shows Inbox icon + issue title", () => {
    // Selection key is issue_id ?? id — n1 links issue i9.
    expect(presentationOf("/acme/inbox?issue=i9")).toEqual({
      visual: { kind: "icon", icon: "Inbox" },
      title: "MUL-9: Crash",
    });
  });

  it("inbox container: selected non-issue shows its display title", () => {
    expect(presentationOf("/acme/inbox?issue=n2")).toEqual({
      visual: { kind: "icon", icon: "Inbox" },
      title: "Quick create failed",
    });
  });

  it("issue-backed selection resolves by object, in either view", () => {
    // The selection key IS the group key (`issue_id ?? id`), so an
    // issue-backed selection names the issue directly and is answered by the
    // issue cache — no inbox list involved. That holds in both views on
    // purpose: i1's notification lives only in the ARCHIVED list, yet the main
    // view still titles the tab by the object the URL names. Treating "not in
    // the list I loaded" as "does not exist" is what this must not do — the
    // page itself resolves such a link to the issue rather than dropping it
    // (see the deep-link fallback in inbox-page).
    expect(presentationOf("/acme/inbox?issue=i1")).toEqual({
      visual: { kind: "icon", icon: "Inbox" },
      title: "MUL-1: Fix login",
    });
    expect(presentationOf("/acme/inbox?view=archived&issue=i1")).toEqual({
      visual: { kind: "icon", icon: "Inbox" },
      title: "MUL-1: Fix login",
    });
  });

  it("issue-backed selection survives a cold inbox list", () => {
    // Regression (MUL-6967): the badge no longer pre-warms the inbox list at
    // app start, so a restored tab may have the issue cached but no list. It
    // must still show the issue, not collapse to the container label.
    const qc = makeClient();
    seed(qc);
    qc.removeQueries({ queryKey: inboxListOptions("ws1").queryKey });
    qc.removeQueries({ queryKey: archivedInboxPagesOptions("ws1", EMPTY_INBOX_FILTERS).queryKey });
    const wrapper = ({ children }: { children: ReactNode }) => (
      <QueryClientProvider client={qc}>{children}</QueryClientProvider>
    );

    const { result } = renderHook(
      () => useTabPresentation("/acme/inbox?issue=i9", "MUL-9: Crash"),
      { wrapper },
    );

    expect(result.current.title).toBe("MUL-9: Crash");
  });

  it("falls back to the persisted title while a selection is unresolved", () => {
    // Nothing cached for this key yet — an issue-less notification whose row
    // has not loaded. The persisted title is a better first frame than
    // "Inbox"; without it the tab loses its identity until the page loads.
    const qc = makeClient();
    const wrapper = ({ children }: { children: ReactNode }) => (
      <QueryClientProvider client={qc}>{children}</QueryClientProvider>
    );

    const { result } = renderHook(
      () => useTabPresentation("/acme/inbox?issue=n7", "Autopilot paused"),
      { wrapper },
    );

    expect(result.current.title).toBe("Autopilot paused");
  });

  it("uses the container label when nothing is selected, persisted title or not", () => {
    // The fallback is for a PENDING identity only. An Inbox tab with no
    // selection is fully resolved — it really is just "Inbox", and a stale
    // persisted title must not override it.
    expect(presentationOf("/acme/inbox", "MUL-9: Crash").title).toBe("Inbox");
  });

  it("archived inbox: selected non-issue resolves against the archived list", () => {
    expect(presentationOf("/acme/inbox?view=archived&issue=a2")).toEqual({
      visual: { kind: "icon", icon: "Inbox" },
      title: "Archived note",
    });
  });

  it("archived inbox: a deep-link lookup supplies the title outside loaded pages", () => {
    expect(presentationOf("/acme/inbox?view=archived&issue=a3")).toEqual({
      visual: { kind: "icon", icon: "Inbox" }, title: "Deep archived note",
    });
  });

  it("attachment: filename from ?name= drives the title and file icon", () => {
    expect(presentationOf("/acme/attachments/att1/preview?name=diagram.png")).toEqual({
      visual: { kind: "icon", icon: "FileImage" },
      title: "diagram.png",
    });
    // Missing filename → generic File + localized "Attachment".
    expect(presentationOf("/acme/attachments/att1/preview")).toEqual({
      visual: { kind: "icon", icon: "File" },
      title: "Attachment",
    });
  });
});

describe("useTabPresentation — pending / fallback", () => {
  it.each([undefined, "Saved session"])("keeps an unresolved chat selection pending with fallback %s", async (fallback) => {
    const qc = makeClient();
    const wrapper = ({ children }: { children: ReactNode }) => (
      <QueryClientProvider client={qc}>{children}</QueryClientProvider>
    );
    const { result } = renderHook(
      () => useTabPresentation("/acme/chat?session=s7", fallback), { wrapper },
    );

    expect(result.current).toMatchObject({ title: fallback ?? "Chat", titleResolved: false });
    act(() => qc.setQueryData(chatSessionsOptions("ws1").queryKey, [
      { id: "s7", title: "Loaded session" },
    ] as never));
    await waitFor(() => expect(result.current).toMatchObject({
      title: "Loaded session", titleResolved: true,
    }));
  });

  it("pending issue keeps the issue-status slot and uses the persisted fallback", () => {
    expect(presentationOf("/acme/issues/unloaded", "MUL-7: Prior")).toEqual({
      visual: { kind: "issue-status", status: null },
      title: "MUL-7: Prior",
    });
  });

  it("pending issue with no fallback shows the localized type label, not Issues", () => {
    const p = presentationOf("/acme/issues/unloaded");
    expect(p.visual).toEqual({ kind: "issue-status", status: null });
    expect(p.title).toBe("Issue");
  });

  it("unknown route is neutral, never Issues", () => {
    expect(presentationOf("/acme/mystery")).toEqual({
      visual: { kind: "icon", icon: "FileQuestion" },
      title: "Unknown page",
    });
  });

  it("actor falls back to a type icon before the workspace resolves", () => {
    ws.current = null;
    expect(presentationOf("/acme/agents/ag1").visual).toEqual({
      kind: "icon",
      icon: "Bot",
    });
  });
});

describe("ResourceLeadingVisual", () => {
  it("uses a neutral skeleton while the status has not loaded", () => {
    const { container, rerender } = render(
      <ResourceLeadingVisual visual={{ kind: "issue-status", status: null }} />,
    );
    expect(container.querySelector("svg")).toBeNull();
    expect(container.querySelector('[data-slot="skeleton"]')).toBeVisible();
    rerender(<ResourceLeadingVisual visual={{ kind: "issue-status", status: "todo" }} />);
    expect(container.querySelector('[data-slot="skeleton"]')).toBeNull();
    expect(container.querySelector("svg")).not.toBeNull();
  });

  it("renders a project icon with its emoji", () => {
    const { getByText } = render(
      <ResourceLeadingVisual visual={{ kind: "project-icon", icon: "🚀" }} />,
    );
    expect(getByText("🚀")).toBeTruthy();
  });

  it("renders a status glyph for an issue", () => {
    const { container } = render(
      <ResourceLeadingVisual visual={{ kind: "issue-status", status: "done" }} />,
    );
    expect(container.querySelector("svg")).toBeTruthy();
  });

  it("renders the actor avatar for an actor visual", () => {
    const { getByTestId } = render(
      <ResourceLeadingVisual
        visual={{ kind: "actor", actorType: "agent", id: "ag1" }}
      />,
    );
    expect(getByTestId("actor-avatar").getAttribute("data-actor")).toBe("agent:ag1");
  });

  it("renders a route icon for a plain icon visual", () => {
    const { container } = render(
      <ResourceLeadingVisual visual={{ kind: "icon", icon: "Inbox" }} />,
    );
    expect(container.querySelector("svg")).toBeTruthy();
  });
});

describe("useTabPresentation — restored issue tabs", () => {
  const issue: Issue = {
    id: "cb240efb-154c-42a8-ae92-42b02676feca", workspace_id: "ws1",
    number: 7, identifier: "MUL-7", title: "Restore tabs", description: null,
    status: "in_progress", status_category: "started", priority: "medium",
    assignee_type: null, assignee_id: null, creator_type: "member", creator_id: "u1",
    parent_issue_id: null, project_id: null, position: 0, stage: null,
    start_date: null, due_date: null, metadata: {}, properties: {}, labels: [],
    created_at: "2026-11-06T00:00:00Z", updated_at: "2026-11-06T00:00:00Z",
  };
  let qc: QueryClient;
  let getIssue: ReturnType<typeof vi.fn>;
  let listIssueStatuses: ReturnType<typeof vi.fn>;

  beforeEach(() => {
    qc = createQueryClient();
    qc.setDefaultOptions({ queries: { ...qc.getDefaultOptions().queries, retry: false } });
    getIssue = vi.fn(async () => issue);
    listIssueStatuses = vi.fn(async (): Promise<ListIssueStatusesResponse> => ({
      statuses: [], categories: ["unstarted", "started", "done", "closed"], total: 0,
    }));
    setApiInstance({ getIssue, listIssueStatuses } as unknown as ApiClient);
  });

  afterEach(() => qc.clear());

  function wrapper({ children }: { children: ReactNode }) {
    return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
  }

  it("loads an identifier tab once and follows UUID realtime patches without opening its page", async () => {
    const { result } = renderHook(
      () => useTabPresentation("/acme/issues/MUL-7", "Prior title", { fetch: true }),
      { wrapper },
    );
    await waitFor(() => expect(result.current.title).toBe("MUL-7: Restore tabs"));
    expect(result.current.titleResolved).toBe(true);
    expect(result.current.issueIdentity).toEqual({ id: issue.id, identifier: "MUL-7" });
    expect(qc.getQueryData(issueDetailOptions("ws1", issue.id).queryKey)).toEqual(issue);
    expect(getIssue).toHaveBeenCalledExactlyOnceWith("MUL-7");

    act(() => onIssueUpdated(qc, "ws1", { ...issue, status: "done", status_category: "done", title: "Fixed" }));
    await waitFor(() => expect(result.current.visual).toMatchObject({ status: "done", category: "done" }));
    expect(result.current.title).toBe("MUL-7: Fixed");
    expect(getIssue).toHaveBeenCalledTimes(1);
  });

  it("shares the detail and catalog requests between tabs for the same issue", async () => {
    const { result } = renderHook(() => [
      useTabPresentation(`/acme/issues/${issue.id}`, undefined, { fetch: true }),
      useTabPresentation(`/acme/issues/${issue.id}`, undefined, { fetch: true }),
    ], { wrapper });
    await waitFor(() => expect(result.current.every((tab) => tab.title === "MUL-7: Restore tabs")).toBe(true));
    expect(getIssue).toHaveBeenCalledExactlyOnceWith(issue.id);
    expect(listIssueStatuses).toHaveBeenCalledExactlyOnceWith(true);
  });

  it("preserves server categories and loads custom colors without a custom icon", async () => {
    getIssue.mockResolvedValue({ ...issue, status: "qa" });
    listIssueStatuses.mockResolvedValue({
      statuses: [{ id: "qa", workspace_id: "ws1", key: "qa", name: "QA", description: "",
        category: "started", color: "#123456", icon: null, is_system: false,
        position: 0, archived_at: null, created_at: "", updated_at: "" }],
      categories: ["unstarted", "started", "done", "closed"], total: 1,
    });
    const { result } = renderHook(
      () => useTabPresentation(`/acme/issues/${issue.id}`, undefined, { fetch: true }), { wrapper },
    );
    await waitFor(() => expect(result.current.visual).toMatchObject({
      status: "qa", category: "started", color: "#123456", icon: null,
    }));
  });

  it("keeps the server category when the catalog is unavailable", async () => {
    getIssue.mockResolvedValue({ ...issue, status: "qa" });
    listIssueStatuses.mockRejectedValue(new Error("offline"));
    const { result } = renderHook(
      () => useTabPresentation(`/acme/issues/${issue.id}`, undefined, { fetch: true }), { wrapper },
    );
    await waitFor(() => expect(result.current.visual).toMatchObject({ status: "qa", category: "started" }));
  });

  it("stays cache-only unless fetching is requested", async () => {
    const { result } = renderHook(() => useTabPresentation(`/acme/issues/${issue.id}`, "Saved"), { wrapper });
    await act(async () => {});
    expect(getIssue).not.toHaveBeenCalled();
    expect(listIssueStatuses).not.toHaveBeenCalled();
    expect(result.current.title).toBe("Saved");
  });

  it("waits for the workspace before starting requests", async () => {
    ws.current = null;
    const { result, rerender } = renderHook(
      () => useTabPresentation(`/acme/issues/${issue.id}`, "Saved", { fetch: true }), { wrapper },
    );
    await act(async () => {});
    expect(getIssue).not.toHaveBeenCalled();
    expect(listIssueStatuses).not.toHaveBeenCalled();
    ws.current = { id: "ws1", slug: "acme" };
    rerender();
    await waitFor(() => expect(result.current.title).toBe("MUL-7: Restore tabs"));
    expect(getIssue).toHaveBeenCalledTimes(1);
  });

  it("only fetches inbox selections known to reference an issue", async () => {
    qc.setQueryData(inboxListOptions("ws1").queryKey, [{
      id: "n1", workspace_id: "ws1", recipient_type: "member", recipient_id: "u1",
      actor_type: null, actor_id: null, type: "issue_assigned", severity: "info",
      issue_id: issue.id, title: "Assigned to you", body: null, issue_status: "in_progress",
      read: false, archived: false, created_at: issue.created_at, details: null,
    }]);
    const { result } = renderHook(
      () => useTabPresentation(`/acme/inbox?issue=${issue.id}`, "Saved", { fetch: true }), { wrapper },
    );
    await waitFor(() => expect(result.current.title).toBe("MUL-7: Restore tabs"));
    expect(getIssue).toHaveBeenCalledExactlyOnceWith(issue.id);
  });

  it.each(["n2", "unknown-notification"])("does not query an issue for the notification %s", async (key) => {
    seed(qc);
    renderHook(() => useTabPresentation(`/acme/inbox?issue=${key}`, "Saved", { fetch: true }), { wrapper });
    await act(async () => {});
    expect(getIssue).not.toHaveBeenCalled();
  });

  it.each([new Error("offline"), new ApiError("Not found", 404, "Not Found")])("preserves the title and unresolved status when the request fails: %s", async (error) => {
    getIssue.mockRejectedValue(error);
    const { result } = renderHook(
      () => useTabPresentation(`/acme/issues/${issue.id}`, "Saved", { fetch: true }), { wrapper },
    );
    await waitFor(() => expect(qc.getQueryState(issueDetailOptions("ws1", issue.id).queryKey)?.status).toBe("error"));
    expect(result.current).toMatchObject({ title: "Saved", titleResolved: false, visual: { status: null } });
    expect(getIssue).toHaveBeenCalledTimes(1);
  });

  it("refreshes a background tab after reconnect invalidation", async () => {
    const { result } = renderHook(
      () => useTabPresentation(`/acme/issues/${issue.id}`, undefined, { fetch: true }), { wrapper },
    );
    await waitFor(() => expect(result.current.title).toBe("MUL-7: Restore tabs"));
    getIssue.mockResolvedValue({ ...issue, title: "Changed while offline", status: "done", status_category: "done" });
    await act(() => qc.invalidateQueries({ queryKey: ["issues", "ws1"] }));
    await waitFor(() => expect(result.current.title).toBe("MUL-7: Changed while offline"));
    expect(result.current.visual).toMatchObject({ status: "done", category: "done" });
  });
});