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(present): tell the repository as a short story (#2734)
Raghav Chamadiya8957506974b6
diff --git a/docs/start/DASHBOARD.md b/docs/start/DASHBOARD.mdindex c75167666..73cddbdc2 100644--- a/docs/start/DASHBOARD.md+++ b/docs/start/DASHBOARD.md@@ -70,34 +70,33 @@ restores when you leave.### Present mode (the hidden one)Inside the docs header there is a **Present** button. It turns the wiki you-already generated into a full-screen, keyboard-driven presentation. Nothing is-generated for it: the deck is derived synchronously from the pages already-loaded, so there is no LLM call, no network round trip, and no extra cost. The-button only appears when the repo has a `repo_overview` page.--The state lives in the URL (`?present=deck` or `?present=walkthrough`), so a-particular mode is shareable.--**Deck** is a slide view assembled in a fixed order: a title slide from the-overview page, up to two architecture-diagram slides, up to five layer slides-(prose on the left and the layer's mermaid diagram on the right when it has-one), up to five module slides, a "where to start" slide built from the guided-tour metadata, and a closing slide. Each slide carries a freshness dot and an-"open in reader" link that drops you back into the docs view on that page.--**Walkthrough** is the guided-reading version of the same content: one step per-guided-tour stop, each with a "why this matters" callout, a longer excerpt from-the target page, and a reading-time estimate. A left rail tracks which steps-you have finished and shows the total estimate. If the index has no guided tour,-the walkthrough falls back to the deck's sections rather than showing an empty-pane.+already generated into a short, full-screen, keyboard-driven deck. Nothing is+generated for it: the deck is built from the overview and a handful of module+pages, fetched when you open it, so there is no LLM call and no extra cost. The+button only appears when the repo has a `repo_overview` page. The state lives in+the URL (`?present=deck`), so a deck link is shareable.++The deck tells one story in a fixed order:++1. **Title**: the repository name and the overview's opening.+2. **How it fits together**: the overview's architecture diagram, with the+ sentence around it. A flowchart with no edges is skipped.+3. **One slide per major part**: the largest top-level sections of the docs+ tree (up to six, in tree order). Each shows the page's opening, its first+ diagram beside it, and its step-named sections as a numbered list.+4. **One flow, end to end**: a sequence diagram from those pages that no earlier+ slide showed, when one exists.+5. **Where to start reading**: each part's first recommended file, then the+ guided tour's stops, grouped by why they matter. When some top-level+ sections were left out, this slide says how many.++Prose is cut on sentence boundaries only, and tables, lists and stat lines never+become slide text, so older pages give a shorter deck, not a broken one. Every+slide drawn from a page has an "Open in docs" link back to it, and a stale or+outdated source page is marked.Keys while the overlay is open: `→` / `Space` / `PageDown` next, `←` / `PageUp`-back, `Home` / `End` first and last, `Esc` to close. Deck and Walkthrough each-keep their own position, so toggling between them does not lose your place.--This is the fastest way to hand a repo to a new joiner: open Present, hit-Walkthrough, and let the guided tour do the talking.+back, `Home` / `End` first and last, `Esc` to close.### Doc freshness@@ -316,7 +315,7 @@ These appear only when repowise is running over a multi-repo workspace. See| Key | Does ||---|---|| `⌘K` / `Ctrl+K` | Command palette (jump to a page, file, or symbol) |-| `→` `Space` `PageDown` | Present mode: next slide or step |+| `→` `Space` `PageDown` | Present mode: next slide || `←` `PageUp` | Present mode: previous || `Home` `End` | Present mode: first / last || `Esc` | Close Present mode or the open drawer |diff --git a/packages/ui/__tests__/present/build-present-model.test.ts b/packages/ui/__tests__/present/build-present-model.test.tsindex 6387274fc..be606461f 100644--- a/packages/ui/__tests__/present/build-present-model.test.ts+++ b/packages/ui/__tests__/present/build-present-model.test.ts@@ -2,12 +2,16 @@ import { describe, it, expect } from "vitest";import { buildPresentModel, canPresent } from "../../src/present/build-present-model.js";import {splitOnH2,- extractMermaidBlocks,+ splitBlocks,stripLeadingH1,- countWords,- clampProse,+ extractMermaidBlocks,+ isProse,+ isDrawable,+ diagramKind,+ wholeSentences,} from "../../src/present/split-markdown.js";import type { DocPage } from "@repowise-dev/types/docs";+import type { PresentSource } from "../../src/present/types.js";function makePage(overrides: Partial<DocPage> = {}): DocPage {return {@@ -35,173 +39,341 @@ function makePage(overrides: Partial<DocPage> = {}): DocPage {};}+function source(overrides: Partial<PresentSource> = {}): PresentSource {+ return {+ overview: makePage({+ id: "ov",+ page_type: "repo_overview",+ title: "Repository Overview: acme",+ target_path: "acme",+ content: "## Summary\n\nAcme turns orders into shipments through a queue of workers.",+ }),+ parts: [],+ totalParts: 0,+ pageIdByPath: new Map(),+ ...overrides,+ };+}++const FLOW = 'flowchart TB\n api["API"] -->|queues| worker["Worker"]';+const SEQUENCE = "sequenceDiagram\n participant A\n participant B\n A->>B: request";++// The current module-page contract: plain opening, a diagram, step-named+// sections that close on a Sources line, and a reading list.+const CONTRACT_PART = [+ "# Order Intake",+ "",+ "This part accepts orders over HTTP and hands them to the queue. Everything downstream reads what it writes.",+ "",+ "```mermaid",+ SEQUENCE,+ "```",+ "",+ "## From request to queued job",+ "",+ "The handler validates the payload before anything is stored.",+ "",+ "Sources: `handler.py`, `schema.py`",+ "",+ "## How retries are bounded",+ "",+ "Each job carries an attempt counter.",+ "",+ "Sources: `retry.py`",+ "",+ "## Where to start reading",+ "",+ "- `handler.py` - The request entry point.",+ "- `retry.py` - The retry policy.",+ "",+ "## How it connects",+ "",+ "Workers consume the queue this part fills.",+].join("\n");+describe("split-markdown", () => {it("splits on H2 and keeps the lead", () => {const { lead, sections } = splitOnH2("Intro line.\n\n## First\nbody a\n\n## Second\nbody b");expect(lead).toBe("Intro line.");expect(sections.map((s) => s.heading)).toEqual(["First", "Second"]);- expect(sections[0]!.body).toContain("body a");});- it("ignores ## inside a code fence", () => {- const { sections } = splitOnH2("lead\n\n```\n## not a heading\n```\n\n## Real\nx");- expect(sections.map((s) => s.heading)).toEqual(["Real"]);+ it("ignores headings and blank lines inside code fences", () => {+ expect(splitOnH2("lead\n\n```\n## not a heading\n```\n\n## Real\nx").sections).toHaveLength(1);+ expect(splitBlocks("a\n\n```\nx\n\ny\n```\n\nb")).toEqual(["a", "```\nx\n\ny\n```", "b"]);});- it("strips a single leading H1", () => {+ it("strips a leading H1 and extracts mermaid blocks", () => {expect(stripLeadingH1("# Title\n\nbody")).toBe("body");expect(stripLeadingH1("no heading")).toBe("no heading");+ expect(extractMermaidBlocks("text\n\n```mermaid\ngraph TD\nA-->B\n```\n\nmore")).toEqual([+ "graph TD\nA-->B",+ ]);});- it("extracts mermaid blocks", () => {- const blocks = extractMermaidBlocks("text\n\n```mermaid\ngraph TD\nA-->B\n```\n\nmore");- expect(blocks).toEqual(["graph TD\nA-->B"]);+ it("tells prose from tables, lists, stat lines and footnotes", () => {+ expect(isProse("The service accepts orders and hands them to a queue.")).toBe(true);+ expect(isProse("The subsystem has three distinct ways in, listed below:")).toBe(true);+ expect(isProse("| a | b |\n|---|---|\n| 1 | 2 |")).toBe(false);+ expect(isProse("- one item that is long enough to pass the length floor.")).toBe(false);+ expect(isProse("**Files:** 130 | **Lines:** 16167 | **Packages:** 3 and more.")).toBe(false);+ expect(isProse("*Built from the code's structure. It states what is there.*")).toBe(false);+ expect(isProse("A paragraph that stops without finishing its")).toBe(false);});- it("counts words ignoring fences and markdown punctuation", () => {- expect(countWords("## Heading\n\none two three\n\n```\nignored code here\n```")).toBe(4);+ it("keeps whole sentences and never cuts one", () => {+ const text = "First sentence is here. Second one, e.g. with an aside, follows. Third.";+ expect(wholeSentences(text, 30)).toBe("First sentence is here.");+ expect(wholeSentences(text, 70)).toBe(+ "First sentence is here. Second one, e.g. with an aside, follows.",+ );+ const long = `${"word ".repeat(100).trim()}.`;+ expect(wholeSentences(long, 20)).toBe(long);});- it("clamps prose on paragraph boundaries but always returns the first", () => {- const long = "a".repeat(600);- expect(clampProse(`${long}\n\nsecond`, 300)).toBe(long);+ it("treats an edgeless flowchart as not worth drawing", () => {+ expect(isDrawable('flowchart LR\n subgraph a["A"]\n x["X -- label"]\n end')).toBe(false);+ expect(isDrawable(FLOW)).toBe(true);+ expect(isDrawable("graph TD\n a -.-> b")).toBe(true);+ expect(isDrawable(SEQUENCE)).toBe(true);+ });++ it("reads the diagram type past front matter and init directives", () => {+ expect(diagramKind("%%{init: {'theme': 'base'}}%%\nsequenceDiagram\n A->>B: x")).toBe(+ "sequencediagram",+ );+ expect(diagramKind("---\ntitle: Flow\n---\n%% note\nflowchart LR\n a --> b")).toBe(+ "flowchart",+ );+ expect(isDrawable('%%{init: {}}%%\nflowchart LR\n a["A"]')).toBe(false);});});describe("canPresent", () => {- it("requires a repo_overview page", () => {- expect(canPresent([makePage({ page_type: "file_page" })])).toBe(false);+ it("requires an overview page", () => {+ expect(canPresent([makePage()])).toBe(false);expect(canPresent([makePage({ page_type: "repo_overview" })])).toBe(true);});});describe("buildPresentModel", () => {- const overview = makePage({- id: "ov",- page_type: "repo_overview",- title: "Acme Overview",- target_path: "repo",- content: "# Acme\n\nA build tool.\n\n## Details\nmore",- metadata: {- layer_order: ["layer:api", "layer:core"],- guided_tour: [- { order: 1, title: "main.py", target_path: "src/main.py", reason: "entry point" },- { order: 2, title: "core.py", target_path: "src/core.py", reason: "the engine" },- ],- },- });- const arch = makePage({- id: "arch",- page_type: "architecture_diagram",- title: "System architecture",- content: "Intro\n\n```mermaid\ngraph TD\nA-->B\n```",- });- const layerCore = makePage({- id: "lc",- page_type: "layer_page",- title: "Core layer",- target_path: "layer:core",- content: "# Core\n\nThe core does the work and holds the pipeline together nicely.",- // Display name deliberately unlike the id: the enrichment pass rewrites- // layer_name, so ordering must not depend on it.- metadata: { layer_name: "Engine and Pipeline Core" },- });- const layerApi = makePage({- id: "la",- page_type: "layer_page",- title: "API layer",- target_path: "layer:api",- content: "# API\n\nThe API exposes endpoints to callers over HTTP with care.",- metadata: { layer_name: "Typed RPC Interfaces" },- });- const mainFile = makePage({ id: "mf", target_path: "src/main.py", title: "main.py", content: "# main\n\nStarts the program and wires everything up on boot." });-- it("derives a clean repo name from a 'Repository Overview: name' title", () => {- const colonOverview = makePage({+ it("tells the story in order on the current page contract", () => {+ const overview = makePage({+ id: "ov",page_type: "repo_overview",- title: "Repository Overview: repowise",- content: "## Project Summary\n\nRepowise is a codebase documentation engine.",- metadata: {},+ title: "Repository Overview: acme",+ target_path: "acme",+ content: [+ "**Files:** 40 | **Lines:** 5000",+ "",+ "## Summary",+ "",+ "Acme turns orders into shipments. It runs as an API in front of a pool of workers.",+ "",+ "## Architecture",+ "",+ "Requests enter through the API and wait on a queue until a worker takes them.",+ "",+ "```mermaid",+ FLOW,+ "```",+ ].join("\n"),+ });+ const part = makePage({+ id: "m1",+ page_type: "module_page",+ title: "Order Intake",+ target_path: "src/intake",+ content: CONTRACT_PART,});- const model = buildPresentModel([colonOverview]);- expect(model.repoName).toBe("repowise");- // Title tagline is the real summary sentence, not the "Project Summary" heading.- expect(model.deck[0]!.bodyMarkdown).toContain("codebase documentation engine");- expect(model.deck[0]!.bodyMarkdown).not.toContain("Project Summary");+ const model = buildPresentModel(+ source({+ overview,+ parts: [part],+ totalParts: 1,+ pageIdByPath: new Map([["src/intake/handler.py", "f1"]]),+ }),+ );++ expect(model.repoName).toBe("acme");+ expect(model.slides.map((s) => s.kind)).toEqual(["title", "architecture", "part", "start"]);++ const [title, arch, partSlide, start] = model.slides;+ expect(title!.body).toBe(+ "Acme turns orders into shipments. It runs as an API in front of a pool of workers.",+ );+ expect(arch!.mermaid).toBe(FLOW);+ expect(arch!.body).toBe(+ "Requests enter through the API and wait on a queue until a worker takes them.",+ );+ expect(partSlide!.eyebrow).toBe("Part 1 of 1");+ expect(partSlide!.body).toBe(+ "This part accepts orders over HTTP and hands them to the queue. Everything downstream reads what it writes.",+ );+ expect(partSlide!.mermaid).toBe(SEQUENCE);+ expect(partSlide!.steps).toEqual(["From request to queued job", "How retries are bounded"]);+ // The part's reading list resolves relative to its directory.+ expect(start!.start?.[0]).toEqual({+ label: "Order Intake",+ note: "The request entry point.",+ files: [{ path: "src/intake/handler.py", pageId: "f1" }],+ });+ // Every part was presented, so no scope note.+ expect(start!.body).toBeUndefined();});- it("builds a title slide, diagram slide, ordered layers, and a closing", () => {- const model = buildPresentModel([overview, arch, layerCore, layerApi, mainFile]);- expect(model.repoName).toBe("Acme");- expect(model.deck[0]!.kind).toBe("title");- expect(model.deck.some((s) => s.kind === "diagram" && s.mermaid?.includes("graph TD"))).toBe(true);- // Layers ordered by layer_order: API before Core.- const layerTitles = model.deck.filter((s) => s.eyebrow === "Layer").map((s) => s.title);- expect(layerTitles).toEqual(["API layer", "Core layer"]);- expect(model.deck[model.deck.length - 1]!.kind).toBe("closing");+ it("adds one flow slide for a sequence diagram no part slide shows", () => {+ const part = makePage({+ id: "m1",+ page_type: "module_page",+ title: "Workers",+ target_path: "src/workers",+ content: [+ "Workers drain the queue and write shipments to the store.",+ "",+ "```mermaid",+ FLOW,+ "```",+ "",+ "## How a job runs",+ "",+ "A worker claims a job, runs it, then acknowledges it.",+ "",+ "```mermaid",+ SEQUENCE,+ "```",+ ].join("\n"),+ });+ const model = buildPresentModel(source({ parts: [part], totalParts: 1 }));+ const flow = model.slides.find((s) => s.kind === "flow");+ expect(flow?.title).toBe("How a job runs");+ expect(flow?.mermaid).toBe(SEQUENCE);+ expect(flow?.body).toBe("A worker claims a job, runs it, then acknowledges it.");+ expect(model.slides.find((s) => s.kind === "part")?.mermaid).toBe(FLOW);});- it("builds a split slide for a layer page that embeds a diagram", () => {- const layerWithDiagram = makePage({- id: "ld",- page_type: "layer_page",- title: "Data layer",- target_path: "layer:data",- content:- "# Data\n\nThe data layer persists and indexes everything the pipeline produces, and it is the durable backbone every other layer leans on.\n\n## Architecture\n\n```mermaid\nflowchart TD\nX-->Y\n```",- metadata: { layer_name: "Data" },+ it("degrades on older pages: no diagrams, list lead-ins, reference sections", () => {+ const part = makePage({+ id: "m1",+ page_type: "module_page",+ title: "Storage",+ target_path: "src/storage",+ content: [+ "## How storage is divided",+ "",+ "Storage is split into two layers with separate jobs:",+ "",+ "| Layer | Role |",+ "|---|---|",+ "| cache | reads |",+ "",+ "Both layers share one connection pool and never open their own.",+ "",+ "## Questions this page answers",+ "",+ "- Where is data cached?",+ ].join("\n"),});- const model = buildPresentModel([overview, layerWithDiagram]);- const slide = model.deck.find((s) => s.eyebrow === "Layer");- expect(slide!.kind).toBe("split");- expect(slide!.mermaid).toContain("flowchart TD");- expect(slide!.bodyMarkdown).toBeTruthy();- // Prose column must not carry the diagram fence — it renders separately.- expect(slide!.bodyMarkdown).not.toContain("```mermaid");+ const model = buildPresentModel(source({ parts: [part], totalParts: 4 }));+ const partSlide = model.slides.find((s) => s.kind === "part")!;+ expect(partSlide.body).toBe(+ "Storage is split into two layers with separate jobs. Both layers share one connection pool and never open their own.",+ );+ expect(partSlide.mermaid).toBeUndefined();+ expect(partSlide.steps).toEqual([]);+ expect(model.slides.some((s) => s.kind === "architecture")).toBe(false);+ // Three parts were left out, and the deck says so.+ expect(model.slides.at(-1)?.body).toBe(+ "This deck covers 1 of the 4 top-level sections. The rest are in the documentation.",+ );});- it("keeps a plain section slide for a layer page without a diagram", () => {- const model = buildPresentModel([overview, layerCore]);- const slide = model.deck.find((s) => s.eyebrow === "Layer");- expect(slide!.kind).toBe("section");- expect(slide!.mermaid).toBeUndefined();+ it("skips an edgeless architecture map", () => {+ const overview = makePage({+ id: "ov",+ page_type: "repo_overview",+ title: "Overview",+ content:+ 'Acme is a small service that ships orders.\n\n## Map\n\n```mermaid\nflowchart LR\n a["A"]\n b["B"]\n```',+ });+ const model = buildPresentModel(source({ overview }));+ expect(model.slides.map((s) => s.kind)).toEqual(["title"]);});- it("builds a walkthrough from the guided tour with time estimates", () => {- const model = buildPresentModel([overview, mainFile]);- expect(model.walkthrough).toHaveLength(2);- expect(model.walkthrough[0]!.title).toBe("main.py");- expect(model.walkthrough[0]!.reason).toBe("entry point");- expect(model.walkthrough[0]!.sourcePageId).toBe("mf");- expect(model.walkthrough[0]!.estMinutes).toBeGreaterThanOrEqual(2);- expect(model.totalMinutes).toBe(- model.walkthrough.reduce((s, w) => s + w.estMinutes, 0),+ it("fills the reading list from the guided tour, deduped and grouped by reason", () => {+ const overview = makePage({+ id: "ov",+ page_type: "repo_overview",+ title: "Overview",+ content: "Acme is a small service that ships orders.",+ metadata: {+ guided_tour: [+ { target_path: "README.md", reason: "Start here." },+ { target_path: "src/app.py", reason: "An entry point." },+ { target_path: "src/cli.py", reason: "An entry point." },+ { target_path: "src/db.py", reason: "Widely imported." },+ { target_path: "src/app.py", reason: "An entry point." },+ { title: "no path" },+ ],+ },+ });+ const model = buildPresentModel(+ source({ overview, pageIdByPath: new Map([["src/app.py", "f-app"]]) }),);+ const start = model.slides.find((s) => s.kind === "start");+ expect(start?.start).toEqual([+ { note: "Start here.", files: [{ path: "README.md", pageId: undefined }] },+ {+ note: "An entry point.",+ files: [+ { path: "src/app.py", pageId: "f-app" },+ { path: "src/cli.py", pageId: undefined },+ ],+ },+ { note: "Widely imported.", files: [{ path: "src/db.py", pageId: undefined }] },+ ]);});- it("falls back to deck sections when there is no guided tour", () => {- const bareOverview = makePage({ id: "ov2", page_type: "repo_overview", title: "Bare", content: "# Bare\n\nx", metadata: {} });- const model = buildPresentModel([bareOverview, layerCore]);- expect(model.walkthrough.length).toBeGreaterThan(0);+ it("does not repeat a tour stop a part already recommends", () => {+ const overview = makePage({+ id: "ov",+ page_type: "repo_overview",+ title: "Overview",+ metadata: {+ guided_tour: [+ { target_path: "src/intake/handler.py", reason: "An entry point." },+ { target_path: "src/db.py", reason: "Widely imported." },+ ],+ },+ });+ const part = makePage({+ id: "m1",+ page_type: "module_page",+ title: "Order Intake",+ target_path: "src/intake",+ content: CONTRACT_PART,+ });+ const model = buildPresentModel(+ source({+ overview,+ parts: [part],+ totalParts: 1,+ pageIdByPath: new Map([["src/intake/handler.py", "f1"]]),+ }),+ );+ const paths = model.slides+ .find((s) => s.kind === "start")+ ?.start?.flatMap((g) => g.files.map((f) => f.path));+ expect(paths).toEqual(["src/intake/handler.py", "src/db.py"]);});- // The assumption the Guided Tour page's retirement rests on. The page is- // gone; the ordered stops it used to narrate are still computed and still- // written to the overview's metadata, and every consumer outside that page- // read the metadata rather than the page. If that were ever untrue, this is- // where it would show: a deck built from an index that has no onboarding- // page at all must still walk the tour.- it("builds a full deck and walkthrough with no onboarding page in the index", () => {- const pages = [overview, arch, layerApi, layerCore, mainFile];- expect(pages.some((p) => p.page_type === "onboarding")).toBe(false);-- const model = buildPresentModel(pages);-- expect(model.deck.some((s) => s.kind === "title")).toBe(true);- expect(model.deck.some((s) => s.kind === "diagram")).toBe(true);- expect(model.deck.length).toBeGreaterThan(3);- expect(model.walkthrough).toHaveLength(2);- expect(model.walkthrough.map((w) => w.title)).toEqual(["main.py", "core.py"]);- expect(model.totalMinutes).toBeGreaterThan(0);+ it("always yields a title slide, even for a bare overview", () => {+ const model = buildPresentModel(+ source({+ overview: makePage({ id: "ov", page_type: "repo_overview", title: "Overview", content: "" }),+ }),+ );+ expect(model.slides).toHaveLength(1);+ expect(model.slides[0]).toMatchObject({ kind: "title", title: "Overview", body: undefined });});});diff --git a/packages/ui/__tests__/present/load-present-pages.test.ts b/packages/ui/__tests__/present/load-present-pages.test.tsdeleted file mode 100644index 42d55e18f..000000000--- a/packages/ui/__tests__/present/load-present-pages.test.ts+++ /dev/null@@ -1,136 +0,0 @@-import { describe, it, expect, vi } from "vitest";-import { loadPresentPages } from "../../src/present/load-present-pages.js";-import type { DocPage, DocPageSummary } from "@repowise-dev/types/docs";--function summary(overrides: Partial<DocPageSummary> = {}): DocPageSummary {- return {- id: "p1",- repository_id: "r1",- page_type: "file_page",- title: "Page",- target_path: "src/foo.ts",- source_hash: "h",- model_name: "m",- provider_name: "p",- input_tokens: 0,- output_tokens: 0,- cached_tokens: 0,- generation_level: 0,- version: 1,- confidence: 1,- freshness_status: "fresh",- human_notes: null,- created_at: "",- updated_at: "",- ...overrides,- };-}--function full(overrides: Partial<DocPage> = {}): DocPage {- return {- ...summary(overrides),- content: "body",- metadata: {},- ...overrides,- };-}--/** Fetcher that serves whatever it is given and records what was asked for. */-function fetcher(pool: DocPage[]) {- const asked: string[] = [];- const fetchPage = vi.fn(async (id: string) => {- asked.push(id);- const hit = pool.find((p) => p.id === id);- if (!hit) throw new Error(`no page ${id}`);- return hit;- });- return { fetchPage, asked };-}--describe("loadPresentPages", () => {- it("returns nothing when there is no overview to present", async () => {- const { fetchPage } = fetcher([]);- expect(await loadPresentPages([summary()], fetchPage)).toEqual([]);- expect(fetchPage).not.toHaveBeenCalled();- });-- it("leaves the bulk of the wiki alone", async () => {- const pages: DocPageSummary[] = [- summary({ id: "overview", page_type: "repo_overview", target_path: "repo" }),- ...Array.from({ length: 500 }, (_, i) =>- summary({ id: `file-${i}`, target_path: `src/f${i}.ts` }),- ),- ];- const { fetchPage, asked } = fetcher([- full({ id: "overview", page_type: "repo_overview", target_path: "repo" }),- ]);-- const loaded = await loadPresentPages(pages, fetchPage);-- expect(asked).toEqual(["overview"]);- expect(loaded.map((p) => p.id)).toEqual(["overview"]);- });-- it("takes the richest modules by content_chars, not by whatever came first", async () => {- const modules = [- summary({ id: "m-small", page_type: "module_page", content_chars: 10 }),- summary({ id: "m-big", page_type: "module_page", content_chars: 9000 }),- summary({ id: "m-mid", page_type: "module_page", content_chars: 500 }),- ];- const pages = [- summary({ id: "overview", page_type: "repo_overview" }),- ...modules,- ];- const pool = [- full({ id: "overview", page_type: "repo_overview" }),- ...modules.map((m) => full({ id: m.id, page_type: "module_page" })),- ];- const { fetchPage, asked } = fetcher(pool);-- await loadPresentPages(pages, fetchPage);-- // All three fit under the cap, but the order they are taken in is the- // order the deck shows them.- expect(asked.slice(1)).toEqual(["m-big", "m-mid", "m-small"]);- });-- it("follows the overview's guided tour to its landmark pages", async () => {- const overview = full({- id: "overview",- page_type: "repo_overview",- metadata: {- guided_tour: [- { order: 1, target_path: "src/entry.ts" },- { order: 2, target_path: "src/missing.ts" },- ],- },- });- const pages = [- summary({ id: "overview", page_type: "repo_overview" }),- summary({ id: "entry", target_path: "src/entry.ts" }),- ];- const { fetchPage, asked } = fetcher([- overview,- full({ id: "entry", target_path: "src/entry.ts" }),- ]);-- const loaded = await loadPresentPages(pages, fetchPage);-- // The stop with no page behind it is skipped rather than fetched blindly.- expect(asked).toEqual(["overview", "entry"]);- expect(loaded.map((p) => p.id)).toEqual(["overview", "entry"]);- });-- it("does not refetch a row that already carries its body", async () => {- const pages = [- full({ id: "overview", page_type: "repo_overview" }),- full({ id: "arch", page_type: "architecture_diagram" }),- ];- const { fetchPage } = fetcher([]);-- const loaded = await loadPresentPages(pages, fetchPage);-- expect(fetchPage).not.toHaveBeenCalled();- expect(loaded.map((p) => p.id)).toEqual(["overview", "arch"]);- });-});diff --git a/packages/ui/__tests__/present/load-present-source.test.ts b/packages/ui/__tests__/present/load-present-source.test.tsnew file mode 100644index 000000000..c2164117c--- /dev/null+++ b/packages/ui/__tests__/present/load-present-source.test.ts@@ -0,0 +1,140 @@+import { describe, it, expect, vi } from "vitest";+import { loadPresentSource } from "../../src/present/load-present-source.js";+import type { DocPage, DocPageSummary } from "@repowise-dev/types/docs";++function summary(overrides: Partial<DocPageSummary> = {}): DocPageSummary {+ return {+ id: "p1",+ repository_id: "r1",+ page_type: "file_page",+ title: "Page",+ target_path: "src/foo.ts",+ source_hash: "h",+ model_name: "m",+ provider_name: "p",+ input_tokens: 0,+ output_tokens: 0,+ cached_tokens: 0,+ generation_level: 0,+ version: 1,+ confidence: 1,+ freshness_status: "fresh",+ human_notes: null,+ created_at: "",+ updated_at: "",+ ...overrides,+ };+}++function full(overrides: Partial<DocPage> = {}): DocPage {+ return {+ ...summary(overrides),+ content: "body",+ metadata: {},+ ...overrides,+ };+}++/** Fetcher that serves a page for any id and records what was asked for. */+function fetcher() {+ const asked: string[] = [];+ const fetchPage = vi.fn(async (id: string) => {+ asked.push(id);+ return full({ id });+ });+ return { fetchPage, asked };+}++const OVERVIEW = summary({ id: "ov", page_type: "repo_overview", target_path: "repo" });++function module(id: string, overrides: Partial<DocPageSummary> = {}): DocPageSummary {+ return summary({ id, page_type: "module_page", target_path: `src/${id}`, ...overrides });+}++describe("loadPresentSource", () => {+ it("returns null when there is no overview to present", async () => {+ const { fetchPage } = fetcher();+ expect(await loadPresentSource([summary()], fetchPage)).toBeNull();+ expect(fetchPage).not.toHaveBeenCalled();+ });++ it("fetches only the overview and the chosen parts", async () => {+ const pages = [+ OVERVIEW,+ module("m1"),+ ...Array.from({ length: 500 }, (_, i) => summary({ id: `f${i}`, target_path: `src/f${i}.ts` })),+ ];+ const { fetchPage, asked } = fetcher();++ const source = await loadPresentSource(pages, fetchPage);++ expect(asked).toEqual(["ov", "m1"]);+ expect(source?.parts.map((p) => p.id)).toEqual(["m1"]);+ expect(source?.pageIdByPath.get("src/f7.ts")).toBe("f7");+ });++ it("picks the top-level sections with the most nested pages, shown in outline order", async () => {+ const pages = [+ OVERVIEW,+ module("small", { parent_page_id: "ov", display_order: 1 }),+ module("big", { parent_page_id: "ov", display_order: 3 }),+ module("big-a", { parent_page_id: "big" }),+ module("big-b", { parent_page_id: "big" }),+ module("big-a-1", { parent_page_id: "big-a" }),+ module("mid", { parent_page_id: "ov", display_order: 2 }),+ module("mid-a", { parent_page_id: "mid" }),+ ...Array.from({ length: 6 }, (_, i) =>+ module(`leaf${i}`, { parent_page_id: "ov", display_order: 10 + i }),+ ),+ ];+ const { fetchPage } = fetcher();++ const source = await loadPresentSource(pages, fetchPage);++ // Nine top-level sections; the cap keeps six. The two with children rank+ // first, and the deck presents the selection in outline order.+ expect(source?.totalParts).toBe(9);+ expect(source?.parts.map((p) => p.id)).toEqual([+ "small",+ "mid",+ "big",+ "leaf0",+ "leaf1",+ "leaf2",+ ]);+ });++ it("ranks a flat wiki by how much was written", async () => {+ const pages = [+ OVERVIEW,+ module("m-small", { content_chars: 10 }),+ module("m-big", { content_chars: 9000 }),+ module("m-mid", { content_chars: 500 }),+ ];+ const { fetchPage } = fetcher();++ const source = await loadPresentSource(pages, fetchPage);++ expect(source?.parts.map((p) => p.id)).toEqual(["m-big", "m-mid", "m-small"]);+ });++ it("does not hang on a malformed parent cycle", async () => {+ const pages = [OVERVIEW, module("a", { parent_page_id: "b" }), module("b", { parent_page_id: "a" })];+ const { fetchPage } = fetcher();++ const source = await loadPresentSource(pages, fetchPage);++ expect(source?.parts).toEqual([]);+ });++ it("does not refetch a row that already carries its body", async () => {+ const pages = [full({ id: "ov", page_type: "repo_overview" }), full({ id: "m1", page_type: "module_page" })];+ const { fetchPage } = fetcher();++ const source = await loadPresentSource(pages, fetchPage);++ expect(fetchPage).not.toHaveBeenCalled();+ expect(source?.overview.id).toBe("ov");+ expect(source?.parts.map((p) => p.id)).toEqual(["m1"]);+ });+});diff --git a/packages/ui/__tests__/present/present-overlay.test.tsx b/packages/ui/__tests__/present/present-overlay.test.tsxnew file mode 100644index 000000000..2a4d3db16--- /dev/null+++ b/packages/ui/__tests__/present/present-overlay.test.tsx@@ -0,0 +1,93 @@+import { describe, it, expect, vi, afterEach } from "vitest";+import { render, screen, fireEvent, cleanup, waitFor } from "@testing-library/react";+import { PresentOverlay } from "../../src/present/present-overlay.js";+import type { PresentModel } from "../../src/present/types.js";++const MODEL: PresentModel = {+ repoName: "acme",+ slides: [+ { id: "title", kind: "title", title: "acme", body: "Acme ships orders." },+ { id: "part", kind: "part", eyebrow: "Part 1 of 1", title: "Order Intake", sourcePageId: "m1" },+ { id: "start", kind: "start", title: "Where to start reading", start: [] },+ ],+};++function open(onClose = vi.fn()) {+ render(<PresentOverlay model={MODEL} onClose={onClose} onOpenPage={() => {}} />);+ return onClose;+}++const heading = () => screen.getByRole("heading", { level: 2 }).textContent;++// The outgoing slide fades before the next mounts, so wait for the swap.+const showing = (title: string) => waitFor(() => expect(heading()).toBe(title));++afterEach(() => {+ cleanup();+ document.body.innerHTML = "";+});++describe("PresentOverlay keyboard", () => {+ it("moves with the arrow keys and closes on Escape", async () => {+ const onClose = open();+ expect(heading()).toBe("acme");+ fireEvent.keyDown(window, { key: "ArrowRight" });+ await showing("Order Intake");+ fireEvent.keyDown(window, { key: "End" });+ await showing("Where to start reading");+ fireEvent.keyDown(window, { key: "ArrowLeft" });+ await showing("Order Intake");+ fireEvent.keyDown(window, { key: "Escape" });+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it("announces the slide title with its position", async () => {+ open();+ fireEvent.keyDown(window, { key: "ArrowRight" });+ expect(await screen.findByText("Slide 2 of 3: Order Intake")).toBeInTheDocument();+ });++ it("leaves every key to a modal opened from a slide", async () => {+ const onClose = open();+ const nested = document.createElement("div");+ nested.setAttribute("role", "dialog");+ nested.setAttribute("aria-modal", "true");+ document.body.appendChild(nested);++ fireEvent.keyDown(nested, { key: "ArrowRight" });+ fireEvent.keyDown(nested, { key: "Escape" });+ // The position updates synchronously, unlike the animated slide.+ expect(screen.getByText("Slide 1 of 3: acme")).toBeInTheDocument();+ expect(onClose).not.toHaveBeenCalled();++ nested.remove();+ fireEvent.keyDown(window, { key: "ArrowRight" });+ await showing("Order Intake");+ });++ it("lets Space press a focused button instead of advancing", () => {+ open();+ const close = screen.getByRole("button", { name: /close presentation/i });+ close.focus();+ fireEvent.keyDown(close, { key: " " });+ expect(screen.getByText("Slide 1 of 3: acme")).toBeInTheDocument();+ });++ it("keeps Tab inside the dialog and returns focus to the opener on close", () => {+ const opener = document.createElement("button");+ document.body.appendChild(opener);+ opener.focus();++ const { unmount } = render(<PresentOverlay model={MODEL} onClose={() => {}} />);+ const dialog = screen.getByRole("dialog");+ expect(document.activeElement).toBe(dialog);++ fireEvent.keyDown(window, { key: "Tab" });+ expect(dialog.contains(document.activeElement)).toBe(true);+ fireEvent.keyDown(window, { key: "Tab", shiftKey: true });+ expect(dialog.contains(document.activeElement)).toBe(true);++ unmount();+ expect(document.activeElement).toBe(opener);+ });+});diff --git a/packages/ui/src/present/build-present-model.ts b/packages/ui/src/present/build-present-model.tsindex 511e26ea7..b5a8e14a8 100644--- a/packages/ui/src/present/build-present-model.ts+++ b/packages/ui/src/present/build-present-model.ts@@ -1,272 +1,277 @@-// Build a Present model (slide deck + guided walkthrough) from already-loaded-// wiki pages. Pure and synchronous: no LLM, no network, no DB. Every section is-// guarded so missing page types (e.g. no architecture diagram, index-only repos)-// degrade to a shorter deck instead of erroring.+// Build a Present deck from already-loaded wiki pages. Pure and synchronous:+// no LLM, no network, no DB.+//+// The deck tells one story in a fixed order: what the repository is (the+// overview's opening), how it fits together (the overview's diagram), one+// slide per major part (its opening, its own diagram, its step-named+// sections), one traced flow when a page carries a sequence diagram, and where+// to start reading. Every slide is optional except the title, so a page shape+// without diagrams or step sections yields a shorter deck, never a broken one.+// Prose is cut on sentence boundaries only; tables, lists and stat lines are+// never shown as slide text.import type { DocPage, DocPageSummary } from "@repowise-dev/types/docs";import { filterMarkdownByPersona } from "../docs/reader-persona";import {+ diagramKind,+ extractMermaidBlocks,+ isDrawable,+ isProse,+ splitBlocks,splitOnH2,stripLeadingH1,- extractMermaidBlocks,- clampProse,- countWords,+ wholeSentences,+ type SplitMarkdown,} from "./split-markdown";-import { readLayerOrder } from "../lib/layers";-import type { PresentModel, PresentSlide, PresentStep } from "./types";+import type {+ PresentModel,+ PresentSlide,+ PresentSource,+ StartGroup,+} from "./types";-// Curation caps keep the deck tight and premium on large repos.-export const MAX_LAYER_SLIDES = 5;-export const MAX_MODULE_SLIDES = 5;-const MAX_TOUR_STOPS = 8;-const DECK_BODY_CHARS = 520;-const STEP_BODY_CHARS = 1100;+const TITLE_CHARS = 360;+const PART_CHARS = 420;+const CAPTION_CHARS = 280;+const SHORT_OPENING = 160;+const MAX_STEPS = 5;+const MAX_START_FILES = 8;-export interface TourStop {- order?: number | undefined;- title?: string | undefined;- target_path?: string | undefined;- reason?: string | undefined;- kind?: string | undefined;-}--export function readTour(overview: DocPage | undefined): TourStop[] {- const raw = overview?.metadata?.["guided_tour"];- if (!Array.isArray(raw)) return [];- return raw- .filter((s): s is Record<string, unknown> => !!s && typeof s === "object")- .map((s) => ({- order: typeof s["order"] === "number" ? (s["order"] as number) : undefined,- title: typeof s["title"] === "string" ? (s["title"] as string) : undefined,- target_path:- typeof s["target_path"] === "string" ? (s["target_path"] as string) : undefined,- reason: typeof s["reason"] === "string" ? (s["reason"] as string) : undefined,- kind: typeof s["kind"] === "string" ? (s["kind"] as string) : undefined,- }));+/** True when there is enough generated content to present. Reads only the page+ * type, so it answers from a summary listing without fetching any bodies. */+export function canPresent(pages: readonly DocPageSummary[]): boolean {+ return pages.some((p) => p.page_type === "repo_overview");}-// The spine reader lives with the rest of the layer logic — the docs tree-// groups by the same order this deck presents in, and one repository can only-// have one layer order.-export { readLayerOrder } from "../lib/layers";-/*** A readable repo name from the overview page title. Titles look like- * "Repository Overview: repowise" — prefer the part after the colon, then- * strip stray "repository"/"overview" words, so the title slide reads "repowise"- * not "This repository".+ * "Repository Overview: name": prefer the part after the colon, then strip+ * stray "repository"/"overview" words.*/-function deriveRepoName(overview: DocPage | undefined, override?: string): string {- const fromOverride = override?.trim();- if (fromOverride) return fromOverride;- if (!overview) return "This repository";+function deriveRepoName(overview: DocPage): string {const title = overview.title.trim();const afterColon = title.includes(":") ? (title.split(":").pop() ?? title).trim() : title;const cleaned = afterColon.replace(/\b(repository|repo|overview)\b/gi, "").replace(/\s+/g, " ").trim();return cleaned || afterColon || "This repository";}-/** First real prose paragraph of a page (skips a leading heading). */-function firstProse(page: DocPage, maxChars: number): string {- const filtered = stripLeadingH1(filterMarkdownByPersona(page.content, "overview"));- const { lead, sections } = splitOnH2(filtered);- const leadText = lead.trim();- const source = leadText.length >= 40 ? leadText : (sections[0]?.body.trim() ?? leadText);- const firstPara = source.split(/\n{2,}/)[0] ?? "";- return clampProse(firstPara, maxChars);+/** A page's human reading path: reference sections dropped, title removed. */+function readable(page: DocPage): SplitMarkdown {+ return splitOnH2(stripLeadingH1(filterMarkdownByPersona(page.content, "overview")));}-/** Persona-filtered lead excerpt for a slide (prose + diagrams only). */-function slideBody(page: DocPage, maxChars: number): string {- const filtered = stripLeadingH1(filterMarkdownByPersona(page.content, "overview"));- const { lead, sections } = splitOnH2(filtered);- let text = lead.trim();- const first = sections[0];- if (text.length < 60 && first) {- text = `## ${first.heading}\n\n${first.body}`.trim();+/** Prose paragraphs of a region; a list's lead-in closes as a statement. */+function proseOf(markdown: string): string[] {+ return splitBlocks(markdown)+ .filter(isProse)+ .map((p) => p.replace(/:\s*$/, "."));+}++function firstProse(markdown: string): string | undefined {+ return proseOf(markdown)[0];+}++/**+ * The opening of a page: whole sentences from the first region (lead, then+ * each section) that has prose. A one-line lead-in borrows the paragraph after+ * it, so a slide says more than "It has three parts."+ */+function opening(doc: SplitMarkdown, maxChars: number): string | undefined {+ for (const region of [doc.lead, ...doc.sections.map((s) => s.body)]) {+ const [first, next] = proseOf(region);+ if (!first) continue;+ const text = wholeSentences(first, maxChars);+ if (text.length >= SHORT_OPENING || !next) return text;+ const more = wholeSentences(next, maxChars);+ return text.length + 1 + more.length <= maxChars ? `${text} ${more}` : text;}- return clampProse(text, maxChars);+ return undefined;}-function estimateMinutes(markdown: string): number {- const words = countWords(markdown);- return Math.min(12, Math.max(2, 2 + Math.ceil(words / 200)));+interface PlacedDiagram {+ chart: string;+ /** The H2 the diagram sits under; absent when it is in the lead. */+ heading?: string | undefined;+ /** The text of that section (or the lead), for a caption. */+ context: string;}-/** True when there is enough generated content to present. Reads only the page- * type, so it answers from a summary listing without fetching any bodies. */-export function canPresent(pages: readonly DocPageSummary[]): boolean {- return pages.some((p) => p.page_type === "repo_overview");+function diagrams(doc: SplitMarkdown): PlacedDiagram[] {+ const regions = [+ { heading: undefined, body: doc.lead },+ ...doc.sections.map((s) => ({ heading: s.heading, body: s.body })),+ ];+ return regions.flatMap((r) =>+ extractMermaidBlocks(r.body)+ .filter(isDrawable)+ .map((chart) => ({ chart, heading: r.heading, context: r.body })),+ );}-/** Rank layer pages the way the deck orders them, longest-standing first. */-export function orderedLayers<T extends DocPageSummary>(- pages: readonly T[],- overview: DocPage | undefined,-): T[] {- const layerOrder = readLayerOrder(overview);- const rankOf = (name: string | undefined) => {- if (!name) return Number.MAX_SAFE_INTEGER;- const idx = layerOrder.indexOf(name);- return idx === -1 ? Number.MAX_SAFE_INTEGER : idx;+/** A caption from the diagram's own section, unless it opens like `shown`. */+function caption(placed: PlacedDiagram, shown: string | undefined): string | undefined {+ const para = firstProse(placed.context);+ if (!para) return undefined;+ const text = wholeSentences(para, CAPTION_CHARS);+ return shown && shown.startsWith(text.slice(0, 60)) ? undefined : text;+}++/** Step-named sections: the ones that close on a `Sources:` line. */+function steps(doc: SplitMarkdown): string[] {+ return doc.sections+ .filter((s) => {+ const last = s.body.trim().split("\n").pop() ?? "";+ return /^\W*sources\W*:/i.test(last.trim());+ })+ .map((s) => s.heading)+ .slice(0, MAX_STEPS);+}++const START_ITEM = /^\s*[-*+]\s+`([^`]+)`\s*(?:[-:\u2013\u2014]+\s*(.+))?$/;++/** The first entry of a part's "Where to start reading" list, if it has one. */+function partStart(+ part: DocPage,+ doc: SplitMarkdown,+ pageIdByPath: ReadonlyMap<string, string>,+): StartGroup | undefined {+ const section = doc.sections.find((s) => /^where to start/i.test(s.heading.trim()));+ const match = section?.body+ .split("\n")+ .map((line) => START_ITEM.exec(line))+ .find((m) => m !== null);+ const raw = match?.[1]?.trim();+ if (!raw) return undefined;+ // Entries are written relative to the part's directory; resolve when possible.+ const nested = `${part.target_path.replace(/\/+$/, "")}/${raw.replace(/^\.?\//, "")}`;+ const path = pageIdByPath.has(raw) ? raw : pageIdByPath.has(nested) ? nested : raw;+ return {+ label: part.title,+ note: match?.[2]?.trim() || undefined,+ files: [{ path, pageId: pageIdByPath.get(path) }],};- return pages- .filter((p) => p.page_type === "layer_page")- // Rank on the layer page's target_path, which is the stable ``layer:<slug>``- // id. layer_name is display text the LLM rewrites between generations, so- // ranking on it silently drops every layer to MAX_SAFE_INTEGER.- .sort((a, b) => rankOf(a.target_path) - rankOf(b.target_path));}-export function buildPresentModel(- pages: DocPage[],- opts: { repoName?: string } = {},-): PresentModel {- const overview = pages.find((p) => p.page_type === "repo_overview");- const repoName = deriveRepoName(overview, opts.repoName);+/**+ * The overview's guided-tour stops not already listed (nor repeated),+ * grouped where consecutive stops share a reason, up to `budget` files.+ */+function tourStart(+ overview: DocPage,+ pageIdByPath: ReadonlyMap<string, string>,+ listed: ReadonlySet<string>,+ budget: number,+): StartGroup[] {+ const raw = overview.metadata?.["guided_tour"];+ if (!Array.isArray(raw)) return [];+ const seen = new Set(listed);+ const groups: StartGroup[] = [];+ for (const stop of raw) {+ if (seen.size - listed.size >= budget) break;+ if (!stop || typeof stop !== "object") continue;+ const path = (stop as Record<string, unknown>)["target_path"];+ const reason = (stop as Record<string, unknown>)["reason"];+ if (typeof path !== "string" || !path || seen.has(path)) continue;+ seen.add(path);+ const note = typeof reason === "string" && reason ? reason : undefined;+ const file = { path, pageId: pageIdByPath.get(path) };+ const last = groups[groups.length - 1];+ if (last && !last.label && last.note === note) last.files.push(file);+ else groups.push({ note, files: [file] });+ }+ return groups;+}- const deck: PresentSlide[] = [];+export function buildPresentModel(source: PresentSource): PresentModel {+ const { overview, parts, totalParts, pageIdByPath } = source;+ const overviewDoc = readable(overview);+ const repoName = deriveRepoName(overview);+ const slides: PresentSlide[] = [];+ const shownCharts = new Set<string>();- // 1 — Title- deck.push({+ const summary = opening(overviewDoc, TITLE_CHARS);+ slides.push({id: "title",kind: "title",- eyebrow: "Repository",title: repoName,- bodyMarkdown: overview ? firstProse(overview, 280) : undefined,- sourcePageId: overview?.id,- sourcePath: overview?.target_path,- freshness: overview?.freshness_status,+ body: summary,+ sourcePageId: overview.id,+ freshness: overview.freshness_status,});- // 2 — Architecture diagram slides- const archPage = pages.find((p) => p.page_type === "architecture_diagram");- if (archPage) {- const charts = extractMermaidBlocks(archPage.content).slice(0, 2);- charts.forEach((chart, i) => {- deck.push({- id: `arch-${i}`,- kind: "diagram",- eyebrow: "Architecture",- title: charts.length > 1 ? `${archPage.title} (${i + 1})` : archPage.title,- mermaid: chart,- sourcePageId: archPage.id,- sourcePath: archPage.target_path,- freshness: archPage.freshness_status,- });+ const hero = diagrams(overviewDoc)[0];+ if (hero) {+ shownCharts.add(hero.chart);+ slides.push({+ id: "architecture",+ kind: "architecture",+ eyebrow: "Architecture",+ title: "How it fits together",+ body: caption(hero, summary),+ mermaid: hero.chart,+ sourcePageId: overview.id,+ freshness: overview.freshness_status,});}- // 3 — Layers, ordered by the overview's layer_order when resolvable- const layerPages = orderedLayers(pages, overview).slice(0, MAX_LAYER_SLIDES);- for (const p of layerPages) {- // Layer pages generated with the deterministic architecture diagram embed- // it as a mermaid block; pair prose with diagram in a split slide. Older- // indexes without a diagram degrade to a plain prose section.- const layerChart = extractMermaidBlocks(p.content)[0];- let body = slideBody(p, DECK_BODY_CHARS);- // The diagram renders in its own column on a split slide, so keep any- // embedded fence out of the prose body.- if (layerChart) body = body.replace(/```mermaid[\s\S]*?```/g, "").trim();- deck.push({- id: `layer-${p.id}`,- kind: layerChart ? "split" : "section",- eyebrow: "Layer",- title: p.title,- bodyMarkdown: body,- mermaid: layerChart,- sourcePageId: p.id,- sourcePath: p.target_path,- freshness: p.freshness_status,+ const partDocs = parts.map((page) => ({ page, doc: readable(page) }));+ partDocs.forEach(({ page, doc }, i) => {+ const chart = diagrams(doc)[0]?.chart;+ if (chart) shownCharts.add(chart);+ slides.push({+ id: `part-${page.id}`,+ kind: "part",+ eyebrow: `Part ${i + 1} of ${parts.length}`,+ title: page.title,+ body: opening(doc, PART_CHARS),+ mermaid: chart,+ steps: steps(doc),+ sourcePageId: page.id,+ freshness: page.freshness_status,});- }+ });- // 4 — Modules, richest first (longest content is a decent proxy)- const modulePages = pages- .filter((p) => p.page_type === "module_page")- .sort((a, b) => b.content.length - a.content.length)- .slice(0, MAX_MODULE_SLIDES);- for (const p of modulePages) {- deck.push({- id: `module-${p.id}`,- kind: "section",- eyebrow: "Module",- title: p.title,- bodyMarkdown: slideBody(p, DECK_BODY_CHARS),- sourcePageId: p.id,- sourcePath: p.target_path,- freshness: p.freshness_status,+ // One traced flow: the first sequence diagram no earlier slide has shown.+ const flow = [...partDocs, { page: overview, doc: overviewDoc }]+ .flatMap(({ page, doc }) => diagrams(doc).map((d) => ({ page, doc, d })))+ .find(({ d }) => diagramKind(d.chart) === "sequencediagram" && !shownCharts.has(d.chart));+ if (flow) {+ slides.push({+ id: "flow",+ kind: "flow",+ eyebrow: "One flow, end to end",+ title: flow.d.heading ?? flow.page.title,+ body: caption(flow.d, opening(flow.doc, PART_CHARS)),+ mermaid: flow.d.chart,+ sourcePageId: flow.page.id,+ freshness: flow.page.freshness_status,});}- // 5 — Where to start (guided-tour landmarks as one list slide)- const tour = readTour(overview);- if (tour.length > 0) {- const items = tour- .slice(0, MAX_TOUR_STOPS)- .map((s) => {- const label = s.title || s.target_path || "";- const reason = s.reason ? ` — ${s.reason}` : "";- return `- **${label}**${reason}`;- })- .join("\n");- deck.push({- id: "key-files",- kind: "section",- eyebrow: "Where to start",- title: "Key files to read first",- bodyMarkdown: items,+ const fromParts = partDocs+ .map(({ page, doc }) => partStart(page, doc, pageIdByPath))+ .filter((g): g is StartGroup => g !== undefined);+ // Parts name their own first file; the guided tour fills the rest.+ const listed = new Set(fromParts.flatMap((g) => g.files.map((f) => f.path)));+ const start = [+ ...fromParts,+ ...tourStart(overview, pageIdByPath, listed, MAX_START_FILES - listed.size),+ ];+ const omitted = totalParts - parts.length;+ const scope =+ omitted > 0+ ? `This deck covers ${parts.length} of the ${totalParts} top-level sections. The rest are in the documentation.`+ : undefined;+ if (start.length > 0 || scope) {+ slides.push({+ id: "start",+ kind: "start",+ eyebrow: "Reading list",+ title: "Where to start reading",+ body: scope,+ start,});}- // 6 — Closing- deck.push({- id: "closing",- kind: "closing",- eyebrow: "Keep exploring",- title: "That's the tour",- bodyMarkdown:- "Open any page in the reader for the full detail, ask the assistant a question, or dive into the knowledge graph.",- });-- // Walkthrough — one step per guided-tour stop, in order.- const byPath = new Map(pages.map((p) => [p.target_path, p]));- let walkthrough: PresentStep[] = tour.map((stop, i) => {- const page = stop.target_path ? byPath.get(stop.target_path) : undefined;- const body = page ? slideBody(page, STEP_BODY_CHARS) : "";- const forEstimate = body || stop.reason || stop.title || "";- return {- id: `step-${i}`,- order: stop.order ?? i + 1,- title: stop.title || page?.title || stop.target_path || `Step ${i + 1}`,- reason: stop.reason,- targetPath: stop.target_path,- bodyMarkdown: body,- estMinutes: estimateMinutes(forEstimate),- sourcePageId: page?.id,- freshness: page?.freshness_status,- };- });-- // Fallback: no tour metadata (older/edge indexes) — walk the deck's section- // slides so the walkthrough is never empty when a deck exists.- if (walkthrough.length === 0) {- walkthrough = deck- .filter((s) => (s.kind === "section" || s.kind === "split") && s.bodyMarkdown)- .map((s, i) => ({- id: `step-${i}`,- order: i + 1,- title: s.title,- reason: s.eyebrow,- targetPath: s.sourcePath,- bodyMarkdown: s.bodyMarkdown,- estMinutes: estimateMinutes(s.bodyMarkdown ?? ""),- sourcePageId: s.sourcePageId,- freshness: s.freshness,- }));- }-- const totalMinutes = walkthrough.reduce((sum, s) => sum + s.estMinutes, 0);-- return { repoName, deck, walkthrough, totalMinutes };+ return { repoName, slides };}diff --git a/packages/ui/src/present/deck-view.tsx b/packages/ui/src/present/deck-view.tsxindex 41835bc2f..bad1aeac6 100644--- a/packages/ui/src/present/deck-view.tsx+++ b/packages/ui/src/present/deck-view.tsx@@ -1,181 +1,257 @@"use client";+import { useEffect, useRef } from "react";import { AnimatePresence, motion, useReducedMotion } from "framer-motion";-import { ChevronLeft, ChevronRight, ExternalLink } from "lucide-react";+import { BookOpen, ChevronLeft, ChevronRight } from "lucide-react";import { WikiMarkdown } from "../wiki/wiki-markdown";import { MermaidDiagram } from "../wiki/mermaid-diagram";import { cn } from "../lib/cn";import { SlideProgress } from "./slide-progress";-import type { PresentSlide } from "./types";+import type { PresentSlide, StartGroup } from "./types";-export interface PresentLinkComponent {- (props: { href: string; className?: string; children: React.ReactNode }): React.ReactElement;-}+type OpenPage = ((pageId: string) => void) | undefined;interface DeckViewProps {slides: PresentSlide[];index: number;onIndex: (i: number) => void;- onOpenPage?: ((pageId: string) => void) | undefined;+ onOpenPage?: OpenPage;}-const FRESHNESS_DOT: Record<string, string> = {- fresh: "var(--color-confidence-fresh)",- stale: "var(--color-confidence-stale)",- outdated: "var(--color-confidence-outdated)",+const FOCUS =+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]";++// Fresh is the quiet default; only a source that needs attention is marked.+const FRESHNESS: Record<string, { color: string; word: string }> = {+ stale: { color: "var(--color-confidence-stale)", word: "Source page is stale" },+ outdated: { color: "var(--color-confidence-outdated)", word: "Source page is outdated" },};+function Eyebrow({ children }: { children: React.ReactNode }) {+ return (+ <p className="mb-3 font-mono text-[10px] uppercase tracking-[0.14em] text-[var(--color-text-tertiary)]">+ {children}+ </p>+ );+}++function Body({ markdown, large }: { markdown: string; large?: boolean }) {+ return (+ <div+ className={cn(+ "mt-5 max-w-[65ch] [&_p]:mb-0 [&_p]:leading-[1.65]",+ large ? "[&_p]:text-[18px]" : "[&_p]:text-[16px]",+ )}+ >+ <WikiMarkdown content={markdown} />+ </div>+ );+}++function Steps({ steps }: { steps: string[] }) {+ return (+ <div className="mt-8">+ <Eyebrow>In this part</Eyebrow>+ <ol className="border-t border-[var(--color-border-default)]">+ {steps.map((step, i) => (+ <li+ key={step}+ className="flex gap-3 border-b border-[var(--color-border-default)] py-2.5 text-[15px] text-[var(--color-text-primary)]"+ >+ <span className="w-5 shrink-0 pt-px font-mono text-[12px] tabular-nums text-[var(--color-text-tertiary)]">+ {i + 1}+ </span>+ <span className="min-w-0">{step}</span>+ </li>+ ))}+ </ol>+ </div>+ );+}++function StartList({ groups, onOpenPage }: { groups: StartGroup[]; onOpenPage: OpenPage }) {+ return (+ <ul className="mt-8 border-t border-[var(--color-border-default)]">+ {groups.map((group, i) => (+ <li key={i} className="border-b border-[var(--color-border-default)] py-4">+ {group.label && (+ <p className="mb-1.5 font-mono text-[10px] uppercase tracking-[0.14em] text-[var(--color-text-tertiary)]">+ {group.label}+ </p>+ )}+ <div className="flex flex-col items-start gap-1">+ {group.files.map((file) =>+ file.pageId && onOpenPage ? (+ <button+ key={file.path}+ type="button"+ onClick={() => onOpenPage(file.pageId!)}+ className={cn(+ "max-w-full break-all rounded-sm text-left font-mono text-[15px] text-[var(--color-text-primary)] underline decoration-[var(--color-border-active)] underline-offset-4 transition-colors hover:text-[var(--color-accent-primary)] hover:decoration-[var(--color-accent-primary)]",+ FOCUS,+ )}+ >+ {file.path}+ </button>+ ) : (+ <span key={file.path} className="max-w-full break-all font-mono text-[15px] text-[var(--color-text-secondary)]">+ {file.path}+ </span>+ ),+ )}+ </div>+ {group.note && (+ <p className="mt-1.5 max-w-[65ch] text-[15px] text-[var(--color-text-secondary)]">{group.note}</p>+ )}+ </li>+ ))}+ </ul>+ );+}++function SourceLink({ slide, onOpenPage }: { slide: PresentSlide; onOpenPage: OpenPage }) {+ const fresh = slide.freshness ? FRESHNESS[slide.freshness] : undefined;+ if (!fresh && !(slide.sourcePageId && onOpenPage)) return null;+ return (+ <div className="mt-8 flex flex-wrap items-center gap-x-5 gap-y-2 text-[12px]">+ {slide.sourcePageId && onOpenPage && (+ <button+ type="button"+ onClick={() => onOpenPage(slide.sourcePageId!)}+ className={cn(+ "inline-flex items-center gap-1.5 rounded-sm font-medium text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-accent-primary)]",+ FOCUS,+ )}+ >+ <BookOpen className="h-3.5 w-3.5" aria-hidden />+ Open in docs+ </button>+ )}+ {fresh && (+ <span className="inline-flex items-center gap-1.5 text-[var(--color-text-tertiary)]">+ <span className="h-1.5 w-1.5 rounded-full" style={{ background: fresh.color }} aria-hidden />+ {fresh.word}+ </span>+ )}+ </div>+ );+}++function SlideContent({ slide, onOpenPage }: { slide: PresentSlide; onOpenPage: OpenPage }) {+ const diagram = slide.mermaid ? <MermaidDiagram chart={slide.mermaid} securityLevel="loose" /> : null;+ const heading = (+ <h2+ className={cn(+ "font-serif font-semibold tracking-tight text-[var(--color-text-primary)]",+ slide.kind === "title"+ ? "text-[32px] leading-[1.1] sm:text-[52px]"+ : "text-[24px] leading-tight sm:text-[32px]",+ )}+ >+ {slide.title}+ </h2>+ );+ const prose = (+ <>+ {slide.eyebrow && <Eyebrow>{slide.eyebrow}</Eyebrow>}+ {heading}+ {slide.body && <Body markdown={slide.body} large={slide.kind !== "start"} />}+ </>+ );++ // A part with a diagram pairs its prose with the picture; stacks when narrow.+ if (slide.kind === "part" && diagram) {+ return (+ <div className="grid items-start gap-8 lg:grid-cols-[minmax(0,5fr)_minmax(0,7fr)] lg:gap-12">+ <div className="min-w-0">+ {prose}+ {slide.steps && slide.steps.length > 0 && <Steps steps={slide.steps} />}+ <SourceLink slide={slide} onOpenPage={onOpenPage} />+ </div>+ <div className="min-w-0">{diagram}</div>+ </div>+ );+ }+ return (+ <>+ {prose}+ {diagram && <div className="mt-6">{diagram}</div>}+ {slide.steps && slide.steps.length > 0 && <Steps steps={slide.steps} />}+ {slide.start && slide.start.length > 0 && (+ <StartList groups={slide.start} onOpenPage={onOpenPage} />+ )}+ <SourceLink slide={slide} onOpenPage={onOpenPage} />+ </>+ );+}+export function DeckView({ slides, index, onIndex, onOpenPage }: DeckViewProps) {const reduce = useReducedMotion();+ const scrollRef = useRef<HTMLDivElement | null>(null);const slide = slides[index];+ // Each slide opens at its top, not where the previous one was scrolled to.+ useEffect(() => {+ scrollRef.current?.scrollTo?.({ top: 0 });+ }, [index]);if (!slide) return null;- const atStart = index === 0;- const atEnd = index === slides.length - 1;- const isTitle = slide.kind === "title";- const isDiagram = slide.kind === "diagram";- // A layer slide pairing overview prose (left) with its diagram (right).- const isSplit = slide.kind === "split";- const isWide = isDiagram || isSplit;+ const wide = !!slide.mermaid;+ const navButton = cn(+ "inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-[12px] font-medium text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] disabled:pointer-events-none disabled:opacity-40",+ FOCUS,+ );return (- <div className="relative flex h-full flex-col">- {/* Slide canvas */}+ <div className="flex h-full flex-col">+ {/* Focusable so Up/Down scroll a slide taller than the screen. */}<div- className={cn(- "relative flex flex-1 items-center justify-center overflow-hidden py-4",- isWide ? "px-4 sm:px-8" : "px-6 sm:px-16",- )}+ ref={scrollRef}+ tabIndex={0}+ aria-label="Slide content"+ className={cn("min-h-0 flex-1 overflow-y-auto", FOCUS, "focus-visible:ring-inset")}>- <AnimatePresence mode="wait">- <motion.div- key={slide.id}- initial={reduce ? false : { opacity: 0, y: 12 }}- animate={{ opacity: 1, y: 0 }}- exit={reduce ? { opacity: 0 } : { opacity: 0, y: -12 }}- transition={{ duration: 0.22, ease: "easeOut" }}- className={cn(- "w-full",- isTitle ? "max-w-3xl text-center" : isWide ? "max-w-6xl" : "max-w-3xl text-left",- )}- >- {(() => {- const eyebrowEl = slide.eyebrow ? (- <p className="mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-[var(--color-text-tertiary)]">- {slide.eyebrow}- </p>- ) : null;- const titleEl = (- <h2- className={cn(- "font-serif font-semibold tracking-tight text-[var(--color-text-primary)]",- isTitle- ? "text-5xl sm:text-6xl"- : isWide- ? "text-2xl sm:text-3xl"- : "text-3xl sm:text-4xl",- )}- >- {slide.title}- </h2>- );- const diagramEl = slide.mermaid ? (- <div className={cn("flex justify-center", isSplit ? "" : "mt-4")}>- <div className="w-full">- <MermaidDiagram chart={slide.mermaid} securityLevel="loose" />- </div>- </div>- ) : null;- const bodyEl = slide.bodyMarkdown ? (- <div- className={cn(- "text-[var(--color-text-secondary)]",- isSplit ? "mt-4" : "mt-6",- isTitle ? "mx-auto max-w-xl text-lg" : "text-base",- )}- >- <WikiMarkdown content={slide.bodyMarkdown} />- </div>- ) : null;- const sourceEl =- slide.sourcePageId && onOpenPage ? (- <button- type="button"- onClick={() => onOpenPage(slide.sourcePageId!)}- className={cn(- "mt-6 inline-flex items-center gap-1.5 text-xs font-medium text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-accent-primary)]",- isTitle && "mx-auto",- )}- >- <ExternalLink className="h-3.5 w-3.5" />- Open{slide.sourcePath ? ` ${slide.sourcePath}` : ""} in reader- </button>- ) : null;-- // Split: prose left, diagram right; stacks on narrow screens.- if (isSplit) {- return (- <div className="grid items-center gap-8 md:grid-cols-2">- <div className="min-w-0 text-left">- {eyebrowEl}- {titleEl}- {bodyEl}- {sourceEl}- </div>- <div className="min-w-0">{diagramEl}</div>- </div>- );- }- return (- <>- {eyebrowEl}- {titleEl}- {diagramEl}- {bodyEl}- {sourceEl}- </>- );- })()}- </motion.div>- </AnimatePresence>-- {/* Prev / next click zones */}+ <div className="flex min-h-full items-center px-4 py-10 sm:px-16">+ <AnimatePresence mode="wait" initial={false}>+ <motion.section+ key={slide.id}+ aria-label={slide.title}+ initial={reduce ? false : { opacity: 0, y: 8 }}+ animate={{ opacity: 1, y: 0 }}+ exit={reduce ? { opacity: 1 } : { opacity: 0 }}+ transition={{ duration: reduce ? 0 : 0.18, ease: "easeOut" }}+ className={cn("mx-auto w-full min-w-0", wide ? "max-w-6xl" : "max-w-3xl")}+ >+ <SlideContent slide={slide} onOpenPage={onOpenPage} />+ </motion.section>+ </AnimatePresence>+ </div>+ </div>++ <footer className="flex shrink-0 items-center justify-between gap-3 border-t border-[var(--color-border-default)] px-4 py-3 sm:px-16"><buttontype="button"onClick={() => onIndex(index - 1)}- disabled={atStart}- aria-label="Previous slide"- className="absolute left-3 top-1/2 -translate-y-1/2 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]/70 p-2 text-[var(--color-text-secondary)] backdrop-blur transition-opacity hover:text-[var(--color-text-primary)] disabled:pointer-events-none disabled:opacity-0"+ disabled={index === 0}+ title="Previous (Left arrow)"+ className={navButton}>- <ChevronLeft className="h-5 w-5" />+ <ChevronLeft className="h-4 w-4" aria-hidden />+ <span className="hidden sm:inline">Previous</span>+ <span className="sr-only sm:hidden">Previous slide</span></button>+ <SlideProgress index={index} total={slides.length} title={slide.title} onSelect={onIndex} /><buttontype="button"onClick={() => onIndex(index + 1)}- disabled={atEnd}- aria-label="Next slide"- className="absolute right-3 top-1/2 -translate-y-1/2 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]/70 p-2 text-[var(--color-text-secondary)] backdrop-blur transition-opacity hover:text-[var(--color-text-primary)] disabled:pointer-events-none disabled:opacity-0"+ disabled={index === slides.length - 1}+ title="Next (Right arrow or Space)"+ className={navButton}>- <ChevronRight className="h-5 w-5" />+ <span className="hidden sm:inline">Next</span>+ <span className="sr-only sm:hidden">Next slide</span>+ <ChevronRight className="h-4 w-4" aria-hidden /></button>- </div>-- {/* Footer: freshness + progress */}- <div className="flex shrink-0 items-center justify-between px-6 pb-6 pt-2 sm:px-16">- <div className="flex items-center gap-2">- {slide.freshness && FRESHNESS_DOT[slide.freshness] && (- <span- className="h-1.5 w-1.5 rounded-full"- style={{ background: FRESHNESS_DOT[slide.freshness] }}- title={`Source is ${slide.freshness}`}- />- )}- </div>- <SlideProgress index={index} total={slides.length} onSelect={onIndex} />- <span className="hidden text-[11px] text-[var(--color-text-tertiary)] sm:block">- ← → to navigate- </span>- </div>+ </footer></div>);}diff --git a/packages/ui/src/present/index.ts b/packages/ui/src/present/index.tsindex 3eeab7ce4..1c81da1d3 100644--- a/packages/ui/src/present/index.ts+++ b/packages/ui/src/present/index.ts@@ -1,10 +1,10 @@-// Present mode — on-the-fly slide deck + guided walkthrough over already-loaded-// wiki pages. Framework-light and self-contained so the OSS dashboard and a-// future hosted app share one implementation: the host supplies DocPage[] and-// renders <PresentOverlay>.+// Present mode: a short narrated deck over already-generated wiki pages.+// Framework-light and self-contained so every host shares one implementation:+// the host gathers pages with `loadPresentSource`, builds the model and renders+// <PresentOverlay>.export { buildPresentModel, canPresent } from "./build-present-model";-export { loadPresentPages } from "./load-present-pages";-export { PresentOverlay, type PresentMode } from "./present-overlay";+export { loadPresentSource } from "./load-present-source";+export { PresentOverlay } from "./present-overlay";export { PresentButton } from "./present-button";-export type { PresentModel, PresentSlide, PresentStep, PresentSlideKind } from "./types";+export type { PresentModel, PresentSource } from "./types";diff --git a/packages/ui/src/present/load-present-pages.ts b/packages/ui/src/present/load-present-pages.tsdeleted file mode 100644index b9afeb60d..000000000--- a/packages/ui/src/present/load-present-pages.ts+++ /dev/null@@ -1,68 +0,0 @@-// Gather the pages a Present deck is built from.-//-// `buildPresentModel` needs bodies, but the host's page list no longer carries-// them: on a large wiki that would be tens of megabytes loaded before anything-// renders. A deck only ever draws on a couple of dozen pages, though — the-// overview, the architecture diagram, the first few layers and modules, and the-// guided tour's landmarks — so they can be fetched when Present is opened.-//-// The selection rules live here rather than being re-derived from the builder's-// caps: same constants, same ordering functions, one definition each.--import type { DocPage, DocPageSummary } from "@repowise-dev/types/docs";-import {- MAX_LAYER_SLIDES,- MAX_MODULE_SLIDES,- orderedLayers,- readTour,-} from "./build-present-model";--/** A row is usable as a `DocPage` once it carries both of the heavy fields. */-function isHydrated(page: DocPageSummary): page is DocPage {- return typeof page.content === "string" && page.metadata !== undefined;-}--/**- * Resolve the deck's source pages, fetching bodies only for rows that arrived- * without one. Returns an empty list when there is nothing to present, which- * is the same condition `canPresent` reports.- */-export async function loadPresentPages(- pages: readonly DocPageSummary[],- fetchPage: (pageId: string) => Promise<DocPage>,-): Promise<DocPage[]> {- const hydrate = (page: DocPageSummary): Promise<DocPage> =>- isHydrated(page) ? Promise.resolve(page) : fetchPage(page.id);-- const overviewRow = pages.find((p) => p.page_type === "repo_overview");- if (!overviewRow) return [];- // The overview comes first on its own: the guided tour and the layer order- // are read out of its metadata, and both decide what else is worth fetching.- const overview = await hydrate(overviewRow);-- const wanted: DocPageSummary[] = [overview];-- const arch = pages.find((p) => p.page_type === "architecture_diagram");- if (arch) wanted.push(arch);-- wanted.push(...orderedLayers(pages, overview).slice(0, MAX_LAYER_SLIDES));-- // "Richest first" — the builder proxies richness by body length, which the- // summary reports as content_chars. A row with no count sorts last rather- // than winning on a NaN comparison.- wanted.push(- ...pages- .filter((p) => p.page_type === "module_page")- .sort((a, b) => (b.content_chars ?? 0) - (a.content_chars ?? 0))- .slice(0, MAX_MODULE_SLIDES),- );-- const byPath = new Map(pages.map((p) => [p.target_path, p]));- for (const stop of readTour(overview)) {- const hit = stop.target_path ? byPath.get(stop.target_path) : undefined;- if (hit) wanted.push(hit);- }-- const unique = [...new Map(wanted.map((p) => [p.id, p])).values()];- return Promise.all(unique.map(hydrate));-}diff --git a/packages/ui/src/present/load-present-source.ts b/packages/ui/src/present/load-present-source.tsnew file mode 100644index 000000000..330ac62c2--- /dev/null+++ b/packages/ui/src/present/load-present-source.ts@@ -0,0 +1,83 @@+// Gather the pages a Present deck is built from.+//+// `buildPresentModel` needs bodies, but the host's page list does not carry+// them: on a large wiki that would be tens of megabytes loaded before anything+// renders. A deck only draws on the overview and a handful of major parts, so+// those bodies are fetched when Present is opened.+//+// A major part is a top-level section of the wiki outline. The biggest ones+// (most module pages nested beneath them, then most written) are presented,+// in outline order so the deck follows the documentation tree.++import type { DocPage, DocPageSummary } from "@repowise-dev/types/docs";+import type { PresentSource } from "./types";++const MAX_PARTS = 6;++/** A row is usable as a `DocPage` once it carries both of the heavy fields. */+function isHydrated(page: DocPageSummary): page is DocPage {+ return typeof page.content === "string" && page.metadata !== undefined;+}++/**+ * Top-level module pages, biggest first. A module whose parent is not itself+ * a module page (the overview, or no outline at all) is top-level; its size is+ * the number of module pages nested beneath it.+ */+function rankParts<T extends DocPageSummary>(pages: readonly T[]): T[] {+ const modules = pages.filter((p) => p.page_type === "module_page");+ const byId = new Map(modules.map((p) => [p.id, p]));+ const parentOf = (p: T | undefined) =>+ p?.parent_page_id && byId.has(p.parent_page_id) ? p.parent_page_id : undefined;++ const nested = new Map<string, number>();+ for (const page of modules) {+ // Bounded walk: an outline is shallow, and a malformed cycle must not hang.+ let parent = parentOf(page);+ for (let depth = 0; parent && depth < modules.length; depth++) {+ nested.set(parent, (nested.get(parent) ?? 0) + 1);+ parent = parentOf(byId.get(parent));+ }+ }+ return modules+ .filter((p) => !parentOf(p))+ .sort(+ (a, b) =>+ (nested.get(b.id) ?? 0) - (nested.get(a.id) ?? 0) ||+ (b.content_chars ?? 0) - (a.content_chars ?? 0),+ );+}++/**+ * Resolve the deck's source pages, fetching bodies only for rows that arrived+ * without one. Returns null when there is nothing to present, which is the+ * same condition `canPresent` reports.+ */+export async function loadPresentSource(+ pages: readonly DocPageSummary[],+ fetchPage: (pageId: string) => Promise<DocPage>,+): Promise<PresentSource | null> {+ const hydrate = (page: DocPageSummary): Promise<DocPage> =>+ isHydrated(page) ? Promise.resolve(page) : fetchPage(page.id);++ const overviewRow = pages.find((p) => p.page_type === "repo_overview");+ if (!overviewRow) return null;++ const ranked = rankParts(pages);+ // Outline order for the story; rows without a position keep their rank.+ const chosen = ranked+ .slice(0, MAX_PARTS)+ .map((page, rank) => ({ page, rank }))+ .sort(+ (a, b) =>+ (a.page.display_order ?? Infinity) - (b.page.display_order ?? Infinity) ||+ a.rank - b.rank,+ )+ .map(({ page }) => page);++ const [overview, ...parts] = await Promise.all([overviewRow, ...chosen].map(hydrate));+ const pageIdByPath = new Map(+ pages.filter((p) => p.page_type === "file_page").map((p) => [p.target_path, p.id]),+ );+ return { overview: overview!, parts, totalParts: ranked.length, pageIdByPath };+}diff --git a/packages/ui/src/present/present-overlay.tsx b/packages/ui/src/present/present-overlay.tsxindex 2b3bb544c..f9cd31cdf 100644--- a/packages/ui/src/present/present-overlay.tsx+++ b/packages/ui/src/present/present-overlay.tsx@@ -1,57 +1,31 @@"use client";-import { useCallback, useEffect, useState } from "react";-import { X, Presentation, Route } from "lucide-react";-import { cn } from "../lib/cn";+import { useCallback, useEffect, useRef, useState } from "react";+import { X } from "lucide-react";import { DeckView } from "./deck-view";-import { WalkthroughView } from "./walkthrough-view";import { usePresentKeyboard } from "./use-present-keyboard";import type { PresentModel } from "./types";-export type PresentMode = "deck" | "walkthrough";-interface PresentOverlayProps {model: PresentModel;- initialMode?: PresentMode;onClose: () => void;- onModeChange?: (mode: PresentMode) => void;/** Jump to a page in the reader (host closes the overlay + navigates). */onOpenPage?: (pageId: string) => void;}-const MODES: { value: PresentMode; label: string; icon: typeof Presentation }[] = [- { value: "deck", label: "Deck", icon: Presentation },- { value: "walkthrough", label: "Walkthrough", icon: Route },-];-/*** Full-screen, keyboard-driven presentation surface. Escapes the dashboard* chrome entirely (fixed inset-0), locks page scroll, and is theme-aware via- * CSS tokens only. Holds a separate index per mode so toggling Deck /- * Walkthrough preserves each one's position.+ * CSS tokens only. Slides sit on the base plane; the bar above is chrome.*/-export function PresentOverlay({ model, initialMode = "deck", onClose, onModeChange, onOpenPage }: PresentOverlayProps) {- const [mode, setMode] = useState<PresentMode>(initialMode);- const [deckIndex, setDeckIndex] = useState(0);- const [stepIndex, setStepIndex] = useState(0);+export function PresentOverlay({ model, onClose, onOpenPage }: PresentOverlayProps) {+ const [index, setIndex] = useState(0);+ const dialogRef = useRef<HTMLDivElement | null>(null);+ const total = model.slides.length;- const hasWalkthrough = model.walkthrough.length > 0;- const total = mode === "deck" ? model.deck.length : model.walkthrough.length;- const index = mode === "deck" ? deckIndex : stepIndex;- const setIndex = mode === "deck" ? setDeckIndex : setStepIndex;+ const goto = useCallback((i: number) => setIndex(Math.min(total - 1, Math.max(0, i))), [total]);- const clamp = useCallback((i: number) => Math.min(total - 1, Math.max(0, i)), [total]);- const goto = useCallback((i: number) => setIndex(clamp(i)), [setIndex, clamp]);-- const switchMode = useCallback(- (next: PresentMode) => {- setMode(next);- onModeChange?.(next);- },- [onModeChange],- );-- usePresentKeyboard({+ usePresentKeyboard(dialogRef, {onPrev: () => goto(index - 1),onNext: () => goto(index + 1),onFirst: () => goto(0),@@ -59,79 +33,45 @@ export function PresentOverlay({ model, initialMode = "deck", onClose, onModeChaonClose,});- // Lock page scroll for the overlay's lifetime.+ // Lock page scroll and take focus for the overlay's lifetime; hand focus+ // back to whatever opened it on close.useEffect(() => {+ const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;const prev = document.body.style.overflow;document.body.style.overflow = "hidden";+ dialogRef.current?.focus();return () => {document.body.style.overflow = prev;+ opener?.focus();};}, []);return (<div+ ref={dialogRef}+ tabIndex={-1}role="dialog"aria-modal="true"- aria-label="Repository presentation"- className="fixed inset-0 z-[var(--z-modal)] flex flex-col bg-[var(--color-bg-inset)]"+ aria-label={`${model.repoName} presentation`}+ className="fixed inset-0 z-[var(--z-modal)] flex flex-col bg-[var(--color-bg-root)] outline-none">- {/* Top bar */}- <header className="flex h-12 shrink-0 items-center justify-between border-b border-[var(--color-border-default)] bg-[var(--color-bg-root)]/80 px-4 backdrop-blur">- <div className="flex items-center rounded-lg bg-[var(--color-bg-elevated)] p-0.5" role="tablist" aria-label="Presentation mode">- {MODES.map((m) => {- const Icon = m.icon;- const disabled = m.value === "walkthrough" && !hasWalkthrough;- const active = mode === m.value;- return (- <button- key={m.value}- type="button"- role="tab"- aria-selected={active}- disabled={disabled}- onClick={() => switchMode(m.value)}- className={cn(- "flex items-center gap-1.5 rounded-md px-3 py-1 text-xs font-medium transition-colors disabled:opacity-40",- active- ? "bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] shadow-sm"- : "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",- )}- >- <Icon className="h-3.5 w-3.5" />- {m.label}- </button>- );- })}- </div>-- <span className="pointer-events-none absolute left-1/2 hidden -translate-x-1/2 text-xs font-medium text-[var(--color-text-tertiary)] sm:block">+ <header className="flex h-12 shrink-0 items-center justify-between gap-3 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-4">+ <span className="min-w-0 truncate text-[12px] font-medium text-[var(--color-text-secondary)]">{model.repoName}</span>-<buttontype="button"onClick={onClose}aria-label="Close presentation (Esc)"title="Close (Esc)"- className="rounded-md p-1.5 text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"+ className="rounded-md p-1.5 text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"><X className="h-4 w-4" /></button></header>- {/* Body */}<div className="min-h-0 flex-1">- {mode === "deck" ? (- <DeckView slides={model.deck} index={deckIndex} onIndex={goto} onOpenPage={onOpenPage} />- ) : (- <WalkthroughView- steps={model.walkthrough}- index={stepIndex}- onIndex={goto}- totalMinutes={model.totalMinutes}- onOpenPage={onOpenPage}- />- )}+ <DeckView slides={model.slides} index={index} onIndex={goto} onOpenPage={onOpenPage} /></div></div>);diff --git a/packages/ui/src/present/slide-progress.tsx b/packages/ui/src/present/slide-progress.tsxindex dcb18bd37..c54bcda72 100644--- a/packages/ui/src/present/slide-progress.tsx+++ b/packages/ui/src/present/slide-progress.tsx@@ -3,51 +3,47 @@import { cn } from "../lib/cn";/**- * Bottom-of-deck progress: clickable dots when the deck is short, a slim bar- * when it's long, always with a "n / total" counter. Accent marks the current- * slide; everything else stays neutral (Linear-style restraint).+ * Bottom-of-deck progress: one clickable dot per slide (a deck is at most a+ * dozen slides) and an "n / total" counter. Accent marks the current slide;+ * everything else stays neutral.*/export function SlideProgress({index,total,+ title,onSelect,}: {index: number;total: number;+ /** Announced with the position, so a screen reader hears what the slide is. */+ title: string;onSelect: (i: number) => void;}) {- const showDots = total <= 16;return (<div className="flex items-center gap-3">- {showDots ? (- <div className="flex items-center gap-1.5">- {Array.from({ length: total }).map((_, i) => (- <button- key={i}- type="button"- onClick={() => onSelect(i)}- aria-label={`Go to slide ${i + 1}`}- aria-current={i === index ? "true" : undefined}- className={cn(- "h-1.5 rounded-full transition-all",- i === index- ? "w-5 bg-[var(--color-accent-primary)]"- : "w-1.5 bg-[var(--color-border-active)] hover:bg-[var(--color-text-tertiary)]",- )}- />- ))}- </div>- ) : (- <div className="h-1.5 w-40 overflow-hidden rounded-full bg-[var(--color-border-active)]">- <div- className="h-full rounded-full bg-[var(--color-accent-primary)] transition-all"- style={{ width: `${((index + 1) / total) * 100}%` }}+ <div className="hidden items-center gap-1.5 sm:flex">+ {Array.from({ length: total }).map((_, i) => (+ <button+ key={i}+ type="button"+ onClick={() => onSelect(i)}+ aria-label={`Go to slide ${i + 1}`}+ aria-current={i === index ? "step" : undefined}+ className={cn(+ "h-1.5 rounded-full transition-all motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]",+ i === index+ ? "w-5 bg-[var(--color-accent-primary)]"+ : "w-1.5 bg-[var(--color-border-active)] hover:bg-[var(--color-text-tertiary)]",+ )}/>- </div>- )}- <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">+ ))}+ </div>+ <span aria-hidden className="font-mono text-[12px] tabular-nums text-[var(--color-text-tertiary)]">{index + 1} / {total}</span>+ <span aria-live="polite" className="sr-only">+ Slide {index + 1} of {total}: {title}+ </span></div>);}diff --git a/packages/ui/src/present/split-markdown.ts b/packages/ui/src/present/split-markdown.tsindex 199e9d012..24880031b 100644--- a/packages/ui/src/present/split-markdown.ts+++ b/packages/ui/src/present/split-markdown.ts@@ -1,6 +1,6 @@// Small, dependency-free markdown helpers for turning a wiki page into slide-// material. All fence-aware so a `## ` or ``` inside a fenced code block is-// never mistaken for a heading or a block boundary (same care as+// material. All fence-aware so a `## ` or a blank line inside a fenced block is+// never mistaken for a heading or a paragraph boundary (same care as// reader-persona's filter).export interface MarkdownSection {@@ -86,33 +86,78 @@ export function extractMermaidBlocks(markdown: string): string[] {return blocks;}-/** Remove fenced code and mermaid blocks (used only for word counting). */-function stripFences(markdown: string): string {- return markdown.replace(/```[\s\S]*?```/g, " ");+/** Split markdown into blank-line separated blocks, keeping fences whole. */+export function splitBlocks(markdown: string): string[] {+ const blocks: string[] = [];+ let buf: string[] = [];+ let inFence = false;+ const flush = () => {+ const text = buf.join("\n").trim();+ if (text) blocks.push(text);+ buf = [];+ };+ for (const line of markdown.split("\n")) {+ if (FENCE.test(line)) inFence = !inFence;+ if (!inFence && line.trim() === "") flush();+ else buf.push(line);+ }+ flush();+ return blocks;}-export function countWords(markdown: string): number {- const text = stripFences(markdown).replace(/[#>*`_\-|]/g, " ");- const words = text.trim().split(/\s+/).filter(Boolean);- return words.length;+/**+ * Whether a block reads as explanatory prose: not a heading, list, table,+ * fence, quote, rule, an emphasis-only footnote or a `**Label:** value` stat+ * line, and it ends a sentence (or introduces a list with a colon).+ */+export function isProse(block: string): boolean {+ const text = block.trim();+ if (text.length < 40) return false;+ if (/^(#|\||>|```|---|\*\*\*|[-*+]\s|\d+[.)]\s)/.test(text)) return false;+ if (/^\*\*[^*\n]+:\*\*/.test(text)) return false;+ if (/^([*_])[^*_][\s\S]*\1$/.test(text)) return false;+ return /[.!?:][)"'`*_]*$/.test(text);}/**- * Trim prose to a slide-sized excerpt on a paragraph boundary. Keeps whole- * paragraphs up to `maxChars`, and always returns at least the first paragraph- * so a slide is never blank when the first block is long.+ * Keep whole sentences up to `maxChars`. Always returns at least the first+ * sentence, however long, so a slide never ends mid-thought.*/-export function clampProse(markdown: string, maxChars: number): string {- const trimmed = markdown.trim();- if (trimmed.length <= maxChars) return trimmed;- const paras = trimmed.split(/\n{2,}/);- const out: string[] = [];- let len = 0;- for (const p of paras) {- if (out.length > 0 && len + p.length > maxChars) break;- out.push(p);- len += p.length + 2;- if (len >= maxChars) break;+export function wholeSentences(paragraph: string, maxChars: number): string {+ const text = paragraph.replace(/\s*\n\s*/g, " ").trim();+ // A sentence ends at . ! ? followed by a space and an uppercase or markup+ // start, so "e.g. the" and "v1.2" do not split.+ const sentences = text.split(/(?<=[.!?][)"'`*_]*)\s+(?=[A-Z`*_("[])/);+ let out = sentences[0] ?? "";+ for (const s of sentences.slice(1)) {+ if (out.length + 1 + s.length > maxChars) break;+ out += ` ${s}`;}- return out.join("\n\n").trim();+ return out;+}++/**+ * The diagram type a mermaid source declares: the first word after any+ * front matter block, `%%` comments and `%%{init}%%` directives.+ */+export function diagramKind(chart: string): string {+ const body = chart.trimStart().replace(/^---\r?\n[\s\S]*?\n---[ \t]*(\r?\n|$)/, "");+ const line = body+ .split("\n")+ .map((l) => l.trim())+ .find((l) => l !== "" && !l.startsWith("%%"));+ return (line?.split(/\s/, 1)[0] ?? "").toLowerCase();+}++/**+ * Whether a diagram has anything to show. A flowchart with no edges is a row+ * of boxes, which says less than the list it came from; every other kind is+ * taken as drawn.+ */+export function isDrawable(chart: string): boolean {+ const kind = diagramKind(chart);+ if (kind !== "flowchart" && kind !== "graph") return true;+ return chart+ .split("\n")+ .some((line) => /(--|==|-\.|~~~)/.test(line.replace(/"[^"]*"/g, "")));}diff --git a/packages/ui/src/present/types.ts b/packages/ui/src/present/types.tsindex c1ec57675..da4c5a4d1 100644--- a/packages/ui/src/present/types.ts+++ b/packages/ui/src/present/types.ts@@ -1,52 +1,65 @@-// Present mode — the data model for an on-the-fly slide deck + guided-// walkthrough, built entirely from already-generated wiki pages. No new-// generation, no network, no DB: `buildPresentModel` (build-present-model.ts)-// transforms the loaded `DocPage[]` into this shape, and the overlay renders it.+// Present mode: a short narrated deck built entirely from already-generated+// wiki pages. No new generation, no network, no DB: `buildPresentModel`+// (build-present-model.ts) turns the loaded pages into this shape, and the+// overlay renders it.//-// Kept framework-free (plain data) so the same model serves the OSS dashboard-// and a future hosted app without re-implementing any logic.+// Kept framework-free (plain data) so every host renders the same deck.-// "split" pairs overview prose with a diagram side by side (used for layer-// pages that carry a deterministic architecture diagram).-export type PresentSlideKind = "title" | "section" | "diagram" | "split" | "closing";+import type { DocPage } from "@repowise-dev/types/docs";++/**+ * The deck's story, in order: what the repository is, how it fits together,+ * each major part, one flow end to end, and where to start reading.+ */+export type PresentSlideKind = "title" | "architecture" | "part" | "flow" | "start";++export interface StartFile {+ path: string;+ /** Page to open for this file, when the wiki has one. */+ pageId?: string | undefined;+}++/** A group of files to read first, with why they are worth opening. */+export interface StartGroup {+ /** The part the files belong to, when they came from a part's page. */+ label?: string | undefined;+ note?: string | undefined;+ files: StartFile[];+}export interface PresentSlide {- /** Stable id within the deck (slug), used as a React key. */+ /** Stable id within the deck, used as a React key. */id: string;kind: PresentSlideKind;- /** Small uppercase label above the title (e.g. "Architecture", "Module"). */+ /** Small label above the title (e.g. "Part 2 of 5"). */eyebrow?: string | undefined;title: string;- /** Prose body rendered via WikiMarkdown. Omitted on pure-diagram slides. */- bodyMarkdown?: string | undefined;- /** Mermaid source for a diagram slide, rendered via MermaidDiagram. */+ /** Whole-sentence prose rendered via WikiMarkdown. */+ body?: string | undefined;+ /** Mermaid source rendered via MermaidDiagram. */mermaid?: string | undefined;- /** Page this slide was derived from, so "open in reader" can jump there. */- sourcePageId?: string | undefined;- sourcePath?: string | undefined;- /** Freshness of the source page (fresh/stale/outdated), for a subtle dot. */- freshness?: string | undefined;-}--export interface PresentStep {- id: string;- order: number;- title: string;- /** One-line "why this matters" pulled from the guided-tour stop. */- reason?: string | undefined;- targetPath?: string | undefined;- /** Reading body for the step, rendered via WikiMarkdown. */- bodyMarkdown?: string | undefined;- /** Deterministic reading-time estimate in minutes. */- estMinutes: number;+ /** Step-named section headings of a part, in reading order. */+ steps?: string[] | undefined;+ /** Files to read first (the closing slide only). */+ start?: StartGroup[] | undefined;+ /** Page this slide was derived from, so "open in docs" can jump there. */sourcePageId?: string | undefined;+ /** Freshness of the source page (fresh/stale/outdated). */freshness?: string | undefined;}export interface PresentModel {repoName: string;- deck: PresentSlide[];- walkthrough: PresentStep[];- /** Sum of every walkthrough step's estMinutes. */- totalMinutes: number;+ slides: PresentSlide[];+}++/** The pages a deck is built from, as gathered by `loadPresentSource`. */+export interface PresentSource {+ overview: DocPage;+ /** The major parts, in the order the deck presents them. */+ parts: DocPage[];+ /** How many top-level parts the wiki has, of which `parts` is a selection. */+ totalParts: number;+ /** Page id per file path, so "where to start" entries can open their page. */+ pageIdByPath: ReadonlyMap<string, string>;}diff --git a/packages/ui/src/present/use-present-keyboard.ts b/packages/ui/src/present/use-present-keyboard.tsindex 495887720..4c474c0a5 100644--- a/packages/ui/src/present/use-present-keyboard.ts+++ b/packages/ui/src/present/use-present-keyboard.ts@@ -1,58 +1,81 @@"use client";-import { useEffect } from "react";+import { useEffect, type RefObject } from "react";interface PresentKeys {onPrev: () => void;onNext: () => void;onClose: () => void;- onFirst?: () => void;- onLast?: () => void;+ onFirst: () => void;+ onLast: () => void;+}++const FOCUSABLE =+ 'a[href], button:not([disabled]), input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])';++/** Keep Tab inside `dialog`, wrapping at either end. */+function trapTab(e: KeyboardEvent, dialog: HTMLElement) {+ const items = [...dialog.querySelectorAll<HTMLElement>(FOCUSABLE)];+ const first = items[0];+ const last = items[items.length - 1];+ if (!first || !last) {+ e.preventDefault();+ dialog.focus();+ return;+ }+ const active = document.activeElement;+ const inside = active instanceof Node && dialog.contains(active) && active !== dialog;+ if (!inside || (e.shiftKey && active === first) || (!e.shiftKey && active === last)) {+ e.preventDefault();+ (e.shiftKey ? last : first).focus();+ }}/**- * Global keyboard navigation for the Present overlay: ←/PageUp = prev,- * →/PageDown/Space = next, Home/End = first/last, Escape = close. Ignores key- * events while a text input/textarea is focused so nothing is hijacked.+ * Keyboard for the Present dialog: Left/PageUp = prev, Right/PageDown/Space =+ * next, Home/End = first/last, Escape = close, Tab stays inside. Ignores keys+ * while a text field is focused, and Space on a button so it still presses it.+ *+ * A modal opened from a slide (a maximized diagram) owns every key while it is+ * mounted, so the deck neither moves nor closes underneath it.*/-export function usePresentKeyboard({ onPrev, onNext, onClose, onFirst, onLast }: PresentKeys) {+export function usePresentKeyboard(+ dialogRef: RefObject<HTMLElement | null>,+ { onPrev, onNext, onClose, onFirst, onLast }: PresentKeys,+) {useEffect(() => {const onKey = (e: KeyboardEvent) => {+ const dialog = dialogRef.current;+ if (!dialog) return;+ const nested = [...document.querySelectorAll('[role="dialog"][aria-modal="true"]')].some(+ (el) => el !== dialog,+ );+ if (nested) return;+ if (e.key === "Tab") {+ trapTab(e, dialog);+ return;+ }const target = e.target as HTMLElement | null;if (target && (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable)) {return;}- switch (e.key) {- case "ArrowRight":- case "PageDown":- case " ":- e.preventDefault();- onNext();- break;- case "ArrowLeft":- case "PageUp":- e.preventDefault();- onPrev();- break;- case "Home":- if (onFirst) {- e.preventDefault();- onFirst();- }- break;- case "End":- if (onLast) {- e.preventDefault();- onLast();- }- break;- case "Escape":- e.preventDefault();- onClose();- break;- }+ if (e.key === " " && target?.closest?.("button, a")) return;+ const action: Record<string, () => void> = {+ ArrowRight: onNext,+ PageDown: onNext,+ " ": onNext,+ ArrowLeft: onPrev,+ PageUp: onPrev,+ Home: onFirst,+ End: onLast,+ Escape: onClose,+ };+ const run = action[e.key];+ if (!run) return;+ e.preventDefault();+ run();};- document.addEventListener("keydown", onKey);- return () => document.removeEventListener("keydown", onKey);- }, [onPrev, onNext, onClose, onFirst, onLast]);+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [dialogRef, onPrev, onNext, onClose, onFirst, onLast]);}diff --git a/packages/ui/src/present/walkthrough-view.tsx b/packages/ui/src/present/walkthrough-view.tsxdeleted file mode 100644index 2b2c8cbe4..000000000--- a/packages/ui/src/present/walkthrough-view.tsx+++ /dev/null@@ -1,138 +0,0 @@-"use client";--import { Check, Clock, ChevronLeft, ChevronRight, ExternalLink } from "lucide-react";-import { WikiMarkdown } from "../wiki/wiki-markdown";-import { cn } from "../lib/cn";-import type { PresentStep } from "./types";--interface WalkthroughViewProps {- steps: PresentStep[];- index: number;- onIndex: (i: number) => void;- totalMinutes: number;- onOpenPage?: ((pageId: string) => void) | undefined;-}--export function WalkthroughView({ steps, index, onIndex, totalMinutes, onOpenPage }: WalkthroughViewProps) {- const step = steps[index];- if (!step) return null;-- const pct = ((index + 1) / steps.length) * 100;-- return (- <div className="flex h-full min-h-0">- {/* Step rail */}- <aside className="hidden w-72 shrink-0 flex-col border-r border-[var(--color-border-default)] bg-[var(--color-bg-surface)] md:flex">- <div className="shrink-0 border-b border-[var(--color-border-default)] px-4 py-3">- <div className="flex items-center justify-between">- <span className="text-xs font-semibold uppercase tracking-wider text-[var(--color-text-tertiary)]">- Walkthrough- </span>- <span className="inline-flex items-center gap-1 rounded-full bg-[var(--color-bg-elevated)] px-2 py-0.5 text-[11px] text-[var(--color-text-secondary)]">- <Clock className="h-3 w-3" />~{totalMinutes} min- </span>- </div>- <div className="mt-2 h-1 w-full overflow-hidden rounded-full bg-[var(--color-border-active)]">- <div className="h-full rounded-full bg-[var(--color-accent-primary)] transition-all" style={{ width: `${pct}%` }} />- </div>- </div>- <nav className="flex-1 overflow-y-auto p-2">- {steps.map((s, i) => {- const done = i < index;- const current = i === index;- return (- <button- key={s.id}- type="button"- onClick={() => onIndex(i)}- className={cn(- "flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-sm transition-colors",- current- ? "bg-[var(--color-accent-muted)] text-[var(--color-text-primary)]"- : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",- )}- >- <span- className={cn(- "flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[11px] font-semibold",- done- ? "bg-[var(--color-accent-primary)] text-[var(--color-text-on-accent)]"- : current- ? "border border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"- : "border border-[var(--color-border-active)] text-[var(--color-text-tertiary)]",- )}- >- {done ? <Check className="h-3 w-3" /> : i + 1}- </span>- <span className="min-w-0 flex-1 truncate">{s.title}</span>- </button>- );- })}- </nav>- </aside>-- {/* Content pane */}- <div className="flex min-h-0 flex-1 flex-col">- <div className="flex-1 overflow-y-auto px-6 py-8 sm:px-12">- <div className="mx-auto max-w-3xl">- <p className="mb-2 text-xs font-semibold uppercase tracking-[0.14em] text-[var(--color-text-tertiary)]">- Step {index + 1} of {steps.length} · ~{step.estMinutes} min- </p>- <h2 className="font-serif text-3xl font-semibold tracking-tight text-[var(--color-text-primary)]">- {step.title}- </h2>- {step.reason && (- <div className="mt-4 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-4 py-3">- <p className="text-xs font-semibold uppercase tracking-wider text-[var(--color-text-tertiary)]">- Why this matters- </p>- <p className="mt-1 text-sm text-[var(--color-text-secondary)]">{step.reason}</p>- </div>- )}- {step.bodyMarkdown ? (- <div className="mt-6 text-base text-[var(--color-text-secondary)]">- <WikiMarkdown content={step.bodyMarkdown} />- </div>- ) : (- <p className="mt-6 text-sm text-[var(--color-text-tertiary)]">- No generated page for this file yet. Open it in the reader to read the source.- </p>- )}- {step.sourcePageId && onOpenPage && (- <button- type="button"- onClick={() => onOpenPage(step.sourcePageId!)}- className="mt-6 inline-flex items-center gap-1.5 text-xs font-medium text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-accent-primary)]"- >- <ExternalLink className="h-3.5 w-3.5" />- Open{step.targetPath ? ` ${step.targetPath}` : ""} in reader- </button>- )}- </div>- </div>-- {/* Footer nav */}- <div className="flex shrink-0 items-center justify-between border-t border-[var(--color-border-default)] px-6 py-3 sm:px-12">- <button- type="button"- onClick={() => onIndex(index - 1)}- disabled={index === 0}- className="inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] disabled:pointer-events-none disabled:opacity-40"- >- <ChevronLeft className="h-4 w-4" />- Prev- </button>- <button- type="button"- onClick={() => onIndex(index + 1)}- disabled={index === steps.length - 1}- className="inline-flex items-center gap-1.5 rounded-md bg-[var(--color-accent-fill)] px-4 py-1.5 text-sm font-medium text-[var(--color-text-on-accent)] shadow-[var(--shadow-button)] transition-[filter] hover:brightness-[1.06] disabled:pointer-events-none disabled:opacity-40"- >- Next stop- <ChevronRight className="h-4 w-4" />- </button>- </div>- </div>- </div>- );-}diff --git a/packages/web/src/components/docs/docs-explorer.tsx b/packages/web/src/components/docs/docs-explorer.tsxindex 0e7906926..3d3f8412c 100644--- a/packages/web/src/components/docs/docs-explorer.tsx+++ b/packages/web/src/components/docs/docs-explorer.tsx@@ -13,8 +13,7 @@ import {PresentOverlay,buildPresentModel,canPresent,- loadPresentPages,- type PresentMode,+ loadPresentSource,} from "@repowise-dev/ui/present";import {DEFAULT_PERSONA,@@ -149,29 +148,27 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {router.replace(`?${params.toString()}`, { scroll: false });}, [searchParams, router]);- // Present mode — an on-the-fly slide deck + guided walkthrough over the same- // loaded pages. Open state lives in ?present=deck|walkthrough so a specific- // mode is shareable. The model is derived, never generated or fetched.+ // Present mode: a short deck derived from the same pages, never generated.+ // Open state lives in ?present so a deck link is shareable; any value opens+ // it, which keeps older ?present=deck links working.const presentable = useMemo(() => canPresent(pages), [pages]);- const presentParam = searchParams.get("present");- const presentMode: PresentMode | null =- presentParam === "walkthrough" ? "walkthrough" : presentParam === "deck" ? "deck" : null;- // A deck draws on a couple of dozen pages out of thousands, so their bodies- // are fetched when Present is opened rather than carried by the page list.+ const presentOpen = searchParams.has("present");+ // A deck draws on a handful of pages out of thousands, so their bodies are+ // fetched when Present is opened, not carried by the page list.const { data: presentModel = null } = useSWR(- presentable && presentMode ? `present:${repoId}` : null,+ presentable && presentOpen ? `present:${repoId}` : null,async () => {- const source = await loadPresentPages(pages, (id) =>+ const source = await loadPresentSource(pages, (id) =>getPageById(id, repoId) as Promise<DocPage>,);- return source.length > 0 ? buildPresentModel(source) : null;+ return source ? buildPresentModel(source) : null;},{ revalidateOnFocus: false },);const setPresent = useCallback(- (mode: PresentMode | null, pageId?: string) => {+ (open: boolean, pageId?: string) => {const params = new URLSearchParams(searchParams.toString());- if (mode) params.set("present", mode);+ if (open) params.set("present", "deck");else params.delete("present");if (pageId) params.set("page", pageId);const qs = params.toString();@@ -182,7 +179,7 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {const openInReaderFromPresent = useCallback((pageId: string) => {setSelectedPageId(pageId);- setPresent(null, pageId);+ setPresent(false, pageId);},[setPresent],);@@ -396,7 +393,7 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {page={selectedPage}repoId={repoId}/>- {presentable && <PresentButton onClick={() => setPresent("deck")} />}+ {presentable && <PresentButton onClick={() => setPresent(true)} />}{selectedPage && (<SidebarToggleopen={sidebarOpen}@@ -409,12 +406,10 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {</div>{/* Present mode overlay — full-screen, escapes the dashboard chrome */}- {presentMode && presentModel && (+ {presentOpen && presentModel && (<PresentOverlaymodel={presentModel}- initialMode={presentMode}- onClose={() => setPresent(null)}- onModeChange={(m) => setPresent(m)}+ onClose={() => setPresent(false)}onOpenPage={openInReaderFromPresent}/>)}