Skip to content

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

Go
33.5 KB
Raw Blame
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { AgentTask, Issue, QuickAction } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../../locales/en/common.json";
import enIssues from "../../../locales/en/issues.json";
import { useAssigneePicksStore } from "@multica/core/issues/stores/assignee-picks-store";

const TEST_RESOURCES = { en: { common: enCommon, issues: enIssues } };

// ---------------------------------------------------------------------------
// Mocks — same pattern as the issue-detail test suite.
// ---------------------------------------------------------------------------

const deletionPolicy = vi.hoisted(() => ({ allowed: true, offered: true }));
vi.mock("@multica/core/issues/use-issue-deletion", () => ({
  useIssueDeletion: () => ({ canDelete: () => deletionPolicy.allowed, offersDelete: deletionPolicy.offered }),
}));

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(),
}));

const viewer = vi.hoisted(() => ({ role: "admin" }));
vi.mock("@multica/core/workspace/queries", () => ({
  memberListOptions: () => ({
    queryKey: ["workspaces", "ws-1", "members"],
    queryFn: () =>
      Promise.resolve([
        { user_id: "user-1", name: "Test User", email: "[email protected]", role: viewer.role },
      ]),
  }),
  agentListOptions: () => ({
    queryKey: ["workspaces", "ws-1", "agents"],
    queryFn: () => Promise.resolve([]),
  }),
  squadListOptions: () => ({
    queryKey: ["workspaces", "ws-1", "squads"],
    queryFn: () => Promise.resolve([]),
  }),
}));

const { ACTOR_NAMES } = vi.hoisted(() => ({
  ACTOR_NAMES: { "user-1": "Test User", "agent-1": "Lambda" } as Record<string, string>,
}));

vi.mock("@multica/core/workspace/hooks", () => ({
  useActorName: () => ({ getActorName: (_t: string, id: string) => ACTOR_NAMES[id] ?? "" }),
}));

vi.mock("@multica/core/pins", () => ({
  pinListOptions: () => ({
    queryKey: ["pins", "ws-1", "user-1"],
    queryFn: () => Promise.resolve([]),
  }),
  useCreatePin: () => ({ mutate: vi.fn() }),
  useDeletePin: () => ({ mutate: vi.fn() }),
}));

const { cancelRunMock, updateIssueMock } = vi.hoisted(() => ({
  cancelRunMock: vi.fn(),
  updateIssueMock: vi.fn(),
}));

vi.mock("@multica/core/issues/mutations", () => ({
  useUpdateIssue: () => ({ mutate: updateIssueMock, mutateAsync: updateIssueMock }),
  useCancelIssueRun: () => ({ mutateAsync: cancelRunMock }),
}));

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"),
  };
});

// Module-level flag toggled per-test: desktop implements `openInNewTab`,
// web omits it and the menu has to fall back to a real browser tab.
const { openInNewTabMock, openInDesktopMock, getShareableUrlMock, navState } = vi.hoisted(() => ({
  openInNewTabMock: vi.fn(),
  openInDesktopMock: vi.fn(),
  getShareableUrlMock: vi.fn((p: string) => `https://app.example${p}`),
  navState: { hasOpenInNewTab: true, hasOpenInDesktop: false, pathname: "/test/issues/issue-1", hash: "" },
}));

vi.mock("../../../navigation", () => ({
  useNavigation: () => ({
    push: vi.fn(),
    pathname: navState.pathname,
    searchParams: new URLSearchParams(),
    hash: navState.hash,
    back: vi.fn(),
    replace: vi.fn(),
    ...(navState.hasOpenInNewTab ? { openInNewTab: openInNewTabMock } : {}),
    ...(navState.hasOpenInDesktop ? { openInDesktop: openInDesktopMock } : {}),
    getShareableUrl: getShareableUrlMock,
  }),
}));

const { toastSuccessMock, toastErrorMock } = vi.hoisted(() => ({
  toastSuccessMock: vi.fn(),
  toastErrorMock: vi.fn(),
}));

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

const { apiMocks, copyTextMock, copyTextAndHtmlMock } = vi.hoisted(() => ({
  apiMocks: {
    listTasksByIssue: vi.fn(),
    listIssueWorkflows: vi.fn(),
    listProjects: vi.fn(),
    getAgentTaskSnapshot: vi.fn(),
    listIssueUnread: vi.fn(),
    markIssueRead: vi.fn(),
    markIssueUnread: vi.fn(),
    listQuickActions: vi.fn(),
    runQuickAction: vi.fn(),
  },
  copyTextMock: vi.fn(),
  copyTextAndHtmlMock: vi.fn(),
}));

vi.mock("@multica/core/api", () => ({
  api: apiMocks,
  dispatchReasonCode: (err: unknown) => (err as { reason_code?: string })?.reason_code,
}));

vi.mock("@multica/ui/lib/clipboard", () => ({
  copyText: copyTextMock,
  copyTextAndHtml: copyTextAndHtmlMock,
}));

vi.mock("../../../common/actor-avatar", () => ({
  ActorAvatar: ({ actorId }: any) => <span data-testid="actor">{actorId}</span>,
}));

const platform = vi.hoisted(() => ({ desktop: false }));
vi.mock("../../../platform/local-directory", async (importOriginal) => ({
  ...(await importOriginal<typeof import("../../../platform/local-directory")>()),
  isDesktopShell: () => platform.desktop,
}));

// Import after mocks.
import { memberListOptions } from "@multica/core/workspace/queries";
import { IssueActionsDropdown, useIssuePageMenu } from "../issue-actions-dropdown";
import {
  IssueActionsContextMenu,
  IssueContextMenuProvider,
} from "../issue-actions-context-menu";

const listTasksByIssueMock = apiMocks.listTasksByIssue;

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 wrap(ui: React.ReactNode) {
  const qc = new QueryClient({
    defaultOptions: { queries: { retry: false } },
  });
  return (
    <I18nProvider locale="en" resources={TEST_RESOURCES}>
      <QueryClientProvider client={qc}>{ui}</QueryClientProvider>
    </I18nProvider>
  );
}

beforeEach(() => {
  // Picks persist in a real store; keep one test's picks out of the next's Recent.
  useAssigneePicksStore.setState({ byScope: {} });
  platform.desktop = false;
  deletionPolicy.allowed = true;
  deletionPolicy.offered = true;
  viewer.role = "admin";
  mockOpenModal.mockReset();
  openInNewTabMock.mockReset();
  openInDesktopMock.mockReset();
  getShareableUrlMock.mockClear();
  navState.hasOpenInNewTab = true;
  navState.hasOpenInDesktop = false;
  navState.pathname = "/test/issues/issue-1";
  navState.hash = "";
  copyTextMock.mockReset();
  copyTextMock.mockResolvedValue(true);
  copyTextAndHtmlMock.mockReset();
  copyTextAndHtmlMock.mockResolvedValue(true);
  toastSuccessMock.mockReset();
  toastErrorMock.mockReset();
  apiMocks.listQuickActions.mockReset();
  apiMocks.listQuickActions.mockResolvedValue({ quick_actions: [] });
  apiMocks.runQuickAction.mockReset();
  listTasksByIssueMock.mockReset();
  listTasksByIssueMock.mockResolvedValue([]);
  apiMocks.listIssueWorkflows.mockReset();
  apiMocks.listIssueWorkflows.mockResolvedValue({ workflows: [] });
  apiMocks.listProjects.mockReset();
  apiMocks.listProjects.mockResolvedValue({ projects: [] });
  apiMocks.getAgentTaskSnapshot.mockReset();
  apiMocks.getAgentTaskSnapshot.mockResolvedValue([]);
  apiMocks.listIssueUnread.mockReset();
  apiMocks.listIssueUnread.mockResolvedValue([]);
  apiMocks.markIssueRead.mockReset();
  apiMocks.markIssueRead.mockResolvedValue({ unread: false });
  apiMocks.markIssueUnread.mockReset();
  apiMocks.markIssueUnread.mockResolvedValue({ unread: true });
  cancelRunMock.mockReset();
  cancelRunMock.mockResolvedValue(undefined);
  updateIssueMock.mockReset().mockResolvedValue(mockIssue);
});

describe("IssueActionsDropdown", () => {
  it("renders the top-level items when the trigger is clicked", async () => {
    render(
      wrap(
        <IssueActionsDropdown
          issue={mockIssue}
          trigger={<button data-testid="trigger">Menu</button>}
        />,
      ),
    );

    fireEvent.click(screen.getByTestId("trigger"));

    // Base UI portals the popup; role=menu lands on the popup wrapper.
    expect(await screen.findByText("Status")).toBeInTheDocument();
    expect(screen.getByText("Priority")).toBeInTheDocument();
    expect(screen.getByText("Assignee")).toBeInTheDocument();
    expect(screen.getByText("Due date")).toBeInTheDocument();
    expect(screen.getByText("Rename issue")).toBeInTheDocument();
    expect(screen.getByText("Open in new tab")).toBeInTheDocument();
    expect(screen.getByText("Copy link")).toBeInTheDocument();
    expect(screen.getByText("Copy link with title")).toBeInTheDocument();
    expect(screen.getByText("Create sub-issue")).toBeInTheDocument();
    expect(screen.getByText("Relations")).toBeInTheDocument();
    expect(screen.getByText("Delete issue")).toBeInTheDocument();
    // Linking to existing issues stays inside the "Relations" submenu.
    expect(screen.queryByText("Set parent issue...")).not.toBeInTheDocument();
    expect(screen.queryByText("Add sub-issue...")).not.toBeInTheDocument();
  });

  it("copies the identifier and title as a rich link", async () => {
    render(
      wrap(
        <IssueActionsDropdown
          issue={mockIssue}
          trigger={<button data-testid="trigger">Menu</button>}
        />,
      ),
    );

    fireEvent.click(screen.getByTestId("trigger"));
    fireEvent.click(await screen.findByText("Copy link with title"));

    expect(copyTextAndHtmlMock).toHaveBeenCalledWith(
      "[TES-1 Example](https://app.example/test/issues/TES-1)",
      '<a href="https://app.example/test/issues/TES-1">TES-1 Example</a>',
    );
  });

  it("lists Create sub-issue directly below Rename issue", async () => {
    render(
      wrap(
        <IssueActionsDropdown
          issue={mockIssue}
          trigger={<button data-testid="trigger">Menu</button>}
        />,
      ),
    );

    fireEvent.click(screen.getByTestId("trigger"));
    await screen.findByText("Rename issue");

    const labels = screen
      .getAllByRole("menuitem")
      .map((item) => item.textContent?.trim());
    // Status trails its current value.
    expect(labels.slice(0, 3)).toEqual(["Rename issue", "Create sub-issue", "StatusTodo"]);
  });

  it("opens Assignee as a submenu holding the shared assignee picker", async () => {
    render(
      wrap(
        <IssueActionsDropdown
          issue={mockIssue}
          trigger={<button data-testid="trigger">Menu</button>}
        />,
      ),
    );

    fireEvent.click(screen.getByTestId("trigger"));
    fireEvent.click(await screen.findByText("Assignee"));

    // The search box and the "Members" group come from the shared assignee
    // picker, so the submenu offers what every other assignee entry point does.
    expect(
      await screen.findByPlaceholderText("Assign to..."),
    ).toBeInTheDocument();
    expect(await screen.findByText("Members")).toBeInTheDocument();
    fireEvent.click(await screen.findByText("Test User"));

    expect(updateIssueMock).toHaveBeenCalledWith(
      { id: "issue-1", assignee_type: "member", assignee_id: "user-1" },
      expect.anything(),
    );
    await waitFor(() => expect(screen.queryByText("Status")).not.toBeInTheDocument());
  });

  it("shows 'Remove parent issue' in the Relations submenu only when the issue has a parent", async () => {
    const childIssue = { ...mockIssue, parent_issue_id: "parent-1" } as Issue;
    render(
      wrap(
        <IssueActionsDropdown
          issue={childIssue}
          trigger={<button data-testid="trigger">Menu</button>}
        />,
      ),
    );

    fireEvent.click(screen.getByTestId("trigger"));
    fireEvent.click(await screen.findByText("Relations"));

    expect(await screen.findByText("Remove parent issue")).toBeInTheDocument();
  });

  it("hides 'Remove parent issue' when the issue has no parent", async () => {
    render(
      wrap(
        <IssueActionsDropdown
          issue={mockIssue}
          trigger={<button data-testid="trigger">Menu</button>}
        />,
      ),
    );

    fireEvent.click(screen.getByTestId("trigger"));
    fireEvent.click(await screen.findByText("Relations"));

    // The sibling "Set parent issue..." proves the submenu opened.
    expect(await screen.findByText("Set parent issue...")).toBeInTheDocument();
    expect(screen.queryByText("Remove parent issue")).not.toBeInTheDocument();
  });

  it("disables Delete issue when the user cannot delete the issue", async () => {
    deletionPolicy.allowed = false;
    render(wrap(<IssueActionsDropdown issue={mockIssue} trigger={<button data-testid="trigger">Menu</button>} />));
    fireEvent.click(screen.getByTestId("trigger"));
    const item = await screen.findByText("Delete issue");
    expect(item.closest('[role="menuitem"]')).toHaveAttribute("aria-disabled", "true");
    fireEvent.click(item);
    expect(mockOpenModal).not.toHaveBeenCalled();
  });

  it("leaves Delete issue out for a viewer who can delete nothing (a guest)", async () => {
    deletionPolicy.allowed = false;
    deletionPolicy.offered = false;
    render(wrap(<IssueActionsDropdown issue={mockIssue} trigger={<button data-testid="trigger">Menu</button>} />));
    fireEvent.click(screen.getByTestId("trigger"));
    expect(await screen.findByText("Copy link")).toBeInTheDocument();
    expect(screen.queryByText("Delete issue")).not.toBeInTheDocument();
  });

  it("offers a guest only the entries the server lets it use, without asking for runs or quick actions (MUL-9883)", async () => {
    viewer.role = "guest";
    deletionPolicy.allowed = false;
    deletionPolicy.offered = false;
    apiMocks.listQuickActions.mockResolvedValue({
      quick_actions: [{ id: "qa-1", name: "Triage", status: "active" }],
    });
    listTasksByIssueMock.mockResolvedValue([
      { id: "task-1", status: "completed", work_dir: "/tmp/work", created_at: "2026-01-01T00:00:00Z" },
    ]);
    const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
    // The shell has the member list cached before any menu opens.
    await queryClient.fetchQuery(memberListOptions("ws-1"));
    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={queryClient}>
          <IssueActionsDropdown issue={mockIssue} trigger={<button data-testid="trigger">Menu</button>} />
        </QueryClientProvider>
      </I18nProvider>,
    );
    fireEvent.click(screen.getByTestId("trigger"));
    await screen.findByText("Copy link");

    expect(screen.getAllByRole("menuitem").map((item) => item.textContent?.trim())).toEqual([
      "Open in new tab",
      "Pin to sidebar",
      "Copy link",
      "Copy link with title",
      "Copy issue ID",
    ]);
    expect(listTasksByIssueMock).not.toHaveBeenCalled();
    expect(apiMocks.listQuickActions).not.toHaveBeenCalled();
  });

  it("clicking Delete issue opens the delete-confirm modal", async () => {
    render(
      wrap(
        <IssueActionsDropdown
          issue={mockIssue}
          trigger={<button data-testid="trigger">Menu</button>}
          onDeletedFallbackPath="/test/issues"
        />,
      ),
    );

    fireEvent.click(screen.getByTestId("trigger"));
    const del = await screen.findByText("Delete issue");
    fireEvent.click(del);

    expect(mockOpenModal).toHaveBeenCalledWith("issue-delete-confirm", {
      issueId: "issue-1",
      identifier: "TES-1",
      onDeletedFallbackPath: "/test/issues",
    });
  });

  it("clicking Create sub-issue opens the create modal parented to this issue", async () => {
    render(
      wrap(
        <IssueActionsDropdown
          issue={mockIssue}
          trigger={<button data-testid="trigger">Menu</button>}
        />,
      ),
    );

    fireEvent.click(screen.getByTestId("trigger"));
    fireEvent.click(await screen.findByText("Create sub-issue"));

    expect(mockOpenModal).toHaveBeenCalledWith(
      "create-issue",
      expect.objectContaining({
        parent_issue_id: "issue-1",
        parent_issue_identifier: "TES-1",
      }),
    );
  });

  it("clicking Rename issue opens the rename modal with the current title", async () => {
    render(
      wrap(
        <IssueActionsDropdown
          issue={mockIssue}
          trigger={<button data-testid="trigger">Menu</button>}
        />,
      ),
    );

    fireEvent.click(screen.getByTestId("trigger"));
    fireEvent.click(await screen.findByText("Rename issue"));

    expect(mockOpenModal).toHaveBeenCalledWith("issue-rename", {
      issueId: "issue-1",
      identifier: "TES-1",
      title: "Example",
    });
  });

  it("copies the durable local project path for a worktree task", async () => {
    listTasksByIssueMock.mockResolvedValue([
      {
        status: "completed",
        created_at: "2026-08-18T10:00:00Z",
        work_dir: "/managed/task/worktree",
        durable_work_dir: "/Users/dev/project",
        branch_name: "agent/j/abc12345",
      } as AgentTask,
    ]);

    render(
      wrap(
        <IssueActionsDropdown
          issue={mockIssue}
          trigger={<button data-testid="trigger">Menu</button>}
        />,
      ),
    );

    fireEvent.click(screen.getByTestId("trigger"));
    fireEvent.click(await screen.findByText("Copy project directory path"));

    await waitFor(() => {
      expect(copyTextMock).toHaveBeenCalledWith("/Users/dev/project");
      expect(toastSuccessMock).toHaveBeenCalledWith(
        "Project directory path copied — work is on agent/j/abc12345",
      );
    });
  });

  it("keeps a live task on its actual workdir", async () => {
    listTasksByIssueMock.mockResolvedValue([
      {
        status: "running",
        created_at: "2026-08-18T10:00:00Z",
        work_dir: "/managed/task/worktree",
        durable_work_dir: "/Users/dev/project",
      } as AgentTask,
    ]);

    render(
      wrap(
        <IssueActionsDropdown
          issue={mockIssue}
          trigger={<button data-testid="trigger">Menu</button>}
        />,
      ),
    );

    fireEvent.click(screen.getByTestId("trigger"));
    await waitFor(() => {
      expect(listTasksByIssueMock).toHaveBeenCalledWith("issue-1", false, { view: "timeline" });
    });
    fireEvent.click(await screen.findByText("Copy local working directory path"));

    await waitFor(() => {
      expect(copyTextMock).toHaveBeenCalledWith("/managed/task/worktree");
    });
  });
});

describe("Open in new tab", () => {
  async function openMenuAndClickOpenInNewTab() {
    render(
      wrap(
        <IssueActionsDropdown
          issue={mockIssue}
          trigger={<button data-testid="trigger">Menu</button>}
        />,
      ),
    );
    fireEvent.click(screen.getByTestId("trigger"));
    fireEvent.click(await screen.findByText("Open in new tab"));
  }

  it("uses the desktop adapter and focuses the new tab", async () => {
    const windowOpen = vi
      .spyOn(window, "open")
      .mockReturnValue(null as unknown as Window);

    await openMenuAndClickOpenInNewTab();

    // `activate: true` — an explicit CTA moves the user into the new context,
    // unlike modifier-click, which stashes a background tab. The path carries
    // the identifier, matching copyLink, so the opened tab is already on the
    // canonical URL instead of being rewritten off the UUID after it lands.
    expect(openInNewTabMock).toHaveBeenCalledWith(
      "/test/issues/TES-1",
      "TES-1",
      { activate: true },
    );
    expect(windowOpen).not.toHaveBeenCalled();

    windowOpen.mockRestore();
  });

  it("falls back to a browser tab when the adapter is absent (web)", async () => {
    navState.hasOpenInNewTab = false;
    const windowOpen = vi
      .spyOn(window, "open")
      .mockReturnValue(null as unknown as Window);

    await openMenuAndClickOpenInNewTab();

    expect(openInNewTabMock).not.toHaveBeenCalled();
    expect(getShareableUrlMock).toHaveBeenCalledWith("/test/issues/TES-1");
    expect(windowOpen).toHaveBeenCalledWith(
      "https://app.example/test/issues/TES-1",
      "_blank",
      "noopener,noreferrer",
    );

    windowOpen.mockRestore();
  });
});

describe("Open in Desktop", () => {
  async function openMenu() {
    render(wrap(<IssueActionsDropdown issue={mockIssue} trigger={<button data-testid="trigger">Menu</button>} />));
    fireEvent.click(screen.getByTestId("trigger"));
    await screen.findByText("Open in new tab");
  }

  it("appears directly below Open in new tab on web and hands off the current comment", async () => {
    navState.hasOpenInDesktop = true;
    navState.pathname = "/test/issues/TES-1";
    navState.hash = "#comment-c1";
    await openMenu();
    const labels = screen.getAllByRole("menuitem").map((item) => item.textContent);
    expect(labels[labels.indexOf("Open in new tab") + 1]).toBe("Open in Desktop");
    fireEvent.click(screen.getByText("Open in Desktop"));
    expect(openInDesktopMock).toHaveBeenCalledWith("/test/issues/TES-1#comment-c1");
  });

  it("opens the selected issue without copying another issue's comment anchor", async () => {
    navState.hasOpenInDesktop = true;
    navState.pathname = "/test/issues/TES-99";
    navState.hash = "#comment-other";
    await openMenu();
    fireEvent.click(screen.getByText("Open in Desktop"));
    expect(openInDesktopMock).toHaveBeenCalledWith("/test/issues/TES-1");
  });

  it("is hidden in the desktop app", async () => {
    await openMenu();
    expect(screen.queryByText("Open in Desktop")).not.toBeInTheDocument();
  });
});

describe("IssueActionsContextMenu", () => {
  it("renders the menu when the wrapped element receives a contextmenu event", async () => {
    render(
      wrap(
        <IssueContextMenuProvider>
          <IssueActionsContextMenu issue={mockIssue}>
            <div data-testid="row">Row</div>
          </IssueActionsContextMenu>
        </IssueContextMenuProvider>,
      ),
    );

    fireEvent.contextMenu(screen.getByTestId("row"));

    expect(await screen.findByText("Status")).toBeInTheDocument();
    // The right-click surface is what list rows, board cards, gantt bars and
    // sub-issue rows all share, so this one assertion covers them together.
    expect(screen.getByText("Rename issue")).toBeInTheDocument();
    expect(screen.getByText("Open in new tab")).toBeInTheDocument();
    expect(screen.getByText("Delete issue")).toBeInTheDocument();
  });

  it("keeps typed keys in the assignee search box and assigns the match on Enter", async () => {
    const user = userEvent.setup();
    render(
      wrap(
        <IssueContextMenuProvider>
          <IssueActionsContextMenu issue={mockIssue}>
            <div data-testid="row">Row</div>
          </IssueActionsContextMenu>
        </IssueContextMenuProvider>,
      ),
    );

    fireEvent.contextMenu(screen.getByTestId("row"));
    await user.click(await screen.findByText("Assignee"));
    const search = await screen.findByPlaceholderText("Assign to...");
    await screen.findByText("Test User");
    await waitFor(() => expect(search).toHaveFocus());

    // The menu's typeahead would otherwise swallow these keys.
    await user.keyboard("test");
    expect(search).toHaveValue("test");
    await user.keyboard("{Enter}");

    expect(updateIssueMock).toHaveBeenCalledWith(
      { id: "issue-1", assignee_type: "member", assignee_id: "user-1" },
      expect.anything(),
    );
    await waitFor(() => expect(screen.queryByText("Rename issue")).not.toBeInTheDocument());
  });
});

describe("Quick actions (MUL-9093)", () => {
  const quickAction = (overrides: Partial<QuickAction>): QuickAction => ({
    id: "qa-1",
    workspace_id: "ws-1",
    name: "Review",
    description: "",
    assignee_type: "agent",
    assignee_id: "agent-1",
    prompt: "Review this",
    visibility: "public",
    status: "active",
    last_used_at: null,
    use_count: 0,
    created_by_id: "user-1",
    created_at: "2026-01-01T00:00:00Z",
    updated_at: "2026-01-01T00:00:00Z",
    target_name: "Lambda",
    target_public: true,
    target_missing: false,
    ...overrides,
  });

  function openContextMenu() {
    render(
      wrap(
        <IssueContextMenuProvider>
          <IssueActionsContextMenu issue={mockIssue}>
            <div data-testid="row">Row</div>
          </IssueActionsContextMenu>
        </IssueContextMenuProvider>,
      ),
    );
    fireEvent.contextMenu(screen.getByTestId("row"));
  }

  beforeEach(() => {
    apiMocks.listQuickActions.mockResolvedValue({
      quick_actions: [
        quickAction({}),
        quickAction({ id: "qa-2", name: "Old triage", status: "archived" }),
      ],
    });
  });

  it("lists the workspace's active quick actions below Create sub-issue", async () => {
    openContextMenu();
    await screen.findByText("Quick actions");
    const labels = screen.getAllByRole("menuitem").map((item) => item.textContent?.trim());
    expect(labels.slice(0, 3)).toEqual(["Rename issue", "Create sub-issue", "Quick actions"]);

    fireEvent.click(screen.getByText("Quick actions"));
    expect(await screen.findByText("Review")).toBeInTheDocument();
    expect(screen.queryByText("Old triage")).not.toBeInTheDocument();
  });

  it("runs the picked action on this issue and reports the outcome", async () => {
    apiMocks.runQuickAction.mockResolvedValue({
      id: "c-1",
      trigger_outcomes: [{ status: "queued" }],
    });
    openContextMenu();
    fireEvent.click(await screen.findByText("Quick actions"));
    fireEvent.click(await screen.findByText("Review"));

    await waitFor(() => expect(apiMocks.runQuickAction).toHaveBeenCalledWith("issue-1", "qa-1"));
    await waitFor(() => expect(toastSuccessMock).toHaveBeenCalledWith("Lambda started working"));
  });

  it("explains a permission refusal", async () => {
    apiMocks.runQuickAction.mockRejectedValue({ reason_code: "invocation_not_allowed" });
    openContextMenu();
    fireEvent.click(await screen.findByText("Quick actions"));
    fireEvent.click(await screen.findByText("Review"));

    await waitFor(() =>
      expect(toastErrorMock).toHaveBeenCalledWith(expect.stringContaining("“Review” runs as an agent")),
    );
  });

  function IssuePageHarness() {
    const pageMenu = useIssuePageMenu();
    return (
      <div>
        <IssueActionsDropdown
          issue={mockIssue}
          rowMenu={pageMenu.rowMenu}
          trigger={<button data-testid="trigger">Menu</button>}
        />
        <div data-testid="page-body" onContextMenu={pageMenu.onContextMenu}>
          <p data-testid="blank">Body</p>
          <a href="https://example.com" data-testid="link">Link</a>
        </div>
      </div>
    );
  }

  describe("right-click in the issue page body", () => {
    it("opens the issue menu, quick actions included, on Desktop", async () => {
      platform.desktop = true;
      render(wrap(<IssuePageHarness />));
      // fireEvent returns false once a handler called preventDefault.
      expect(fireEvent.contextMenu(screen.getByTestId("blank"))).toBe(false);

      expect(await screen.findByText("Rename issue")).toBeInTheDocument();
      fireEvent.click(await screen.findByText("Quick actions"));
      expect(await screen.findByText("Review")).toBeInTheDocument();
    });

    it("leaves a link's right-click to the link's own menu on Desktop", async () => {
      platform.desktop = true;
      render(wrap(<IssuePageHarness />));
      expect(fireEvent.contextMenu(screen.getByTestId("link"))).toBe(true);

      await waitFor(() => expect(apiMocks.listQuickActions).not.toHaveBeenCalled());
      expect(screen.queryByText("Rename issue")).not.toBeInTheDocument();
    });

    it("keeps the browser's own menu on web, with Quick actions still under the ⋯ button", async () => {
      render(wrap(<IssuePageHarness />));
      expect(fireEvent.contextMenu(screen.getByTestId("blank"))).toBe(true);
      await waitFor(() => expect(apiMocks.listQuickActions).not.toHaveBeenCalled());
      expect(screen.queryByText("Rename issue")).not.toBeInTheDocument();

      fireEvent.click(screen.getByTestId("trigger"));
      fireEvent.click(await screen.findByText("Quick actions"));
      expect(await screen.findByText("Review")).toBeInTheDocument();
    });
  });

  it("is absent when the workspace has no active quick actions", async () => {
    apiMocks.listQuickActions.mockResolvedValue({
      quick_actions: [quickAction({ status: "archived" })],
    });
    openContextMenu();
    await screen.findByText("Rename issue");
    await waitFor(() => expect(apiMocks.listQuickActions).toHaveBeenCalled());
    expect(screen.queryByText("Quick actions")).not.toBeInTheDocument();
  });
});

describe("Sidebar variant (MUL-8425)", () => {
  function openSidebarMenu(issue: Issue = mockIssue) {
    render(
      wrap(
        <IssueContextMenuProvider variant="sidebar">
          <IssueActionsContextMenu issue={issue}>
            <div data-testid="row">Row</div>
          </IssueActionsContextMenu>
        </IssueContextMenuProvider>,
      ),
    );
    fireEvent.contextMenu(screen.getByTestId("row"));
  }

  const menuLabels = () =>
    screen.getAllByRole("menuitem").map((item) => item.textContent?.trim());

  it("names the issue and keeps the triage and navigation entries, with current values", async () => {
    openSidebarMenu({ ...mockIssue, assignee_type: "member", assignee_id: "user-1" } as Issue);

    expect(await screen.findByText("TES-1")).toBeInTheDocument();
    expect(screen.getByText("Example")).toBeInTheDocument();
    expect(menuLabels()).toEqual([
      "StatusTodo",
      "PriorityMedium",
      "AssigneeTest User",
      "Open in new tab",
      "Pin to sidebar",
      "Mark as unread",
      "Copy link",
      "Copy link with title",
      "Copy issue ID",
    ]);
    expect(screen.getByTestId("row")).toHaveAttribute("data-popup-open");
    // No workdir entry, so the menu has no reason to fetch the task list.
    expect(listTasksByIssueMock).not.toHaveBeenCalled();
  });

  it("marks an unread issue as read", async () => {
    apiMocks.listIssueUnread.mockResolvedValue([
      { issue_id: "issue-1", outcome: "completed", agent_id: "agent-1", created_at: "2026-01-01T00:00:00Z" },
    ]);
    openSidebarMenu();
    fireEvent.click(await screen.findByText("Mark as read"));

    await waitFor(() => expect(apiMocks.markIssueRead).toHaveBeenCalledWith("issue-1"));
  });

  it("marks a read issue as unread", async () => {
    openSidebarMenu();
    fireEvent.click(await screen.findByText("Mark as unread"));

    await waitFor(() => expect(apiMocks.markIssueUnread).toHaveBeenCalledWith("issue-1"));
  });

  it("shows Unassigned when nobody owns the issue", async () => {
    openSidebarMenu();
    expect(await screen.findByText("Unassigned")).toBeInTheDocument();
  });

  it("copies the identifier", async () => {
    openSidebarMenu();
    fireEvent.click(await screen.findByText("Copy issue ID"));

    await waitFor(() => {
      expect(copyTextMock).toHaveBeenCalledWith("TES-1");
      expect(toastSuccessMock).toHaveBeenCalledWith("Copied TES-1");
    });
  });

  it("stops a running agent's run after confirming", async () => {
    apiMocks.getAgentTaskSnapshot.mockResolvedValue([
      { id: "task-1", issue_id: "issue-1", agent_id: "agent-1", status: "running" },
      { id: "task-2", issue_id: "issue-2", agent_id: "agent-1", status: "running" },
    ] as AgentTask[]);
    openSidebarMenu();

    fireEvent.click(await screen.findByText("Stop Lambda’s run"));
    expect(cancelRunMock).not.toHaveBeenCalled();
    fireEvent.click(await screen.findByRole("button", { name: "Stop run" }));

    expect(cancelRunMock).toHaveBeenCalledWith("task-1");
  });
});

describe("Status in a workflow project (MUL-7420)", () => {
  const workflowIssue = { ...mockIssue, project_id: "proj-1" } as Issue;

  beforeEach(() => {
    apiMocks.listProjects.mockResolvedValue({
      projects: [{ id: "proj-1", title: "App", workflow_id: "wf-1", lead_type: null, lead_id: null }],
    });
    apiMocks.listIssueWorkflows.mockResolvedValue({
      workflows: [
        {
          id: "wf-1",
          name: "Delivery",
          description: "",
          is_default: false,
          project_ids: ["proj-1"],
          steps: [
            { status_key: "todo", handler: { type: "none" }, instructions: "" },
            { status_key: "in_progress", handler: { type: "agent", id: "agent-1" }, instructions: "" },
            { status_key: "done", handler: { type: "none" }, instructions: "" },
          ],
        },
      ],
    });
  });

  it("offers only the workflow's statuses and confirms a handoff before applying it", async () => {
    render(
      wrap(
        <IssueActionsDropdown
          issue={workflowIssue}
          trigger={<button data-testid="trigger">Menu</button>}
        />,
      ),
    );

    fireEvent.click(screen.getByTestId("trigger"));
    fireEvent.click(await screen.findByText("Status"));

    await waitFor(() => expect(screen.queryByText("Backlog")).not.toBeInTheDocument());
    expect(screen.queryByText("In Review")).not.toBeInTheDocument();
    fireEvent.click(await screen.findByText("In Progress"));

    expect(mockOpenModal).toHaveBeenCalledWith("issue-workflow-handoff", {
      issueId: "issue-1",
      identifier: "TES-1",
      status: "in_progress",
    });
  });
});