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.

15.2 KB
Raw Blame
/**
 * The drawer when an opportunity resolves but its steps do not load.
 *
 * A host that cannot read the steps still has the opportunity itself, so the
 * drawer keeps its facts and its triage control and says the steps are missing,
 * instead of an empty list under "The steps, in order".
 */

import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import type {
  OpportunityStep,
  RecommendationValidation,
  RefactoringOpportunityDetailResolved,
  RefactoringPlan,
} from "@repowise-dev/types/refactoring";

import { OpportunityDrawer } from "../../src/refactoring/opportunity-drawer";
import { RefactoringDrawer } from "../../src/refactoring/refactoring-drawer";

function detail(
  overrides: Partial<RefactoringOpportunityDetailResolved> = {},
): RefactoringOpportunityDetailResolved {
  return {
    found: true,
    opportunity_id: "refop2_drawer",
    refactoring_model_version: 2,
    status: "open",
    file_path: "packages/core/src/big.py",
    lead_biomarker: "nested_complexity",
    lead_refactoring_type: "split_file",
    addresses_primary_problem: true,
    effort_bucket: "M",
    confidence: "high",
    step_count: 7,
    mechanical_steps: 5,
    judgment_steps: 2,
    evidence_total: 0,
    affected_files_total: 1,
    recoverable_health: 1.4,
    rank_score: 1.45,
    rank_position: 1,
    queue_position: 1,
    rank_factors: {},
    why_ranked: [],
    steps: [],
    steps_total: 7,
    steps_emitted: 0,
    evidence: [],
    evidence_emitted: 0,
    evidence_truncated: false,
    affected_files: ["packages/core/src/big.py"],
    validation_profiles: [],
    plans: [],
    next_actions: [],
    ...overrides,
  };
}

function renderDrawer(d: RefactoringOpportunityDetailResolved) {
  render(
    <OpportunityDrawer
      detail={d}
      open
      onOpenChange={() => {}}
      onStatusChange={() => {}}
      onAiPrompt={() => {}}
    />,
  );
}

describe("OpportunityDrawer steps unavailable", () => {
  it("keeps triage and says the steps did not load", () => {
    renderDrawer(detail({ details_status: "unavailable", steps_total: null }));

    expect(screen.getByRole("radiogroup", { name: "Triage this refactoring plan" })).toBeTruthy();
    expect(screen.getByText(/The 7 steps for this refactoring plan could not be loaded/)).toBeTruthy();
    expect(screen.queryByText(/Showing 0 of/)).toBeNull();
    // The prompt is built from the steps, so it is not offered without them.
    expect(screen.queryByRole("button", { name: /Agent prompt/ })).toBeNull();
  });

  it("says nothing about missing steps when they loaded", () => {
    renderDrawer(detail({ details_status: "available", steps_total: 12, steps_emitted: 0 }));

    expect(screen.queryByText(/could not be loaded/)).toBeNull();
    expect(screen.getByText("Showing 0 of 12 steps.")).toBeTruthy();
    expect(screen.getByRole("button", { name: /Agent prompt/ })).toBeTruthy();
  });
});

const STEP: OpportunityStep = {
  plan_id: "refac3_step",
  refactoring_type: "extract_method",
  target_symbol: "quick_repo_scan",
  file_path: "packages/core/src/big.py",
  line_start: 3,
  line_end: 4,
  effort_bucket: "S",
  confidence: "high",
  impact_delta: 1.7,
  source_biomarker: "complex_method",
  relocated_by: null,
  applicability: { classification: "mechanical", reasons: [], facts: {}, unknowns: [] },
};

const PLAN = {
  id: "refac3_step",
  refactoring_type: "extract_method",
  file_path: "packages/core/src/big.py",
  target_symbol: "quick_repo_scan",
  line_start: 3,
  line_end: 4,
  plan: {},
  evidence: {},
  impact_delta: 1.7,
  effort_bucket: "S",
  blast_radius: {},
  confidence: "high",
  source_biomarker: "complex_method",
  rank_score: 1,
} as RefactoringPlan;

describe("OpportunityDrawer reach, verification and code", () => {
  it("states the blast radius for every type, importers included when stored", () => {
    renderDrawer(detail({ affected_files_total: 2, dependents: 4 }));
    expect(screen.getByText(/^Touches 2 files; 4 files import it\./)).toBeTruthy();
  });

  it("says when importers were not recorded instead of implying none", () => {
    renderDrawer(detail());
    expect(
      screen.getByText("Touches 1 file; importers not recorded. No guarding tests found."),
    ).toBeTruthy();
  });

  it("opens Verify with the explicit message when nothing guards the file", () => {
    renderDrawer(detail());
    const verify = screen.getByRole("button", { name: /Verify/ });
    expect(verify.getAttribute("aria-expanded")).toBe("true");
    expect(verify.textContent).toContain("none guarding");
    expect(screen.getByText(/Write one that pins the current behaviour/)).toBeTruthy();
  });

  it("keeps Verify collapsed when tests guard the file, counting each test once", () => {
    const profile: Omit<RecommendationValidation, "total" | "tests"> = {
      basis: "measured",
      via: "call-graph",
      truncated: false,
      affected_files: [],
      affected_symbols: [],
      commands: [],
      targets: [],
    };
    renderDrawer(
      detail({
        validation_profiles: [
          { ...profile, id: "a", total: 2, tests: ["tests/test_a.py", "tests/test_b.py"] },
          { ...profile, id: "b", total: 2, tests: ["tests/test_b.py", "tests/test_c.py"] },
        ],
      }),
    );
    const verify = screen.getByRole("button", { name: /Verify/ });
    expect(verify.getAttribute("aria-expanded")).toBe("false");
    expect(verify.textContent).toContain("3 tests");
    expect(screen.getByText(/3 guarding tests reach it\./)).toBeTruthy();
  });

  it("keeps the agent id collapsed until asked for", () => {
    renderDrawer(detail());
    expect(screen.queryByText(/get_health\(opportunity_id=/)).toBeNull();
    fireEvent.click(screen.getByRole("button", { name: /Ask for this by id/ }));
    expect(screen.getByText(/get_health\(opportunity_id=/)).toBeTruthy();
  });

  it("reads the step's span from the file for an inline excerpt", async () => {
    const readSource = vi
      .fn()
      .mockResolvedValue(["a = 1", "b = 2", "c = 3", "d = 4", "e = 5"].join("\n"));
    render(
      <OpportunityDrawer
        detail={detail({ steps: [STEP], steps_emitted: 1, plans: [PLAN] })}
        open
        onOpenChange={() => {}}
        readSource={readSource}
      />,
    );
    fireEvent.click(screen.getByRole("button", { name: "Show the code" }));
    expect(await screen.findByText("c = 3")).toBeTruthy();
    expect(screen.getByText("d = 4")).toBeTruthy();
    expect(screen.queryByText("e = 5")).toBeNull();
    expect(readSource).toHaveBeenCalledWith("packages/core/src/big.py");
    // Generation is off, so the diff preview says how it would be drafted.
    expect(screen.getByText(/A diff preview is drafted by a model on request/)).toBeTruthy();
  });

  it("shows an extraction's slice under the helper's signature, not the whole function", async () => {
    const readSource = vi
      .fn()
      .mockResolvedValue(["def f():", "  a = 1", "  b = 2", "  c = 3", "  return c"].join("\n"));
    const plan = {
      ...PLAN,
      line_start: 1,
      line_end: 5,
      plan: { span: { start: 2, end: 3 }, params: [], returns: ["b"], suggested_name: "_setup" },
    } as RefactoringPlan;
    render(
      <OpportunityDrawer
        detail={detail({
          steps: [{ ...STEP, line_start: 1, line_end: 5 }],
          steps_emitted: 1,
          plans: [plan],
        })}
        open
        onOpenChange={() => {}}
        readSource={readSource}
      />,
    );
    fireEvent.click(screen.getByRole("button", { name: "Show the code" }));
    expect(screen.getByText("_setup() -> b")).toBeTruthy();
    expect(await screen.findByText("a = 1", { exact: false })).toBeTruthy();
    expect(screen.queryByText("def f():")).toBeNull();
    expect(screen.queryByText("return c", { exact: false })).toBeNull();
  });

  it("shows each stage of a staged plan as its own excerpt, not the lines between", async () => {
    // 120 lines; stages 10-12 and 90-92, a gap far over the 40-line excerpt cap.
    const source = Array.from({ length: 120 }, (_, i) => `line_${i + 1}`).join("\n");
    const readSource = vi.fn().mockResolvedValue(source);
    const stage = (start: number, end: number) => ({
      span: { start, end },
      params: [],
      returns: [],
      suggested_name: null,
      ccn: 3,
      new_symbol: { signature_text: "def <name>():" },
      call_site: { replace_span: { start, end }, new_text: "<name>()" },
    });
    const plan = {
      ...PLAN,
      line_start: 1,
      line_end: 120,
      plan: { ...stage(10, 12), stages: [stage(10, 12), stage(90, 92)] },
    } as unknown as RefactoringPlan;
    render(
      <OpportunityDrawer
        detail={detail({
          steps: [{ ...STEP, line_start: 1, line_end: 120 }],
          steps_emitted: 1,
          plans: [plan],
        })}
        open
        onOpenChange={() => {}}
        readSource={readSource}
      />,
    );
    fireEvent.click(screen.getByRole("button", { name: "Show the code" }));
    expect(await screen.findByText("line_10", { exact: false })).toBeTruthy();
    expect(await screen.findByText("line_92", { exact: false })).toBeTruthy();
    expect(screen.queryByText("line_50", { exact: false })).toBeNull();
    expect(screen.getByText("Stage 2 · lines 90–92")).toBeTruthy();
    // Both excerpts share one read of the file.
    expect(readSource).toHaveBeenCalledTimes(1);
  });

  it("offers the model-drafted diff preview when the host turned generation on", () => {
    render(
      <OpportunityDrawer
        detail={detail({ steps: [STEP], steps_emitted: 1, plans: [PLAN] })}
        open
        onOpenChange={() => {}}
        onGenerateCode={vi.fn()}
      />,
    );
    fireEvent.click(screen.getByRole("button", { name: "Show the code" }));
    expect(screen.getByRole("button", { name: /Generate code/ })).toBeTruthy();
  });

  it("shows the model toggle when modelSetting is passed and onGenerateCode is not", () => {
    render(
      <OpportunityDrawer
        detail={detail({ steps: [STEP], steps_emitted: 1, plans: [PLAN] })}
        open
        onOpenChange={() => {}}
        modelSetting={{
          value: { enabled: false, provider: "anthropic", model: "claude-test" },
          onToggle: vi.fn(),
        }}
      />,
    );
    fireEvent.click(screen.getByRole("button", { name: "Show the code" }));
    expect(screen.getByRole("switch", { name: /name helpers and draft code/ })).toBeTruthy();
    expect(screen.queryByRole("button", { name: /Generate code/ })).toBeNull();
    expect(screen.queryByText(/Code generation is off here/)).toBeNull();
  });

  it("shows the code generation off sentence when neither onGenerateCode nor modelSetting is passed", () => {
    render(
      <OpportunityDrawer
        detail={detail({ steps: [STEP], steps_emitted: 1, plans: [PLAN] })}
        open
        onOpenChange={() => {}}
      />,
    );
    fireEvent.click(screen.getByRole("button", { name: "Show the code" }));
    expect(screen.getByText(/Code generation is off here/)).toBeTruthy();
    expect(screen.queryByRole("switch")).toBeNull();
    expect(screen.queryByRole("button", { name: /Generate code/ })).toBeNull();
  });
});

describe("RefactoringDrawer validation", () => {
  const validation = {
    basis: "unknown",
    via: null,
    total: 0,
    tests: [],
    truncated: false,
    affected_files: [],
    affected_symbols: [],
    commands: [],
    targets: [],
  } as const;

  it("opens Validation when no test guards the plan", () => {
    render(
      <RefactoringDrawer
        plan={{ ...PLAN, validation } as unknown as RefactoringPlan}
        open
        onOpenChange={() => {}}
      />,
    );
    const toggle = screen.getByRole("button", { name: /Validation/ });
    expect(toggle.getAttribute("aria-expanded")).toBe("true");
    expect(toggle.textContent).toContain("none guarding");
  });

  it("keeps Validation collapsed, with no count, when the plan carries none", () => {
    render(<RefactoringDrawer plan={PLAN} open onOpenChange={() => {}} />);
    const toggle = screen.getByRole("button", { name: /Validation/ });
    expect(toggle.getAttribute("aria-expanded")).toBe("false");
    expect(toggle.textContent).not.toContain("guarding");
  });
});

describe("RefactoringDrawer code generation", () => {
  const modelSetting = {
    value: { enabled: false, provider: "anthropic", model: "claude-test" },
    onToggle: async () => {},
  };

  it("offers the model switch while generation is off", () => {
    render(
      <RefactoringDrawer plan={PLAN} open onOpenChange={() => {}} modelSetting={modelSetting} />,
    );
    expect(screen.getByRole("switch", { name: /name helpers and draft code/ })).toBeTruthy();
    expect(screen.queryByRole("button", { name: "Generate code" })).toBeNull();
  });

  it("shows the action, not the switch, once generation is on", () => {
    render(
      <RefactoringDrawer
        plan={PLAN}
        open
        onOpenChange={() => {}}
        modelSetting={modelSetting}
        onGenerateCode={async () => {
          throw new Error("not called");
        }}
      />,
    );
    expect(screen.getByRole("button", { name: "Generate code" })).toBeTruthy();
    expect(screen.queryByRole("switch")).toBeNull();
  });
});

describe("RefactoringDrawer with no model configured", () => {
  it("shows the setup hint, not a generate action", () => {
    render(
      <RefactoringDrawer
        plan={PLAN}
        open
        onOpenChange={() => {}}
        modelSetting={{
          value: { enabled: true, provider: null, model: null },
          onToggle: async () => {},
          setupHref: "/repos/r1/settings/models",
        }}
      />,
    );
    expect(screen.getByRole("link", { name: "Set one up" })).toBeTruthy();
    expect(screen.queryByRole("button", { name: "Generate code" })).toBeNull();
  });
});

describe("RefactoringDrawer risks", () => {
  it("lists each risk as one line before the change", () => {
    const risks = [
      {
        kind: "decision",
        text: 'Decision "Keep the writer inline" governs this file; check it allows this change first.',
        ref: "dec1",
      },
      {
        kind: "active_edit",
        text: "Changed in 3 commits by 2 authors in the 14 days before the last index; check nobody is mid-change.",
        ref: "abc123",
      },
    ] as const;
    render(<RefactoringDrawer plan={{ ...PLAN, risks: [...risks] }} open onOpenChange={() => {}} />);
    expect(screen.getByText("Before you start")).toBeTruthy();
    for (const risk of risks) expect(screen.getByText(risk.text)).toBeTruthy();
  });

  it("renders no risk section when the plan carries none", () => {
    render(<RefactoringDrawer plan={{ ...PLAN, risks: [] }} open onOpenChange={() => {}} />);
    expect(screen.queryByText("Before you start")).toBeNull();
  });
});

describe("OpportunityDrawer preview", () => {
  const NOTE = "preview, measured 22% precision on 55 judged plans from 2 Java repos, 2026-10-15";

  it("marks a preview opportunity and its preview plan", () => {
    renderDrawer(
      detail({
        preview: NOTE,
        steps: [STEP],
        steps_emitted: 1,
        plans: [{ ...PLAN, preview: NOTE }],
      }),
    );
    expect(screen.getAllByRole("button", { name: `Preview: ${NOTE}` })).toHaveLength(2);
  });

  it("carries no mark for a validated cell", () => {
    renderDrawer(detail({ steps: [STEP], steps_emitted: 1, plans: [PLAN] }));
    expect(document.querySelector("[data-preview]")).toBeNull();
  });
});