Skip to content

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

Go
16.3 KB
Raw Blame
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { renderHook, act, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { buildIssueStatusCatalog } from "@multica/core/issue-statuses";
import { statusCategoryOfKey } from "@multica/core/issues";
import type { Issue, IssueStatusEntry } from "@multica/core/types";
import * as clipboard from "@multica/ui/lib/clipboard";

vi.mock("@multica/core/hooks", () => ({
  useWorkspaceId: () => "ws-1",
}));

const mockOpenModal = vi.fn();
vi.mock("@multica/core/modals", () => ({
  useModalStore: Object.assign(
    (selector?: any) => {
      const state = { open: mockOpenModal };
      return selector ? selector(state) : state;
    },
    { getState: () => ({ open: mockOpenModal }) },
  ),
}));

const mockAuthState = { user: { id: "user-1" }, isAuthenticated: true };
vi.mock("@multica/core/auth", () => ({
  useAuthStore: Object.assign(
    (selector?: any) => (selector ? selector(mockAuthState) : mockAuthState),
    { getState: () => mockAuthState },
  ),
  registerAuthStore: vi.fn(),
}));

// Mutable so individual tests can seed the pin list.
const pinListRef: { value: Array<{ item_type: string; item_id: string }> } = {
  value: [],
};
const mockCreatePinMutate = vi.fn();
const mockDeletePinMutate = vi.fn();
vi.mock("@multica/core/pins", () => ({
  pinListOptions: () => ({
    queryKey: ["pins", "ws-1", "user-1"],
    queryFn: () => Promise.resolve(pinListRef.value),
  }),
  useCreatePin: () => ({ mutate: mockCreatePinMutate }),
  useDeletePin: () => ({ mutate: mockDeletePinMutate }),
}));

const mockUpdateMutate = vi.fn();
const mockUpdateMutateAsync = vi.fn();
vi.mock("@multica/core/issues/mutations", () => ({
  useUpdateIssue: () => ({ mutate: mockUpdateMutate, mutateAsync: mockUpdateMutateAsync }),
}));

// The status catalog is server state; this suite only needs it to answer which
// CATEGORY a key belongs to, so the entries are fed in directly. `later` parks
// like Backlog and `rework` starts work like Todo — the two cases a raw
// `status === "backlog"` / `=== "todo"` comparison gets wrong (MUL-6463).
const catalogEntries: IssueStatusEntry[] = [
  ...(["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"] as const).map(
    (key, i) =>
      statusEntry({
        id: key,
        key,
        name: key,
        category: statusCategoryOfKey(key),
        is_system: true,
        position: i,
      }),
  ),
  statusEntry({ id: "later", key: "later", name: "Later", category: "unstarted", position: 7 }),
  statusEntry({ id: "rework", key: "rework", name: "Rework", category: "unstarted", position: 8 }),
];
function statusEntry(overrides: Partial<IssueStatusEntry>): IssueStatusEntry {
  return {
    id: "id",
    workspace_id: "ws-1",
    key: "custom",
    name: "Custom",
    description: "",
    category: "unstarted",
    color: "#22c55e",
    is_system: false,
    position: 0,
    archived_at: null,
    created_at: "",
    updated_at: "",
    ...overrides,
  };
}
vi.mock("@multica/core/issue-statuses/hooks", () => ({
  useIssueStatuses: () => buildIssueStatusCatalog(catalogEntries),
}));

vi.mock("@multica/core/paths", async () => {
  const actual = await vi.importActual<typeof import("@multica/core/paths")>(
    "@multica/core/paths",
  );
  return {
    ...actual,
    useCurrentWorkspace: () => ({ id: "ws-1", name: "Test", slug: "test" }),
    useWorkspacePaths: () => actual.paths.workspace("test"),
  };
});

vi.mock("../../../navigation", () => ({
  useNavigation: () => ({
    push: vi.fn(),
    pathname: "/test/issues/issue-1",
    searchParams: new URLSearchParams(),
    hash: "",
    back: vi.fn(),
    replace: vi.fn(),
    getShareableUrl: (p: string) => `https://app.multica.com${p}`,
  }),
}));

vi.mock("sonner", () => ({
  toast: { success: vi.fn(), error: vi.fn() },
}));

// Import AFTER mocks are registered.
import { toast } from "sonner";
import { useIssueActions } from "../use-issue-actions";

const mockIssue: Issue = {
  id: "issue-1",
  workspace_id: "ws-1",
  number: 1,
  identifier: "TES-1",
  title: "Example",
  description: null,
  status: "todo",
  priority: "medium",
  assignee_type: null,
  assignee_id: null,
  creator_type: "member",
  creator_id: "user-1",
  parent_issue_id: null,
  start_date: null,
  due_date: null,
  project_id: null,
  created_at: "2026-01-01T00:00:00Z",
  updated_at: "2026-01-01T00:00:00Z",
} as Issue;

function wrapper({ children }: { children: React.ReactNode }) {
  const qc = new QueryClient({
    defaultOptions: { queries: { retry: false } },
  });
  return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
}

beforeEach(() => {
  mockOpenModal.mockReset();
  mockUpdateMutate.mockReset();
  mockUpdateMutateAsync.mockReset().mockResolvedValue(mockIssue);
  mockCreatePinMutate.mockReset();
  mockDeletePinMutate.mockReset();
  vi.mocked(toast.success).mockReset();
  vi.mocked(toast.error).mockReset();
  pinListRef.value = [];
  localStorage.clear();
  Object.defineProperty(navigator, "clipboard", {
    configurable: true,
    value: { writeText: vi.fn().mockResolvedValue(undefined) },
  });
});

afterEach(() => {
  vi.restoreAllMocks();
});

describe("useIssueActions", () => {
  it("updateField dispatches useUpdateIssue.mutateAsync with the correct payload", () => {
    const { result } = renderHook(() => useIssueActions(mockIssue), { wrapper });

    act(() => {
      result.current.updateField({ status: "done" });
    });

    expect(mockUpdateMutateAsync).toHaveBeenCalledWith(
      { id: "issue-1", status: "done" },
      expect.any(Object),
    );
  });

  it("assigning an agent routes through the run-confirm modal instead of mutating directly", () => {
    const { result } = renderHook(() => useIssueActions(mockIssue), { wrapper });

    act(() => {
      result.current.updateField({
        assignee_type: "agent",
        assignee_id: "agent-1",
      });
    });

    expect(mockOpenModal).toHaveBeenCalledWith("issue-run-confirm", {
      issueIds: ["issue-1"],
      mode: "assign",
      assigneeType: "agent",
      assigneeId: "agent-1",
    });
    expect(mockUpdateMutateAsync).not.toHaveBeenCalled();
  });

  it("assigning an agent to a backlog issue applies directly — backlog never starts a run", () => {
    const backlogIssue = { ...mockIssue, status: "backlog" } as Issue;
    const { result } = renderHook(() => useIssueActions(backlogIssue), { wrapper });

    act(() => {
      result.current.updateField({
        assignee_type: "agent",
        assignee_id: "agent-1",
      });
    });

    expect(mockUpdateMutateAsync).toHaveBeenCalledWith(
      { id: "issue-1", assignee_type: "agent", assignee_id: "agent-1" },
      expect.any(Object),
    );
    expect(mockOpenModal).not.toHaveBeenCalled();
  });

  // Which writes need confirming is decided by runConfirmIntent, whose matrix
  // (parked / unresolvable categories, every promotion target) is canonical in
  // ../run-confirm-gate.test.ts. These two only prove the hook routes on it.
  it("promoting an agent-owned parked issue routes through the run-confirm modal", () => {
    const parked = {
      ...mockIssue,
      status: "backlog",
      assignee_type: "agent",
      assignee_id: "agent-1",
    } as Issue;
    const { result } = renderHook(() => useIssueActions(parked), { wrapper });

    act(() => {
      result.current.updateField({ status: "rework" });
    });

    expect(mockOpenModal).toHaveBeenCalledWith("issue-run-confirm", {
      issueIds: ["issue-1"],
      mode: "promote",
      status: "rework",
      assigneeType: "agent",
      assigneeId: "agent-1",
    });
    expect(mockUpdateMutateAsync).not.toHaveBeenCalled();
  });

  it("a status change that starts no run applies directly", () => {
    const { result } = renderHook(() => useIssueActions(mockIssue), { wrapper });

    act(() => {
      result.current.updateField({ status: "in_progress" });
    });

    expect(mockUpdateMutateAsync).toHaveBeenCalledWith(
      { id: "issue-1", status: "in_progress" },
      expect.any(Object),
    );
    expect(mockOpenModal).not.toHaveBeenCalled();
  });

  it("assigning a member applies directly without the run-confirm modal", () => {
    const { result } = renderHook(() => useIssueActions(mockIssue), { wrapper });

    act(() => {
      result.current.updateField({
        assignee_type: "member",
        assignee_id: "user-1",
      });
    });

    expect(mockUpdateMutateAsync).toHaveBeenCalledWith(
      { id: "issue-1", assignee_type: "member", assignee_id: "user-1" },
      expect.any(Object),
    );
    expect(mockOpenModal).not.toHaveBeenCalled();
  });

  it("copyLink writes the issue's human-readable shareable URL to the clipboard", async () => {
    const { result } = renderHook(() => useIssueActions(mockIssue), { wrapper });

    await act(async () => {
      await result.current.copyLink();
    });

    expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
      "https://app.multica.com/test/issues/TES-1",
    );
  });

  it("copyLink falls back to the UUID when the issue has no identifier", async () => {
    const { result } = renderHook(
      () => useIssueActions({ ...mockIssue, identifier: "" } as Issue),
      { wrapper },
    );

    await act(async () => {
      await result.current.copyLink();
    });

    expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
      "https://app.multica.com/test/issues/issue-1",
    );
  });

  it("copyTitleAsLink copies the identifier and title as a Markdown link", async () => {
    const { result } = renderHook(() => useIssueActions(mockIssue), { wrapper });

    await act(async () => {
      await result.current.copyTitleAsLink();
    });

    expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
      "[TES-1 Example](https://app.multica.com/test/issues/TES-1)",
    );
  });

  it("copyTitleAsLink reports a failed copy without a success toast", async () => {
    vi.spyOn(clipboard, "copyTextAndHtml").mockResolvedValueOnce(false);
    const { result } = renderHook(() => useIssueActions(mockIssue), { wrapper });

    await act(async () => {
      await result.current.copyTitleAsLink();
    });

    expect(toast.error).toHaveBeenCalledOnce();
    expect(toast.success).not.toHaveBeenCalled();
  });

  it("copyCommentLink writes the issue's shareable URL anchored at the comment", async () => {
    const { result } = renderHook(() => useIssueActions(mockIssue), { wrapper });

    await act(async () => {
      await result.current.copyCommentLink("comment-7");
    });

    expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
      "https://app.multica.com/test/issues/TES-1#comment-comment-7",
    );
  });

  it("openSetParent / openAddChild / openDeleteConfirm / openCreateSubIssue open the correct modal with payload", () => {
    const { result } = renderHook(() => useIssueActions(mockIssue), { wrapper });

    act(() => {
      result.current.openSetParent();
    });
    expect(mockOpenModal).toHaveBeenLastCalledWith("issue-set-parent", {
      issueId: "issue-1",
    });

    act(() => {
      result.current.openAddChild();
    });
    expect(mockOpenModal).toHaveBeenLastCalledWith("issue-add-child", {
      issueId: "issue-1",
    });

    act(() => {
      result.current.openAddBlocker();
    });
    expect(mockOpenModal).toHaveBeenLastCalledWith("issue-add-blocker", {
      issueId: "issue-1",
    });

    act(() => {
      result.current.openAddBlocking();
    });
    expect(mockOpenModal).toHaveBeenLastCalledWith("issue-add-blocking", {
      issueId: "issue-1",
    });

    act(() => {
      result.current.openCreateSubIssue();
    });
    expect(mockOpenModal).toHaveBeenLastCalledWith("create-issue", {
      parent_issue_id: "issue-1",
      parent_issue_identifier: "TES-1",
    });

    act(() => {
      result.current.openDeleteConfirm({ onDeletedFallbackPath: "/test/issues" });
    });
    expect(mockOpenModal).toHaveBeenLastCalledWith("issue-delete-confirm", {
      issueId: "issue-1",
      identifier: "TES-1",
      onDeletedFallbackPath: "/test/issues",
    });
  });

  it("openCreateSubIssue seeds the parent's project and assignee so the sub-issue inherits them", () => {
    const parentIssue = {
      ...mockIssue,
      project_id: "project-1",
      assignee_type: "agent",
      assignee_id: "agent-1",
    } as Issue;
    const { result } = renderHook(() => useIssueActions(parentIssue), { wrapper });

    act(() => {
      result.current.openCreateSubIssue();
    });

    expect(mockOpenModal).toHaveBeenLastCalledWith("create-issue", {
      parent_issue_id: "issue-1",
      parent_issue_identifier: "TES-1",
      project_id: "project-1",
      assignee_type: "agent",
      assignee_id: "agent-1",
    });
  });

  it("openCreateSubIssue omits assignee when the parent has none", () => {
    const parentIssue = {
      ...mockIssue,
      project_id: "project-1",
      assignee_type: null,
      assignee_id: null,
    } as Issue;
    const { result } = renderHook(() => useIssueActions(parentIssue), { wrapper });

    act(() => {
      result.current.openCreateSubIssue();
    });

    expect(mockOpenModal).toHaveBeenLastCalledWith("create-issue", {
      parent_issue_id: "issue-1",
      parent_issue_identifier: "TES-1",
      project_id: "project-1",
    });
  });

  it("removeParent clears parent_issue_id and stage in one write, never via the run-confirm modal", () => {
    const childIssue = {
      ...mockIssue,
      parent_issue_id: "parent-1",
      stage: 2,
    } as Issue;
    const { result } = renderHook(() => useIssueActions(childIssue), { wrapper });

    act(() => {
      result.current.removeParent();
    });

    expect(mockUpdateMutate).toHaveBeenCalledWith(
      { id: "issue-1", parent_issue_id: null, stage: null },
      expect.objectContaining({
        onSuccess: expect.any(Function),
        onError: expect.any(Function),
      }),
    );
    // Detaching never routes through the run-confirm modal.
    expect(mockOpenModal).not.toHaveBeenCalled();
  });

  it("removeParent toasts success only from onSuccess — not eagerly, and not on failure", () => {
    const childIssue = {
      ...mockIssue,
      parent_issue_id: "parent-1",
    } as Issue;
    const { result } = renderHook(() => useIssueActions(childIssue), { wrapper });

    act(() => {
      result.current.removeParent();
    });

    // mutate() is fire-and-forget here (mocked), so nothing is confirmed yet.
    expect(toast.success).not.toHaveBeenCalled();
    expect(mockUpdateMutate).toHaveBeenCalledTimes(1);

    const opts = mockUpdateMutate.mock.calls[0]![1] as {
      onSuccess: () => void;
      onError: (err: unknown) => void;
    };

    // A failed write surfaces the error, never a false "removed" confirmation.
    act(() => {
      opts.onError(new Error("forbidden"));
    });
    expect(toast.error).toHaveBeenCalledWith("forbidden");
    expect(toast.success).not.toHaveBeenCalled();

    // Only the server-confirmed success toasts.
    act(() => {
      opts.onSuccess();
    });
    expect(toast.success).toHaveBeenCalledTimes(1);
  });

  it("togglePin calls createPin when not pinned and deletePin when pinned", async () => {
    pinListRef.value = [];
    const { result: r1 } = renderHook(() => useIssueActions(mockIssue), { wrapper });
    await waitFor(() => {
      expect(r1.current.isPinned).toBe(false);
    });
    act(() => {
      r1.current.togglePin();
    });
    expect(mockCreatePinMutate).toHaveBeenCalledWith({
      item_type: "issue",
      item_id: "issue-1",
    });
    expect(mockDeletePinMutate).not.toHaveBeenCalled();

    mockCreatePinMutate.mockReset();
    mockDeletePinMutate.mockReset();
    pinListRef.value = [{ item_type: "issue", item_id: "issue-1" }];
    const { result: r2 } = renderHook(() => useIssueActions(mockIssue), { wrapper });
    await waitFor(() => {
      expect(r2.current.isPinned).toBe(true);
    });
    act(() => {
      r2.current.togglePin();
    });
    expect(mockDeletePinMutate).toHaveBeenCalledWith({
      itemType: "issue",
      itemId: "issue-1",
    });
    expect(mockCreatePinMutate).not.toHaveBeenCalled();
  });

  it("is a safe no-op when issue is null", () => {
    const { result } = renderHook(() => useIssueActions(null), { wrapper });

    act(() => {
      result.current.updateField({ status: "done" });
      result.current.togglePin();
      result.current.openSetParent();
    });

    expect(mockUpdateMutate).not.toHaveBeenCalled();
    expect(mockOpenModal).not.toHaveBeenCalled();
  });

});