Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(web): add a Setup page, a setup pill and grouped settings (#4683)
Raghav Chamadiya52336cda3627
diff --git a/packages/ui/__tests__/health/setup-prompt.test.ts b/packages/ui/__tests__/health/setup-prompt.test.tsnew file mode 100644index 000000000..d0c0ef957--- /dev/null+++ b/packages/ui/__tests__/health/setup-prompt.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from "vitest";+import { buildSetupAiPrompt, type SetupPromptRow } from "../../src/health/ai-prompt-builder.js";++const SYNC: SetupPromptRow = {+ repoName: "orbit-api",+ title: "Keep the index in sync",+ state: "The post-commit hook is not installed, so the index updates only on `repowise update`.",+ command: "repowise hook install",+ verify: "status",+};++describe("buildSetupAiPrompt", () => {+ it("carries the repo, the detected state, the exact command and the status check", () => {+ const prompt = buildSetupAiPrompt(SYNC);+ expect(prompt).toContain("## Setup: Keep the index in sync (`orbit-api`)");+ expect(prompt).toContain(`What repowise detected: ${SYNC.state}`);+ expect(prompt).toContain("```\nrepowise hook install\n```");+ expect(prompt).toContain("`repowise status`");+ expect(prompt).not.toContain("Confirm with me before changing anything");+ });++ it("asks a fix to confirm before changing anything and verifies with doctor", () => {+ const prompt = buildSetupAiPrompt({+ ...SYNC,+ title: "Index",+ state: "3 files could not be parsed.",+ command: "repowise doctor --format json",+ verify: "doctor",+ fix: true,+ items: ["src/legacy/report.py", "scripts/gen.py"],+ });+ expect(prompt).toContain("Confirm with me before changing anything");+ expect(prompt).toContain("Find out why first");+ expect(prompt).toContain("`repowise doctor --format json` afterwards");+ expect(prompt).toContain("- `src/legacy/report.py`\n- `scripts/gen.py`");+ });++ it("lists at most 20 items and counts the rest", () => {+ const items = Array.from({ length: 23 }, (_, i) => `f${i}.py`);+ const prompt = buildSetupAiPrompt({ ...SYNC, items });+ expect(prompt).toContain("- `f19.py`");+ expect(prompt).not.toContain("`f20.py`");+ expect(prompt).toContain("- and 3 more");+ });++ it("opens with the flavor's role", () => {+ expect(buildSetupAiPrompt(SYNC, "claude-code").startsWith("You are Claude Code")).toBe(true);+ });+});diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.tsindex 9396ab8a1..fdcae14fa 100644--- a/packages/ui/src/health/ai-prompt-builder.ts+++ b/packages/ui/src/health/ai-prompt-builder.ts@@ -98,6 +98,7 @@ export {type AreaPromptFinding,type BuildAreaPromptOptions,} from "./ai-prompts/area-prompt";+export { buildSetupAiPrompt, type SetupPromptRow } from "./ai-prompts/setup-prompt";export {buildPerformanceAreaPrompt,type BuildPerformanceAreaPromptOptions,diff --git a/packages/ui/src/health/ai-prompts/setup-prompt.ts b/packages/ui/src/health/ai-prompts/setup-prompt.tsnew file mode 100644index 000000000..b70c40bbd--- /dev/null+++ b/packages/ui/src/health/ai-prompts/setup-prompt.ts@@ -0,0 +1,81 @@+import { bulletList, REPO_ROLE, repoSuffix, type AiPromptFlavor } from "./shared";++// ─────────────────────────────────────────────────────────────────────+// Setup prompt: one Setup page row, handed to the agent to finish or fix+// ─────────────────────────────────────────────────────────────────────++export interface SetupPromptRow {+ /** The repository, as the dashboard names it. */+ repoName: string;+ /** The row's title, e.g. "Keep the index in sync". */+ title: string;+ /** What repowise detected, in a sentence or two. */+ state: string;+ /** The exact command that makes the change. */+ command: string;+ /** How the agent checks the result. */+ verify: "status" | "doctor";+ /** Something is wrong: the agent investigates and confirms before changing anything. */+ fix?: boolean;+ /** Paths or names the state refers to, listed under it. */+ items?: string[];+}++const VERIFY: Record<SetupPromptRow["verify"], string> = {+ status: "Run `repowise status` afterwards and tell me what it reports for this repository.",+ doctor:+ "Run `repowise doctor --format json` afterwards and tell me the level and detail of the matching check.",+};++const MAX_ITEMS = 20;++function itemLines(items: string[] | undefined): string | null {+ if (!items?.length) return null;+ const shown = items.slice(0, MAX_ITEMS).map((item) => `\`${item}\``);+ const more = items.length - shown.length;+ return bulletList([...shown, more > 0 ? `and ${more} more` : null]);+}++/**+ * A prompt for one Setup row: the repo, what was detected, the exact command+ * and how to verify it. A fix asks the agent to find the cause and confirm+ * with the person before changing anything.+ */+export function buildSetupAiPrompt(+ row: SetupPromptRow,+ flavor: AiPromptFlavor = "generic",+): string {+ const task = row.fix+ ? "Find out why first, then tell me what you found and what you would change. The usual fix is this command, run from the repository root:"+ : "Run this from the repository root:";+ const constraints = row.fix+ ? [+ "Confirm with me before changing anything: files, config, hooks or the index.",+ "If the problem is not what repowise reported, say so and stop.",+ ]+ : [+ "Run only the command above and the check below. Do not edit other files.",+ "If the command fails, show me its output and stop.",+ ];+ const expected = row.fix+ ? "What you found, the change you propose, and, once I confirm and you run it, what the check reports."+ : "The command's result and what the check reports.";+ const detected = [`What repowise detected: ${row.state}`, itemLines(row.items)]+ .filter(Boolean)+ .join("\n");++ // Blocks joined by a blank line, so the prompt reads as sections when pasted.+ return [+ REPO_ROLE[flavor],+ `## Setup: ${row.title}${repoSuffix(row.repoName)}`,+ detected,+ "## Do this",+ `${task}\n\n\`\`\`\n${row.command}\n\`\`\``,+ "## Verify",+ VERIFY[row.verify],+ "## Hard constraints",+ bulletList(constraints),+ "## What I expect back",+ expected,+ ].join("\n\n");+}diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex cbb5c52de..6b3952a3f 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -189,7 +189,8 @@"zoom": "Zoom Map","files": "Files","tests": "Tests",- "docDrift": "Doc drift"+ "docDrift": "Doc drift",+ "setup": "Setup"},"errors": {"workspaceErrorTitle": "Failed to load the workspace",@@ -1124,6 +1125,31 @@"embedderHint": "What semantic search is built from. The mock embedder disables it.","embedderOffNote": "Semantic search is off. Set <code>REPOWISE_EMBEDDER</code> on the server for real retrieval.","embedderOnNote": "Set with <code>{env}</code> on the server."+ },+ "groups": {+ "navLabel": "Settings sections",+ "setup": {+ "title": "Setup"+ },+ "agents": {+ "title": "Agents & editors",+ "description": "Connected agents read the index through MCP. Connecting writes the editor's own config file, named on each row."+ },+ "models": {+ "title": "Models & documentation"+ },+ "sync": {+ "title": "Sync & hooks"+ },+ "coverage": {+ "title": "Coverage"+ },+ "server": {+ "title": "Server"+ },+ "privacy": {+ "title": "Privacy"+ }}},"repos": {@@ -2276,5 +2302,157 @@"commits": "Loading commits","coverage": "Loading coverage","knowledgeGraph": "Loading knowledge graph"+ },+ "setup": {+ "title": "Setup",+ "doneTitle": "You're set up",+ "progress": "{done} of 3 essentials done. Each row also shows its terminal command.",+ "doneLede": "{agent} made its first call {when}. The index updates after each commit.",+ "yourAgent": "Your agent",+ "loading": "Checking this repository's setup. The first check can take about 20 seconds.",+ "loadFailedLabel": "Couldn't check",+ "loadFailed": "The setup check didn't finish. Run repowise doctor in a terminal to see why, or try again.",+ "retry": "Try again",+ "writesOffLabel": "Read only",+ "writesOff": "Changes from the browser are off on this server, because it uses an API key or isn't on this machine. Copy the command or the prompt and run it in a terminal.",+ "writesOffShort": "Changes from the browser are off on this server. Run the command in a terminal.",+ "writeFailed": "That didn't work",+ "attention": "Needs attention",+ "essentials": "Essentials",+ "optional": "Optional",+ "tour": "Take the tour",+ "copyPrompt": "Copy prompt for your agent",+ "promptDescription": "Hand this to your coding agent. It names the command and how to check the result.",+ "promptPreview": "Prompt preview",+ "copied": "copied",+ "showFiles": "Show files",+ "hideFiles": "Hide files",+ "connect": "Connect {agent}",+ "disconnect": "Disconnect",+ "disconnectAgent": "Disconnect {agent}",+ "useReport": "Use this report",+ "addModel": "Add a model",+ "changeModel": "Change model",+ "syncOff": {+ "title": "Turn off sync?",+ "body": "This runs repowise hook uninstall, which also removes the pre-commit security check and the health gate. The index will update only when you run repowise update.",+ "confirm": "Turn off",+ "cancel": "Keep it on"+ },+ "hosted": {+ "eyebrow": "Hosted repowise",+ "title": "All of this, run for you and your team",+ "lede": "Take a look whenever you need it.",+ "items": {+ "push": "Indexed on every push",+ "reviews": "Pull request reviews",+ "dashboard": "One dashboard for the team",+ "webApps": "Use it from Claude.ai and ChatGPT"+ },+ "start": "Start free",+ "see": "See what hosted adds",+ "hide": "Hide on this machine"+ },+ "pill": {+ "label": "Setup",+ "progress": "{done} of {total}",+ "aria": "Setup: {done} of {total} essentials done",+ "hide": "Hide the setup reminder on this machine"+ },+ "settings": {+ "repoLead": "Index, coding agent and sync for this repository, each with its terminal command.",+ "openSetup": "Open Setup",+ "openSetupFor": "Open Setup for {repo}",+ "globalLead": "Setup is per repository: its index, its coding agent and keeping it in sync.",+ "noRepos": "Add a repository to set it up.",+ "telemetryTitle": "Anonymous usage telemetry",+ "telemetryDescription": "repowise sends anonymous usage counts: command names and coarse environment, never code, paths or names. DO_NOT_TRACK=1 also turns it off.",+ "telemetryCheck": "See whether it's on:",+ "telemetryOff": "Turn it off:"+ },+ "row": {+ "index": {+ "title": "Index",+ "statusUpToDate": "Up to date",+ "statusIncomplete": "Not indexed",+ "statusBehind": "Behind",+ "statusSkipped": "{count, plural, one {# file skipped} other {# files skipped}}",+ "detailUpToDate": "{files} files indexed at {commit}.",+ "detailIncomplete": "There's no complete index for this repository yet.",+ "detailBehind": "Indexed at {indexed}. HEAD has moved on to {live}.",+ "detailSkipped": "{count, plural, one {# file could not be parsed, so its symbols are missing from the graph.} other {# files could not be parsed, so their symbols are missing from the graph.}}"+ },+ "agent": {+ "title": "Coding agent",+ "statusConnected": "Connected",+ "statusWaiting": "Waiting",+ "statusOff": "Not connected",+ "statusNoCalls": "No calls yet",+ "detailCalled": "{agent} made its first call {when}.",+ "detailCalledAnon": "An agent made its first call {when}.",+ "detailWaiting": "{count, plural, one {{agents} is registered.} other {{agents} are registered.}} This ticks on its first call.",+ "detailWaitingOther": "{count, plural, one {{agents} is registered.} other {{agents} are registered.}} This ticks on its first call. {other} is installed, not connected.",+ "detailInstalled": "{agent} is installed. Connecting writes its MCP config.",+ "detailNone": "No coding agent found on this machine. Install one, then connect it here.",+ "detailNoCalls": "{agent} is registered but hasn't reached this index. If it opened a different folder, open {repo} in it or run repowise init there."+ },+ "sync": {+ "title": "Keep the index in sync",+ "statusOn": "On",+ "statusOff": "Off",+ "statusUnknown": "Couldn't check",+ "detailOn": "Updates after each commit.",+ "detailOff": "The index updates only when you run repowise update.",+ "detailUnknown": "The post-commit hook couldn't be read."+ },+ "model": {+ "title": "A model for docs, chat and answers",+ "statusLlm": "Written by a model",+ "statusBuilt": "Built from index",+ "detailActive": "Using {provider}.",+ "detailReady": "{providers} ready on this machine.",+ "detailNone": "Docs are built from the index. A model writes fuller docs and answers in chat."+ },+ "coverage": {+ "title": "Test coverage",+ "statusOn": "On",+ "statusFound": "Found",+ "statusOff": "Not found",+ "detailOn": "Coverage stored {when}.",+ "detailFound": "Found {path}, {age, plural, =0 {from today} one {# day old} other {# days old}}.",+ "detailNone": "No coverage report found. Run your tests with coverage, then add the report."+ },+ "rewrite": {+ "title": "Shorter command output",+ "statusOn": "On",+ "statusOff": "Off",+ "statusNa": "Needs Claude Code",+ "statusUnknown": "Couldn't check",+ "detail": "Claude Code reads test, build and git output through distill.",+ "detailNa": "This works with Claude Code, which isn't on this machine."+ },+ "check": {+ "statusWarn": "Warning",+ "statusFail": "Failed"+ },+ "agents": {+ "statusConnected": "Connected",+ "statusNotConnected": "Not connected",+ "statusNotInstalled": "Not installed",+ "statusHosted": "Hosted",+ "detailLastCall": "Last call {when}. {path}",+ "detailNoCall": "No calls yet. {path}",+ "detailInstalledWrites": "Installed. Writes {path}.",+ "detailInstalled": "Installed.",+ "detailNotInstalled": "Connect after installing, or copy the editor config in global settings.",+ "hostedTitle": "Claude.ai and ChatGPT",+ "hostedDetail": "Use this repo from the web apps too, through hosted repowise's MCP address.",+ "hostedLink": "See hosted"+ },+ "unreadable": {+ "status": "Couldn't check",+ "detail": "Couldn't read this here. Run {command} in a terminal to check."+ }+ }}}diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex 76f14ce64..c915cfcbf 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -189,7 +189,8 @@"zoom": "缩放地图","files": "文件","tests": "测试",- "docDrift": "文档漂移"+ "docDrift": "文档漂移",+ "setup": "设置向导"},"errors": {"workspaceErrorTitle": "无法加载工作区",@@ -1124,6 +1125,31 @@"embedderHint": "语义搜索基于它构建。mock 嵌入模型会禁用语义搜索。","embedderOffNote": "语义搜索已关闭。请在服务端设置 <code>REPOWISE_EMBEDDER</code> 以启用真实检索。","embedderOnNote": "通过服务端的 <code>{env}</code> 设置。"+ },+ "groups": {+ "navLabel": "设置分组",+ "setup": {+ "title": "设置向导"+ },+ "agents": {+ "title": "智能体与编辑器",+ "description": "已连接的智能体通过 MCP 读取索引。连接时会写入该编辑器自己的配置文件,每一行都注明了文件名。"+ },+ "models": {+ "title": "模型与文档"+ },+ "sync": {+ "title": "同步与钩子"+ },+ "coverage": {+ "title": "覆盖率"+ },+ "server": {+ "title": "服务器"+ },+ "privacy": {+ "title": "隐私"+ }}},"repos": {@@ -2276,5 +2302,157 @@"commits": "正在加载提交","coverage": "正在加载覆盖率","knowledgeGraph": "正在加载知识图谱"+ },+ "setup": {+ "title": "设置向导",+ "doneTitle": "已全部设置好",+ "progress": "已完成 {done}/3 项必备设置。每一行也列出了对应的终端命令。",+ "doneLede": "{agent} 在{when}首次调用了索引。每次提交后索引都会更新。",+ "yourAgent": "你的智能体",+ "loading": "正在检查此仓库的设置。首次检查可能需要约 20 秒。",+ "loadFailedLabel": "无法检查",+ "loadFailed": "设置检查没有完成。可在终端运行 repowise doctor 查看原因,或重试。",+ "retry": "重试",+ "writesOffLabel": "只读",+ "writesOff": "此服务器使用了 API 密钥或不在本机上,因此无法从浏览器修改设置。请复制命令或提示词,在终端中运行。",+ "writesOffShort": "此服务器不允许从浏览器修改设置。请在终端中运行命令。",+ "writeFailed": "操作未成功",+ "attention": "需要处理",+ "essentials": "必备",+ "optional": "可选",+ "tour": "查看导览",+ "copyPrompt": "复制给智能体的提示词",+ "promptDescription": "把它交给你的编程智能体。其中写明了要运行的命令以及如何检查结果。",+ "promptPreview": "提示词预览",+ "copied": "已复制",+ "showFiles": "显示文件",+ "hideFiles": "隐藏文件",+ "connect": "连接 {agent}",+ "disconnect": "断开连接",+ "disconnectAgent": "断开 {agent}",+ "useReport": "使用此报告",+ "addModel": "添加模型",+ "changeModel": "更换模型",+ "syncOff": {+ "title": "关闭同步?",+ "body": "这会运行 repowise hook uninstall,同时移除提交前的安全检查和健康门禁。之后只有运行 repowise update 时索引才会更新。",+ "confirm": "关闭",+ "cancel": "保持开启"+ },+ "hosted": {+ "eyebrow": "托管版 repowise",+ "title": "以上这些,都可以替你和团队运行",+ "lede": "需要时随时看看。",+ "items": {+ "push": "每次推送都会索引",+ "reviews": "拉取请求审查",+ "dashboard": "团队共用一个仪表盘",+ "webApps": "在 Claude.ai 和 ChatGPT 中使用"+ },+ "start": "免费开始",+ "see": "了解托管版的更多功能",+ "hide": "在此电脑上隐藏"+ },+ "pill": {+ "label": "设置向导",+ "progress": "{done}/{total}",+ "aria": "设置向导:已完成 {done}/{total} 项必备设置",+ "hide": "在此电脑上隐藏设置提醒"+ },+ "settings": {+ "repoLead": "此仓库的索引、编程智能体和同步,每项都附有终端命令。",+ "openSetup": "打开设置向导",+ "openSetupFor": "打开 {repo} 的设置向导",+ "globalLead": "设置向导按仓库区分:每个仓库的索引、编程智能体以及同步。",+ "noRepos": "添加一个仓库后即可设置。",+ "telemetryTitle": "匿名使用遥测",+ "telemetryDescription": "repowise 会发送匿名使用统计:命令名称和大致的运行环境,从不包含代码、路径或名称。设置 DO_NOT_TRACK=1 也可以关闭。",+ "telemetryCheck": "查看是否开启:",+ "telemetryOff": "关闭:"+ },+ "row": {+ "index": {+ "title": "索引",+ "statusUpToDate": "已是最新",+ "statusIncomplete": "未索引",+ "statusBehind": "落后",+ "statusSkipped": "跳过了 {count} 个文件",+ "detailUpToDate": "已在 {commit} 索引 {files} 个文件。",+ "detailIncomplete": "此仓库还没有完整的索引。",+ "detailBehind": "索引位于 {indexed},HEAD 已前进到 {live}。",+ "detailSkipped": "有 {count} 个文件无法解析,因此图中缺少它们的符号。"+ },+ "agent": {+ "title": "编程智能体",+ "statusConnected": "已连接",+ "statusWaiting": "等待中",+ "statusOff": "未连接",+ "statusNoCalls": "尚无调用",+ "detailCalled": "{agent} 在{when}首次调用。",+ "detailCalledAnon": "有智能体在{when}首次调用。",+ "detailWaiting": "{agents} 已注册,首次调用后此项即完成。",+ "detailWaitingOther": "{agents} 已注册,首次调用后此项即完成。{other} 已安装,但尚未连接。",+ "detailInstalled": "已安装 {agent}。连接时会写入它的 MCP 配置。",+ "detailNone": "此电脑上没有找到编程智能体。安装一个后,在这里连接即可。",+ "detailNoCalls": "{agent} 已注册,但还没有访问此索引。如果它打开的是其他文件夹,请在其中打开 {repo},或在那个文件夹中运行 repowise init。"+ },+ "sync": {+ "title": "保持索引同步",+ "statusOn": "开启",+ "statusOff": "关闭",+ "statusUnknown": "无法检查",+ "detailOn": "每次提交后更新。",+ "detailOff": "只有运行 repowise update 时索引才会更新。",+ "detailUnknown": "无法读取 post-commit 钩子。"+ },+ "model": {+ "title": "用于文档、对话和回答的模型",+ "statusLlm": "由模型撰写",+ "statusBuilt": "基于索引生成",+ "detailActive": "正在使用 {provider}。",+ "detailReady": "此电脑上可用:{providers}。",+ "detailNone": "文档目前基于索引生成。模型能写出更完整的文档,并在对话中回答问题。"+ },+ "coverage": {+ "title": "测试覆盖率",+ "statusOn": "开启",+ "statusFound": "已找到",+ "statusOff": "未找到",+ "detailOn": "覆盖率已于{when}保存。",+ "detailFound": "找到 {path},{age, plural, =0 {今天生成} other {已有 # 天}}。",+ "detailNone": "没有找到覆盖率报告。运行带覆盖率的测试,然后添加生成的报告。"+ },+ "rewrite": {+ "title": "更简短的命令输出",+ "statusOn": "开启",+ "statusOff": "关闭",+ "statusNa": "需要 Claude Code",+ "statusUnknown": "无法检查",+ "detail": "Claude Code 通过 distill 读取测试、构建和 git 的输出。",+ "detailNa": "此功能配合 Claude Code 使用,而此电脑上没有安装它。"+ },+ "check": {+ "statusWarn": "警告",+ "statusFail": "失败"+ },+ "agents": {+ "statusConnected": "已连接",+ "statusNotConnected": "未连接",+ "statusNotInstalled": "未安装",+ "statusHosted": "托管版",+ "detailLastCall": "最近一次调用:{when}。{path}",+ "detailNoCall": "尚无调用。{path}",+ "detailInstalledWrites": "已安装。会写入 {path}。",+ "detailInstalled": "已安装。",+ "detailNotInstalled": "安装后即可连接,或在全局设置中复制编辑器配置。",+ "hostedTitle": "Claude.ai 和 ChatGPT",+ "hostedDetail": "通过托管版 repowise 的 MCP 地址,也能在这些网页应用中使用此仓库。",+ "hostedLink": "了解托管版"+ },+ "unreadable": {+ "status": "无法检查",+ "detail": "此处无法读取。请在终端运行 {command} 进行检查。"+ }+ }}}diff --git a/packages/web/src/app/repos/[id]/settings/page.tsx b/packages/web/src/app/repos/[id]/settings/page.tsxindex 48ed7fc94..4e148f3da 100644--- a/packages/web/src/app/repos/[id]/settings/page.tsx+++ b/packages/web/src/app/repos/[id]/settings/page.tsx@@ -14,6 +14,18 @@ import { DeleteRepoButton } from "@/components/repos/delete-repo-button";import { OperationsPanel } from "@/components/repos/operations-panel";import { getTranslations } from "next-intl/server";import { PublishPanel } from "@/components/hosted/publish";+import {+ SettingsGroup,+ SettingsGroupNav,+ settingsGroupTitles,+ type SettingsGroupId,+} from "@/components/settings/settings-groups";+import { RepoAgentRows, RepoSetupRows, SetupLinkRow } from "@/components/setup/setup-settings";++/** Telemetry is per machine, so Privacy lives on global settings only. */+const GROUPS: SettingsGroupId[] = ["setup", "agents", "models", "sync", "coverage", "server"];+const SYNC_ROWS = ["sync", "rewrite"];+const COVERAGE_ROWS = ["coverage"];interface Props {params: Promise<{ id: string }>;@@ -32,6 +44,10 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {/*** Per-repository settings.*+ * Grouped by what people manage, under the same group names as global+ * settings. The Setup page's own rows (agents, hooks, coverage) render here+ * too, with the same controls.+ ** Was seven `Card`s and two `Separator`s. Sections carry the grouping now, and* the page shares its frame and its vocabulary with global settings.*@@ -53,6 +69,8 @@ export default async function RepoSettingsPage({ params }: Props) {}const coordinatorHealth = await getCoordinatorHealth(id).catch(() => null);+ const tg = await getTranslations("settings.groups");+ const titles = settingsGroupTitles(tg);return (<PageShell@@ -60,56 +78,75 @@ export default async function RepoSettingsPage({ params }: Props) {description={t("description", { repo: repo.name })}maxWidth="narrow">- <OverviewSection- title={t("generalTitle")}- description={t("generalDescription")}- flush- >- <RepoSettingsForm repo={repo} />- </OverviewSection>-- <OverviewSection- title={t("syncTitle")}- description={t("syncDescription")}- >- <OperationsPanel repoId={id} repoName={repo.name} />- </OverviewSection>-- <OverviewSection- id="provider"- title={t("providerTitle")}- description={t("providerDescription")}- >- <ProviderSettingsPanel repoId={id} />- </OverviewSection>-- <OverviewSection- title={t("captureTitle")}- description={t("captureDescription")}- >- <DecisionCaptureSettingsWrapper repoId={id} />- </OverviewSection>-- <OverviewSection- title={t("refactoringTitle")}- description={t("refactoringDescription")}- >- <RefactoringSettingsSection repoId={id} />- </OverviewSection>-- <OverviewSection- title={t("healthTitle")}- description={t("healthDescription")}- >- <CoordinatorHealthPanel repoId={id} initial={coordinatorHealth} />- </OverviewSection>-- <OverviewSection- title="Publish on repowise.dev"- description="Put this repository on repowise.dev, indexed from its GitHub remote. Nothing on this machine is uploaded."- >- <PublishPanel repoId={id} />- </OverviewSection>+ <SettingsGroupNav groups={GROUPS} label={tg("navLabel")} titles={titles} />++ <SettingsGroup id="setup" title={titles.setup}>+ <SetupLinkRow repoId={id} />+ <OverviewSection+ title={t("generalTitle")}+ description={t("generalDescription")}+ >+ <RepoSettingsForm repo={repo} />+ </OverviewSection>++ <OverviewSection+ title={t("healthTitle")}+ description={t("healthDescription")}+ >+ <CoordinatorHealthPanel repoId={id} initial={coordinatorHealth} />+ </OverviewSection>+ </SettingsGroup>++ <SettingsGroup id="agents" title={titles.agents} description={tg("agents.description")}>+ <RepoAgentRows repoId={id} repoName={repo.name} />+ </SettingsGroup>++ <SettingsGroup id="models" title={titles.models}>+ <OverviewSection+ id="provider"+ title={t("providerTitle")}+ description={t("providerDescription")}+ >+ <ProviderSettingsPanel repoId={id} />+ </OverviewSection>++ <OverviewSection+ title={t("captureTitle")}+ description={t("captureDescription")}+ >+ <DecisionCaptureSettingsWrapper repoId={id} />+ </OverviewSection>++ <OverviewSection+ title={t("refactoringTitle")}+ description={t("refactoringDescription")}+ >+ <RefactoringSettingsSection repoId={id} />+ </OverviewSection>+ </SettingsGroup>++ <SettingsGroup id="sync" title={titles.sync}>+ <OverviewSection+ title={t("syncTitle")}+ description={t("syncDescription")}+ >+ <OperationsPanel repoId={id} repoName={repo.name} />+ </OverviewSection>+ <RepoSetupRows repoId={id} repoName={repo.name} ids={SYNC_ROWS} />+ </SettingsGroup>++ <SettingsGroup id="coverage" title={titles.coverage}>+ <RepoSetupRows repoId={id} repoName={repo.name} ids={COVERAGE_ROWS} />+ </SettingsGroup>++ <SettingsGroup id="server" title={titles.server}>+ <OverviewSection+ title="Publish on repowise.dev"+ description="Put this repository on repowise.dev, indexed from its GitHub remote. Nothing on this machine is uploaded."+ >+ <PublishPanel repoId={id} />+ </OverviewSection>+ </SettingsGroup>{/* Not a tinted card. A destructive action earns emphasis on the verb andthe sentence, not on a coloured ground the eye reads before either. */}diff --git a/packages/web/src/app/repos/[id]/settings/setup/page.tsx b/packages/web/src/app/repos/[id]/settings/setup/page.tsxnew file mode 100644index 000000000..c9669804d--- /dev/null+++ b/packages/web/src/app/repos/[id]/settings/setup/page.tsx@@ -0,0 +1,30 @@+import type { Metadata } from "next";+import { notFound } from "next/navigation";+import { getRepo } from "@/lib/api/repos";+import { SetupPage } from "@/components/setup/setup-page";++interface Props {+ params: Promise<{ id: string }>;+}++export async function generateMetadata({ params }: Props): Promise<Metadata> {+ const { id } = await params;+ try {+ const repo = await getRepo(id);+ return { title: `${repo.name} · Setup` };+ } catch {+ return { title: "Setup" };+ }+}++/** `/repos/[id]/settings/setup`: what is set up for this repo. The checks load client side. */+export default async function RepoSetupPage({ params }: Props) {+ const { id } = await params;+ let repo;+ try {+ repo = await getRepo(id);+ } catch {+ notFound();+ }+ return <SetupPage repoId={id} repoName={repo.name} />;+}diff --git a/packages/web/src/app/settings/page.tsx b/packages/web/src/app/settings/page.tsxindex f72363e6c..91a17156b 100644--- a/packages/web/src/app/settings/page.tsx+++ b/packages/web/src/app/settings/page.tsx@@ -7,11 +7,22 @@ import { WebhookSection } from "@/components/settings/webhook-section";import { McpSection } from "@/components/settings/mcp-section";import { McpToolsSection } from "@/components/settings/mcp-tools-section";import { DisplaySection } from "@/components/settings/display-section";+import {+ SettingsGroup,+ SettingsGroupNav,+ settingsGroupTitles,+ type SettingsGroupId,+} from "@/components/settings/settings-groups";+import { GlobalSetupLinks, HostedAgentsRow, TelemetryRow } from "@/components/setup/setup-settings";+import { listRepos } from "@/lib/api/repos";import { getTranslations } from "next-intl/server";import { HostedNudgeSlot } from "@/components/hosted/hosted-nudge-slot";export const metadata: Metadata = { title: "Settings" };+/** Coverage is per repository, so this page has no Coverage group. */+const GROUPS: SettingsGroupId[] = ["setup", "agents", "models", "sync", "server", "privacy"];+/*** Global settings.*@@ -20,11 +31,17 @@ export const metadata: Metadata = { title: "Settings" };* systems, two heading scales for the same role. Both run `PageShell` and* `OverviewSection` now, and everything on the page autosaves.*+ * Sections are grouped by what people manage, under the same group names as+ * the repo settings page, with Privacy last.+ ** `narrow` rather than the default 1280: this is a form, and a control that* stretches to 1280 loses the relationship between its label and itself.*/export default async function SettingsPage() {const t = await getTranslations("views.globalSettings");+ const tg = await getTranslations("settings.groups");+ const titles = settingsGroupTitles(tg);+ const repos = await listRepos().catch(() => []);return (<PageShell@@ -32,13 +49,35 @@ export default async function SettingsPage() {description={t("description")}maxWidth="narrow">- <ConnectionSection />- <ProviderSection />- <DisplaySection />- <HostedNudgeSlot candidates={["mcp"]} />- <McpSection />- <McpToolsSection />- <WebhookSection />+ <SettingsGroupNav groups={GROUPS} label={tg("navLabel")} titles={titles} />++ <SettingsGroup id="setup" title={titles.setup}>+ <GlobalSetupLinks repos={repos} />+ </SettingsGroup>++ <SettingsGroup id="agents" title={titles.agents} description={tg("agents.description")}>+ <HostedNudgeSlot candidates={["mcp"]} />+ <McpSection />+ <McpToolsSection />+ <HostedAgentsRow />+ </SettingsGroup>++ <SettingsGroup id="models" title={titles.models}>+ <ProviderSection />+ </SettingsGroup>++ <SettingsGroup id="sync" title={titles.sync}>+ <WebhookSection />+ </SettingsGroup>++ <SettingsGroup id="server" title={titles.server}>+ <ConnectionSection />+ <DisplaySection />+ </SettingsGroup>++ <SettingsGroup id="privacy" title={titles.privacy}>+ <TelemetryRow />+ </SettingsGroup><p className="border-t border-[var(--color-border-default)] pt-6 text-xs text-[var(--color-text-tertiary)]">{t.rich("footer", {diff --git a/packages/web/src/components/hosted/hosted-nudge-slot.test.tsx b/packages/web/src/components/hosted/hosted-nudge-slot.test.tsxindex c8eff9129..e314c43f8 100644--- a/packages/web/src/components/hosted/hosted-nudge-slot.test.tsx+++ b/packages/web/src/components/hosted/hosted-nudge-slot.test.tsx@@ -17,7 +17,7 @@ vi.mock("@/lib/api/platform", () => ({ publishRepo: mocks.publishRepo }));import { config } from "@/lib/config";import { HostedNudgeSlot } from "./hosted-nudge-slot";-const MCP = "Use this repo inside Claude.ai or ChatGPT. Local MCP only works in desktop tools.";+const MCP = "Use this repo from Claude.ai or ChatGPT too.";const DOCS = "Want AI-written docs without an API key? repowise.dev includes the model.";beforeEach(() => {diff --git a/packages/web/src/components/layout/footer-setup-pill.test.tsx b/packages/web/src/components/layout/footer-setup-pill.test.tsxnew file mode 100644index 000000000..4c6cf1758--- /dev/null+++ b/packages/web/src/components/layout/footer-setup-pill.test.tsx@@ -0,0 +1,86 @@+// @vitest-environment jsdom++import React from "react";+import { SWRConfig } from "swr";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { RepoResponse } from "@/lib/api/types";+import { setupFixture } from "@/components/setup/setup-fixture";++const mocks = vi.hoisted(() => ({+ getRepoSetup: vi.fn(),+ getOnboardingState: vi.fn(),+ pathname: "/repos/r1/overview",+}));++vi.mock("@/lib/api/setup", () => ({+ getRepoSetup: mocks.getRepoSetup,+ getOnboardingState: mocks.getOnboardingState,+ updateOnboardingState: vi.fn(),+}));+vi.mock("next/navigation", () => ({+ usePathname: () => mocks.pathname,+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn(), prefetch: vi.fn() }),+ useSearchParams: () => new URLSearchParams(),+}));+// Footer and dialog neighbours fetch on their own; this file is about the pill's wiring.+vi.mock("@/components/repos/add-repo-dialog", () => ({ AddRepoDialog: () => null }));+vi.mock("./feedback-button", () => ({ FeedbackButton: () => null }));+vi.mock("./version-footer", () => ({ VersionFooter: () => null }));+vi.mock("./language-switcher", () => ({ LanguageSwitcher: () => null }));++import { Sidebar } from "./sidebar";+import { MobileNav } from "./mobile-nav";++const repo = (workspace_status: string | null): RepoResponse =>+ ({ id: "r1", name: "orbit-api", workspace_status }) as unknown as RepoResponse;++const PILL = { name: "Setup: 2 of 3 essentials done" };++function wrap(ui: React.ReactElement) {+ return render(<SWRConfig value={{ provider: () => new Map() }}>{ui}</SWRConfig>);+}++beforeEach(() => {+ window.localStorage.clear();+ const setup = setupFixture();+ mocks.getRepoSetup.mockResolvedValue(setup);+ mocks.getOnboardingState.mockResolvedValue(setup.onboarding);+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("Setup pill in the desktop sidebar", () => {+ it("shows for the active indexed repo", async () => {+ wrap(<Sidebar repos={[repo("indexed")]} />);+ const link = await screen.findByRole("link", PILL);+ expect(link.getAttribute("href")).toBe("/repos/r1/settings/setup");+ });++ it("stays out for a workspace repo that still needs an index", async () => {+ wrap(<Sidebar repos={[repo("needs_index")]} />);+ await Promise.resolve();+ expect(screen.queryByRole("link", PILL)).toBeNull();+ expect(mocks.getRepoSetup).not.toHaveBeenCalled();+ });+});++describe("Setup pill in the mobile nav", () => {+ it("shows for the active indexed repo", async () => {+ wrap(<MobileNav repos={[repo("indexed")]} />);+ fireEvent.click(screen.getByRole("button", { name: /navigation/i }));+ const link = await screen.findByRole("link", PILL);+ expect(link.getAttribute("href")).toBe("/repos/r1/settings/setup");+ });++ it("stays out for a workspace repo that still needs an index", async () => {+ wrap(<MobileNav repos={[repo("needs_index")]} />);+ fireEvent.click(screen.getByRole("button", { name: /navigation/i }));+ await waitFor(() => expect(screen.getByRole("dialog")).toBeTruthy());+ expect(screen.queryByRole("link", PILL)).toBeNull();+ expect(mocks.getRepoSetup).not.toHaveBeenCalled();+ });+});diff --git a/packages/web/src/components/layout/mobile-nav.tsx b/packages/web/src/components/layout/mobile-nav.tsxindex d4e33cf29..cf805bc8b 100644--- a/packages/web/src/components/layout/mobile-nav.tsx+++ b/packages/web/src/components/layout/mobile-nav.tsx@@ -22,6 +22,7 @@ import { NewMark } from "./new-mark";import { useIsNewSurface } from "@/lib/hooks/use-new-surfaces";import { FeedbackButton } from "./feedback-button";import { LanguageSwitcher } from "./language-switcher";+import { FooterSetupPill } from "@/components/setup/setup-pill";import { ThemeToggle } from "@repowise-dev/ui/shared/theme-toggle";import { cn } from "@/lib/utils/cn";import { GLOBAL_NAV, WORKSPACE_NAV, repoNavGroups } from "./nav-items";@@ -245,6 +246,7 @@ export function MobileNav({ repos = [], workspace }: MobileNavProps) {</ScrollArea><div className="flex flex-col gap-2 border-t border-[var(--color-border-default)] px-4 py-2.5">+ <FooterSetupPill repos={repos} activeRepoId={activeRepoId} /><FeedbackButton />{/* Mobile had no theme control anywhere in the shell, so thepreference was simply unreachable on a phone. It shares thediff --git a/packages/web/src/components/layout/repo-breadcrumb-label.ts b/packages/web/src/components/layout/repo-breadcrumb-label.tsindex 0927b6a18..babfb9735 100644--- a/packages/web/src/components/layout/repo-breadcrumb-label.ts+++ b/packages/web/src/components/layout/repo-breadcrumb-label.ts@@ -27,6 +27,7 @@ const SEGMENT_LABELS: Record<string, string> = {risk: "Risk",security: "Security",settings: "Settings",+ setup: "Setup","knowledge-graph": "Knowledge Graph",zoom: "Zoom Map",files: "Files",@@ -69,6 +70,7 @@ export const SEGMENT_MESSAGE_KEYS: Record<string, string> = {risk: "risk",security: "security",settings: "settings",+ setup: "setup","knowledge-graph": "knowledgeGraph",zoom: "zoom",files: "files",diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 8f42bef8d..6f0ed214f 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -30,6 +30,7 @@ import { VersionFooter } from "./version-footer";import { NewMark, useNavNewMark } from "./new-mark";import { FeedbackButton } from "./feedback-button";import { LanguageSwitcher } from "./language-switcher";+import { FooterSetupPill } from "@/components/setup/setup-pill";import type { RepoResponse, WorkspaceResponse } from "@/lib/api/types";interface SidebarProps {@@ -427,6 +428,7 @@ export function Sidebar({version were unreachable without expanding first. */}{isIconOnly ? (<div className="flex flex-col items-center gap-1 border-t border-[var(--color-border-default)] py-1.5">+ <FooterSetupPill repos={repos} activeRepoId={derivedActiveRepoId} compact /><LanguageSwitcher compact /><ThemeToggleswitchToDarkLabel={ts("switchToDarkTheme")}@@ -435,6 +437,7 @@ export function Sidebar({</div>) : (<div className="flex flex-col gap-2 border-t border-[var(--color-border-default)] px-3 py-2">+ <FooterSetupPill repos={repos} activeRepoId={derivedActiveRepoId} /><FeedbackButton />{/* Version, language and theme share a row. The toggle was afull-width bordered track stacked on its own line, which made adiff --git a/packages/web/src/components/settings/settings-groups.tsx b/packages/web/src/components/settings/settings-groups.tsxnew file mode 100644index 000000000..e2324b6e2--- /dev/null+++ b/packages/web/src/components/settings/settings-groups.tsx@@ -0,0 +1,96 @@+import type { ReactNode } from "react";+import { cn } from "@/lib/utils/cn";++/**+ * Settings, grouped by what people manage, in this order. Privacy sits last.+ * The global page and the repo page use the same names, and each shows the+ * groups it has something for.+ */+export const SETTINGS_GROUPS = [+ "setup",+ "agents",+ "models",+ "sync",+ "coverage",+ "server",+ "privacy",+] as const;++export type SettingsGroupId = (typeof SETTINGS_GROUPS)[number];++/** Every group's title, from `settings.groups.<id>.title`. */+export function settingsGroupTitles(t: (key: string) => string): Record<SettingsGroupId, string> {+ return Object.fromEntries(SETTINGS_GROUPS.map((g) => [g, t(`${g}.title`)])) as Record<+ SettingsGroupId,+ string+ >;+}++export const settingsGroupAnchor =(id: SettingsGroupId) => `group-${id}`;++/** In-page links to the groups a page shows; wraps instead of scrolling sideways. */+export function SettingsGroupNav({+ groups,+ label,+ titles,+}: {+ groups: readonly SettingsGroupId[];+ label: string;+ titles: Record<SettingsGroupId, string>;+}) {+ return (+ <nav aria-label={label} className="-mt-2">+ <ul className="flex flex-wrap gap-1.5">+ {SETTINGS_GROUPS.filter((g) => groups.includes(g)).map((g) => (+ <li key={g}>+ <a+ href={`#${settingsGroupAnchor(g)}`}+ className="inline-flex rounded-md px-2 py-1 text-xs text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-wash)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ {titles[g]}+ </a>+ </li>+ ))}+ </ul>+ </nav>+ );+}++/** One group: a heading the nav links to, then the sections it holds, unchanged. */+export function SettingsGroup({+ id,+ title,+ description,+ children,+ className,+}: {+ id: SettingsGroupId;+ title: string;+ description?: string;+ children: ReactNode;+ className?: string;+}) {+ const anchor = settingsGroupAnchor(id);+ return (+ <section+ id={anchor}+ aria-labelledby={`${anchor}-title`}+ className={cn("flex scroll-mt-24 flex-col gap-6 sm:gap-8", className)}+ >+ <header className="-mb-2 border-t-2 border-[var(--color-border-hover)] pt-4">+ <h2+ id={`${anchor}-title`}+ className="font-mono text-[11px] uppercase tracking-[0.1em] text-[var(--color-text-tertiary)]"+ >+ {title}+ </h2>+ {description && (+ <p className="mt-1 max-w-[62ch] text-xs leading-relaxed text-[var(--color-text-tertiary)] [text-wrap:pretty]">+ {description}+ </p>+ )}+ </header>+ {children}+ </section>+ );+}diff --git a/packages/web/src/components/setup/hosted-setup-card.tsx b/packages/web/src/components/setup/hosted-setup-card.tsxnew file mode 100644index 000000000..26df6fab6--- /dev/null+++ b/packages/web/src/components/setup/hosted-setup-card.tsx@@ -0,0 +1,89 @@+"use client";++import { useEffect, useState } from "react";+import { useTranslations } from "next-intl";+import { X } from "lucide-react";+import { Button } from "@repowise-dev/ui/ui/button";+import { config } from "@/lib/config";+import { hostedLink } from "@/lib/hosted";+import type { OnboardingState } from "@/lib/api/setup";+import { useHideOnThisMachine } from "./use-setup";++/** `src=local_web_setup_card` on both links. */+export const HOSTED_CARD_SURFACE = "setup_card";++const ITEMS = ["push", "reviews", "dashboard", "webApps"] as const;++/**+ * Shown once the essentials are done, unless tips are off (`repowise config+ * hints off`, `REPOWISE_NO_HINTS`, `DO_NOT_TRACK`, or this browser's tips+ * switch), the person is signed in, or it was hidden on this machine.+ */+export function hostedCardVisible(onboarding: OnboardingState, tipsHiddenHere: boolean): boolean {+ return (+ onboarding.hints_enabled &&+ !onboarding.signed_in &&+ !onboarding.hosted_card_hidden &&+ !tipsHiddenHere+ );+}++export function HostedSetupCard({ onboarding }: { onboarding: OnboardingState }) {+ const t = useTranslations("setup.hosted");+ const { hide, hiddenNow } = useHideOnThisMachine();+ // Off until read after mount, so SSR and the first client render agree.+ const [tipsHiddenHere, setTipsHiddenHere] = useState(true);+ useEffect(() => setTipsHiddenHere(config.getHostedTipsHidden()), []);++ if (hiddenNow.has("hosted_card_hidden") || !hostedCardVisible(onboarding, tipsHiddenHere)) {+ return null;+ }+ return (+ <section+ aria-labelledby="hosted-setup-card-title"+ className="mt-6 rounded-[10px] border border-[var(--color-border-default)] border-l-[3px] border-l-[var(--color-info)] bg-[var(--color-release-card)] px-4 py-3.5"+ >+ <div className="flex items-center justify-between gap-2">+ <span className="font-mono text-[10px] uppercase tracking-[0.1em] text-[var(--color-text-tertiary)]">+ {t("eyebrow")}+ </span>+ <button+ type="button"+ onClick={() => void hide("hosted_card_hidden")}+ aria-label={t("hide")}+ title={t("hide")}+ className="-m-1.5 rounded p-1.5 text-[var(--color-text-tertiary)] transition-colors 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>+ </div>+ <h2 id="hosted-setup-card-title" className="mt-1 text-[15px] font-semibold text-[var(--color-text-primary)]">+ {t("title")}+ </h2>+ <p className="text-xs text-[var(--color-text-secondary)]">{t("lede")}</p>+ <ul className="my-3 grid grid-cols-1 gap-x-4 gap-y-1.5 text-xs text-[var(--color-text-secondary)] sm:grid-cols-2">+ {ITEMS.map((item) => (+ <li key={item} className="flex items-baseline gap-2">+ <span aria-hidden className="inline-block h-[7px] w-[7px] shrink-0 rounded-full bg-[var(--color-info)]" />+ {t(`items.${item}`)}+ </li>+ ))}+ </ul>+ <div className="flex flex-wrap items-center gap-3">+ <Button asChild size="sm">+ <a href={hostedLink(HOSTED_CARD_SURFACE, "start")} target="_blank" rel="noopener noreferrer">+ {t("start")}+ </a>+ </Button>+ <a+ href={hostedLink(HOSTED_CARD_SURFACE, "team")}+ target="_blank"+ rel="noopener noreferrer"+ className="text-xs font-medium text-[var(--color-text-primary)] underline decoration-[var(--color-border-hover)] underline-offset-[3px] hover:decoration-[var(--color-text-primary)]"+ >+ {t("see")}+ </a>+ </div>+ </section>+ );+}diff --git a/packages/web/src/components/setup/setup-controls.tsx b/packages/web/src/components/setup/setup-controls.tsxnew file mode 100644index 000000000..af1a562af--- /dev/null+++ b/packages/web/src/components/setup/setup-controls.tsx@@ -0,0 +1,139 @@+"use client";++import { useState, type ReactNode } from "react";+import { useTranslations } from "next-intl";+import { Button } from "@repowise-dev/ui/ui/button";+import { Switch } from "@repowise-dev/ui/ui/switch";+import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";+import { useAiPromptAction } from "@repowise-dev/ui/health/ai-prompt-action";+import { buildSetupAiPrompt } from "@repowise-dev/ui/health/ai-prompt-builder";+import { useModelUpgrade } from "@/components/model-upgrade/model-upgrade";+import type { SetupAction, SetupRow } from "./setup-rows";+import { useSetupText } from "./setup-row";+import { useSetupData, useSetupWrites } from "./use-setup";++/** Green when on, the same switch everywhere Setup rows render. */+const SWITCH_ON = "data-[state=checked]:bg-[var(--color-success)]";++/**+ * Everything a Setup row's controls need: the writes, the sync-off confirm,+ * the model sheet and the prompt modal. Render `dialogs` once and call+ * `actionFor(row)` per row. Shared by the Setup page and repo settings.+ */+export function useSetupControls(repoId: string) {+ const t = useTranslations("setup");+ const text = useSetupText();+ const { data, mutate } = useSetupData(repoId);+ const writes = useSetupWrites(repoId);+ const model = useModelUpgrade(repoId, { onGenerated: () => void mutate() });+ const { openPrompt, promptModal } = useAiPromptAction();+ const [confirmSyncOff, setConfirmSyncOff] = useState(false);++ const writesAllowed = data?.writes_allowed ?? false;+ // One write at a time: each rolls back to the payload it started from.+ const writesOffTitle = writesAllowed ? undefined : t("writesOffShort");++ function hookSwitch(row: SetupRow, action: Extract<SetupAction, { kind: "hook" }>) {+ return (+ <Switch+ checked={action.enabled}+ disabled={!writesAllowed || action.unavailable || writes.busy !== null}+ aria-label={text(row.title)}+ title={writesOffTitle}+ className={SWITCH_ON}+ onCheckedChange={(next) => {+ if (action.hook === "post-commit" && !next) setConfirmSyncOff(true);+ else void writes.setHook(action.hook, next);+ }}+ />+ );+ }++ function actionFor(row: SetupRow): ReactNode {+ const action = row.action;+ if (!action) return null;+ switch (action.kind) {+ case "hook":+ return hookSwitch(row, action);+ case "connect":+ return (+ <Button+ variant="outline"+ size="sm"+ disabled={!writesAllowed || writes.busy !== null}+ title={writesOffTitle}+ onClick={() => void writes.connect(action.agentId)}+ >+ {t("connect", { agent: action.agentName })}+ </Button>+ );+ case "disconnect":+ return (+ <Button+ variant="ghost"+ size="sm"+ disabled={!writesAllowed || writes.busy !== null}+ title={writesOffTitle}+ aria-label={t("disconnectAgent", { agent: action.agentName })}+ onClick={() => void writes.disconnect(action.agentId)}+ >+ {t("disconnect")}+ </Button>+ );+ case "coverage":+ return (+ <Button+ variant="outline"+ size="sm"+ disabled={!writesAllowed || writes.busy !== null}+ title={writesOffTitle}+ onClick={() => void writes.addCoverage(action.path)}+ >+ {t("useReport")}+ </Button>+ );+ case "model":+ return (+ <Button+ size="sm"+ className="bg-[var(--color-model)] text-[var(--color-text-on-model)] hover:bg-[var(--color-model-hover)]"+ onClick={model.openSheet}+ >+ {action.hasModel ? t("changeModel") : t("addModel")}+ </Button>+ );+ default:+ return null;+ }+ }++ function openRowPrompt(row: SetupRow) {+ openPrompt({+ title: text(row.title),+ description: t("promptDescription"),+ getPrompt: (flavor) => buildSetupAiPrompt(row.prompt, flavor),+ });+ }++ const dialogs = (+ <>+ <ConfirmDialog+ open={confirmSyncOff}+ onOpenChange={setConfirmSyncOff}+ title={t("syncOff.title")}+ description={t("syncOff.body")}+ confirmLabel={t("syncOff.confirm")}+ cancelLabel={t("syncOff.cancel")}+ destructive+ onConfirm={() => {+ setConfirmSyncOff(false);+ void writes.setHook("post-commit", false);+ }}+ />+ {model.sheet}+ {promptModal}+ </>+ );++ return { actionFor, openRowPrompt, dialogs, writes, writesAllowed };+}diff --git a/packages/web/src/components/setup/setup-fixture.ts b/packages/web/src/components/setup/setup-fixture.tsnew file mode 100644index 000000000..8ce96a3f5--- /dev/null+++ b/packages/web/src/components/setup/setup-fixture.ts@@ -0,0 +1,81 @@+import type { SetupResponse } from "@/lib/api/setup";++export const NOW = Date.parse("2026-10-25T12:00:00Z");++/** Index up to date, Claude Code connected with no calls, Cursor installed, sync on. */+export function setupFixture(overrides: Partial<SetupResponse> = {}): SetupResponse {+ return {+ repo_id: "r1",+ generated_at: "2026-10-25T12:00:00Z",+ index: {+ state: "up_to_date",+ indexed_commit: "abcdef1234",+ live_head: "abcdef1234",+ indexed_at: "2026-10-25T11:00:00Z",+ file_count: 120,+ parse_error_count: 0,+ parse_error_files: [],+ },+ agents_available: true,+ calls_available: true,+ coverage_available: true,+ model_available: true,+ agents: [+ {+ id: "claude-code",+ display_name: "Claude Code",+ installed: true,+ connected: true,+ registrations: [{ method: "mcp", scope: "user", config_path: "~/.claude.json" }],+ config_files: { user: ["~/.claude.json"] },+ first_call_at: null,+ last_call_at: null,+ },+ {+ id: "cursor",+ display_name: "Cursor",+ installed: true,+ connected: false,+ config_files: { project: [".cursor/mcp.json"] },+ },+ { id: "codex", display_name: "Codex", installed: false, connected: false },+ ],+ calls: { first_call_at: null, last_call_at: null, unattributed: false },+ sync: { installed: true, detail: "installed" },+ rewrite_hook: { state: "not_installed", detail: "not installed" },+ coverage: {+ ingested_at: null,+ configured_paths: [],+ discovered: [{ path: "coverage/lcov.info", modified_at: "2026-10-23T00:00:00Z", age_days: 2 }],+ },+ model: { docs_mode: "deterministic", active_provider: null, configured_providers: ["provider-a"] },+ checks_available: true,+ checks: [+ { id: "post-commit-hook", name: "Post-commit hook", level: "ok", detail: "installed" },+ { id: "database", name: "Database", level: "ok", detail: "ok" },+ ],+ onboarding: {+ welcome_seen: {},+ setup_pill_hidden: false,+ hosted_card_hidden: false,+ hints_enabled: true,+ signed_in: false,+ },+ writes_allowed: true,+ ...overrides,+ };+}++/** Everything done: index current, an agent has called, sync on. */+export function doneFixture(overrides: Partial<SetupResponse> = {}): SetupResponse {+ const base = setupFixture();+ return setupFixture({+ agents: (base.agents ?? []).map((a) =>+ a.id === "claude-code"+ ? { ...a, first_call_at: "2026-10-25T11:56:00Z", last_call_at: "2026-10-25T11:58:00Z" }+ : a,+ ),+ calls: { first_call_at: "2026-10-25T11:56:00Z", last_call_at: "2026-10-25T11:58:00Z" },+ ...overrides,+ });+}diff --git a/packages/web/src/components/setup/setup-page.test.tsx b/packages/web/src/components/setup/setup-page.test.tsxnew file mode 100644index 000000000..bad2db831--- /dev/null+++ b/packages/web/src/components/setup/setup-page.test.tsx@@ -0,0 +1,163 @@+// @vitest-environment jsdom++import React from "react";+import { SWRConfig } from "swr";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { SetupResponse } from "@/lib/api/setup";+import { doneFixture, setupFixture } from "./setup-fixture";++const mocks = vi.hoisted(() => ({+ getRepoSetup: vi.fn(),+ setSetupHook: vi.fn(),+ updateOnboardingState: vi.fn(),+ toastError: vi.fn(),+ toastSuccess: vi.fn(),+}));++vi.mock("@/lib/api/setup", () => ({+ getRepoSetup: mocks.getRepoSetup,+ setSetupHook: mocks.setSetupHook,+ updateOnboardingState: mocks.updateOnboardingState,+ connectSetupAgent: vi.fn(),+ disconnectSetupAgent: vi.fn(),+ addSetupCoverage: vi.fn(),+ getOnboardingState: vi.fn(),+}));+vi.mock("sonner", () => ({ toast: { error: mocks.toastError, success: mocks.toastSuccess } }));+// The sheet pulls in the providers and bulk generate flows; Setup only opens it.+vi.mock("@/components/model-upgrade/model-upgrade", () => ({+ useModelUpgrade: () => ({ openSheet: vi.fn(), sheet: null }),+}));++import { SetupPage } from "./setup-page";+import { hostedCardVisible } from "./hosted-setup-card";++function renderPage(setup: SetupResponse) {+ mocks.getRepoSetup.mockResolvedValue(setup);+ return render(+ <SWRConfig value={{ provider: () => new Map() }}>+ <SetupPage repoId="r1" repoName="orbit-api" />+ </SWRConfig>,+ );+}++beforeEach(() => {+ window.localStorage.clear();+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("SetupPage", () => {+ it("shows the essentials count and the tour link", async () => {+ renderPage(setupFixture());+ expect(await screen.findByText(/2 of 3 essentials done/)).toBeTruthy();+ expect(screen.getByRole("link", { name: "Take the tour" }).getAttribute("href")).toBe(+ "/repos/r1/overview?tour=1",+ );+ });++ it("rolls a switch back and says why when the command reports ok: false", async () => {+ mocks.setSetupHook.mockResolvedValue({+ ok: false,+ command: "repowise hook rewrite install",+ message: "That didn't work here. Run it in a terminal: repowise hook rewrite install",+ });+ renderPage(setupFixture());+ const toggle = await screen.findByRole("switch", { name: "Shorter command output" });+ expect(toggle.getAttribute("aria-checked")).toBe("false");++ fireEvent.click(toggle);+ await waitFor(() => expect(mocks.setSetupHook).toHaveBeenCalledWith("r1", "rewrite", true));+ await waitFor(() =>+ expect(mocks.toastError).toHaveBeenCalledWith(+ "That didn't work here. Run it in a terminal: repowise hook rewrite install",+ { description: "repowise hook rewrite install" },+ ),+ );+ expect(+ screen.getByRole("switch", { name: "Shorter command output" }).getAttribute("aria-checked"),+ ).toBe("false");+ });++ it("asks before turning sync off, naming the security check and the health gate", async () => {+ mocks.setSetupHook.mockResolvedValue({ ok: true, command: "repowise hook uninstall" });+ renderPage(setupFixture());+ fireEvent.click(await screen.findByRole("switch", { name: "Keep the index in sync" }));++ const dialog = await screen.findByRole("dialog");+ expect(dialog.textContent).toContain("pre-commit security check and the health gate");+ expect(mocks.setSetupHook).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole("button", { name: "Turn off" }));+ await waitFor(() => expect(mocks.setSetupHook).toHaveBeenCalledWith("r1", "post-commit", false));+ });++ it("disables writes and says why when the server does not allow them", async () => {+ renderPage(setupFixture({ writes_allowed: false }));+ const toggle = await screen.findByRole("switch", { name: "Shorter command output" });+ expect(toggle.hasAttribute("disabled")).toBe(true);+ expect(screen.getByText(/Changes from the browser are off on this server/)).toBeTruthy();+ expect(screen.getByRole("button", { name: "Connect Cursor" }).hasAttribute("disabled")).toBe(true);+ });++ it("puts the prompt first on a Needs attention row, with a preview", async () => {+ const s = setupFixture();+ renderPage({ ...s, index: { ...s.index, parse_error_count: 1, parse_error_files: ["gen.py"] } });+ expect(await screen.findByText("Needs attention")).toBeTruthy();+ expect(screen.getByText("Prompt preview")).toBeTruthy();+ expect(screen.getByText(/gen\.py\. Run repowise doctor --format json to confirm/)).toBeTruthy();+ });+});++describe("unreadable sections", () => {+ it("says doctor couldn't run instead of showing an empty Needs attention", async () => {+ renderPage(setupFixture({ checks_available: false, checks: [] }));+ expect(await screen.findByText("Needs attention")).toBeTruthy();+ expect(+ screen.getByText("Couldn't read this here. Run repowise doctor in a terminal to check."),+ ).toBeTruthy();+ });++ it("shows the unreadable line for coverage in place of its empty state", async () => {+ renderPage(setupFixture({ coverage_available: false }));+ expect(+ await screen.findByText("Couldn't read this here. Run repowise coverage status in a terminal to check."),+ ).toBeTruthy();+ expect(screen.queryByRole("button", { name: "Use this report" })).toBeNull();+ });+});++describe("hosted card", () => {+ it("appears once the essentials are done, and × hides it on this machine", async () => {+ mocks.updateOnboardingState.mockResolvedValue({ ...doneFixture().onboarding, hosted_card_hidden: true });+ renderPage(doneFixture());+ expect(await screen.findByText("You're set up")).toBeTruthy();+ expect(screen.getByText("All of this, run for you and your team")).toBeTruthy();+ expect(screen.getByRole("link", { name: "Start free" }).getAttribute("href")).toContain(+ "src=local_web_setup_card",+ );++ fireEvent.click(screen.getByRole("button", { name: "Hide on this machine" }));+ expect(screen.queryByText("All of this, run for you and your team")).toBeNull();+ expect(mocks.updateOnboardingState).toHaveBeenCalledWith({ hosted_card_hidden: true });+ });++ it("is not shown before the essentials are done", async () => {+ renderPage(setupFixture());+ await screen.findByText(/2 of 3 essentials done/);+ expect(screen.queryByText("All of this, run for you and your team")).toBeNull();+ });++ it("stays hidden with tips off, when signed in, or when hidden before", () => {+ const on = doneFixture().onboarding;+ expect(hostedCardVisible(on, false)).toBe(true);+ expect(hostedCardVisible({ ...on, hints_enabled: false }, false)).toBe(false);+ expect(hostedCardVisible({ ...on, signed_in: true }, false)).toBe(false);+ expect(hostedCardVisible({ ...on, hosted_card_hidden: true }, false)).toBe(false);+ expect(hostedCardVisible(on, true)).toBe(false);+ });+});diff --git a/packages/web/src/components/setup/setup-page.tsx b/packages/web/src/components/setup/setup-page.tsxnew file mode 100644index 000000000..06a18ea05--- /dev/null+++ b/packages/web/src/components/setup/setup-page.tsx@@ -0,0 +1,174 @@+"use client";++import { useEffect, useId, useState } from "react";+import Link from "next/link";+import { useFormatter, useTranslations } from "next-intl";+import { PageShell } from "@repowise-dev/ui/shared/page-shell";+import { Callout } from "@repowise-dev/ui/shared/callout";+import { Button } from "@repowise-dev/ui/ui/button";+import { Skeleton, SkeletonRegion } from "@repowise-dev/ui/ui/skeleton";+import { tourHref } from "@/lib/tour";+import type { SetupResponse } from "@/lib/api/setup";+import { HostedSetupCard } from "./hosted-setup-card";+import { SetupRowView, useSetupText } from "./setup-row";+import { firstCallerName, type SetupRow, type SetupView } from "./setup-rows";+import { useSetupControls } from "./setup-controls";+import { rememberSetupDone, useSetupData, useSetupView } from "./use-setup";++const MICRO = "font-mono text-[10px] uppercase tracking-[0.1em] text-[var(--color-text-tertiary)]";++/** The Setup page: what is set up for one repo, with one action per row. */+export function SetupPage({ repoId, repoName }: { repoId: string; repoName: string }) {+ const t = useTranslations("setup");+ const { data, error, isLoading, mutate } = useSetupData(repoId);+ const view = useSetupView(repoId, repoName, data);++ useEffect(() => {+ if (view) rememberSetupDone(repoId, view.allDone);+ }, [repoId, view]);++ if (!data || !view) {+ return (+ <PageShell title={t("title")} description={t("loading")} maxWidth="narrow">+ {error && !isLoading ? (+ <Callout tone="error" label={t("loadFailedLabel")} action={<Button size="sm" variant="outline" onClick={() => void mutate()}>{t("retry")}</Button>}>+ {t("loadFailed")}+ </Callout>+ ) : (+ <SetupSkeleton label={t("loading")} />+ )}+ </PageShell>+ );+ }+ return <SetupLoaded repoId={repoId} setup={data} view={view} />;+}++function SetupSkeleton({ label }: { label: string }) {+ return (+ <SkeletonRegion label={label} className="flex flex-col gap-3">+ {Array.from({ length: 6 }, (_, i) => (+ <div key={i} className="grid grid-cols-1 gap-3 border-t border-[var(--color-border-default)] pt-3 sm:grid-cols-[124px_minmax(0,1fr)_auto]">+ <Skeleton className="h-4 w-20" />+ <div className="space-y-1.5">+ <Skeleton className="h-4 w-48 max-w-full" />+ <Skeleton className="h-3 w-full" />+ </div>+ <Skeleton className="h-7 w-28" />+ </div>+ ))}+ </SkeletonRegion>+ );+}++function SetupLoaded({ repoId, setup, view }: { repoId: string; setup: SetupResponse; view: SetupView }) {+ const t = useTranslations("setup");+ const format = useFormatter();+ const controls = useSetupControls(repoId);+ const text = useSetupText();++ const description = view.allDone+ ? t("doneLede", {+ agent: firstCallerName(setup) ?? t("yourAgent"),+ when: format.relativeTime(new Date(setup.calls.first_call_at ?? Date.now())),+ })+ : t("progress", { done: view.doneCount });++ const rows = (list: SetupRow[]) =>+ list.map((row) => (+ <SetupRowView+ key={row.id}+ row={row}+ action={controls.actionFor(row)}+ onOpenPrompt={() => controls.openRowPrompt(row)}+ >+ {row.files?.length ? <SkippedFiles files={row.files} /> : null}+ </SetupRowView>+ ));++ return (+ <PageShell title={view.allDone ? t("doneTitle") : t("title")} description={description} maxWidth="narrow">+ {!setup.writes_allowed && (+ <Callout tone="info" label={t("writesOffLabel")}>+ {t("writesOff")}+ </Callout>+ )}+ <div>+ {(view.attention.length > 0 || view.checksUnreadable) && (+ <RowGroup label={t("attention")}>+ {view.checksUnreadable && (+ <p className="border-t border-[var(--color-border-default)] py-3 text-xs text-[var(--color-text-tertiary)]">+ {text({ key: "unreadable.detail", values: { command: "repowise doctor" } })}+ </p>+ )}+ {rows(view.attention)}+ </RowGroup>+ )}+ <RowGroup+ label={t("essentials")}+ aside={+ <Link+ href={tourHref(repoId)}+ className="text-xs font-medium text-[var(--color-text-primary)] underline decoration-[var(--color-border-hover)] underline-offset-[3px] hover:decoration-[var(--color-text-primary)]"+ >+ {t("tour")}+ </Link>+ }+ >+ {rows(view.essentials)}+ </RowGroup>+ {view.allDone && <HostedSetupCard onboarding={setup.onboarding} />}+ <RowGroup label={t("optional")}>{rows(view.optional)}</RowGroup>+ </div>+ {controls.dialogs}+ </PageShell>+ );+}++function RowGroup({+ label,+ aside,+ children,+}: {+ label: string;+ aside?: React.ReactNode;+ children: React.ReactNode;+}) {+ const headingId = useId();+ return (+ <section className="mt-6 first:mt-0" aria-labelledby={headingId}>+ <div className="mb-1 flex items-baseline justify-between gap-3">+ <h2 id={headingId} className={MICRO}>+ {label}+ </h2>+ {aside}+ </div>+ {children}+ </section>+ );+}++function SkippedFiles({ files }: { files: string[] }) {+ const t = useTranslations("setup");+ const [open, setOpen] = useState(false);+ return (+ <div className="mt-1">+ <button+ type="button"+ aria-expanded={open}+ onClick={() => setOpen((v) => !v)}+ className="text-xs font-medium text-[var(--color-text-primary)] underline decoration-[var(--color-border-hover)] underline-offset-[3px]"+ >+ {open ? t("hideFiles") : t("showFiles")}+ </button>+ {open && (+ <ul className="mt-1.5 space-y-0.5 font-mono text-[11px] text-[var(--color-text-secondary)]">+ {files.map((f) => (+ <li key={f} className="[overflow-wrap:anywhere]">+ {f}+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}diff --git a/packages/web/src/components/setup/setup-pill.test.tsx b/packages/web/src/components/setup/setup-pill.test.tsxnew file mode 100644index 000000000..23197cafe--- /dev/null+++ b/packages/web/src/components/setup/setup-pill.test.tsx@@ -0,0 +1,85 @@+// @vitest-environment jsdom++import React from "react";+import { SWRConfig } from "swr";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { SetupResponse } from "@/lib/api/setup";+import { doneFixture, setupFixture } from "./setup-fixture";++const mocks = vi.hoisted(() => ({+ getRepoSetup: vi.fn(),+ getOnboardingState: vi.fn(),+ updateOnboardingState: vi.fn(),+}));++vi.mock("@/lib/api/setup", () => ({+ getRepoSetup: mocks.getRepoSetup,+ getOnboardingState: mocks.getOnboardingState,+ updateOnboardingState: mocks.updateOnboardingState,+}));++import { SetupPill, setupPillRepoId } from "./setup-pill";++function renderPill(setup: SetupResponse, compact = false) {+ mocks.getRepoSetup.mockResolvedValue(setup);+ mocks.getOnboardingState.mockResolvedValue(setup.onboarding);+ return render(+ <SWRConfig value={{ provider: () => new Map() }}>+ <SetupPill repoId="r1" compact={compact} />+ </SWRConfig>,+ );+}++beforeEach(() => window.localStorage.clear());+afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("SetupPill", () => {+ it("shows how many essentials are done and links to Setup", async () => {+ renderPill(setupFixture());+ const link = await screen.findByRole("link", { name: "Setup: 2 of 3 essentials done" });+ expect(link.getAttribute("href")).toBe("/repos/r1/settings/setup");+ expect(link.textContent).toContain("2 of 3");+ });++ it("hides on this machine with ×", async () => {+ mocks.updateOnboardingState.mockResolvedValue({ ...setupFixture().onboarding, setup_pill_hidden: true });+ renderPill(setupFixture());+ fireEvent.click(await screen.findByRole("button", { name: "Hide the setup reminder on this machine" }));+ expect(screen.queryByRole("link")).toBeNull();+ expect(mocks.updateOnboardingState).toHaveBeenCalledWith({ setup_pill_hidden: true });+ });++ it("does not run the setup checks once hidden", async () => {+ const s = setupFixture();+ renderPill({ ...s, onboarding: { ...s.onboarding, setup_pill_hidden: true } });+ await waitFor(() => expect(mocks.getOnboardingState).toHaveBeenCalled());+ expect(mocks.getRepoSetup).not.toHaveBeenCalled();+ expect(screen.queryByRole("link")).toBeNull();+ });++ it("disappears when all three essentials are done, and stops checking after", async () => {+ const first = renderPill(doneFixture());+ await waitFor(() => expect(mocks.getRepoSetup).toHaveBeenCalled());+ expect(screen.queryByRole("link")).toBeNull();+ await waitFor(() => expect(window.localStorage.getItem("repowise:setup-done:r1")).toBe("1"));+ first.unmount();++ vi.clearAllMocks();+ renderPill(setupFixture());+ await Promise.resolve();+ expect(mocks.getRepoSetup).not.toHaveBeenCalled();+ });++ it("follows the active repo only once it has an index", () => {+ const repo = (id: string, status: string | null = null) =>+ ({ id, name: id, workspace_status: status }) as never;+ expect(setupPillRepoId([repo("r1")], "r1")).toBe("r1");+ expect(setupPillRepoId([repo("r1", "needs_index")], "r1")).toBeUndefined();+ expect(setupPillRepoId([repo("ws:x")], "ws:x")).toBeUndefined();+ expect(setupPillRepoId([repo("r1")], undefined)).toBeUndefined();+ });+});diff --git a/packages/web/src/components/setup/setup-pill.tsx b/packages/web/src/components/setup/setup-pill.tsxnew file mode 100644index 000000000..95ff04fff--- /dev/null+++ b/packages/web/src/components/setup/setup-pill.tsx@@ -0,0 +1,135 @@+"use client";++import { useEffect, useState } from "react";+import Link from "next/link";+import { useTranslations } from "next-intl";+import { X } from "lucide-react";+import { cn } from "@/lib/utils/cn";+import type { RepoResponse } from "@/lib/api/types";+import { deriveSetup, ESSENTIALS_TOTAL } from "./setup-rows";+import {+ rememberSetupDone,+ setupRememberedDone,+ useHideOnThisMachine,+ useOnboardingState,+ useSetupData,+} from "./use-setup";++export function setupHref(repoId: string): string {+ return `/repos/${encodeURIComponent(repoId)}/settings/setup`;+}++/**+ * The repo whose Setup pill the footer shows: the active one, once it has an+ * index. A repo still waiting for its first index has its own call to action.+ */+export function setupPillRepoId(+ repos: RepoResponse[],+ activeRepoId: string | undefined,+): string | undefined {+ const repo = repos.find((r) => r.id === activeRepoId);+ if (!repo || repo.id.startsWith("ws:")) return undefined;+ if (repo.workspace_status === "needs_index" || repo.workspace_status === "missing_dir") {+ return undefined;+ }+ return repo.id;+}++/** A small progress ring: green for the done share, the border tone for the rest. */+export function SetupRing({ done, className }: { done: number; className?: string }) {+ const share = Math.round((done / ESSENTIALS_TOTAL) * 100);+ return (+ <span+ aria-hidden+ className={cn("relative inline-block h-3.5 w-3.5 shrink-0 rounded-full", className)}+ style={{+ background: `conic-gradient(var(--color-success) 0 ${share}%, var(--color-border-hover) ${share}% 100%)`,+ }}+ >+ <span className="absolute inset-[3px] rounded-full bg-[var(--color-bg-surface)]" />+ </span>+ );+}++/** How many essentials are done, or null while unknown, hidden or finished. */+function usePillProgress(repoId: string): number | null {+ // Read after mount: storage is not there during SSR.+ const [rememberedDone, setRememberedDone] = useState(true);+ useEffect(() => setRememberedDone(setupRememberedDone(repoId)), [repoId]);+ const onboarding = useOnboardingState(!rememberedDone);+ const hidden = onboarding.data?.setup_pill_hidden ?? true;+ // The full payload runs doctor, so it is asked for only when the pill can show.+ const { data } = useSetupData(!rememberedDone && !hidden ? repoId : null);+ // Only the count is needed here, so the copy-shaping options stay inert.+ const view = data ? deriveSetup(data, { repoName: "", now: Date.now(), relative: () => "" }) : null;+ const allDone = view?.allDone ?? false;+ useEffect(() => {+ if (allDone) rememberSetupDone(repoId, true);+ }, [repoId, allDone]);+ if (!view || allDone || rememberedDone || hidden) return null;+ return view.doneCount;+}++/**+ * "Setup N of 3" with a green ring, in the repo sidebar footer and the mobile+ * nav. Links to the Setup page, hides with ×, and goes away once the three+ * essentials are done.+ */+export function SetupPill({ repoId, compact = false }: { repoId: string; compact?: boolean }) {+ const t = useTranslations("setup.pill");+ const done = usePillProgress(repoId);+ const { hide, hiddenNow } = useHideOnThisMachine();+ if (done === null || hiddenNow.has("setup_pill_hidden")) return null;++ const label = t("aria", { done, total: ESSENTIALS_TOTAL });+ if (compact) {+ return (+ <Link+ href={setupHref(repoId)}+ aria-label={label}+ title={label}+ className="flex items-center justify-center rounded-md p-2 transition-colors hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <SetupRing done={done} />+ </Link>+ );+ }+ return (+ <div className="flex items-center gap-1 rounded-full border border-[var(--color-border-hover)] pr-1 text-xs text-[var(--color-text-primary)]">+ <Link+ href={setupHref(repoId)}+ aria-label={label}+ className="flex min-w-0 flex-1 items-center gap-2 rounded-full py-1.5 pl-2.5 transition-colors hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <SetupRing done={done} />+ <span className="truncate">{t("label")}</span>+ <span className="ml-auto pr-1 tabular-nums text-[var(--color-text-tertiary)]">+ {t("progress", { done, total: ESSENTIALS_TOTAL })}+ </span>+ </Link>+ <button+ type="button"+ onClick={() => void hide("setup_pill_hidden")}+ aria-label={t("hide")}+ title={t("hide")}+ className="shrink-0 rounded-full p-1 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-3.5 w-3.5" />+ </button>+ </div>+ );+}++/** The pill for the active repo in the sidebar or mobile nav footer; nothing elsewhere. */+export function FooterSetupPill({+ repos,+ activeRepoId,+ compact = false,+}: {+ repos: RepoResponse[];+ activeRepoId: string | undefined;+ compact?: boolean;+}) {+ const repoId = setupPillRepoId(repos, activeRepoId);+ return repoId ? <SetupPill repoId={repoId} compact={compact} /> : null;+}diff --git a/packages/web/src/components/setup/setup-row.tsx b/packages/web/src/components/setup/setup-row.tsxnew file mode 100644index 000000000..9af24447f--- /dev/null+++ b/packages/web/src/components/setup/setup-row.tsx@@ -0,0 +1,146 @@+"use client";++import { useState, type ReactNode } from "react";+import { useTranslations } from "next-intl";+import { Check } from "lucide-react";+import { AiPromptButton } from "@repowise-dev/ui/health/ai-prompt-button";+import { RowPromptAction } from "@repowise-dev/ui/health/row-prompt-action";+import { buildSetupAiPrompt } from "@repowise-dev/ui/health/ai-prompt-builder";+import { cn } from "@/lib/utils/cn";+import type { SetupMsg, SetupRow, SetupTone } from "./setup-rows";++const DOT: Record<SetupTone, string> = {+ done: "bg-[var(--color-success)]",+ waiting: "bg-[var(--color-warning)]",+ attention: "bg-[var(--color-warning)]",+ off: "bg-[var(--color-text-tertiary)]",+ found: "bg-[var(--color-info)]",+ model: "bg-[var(--color-model)]",+};++/** A `SetupMsg` in the reader's locale; doctor text passes through as is. */+export function useSetupText() {+ const t = useTranslations("setup.row");+ return (m: SetupMsg) => ("text" in m ? m.text : t(m.key, m.values));+}++export function StatusDot({ tone, className }: { tone: SetupTone; className?: string }) {+ return (+ <span aria-hidden className={cn("inline-block h-[7px] w-[7px] shrink-0 rounded-full", DOT[tone], className)} />+ );+}++/** The terminal command a row stands for, in mono. */+export function SetupCommand({ command }: { command: string }) {+ return (+ <code className="max-w-full rounded bg-[var(--color-bg-inset)] px-1.5 py-px font-mono text-[11px] text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">+ {command}+ </code>+ );+}++interface Props {+ row: SetupRow;+ /** The row's one primary action (a button or switch), if it has one. */+ action?: ReactNode;+ /** Opens the prompt modal; rows outside "Needs attention" use it. */+ onOpenPrompt: () => void;+ /** Extra content under the detail, e.g. the skipped files. */+ children?: ReactNode;+}++/**+ * One Setup row: status dot and word, title, one line of detail, then the+ * action column: the primary action, "Copy prompt for your agent" and the+ * terminal command. The prompt shows on hover and focus-within, always on+ * touch screens, and on a "Needs attention" row it is the primary action,+ * with the prompt it copies previewed under the row.+ */+export function SetupRowView({ row, action, onOpenPrompt, children }: Props) {+ const text = useSetupText();+ const attention = row.action?.kind === "prompt";+ const title = text(row.title);+ const [copied, setCopied] = useState(false);+ return (+ <div+ data-row={row.id}+ className={cn(+ "group/row grid grid-cols-1 gap-x-4 gap-y-2 border-t border-[var(--color-border-default)] py-3 sm:grid-cols-[124px_minmax(0,1fr)_auto]",+ attention &&+ "-mx-2.5 rounded-lg border-transparent bg-[var(--color-warning-muted)] px-2.5 [&+&]:mt-1",+ )}+ >+ <span className="flex items-center gap-1.5 pt-px text-xs text-[var(--color-text-secondary)]">+ <StatusDot tone={row.tone} />+ {text(row.status)}+ </span>+ <div className="min-w-0">+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">{title}</h3>+ <p className="mt-0.5 text-xs text-[var(--color-text-secondary)] [text-wrap:pretty]">+ {text(row.detail)}+ </p>+ {children}+ </div>+ <div className="flex flex-wrap items-center gap-2 sm:flex-col sm:flex-nowrap sm:items-end">+ {attention ? <AttentionPrompt row={row} onCopied={() => setCopied(true)} /> : action}+ {!attention && <RowPromptAction onClick={onOpenPrompt} subject={title} />}+ <SetupCommand command={row.command} />+ </div>+ {attention && <PromptPreview row={row} copied={copied} />}+ </div>+ );+}++/** Copies the prompt on click; the preview under the row says it did. */+function AttentionPrompt({ row, onCopied }: { row: SetupRow; onCopied: () => void }) {+ const t = useTranslations("setup");+ return (+ <AiPromptButton+ label={t("copyPrompt")}+ ariaLabel={`${t("copyPrompt")}: ${row.prompt.title}`}+ onClick={() => {+ void copyText(buildSetupAiPrompt(row.prompt)).then((ok) => ok && onCopied());+ }}+ />+ );+}++async function copyText(value: string): Promise<boolean> {+ try {+ await navigator.clipboard.writeText(value);+ return true;+ } catch {+ // Clipboard blocked: the preview stays selectable.+ return false;+ }+}++function PromptPreview({ row, copied }: { row: SetupRow; copied: boolean }) {+ const t = useTranslations("setup");+ return (+ <div className="col-span-full min-w-0 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-inset)] px-3 py-2.5">+ <p className="mb-1 flex items-center justify-between gap-2 text-xs font-medium text-[var(--color-text-primary)]">+ {t("promptPreview")}+ <span aria-live="polite" className="flex items-center gap-1 font-normal text-[var(--color-text-tertiary)]">+ {copied && (+ <>+ <Check className="h-3 w-3 text-[var(--color-success)]" aria-hidden />+ {t("copied")}+ </>+ )}+ </span>+ </p>+ <p className="line-clamp-4 font-mono text-[11px] leading-relaxed text-[var(--color-text-secondary)] [overflow-wrap:anywhere]">+ {previewText(row)}+ </p>+ </div>+ );+}++/** The part of the prompt worth reading at a glance: what was found, what to run, the ask. */+export function previewText(row: SetupRow): string {+ const { state, items, fix } = row.prompt;+ const listed = items?.length ? ` ${items.slice(0, 5).join(", ")}${items.length > 5 ? ", ..." : ""}.` : "";+ const ask = fix ? " Do not change anything until I confirm." : "";+ return `In ${row.prompt.repoName}: ${state}${listed} Run ${row.command} to confirm.${ask}`;+}diff --git a/packages/web/src/components/setup/setup-rows.test.ts b/packages/web/src/components/setup/setup-rows.test.tsnew file mode 100644index 000000000..cb6d34fb3--- /dev/null+++ b/packages/web/src/components/setup/setup-rows.test.ts@@ -0,0 +1,183 @@+import { describe, expect, it } from "vitest";+import { agentListRows, deriveSetup, type DeriveOptions, type SetupRow } from "./setup-rows";+import { doneFixture, NOW, setupFixture } from "./setup-fixture";++const OPTS: DeriveOptions = { repoName: "orbit-api", now: NOW, relative: (iso) => `@${iso}` };+const ids = (rows: SetupRow[]) => rows.map((r) => r.id);++describe("deriveSetup", () => {+ it("splits rows into essentials and optional, with no attention when nothing is wrong", () => {+ const view = deriveSetup(setupFixture(), OPTS);+ expect(view.attention).toEqual([]);+ expect(ids(view.essentials)).toEqual(["index", "agent", "sync"]);+ expect(ids(view.optional)).toEqual(["model", "coverage", "rewrite"]);+ expect(view.doneCount).toBe(2);+ expect(view.allDone).toBe(false);+ });++ it("offers to connect an installed agent while a registered one waits for its first call", () => {+ const agent = deriveSetup(setupFixture(), OPTS).essentials[1]!;+ expect(agent.tone).toBe("waiting");+ expect(agent.detail).toEqual({+ key: "agent.detailWaitingOther",+ values: { agents: "Claude Code", count: 1, other: "Cursor" },+ });+ expect(agent.action).toEqual({ kind: "connect", agentId: "cursor", agentName: "Cursor" });+ expect(agent.command).toBe("repowise agents add --target=cursor");+ });++ it("is done when the index is current, an agent has called and sync is on", () => {+ const view = deriveSetup(doneFixture(), OPTS);+ expect(view.doneCount).toBe(3);+ expect(view.allDone).toBe(true);+ expect(view.essentials.every((r) => r.tone === "done")).toBe(true);+ expect(view.essentials[1]!.detail).toEqual({+ key: "agent.detailCalled",+ values: { agent: "Claude Code", when: "@2026-10-25T11:56:00Z" },+ });+ });++ it("moves an index with skipped files into Needs attention, with the files", () => {+ const s = setupFixture();+ const view = deriveSetup(+ { ...s, index: { ...s.index, parse_error_count: 2, parse_error_files: ["a.py", "b.py"] } },+ OPTS,+ );+ expect(ids(view.attention)).toEqual(["index-parse"]);+ expect(ids(view.essentials)).toEqual(["agent", "sync"]);+ const row = view.attention[0]!;+ expect(row.action).toEqual({ kind: "prompt" });+ expect(row.files).toEqual(["a.py", "b.py"]);+ expect(row.prompt).toMatchObject({ fix: true, verify: "doctor", items: ["a.py", "b.py"] });+ // Skipped files do not undo a current index.+ expect(view.doneCount).toBe(2);+ });++ it("keeps the Not indexed row when an incomplete index also skipped files", () => {+ const s = setupFixture();+ const view = deriveSetup(+ { ...s, index: { ...s.index, state: "incomplete", parse_error_count: 1, parse_error_files: ["a.py"] } },+ OPTS,+ );+ expect(ids(view.attention)).toEqual(["index-parse"]);+ expect(view.essentials[0]!.status).toEqual({ key: "index.statusIncomplete" });+ });++ it("flags an index that is behind HEAD", () => {+ const s = setupFixture();+ const view = deriveSetup({ ...s, index: { ...s.index, state: "behind", live_head: "9999999aaa" } }, OPTS);+ expect(ids(view.attention)).toEqual(["index-behind"]);+ expect(view.attention[0]!.command).toBe("repowise update");+ expect(view.doneCount).toBe(1);+ });++ it("names the wrong-folder case for an agent with no call a day after it connected", () => {+ const s = setupFixture();+ const old = { ...s, index: { ...s.index, indexed_at: "2026-10-23T12:00:00Z" } };+ const view = deriveSetup(old, OPTS);+ expect(ids(view.attention)).toEqual(["agent-silent-claude-code"]);+ expect(view.attention[0]!.detail).toEqual({+ key: "agent.detailNoCalls",+ values: { agent: "Claude Code", repo: "orbit-api" },+ });+ expect(ids(view.essentials)).toEqual(["index", "sync"]);++ // Seen connected in this browser an hour ago: not a day yet.+ const recent = deriveSetup(old, {+ ...OPTS,+ agentSeenAt: { "claude-code": "2026-10-25T11:00:00Z" },+ });+ expect(recent.attention).toEqual([]);+ });++ it("turns doctor warnings and failures into attention rows, except the sync hook row", () => {+ const view = deriveSetup(+ setupFixture({+ checks: [+ { id: "post-commit-hook", name: "Post-commit hook", level: "warn", detail: "not installed" },+ { id: "vector-store", name: "Vector store", level: "fail", detail: "missing", fix: "repowise reindex" },+ ],+ }),+ OPTS,+ );+ expect(ids(view.attention)).toEqual(["check-vector-store"]);+ expect(view.attention[0]).toMatchObject({+ title: { text: "Vector store" },+ status: { key: "check.statusFail" },+ command: "repowise reindex",+ });+ });++ it("offers a discovered coverage report and the model sheet", () => {+ const [model, coverage, rewrite] = deriveSetup(setupFixture(), OPTS).optional;+ expect(model!.action).toEqual({ kind: "model", hasModel: false });+ expect(coverage!.tone).toBe("found");+ expect(coverage!.action).toEqual({ kind: "coverage", path: "coverage/lcov.info" });+ expect(coverage!.command).toBe("repowise coverage add coverage/lcov.info");+ expect(rewrite!.action).toEqual({ kind: "hook", hook: "rewrite", enabled: false, unavailable: false });+ });+});++describe("sections the server could not read", () => {+ const unreadable = (command: string) => ({ key: "unreadable.detail", values: { command } });+ const OLD_INDEX = { indexed_at: "2026-10-20T12:00:00Z" };++ it("calls_available false: no silent-agent row, and a registered agent is not failing", () => {+ const s = setupFixture({ calls_available: false });+ const view = deriveSetup({ ...s, index: { ...s.index, ...OLD_INDEX } }, OPTS);+ expect(view.attention).toEqual([]);+ const agent = view.essentials.find((r) => r.id === "agent")!;+ expect(agent.tone).toBe("done");+ expect(agent.detail).toEqual(unreadable("repowise status"));+ expect(view.doneCount).toBe(3);+ });++ it("agents_available false: the agent row says it couldn't read, not that none is connected", () => {+ const agent = deriveSetup(setupFixture({ agents_available: false, agents: [] }), OPTS).essentials[1]!;+ expect(agent.status).toEqual({ key: "unreadable.status" });+ expect(agent.detail).toEqual(unreadable("repowise agents"));+ expect(agent.action).toBeNull();+ });++ it("model_available false: the model row is not 'built from index'", () => {+ const model = deriveSetup(setupFixture({ model_available: false }), OPTS).optional[0]!;+ expect(model.status).toEqual({ key: "unreadable.status" });+ expect(model.detail).toEqual(unreadable("repowise status"));+ const llm = setupFixture({ model_available: false });+ const written = deriveSetup({ ...llm, model: { ...llm.model, docs_mode: "llm" } }, OPTS).optional[0]!;+ expect(written.status).toEqual({ key: "model.statusLlm" });+ });++ it("coverage_available false: no 'not found' state and no report action", () => {+ const coverage = deriveSetup(setupFixture({ coverage_available: false }), OPTS).optional[1]!;+ expect(coverage.status).toEqual({ key: "unreadable.status" });+ expect(coverage.detail).toEqual(unreadable("repowise coverage status"));+ expect(coverage.action).toBeNull();+ });++ it("checks_available false: flags the empty attention list as unknown", () => {+ expect(deriveSetup(setupFixture({ checks_available: false, checks: [] }), OPTS).checksUnreadable).toBe(true);+ expect(deriveSetup(setupFixture(), OPTS).checksUnreadable).toBe(false);+ });++ it("settings agent rows follow the same flags", () => {+ expect(agentListRows(setupFixture({ agents_available: false, agents: [] }), OPTS).map((r) => r.id)).toEqual([+ "agents-unreadable",+ ]);+ const rows = agentListRows(setupFixture({ calls_available: false }), OPTS);+ expect(rows[0]!.detail).toEqual(unreadable("repowise status"));+ });+});++describe("agentListRows", () => {+ it("lists connected, then installed, then the agents not installed in one row", () => {+ const rows = agentListRows(setupFixture(), OPTS);+ expect(ids(rows)).toEqual(["agent-claude-code", "agent-cursor", "agents-absent"]);+ expect(rows[0]!.action).toMatchObject({ kind: "disconnect", agentId: "claude-code" });+ expect(rows[1]!.detail).toEqual({+ key: "agents.detailInstalledWrites",+ values: { path: ".cursor/mcp.json" },+ });+ expect(rows[2]!.title).toEqual({ text: "Codex" });+ });+});diff --git a/packages/web/src/components/setup/setup-rows.ts b/packages/web/src/components/setup/setup-rows.tsnew file mode 100644index 000000000..c3d58503e--- /dev/null+++ b/packages/web/src/components/setup/setup-rows.ts@@ -0,0 +1,609 @@+/**+ * The Setup page's rows, derived from one `SetupResponse`. Pure, so the page,+ * the sidebar pill and the settings groups all read the same answer.+ *+ * Copy is returned as message keys under `setup.row` (or as server text for+ * doctor checks); the agent prompt is English, since it is written for the+ * agent, not the reader.+ */++import type { SetupPromptRow } from "@repowise-dev/ui/health/ai-prompt-builder";+import type { SetupAgent } from "@repowise-dev/types/generated/http";+import type { SetupResponse } from "@/lib/api/setup";++export type SetupMsg =+ | { key: string; values?: Record<string, string | number> }+ | { text: string };++export type SetupTone = "done" | "waiting" | "attention" | "off" | "found" | "model";++export type SetupHook = "post-commit" | "rewrite";++export type SetupAction =+ | { kind: "connect"; agentId: string; agentName: string }+ | { kind: "disconnect"; agentId: string; agentName: string }+ | { kind: "hook"; hook: SetupHook; enabled: boolean; unavailable?: boolean }+ | { kind: "coverage"; path: string }+ | { kind: "model"; hasModel: boolean }+ /** Needs attention: the prompt is the primary action. */+ | { kind: "prompt" };++export interface SetupRow {+ id: string;+ tone: SetupTone;+ status: SetupMsg;+ title: SetupMsg;+ detail: SetupMsg;+ action: SetupAction | null;+ command: string;+ prompt: SetupPromptRow;+ /** Paths the row can list on request, e.g. files that failed to parse. */+ files?: string[];+}++export interface SetupView {+ attention: SetupRow[];+ /** Doctor could not run, so an empty "Needs attention" proves nothing. */+ checksUnreadable: boolean;+ essentials: SetupRow[];+ optional: SetupRow[];+ /** Index up to date, an agent has called, sync on. */+ doneCount: number;+ allDone: boolean;+}++export interface DeriveOptions {+ repoName: string;+ /** Epoch ms; injected so the 24h rule is testable. */+ now: number;+ /** "4 minutes ago" for an ISO time, in the reader's locale. */+ relative: (iso: string) => string;+ /** When this browser first saw each agent connected, by agent id. */+ agentSeenAt?: Record<string, string>;+}++export const ESSENTIALS_TOTAL = 3;++const DAY_MS = 24 * 60 * 60 * 1000;++/** Doctor rows another Setup row already shows. */+const CHECKS_SHOWN_AS_ROWS = new Set(["post-commit-hook"]);++const msg = (key: string, values?: Record<string, string | number>): SetupMsg =>+ values ? { key, values } : { key };++/** A section the server could not read: say so, never show its empty state. */+const unreadable = (command: string): Pick<SetupRow, "tone" | "status" | "detail"> => ({+ tone: "off",+ status: msg("unreadable.status"),+ detail: msg("unreadable.detail", { command }),+});++const shortSha = (sha: string | null | undefined) => (sha ? sha.slice(0, 7) : "?");++// -- index -------------------------------------------------------------------++function indexBehindRow(s: SetupResponse, o: DeriveOptions): SetupRow {+ const values = { indexed: shortSha(s.index.indexed_commit), live: shortSha(s.index.live_head) };+ return {+ id: "index-behind",+ tone: "attention",+ status: msg("index.statusBehind"),+ title: msg("index.title"),+ detail: msg("index.detailBehind", values),+ action: { kind: "prompt" },+ command: "repowise update",+ prompt: {+ repoName: o.repoName,+ title: "Index is behind",+ state: `The index is at commit ${values.indexed}, and HEAD has moved on to ${values.live}.`,+ command: "repowise update",+ verify: "status",+ fix: true,+ },+ };+}++function indexParseRow(s: SetupResponse, o: DeriveOptions): SetupRow {+ const count = s.index.parse_error_count ?? 0;+ const files = s.index.parse_error_files ?? [];+ return {+ id: "index-parse",+ tone: "attention",+ status: msg("index.statusSkipped", { count }),+ title: msg("index.title"),+ detail: msg("index.detailSkipped", { count }),+ action: { kind: "prompt" },+ command: "repowise doctor --format json",+ files,+ prompt: {+ repoName: o.repoName,+ title: "Files that could not be parsed",+ state: `repowise could not parse ${count} file${count === 1 ? "" : "s"} while indexing, so their symbols are missing from the graph. For each file, tell me whether it should be excluded (exclude_patterns in .repowise/config.yaml) or whether its syntax needs a fix.`,+ command: "repowise doctor --format json",+ verify: "doctor",+ fix: true,+ items: files,+ },+ };+}++function indexRow(s: SetupResponse, o: DeriveOptions): SetupRow {+ const incomplete = s.index.state === "incomplete";+ const command = incomplete ? "repowise init" : "repowise status";+ return {+ id: "index",+ tone: incomplete ? "off" : "done",+ status: msg(incomplete ? "index.statusIncomplete" : "index.statusUpToDate"),+ title: msg("index.title"),+ detail: incomplete+ ? msg("index.detailIncomplete")+ : msg("index.detailUpToDate", {+ files: s.index.file_count ?? 0,+ commit: shortSha(s.index.indexed_commit),+ }),+ action: null,+ command,+ prompt: {+ repoName: o.repoName,+ title: "Index",+ state: incomplete+ ? "There is no complete index for this repository yet."+ : `The index is up to date at commit ${shortSha(s.index.indexed_commit)}.`,+ command,+ verify: "status",+ fix: incomplete,+ },+ };+}++// -- agent -------------------------------------------------------------------++/** The agent that called first, or null when no call names one. */+function firstCaller(agents: SetupAgent[]): SetupAgent | null {+ const called = agents.filter((a) => a.first_call_at);+ called.sort((a, b) => String(a.first_call_at).localeCompare(String(b.first_call_at)));+ return called[0] ?? null;+}++function connectCommand(agentId: string | null): string {+ return agentId ? `repowise agents add --target=${agentId}` : "repowise agents add";+}++/** Registered agents that have not called for a day since they connected. */+function silentAgents(s: SetupResponse, o: DeriveOptions): SetupAgent[] {+ if (!s.calls_available || s.calls.first_call_at || s.calls.unattributed) return [];+ // The API has no connect time, so "since" is when this browser first saw+ // the agent connected, else when the repo was indexed (init registers+ // agents then). Upgrade path: a registration time in the setup payload.+ return (s.agents ?? []).filter((a) => {+ if (!a.connected || a.first_call_at) return false;+ const since = o.agentSeenAt?.[a.id] ?? s.index.indexed_at;+ return since ? o.now - Date.parse(since) >= DAY_MS : false;+ });+}++function agentSilentRow(agent: SetupAgent, o: DeriveOptions): SetupRow {+ const command = "repowise doctor --format json";+ return {+ id: `agent-silent-${agent.id}`,+ tone: "attention",+ status: msg("agent.statusNoCalls"),+ title: msg("agent.title"),+ detail: msg("agent.detailNoCalls", { agent: agent.display_name, repo: o.repoName }),+ action: { kind: "prompt" },+ command,+ prompt: {+ repoName: o.repoName,+ title: "Coding agent has not reached the index",+ state: `${agent.display_name} is registered but has not called this repository's index in the day since it connected. It may have opened a different folder: if so, open ${o.repoName} in it, or run \`repowise init\` in the folder it opened.`,+ command,+ verify: "doctor",+ fix: true,+ },+ };+}++function agentRow(s: SetupResponse, o: DeriveOptions): SetupRow {+ const agents = s.agents ?? [];+ const connected = agents.filter((a) => a.connected);+ const offer = agents.find((a) => a.installed && !a.connected) ?? null;+ const connectAction: SetupAction | null = offer+ ? { kind: "connect", agentId: offer.id, agentName: offer.display_name }+ : null;+ const base = { id: "agent", title: msg("agent.title"), command: connectCommand(offer?.id ?? null) };+ const prompt = (state: string, fix = false): SetupPromptRow => ({+ repoName: o.repoName,+ title: "Coding agent",+ state,+ command: base.command,+ verify: "doctor",+ fix,+ });++ if (!s.agents_available) {+ return {+ ...base,+ ...unreadable("repowise agents"),+ action: null,+ prompt: prompt("repowise could not list the coding agents on this machine.", true),+ };+ }+ if (!s.calls_available && connected.length) {+ // Calls unreadable: a registered agent is not counted as failing.+ return {+ ...base,+ command: "repowise status",+ tone: "done",+ status: msg("agent.statusConnected"),+ detail: msg("unreadable.detail", { command: "repowise status" }),+ action: null,+ prompt: { ...prompt("An agent is registered; its calls could not be read here."), command: "repowise status", verify: "status" },+ };+ }+ if (s.calls.first_call_at) {+ const caller = firstCaller(agents);+ const when = o.relative(s.calls.first_call_at);+ return {+ ...base,+ command: "repowise status",+ tone: "done",+ status: msg("agent.statusConnected"),+ detail: caller+ ? msg("agent.detailCalled", { agent: caller.display_name, when })+ : msg("agent.detailCalledAnon", { when }),+ action: null,+ prompt: { ...prompt("An agent has called this repository's index."), command: "repowise status", verify: "status" },+ };+ }+ if (connected.length) {+ const names = connected.map((a) => a.display_name).join(", ");+ return {+ ...base,+ tone: "waiting",+ status: msg("agent.statusWaiting"),+ detail: offer+ ? msg("agent.detailWaitingOther", { agents: names, count: connected.length, other: offer.display_name })+ : msg("agent.detailWaiting", { agents: names, count: connected.length }),+ action: connectAction,+ prompt: prompt(`${names} is registered and has not called the index yet.`),+ };+ }+ let detail = msg("agent.detailNone");+ if (offer) detail = msg("agent.detailInstalled", { agent: offer.display_name });+ return {+ ...base,+ tone: "off",+ status: msg("agent.statusOff"),+ detail,+ action: connectAction,+ prompt: prompt(+ offer+ ? `${offer.display_name} is installed but not connected to repowise.`+ : "No coding agent is connected to repowise.",+ ),+ };+}++// -- sync, model, coverage, rewrite -------------------------------------------++function syncRow(s: SetupResponse, o: DeriveOptions): SetupRow {+ const installed = s.sync.installed;+ const word = installed === true ? "On" : installed === false ? "Off" : "Unknown";+ return {+ id: "sync",+ tone: installed ? "done" : "off",+ status: msg(`sync.status${word}`),+ title: msg("sync.title"),+ detail: msg(`sync.detail${word}`),+ action: { kind: "hook", hook: "post-commit", enabled: installed === true },+ command: "repowise hook install",+ prompt: {+ repoName: o.repoName,+ title: "Keep the index in sync",+ state: installed+ ? "The post-commit hook is installed, so the index updates after each commit."+ : "The post-commit hook is not installed, so the index updates only when `repowise update` runs.",+ command: "repowise hook install",+ verify: "doctor",+ },+ };+}++function modelRow(s: SetupResponse, o: DeriveOptions): SetupRow {+ const llm = s.model.docs_mode === "llm";+ const providers = s.model.configured_providers ?? [];+ let detail = msg("model.detailNone");+ if (s.model.active_provider) detail = msg("model.detailActive", { provider: s.model.active_provider });+ else if (providers.length) detail = msg("model.detailReady", { providers: providers.join(", ") });+ if (!s.model_available) detail = msg("unreadable.detail", { command: "repowise status" });+ let status = msg(llm ? "model.statusLlm" : "model.statusBuilt");+ // Provider settings unreadable: only a written-by-model state still holds.+ if (!s.model_available && !llm) status = msg("unreadable.status");+ return {+ id: "model",+ tone: "model",+ status,+ title: msg("model.title"),+ detail,+ action: { kind: "model", hasModel: llm },+ command: "repowise generate",+ prompt: {+ repoName: o.repoName,+ title: "A model for docs, chat and answers",+ state: llm+ ? `The docs are written by a model${s.model.active_provider ? ` (${s.model.active_provider})` : ""}.`+ : "The docs are built from the index, without a model. Pick a model source available on this machine (a signed-in agent CLI, an API key or a local model) and write the docs with it.",+ command: "repowise generate",+ verify: "status",+ },+ };+}++function coverageRow(s: SetupResponse, o: DeriveOptions): SetupRow {+ const stored = s.coverage.ingested_at;+ const report = (s.coverage.discovered ?? [])[0];+ const command = `repowise coverage add ${report?.path ?? "<report>"}`;+ const prompt: SetupPromptRow = {+ repoName: o.repoName,+ title: "Test coverage",+ state: "",+ command,+ verify: "status",+ };+ if (!s.coverage_available) {+ return {+ id: "coverage",+ ...unreadable("repowise coverage status"),+ title: msg("coverage.title"),+ action: null,+ command: "repowise coverage status",+ prompt: { ...prompt, command: "repowise coverage status", state: "repowise could not read the stored coverage or search for reports here." },+ };+ }+ if (stored) {+ return {+ id: "coverage",+ tone: "done",+ status: msg("coverage.statusOn"),+ title: msg("coverage.title"),+ detail: msg("coverage.detailOn", { when: o.relative(stored) }),+ action: report ? { kind: "coverage", path: report.path } : null,+ command,+ prompt: { ...prompt, state: "Coverage is stored for this repository. Refresh it from the newest report." },+ };+ }+ if (report) {+ return {+ id: "coverage",+ tone: "found",+ status: msg("coverage.statusFound"),+ title: msg("coverage.title"),+ detail: msg("coverage.detailFound", { path: report.path, age: report.age_days }),+ action: { kind: "coverage", path: report.path },+ command,+ prompt: { ...prompt, state: `A coverage report was found at ${report.path}, ${report.age_days} days old.` },+ };+ }+ return {+ id: "coverage",+ tone: "off",+ status: msg("coverage.statusOff"),+ title: msg("coverage.title"),+ detail: msg("coverage.detailNone"),+ action: null,+ command,+ prompt: {+ ...prompt,+ state: "No coverage report was found. Run the test suite with coverage (lcov, Cobertura or coverage.py JSON), then add the report it writes.",+ },+ };+}++const REWRITE_WORD = {+ installed: "On",+ not_installed: "Off",+ not_applicable: "Na",+ unknown: "Unknown",+} as const;++function rewriteRow(s: SetupResponse, o: DeriveOptions): SetupRow {+ const state = s.rewrite_hook.state;+ const on = state === "installed";+ return {+ id: "rewrite",+ tone: on ? "done" : "off",+ status: msg(`rewrite.status${REWRITE_WORD[state]}`),+ title: msg("rewrite.title"),+ detail: msg(state === "not_applicable" ? "rewrite.detailNa" : "rewrite.detail"),+ action: { kind: "hook", hook: "rewrite", enabled: on, unavailable: state === "not_applicable" },+ command: "repowise hook rewrite install",+ prompt: {+ repoName: o.repoName,+ title: "Shorter command output",+ state: on+ ? "The distill rewrite hook is installed, so Claude Code reads test, build and git output through distill."+ : "The distill rewrite hook is not installed. With it, Claude Code reads test, build and git output through distill, which keeps errors and drops noise.",+ command: "repowise hook rewrite install",+ verify: "doctor",+ },+ };+}++function checkRow(check: NonNullable<SetupResponse["checks"]>[number], o: DeriveOptions): SetupRow {+ const command = check.fix ?? "repowise doctor --format json";+ return {+ id: `check-${check.id}`,+ tone: "attention",+ status: msg(check.level === "fail" ? "check.statusFail" : "check.statusWarn"),+ title: { text: check.name },+ detail: { text: check.detail ?? "" },+ action: { kind: "prompt" },+ command,+ prompt: {+ repoName: o.repoName,+ title: check.name,+ state: `\`repowise doctor\` reports ${check.level === "fail" ? "a failure" : "a warning"} for "${check.name}": ${check.detail ?? ""}`,+ command,+ verify: "doctor",+ fix: true,+ },+ };+}++// -- the view ------------------------------------------------------------------++/** An agent has called; with calls unreadable, one being registered is enough. */+function agentDone(s: SetupResponse): boolean {+ if (!s.calls_available) return (s.agents ?? []).some((a) => a.connected);+ return Boolean(s.calls.first_call_at);+}++export function deriveSetup(s: SetupResponse, o: DeriveOptions): SetupView {+ const attention: SetupRow[] = [];+ const essentials: SetupRow[] = [];++ // An essential with a problem moves up into "Needs attention".+ const indexProblems = [+ s.index.state === "behind" ? indexBehindRow(s, o) : null,+ (s.index.parse_error_count ?? 0) > 0 ? indexParseRow(s, o) : null,+ ].filter((r): r is SetupRow => r !== null);+ attention.push(...indexProblems);+ if (!indexProblems.length || s.index.state === "incomplete") essentials.push(indexRow(s, o));++ const silent = silentAgents(s, o);+ if (silent.length) attention.push(...silent.map((a) => agentSilentRow(a, o)));+ else essentials.push(agentRow(s, o));++ essentials.push(syncRow(s, o));++ for (const check of s.checks ?? []) {+ if (check.level !== "ok" && !CHECKS_SHOWN_AS_ROWS.has(check.id)) {+ attention.push(checkRow(check, o));+ }+ }++ const done = [+ s.index.state === "up_to_date",+ agentDone(s),+ s.sync.installed === true,+ ].filter(Boolean).length;++ return {+ attention,+ checksUnreadable: !s.checks_available,+ essentials,+ optional: [modelRow(s, o), coverageRow(s, o), rewriteRow(s, o)],+ doneCount: done,+ allDone: done === ESSENTIALS_TOTAL,+ };+}++// -- agents & editors ----------------------------------------------------------++/** The file `repowise agents add` writes for an agent, the repo's own first. */+function configFile(agent: SetupAgent): string | null {+ const files = agent.config_files ?? {};+ return (files.project ?? Object.values(files)[0] ?? [])[0] ?? null;+}++function connectedAgentRow(a: SetupAgent, o: DeriveOptions & { callsReadable: boolean }): SetupRow {+ const path = a.registrations?.[0]?.config_path ?? configFile(a) ?? "";+ let detail = a.last_call_at+ ? msg("agents.detailLastCall", { when: o.relative(a.last_call_at), path })+ : msg("agents.detailNoCall", { path });+ if (!o.callsReadable) detail = msg("unreadable.detail", { command: "repowise status" });+ return {+ id: `agent-${a.id}`,+ tone: "done",+ status: msg("agents.statusConnected"),+ title: { text: a.display_name },+ detail,+ action: { kind: "disconnect", agentId: a.id, agentName: a.display_name },+ command: `repowise agents remove --target=${a.id}`,+ prompt: {+ repoName: o.repoName,+ title: `${a.display_name} and repowise`,+ state: `${a.display_name} is connected to repowise through ${path || "its MCP config"}.`,+ command: "repowise status",+ verify: "status",+ },+ };+}++function installedAgentRow(a: SetupAgent, o: DeriveOptions): SetupRow {+ const file = configFile(a);+ return {+ id: `agent-${a.id}`,+ tone: "off",+ status: msg("agents.statusNotConnected"),+ title: { text: a.display_name },+ detail: file ? msg("agents.detailInstalledWrites", { path: file }) : msg("agents.detailInstalled"),+ action: { kind: "connect", agentId: a.id, agentName: a.display_name },+ command: connectCommand(a.id),+ prompt: {+ repoName: o.repoName,+ title: `Connect ${a.display_name}`,+ state: `${a.display_name} is installed but not connected to repowise.`,+ command: connectCommand(a.id),+ verify: "doctor",+ },+ };+}++/**+ * Settings' "Agents & editors": one row per connected or installed agent,+ * then one row naming the agents that are not installed.+ */+export function agentListRows(s: SetupResponse, o: DeriveOptions): SetupRow[] {+ if (!s.agents_available) {+ return [+ {+ id: "agents-unreadable",+ ...unreadable("repowise agents"),+ title: msg("agent.title"),+ action: null,+ command: "repowise agents",+ prompt: {+ repoName: o.repoName,+ title: "Coding agents",+ state: "repowise could not list the coding agents on this machine.",+ command: "repowise agents",+ verify: "doctor",+ fix: true,+ },+ },+ ];+ }+ const agents = s.agents ?? [];+ const withCalls = { ...o, callsReadable: s.calls_available };+ const rows = [+ ...agents.filter((a) => a.connected).map((a) => connectedAgentRow(a, withCalls)),+ ...agents.filter((a) => a.installed && !a.connected).map((a) => installedAgentRow(a, o)),+ ];+ const absent = agents.filter((a) => !a.installed && !a.connected).map((a) => a.display_name);+ if (absent.length) {+ rows.push({+ id: "agents-absent",+ tone: "off",+ status: msg("agents.statusNotInstalled"),+ title: { text: absent.join(", ") },+ detail: msg("agents.detailNotInstalled"),+ action: null,+ command: "repowise agents add",+ prompt: {+ repoName: o.repoName,+ title: "Connect a coding agent",+ state: `These agents are not installed on this machine: ${absent.join(", ")}.`,+ command: "repowise agents add",+ verify: "doctor",+ },+ });+ }+ return rows;+}++/** The agent that called first, for the "You're set up" line. */+export function firstCallerName(s: SetupResponse): string | null {+ return firstCaller(s.agents ?? [])?.display_name ?? null;+}diff --git a/packages/web/src/components/setup/setup-settings.tsx b/packages/web/src/components/setup/setup-settings.tsxnew file mode 100644index 000000000..89660ea3e--- /dev/null+++ b/packages/web/src/components/setup/setup-settings.tsx@@ -0,0 +1,197 @@+"use client";++import { useMemo } from "react";+import Link from "next/link";+import { useFormatter, useTranslations } from "next-intl";+import { OverviewSection } from "@repowise-dev/ui/overview";+import { Skeleton, SkeletonRegion } from "@repowise-dev/ui/ui/skeleton";+import { Button } from "@repowise-dev/ui/ui/button";+import { hostedLink } from "@/lib/hosted";+import type { RepoResponse } from "@/lib/api/types";+import { SetupCommand, SetupRowView, StatusDot } from "./setup-row";+import { agentListRows, type SetupRow } from "./setup-rows";+import { useSetupControls } from "./setup-controls";+import { setupHref } from "./setup-pill";+import { useSetupData, useSetupView } from "./use-setup";++const LINK =+ "text-xs font-medium text-[var(--color-text-primary)] underline decoration-[var(--color-border-hover)] underline-offset-[3px] hover:decoration-[var(--color-text-primary)]";++const ROW_GRID =+ "grid grid-cols-1 gap-x-4 gap-y-2 border-t border-[var(--color-border-default)] py-3 sm:grid-cols-[124px_minmax(0,1fr)_auto]";++/** Settings rows built from the Setup payload, with the Setup page's own controls. */+function SetupRowsBlock({+ repoId,+ label,+ rows,+}: {+ repoId: string;+ label: string;+ rows: SetupRow[];+}) {+ const t = useTranslations("setup");+ const controls = useSetupControls(repoId);+ const { data, error, isLoading, mutate } = useSetupData(repoId);+ if (!data && error && !isLoading) {+ return (+ <p className="flex flex-wrap items-center gap-2 text-xs text-[var(--color-text-secondary)]">+ {t("loadFailed")}+ <Button size="sm" variant="outline" onClick={() => void mutate()}>+ {t("retry")}+ </Button>+ </p>+ );+ }+ if (!data) {+ return (+ <SkeletonRegion label={label} className="flex flex-col gap-2">+ <Skeleton className="h-12 w-full" />+ <Skeleton className="h-12 w-full" />+ </SkeletonRegion>+ );+ }+ return (+ <div>+ {rows.map((row) => (+ <SetupRowView+ key={row.id}+ row={row}+ action={controls.actionFor(row)}+ onOpenPrompt={() => controls.openRowPrompt(row)}+ />+ ))}+ {controls.dialogs}+ </div>+ );+}++/** Rows from the Setup page, by id: e.g. `["sync", "rewrite"]` for Sync & hooks. */+export function RepoSetupRows({+ repoId,+ repoName,+ ids,+}: {+ repoId: string;+ repoName: string;+ ids: string[];+}) {+ const t = useTranslations("setup");+ const { data } = useSetupData(repoId);+ const view = useSetupView(repoId, repoName, data);+ const rows = useMemo(() => {+ const all = view ? [...view.attention, ...view.essentials, ...view.optional] : [];+ return ids.flatMap((id) => all.filter((r) => r.id === id));+ }, [view, ids]);+ return <SetupRowsBlock repoId={repoId} label={t("loading")} rows={rows} />;+}++/** "Agents & editors" for one repo: the Setup page's agent rows, then hosted. */+export function RepoAgentRows({ repoId, repoName }: { repoId: string; repoName: string }) {+ const t = useTranslations("setup");+ const format = useFormatter();+ const { data } = useSetupData(repoId);+ const rows = useMemo(() => {+ if (!data) return [];+ const now = Date.now();+ return agentListRows(data, {+ repoName,+ now,+ relative: (iso) => format.relativeTime(new Date(iso), now),+ });+ }, [data, repoName, format]);+ return (+ <div>+ <SetupRowsBlock repoId={repoId} label={t("loading")} rows={rows} />+ <HostedAgentsRow />+ </div>+ );+}++/** The one place local MCP can't reach: the web apps, through hosted repowise. */+export function HostedAgentsRow() {+ const t = useTranslations("setup.row.agents");+ return (+ <div className={ROW_GRID}>+ <span className="flex items-center gap-1.5 pt-px text-xs text-[var(--color-text-secondary)]">+ <StatusDot tone="found" />+ {t("statusHosted")}+ </span>+ <div className="min-w-0">+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">{t("hostedTitle")}</h3>+ <p className="mt-0.5 text-xs text-[var(--color-text-secondary)]">{t("hostedDetail")}</p>+ </div>+ <div className="flex items-center sm:justify-end">+ <a+ href={hostedLink("settings_agents", "mcp")}+ target="_blank"+ rel="noopener noreferrer"+ className={LINK}+ >+ {t("hostedLink")}+ </a>+ </div>+ </div>+ );+}++/** Repo settings' Setup group lead: where the full checklist lives. */+export function SetupLinkRow({ repoId }: { repoId: string }) {+ const t = useTranslations("setup.settings");+ return (+ <div className="flex flex-wrap items-center justify-between gap-3">+ <p className="text-xs text-[var(--color-text-secondary)]">{t("repoLead")}</p>+ <Link href={setupHref(repoId)} className={LINK}>+ {t("openSetup")}+ </Link>+ </div>+ );+}++/** Global settings' Setup group: Setup is per repository, so link to each. */+export function GlobalSetupLinks({ repos }: { repos: RepoResponse[] }) {+ const t = useTranslations("setup.settings");+ const indexed = repos.filter((r) => !r.id.startsWith("ws:") && r.workspace_status !== "needs_index");+ return (+ <div className="flex flex-col gap-2">+ <p className="text-xs text-[var(--color-text-secondary)]">{t("globalLead")}</p>+ {indexed.length === 0 ? (+ <p className="text-xs text-[var(--color-text-tertiary)]">{t("noRepos")}</p>+ ) : (+ <ul className="flex flex-col">+ {indexed.map((repo) => (+ <li+ key={repo.id}+ className="flex items-center justify-between gap-3 border-t border-[var(--color-border-default)] py-2"+ >+ <span className="min-w-0 truncate text-sm text-[var(--color-text-primary)]">{repo.name}</span>+ <Link href={setupHref(repo.id)} className={LINK} aria-label={t("openSetupFor", { repo: repo.name })}>+ {t("openSetup")}+ </Link>+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}++/**+ * Privacy holds the telemetry status. The dashboard has no switch for it, so+ * it says how to check and change it from the terminal.+ */+export function TelemetryRow() {+ const t = useTranslations("setup.settings");+ return (+ <OverviewSection title={t("telemetryTitle")} description={t("telemetryDescription")}>+ <div className="flex flex-col gap-1.5 text-xs text-[var(--color-text-secondary)]">+ <span className="flex flex-wrap items-center gap-2">+ {t("telemetryCheck")} <SetupCommand command="repowise telemetry status" />+ </span>+ <span className="flex flex-wrap items-center gap-2">+ {t("telemetryOff")} <SetupCommand command="repowise telemetry disable" />+ </span>+ </div>+ </OverviewSection>+ );+}diff --git a/packages/web/src/components/setup/use-setup.ts b/packages/web/src/components/setup/use-setup.tsnew file mode 100644index 000000000..e8304605c--- /dev/null+++ b/packages/web/src/components/setup/use-setup.ts@@ -0,0 +1,220 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import useSWR, { useSWRConfig } from "swr";+import { toast } from "sonner";+import { useFormatter, useTranslations } from "next-intl";+import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";+import {+ addSetupCoverage,+ connectSetupAgent,+ disconnectSetupAgent,+ getOnboardingState,+ getRepoSetup,+ setSetupHook,+ updateOnboardingState,+ type OnboardingPatch,+ type SetupResponse,+ type SetupWriteResponse,+} from "@/lib/api/setup";+import { deriveSetup, type SetupHook, type SetupView } from "./setup-rows";++/** The SWR key every Setup surface shares, so one doctor run feeds them all. */+export const setupKey = (repoId: string) => ["setup", repoId] as const;+export const ONBOARDING_KEY = "setup-onboarding";++/** First load runs doctor (about 20s), so nothing here refetches on its own. */+const QUIET = {+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ revalidateIfStale: false,+ dedupingInterval: 10 * 60_000,+ shouldRetryOnError: false,+} as const;++export function useSetupData(repoId: string | null) {+ return useSWR<SetupResponse>(repoId ? setupKey(repoId) : null, () => getRepoSetup(repoId!), QUIET);+}++export function useOnboardingState(enabled = true) {+ return useSWR(enabled ? ONBOARDING_KEY : null, getOnboardingState, QUIET);+}++// -- essentials done, remembered ----------------------------------------------++const DONE_KEY = (repoId: string) => `repowise:setup-done:${repoId}`;++/**+ * Once the essentials are done the sidebar pill stops asking, so a page load+ * does not run doctor just to hide it. The Setup page itself always checks+ * and clears this when something comes undone.+ */+export function rememberSetupDone(repoId: string, done: boolean) {+ try {+ if (done) window.localStorage.setItem(DONE_KEY(repoId), "1");+ else window.localStorage.removeItem(DONE_KEY(repoId));+ } catch {+ /* storage blocked: the pill checks every session */+ }+}++export function setupRememberedDone(repoId: string): boolean {+ try {+ return window.localStorage.getItem(DONE_KEY(repoId)) === "1";+ } catch {+ return false;+ }+}++// -- agents first seen connected ---------------------------------------------++const SEEN_KEY = (repoId: string) => `repowise:setup-agent-seen:${repoId}`;++function readSeen(repoId: string): Record<string, string> | null {+ try {+ const raw = window.localStorage.getItem(SEEN_KEY(repoId));+ if (raw === null) return null;+ const parsed: unknown = JSON.parse(raw);+ return parsed && typeof parsed === "object" ? (parsed as Record<string, string>) : {};+ } catch {+ return null;+ }+}++/**+ * When this browser first saw each agent connected; feeds the 24h no-call+ * rule. On the first visit for a repo, agents already connected are dated+ * from the index (init registers them then); one connected later is dated+ * from when it was first seen here.+ */+function useAgentSeenAt(repoId: string, setup: SetupResponse | undefined) {+ // null until read from storage, so the 24h rule never runs on a guess.+ const [seen, setSeen] = useState<Record<string, string> | null>(null);+ useEffect(() => {+ if (!setup) return;+ const known = readSeen(repoId);+ const since = known === null ? setup.index.indexed_at : null;+ const next = { ...(known ?? {}) };+ for (const a of setup.agents ?? []) {+ if (a.connected && !next[a.id]) next[a.id] = since ?? new Date().toISOString();+ }+ try {+ window.localStorage.setItem(SEEN_KEY(repoId), JSON.stringify(next));+ } catch {+ /* storage blocked: the rule falls back to the index time */+ }+ setSeen(next);+ }, [repoId, setup]);+ return seen;+}++/** The rows for a repo, in the reader's locale. */+export function useSetupView(repoId: string, repoName: string, setup: SetupResponse | undefined) {+ const format = useFormatter();+ const seen = useAgentSeenAt(repoId, setup);+ return useMemo<SetupView | null>(() => {+ if (!setup || !seen) return null;+ const now = Date.now();+ return deriveSetup(setup, {+ repoName,+ now,+ relative: (iso) => format.relativeTime(new Date(iso), now),+ agentSeenAt: seen,+ });+ }, [setup, repoName, format, seen]);+}++// -- writes ------------------------------------------------------------------++type Patch = (s: SetupResponse) => SetupResponse;++const patchHook =+ (hook: SetupHook, enabled: boolean): Patch =>+ (s) =>+ hook === "post-commit"+ ? { ...s, sync: { ...s.sync, installed: enabled } }+ : { ...s, rewrite_hook: { ...s.rewrite_hook, state: enabled ? "installed" : "not_installed" } };++const patchAgent =+ (agentId: string, connected: boolean): Patch =>+ (s) => ({+ ...s,+ agents: (s.agents ?? []).map((a) => (a.id === agentId ? { ...a, connected } : a)),+ });++const patchCoverage: Patch = (s) => ({+ ...s,+ coverage: { ...s.coverage, ingested_at: new Date().toISOString() },+});++/**+ * Setup writes. Each shows its result on the control first, then rolls the+ * control back when the command reports `ok: false` (or the request fails)+ * and says why. Success refetches, since a write can change other rows.+ */+export function useSetupWrites(repoId: string) {+ const t = useTranslations("setup");+ const { data, mutate } = useSetupData(repoId);+ const [busy, setBusy] = useState<string | null>(null);++ const run = useCallback(+ async (id: string, patch: Patch, call: () => Promise<SetupWriteResponse>) => {+ const before = data;+ setBusy(id);+ if (before) await mutate(patch(before), { revalidate: false });+ try {+ const res = await call();+ if (!res.ok) {+ await mutate(before, { revalidate: false });+ toast.error(res.message || t("writeFailed"), { description: res.command });+ return false;+ }+ if (res.message) toast.success(res.message);+ void mutate();+ return true;+ } catch (e) {+ await mutate(before, { revalidate: false });+ toast.error(t("writeFailed"), { description: toFriendlyMessage(e) });+ return false;+ } finally {+ setBusy(null);+ }+ },+ [data, mutate, t],+ );++ return {+ busy,+ setHook: (hook: SetupHook, enabled: boolean) =>+ run(`hook:${hook}`, patchHook(hook, enabled), () => setSetupHook(repoId, hook, enabled)),+ connect: (agentId: string) =>+ run(`agent:${agentId}`, patchAgent(agentId, true), () => connectSetupAgent(repoId, agentId)),+ disconnect: (agentId: string) =>+ run(`agent:${agentId}`, patchAgent(agentId, false), () => disconnectSetupAgent(repoId, agentId)),+ addCoverage: (path: string) =>+ run("coverage", patchCoverage, () => addSetupCoverage(repoId, path)),+ };+}++/**+ * Hide an onboarding surface on this machine. The server keeps it in+ * `~/.repowise/platform.json`; when it refuses (a server with an API key),+ * the surface still hides for this session.+ */+export function useHideOnThisMachine() {+ const { mutate } = useSWRConfig();+ const [hiddenNow, setHiddenNow] = useState<Set<keyof OnboardingPatch>>(new Set());+ const hide = useCallback(+ async (field: "setup_pill_hidden" | "hosted_card_hidden") => {+ setHiddenNow((prev) => new Set(prev).add(field));+ try {+ const next = await updateOnboardingState({ [field]: true });+ await mutate(ONBOARDING_KEY, next, { revalidate: false });+ } catch {+ /* refused or offline: hidden for this session only */+ }+ },+ [mutate],+ );+ return { hide, hiddenNow };+}diff --git a/packages/web/src/lib/hosted.ts b/packages/web/src/lib/hosted.tsindex 3c1ea52d7..0f27bb890 100644--- a/packages/web/src/lib/hosted.ts+++ b/packages/web/src/lib/hosted.ts@@ -28,7 +28,7 @@ export interface Nudge {* repos says "free for 10 days, card required", never just "free". */export const NUDGES = {mcp: {- text: "Use this repo inside Claude.ai or ChatGPT. Local MCP only works in desktop tools.",+ text: "Use this repo from Claude.ai or ChatGPT too.",surface: "mcp",moment: "mcp",},diff --git a/packages/web/src/lib/tour.ts b/packages/web/src/lib/tour.tsnew file mode 100644index 000000000..905e4aef4--- /dev/null+++ b/packages/web/src/lib/tour.ts@@ -0,0 +1,10 @@+/**+ * The welcome tour opens from a link: the repo overview with `?tour=1`. The+ * welcome dialog listens for this query param on the overview route, opens+ * itself, and removes the param once it has.+ */+export const TOUR_QUERY_PARAM = "tour";++export function tourHref(repoId: string): string {+ return `/repos/${encodeURIComponent(repoId)}/overview?${TOUR_QUERY_PARAM}=1`;+}