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.

feat: bulk AI doc generation and provenance surfaces in the web UI (#991)

Raghav Chamadiyabdd41f2e68de
diff --git a/packages/ui/__tests__/coverage/freshness-table.test.tsx b/packages/ui/__tests__/coverage/freshness-table.test.tsx
index b5b462bea..1e088bd63 100644
--- a/packages/ui/__tests__/coverage/freshness-table.test.tsx
+++ b/packages/ui/__tests__/coverage/freshness-table.test.tsx
@@ -75,4 +75,70 @@ describe("FreshnessTable", () => {
screen.queryByRole("button", { name: "Regenerate" }),
).not.toBeInTheDocument();
});
+
+ it("filters to auto (template) pages via the Auto tab", () => {
+ render(
+ <FreshnessTable
+ pages={[
+ makePage({ id: "1", target_path: "written.ts", provider_name: "openai" }),
+ makePage({ id: "2", target_path: "auto.ts", is_deterministic: true }),
+ ]}
+ />,
+ );
+ fireEvent.click(screen.getByRole("tab", { name: /Auto/ }));
+ expect(screen.getByText("auto.ts")).toBeInTheDocument();
+ expect(screen.queryByText("written.ts")).not.toBeInTheDocument();
+ });
+
+ describe("selection", () => {
+ it("renders a checkbox per row and toggles onToggleSelect", () => {
+ const onToggleSelect = vi.fn();
+ render(
+ <FreshnessTable
+ pages={[makePage({ id: "p1", target_path: "x.ts" })]}
+ selectable
+ selectedIds={new Set()}
+ onToggleSelect={onToggleSelect}
+ />,
+ );
+ fireEvent.click(screen.getByRole("checkbox", { name: /Select x\.ts/ }));
+ expect(onToggleSelect).toHaveBeenCalledWith("p1");
+ });
+
+ it("selects all template pages, not AI-written ones", () => {
+ const onSelectTemplates = vi.fn();
+ render(
+ <FreshnessTable
+ pages={[
+ makePage({ id: "t1", target_path: "a.ts", is_deterministic: true }),
+ makePage({ id: "t2", target_path: "b.ts", is_deterministic: true }),
+ makePage({ id: "w1", target_path: "c.ts", provider_name: "openai" }),
+ ]}
+ selectable
+ selectedIds={new Set()}
+ onSelectTemplates={onSelectTemplates}
+ />,
+ );
+ fireEvent.click(screen.getByText(/Select all 2 template pages/));
+ expect(onSelectTemplates).toHaveBeenCalledWith(["t1", "t2"]);
+ });
+
+ it("renders the caller-provided toolbar", () => {
+ render(
+ <FreshnessTable
+ pages={[makePage({ is_deterministic: true })]}
+ selectable
+ selectedIds={new Set(["p1"])}
+ toolbar={<div data-testid="sel-toolbar">1 selected</div>}
+ />,
+ );
+ expect(screen.getByTestId("sel-toolbar")).toBeInTheDocument();
+ });
+
+ it("does not render checkboxes or the select-all affordance when not selectable", () => {
+ render(<FreshnessTable pages={[makePage({ is_deterministic: true })]} />);
+ expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
+ expect(screen.queryByText(/template pages/)).not.toBeInTheDocument();
+ });
+ });
});
diff --git a/packages/ui/__tests__/docs/auto-docs-banner.test.tsx b/packages/ui/__tests__/docs/auto-docs-banner.test.tsx
new file mode 100644
index 000000000..c7cb7ce1b
--- /dev/null
+++ b/packages/ui/__tests__/docs/auto-docs-banner.test.tsx
@@ -0,0 +1,48 @@
+import { describe, it, expect, vi } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
+import { AutoDocsBanner } from "../../src/docs/auto-docs-banner.js";
+
+describe("AutoDocsBanner", () => {
+ it("renders nothing when no template pages remain", () => {
+ const { container } = render(
+ <AutoDocsBanner templateCount={0} writtenCount={12} onWriteAll={vi.fn()} />,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("shows the count (formatted) and offers the bulk write", () => {
+ const onWriteAll = vi.fn();
+ render(
+ <AutoDocsBanner templateCount={1238} writtenCount={0} onWriteAll={onWriteAll} />,
+ );
+ expect(screen.getByText("1,238")).toBeInTheDocument();
+ expect(screen.getByText(/auto-documented from your code/i)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: /Write with AI/ }));
+ expect(onWriteAll).toHaveBeenCalledTimes(1);
+ });
+
+ it("words a mixed repo honestly (pages still generated from structure)", () => {
+ render(
+ <AutoDocsBanner templateCount={5} writtenCount={40} onWriteAll={vi.fn()} />,
+ );
+ expect(screen.getByText(/still/i)).toBeInTheDocument();
+ });
+
+ it("shows a dismiss control only when the host owns dismissal", () => {
+ const onDismiss = vi.fn();
+ const { rerender } = render(
+ <AutoDocsBanner templateCount={3} writtenCount={0} onWriteAll={vi.fn()} />,
+ );
+ expect(screen.queryByRole("button", { name: /Dismiss/ })).not.toBeInTheDocument();
+ rerender(
+ <AutoDocsBanner
+ templateCount={3}
+ writtenCount={0}
+ onWriteAll={vi.fn()}
+ onDismiss={onDismiss}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /Dismiss/ }));
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/ui/__tests__/docs/docs-mode-badge.test.tsx b/packages/ui/__tests__/docs/docs-mode-badge.test.tsx
new file mode 100644
index 000000000..cddc42aa1
--- /dev/null
+++ b/packages/ui/__tests__/docs/docs-mode-badge.test.tsx
@@ -0,0 +1,25 @@
+import { describe, it, expect } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { DocsModeBadge } from "../../src/docs/docs-mode-badge.js";
+
+describe("DocsModeBadge", () => {
+ it("renders nothing when there are no docs", () => {
+ const { container } = render(<DocsModeBadge mode="none" />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("labels a template repo as Auto docs, never fully written", () => {
+ render(<DocsModeBadge mode="deterministic" />);
+ expect(screen.getByText("Auto docs")).toBeInTheDocument();
+ });
+
+ it("labels a partly-upgraded repo as Mixed docs", () => {
+ render(<DocsModeBadge mode="mixed" />);
+ expect(screen.getByText("Mixed docs")).toBeInTheDocument();
+ });
+
+ it("labels a fully model-written repo as AI docs", () => {
+ render(<DocsModeBadge mode="llm" />);
+ expect(screen.getByText("AI docs")).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/wiki/regenerate-button.test.tsx b/packages/ui/__tests__/wiki/regenerate-button.test.tsx
index 512b33767..6b93fa38e 100644
--- a/packages/ui/__tests__/wiki/regenerate-button.test.tsx
+++ b/packages/ui/__tests__/wiki/regenerate-button.test.tsx
@@ -1,6 +1,9 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
-import { RegenerateButton } from "../../src/wiki/regenerate-button.js";
+import {
+ RegenerateButton,
+ GenerateConfirmDialog,
+} from "../../src/wiki/regenerate-button.js";
describe("RegenerateButton", () => {
it("renders the regenerate button and fires onRegenerate on click", () => {
@@ -10,6 +13,13 @@ describe("RegenerateButton", () => {
expect(onRegenerate).toHaveBeenCalledTimes(1);
});
+ it("renders a compact inline trigger and still fires onRegenerate", () => {
+ const onRegenerate = vi.fn();
+ render(<RegenerateButton mode="write" inline onRegenerate={onRegenerate} />);
+ fireEvent.click(screen.getByRole("button", { name: /Write this page with AI/ }));
+ expect(onRegenerate).toHaveBeenCalledTimes(1);
+ });
+
it("disables the button while loading", () => {
render(<RegenerateButton onRegenerate={vi.fn()} isLoading />);
expect(screen.getByRole("button", { name: /regenerate/i })).toBeDisabled();
@@ -27,3 +37,43 @@ describe("RegenerateButton", () => {
expect(screen.getByText(/regenerating page/i)).toBeInTheDocument();
});
});
+
+describe("GenerateConfirmDialog (bulk overrides)", () => {
+ const base = {
+ open: true,
+ onOpenChange: vi.fn(),
+ cascade: "none" as const,
+ onCascadeChange: vi.fn(),
+ onConfirm: vi.fn(),
+ };
+
+ it("uses the title, selection-scoped cascade wording, and confirm label overrides", () => {
+ render(
+ <GenerateConfirmDialog
+ {...base}
+ title="Write documentation with AI"
+ cascadeScope="selection"
+ description={<>Write the selected pages with your model.</>}
+ confirmLabel="Write 12 pages"
+ estimate={{ totalPages: 12, costText: "$0.10 to $0.20" }}
+ />,
+ );
+ expect(screen.getByText("Write documentation with AI")).toBeInTheDocument();
+ expect(screen.getByText("Just the selected pages")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /Write 12 pages/ }),
+ ).toBeInTheDocument();
+ });
+
+ it("routes to settings when no provider is configured", () => {
+ render(
+ <GenerateConfirmDialog
+ {...base}
+ noProvider
+ settingsHref="/repos/r1/settings#provider"
+ />,
+ );
+ const link = screen.getByRole("link", { name: /Add a provider key/ });
+ expect(link).toHaveAttribute("href", "/repos/r1/settings#provider");
+ });
+});
diff --git a/packages/ui/src/coverage/freshness-table.tsx b/packages/ui/src/coverage/freshness-table.tsx
index 0b903f715..b0d317169 100644
--- a/packages/ui/src/coverage/freshness-table.tsx
+++ b/packages/ui/src/coverage/freshness-table.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useMemo, useState } from "react";
+import { useMemo, useState, type ReactNode } from "react";
import { Button } from "../ui/button";
import { EmptyState } from "../shared/empty-state";
import { VirtualizedTable } from "../shared/virtualized-table";
@@ -14,10 +14,16 @@ import {
formatConfidence,
formatRelativeTime,
} from "../lib/format";
-import { getPageTypeIcon, getPageTypeLabel } from "../lib/page-types";
+import {
+ getPageTypeIcon,
+ getPageTypeLabel,
+ isDeterministicPage,
+} from "../lib/page-types";
import type { DocPage } from "@repowise-dev/types/docs";
-type Filter = "all" | "fresh" | "stale" | "outdated";
+// "auto" is a provenance filter (template pages), orthogonal to freshness — it
+// lets a user jump to the pages worth upgrading and select them in one place.
+type Filter = "all" | "fresh" | "stale" | "outdated" | "auto";
export interface FreshnessTableProps {
/** Pages to render. Caller is responsible for fetching. */
@@ -28,12 +34,45 @@ export interface FreshnessTableProps {
* per-row pending UI state. Omit to hide the regenerate button.
*/
onRegenerate?: (pageId: string) => Promise<void>;
+ /**
+ * When true, each row gets a checkbox and a "select all template pages"
+ * affordance is shown, for launching a bulk generate. Selection state is
+ * owned by the caller (so the cost estimate lives with the data wiring).
+ */
+ selectable?: boolean;
+ selectedIds?: Set<string>;
+ onToggleSelect?: (pageId: string) => void;
+ /** Called with every template (auto) page id — powers "select all template
+ * pages". */
+ onSelectTemplates?: (templateIds: string[]) => void;
+ onClearSelection?: () => void;
+ /** Rendered above the table — typically the running count + cost + a
+ * "Write selected" action the caller builds from the selection. */
+ toolbar?: ReactNode;
}
-export function FreshnessTable({ pages, onRegenerate }: FreshnessTableProps) {
+export function FreshnessTable({
+ pages,
+ onRegenerate,
+ selectable = false,
+ selectedIds,
+ onToggleSelect,
+ onSelectTemplates,
+ onClearSelection,
+ toolbar,
+}: FreshnessTableProps) {
const [filter, setFilter] = useState<Filter>("all");
const [regenerating, setRegenerating] = useState<Set<string>>(new Set());
+ // Template (auto) page ids power the "select all template pages" affordance.
+ const templateIds = useMemo(
+ () => pages.filter((p) => isDeterministicPage(p)).map((p) => p.id),
+ [pages],
+ );
+ const selectedCount = selectedIds?.size ?? 0;
+ const allTemplatesSelected =
+ templateIds.length > 0 && templateIds.every((id) => selectedIds?.has(id));
+
// The filter is a set of discrete status toggle buttons, not a free-text
// search input, so there are no rapid keystroke updates to debounce — each
// click is a single discrete state change. We only need to memoize the
@@ -43,21 +82,22 @@ export function FreshnessTable({ pages, onRegenerate }: FreshnessTableProps) {
let fresh = 0;
let stale = 0;
let outdated = 0;
+ let auto = 0;
for (const p of pages) {
if (p.freshness_status === "fresh") fresh += 1;
else if (p.freshness_status === "stale") stale += 1;
else if (p.freshness_status === "outdated") outdated += 1;
+ // Provenance is independent of freshness, so count it separately.
+ if (isDeterministicPage(p)) auto += 1;
}
- return { all: pages.length, fresh, stale, outdated };
+ return { all: pages.length, fresh, stale, outdated, auto };
}, [pages]);
- const filtered = useMemo(
- () =>
- filter === "all"
- ? pages
- : pages.filter((p) => p.freshness_status === filter),
- [pages, filter],
- );
+ const filtered = useMemo(() => {
+ if (filter === "all") return pages;
+ if (filter === "auto") return pages.filter((p) => isDeterministicPage(p));
+ return pages.filter((p) => p.freshness_status === filter);
+ }, [pages, filter]);
const handleRegenerate = async (pageId: string) => {
if (!onRegenerate) return;
@@ -75,29 +115,67 @@ export function FreshnessTable({ pages, onRegenerate }: FreshnessTableProps) {
return (
<div className="space-y-4">
- <div role="tablist" aria-label="Freshness filter" className="flex items-center gap-1">
- {(["all", "fresh", "stale", "outdated"] as Filter[]).map((f) => {
- const count = counts[f];
- return (
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div role="tablist" aria-label="Filter pages" className="flex flex-wrap items-center gap-1">
+ {(["all", "fresh", "stale", "outdated", "auto"] as Filter[]).map((f) => {
+ const count = counts[f];
+ const label =
+ f === "all" ? "All" : f === "auto" ? "Auto" : statusLabel(f as FreshnessStatus);
+ return (
+ <button
+ key={f}
+ role="tab"
+ aria-selected={filter === f}
+ onClick={() => setFilter(f)}
+ title={
+ f === "auto"
+ ? "Pages generated from code structure (upgrade candidates)"
+ : undefined
+ }
+ className={cn(
+ "rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
+ filter === f
+ ? "bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] shadow-sm"
+ : "text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",
+ )}
+ >
+ {label}
+ <span className="ml-1 text-[var(--color-text-tertiary)]">({count})</span>
+ </button>
+ );
+ })}
+ </div>
+
+ {selectable && templateIds.length > 0 && (
+ <div className="flex items-center gap-3 text-xs">
<button
- key={f}
- role="tab"
- aria-selected={filter === f}
- onClick={() => setFilter(f)}
- className={cn(
- "rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
- filter === f
- ? "bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] shadow-sm"
- : "text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",
- )}
+ type="button"
+ onClick={() =>
+ allTemplatesSelected
+ ? onClearSelection?.()
+ : onSelectTemplates?.(templateIds)
+ }
+ className="font-medium text-[var(--color-accent-primary)] hover:text-[var(--color-accent-hover)]"
>
- {f === "all" ? "All" : statusLabel(f as FreshnessStatus)}
- <span className="ml-1 text-[var(--color-text-tertiary)]">({count})</span>
+ {allTemplatesSelected
+ ? "Clear selection"
+ : `Select all ${templateIds.length} template pages`}
</button>
- );
- })}
+ {selectedCount > 0 && !allTemplatesSelected && onClearSelection && (
+ <button
+ type="button"
+ onClick={() => onClearSelection()}
+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]"
+ >
+ Clear
+ </button>
+ )}
+ </div>
+ )}
</div>
+ {selectable && toolbar}
+
{filtered.length === 0 ? (
<EmptyState title="No pages" description="No pages match this filter." />
) : (
@@ -111,6 +189,11 @@ export function FreshnessTable({ pages, onRegenerate }: FreshnessTableProps) {
headerClassName="bg-[var(--color-bg-surface)]"
header={
<tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
+ {selectable && (
+ <th scope="col" className="w-10 px-4 py-2.5">
+ <span className="sr-only">Select</span>
+ </th>
+ )}
<th scope="col" className="px-4 py-2.5 text-left text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
Page
</th>
@@ -135,8 +218,22 @@ export function FreshnessTable({ pages, onRegenerate }: FreshnessTableProps) {
const status = page.freshness_status as FreshnessStatus;
return (
<tr
- className="group border-b border-[var(--color-table-divider)] hover:bg-[var(--color-bg-elevated)] transition-colors last:border-0"
+ className={cn(
+ "group border-b border-[var(--color-table-divider)] hover:bg-[var(--color-bg-elevated)] transition-colors last:border-0",
+ selectable && selectedIds?.has(page.id) && "bg-[var(--color-accent-muted)]",
+ )}
>
+ {selectable && (
+ <td className="px-4 py-2.5">
+ <input
+ type="checkbox"
+ checked={selectedIds?.has(page.id) ?? false}
+ onChange={() => onToggleSelect?.(page.id)}
+ className="accent-[var(--color-accent-fill)]"
+ aria-label={`Select ${page.target_path}`}
+ />
+ </td>
+ )}
<td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] min-w-[220px] max-w-[480px]">
<div className="truncate group-hover:underline underline-offset-2" title={page.target_path}>{page.target_path}</div>
{(() => { const TypeIcon = getPageTypeIcon(page.page_type); return (
diff --git a/packages/ui/src/dashboard/quick-actions.tsx b/packages/ui/src/dashboard/quick-actions.tsx
index bf320d92f..57d6bcd3b 100644
--- a/packages/ui/src/dashboard/quick-actions.tsx
+++ b/packages/ui/src/dashboard/quick-actions.tsx
@@ -1,7 +1,7 @@
"use client";
import { useMemo, useState, type ReactNode, type ComponentType } from "react";
-import { RefreshCw, Trash2, AlertTriangle, Zap } from "lucide-react";
+import { RefreshCw, Trash2, AlertTriangle, Zap, Sparkles } from "lucide-react";
import { Button } from "../ui/button";
import {
Dialog,
@@ -67,7 +67,7 @@ function estimateCost(pageCount: number, modelName: string) {
return { inputTokens, outputTokens, cost };
}
-export type QuickActionKey = "sync" | "resync" | "dead-code";
+export type QuickActionKey = "sync" | "resync" | "dead-code" | "generate-docs";
export interface QuickActionDef {
key: QuickActionKey;
@@ -80,6 +80,20 @@ export interface QuickActionDef {
confirmDescription: string;
}
+/** Bulk "Write with AI" entry point. `needsConfirm` is false because the
+ * wrapper opens its own cost-aware confirm dialog (real `/generate/estimate` +
+ * cascade + no-provider routing), not the heuristic panel below. */
+export const GENERATE_DOCS_ACTION: QuickActionDef = {
+ key: "generate-docs",
+ label: "Write with AI",
+ description: "Upgrade pages generated from structure to model-written prose",
+ icon: Sparkles,
+ destructive: false,
+ needsConfirm: false,
+ confirmTitle: "",
+ confirmDescription: "",
+};
+
export const DEFAULT_QUICK_ACTIONS: QuickActionDef[] = [
{
key: "sync",
diff --git a/packages/ui/src/docs/auto-docs-banner.tsx b/packages/ui/src/docs/auto-docs-banner.tsx
new file mode 100644
index 000000000..a587013bd
--- /dev/null
+++ b/packages/ui/src/docs/auto-docs-banner.tsx
@@ -0,0 +1,72 @@
+"use client";
+
+import { Sparkles, X } from "lucide-react";
+import { formatNumber } from "../lib/format";
+import { cn } from "../lib/cn";
+
+/**
+ * A thin, one-line strip shown above the docs reader when a repo still has
+ * pages generated from structure (templates). It reframes an index-only wiki as
+ * "auto-documented, upgrade me" rather than empty, and offers the bulk write,
+ * without stealing vertical space from the reader.
+ *
+ * Presentational only: the caller counts template vs written pages, owns the
+ * launch (`onWriteAll`), and owns dismissal (`onDismiss`) so it can persist
+ * "don't show this again" per repo instead of nagging on every visit.
+ */
+export function AutoDocsBanner({
+ templateCount,
+ writtenCount,
+ onWriteAll,
+ onDismiss,
+ className,
+}: {
+ /** Number of pages still rendered from templates (the upgrade target). */
+ templateCount: number;
+ /** Number of AI-written pages, used to word the "mixed" case honestly. */
+ writtenCount: number;
+ onWriteAll: () => void;
+ /** Omit to hide the dismiss control (host owns whether it persists). */
+ onDismiss?: () => void;
+ className?: string;
+}) {
+ if (templateCount <= 0) return null;
+
+ const mixed = writtenCount > 0;
+ const pageWord = templateCount === 1 ? "page" : "pages";
+
+ return (
+ <div
+ className={cn(
+ "flex items-center gap-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-4 py-1.5 text-xs sm:px-6",
+ className,
+ )}
+ >
+ <Sparkles className="h-3.5 w-3.5 shrink-0 text-[var(--color-accent-primary)]" />
+ <span className="min-w-0 flex-1 truncate text-[var(--color-text-secondary)]">
+ <span className="font-medium text-[var(--color-text-primary)]">
+ {formatNumber(templateCount)}
+ </span>{" "}
+ {mixed ? `${pageWord} still` : pageWord} auto-documented from your code.
+ Upgrade to AI-written prose for the how and why.
+ </span>
+ <button
+ type="button"
+ onClick={onWriteAll}
+ className="shrink-0 font-medium text-[var(--color-accent-primary)] hover:text-[var(--color-accent-hover)]"
+ >
+ Write with AI
+ </button>
+ {onDismiss && (
+ <button
+ type="button"
+ onClick={onDismiss}
+ aria-label="Dismiss"
+ className="shrink-0 rounded p-0.5 text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-inset)] hover:text-[var(--color-text-secondary)]"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/docs/docs-mode-badge.tsx b/packages/ui/src/docs/docs-mode-badge.tsx
new file mode 100644
index 000000000..287048ef5
--- /dev/null
+++ b/packages/ui/src/docs/docs-mode-badge.tsx
@@ -0,0 +1,65 @@
+"use client";
+
+import { Cog, Sparkles, Blend } from "lucide-react";
+import { cn } from "../lib/cn";
+
+/** How a repo's wiki was written. `deterministic` and `mixed` both come from
+ * the repos API `docs_mode: "deterministic"` (which only flips to `llm` once
+ * no template page remains); a caller that can count provenance passes
+ * `mixed` so a partly-upgraded repo never reads as fully written. */
+export type DocsMode = "none" | "deterministic" | "mixed" | "llm";
+
+const CONFIG: Record<
+ Exclude<DocsMode, "none">,
+ { label: string; title: string; icon: typeof Cog; className: string }
+> = {
+ deterministic: {
+ label: "Auto docs",
+ title:
+ "Generated from code structure (no AI). Upgrade individual pages, or write them all, with a model.",
+ icon: Cog,
+ className:
+ "border-[var(--color-info)]/35 bg-[var(--color-info)]/10 text-[var(--color-info)]",
+ },
+ mixed: {
+ label: "Mixed docs",
+ title:
+ "Some pages are AI-written, the rest are generated from code structure. Write the remaining ones with a model.",
+ icon: Blend,
+ className:
+ "border-[var(--color-accent-primary)]/35 bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]",
+ },
+ llm: {
+ label: "AI docs",
+ title: "Written by AI from the code and its context.",
+ icon: Sparkles,
+ className:
+ "border-[var(--color-accent-primary)]/40 bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]",
+ },
+};
+
+/** A small provenance chip for a repo header. Renders nothing when there are
+ * no docs yet (`none`), so the header stays quiet until a repo is documented. */
+export function DocsModeBadge({
+ mode,
+ className,
+}: {
+ mode: DocsMode;
+ className?: string;
+}) {
+ if (mode === "none") return null;
+ const { label, title, icon: Icon, className: tone } = CONFIG[mode];
+ return (
+ <span
+ title={title}
+ className={cn(
+ "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-medium uppercase tracking-wider",
+ tone,
+ className,
+ )}
+ >
+ <Icon className="h-2.5 w-2.5" />
+ {label}
+ </span>
+ );
+}
diff --git a/packages/ui/src/docs/docs-reader.tsx b/packages/ui/src/docs/docs-reader.tsx
index 2d3ef374c..9e78c2fdb 100644
--- a/packages/ui/src/docs/docs-reader.tsx
+++ b/packages/ui/src/docs/docs-reader.tsx
@@ -75,6 +75,12 @@ interface DocsReaderProps {
intelligenceSlot?: React.ReactNode;
/** Data-bound version history (host owns the SWR fetch). */
versionHistorySlot?: React.ReactNode;
+ /**
+ * A compact "Write with AI" affordance rendered inline in the metadata row,
+ * beside the "Auto" pill, on a template page. Host owns the launch; omit it
+ * on AI-written pages so only auto pages advertise the upgrade.
+ */
+ upgradeSlot?: React.ReactNode;
}
export function DocsReader({
@@ -90,6 +96,7 @@ export function DocsReader({
LinkComponent,
intelligenceSlot,
versionHistorySlot,
+ upgradeSlot,
}: DocsReaderProps) {
const scrollRef = useRef<HTMLDivElement>(null);
@@ -145,6 +152,7 @@ export function DocsReader({
LinkComponent={LinkComponent}
intelligenceSlot={intelligenceSlot}
versionHistorySlot={versionHistorySlot}
+ upgradeSlot={upgradeSlot}
/>
);
}
@@ -161,6 +169,7 @@ function DocsReaderBody({
LinkComponent,
intelligenceSlot,
versionHistorySlot,
+ upgradeSlot,
}: {
page: DocPage;
pages: DocPage[];
@@ -173,6 +182,7 @@ function DocsReaderBody({
LinkComponent: ReaderLinkComponent;
intelligenceSlot?: React.ReactNode;
versionHistorySlot?: React.ReactNode;
+ upgradeSlot?: React.ReactNode;
}) {
const nav = useMemo(() => computeDocNav(page, pages), [page, pages]);
const wikiLinks = useMemo(() => getWikiLinks(page.metadata), [page.metadata]);
@@ -326,13 +336,16 @@ function DocsReaderBody({
{getPageTypeLabel(page.page_type)}
</span>
{isDeterministicPage(page) ? (
- <span
- className="inline-flex items-center gap-1 rounded-full border border-[var(--color-info)]/35 bg-[var(--color-info)]/10 px-2 py-0.5 uppercase tracking-wider text-[var(--color-info)]"
- title={DETERMINISTIC_BADGE_TITLE}
- >
- <Cog className="h-2.5 w-2.5" />
- {DETERMINISTIC_BADGE_LABEL}
- </span>
+ <>
+ <span
+ className="inline-flex items-center gap-1 rounded-full border border-[var(--color-info)]/35 bg-[var(--color-info)]/10 px-2 py-0.5 uppercase tracking-wider text-[var(--color-info)]"
+ title={DETERMINISTIC_BADGE_TITLE}
+ >
+ <Cog className="h-2.5 w-2.5" />
+ {DETERMINISTIC_BADGE_LABEL}
+ </span>
+ {upgradeSlot}
+ </>
) : (
<span
className="inline-flex items-center gap-1 rounded-full border border-[var(--color-accent-primary)]/40 bg-[var(--color-accent-muted)] px-2 py-0.5 uppercase tracking-wider text-[var(--color-accent-primary)]"
diff --git a/packages/ui/src/wiki/regenerate-button.tsx b/packages/ui/src/wiki/regenerate-button.tsx
index f73818cf4..9a0dee2b1 100644
--- a/packages/ui/src/wiki/regenerate-button.tsx
+++ b/packages/ui/src/wiki/regenerate-button.tsx
@@ -34,6 +34,10 @@ export interface RegenerateButtonProps {
/** Rendered inside the in-progress dialog — typically a job-progress widget
* owned by the wrapper. */
jobSlot?: ReactNode;
+ /** Compact, link-like trigger for placing the affordance inside page body
+ * copy (e.g. next to the provenance pill) rather than a toolbar. The
+ * progress dialog is unchanged. */
+ inline?: boolean;
}
export function RegenerateButton({
@@ -43,35 +47,49 @@ export function RegenerateButton({
isInProgress = false,
onDialogClose,
jobSlot,
+ inline = false,
}: RegenerateButtonProps) {
const isWrite = mode === "write";
const Icon = isLoading ? Loader2 : isWrite ? Sparkles : RefreshCw;
return (
<>
- <Button
- variant={isWrite ? "outline" : "ghost"}
- size="sm"
- onClick={onRegenerate}
- disabled={isLoading || isInProgress}
- className={cn(
- "h-7 gap-1.5 text-xs",
- isWrite &&
- "border-[var(--color-accent-primary)]/40 bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)] hover:bg-[var(--color-accent-muted)] hover:text-[var(--color-accent-hover)]",
- )}
- aria-label={isWrite ? "Write this page with AI" : "Regenerate this page"}
- >
- <Icon
+ {inline ? (
+ <button
+ type="button"
+ onClick={onRegenerate}
+ disabled={isLoading || isInProgress}
+ className="inline-flex items-center gap-1 rounded-full border border-[var(--color-accent-primary)]/40 bg-[var(--color-accent-muted)] px-2 py-0.5 text-[10px] font-medium uppercase tracking-wider text-[var(--color-accent-primary)] transition-colors hover:bg-[var(--color-accent-muted)] hover:text-[var(--color-accent-hover)] disabled:opacity-60"
+ aria-label={isWrite ? "Write this page with AI" : "Regenerate this page"}
+ >
+ <Icon className={cn("h-2.5 w-2.5", isLoading && "animate-spin")} />
+ {isWrite ? "Write with AI" : "Regenerate"}
+ </button>
+ ) : (
+ <Button
+ variant={isWrite ? "outline" : "ghost"}
+ size="sm"
+ onClick={onRegenerate}
+ disabled={isLoading || isInProgress}
className={cn(
- "h-3.5 w-3.5",
- isLoading && "animate-spin",
- isWrite && !isLoading && "text-[var(--color-accent-primary)]",
+ "h-7 gap-1.5 text-xs",
+ isWrite &&
+ "border-[var(--color-accent-primary)]/40 bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)] hover:bg-[var(--color-accent-muted)] hover:text-[var(--color-accent-hover)]",
)}
- />
- <span className="hidden sm:inline">
- {isWrite ? "Write with AI" : "Regenerate"}
- </span>
- </Button>
+ aria-label={isWrite ? "Write this page with AI" : "Regenerate this page"}
+ >
+ <Icon
+ className={cn(
+ "h-3.5 w-3.5",
+ isLoading && "animate-spin",
+ isWrite && !isLoading && "text-[var(--color-accent-primary)]",
+ )}
+ />
+ <span className="hidden sm:inline">
+ {isWrite ? "Write with AI" : "Regenerate"}
+ </span>
+ </Button>
+ )}
<Dialog
open={isInProgress}
@@ -92,11 +110,10 @@ export function RegenerateButton({
);
}
-const CASCADE_OPTIONS: {
- value: RegenerateCascade;
- label: string;
- hint: string;
-}[] = [
+type CascadeOption = { value: RegenerateCascade; label: string; hint: string };
+
+/** Cascade choices phrased for a single page (the reader upgrade). */
+const CASCADE_OPTIONS_PAGE: CascadeOption[] = [
{ value: "none", label: "Just this page", hint: "Fastest, cheapest." },
{
value: "dependents",
@@ -110,12 +127,38 @@ const CASCADE_OPTIONS: {
},
];
+/** Cascade choices phrased for a multi-page selection (bulk generation). */
+const CASCADE_OPTIONS_SELECTION: CascadeOption[] = [
+ { value: "none", label: "Just the selected pages", hint: "Fastest, cheapest." },
+ {
+ value: "dependents",
+ label: "Selected pages and their summaries",
+ hint: "Also refreshes the module, layer, and overview pages that cover them.",
+ },
+ {
+ value: "full",
+ label: "Selected pages and all repo-wide pages",
+ hint: "Refreshes every page that summarizes the codebase. Costs the most.",
+ },
+];
+
export interface GenerateConfirmDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
mode?: RegenerateMode;
- /** Page title, shown in the body for context. */
+ /** Page title, shown in the body for context (single-page flavour). */
pageTitle?: string;
+ /** Overrides the dialog title. Defaults to the mode's page-centric heading. */
+ title?: string;
+ /** Overrides the body sentence. Use for a bulk selection ("Write all 120
+ * template pages…"). When set, `pageTitle` is ignored. */
+ description?: ReactNode;
+ /** Overrides the confirm button label. Defaults to "Write with AI" /
+ * "Regenerate". */
+ confirmLabel?: string;
+ /** Phrasing of the cascade options: "page" (single-page reader upgrade) or
+ * "selection" (bulk generation). Defaults to "page". */
+ cascadeScope?: "page" | "selection";
cascade: RegenerateCascade;
onCascadeChange: (next: RegenerateCascade) => void;
/** Lazily-fetched estimate for the current cascade. `null` while unknown. */
@@ -143,6 +186,10 @@ export function GenerateConfirmDialog({
onOpenChange,
mode = "write",
pageTitle,
+ title,
+ description,
+ confirmLabel,
+ cascadeScope = "page",
cascade,
onCascadeChange,
estimate,
@@ -154,6 +201,10 @@ export function GenerateConfirmDialog({
launching = false,
}: GenerateConfirmDialogProps) {
const isWrite = mode === "write";
+ const cascadeOptions =
+ cascadeScope === "selection" ? CASCADE_OPTIONS_SELECTION : CASCADE_OPTIONS_PAGE;
+ const heading =
+ title ?? (isWrite ? "Write this page with AI" : "Regenerate this page");
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -163,7 +214,7 @@ export function GenerateConfirmDialog({
{isWrite && (
<Sparkles className="h-4 w-4 text-[var(--color-accent-primary)]" />
)}
- {isWrite ? "Write this page with AI" : "Regenerate this page"}
+ {heading}
</DialogTitle>
</DialogHeader>
@@ -186,21 +237,27 @@ export function GenerateConfirmDialog({
</div>
) : (
<div className="space-y-4">
- {pageTitle && (
+ {description ? (
<p className="text-sm text-[var(--color-text-secondary)]">
- {isWrite ? "Write" : "Regenerate"}{" "}
- <span className="font-medium text-[var(--color-text-primary)]">
- {pageTitle}
- </span>{" "}
- with your configured model.
+ {description}
</p>
+ ) : (
+ pageTitle && (
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ {isWrite ? "Write" : "Regenerate"}{" "}
+ <span className="font-medium text-[var(--color-text-primary)]">
+ {pageTitle}
+ </span>{" "}
+ with your configured model.
+ </p>
+ )
)}
<fieldset className="space-y-1.5">
<legend className="text-xs font-medium text-[var(--color-text-secondary)]">
What else to update
</legend>
- {CASCADE_OPTIONS.map((opt) => (
+ {cascadeOptions.map((opt) => (
<label
key={opt.value}
className={cn(
@@ -281,10 +338,10 @@ export function GenerateConfirmDialog({
) : isWrite ? (
<>
<Sparkles className="mr-1.5 h-3.5 w-3.5" />
- Write with AI
+ {confirmLabel ?? "Write with AI"}
</>
) : (
- "Regenerate"
+ confirmLabel ?? "Regenerate"
)}
</Button>
</div>
diff --git a/packages/web/src/app/repos/[id]/docs/coverage/page.tsx b/packages/web/src/app/repos/[id]/docs/coverage/page.tsx
index 3fb71eb6f..0bdde7ba9 100644
--- a/packages/web/src/app/repos/[id]/docs/coverage/page.tsx
+++ b/packages/web/src/app/repos/[id]/docs/coverage/page.tsx
@@ -6,7 +6,7 @@ import { ConfidenceVsFreshnessMatrix } from "@repowise-dev/ui/coverage/confidenc
import { FreshnessTableWithRegenerate } from "@/components/coverage/freshness-table-wrapper";
import type { DocPage } from "@repowise-dev/types/docs";
import { MetricCard } from "@repowise-dev/ui/shared/metric-card";
-import { listPages } from "@/lib/api/pages";
+import { listAllPages } from "@/lib/api/pages";
import { formatNumber } from "@repowise-dev/ui/lib/format";
export const metadata: Metadata = { title: "Doc freshness" };
@@ -18,10 +18,13 @@ export default async function CoveragePage({
}) {
const { id } = await params;
- let pages: Awaited<ReturnType<typeof listPages>> = [];
+ let pages: Awaited<ReturnType<typeof listAllPages>> = [];
try {
- pages = await listPages(id, { limit: 500 });
+ // Auto-paginate past the 500-item API cap so the counts, donut, and the
+ // "select all template pages" affordance see every page, not just the first
+ // page of results.
+ pages = await listAllPages(id);
} catch {
// API unavailable
}
@@ -100,7 +103,7 @@ export default async function CoveragePage({
<ConfidenceVsFreshnessMatrix pages={pages as DocPage[]} />
)}
- <FreshnessTableWithRegenerate pages={pages} />
+ <FreshnessTableWithRegenerate pages={pages} repoId={id} />
</div>
</div>
);
diff --git a/packages/web/src/app/repos/[id]/layout.tsx b/packages/web/src/app/repos/[id]/layout.tsx
index 2d0912350..f33493709 100644
--- a/packages/web/src/app/repos/[id]/layout.tsx
+++ b/packages/web/src/app/repos/[id]/layout.tsx
@@ -13,9 +13,11 @@ interface RepoLayoutProps {
export default async function RepoLayout({ children, params }: RepoLayoutProps) {
const { id } = await params;
let repoName = id;
+ let docsMode: "none" | "deterministic" | "llm" | null = null;
try {
const repo = await getRepo(id);
repoName = repo.name;
+ docsMode = repo.docs_mode ?? null;
} catch {
redirect("/");
}
@@ -23,7 +25,7 @@ export default async function RepoLayout({ children, params }: RepoLayoutProps)
<>
<ReindexHintBanner repoId={id} />
<ActiveJobBanner repoId={id} />
- <RepoBreadcrumb repoName={repoName} />
+ <RepoBreadcrumb repoName={repoName} docsMode={docsMode ?? "none"} />
<PageTransition>{children}</PageTransition>
</>
);
diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsx
index cd9df463b..1bb75ba16 100644
--- a/packages/web/src/app/repos/[id]/overview/page.tsx
+++ b/packages/web/src/app/repos/[id]/overview/page.tsx
@@ -143,6 +143,9 @@ export default async function OverviewPage({ params }: Props) {
modelName={providers?.active.model ?? sync.last_sync_model ?? ""}
lastSyncAt={sync.last_sync_at}
lastResyncAt={sync.last_resync_at}
+ // Offer the bulk "Write with AI" action only when template (auto)
+ // pages actually exist to upgrade.
+ docsMode={autoPages != null && autoPages > 0 ? "deterministic" : undefined}
/>
)}
diff --git a/packages/web/src/components/coverage/freshness-table-wrapper.tsx b/packages/web/src/components/coverage/freshness-table-wrapper.tsx
index 44c2280bc..78e427062 100644
--- a/packages/web/src/components/coverage/freshness-table-wrapper.tsx
+++ b/packages/web/src/components/coverage/freshness-table-wrapper.tsx
@@ -1,16 +1,156 @@
"use client";
+import { useCallback, useMemo, useState } from "react";
+import { useRouter } from "next/navigation";
+import { toast } from "sonner";
+import { Sparkles } from "lucide-react";
import {
FreshnessTable,
type FreshnessTableProps,
} from "@repowise-dev/ui/coverage/freshness-table";
+import { AutoDocsBanner } from "@repowise-dev/ui/docs/auto-docs-banner";
+import { isDeterministicPage } from "@repowise-dev/ui/lib/page-types";
+import { Button } from "@repowise-dev/ui/ui/button";
+import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
+import { GenerationProgressWrapper } from "@/components/jobs/generation-progress-wrapper";
+import { BulkGenerateConfirm } from "@/components/docs/bulk-generate-confirm";
+import { useBulkGenerate } from "@/lib/hooks/use-bulk-generate";
import { regeneratePage } from "@/lib/api/pages";
export function FreshnessTableWithRegenerate({
pages,
-}: Pick<FreshnessTableProps, "pages">) {
- const handleRegenerate = async (pageId: string) => {
- await regeneratePage(pageId);
- };
- return <FreshnessTable pages={pages} onRegenerate={handleRegenerate} />;
+ repoId,
+}: Pick<FreshnessTableProps, "pages"> & { repoId: string }) {
+ const router = useRouter();
+ const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
+ // A single active job — a per-row regenerate or a bulk write — shown above
+ // the table. On completion we revalidate the (server-rendered) page list.
+ const [activeJobId, setActiveJobId] = useState<string | null>(null);
+ const bulk = useBulkGenerate(repoId);
+
+ const templateCount = useMemo(
+ () => pages.filter((p) => isDeterministicPage(p)).length,
+ [pages],
+ );
+ const writtenCount = pages.length - templateCount;
+
+ const jobId = activeJobId ?? bulk.jobId;
+ // Only one job runs at a time (the server 409s a second), so refuse to launch
+ // another while one is in flight rather than orphaning its progress slot.
+ const busy = jobId != null;
+
+ const toggleSelect = useCallback((pageId: string) => {
+ setSelectedIds((prev) => {
+ const next = new Set(prev);
+ if (next.has(pageId)) next.delete(pageId);
+ else next.add(pageId);
+ return next;
+ });
+ }, []);
+
+ const selectTemplates = useCallback((ids: string[]) => {
+ setSelectedIds(new Set(ids));
+ }, []);
+
+ const clearSelection = useCallback(() => setSelectedIds(new Set()), []);
+
+ // Task 1.3: per-row regenerate now launches a tracked job with a toast and
+ // error handling, instead of firing and forgetting.
+ const handleRegenerate = useCallback(
+ async (pageId: string) => {
+ if (busy) {
+ toast.info("A generation job is already running. Wait for it to finish.");
+ return;
+ }
+ try {
+ const res = await regeneratePage(pageId, { cascade: "none" });
+ setActiveJobId(res.job_id);
+ toast.info("Regeneration started");
+ } catch (e) {
+ toast.error("Couldn't start regeneration", { description: toFriendlyMessage(e) });
+ }
+ },
+ [busy],
+ );
+
+ const selectedList = useMemo(() => [...selectedIds], [selectedIds]);
+
+ function writeSelected() {
+ if (busy || selectedList.length === 0) return;
+ const n = selectedList.length;
+ // Price on open (the confirm dialog), not live per checkbox — the estimate
+ // endpoint is heavy. The toolbar shows the count only.
+ bulk.begin(
+ { kind: "page_ids", page_ids: selectedList },
+ { label: `${n} selected ${n === 1 ? "page" : "pages"}`, defaultCascade: "none" },
+ );
+ }
+
+ function writeAllTemplates() {
+ if (busy || templateCount === 0) return;
+ bulk.begin(
+ { kind: "unwritten" },
+ {
+ label: "every page still generated from structure",
+ defaultCascade: "none",
+ },
+ );
+ }
+
+ const toolbar =
+ selectedIds.size > 0 ? (
+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-md border border-[var(--color-border-active)] bg-[var(--color-accent-muted)] px-3 py-2">
+ <span className="text-sm text-[var(--color-text-primary)]">
+ <span className="font-medium">{selectedIds.size}</span>{" "}
+ {selectedIds.size === 1 ? "page" : "pages"} selected
+ </span>
+ <Button
+ size="sm"
+ onClick={writeSelected}
+ disabled={busy}
+ className="h-7 gap-1.5 text-xs"
+ >
+ <Sparkles className="h-3.5 w-3.5" />
+ Write selected
+ </Button>
+ </div>
+ ) : null;
+
+ return (
+ <div className="space-y-3">
+ {templateCount > 0 && (
+ <AutoDocsBanner
+ templateCount={templateCount}
+ writtenCount={writtenCount}
+ onWriteAll={writeAllTemplates}
+ className="rounded-md border"
+ />
+ )}
+
+ {jobId && (
+ <GenerationProgressWrapper
+ jobId={jobId}
+ onDone={() => {
+ setActiveJobId(null);
+ bulk.clearJob();
+ clearSelection();
+ router.refresh();
+ }}
+ />
+ )}
+
+ <FreshnessTable
+ pages={pages}
+ onRegenerate={handleRegenerate}
+ selectable
+ selectedIds={selectedIds}
+ onToggleSelect={toggleSelect}
+ onSelectTemplates={selectTemplates}
+ onClearSelection={clearSelection}
+ toolbar={toolbar}
+ />
+
+ <BulkGenerateConfirm flow={bulk} repoId={repoId} title="Write selected pages with AI" />
+ </div>
+ );
}
diff --git a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx b/packages/web/src/components/dashboard/quick-actions-wrapper.tsx
index 2d41c4ce8..cb8c8c8ac 100644
--- a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx
+++ b/packages/web/src/components/dashboard/quick-actions-wrapper.tsx
@@ -1,16 +1,21 @@
"use client";
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import {
QuickActions as QuickActionsShell,
+ DEFAULT_QUICK_ACTIONS,
+ GENERATE_DOCS_ACTION,
type QuickActionKey,
} from "@repowise-dev/ui/dashboard/quick-actions";
import { syncRepo, fullResyncRepo } from "@/lib/api/repos";
import { listJobs } from "@/lib/api/jobs";
import { analyzeDeadCode } from "@/lib/api/dead-code";
import { GenerationProgressWrapper } from "@/components/jobs/generation-progress-wrapper";
+import { BulkGenerateConfirm } from "@/components/docs/bulk-generate-confirm";
+import { useBulkGenerate } from "@/lib/hooks/use-bulk-generate";
import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
+import type { RepoResponse } from "@/lib/api/types";
interface Props {
repoId: string;
@@ -19,6 +24,9 @@ interface Props {
modelName?: string;
lastSyncAt?: string | null;
lastResyncAt?: string | null;
+ /** When "deterministic" the repo still has template pages, so the "Write with
+ * AI" bulk action is offered. */
+ docsMode?: RepoResponse["docs_mode"];
}
export function QuickActionsWrapper({
@@ -28,8 +36,10 @@ export function QuickActionsWrapper({
modelName = "",
lastSyncAt,
lastResyncAt,
+ docsMode,
}: Props) {
const [activeJobId, setActiveJobId] = useState<string | null>(null);
+ const bulk = useBulkGenerate(repoId);
// Hydrate from any in-flight job so refreshes don't lose progress visibility.
useEffect(() => {
@@ -52,7 +62,22 @@ export function QuickActionsWrapper({
};
}, [repoId]);
+ const actions = useMemo(
+ () =>
+ docsMode === "deterministic"
+ ? [GENERATE_DOCS_ACTION, ...DEFAULT_QUICK_ACTIONS]
+ : DEFAULT_QUICK_ACTIONS,
+ [docsMode],
+ );
+
async function handleAction(key: QuickActionKey) {
+ if (key === "generate-docs") {
+ bulk.begin(
+ { kind: "unwritten" },
+ { label: "every page still generated from structure", defaultCascade: "none" },
+ );
+ return;
+ }
try {
if (key === "sync") {
const job = await syncRepo(repoId);
@@ -91,22 +116,31 @@ export function QuickActionsWrapper({
}
}
- const activeSlot = activeJobId ? (
+ // A bulk generate job shares the same progress slot as sync/resync.
+ const jobId = activeJobId ?? bulk.jobId;
+ const activeSlot = jobId ? (
<GenerationProgressWrapper
- jobId={activeJobId}
+ jobId={jobId}
repoName={repoName}
- onDone={() => setActiveJobId(null)}
+ onDone={() => {
+ setActiveJobId(null);
+ bulk.clearJob();
+ }}
/>
) : null;
return (
- <QuickActionsShell
- onAction={handleAction}
- lastSyncAt={lastSyncAt}
- lastResyncAt={lastResyncAt}
- pageCount={pageCount}
- modelName={modelName}
- activeJobSlot={activeSlot}
- />
+ <>
+ <QuickActionsShell
+ actions={actions}
+ onAction={handleAction}
+ lastSyncAt={lastSyncAt}
+ lastResyncAt={lastResyncAt}
+ pageCount={pageCount}
+ modelName={modelName}
+ activeJobSlot={activeSlot}
+ />
+ <BulkGenerateConfirm flow={bulk} repoId={repoId} />
+ </>
);
}
diff --git a/packages/web/src/components/docs/bulk-generate-confirm.tsx b/packages/web/src/components/docs/bulk-generate-confirm.tsx
new file mode 100644
index 000000000..bad817883
--- /dev/null
+++ b/packages/web/src/components/docs/bulk-generate-confirm.tsx
@@ -0,0 +1,61 @@
+"use client";
+
+import { GenerateConfirmDialog } from "@repowise-dev/ui/wiki/regenerate-button";
+import { formatEstimateCost } from "@/lib/generate-format";
+import type { useBulkGenerate } from "@/lib/hooks/use-bulk-generate";
+
+/**
+ * Maps a `useBulkGenerate` flow onto the shared, presentational
+ * `GenerateConfirmDialog` (selection-scoped cascade wording). Kept tiny so the
+ * quick action, banner, and coverage toolbar reuse one mapping.
+ */
+export function BulkGenerateConfirm({
+ flow,
+ repoId,
+ title,
+}: {
+ flow: ReturnType<typeof useBulkGenerate>;
+ repoId: string;
+ /** Dialog title, e.g. "Write documentation with AI". */
+ title?: string;
+}) {
+ const { estimate, noProvider, label } = flow;
+ const pages = estimate?.total_pages ?? 0;
+
+ return (
+ <GenerateConfirmDialog
+ open={flow.confirmOpen}
+ onOpenChange={flow.setConfirmOpen}
+ mode="write"
+ title={title ?? "Write documentation with AI"}
+ cascadeScope="selection"
+ description={
+ <>
+ Write{" "}
+ <span className="font-medium text-[var(--color-text-primary)]">
+ {label ?? "the selected pages"}
+ </span>{" "}
+ with your configured model.
+ </>
+ }
+ confirmLabel={pages > 0 ? `Write ${pages} ${pages === 1 ? "page" : "pages"}` : "Write with AI"}
+ cascade={flow.cascade}
+ onCascadeChange={flow.changeCascade}
+ estimate={
+ estimate && !noProvider
+ ? {
+ totalPages: estimate.total_pages,
+ costText: formatEstimateCost(estimate.estimate),
+ staleCount: estimate.pages_to_mark_stale,
+ }
+ : null
+ }
+ estimateLoading={flow.estimateLoading}
+ estimateError={flow.estimateError}
+ noProvider={noProvider}
+ settingsHref={`/repos/${repoId}/settings#provider`}
+ onConfirm={flow.confirm}
+ launching={flow.launching}
+ />
+ );
+}
diff --git a/packages/web/src/components/docs/docs-explorer.tsx b/packages/web/src/components/docs/docs-explorer.tsx
index fc5d851ea..30fca7bd3 100644
--- a/packages/web/src/components/docs/docs-explorer.tsx
+++ b/packages/web/src/components/docs/docs-explorer.tsx
@@ -258,6 +258,7 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {
onSelectPage={handleSelectPage}
persona={persona}
sidebarOpen={sidebarOpen}
+ onGenerated={handleGenerated}
/>
</div>
</div>
diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsx
index 6fb4c4442..317a32186 100644
--- a/packages/web/src/components/docs/docs-viewer.tsx
+++ b/packages/web/src/components/docs/docs-viewer.tsx
@@ -15,6 +15,8 @@ import { cn } from "@/lib/utils/cn";
import { getGitMetadata } from "@/lib/api/git";
import { summarizeFixHistory } from "@repowise-dev/ui/lib/fix-history";
import { DocsReader } from "@repowise-dev/ui/docs/docs-reader";
+import { isDeterministicPage } from "@repowise-dev/ui/lib/page-types";
+import { PageGenerateButton } from "./page-generate-button";
import { Badge } from "@repowise-dev/ui/ui/badge";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
import { VersionHistoryWrapper } from "@/components/wiki/version-history";
@@ -273,6 +275,8 @@ interface DocsViewerProps {
onSelectPage?: (page: PageResponse) => void;
persona: ReaderPersona;
sidebarOpen: boolean;
+ /** Called once an inline page upgrade completes so the host refreshes. */
+ onGenerated?: () => void;
}
/**
@@ -289,6 +293,7 @@ export function DocsViewer({
onSelectPage,
persona,
sidebarOpen,
+ onGenerated,
}: DocsViewerProps) {
const buildPageHref = useCallback(
(pageId: string) =>
@@ -326,6 +331,16 @@ export function DocsViewer({
sidebarOpen={sidebarOpen}
buildPageHref={buildPageHref}
LinkComponent={Link}
+ upgradeSlot={
+ page && isDeterministicPage(page) ? (
+ <PageGenerateButton
+ page={page}
+ repoId={repoId}
+ onGenerated={onGenerated}
+ variant="inline"
+ />
+ ) : undefined
+ }
versionHistorySlot={
page ? (
<VersionHistoryWrapper
diff --git a/packages/web/src/components/docs/page-generate-button.tsx b/packages/web/src/components/docs/page-generate-button.tsx
index d649965fc..31459905e 100644
--- a/packages/web/src/components/docs/page-generate-button.tsx
+++ b/packages/web/src/components/docs/page-generate-button.tsx
@@ -11,18 +11,9 @@ import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
import { GenerationProgressWrapper } from "@/components/jobs/generation-progress-wrapper";
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";
-/** Format the estimate's cost range into a compact string. */
-function formatCost(est: GenerateEstimate["estimate"]): string | null {
- if (!est) return null;
- const fmt = (n: number) => `$${n < 0.01 ? n.toFixed(4) : n.toFixed(2)}`;
- if (est.cost_low_usd != null && est.cost_high_usd != null) {
- return `${fmt(est.cost_low_usd)} to ${fmt(est.cost_high_usd)}`;
- }
- return fmt(est.estimated_cost_usd);
-}
-
/**
* Reader-side "Write with AI" / "Regenerate" for a single page. Owns the
* lazily-fetched cost estimate, the cascade choice, the launch, and the live
@@ -32,11 +23,15 @@ export function PageGenerateButton({
page,
repoId,
onGenerated,
+ variant = "button",
}: {
page: PageResponse;
repoId: string;
/** Called once a run completes so the host can refresh the page list. */
onGenerated?: () => void;
+ /** "button" is the header toolbar affordance; "inline" is the compact,
+ * link-like entry point rendered beside the provenance pill in the reader. */
+ variant?: "button" | "inline";
}) {
const mode = page.is_deterministic ? "write" : "regenerate";
const settingsHref = `/repos/${repoId}/settings#provider`;
@@ -118,6 +113,7 @@ export function PageGenerateButton({
<>
<RegenerateButton
mode={mode}
+ inline={variant === "inline"}
onRegenerate={openConfirm}
isLoading={launching && !jobId}
isInProgress={jobId != null}
@@ -143,7 +139,7 @@ export function PageGenerateButton({
estimate && !noProvider
? {
totalPages: estimate.total_pages,
- costText: formatCost(estimate.estimate),
+ costText: formatEstimateCost(estimate.estimate),
staleCount: estimate.pages_to_mark_stale,
}
: null
diff --git a/packages/web/src/components/layout/repo-breadcrumb.tsx b/packages/web/src/components/layout/repo-breadcrumb.tsx
index 5fb6c5367..673a418e7 100644
--- a/packages/web/src/components/layout/repo-breadcrumb.tsx
+++ b/packages/web/src/components/layout/repo-breadcrumb.tsx
@@ -4,9 +4,17 @@ import Link from "next/link";
import { usePathname } from "next/navigation";
import { Breadcrumb } from "@repowise-dev/ui/shared/breadcrumb";
import type { BreadcrumbSegment } from "@repowise-dev/ui/shared/breadcrumb";
+import { DocsModeBadge, type DocsMode } from "@repowise-dev/ui/docs/docs-mode-badge";
import { getRepoBreadcrumbSegmentLabel } from "./repo-breadcrumb-label";
-export function RepoBreadcrumb({ repoName }: { repoName: string }) {
+export function RepoBreadcrumb({
+ repoName,
+ docsMode = "none",
+}: {
+ repoName: string;
+ /** Provenance of the repo's wiki, from the repos API `docs_mode`. */
+ docsMode?: DocsMode;
+}) {
const pathname = usePathname();
const match = pathname.match(/^\/repos\/([^/]+)(.*)/);
if (!match) return null;
@@ -28,11 +36,15 @@ export function RepoBreadcrumb({ repoName }: { repoName: string }) {
});
}
- if (segments.length <= 2) return null;
+ const showCrumbs = segments.length > 2;
+ const showBadge = docsMode !== "none";
+ // Nothing to show at the repo root with no docs — stay out of the way.
+ if (!showCrumbs && !showBadge) return null;
return (
- <div className="px-4 sm:px-6 py-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
- <Breadcrumb segments={segments} LinkComponent={Link} />
+ <div className="flex items-center justify-between gap-3 px-4 sm:px-6 py-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
+ {showCrumbs ? <Breadcrumb segments={segments} LinkComponent={Link} /> : <span />}
+ {showBadge && <DocsModeBadge mode={docsMode} />}
</div>
);
}
diff --git a/packages/web/src/lib/generate-format.ts b/packages/web/src/lib/generate-format.ts
new file mode 100644
index 000000000..ca084337f
--- /dev/null
+++ b/packages/web/src/lib/generate-format.ts
@@ -0,0 +1,12 @@
+import type { GenerateEstimate } from "@/lib/api/types";
+
+/** Format a generate estimate's cost range into a compact string, or null when
+ * no cost is priced (no provider). Shared by the reader and bulk flows. */
+export function formatEstimateCost(est: GenerateEstimate["estimate"]): string | null {
+ if (!est) return null;
+ const fmt = (n: number) => `$${n < 0.01 ? n.toFixed(4) : n.toFixed(2)}`;
+ if (est.cost_low_usd != null && est.cost_high_usd != null) {
+ return `${fmt(est.cost_low_usd)} to ${fmt(est.cost_high_usd)}`;
+ }
+ return fmt(est.estimated_cost_usd);
+}
diff --git a/packages/web/src/lib/hooks/use-bulk-generate.ts b/packages/web/src/lib/hooks/use-bulk-generate.ts
new file mode 100644
index 000000000..309aa9b96
--- /dev/null
+++ b/packages/web/src/lib/hooks/use-bulk-generate.ts
@@ -0,0 +1,140 @@
+"use client";
+
+import { useCallback, useRef, useState } from "react";
+import { toast } from "sonner";
+import type { RegenerateCascade } from "@repowise-dev/ui/wiki/regenerate-button";
+import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
+import { generateEstimate, generatePages } from "@/lib/api/repos";
+import type { GenerateEstimate, GenerateSelection } from "@/lib/api/types";
+
+/**
+ * The bulk "Write with AI" flow, shared by the dashboard quick action, the
+ * auto-docs banner, and the coverage "Write selected" action. Owns the
+ * lazily-fetched, per-cascade cached `/generate/estimate` (heavy, so never per
+ * render), the launch, and the active job id. The shared `GenerateConfirmDialog`
+ * and `GenerationProgressWrapper` stay presentational; the caller maps this
+ * state onto them and renders progress wherever it fits.
+ */
+export function useBulkGenerate(repoId: string) {
+ const [selection, setSelection] = useState<GenerateSelection | null>(null);
+ const [label, setLabel] = useState<string | undefined>(undefined);
+ 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 [jobId, setJobId] = useState<string | null>(null);
+
+ // Estimate cache keyed by cascade so toggling the choice back doesn't refetch
+ // the heavy endpoint. Cleared on each new `begin`, since the selection (and
+ // thus the estimate) changes.
+ const cacheRef = useRef<Map<RegenerateCascade, GenerateEstimate>>(new Map());
+ const wantedCascadeRef = useRef<RegenerateCascade>("none");
+ const selectionRef = useRef<GenerateSelection | null>(null);
+ // A monotonic token bumped on each `begin`. Latest-wins keys on BOTH the
+ // token and the cascade, so a late estimate for a since-abandoned selection
+ // (not just a since-abandoned cascade) can never write into the current
+ // dialog or its freshly-cleared cache.
+ const requestRef = useRef(0);
+
+ const fetchEstimate = useCallback(
+ async (which: RegenerateCascade) => {
+ const sel = selectionRef.current;
+ if (!sel) return;
+ const token = requestRef.current;
+ wantedCascadeRef.current = which;
+ const cached = cacheRef.current.get(which);
+ if (cached) {
+ setEstimate(cached);
+ setEstimateError(null);
+ return;
+ }
+ setEstimateLoading(true);
+ setEstimateError(null);
+ const current = () =>
+ requestRef.current === token && wantedCascadeRef.current === which;
+ try {
+ const res = await generateEstimate(repoId, { selection: sel, cascade: which });
+ if (requestRef.current !== token) return;
+ cacheRef.current.set(which, res);
+ if (current()) setEstimate(res);
+ } catch (e) {
+ if (current()) {
+ setEstimateError(toFriendlyMessage(e));
+ setEstimate(null);
+ }
+ } finally {
+ if (current()) setEstimateLoading(false);
+ }
+ },
+ [repoId],
+ );
+
+ /** Open the confirm dialog for a selection. The estimate is fetched lazily
+ * here (once, on open) and re-priced per cascade choice — never live as a
+ * selection is built, since the endpoint is heavy. */
+ const begin = useCallback(
+ (
+ sel: GenerateSelection,
+ opts?: { label?: string; defaultCascade?: RegenerateCascade },
+ ) => {
+ const startCascade = opts?.defaultCascade ?? "none";
+ requestRef.current += 1;
+ cacheRef.current.clear();
+ selectionRef.current = sel;
+ setSelection(sel);
+ setLabel(opts?.label);
+ setCascade(startCascade);
+ setEstimateError(null);
+ setEstimate(null);
+ void fetchEstimate(startCascade);
+ setConfirmOpen(true);
+ },
+ [fetchEstimate],
+ );
+
+ const changeCascade = useCallback(
+ (next: RegenerateCascade) => {
+ setCascade(next);
+ void fetchEstimate(next);
+ },
+ [fetchEstimate],
+ );
+
+ const confirm = useCallback(async () => {
+ if (!selection) return;
+ setLaunching(true);
+ try {
+ const res = await generatePages(repoId, { selection, cascade });
+ setJobId(res.job_id);
+ setConfirmOpen(false);
+ } catch (e) {
+ toast.error("Couldn't start generation", { description: toFriendlyMessage(e) });
+ } finally {
+ setLaunching(false);
+ }
+ }, [repoId, selection, cascade]);
+
+ const clearJob = useCallback(() => setJobId(null), []);
+
+ const noProvider = !!estimate && estimate.provider.name == null;
+
+ return {
+ selection,
+ label,
+ confirmOpen,
+ setConfirmOpen,
+ cascade,
+ changeCascade,
+ estimate,
+ estimateLoading,
+ estimateError,
+ noProvider,
+ launching,
+ jobId,
+ begin,
+ confirm,
+ clearJob,
+ };
+}