Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

13.9 KB
Raw Blame
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";
import { FindingsTable } from "../../src/dead-code/findings-table.js";
import type { DeadCodeFinding } from "@repowise-dev/types/dead-code";

// jsdom has no layout engine → stub ResizeObserver for the Radix primitives.
class RO {
  observe() {}
  unobserve() {}
  disconnect() {}
}
vi.stubGlobal("ResizeObserver", RO);

const toastError = vi.fn();
vi.mock("sonner", () => ({
  toast: {
    success: vi.fn(),
    error: (...a: unknown[]) => toastError(...a),
    warning: vi.fn(),
  },
}));

function finding(over: Partial<DeadCodeFinding> & { id: string }): DeadCodeFinding {
  return {
    kind: "unreachable_file",
    file_path: `src/${over.id}.ts`,
    symbol_name: null,
    symbol_kind: null,
    confidence: 0.9,
    reason: "No importers",
    lines: 10,
    safe_to_delete: true,
    risk_factors: [],
    primary_owner: "alice",
    status: "open",
    note: null,
    ...over,
  };
}

const noopPatch = vi.fn(async (id: string) => finding({ id, status: "resolved" }));

const noopBulk = vi.fn(async (ids: string[]) => ids);

function renderTable(findings: DeadCodeFinding[], props: Record<string, unknown> = {}) {
  return render(
    <FindingsTable
      findings={findings}
      onPatch={noopPatch}
      onBulkResolve={noopBulk}
      {...props}
    />,
  );
}

/**
 * `stacked="sm"` renders the table and the mobile card list side by side and
 * lets CSS pick one. jsdom applies no CSS, so both are present and every row
 * control matches twice; scope row-level queries to the table.
 */
function inTable() {
  return within(screen.getByRole("table"));
}

beforeEach(() => {
  toastError.mockClear();
  noopPatch.mockClear();
});

describe("FindingsTable kind bucketing", () => {
  it("gives every kind present a tab, including ones with no hardcoded label", () => {
    renderTable([
      finding({ id: "a", kind: "unreachable_file" }),
      finding({ id: "b", kind: "unused_internal" }),
      finding({ id: "c", kind: "some_future_kind" }),
    ]);

    // The regression this guards: a fixed three-kind allowlist silently dropped
    // unused_internal findings that every other surface was counting.
    expect(screen.getByRole("tab", { name: /Unreachable files/ })).toBeInTheDocument();
    expect(screen.getByRole("tab", { name: /Unused internals/ })).toBeInTheDocument();
    expect(screen.getByRole("tab", { name: /Some future kind/ })).toBeInTheDocument();
  });

  it("shows no tab for a kind that is absent from the data", () => {
    renderTable([finding({ id: "a", kind: "unreachable_file" })]);

    expect(screen.queryByRole("tab", { name: /Zombie packages/ })).not.toBeInTheDocument();
  });

  it("renders an empty state rather than tabs when there are no findings", () => {
    renderTable([]);

    expect(screen.getByText("No open findings")).toBeInTheDocument();
    expect(screen.queryByRole("tab")).not.toBeInTheDocument();
  });

  it("words an empty review slice for its status", () => {
    renderTable([], { status: "acknowledged" });

    expect(screen.getByText("No acknowledged findings")).toBeInTheDocument();
  });

  it("tab counts follow the confidence filter while the tab itself stays put", async () => {
    renderTable([
      finding({ id: "a", kind: "unreachable_file", confidence: 1 }),
      finding({ id: "b", kind: "unreachable_file", confidence: 0.45 }),
    ]);

    expect(screen.getByRole("tab", { name: /Unreachable files 2/ })).toBeInTheDocument();

    fireEvent.click(screen.getByRole("radio", { name: "High only" }));

    // The count drops, but the tab does not disappear from under the pointer.
    await waitFor(() =>
      expect(screen.getByRole("tab", { name: /Unreachable files 1/ })).toBeInTheDocument(),
    );
  });
});

describe("FindingsTable selection", () => {
  it("select-all covers the visible rows and not the filtered-out ones", async () => {
    const onBulkResolve = vi.fn(async (ids: string[]) => ids);
    renderTable(
      [
        finding({ id: "a", confidence: 1 }),
        finding({ id: "hidden", confidence: 0.45 }),
        finding({ id: "b", confidence: 1 }),
      ],
      { onBulkResolve },
    );

    // Push the low-confidence row out of view first, then select all.
    fireEvent.click(screen.getByRole("radio", { name: "High only" }));
    await waitFor(() =>
      expect(screen.queryByLabelText("Select finding src/hidden.ts")).not.toBeInTheDocument(),
    );

    fireEvent.click(screen.getByLabelText("Select all findings"));
    expect(screen.getByRole("button", { name: "Resolve 2 selected" })).toBeInTheDocument();

    fireEvent.click(screen.getByRole("button", { name: "Resolve 2 selected" }));
    fireEvent.click(await screen.findByRole("button", { name: "Resolve all" }));

    await waitFor(() => expect(onBulkResolve).toHaveBeenCalledWith(["a", "b"]));
  });

  it("drops selected rows the confidence filter has hidden", async () => {
    const onBulkResolve = vi.fn(async (ids: string[]) => ids);
    renderTable(
      [finding({ id: "a", confidence: 1 }), finding({ id: "b", confidence: 0.45 })],
      { onBulkResolve },
    );

    fireEvent.click(screen.getByLabelText("Select all findings"));
    expect(screen.getByRole("button", { name: "Resolve 2 selected" })).toBeInTheDocument();

    // Narrow to high confidence: the second finding leaves the table, so it
    // must leave the selection too, otherwise "Resolve N selected" resolves
    // rows the user can no longer see.
    fireEvent.click(screen.getByRole("radio", { name: "High only" }));

    await waitFor(() =>
      expect(screen.getByRole("button", { name: "Resolve 1 selected" })).toBeInTheDocument(),
    );

    fireEvent.click(screen.getByRole("button", { name: "Resolve 1 selected" }));
    fireEvent.click(await screen.findByRole("button", { name: "Resolve all" }));

    await waitFor(() => expect(onBulkResolve).toHaveBeenCalledWith(["a"]));
  });

  it("clears selection when switching tabs", () => {
    renderTable([
      finding({ id: "a", kind: "unreachable_file" }),
      finding({ id: "b", kind: "unused_export" }),
    ]);

    fireEvent.click(screen.getByLabelText("Select all findings"));
    expect(screen.getByRole("button", { name: "Resolve 1 selected" })).toBeInTheDocument();

    // Radix activates a tab on mousedown, not click.
    fireEvent.mouseDown(screen.getByRole("tab", { name: /Unused exports/ }));

    expect(screen.queryByRole("button", { name: /Resolve \d+ selected/ })).not.toBeInTheDocument();
  });
});

describe("FindingsTable sort and search", () => {
  /** File paths in render order, read off the real table (not the card list). */
  function paths() {
    return inTable()
      .getAllByRole("row")
      .slice(1)
      .map((r) => r.querySelector("[data-path]")?.getAttribute("data-path"))
      .filter(Boolean);
  }

  it("defaults to the server's confidence-first order", () => {
    renderTable([
      finding({ id: "a", file_path: "src/a.ts", confidence: 0.5 }),
      finding({ id: "b", file_path: "src/b.ts", confidence: 0.9 }),
    ]);

    expect(paths()).toEqual(["src/b.ts", "src/a.ts"]);
  });

  it("sorts by a column and flips direction on a second click", () => {
    renderTable([
      finding({ id: "a", file_path: "src/a.ts", lines: 5 }),
      finding({ id: "b", file_path: "src/b.ts", lines: 90 }),
    ]);

    const header = inTable().getByRole("button", { name: /Lines/ });
    fireEvent.click(header);
    expect(paths()).toEqual(["src/b.ts", "src/a.ts"]);

    fireEvent.click(header);
    expect(paths()).toEqual(["src/a.ts", "src/b.ts"]);
  });

  it("searches across path, symbol, owner and reason", () => {
    renderTable([
      finding({ id: "a", file_path: "src/keep.ts", reason: "No importers" }),
      finding({ id: "b", file_path: "src/other.ts", reason: "Only self-references" }),
    ]);

    fireEvent.change(screen.getByLabelText("Search findings"), {
      target: { value: "self-ref" },
    });

    expect(paths()).toEqual(["src/other.ts"]);
  });

  it("offers a way back when the filters have emptied the table", () => {
    renderTable([finding({ id: "a", file_path: "src/a.ts" })]);

    fireEvent.change(screen.getByLabelText("Search findings"), {
      target: { value: "nothing matches this" },
    });
    expect(screen.queryByRole("table")).not.toBeInTheDocument();
    expect(screen.getByText("1 finding hidden by the current filters")).toBeInTheDocument();

    // Without this the user is left staring at an empty state with no hint
    // that their own filter, not the repository, is why.
    fireEvent.click(screen.getByRole("button", { name: "Reset filters" }));
    expect(paths()).toEqual(["src/a.ts"]);
  });
});

describe("FindingsTable row affordances", () => {
  it("links the file path and opens the row through the host router", () => {
    const onNavigate = vi.fn();
    renderTable([finding({ id: "a" })], {
      fileHref: (p: string) => `/repos/repo-1/files/${p}`,
      onNavigate,
    });

    const link = inTable().getByRole("link", { name: "src/a.ts" });
    expect(link).toHaveAttribute("href", "/repos/repo-1/files/src/a.ts");

    fireEvent.click(inTable().getByRole("row", { name: /src\/a\.ts/ }));
    expect(onNavigate).toHaveBeenCalledWith("/repos/repo-1/files/src/a.ts");

    // A plain click on the name routes through the host too, rather than
    // falling through to a full page load inside a client-routed row.
    onNavigate.mockClear();
    fireEvent.click(link, { button: 0 });
    expect(onNavigate).toHaveBeenCalledWith("/repos/repo-1/files/src/a.ts");
  });

  it("does not navigate when the checkbox is clicked", () => {
    const onNavigate = vi.fn();
    renderTable([finding({ id: "a" })], { fileHref: (p: string) => `/f/${p}`, onNavigate });

    fireEvent.click(inTable().getByLabelText("Select finding src/a.ts"));

    expect(onNavigate).not.toHaveBeenCalled();
  });

  it("shows the detector's reason, which previously only the AI prompt saw", () => {
    renderTable([finding({ id: "a", reason: "No importers in the dependency graph" })]);

    expect(inTable().getByText("No importers in the dependency graph")).toBeInTheDocument();
  });

  it("leads each row with the agent prompt and offers one for the filtered rows or the selection", () => {
    const onGeneratePrompt = vi.fn();
    renderTable([finding({ id: "a" }), finding({ id: "b" })], { onGeneratePrompt });

    // Per-row: the prompt leads the row, named for the file it is about.
    fireEvent.click(inTable().getByRole("button", { name: "Copy prompt: src/a.ts" }));
    expect(onGeneratePrompt).toHaveBeenCalledWith(["a"]);

    // Header: every row the filters show, until there is a selection.
    fireEvent.click(screen.getByRole("button", { name: "Copy prompt for these 2" }));
    expect(onGeneratePrompt).toHaveBeenLastCalledWith(["a", "b"]);

    fireEvent.click(inTable().getByLabelText("Select finding src/a.ts"));
    fireEvent.click(screen.getByRole("button", { name: "Copy prompt for 1 selected" }));
    expect(onGeneratePrompt).toHaveBeenLastCalledWith(["a"]);
  });

  it("renders the graph action from the host's route, and hides it without one", () => {
    const openMenu = () =>
      fireEvent.click(inTable().getByRole("button", { name: "More actions for src/a.ts" }));
    const LINK = { name: "Open in dependency graph" };

    const { unmount } = renderTable([finding({ id: "a" })], {
      graphHref: (p: string) => `/repos/repo-1/architecture?node=${encodeURIComponent(p)}`,
    });
    openMenu();
    expect(screen.getByRole("link", LINK)).toHaveAttribute(
      "href",
      "/repos/repo-1/architecture?node=src%2Fa.ts",
    );
    unmount();

    // No graph route on the host (the hosted frontend today) means no action,
    // rather than a link into a page that does not exist there.
    renderTable([finding({ id: "a" })]);
    openMenu();
    expect(screen.queryByRole("link", LINK)).not.toBeInTheDocument();
  });

  it("reports a rejecting bulk resolve instead of wedging the dialog open", async () => {
    const onBulkResolve = vi.fn(async () => {
      throw new Error("Service unavailable");
    });
    renderTable([finding({ id: "a" })], { onBulkResolve });

    fireEvent.click(screen.getByLabelText("Select all findings"));
    fireEvent.click(screen.getByRole("button", { name: "Resolve 1 selected" }));
    fireEvent.click(await screen.findByRole("button", { name: "Resolve all" }));

    await waitFor(() => expect(toastError).toHaveBeenCalled());
    expect(String(toastError.mock.calls[0]?.[0])).toMatch(/Couldn't resolve findings/);
  });
});

describe("FindingsTable row actions", () => {
  it("surfaces a toast instead of an unhandled rejection when a patch fails", async () => {
    const onPatch = vi.fn(async () => {
      throw new Error("Network request failed");
    });
    renderTable([finding({ id: "a" })], { onPatch });

    fireEvent.click(inTable().getByRole("button", { name: "Resolve src/a.ts" }));
    fireEvent.click(await screen.findByRole("button", { name: "Resolve" }));

    await waitFor(() => expect(toastError).toHaveBeenCalled());
    expect(String(toastError.mock.calls[0]?.[0])).toMatch(/Couldn't update finding/);
  });
});

describe("FindingsTable colour jobs", () => {
  it("shows confidence as a neutral percent, never in alarm colours", () => {
    renderTable([finding({ id: "a", confidence: 0.95 })]);

    const pct = inTable().getByText("95%");
    expect(pct.className).not.toMatch(/color-error|color-warning|color-success/);
  });

  it("keeps the row's Resolve verb neutral", () => {
    renderTable([finding({ id: "a" })]);

    const resolve = inTable().getByRole("button", { name: "Resolve src/a.ts" });
    expect(resolve.className).not.toMatch(/color-success/);
  });

  it("grounds a selected row on the neutral selected token, not the accent", () => {
    renderTable([finding({ id: "a" })]);

    fireEvent.click(inTable().getByLabelText("Select finding src/a.ts"));
    const row = inTable().getByRole("row", { name: /src\/a\.ts/ });
    expect(row.className).toMatch(/color-bg-selected/);
    expect(row.className).not.toMatch(/accent-muted/);
  });
});