Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(web): add-repo wizard with cost preflight and a live first-index experience (#692)
Raghav Chamadiya1357d33d87d6
diff --git a/packages/api-client/src/client.ts b/packages/api-client/src/client.tsindex d2fc76317..a4e426d42 100644--- a/packages/api-client/src/client.ts+++ b/packages/api-client/src/client.ts@@ -62,12 +62,30 @@ export class ApiClientError extends Error {}}+/** Flatten a FastAPI error `detail` into a readable string. Plain strings+ * pass through; 422 validation errors arrive as a list of objects whose+ * useful text lives in `msg`. */+function stringifyDetail(detail: unknown): string | null {+ if (typeof detail === "string") return detail;+ if (Array.isArray(detail)) {+ const msgs = detail+ .map((d) =>+ d && typeof d === "object" && "msg" in d ? String((d as { msg: unknown }).msg) : null,+ )+ .filter((m): m is string => !!m)+ // Pydantic prefixes custom validator messages with "Value error, ".+ .map((m) => m.replace(/^Value error, /, ""));+ if (msgs.length > 0) return msgs.join("; ");+ }+ return null;+}+async function handleResponse<T>(res: Response): Promise<T> {if (!res.ok) {let detail = res.statusText;try {const json = (await res.json()) as ApiError;- detail = json.detail ?? detail;+ detail = stringifyDetail(json.detail) ?? detail;} catch {// response body is not JSON}diff --git a/packages/api-client/src/dead-code.ts b/packages/api-client/src/dead-code.tsindex 4990e927d..c3980456a 100644--- a/packages/api-client/src/dead-code.ts+++ b/packages/api-client/src/dead-code.ts@@ -18,8 +18,13 @@ export async function listDeadCode(return apiGet<DeadCodeFindingResponse[]>(`/api/repos/${repoId}/dead-code`, opts);}-export async function analyzeDeadCode(repoId: string): Promise<{ job_id: string }> {- return apiPost<{ job_id: string }>(`/api/repos/${repoId}/dead-code/analyze`);+/** Launch an index-only refresh job (no LLM spend). 409 when a job is active. */+export async function analyzeDeadCode(+ repoId: string,+): Promise<{ job_id: string; status: string }> {+ return apiPost<{ job_id: string; status: string }>(+ `/api/repos/${repoId}/dead-code/analyze`,+ );}export async function getDeadCodeSummary(repoId: string): Promise<DeadCodeSummaryResponse> {diff --git a/packages/api-client/src/jobs.ts b/packages/api-client/src/jobs.tsindex f28477286..6fd96fd91 100644--- a/packages/api-client/src/jobs.ts+++ b/packages/api-client/src/jobs.ts@@ -14,8 +14,8 @@ export async function getJob(jobId: string): Promise<JobResponse> {return apiGet<JobResponse>(`/api/jobs/${jobId}`);}-/** Cancel a pending or running job. Marks it failed so the active-job- * guard releases and a new sync can be started. */+/** Cancel a pending or running job. Actually stops the pipeline and marks+ * the job `cancelled`, releasing the active-job guard. */export async function cancelJob(jobId: string): Promise<JobResponse> {return apiPost<JobResponse>(`/api/jobs/${jobId}/cancel`);}diff --git a/packages/api-client/src/repos.ts b/packages/api-client/src/repos.tsindex a0d3c0382..9708e900b 100644--- a/packages/api-client/src/repos.ts+++ b/packages/api-client/src/repos.ts@@ -1,5 +1,12 @@import { apiGet, apiPost, apiPatch, apiDelete } from "./client";-import type { RepoCreate, RepoUpdate, RepoResponse, JobResponse, RepoStatsResponse } from "./types";+import type {+ RepoCreate,+ RepoUpdate,+ RepoResponse,+ JobResponse,+ RepoStatsResponse,+ PreflightResponse,+} from "./types";export async function listRepos(): Promise<RepoResponse[]> {return apiGet<RepoResponse[]>("/api/repos");@@ -25,6 +32,27 @@ export async function fullResyncRepo(repoId: string): Promise<JobResponse> {return apiPost<JobResponse>(`/api/repos/${repoId}/full-resync`);}+/** Start the first full index (docs included) for a registered repo.+ * Returns 409 when a job is already active for it. */+export async function startIndexJob(+ repoId: string,+): Promise<{ job_id: string; status: string }> {+ return apiPost<{ job_id: string; status: string }>(`/api/repos/${repoId}/index`);+}++/** Provider connectivity smoke test + page/cost estimate for a first index. */+export async function preflightIndex(+ repoId: string,+ coveragePct?: number,+): Promise<PreflightResponse> {+ return apiPost<PreflightResponse>(+ `/api/repos/${repoId}/preflight`,+ undefined,+ undefined,+ coveragePct !== undefined ? { coverage_pct: coveragePct } : undefined,+ );+}+export async function deleteRepo(repoId: string): Promise<{ ok: boolean; deleted_pages: number }> {return apiDelete<{ ok: boolean; deleted_pages: number }>(`/api/repos/${repoId}`);}diff --git a/packages/api-client/src/types/pages.ts b/packages/api-client/src/types/pages.tsindex 09003573d..29b1465e7 100644--- a/packages/api-client/src/types/pages.ts+++ b/packages/api-client/src/types/pages.ts@@ -53,7 +53,7 @@ export interface PageListResponse {export interface JobResponse {id: string;repository_id: string;- status: "pending" | "running" | "completed" | "failed" | "paused";+ status: "pending" | "running" | "completed" | "failed" | "cancelled" | "paused";provider_name: string;model_name: string;total_pages: number;@@ -71,15 +71,27 @@ export interface JobResponse {export interface JobProgressEvent {event: "progress" | "done" | "error";job_id: string;- status?: "pending" | "running" | "completed" | "failed" | "paused";+ status?: "pending" | "running" | "completed" | "failed" | "cancelled" | "paused";completed_pages: number;total_pages: number;failed_pages?: number;current_page?: string;current_level?: number;+ /** Human phase label ("Parsing files", "Generating docs") from the pipeline. */+ phase?: string;tokens_input?: number;tokens_output?: number;estimated_cost?: number;actual_cost_usd?: number | null;+ error_message?: string | null;error?: string;}++/** An `event: message` frame on the job SSE stream: one pipeline log line. */+export interface JobMessageEvent {+ seq: number;+ ts: number;+ level: string;+ text: string;+ phase: string;+}diff --git a/packages/api-client/src/types/repository.ts b/packages/api-client/src/types/repository.tsindex 0ebf5a651..bd47231af 100644--- a/packages/api-client/src/types/repository.ts+++ b/packages/api-client/src/types/repository.ts@@ -8,6 +8,10 @@ export interface RepoCreate {url?: string;default_branch?: string;settings?: Record<string, unknown>;+ /** Enqueue the first full index immediately (server default: true).+ * Pass false to register metadata only, e.g. to run a preflight check+ * before committing to generation spend. */+ index?: boolean;}export interface RepoUpdate {@@ -30,12 +34,43 @@ export interface RepoResponse {settings: Record<string, unknown>;created_at: string;updated_at: string;- // Workspace mode (optional — only populated when the server runs in- // workspace mode). Unindexed repos appear as synthetic rows with- // `id="ws:<alias>"` and `workspace_status === "needs_index"`.+ // Workspace metadata (populated in workspace mode). Unindexed workspace+ // repos appear as synthetic rows with `id="ws:<alias>"`. `workspace_status`+ // is also set to "needs_index" for plain registered-but-never-indexed+ // repos in any mode (no repo-local store yet).workspace_alias?: string | null;workspace_status?: "indexed" | "needs_index" | "missing_dir" | null;is_primary?: boolean | null;docs_enabled?: boolean | null;docs_skip_reason?: string | null;+ /** Set on POST /api/repos responses when the create enqueued the first+ * index; attach to /api/jobs/{id}/stream with it. */+ initial_job_id?: string | null;+}++// ---------------------------------------------------------------------------+// Index preflight+// ---------------------------------------------------------------------------++export interface PreflightEstimate {+ total_pages: number;+ estimated_cost_usd: number;+ cost_low_usd: number | null;+ cost_high_usd: number | null;+ estimated_input_tokens: number;+ estimated_output_tokens: number;+ is_calibrated: boolean;+ coverage_pct: number;+}++export interface PreflightResponse {+ provider: {+ ok: boolean;+ name: string | null;+ model: string | null;+ error: string | null;+ };+ file_count: number;+ /** Null when no provider is configured (index-only runs still work). */+ estimate: PreflightEstimate | null;}diff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.pyindex c6d29b3ab..964791608 100644--- a/packages/server/src/repowise/server/routers/chat.py+++ b/packages/server/src/repowise/server/routers/chat.py@@ -355,7 +355,9 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):event_stream(),media_type="text/event-stream",headers={- "Cache-Control": "no-cache",+ # no-transform keeps the Next.js rewrite proxy's compression+ # middleware from gzip-buffering the stream (see jobs stream).+ "Cache-Control": "no-cache, no-transform","X-Accel-Buffering": "no","Connection": "keep-alive",},diff --git a/packages/server/src/repowise/server/routers/jobs.py b/packages/server/src/repowise/server/routers/jobs.pyindex 1b496588d..0291b78d3 100644--- a/packages/server/src/repowise/server/routers/jobs.py+++ b/packages/server/src/repowise/server/routers/jobs.py@@ -232,5 +232,8 @@ async def stream_job(job_id: str, request: Request) -> StreamingResponse:return StreamingResponse(event_generator(),media_type="text/event-stream",- headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},+ # no-transform matters: the web app fronts this API through a Next.js+ # rewrite whose compression middleware would otherwise gzip-buffer the+ # stream, so no event ever reaches the browser until the job ends.+ headers={"Cache-Control": "no-cache, no-transform", "X-Accel-Buffering": "no"},)diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.pyindex b4edd0205..225ca675e 100644--- a/packages/server/src/repowise/server/routers/repos.py+++ b/packages/server/src/repowise/server/routers/repos.py@@ -187,6 +187,21 @@ async def list_repos(if resp.local_path:resp.head_commit = resolve_indexed_commit(resp.head_commit, resp.local_path)+ # Flag registered-but-never-indexed repos. head_commit can't signal this+ # (registration stamps it from the live git HEAD), so the honest check is+ # the repo-local store: since the initial-index path always establishes+ # <repo>/.repowise/wiki.db, its absence means the first index hasn't run.+ # Reuses the workspace "needs_index" contract the sidebar already renders.+ from pathlib import Path as _Path++ for resp in responses:+ if resp.workspace_status is None and resp.local_path:+ try:+ if not (_Path(resp.local_path) / ".repowise" / "wiki.db").is_file():+ resp.workspace_status = "needs_index"+ except OSError:+ pass+# Augment with workspace metadata. We do this in a second pass (rather# than during from_orm) because the workspace context lives on# app.state, not on the Repository row.@@ -523,12 +538,23 @@ async def index_repo(if repo is None:raise HTTPException(status_code=404, detail="Repository not found")+ # Carry settings (e.g. a wiki_style chosen at registration) into the+ # repo-local row this call may be creating; an existing row is never+ # clobbered by registration.+ import json as _json++ try:+ settings = _json.loads(repo.settings_json) or None+ except (TypeError, ValueError):+ settings = None+factory, canonical_id = await ensure_repo_registration(request.app.state,local_path=repo.local_path,name=repo.name,url=repo.url,default_branch=repo.default_branch,+ settings=settings,repo_id=repo.id,)job_id = await _enqueue_index_job(request, factory, canonical_id)diff --git a/packages/types/src/jobs.ts b/packages/types/src/jobs.tsindex a78ea21a7..5745220a9 100644--- a/packages/types/src/jobs.ts+++ b/packages/types/src/jobs.ts@@ -6,7 +6,13 @@* family. Hosted-side hooks resolve and forward into these contracts.*/-export type JobStatus = "pending" | "running" | "completed" | "failed" | "paused";+export type JobStatus =+ | "pending"+ | "running"+ | "completed"+ | "failed"+ | "cancelled"+ | "paused";export interface Job {id: string;diff --git a/packages/ui/__tests__/jobs/generation-progress.test.tsx b/packages/ui/__tests__/jobs/generation-progress.test.tsxindex 4fdfc30ca..9a87046ee 100644--- a/packages/ui/__tests__/jobs/generation-progress.test.tsx+++ b/packages/ui/__tests__/jobs/generation-progress.test.tsx@@ -1,5 +1,5 @@import { describe, it, expect, vi } from "vitest";-import { render, screen } from "@testing-library/react";+import { render, screen, fireEvent } from "@testing-library/react";import { GenerationProgress } from "../../src/jobs/generation-progress.js";describe("GenerationProgress", () => {@@ -64,4 +64,101 @@ describe("GenerationProgress", () => {expect(screen.getByText("Analysing…")).toBeTruthy();expect(screen.queryByText(/Generating level/)).toBeNull();});++ it("prefers the live SSE phase label over the level-derived one", () => {+ render(+ <GenerationProgress+ job={{+ id: "j1",+ status: "running",+ total_pages: 10,+ completed_pages: 3,+ current_level: 1,+ }}+ log={[]}+ elapsed={10_000}+ actualCost={null}+ stuckPending={false}+ cancelling={false}+ onCancel={vi.fn()}+ phase="Parsing files"+ />,+ );+ expect(screen.getByText("Parsing files…")).toBeTruthy();+ expect(screen.queryByText("Analysing…")).toBeNull();+ });++ it("renders the cancelled state distinctly from failed, with a restart action", () => {+ const onRetry = vi.fn();+ render(+ <GenerationProgress+ job={{+ id: "j1",+ status: "cancelled",+ total_pages: 10,+ completed_pages: 4,+ }}+ log={[]}+ elapsed={10_000}+ actualCost={null}+ stuckPending={false}+ cancelling={false}+ onCancel={vi.fn()}+ onRetry={onRetry}+ />,+ );+ expect(screen.getByText("Cancelled")).toBeTruthy();+ expect(screen.queryByText(/Generation failed/)).toBeNull();+ const restart = screen.getByRole("button", { name: /Start again/ });+ fireEvent.click(restart);+ expect(onRetry).toHaveBeenCalled();+ });++ it("offers retry and provider settings recovery on failure", () => {+ render(+ <GenerationProgress+ job={{+ id: "j1",+ status: "failed",+ total_pages: 10,+ completed_pages: 4,+ error_message: "provider auth failed",+ }}+ log={[]}+ elapsed={10_000}+ actualCost={null}+ stuckPending={false}+ cancelling={false}+ onCancel={vi.fn()}+ onRetry={vi.fn()}+ settingsHref="/settings"+ />,+ );+ expect(screen.getByText("provider auth failed")).toBeTruthy();+ expect(screen.getByRole("button", { name: /Retry/ })).toBeTruthy();+ expect(screen.getByRole("link", { name: /Provider settings/ })).toBeTruthy();+ });++ it("tints warning log lines", () => {+ // jsdom has no scrollIntoView; the JobLog autoscroll calls it on mount.+ window.HTMLElement.prototype.scrollIntoView = vi.fn();+ render(+ <GenerationProgress+ job={{+ id: "j1",+ status: "running",+ total_pages: 10,+ completed_pages: 3,+ }}+ log={[{ text: "3 files skipped: encoding error", level: "warning" }]}+ elapsed={10_000}+ actualCost={null}+ stuckPending={false}+ cancelling={false}+ onCancel={vi.fn()}+ />,+ );+ const line = screen.getByText(/files skipped/).closest("div");+ expect(line?.className).toContain("--color-warning");+ });});diff --git a/packages/ui/__tests__/onboarding/add-repo-wizard.test.tsx b/packages/ui/__tests__/onboarding/add-repo-wizard.test.tsxnew file mode 100644index 000000000..be4e84707--- /dev/null+++ b/packages/ui/__tests__/onboarding/add-repo-wizard.test.tsx@@ -0,0 +1,124 @@+import { describe, it, expect, vi } from "vitest";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";+import {+ AddRepoWizard,+ type AddRepoWizardAdapter,+ type AddRepoPreflightResult,+} from "../../src/onboarding/add-repo-wizard.js";++function makePreflight(overrides?: Partial<AddRepoPreflightResult>): AddRepoPreflightResult {+ return {+ provider: { ok: true, name: "gemini", model: "gemini-flash", error: null },+ file_count: 120,+ estimate: {+ total_pages: 40,+ estimated_cost_usd: 0.8,+ cost_low_usd: 0.5,+ cost_high_usd: 1.2,+ is_calibrated: false,+ },+ ...overrides,+ };+}++function makeAdapter(overrides?: Partial<AddRepoWizardAdapter>): AddRepoWizardAdapter {+ return {+ createRepo: vi.fn().mockResolvedValue({ id: "r1", name: "demo" }),+ preflight: vi.fn().mockResolvedValue(makePreflight()),+ startIndex: vi.fn().mockResolvedValue({ job_id: "job-1" }),+ onDone: vi.fn(),+ settingsHref: "/settings",+ ...overrides,+ };+}++async function fillAndSubmitDetails() {+ fireEvent.change(screen.getByLabelText("Name"), { target: { value: "demo" } });+ fireEvent.change(screen.getByLabelText("Local Path"), {+ target: { value: "C:\\repos\\demo" },+ });+ fireEvent.click(screen.getByRole("button", { name: /Continue/ }));+}++describe("AddRepoWizard", () => {+ it("registers without indexing, then auto-starts when the estimate clears the cost gate", async () => {+ const adapter = makeAdapter();+ render(<AddRepoWizard adapter={adapter} open onOpenChange={vi.fn()} />);++ await fillAndSubmitDetails();++ await waitFor(() => expect(adapter.onDone).toHaveBeenCalledWith("r1", "job-1"));+ expect(adapter.createRepo).toHaveBeenCalledWith(+ expect.objectContaining({ name: "demo", local_path: "C:\\repos\\demo" }),+ );+ expect(adapter.preflight).toHaveBeenCalledWith("r1");+ expect(adapter.startIndex).toHaveBeenCalledWith("r1");+ });++ it("stops for explicit confirmation above the cost gate", async () => {+ const adapter = makeAdapter({+ preflight: vi.fn().mockResolvedValue(+ makePreflight({+ estimate: {+ total_pages: 900,+ estimated_cost_usd: 7.4,+ cost_low_usd: 5.0,+ cost_high_usd: 11.0,+ is_calibrated: true,+ },+ }),+ ),+ });+ render(<AddRepoWizard adapter={adapter} open onOpenChange={vi.fn()} />);++ await fillAndSubmitDetails();++ expect(await screen.findByText(/Estimated generation cost/)).toBeTruthy();+ expect(screen.getByText(/\$5\.00 - \$11\.00/)).toBeTruthy();+ expect(adapter.startIndex).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole("button", { name: /Start indexing/ }));+ await waitFor(() => expect(adapter.startIndex).toHaveBeenCalledWith("r1"));+ await waitFor(() => expect(adapter.onDone).toHaveBeenCalledWith("r1", "job-1"));+ });++ it("surfaces a broken provider with recovery paths and never starts a job", async () => {+ const adapter = makeAdapter({+ preflight: vi.fn().mockResolvedValue(+ makePreflight({+ provider: { ok: false, name: "gemini", model: null, error: "invalid API key" },+ estimate: null,+ }),+ ),+ });+ render(<AddRepoWizard adapter={adapter} open onOpenChange={vi.fn()} />);++ await fillAndSubmitDetails();++ expect(await screen.findByText(/gemini check failed/)).toBeTruthy();+ expect(screen.getByText(/invalid API key/)).toBeTruthy();+ expect(screen.getByRole("link", { name: /Provider settings/ })).toBeTruthy();+ expect(screen.getByRole("button", { name: /Retry check/ })).toBeTruthy();+ expect(adapter.startIndex).not.toHaveBeenCalled();++ // "Finish without indexing" still lands the user on the registered repo.+ fireEvent.click(screen.getByRole("button", { name: /Finish without indexing/ }));+ expect(adapter.onDone).toHaveBeenCalledWith("r1", null);+ });++ it("anchors path-shaped registration failures to the path field", async () => {+ const adapter = makeAdapter({+ createRepo: vi+ .fn()+ .mockRejectedValue(new Error("local_path is not a git repository")),+ });+ render(<AddRepoWizard adapter={adapter} open onOpenChange={vi.fn()} />);++ await fillAndSubmitDetails();++ expect(await screen.findByText(/not a git repository/)).toBeTruthy();+ expect(adapter.preflight).not.toHaveBeenCalled();+ // Still on the details step, ready to correct the path.+ expect(screen.getByLabelText("Local Path")).toBeTruthy();+ });+});diff --git a/packages/ui/src/dashboard/health-overview-card.tsx b/packages/ui/src/dashboard/health-overview-card.tsxindex 030a479d6..1214374c1 100644--- a/packages/ui/src/dashboard/health-overview-card.tsx+++ b/packages/ui/src/dashboard/health-overview-card.tsx@@ -277,8 +277,8 @@ export function HealthOverviewCard({<CardContent className="p-0">{!hasData ? (<p className="px-4 pb-4 text-sm text-[var(--color-text-secondary)]">- Run <code className="font-mono text-xs">repowise health</code> to score complexity,- duplication, coverage, churn, and ownership across the repo.+ Health scores land with the first index: complexity, duplication,+ coverage, churn, and ownership across the repo.</p>) : (<>diff --git a/packages/ui/src/files/file-health-tab.tsx b/packages/ui/src/files/file-health-tab.tsxindex 2ae305338..3a93cd762 100644--- a/packages/ui/src/files/file-health-tab.tsx+++ b/packages/ui/src/files/file-health-tab.tsx@@ -92,7 +92,7 @@ export function FileHealthTab({<EmptyStateicon={<HeartPulse className="h-8 w-8" />}title="No health data"- description="Run repowise init (or repowise health) to score this file."+ description="Index this repo to score this file. Health signals land with the first index."/>);}diff --git a/packages/ui/src/health/code-health-map.tsx b/packages/ui/src/health/code-health-map.tsxindex ff05510e5..eb807b055 100644--- a/packages/ui/src/health/code-health-map.tsx+++ b/packages/ui/src/health/code-health-map.tsx@@ -412,7 +412,7 @@ export function CodeHealthMap({className="flex w-full items-center justify-center rounded-xl border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-canvas)] text-sm text-[var(--color-text-tertiary)]"style={{ minHeight }}>- No files to map yet — run <code className="mx-1 font-mono">repowise init</code> to populate health.+ No files to map yet. Index this repo to populate health.</div>);}diff --git a/packages/ui/src/health/findings-view.tsx b/packages/ui/src/health/findings-view.tsxindex e536fd0bd..26f5f31bb 100644--- a/packages/ui/src/health/findings-view.tsx+++ b/packages/ui/src/health/findings-view.tsx@@ -341,7 +341,7 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {) : !queue || queue.targets.length === 0 ? (<EmptyStatetitle="No findings match the current filters"- description="Try widening the severity or effort filters, or run repowise health to populate findings."+ description="Try widening the severity or effort filters, or sync the repo to refresh findings."/>) : (<>diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsxindex 8f08adc27..17fdc1092 100644--- a/packages/ui/src/health/health-file-drawer.tsx+++ b/packages/ui/src/health/health-file-drawer.tsx@@ -147,7 +147,7 @@ export function HealthFileDrawer({<div className="text-sm text-[var(--color-text-tertiary)]">Loading…</div>) : !metric ? (<div className="rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)]">- No metric for this file yet. Run <code>repowise init</code> or <code>repowise health</code>.+ No metric for this file yet. It appears after the next index or sync.</div>) : (<>diff --git a/packages/ui/src/health/module-rollup-list.tsx b/packages/ui/src/health/module-rollup-list.tsxindex 890ae5a97..c05623770 100644--- a/packages/ui/src/health/module-rollup-list.tsx+++ b/packages/ui/src/health/module-rollup-list.tsx@@ -24,7 +24,7 @@ type SortKey = "average_health" | "file_count" | "nloc" | "module";export function ModuleRollupList({modules,- emptyMessage = "No modules detected yet — community labels populate after the first `repowise init`.",+ emptyMessage = "No modules detected yet. Community labels populate after the first index.",onSelect,pageSize = 15,}: ModuleRollupListProps) {diff --git a/packages/ui/src/health/trend-chart.tsx b/packages/ui/src/health/trend-chart.tsxindex 9685cc83b..031e62e8a 100644--- a/packages/ui/src/health/trend-chart.tsx+++ b/packages/ui/src/health/trend-chart.tsx@@ -17,8 +17,8 @@ export function TrendChart({ history, height = 220 }: TrendChartProps) {if (!history || history.length === 0) {return (<div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-center text-sm text-[var(--color-text-tertiary)]">- No snapshots yet. Run <code>repowise init</code> twice (or once + an- update) to start building a trend.+ No snapshots yet. Each index or sync records one; the trend appears+ from the second snapshot on.</div>);}diff --git a/packages/ui/src/health/trend-view.tsx b/packages/ui/src/health/trend-view.tsxindex 4e6c3a6a1..c6ab93c2d 100644--- a/packages/ui/src/health/trend-view.tsx+++ b/packages/ui/src/health/trend-view.tsx@@ -94,7 +94,7 @@ export function TrendView({<EmptyStateicon={<TrendingUp className="h-6 w-6" />}title="One snapshot so far"- description="The trend lines appear once a second snapshot lands. Run repowise update (or wait for the next sync) and this page fills in."+ description="The trend lines appear once a second snapshot lands. Sync the repo (or wait for the next automatic one) and this page fills in."/>) : (<TrendChart history={[...data.history].reverse()} />diff --git a/packages/ui/src/health/triage-view.tsx b/packages/ui/src/health/triage-view.tsxindex 7f634a634..ab6cc5ece 100644--- a/packages/ui/src/health/triage-view.tsx+++ b/packages/ui/src/health/triage-view.tsx@@ -161,7 +161,7 @@ export function TriageView({</div>) : error ? (<div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)] flex items-center justify-between gap-2">- <span>Couldn't load health data. Run <code>repowise init</code> to populate.</span>+ <span>Couldn't load health data. Index this repo to populate it.</span><Button size="sm" variant="outline" onClick={() => mutate()}>Retry</Button></div>) : overview ? (diff --git a/packages/ui/src/jobs/generation-progress.tsx b/packages/ui/src/jobs/generation-progress.tsxindex 3f85a402b..449443b57 100644--- a/packages/ui/src/jobs/generation-progress.tsx+++ b/packages/ui/src/jobs/generation-progress.tsx@@ -1,16 +1,16 @@"use client";-import { CheckCircle, XCircle, Loader2, AlertTriangle, X } from "lucide-react";+import { Ban, CheckCircle, XCircle, Loader2, AlertTriangle, RotateCw, Settings, X } from "lucide-react";import { Progress } from "../ui/progress";import { Badge } from "../ui/badge";import { Button } from "../ui/button";-import { JobLog } from "./job-log";+import { JobLog, type JobLogEntry } from "./job-log";import { formatTokens, formatNumber } from "../lib/format";/** Subset of the Job shape this presentational shell renders. */export interface GenerationProgressJob {id: string;- status: "pending" | "running" | "completed" | "failed" | string;+ status: "pending" | "running" | "completed" | "failed" | "cancelled" | string;total_pages: number;completed_pages: number;failed_pages?: number;@@ -22,7 +22,7 @@ export interface GenerationProgressJob {export interface GenerationProgressProps {job: GenerationProgressJob | undefined;- log: Array<{ text: string }>;+ log: JobLogEntry[];/** Wall-clock elapsed time in ms. The wrapper owns the interval timer. */elapsed: number;/** Live cost in USD (null until first SSE progress event with cost). */@@ -31,6 +31,13 @@ export interface GenerationProgressProps {stuckPending: boolean;cancelling: boolean;onCancel: () => void;+ /** Live pipeline phase label from the SSE stream ("Parsing files", …).+ * Falls back to the coarse level-derived label when absent. */+ phase?: string | null;+ /** Recovery action for failed/cancelled jobs: start a fresh run. */+ onRetry?: () => void;+ /** Where provider/API-key settings live; offered as a failure recovery path. */+ settingsHref?: string;}const PHASE_LABELS: Record<number, string> = {@@ -39,6 +46,12 @@ const PHASE_LABELS: Record<number, string> = {2: "Generating docs",};+/** "knowledge_graph.skeleton" → "Knowledge graph skeleton". */+function humanizePhase(phase: string): string {+ const words = phase.replace(/[._]/g, " ").trim();+ return words.charAt(0).toUpperCase() + words.slice(1);+}+export function GenerationProgress({job,log,@@ -47,6 +60,9 @@ export function GenerationProgress({stuckPending,cancelling,onCancel,+ phase,+ onRetry,+ settingsHref,}: GenerationProgressProps) {const progress = job? job.total_pages > 0@@ -60,8 +76,10 @@ export function GenerationProgress({const isInflight = isPending || isRunning;const isDone = job?.status === "completed";const isFailed = job?.status === "failed";- const phaseLabel =- job?.current_level == null+ const isCancelled = job?.status === "cancelled";+ const phaseLabel = phase+ ? humanizePhase(phase)+ : job?.current_level == null? "Processing": PHASE_LABELS[job.current_level] ?? `Processing phase ${job.current_level}`;@@ -71,12 +89,14 @@ export function GenerationProgress({{isInflight && <Loader2 className="h-4 w-4 animate-spin text-[var(--color-accent-primary)] shrink-0" />}{isDone && <CheckCircle className="h-4 w-4 text-[var(--color-fresh)] shrink-0" />}{isFailed && <XCircle className="h-4 w-4 text-[var(--color-outdated)] shrink-0" />}+ {isCancelled && <Ban className="h-4 w-4 text-[var(--color-text-tertiary)] shrink-0" />}<span className="text-sm font-medium text-[var(--color-text-primary)]">{isPending && "Queued — waiting for worker…"}{isRunning && `${phaseLabel}…`}{isDone && "Generation complete"}{isFailed && "Generation failed"}+ {isCancelled && "Cancelled"}</span><span className="ml-auto text-xs text-[var(--color-text-tertiary)] tabular-nums">@@ -115,6 +135,7 @@ export function GenerationProgress({<Progressvalue={progress}{...(isFailed ? { indicatorClassName: "bg-[var(--color-outdated)]" } : {})}+ {...(isCancelled ? { indicatorClassName: "bg-[var(--color-text-tertiary)]" } : {})}/><div className="flex justify-between text-xs text-[var(--color-text-tertiary)]"><span>@@ -166,7 +187,33 @@ export function GenerationProgress({)}{isFailed && job?.error_message && (- <p className="text-sm text-[var(--color-outdated)]">{job.error_message}</p>+ <p className="text-sm text-[var(--color-outdated)] break-words">{job.error_message}</p>+ )}++ {isCancelled && (+ <p className="text-sm text-[var(--color-text-secondary)]">+ Stopped before completion; nothing more will be generated. Start a new+ run whenever you're ready.+ </p>+ )}++ {(isFailed || isCancelled) && (onRetry || (isFailed && settingsHref)) && (+ <div className="flex flex-wrap gap-2">+ {onRetry && (+ <Button size="sm" variant="outline" onClick={onRetry} className="h-7 px-2 text-xs">+ <RotateCw className="h-3.5 w-3.5 mr-1" />+ {isCancelled ? "Start again" : "Retry"}+ </Button>+ )}+ {isFailed && settingsHref && (+ <Button size="sm" variant="ghost" asChild className="h-7 px-2 text-xs">+ <a href={settingsHref}>+ <Settings className="h-3.5 w-3.5 mr-1" />+ Provider settings+ </a>+ </Button>+ )}+ </div>)}{log.length > 0 && <JobLog entries={log} />}diff --git a/packages/ui/src/jobs/job-log.tsx b/packages/ui/src/jobs/job-log.tsxindex f2e458fec..fb080a616 100644--- a/packages/ui/src/jobs/job-log.tsx+++ b/packages/ui/src/jobs/job-log.tsx@@ -2,17 +2,25 @@import { useEffect, useRef } from "react";import { ScrollArea } from "../ui/scroll-area";+import { cn } from "../lib/cn";-interface LogEntry {+export interface JobLogEntry {text: string;- level?: number;+ /** Pipeline message level ("info", "warning", "error"); tints the line. */+ level?: string | number;}interface JobLogProps {- entries: LogEntry[];+ entries: JobLogEntry[];maxLines?: number;}+function levelClass(level: JobLogEntry["level"]): string {+ if (level === "error") return "text-[var(--color-outdated)]";+ if (level === "warning") return "text-[var(--color-warning)]";+ return "text-[var(--color-text-tertiary)]";+}+export function JobLog({ entries, maxLines = 6 }: JobLogProps) {const bottomRef = useRef<HTMLDivElement>(null);@@ -26,7 +34,7 @@ export function JobLog({ entries, maxLines = 6 }: JobLogProps) {<ScrollArea className="h-28 rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]"><div className="p-2 space-y-0.5 font-mono text-xs">{visible.map((e, i) => (- <div key={i} className="text-[var(--color-text-tertiary)] leading-5 truncate">+ <div key={i} className={cn("leading-5 truncate", levelClass(e.level))}><span className="text-[var(--color-accent-primary)] mr-1">›</span>{e.text}</div>diff --git a/packages/ui/src/onboarding/add-repo-wizard.tsx b/packages/ui/src/onboarding/add-repo-wizard.tsxnew file mode 100644index 000000000..8494f1236--- /dev/null+++ b/packages/ui/src/onboarding/add-repo-wizard.tsx@@ -0,0 +1,543 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import {+ AlertTriangle,+ ArrowLeft,+ CheckCircle2,+ FileText,+ Loader2,+ Settings,+ XCircle,+} from "lucide-react";+import { Button } from "../ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+} from "../ui/dialog";+import { Label } from "../ui/label";+import { Input } from "../ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "../ui/select";+import { formatNumber } from "../lib/format";++/** Built-in wiki styles (mirrors the server's style registry). */+export const WIKI_STYLE_OPTIONS = [+ {+ name: "comprehensive",+ label: "Comprehensive",+ description: "Full, narrative documentation for humans and AI (default).",+ },+ {+ name: "caveman",+ label: "Caveman",+ description: "Token-condensed, AI-first pages. Terse fragments, ~70% smaller.",+ },+ {+ name: "reference",+ label: "Reference",+ description: "API-manual style. Signature-dense, exhaustive, minimal narrative.",+ },+ {+ name: "tutorial",+ label: "Tutorial",+ description: "Guided, beginner-friendly walkthroughs that teach the codebase.",+ },+] as const;++export const DEFAULT_WIKI_STYLE = "comprehensive";++/** Estimates above this auto-start quietly; above it, an explicit confirm is+ * required (same threshold as the CLI's pre-generation cost gate). */+export const COST_GATE_USD = 2.0;++export interface AddRepoPreflightResult {+ provider: {+ ok: boolean;+ name: string | null;+ model: string | null;+ error: string | null;+ };+ file_count: number;+ estimate: {+ total_pages: number;+ estimated_cost_usd: number;+ cost_low_usd: number | null;+ cost_high_usd: number | null;+ is_calibrated: boolean;+ } | null;+}++export interface AddRepoInput {+ name: string;+ local_path: string;+ url?: string | undefined;+ default_branch?: string | undefined;+ wiki_style?: string | undefined;+}++export interface AddRepoWizardAdapter {+ /** Register the repo without indexing; resolves to its id. Rejects with a+ * message (e.g. "path is not a git repository") that is shown inline. */+ createRepo: (input: AddRepoInput) => Promise<{ id: string; name: string }>;+ /** Provider smoke test + size/cost estimate for the registered repo. */+ preflight: (repoId: string) => Promise<AddRepoPreflightResult>;+ /** Kick off the first full index; resolves to the job id. */+ startIndex: (repoId: string) => Promise<{ job_id: string }>;+ /** Currently active provider/model, or null when none is configured.+ * Shown as a readiness hint before the repo is even registered. */+ getProviderStatus?: () => Promise<{ provider: string | null; model: string | null } | null>;+ /** Where the provider/API-key settings live, for recovery links. */+ settingsHref?: string;+ /** Called when indexing started (jobId set) or the user chose to finish+ * without starting one (jobId null). Navigate to the repo from here. */+ onDone: (repoId: string, jobId: string | null) => void;+}++type Step = "details" | "checking" | "confirm" | "provider-error";++function formatCostRange(est: NonNullable<AddRepoPreflightResult["estimate"]>): string {+ if (est.cost_low_usd != null && est.cost_high_usd != null) {+ return `$${est.cost_low_usd.toFixed(2)} - $${est.cost_high_usd.toFixed(2)}`;+ }+ return `$${est.estimated_cost_usd.toFixed(2)}`;+}++export interface AddRepoWizardProps {+ adapter: AddRepoWizardAdapter;+ open: boolean;+ onOpenChange: (open: boolean) => void;+}++/**+ * Add-repository flow: details (path, style) → preflight (provider smoke+ * test + cost estimate) → auto-start indexing. Cheap runs start quietly;+ * estimates above {@link COST_GATE_USD} stop for an explicit confirm, and a+ * broken provider surfaces its error with recovery paths before any spend.+ */+export function AddRepoWizard({ adapter, open, onOpenChange }: AddRepoWizardProps) {+ const [step, setStep] = useState<Step>("details");+ const [name, setName] = useState("");+ const [localPath, setLocalPath] = useState("");+ const [url, setUrl] = useState("");+ const [branch, setBranch] = useState("main");+ const [wikiStyle, setWikiStyle] = useState<string>(DEFAULT_WIKI_STYLE);+ const [submitting, setSubmitting] = useState(false);+ const [pathError, setPathError] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [repoId, setRepoId] = useState<string | null>(null);+ const [preflight, setPreflight] = useState<AddRepoPreflightResult | null>(null);+ const [providerHint, setProviderHint] = useState<{+ provider: string | null;+ model: string | null;+ } | null>(null);+ const [starting, setStarting] = useState(false);+ // Guards the preflight effect against firing twice (StrictMode) and+ // against a stale run resolving after the dialog moved on.+ const preflightRun = useRef(0);++ useEffect(() => {+ if (!open || !adapter.getProviderStatus) return;+ let cancelled = false;+ adapter.getProviderStatus().then(+ (s) => {+ if (!cancelled) setProviderHint(s);+ },+ () => {},+ );+ return () => {+ cancelled = true;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open]);++ const reset = useCallback(() => {+ setStep("details");+ setName("");+ setLocalPath("");+ setUrl("");+ setBranch("main");+ setWikiStyle(DEFAULT_WIKI_STYLE);+ setPathError(null);+ setError(null);+ setRepoId(null);+ setPreflight(null);+ setStarting(false);+ preflightRun.current++;+ }, []);++ const handleOpenChange = (v: boolean) => {+ onOpenChange(v);+ if (!v) reset();+ };++ const startIndexing = useCallback(+ async (id: string) => {+ setStarting(true);+ setError(null);+ try {+ const { job_id } = await adapter.startIndex(id);+ handleOpenChange(false);+ adapter.onDone(id, job_id);+ } catch (e) {+ setError(e instanceof Error ? e.message : "Couldn't start indexing");+ setStep("confirm");+ setStarting(false);+ }+ },+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [adapter],+ );++ const runPreflight = useCallback(+ async (id: string) => {+ const run = ++preflightRun.current;+ setStep("checking");+ setError(null);+ try {+ const result = await adapter.preflight(id);+ if (run !== preflightRun.current) return;+ setPreflight(result);+ if (!result.provider.ok) {+ setStep("provider-error");+ return;+ }+ const cost = result.estimate?.estimated_cost_usd ?? 0;+ if (cost > COST_GATE_USD) {+ setStep("confirm");+ return;+ }+ // Below the gate: start quietly, same as the CLI.+ await startIndexing(id);+ } catch (e) {+ if (run !== preflightRun.current) return;+ setError(e instanceof Error ? e.message : "Preflight check failed");+ setStep("confirm");+ }+ },+ [adapter, startIndexing],+ );++ async function handleDetailsSubmit(e: React.FormEvent) {+ e.preventDefault();+ if (!name.trim() || !localPath.trim()) return;+ setSubmitting(true);+ setPathError(null);+ setError(null);+ try {+ const repo = await adapter.createRepo({+ name: name.trim(),+ local_path: localPath.trim(),+ url: url.trim() || undefined,+ default_branch: branch.trim() || "main",+ wiki_style: wikiStyle !== DEFAULT_WIKI_STYLE ? wikiStyle : undefined,+ });+ setRepoId(repo.id);+ await runPreflight(repo.id);+ } catch (err) {+ const msg = err instanceof Error ? err.message : "Failed to add repository";+ // Path problems are by far the most common failure; anchor them to the field.+ if (/path|director|git|exist/i.test(msg)) setPathError(msg);+ else setError(msg);+ } finally {+ setSubmitting(false);+ }+ }++ function handleFinishWithoutIndex() {+ if (!repoId) return;+ const id = repoId;+ handleOpenChange(false);+ adapter.onDone(id, null);+ }++ const estimate = preflight?.estimate ?? null;++ return (+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogContent className="sm:max-w-md w-[calc(100vw-2rem)]">+ {step === "details" && (+ <>+ <DialogHeader>+ <DialogTitle>Add Repository</DialogTitle>+ </DialogHeader>++ <form onSubmit={handleDetailsSubmit} className="space-y-4 py-2">+ <div className="space-y-1.5">+ <Label htmlFor="repo-name">Name</Label>+ <Input+ id="repo-name"+ placeholder="my-project"+ value={name}+ onChange={(e) => setName(e.target.value)}+ required+ />+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="repo-path">Local Path</Label>+ <Input+ id="repo-path"+ placeholder="C:\Users\you\projects\my-project"+ value={localPath}+ onChange={(e) => {+ setLocalPath(e.target.value);+ setPathError(null);+ }}+ className="font-mono"+ aria-invalid={!!pathError}+ aria-describedby="repo-path-hint"+ required+ />+ {pathError ? (+ <p id="repo-path-hint" className="text-xs text-[var(--color-outdated)]">+ {pathError}+ </p>+ ) : (+ <p id="repo-path-hint" className="text-xs text-[var(--color-text-tertiary)]">+ Absolute path to a local git checkout.+ </p>+ )}+ </div>++ <div className="grid grid-cols-2 gap-3">+ <div className="space-y-1.5">+ <Label htmlFor="repo-url">+ Remote URL{" "}+ <span className="font-normal text-[var(--color-text-tertiary)]">+ (optional)+ </span>+ </Label>+ <Input+ id="repo-url"+ placeholder="https://github.com/org/repo"+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="repo-branch">Default Branch</Label>+ <Input+ id="repo-branch"+ placeholder="main"+ value={branch}+ onChange={(e) => setBranch(e.target.value)}+ />+ </div>+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="repo-style">Wiki style</Label>+ <Select value={wikiStyle} onValueChange={setWikiStyle}>+ <SelectTrigger id="repo-style" aria-label="Wiki style">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {WIKI_STYLE_OPTIONS.map((s) => (+ <SelectItem key={s.name} value={s.name} textValue={s.label}>+ <span className="font-medium">{s.label}</span>+ <span className="ml-1.5 text-xs text-[var(--color-text-tertiary)]">+ {s.description}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ {providerHint !== null && (+ <p className="flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)]">+ {providerHint.provider ? (+ <>+ <CheckCircle2 className="h-3.5 w-3.5 shrink-0 text-[var(--color-fresh)]" />+ Docs will use {providerHint.provider}+ {providerHint.model ? ` · ${providerHint.model}` : ""}+ </>+ ) : (+ <>+ <AlertTriangle className="h-3.5 w-3.5 shrink-0 text-[var(--color-warning)]" />+ No AI provider configured yet.+ {adapter.settingsHref && (+ <a+ href={adapter.settingsHref}+ className="text-[var(--color-accent-primary)] hover:underline"+ >+ Set one up+ </a>+ )}+ </>+ )}+ </p>+ )}++ {error && <p className="text-sm text-[var(--color-outdated)]">{error}</p>}++ <DialogFooter>+ <Button type="button" variant="ghost" onClick={() => handleOpenChange(false)}>+ Cancel+ </Button>+ <Button+ type="submit"+ disabled={submitting || !name.trim() || !localPath.trim()}+ >+ {submitting ? "Adding…" : "Continue"}+ </Button>+ </DialogFooter>+ </form>+ </>+ )}++ {step === "checking" && (+ <>+ <DialogHeader>+ <DialogTitle>Getting ready to index</DialogTitle>+ </DialogHeader>+ <div className="flex flex-col items-center gap-3 py-8">+ <Loader2 className="h-6 w-6 animate-spin text-[var(--color-accent-primary)]" />+ <p className="text-sm text-[var(--color-text-secondary)]">+ Checking the provider and sizing the repository…+ </p>+ </div>+ </>+ )}++ {step === "provider-error" && preflight && (+ <>+ <DialogHeader>+ <DialogTitle>Provider isn't ready</DialogTitle>+ </DialogHeader>+ <div className="space-y-3 py-2">+ <div className="flex items-start gap-2 rounded-md border border-[var(--color-outdated)]/40 bg-[var(--color-outdated)]/10 px-3 py-2 text-sm">+ <XCircle className="mt-0.5 h-4 w-4 shrink-0 text-[var(--color-outdated)]" />+ <div className="min-w-0">+ <p className="font-medium text-[var(--color-text-primary)]">+ {preflight.provider.name+ ? `${preflight.provider.name} check failed`+ : "No AI provider is configured"}+ </p>+ {preflight.provider.error && (+ <p className="mt-0.5 break-words text-xs text-[var(--color-text-secondary)]">+ {preflight.provider.error}+ </p>+ )}+ </div>+ </div>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ The repository is registered. Fix the provider (usually an API key) and+ retry, or index without docs now and generate them later.+ </p>+ </div>+ <DialogFooter className="flex-wrap gap-2">+ <Button+ type="button"+ variant="ghost"+ onClick={() => setStep("details")}+ aria-label="Back to details"+ >+ <ArrowLeft className="mr-1 h-3.5 w-3.5" />+ Back+ </Button>+ <Button type="button" variant="ghost" onClick={handleFinishWithoutIndex}>+ Finish without indexing+ </Button>+ {adapter.settingsHref && (+ <Button type="button" variant="outline" asChild>+ <a href={adapter.settingsHref}>+ <Settings className="mr-1.5 h-3.5 w-3.5" />+ Provider settings+ </a>+ </Button>+ )}+ <Button type="button" onClick={() => repoId && runPreflight(repoId)}>+ Retry check+ </Button>+ </DialogFooter>+ </>+ )}++ {step === "confirm" && (+ <>+ <DialogHeader>+ <DialogTitle>Ready to index</DialogTitle>+ </DialogHeader>+ <div className="space-y-3 py-2">+ {preflight && (+ <div className="grid grid-cols-2 gap-2">+ <div className="rounded border border-[var(--color-border-default)] p-2.5 text-center">+ <p className="text-lg font-semibold text-[var(--color-text-primary)]">+ {formatNumber(preflight.file_count)}+ </p>+ <p className="text-xs text-[var(--color-text-tertiary)]">files</p>+ </div>+ <div className="rounded border border-[var(--color-border-default)] p-2.5 text-center">+ <p className="text-lg font-semibold text-[var(--color-text-primary)]">+ {estimate ? formatNumber(estimate.total_pages) : "—"}+ </p>+ <p className="text-xs text-[var(--color-text-tertiary)]">doc pages</p>+ </div>+ </div>+ )}+ {estimate && (+ <div className="flex items-start gap-2 rounded-md border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/10 px-3 py-2 text-sm">+ <FileText className="mt-0.5 h-4 w-4 shrink-0 text-[var(--color-warning)]" />+ <div>+ <p className="font-medium text-[var(--color-text-primary)]">+ Estimated generation cost: {formatCostRange(estimate)}+ </p>+ <p className="mt-0.5 text-xs text-[var(--color-text-secondary)]">+ {preflight?.provider.name}+ {preflight?.provider.model ? ` · ${preflight.provider.model}` : ""}+ {estimate.is_calibrated+ ? " · calibrated from previous runs"+ : " · rough estimate, actuals vary"}+ </p>+ </div>+ </div>+ )}+ {error && <p className="text-sm text-[var(--color-outdated)]">{error}</p>}+ </div>+ <DialogFooter className="flex-wrap gap-2">+ <Button+ type="button"+ variant="ghost"+ onClick={() => setStep("details")}+ disabled={starting}+ aria-label="Back to details"+ >+ <ArrowLeft className="mr-1 h-3.5 w-3.5" />+ Back+ </Button>+ <Button+ type="button"+ variant="ghost"+ onClick={handleFinishWithoutIndex}+ disabled={starting}+ >+ Not now+ </Button>+ <Button+ type="button"+ onClick={() => repoId && startIndexing(repoId)}+ disabled={starting}+ >+ {starting+ ? "Starting…"+ : estimate+ ? `Start indexing (~$${estimate.estimated_cost_usd.toFixed(2)})`+ : "Start indexing"}+ </Button>+ </DialogFooter>+ </>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/ui/src/onboarding/index-celebration.tsx b/packages/ui/src/onboarding/index-celebration.tsxnew file mode 100644index 000000000..8420a38d8--- /dev/null+++ b/packages/ui/src/onboarding/index-celebration.tsx@@ -0,0 +1,103 @@+"use client";++import { useState } from "react";+import { DotLottieReact } from "@lottiefiles/dotlottie-react";+import { motion, useReducedMotion } from "framer-motion";+import { CheckCircle2 } from "lucide-react";+import { Button } from "../ui/button";+import { formatNumber } from "../lib/format";++export interface IndexCelebrationProps {+ repoName: string;+ /** Pages generated by the first index, when known. */+ pagesGenerated?: number;+ /** Owl Lottie asset path, served from the consuming app's public/. */+ lottieSrc?: string;+ /** "Start here" handoff content, e.g. a FirstFiveFiles card. */+ children?: React.ReactNode;+ exploreLabel?: string;+ onExplore?: () => void;+}++const CONFETTI_COLORS = [+ "var(--color-accent-primary)",+ "var(--color-fresh)",+ "var(--color-warning)",+ "var(--color-stale)",+];++/**+ * First-index success moment: the brand owl takes a bow over a confetti+ * burst, then hands off to "start here" content. Falls back to a plain+ * check icon if the animation asset fails, and skips the confetti when the+ * user prefers reduced motion.+ */+export function IndexCelebration({+ repoName,+ pagesGenerated,+ lottieSrc = "/owl-loading.json",+ children,+ exploreLabel = "Explore the dashboard",+ onExplore,+}: IndexCelebrationProps) {+ const reducedMotion = useReducedMotion();+ const [lottieFailed, setLottieFailed] = useState(false);++ return (+ <div className="relative overflow-hidden rounded-lg border border-[var(--color-border-default)] p-8 text-center [background-image:var(--gradient-warm-wash)]">+ {!reducedMotion && (+ <div aria-hidden className="pointer-events-none absolute inset-0">+ {Array.from({ length: 16 }).map((_, i) => (+ <motion.span+ key={i}+ className="absolute top-1/3 left-1/2 h-2 w-1.5 rounded-sm"+ style={{ backgroundColor: CONFETTI_COLORS[i % CONFETTI_COLORS.length] }}+ initial={{ x: 0, y: 0, opacity: 1, rotate: 0 }}+ animate={{+ x: (i - 7.5) * 28 + ((i * 37) % 23) - 11,+ y: 140 + ((i * 53) % 60),+ opacity: 0,+ rotate: i % 2 === 0 ? 260 : -220,+ }}+ transition={{ duration: 1.6 + (i % 5) * 0.18, ease: "easeOut" }}+ />+ ))}+ </div>+ )}++ <div className="relative flex flex-col items-center gap-3">+ {lottieFailed ? (+ <CheckCircle2 className="h-14 w-14 text-[var(--color-fresh)]" />+ ) : (+ <DotLottieReact+ src={lottieSrc}+ autoplay+ loop={false}+ style={{ width: 120, height: 120 }}+ dotLottieRefCallback={(dotLottie) => {+ dotLottie?.addEventListener("loadError", () => setLottieFailed(true));+ }}+ />+ )}+ <div className="space-y-1">+ <h3 className="text-lg font-semibold text-[var(--color-text-primary)]">+ {repoName} is ready+ </h3>+ <p className="text-sm text-[var(--color-text-secondary)]">+ {pagesGenerated != null && pagesGenerated > 0+ ? `${formatNumber(pagesGenerated)} documentation pages generated. `+ : "The index is built. "}+ Search, health, and architecture views are live.+ </p>+ </div>+ {onExplore && (+ <Button size="sm" onClick={onExplore}>+ {exploreLabel}+ </Button>+ )}+ </div>++ {children && <div className="relative mt-6 text-left">{children}</div>}+ </div>+ );+}diff --git a/packages/ui/src/onboarding/index.ts b/packages/ui/src/onboarding/index.tsindex b0998f3fb..721a1bc49 100644--- a/packages/ui/src/onboarding/index.ts+++ b/packages/ui/src/onboarding/index.ts@@ -1 +1,3 @@export * from "./first-five-files";+export * from "./add-repo-wizard";+export * from "./index-celebration";diff --git a/packages/web/src/app/page.tsx b/packages/web/src/app/page.tsxindex bdadf1740..f3daea335 100644--- a/packages/web/src/app/page.tsx+++ b/packages/web/src/app/page.tsx@@ -5,6 +5,7 @@ import {FileText,CheckCircle2,AlertCircle,+ Ban,Skull,Activity,RefreshCw,@@ -236,6 +237,8 @@ export default async function DashboardPage() {? "outdated": job.status === "running"? "accent"+ : job.status === "cancelled"+ ? "stale": "default"}>@@ -270,5 +273,8 @@ function JobStatusIcon({ status }: { status: string }) {if (status === "failed") {return <AlertCircle className="h-4 w-4 shrink-0 text-[var(--color-error)]" />;}+ if (status === "cancelled") {+ return <Ban className="h-4 w-4 shrink-0 text-[var(--color-text-tertiary)]" />;+ }return <Clock className="h-4 w-4 shrink-0 text-[var(--color-text-tertiary)]" />;}diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsxindex edb7a7510..1bd93ae93 100644--- a/packages/web/src/app/repos/[id]/overview/page.tsx+++ b/packages/web/src/app/repos/[id]/overview/page.tsx@@ -7,7 +7,8 @@ import { getProviders } from "@/lib/api/providers";import { getStatsHighlights } from "@/lib/api/stats";import { StatsTeaserCard } from "@/components/overview/stats-teaser-card";import { Badge } from "@repowise-dev/ui/ui/badge";-import { EmptyState, PageShell } from "@repowise-dev/ui/shared";+import { PageShell } from "@repowise-dev/ui/shared";+import { FirstIndexExperience } from "@/components/repos/first-index-experience";import { HealthOverviewCard } from "@repowise-dev/ui/dashboard/health-overview-card";import { AttentionPanel } from "@repowise-dev/ui/dashboard/attention-panel";import { KpiStrip, kpiDelta, type KpiItem } from "@repowise-dev/ui/dashboard/kpi-strip";@@ -117,24 +118,21 @@ export default async function OverviewPage({ params }: Props) {return (<PageShell title={repo.name} description={repo.local_path} actions={headerMeta} maxWidth="wide">- <QuickActions- repoId={id}- repoName={repo.name}- pageCount={sync.page_count || stats.file_count}- modelName={providers?.active.model ?? sync.last_sync_model ?? ""}- lastSyncAt={sync.last_sync_at}- lastResyncAt={sync.last_resync_at}- />+ {/* Fresh repos get one prominent index action instead of the sync+ toolbar; everything else appears once the first index lands. */}+ {!isFresh && (+ <QuickActions+ repoId={id}+ repoName={repo.name}+ pageCount={sync.page_count || stats.file_count}+ modelName={providers?.active.model ?? sync.last_sync_model ?? ""}+ lastSyncAt={sync.last_sync_at}+ lastResyncAt={sync.last_resync_at}+ />+ )}{isFresh ? (- <EmptyState- title={- lastActivityAt- ? `Indexed ${formatRelativeTime(lastActivityAt)} — nothing to show yet`- : "This repo hasn't been indexed yet"- }- description="Start a sync above to build the index. Stats, attention items, and activity appear as soon as the first index lands."- />+ <FirstIndexExperience repoId={id} repoName={repo.name} />) : (<>{/* ── KPI bar leads ── */}diff --git a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx b/packages/web/src/components/dashboard/quick-actions-wrapper.tsxindex 543c847d3..3e901ddc8 100644--- a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx+++ b/packages/web/src/components/dashboard/quick-actions-wrapper.tsx@@ -62,7 +62,8 @@ export function QuickActionsWrapper({setActiveJobId(job.id);toast.info(`Full resync started${repoName ? ` — ${repoName}` : ""}`);} else if (key === "dead-code") {- await analyzeDeadCode(repoId);+ const { job_id } = await analyzeDeadCode(repoId);+ setActiveJobId(job_id);toast.info("Dead code analysis started");}} catch (e) {diff --git a/packages/web/src/components/jobs/generation-progress-wrapper.tsx b/packages/web/src/components/jobs/generation-progress-wrapper.tsxindex 9287b79fd..9b45cdc63 100644--- a/packages/web/src/components/jobs/generation-progress-wrapper.tsx+++ b/packages/web/src/components/jobs/generation-progress-wrapper.tsx@@ -1,25 +1,28 @@"use client";-import { useEffect, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { GenerationProgress } from "@repowise-dev/ui/jobs/generation-progress";import { useJob } from "@/lib/hooks/use-job";import { cancelJob } from "@/lib/api/jobs";import { formatNumber } from "@repowise-dev/ui/lib/format";-import type { JobProgressEvent } from "@/lib/api/types";import { computeElapsedMs } from "@/lib/jobs/progress";interface Props {jobId: string;repoName?: string;onDone?: () => void;+ /** Start a fresh run after a failure or cancellation. */+ onRetry?: () => void;+ /** Suppress the completion/failure toasts (when the host surface renders+ * its own completion moment). */+ quiet?: boolean;}const PENDING_STUCK_THRESHOLD_MS = 30_000;-export function GenerationProgressWrapper({ jobId, repoName, onDone }: Props) {- const { job, sse } = useJob(jobId);- const [log, setLog] = useState<Array<{ text: string }>>([]);+export function GenerationProgressWrapper({ jobId, repoName, onDone, onRetry, quiet }: Props) {+ const { job, sse, messages, phase } = useJob(jobId);const [elapsed, setElapsed] = useState(0);const [actualCost, setActualCost] = useState<number | null>(null);const [cancelling, setCancelling] = useState(false);@@ -33,35 +36,43 @@ export function GenerationProgressWrapper({ jobId, repoName, onDone }: Props) {}, [job]);useEffect(() => {- if (!sse.data) return;- const ev = sse.data as JobProgressEvent;- if (ev.current_page) {- setLog((prev) => [- ...prev,- { text: `[L${ev.current_level ?? "?"}] ${ev.current_page}` },- ]);- }- if (ev.actual_cost_usd != null) {- setActualCost(ev.actual_cost_usd);- }+ const cost = sse.data?.actual_cost_usd;+ if (cost != null) setActualCost(cost);}, [sse.data]);+ const log = useMemo(+ () => messages.map((m) => ({ text: m.text, level: m.level })),+ [messages],+ );+useEffect(() => {if (notifiedRef.current) return;if (job?.status === "completed") {notifiedRef.current = true;- toast.success(`Documentation updated${repoName ? ` — ${repoName}` : ""}`, {- description: `${formatNumber(job.completed_pages)} pages generated`,- });+ if (!quiet) {+ toast.success(`Documentation updated${repoName ? ` — ${repoName}` : ""}`, {+ description: `${formatNumber(job.completed_pages)} pages generated`,+ });+ }onDone?.();} else if (job?.status === "failed") {notifiedRef.current = true;- toast.error("Generation failed", {- description: job.error_message ?? "Unknown error",- });+ if (!quiet) {+ toast.error("Generation failed", {+ description: job.error_message ?? "Unknown error",+ });+ }+ onDone?.();+ } else if (job?.status === "cancelled") {+ notifiedRef.current = true;+ if (!quiet) {+ toast.info("Job cancelled", {+ description: "The pipeline was stopped before completion.",+ });+ }onDone?.();}- }, [job?.status, job?.completed_pages, job?.error_message, repoName, onDone]);+ }, [job?.status, job?.completed_pages, job?.error_message, repoName, onDone, quiet]);const isPending = job?.status === "pending";const stuckPending =@@ -74,8 +85,8 @@ export function GenerationProgressWrapper({ jobId, repoName, onDone }: Props) {setCancelling(true);try {await cancelJob(job.id);- toast.success("Job cancelled");- onDone?.();+ // The stream/poll flips the job to "cancelled"; the status effect above+ // owns the toast so cancel-from-button and cancel-from-elsewhere match.} catch (e) {toast.error("Couldn't cancel job", {description: e instanceof Error ? e.message : "Unknown error",@@ -94,7 +105,9 @@ export function GenerationProgressWrapper({ jobId, repoName, onDone }: Props) {stuckPending={stuckPending}cancelling={cancelling}onCancel={handleCancel}+ phase={phase}+ onRetry={onRetry}+ settingsHref="/settings"/>);}-diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 2241481c9..83e9e8e8b 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -202,25 +202,32 @@ export function Sidebar({ repos = [], activeRepoId, workspace }: SidebarProps) {const isExpanded = expandedRepos.has(repo.id);const isActive = derivedActiveRepoId === repo.id;const navGroups = repoNavGroups(repo.id);+ // The server flags never-indexed repos (workspace members+ // and plain registrations alike) with "needs_index";+ // synthetic workspace entries additionally have "ws:" ids.+ const isSynthetic = repo.id.startsWith("ws:");const needsIndex =- repo.workspace_status === "needs_index" ||- repo.id.startsWith("ws:");+ repo.workspace_status === "needs_index" || isSynthetic;const isMissing = repo.workspace_status === "missing_dir";if (needsIndex || isMissing) {- // Synthetic / unindexed workspace entry — show as a- // disabled row with a status hint. The Index/Sync- // CTA lives in the Workspace dashboard.+ // Unindexed entry: a status pill that routes to where+ // the Index CTA lives, the Workspace dashboard for+ // synthetic entries and the repo overview otherwise.+ const indexHref = isSynthetic || isMissing+ ? "/workspace"+ : `/repos/${repo.id}/overview`;if (isIconOnly) {return (<Tooltip key={repo.id}><TooltipTrigger asChild>- <div- className="flex w-full items-center justify-center rounded-md p-2 text-[var(--color-text-tertiary)] opacity-60"+ <Link+ href={indexHref}+ className="flex w-full items-center justify-center rounded-md p-2 text-[var(--color-text-tertiary)] opacity-60 transition-colors hover:bg-[var(--color-bg-elevated)]"aria-label={`${repo.name} (${isMissing ? "missing" : "needs index"})`}><Circle className="h-2.5 w-2.5 stroke-current" />- </div>+ </Link></TooltipTrigger><TooltipContent side="right">{repo.workspace_alias ?? repo.name}@@ -233,12 +240,14 @@ export function Sidebar({ repos = [], activeRepoId, workspace }: SidebarProps) {return (<Linkkey={repo.id}- href="/workspace"+ href={indexHref}className="flex w-full items-center gap-2.5 rounded-lg px-2 py-2 text-sm text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-elevated)]"title={isMissing? "Directory missing — open Workspace to remove or fix"- : "Not indexed yet — open Workspace to index"+ : isSynthetic+ ? "Not indexed yet. Open Workspace to index."+ : "Not indexed yet. Open the repo to index."}><Circle className="h-2 w-2 shrink-0 stroke-current" />diff --git a/packages/web/src/components/overview/structure-tab.tsx b/packages/web/src/components/overview/structure-tab.tsxindex 46accff8a..1fd2989e8 100644--- a/packages/web/src/components/overview/structure-tab.tsx+++ b/packages/web/src/components/overview/structure-tab.tsx@@ -66,7 +66,7 @@ export function StructureTab({ repoId }: StructureTabProps) {) : (<EmptyStatetitle="No module graph yet"- description="Module structure appears once indexing completes. Run repowise update to refresh."+ description="Module structure appears once indexing completes. Sync the repo to refresh."/>)}diff --git a/packages/web/src/components/repos/add-repo-dialog.tsx b/packages/web/src/components/repos/add-repo-dialog.tsxindex 4e2bb9a2e..fa7f25002 100644--- a/packages/web/src/components/repos/add-repo-dialog.tsx+++ b/packages/web/src/components/repos/add-repo-dialog.tsx@@ -1,21 +1,17 @@"use client";-import { useState } from "react";+import { useMemo, useState } from "react";import { useRouter } from "next/navigation";import { Plus } from "lucide-react";import { toast } from "sonner";import { useSWRConfig } from "swr";-import { createRepo } from "@/lib/api/repos";+import { createRepo, preflightIndex, startIndexJob } from "@/lib/api/repos";+import { getProviders } from "@/lib/api/providers";import { Button } from "@repowise-dev/ui/ui/button";import {- Dialog,- DialogContent,- DialogHeader,- DialogTitle,- DialogFooter,-} from "@repowise-dev/ui/ui/dialog";-import { Label } from "@repowise-dev/ui/ui/label";-import { Input } from "@repowise-dev/ui/ui/input";+ AddRepoWizard,+ type AddRepoWizardAdapter,+} from "@repowise-dev/ui/onboarding/add-repo-wizard";interface Props {/** Render as a sidebar button (icon + label) vs standalone button */@@ -38,47 +34,38 @@ export function AddRepoDialog({const [uncontrolledOpen, setUncontrolledOpen] = useState(false);const open = controlledOpen ?? uncontrolledOpen;const setOpen = onOpenChange ?? setUncontrolledOpen;- const [name, setName] = useState("");- const [localPath, setLocalPath] = useState("");- const [url, setUrl] = useState("");- const [branch, setBranch] = useState("main");- const [submitting, setSubmitting] = useState(false);- const [error, setError] = useState<string | null>(null);- function reset() {- setName("");- setLocalPath("");- setUrl("");- setBranch("main");- setError(null);- }-- async function handleSubmit(e: React.FormEvent) {- e.preventDefault();- if (!name.trim() || !localPath.trim()) return;- setSubmitting(true);- setError(null);- try {- const repo = await createRepo({- name: name.trim(),- local_path: localPath.trim(),- url: url.trim() || undefined,- default_branch: branch.trim() || "main",- });- // Invalidate the repos list so sidebar/dashboard refresh- await mutate("/api/repos");- setOpen(false);- reset();- toast.success(`Added ${repo.name}`);- // Land on the new repo's overview, where the sync actions live.- router.push(`/repos/${repo.id}/overview`);- router.refresh();- } catch (e) {- setError(e instanceof Error ? e.message : "Failed to add repository");- } finally {- setSubmitting(false);- }- }+ const adapter: AddRepoWizardAdapter = useMemo(+ () => ({+ createRepo: async (input) => {+ const repo = await createRepo({+ name: input.name,+ local_path: input.local_path,+ url: input.url,+ default_branch: input.default_branch,+ settings: input.wiki_style ? { wiki_style: input.wiki_style } : undefined,+ // Register first; the wizard runs preflight (provider check + cost+ // estimate) before committing to generation spend.+ index: false,+ });+ await mutate("/api/repos");+ return { id: repo.id, name: repo.name };+ },+ preflight: (repoId) => preflightIndex(repoId),+ startIndex: (repoId) => startIndexJob(repoId),+ getProviderStatus: async () => {+ const res = await getProviders();+ return res.active;+ },+ settingsHref: "/settings",+ onDone: (repoId, jobId) => {+ toast.success(jobId ? "Repository added, indexing started" : "Repository added");+ router.push(`/repos/${repoId}/overview`);+ router.refresh();+ },+ }),+ [mutate, router],+ );return (<>@@ -98,78 +85,7 @@ export function AddRepoDialog({</Button>)}- <Dialog open={open} onOpenChange={(v) => { setOpen(v); if (!v) reset(); }}>- <DialogContent className="sm:max-w-md w-[calc(100vw-2rem)]">- <DialogHeader>- <DialogTitle>Add Repository</DialogTitle>- </DialogHeader>-- <form onSubmit={handleSubmit} className="space-y-4 py-2">- <div className="space-y-1.5">- <Label htmlFor="repo-name">Name</Label>- <Input- id="repo-name"- placeholder="my-project"- value={name}- onChange={(e) => setName(e.target.value)}- required- />- </div>-- <div className="space-y-1.5">- <Label htmlFor="repo-path">Local Path</Label>- <Input- id="repo-path"- placeholder="C:\Users\you\projects\my-project"- value={localPath}- onChange={(e) => setLocalPath(e.target.value)}- className="font-mono"- required- />- </div>-- <div className="space-y-1.5">- <Label htmlFor="repo-url">- Remote URL{" "}- <span className="font-normal text-[var(--color-text-tertiary)]">(optional)</span>- </Label>- <Input- id="repo-url"- placeholder="https://github.com/org/repo"- value={url}- onChange={(e) => setUrl(e.target.value)}- />- </div>-- <div className="space-y-1.5">- <Label htmlFor="repo-branch">Default Branch</Label>- <Input- id="repo-branch"- placeholder="main"- value={branch}- onChange={(e) => setBranch(e.target.value)}- />- </div>-- {error && (- <p className="text-sm text-[var(--color-outdated)]">{error}</p>- )}-- <DialogFooter>- <Button- type="button"- variant="ghost"- onClick={() => { setOpen(false); reset(); }}- >- Cancel- </Button>- <Button type="submit" disabled={submitting || !name.trim() || !localPath.trim()}>- {submitting ? "Adding…" : "Add Repository"}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>+ <AddRepoWizard adapter={adapter} open={open} onOpenChange={setOpen} /></>);}diff --git a/packages/web/src/components/repos/first-index-experience.tsx b/packages/web/src/components/repos/first-index-experience.tsxnew file mode 100644index 000000000..4e76de0c4--- /dev/null+++ b/packages/web/src/components/repos/first-index-experience.tsx@@ -0,0 +1,157 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { useRouter } from "next/navigation";+import { Sparkles } from "lucide-react";+import { toast } from "sonner";+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";+import { IndexCelebration } from "@repowise-dev/ui/onboarding/index-celebration";+import { FirstFiveFiles, type FirstFiveFile } from "@repowise-dev/ui/onboarding/first-five-files";+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";+import { startIndexJob } from "@/lib/api/repos";+import { listJobs, getJob } from "@/lib/api/jobs";+import { getOverviewSummary } from "@/lib/api/overview";+import { GenerationProgressWrapper } from "@/components/jobs/generation-progress-wrapper";++interface Props {+ repoId: string;+ repoName: string;+}++/**+ * The fresh-repo overview surface: one prominent "Index this repo" action,+ * live phase-labeled progress once a job is running, and a celebratory+ * handoff (with the first five files to read) when the first index lands.+ * Hydrates from any in-flight job so a page refresh mid-index rejoins it.+ */+export function FirstIndexExperience({ repoId, repoName }: Props) {+ const router = useRouter();+ const [jobId, setJobId] = useState<string | null>(null);+ const [starting, setStarting] = useState(false);+ const [completed, setCompleted] = useState<{ pages: number } | null>(null);+ const [startHere, setStartHere] = useState<FirstFiveFile[]>([]);++ // Rejoin an in-flight first index after refresh/navigation.+ useEffect(() => {+ let cancelled = false;+ (async () => {+ try {+ const [running, pending] = await Promise.all([+ listJobs({ repo_id: repoId, status: "running", limit: 1 }),+ listJobs({ repo_id: repoId, status: "pending", limit: 1 }),+ ]);+ if (cancelled) return;+ const inflight = running[0] ?? pending[0];+ if (inflight) setJobId(inflight.id);+ } catch {+ // best-effort+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [repoId]);++ const startIndex = useCallback(async () => {+ setStarting(true);+ try {+ const { job_id } = await startIndexJob(repoId);+ setCompleted(null);+ setJobId(job_id);+ } catch (e) {+ const msg = e instanceof Error ? e.message : "Unknown error";+ if (/already in progress/i.test(msg)) {+ // Attach to whatever is running instead of failing the click.+ try {+ const [running, pending] = await Promise.all([+ listJobs({ repo_id: repoId, status: "running", limit: 1 }),+ listJobs({ repo_id: repoId, status: "pending", limit: 1 }),+ ]);+ const inflight = running[0] ?? pending[0];+ if (inflight) {+ setJobId(inflight.id);+ return;+ }+ } catch {+ // fall through+ }+ }+ toast.error("Couldn't start indexing", { description: msg });+ } finally {+ setStarting(false);+ }+ }, [repoId]);++ const handleJobDone = useCallback(async () => {+ if (!jobId) return;+ try {+ const job = await getJob(jobId);+ if (job.status === "completed") {+ setCompleted({ pages: job.completed_pages });+ // Best-effort "start here" handoff; the celebration stands alone if+ // the summary isn't ready yet.+ try {+ const summary = await getOverviewSummary(repoId);+ setStartHere(+ summary.onboarding_targets.map((t) => ({+ file_path: t.path,+ pagerank: t.pagerank,+ has_doc: t.doc_words > 0,+ })),+ );+ } catch {+ // keep the celebration without the list+ }+ }+ } catch {+ // job fetch failed; leave the progress panel's terminal state visible+ }+ }, [jobId, repoId]);++ if (completed) {+ return (+ <IndexCelebration+ repoName={repoName}+ pagesGenerated={completed.pages}+ onExplore={() => router.refresh()}+ >+ {startHere.length > 0 && (+ <FirstFiveFiles+ files={startHere}+ title="Start here"+ // Targets can be symbol pages ("calc.py::add"); link to the file.+ hrefFor={(f) => fileEntityPath(`/repos/${repoId}`, f.file_path.split("::")[0]!)}+ />+ )}+ </IndexCelebration>+ );+ }++ if (jobId) {+ return (+ <div className="rounded-lg border border-[var(--color-border-default)] p-4">+ <GenerationProgressWrapper+ jobId={jobId}+ repoName={repoName}+ onDone={handleJobDone}+ onRetry={startIndex}+ quiet+ />+ </div>+ );+ }++ return (+ <EmptyState+ icon={<Sparkles className="h-8 w-8" />}+ title="This repo hasn't been indexed yet"+ description="One click builds the code index, health signals, and documentation. You can watch it happen live."+ action={{+ label: starting ? "Starting…" : "Index this repo",+ onClick: () => {+ if (!starting) void startIndex();+ },+ }}+ />+ );+}diff --git a/packages/web/src/components/repos/operations-panel.tsx b/packages/web/src/components/repos/operations-panel.tsxindex b4e91d9df..54ebb1e34 100644--- a/packages/web/src/components/repos/operations-panel.tsx+++ b/packages/web/src/components/repos/operations-panel.tsx@@ -2,7 +2,7 @@import { useState } from "react";import { toast } from "sonner";-import { RefreshCw, Zap, ChevronDown, ChevronUp, AlertTriangle, Download } from "lucide-react";+import { RefreshCw, Zap, AlertTriangle, Download } from "lucide-react";import { syncRepo, fullResyncRepo } from "@/lib/api/repos";import { Button } from "@repowise-dev/ui/ui/button";import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";@@ -13,7 +13,6 @@ import {DialogTitle,DialogFooter,} from "@repowise-dev/ui/ui/dialog";-import { RunConfigForm, type RunConfig } from "./run-config-form";import { GenerationProgressWrapper as GenerationProgress } from "@/components/jobs/generation-progress-wrapper";interface Props {@@ -21,17 +20,7 @@ interface Props {repoName: string;}-const DEFAULT_CONFIG: RunConfig = {- provider: "litellm",- model: "",- skipTests: false,- skipInfra: false,- concurrency: 4,-};-export function OperationsPanel({ repoId, repoName }: Props) {- const [open, setOpen] = useState(false);- const [runConfig, setRunConfig] = useState<RunConfig>(DEFAULT_CONFIG);const [activeJobId, setActiveJobId] = useState<string | null>(null);const [confirmResync, setConfirmResync] = useState(false);const [loading, setLoading] = useState<"sync" | "resync" | null>(null);@@ -75,18 +64,7 @@ export function OperationsPanel({ repoId, repoName }: Props) {<><Card><CardHeader className="pb-2">- <div className="flex items-center justify-between">- <CardTitle className="text-sm">Operations</CardTitle>- <button- onClick={() => setOpen((v) => !v)}- aria-expanded={open}- aria-controls="operations-panel-content"- className="flex items-center gap-1 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] transition-colors cursor-pointer"- >- {open ? <ChevronUp className="h-3.5 w-3.5" /> : <ChevronDown className="h-3.5 w-3.5" />}- {open ? "Collapse" : "Configure"}- </button>- </div>+ <CardTitle className="text-sm">Operations</CardTitle></CardHeader><CardContent id="operations-panel-content" className="space-y-4">@@ -99,11 +77,6 @@ export function OperationsPanel({ repoId, repoName }: Props) {/>)}- {/* Config form (collapsible) */}- {open && !activeJobId && (- <RunConfigForm value={runConfig} onChange={setRunConfig} />- )}-{/* Action buttons */}{!activeJobId && (<div className="flex gap-2">diff --git a/packages/web/src/components/repos/run-config-form.tsx b/packages/web/src/components/repos/run-config-form.tsxdeleted file mode 100644index 6decee46f..000000000--- a/packages/web/src/components/repos/run-config-form.tsx+++ /dev/null@@ -1,132 +0,0 @@-"use client";--import { useEffect } from "react";-import { config } from "@/lib/config";-import { Label } from "@repowise-dev/ui/ui/label";-import { Input } from "@repowise-dev/ui/ui/input";-import { Switch } from "@repowise-dev/ui/ui/switch";-import { Slider } from "@repowise-dev/ui/ui/slider";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@repowise-dev/ui/ui/select";--export interface RunConfig {- provider: string;- model: string;- skipTests: boolean;- skipInfra: boolean;- concurrency: number;-}--interface Props {- value: RunConfig;- onChange: (v: RunConfig) => void;-}--const PROVIDERS = ["litellm", "openai", "anthropic", "gemini", "deepseek", "opencode", "ollama", "mock"] as const;--export function RunConfigForm({ value, onChange }: Props) {- // Seed from saved settings on mount- useEffect(() => {- onChange({- provider: config.getProvider(),- model: config.getModel(),- skipTests: false,- skipInfra: false,- concurrency: 4,- });- // only on mount- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- function set<K extends keyof RunConfig>(key: K, v: RunConfig[K]) {- onChange({ ...value, [key]: v });- }-- return (- <div className="space-y-4">- <div className="grid grid-cols-2 gap-3">- <div className="space-y-1.5">- <Label htmlFor="run-provider">Provider</Label>- <Select value={value.provider} onValueChange={(v) => set("provider", v)}>- <SelectTrigger id="run-provider" aria-label="Provider">- <SelectValue />- </SelectTrigger>- <SelectContent>- {PROVIDERS.map((p) => (- <SelectItem key={p} value={p}>- {p}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>-- <div className="space-y-1.5">- <Label htmlFor="run-model">Model</Label>- <Input- id="run-model"- value={value.model}- onChange={(e) => set("model", e.target.value)}- placeholder="gemini/gemini-2.0-flash"- className="font-mono"- />- </div>- </div>-- <div className="space-y-3">- <div className="flex items-center justify-between">- <div>- <p className="text-sm text-[var(--color-text-primary)]">Skip test files</p>- <p className="text-xs text-[var(--color-text-tertiary)]">- Exclude test files from documentation- </p>- </div>- <Switch- checked={value.skipTests}- onCheckedChange={(v) => set("skipTests", v)}- />- </div>-- <div className="flex items-center justify-between">- <div>- <p className="text-sm text-[var(--color-text-primary)]">Skip infra files</p>- <p className="text-xs text-[var(--color-text-tertiary)]">- Exclude CI, Docker, config files- </p>- </div>- <Switch- checked={value.skipInfra}- onCheckedChange={(v) => set("skipInfra", v)}- />- </div>- </div>-- <div className="space-y-2">- <div className="flex items-center justify-between">- <Label htmlFor="run-concurrency">Concurrency</Label>- <span className="text-sm tabular-nums text-[var(--color-text-secondary)]">- {value.concurrency}- </span>- </div>- <Slider- id="run-concurrency"- aria-label="Concurrency"- aria-valuetext={`${value.concurrency} parallel`}- min={1}- max={10}- step={1}- value={[value.concurrency]}- onValueChange={([v]) => set("concurrency", v)}- />- <p className="text-xs text-[var(--color-text-tertiary)]">- Parallel page generations (higher = faster but more API usage)- </p>- </div>- </div>- );-}diff --git a/packages/web/src/components/settings/mcp-section.tsx b/packages/web/src/components/settings/mcp-section.tsxindex 0471441c1..0521f08d7 100644--- a/packages/web/src/components/settings/mcp-section.tsx+++ b/packages/web/src/components/settings/mcp-section.tsx@@ -55,8 +55,8 @@ export function McpSection() {</div><p className="text-xs text-[var(--color-text-tertiary)]">Replace <code className="font-mono">/path/to/your/repo</code> with the local path- of the repository you want to query. Run{" "}- <code className="font-mono">repowise init</code> first to generate documentation.+ of the repository you want to query. Index the repository first so there is+ documentation to serve.</p></CardContent></Card>diff --git a/packages/web/src/components/settings/mcp-tools-section.tsx b/packages/web/src/components/settings/mcp-tools-section.tsxindex 7bda22a03..071d0f5db 100644--- a/packages/web/src/components/settings/mcp-tools-section.tsx+++ b/packages/web/src/components/settings/mcp-tools-section.tsx@@ -133,8 +133,7 @@ export function McpToolsSection() {<CardContent className="space-y-4">{repos.length === 0 && !loading && (<p className="text-sm text-[var(--color-text-tertiary)]">- No indexed repos found. Run <code className="font-mono">repowise init</code>{" "}- first.+ No indexed repos found. Add and index a repository first.</p>)}diff --git a/packages/web/src/lib/hooks/use-job.ts b/packages/web/src/lib/hooks/use-job.tsindex fb8f31476..b7881971d 100644--- a/packages/web/src/lib/hooks/use-job.ts+++ b/packages/web/src/lib/hooks/use-job.ts@@ -4,7 +4,7 @@ import { useEffect, useMemo } from "react";import useSWR from "swr";import { getJob, getJobStreamUrl } from "@/lib/api/jobs";import { useSSE } from "./use-sse";-import type { JobResponse, JobProgressEvent } from "@/lib/api/types";+import type { JobResponse, JobProgressEvent, JobMessageEvent } from "@/lib/api/types";import { mergeJobProgress } from "@/lib/jobs/progress";/**@@ -39,5 +39,17 @@ export function useJob(jobId: string | null) {return mergeJobProgress(job, ev);}, [job, sse.data]);- return { job: liveJob, sse, isActive };+ // Pipeline log lines from `event: message` frames; the wrapper renders+ // them in the JobLog tail.+ const messages = useMemo(+ () =>+ (sse.messages as JobMessageEvent[]).filter(+ (m) => m && typeof m === "object" && typeof m.text === "string",+ ),+ [sse.messages],+ );++ const phase = (sse.data as JobProgressEvent | null)?.phase ?? null;++ return { job: liveJob, sse, isActive, messages, phase };}diff --git a/packages/web/src/lib/hooks/use-sse.ts b/packages/web/src/lib/hooks/use-sse.tsindex aa22ceff0..ff97d7f8f 100644--- a/packages/web/src/lib/hooks/use-sse.ts+++ b/packages/web/src/lib/hooks/use-sse.ts@@ -4,11 +4,18 @@ import { useCallback, useEffect, useRef, useState } from "react";export interface SSEState<T> {data: T | null;+ /** Accumulated default-type frames (`event: message`); the job streams+ * use these for pipeline log lines, interleaved with progress frames. */+ messages: unknown[];error: Error | null;isConnected: boolean;isDone: boolean;}+// Matches the server's per-job ring buffer so a pathological stream can't+// grow client memory unbounded.+const MAX_MESSAGES = 500;+/*** Generic Server-Sent Events hook.* Connects to the given URL when enabled=true.@@ -20,6 +27,7 @@ export function useSSE<T>(): SSEState<T> & { close: () => void } {const [state, setState] = useState<SSEState<T>>({data: null,+ messages: [],error: null,isConnected: false,isDone: false,@@ -49,10 +57,16 @@ export function useSSE<T>(retriesRef.current = 0;};+ // `event: message` is the default SSE event type, so it arrives here+ // rather than via addEventListener. These frames are log lines, not+ // progress snapshots; collect them instead of overwriting `data`.es.onmessage = (event) => {try {- const parsed = JSON.parse(event.data) as T;- setState((s) => ({ ...s, data: parsed }));+ const parsed = JSON.parse(event.data) as unknown;+ setState((s) => ({+ ...s,+ messages: [...s.messages, parsed].slice(-MAX_MESSAGES),+ }));} catch {// non-JSON message, ignore}diff --git a/packages/web/src/lib/jobs/progress.ts b/packages/web/src/lib/jobs/progress.tsindex a53b5a158..4b60ad1d2 100644--- a/packages/web/src/lib/jobs/progress.ts+++ b/packages/web/src/lib/jobs/progress.ts@@ -5,7 +5,7 @@ export function computeElapsedMs(job: JobResponse | undefined, nowMs = Date.now(const start = Date.parse(job.started_at ?? job.created_at);if (!Number.isFinite(start)) return 0;const end =- job.status === "completed" || job.status === "failed"+ job.status === "completed" || job.status === "failed" || job.status === "cancelled"? Date.parse(job.finished_at ?? ""): nowMs;const effectiveEnd = Number.isFinite(end) ? end : nowMs;@@ -24,5 +24,6 @@ export function mergeJobProgress(total_pages: ev.total_pages ?? job.total_pages,failed_pages: ev.failed_pages ?? job.failed_pages,current_level: ev.current_level ?? job.current_level,+ error_message: ev.error_message ?? job.error_message,};}