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.

5.6 KB
Raw Blame
"use client";

import { useCallback, useRef, useState } from "react";
import { providerSetupHref } from "@/lib/utils/page-href";
import { toast } from "sonner";
import {
  RegenerateButton,
  GenerateConfirmDialog,
  type RegenerateCascade,
} from "@repowise-dev/ui/wiki/regenerate-button";
import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
import { isStubPage } from "@repowise-dev/ui/lib/page-types";
import { GenerationProgressWrapper } from "@/components/jobs/generation-progress-wrapper";
import { useWatchedJob } from "@/lib/hooks/use-watched-job";
import { regeneratePage } from "@/lib/api/pages";
import { generateEstimate } from "@/lib/api/repos";
import { formatEstimateCost } from "@/lib/generate-format";
import type { PageResponse, GenerateEstimate } from "@/lib/api/types";
import { useTranslations } from "next-intl";

/**
 * The page's own "Write this page with AI" / "Rewrite with AI", a quiet
 * model-coloured action in the reader's metadata row. Owns the
 * lazily-fetched cost estimate, the cascade choice, the launch, and the live
 * progress — the shared `ui` components stay presentational.
 */
export function PageGenerateButton({
  page,
  repoId,
  onGenerated,
}: {
  page: PageResponse;
  repoId: string;
  /** Called once a run completes so the host can refresh the page list. */
  onGenerated?: () => void;
}) {
  // "Write" on a stub concept page, "Regenerate" on a written one. Callers only
  // mount this on the model-written page types, so a stub here is genuinely a
  // page awaiting its first prose, never a structural file page.
  const t = useTranslations("docs");
  const mode = isStubPage(page) ? "write" : "regenerate";
  const settingsHref = providerSetupHref(repoId);

  const [confirmOpen, setConfirmOpen] = useState(false);
  const [cascade, setCascade] = useState<RegenerateCascade>("none");
  const [estimate, setEstimate] = useState<GenerateEstimate | null>(null);
  const [estimateLoading, setEstimateLoading] = useState(false);
  const [estimateError, setEstimateError] = useState<string | null>(null);
  const [launching, setLaunching] = useState(false);
  const { watched, watch, settle, dismiss } = useWatchedJob<"page">();
  const jobId = watched?.id ?? null;

  // Cache estimates per cascade so toggling the choice back doesn't refetch the
  // heavy /generate/estimate endpoint.
  const cacheRef = useRef<Map<RegenerateCascade, GenerateEstimate>>(new Map());
  // The cascade whose estimate we currently want shown. A slow response for a
  // since-abandoned cascade must not overwrite the displayed one (latest wins).
  const wantedCascadeRef = useRef<RegenerateCascade>("none");

  const fetchEstimate = useCallback(
    async (which: RegenerateCascade) => {
      wantedCascadeRef.current = which;
      const cached = cacheRef.current.get(which);
      if (cached) {
        setEstimate(cached);
        setEstimateError(null);
        return;
      }
      setEstimateLoading(true);
      setEstimateError(null);
      try {
        const res = await generateEstimate(repoId, {
          selection: { kind: "page_ids", page_ids: [page.id] },
          cascade: which,
        });
        cacheRef.current.set(which, res);
        if (wantedCascadeRef.current === which) setEstimate(res);
      } catch (e) {
        if (wantedCascadeRef.current === which) {
          setEstimateError(toFriendlyMessage(e));
          setEstimate(null);
        }
      } finally {
        if (wantedCascadeRef.current === which) setEstimateLoading(false);
      }
    },
    [repoId, page.id],
  );

  function openConfirm() {
    cacheRef.current.clear();
    setEstimate(null);
    setEstimateError(null);
    setConfirmOpen(true);
    void fetchEstimate(cascade);
  }

  function changeCascade(next: RegenerateCascade) {
    setCascade(next);
    void fetchEstimate(next);
  }

  async function confirm() {
    setLaunching(true);
    try {
      const res = await regeneratePage(page.id, { cascade, repoId });
      watch(res.job_id, "page");
      setConfirmOpen(false);
    } catch (e) {
      toast.error(t("pageGenerate.failed"), {
        description: toFriendlyMessage(e),
      });
    } finally {
      setLaunching(false);
    }
  }

  const noProvider = !!estimate && estimate.provider.name == null;

  return (
    <>
      <RegenerateButton
        mode={mode}
        quiet
        label={mode === "write" ? t("pageGenerate.write") : t("pageGenerate.rewrite")}
        onRegenerate={openConfirm}
        isLoading={launching && !jobId}
        isInProgress={jobId != null}
        onDialogClose={dismiss}
        jobSlot={
          jobId != null ? (
            <GenerationProgressWrapper
              key={jobId}
              jobId={jobId}
              onDone={(outcome) => {
                settle(outcome);
                onGenerated?.();
              }}
              onRetry={() => {
                dismiss();
                openConfirm();
              }}
              onDismiss={dismiss}
            />
          ) : null
        }
      />

      <GenerateConfirmDialog
        open={confirmOpen}
        onOpenChange={setConfirmOpen}
        mode={mode}
        pageTitle={page.title}
        cascade={cascade}
        onCascadeChange={changeCascade}
        estimate={
          estimate && !noProvider
            ? {
                totalPages: estimate.total_pages,
                costText: formatEstimateCost(estimate.estimate),
                staleCount: estimate.pages_to_mark_stale,
              }
            : null
        }
        estimateLoading={estimateLoading}
        estimateError={estimateError}
        noProvider={noProvider}
        settingsHref={settingsHref}
        onConfirm={confirm}
        launching={launching}
      />
    </>
  );
}