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): split settings into sub-pages with one row pattern and autosave (#4694)
Raghav Chamadiya640a7df6a949
diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.mdindex 1503e8df9..e20ed809f 100644--- a/packages/ui/COMPONENT_CONTRACTS.md+++ b/packages/ui/COMPONENT_CONTRACTS.md@@ -1266,6 +1266,7 @@ multi-tenant settings persistence is deferred to Phase 5 RBAC.|------|------|----------|| `value` | `RepoSettingsValue` | yes || `onSubmit` | `(next: RepoSettingsValue) => Promise<void>` | no |+| `autosave` | `boolean` (saves each field on commit, rolls back when `onSubmit` rejects) | no || `localPath` | `string` | no || `remoteUrl` | `string` | no || `disabledHint` | `string` | no |diff --git a/packages/ui/__tests__/dashboard/active-job-banner.test.tsx b/packages/ui/__tests__/dashboard/active-job-banner.test.tsxindex d0856b93a..a3d6ae85a 100644--- a/packages/ui/__tests__/dashboard/active-job-banner.test.tsx+++ b/packages/ui/__tests__/dashboard/active-job-banner.test.tsx@@ -76,7 +76,7 @@ describe("ActiveJobBanner", () => {provider_issue: { kind: "auth", message: "API key rejected by openai. Update it in Settings." },},})}- settingsHref="/repos/r1/settings#provider"+ settingsHref="/repos/r1/settings/models"onDismiss={onDismiss}/>,);@@ -85,7 +85,7 @@ describe("ActiveJobBanner", () => {expect(screen.getByText(/API key rejected by openai/)).toBeInTheDocument();expect(screen.getByRole("link", { name: /Provider settings/ })).toHaveAttribute("href",- "/repos/r1/settings#provider",+ "/repos/r1/settings/models",);fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));expect(onDismiss).toHaveBeenCalled();diff --git a/packages/ui/__tests__/jobs/generation-progress.test.tsx b/packages/ui/__tests__/jobs/generation-progress.test.tsxindex 505251b92..b245e99a2 100644--- a/packages/ui/__tests__/jobs/generation-progress.test.tsx+++ b/packages/ui/__tests__/jobs/generation-progress.test.tsx@@ -197,7 +197,7 @@ describe("GenerationProgress", () => {onCancel={vi.fn()}onRetry={vi.fn()}onDismiss={onDismiss}- settingsHref="/repos/r1/settings#provider"+ settingsHref="/repos/r1/settings/models"/>,);expect(screen.getByText("Finished with problems")).toBeTruthy();@@ -206,7 +206,7 @@ describe("GenerationProgress", () => {expect(screen.getByText(/API key rejected by openai/)).toBeTruthy();expect(screen.getByRole("link", { name: /Provider settings/ })).toHaveAttribute("href",- "/repos/r1/settings#provider",+ "/repos/r1/settings/models",);fireEvent.click(screen.getByRole("button", { name: /Dismiss/ }));expect(onDismiss).toHaveBeenCalled();diff --git a/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx b/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsxindex cde2a2045..0b739f3b4 100644--- a/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx+++ b/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx@@ -384,7 +384,7 @@ describe("RefactoringDrawer with no model configured", () => {modelSetting={{value: { enabled: true, provider: null, model: null },onToggle: async () => {},- setupHref: "/repos/r1/settings#provider",+ setupHref: "/repos/r1/settings/models",}}/>,);diff --git a/packages/ui/__tests__/refactoring/refactoring-model-toggle.test.tsx b/packages/ui/__tests__/refactoring/refactoring-model-toggle.test.tsxindex 39709f776..909ea08d8 100644--- a/packages/ui/__tests__/refactoring/refactoring-model-toggle.test.tsx+++ b/packages/ui/__tests__/refactoring/refactoring-model-toggle.test.tsx@@ -24,13 +24,13 @@ describe("RefactoringModelToggle", () => {<RefactoringModelTogglevalue={{ enabled: false, provider: null, model: null }}onToggle={vi.fn()}- setupHref="/repos/r1/settings#provider"+ setupHref="/repos/r1/settings/models"/>,);expect(screen.getByText("No model configured.", { exact: false })).toBeInTheDocument();expect(screen.getByRole("link", { name: "Set one up" })).toHaveAttribute("href",- "/repos/r1/settings#provider",+ "/repos/r1/settings/models",);});diff --git a/packages/ui/__tests__/settings/general-form.test.tsx b/packages/ui/__tests__/settings/general-form.test.tsxindex a1e8371cc..ee5493a91 100644--- a/packages/ui/__tests__/settings/general-form.test.tsx+++ b/packages/ui/__tests__/settings/general-form.test.tsx@@ -83,4 +83,68 @@ describe("GeneralForm", () => {"true",);});++ describe("autosave", () => {+ it("has no Save button and saves a text field on blur, with a Saved tick", async () => {+ const onSubmit = vi.fn().mockResolvedValue(undefined);+ render(<GeneralForm value={baseValue} onSubmit={onSubmit} autosave />);+ expect(screen.queryByRole("button", { name: /Save changes/i })).not.toBeInTheDocument();++ const name = screen.getByLabelText("Repository name");+ fireEvent.change(name, { target: { value: "renamed" } });+ expect(onSubmit).not.toHaveBeenCalled();+ fireEvent.blur(name);+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));+ expect(onSubmit.mock.calls[0]![0]).toMatchObject({ name: "renamed", default_branch: "main" });+ expect(await screen.findByText("Saved")).toBeInTheDocument();+ });++ it("does not save an unchanged or emptied text field", () => {+ const onSubmit = vi.fn().mockResolvedValue(undefined);+ render(<GeneralForm value={baseValue} onSubmit={onSubmit} autosave />);+ const branch = screen.getByLabelText("Default branch");+ fireEvent.blur(branch);+ fireEvent.change(branch, { target: { value: " " } });+ fireEvent.keyDown(branch, { key: "Enter" });+ expect(onSubmit).not.toHaveBeenCalled();+ expect(branch).toHaveValue("main");+ });++ it("saves a style on click and rolls it back when the write fails", async () => {+ const onSubmit = vi.fn().mockRejectedValue(new Error("nope"));+ render(<GeneralForm value={baseValue} onSubmit={onSubmit} autosave />);+ fireEvent.click(screen.getByRole("radio", { name: /Caveman/i }));+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));+ expect(onSubmit.mock.calls[0]![0]).toMatchObject({ wiki_style: "caveman" });+ await waitFor(() =>+ expect(screen.getByRole("radio", { name: /Comprehensive/i })).toHaveAttribute("aria-checked", "true"),+ );+ expect(screen.getByText("Could not save")).toBeInTheDocument();+ });++ it("keeps a superseded write that succeeded when a newer one fails", async () => {+ let releaseFirst: () => void = () => {};+ const onSubmit = vi+ .fn()+ .mockImplementationOnce(() => new Promise<void>((r) => (releaseFirst = r)))+ .mockRejectedValueOnce(new Error("nope"));+ render(<GeneralForm value={baseValue} onSubmit={onSubmit} autosave />);+ fireEvent.click(screen.getByRole("radio", { name: /Caveman/i }));+ fireEvent.click(screen.getByRole("button", { name: "+ vendor/" }));+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(2));+ releaseFirst();+ await waitFor(() => expect(screen.getByText("Could not save")).toBeInTheDocument());+ // The style write landed; only the path write rolls back.+ expect(screen.getByRole("radio", { name: /Caveman/i })).toHaveAttribute("aria-checked", "true");+ expect(screen.queryByText("vendor/")).not.toBeInTheDocument();+ });++ it("saves an excluded path as soon as it is added", async () => {+ const onSubmit = vi.fn().mockResolvedValue(undefined);+ render(<GeneralForm value={baseValue} onSubmit={onSubmit} autosave />);+ fireEvent.click(screen.getByRole("button", { name: "+ vendor/" }));+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));+ expect(onSubmit.mock.calls[0]![0].exclude_patterns).toEqual(["node_modules/", "vendor/"]);+ });+ });});diff --git a/packages/ui/__tests__/settings/settings-primitives.test.tsx b/packages/ui/__tests__/settings/settings-primitives.test.tsxindex 8bddddc9d..e2a267914 100644--- a/packages/ui/__tests__/settings/settings-primitives.test.tsx+++ b/packages/ui/__tests__/settings/settings-primitives.test.tsx@@ -4,9 +4,12 @@ import {CopyLine,EnvVarLine,SaveIndicator,+ SettingsAdvanced,SettingsRow,StatusLine,+ useSaveState,} from "../../src/settings/settings-primitives.js";+import { act, renderHook } from "@testing-library/react";describe("SaveIndicator", () => {it("renders nothing at rest", () => {@@ -103,3 +106,68 @@ describe("SettingsRow", () => {expect(screen.getByText("Where to reach it.")).toBeInTheDocument();});});++describe("SettingsRow save tick", () => {+ it("shows its own save state beside the label, nothing at rest", () => {+ const { rerender } = render(+ <SettingsRow label="Name">+ <input />+ </SettingsRow>,+ );+ expect(screen.queryByText("Saved")).not.toBeInTheDocument();+ rerender(+ <SettingsRow label="Name" saveState="saved">+ <input />+ </SettingsRow>,+ );+ expect(screen.getByText("Saved")).toBeInTheDocument();+ });+});++describe("SettingsAdvanced", () => {+ it("is folded by default and names what it holds", () => {+ render(+ <SettingsAdvanced hint="Rare knobs.">+ <p>inside</p>+ </SettingsAdvanced>,+ );+ const details = screen.getByText("Advanced").closest("details");+ expect(details).not.toHaveAttribute("open");+ expect(screen.getByText("Rare knobs.")).toBeInTheDocument();+ });+});++describe("useSaveState", () => {+ it("reports saved, then failed, and ignores a stale write", async () => {+ const { result } = renderHook(() => useSaveState());+ let outcome: string = "";+ await act(async () => {+ outcome = await result.current.track(() => Promise.resolve());+ });+ expect(outcome).toBe("saved");+ expect(result.current.state).toBe("saved");++ await act(async () => {+ outcome = await result.current.track(+ () => Promise.reject(new Error("x")),+ () => "Disk full",+ );+ });+ expect(outcome).toBe("failed");+ expect(result.current.state).toBe("error");+ expect(result.current.error).toBe("Disk full");++ let release: () => void = () => {};+ const slow = new Promise<void>((r) => (release = r));+ let first: Promise<string> = Promise.resolve("");+ await act(async () => {+ first = result.current.track(() => slow);+ await result.current.track(() => Promise.resolve());+ });+ await act(async () => {+ release();+ expect(await first).toBe("stale");+ });+ expect(result.current.state).toBe("saved");+ });+});diff --git a/packages/ui/__tests__/wiki/regenerate-button.test.tsx b/packages/ui/__tests__/wiki/regenerate-button.test.tsxindex af5469c1f..fe35bc556 100644--- a/packages/ui/__tests__/wiki/regenerate-button.test.tsx+++ b/packages/ui/__tests__/wiki/regenerate-button.test.tsx@@ -70,11 +70,11 @@ describe("GenerateConfirmDialog (bulk overrides)", () => {<GenerateConfirmDialog{...base}noProvider- settingsHref="/repos/r1/settings#provider"+ settingsHref="/repos/r1/settings/models"/>,);const link = screen.getByRole("link", { name: /Add a provider key/ });- expect(link).toHaveAttribute("href", "/repos/r1/settings#provider");+ expect(link).toHaveAttribute("href", "/repos/r1/settings/models");});it("never renders a coverage bucket picker", () => {diff --git a/packages/ui/src/settings/general-form.tsx b/packages/ui/src/settings/general-form.tsxindex 111641367..77f51d39d 100644--- a/packages/ui/src/settings/general-form.tsx+++ b/packages/ui/src/settings/general-form.tsx@@ -1,19 +1,12 @@"use client";-import { useState } from "react";-import { Info, Save, X } from "lucide-react";-import { Badge } from "../ui/badge";+import { useRef, useState, type ChangeEvent, type KeyboardEvent } from "react";+import { Save, X } from "lucide-react";import { Button } from "../ui/button";import { Input } from "../ui/input";-import { Label } from "../ui/label";-import {- Tooltip,- TooltipContent,- TooltipProvider,- TooltipTrigger,-} from "../ui/tooltip";import { DEFAULT_WIKI_STYLE, WIKI_STYLES } from "@repowise-dev/types";import type { RepoSettingsValue, WikiStyle } from "@repowise-dev/types/settings";+import { SettingsRow, SettingsRows, useSaveState } from "./settings-primitives";const SUGGESTIONS = ["vendor/",@@ -24,19 +17,31 @@ const SUGGESTIONS = ["**/fixtures/**",];+type Field = keyof RepoSettingsValue;+type TextField = "name" | "default_branch";+function arraysEqual(a: string[], b: string[]) {return a.length === b.length && a.every((v, i) => v === b[i]);}+function withStyle(value: RepoSettingsValue): RepoSettingsValue {+ return { ...value, wiki_style: value.wiki_style ?? DEFAULT_WIKI_STYLE };+}+export interface GeneralFormProps {/** Initial form value. Also used as the "saved" baseline for dirty-check. */value: RepoSettingsValue;/*** Optional save handler. When omitted, the form renders read-only — useful* for hosted, where multi-tenant settings persistence is deferred to the- * Phase 5 RBAC data-model rewrite.+ * Phase 5 RBAC data-model rewrite. Rejecting rolls an autosaved field back.*/onSubmit?: (next: RepoSettingsValue) => Promise<void>;+ /**+ * Save each field as it is committed (blur or Enter for text, on click for+ * the rest) with a "Saved" tick on its row, instead of one Save button.+ */+ autosave?: boolean;/** Read-only fields shown alongside the editable form. */localPath?: string;remoteUrl?: string;@@ -47,261 +52,290 @@ export interface GeneralFormProps {disabledHint?: string;}+/** The form's values, the last saved baseline, and both save models. */+function useGeneralFormState(value: RepoSettingsValue, onSubmit: GeneralFormProps["onSubmit"]) {+ const [form, setForm] = useState<RepoSettingsValue>(() => withStyle(value));+ const [saving, setSaving] = useState(false);+ const [field, setField] = useState<Field | null>(null);+ const save = useSaveState();+ // Writes are whole-object, so each builds on the newest intended value;+ // a failure puts its field back to what the server last accepted.+ const saved = useRef<RepoSettingsValue>(withStyle(value));+ const pending = useRef<RepoSettingsValue>(withStyle(value));+ // Which write the baseline came from, so a slower older success never+ // replaces a newer one, and a superseded success still counts as saved.+ const writeSeq = useRef(0);+ const savedSeq = useRef(0);++ const set = <K extends Field>(key: K, next: RepoSettingsValue[K]) =>+ setForm((f) => ({ ...f, [key]: next }));++ async function commit<K extends Field>(key: K, next: RepoSettingsValue[K]) {+ if (!onSubmit) return;+ const nextValue = { ...pending.current, [key]: next };+ pending.current = nextValue;+ set(key, next);+ setField(key);+ const mine = ++writeSeq.current;+ const outcome = await save.track(async () => {+ await onSubmit(nextValue);+ if (mine > savedSeq.current) {+ saved.current = nextValue;+ savedSeq.current = mine;+ }+ });+ // Only the field that failed goes back; an older write still in flight+ // for another field keeps its value and rolls back itself if it fails.+ if (outcome === "failed") {+ const accepted = saved.current[key];+ pending.current = { ...pending.current, [key]: accepted };+ set(key, accepted);+ }+ }++ async function submitAll() {+ if (!onSubmit) return;+ setSaving(true);+ try {+ await onSubmit(form);+ saved.current = form;+ pending.current = form;+ } finally {+ setSaving(false);+ }+ }++ const hasChanges =+ form.name !== saved.current.name ||+ form.default_branch !== saved.current.default_branch ||+ !arraysEqual(form.exclude_patterns, saved.current.exclude_patterns) ||+ form.wiki_style !== saved.current.wiki_style;++ const rowSave = (key: Field) =>+ field === key ? { saveState: save.state, saveError: save.error } : {};++ return { form, set, commit, submitAll, saving, hasChanges, saved, pending, rowSave };+}+export function GeneralForm({value,onSubmit,+ autosave = false,localPath,remoteUrl,disabledHint = "Editing repository settings is not yet available on this surface.",}: GeneralFormProps) {- const [name, setName] = useState(value.name);- const [branch, setBranch] = useState(value.default_branch);- const [patterns, setPatterns] = useState<string[]>(value.exclude_patterns);- const [newPattern, setNewPattern] = useState("");- const [wikiStyle, setWikiStyle] = useState<WikiStyle>(- value.wiki_style ?? DEFAULT_WIKI_STYLE,- );- const [saving, setSaving] = useState(false);-+ const state = useGeneralFormState(value, onSubmit);+ const { form, set, saved, pending, rowSave } = state;const readOnly = onSubmit === undefined;- const hasChanges =- name !== value.name ||- branch !== value.default_branch ||- !arraysEqual(patterns, value.exclude_patterns) ||- wikiStyle !== (value.wiki_style ?? DEFAULT_WIKI_STYLE);+ const live = autosave && !readOnly;- function addPattern(pattern: string) {- const trimmed = pattern.trim();- if (!trimmed || patterns.includes(trimmed)) return;- setPatterns([...patterns, trimmed]);- setNewPattern("");+ /** Text fields: autosave commits on blur or Enter; an emptied field reverts. */+ function commitText(key: TextField) {+ if (!live) return;+ const next = form[key].trim();+ if (!next) set(key, saved.current[key]);+ else if (next !== pending.current[key]) void state.commit(key, next);}- function removePattern(pattern: string) {- setPatterns(patterns.filter((p) => p !== pattern));+ function setPatterns(next: string[]) {+ if (live) void state.commit("exclude_patterns", next);+ else set("exclude_patterns", next);}- async function handleSave() {- if (!onSubmit || !hasChanges) return;- setSaving(true);- try {- await onSubmit({- name,- default_branch: branch,- exclude_patterns: patterns,- wiki_style: wikiStyle,- });- } finally {- setSaving(false);- }+ function setStyle(next: WikiStyle) {+ if (next === form.wiki_style) return;+ if (live) void state.commit("wiki_style", next);+ else set("wiki_style", next);}- return (- <div className="space-y-5">- <div className="space-y-1.5">- <Label htmlFor="repo-name">Repository name</Label>- <Input- id="repo-name"- value={name}- onChange={(e) => setName(e.target.value)}- placeholder="my-project"- className="max-w-sm"- disabled={readOnly}- />- </div>-- <div className="space-y-1.5">- <Label htmlFor="repo-branch">Default branch</Label>- <Input- id="repo-branch"- value={branch}- onChange={(e) => setBranch(e.target.value)}- placeholder="main"- className="max-w-sm"- disabled={readOnly}- />- </div>+ const textProps = (key: TextField) => ({+ value: form[key],+ onChange: (e: ChangeEvent<HTMLInputElement>) => set(key, e.target.value),+ onBlur: () => commitText(key),+ onKeyDown: (e: KeyboardEvent<HTMLInputElement>) => {+ if (e.key === "Enter") commitText(key);+ },+ className: "max-w-sm",+ disabled: readOnly,+ });- {localPath && (- <div className="space-y-1.5">- <Label>Local path</Label>- <p className="text-sm font-mono text-[var(--color-text-secondary)] break-all">- {localPath}- </p>- <p className="text-xs text-[var(--color-text-tertiary)]">- Path cannot be changed after repository is registered.- </p>- </div>- )}+ return (+ <div className="space-y-4">+ <SettingsRows>+ <SettingsRow label="Repository name" htmlFor="repo-name" {...rowSave("name")}>+ <Input id="repo-name" placeholder="my-project" {...textProps("name")} />+ </SettingsRow>+ <SettingsRow+ label="Default branch"+ htmlFor="repo-branch"+ hint="The branch that gets indexed."+ {...rowSave("default_branch")}+ >+ <Input id="repo-branch" placeholder="main" {...textProps("default_branch")} />+ </SettingsRow>+ {localPath && (+ <SettingsRow label="Local path" hint="Fixed once the repository is registered.">+ <p className="break-all font-mono text-sm text-[var(--color-text-secondary)]">{localPath}</p>+ </SettingsRow>+ )}+ {remoteUrl && (+ <SettingsRow label="Remote URL">+ <p className="break-all font-mono text-sm text-[var(--color-text-secondary)]">{remoteUrl}</p>+ </SettingsRow>+ )}+ <SettingsRow+ label="Excluded paths"+ htmlFor="exclude-pattern"+ hint="Gitignore-style patterns, relative to the repo root, that indexing and generation skip. .gitignore and .repowiseIgnore always apply."+ {...rowSave("exclude_patterns")}+ >+ <ExcludedPaths patterns={form.exclude_patterns} readOnly={readOnly} onChange={setPatterns} />+ </SettingsRow>+ <SettingsRow+ label="Documentation style"+ hint="The voice and density of generated pages. Changing it offers to regenerate the docs."+ {...rowSave("wiki_style")}+ >+ <StylePicker value={form.wiki_style ?? DEFAULT_WIKI_STYLE} readOnly={readOnly} onChange={setStyle} />+ </SettingsRow>+ </SettingsRows>- {remoteUrl && (+ {!live && (<div className="space-y-1.5">- <Label>Remote URL</Label>- <p className="text-sm font-mono text-[var(--color-text-secondary)] break-all">- {remoteUrl}- </p>+ <Button+ onClick={() => void state.submitAll()}+ disabled={readOnly || !state.hasChanges || state.saving}+ size="sm"+ className="gap-2"+ >+ <Save className="h-3.5 w-3.5" />+ {state.saving ? "Saving…" : "Save changes"}+ </Button>+ {readOnly && <p className="text-xs text-[var(--color-text-tertiary)]">{disabledHint}</p>}</div>)}+ </div>+ );+}- <div className="space-y-3 border-t border-[var(--color-border-default)] pt-5">- <div className="flex items-center gap-2">- <span className="text-sm font-medium">Excluded Paths</span>- {patterns.length > 0 && (- <Badge variant="accent" className="text-xs">- {patterns.length} active- </Badge>- )}- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <Info className="h-3.5 w-3.5 text-[var(--color-text-tertiary)] cursor-help" />- </TooltipTrigger>- <TooltipContent>- <p>Supports full .gitignore syntax. Paths are relative to the repo root.</p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- <p className="text-xs text-[var(--color-text-secondary)]">- Gitignore-style patterns. Excluded folders are skipped during indexing and generation.- </p>-- {patterns.length === 0 ? (- <p className="text-xs text-[var(--color-text-tertiary)] italic">- No custom patterns — .gitignore and .repowiseIgnore are always respected.- </p>- ) : (- <div className="flex flex-wrap gap-1.5">- {patterns.map((p) => (- <span- key={p}- className="inline-flex items-center gap-1 rounded-full bg-[var(--color-bg-inset)] px-2.5 py-0.5 text-xs font-mono text-[var(--color-text-primary)] border border-[var(--color-border-default)]"- >- {p}- {!readOnly && (- <button- type="button"- onClick={() => removePattern(p)}- className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] transition-colors"- aria-label={`Remove ${p}`}- >- <X className="h-3 w-3" />- </button>- )}- </span>- ))}- </div>- )}+function ExcludedPaths({+ patterns,+ readOnly,+ onChange,+}: {+ patterns: string[];+ readOnly: boolean;+ onChange: (next: string[]) => void;+}) {+ const [draft, setDraft] = useState("");- {!readOnly && (- <>- <div className="flex gap-2 max-w-sm">- <Input- id="exclude-pattern"- aria-label="New excluded pattern"- value={newPattern}- onChange={(e) => setNewPattern(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter") {- e.preventDefault();- addPattern(newPattern);- }- }}- placeholder="e.g. vendor/, src/generated/**, *.min.js"- className="font-mono text-xs"- />- <Button- type="button"- variant="outline"- size="sm"- onClick={() => addPattern(newPattern)}- disabled={!newPattern.trim()}- >- Add- </Button>- </div>+ function add(pattern: string) {+ const trimmed = pattern.trim();+ if (!trimmed || patterns.includes(trimmed)) return;+ onChange([...patterns, trimmed]);+ setDraft("");+ }- <div className="flex flex-wrap gap-1.5">- {SUGGESTIONS.map((suggestion) => (+ return (+ <div className="space-y-3">+ {patterns.length === 0 ? (+ <p className="text-xs text-[var(--color-text-tertiary)]">No custom patterns.</p>+ ) : (+ <div className="flex flex-wrap gap-1.5">+ {patterns.map((p) => (+ <span+ key={p}+ className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-inset)] px-2.5 py-0.5 font-mono text-xs text-[var(--color-text-primary)]"+ >+ {p}+ {!readOnly && (<button- key={suggestion}type="button"- onClick={() => addPattern(suggestion)}- disabled={patterns.includes(suggestion)}- className="text-xs rounded-full border border-[var(--color-border-default)] px-2.5 py-0.5 font-mono text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-inset)] transition-colors disabled:opacity-40 disabled:cursor-not-allowed"+ onClick={() => onChange(patterns.filter((x) => x !== p))}+ className="text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-primary)]"+ aria-label={`Remove ${p}`}>- + {suggestion}+ <X className="h-3 w-3" /></button>- ))}- </div>- </>- )}- </div>-- <div className="space-y-3 border-t border-[var(--color-border-default)] pt-5">- <div className="flex items-center gap-2">- <span className="text-sm font-medium">Documentation style</span>- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <Info className="h-3.5 w-3.5 text-[var(--color-text-tertiary)] cursor-help" />- </TooltipTrigger>- <TooltipContent>- <p>- Controls the voice and density of generated wiki pages. Changing- it regenerates the wiki in the new style.- </p>- </TooltipContent>- </Tooltip>- </TooltipProvider>+ )}+ </span>+ ))}</div>- <div- role="radiogroup"- aria-label="Documentation style"- className="grid gap-2 sm:grid-cols-2 max-w-2xl"- >- {WIKI_STYLES.map((style) => {- const selected = wikiStyle === style.id;- return (+ )}++ {!readOnly && (+ <>+ <div className="flex max-w-sm gap-2">+ <Input+ id="exclude-pattern"+ aria-label="New excluded pattern"+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ add(draft);+ }+ }}+ placeholder="e.g. vendor/, src/generated/**"+ className="font-mono text-xs"+ />+ <Button type="button" variant="outline" size="sm" onClick={() => add(draft)} disabled={!draft.trim()}>+ Add+ </Button>+ </div>+ <div className="flex flex-wrap gap-1.5">+ {SUGGESTIONS.map((suggestion) => (<button- key={style.id}+ key={suggestion}type="button"- role="radio"- aria-checked={selected}- disabled={readOnly}- onClick={() => setWikiStyle(style.id)}- className={`text-left rounded-md border px-3 py-2 transition-colors disabled:opacity-60 disabled:cursor-not-allowed ${- selected- ? "border-[var(--color-border-accent)] bg-[var(--color-bg-inset)]"- : "border-[var(--color-border-default)] hover:bg-[var(--color-bg-inset)]"- }`}+ onClick={() => add(suggestion)}+ disabled={patterns.includes(suggestion)}+ className="rounded-full border border-[var(--color-border-default)] px-2.5 py-0.5 font-mono text-xs text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-inset)] hover:text-[var(--color-text-primary)] disabled:cursor-not-allowed disabled:opacity-40">- <span className="block text-sm font-medium text-[var(--color-text-primary)]">- {style.label}- </span>- <span className="block text-xs text-[var(--color-text-secondary)]">- {style.description}- </span>+ + {suggestion}</button>- );- })}- </div>- </div>+ ))}+ </div>+ </>+ )}+ </div>+ );+}- <div className="space-y-1.5">- <Button- onClick={handleSave}- disabled={readOnly || !hasChanges || saving}- size="sm"- className="gap-2"- >- <Save className="h-3.5 w-3.5" />- {saving ? "Saving…" : "Save changes"}- </Button>- {readOnly && (- <p className="text-xs text-[var(--color-text-tertiary)]">{disabledHint}</p>- )}- </div>+function StylePicker({+ value,+ readOnly,+ onChange,+}: {+ value: WikiStyle;+ readOnly: boolean;+ onChange: (next: WikiStyle) => void;+}) {+ return (+ <div role="radiogroup" aria-label="Documentation style" className="grid gap-2">+ {WIKI_STYLES.map((style) => {+ const selected = value === style.id;+ return (+ <button+ key={style.id}+ type="button"+ role="radio"+ aria-checked={selected}+ disabled={readOnly}+ onClick={() => onChange(style.id)}+ className={`rounded-md border px-3 py-2 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${+ selected+ ? "border-[var(--color-border-accent)] bg-[var(--color-bg-inset)]"+ : "border-[var(--color-border-default)] hover:bg-[var(--color-bg-inset)]"+ }`}+ >+ <span className="block text-sm font-medium text-[var(--color-text-primary)]">{style.label}</span>+ <span className="block text-xs text-[var(--color-text-secondary)]">{style.description}</span>+ </button>+ );+ })}</div>);}diff --git a/packages/ui/src/settings/settings-primitives.tsx b/packages/ui/src/settings/settings-primitives.tsxindex 7c5c80fb8..5ea765787 100644--- a/packages/ui/src/settings/settings-primitives.tsx+++ b/packages/ui/src/settings/settings-primitives.tsx@@ -12,7 +12,7 @@*/import * as React from "react";-import { Check, Copy } from "lucide-react";+import { Check, ChevronRight, Copy } from "lucide-react";import { Spinner } from "../ui/spinner";import { cn } from "../lib/cn";@@ -20,52 +20,158 @@ export const SETTINGS_MICRO_LABEL ="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";/**- * One setting. The label column is fixed so a run of rows aligns; below `sm`+ * One setting: what it is and one line of help on the left, the control on+ * the right. The label column is fixed so a run of rows aligns; below `sm`* it stacks, because a 240px label column on a 390px viewport leaves the- * control nothing.+ * control nothing. An `inline` row (a switch, a short button) keeps its+ * control beside the label at every width.*/export function SettingsRow({label,htmlFor,hint,children,+ saveState = "idle",+ saveError,+ inline = false,className,}: {- label: string;+ label: React.ReactNode;/** Associates the label with the control it names. */htmlFor?: string;/** What the setting does, or what it costs. One line where possible. */hint?: React.ReactNode;children: React.ReactNode;+ /** This row's own autosave state, shown as a small tick beside the label. */+ saveState?: SaveState;+ saveError?: string | null;+ /** Keep the control beside the label below `sm` too. */+ inline?: boolean;className?: string;}) {return (<divclassName={cn(- "flex flex-col gap-2 border-b border-[var(--color-border-default)] py-4 last:border-b-0",- "sm:flex-row sm:items-start sm:gap-6",+ "flex gap-2 border-b border-[var(--color-border-default)] py-4 last:border-b-0",+ inline+ ? "flex-row items-start justify-between gap-4 sm:gap-6"+ : "flex-col sm:flex-row sm:items-start sm:gap-6",className,)}>- <div className="min-w-0 sm:w-[240px] sm:shrink-0">- <label- className="text-sm font-medium text-[var(--color-text-primary)]"- {...(htmlFor ? { htmlFor } : {})}- >- {label}- </label>+ <div className={cn("min-w-0", inline ? "flex-1" : "sm:w-[240px] sm:shrink-0")}>+ <div className="flex flex-wrap items-center gap-x-2">+ {/* A label only when there is one control to name; a span otherwise. */}+ {htmlFor ? (+ <label htmlFor={htmlFor} className="text-sm font-medium text-[var(--color-text-primary)]">+ {label}+ </label>+ ) : (+ <span className="text-sm font-medium text-[var(--color-text-primary)]">{label}</span>+ )}+ <SaveIndicator state={saveState} error={saveError ?? null} />+ </div>{hint && (<p className="mt-1 text-xs leading-relaxed text-[var(--color-text-tertiary)] [text-wrap:pretty]">{hint}</p>)}</div>- <div className="min-w-0 flex-1">{children}</div>+ <div className={cn("min-w-0", inline ? "shrink-0" : "flex-1")}>{children}</div></div>);}-/** A group of rows. Exists only to close the trailing hairline cleanly. */+/**+ * Rarely needed options for one group, folded away. A native `<details>`:+ * keyboard and screen-reader behaviour come with it, and the content stays+ * in the page for find-in-page.+ */+export function SettingsAdvanced({+ label = "Advanced",+ hint,+ defaultOpen = false,+ children,+ className,+}: {+ label?: string;+ /** One line under the summary naming what is inside. */+ hint?: React.ReactNode;+ defaultOpen?: boolean;+ children: React.ReactNode;+ className?: string;+}) {+ return (+ <details+ className={cn("group/adv border-t border-[var(--color-border-default)] pt-3", className)}+ {...(defaultOpen ? { open: true } : {})}+ >+ <summary className="flex cursor-pointer list-none items-center gap-1.5 rounded-sm py-1 text-sm font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] [&::-webkit-details-marker]:hidden">+ <ChevronRight+ aria-hidden+ className="h-3.5 w-3.5 transition-transform group-open/adv:rotate-90 motion-reduce:transition-none"+ />+ {label}+ </summary>+ {hint && (+ <p className="ml-5 text-xs text-[var(--color-text-tertiary)] [text-wrap:pretty]">{hint}</p>+ )}+ <div className="mt-2">{children}</div>+ </details>+ );+}++/** How long "Saved" stays before the row returns to rest. */+export const SAVED_MS = 2000;++/**+ * One autosave lifecycle: `track(write)` shows saving, then a short-lived+ * "Saved", or the error. Only the newest write may set the state, so an older+ * response landing late cannot overwrite a newer one. Resolves `"failed"`+ * when the caller should roll its optimistic value back, `"stale"` when a+ * newer write owns the row, else `"saved"`.+ */+export function useSaveState() {+ const [state, setState] = React.useState<SaveState>("idle");+ const [error, setError] = React.useState<string | null>(null);+ const seq = React.useRef(0);+ const timer = React.useRef<ReturnType<typeof setTimeout> | null>(null);++ React.useEffect(+ () => () => {+ if (timer.current) clearTimeout(timer.current);+ },+ [],+ );++ const track = React.useCallback(+ async (+ write: () => Promise<unknown>,+ errorMessage?: (e: unknown) => string,+ ): Promise<"saved" | "failed" | "stale"> => {+ const mine = ++seq.current;+ if (timer.current) clearTimeout(timer.current);+ setState("saving");+ setError(null);+ try {+ await write();+ if (mine !== seq.current) return "stale";+ setState("saved");+ timer.current = setTimeout(() => setState("idle"), SAVED_MS);+ return "saved";+ } catch (e) {+ if (mine !== seq.current) return "stale";+ setError(errorMessage ? errorMessage(e) : null);+ setState("error");+ return "failed";+ }+ },+ [],+ );++ return { state, error, track };+}+export function SettingsRows({children,className,diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex 6b3952a3f..392671fdc 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -858,11 +858,8 @@"repoSettings": {"title": "Settings","description": "Indexing, model keys and health for {repo}. Server, webhook and editor configuration are shared across repositories.",- "generalTitle": "General","generalDescription": "Where this repository lives and which branch is indexed.",- "syncTitle": "Sync and indexing","syncDescription": "Pull recent commits into the existing index, or rebuild it from scratch.",- "providerTitle": "AI provider","providerDescription": "A model key lets this repository's documentation be written with AI. Keys are stored with the repository and used by generation from the UI or the CLI.","captureTitle": "Decision capture","captureDescription": "What mines architectural decisions from this repository, and whether any of it may send prose to your configured model. Capture only ever produces candidates: nothing here can accept a decision on your behalf.",@@ -871,13 +868,14 @@"healthTitle": "Index health","healthDescription": "Per-population drift: wiki pages against page vectors, and decision records against decision vectors. A gap means search is answering from a stale set.","deleteTitle": "Delete this repository",- "deleteDescription": "Removes the index and everything generated from it — pages, symbols, decisions and history. Your source files are untouched. This cannot be undone.",- "footer": "Server connection, webhooks, model defaults and MCP configuration are in <link>global settings</link>."+ "deleteDescription": "Removes the index and everything generated from it: pages, symbols, decisions and history. Your source files are untouched. This cannot be undone.",+ "dangerTitle": "Danger zone",+ "publishTitle": "Publish on repowise.dev",+ "publishDescription": "Put this repository on repowise.dev, indexed from its GitHub remote. Nothing on this machine is uploaded."},"globalSettings": {"title": "Settings",- "description": "How this dashboard reaches your server, which model it defaults to, and what the MCP server offers an agent. Changes save as you make them.",- "footer": "Sync schedule, exclude patterns and deletion are per repository, on <link>the repository page</link>."+ "description": "How this dashboard reaches your server, which model it defaults to, and what the MCP server offers an agent. Changes save as you make them."},"workspace": {"emptyAction": "Read the quickstart",@@ -1110,13 +1108,14 @@"mcpTools": {"title": "Tool surface","description": "Which tools the MCP server offers an agent. Saved to the repo's .repowise/config.yaml and applied the next time you start repowise mcp for it.",- "empty": "Index a repository and its tool surface shows up here.",- "repoLabel": "Repository",- "repoHint": "The surface is stored per repo.","workspaceOnly": "workspace only","summary": "{on} of {total} tools exposed. {mode}","summaryWorkspace": "Workspace mode, so workspace-only tools are available.",- "summarySingleRepo": "Single-repo mode, so workspace-only tools are unavailable here."+ "summarySingleRepo": "Single-repo mode, so workspace-only tools are unavailable here.",+ "perRepoLabel": "Tools per repository",+ "perRepoHint": "Which tools the MCP server offers is saved per repository, in its Agents settings.",+ "chooseTools": "Choose tools",+ "chooseToolsFor": "Choose tools for {repo}"},"provider": {"title": "Default model",@@ -1142,14 +1141,34 @@"title": "Sync & hooks"},"coverage": {- "title": "Coverage"+ "title": "Coverage",+ "description": "The test coverage report this repository reads, so health and tests use measured coverage."},"server": {"title": "Server"},"privacy": {"title": "Privacy"+ },+ "general": {+ "title": "General"+ },+ "display": {+ "title": "Display"}+ },+ "advanced": "Advanced",+ "advancedHints": {+ "agents": "Which MCP tools agents get in this repository.",+ "models": "Decision capture, refactoring code generation and the docs export.",+ "sync": "Index health: whether search reads the same pages and decisions the database holds."+ },+ "scope": {+ "allRepos": "Set for all repos in Settings",+ "defaultModelLabel": "Default model",+ "defaultModelHint": "Repositories without their own model use the server default.",+ "webhooksLabel": "Webhooks",+ "webhooksHint": "A push on GitHub or GitLab can start a sync. The addresses are the same for every repository."}},"repos": {@@ -1199,20 +1218,24 @@"refresh": "Refresh"},"ops": {- "syncStarted": "Sync started — {name}",+ "syncStarted": "Sync started for {name}","syncFailed": "Sync failed",- "resyncStarted": "Full resync started — {name}",+ "resyncStarted": "Full resync started for {name}","resyncFailed": "Resync failed",- "title": "Operations","export": "Export","starting": "Starting…","sync": "Sync","resync": "Full Resync","resyncConfirm": "This regenerates every page for <repo>{name}</repo> from scratch. All existing pages will be overwritten.",- "resyncConfirmAction": "Resync Everything"+ "resyncConfirmAction": "Resync Everything",+ "syncLabel": "Sync now",+ "syncHint": "Pull recent commits into the existing index.",+ "resyncLabel": "Full resync",+ "resyncHint": "Rebuild the index and regenerate every page from scratch. Asks first.",+ "exportLabel": "Export docs",+ "exportHint": "Download the generated docs as a zip of Markdown files."},"settings": {- "toastSaved": "Repository settings saved","saveFailed": "Failed to save settings","regenQueued": "Wiki regeneration queued","regenFailed": "Failed to queue regeneration",@@ -2360,15 +2383,15 @@"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:"+ "telemetryCheckLabel": "Check whether it's on",+ "telemetryOffLabel": "Turn it off",+ "telemetryOffHint": "Run it in a terminal on this machine."},"row": {"index": {@@ -2453,6 +2476,7 @@"status": "Couldn't check","detail": "Couldn't read this here. Run {command} in a terminal to check."}- }+ },+ "changeIn": "Change in {group}"}}diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex c915cfcbf..c787f77d6 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -858,11 +858,8 @@"repoSettings": {"title": "设置","description": "{repo} 的索引、模型密钥与健康度。服务器、webhook 与编辑器配置由所有代码仓库共享。",- "generalTitle": "通用","generalDescription": "这个代码仓库所在的位置,以及索引的是哪个分支。",- "syncTitle": "同步与索引","syncDescription": "把最近的提交拉进现有索引,或者从零重建索引。",- "providerTitle": "AI 提供商","providerDescription": "有了模型密钥,这个代码仓库的文档就可以用 AI 撰写。密钥随仓库一起保存,供界面或 CLI 触发的生成使用。","captureTitle": "决策采集","captureDescription": "从哪些来源为这个代码仓库挖掘架构决策,以及其中是否有任何环节会把正文发送给你配置的模型。采集只会产生候选:这里没有任何操作能替你接受一条决策。",@@ -871,13 +868,14 @@"healthTitle": "索引健康","healthDescription": "按群体对比漂移:wiki 页面与其页面向量、决策记录与其决策向量。出现缺口意味着搜索正在用过期的集合作答。","deleteTitle": "删除这个代码仓库",- "deleteDescription": "删除索引以及由它生成的一切——页面、符号、决策和历史。你的源文件不会被改动。此操作无法撤销。",- "footer": "服务器连接、webhook、模型默认值和 MCP 配置都在 <link>全局设置</link> 里。"+ "deleteDescription": "删除索引以及由它生成的一切:页面、符号、决策和历史。你的源文件不会被改动。此操作无法撤销。",+ "dangerTitle": "危险操作",+ "publishTitle": "发布到 repowise.dev",+ "publishDescription": "把此仓库放到 repowise.dev 上,从它的 GitHub 远程仓库建立索引。不会上传本机上的任何内容。"},"globalSettings": {"title": "设置",- "description": "这个仪表盘如何连接你的服务器、默认使用哪个模型,以及 MCP 服务器向智能体提供什么。改动会随改随存。",- "footer": "同步计划、排除规则与删除按代码仓库分别设置,见<link>代码仓库页面</link>。"+ "description": "这个仪表盘如何连接你的服务器、默认使用哪个模型,以及 MCP 服务器向智能体提供什么。改动会随改随存。"},"workspace": {"emptyAction": "阅读快速入门",@@ -1110,13 +1108,14 @@"mcpTools": {"title": "工具集","description": "MCP 服务器向智能体提供哪些工具。会保存到代码仓库的 .repowise/config.yaml,并在你下次为它启动 repowise mcp 时生效。",- "empty": "索引一个代码仓库后,它的工具集就会显示在这里。",- "repoLabel": "代码仓库",- "repoHint": "工具集按代码仓库分别保存。","workspaceOnly": "仅工作区","summary": "已开放 {on}/{total} 个工具。{mode}","summaryWorkspace": "当前为工作区模式,因此仅限工作区的工具可用。",- "summarySingleRepo": "当前为单仓库模式,因此仅限工作区的工具在此不可用。"+ "summarySingleRepo": "当前为单仓库模式,因此仅限工作区的工具在此不可用。",+ "perRepoLabel": "每个仓库的工具",+ "perRepoHint": "MCP 服务器提供哪些工具按仓库保存,在该仓库的智能体设置中选择。",+ "chooseTools": "选择工具",+ "chooseToolsFor": "为 {repo} 选择工具"},"provider": {"title": "默认模型",@@ -1142,14 +1141,34 @@"title": "同步与钩子"},"coverage": {- "title": "覆盖率"+ "title": "覆盖率",+ "description": "此仓库读取的测试覆盖率报告,让健康度和测试使用实测覆盖率。"},"server": {"title": "服务器"},"privacy": {"title": "隐私"+ },+ "general": {+ "title": "常规"+ },+ "display": {+ "title": "显示"}+ },+ "advanced": "高级",+ "advancedHints": {+ "agents": "智能体在此仓库中可用的 MCP 工具。",+ "models": "决策捕获、重构代码生成和文档导出。",+ "sync": "索引健康:搜索读取的页面和决策是否与数据库一致。"+ },+ "scope": {+ "allRepos": "在设置中为所有仓库设置",+ "defaultModelLabel": "默认模型",+ "defaultModelHint": "没有单独设置模型的仓库使用服务器默认模型。",+ "webhooksLabel": "Webhook",+ "webhooksHint": "GitHub 或 GitLab 上的推送可以触发同步。所有仓库使用相同的地址。"}},"repos": {@@ -1199,20 +1218,24 @@"refresh": "刷新"},"ops": {- "syncStarted": "同步已开始 —— {name}",+ "syncStarted": "已开始同步 {name}","syncFailed": "同步失败",- "resyncStarted": "全量重新同步已开始 —— {name}",+ "resyncStarted": "已开始全量重新同步 {name}","resyncFailed": "重新同步失败",- "title": "运维操作","export": "导出","starting": "正在启动…","sync": "同步","resync": "全量重新同步","resyncConfirm": "这会从头重新生成 <repo>{name}</repo> 的每一个页面。所有现有页面都会被覆盖。",- "resyncConfirmAction": "重新同步全部"+ "resyncConfirmAction": "重新同步全部",+ "syncLabel": "立即同步",+ "syncHint": "把最近的提交拉取到现有索引中。",+ "resyncLabel": "全量重新同步",+ "resyncHint": "从头重建索引并重新生成每个页面。执行前会先确认。",+ "exportLabel": "导出文档",+ "exportHint": "把生成的文档下载为 Markdown 文件的 zip 压缩包。"},"settings": {- "toastSaved": "代码仓库设置已保存","saveFailed": "保存设置失败","regenQueued": "Wiki 重新生成已排队","regenFailed": "重新生成排队失败",@@ -2360,15 +2383,15 @@"hide": "在此电脑上隐藏设置提醒"},"settings": {- "repoLead": "此仓库的索引、编程智能体和同步,每项都附有终端命令。","openSetup": "打开设置向导","openSetupFor": "打开 {repo} 的设置向导","globalLead": "设置向导按仓库区分:每个仓库的索引、编程智能体以及同步。","noRepos": "添加一个仓库后即可设置。","telemetryTitle": "匿名使用遥测","telemetryDescription": "repowise 会发送匿名使用统计:命令名称和大致的运行环境,从不包含代码、路径或名称。设置 DO_NOT_TRACK=1 也可以关闭。",- "telemetryCheck": "查看是否开启:",- "telemetryOff": "关闭:"+ "telemetryCheckLabel": "查看是否已开启",+ "telemetryOffLabel": "关闭遥测",+ "telemetryOffHint": "在本机终端中运行。"},"row": {"index": {@@ -2453,6 +2476,7 @@"status": "无法检查","detail": "此处无法读取。请在终端运行 {command} 进行检查。"}- }+ },+ "changeIn": "在{group}中更改"}}diff --git a/packages/web/src/app/repos/[id]/refactoring/page.tsx b/packages/web/src/app/repos/[id]/refactoring/page.tsxindex 5e35cb8b3..bda3b5897 100644--- a/packages/web/src/app/repos/[id]/refactoring/page.tsx+++ b/packages/web/src/app/repos/[id]/refactoring/page.tsx@@ -402,7 +402,7 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri}}onAiPrompt={(plan) => setPromptFor({ kind: "plan", id: plan.id, filePath: plan.file_path })}onGenerateCode={onGenerateCode}- settingsHref={`${prefix}/settings`}+ settingsHref={providerSetupHref(repoId)}modelSetting={modelSetting}fileHref={fileHref}/>diff --git a/packages/web/src/app/repos/[id]/settings/agents/page.tsx b/packages/web/src/app/repos/[id]/settings/agents/page.tsxnew file mode 100644index 000000000..556fc44e8--- /dev/null+++ b/packages/web/src/app/repos/[id]/settings/agents/page.tsx@@ -0,0 +1,35 @@+import { notFound } from "next/navigation";+import { getTranslations } from "next-intl/server";+import { SettingsAdvanced } from "@repowise-dev/ui/settings";+import { getRepo } from "@/lib/api/repos";+import { RepoAgentRows } from "@/components/setup/setup-settings";+import { McpToolsSection } from "@/components/settings/mcp-tools-section";+import { SettingsBlock, SettingsGroup } from "@/components/settings/settings-groups";++interface Props {+ params: Promise<{ id: string }>;+}++/** Which agents read this repository, and which MCP tools they get. */+export default async function RepoAgentsSettingsPage({ params }: Props) {+ const { id } = await params;+ const ts = await getTranslations("settings");+ const tg = await getTranslations("settings.groups");+ let repo;+ try {+ repo = await getRepo(id);+ } catch {+ notFound();+ }++ return (+ <SettingsGroup title={tg("agents.title")} description={tg("agents.description")}>+ <RepoAgentRows repoId={id} repoName={repo.name} />+ <SettingsAdvanced label={ts("advanced")} hint={ts("advancedHints.agents")}>+ <SettingsBlock title={ts("mcpTools.title")} description={ts("mcpTools.description")}>+ <McpToolsSection repoId={id} />+ </SettingsBlock>+ </SettingsAdvanced>+ </SettingsGroup>+ );+}diff --git a/packages/web/src/app/repos/[id]/settings/coverage/page.tsx b/packages/web/src/app/repos/[id]/settings/coverage/page.tsxnew file mode 100644index 000000000..513e272ed--- /dev/null+++ b/packages/web/src/app/repos/[id]/settings/coverage/page.tsx@@ -0,0 +1,31 @@+import { notFound } from "next/navigation";+import { getTranslations } from "next-intl/server";+import { SettingsRows } from "@repowise-dev/ui/settings";+import { getRepo } from "@/lib/api/repos";+import { RepoSetupRows } from "@/components/setup/setup-settings";+import { SettingsGroup } from "@/components/settings/settings-groups";++const COVERAGE_ROWS = ["coverage"];++interface Props {+ params: Promise<{ id: string }>;+}++/** The coverage report this repository reads. */+export default async function RepoCoverageSettingsPage({ params }: Props) {+ const { id } = await params;+ const tg = await getTranslations("settings.groups");+ let repo;+ try {+ repo = await getRepo(id);+ } catch {+ notFound();+ }+ return (+ <SettingsGroup title={tg("coverage.title")} description={tg("coverage.description")}>+ <SettingsRows>+ <RepoSetupRows repoId={id} repoName={repo.name} ids={COVERAGE_ROWS} />+ </SettingsRows>+ </SettingsGroup>+ );+}diff --git a/packages/web/src/app/repos/[id]/settings/general/page.tsx b/packages/web/src/app/repos/[id]/settings/general/page.tsxnew file mode 100644index 000000000..7bde505e1--- /dev/null+++ b/packages/web/src/app/repos/[id]/settings/general/page.tsx@@ -0,0 +1,51 @@+import { notFound } from "next/navigation";+import { getTranslations } from "next-intl/server";+import { SettingsRow, SettingsRows } from "@repowise-dev/ui/settings";+import { getRepo } from "@/lib/api/repos";+import { RepoSettingsFormWrapper as RepoSettingsForm } from "@/components/repos/repo-settings-form-wrapper";+import { DeleteRepoButton } from "@/components/repos/delete-repo-button";+import { PublishRow } from "@/components/hosted/publish";+import { SettingsGroup } from "@/components/settings/settings-groups";++interface Props {+ params: Promise<{ id: string }>;+}++/** Name, branch, what to skip, the docs voice, publishing, then deletion. */+export default async function RepoGeneralSettingsPage({ params }: Props) {+ const { id } = await params;+ const t = await getTranslations("views.repoSettings");+ const tg = await getTranslations("settings.groups");+ let repo;+ try {+ repo = await getRepo(id);+ } catch {+ notFound();+ }++ return (+ <div className="flex flex-col gap-10">+ <SettingsGroup title={tg("general.title")} description={t("generalDescription")}>+ <RepoSettingsForm repo={repo} />+ <SettingsRows className="border-t border-[var(--color-border-default)]">+ <PublishRow repoId={id} />+ </SettingsRows>+ </SettingsGroup>++ {/* Not a tinted card. A destructive action earns emphasis on the verb and+ the sentence, not on a coloured ground the eye reads before either. */}+ <section aria-labelledby="danger-zone" className="flex flex-col gap-2">+ <h2 id="danger-zone" className="text-base font-semibold text-[var(--color-error)]">+ {t("dangerTitle")}+ </h2>+ <SettingsRows className="border-t border-[var(--color-border-default)]">+ <SettingsRow label={t("deleteTitle")} hint={t("deleteDescription")}>+ <div className="flex sm:justify-end">+ <DeleteRepoButton repoId={id} repoName={repo.name} variant="button" redirectTo="/" />+ </div>+ </SettingsRow>+ </SettingsRows>+ </section>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/settings/layout.tsx b/packages/web/src/app/repos/[id]/settings/layout.tsxnew file mode 100644index 000000000..0140d1d9d--- /dev/null+++ b/packages/web/src/app/repos/[id]/settings/layout.tsx@@ -0,0 +1,48 @@+import type { Metadata } from "next";+import type { ReactNode } from "react";+import { notFound } from "next/navigation";+import { getTranslations } from "next-intl/server";+import { getRepo } from "@/lib/api/repos";+import { SettingsFrame } from "@/components/settings/settings-frame";+import { REPO_SETTINGS_GROUPS, repoSettingsBase } from "@/components/settings/settings-groups";++interface Props {+ params: Promise<{ id: string }>;+ children: ReactNode;+}++export async function generateMetadata({ params }: Omit<Props, "children">): Promise<Metadata> {+ const { id } = await params;+ try {+ const repo = await getRepo(id);+ return { title: `${repo.name} · Settings` };+ } catch {+ return { title: "Settings" };+ }+}++/**+ * Per-repository settings: one group per sub-page, under the same group+ * names as global settings. Options shared by every repository live in global+ * settings, and these pages link there instead of repeating them.+ */+export default async function RepoSettingsLayout({ params, children }: Props) {+ const { id } = await params;+ const t = await getTranslations("views.repoSettings");+ let repo;+ try {+ repo = await getRepo(id);+ } catch {+ notFound();+ }+ return (+ <SettingsFrame+ title={t("title")}+ description={t("description", { repo: repo.name })}+ base={repoSettingsBase(id)}+ groups={REPO_SETTINGS_GROUPS}+ >+ {children}+ </SettingsFrame>+ );+}diff --git a/packages/web/src/app/repos/[id]/settings/loading.tsx b/packages/web/src/app/repos/[id]/settings/loading.tsxnew file mode 100644index 000000000..55d2ea374--- /dev/null+++ b/packages/web/src/app/repos/[id]/settings/loading.tsx@@ -0,0 +1,15 @@+import { getTranslations } from "next-intl/server";+import { Skeleton, SkeletonRegion } from "@repowise-dev/ui/ui/skeleton";++/** One group's rows loading; the frame and rail stay put. */+export default async function SettingsLoading() {+ const t = await getTranslations("loading");+ return (+ <SkeletonRegion label={t("settings")} className="flex flex-col gap-3">+ <Skeleton className="h-5 w-40" />+ <Skeleton className="h-16 w-full" />+ <Skeleton className="h-16 w-full" />+ <Skeleton className="h-16 w-full" />+ </SkeletonRegion>+ );+}diff --git a/packages/web/src/app/repos/[id]/settings/models/page.tsx b/packages/web/src/app/repos/[id]/settings/models/page.tsxnew file mode 100644index 000000000..9c3ad2c24--- /dev/null+++ b/packages/web/src/app/repos/[id]/settings/models/page.tsx@@ -0,0 +1,54 @@+import Link from "next/link";+import { getTranslations } from "next-intl/server";+import { SettingsAdvanced, SettingsRow, SettingsRows } from "@repowise-dev/ui/settings";+import { DecisionCaptureSettingsWrapper } from "@/components/decisions/decision-capture-settings-wrapper";+import { RefactoringSettingsSection } from "@/components/repos/refactoring-settings-section";+import { ExportDocsRow } from "@/components/repos/operations-panel";+import { ProviderSettingsPanel } from "@/components/settings/provider-settings-panel";+import {+ SETTINGS_LINK,+ SettingsBlock,+ SettingsGroup,+ settingsHref,+} from "@/components/settings/settings-groups";++interface Props {+ params: Promise<{ id: string }>;+}++/**+ * This repository's model, with the server default one link away. Decision+ * capture, code generation and the docs export sit under Advanced.+ */+export default async function RepoModelsSettingsPage({ params }: Props) {+ const { id } = await params;+ const t = await getTranslations("views.repoSettings");+ const ts = await getTranslations("settings");+ const tg = await getTranslations("settings.groups");++ return (+ <SettingsGroup title={tg("models.title")} description={t("providerDescription")}>+ <ProviderSettingsPanel repoId={id} />+ <SettingsRows>+ <SettingsRow label={ts("scope.defaultModelLabel")} hint={ts("scope.defaultModelHint")}>+ <div className="flex sm:justify-end">+ <Link href={settingsHref("models")} className={SETTINGS_LINK}>+ {ts("scope.allRepos")}+ </Link>+ </div>+ </SettingsRow>+ </SettingsRows>+ <SettingsAdvanced label={ts("advanced")} hint={ts("advancedHints.models")}>+ <SettingsBlock title={t("captureTitle")} description={t("captureDescription")}>+ <DecisionCaptureSettingsWrapper repoId={id} />+ </SettingsBlock>+ <SettingsBlock title={t("refactoringTitle")} description={t("refactoringDescription")}>+ <RefactoringSettingsSection repoId={id} />+ </SettingsBlock>+ <SettingsRows className="border-t border-[var(--color-border-default)]">+ <ExportDocsRow repoId={id} />+ </SettingsRows>+ </SettingsAdvanced>+ </SettingsGroup>+ );+}diff --git a/packages/web/src/app/repos/[id]/settings/page.tsx b/packages/web/src/app/repos/[id]/settings/page.tsxindex 4e148f3da..0440eb822 100644--- a/packages/web/src/app/repos/[id]/settings/page.tsx+++ b/packages/web/src/app/repos/[id]/settings/page.tsx@@ -1,184 +1,15 @@-import type { Metadata } from "next";-import Link from "next/link";-import { notFound } from "next/navigation";-import { OverviewSection } from "@repowise-dev/ui/overview";-import { PageShell } from "@repowise-dev/ui/shared/page-shell";-import { DecisionCaptureSettingsWrapper } from "@/components/decisions/decision-capture-settings-wrapper";-import { RefactoringSettingsSection } from "@/components/repos/refactoring-settings-section";-import { ProviderSettingsPanel } from "@/components/settings/provider-settings-panel";-import { getRepo } from "@/lib/api/repos";-import { getCoordinatorHealth } from "@/lib/api/health";-import { RepoSettingsFormWrapper as RepoSettingsForm } from "@/components/repos/repo-settings-form-wrapper";-import { CoordinatorHealthPanel } from "@/components/repos/coordinator-health-panel";-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"];+import { SettingsRedirect } from "@/components/settings/settings-nav";+import { REPO_SETTINGS_GROUPS, repoSettingsBase } from "@/components/settings/settings-groups";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} — Settings` };- } catch {- return { title: "Settings" };- }-}-/**- * 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.- *- * `WebhookSection` used to render here in full *and* on the global page, while- * this page separately linked out to global settings for connection and MCP —- * pointing elsewhere for two things and copying a third. Webhooks are a server- * address, not a repo preference, so they live in one place and this page links- * to them with everything else.+ * `/repos/[id]/settings` opens Setup, or the group an old link named+ * (`#provider` opens Models).*/-export default async function RepoSettingsPage({ params }: Props) {+export default async function RepoSettingsIndexPage({ params }: Props) {const { id } = await params;- const t = await getTranslations("views.repoSettings");-- let repo;- try {- repo = await getRepo(id);- } catch {- notFound();- }-- const coordinatorHealth = await getCoordinatorHealth(id).catch(() => null);- const tg = await getTranslations("settings.groups");- const titles = settingsGroupTitles(tg);-- return (- <PageShell- title={t("title")}- description={t("description", { repo: repo.name })}- maxWidth="narrow"- >- <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 and- the sentence, not on a coloured ground the eye reads before either. */}- <section className="flex flex-col gap-3 border-t border-[var(--color-border-default)] pt-6 sm:pt-8">- <h2 className="text-base font-semibold tracking-tight text-[var(--color-error)]">- {t("deleteTitle")}- </h2>- <p className="max-w-[62ch] text-xs leading-relaxed text-[var(--color-text-tertiary)] [text-wrap:pretty]">- {t("deleteDescription")}- </p>- <div>- <DeleteRepoButton- repoId={id}- repoName={repo.name}- variant="button"- redirectTo="/"- />- </div>- </section>-- <p className="border-t border-[var(--color-border-default)] pt-6 text-xs text-[var(--color-text-tertiary)]">- {t.rich("footer", {- link: (chunks) => (- <Link- href="/settings"- className="text-[var(--color-accent-primary)] hover:underline"- >- {chunks}- </Link>- ),- })}- </p>- </PageShell>- );+ return <SettingsRedirect base={repoSettingsBase(id)} groups={REPO_SETTINGS_GROUPS} />;}diff --git a/packages/web/src/app/repos/[id]/settings/sync/page.tsx b/packages/web/src/app/repos/[id]/settings/sync/page.tsxnew file mode 100644index 000000000..042aece22--- /dev/null+++ b/packages/web/src/app/repos/[id]/settings/sync/page.tsx@@ -0,0 +1,57 @@+import Link from "next/link";+import { notFound } from "next/navigation";+import { getTranslations } from "next-intl/server";+import { SettingsAdvanced, SettingsRow, SettingsRows } from "@repowise-dev/ui/settings";+import { getRepo } from "@/lib/api/repos";+import { getCoordinatorHealth } from "@/lib/api/health";+import { OperationsPanel } from "@/components/repos/operations-panel";+import { CoordinatorHealthPanel } from "@/components/repos/coordinator-health-panel";+import { RepoSetupRows } from "@/components/setup/setup-settings";+import {+ SETTINGS_LINK,+ SettingsBlock,+ SettingsGroup,+ settingsHref,+} from "@/components/settings/settings-groups";++const SYNC_ROWS = ["sync", "rewrite"];++interface Props {+ params: Promise<{ id: string }>;+}++/** Sync now, the hooks that keep the index current, and the shared webhooks. */+export default async function RepoSyncSettingsPage({ params }: Props) {+ const { id } = await params;+ const t = await getTranslations("views.repoSettings");+ const ts = await getTranslations("settings");+ const tg = await getTranslations("settings.groups");+ let repo;+ try {+ repo = await getRepo(id);+ } catch {+ notFound();+ }+ const coordinatorHealth = await getCoordinatorHealth(id).catch(() => null);++ return (+ <SettingsGroup title={tg("sync.title")} description={t("syncDescription")}>+ <OperationsPanel repoId={id} repoName={repo.name} />+ <SettingsRows>+ <RepoSetupRows repoId={id} repoName={repo.name} ids={SYNC_ROWS} />+ <SettingsRow label={ts("scope.webhooksLabel")} hint={ts("scope.webhooksHint")}>+ <div className="flex sm:justify-end">+ <Link href={settingsHref("sync")} className={SETTINGS_LINK}>+ {ts("scope.allRepos")}+ </Link>+ </div>+ </SettingsRow>+ </SettingsRows>+ <SettingsAdvanced label={ts("advanced")} hint={ts("advancedHints.sync")}>+ <SettingsBlock title={t("healthTitle")} description={t("healthDescription")}>+ <CoordinatorHealthPanel repoId={id} initial={coordinatorHealth} />+ </SettingsBlock>+ </SettingsAdvanced>+ </SettingsGroup>+ );+}diff --git a/packages/web/src/app/settings/agents/page.tsx b/packages/web/src/app/settings/agents/page.tsxnew file mode 100644index 000000000..a3f689808--- /dev/null+++ b/packages/web/src/app/settings/agents/page.tsx@@ -0,0 +1,29 @@+import { getTranslations } from "next-intl/server";+import { SettingsRow, SettingsRows } from "@repowise-dev/ui/settings";+import { listRepos } from "@/lib/api/repos";+import { HostedNudgeSlot } from "@/components/hosted/hosted-nudge-slot";+import { McpSection } from "@/components/settings/mcp-section";+import { SettingsGroup } from "@/components/settings/settings-groups";+import { HostedAgentsRow, McpToolsRepoLinks } from "@/components/setup/setup-settings";++/**+ * The editor config every agent needs, then where each repository's tools+ * are chosen. Tools are stored per repository, so they are set there.+ */+export default async function AgentsSettingsPage() {+ const ts = await getTranslations("settings");+ const tg = await getTranslations("settings.groups");+ const repos = await listRepos().catch(() => []);+ return (+ <SettingsGroup title={tg("agents.title")} description={tg("agents.description")}>+ <HostedNudgeSlot candidates={["mcp"]} />+ <SettingsRows>+ <McpSection />+ <SettingsRow label={ts("mcpTools.perRepoLabel")} hint={ts("mcpTools.perRepoHint")}>+ <McpToolsRepoLinks repos={repos} />+ </SettingsRow>+ <HostedAgentsRow />+ </SettingsRows>+ </SettingsGroup>+ );+}diff --git a/packages/web/src/app/settings/display/page.tsx b/packages/web/src/app/settings/display/page.tsxnew file mode 100644index 000000000..9a505d103--- /dev/null+++ b/packages/web/src/app/settings/display/page.tsx@@ -0,0 +1,14 @@+import { getTranslations } from "next-intl/server";+import { DisplaySection } from "@/components/settings/display-section";+import { SettingsGroup } from "@/components/settings/settings-groups";++/** Preferences for this browser. */+export default async function DisplaySettingsPage() {+ const t = await getTranslations("settings");+ const tg = await getTranslations("settings.groups");+ return (+ <SettingsGroup title={tg("display.title")} description={t("display.description")}>+ <DisplaySection />+ </SettingsGroup>+ );+}diff --git a/packages/web/src/app/settings/layout.tsx b/packages/web/src/app/settings/layout.tsxnew file mode 100644index 000000000..1b5c3090a--- /dev/null+++ b/packages/web/src/app/settings/layout.tsx@@ -0,0 +1,22 @@+import type { Metadata } from "next";+import type { ReactNode } from "react";+import { getTranslations } from "next-intl/server";+import { SettingsFrame } from "@/components/settings/settings-frame";+import { GLOBAL_SETTINGS_BASE, GLOBAL_SETTINGS_GROUPS } from "@/components/settings/settings-groups";++export const metadata: Metadata = { title: "Settings" };++/** Global settings: one group per sub-page, everything autosaves. */+export default async function SettingsLayout({ children }: { children: ReactNode }) {+ const t = await getTranslations("views.globalSettings");+ return (+ <SettingsFrame+ title={t("title")}+ description={t("description")}+ base={GLOBAL_SETTINGS_BASE}+ groups={GLOBAL_SETTINGS_GROUPS}+ >+ {children}+ </SettingsFrame>+ );+}diff --git a/packages/web/src/app/settings/loading.tsx b/packages/web/src/app/settings/loading.tsxindex eb32234f7..55d2ea374 100644--- a/packages/web/src/app/settings/loading.tsx+++ b/packages/web/src/app/settings/loading.tsx@@ -1,14 +1,15 @@import { getTranslations } from "next-intl/server";-import { PageSkeleton } from "@repowise-dev/ui/shared/loading-skeletons";-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";+import { Skeleton, SkeletonRegion } from "@repowise-dev/ui/ui/skeleton";+/** One group's rows loading; the frame and rail stay put. */export default async function SettingsLoading() {const t = await getTranslations("loading");return (- <PageSkeleton maxWidth="narrow" actions={false} label={t("settings")}>- <Skeleton className="h-40 w-full" />- <Skeleton className="h-40 w-full" />- <Skeleton className="h-40 w-full" />- </PageSkeleton>+ <SkeletonRegion label={t("settings")} className="flex flex-col gap-3">+ <Skeleton className="h-5 w-40" />+ <Skeleton className="h-16 w-full" />+ <Skeleton className="h-16 w-full" />+ <Skeleton className="h-16 w-full" />+ </SkeletonRegion>);}diff --git a/packages/web/src/app/settings/models/page.tsx b/packages/web/src/app/settings/models/page.tsxnew file mode 100644index 000000000..c0bc53f18--- /dev/null+++ b/packages/web/src/app/settings/models/page.tsx@@ -0,0 +1,14 @@+import { getTranslations } from "next-intl/server";+import { ProviderSection } from "@/components/settings/provider-section";+import { SettingsGroup } from "@/components/settings/settings-groups";++/** The server-wide default model, for every repository without its own. */+export default async function ModelsSettingsPage() {+ const t = await getTranslations("settings");+ const tg = await getTranslations("settings.groups");+ return (+ <SettingsGroup title={tg("models.title")} description={t("provider.description")}>+ <ProviderSection />+ </SettingsGroup>+ );+}diff --git a/packages/web/src/app/settings/page.tsx b/packages/web/src/app/settings/page.tsxindex 91a17156b..3d2dfa819 100644--- a/packages/web/src/app/settings/page.tsx+++ b/packages/web/src/app/settings/page.tsx@@ -1,96 +1,7 @@-import type { Metadata } from "next";-import Link from "next/link";-import { PageShell } from "@repowise-dev/ui/shared/page-shell";-import { ConnectionSection } from "@/components/settings/connection-section";-import { ProviderSection } from "@/components/settings/provider-section";-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";+import { SettingsRedirect } from "@/components/settings/settings-nav";+import { GLOBAL_SETTINGS_BASE, GLOBAL_SETTINGS_GROUPS } from "@/components/settings/settings-groups";-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.- *- * Was seven `Card`s in a hand-rolled `p-4 sm:p-6 max-w-2xl` frame, while the- * per-repo settings page used `PageShell` — two settings surfaces, two layout- * 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- title={t("title")}- description={t("description")}- maxWidth="narrow"- >- <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", {- link: (chunks) => (- <Link- href="/"- className="text-[var(--color-accent-primary)] hover:underline"- >- {chunks}- </Link>- ),- })}- </p>- </PageShell>- );+/** `/settings` opens the first group, or the one an old `#group-<id>` link named. */+export default function SettingsIndexPage() {+ return <SettingsRedirect base={GLOBAL_SETTINGS_BASE} groups={GLOBAL_SETTINGS_GROUPS} />;}diff --git a/packages/web/src/app/settings/privacy/page.tsx b/packages/web/src/app/settings/privacy/page.tsxnew file mode 100644index 000000000..19bf01baa--- /dev/null+++ b/packages/web/src/app/settings/privacy/page.tsx@@ -0,0 +1,14 @@+import { getTranslations } from "next-intl/server";+import { SettingsGroup } from "@/components/settings/settings-groups";+import { TelemetryRows } from "@/components/setup/setup-settings";++/** Anonymous usage telemetry, checked and turned off from the terminal. Always last. */+export default async function PrivacySettingsPage() {+ const t = await getTranslations("setup.settings");+ const tg = await getTranslations("settings.groups");+ return (+ <SettingsGroup title={tg("privacy.title")} description={t("telemetryDescription")}>+ <TelemetryRows />+ </SettingsGroup>+ );+}diff --git a/packages/web/src/app/settings/server/page.tsx b/packages/web/src/app/settings/server/page.tsxnew file mode 100644index 000000000..cb9fb3266--- /dev/null+++ b/packages/web/src/app/settings/server/page.tsx@@ -0,0 +1,14 @@+import { getTranslations } from "next-intl/server";+import { ConnectionSection } from "@/components/settings/connection-section";+import { SettingsGroup } from "@/components/settings/settings-groups";++/** How this dashboard reaches the repowise server. */+export default async function ServerSettingsPage() {+ const t = await getTranslations("settings");+ const tg = await getTranslations("settings.groups");+ return (+ <SettingsGroup title={tg("server.title")} description={t("connection.description")}>+ <ConnectionSection />+ </SettingsGroup>+ );+}diff --git a/packages/web/src/app/settings/setup/page.tsx b/packages/web/src/app/settings/setup/page.tsxnew file mode 100644index 000000000..c3de9ec52--- /dev/null+++ b/packages/web/src/app/settings/setup/page.tsx@@ -0,0 +1,16 @@+import { getTranslations } from "next-intl/server";+import { listRepos } from "@/lib/api/repos";+import { SettingsGroup } from "@/components/settings/settings-groups";+import { SetupRepoLinks } from "@/components/setup/setup-settings";++/** Setup is per repository, so global settings links to each one's. */+export default async function SetupSettingsPage() {+ const t = await getTranslations("setup.settings");+ const tg = await getTranslations("settings.groups");+ const repos = await listRepos().catch(() => []);+ return (+ <SettingsGroup title={tg("setup.title")} description={t("globalLead")}>+ <SetupRepoLinks repos={repos} />+ </SettingsGroup>+ );+}diff --git a/packages/web/src/app/settings/sync/page.tsx b/packages/web/src/app/settings/sync/page.tsxnew file mode 100644index 000000000..2213f8da4--- /dev/null+++ b/packages/web/src/app/settings/sync/page.tsx@@ -0,0 +1,14 @@+import { getTranslations } from "next-intl/server";+import { WebhookSection } from "@/components/settings/webhook-section";+import { SettingsGroup } from "@/components/settings/settings-groups";++/** Webhook addresses, shared by every repository on this server. */+export default async function SyncSettingsPage() {+ const t = await getTranslations("settings");+ const tg = await getTranslations("settings.groups");+ return (+ <SettingsGroup title={tg("sync.title")} description={t("webhook.description")}>+ <WebhookSection />+ </SettingsGroup>+ );+}diff --git a/packages/web/src/components/chat/model-selector.tsx b/packages/web/src/components/chat/model-selector.tsxindex cc19fcec7..d55801f43 100644--- a/packages/web/src/components/chat/model-selector.tsx+++ b/packages/web/src/components/chat/model-selector.tsx@@ -1,6 +1,7 @@"use client";import { useState } from "react";+import { providerSetupHref } from "@/lib/utils/page-href";import { useTranslations } from "next-intl";import { ModelSelector as ModelSelectorShell } from "@repowise-dev/ui/chat/model-selector";import { useProviders } from "@/lib/hooks/use-providers";@@ -37,7 +38,7 @@ export function ModelSelector({onBrowse={setBrowsing}{...(models ? { models: models.models } : {})}modelsLoading={modelsLoading}- settingsHref={repoId ? `/repos/${repoId}/settings` : "/settings"}+ settingsHref={repoId ? providerSetupHref(repoId) : "/settings/models"}labels={{dialog: t("dialog"),provider: t("provider"),diff --git a/packages/web/src/components/chat/no-provider-reason.tsx b/packages/web/src/components/chat/no-provider-reason.tsxindex 36fe7a391..ad83f9c12 100644--- a/packages/web/src/components/chat/no-provider-reason.tsx+++ b/packages/web/src/components/chat/no-provider-reason.tsx@@ -27,7 +27,7 @@ export function NoProviderReason({{t.rich(message, {link: (chunks) => (<Link- href="/settings"+ href="/settings/models"className="text-[var(--color-accent-primary)] hover:underline">{chunks}diff --git a/packages/web/src/components/dashboard/active-job-banner-wrapper.test.tsx b/packages/web/src/components/dashboard/active-job-banner-wrapper.test.tsxindex 6447ac7bf..3c730418c 100644--- a/packages/web/src/components/dashboard/active-job-banner-wrapper.test.tsx+++ b/packages/web/src/components/dashboard/active-job-banner-wrapper.test.tsx@@ -41,7 +41,7 @@ describe("ActiveJobBannerWrapper", () => {render(<ActiveJobBannerWrapper repoId="r1" />);expect(screen.getByRole("alert").textContent).toContain("Sync failed");expect(screen.getByRole("link", { name: /Provider settings/ }).getAttribute("href")).toBe(- "/repos/r1/settings#provider",+ "/repos/r1/settings/models",);});diff --git a/packages/web/src/components/docs/bulk-generate-confirm.tsx b/packages/web/src/components/docs/bulk-generate-confirm.tsxindex 00d3f2462..3891150ed 100644--- a/packages/web/src/components/docs/bulk-generate-confirm.tsx+++ b/packages/web/src/components/docs/bulk-generate-confirm.tsx@@ -1,6 +1,7 @@"use client";import { GenerateConfirmDialog } from "@repowise-dev/ui/wiki/regenerate-button";+import { providerSetupHref } from "@/lib/utils/page-href";import { formatEstimateCost } from "@/lib/generate-format";import { type useBulkGenerate } from "@/lib/hooks/use-bulk-generate";import { useTranslations } from "next-intl";@@ -51,7 +52,7 @@ export function BulkGenerateConfirm({estimateLoading={flow.estimateLoading}estimateError={flow.estimateError}noProvider={noProvider}- settingsHref={`/repos/${repoId}/settings#provider`}+ settingsHref={providerSetupHref(repoId)}onConfirm={flow.confirm}launching={flow.launching}/>diff --git a/packages/web/src/components/docs/page-generate-button.tsx b/packages/web/src/components/docs/page-generate-button.tsxindex 03c25cece..67275fb51 100644--- a/packages/web/src/components/docs/page-generate-button.tsx+++ b/packages/web/src/components/docs/page-generate-button.tsx@@ -1,6 +1,7 @@"use client";import { useCallback, useRef, useState } from "react";+import { providerSetupHref } from "@/lib/utils/page-href";import { toast } from "sonner";import {RegenerateButton,@@ -41,7 +42,7 @@ export function PageGenerateButton({// page awaiting its first prose, never a structural file page.const t = useTranslations("docs");const mode = isStubPage(page) ? "write" : "regenerate";- const settingsHref = `/repos/${repoId}/settings#provider`;+ const settingsHref = providerSetupHref(repoId);const [confirmOpen, setConfirmOpen] = useState(false);const [cascade, setCascade] = useState<RegenerateCascade>("none");diff --git a/packages/web/src/components/hosted/publish.tsx b/packages/web/src/components/hosted/publish.tsxindex 2ff85fbe0..a2b207375 100644--- a/packages/web/src/components/hosted/publish.tsx+++ b/packages/web/src/components/hosted/publish.tsx@@ -2,6 +2,8 @@import { useEffect, useState } from "react";import { OverviewSection } from "@repowise-dev/ui/overview";+import { SettingsRow } from "@repowise-dev/ui/settings";+import { useTranslations } from "next-intl";import { Button } from "@repowise-dev/ui/ui/button";import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";@@ -116,6 +118,19 @@ export function PublishPanel({ repoId }: { repoId: string }) {);}+/** Publishing as one row of repo settings' General group. */+export function PublishRow({ repoId }: { repoId: string }) {+ const t = useTranslations("views.repoSettings");+ const { identity } = useHostedIdentity();+ // A server without the endpoint answers nothing; no row beats a broken one.+ if (!identity) return null;+ return (+ <SettingsRow label={t("publishTitle")} hint={t("publishDescription")}>+ <PublishPanel repoId={repoId} />+ </SettingsRow>+ );+}+/** The panel as a repo overview section. Unlike repo settings, the overview* is not where someone goes to publish, so it follows the tips switches. */export function PublishOverviewSection({ repoId }: { repoId: string }) {diff --git a/packages/web/src/components/jobs/generation-progress-wrapper.test.tsx b/packages/web/src/components/jobs/generation-progress-wrapper.test.tsxindex 53dc208d0..54cb7e80d 100644--- a/packages/web/src/components/jobs/generation-progress-wrapper.test.tsx+++ b/packages/web/src/components/jobs/generation-progress-wrapper.test.tsx@@ -63,7 +63,7 @@ describe("GenerationProgressWrapper", () => {expect.objectContaining({ description: "API key rejected by openai. Update it in Settings." }),);expect(screen.getByRole("link", { name: /Provider settings/ }).getAttribute("href")).toBe(- "/repos/r1/settings#provider",+ "/repos/r1/settings/models",);});diff --git a/packages/web/src/components/layout/mobile-nav.tsx b/packages/web/src/components/layout/mobile-nav.tsxindex cf805bc8b..912c59e7c 100644--- a/packages/web/src/components/layout/mobile-nav.tsx+++ b/packages/web/src/components/layout/mobile-nav.tsx@@ -25,7 +25,7 @@ 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";+import { GLOBAL_NAV, WORKSPACE_NAV, isNavItemActive, repoNavGroups } from "./nav-items";import { NAV_ROW_ACTIVE, NAV_ROW_IDLE, NavGroupList } from "./nav-group-list";import type { RepoResponse, WorkspaceResponse } from "@/lib/api/types";@@ -114,7 +114,7 @@ export function MobileNav({ repos = [], workspace }: MobileNavProps) {<nav className="space-y-1">{GLOBAL_NAV.map((item) => {const Icon = item.icon;- const isActive = pathname === item.href;+ const isActive = isNavItemActive(item, pathname);return (<Linkkey={item.href}diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 6f0ed214f..4424d1181 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -149,7 +149,7 @@ export function Sidebar({<SidebarNavItemkey={item.href}item={item}- isActive={pathname === item.href}+ isActive={isNavItemActive(item, pathname)}iconOnly={isIconOnly}/>))}diff --git a/packages/web/src/components/model-upgrade/model-upgrade.test.tsx b/packages/web/src/components/model-upgrade/model-upgrade.test.tsxindex beaba028a..23633d729 100644--- a/packages/web/src/components/model-upgrade/model-upgrade.test.tsx+++ b/packages/web/src/components/model-upgrade/model-upgrade.test.tsx@@ -111,7 +111,7 @@ describe("ways in to the model sheet", () => {it("the chat no-provider state opens it and keeps the settings link", async () => {renderFresh(<ChatHarness message="noProvider" />);- expect(screen.getByRole("link", { name: "settings" }).getAttribute("href")).toBe("/settings");+ expect(screen.getByRole("link", { name: "settings" }).getAttribute("href")).toBe("/settings/models");fireEvent.click(screen.getByRole("button", { name: "Add a model" }));diff --git a/packages/web/src/components/repos/add-repo-dialog.tsx b/packages/web/src/components/repos/add-repo-dialog.tsxindex 3e7ed6b1b..4c4d7ac46 100644--- a/packages/web/src/components/repos/add-repo-dialog.tsx+++ b/packages/web/src/components/repos/add-repo-dialog.tsx@@ -59,7 +59,7 @@ export function AddRepoDialog({const res = await getProviders();return res.active;},- settingsHref: "/settings",+ settingsHref: "/settings/models",onDone: (repoId, jobId) => {toast.success(jobId ? t("addDialog.toastStarted") : t("addDialog.toastAdded"),diff --git a/packages/web/src/components/repos/operations-panel.tsx b/packages/web/src/components/repos/operations-panel.tsxindex 5bbacd870..ba8f6087e 100644--- a/packages/web/src/components/repos/operations-panel.tsx+++ b/packages/web/src/components/repos/operations-panel.tsx@@ -3,9 +3,9 @@import { useState } from "react";import { toast } from "sonner";import { RefreshCw, Zap, AlertTriangle, Download } from "lucide-react";+import { SettingsRow, SettingsRows } from "@repowise-dev/ui/settings";import { syncRepo, fullResyncRepo } from "@/lib/api/repos";import { Button } from "@repowise-dev/ui/ui/button";-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";import {Dialog,DialogContent,@@ -61,64 +61,40 @@ export function OperationsPanel({ repoId, repoName }: Props) {}}+ const busy = loading !== null || watched !== null;+return (<>- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm">{t("ops.title")}</CardTitle>- </CardHeader>-- <CardContent id="operations-panel-content" className="space-y-4">- {/* Active job progress */}- {watched && (- <GenerationProgress- key={watched.id}- jobId={watched.id}- repoName={repoName}- onDone={settle}- // A full re-index retry goes back through its confirmation.- onRetry={watched.action === "resync" ? () => setConfirmResync(true) : handleSync}- onDismiss={dismiss}- />- )}+ <SettingsRows>+ <SettingsRow label={t("ops.syncLabel")} hint={t("ops.syncHint")}>+ <div className="flex sm:justify-end">+ <Button size="sm" onClick={handleSync} disabled={busy}>+ <Zap className="mr-1.5 h-3.5 w-3.5" />+ {loading === "sync" ? t("ops.starting") : t("ops.sync")}+ </Button>+ </div>+ </SettingsRow>+ <SettingsRow label={t("ops.resyncLabel")} hint={t("ops.resyncHint")}>+ <div className="flex sm:justify-end">+ <Button variant="outline" size="sm" onClick={() => setConfirmResync(true)} disabled={busy}>+ <RefreshCw className="mr-1.5 h-3.5 w-3.5" />+ {loading === "resync" ? t("ops.starting") : t("ops.resync")}+ </Button>+ </div>+ </SettingsRow>+ </SettingsRows>- {/* Action buttons */}- {!watched && (- <div className="flex gap-2">- <Button- variant="default"- size="sm"- onClick={handleSync}- disabled={loading !== null}- className="flex-1"- >- <Zap className="h-3.5 w-3.5 mr-1.5" />- {loading === "sync" ? t("ops.starting") : t("ops.sync")}- </Button>- <Button- variant="outline"- size="sm"- onClick={() => setConfirmResync(true)}- disabled={loading !== null}- className="flex-1"- >- <RefreshCw className="h-3.5 w-3.5 mr-1.5" />- {loading === "resync" ? t("ops.starting") : t("ops.resync")}- </Button>- <Button- variant="ghost"- size="sm"- asChild- >- <a href={`/api/repos/${repoId}/export`} download>- <Download className="h-3.5 w-3.5 mr-1.5" />- {t("ops.export")}- </a>- </Button>- </div>- )}- </CardContent>- </Card>+ {watched && (+ <GenerationProgress+ key={watched.id}+ jobId={watched.id}+ repoName={repoName}+ onDone={settle}+ // A full re-index retry goes back through its confirmation.+ onRetry={watched.action === "resync" ? () => setConfirmResync(true) : handleSync}+ onDismiss={dismiss}+ />+ )}{/* Confirm resync dialog */}<Dialog open={confirmResync} onOpenChange={setConfirmResync}>@@ -152,3 +128,20 @@ export function OperationsPanel({ repoId, repoName }: Props) {</>);}++/** Download this repository's index; rare, so it sits under Models' Advanced. */+export function ExportDocsRow({ repoId }: { repoId: string }) {+ const t = useTranslations("repos");+ return (+ <SettingsRow label={t("ops.exportLabel")} hint={t("ops.exportHint")}>+ <div className="flex sm:justify-end">+ <Button variant="outline" size="sm" asChild>+ <a href={`/api/repos/${encodeURIComponent(repoId)}/export`} download>+ <Download className="mr-1.5 h-3.5 w-3.5" />+ {t("ops.export")}+ </a>+ </Button>+ </div>+ </SettingsRow>+ );+}diff --git a/packages/web/src/components/repos/repo-settings-form-wrapper.tsx b/packages/web/src/components/repos/repo-settings-form-wrapper.tsxindex 3044e7cd8..6c8c5885f 100644--- a/packages/web/src/components/repos/repo-settings-form-wrapper.tsx+++ b/packages/web/src/components/repos/repo-settings-form-wrapper.tsx@@ -1,6 +1,6 @@"use client";-import { useState } from "react";+import { useRef, useState } from "react";import { toast } from "sonner";import { GeneralForm } from "@repowise-dev/ui/settings/general-form";import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";@@ -30,6 +30,9 @@ export function RepoSettingsFormWrapper({ repo }: Props) {// When the style changes on save, offer to regenerate the wiki in the new// voice (the persisted style only takes effect on the next generation).+ // Fields autosave one at a time, so compare with the last saved style, not+ // the one the page loaded with.+ const savedStyle = useRef<WikiStyle>(currentStyle);const [regenOpen, setRegenOpen] = useState(false);const [pendingStyle, setPendingStyle] = useState<WikiStyle | null>(null);const [regenLoading, setRegenLoading] = useState(false);@@ -46,8 +49,8 @@ export function RepoSettingsFormWrapper({ repo }: Props) {wiki_style: nextStyle,},});- toast.success(t("settings.toastSaved"));- if (nextStyle !== currentStyle) {+ if (nextStyle !== savedStyle.current) {+ savedStyle.current = nextStyle;setPendingStyle(nextStyle);setRegenOpen(true);}@@ -77,6 +80,7 @@ export function RepoSettingsFormWrapper({ repo }: Props) {<GeneralFormvalue={value}onSubmit={handleSubmit}+ autosavelocalPath={repo.local_path}remoteUrl={repo.url ?? undefined}/>diff --git a/packages/web/src/components/settings/connection-section.tsx b/packages/web/src/components/settings/connection-section.tsxindex 5e3b8ef7a..7dbba542a 100644--- a/packages/web/src/components/settings/connection-section.tsx+++ b/packages/web/src/components/settings/connection-section.tsx@@ -1,23 +1,18 @@"use client";-import { useState, useEffect, useRef } from "react";+import { useState, useEffect, useRef, type KeyboardEvent } from "react";import { Spinner } from "@repowise-dev/ui/ui/spinner";import { config } from "@/lib/config";import { getHealth } from "@/lib/api/health";-import { OverviewSection } from "@repowise-dev/ui/overview";import { Input } from "@repowise-dev/ui/ui/input";import { Button } from "@repowise-dev/ui/ui/button";-import {- SettingsRow,- SettingsRows,- SaveIndicator,- StatusLine,- type SaveState,-} from "@repowise-dev/ui/settings";+import { SettingsRow, SettingsRows, StatusLine, useSaveState } from "@repowise-dev/ui/settings";import type { HealthResponse } from "@/lib/api/types";import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";import { useTranslations } from "next-intl";+type Field = "url" | "key";+/*** Server connection, and the page's only connection test.*@@ -25,6 +20,8 @@ import { useTranslations } from "next-intl";* Test button hitting the same `/health`, reporting the result in a* different vocabulary through a hand-rolled `<button>` whose border token did* not exist. This one reports more (version and DB), so that one went.+ *+ * Both fields save to this browser on blur or Enter, with a tick on the row.*/export function ConnectionSection() {const t = useTranslations("settings");@@ -33,11 +30,11 @@ export function ConnectionSection() {const [testing, setTesting] = useState(false);const [health, setHealth] = useState<HealthResponse | null>(null);const [error, setError] = useState<string | null>(null);- const [saveState, setSaveState] = useState<SaveState>("idle");+ const [field, setField] = useState<Field | null>(null);+ const save = useSaveState();const initialUrlRef = useRef("");const initialKeyRef = useRef("");- const savedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);useEffect(() => {setApiUrl(config.getApiUrl());@@ -46,30 +43,20 @@ export function ConnectionSection() {initialKeyRef.current = config.getApiKey();}, []);- useEffect(- () => () => {- if (savedTimer.current) clearTimeout(savedTimer.current);- },- [],- );-- function save() {- const changed =- apiUrl !== initialUrlRef.current || apiKey !== initialKeyRef.current;- config.setApiUrl(apiUrl);- config.setApiKey(apiKey);- if (!changed) return;- initialUrlRef.current = apiUrl;- initialKeyRef.current = apiKey;- // Autosave, with the one save affordance the whole surface shares — no- // toast, and nothing at rest.- setSaveState("saved");- if (savedTimer.current) clearTimeout(savedTimer.current);- savedTimer.current = setTimeout(() => setSaveState("idle"), 2000);+ function saveField(which: Field) {+ const [value, ref, write] =+ which === "url"+ ? [apiUrl, initialUrlRef, config.setApiUrl]+ : [apiKey, initialKeyRef, config.setApiKey];+ if (value === ref.current) return;+ ref.current = value;+ setField(which);+ void save.track(async () => write(value));}async function testConnection() {- save();+ saveField("url");+ saveField("key");setTesting(true);setHealth(null);setError(null);@@ -82,77 +69,66 @@ export function ConnectionSection() {}}- return (- <OverviewSection- title={t("connection.title")}- description={t("connection.description")}- flush- action={<SaveIndicator state={saveState} />}- >- <SettingsRows>- <SettingsRow- label={t("connection.urlLabel")}- htmlFor="api-url"- hint={t("connection.urlHint")}- >- <Input- id="api-url"- placeholder="http://localhost:7337"- value={apiUrl}- onChange={(e) => setApiUrl(e.target.value)}- onBlur={save}- className="font-mono"- />- </SettingsRow>+ const tick = (which: Field) => (field === which ? { saveState: save.state } : {});+ const onEnter = (which: Field) => (e: KeyboardEvent) => {+ if (e.key === "Enter") saveField(which);+ };- <SettingsRow- label={t("connection.apiKeyLabel")}- htmlFor="api-key"- hint={t("connection.apiKeyHint")}- >- <Input- id="api-key"- type="password"- placeholder={t("connection.apiKeyPlaceholder")}- value={apiKey}- onChange={(e) => setApiKey(e.target.value)}- onBlur={save}- className="font-mono"- />- </SettingsRow>+ return (+ <SettingsRows>+ <SettingsRow label={t("connection.urlLabel")} htmlFor="api-url" hint={t("connection.urlHint")} {...tick("url")}>+ <Input+ id="api-url"+ placeholder="http://localhost:7337"+ value={apiUrl}+ onChange={(e) => setApiUrl(e.target.value)}+ onBlur={() => saveField("url")}+ onKeyDown={onEnter("url")}+ className="font-mono"+ />+ </SettingsRow>- <SettingsRow- label={t("connection.testLabel")}- hint={t("connection.testHint")}- >- <div className="flex flex-wrap items-center gap-3">- <Button- variant="outline"- size="sm"- onClick={testConnection}- disabled={testing}- >- {testing ? (- <>- <Spinner size="sm" />- {t("connection.testing")}- </>- ) : (- t("connection.test")- )}- </Button>+ <SettingsRow+ label={t("connection.apiKeyLabel")}+ htmlFor="api-key"+ hint={t("connection.apiKeyHint")}+ {...tick("key")}+ >+ <Input+ id="api-key"+ type="password"+ placeholder={t("connection.apiKeyPlaceholder")}+ value={apiKey}+ onChange={(e) => setApiKey(e.target.value)}+ onBlur={() => saveField("key")}+ onKeyDown={onEnter("key")}+ className="font-mono"+ />+ </SettingsRow>- {health && (- <StatusLine status="ok">- <span className="tabular-nums">- {t("connection.status", { version: health.version, db: health.db })}- </span>- </StatusLine>+ <SettingsRow label={t("connection.testLabel")} hint={t("connection.testHint")}>+ <div className="flex flex-wrap items-center gap-3">+ <Button variant="outline" size="sm" onClick={testConnection} disabled={testing}>+ {testing ? (+ <>+ <Spinner size="sm" />+ {t("connection.testing")}+ </>+ ) : (+ t("connection.test"))}- {error && <StatusLine status="error">{error}</StatusLine>}- </div>- </SettingsRow>- </SettingsRows>- </OverviewSection>+ </Button>++ {health && (+ <StatusLine status="ok">+ <span className="tabular-nums">+ {t("connection.status", { version: health.version, db: health.db })}+ </span>+ </StatusLine>+ )}+ {error && <StatusLine status="error">{error}</StatusLine>}+ </div>+ </SettingsRow>+ </SettingsRows>);}diff --git a/packages/web/src/components/settings/display-section.tsx b/packages/web/src/components/settings/display-section.tsxindex cb92b6a8a..e1cc49d0a 100644--- a/packages/web/src/components/settings/display-section.tsx+++ b/packages/web/src/components/settings/display-section.tsx@@ -1,8 +1,7 @@"use client";-import { useEffect, useRef, useState } from "react";+import { useEffect, useState } from "react";import { useTranslations } from "next-intl";-import { OverviewSection } from "@repowise-dev/ui/overview";import {Select,SelectContent,@@ -10,12 +9,7 @@ import {SelectTrigger,SelectValue,} from "@repowise-dev/ui/ui/select";-import {- SettingsRow,- SettingsRows,- SaveIndicator,- type SaveState,-} from "@repowise-dev/ui/settings";+import { SettingsRow, SettingsRows, useSaveState } from "@repowise-dev/ui/settings";import { Switch } from "@repowise-dev/ui/ui/switch";import { DEFAULT_WEEKEND_PRESET, WEEKEND_PRESETS } from "@repowise-dev/ui/stats";import {@@ -61,9 +55,8 @@ export function DisplaySection() {ask: true,selection: true,});- const [tipsShown, setTipsShown] = useState(true);- const [saveState, setSaveState] = useState<SaveState>("idle");- const savedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const [savedRow, setSavedRow] = useState<string | null>(null);+ const save = useSaveState();const t = useTranslations("settings");/** The three switches, with their copy taken from the active locale. */const chatSwitches: {@@ -100,7 +93,6 @@ export function DisplaySection() {// Read after mount so SSR and the first client render agree.useEffect(() => {setWeekend(config.getWeekend() || DEFAULT_WEEKEND_PRESET.id);- setTipsShown(!config.getHostedTipsHidden());}, []);// The same two listeners the affordances themselves use: `storage` covers@@ -122,30 +114,20 @@ export function DisplaySection() {};}, []);- useEffect(- () => () => {- if (savedTimer.current) clearTimeout(savedTimer.current);- },- [],- );-- function markSaved() {- setSaveState("saved");- if (savedTimer.current) clearTimeout(savedTimer.current);- savedTimer.current = setTimeout(() => setSaveState("idle"), 2000);+ /** These write to this browser and cannot fail; the tick says it took. */+ function markSaved(row: string) {+ setSavedRow(row);+ void save.track(() => Promise.resolve());}+ const tick = (row: string) => (savedRow === row ? { saveState: save.state } : {});+function handleChange(v: string) {setWeekend(v);config.setWeekend(v);- markSaved();+ markSaved("weekend");}- function handleTipsChange(shown: boolean) {- setTipsShown(shown);- config.setHostedTipsHidden(!shown);- markSaved();- }function handleChatChange(entry: { key: ChatSwitchKey; write: (shown: boolean) => void },@@ -156,22 +138,19 @@ export function DisplaySection() {// also drives this component's own sync, so there is no optimistic state// that could drift from storage.entry.write(shown);- markSaved();+ markSaved(entry.key);}return (- <OverviewSection- title={t("display.title")}- description={t("display.description")}- action={<SaveIndicator state={saveState} />}- ><SettingsRows><SettingsRowlabel={t("display.weekendLabel")}+ htmlFor="weekend-preset"hint={t("display.weekendHint")}+ {...tick("weekend")}><Select value={weekend} onValueChange={handleChange}>- <SelectTrigger className="w-full sm:w-64">+ <SelectTrigger id="weekend-preset" className="w-full sm:w-64"><SelectValue /></SelectTrigger><SelectContent>@@ -190,6 +169,8 @@ export function DisplaySection() {return (<SettingsRowkey={entry.key}+ inline+ {...tick(entry.key)}label={entry.label}hint={gated@@ -206,17 +187,6 @@ export function DisplaySection() {</SettingsRow>);})}- <SettingsRow- label="Show repowise.dev tips"- hint="An occasional one-line tip about what repowise.dev adds, at most one per page. Never shown once you have signed in with repowise login."- >- <Switch- checked={tipsShown}- onCheckedChange={handleTipsChange}- aria-label="Show repowise.dev tips"- />- </SettingsRow></SettingsRows>- </OverviewSection>);}diff --git a/packages/web/src/components/settings/mcp-section.tsx b/packages/web/src/components/settings/mcp-section.tsxindex 016cde181..d368c44c9 100644--- a/packages/web/src/components/settings/mcp-section.tsx+++ b/packages/web/src/components/settings/mcp-section.tsx@@ -1,7 +1,6 @@"use client";-import { OverviewSection } from "@repowise-dev/ui/overview";-import { CopyLine, SettingsRow, SettingsRows } from "@repowise-dev/ui/settings";+import { CopyLine, SettingsRow } from "@repowise-dev/ui/settings";import { useTranslations } from "next-intl";const MCP_CONFIG = JSON.stringify(@@ -21,18 +20,8 @@ export function McpSection() {const t = useTranslations("settings");return (- <OverviewSection- title={t("mcp.title")}- description={t("mcp.description")}- >- <SettingsRows>- <SettingsRow- label={t("mcp.serverLabel")}- hint={t("mcp.serverHint")}- >- <CopyLine value={MCP_CONFIG} />- </SettingsRow>- </SettingsRows>- </OverviewSection>+ <SettingsRow label={t("mcp.serverLabel")} hint={t("mcp.serverHint")}>+ <CopyLine value={MCP_CONFIG} copyLabel={t("mcp.serverLabel")} />+ </SettingsRow>);}diff --git a/packages/web/src/components/settings/mcp-tools-section.test.tsx b/packages/web/src/components/settings/mcp-tools-section.test.tsxnew file mode 100644index 000000000..9587e0428--- /dev/null+++ b/packages/web/src/components/settings/mcp-tools-section.test.tsx@@ -0,0 +1,43 @@+// @vitest-environment jsdom++import React from "react";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({ getMcpToolSurface: vi.fn(), updateMcpTools: vi.fn() }));+vi.mock("@/lib/api/mcp-tools", () => mocks);++import { McpToolsSection } from "./mcp-tools-section";++const surface = {+ is_workspace: false,+ tools: [+ { name: "get_answer", enabled: true, default: true, requires_workspace: false, description: "Answers." },+ { name: "get_dead_code", enabled: false, default: false, requires_workspace: false, description: "Dead code." },+ ],+};++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("McpToolsSection", () => {+ it("saves one repository's tools on change and rolls a failed write back", async () => {+ mocks.getMcpToolSurface.mockResolvedValue(surface);+ mocks.updateMcpTools.mockRejectedValue(new Error("disk full"));+ render(<McpToolsSection repoId="r1" />);++ const toggle = await screen.findByRole("switch", { name: "get_dead_code" });+ expect(mocks.getMcpToolSurface).toHaveBeenCalledWith("r1");+ fireEvent.click(toggle);++ await waitFor(() =>+ expect(mocks.updateMcpTools).toHaveBeenCalledWith({ repo_id: "r1", tools: ["+get_dead_code"] }),+ );+ await waitFor(() =>+ expect(screen.getByRole("switch", { name: "get_dead_code" }).getAttribute("aria-checked")).toBe("false"),+ );+ expect(screen.getByText("disk full")).toBeTruthy();+ });+});diff --git a/packages/web/src/components/settings/mcp-tools-section.tsx b/packages/web/src/components/settings/mcp-tools-section.tsxindex 108878670..974071385 100644--- a/packages/web/src/components/settings/mcp-tools-section.tsx+++ b/packages/web/src/components/settings/mcp-tools-section.tsx@@ -1,32 +1,13 @@"use client";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { OverviewSection } from "@repowise-dev/ui/overview";+import { useEffect, useMemo, useRef, useState } from "react";import { Switch } from "@repowise-dev/ui/ui/switch";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@repowise-dev/ui/ui/select";-import {- SaveIndicator,- SettingsRow,- SettingsRows,- type SaveState,-} from "@repowise-dev/ui/settings";-import { listRepos } from "@/lib/api/repos";+import { SettingsRow, SettingsRows, useSaveState } from "@repowise-dev/ui/settings";import { getMcpToolSurface, updateMcpTools } from "@/lib/api/mcp-tools";import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";import type { McpToolSurface } from "@/lib/api/types";import { useTranslations } from "next-intl";-interface RepoOption {- id: string;- name: string;-}-function enabledNames(surface: McpToolSurface): Set<string> {return new Set(surface.tools.filter((t) => t.enabled).map((t) => t.name));}@@ -43,192 +24,97 @@ function toDeltas(surface: McpToolSurface, enabled: Set<string>): string[] {}/**- * Which tools the MCP server exposes.+ * Which tools the MCP server exposes in one repository.*- * This was the page's only explicit Save button, on a surface where every other- * control wrote on change. Nothing said which half you were in, so a toggle- * that silently did nothing until you found the button read as broken. It- * autosaves now, like everything else, and reports through the one shared- * indicator.+ * Autosaves, like everything else in settings: each switch writes on change,+ * shows its tick on its own row, and goes back where the server has it when+ * the write fails. Only the newest write may land, so a slow older response+ * cannot undo a newer switch.*/-export function McpToolsSection() {+export function McpToolsSection({ repoId }: { repoId: string }) {const t = useTranslations("settings");- const [repos, setRepos] = useState<RepoOption[]>([]);- const [repoId, setRepoId] = useState<string | null>(null);const [surface, setSurface] = useState<McpToolSurface | null>(null);const [enabled, setEnabled] = useState<Set<string>>(new Set());const [loading, setLoading] = useState(true);- const [saveState, setSaveState] = useState<SaveState>("idle");- const [error, setError] = useState<string | null>(null);-- const savedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);- // Guards against an older in-flight save landing after a newer one.- const saveSeq = useRef(0);+ const [loadError, setLoadError] = useState<string | null>(null);+ const [savedTool, setSavedTool] = useState<string | null>(null);+ const save = useSaveState();+ // What the server last accepted, from the newest write that succeeded.+ const server = useRef<{ surface: McpToolSurface | null; seq: number }>({ surface: null, seq: 0 });+ const writeSeq = useRef(0);useEffect(() => {- listRepos()- .then((rows) => {- const opts = rows- .filter((r) => !r.id.startsWith("ws:"))- .map((r) => ({ id: r.id, name: r.name }));- setRepos(opts);- setRepoId((cur) => cur ?? opts[0]?.id ?? null);- if (opts.length === 0) setLoading(false);- })- .catch((e) => {- setError(toFriendlyMessage(e, "Could not list repositories"));- setLoading(false);- });- }, []);-- useEffect(- () => () => {- if (savedTimer.current) clearTimeout(savedTimer.current);- },- [],- );-- const loadSurface = useCallback((id: string) => {setLoading(true);- setError(null);- getMcpToolSurface(id)+ setLoadError(null);+ getMcpToolSurface(repoId).then((s) => {+ server.current = { surface: s, seq: 0 };setSurface(s);setEnabled(enabledNames(s));})- .catch((e) => setError(toFriendlyMessage(e, "Could not load tools")))+ .catch((e) => setLoadError(toFriendlyMessage(e, "Could not load tools"))).finally(() => setLoading(false));- }, []);-- useEffect(() => {- if (repoId) loadSurface(repoId);- }, [repoId, loadSurface]);+ }, [repoId]);async function toggle(name: string, on: boolean) {- if (!surface || !repoId) return;-+ if (!surface) return;const next = new Set(enabled);if (on) next.add(name);else next.delete(name);setEnabled(next);-- const seq = ++saveSeq.current;- setSaveState("saving");- setError(null);- try {- const deltas = toDeltas(surface, next);- const updated = await updateMcpTools({- repo_id: repoId,- tools: deltas.length ? deltas : null,- });- if (seq !== saveSeq.current) return;- setSurface(updated);- setEnabled(enabledNames(updated));- setSaveState("saved");- if (savedTimer.current) clearTimeout(savedTimer.current);- savedTimer.current = setTimeout(() => setSaveState("idle"), 2000);- } catch (e) {- if (seq !== saveSeq.current) return;- // Put the switch back where the server still has it.- setEnabled(enabledNames(surface));- setError(toFriendlyMessage(e, "Could not save"));- setSaveState("error");- }+ setSavedTool(name);++ const deltas = toDeltas(surface, next);+ const mine = ++writeSeq.current;+ const outcome = await save.track(+ async () => {+ const updated = await updateMcpTools({ repo_id: repoId, tools: deltas.length ? deltas : null });+ if (mine > server.current.seq) server.current = { surface: updated, seq: mine };+ },+ (e) => toFriendlyMessage(e, "Could not save"),+ );+ const accepted = server.current.surface;+ if (outcome === "saved" && accepted) setSurface(accepted);+ // A failure puts every switch back where the server still has it.+ if (outcome !== "stale" && accepted) setEnabled(enabledNames(accepted));}const summary = useMemo(() => {if (!surface) return null;- const available = surface.tools.filter(- (t) => !(t.requires_workspace && !surface.is_workspace),- );- const on = available.filter((t) => enabled.has(t.name)).length;- const mode = surface.is_workspace- ? t("mcpTools.summaryWorkspace")- : t("mcpTools.summarySingleRepo");+ const available = surface.tools.filter((tool) => !(tool.requires_workspace && !surface.is_workspace));+ const on = available.filter((tool) => enabled.has(tool.name)).length;+ const mode = surface.is_workspace ? t("mcpTools.summaryWorkspace") : t("mcpTools.summarySingleRepo");return t("mcpTools.summary", { on, total: available.length, mode });}, [surface, enabled, t]);- return (- <OverviewSection- title={t("mcpTools.title")}- // Rule 4: the figure is the point. "9 of 15 exposed" answers the question- // the list is there to answer, before you read fifteen rows.- description={- summary ?? t("mcpTools.description")- }- action={<SaveIndicator state={saveState} error={error} />}- >- {repos.length === 0 && !loading && (- <p className="text-sm text-[var(--color-text-tertiary)]">- {t("mcpTools.empty")}- </p>- )}-- {repos.length > 1 && (- <SettingsRows>- <SettingsRow- label={t("mcpTools.repoLabel")}- hint={t("mcpTools.repoHint")}- >- <Select value={repoId ?? undefined} onValueChange={setRepoId}>- <SelectTrigger className="w-full sm:w-64">- <SelectValue />- </SelectTrigger>- <SelectContent>- {repos.map((r) => (- <SelectItem key={r.id} value={r.id}>- {r.name}- </SelectItem>- ))}- </SelectContent>- </Select>- </SettingsRow>- </SettingsRows>- )}+ if (loadError) return <p className="text-xs text-[var(--color-error)]">{loadError}</p>;+ if (loading || !surface) return null;- {surface && !loading && (- <ul className="border-t border-[var(--color-border-default)]">- {surface.tools.map((tool) => {- const locked = tool.requires_workspace && !surface.is_workspace;- return (- <li- key={tool.name}- className="flex items-start gap-3 border-b border-[var(--color-border-default)] py-3"- >- <Switch- checked={enabled.has(tool.name)}- disabled={locked}- onCheckedChange={(v) => void toggle(tool.name, v)}- aria-label={tool.name}- className="mt-0.5"- />- <div className="min-w-0 flex-1">- <div className="flex flex-wrap items-baseline gap-x-2">- <code className="font-mono text-sm text-[var(--color-text-primary)]">- {tool.name}- </code>- {/* Rule 10: only mark what needs attention. Every non-default- tool carried an "opt-in" badge and every workspace tool a- "workspace" badge, which badged most rows and so said- nothing. The switch already reports opt-in state; only- the unavailable case needs a word. */}- {locked && (- <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">- {t("mcpTools.workspaceOnly")}- </span>- )}- </div>- {tool.description && (- <p className="mt-0.5 text-xs leading-relaxed text-[var(--color-text-tertiary)]">- {tool.description}- </p>- )}- </div>- </li>- );- })}- </ul>- )}- </OverviewSection>+ return (+ <div className="flex flex-col gap-2">+ {/* The figure is the point: "9 of 15 exposed" before fifteen rows. */}+ {summary && <p className="text-xs text-[var(--color-text-secondary)]">{summary}</p>}+ <SettingsRows>+ {surface.tools.map((tool) => {+ const locked = tool.requires_workspace && !surface.is_workspace;+ return (+ <SettingsRow+ key={tool.name}+ inline+ label={<code className="font-mono">{tool.name}</code>}+ hint={locked ? `${t("mcpTools.workspaceOnly")} · ${tool.description ?? ""}` : tool.description}+ {...(savedTool === tool.name ? { saveState: save.state, saveError: save.error } : {})}+ >+ <Switch+ checked={enabled.has(tool.name)}+ disabled={locked}+ onCheckedChange={(v) => void toggle(tool.name, v)}+ aria-label={tool.name}+ />+ </SettingsRow>+ );+ })}+ </SettingsRows>+ </div>);}diff --git a/packages/web/src/components/settings/provider-section.tsx b/packages/web/src/components/settings/provider-section.tsxindex c43777204..1788bbcda 100644--- a/packages/web/src/components/settings/provider-section.tsx+++ b/packages/web/src/components/settings/provider-section.tsx@@ -1,8 +1,7 @@"use client";import React from "react";-import { OverviewSection } from "@repowise-dev/ui/overview";-import { SettingsRow, SettingsRows, EnvVarLine } from "@repowise-dev/ui/settings";+import { SettingsAdvanced, SettingsRow, SettingsRows, EnvVarLine } from "@repowise-dev/ui/settings";import { useTranslations } from "next-intl";import { useProviders } from "@/lib/hooks/use-providers";import { ProviderSettingsPanel } from "./provider-settings-panel";@@ -11,7 +10,7 @@ import { ProviderSettingsPanel } from "./provider-settings-panel";* The server-wide default model: the same form as a repository's settings,* without a repository, so it writes the server default that every repo* without its own `.repowise/config.yaml` model uses. The embedder is read- * from the server's environment, so it is shown, not edited.+ * from the server's environment, so it is shown, not edited, under Advanced.*/export function ProviderSection() {const t = useTranslations("settings");@@ -22,10 +21,11 @@ export function ProviderSection() {);return (- <OverviewSection title={t("provider.title")} description={t("provider.description")}>+ <><ProviderSettingsPanel />{embedder && (- <SettingsRows className="mt-4">+ <SettingsAdvanced label={t("advanced")}>+ <SettingsRows><SettingsRow label={t("provider.embedderLabel")} hint={t("provider.embedderHint")}><div className="space-y-2"><p className="font-mono text-sm text-[var(--color-text-primary)]">{embedder}</p>@@ -43,7 +43,8 @@ export function ProviderSection() {</div></SettingsRow></SettingsRows>+ </SettingsAdvanced>)}- </OverviewSection>+ </>);}diff --git a/packages/web/src/components/settings/settings-frame.tsx b/packages/web/src/components/settings/settings-frame.tsxnew file mode 100644index 000000000..c99d52cf5--- /dev/null+++ b/packages/web/src/components/settings/settings-frame.tsx@@ -0,0 +1,38 @@+import type { ReactNode } from "react";+import { getTranslations } from "next-intl/server";+import { PageFrame, PAGE_SHELL_DESCRIPTION, PAGE_SHELL_TITLE } from "@repowise-dev/ui/shared/page-shell";+import { settingsGroupTitles, type SettingsGroupId } from "./settings-groups";+import { SettingsNav } from "./settings-nav";++/**+ * The frame every settings sub-page shares: the page title, the rail of+ * groups, and one group's rows beside it. Rows keep a form's measure even+ * though the frame is wider, so a control stays near its label.+ */+export async function SettingsFrame({+ title,+ description,+ base,+ groups,+ children,+}: {+ title: string;+ description: string;+ base: string;+ groups: readonly SettingsGroupId[];+ children: ReactNode;+}) {+ const tg = await getTranslations("settings.groups");+ return (+ <PageFrame maxWidth="default">+ <header className="min-w-0 space-y-1">+ <h1 className={PAGE_SHELL_TITLE}>{title}</h1>+ <p className={`${PAGE_SHELL_DESCRIPTION} [text-wrap:pretty]`}>{description}</p>+ </header>+ <div className="flex flex-col gap-6 lg:flex-row lg:gap-10">+ <SettingsNav base={base} groups={groups} titles={settingsGroupTitles(tg)} label={tg("navLabel")} />+ <div className="min-w-0 max-w-3xl flex-1">{children}</div>+ </div>+ </PageFrame>+ );+}diff --git a/packages/web/src/components/settings/settings-groups.tsx b/packages/web/src/components/settings/settings-groups.tsxindex e2324b6e2..f1d62fad0 100644--- a/packages/web/src/components/settings/settings-groups.tsx+++ b/packages/web/src/components/settings/settings-groups.tsx@@ -3,21 +3,74 @@ 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.+ * Each group is its own sub-page (`/settings/<group>`,+ * `/repos/<id>/settings/<group>`), and each surface shows the groups it has+ * something for.*/export const SETTINGS_GROUPS = ["setup",+ "general","agents","models","sync","coverage","server",+ "display","privacy",] as const;export type SettingsGroupId = (typeof SETTINGS_GROUPS)[number];+/** General and Coverage are per repository, so global settings has neither. */+export const GLOBAL_SETTINGS_GROUPS: readonly SettingsGroupId[] = [+ "setup",+ "agents",+ "models",+ "sync",+ "server",+ "display",+ "privacy",+];++/** Server, display and telemetry are per machine, so repo settings has none of them. */+export const REPO_SETTINGS_GROUPS: readonly SettingsGroupId[] = [+ "setup",+ "general",+ "agents",+ "models",+ "sync",+ "coverage",+];++export const GLOBAL_SETTINGS_BASE = "/settings";++export function repoSettingsBase(repoId: string): string {+ return `/repos/${encodeURIComponent(repoId)}/settings`;+}++/** A global settings sub-page. */+export function settingsHref(group: SettingsGroupId): string {+ return `${GLOBAL_SETTINGS_BASE}/${group}`;+}++/** One repository's settings sub-page. */+export function repoSettingsHref(repoId: string, group: SettingsGroupId): string {+ return `${repoSettingsBase(repoId)}/${group}`;+}++/** Anchors from when settings was one long page, and where each lives now. */+const LEGACY_ANCHORS: Record<string, SettingsGroupId> = { provider: "models" };++/**+ * The sub-page an old in-page link meant: `#group-<id>` or `#provider`. Null+ * when the hash names nothing this surface has.+ */+export function groupFromHash(hash: string, groups: readonly SettingsGroupId[]): SettingsGroupId | null {+ const anchor = hash.replace(/^#/, "");+ const id = LEGACY_ANCHORS[anchor] ?? anchor.replace(/^group-/, "");+ return (groups as readonly string[]).includes(id) ? (id as SettingsGroupId) : null;+}+/** 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<@@ -26,62 +79,22 @@ export function settingsGroupTitles(t: (key: string) => string): Record<Settings>;}-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. */+/** One sub-page: its heading, one line on what it holds, then its rows. */export function SettingsGroup({- id,title,description,children,className,}: {- id: SettingsGroupId;title: string;- description?: string;+ description?: ReactNode;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)]"- >+ <section aria-labelledby="settings-group-title" className={cn("flex flex-col gap-4", className)}>+ <header>+ <h2 id="settings-group-title" className="text-base font-semibold text-[var(--color-text-primary)]">{title}</h2>{description && (@@ -94,3 +107,31 @@ export function SettingsGroup({</section>);}++/** A titled block inside a group's Advanced, e.g. decision capture. */+export function SettingsBlock({+ title,+ description,+ children,+}: {+ title: string;+ description?: ReactNode;+ children: ReactNode;+}) {+ return (+ <div className="flex flex-col gap-3 border-t border-[var(--color-border-default)] py-4 first:border-t-0 first:pt-1">+ <div>+ <h3 className="text-sm font-medium text-[var(--color-text-primary)]">{title}</h3>+ {description && (+ <p className="mt-0.5 max-w-[62ch] text-xs leading-relaxed text-[var(--color-text-tertiary)] [text-wrap:pretty]">+ {description}+ </p>+ )}+ </div>+ {children}+ </div>+ );+}++export const SETTINGS_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)]";diff --git a/packages/web/src/components/settings/settings-nav.test.tsx b/packages/web/src/components/settings/settings-nav.test.tsxnew file mode 100644index 000000000..8a085ec4d--- /dev/null+++ b/packages/web/src/components/settings/settings-nav.test.tsx@@ -0,0 +1,86 @@+// @vitest-environment jsdom++import React from "react";+import { existsSync } from "node:fs";+import { join } from "node:path";+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++const nav = vi.hoisted(() => ({ pathname: "/settings/agents", replace: vi.fn() }));+vi.mock("next/navigation", () => ({+ usePathname: () => nav.pathname,+ useRouter: () => ({ replace: nav.replace }),+}));++import {+ GLOBAL_SETTINGS_GROUPS,+ REPO_SETTINGS_GROUPS,+ SETTINGS_GROUPS,+ groupFromHash,+ repoSettingsHref,+ settingsHref,+ type SettingsGroupId,+} from "./settings-groups";+import { SettingsNav, SettingsRedirect } from "./settings-nav";++const titles = Object.fromEntries(SETTINGS_GROUPS.map((g) => [g, `T-${g}`])) as Record<+ SettingsGroupId,+ string+>;++afterEach(() => {+ cleanup();+ nav.replace.mockClear();+ window.location.hash = "";+});++describe("settings routes", () => {+ it("keeps Privacy last, and gives every group a page on disk", () => {+ expect(GLOBAL_SETTINGS_GROUPS.at(-1)).toBe("privacy");+ const app = join(__dirname, "..", "..", "app");+ for (const g of GLOBAL_SETTINGS_GROUPS) {+ expect(existsSync(join(app, "settings", g, "page.tsx")), g).toBe(true);+ }+ for (const g of REPO_SETTINGS_GROUPS) {+ expect(existsSync(join(app, "repos", "[id]", "settings", g, "page.tsx")), g).toBe(true);+ }+ });++ it("builds sub-page hrefs", () => {+ expect(settingsHref("models")).toBe("/settings/models");+ expect(repoSettingsHref("r1", "sync")).toBe("/repos/r1/settings/sync");+ });++ it("maps old in-page anchors to the sub-page they meant", () => {+ expect(groupFromHash("#provider", REPO_SETTINGS_GROUPS)).toBe("models");+ expect(groupFromHash("#group-sync", REPO_SETTINGS_GROUPS)).toBe("sync");+ expect(groupFromHash("#group-privacy", REPO_SETTINGS_GROUPS)).toBeNull();+ expect(groupFromHash("", GLOBAL_SETTINGS_GROUPS)).toBeNull();+ });+});++describe("SettingsNav", () => {+ it("links every group and marks the current one", () => {+ nav.pathname = "/settings/agents";+ render(<SettingsNav base="/settings" groups={GLOBAL_SETTINGS_GROUPS} titles={titles} label="Sections" />);+ const links = screen.getAllByRole("link");+ expect(links.map((a) => a.getAttribute("href"))).toEqual(+ GLOBAL_SETTINGS_GROUPS.map((g) => `/settings/${g}`),+ );+ expect(screen.getByRole("link", { name: "T-agents" }).getAttribute("aria-current")).toBe("page");+ expect(screen.getByRole("link", { name: "T-models" }).getAttribute("aria-current")).toBeNull();+ });+});++describe("SettingsRedirect", () => {+ it("opens the first group by default", () => {+ render(<SettingsRedirect base="/repos/r1/settings" groups={REPO_SETTINGS_GROUPS} />);+ expect(nav.replace).toHaveBeenCalledWith("/repos/r1/settings/setup");+ });++ it("follows an old #provider link to Models", () => {+ window.location.hash = "#provider";+ render(<SettingsRedirect base="/repos/r1/settings" groups={REPO_SETTINGS_GROUPS} />);+ expect(nav.replace).toHaveBeenCalledWith("/repos/r1/settings/models");+ });+});diff --git a/packages/web/src/components/settings/settings-nav.tsx b/packages/web/src/components/settings/settings-nav.tsxnew file mode 100644index 000000000..0f60c5414--- /dev/null+++ b/packages/web/src/components/settings/settings-nav.tsx@@ -0,0 +1,71 @@+"use client";++import { useEffect } from "react";+import Link from "next/link";+import { usePathname, useRouter } from "next/navigation";+import { cn } from "@/lib/utils/cn";+import { groupFromHash, type SettingsGroupId } from "./settings-groups";++/**+ * The settings sub-pages: a left rail on wide screens, a wrapping row of+ * tabs below `lg` so nothing scrolls sideways at 390px.+ */+export function SettingsNav({+ base,+ groups,+ titles,+ label,+}: {+ base: string;+ groups: readonly SettingsGroupId[];+ titles: Record<SettingsGroupId, string>;+ label: string;+}) {+ const pathname = usePathname() ?? "";+ return (+ <nav aria-label={label} className="lg:sticky lg:top-6 lg:w-44 lg:shrink-0 lg:self-start">+ <ul className="flex flex-wrap gap-1 lg:flex-col lg:gap-0.5">+ {groups.map((g) => {+ const href = `${base}/${g}`;+ const active = pathname === href || pathname.startsWith(`${href}/`);+ return (+ <li key={g}>+ <Link+ href={href}+ aria-current={active ? "page" : undefined}+ className={cn(+ "flex rounded-md px-2.5 py-1.5 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]",+ active+ ? "bg-[var(--color-bg-wash)] font-medium text-[var(--color-text-primary)]"+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-wash)] hover:text-[var(--color-text-primary)]",+ )}+ >+ {titles[g]}+ </Link>+ </li>+ );+ })}+ </ul>+ </nav>+ );+}++/**+ * The bare settings route: opens the sub-page an old `#group-<id>` or+ * `#provider` link meant, else the first group. Client side, because the+ * hash never reaches the server.+ */+export function SettingsRedirect({+ base,+ groups,+}: {+ base: string;+ groups: readonly SettingsGroupId[];+}) {+ const router = useRouter();+ useEffect(() => {+ const group = groupFromHash(window.location.hash, groups) ?? groups[0];+ router.replace(`${base}/${group}`);+ }, [base, groups, router]);+ return null;+}diff --git a/packages/web/src/components/settings/webhook-section.tsx b/packages/web/src/components/settings/webhook-section.tsxindex cfc24af8c..664dfc72c 100644--- a/packages/web/src/components/settings/webhook-section.tsx+++ b/packages/web/src/components/settings/webhook-section.tsx@@ -1,7 +1,6 @@"use client";import { useEffect, useState } from "react";-import { OverviewSection } from "@repowise-dev/ui/overview";import { CopyLine, SettingsRow, SettingsRows } from "@repowise-dev/ui/settings";import { useTranslations } from "next-intl";@@ -26,11 +25,7 @@ export function WebhookSection() {}, []);return (- <OverviewSection- title={t("webhook.title")}- description={t("webhook.description")}- >- <SettingsRows>+ <SettingsRows><SettingsRow label="GitHub" hint={t("webhook.githubHint")}><CopyLine value={`${serverUrl}/api/webhooks/github`} /></SettingsRow>@@ -55,7 +50,6 @@ export function WebhookSection() {</p></div></SettingsRow>- </SettingsRows>- </OverviewSection>+ </SettingsRows>);}diff --git a/packages/web/src/components/setup/setup-page.test.tsx b/packages/web/src/components/setup/setup-page.test.tsxindex bad2db831..c0e4fc5e2 100644--- a/packages/web/src/components/setup/setup-page.test.tsx+++ b/packages/web/src/components/setup/setup-page.test.tsx@@ -60,48 +60,17 @@ describe("SetupPage", () => {);});- 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",- });+ it("links each row to the settings page that holds its control, once", async () => {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);+ expect(await screen.findByText(/2 of 3 essentials done/)).toBeTruthy();+ // The switches and buttons live on the settings pages, not here too.+ expect(screen.queryByRole("switch")).toBeNull();+ expect(screen.queryByRole("button", { name: "Connect Cursor" })).toBeNull();+ const hrefs = screen+ .getAllByRole("link", { name: /^Change in / })+ .map((a) => a.getAttribute("href"));+ expect(hrefs).toContain("/repos/r1/settings/sync");+ expect(hrefs).toContain("/repos/r1/settings/agents");});it("puts the prompt first on a Needs attention row, with a preview", async () => {diff --git a/packages/web/src/components/setup/setup-page.tsx b/packages/web/src/components/setup/setup-page.tsxindex 06a18ea05..d71cfd29a 100644--- a/packages/web/src/components/setup/setup-page.tsx+++ b/packages/web/src/components/setup/setup-page.tsx@@ -3,11 +3,11 @@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 { SETTINGS_LINK, SettingsGroup, repoSettingsHref, type SettingsGroupId } from "@/components/settings/settings-groups";import type { SetupResponse } from "@/lib/api/setup";import { HostedSetupCard } from "./hosted-setup-card";import { SetupRowView, useSetupText } from "./setup-row";@@ -17,6 +17,29 @@ import { rememberSetupDone, useSetupData, useSetupView } from "./use-setup";const MICRO = "font-mono text-[10px] uppercase tracking-[0.1em] text-[var(--color-text-tertiary)]";+/**+ * Where each row's control lives. Setup shows status and fixes; the switch or+ * button itself is on the settings page for its group, so it exists once.+ * The model row keeps its own button: it opens the model sheet, a flow that+ * also writes the docs, not a setting.+ */+const ROW_GROUP: Record<string, SettingsGroupId> = {+ agent: "agents",+ sync: "sync",+ rewrite: "sync",+ coverage: "coverage",+};++function SettingsLink({ repoId, group }: { repoId: string; group: SettingsGroupId }) {+ const t = useTranslations("setup");+ const tg = useTranslations("settings.groups");+ return (+ <Link href={repoSettingsHref(repoId, group)} className={SETTINGS_LINK}>+ {t("changeIn", { group: tg(`${group}.title`) })}+ </Link>+ );+}+/** 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");@@ -29,7 +52,7 @@ export function SetupPage({ repoId, repoName }: { repoId: string; repoName: striif (!data || !view) {return (- <PageShell title={t("title")} description={t("loading")} maxWidth="narrow">+ <SettingsGroup title={t("title")} description={t("loading")}>{error && !isLoading ? (<Callout tone="error" label={t("loadFailedLabel")} action={<Button size="sm" variant="outline" onClick={() => void mutate()}>{t("retry")}</Button>}>{t("loadFailed")}@@ -37,7 +60,7 @@ export function SetupPage({ repoId, repoName }: { repoId: string; repoName: stri) : (<SetupSkeleton label={t("loading")} />)}- </PageShell>+ </SettingsGroup>);}return <SetupLoaded repoId={repoId} setup={data} view={view} />;@@ -78,7 +101,13 @@ function SetupLoaded({ repoId, setup, view }: { repoId: string; setup: SetupResp<SetupRowViewkey={row.id}row={row}- action={controls.actionFor(row)}+ action={+ ROW_GROUP[row.id] ? (+ <SettingsLink repoId={repoId} group={ROW_GROUP[row.id]!} />+ ) : (+ controls.actionFor(row)+ )+ }onOpenPrompt={() => controls.openRowPrompt(row)}>{row.files?.length ? <SkippedFiles files={row.files} /> : null}@@ -86,7 +115,7 @@ function SetupLoaded({ repoId, setup, view }: { repoId: string; setup: SetupResp));return (- <PageShell title={view.allDone ? t("doneTitle") : t("title")} description={description} maxWidth="narrow">+ <SettingsGroup title={view.allDone ? t("doneTitle") : t("title")} description={description}>{!setup.writes_allowed && (<Callout tone="info" label={t("writesOffLabel")}>{t("writesOff")}@@ -120,7 +149,7 @@ function SetupLoaded({ repoId, setup, view }: { repoId: string; setup: SetupResp<RowGroup label={t("optional")}>{rows(view.optional)}</RowGroup></div>{controls.dialogs}- </PageShell>+ </SettingsGroup>);}diff --git a/packages/web/src/components/setup/setup-settings.test.tsx b/packages/web/src/components/setup/setup-settings.test.tsxnew file mode 100644index 000000000..9d56406c7--- /dev/null+++ b/packages/web/src/components/setup/setup-settings.test.tsx@@ -0,0 +1,98 @@+// @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 { setupFixture } from "./setup-fixture";++const mocks = vi.hoisted(() => ({+ getRepoSetup: vi.fn(),+ setSetupHook: vi.fn(),+ toastError: vi.fn(),+ toastSuccess: vi.fn(),+}));++vi.mock("@/lib/api/setup", () => ({+ getRepoSetup: mocks.getRepoSetup,+ setSetupHook: mocks.setSetupHook,+ updateOnboardingState: vi.fn(),+ connectSetupAgent: vi.fn(),+ disconnectSetupAgent: vi.fn(),+ addSetupCoverage: vi.fn(),+ getOnboardingState: vi.fn(),+}));+vi.mock("sonner", () => ({ toast: { error: mocks.toastError, success: mocks.toastSuccess } }));+vi.mock("@/components/model-upgrade/model-upgrade", () => ({+ useModelUpgrade: () => ({ openSheet: vi.fn(), sheet: null }),+}));++import { RepoAgentRows, RepoSetupRows } from "./setup-settings";++function wrap(setup: SetupResponse, node: React.ReactNode) {+ mocks.getRepoSetup.mockResolvedValue(setup);+ return render(<SWRConfig value={{ provider: () => new Map() }}>{node}</SWRConfig>);+}++const syncRows = (setup: SetupResponse) =>+ wrap(setup, <RepoSetupRows repoId="r1" repoName="orbit-api" ids={["sync", "rewrite"]} />);++beforeEach(() => window.localStorage.clear());+afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("Sync settings rows", () => {+ 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",+ });+ syncRows(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" });+ syncRows(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 when the server does not allow them", async () => {+ syncRows(setupFixture({ writes_allowed: false }));+ const toggle = await screen.findByRole("switch", { name: "Shorter command output" });+ expect(toggle.hasAttribute("disabled")).toBe(true);+ });+});++describe("Agents settings rows", () => {+ it("lists each agent with its own connect button, and hosted last", async () => {+ wrap(setupFixture({ writes_allowed: false }), <RepoAgentRows repoId="r1" repoName="orbit-api" />);+ const connect = await screen.findByRole("button", { name: "Connect Cursor" });+ expect(connect.hasAttribute("disabled")).toBe(true);+ expect(screen.getByText("Claude.ai and ChatGPT")).toBeTruthy();+ });+});diff --git a/packages/web/src/components/setup/setup-settings.tsx b/packages/web/src/components/setup/setup-settings.tsxindex 89660ea3e..84cc48ad1 100644--- a/packages/web/src/components/setup/setup-settings.tsx+++ b/packages/web/src/components/setup/setup-settings.tsx@@ -1,35 +1,59 @@"use client";-import { useMemo } from "react";+import { useMemo, type ReactNode } 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 { RowPromptAction } from "@repowise-dev/ui/health/row-prompt-action";+import { CopyLine, SettingsRow, SettingsRows } from "@repowise-dev/ui/settings";import { hostedLink } from "@/lib/hosted";import type { RepoResponse } from "@/lib/api/types";-import { SetupCommand, SetupRowView, StatusDot } from "./setup-row";+import { SETTINGS_LINK, repoSettingsHref } from "@/components/settings/settings-groups";+import { StatusDot, useSetupText } 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,+/**+ * One Setup row as a settings row: what it is, its status and one line of+ * detail on the left; its control and the agent prompt on the right.+ */+function SetupSettingRow({+ row,+ action,+ onOpenPrompt,}: {- repoId: string;- label: string;- rows: SetupRow[];+ row: SetupRow;+ action: ReactNode;+ onOpenPrompt: () => void;}) {+ const text = useSetupText();+ const title = text(row.title);+ return (+ <SettingsRow+ className="group/row"+ label={title}+ hint={+ <>+ <span className="mr-1.5 inline-flex items-center gap-1.5 text-[var(--color-text-secondary)]">+ <StatusDot tone={row.tone} />+ {text(row.status)}+ </span>+ {text(row.detail)}+ </>+ }+ >+ <div className="flex flex-wrap items-center gap-2 sm:justify-end">+ {action}+ <RowPromptAction onClick={onOpenPrompt} subject={title} />+ </div>+ </SettingsRow>+ );+}++/** Settings rows built from the Setup payload, with the Setup controls. */+function SetupRowsBlock({ repoId, rows }: { repoId: string; rows: SetupRow[] }) {const t = useTranslations("setup");const controls = useSetupControls(repoId);const { data, error, isLoading, mutate } = useSetupData(repoId);@@ -45,16 +69,16 @@ function SetupRowsBlock({}if (!data) {return (- <SkeletonRegion label={label} className="flex flex-col gap-2">+ <SkeletonRegion label={t("loading")} 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+ <SetupSettingRowkey={row.id}row={row}action={controls.actionFor(row)}@@ -62,7 +86,7 @@ function SetupRowsBlock({/>))}{controls.dialogs}- </div>+ </>);}@@ -76,19 +100,17 @@ export function RepoSetupRows({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} />;+ return <SetupRowsBlock repoId={repoId} rows={rows} />;}-/** "Agents & editors" for one repo: the Setup page's agent rows, then hosted. */+/** "Agents & editors" for one repo: one row per agent, 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(() => {@@ -101,10 +123,10 @@ export function RepoAgentRows({ repoId, repoName }: { repoId: string; repoName:});}, [data, repoName, format]);return (- <div>- <SetupRowsBlock repoId={repoId} label={t("loading")} rows={rows} />+ <SettingsRows>+ <SetupRowsBlock repoId={repoId} rows={rows} /><HostedAgentsRow />- </div>+ </SettingsRows>);}@@ -112,67 +134,76 @@ export function RepoAgentRows({ repoId, repoName }: { repoId: string; repoName: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}- >+ <SettingsRow label={t("hostedTitle")} hint={t("hostedDetail")}>+ <div className="flex sm:justify-end">+ <a href={hostedLink("settings_agents", "mcp")} target="_blank" rel="noopener noreferrer" className={SETTINGS_LINK}>{t("hostedLink")}</a></div>- </div>+ </SettingsRow>);}-/** Repo settings' Setup group lead: where the full checklist lives. */-export function SetupLinkRow({ repoId }: { repoId: string }) {+/**+ * Indexed repositories, each with a link into its own settings: global+ * settings lists them where an option is set per repository.+ */+function RepoLinkRows({+ repos,+ hrefFor,+ linkLabel,+ linkAria,+}: {+ repos: RepoResponse[];+ hrefFor: (repoId: string) => string;+ linkLabel: string;+ linkAria: (repo: string) => string;+}) {const t = useTranslations("setup.settings");+ const indexed = repos.filter((r) => !r.id.startsWith("ws:") && r.workspace_status !== "needs_index");+ if (indexed.length === 0) {+ return <p className="text-xs text-[var(--color-text-tertiary)]">{t("noRepos")}</p>;+ }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>+ <ul className="flex flex-col">+ {indexed.map((repo) => (+ <li+ key={repo.id}+ className="flex items-center justify-between gap-3 border-b border-[var(--color-border-default)] py-2.5 last:border-b-0"+ >+ <span className="min-w-0 truncate text-sm text-[var(--color-text-primary)]">{repo.name}</span>+ <Link href={hrefFor(repo.id)} className={SETTINGS_LINK} aria-label={linkAria(repo.name)}>+ {linkLabel}+ </Link>+ </li>+ ))}+ </ul>);}-/** Global settings' Setup group: Setup is per repository, so link to each. */-export function GlobalSetupLinks({ repos }: { repos: RepoResponse[] }) {+/** Global Setup: each repository's Setup page. */+export function SetupRepoLinks({ 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>+ <RepoLinkRows+ repos={repos}+ hrefFor={(id) => repoSettingsHref(id, "setup")}+ linkLabel={t("openSetup")}+ linkAria={(repo) => t("openSetupFor", { repo })}+ />+ );+}++/** Global Agents: MCP tools are chosen in each repository's Agents settings. */+export function McpToolsRepoLinks({ repos }: { repos: RepoResponse[] }) {+ const t = useTranslations("settings.mcpTools");+ return (+ <RepoLinkRows+ repos={repos}+ hrefFor={(id) => repoSettingsHref(id, "agents")}+ linkLabel={t("chooseTools")}+ linkAria={(repo) => t("chooseToolsFor", { repo })}+ />);}@@ -180,18 +211,16 @@ export function GlobalSetupLinks({ repos }: { repos: RepoResponse[] }) {* 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() {+export function TelemetryRows() {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>+ <SettingsRows>+ <SettingsRow label={t("telemetryCheckLabel")}>+ <CopyLine value="repowise telemetry status" copyLabel={t("telemetryCheckLabel")} />+ </SettingsRow>+ <SettingsRow label={t("telemetryOffLabel")} hint={t("telemetryOffHint")}>+ <CopyLine value="repowise telemetry disable" copyLabel={t("telemetryOffLabel")} />+ </SettingsRow>+ </SettingsRows>);}diff --git a/packages/web/src/lib/utils/page-href.ts b/packages/web/src/lib/utils/page-href.tsindex a5b145157..437c14312 100644--- a/packages/web/src/lib/utils/page-href.ts+++ b/packages/web/src/lib/utils/page-href.ts@@ -13,7 +13,7 @@ const FILE_PAGE_PREFIX = filePageId("");*//** Where a repo's LLM provider and model are set up. */export function providerSetupHref(repoId: string): string {- return `/repos/${repoId}/settings#provider`;+ return `/repos/${repoId}/settings/models`;}export function pageHref(repoId: string, pageId: string): string {