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.

3.8 KB
Raw Blame
"use client";

/**
 * Dead Code host — binds the shared {@link DeadCodeView} to web's `/api`
 * client and `/repos/:id` routing. The composition (lede, safe-to-delete
 * list, findings table, patch/undo, bulk resolve, Propose cleanup,
 * Re-analyze) lives in `@repowise-dev/ui/dead-code`; this file only
 * injects the app-specific pieces so web and hosted render the same view.
 */

import { useMemo } from "react";
import { useRouter } from "next/navigation";
import {
  DeadCodeView,
  type DeadCodeAdapter,
  type DeadCodeLedeLabels,
} from "@repowise-dev/ui/dead-code";
import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
import {
  getDeadCodeSummary,
  listDeadCode,
  analyzeDeadCode,
  patchDeadCodeFinding,
} from "@/lib/api/dead-code";
import { getJob } from "@/lib/api/jobs";
import { useTranslations } from "next-intl";
import { formatNumber } from "@repowise-dev/ui/lib/format";
import { useRepoFileCount } from "@/lib/hooks/use-repo";

const POLL_INTERVAL_MS = 3_000;
/** Give up watching after this long; the job may still be running server-side. */
const POLL_TIMEOUT_MS = 15 * 60_000;

/**
 * Resolve once the analysis job finishes. Polling rather than SSE: the view
 * only needs the terminal state to know when to refetch, and a plain promise
 * keeps the shared view free of any streaming dependency.
 */
async function waitForJob(jobId: string, timeoutMessage: string): Promise<void> {
  const deadline = Date.now() + POLL_TIMEOUT_MS;
  for (;;) {
    await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
    const job = await getJob(jobId);
    if (job.status === "completed") return;
    if (job.status === "failed" || job.status === "cancelled") {
      throw new Error(job.error_message || `Analysis ${job.status}`);
    }
    if (Date.now() > deadline) {
      throw new Error(timeoutMessage);
    }
  }
}

export function DeadCodeTab({ repoId }: { repoId: string }) {
  const t = useTranslations("risk");
  const router = useRouter();
  const ledeLabels = useLedeLabels();
  const fileCount = useRepoFileCount(repoId);
  const prefix = `/repos/${repoId}`;

  const adapter: DeadCodeAdapter = {
    cacheKey: repoId,
    repoId,
    getSummary: () => getDeadCodeSummary(repoId),
    listFindings: (opts) => listDeadCode(repoId, opts),
    analyze: () => analyzeDeadCode(repoId),
    waitForAnalysis: (jobId) => waitForJob(jobId, t("analysisTimeout")),
    patchFinding: (findingId, patch) => patchDeadCodeFinding(findingId, patch),
    fileHref: (path) => fileEntityPath(prefix, path),
    graphHref: (path) =>
      `${prefix}/architecture?view=files&node=${encodeURIComponent(path)}`,
    navigate: (href) => router.push(href),
  };

  // The clean state names its scope once the file count lands.
  const clean = {
    title:
      fileCount != null
        ? t("deadCodeClean.titleScoped", { files: formatNumber(fileCount) })
        : t("deadCodeClean.title"),
    description: t("deadCodeClean.body"),
  };

  return <DeadCodeView adapter={adapter} ledeLabels={ledeLabels} clean={clean} />;
}

/** The lede copy from the catalog; exported for its test. */
export function useLedeLabels(): DeadCodeLedeLabels {
  const t = useTranslations("risk.deadCodeLede");
  return useMemo<DeadCodeLedeLabels>(
    () => ({
      label: t("label"),
      labelHint: t("labelHint"),
      unit: t("unit"),
      findingsUnit: (count) => t("findingsUnit", { count }),
      separator: t("separator"),
      clean: t("clean"),
      ready: (count) => t("ready", { count }),
      readyUncounted: t("readyUncounted"),
      moreFlagged: (count) => t("moreFlagged", { count }),
      flaggedInAll: ({ findings, lines }) => t("flaggedInAll", { findings, lines }),
      noneReady: t("noneReady"),
      flaggedForReview: ({ findings, lines }) => t("flaggedForReview", { findings, lines }),
    }),
    [t],
  );
}