Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(ui): rebuild Chat, Settings and Decisions on the section design language (#1134)

Raghav Chamadiya6a4ed6ead2ed
diff --git a/packages/api-client/src/decisions.ts b/packages/api-client/src/decisions.ts
index a214969ab..a3a49c381 100644
--- a/packages/api-client/src/decisions.ts
+++ b/packages/api-client/src/decisions.ts
@@ -3,6 +3,7 @@ import type {
DecisionCreate,
DecisionEvidence,
DecisionEvidenceResponse,
+ DecisionCounts,
DecisionGraph,
DecisionLineageEntry,
DecisionLineageResponse,
@@ -19,11 +20,33 @@ export async function listDecisions(
module?: string;
include_proposed?: boolean;
limit?: number;
+ offset?: number;
+ /**
+ * `priority` (server default) leads with confirmed rules, then the
+ * highest-confidence proposals. `recent` is newest-first.
+ */
+ sort?: "priority" | "recent";
},
): Promise<DecisionRecordResponse[]> {
return apiGet<DecisionRecordResponse[]>(`/api/repos/${repoId}/decisions`, opts);
}
+/**
+ * Counts by status. A grouped COUNT, so the total is measured rather than
+ * inferred from however many rows a page happened to fetch.
+ */
+export async function getDecisionCounts(
+ repoId: string,
+ opts?: {
+ source?: string;
+ tag?: string;
+ module?: string;
+ include_proposed?: boolean;
+ },
+): Promise<DecisionCounts> {
+ return apiGet<DecisionCounts>(`/api/repos/${repoId}/decisions/counts`, opts);
+}
+
export async function getDecision(
repoId: string,
decisionId: string,
diff --git a/packages/api-client/src/types/decisions.ts b/packages/api-client/src/types/decisions.ts
index 26db63460..e41eba61b 100644
--- a/packages/api-client/src/types/decisions.ts
+++ b/packages/api-client/src/types/decisions.ts
@@ -125,3 +125,12 @@ export interface DecisionStatusUpdate {
affected_modules?: string[];
affected_files?: string[];
}
+
+/** Counts by status, from a grouped COUNT on the server. */
+export interface DecisionCounts {
+ total: number;
+ active: number;
+ proposed: number;
+ superseded: number;
+ deprecated: number;
+}
diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.py
index e4d53399f..a379d112d 100644
--- a/packages/core/src/repowise/core/persistence/crud/decisions.py
+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py
@@ -11,7 +11,7 @@ from datetime import datetime
from typing import Any
import structlog
-from sqlalchemy import delete, or_, select
+from sqlalchemy import case, delete, func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.decision_provenance import compute_confidence, rank_for_source
@@ -169,11 +169,22 @@ async def list_decisions(
include_proposed: bool = True,
limit: int = 100,
offset: int = 0,
+ sort: str = "priority",
) -> list[DecisionRecord]:
"""Return decision records with optional filters.
Dismissed records are tombstones and only show up when explicitly asked
for via ``status="dismissed"``.
+
+ ``sort`` controls ordering:
+
+ * ``"priority"`` (default) — what a reader needs first. Confirmed rules
+ lead, then the proposals most likely to be real (highest confidence),
+ then the records that have been retired. Newest breaks every tie.
+ Ordering by ``created_at`` alone buried all eleven active decisions on
+ this repo under 468 unreviewed proposals, so page one of the table was
+ entirely machine guesses.
+ * ``"recent"`` — the previous behaviour, newest first.
"""
q = select(DecisionRecord).where(DecisionRecord.repository_id == repository_id)
if status is not None:
@@ -191,11 +202,70 @@ async def list_decisions(
if module is not None:
# Match exact module path in JSON array
q = q.where(DecisionRecord.affected_modules_json.contains(f'"{module}"'))
- q = q.order_by(DecisionRecord.created_at.desc()).limit(limit).offset(offset)
+ q = q.order_by(*_decision_order(sort)).limit(limit).offset(offset)
result = await session.execute(q)
return list(result.scalars().all())
+# Lower sorts first. Active is a rule the team stands behind; proposed is a
+# candidate; superseded and deprecated are history.
+_STATUS_RANK = {"active": 0, "proposed": 1, "superseded": 2, "deprecated": 3}
+
+
+def _decision_order(sort: str) -> tuple[Any, ...]:
+ """ORDER BY terms for :func:`list_decisions`."""
+ if sort == "recent":
+ return (DecisionRecord.created_at.desc(),)
+ rank = case(_STATUS_RANK, value=DecisionRecord.status, else_=4)
+ return (
+ rank,
+ DecisionRecord.confidence.desc(),
+ DecisionRecord.created_at.desc(),
+ )
+
+
+async def count_decisions_by_status(
+ session: AsyncSession,
+ repository_id: str,
+ *,
+ source: str | None = None,
+ tag: str | None = None,
+ module: str | None = None,
+ include_proposed: bool = True,
+) -> dict[str, int]:
+ """Return ``{status: count}`` for a repository, plus a ``"total"`` key.
+
+ A grouped ``COUNT`` rather than a page of rows. The list endpoint caps at
+ 500, so a caller that counted what it fetched reported "97 of 100" on a
+ repository holding several hundred records — a count nobody measured.
+ ``get_decision_health_summary`` still loads every row to tally them; this
+ is the aggregate version for callers that only need the numbers.
+
+ Statuses absent from the table are zero-filled, so the shape is stable.
+ """
+ q = select(DecisionRecord.status, func.count(DecisionRecord.id)).where(
+ DecisionRecord.repository_id == repository_id
+ )
+ q = q.where(DecisionRecord.status != "dismissed")
+ if not include_proposed:
+ q = q.where(DecisionRecord.status != "proposed")
+ if source is not None:
+ q = q.where(DecisionRecord.source == source)
+ if tag is not None:
+ q = q.where(DecisionRecord.tags_json.contains(f'"{tag}"'))
+ if module is not None:
+ q = q.where(DecisionRecord.affected_modules_json.contains(f'"{module}"'))
+ q = q.group_by(DecisionRecord.status)
+
+ counts = {status: 0 for status in _STATUS_RANK}
+ total = 0
+ for status, n in await session.execute(q):
+ counts[status] = n
+ total += n
+ counts["total"] = total
+ return counts
+
+
async def update_decision_metadata(
session: AsyncSession,
decision_id: str,
diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.py
index 5d7e830b6..5bbfcc4f7 100644
--- a/packages/server/src/repowise/server/routers/decisions.py
+++ b/packages/server/src/repowise/server/routers/decisions.py
@@ -11,6 +11,7 @@ from repowise.core.persistence.models import DecisionEvidence
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.schemas import (
DecisionCodeEdge,
+ DecisionCountsResponse,
DecisionCreate,
DecisionEvidenceResponse,
DecisionGraphEdge,
@@ -41,6 +42,11 @@ async def list_decisions(
include_proposed: bool = Query(True),
limit: int = Query(100, ge=1, le=500),
offset: int = Query(0, ge=0),
+ sort: str = Query(
+ "priority",
+ pattern="^(priority|recent)$",
+ description="priority: confirmed rules first, then likeliest proposals. recent: newest first.",
+ ),
session: AsyncSession = Depends(get_db_session), # noqa: B008
) -> list[DecisionRecordResponse]:
"""List architectural decision records for a repository.
@@ -48,6 +54,10 @@ async def list_decisions(
Each row carries an ``evidence_preview`` (the top-ranked evidence row's
verbatim quote) plus the total ``evidence_count``, so the table can show
provenance without N+1 calls to the per-decision /evidence endpoint.
+
+ Defaults to ``sort=priority``. Newest-first buried every confirmed
+ decision under the unreviewed proposals the indexer had just mined, so
+ page one was entirely machine guesses.
"""
decisions = await crud.list_decisions(
session,
@@ -59,6 +69,7 @@ async def list_decisions(
include_proposed=include_proposed,
limit=limit,
offset=offset,
+ sort=sort,
)
items = [DecisionRecordResponse.from_orm(d) for d in decisions]
@@ -113,6 +124,41 @@ async def decision_health(
}
+ "/api/repos/{repo_id}/decisions/counts",
+ response_model=DecisionCountsResponse,
+)
+async def decision_counts(
+ repo_id: str,
+ source: str | None = Query(None, description="Filter by source"),
+ tag: str | None = Query(None, description="Filter by tag"),
+ module: str | None = Query(None, description="Filter by module path"),
+ include_proposed: bool = Query(True),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> DecisionCountsResponse:
+ """Counts by status, as a grouped COUNT rather than a page of rows.
+
+ Declared above ``/{decision_id}`` on purpose: FastAPI matches in
+ declaration order, so a literal sub-path below it would be swallowed by
+ the parameterised route and "counts" would be looked up as a decision id.
+ """
+ counts = await crud.count_decisions_by_status(
+ session,
+ repo_id,
+ source=source,
+ tag=tag,
+ module=module,
+ include_proposed=include_proposed,
+ )
+ return DecisionCountsResponse(
+ total=counts["total"],
+ active=counts["active"],
+ proposed=counts["proposed"],
+ superseded=counts["superseded"],
+ deprecated=counts["deprecated"],
+ )
+
+
@router.get(
"/api/repos/{repo_id}/decisions/graph",
response_model=DecisionGraphResponse,
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 050b30b5a..37276f280 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -54,6 +54,7 @@ from .code_quality import (
SecurityFindingResponse,
)
from .decisions import (
+ DecisionCountsResponse,
DecisionCodeEdge,
DecisionCreate,
DecisionEvidenceResponse,
@@ -264,6 +265,7 @@ __all__ = [
"DeadCodePatchRequest",
"DeadCodeSummaryResponse",
"DecisionCodeEdge",
+ "DecisionCountsResponse",
"DecisionCreate",
"DecisionEvidenceResponse",
"DecisionGraphEdge",
diff --git a/packages/server/src/repowise/server/schemas/decisions.py b/packages/server/src/repowise/server/schemas/decisions.py
index e7c4c48f8..d61ca91ca 100644
--- a/packages/server/src/repowise/server/schemas/decisions.py
+++ b/packages/server/src/repowise/server/schemas/decisions.py
@@ -97,6 +97,21 @@ class DecisionRecordResponse(BaseModel):
)
+class DecisionCountsResponse(BaseModel):
+ """Counts by status for a repository, from a grouped COUNT.
+
+ Exists so a caller can state a total it actually measured. The list
+ endpoint caps at 500 rows, so counting the page reported "97 of 100" on a
+ repository holding several hundred records.
+ """
+
+ total: int
+ active: int
+ proposed: int
+ superseded: int
+ deprecated: int
+
+
class DecisionCreate(BaseModel):
title: str
context: str = ""
diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.ts
index 1d098b941..a29e741e1 100644
--- a/packages/types/src/decisions.ts
+++ b/packages/types/src/decisions.ts
@@ -176,3 +176,12 @@ export interface DecisionGraph {
decision_edges: DecisionGraphEdge[];
code_edges: DecisionCodeEdge[];
}
+
+/** Counts by status, from a grouped COUNT on the server. */
+export interface DecisionCounts {
+ total: number;
+ active: number;
+ proposed: number;
+ superseded: number;
+ deprecated: number;
+}
diff --git a/packages/ui/__tests__/chat/chat-message.test.tsx b/packages/ui/__tests__/chat/chat-message.test.tsx
new file mode 100644
index 000000000..502c02770
--- /dev/null
+++ b/packages/ui/__tests__/chat/chat-message.test.tsx
@@ -0,0 +1,56 @@
+import { describe, it, expect } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { ChatMessage } from "../../src/chat/chat-message.js";
+import type { ChatUIMessage } from "@repowise-dev/types/chat";
+
+const USER: ChatUIMessage = {
+ id: "u1",
+ role: "user",
+ text: "Where is auth handled?",
+ toolCalls: [],
+ isStreaming: false,
+};
+
+const ASSISTANT: ChatUIMessage = {
+ id: "a1",
+ role: "assistant",
+ text: "In `src/auth/session.py`.",
+ toolCalls: [],
+ isStreaming: false,
+};
+
+describe("ChatMessage", () => {
+ it("renders the user's turn without an accent ground", () => {
+ // The question used to be a solid accent bubble: the loudest object on the
+ // page, spent on the one element that does not respond to anything.
+ const { container } = render(<ChatMessage message={USER} repoId="r1" />);
+ expect(screen.getByText("Where is auth handled?")).toBeInTheDocument();
+ expect(
+ container.querySelector('[class*="bg-[var(--color-accent-primary)]"]'),
+ ).toBeNull();
+ });
+
+ it("renders the question above the reply's body size", () => {
+ render(<ChatMessage message={USER} repoId="r1" />);
+ expect(screen.getByText("Where is auth handled?").className).toContain(
+ "text-lg",
+ );
+ });
+
+ it("renders assistant text as markdown", () => {
+ const { container } = render(
+ <ChatMessage message={ASSISTANT} repoId="r1" />,
+ );
+ expect(container.querySelector("code")?.textContent).toBe(
+ "src/auth/session.py",
+ );
+ });
+
+ it("is memoised so a streaming tail does not re-render the transcript", () => {
+ // Rule 16. Without the memo, every SSE token re-parses every prior reply
+ // through react-markdown.
+ expect(
+ (ChatMessage as unknown as { $$typeof: symbol }).$$typeof,
+ ).toBe(Symbol.for("react.memo"));
+ });
+});
diff --git a/packages/ui/__tests__/chat/source-citations.test.tsx b/packages/ui/__tests__/chat/source-citations.test.tsx
index f9b990e26..c26088b28 100644
--- a/packages/ui/__tests__/chat/source-citations.test.tsx
+++ b/packages/ui/__tests__/chat/source-citations.test.tsx
@@ -1,5 +1,9 @@
import { describe, it, expect } from "vitest";
-import { extractSources } from "../../src/chat/source-citations.js";
+import { render, screen } from "@testing-library/react";
+import {
+ SourceCitations,
+ extractSources,
+} from "../../src/chat/source-citations.js";
import type { ChatUIToolCall } from "@repowise-dev/types/chat";
function searchCall(results: Array<Record<string, unknown>>): ChatUIToolCall {
@@ -63,3 +67,51 @@ describe("extractSources", () => {
expect(sources[0]?.confidence).toBeUndefined();
});
});
+
+describe("SourceCitations render", () => {
+ const LONG_TITLE =
+ "Authentication session handling and refresh-token rotation";
+
+ function renderList() {
+ return render(
+ <SourceCitations
+ toolCalls={[
+ searchCall([
+ {
+ page_id: "file_page:auth.py",
+ title: LONG_TITLE,
+ confidence_score: 0.82,
+ },
+ { page_id: "file_page:b.py", title: "b.py", confidence_score: 0.4 },
+ ]),
+ ]}
+ repoId="repo1"
+ />,
+ );
+ }
+
+ it("renders sources as links, not numbered chips", () => {
+ // A border and a ground on every entry turned a list of eight into a wall
+ // of boxes that outweighed the answer above it. The counter went with them:
+ // numbering only earns its weight when the prose cites [1], and it does not.
+ const { container } = renderList();
+ expect(container.querySelectorAll("a")).toHaveLength(2);
+ expect(screen.queryByText("1")).not.toBeInTheDocument();
+ expect(screen.queryByText("2")).not.toBeInTheDocument();
+ });
+
+ it("does not truncate a source title", () => {
+ // Rule 6: a cut title reports a width decision as missing content.
+ renderList();
+ const title = screen.getByText(LONG_TITLE);
+ expect(title.className).not.toContain("truncate");
+ expect(title.className).not.toContain("max-w-");
+ });
+
+ it("renders confidence as tabular mono", () => {
+ renderList();
+ const pct = screen.getByText("82%");
+ expect(pct.className).toContain("tabular-nums");
+ expect(pct.className).toContain("font-mono");
+ });
+});
diff --git a/packages/ui/__tests__/chat/tool-call-group.test.tsx b/packages/ui/__tests__/chat/tool-call-group.test.tsx
new file mode 100644
index 000000000..bf5002015
--- /dev/null
+++ b/packages/ui/__tests__/chat/tool-call-group.test.tsx
@@ -0,0 +1,65 @@
+import { describe, it, expect } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
+import { ToolCallGroup } from "../../src/chat/tool-call-group.js";
+import type { ChatUIToolCall } from "@repowise-dev/types/chat";
+
+function call(id: string, status: ChatUIToolCall["status"]): ChatUIToolCall {
+ return {
+ id,
+ name: "search_codebase",
+ arguments: { query: "auth" },
+ status,
+ ...(status === "done" ? { result: { results: [] } } : {}),
+ };
+}
+
+/** Every element carrying the group shell's ground. */
+function shells(container: HTMLElement) {
+ return container.querySelectorAll(
+ '[class*="rounded-lg"][class*="border"][class*="bg-[var(--color-bg-surface)]"]',
+ );
+}
+
+describe("ToolCallGroup", () => {
+ it("renders one container for a lone call, not a box inside a box", () => {
+ const { container } = render(<ToolCallGroup toolCalls={[call("a", "done")]} />);
+ expect(shells(container)).toHaveLength(1);
+ });
+
+ it("keeps a single container when the group is expanded", () => {
+ // Steps used to be bordered `bg-elevated` boxes nested inside the group's
+ // bordered `bg-elevated` box — the same plane twice, once per step.
+ const { container } = render(
+ <ToolCallGroup
+ toolCalls={[call("a", "done"), call("b", "done"), call("c", "done")]}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /Thinking/ }));
+ expect(shells(container)).toHaveLength(1);
+ });
+
+ it("marks a running step but not a finished one", () => {
+ // Rule 10: a badge every row carries says nothing. Success is the default,
+ // so only work in flight gets a marker.
+ const { container: done } = render(
+ <ToolCallGroup toolCalls={[call("a", "done")]} />,
+ );
+ expect(done.querySelector(".animate-spin")).toBeNull();
+ expect(done.querySelector('[class*="color-success"]')).toBeNull();
+
+ const { container: running } = render(
+ <ToolCallGroup toolCalls={[call("b", "running")]} />,
+ );
+ expect(running.querySelector(".animate-spin")).not.toBeNull();
+ });
+
+ it("auto-expands while a step is running and reports the step count", () => {
+ render(
+ <ToolCallGroup toolCalls={[call("a", "done"), call("b", "running")]} />,
+ );
+ expect(screen.getByText(/Working/)).toBeInTheDocument();
+ expect(screen.getByText(/2 steps/)).toBeInTheDocument();
+ // Expanded without a click: both step labels are on screen.
+ expect(screen.getAllByText("Searching codebase")).toHaveLength(2);
+ });
+});
diff --git a/packages/ui/__tests__/decisions/decision-detail.test.tsx b/packages/ui/__tests__/decisions/decision-detail.test.tsx
index f98219d74..adfbb4593 100644
--- a/packages/ui/__tests__/decisions/decision-detail.test.tsx
+++ b/packages/ui/__tests__/decisions/decision-detail.test.tsx
@@ -126,10 +126,27 @@ describe("DecisionDetail", () => {
adapter={makeAdapter()}
/>,
);
- expect(screen.getByText("Created: —")).toBeInTheDocument();
+ // The meta ribbon is a <dl>: the label is the term, the value the
+ // definition, so they are no longer one "Created: —" string.
+ const term = screen.getByText("Recorded");
+ expect(term.nextElementSibling).toHaveTextContent("—");
expect(screen.queryByText(/Invalid Date/i)).not.toBeInTheDocument();
});
+ it("reports staleness as a percentage, like the decisions table does", () => {
+ // It used to render "Staleness: 0.42" here and "42%" in the table — the
+ // same number in two units on two surfaces.
+ renderView(
+ <DecisionDetail
+ decision={makeDecision({ staleness_score: 0.42 })}
+ adapter={makeAdapter()}
+ />,
+ );
+ expect(screen.getByText("Staleness").nextElementSibling).toHaveTextContent(
+ "42%",
+ );
+ });
+
it("explains what Confirm/Dismiss do next to the buttons", () => {
renderView(<DecisionDetail decision={makeDecision()} adapter={makeAdapter()} />);
expect(
diff --git a/packages/ui/__tests__/decisions/decision-governance.test.tsx b/packages/ui/__tests__/decisions/decision-governance.test.tsx
new file mode 100644
index 000000000..7eac24878
--- /dev/null
+++ b/packages/ui/__tests__/decisions/decision-governance.test.tsx
@@ -0,0 +1,181 @@
+import { describe, it, expect } from "vitest";
+import { render, screen } from "@testing-library/react";
+import {
+ DecisionConflicts,
+ GovernedFiles,
+ summarizeGovernance,
+} from "../../src/decisions/decision-governance.js";
+import type { DecisionGraph } from "@repowise-dev/types/decisions";
+
+function graph(over: Partial<DecisionGraph> = {}): DecisionGraph {
+ return {
+ nodes: [
+ { id: "a", title: "Use SWR", status: "active", source: "cli", confidence: 0.9, staleness_score: 0, verification: "exact" },
+ { id: "b", title: "Use React Query", status: "proposed", source: "cli", confidence: 0.8, staleness_score: 0, verification: "exact" },
+ { id: "c", title: "Vendor the client", status: "proposed", source: "cli", confidence: 0.7, staleness_score: 0, verification: "fuzzy" },
+ ],
+ decision_edges: [],
+ code_edges: [],
+ ...over,
+ };
+}
+
+describe("summarizeGovernance", () => {
+ it("returns empty lists for a missing graph rather than throwing", () => {
+ expect(summarizeGovernance(undefined)).toEqual({
+ conflicts: [],
+ governedFiles: [],
+ governedFileTotal: 0,
+ });
+ });
+
+ it("keeps conflicts and drops every other edge kind", () => {
+ // On a real index 373 of 376 edges were `supersedes` and 3 were conflicts;
+ // `refines` and `relates_to` never occurred at all. A supersession is
+ // lineage, which DecisionLineage already renders linearly.
+ const { conflicts } = summarizeGovernance(
+ graph({
+ decision_edges: [
+ { src: "a", dst: "b", kind: "conflicts_with", confidence: 0.7, evidence: "sim=0.68" },
+ { src: "a", dst: "c", kind: "supersedes", confidence: 0.9, evidence: "" },
+ { src: "b", dst: "c", kind: "relates_to", confidence: 0.5, evidence: "" },
+ ],
+ }),
+ );
+ expect(conflicts).toHaveLength(1);
+ expect(conflicts[0]).toMatchObject({
+ aTitle: "Use SWR",
+ bTitle: "Use React Query",
+ evidence: "sim=0.68",
+ });
+ });
+
+ it("lists a conflicting pair once, whichever direction it arrives in", () => {
+ const { conflicts } = summarizeGovernance(
+ graph({
+ decision_edges: [
+ { src: "a", dst: "b", kind: "conflicts_with", confidence: 0.7, evidence: "" },
+ { src: "b", dst: "a", kind: "conflicts_with", confidence: 0.7, evidence: "" },
+ ],
+ }),
+ );
+ expect(conflicts).toHaveLength(1);
+ });
+
+ it("leaves a title undefined when an edge points outside the node payload", () => {
+ // 321 of 387 edge endpoints referenced decisions the graph never carried,
+ // and on a live index *every* conflict endpoint did. The first cut fell
+ // back to the id, which rendered a 32-character hash where a sentence
+ // belongs; the caller resolves or drops it instead.
+ const { conflicts } = summarizeGovernance(
+ graph({
+ decision_edges: [
+ { src: "a", dst: "ghost", kind: "conflicts_with", confidence: 0.7, evidence: "" },
+ ],
+ }),
+ );
+ expect(conflicts[0]?.aTitle).toBe("Use SWR");
+ expect(conflicts[0]?.bTitle).toBeUndefined();
+ });
+
+ it("accepts caller-supplied titles for ids the graph does not carry", () => {
+ const { conflicts } = summarizeGovernance(
+ graph({
+ decision_edges: [
+ { src: "a", dst: "ghost", kind: "conflicts_with", confidence: 0.7, evidence: "" },
+ ],
+ }),
+ { titles: new Map([["ghost", "Recorded elsewhere"]]) },
+ );
+ expect(conflicts[0]?.bTitle).toBe("Recorded elsewhere");
+ });
+
+ it("ranks files by how many distinct decisions govern them", () => {
+ const { governedFiles, governedFileTotal } = summarizeGovernance(
+ graph({
+ code_edges: [
+ { decision_id: "a", node_id: "src/api.ts", link_type: "file" },
+ { decision_id: "b", node_id: "src/api.ts", link_type: "file" },
+ { decision_id: "a", node_id: "src/api.ts", link_type: "file" },
+ { decision_id: "a", node_id: "src/one.ts", link_type: "file" },
+ { decision_id: "c", node_id: "src/mod", link_type: "module" },
+ ],
+ }),
+ );
+ // The duplicate (a, src/api.ts) counts once; the module link is not a file.
+ expect(governedFiles).toEqual([
+ { path: "src/api.ts", decisionCount: 2 },
+ { path: "src/one.ts", decisionCount: 1 },
+ ]);
+ expect(governedFileTotal).toBe(2);
+ });
+
+ it("caps the file list without hiding the true total", () => {
+ // The canvas silently dropped 6,400 of 9,221 code links to a per-decision
+ // cap. The count it truncated to is reported, so the page can say so.
+ const code_edges = Array.from({ length: 30 }, (_, i) => ({
+ decision_id: "a",
+ node_id: `src/f${i}.ts`,
+ link_type: "file" as const,
+ }));
+ const { governedFiles, governedFileTotal } = summarizeGovernance(
+ graph({ code_edges }),
+ { topFiles: 5 },
+ );
+ expect(governedFiles).toHaveLength(5);
+ expect(governedFileTotal).toBe(30);
+ });
+});
+
+describe("DecisionConflicts", () => {
+ it("renders nothing when there are none", () => {
+ const { container } = render(
+ <DecisionConflicts conflicts={[]} decisionHref={(id) => `/d/${id}`} />,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("drops a pair it cannot name rather than printing a hash", () => {
+ const { container } = render(
+ <DecisionConflicts
+ conflicts={[
+ { aId: "a", aTitle: "Use SWR", bId: "e71b45c7eaaa4798a745f59ae80118fc" },
+ ]}
+ decisionHref={(id) => `/d/${id}`}
+ />,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("links both sides of a pair", () => {
+ render(
+ <DecisionConflicts
+ conflicts={[
+ { aId: "a", aTitle: "Use SWR", bId: "b", bTitle: "Use React Query" },
+ ]}
+ decisionHref={(id) => `/d/${id}`}
+ />,
+ );
+ expect(screen.getByText("Use SWR").closest("a")).toHaveAttribute("href", "/d/a");
+ expect(screen.getByText("Use React Query").closest("a")).toHaveAttribute("href", "/d/b");
+ });
+});
+
+describe("GovernedFiles", () => {
+ it("renders paths in mono with tabular counts", () => {
+ const { container } = render(
+ <GovernedFiles
+ files={[
+ { path: "src/api.ts", decisionCount: 12 },
+ { path: "src/one.ts", decisionCount: 3 },
+ ]}
+ />,
+ );
+ expect(screen.getByText("src/api.ts").className).toContain("font-mono");
+ expect(screen.getByText("12").className).toContain("tabular-nums");
+ // The bar is proportional to the leader, not to an arbitrary ceiling.
+ const bars = container.querySelectorAll('[style*="width"]');
+ expect((bars[0] as HTMLElement).style.width).toBe("100%");
+ expect((bars[1] as HTMLElement).style.width).toBe("25%");
+ });
+});
diff --git a/packages/ui/__tests__/settings/settings-primitives.test.tsx b/packages/ui/__tests__/settings/settings-primitives.test.tsx
new file mode 100644
index 000000000..8bddddc9d
--- /dev/null
+++ b/packages/ui/__tests__/settings/settings-primitives.test.tsx
@@ -0,0 +1,105 @@
+import { describe, it, expect } from "vitest";
+import { render, screen } from "@testing-library/react";
+import {
+ CopyLine,
+ EnvVarLine,
+ SaveIndicator,
+ SettingsRow,
+ StatusLine,
+} from "../../src/settings/settings-primitives.js";
+
+describe("SaveIndicator", () => {
+ it("renders nothing at rest", () => {
+ // Rule 10: a permanent "Saved" is a badge every row carries.
+ const { container } = render(<SaveIndicator state="idle" />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("announces each transient state politely", () => {
+ const { rerender } = render(<SaveIndicator state="saving" />);
+ expect(screen.getByText(/Saving/)).toBeInTheDocument();
+
+ rerender(<SaveIndicator state="saved" />);
+ const saved = screen.getByText("Saved");
+ expect(saved).toBeInTheDocument();
+ expect(saved.closest("[aria-live]")).toHaveAttribute("aria-live", "polite");
+
+ rerender(<SaveIndicator state="error" error="Disk full" />);
+ expect(screen.getByText("Disk full")).toBeInTheDocument();
+ });
+
+ it("falls back to a message when an error carries none", () => {
+ render(<SaveIndicator state="error" />);
+ expect(screen.getByText("Could not save")).toBeInTheDocument();
+ });
+});
+
+describe("StatusLine", () => {
+ it("uses the success/error pair, never the freshness pair", () => {
+ // Three settings components signalled "the server answered" with
+ // --color-fresh / --color-outdated, which carry doc-staleness semantics
+ // everywhere else in the app.
+ const { container: ok } = render(
+ <StatusLine status="ok">Connected</StatusLine>,
+ );
+ expect(ok.innerHTML).toContain("--color-success");
+ expect(ok.innerHTML).not.toContain("--color-fresh");
+
+ const { container: bad } = render(
+ <StatusLine status="error">Refused</StatusLine>,
+ );
+ expect(bad.innerHTML).toContain("--color-error");
+ expect(bad.innerHTML).not.toContain("--color-outdated");
+ });
+});
+
+describe("CopyLine", () => {
+ it("never truncates the value it exists to hand you", () => {
+ // Rule 6. The webhook URL is the one string on that page whose whole job is
+ // to be read and copied; it used to render with `truncate`.
+ const url = "https://a-fairly-long-host.example.com/api/webhooks/github";
+ const { container } = render(<CopyLine value={url} label="GitHub" />);
+ const code = container.querySelector("code")!;
+ expect(code.textContent).toBe(url);
+ expect(code.className).not.toContain("truncate");
+ expect(code.className).toContain("overflow-x-auto");
+ });
+
+ it("gives the label the mono micro-label treatment", () => {
+ render(<CopyLine value="x" label="GitHub" />);
+ const label = screen.getByText("GitHub");
+ expect(label.className).toContain("font-mono");
+ expect(label.className).toContain("uppercase");
+ });
+});
+
+describe("EnvVarLine", () => {
+ it("renders nothing when there is nothing to require", () => {
+ const { container } = render(<EnvVarLine vars={[]} />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("lists vars as mono code without a nested box", () => {
+ const { container } = render(
+ <EnvVarLine vars={["GEMINI_API_KEY", "OTHER"]} />,
+ );
+ const codes = container.querySelectorAll("code");
+ expect([...codes].map((c) => c.textContent)).toEqual([
+ "GEMINI_API_KEY",
+ "OTHER",
+ ]);
+ expect(container.querySelector("[class*='border-dashed']")).toBeNull();
+ });
+});
+
+describe("SettingsRow", () => {
+ it("associates its label with the control it names", () => {
+ render(
+ <SettingsRow label="Server URL" htmlFor="api-url" hint="Where to reach it.">
+ <input id="api-url" />
+ </SettingsRow>,
+ );
+ expect(screen.getByLabelText("Server URL")).toHaveAttribute("id", "api-url");
+ expect(screen.getByText("Where to reach it.")).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/shared/markdown.test.tsx b/packages/ui/__tests__/shared/markdown.test.tsx
new file mode 100644
index 000000000..f15bc4bfb
--- /dev/null
+++ b/packages/ui/__tests__/shared/markdown.test.tsx
@@ -0,0 +1,61 @@
+import { describe, it, expect } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { Markdown } from "../../src/shared/markdown.js";
+
+describe("Markdown", () => {
+ it("renders reply body at the reading scale, not chrome sizes", () => {
+ // Chat is a reading surface: a reply is read for minutes, so body is 16px.
+ // It used to render at 14px secondary because the surface lives behind a
+ // control row in the app shell.
+ render(<Markdown content="A plain paragraph." />);
+ const p = screen.getByText("A plain paragraph.");
+ expect(p.className).toContain("text-base");
+ expect(p.className).toContain("text-[var(--color-text-primary)]");
+ });
+
+ it("separates headings from body by size, not weight alone", () => {
+ // h1/h2/h3 previously landed at 16/14/14 against 14px body, so an h2 was
+ // the same size as the text under it — bolded body, not a heading.
+ render(<Markdown content={"# One\n\n## Two\n\n### Three\n\nBody."} />);
+ expect(screen.getByRole("heading", { level: 1 }).className).toContain(
+ "text-2xl",
+ );
+ expect(screen.getByRole("heading", { level: 2 }).className).toContain(
+ "text-xl",
+ );
+ expect(screen.getByRole("heading", { level: 3 }).className).toContain(
+ "text-lg",
+ );
+ expect(screen.getByText("Body.").className).toContain("text-base");
+ });
+
+ it("never renders inline code in the accent", () => {
+ // Rule 9: nothing in a reply resolves to a page, so an accent path would
+ // decorate something that does not respond. This is the exact wall-of-orange
+ // the wiki renderer already fixed.
+ const { container } = render(
+ <Markdown content="Look at `src/auth/session.py` for this." />,
+ );
+ const code = container.querySelector("code");
+ expect(code).not.toBeNull();
+ expect(code!.className).not.toContain("accent");
+ expect(code!.className).toContain("font-mono");
+ });
+
+ it("drops to chrome sizes under density=compact", () => {
+ // The narrow graph doc panel shares this renderer; its column cannot pay
+ // for 16px body. One component with a prop, not a second renderer.
+ render(<Markdown content="Panel text." density="compact" />);
+ expect(screen.getByText("Panel text.").className).toContain("text-xs");
+ });
+
+ it("gives table headers the mono micro-label treatment", () => {
+ const { container } = render(
+ <Markdown content={"| File | Score |\n|---|---|\n| a.py | 4 |"} />,
+ );
+ const th = container.querySelector("th");
+ expect(th).not.toBeNull();
+ expect(th!.className).toContain("font-mono");
+ expect(th!.className).toContain("uppercase");
+ });
+});
diff --git a/packages/ui/__tests__/token-drift.test.ts b/packages/ui/__tests__/token-drift.test.ts
new file mode 100644
index 000000000..be77d001f
--- /dev/null
+++ b/packages/ui/__tests__/token-drift.test.ts
@@ -0,0 +1,85 @@
+import { describe, it, expect } from "vitest";
+import { readFileSync, readdirSync, statSync } from "node:fs";
+import { join } from "node:path";
+
+/**
+ * Drift guard for token *names*.
+ *
+ * `brand.test.ts` pins token values. This pins their existence, which is a
+ * different failure: Tailwind's arbitrary-value syntax will happily emit
+ * `background: var(--color-bg-secondary)` for a name no stylesheet has ever
+ * carried. Nothing errors, nothing logs, and the element renders without the
+ * ground or border it claims.
+ *
+ * A sweep at the time this was written found seven such names across ~45 call
+ * sites — including `--color-bg-muted`, the track of every proportion bar on
+ * Code Health and Dead code, which had been rendering transparent. They are
+ * invisible precisely because a missing ground reads as a design choice.
+ *
+ * `var(--name, fallback)` is legal and deliberate; those are skipped.
+ */
+
+const UI_SRC = join(__dirname, "../src");
+const CSS = join(__dirname, "../styles/globals.css");
+
+function walk(dir: string, out: string[] = []): string[] {
+ for (const entry of readdirSync(dir)) {
+ const p = join(dir, entry);
+ if (statSync(p).isDirectory()) walk(p, out);
+ else if (/\.(tsx?|css)$/.test(entry)) out.push(p);
+ }
+ return out;
+}
+
+function definedTokens(): Set<string> {
+ const css = readFileSync(CSS, "utf8");
+ const names = css.match(/--color-[a-z0-9-]+\s*:/g) ?? [];
+ return new Set(names.map((n) => n.replace(/\s*:$/, "")));
+}
+
+/** Every `var(--color-x)` with no fallback, mapped to the files using it. */
+function referencedTokens(files: string[]): Map<string, string[]> {
+ const refs = new Map<string, string[]>();
+ for (const file of files) {
+ const text = readFileSync(file, "utf8");
+ // The negative lookahead skips `var(--name, fallback)`.
+ for (const m of text.matchAll(/var\((--color-[a-z0-9-]+)\s*\)/g)) {
+ const name = m[1]!;
+ const seen = refs.get(name) ?? [];
+ if (!seen.includes(file)) seen.push(file);
+ refs.set(name, seen);
+ }
+ }
+ return refs;
+}
+
+describe("token drift", () => {
+ it("references no colour token that globals.css does not define", () => {
+ const defined = definedTokens();
+ const referenced = referencedTokens(walk(UI_SRC));
+
+ const missing = [...referenced.entries()]
+ .filter(([name]) => !defined.has(name))
+ .map(([name, files]) => {
+ const rel = files.map((f) => f.replace(UI_SRC, "src")).slice(0, 3);
+ return `${name} (${files.length} file(s): ${rel.join(", ")})`;
+ })
+ .sort();
+
+ expect(missing).toEqual([]);
+ });
+
+ it("finds tokens at all, so a broken matcher cannot pass vacuously", () => {
+ const referenced = referencedTokens(walk(UI_SRC));
+ expect(referenced.size).toBeGreaterThan(50);
+ expect(definedTokens().size).toBeGreaterThan(50);
+ });
+
+ it("ignores the deliberate var(--name, fallback) form", () => {
+ const defined = definedTokens();
+ // Both halves of the pair the churn ledger used to inline are real tokens
+ // now, so the ledger tracks the theme instead of a hardcoded paper green.
+ expect(defined.has("--color-success-muted")).toBe(true);
+ expect(defined.has("--color-error-muted")).toBe(true);
+ });
+});
diff --git a/packages/ui/src/c4/ArchCanvas.tsx b/packages/ui/src/c4/ArchCanvas.tsx
index a31671d57..bfaf33815 100644
--- a/packages/ui/src/c4/ArchCanvas.tsx
+++ b/packages/ui/src/c4/ArchCanvas.tsx
@@ -123,7 +123,12 @@ export function ArchCanvas({
{hiddenEdgeCount > 0 && (
<div
- className="absolute bottom-4 left-14 z-10 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-secondary)]/90 px-3 py-1 text-xs text-[var(--color-text-secondary)]"
+ // `--color-bg-glass` is the chip ground on every canvas. This chip
+ // asked for `--color-bg-secondary`, which no stylesheet defines, so
+ // it has been painting transparent — and it survived because it
+ // only ever renders on top of a diagram, which is exactly how the
+ // stale glass token hid for a month.
+ className="absolute bottom-4 left-14 z-10 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-3 py-1 text-xs text-[var(--color-text-secondary)]"
title="Weakest aggregated connections are hidden to keep the view legible. Drill in to see them."
>
+{hiddenEdgeCount} weaker link{hiddenEdgeCount === 1 ? "" : "s"} hidden
diff --git a/packages/ui/src/chat/artifact-panel.tsx b/packages/ui/src/chat/artifact-panel.tsx
index 71e3dc011..6b4ec020c 100644
--- a/packages/ui/src/chat/artifact-panel.tsx
+++ b/packages/ui/src/chat/artifact-panel.tsx
@@ -3,7 +3,7 @@
import { useState } from "react";
import { cn } from "../lib/cn";
import { AdaptivePanel } from "../shared/adaptive-panel";
-import { ChatMarkdown } from "./chat-markdown";
+import { Markdown } from "../shared/markdown";
import {
ContextRenderer,
DeadCodeRenderer,
@@ -116,7 +116,7 @@ function ArtifactRenderer({ artifact }: { artifact: Artifact | ChatArtifact }) {
((data as Record<string, unknown>).content as string) ??
"";
return content ? (
- <ChatMarkdown content={content} />
+ <Markdown content={content} density="compact" />
) : (
<GenericJsonRenderer data={data as Record<string, unknown>} />
);
diff --git a/packages/ui/src/chat/artifacts.tsx b/packages/ui/src/chat/artifacts.tsx
index e9ea207e2..8fe1fce31 100644
--- a/packages/ui/src/chat/artifacts.tsx
+++ b/packages/ui/src/chat/artifacts.tsx
@@ -31,7 +31,7 @@ import type {
RiskReportArtifactData,
SearchResultsArtifactData,
} from "@repowise-dev/types/chat";
-import { ChatMarkdown } from "./chat-markdown";
+import { Markdown } from "../shared/markdown";
import { MermaidDiagram } from "../wiki/mermaid-diagram";
import { getPageTypeLabel } from "../lib/page-types";
@@ -159,7 +159,7 @@ export function ContextRenderer({ data }: { data: ContextArtifactData }) {
{target}
</h3>
{md ? (
- <ChatMarkdown content={md} />
+ <Markdown content={md} />
) : (
<p className="text-xs text-[var(--color-text-tertiary)]">
No documentation available.
diff --git a/packages/ui/src/chat/chat-interface.tsx b/packages/ui/src/chat/chat-interface.tsx
index 028093fc8..14a4ec80c 100644
--- a/packages/ui/src/chat/chat-interface.tsx
+++ b/packages/ui/src/chat/chat-interface.tsx
@@ -10,7 +10,12 @@
* - artifact panel state (artifacts list + open boolean).
*
* The shell is stateless apart from the textarea input value and renders
- * messages, the empty-state suggestion chips, the input area, and slots.
+ * messages, the empty-state suggestions, the input area, and slots.
+ *
+ * Chat is a reading surface: the transcript sits on `--color-bg-root` and the
+ * one chrome row above it on `--color-bg-surface`. There is exactly one chrome
+ * row — the page used to stack its own repo header on top of this one, under a
+ * breadcrumb, so three hairlines ran before the first word of content.
*/
import {
@@ -39,6 +44,9 @@ const DEFAULT_SUGGESTIONS = [
"Search for authentication-related code",
];
+const MICRO_LABEL =
+ "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
+
export interface ChatInterfaceProps {
/** Identifier forwarded to `ChatMessage` for source-citation hrefs. */
repoId: string;
@@ -81,7 +89,8 @@ export interface ChatInterfaceProps {
/** Override default suggestion chips. */
suggestions?: string[];
/** Orientation line under the empty-state subtitle — index status, page
- * counts, last sync. Keeps the blank page honest about what's loaded. */
+ * counts, branch, last sync. Keeps the blank page honest about what's
+ * loaded, and is the only figure on it, so it is not buried. */
statusSlot?: ReactNode;
/** Disables the composer (e.g. no chat provider configured). */
sendDisabled?: boolean;
@@ -180,24 +189,24 @@ export function ChatInterface({
return (
<div className="flex h-full flex-col min-h-0">
- {/* Header bar — the single home for model + history (both empty and
- active states), so the controls don't render twice. */}
+ {/* The one chrome row. */}
{(historySlot || modelSelectorSlot) && (
- <div className="flex items-center justify-between px-4 py-2.5 border-b border-[var(--color-border-default)] shrink-0 bg-[var(--color-bg-surface)]/95 backdrop-blur-sm">
- <div className="flex items-center gap-2">{historySlot}</div>
- <div className="flex items-center gap-2">
+ <div className="flex items-center justify-between gap-2 px-[var(--page-pad)] py-2.5 border-b border-[var(--color-border-default)] shrink-0 bg-[var(--color-bg-surface)]">
+ <div className="flex min-w-0 items-center gap-2">{historySlot}</div>
+ <div className="flex items-center gap-2 shrink-0">
{totalArtifactCount > 0 && (
<Button
variant="ghost"
size="sm"
className={cn(
- "h-8 text-xs gap-1.5",
+ "h-8 text-xs gap-1.5 tabular-nums",
artifactPulse &&
"animate-pulse text-[var(--color-accent-primary)]",
)}
onClick={() => setArtifactPanelOpen(true)}
>
<PanelRight className="h-4 w-4" />
+ <span className="sr-only sm:not-sr-only">Artifacts</span>
{totalArtifactCount}
</Button>
)}
@@ -209,44 +218,53 @@ export function ChatInterface({
{/* Message list or empty state */}
<div className="flex-1 min-h-0 relative">
{isEmpty ? (
- <div className="flex flex-col items-center justify-center h-full gap-10 px-4">
- <div className="text-center space-y-3">
- <div className="flex items-center justify-center mb-6">
- <BrandMark
- darkSrc={emptyStateLogoSrc}
- size={48}
- className="drop-shadow-[0_0_8px_rgba(245,149,32,0.18)]"
- />
+ // Scrolls: at 390x667 the mark, heading, status and six suggestions
+ // exceed the viewport, and the old centred flex column clipped them.
+ // Top-anchored rather than centred — vertical centring would need a
+ // height Radix's `display:table` viewport wrapper does not pass down,
+ // and the section style reads left-aligned everywhere else anyway.
+ <ScrollArea className="h-full">
+ <div className="mx-auto flex max-w-2xl flex-col gap-10 px-[var(--page-pad)] py-14">
+ <div className="space-y-4">
+ <BrandMark darkSrc={emptyStateLogoSrc} size={40} />
+ <h2 className="text-[22px] font-semibold text-[var(--color-text-primary)]">
+ Ask anything about {repoName ?? "this codebase"}
+ </h2>
+ <p className="text-base text-[var(--color-text-secondary)] leading-relaxed">
+ Explore architecture, assess risk, search code, trace
+ dependencies, and understand decisions. Every answer cites the
+ pages it read.
+ </p>
+ {statusSlot && (
+ <p className="font-mono text-xs text-[var(--color-text-tertiary)] tabular-nums">
+ {statusSlot}
+ </p>
+ )}
</div>
- <h2 className="text-xl font-semibold text-[var(--color-text-primary)]">
- Ask anything about {repoName ?? "this codebase"}
- </h2>
- <p className="text-sm text-[var(--color-text-secondary)] max-w-md leading-relaxed">
- Explore architecture, assess risk, search code, trace
- dependencies, and understand decisions.
- </p>
- {statusSlot && (
- <div className="text-xs text-[var(--color-text-tertiary)]">
- {statusSlot}
- </div>
- )}
- </div>
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5 max-w-xl w-full">
- {suggestions.map((s) => (
- <button
- key={s}
- className="text-left text-sm text-[var(--color-text-secondary)] rounded-xl border border-[var(--color-border-default)] px-4 py-3 hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-hover)] transition-colors"
- onClick={() => handleSuggestion(s)}
- >
- {s}
- </button>
- ))}
+ {/* Hairline rows, not a grid of bordered boxes. A suggestion is
+ not a discrete object you act on repeatedly; it is a list. */}
+ <div>
+ <p className={cn(MICRO_LABEL, "mb-1")}>Start with</p>
+ <ul className="border-t border-[var(--color-border-default)]">
+ {suggestions.map((s) => (
+ <li key={s}>
+ <button
+ className="group flex w-full items-center gap-3 border-b border-[var(--color-border-default)] py-3 text-left text-[15px] text-[var(--color-text-secondary)] transition-colors hover:text-[var(--color-accent-primary)]"
+ onClick={() => handleSuggestion(s)}
+ >
+ <span className="flex-1 min-w-0">{s}</span>
+ <Send className="h-3.5 w-3.5 shrink-0 opacity-0 transition-opacity group-hover:opacity-100" />
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
</div>
- </div>
+ </ScrollArea>
) : (
<ScrollArea className="h-full">
- <div className="px-4 py-6 space-y-5 max-w-3xl mx-auto">
+ <div className="px-[var(--page-pad)] py-10 space-y-10 max-w-3xl mx-auto">
{messages.map((m) => (
<ChatMessage
key={m.id}
@@ -269,10 +287,11 @@ export function ChatInterface({
)}
</div>
- {/* Input area */}
+ {/* Input area. The composer keeps its elevation: it is a genuinely
+ interactive surface, which is what rule 1 reserves elevation for. */}
<div
className={cn(
- "shrink-0 px-4 py-4",
+ "shrink-0 px-[var(--page-pad)] pb-5 pt-4",
!isEmpty && "border-t border-[var(--color-border-default)]",
)}
>
@@ -298,11 +317,11 @@ export function ChatInterface({
void handleSubmit();
}
}}
- placeholder="Ask anything about this codebase..."
+ placeholder="Ask a question, or paste a file path"
aria-label="Chat message"
disabled={sendDisabled}
rows={1}
- className="flex-1 resize-none bg-transparent text-sm text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] outline-none leading-6 max-h-36 overflow-y-auto"
+ className="flex-1 resize-none bg-transparent text-[15px] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] outline-none leading-6 max-h-36 overflow-y-auto"
style={{ scrollbarWidth: "none" }}
/>
<Button
@@ -321,7 +340,7 @@ export function ChatInterface({
</Button>
</div>
{isEmpty && (
- <p className="text-center text-xs text-[var(--color-text-tertiary)] mt-2.5">
+ <p className={cn(MICRO_LABEL, "mt-2.5 text-center")}>
Shift+Enter for newline · Enter to send
</p>
)}
diff --git a/packages/ui/src/chat/chat-markdown.tsx b/packages/ui/src/chat/chat-markdown.tsx
index e70f3e14b..d4b4fc6fa 100644
--- a/packages/ui/src/chat/chat-markdown.tsx
+++ b/packages/ui/src/chat/chat-markdown.tsx
@@ -1,146 +1,18 @@
"use client";
-import { lazy, Suspense } from "react";
-import ReactMarkdown from "react-markdown";
-import remarkGfm from "remark-gfm";
-import type { Components } from "react-markdown";
+/**
+ * Back-compat shim. The renderer moved to `shared/markdown` once decisions
+ * needed it too — it was never chat-specific, and leaving it under `chat/`
+ * invited a fourth copy for the next surface that wanted themed markdown.
+ *
+ * This path stays because the hosted frontend imports
+ * `@repowise-dev/ui/chat/chat-markdown` directly.
+ */
-// Mermaid pulls a heavy renderer that is strictly client-side. Lazy-load it so
-// it never enters the chat bundle (or SSR pass) unless a reply actually contains
-// an inline ```mermaid block — parity with the wiki/docs reader.
-const MermaidDiagram = lazy(() =>
- import("../wiki/mermaid-diagram").then((m) => ({ default: m.MermaidDiagram })),
-);
-
-const components: Components = {
- h1: ({ children }) => (
- <h1 className="text-base font-semibold text-[var(--color-text-primary)] mt-4 mb-2">
- {children}
- </h1>
- ),
- h2: ({ children }) => (
- <h2 className="text-sm font-semibold text-[var(--color-text-primary)] mt-3 mb-1.5">
- {children}
- </h2>
- ),
- h3: ({ children }) => (
- <h3 className="text-sm font-medium text-[var(--color-text-primary)] mt-2 mb-1">
- {children}
- </h3>
- ),
- p: ({ children }) => (
- <p className="text-sm text-[var(--color-text-secondary)] leading-relaxed mb-2">
- {children}
- </p>
- ),
- ul: ({ children }) => (
- <ul className="list-disc ml-4 text-sm text-[var(--color-text-secondary)] space-y-0.5 mb-2">
- {children}
- </ul>
- ),
- ol: ({ children }) => (
- <ol className="list-decimal ml-4 text-sm text-[var(--color-text-secondary)] space-y-0.5 mb-2">
- {children}
- </ol>
- ),
- li: ({ children }) => <li className="leading-relaxed">{children}</li>,
- code: ({ className, children, ...props }) => {
- const isBlock = className?.includes("language-");
- if (isBlock) {
- const isMermaid = className?.includes("language-mermaid");
- if (isMermaid) {
- const chart = String(children ?? "").replace(/\n$/, "");
- return (
- <Suspense
- fallback={
- <pre className="my-2 rounded-md bg-[var(--color-bg-inset)] border border-[var(--color-border-default)] p-3 overflow-x-auto">
- <code className="text-xs font-mono text-[var(--color-text-primary)]">
- {chart}
- </code>
- </pre>
- }
- >
- <MermaidDiagram chart={chart} />
- </Suspense>
- );
- }
- return (
- <pre className="my-2 rounded-md bg-[var(--color-bg-inset)] border border-[var(--color-border-default)] p-3 overflow-x-auto">
- <code
- className="text-xs font-mono text-[var(--color-text-primary)]"
- {...props}
- >
- {children}
- </code>
- </pre>
- );
- }
- return (
- <code
- className="rounded px-1.5 py-0.5 bg-[var(--color-bg-elevated)] text-[var(--color-accent-primary)] text-xs font-mono"
- {...props}
- >
- {children}
- </code>
- );
- },
- pre: ({ children }) => <>{children}</>,
- blockquote: ({ children }) => (
- <blockquote className="border-l-2 border-[var(--color-accent-primary)] pl-3 my-2 text-sm text-[var(--color-text-secondary)] italic">
- {children}
- </blockquote>
- ),
- a: ({ href, children }) => (
- <a
- href={href}
- className="text-[var(--color-accent-primary)] hover:underline"
- target="_blank"
- rel="noopener noreferrer"
- >
- {children}
- </a>
- ),
- table: ({ children }) => (
- <div className="overflow-x-auto my-2">
- <table className="text-xs w-full border-collapse">{children}</table>
- </div>
- ),
- thead: ({ children }) => (
- <thead className="bg-[var(--color-bg-surface)] border-b border-[var(--color-border-default)]">
- {children}
- </thead>
- ),
- th: ({ children }) => (
- <th className="text-left px-3 py-2.5 text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- {children}
- </th>
- ),
- tr: ({ children }) => (
- <tr className="border-t border-[var(--color-table-divider)] transition-colors hover:bg-[var(--color-bg-elevated)]">
- {children}
- </tr>
- ),
- td: ({ children }) => (
- <td className="px-3 py-2.5 text-[var(--color-text-secondary)]">
- {children}
- </td>
- ),
- strong: ({ children }) => (
- <strong className="font-medium text-[var(--color-text-primary)]">
- {children}
- </strong>
- ),
- hr: () => <hr className="my-3 border-[var(--color-border-default)]" />,
-};
-
-interface ChatMarkdownProps {
- content: string;
-}
-
-export function ChatMarkdown({ content }: ChatMarkdownProps) {
- return (
- <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
- {content}
- </ReactMarkdown>
- );
-}
+export {
+ Markdown,
+ ChatMarkdown,
+ type MarkdownProps,
+ type MarkdownDensity,
+ type ChatMarkdownDensity,
+} from "../shared/markdown";
diff --git a/packages/ui/src/chat/chat-message.tsx b/packages/ui/src/chat/chat-message.tsx
index ecf0ba86f..cbb23378f 100644
--- a/packages/ui/src/chat/chat-message.tsx
+++ b/packages/ui/src/chat/chat-message.tsx
@@ -1,10 +1,10 @@
"use client";
-import { User } from "lucide-react";
+import { memo } from "react";
import { cn } from "../lib/cn";
import { BrandMark } from "../shared/brand-mark";
import { ToolCallGroup } from "./tool-call-group";
-import { ChatMarkdown } from "./chat-markdown";
+import { Markdown } from "../shared/markdown";
import { SourceCitations, type SourceReference } from "./source-citations";
import type { ChatUIMessage } from "@repowise-dev/types/chat";
@@ -20,7 +20,20 @@ interface ChatMessageProps {
linkPrefix?: string;
}
-export function ChatMessage({
+/**
+ * One turn of the transcript.
+ *
+ * The user's turn used to be a solid accent bubble with an accent avatar disc —
+ * the highest-contrast object on the page, spent on the one element that is
+ * purely a record of what you already typed. The accent belongs to things that
+ * respond. A question now reads as the heading it functionally is, and the
+ * answer below it gets the page.
+ *
+ * Memoised: without it every SSE token re-renders the whole list, which means
+ * react-markdown re-parses every prior reply on every frame of a stream. The
+ * cost is invisible in the JSX and scales with transcript length.
+ */
+function ChatMessageImpl({
message,
repoId,
onViewArtifact,
@@ -30,81 +43,70 @@ export function ChatMessage({
}: ChatMessageProps) {
const isUser = message.role === "user";
+ if (isUser) {
+ return (
+ <div className="flex gap-3">
+ <span
+ aria-hidden
+ className="mt-[0.7rem] h-px w-6 shrink-0 bg-[var(--color-border-default)]"
+ />
+ <p className="flex-1 min-w-0 text-lg font-medium leading-snug text-[var(--color-text-primary)]">
+ {message.text}
+ </p>
+ </div>
+ );
+ }
+
return (
- <div className={cn("flex gap-3.5", isUser && "flex-row-reverse")}>
+ <div className="flex gap-3.5">
<div
className={cn(
- "flex shrink-0 items-center justify-center rounded-full mt-0.5",
- isUser
- ? "h-8 w-8 bg-[var(--color-accent-primary)]"
- : "h-8 w-8 bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)]",
+ "flex h-8 w-8 shrink-0 items-center justify-center rounded-full mt-0.5",
+ "bg-[var(--color-bg-surface)] border border-[var(--color-border-default)]",
)}
>
- {isUser ? (
- <User className="h-4 w-4 text-white" />
- ) : (
- <BrandMark
- darkSrc={assistantAvatarSrc}
- size={22}
- className="drop-shadow-[0_0_3px_rgba(245,149,32,0.15)]"
- />
- )}
+ <BrandMark darkSrc={assistantAvatarSrc} size={22} />
</div>
- <div
- className={cn(
- "flex-1 min-w-0",
- isUser && "flex flex-col items-end",
- )}
- >
- {isUser && (
- <div className="rounded-2xl rounded-tr-sm bg-[var(--color-accent-primary)] px-4 py-2.5 text-sm text-white max-w-[85%]">
- {message.text}
- </div>
- )}
+ <div className="flex-1 min-w-0">
+ <div className="max-w-full space-y-3">
+ {message.toolCalls.length > 0 && (
+ <ToolCallGroup
+ toolCalls={message.toolCalls}
+ {...(onViewArtifact ? { onViewArtifact } : {})}
+ />
+ )}
- {!isUser && (
- <div className="max-w-full space-y-1.5">
- {message.toolCalls.length > 0 && (
- <ToolCallGroup
- toolCalls={message.toolCalls}
- {...(onViewArtifact ? { onViewArtifact } : {})}
- />
- )}
+ {message.text && <Markdown content={message.text} />}
- {message.text && (
- <div className="prose-chat">
- <ChatMarkdown content={message.text} />
- </div>
- )}
+ {!message.isStreaming && message.toolCalls.length > 0 && (
+ <SourceCitations
+ toolCalls={message.toolCalls}
+ repoId={repoId}
+ {...(linkPrefix ? { linkPrefix } : {})}
+ {...(buildCitationHref ? { buildHref: buildCitationHref } : {})}
+ />
+ )}
- {!message.isStreaming && message.toolCalls.length > 0 && (
- <SourceCitations
- toolCalls={message.toolCalls}
- repoId={repoId}
- {...(linkPrefix ? { linkPrefix } : {})}
- {...(buildCitationHref ? { buildHref: buildCitationHref } : {})}
- />
+ {message.isStreaming &&
+ !message.text &&
+ message.toolCalls.length === 0 && (
+ <div className="flex items-center gap-1.5 py-2">
+ <div className="h-1.5 w-1.5 rounded-full bg-[var(--color-text-tertiary)] animate-pulse" />
+ <div
+ className="h-1.5 w-1.5 rounded-full bg-[var(--color-text-tertiary)] animate-pulse"
+ style={{ animationDelay: "0.15s" }}
+ />
+ <div
+ className="h-1.5 w-1.5 rounded-full bg-[var(--color-text-tertiary)] animate-pulse"
+ style={{ animationDelay: "0.3s" }}
+ />
+ </div>
)}
-
- {message.isStreaming &&
- !message.text &&
- message.toolCalls.length === 0 && (
- <div className="flex items-center gap-1.5 py-2">
- <div className="h-1.5 w-1.5 rounded-full bg-[var(--color-accent-primary)] animate-pulse" />
- <div
- className="h-1.5 w-1.5 rounded-full bg-[var(--color-accent-primary)] animate-pulse"
- style={{ animationDelay: "0.15s" }}
- />
- <div
- className="h-1.5 w-1.5 rounded-full bg-[var(--color-accent-primary)] animate-pulse"
- style={{ animationDelay: "0.3s" }}
- />
- </div>
- )}
- </div>
- )}
+ </div>
</div>
</div>
);
}
+
+export const ChatMessage = memo(ChatMessageImpl);
diff --git a/packages/ui/src/chat/conversation-history.tsx b/packages/ui/src/chat/conversation-history.tsx
index 7457c6902..82b9877cf 100644
--- a/packages/ui/src/chat/conversation-history.tsx
+++ b/packages/ui/src/chat/conversation-history.tsx
@@ -52,8 +52,8 @@ export function ConversationHistory({
"hover:bg-[var(--color-bg-elevated)] transition-colors",
)}
>
- <History className="h-3.5 w-3.5" />
- History
+ <History className="h-3.5 w-3.5 shrink-0" />
+ <span className="sr-only sm:not-sr-only">History</span>
</button>
{open && (
@@ -117,10 +117,13 @@ export function ConversationHistory({
}}
>
<div className="flex-1 min-w-0">
- <div className="text-xs text-[var(--color-text-primary)] truncate">
+ {/* Two lines rather than an ellipsis: a conversation is
+ identified by its title, so cutting it mid-word reports
+ a width decision as missing content. */}
+ <div className="text-xs text-[var(--color-text-primary)] line-clamp-2">
{conv.title}
</div>
- <div className="text-[10px] text-[var(--color-text-tertiary)]">
+ <div className="font-mono text-[10px] text-[var(--color-text-tertiary)] tabular-nums mt-0.5">
{formatRelativeTime(conv.updated_at)} ·{" "}
{conv.message_count} msgs
</div>
@@ -130,7 +133,7 @@ export function ConversationHistory({
e.stopPropagation();
void onDelete(conv.id);
}}
- className="opacity-0 group-hover:opacity-100 p-1 text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] transition-all"
+ className="opacity-0 group-hover:opacity-100 focus-visible:opacity-100 p-1 shrink-0 self-start text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] transition-all"
aria-label="Delete conversation"
>
<Trash2 className="h-3 w-3" />
diff --git a/packages/ui/src/chat/index.ts b/packages/ui/src/chat/index.ts
index bea5c0133..f0e225eba 100644
--- a/packages/ui/src/chat/index.ts
+++ b/packages/ui/src/chat/index.ts
@@ -1,7 +1,7 @@
export * from "./artifact-panel";
export * from "./artifacts";
export * from "./chat-interface";
-export * from "./chat-markdown";
+export * from "../shared/markdown";
export * from "./chat-message";
export * from "./conversation-history";
export * from "./model-selector";
diff --git a/packages/ui/src/chat/model-selector.tsx b/packages/ui/src/chat/model-selector.tsx
index 764807f3b..e704e5ea6 100644
--- a/packages/ui/src/chat/model-selector.tsx
+++ b/packages/ui/src/chat/model-selector.tsx
@@ -81,8 +81,11 @@ export function ModelSelector({
"border border-[var(--color-border-default)]",
)}
>
- <span className="truncate max-w-[200px]">
- {isLoading ? "..." : label}
+ {/* The model name is the longest string in a crowded row. Below `sm`
+ it drops to the provider alone rather than squeezing the row —
+ labels go before controls do. */}
+ <span className="truncate max-w-[120px] sm:max-w-[200px]">
+ {isLoading ? "…" : label}
</span>
<ChevronDown className="h-3 w-3 shrink-0" />
</button>
diff --git a/packages/ui/src/chat/source-citations.tsx b/packages/ui/src/chat/source-citations.tsx
index fb6bf50c9..d714472ba 100644
--- a/packages/ui/src/chat/source-citations.tsx
+++ b/packages/ui/src/chat/source-citations.tsx
@@ -165,31 +165,39 @@ export function SourceCitations({
if (sources.length === 0) return null;
return (
- <div className="mt-2 pt-2 border-t border-[var(--color-border-default)]/50">
- <p className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium mb-1.5">
+ <div className="mt-5 pt-4 border-t border-[var(--color-border-default)]">
+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] mb-2.5">
Sources
</p>
- <div className="flex flex-wrap gap-1.5">
- {sources.map((source, idx) => (
- <a
- key={source.id}
- href={buildHref ? buildHref(source) : defaultBuildHref(source, prefix)}
- className="group inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-[10px] text-[var(--color-text-secondary)] hover:border-[var(--color-accent-primary)] hover:text-[var(--color-accent-primary)] hover:bg-[var(--color-accent-muted)] transition-all"
- >
- <span className="flex items-center justify-center h-3.5 w-3.5 rounded-sm bg-[var(--color-bg-overlay)] text-[10px] font-bold text-[var(--color-text-tertiary)] group-hover:bg-[var(--color-accent-primary)] group-hover:text-white shrink-0 transition-colors">
- {idx + 1}
- </span>
- <SourceIcon pageType={source.pageType} className="h-3 w-3 shrink-0 opacity-60" />
- <span className="truncate max-w-[160px] font-medium">{source.title}</span>
- {source.confidence != null && (
- <span className="text-[10px] text-[var(--color-text-tertiary)] tabular-nums">
- {(source.confidence * 100).toFixed(0)}%
- </span>
- )}
- <ArrowUpRight className="h-2.5 w-2.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0" />
- </a>
+ {/* Links, not chips. Each one goes somewhere, so the accent is earned on
+ hover; a border and a ground on every entry turned a list of eight
+ into a wall of boxes that outweighed the answer above it. The counter
+ badge went with them — numbering is only worth its weight when the
+ prose cites [1], and a reply does not. */}
+ <ul className="flex flex-col gap-1.5">
+ {sources.map((source) => (
+ <li key={source.id}>
+ <a
+ href={buildHref ? buildHref(source) : defaultBuildHref(source, prefix)}
+ className="group inline-flex items-baseline gap-2 text-[13px] text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] transition-colors"
+ >
+ <SourceIcon
+ pageType={source.pageType}
+ className="h-3.5 w-3.5 shrink-0 self-center text-[var(--color-text-tertiary)] group-hover:text-[var(--color-accent-primary)] transition-colors"
+ />
+ {/* No truncation: a cut title reports a layout decision to the
+ reader as missing content. Long ones wrap. */}
+ <span className="font-medium">{source.title}</span>
+ {source.confidence != null && (
+ <span className="font-mono text-[11px] text-[var(--color-text-tertiary)] tabular-nums">
+ {(source.confidence * 100).toFixed(0)}%
+ </span>
+ )}
+ <ArrowUpRight className="h-3 w-3 shrink-0 self-center opacity-0 group-hover:opacity-100 transition-opacity" />
+ </a>
+ </li>
))}
- </div>
+ </ul>
</div>
);
}
diff --git a/packages/ui/src/chat/tool-call-block.tsx b/packages/ui/src/chat/tool-call-block.tsx
index 9d72f22a8..f46709f88 100644
--- a/packages/ui/src/chat/tool-call-block.tsx
+++ b/packages/ui/src/chat/tool-call-block.tsx
@@ -1,7 +1,20 @@
"use client";
+/**
+ * One step of the model's work, as a hairline row.
+ *
+ * It used to be a bordered `bg-elevated` box that `ToolCallGroup` then nested
+ * inside another bordered `bg-elevated` box — the same plane twice, with two
+ * borders around it. The group owns the container now; a step is a row.
+ *
+ * A finished step carries no success badge. A green check on every completed
+ * row says nothing, because success is the default and the failure case is what
+ * needs marking. Only a *running* step shows a marker, and only while it runs.
+ */
+
import { useState } from "react";
-import { ChevronDown, ChevronRight, Loader2, CheckCircle2, ExternalLink } from "lucide-react";
+import { ChevronDown, ChevronRight, Loader2, ArrowUpRight } from "lucide-react";
+import { cn } from "../lib/cn";
import type { ChatUIToolCall } from "@repowise-dev/types/chat";
const TOOL_LABELS: Record<string, string> = {
@@ -15,19 +28,33 @@ const TOOL_LABELS: Record<string, string> = {
get_architecture_diagram: "Generating architecture diagram",
};
+const MICRO_LABEL =
+ "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
+
interface ToolCallBlockProps {
toolCall: ChatUIToolCall;
onViewArtifact?: () => void;
+ /** Renders the top hairline. Omitted on the first row of a group. */
+ divided?: boolean;
}
-export function ToolCallBlock({ toolCall, onViewArtifact }: ToolCallBlockProps) {
+export function ToolCallBlock({
+ toolCall,
+ onViewArtifact,
+ divided = false,
+}: ToolCallBlockProps) {
const [expanded, setExpanded] = useState(false);
const label = TOOL_LABELS[toolCall.name] ?? toolCall.name;
const isRunning = toolCall.status === "running";
return (
- <div className="my-1.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] text-xs overflow-hidden">
- <div className="flex items-center gap-2 px-3 py-2 hover:bg-[var(--color-bg-overlay)] transition-colors">
+ <div
+ className={cn(
+ "text-xs",
+ divided && "border-t border-[var(--color-border-default)]",
+ )}
+ >
+ <div className="flex items-center gap-2 px-3 py-2">
<button
type="button"
className="flex flex-1 min-w-0 items-center gap-2 text-left"
@@ -35,26 +62,26 @@ export function ToolCallBlock({ toolCall, onViewArtifact }: ToolCallBlockProps)
disabled={isRunning}
aria-expanded={expanded}
>
- {isRunning ? (
+ {isRunning && (
<Loader2 className="h-3.5 w-3.5 animate-spin text-[var(--color-accent-primary)] shrink-0" />
- ) : (
- <CheckCircle2 className="h-3.5 w-3.5 text-[var(--color-success)] shrink-0" />
)}
- <span className="font-medium text-[var(--color-text-secondary)]">{label}</span>
+ <span className="font-medium text-[var(--color-text-secondary)]">
+ {label}
+ </span>
{toolCall.summary && !isRunning && (
<span className="text-[var(--color-text-tertiary)] truncate ml-1">
— {toolCall.summary}
</span>
)}
</button>
- <span className="ml-auto flex items-center gap-1 shrink-0">
+ <span className="ml-auto flex items-center gap-2 shrink-0">
{toolCall.artifact && onViewArtifact && !isRunning && (
<button
type="button"
onClick={onViewArtifact}
className="text-[var(--color-accent-primary)] hover:underline flex items-center gap-0.5"
>
- View <ExternalLink className="h-3 w-3" />
+ View <ArrowUpRight className="h-3 w-3" />
</button>
)}
{!isRunning &&
@@ -67,20 +94,16 @@ export function ToolCallBlock({ toolCall, onViewArtifact }: ToolCallBlockProps)
</div>
{expanded && (
- <div className="border-t border-[var(--color-border-default)] px-3 py-2 space-y-2">
+ <div className="px-3 pb-2.5 space-y-2.5">
<div>
- <span className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium">
- Input
- </span>
+ <span className={MICRO_LABEL}>Input</span>
<pre className="mt-1 text-[10px] font-mono text-[var(--color-text-secondary)] overflow-x-auto max-h-32 overflow-y-auto">
{JSON.stringify(toolCall.arguments, null, 2)}
</pre>
</div>
{toolCall.result && (
<div>
- <span className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium">
- Result
- </span>
+ <span className={MICRO_LABEL}>Result</span>
<pre className="mt-1 text-[10px] font-mono text-[var(--color-text-secondary)] overflow-x-auto max-h-48 overflow-y-auto">
{JSON.stringify(toolCall.result, null, 2).slice(0, 2000)}
{JSON.stringify(toolCall.result).length > 2000 ? "\n..." : ""}
diff --git a/packages/ui/src/chat/tool-call-group.tsx b/packages/ui/src/chat/tool-call-group.tsx
index b3855439f..2446ed364 100644
--- a/packages/ui/src/chat/tool-call-group.tsx
+++ b/packages/ui/src/chat/tool-call-group.tsx
@@ -1,7 +1,7 @@
"use client";
import { useState } from "react";
-import { ChevronDown, ChevronRight, Loader2, Sparkles } from "lucide-react";
+import { ChevronDown, ChevronRight, Loader2 } from "lucide-react";
import { ToolCallBlock } from "./tool-call-block";
import type { ChatUIToolCall } from "@repowise-dev/types/chat";
@@ -14,6 +14,11 @@ interface ToolCallGroupProps {
* Collapses a run of tool calls into a single "thinking" group instead of N
* stacked bordered boxes. Auto-expands while any step is running so progress
* stays visible; collapses to a one-line summary once the work is done.
+ *
+ * The group owns the one border and the one ground. Steps inside it are
+ * hairline rows — nesting a bordered box inside a bordered box of the same
+ * plane was the "box soup" the section style exists to remove, and it happened
+ * once per step.
*/
export function ToolCallGroup({ toolCalls, onViewArtifact }: ToolCallGroupProps) {
const running = toolCalls.some((tc) => tc.status === "running");
@@ -21,33 +26,39 @@ export function ToolCallGroup({ toolCalls, onViewArtifact }: ToolCallGroupProps)
if (toolCalls.length === 0) return null;
- // A lone tool call doesn't need a group wrapper.
+ const shell =
+ "rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-xs overflow-hidden";
+
+ // A lone tool call doesn't need a group wrapper, but it still needs the
+ // container the row no longer carries itself.
if (toolCalls.length === 1) {
const tc = toolCalls[0]!;
const artifact = tc.artifact;
const handler = artifact && onViewArtifact ? () => onViewArtifact(artifact) : undefined;
- return <ToolCallBlock toolCall={tc} {...(handler ? { onViewArtifact: handler } : {})} />;
+ return (
+ <div className={shell}>
+ <ToolCallBlock toolCall={tc} {...(handler ? { onViewArtifact: handler } : {})} />
+ </div>
+ );
}
const open = expanded || running;
return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] text-xs overflow-hidden">
+ <div className={shell}>
<button
type="button"
- className="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-[var(--color-bg-overlay)] transition-colors"
+ className="flex w-full items-center gap-2 px-3 py-2 text-left"
onClick={() => setExpanded((e) => !e)}
aria-expanded={open}
>
- {running ? (
+ {running && (
<Loader2 className="h-3.5 w-3.5 animate-spin text-[var(--color-accent-primary)] shrink-0" />
- ) : (
- <Sparkles className="h-3.5 w-3.5 text-[var(--color-text-tertiary)] shrink-0" />
)}
<span className="font-medium text-[var(--color-text-secondary)]">
{running ? "Working" : "Thinking"}
</span>
- <span className="text-[var(--color-text-tertiary)]">
+ <span className="text-[var(--color-text-tertiary)] tabular-nums">
· {toolCalls.length} steps
</span>
<span className="ml-auto shrink-0">
@@ -59,8 +70,8 @@ export function ToolCallGroup({ toolCalls, onViewArtifact }: ToolCallGroupProps)
</span>
</button>
{open && (
- <div className="border-t border-[var(--color-border-default)] p-1.5 space-y-1">
- {toolCalls.map((tc) => {
+ <div className="border-t border-[var(--color-border-default)]">
+ {toolCalls.map((tc, idx) => {
const artifact = tc.artifact;
const handler =
artifact && onViewArtifact ? () => onViewArtifact(artifact) : undefined;
@@ -68,6 +79,7 @@ export function ToolCallGroup({ toolCalls, onViewArtifact }: ToolCallGroupProps)
<ToolCallBlock
key={tc.id}
toolCall={tc}
+ divided={idx > 0}
{...(handler ? { onViewArtifact: handler } : {})}
/>
);
diff --git a/packages/ui/src/coupling/coupling-graph.tsx b/packages/ui/src/coupling/coupling-graph.tsx
index f6642c468..e23951b06 100644
--- a/packages/ui/src/coupling/coupling-graph.tsx
+++ b/packages/ui/src/coupling/coupling-graph.tsx
@@ -309,7 +309,7 @@ export function CouplingGraph({
d={`M ${x0} ${y0} A ${radius + 12} ${radius + 12} 0 ${large} 1 ${x1} ${y1}`}
fill="none"
stroke="currentColor"
- className="text-[var(--color-border-strong)]"
+ className="text-[var(--color-border-hover)]"
strokeOpacity={0.5}
strokeWidth={1.5}
strokeLinecap="round"
diff --git a/packages/ui/src/dead-code/dead-code-lede.tsx b/packages/ui/src/dead-code/dead-code-lede.tsx
index aac37eedb..6ecd97799 100644
--- a/packages/ui/src/dead-code/dead-code-lede.tsx
+++ b/packages/ui/src/dead-code/dead-code-lede.tsx
@@ -203,7 +203,7 @@ function ConfidenceSplit({
return (
<div className="space-y-1.5">
- <div className="flex h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-muted)]">
+ <div className="flex h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
{segments.map((s) => (
<div
key={s.key}
diff --git a/packages/ui/src/decisions/decision-detail.tsx b/packages/ui/src/decisions/decision-detail.tsx
index 3351bf173..26411fa15 100644
--- a/packages/ui/src/decisions/decision-detail.tsx
+++ b/packages/ui/src/decisions/decision-detail.tsx
@@ -12,11 +12,10 @@
*/
import * as React from "react";
-import ReactMarkdown from "react-markdown";
-import remarkGfm from "remark-gfm";
import useSWR from "swr";
import { toast } from "sonner";
import {
+ AlertTriangle,
ChevronLeft,
ChevronRight,
FileSearch,
@@ -28,9 +27,9 @@ import type {
DecisionStatus,
} from "@repowise-dev/types/decisions";
-import { Badge } from "../ui/badge";
+import { Markdown } from "../shared/markdown";
import { ConfirmDialog } from "../ui/confirm-dialog";
-import { stripMarkdown } from "../lib/format";
+import { formatDate, stripMarkdown } from "../lib/format";
import { AiPromptButton } from "../health/ai-prompt-button";
import { AiPromptModal } from "../health/ai-prompt-modal";
import {
@@ -40,6 +39,7 @@ import {
import { ModuleLinkEditor } from "./module-link-editor";
import { VerificationBadge } from "./verification-badge";
+import { DecisionStatusMark } from "./decision-status-mark";
import { DecisionEvidenceDrawer } from "./decision-evidence-drawer";
import { DecisionLineage } from "./decision-lineage";
import type {
@@ -48,16 +48,21 @@ import type {
} from "./decision-detail-adapter";
import { toFriendlyMessage } from "../lib/errors";
-const STATUS_VARIANT: Record<
- string,
- "default" | "fresh" | "stale" | "outdated" | "outline" | "accent"
-> = {
- active: "fresh",
- proposed: "accent",
- deprecated: "outdated",
- superseded: "outline",
+const SOURCE_LABEL: Record<string, string> = {
+ inline_marker: "Marker",
+ git_archaeology: "Git history",
+ readme_mining: "Docs",
+ cli: "Manual",
+ comment: "Comment",
+ pr: "Pull request",
+ adr: "ADR",
+ changelog: "Changelog",
+ session: "Session",
};
+const MICRO_LABEL =
+ "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
+
const CONFIRM_COPY: Record<
string,
{ title: string; description: string; confirmLabel: string; destructive: boolean }
@@ -251,20 +256,46 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {
</PrevNextLink>
</div>
</div>
- {/* Header */}
- <div className="space-y-2">
- <div className="flex flex-wrap items-center gap-3">
- <h1 className="text-xl font-semibold text-[var(--color-text-primary)]">
+ {/* Header. The title is the subject, so it gets the size; status and
+ trust are marks beside it, and the verbs sit in one row underneath
+ rather than crowding the heading line. */}
+ <div className="space-y-4">
+ <div className="space-y-2.5">
+ <h1 className="text-[26px] font-semibold leading-tight text-[var(--color-text-primary)]">
{stripMarkdown(decision.title)}
</h1>
- <Badge variant={STATUS_VARIANT[status] ?? "outline"}>{status}</Badge>
- {decision.verification && (
- <VerificationBadge verification={decision.verification} />
- )}
+ <div className="flex flex-wrap items-center gap-2">
+ <DecisionStatusMark status={status} />
+ {decision.verification && (
+ <VerificationBadge verification={decision.verification} />
+ )}
+ </div>
+ </div>
+
+ {/* One mono ribbon, tabular, instead of four sans sentences. Staleness
+ is a percentage here and a percentage in the table; it used to be
+ "0.42" on one surface and "42%" on the other. */}
+ <dl className="flex flex-wrap gap-x-8 gap-y-2">
+ <MetaItem label="Source" value={SOURCE_LABEL[decision.source] ?? decision.source} />
+ <MetaItem label="Confidence" value={`${Math.round(decision.confidence * 100)}%`} />
+ <MetaItem
+ label="Staleness"
+ value={
+ decision.staleness_score > 0
+ ? `${Math.round(decision.staleness_score * 100)}%`
+ : "—"
+ }
+ {...(decision.staleness_score > 0.5
+ ? { valueClassName: "text-[var(--color-error)]" }
+ : {})}
+ />
+ <MetaItem label="Recorded" value={formatDateOrDash(decision.created_at)} />
+ </dl>
+
+ <div className="flex flex-wrap items-center gap-2">
<AiPromptButton
label={status === "proposed" ? "Verify & confirm with AI" : "Verify with AI"}
onClick={() => setPromptMode("verify")}
- className="ml-auto"
/>
{status === "active" && (
<AiPromptButton
@@ -279,25 +310,27 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {
>
<FileSearch className="h-3.5 w-3.5" />
Evidence
+ {(decision.evidence_count ?? 0) > 0 && (
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">
+ {decision.evidence_count}
+ </span>
+ )}
</button>
</div>
- <div className="flex gap-4 text-sm text-[var(--color-text-tertiary)]">
- <span>Source: {decision.source}</span>
- <span>Confidence: {Math.round(decision.confidence * 100)}%</span>
- {decision.staleness_score > 0 && (
- <span className={decision.staleness_score > 0.5 ? "text-[var(--color-error)]" : ""}>
- Staleness: {decision.staleness_score.toFixed(2)}
- </span>
- )}
- <span>Created: {formatDateOrDash(decision.created_at)}</span>
- </div>
</div>
- {/* Stale warning */}
+ {/* Stale warning. A line, not a filled panel: a tinted ground plus a
+ border plus coloured text says the same thing three times, and it
+ outweighed the record it was warning about. Same argument as the
+ status marks. */}
{decision.staleness_score > 0.5 && (
- <div className="rounded-md border border-[var(--color-warning)]/30 bg-[var(--color-warning)]/10 px-4 py-3 text-sm text-[var(--color-warning)]">
- This decision may be stale — affected files have changed significantly since it was recorded.
- </div>
+ <p className="flex items-start gap-2 text-sm text-[var(--color-warning)]">
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden />
+ <span>
+ Affected files have changed significantly since this was recorded,
+ so it may no longer describe the code.
+ </span>
+ </p>
)}
{/* Evolution / lineage chain */}
@@ -310,8 +343,8 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {
/>
)}
- {/* Content sections */}
- <div className="space-y-4">
+ {/* Content sections. This is the part someone came to read. */}
+ <div className="space-y-7 border-t border-[var(--color-border-default)] pt-7">
{decision.context && <Section title="Context" text={decision.context} />}
{decision.decision && <Section title="Decision" text={decision.decision} />}
{decision.rationale && <Section title="Rationale" text={decision.rationale} />}
@@ -323,8 +356,10 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {
)}
</div>
- {/* Governance linkage — writable editor + evidence card */}
- <div className="grid gap-4 sm:grid-cols-2">
+ {/* Governance linkage. Was two bordered cards side by side; a hairline
+ and vertical rhythm group them at a fraction of the ink, and neither
+ is a discrete object you act on repeatedly. */}
+ <div className="space-y-7 border-t border-[var(--color-border-default)] pt-7">
<ModuleLinkEditor
modules={linkedModules}
files={linkedFiles}
@@ -334,11 +369,9 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {
/>
{/* The full evidence rows live in the drawer (Evidence button); this
- card answers "what happened to the governed code since?". */}
- <div className="rounded-lg border border-[var(--color-border-default)] p-4">
- <h3 className="mb-2 text-sm font-medium text-[var(--color-text-secondary)]">
- Since this decision
- </h3>
+ block answers "what happened to the governed code since?". */}
+ <div>
+ <h2 className={MICRO_LABEL + " mb-2"}>Since this decision</h2>
<div className="space-y-2 text-sm">
{decision.last_code_change && (
<p className="text-xs text-[var(--color-text-tertiary)]">
@@ -386,11 +419,12 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {
{/* Tags */}
{decision.tags.length > 0 && (
- <div className="flex flex-wrap gap-1.5">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
+ <span className={MICRO_LABEL}>Tags</span>
{decision.tags.map((tag) => (
<span
key={tag}
- className="inline-block rounded-full bg-[var(--color-bg-elevated)] px-2.5 py-0.5 text-xs font-medium text-[var(--color-text-secondary)]"
+ className="font-mono text-xs text-[var(--color-text-secondary)]"
>
{tag}
</span>
@@ -406,7 +440,10 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {
<button
onClick={() => handleStatusChange("active")}
disabled={loading}
- className="rounded-md bg-[var(--color-success)] px-3 py-1.5 text-sm font-medium text-[var(--color-text-inverse)] hover:opacity-90 disabled:opacity-50"
+ // Accent, not a filled green: green/amber/red are reserved for
+ // health readouts where they carry a band. This is the page's
+ // one primary action, which is what the accent is for.
+ className="rounded-md bg-[var(--color-accent-primary)] px-3 py-1.5 text-sm font-medium text-[var(--color-text-on-accent)] hover:opacity-90 disabled:opacity-50"
>
Confirm
</button>
@@ -505,12 +542,41 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {
);
}
+function MetaItem({
+ label,
+ value,
+ valueClassName,
+}: {
+ label: string;
+ value: string;
+ valueClassName?: string;
+}) {
+ return (
+ <div>
+ <dt className={MICRO_LABEL}>{label}</dt>
+ <dd
+ className={`mt-0.5 font-mono text-xs tabular-nums text-[var(--color-text-secondary)] ${
+ valueClassName ?? ""
+ }`}
+ >
+ {value}
+ </dd>
+ </div>
+ );
+}
+
/** Older/hosted backends can omit decision timestamps — render "—" instead of
- * "Invalid Date" for a missing or unparseable value. */
+ * "Invalid Date" for a missing or unparseable value.
+ *
+ * Uses `formatDate`, which pins the locale, rather than
+ * `toLocaleDateString()`. The latter formats against the *runtime's* locale,
+ * so the server rendered "23/06/2026" and the browser "23/6/2026" — a
+ * hydration mismatch that made React throw away and re-render the tree on
+ * every visit to a decision. */
function formatDateOrDash(iso: string | null | undefined): string {
if (!iso) return "—";
const d = new Date(iso);
- return Number.isNaN(d.getTime()) ? "—" : d.toLocaleDateString();
+ return Number.isNaN(d.getTime()) ? "—" : formatDate(d);
}
function PrevNextLink({
@@ -545,10 +611,12 @@ function PrevNextLink({
function Section({ title, text }: { title: string; text: string }) {
return (
<div>
- <h3 className="mb-1 text-sm font-medium text-[var(--color-text-secondary)]">{title}</h3>
- <div className="text-sm text-[var(--color-text-primary)] leading-relaxed prose prose-sm prose-invert max-w-none [&>p]:mb-2 [&>p:last-child]:mb-0">
- <ReactMarkdown remarkPlugins={[remarkGfm]}>{text}</ReactMarkdown>
- </div>
+ <h2 className={MICRO_LABEL + " mb-2"}>{title}</h2>
+ {/* Not `prose`: Tailwind Typography is banned on our markdown. It printed
+ literal backticks through `code::before`, and `prose-invert` is a
+ static class that cannot follow the theme, so this block was locked to
+ dark styling in light mode. `Markdown` is themed through our tokens. */}
+ <Markdown content={text} />
</div>
);
}
@@ -556,8 +624,8 @@ function Section({ title, text }: { title: string; text: string }) {
function ListSection({ title, items }: { title: string; items: string[] }) {
return (
<div>
- <h3 className="mb-1 text-sm font-medium text-[var(--color-text-secondary)]">{title}</h3>
- <ul className="list-disc space-y-0.5 pl-5 text-sm text-[var(--color-text-primary)]">
+ <h2 className={MICRO_LABEL + " mb-2"}>{title}</h2>
+ <ul className="list-disc space-y-1.5 pl-5 text-[15.5px] leading-relaxed text-[var(--color-text-primary)]">
{items.map((item, i) => (
<li key={i}>{item}</li>
))}
diff --git a/packages/ui/src/decisions/decision-governance.tsx b/packages/ui/src/decisions/decision-governance.tsx
new file mode 100644
index 000000000..209edbbab
--- /dev/null
+++ b/packages/ui/src/decisions/decision-governance.tsx
@@ -0,0 +1,242 @@
+import * as React from "react";
+import type {
+ DecisionGraph,
+ DecisionGraphNode,
+} from "@repowise-dev/types/decisions";
+
+/**
+ * What the decision graph actually knew, as lists.
+ *
+ * The page used to close with a React Flow canvas of the same payload. It lost
+ * on its *data*, the way the churn scatter did:
+ *
+ * - 373 of 376 decision edges were `supersedes` and 3 were `conflicts_with`.
+ * `refines` and `relates_to` — two of the four kinds the canvas styled —
+ * never occurred at all, so it was a one-relation diagram.
+ * - Two thirds of the nodes had no decision edge whatsoever, and rendered as
+ * a field of isolated boxes.
+ * - Of 387 distinct edge endpoints, only 66 were in the node payload. The
+ * rest pointed at decisions the canvas could not draw.
+ * - It carried 9,221 code links and dropped 6,400 of them to a per-decision
+ * cap of 8, silently, on top of a 300-node layout ceiling.
+ *
+ * A supersession is lineage, which is linear — `DecisionLineage` already
+ * renders it properly on the detail page. That leaves two things worth
+ * surfacing, and both are lists: the handful of genuine conflicts, and the
+ * files that the most decisions govern, which is the question you actually ask
+ * before touching code.
+ *
+ * The aggregation runs on the server so the 9,221-edge payload never reaches
+ * the browser. It used to be downloaded in full, to draw a diagram that threw
+ * away two thirds of it.
+ */
+
+export interface DecisionConflict {
+ aId: string;
+ /** Undefined when the id resolves to nothing the caller could name. */
+ aTitle?: string | undefined;
+ bId: string;
+ bTitle?: string | undefined;
+ /** Why the pair was flagged. Auto-detected pairs carry a similarity note. */
+ evidence?: string | undefined;
+}
+
+export interface GovernedFile {
+ path: string;
+ decisionCount: number;
+}
+
+export interface DecisionGovernanceSummary {
+ conflicts: DecisionConflict[];
+ governedFiles: GovernedFile[];
+ /** Distinct files with at least one governing decision. */
+ governedFileTotal: number;
+}
+
+/**
+ * Reduces a `DecisionGraph` to the two lists worth rendering. Pure, so the
+ * server component can call it directly and ship only the result.
+ */
+export function summarizeGovernance(
+ graph: DecisionGraph | undefined,
+ options: {
+ topFiles?: number;
+ /**
+ * Extra id -> title pairs. Conflict endpoints routinely fall outside the
+ * node payload — on a live index only 66 of 387 endpoints were in it — so
+ * the caller supplies whatever else it has loaded and resolves the rest.
+ */
+ titles?: ReadonlyMap<string, string> | undefined;
+ } = {},
+): DecisionGovernanceSummary {
+ const empty: DecisionGovernanceSummary = {
+ conflicts: [],
+ governedFiles: [],
+ governedFileTotal: 0,
+ };
+ if (!graph) return empty;
+
+ const titleById = new Map<string, string>(
+ (graph.nodes ?? []).map((n: DecisionGraphNode) => [n.id, n.title]),
+ );
+ for (const [id, title] of options.titles ?? []) titleById.set(id, title);
+
+ const seen = new Set<string>();
+ const conflicts: DecisionConflict[] = [];
+ for (const e of graph.decision_edges ?? []) {
+ if (e.kind !== "conflicts_with") continue;
+ // A conflict is symmetric; key on the unordered pair so it lists once.
+ const key = [e.src, e.dst].sort().join("|");
+ if (seen.has(key)) continue;
+ seen.add(key);
+ conflicts.push({
+ aId: e.src,
+ aTitle: titleById.get(e.src),
+ bId: e.dst,
+ bTitle: titleById.get(e.dst),
+ evidence: e.evidence ?? undefined,
+ });
+ }
+
+ const perFile = new Map<string, Set<string>>();
+ for (const e of graph.code_edges ?? []) {
+ if (e.link_type !== "file") continue;
+ const set = perFile.get(e.node_id) ?? new Set<string>();
+ set.add(e.decision_id);
+ perFile.set(e.node_id, set);
+ }
+
+ const governedFiles = [...perFile.entries()]
+ .map(([path, ids]) => ({ path, decisionCount: ids.size }))
+ .sort((a, b) => b.decisionCount - a.decisionCount || a.path.localeCompare(b.path))
+ .slice(0, options.topFiles ?? 12);
+
+ return { conflicts, governedFiles, governedFileTotal: perFile.size };
+}
+
+const MICRO_LABEL =
+ "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
+
+type LinkComponent = React.ElementType<{
+ href: string;
+ className?: string;
+ children: React.ReactNode;
+}>;
+
+export interface DecisionConflictsProps {
+ conflicts: DecisionConflict[];
+ decisionHref: (id: string) => string;
+ LinkComponent?: LinkComponent;
+}
+
+/**
+ * The only genuinely relational thing the graph carried, and the only one that
+ * needs acting on. Renders nothing when there are none — rule 10: a quiet page
+ * is a healthy page.
+ */
+export function DecisionConflicts({
+ conflicts,
+ decisionHref,
+ LinkComponent = "a",
+}: DecisionConflictsProps) {
+ // A conflict we cannot name is not worth a row. Printing the id renders a
+ // 32-character hash where a sentence should be, which tells the reader
+ // nothing and cannot be acted on — the fallback that shipped in the first
+ // cut of this component.
+ const named = conflicts.filter((c) => c.aTitle && c.bTitle);
+ if (named.length === 0) return null;
+ const Link = LinkComponent;
+
+ return (
+ <ul className="border-t border-[var(--color-border-default)]">
+ {named.map((c) => (
+ <li
+ key={`${c.aId}|${c.bId}`}
+ className="border-b border-[var(--color-border-default)] py-3"
+ >
+ <div className="flex flex-col gap-1 text-sm sm:flex-row sm:items-baseline sm:gap-2">
+ <Link
+ href={decisionHref(c.aId)}
+ className="font-medium text-[var(--color-text-primary)] hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {c.aTitle}
+ </Link>
+ <span className={MICRO_LABEL}>conflicts with</span>
+ <Link
+ href={decisionHref(c.bId)}
+ className="font-medium text-[var(--color-text-primary)] hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {c.bTitle}
+ </Link>
+ </div>
+ {c.evidence && (
+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">
+ {c.evidence}
+ </p>
+ )}
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+export interface GovernedFilesProps {
+ files: GovernedFile[];
+ fileHref?: (path: string) => string;
+ LinkComponent?: LinkComponent;
+}
+
+/**
+ * Which files carry the most decisions. This is the question the graph's
+ * 9,221 code links could answer and its canvas could not, having dropped 69%
+ * of them to stay laid out.
+ */
+export function GovernedFiles({
+ files,
+ fileHref,
+ LinkComponent = "a",
+}: GovernedFilesProps) {
+ if (files.length === 0) return null;
+ const Link = LinkComponent;
+ const max = files[0]?.decisionCount ?? 1;
+
+ return (
+ <ul className="border-t border-[var(--color-border-default)]">
+ {files.map((f) => (
+ <li
+ key={f.path}
+ className="flex items-center gap-4 border-b border-[var(--color-border-default)] py-2.5"
+ >
+ <span className="min-w-0 flex-1">
+ {fileHref ? (
+ <Link
+ href={fileHref(f.path)}
+ className="font-mono text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {f.path}
+ </Link>
+ ) : (
+ <span className="font-mono text-xs text-[var(--color-text-secondary)]">
+ {f.path}
+ </span>
+ )}
+ </span>
+ {/* Proportion bar steps the accent down toward the inset ground
+ rather than reaching for a second hue. */}
+ <span
+ aria-hidden
+ className="hidden h-1 w-24 shrink-0 overflow-hidden rounded-full bg-[var(--color-bg-inset)] sm:block"
+ >
+ <span
+ className="block h-full rounded-full bg-[var(--color-accent-primary)]"
+ style={{ width: `${Math.round((f.decisionCount / max) * 100)}%` }}
+ />
+ </span>
+ <span className="w-16 shrink-0 text-right font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ {f.decisionCount}
+ </span>
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/packages/ui/src/decisions/decision-graph-view.tsx b/packages/ui/src/decisions/decision-graph-view.tsx
deleted file mode 100644
index 823a8a02f..000000000
--- a/packages/ui/src/decisions/decision-graph-view.tsx
+++ /dev/null
@@ -1,517 +0,0 @@
-"use client";
-
-/**
- * Self-contained decision-graph diagram.
- *
- * Renders decision -> decision typed edges (supersedes / refines / relates_to /
- * conflicts_with) plus decision -> code "governs" links, laid out with the same
- * ELK layered engine the C4 view uses (`computeC4Layout`). Conflicts are
- * highlighted in red. Clicking a decision node calls `onSelectDecision`.
- *
- * Props-driven: the host fetches the `DecisionGraph` (via SWR) and passes it in.
- */
-
-import { memo, useEffect, useMemo, useState } from "react";
-import {
- Background,
- BaseEdge,
- Controls,
- EdgeLabelRenderer,
- Handle,
- Position,
- ReactFlow,
- ReactFlowProvider,
- getBezierPath,
- type Edge,
- type EdgeProps,
- type Node,
- type NodeMouseHandler,
- type NodeProps,
-} from "@xyflow/react";
-import "@xyflow/react/dist/style.css";
-import { computeC4Layout, type C4LayoutNode } from "../c4/layout/elk-c4-layout";
-import type {
- DecisionEdgeKind,
- DecisionGraph,
- DecisionGraphNode,
-} from "@repowise-dev/types/decisions";
-
-const DECISION_NODE_SIZE = { width: 200, height: 72 };
-const CODE_NODE_SIZE = { width: 180, height: 44 };
-
-// ELK's layered layout runs on the main thread; an unbounded node set (one
-// demo decision alone fans out into 160 code nodes) hangs the tab. Cap the
-// per-decision code fan-out and the total node count, and say what was
-// dropped instead of freezing.
-const MAX_CODE_LINKS_PER_DECISION = 8;
-const MAX_LAYOUT_NODES = 300;
-
-const STATUS_DOT: Record<string, string> = {
- active: "var(--color-success)",
- proposed: "var(--color-info)",
- deprecated: "var(--color-error)",
- superseded: "var(--color-text-tertiary)",
-};
-
-const EDGE_STYLE: Record<DecisionEdgeKind, { stroke: string; label: string; dashed?: boolean }> = {
- supersedes: { stroke: "var(--color-accent-secondary)", label: "supersedes" },
- refines: { stroke: "var(--color-edge-co-change)", label: "refines" },
- relates_to: { stroke: "var(--color-text-tertiary)", label: "relates to" },
- conflicts_with: { stroke: "var(--color-error)", label: "conflicts" },
-};
-
-// ---------------------------------------------------------------------------
-// Node + edge data carried through React Flow
-// ---------------------------------------------------------------------------
-
-interface DecisionNodeData extends Record<string, unknown> {
- kind: "decision";
- decision: DecisionGraphNode;
-}
-interface CodeNodeData extends Record<string, unknown> {
- kind: "code";
- label: string;
- linkType: "file" | "module";
-}
-interface DecisionEdgeData extends Record<string, unknown> {
- edgeKind?: DecisionEdgeKind;
- governs?: boolean;
-}
-
-// ---------------------------------------------------------------------------
-// Node components
-// ---------------------------------------------------------------------------
-
-const DecisionNode = memo(function DecisionNode({ data }: NodeProps) {
- const { decision } = data as DecisionNodeData;
- const dot = STATUS_DOT[decision.status] ?? STATUS_DOT.active;
- const stale = decision.staleness_score > 0.5;
- return (
- <div
- style={{
- width: DECISION_NODE_SIZE.width,
- minHeight: DECISION_NODE_SIZE.height,
- padding: "8px 10px",
- borderRadius: 8,
- border: `1px solid ${stale ? "var(--color-warning)" : "var(--color-border-default)"}`,
- background: "var(--color-bg-surface)",
- color: "var(--color-text-primary)",
- fontSize: 12,
- cursor: "pointer",
- }}
- title={decision.title}
- >
- <Handle type="target" position={Position.Top} style={{ opacity: 0 }} />
- <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
- <span style={{ width: 9, height: 9, borderRadius: 999, background: dot, flexShrink: 0 }} />
- <span style={{ fontSize: 10, textTransform: "capitalize", color: "var(--color-text-tertiary)" }}>
- {decision.status}
- {stale && " · stale"}
- </span>
- </div>
- <div
- style={{
- fontWeight: 500,
- lineHeight: 1.25,
- display: "-webkit-box",
- WebkitLineClamp: 2,
- WebkitBoxOrient: "vertical",
- overflow: "hidden",
- }}
- >
- {decision.title}
- </div>
- <Handle type="source" position={Position.Bottom} style={{ opacity: 0 }} />
- </div>
- );
-});
-
-const CodeNode = memo(function CodeNode({ data }: NodeProps) {
- const { label, linkType } = data as CodeNodeData;
- return (
- <div
- style={{
- width: CODE_NODE_SIZE.width,
- minHeight: CODE_NODE_SIZE.height,
- padding: "6px 8px",
- borderRadius: 6,
- border: "1px dashed var(--color-border-default)",
- background: "var(--color-bg-elevated)",
- color: "var(--color-text-secondary)",
- fontSize: 10,
- fontFamily: "var(--font-mono, ui-monospace, monospace)",
- }}
- title={label}
- >
- <Handle type="target" position={Position.Top} style={{ opacity: 0 }} />
- <div style={{ fontSize: 8, textTransform: "uppercase", opacity: 0.7 }}>{linkType}</div>
- <div style={{ wordBreak: "break-all", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
- {label}
- </div>
- </div>
- );
-});
-
-const nodeTypes = { decision: DecisionNode, code: CodeNode };
-
-// ---------------------------------------------------------------------------
-// Edge component
-// ---------------------------------------------------------------------------
-
-const DecisionEdge = memo(function DecisionEdge(props: EdgeProps) {
- const { id, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, data } = props;
- const ed = data as DecisionEdgeData | undefined;
- const [path, labelX, labelY] = getBezierPath({
- sourceX,
- sourceY,
- sourcePosition,
- targetX,
- targetY,
- targetPosition,
- });
-
- if (ed?.governs) {
- return (
- <BaseEdge
- id={id}
- path={path}
- style={{ stroke: "var(--color-text-tertiary)", strokeWidth: 1, strokeDasharray: "4 3" }}
- />
- );
- }
-
- const kind = ed?.edgeKind ?? "relates_to";
- const style = EDGE_STYLE[kind];
- const isConflict = kind === "conflicts_with";
-
- return (
- <>
- <BaseEdge
- id={id}
- path={path}
- style={{
- stroke: style.stroke,
- strokeWidth: isConflict ? 2.5 : 1.5,
- strokeDasharray: kind === "relates_to" ? "5 4" : undefined,
- }}
- />
- <EdgeLabelRenderer>
- <div
- style={{
- position: "absolute",
- transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,
- background: isConflict ? "var(--color-error)" : "var(--color-bg-overlay)",
- color: isConflict ? "white" : "var(--color-text-primary)",
- padding: "1px 6px",
- borderRadius: 4,
- fontSize: 11,
- fontWeight: 600,
- pointerEvents: "none",
- border: `1px solid ${isConflict ? "var(--color-error)" : "var(--color-border-default)"}`,
- whiteSpace: "nowrap",
- }}
- className="nodrag nopan"
- >
- {style.label}
- </div>
- </EdgeLabelRenderer>
- </>
- );
-});
-
-const edgeTypes = { decision: DecisionEdge };
-
-// ---------------------------------------------------------------------------
-// Layout hook
-// ---------------------------------------------------------------------------
-
-interface LayoutResult {
- nodes: Node[];
- edges: Edge[];
- loading: boolean;
- /** Human-readable note when the graph was capped for rendering. */
- truncationNote: string | null;
-}
-
-function useDecisionGraphLayout(graph: DecisionGraph | undefined, showCode: boolean): LayoutResult {
- const [result, setResult] = useState<LayoutResult>({
- nodes: [],
- edges: [],
- loading: false,
- truncationNote: null,
- });
-
- // Stable identity key so the effect only re-runs when content changes.
- const graphKey = useMemo(() => {
- if (!graph) return "";
- return JSON.stringify({
- n: graph.nodes.map((n) => n.id),
- de: graph.decision_edges.map((e) => [e.src, e.dst, e.kind]),
- ce: graph.code_edges.map((e) => [e.decision_id, e.node_id]),
- showCode,
- });
- }, [graph, showCode]);
-
- useEffect(() => {
- if (!graph || graph.nodes.length === 0) {
- setResult({ nodes: [], edges: [], loading: false, truncationNote: null });
- return;
- }
- let cancelled = false;
- setResult((r) => ({ ...r, loading: true }));
-
- // ---- Bound the graph before ELK ever sees it ----
- // Decisions first: if they alone exceed the ceiling, keep the highest-
- // impact ones (impact = how much code a decision governs).
- const codeLinkCounts = new Map<string, number>();
- for (const e of graph.code_edges) {
- codeLinkCounts.set(e.decision_id, (codeLinkCounts.get(e.decision_id) ?? 0) + 1);
- }
- let decisionNodes = graph.nodes;
- let droppedDecisions = 0;
- if (decisionNodes.length > MAX_LAYOUT_NODES) {
- decisionNodes = [...decisionNodes]
- .sort((a, b) => (codeLinkCounts.get(b.id) ?? 0) - (codeLinkCounts.get(a.id) ?? 0))
- .slice(0, MAX_LAYOUT_NODES);
- droppedDecisions = graph.nodes.length - decisionNodes.length;
- }
- const decisionIds = new Set(decisionNodes.map((n) => n.id));
-
- // Code links: cap the fan-out per decision, then stop adding new code
- // nodes once the total node budget is spent.
- const allCodeEdges = showCode ? graph.code_edges : [];
- const perDecision = new Map<string, number>();
- const codeNodeIds = new Map<string, "file" | "module">();
- const codeEdges: typeof allCodeEdges = [];
- let droppedCodeLinks = 0;
- for (const e of allCodeEdges) {
- if (!decisionIds.has(e.decision_id)) continue;
- const used = perDecision.get(e.decision_id) ?? 0;
- const isNewNode = !codeNodeIds.has(e.node_id);
- if (
- used >= MAX_CODE_LINKS_PER_DECISION ||
- (isNewNode && decisionIds.size + codeNodeIds.size >= MAX_LAYOUT_NODES)
- ) {
- droppedCodeLinks++;
- continue;
- }
- perDecision.set(e.decision_id, used + 1);
- if (isNewNode) codeNodeIds.set(e.node_id, e.link_type);
- codeEdges.push(e);
- }
-
- const truncationNote =
- droppedDecisions > 0 || droppedCodeLinks > 0
- ? `Too large to render fully — showing the top ${decisionNodes.length} decisions by impact` +
- (droppedCodeLinks > 0
- ? ` and up to ${MAX_CODE_LINKS_PER_DECISION} code links each (${droppedCodeLinks} links hidden).`
- : ".")
- : null;
-
- const layoutNodes: C4LayoutNode[] = [
- ...decisionNodes.map((n) => ({ id: n.id, ...DECISION_NODE_SIZE })),
- ...[...codeNodeIds.keys()].map((id) => ({ id: `code:${id}`, ...CODE_NODE_SIZE })),
- ];
-
- const decisionEdges = graph.decision_edges.filter(
- (e) => decisionIds.has(e.src) && decisionIds.has(e.dst),
- );
- const layoutEdges = [
- ...decisionEdges.map((e, i) => ({ id: `d${i}:${e.src}->${e.dst}`, source: e.src, target: e.dst })),
- ...codeEdges
- .filter((e) => decisionIds.has(e.decision_id) && codeNodeIds.has(e.node_id))
- .map((e, i) => ({ id: `c${i}:${e.decision_id}->${e.node_id}`, source: e.decision_id, target: `code:${e.node_id}` })),
- ];
-
- void computeC4Layout(layoutNodes, layoutEdges).then((positions) => {
- if (cancelled) return;
- const nodes: Node[] = [
- ...decisionNodes.map((n) => {
- const pos = positions.get(n.id) ?? { x: 0, y: 0 };
- return {
- id: n.id,
- type: "decision",
- position: { x: pos.x, y: pos.y },
- data: { kind: "decision", decision: n } satisfies DecisionNodeData,
- ...DECISION_NODE_SIZE,
- } as Node;
- }),
- ...[...codeNodeIds.entries()].map(([id, linkType]) => {
- const pos = positions.get(`code:${id}`) ?? { x: 0, y: 0 };
- return {
- id: `code:${id}`,
- type: "code",
- position: { x: pos.x, y: pos.y },
- data: { kind: "code", label: id, linkType } satisfies CodeNodeData,
- ...CODE_NODE_SIZE,
- } as Node;
- }),
- ];
-
- const edges: Edge[] = [
- ...decisionEdges.map((e, i) => ({
- id: `d${i}:${e.src}->${e.dst}`,
- source: e.src,
- target: e.dst,
- type: "decision",
- data: { edgeKind: e.kind } satisfies DecisionEdgeData,
- })),
- ...codeEdges
- .filter((e) => decisionIds.has(e.decision_id) && codeNodeIds.has(e.node_id))
- .map((e, i) => ({
- id: `c${i}:${e.decision_id}->${e.node_id}`,
- source: e.decision_id,
- target: `code:${e.node_id}`,
- type: "decision",
- data: { governs: true } satisfies DecisionEdgeData,
- })),
- ];
-
- setResult({ nodes, edges, loading: false, truncationNote });
- });
-
- return () => {
- cancelled = true;
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [graphKey]);
-
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// Public component
-// ---------------------------------------------------------------------------
-
-export interface DecisionGraphViewProps {
- graph: DecisionGraph | undefined;
- isLoading?: boolean;
- onSelectDecision?: (id: string) => void;
-}
-
-export function DecisionGraphView(props: DecisionGraphViewProps) {
- return (
- <ReactFlowProvider>
- <DecisionGraphViewInner {...props} />
- </ReactFlowProvider>
- );
-}
-
-function DecisionGraphViewInner({ graph, isLoading, onSelectDecision }: DecisionGraphViewProps) {
- const [showCode, setShowCode] = useState(true);
- const { nodes, edges, loading, truncationNote } = useDecisionGraphLayout(graph, showCode);
-
- const handleNodeClick: NodeMouseHandler = (_, node) => {
- if (node.type === "decision") onSelectDecision?.(node.id);
- };
-
- const busy = isLoading || loading;
- const empty = !busy && nodes.length === 0;
-
- return (
- <div
- style={{
- position: "relative",
- width: "100%",
- height: "100%",
- minHeight: 420,
- display: "flex",
- flexDirection: "column",
- background: "var(--color-bg-canvas)",
- border: "1px solid var(--color-border-default)",
- borderRadius: 8,
- overflow: "hidden",
- }}
- >
- <div
- style={{
- display: "flex",
- alignItems: "center",
- gap: 12,
- padding: "6px 10px",
- borderBottom: "1px solid var(--color-border-default)",
- fontSize: 11,
- color: "var(--color-text-secondary)",
- }}
- >
- <Legend color={EDGE_STYLE.supersedes.stroke} label="supersedes" />
- <Legend color={EDGE_STYLE.refines.stroke} label="refines" />
- <Legend color={EDGE_STYLE.relates_to.stroke} label="relates to" />
- <Legend color={EDGE_STYLE.conflicts_with.stroke} label="conflicts" />
- <label style={{ marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 6, cursor: "pointer" }}>
- <input type="checkbox" checked={showCode} onChange={(e) => setShowCode(e.target.checked)} />
- Code links
- </label>
- </div>
-
- {truncationNote && (
- <div
- role="status"
- style={{
- padding: "4px 10px",
- borderBottom: "1px solid var(--color-border-default)",
- fontSize: 11,
- color: "var(--color-warning)",
- }}
- >
- {truncationNote}
- </div>
- )}
-
- <div style={{ position: "relative", flex: 1, minHeight: 0 }}>
- {busy && nodes.length === 0 && <Centered text="Laying out decision graph…" />}
- {empty && <Centered text="No decision relationships to show." />}
- <ReactFlow
- nodes={nodes}
- edges={edges}
- nodeTypes={nodeTypes}
- edgeTypes={edgeTypes}
- onNodeClick={handleNodeClick}
- fitView
- fitViewOptions={{ padding: 0.18 }}
- minZoom={0.2}
- maxZoom={2.5}
- proOptions={{ hideAttribution: true }}
- nodesDraggable={false}
- nodesConnectable={false}
- >
- {/* Theme-neutral dot grid — React Flow renders this as an SVG fill
- attribute, which can't resolve var(); a low-alpha gray reads on
- both the warm-paper and charcoal canvases. */}
- <Background gap={28} size={1} color="rgba(140,127,136,0.18)" />
- <Controls showInteractive={false} />
- </ReactFlow>
- </div>
- </div>
- );
-}
-
-function Legend({ color, label }: { color: string; label: string }) {
- return (
- <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
- <span style={{ width: 14, height: 2, background: color, display: "inline-block" }} />
- {label}
- </span>
- );
-}
-
-function Centered({ text }: { text: string }) {
- return (
- <div
- role="status"
- style={{
- position: "absolute",
- inset: 0,
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- color: "var(--color-text-tertiary)",
- fontSize: 13,
- pointerEvents: "none",
- zIndex: 3,
- }}
- >
- {text}
- </div>
- );
-}
diff --git a/packages/ui/src/decisions/decision-status-mark.tsx b/packages/ui/src/decisions/decision-status-mark.tsx
new file mode 100644
index 000000000..78163e215
--- /dev/null
+++ b/packages/ui/src/decisions/decision-status-mark.tsx
@@ -0,0 +1,46 @@
+import * as React from "react";
+import { cn } from "../lib/cn";
+import type { DecisionStatus } from "@repowise-dev/types/decisions";
+
+const STATUS_COLOR: Record<string, string> = {
+ active: "var(--color-success)",
+ proposed: "var(--color-accent-primary)",
+ deprecated: "var(--color-error)",
+ superseded: "var(--color-text-tertiary)",
+};
+
+export interface DecisionStatusMarkProps {
+ status: DecisionStatus | string;
+ className?: string;
+}
+
+/**
+ * A decision's status as a dot plus the word.
+ *
+ * Replaces the filled `Badge`. A tinted ground, a border *and* coloured text on
+ * a token that repeats once per row tiles into stripes down a table and
+ * outweighs the decision titles it belongs to — the same argument that replaced
+ * `SEVERITY_CHIP` with `SeverityMark`.
+ *
+ * The word stays. `proposed` and `active` are the pair a reader must separate
+ * to use this page at all, and colour alone does not separate them for everyone.
+ */
+export function DecisionStatusMark({ status, className }: DecisionStatusMarkProps) {
+ const color = STATUS_COLOR[status] ?? "var(--color-text-tertiary)";
+ return (
+ <span
+ className={cn(
+ "inline-flex items-center gap-1.5 whitespace-nowrap text-xs",
+ className,
+ )}
+ style={{ color }}
+ >
+ <span
+ aria-hidden
+ className="h-1.5 w-1.5 shrink-0 rounded-full"
+ style={{ backgroundColor: color }}
+ />
+ {status}
+ </span>
+ );
+}
diff --git a/packages/ui/src/decisions/decisions-table.tsx b/packages/ui/src/decisions/decisions-table.tsx
index c8db10480..7d8c0a799 100644
--- a/packages/ui/src/decisions/decisions-table.tsx
+++ b/packages/ui/src/decisions/decisions-table.tsx
@@ -1,7 +1,6 @@
"use client";
import * as React from "react";
-import { Badge } from "../ui/badge";
import { ApiError } from "../shared/api-error";
import { EmptyState } from "../shared/empty-state";
import {
@@ -9,6 +8,7 @@ import {
type ResponsiveColumn,
} from "../shared/responsive-table";
import { VerificationBadge } from "./verification-badge";
+import { DecisionStatusMark } from "./decision-status-mark";
import { stripMarkdown } from "../lib/format";
import type {
DecisionRecord,
@@ -17,18 +17,19 @@ import type {
DecisionScope,
} from "@repowise-dev/types/decisions";
-const STATUS_VARIANT: Record<string, "default" | "fresh" | "stale" | "outdated" | "outline" | "accent"> = {
- active: "fresh",
- proposed: "accent",
- deprecated: "outdated",
- superseded: "outline",
-};
-
+// The engine emits more sources than the four the type union names — a live
+// index carries comment / pr / adr / changelog / session as well. Unmapped
+// values used to fall through raw, so one column mixed "Docs" with "pr".
const SOURCE_LABEL: Record<string, string> = {
- inline_marker: "Inline",
- git_archaeology: "Git",
+ inline_marker: "Marker",
+ git_archaeology: "Git history",
readme_mining: "Docs",
cli: "Manual",
+ comment: "Comment",
+ pr: "Pull request",
+ adr: "ADR",
+ changelog: "Changelog",
+ session: "Session",
};
const SCOPE_LABEL: Record<string, string> = {
@@ -138,7 +139,7 @@ export function DecisionsTable({
key: "status",
header: "Status",
priority: 1,
- render: (d) => <Badge variant={STATUS_VARIANT[d.status] ?? "outline"}>{d.status}</Badge>,
+ render: (d) => <DecisionStatusMark status={d.status} />,
},
{
key: "source",
@@ -153,7 +154,9 @@ export function DecisionsTable({
priority: 3,
render: (d) =>
d.scope ? (
- <Badge variant="outline">{SCOPE_LABEL[d.scope] ?? d.scope}</Badge>
+ <span className="text-[var(--color-text-secondary)]">
+ {SCOPE_LABEL[d.scope] ?? d.scope}
+ </span>
) : (
<span className="text-[var(--color-text-tertiary)]">—</span>
),
@@ -183,18 +186,18 @@ export function DecisionsTable({
header: "Tags",
priority: 3,
render: (d) => (
- <div className="flex flex-wrap gap-1">
+ <div className="flex flex-wrap gap-x-2 gap-y-0.5">
{d.tags.slice(0, 3).map((tag) => (
<span
key={tag}
- className="inline-block rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs text-[var(--color-text-tertiary)]"
+ className="font-mono text-[11px] text-[var(--color-text-tertiary)]"
>
{tag}
</span>
))}
{d.tags.length > 3 && (
<span
- className="inline-block rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs text-[var(--color-text-tertiary)]"
+ className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]"
title={d.tags.slice(3).join(", ")}
>
+{d.tags.length - 3}
diff --git a/packages/ui/src/decisions/index.ts b/packages/ui/src/decisions/index.ts
index 676704866..470e32981 100644
--- a/packages/ui/src/decisions/index.ts
+++ b/packages/ui/src/decisions/index.ts
@@ -1,8 +1,9 @@
export * from "./decisions-table";
export * from "./module-link-editor";
export * from "./verification-badge";
+export * from "./decision-status-mark";
export * from "./decision-evidence-drawer";
export * from "./decision-lineage";
-export * from "./decision-graph-view";
export * from "./decision-detail-adapter";
export * from "./decision-detail";
+export * from "./decision-governance";
diff --git a/packages/ui/src/decisions/module-link-editor.tsx b/packages/ui/src/decisions/module-link-editor.tsx
index 1f134b53c..60b3d354a 100644
--- a/packages/ui/src/decisions/module-link-editor.tsx
+++ b/packages/ui/src/decisions/module-link-editor.tsx
@@ -141,7 +141,7 @@ export function ModuleLinkEditor({
key={s}
type="button"
onClick={() => addModule(s)}
- className="block w-full px-3 py-1.5 text-left font-mono text-xs text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"
+ className="block w-full px-3 py-1.5 text-left font-mono text-xs text-[var(--color-text-primary)] hover:bg-[var(--color-bg-wash-hover)]"
>
{s}
</button>
@@ -247,7 +247,7 @@ function Field({ icon, label, chips, onRemove, disabled, children }: FieldProps)
type="button"
onClick={() => onRemove(c)}
disabled={disabled}
- className="rounded-full p-0.5 hover:bg-[var(--color-bg-hover)] disabled:cursor-not-allowed disabled:opacity-50"
+ className="rounded-full p-0.5 hover:bg-[var(--color-bg-wash-hover)] disabled:cursor-not-allowed disabled:opacity-50"
aria-label={`Remove ${c}`}
>
<X className="h-2.5 w-2.5" />
diff --git a/packages/ui/src/decisions/verification-badge.tsx b/packages/ui/src/decisions/verification-badge.tsx
index 679fbf776..80a2f43c7 100644
--- a/packages/ui/src/decisions/verification-badge.tsx
+++ b/packages/ui/src/decisions/verification-badge.tsx
@@ -2,28 +2,28 @@
import * as React from "react";
import { ShieldCheck, ShieldAlert, ShieldQuestion } from "lucide-react";
-import { Badge } from "../ui/badge";
+import { cn } from "../lib/cn";
import type { DecisionVerification } from "@repowise-dev/types/decisions";
const VERIFICATION_CONFIG: Record<
DecisionVerification,
- { label: string; variant: "fresh" | "stale" | "default"; Icon: typeof ShieldCheck; title: string }
+ { label: string; color: string; Icon: typeof ShieldCheck; title: string }
> = {
exact: {
label: "Verified quote",
- variant: "fresh",
+ color: "var(--color-success)",
Icon: ShieldCheck,
title: "The source quote was found verbatim in the cited source.",
},
fuzzy: {
label: "Fuzzy match",
- variant: "stale",
+ color: "var(--color-warning)",
Icon: ShieldAlert,
title: "A near-match of the quote was located in the source.",
},
unverified: {
label: "Unverified",
- variant: "default",
+ color: "var(--color-text-tertiary)",
Icon: ShieldQuestion,
title: "The quote could not be located in the source — treat with care.",
},
@@ -37,18 +37,26 @@ export interface VerificationBadgeProps {
}
/**
- * Small trust badge for a decision/evidence row. Surfaces the anti-hallucination
- * verification tier (exact / fuzzy / unverified) so users can gauge how grounded
- * a decision's supporting evidence is.
+ * The anti-hallucination verification tier (exact / fuzzy / unverified) for a
+ * decision or evidence row.
+ *
+ * A mark, not a filled badge. This repeats once per row, and a tinted ground
+ * plus a border plus coloured text on a per-row token tiles into stripes down
+ * the table that outweigh the decision titles beside them — the argument that
+ * retired `SEVERITY_CHIP`. The icon already carries the tier; the ground was
+ * saying it a second time.
*/
export function VerificationBadge({ verification, iconOnly, className }: VerificationBadgeProps) {
const config = VERIFICATION_CONFIG[verification] ?? VERIFICATION_CONFIG.unverified;
- const { label, variant, Icon, title } = config;
+ const { label, color, Icon, title } = config;
return (
- <Badge variant={variant} className={className} title={title}>
- <Icon className="h-3 w-3" aria-hidden />
- {!iconOnly && <span>{label}</span>}
- {iconOnly && <span className="sr-only">{label}</span>}
- </Badge>
+ <span
+ className={cn("inline-flex items-center gap-1.5 text-xs", className)}
+ style={{ color }}
+ title={title}
+ >
+ <Icon className="h-3.5 w-3.5 shrink-0" aria-hidden />
+ {iconOnly ? <span className="sr-only">{label}</span> : <span>{label}</span>}
+ </span>
);
}
diff --git a/packages/ui/src/files/file-health-tab.tsx b/packages/ui/src/files/file-health-tab.tsx
index 7779d48bd..ed40f8ef8 100644
--- a/packages/ui/src/files/file-health-tab.tsx
+++ b/packages/ui/src/files/file-health-tab.tsx
@@ -228,7 +228,7 @@ export function FileHealthTab({
className={`rounded border px-1.5 py-0.5 text-[10px] transition-colors ${
status === opt.value
? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"
- : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"
+ : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-hover)]"
}`}
>
{opt.label}
diff --git a/packages/ui/src/files/files-treemap.tsx b/packages/ui/src/files/files-treemap.tsx
index 114a79656..5940e34a7 100644
--- a/packages/ui/src/files/files-treemap.tsx
+++ b/packages/ui/src/files/files-treemap.tsx
@@ -255,7 +255,7 @@ export function FilesTreemap({
fill={fill(c)}
opacity={c.isFolder ? 0.55 : 0.85}
rx={3}
- stroke={c.isFolder ? "var(--color-border-strong)" : "none"}
+ stroke={c.isFolder ? "var(--color-border-hover)" : "none"}
strokeWidth={c.isFolder ? 1 : 0}
className="transition-opacity hover:opacity-100"
/>
diff --git a/packages/ui/src/git/hotspot-table.tsx b/packages/ui/src/git/hotspot-table.tsx
index 6bdf6c088..aaa9c6cce 100644
--- a/packages/ui/src/git/hotspot-table.tsx
+++ b/packages/ui/src/git/hotspot-table.tsx
@@ -482,7 +482,7 @@ export function HotspotTable({
</td>
</tr>
{expandable && isExpanded && (
- <tr className="border-b border-[var(--color-table-divider)] bg-[var(--color-bg-subtle)] last:border-0">
+ <tr className="border-b border-[var(--color-table-divider)] bg-[var(--color-bg-wash)] last:border-0">
<td className="px-1" />
<td colSpan={hasFixData ? 10 : 9} className="px-3 py-3">
{renderExpandedRow!(h)}
diff --git a/packages/ui/src/graph/graph-doc-panel.tsx b/packages/ui/src/graph/graph-doc-panel.tsx
index 49208d078..7c88b6a12 100644
--- a/packages/ui/src/graph/graph-doc-panel.tsx
+++ b/packages/ui/src/graph/graph-doc-panel.tsx
@@ -12,7 +12,7 @@ import {
} from "lucide-react";
import { Button } from "../ui/button";
import { Badge } from "../ui/badge";
-import { ChatMarkdown } from "../chat/chat-markdown";
+import { Markdown } from "../shared/markdown";
import { ConfidenceBadge } from "../wiki/confidence-badge";
import { formatRelativeTime } from "../lib/format";
import type { DocPage } from "@repowise-dev/types/docs";
@@ -128,8 +128,8 @@ export function GraphDocPanel({
{page && !isLoading && (
<div className="px-4 py-4">
- <article className="prose-chat text-xs">
- <ChatMarkdown content={page.content} />
+ <article>
+ <Markdown content={page.content} density="compact" />
</article>
</div>
)}
diff --git a/packages/ui/src/health/ai-prompt-modal.tsx b/packages/ui/src/health/ai-prompt-modal.tsx
index a3694e39e..c65e617a3 100644
--- a/packages/ui/src/health/ai-prompt-modal.tsx
+++ b/packages/ui/src/health/ai-prompt-modal.tsx
@@ -130,7 +130,7 @@ export function AiPromptModal({
"rounded-md border px-3 py-2 text-left transition-colors " +
(active
? "border-[var(--color-accent-primary)] bg-[var(--color-accent-muted)]"
- : "border-[var(--color-border-default)] hover:border-[var(--color-border-strong)] hover:bg-[var(--color-bg-elevated)]")
+ : "border-[var(--color-border-default)] hover:border-[var(--color-border-hover)] hover:bg-[var(--color-bg-elevated)]")
}
title={f.hint}
>
@@ -149,7 +149,7 @@ export function AiPromptModal({
</div>
</div>
- <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-muted)] max-h-[420px] overflow-y-auto">
+ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-inset)] max-h-[420px] overflow-y-auto">
<pre className="px-3 py-2 text-[11.5px] font-mono text-[var(--color-text-primary)] whitespace-pre-wrap break-words">
{prompt}
</pre>
diff --git a/packages/ui/src/health/code-health-controls.tsx b/packages/ui/src/health/code-health-controls.tsx
index 40a5d0597..297589f2b 100644
--- a/packages/ui/src/health/code-health-controls.tsx
+++ b/packages/ui/src/health/code-health-controls.tsx
@@ -53,7 +53,7 @@ export function FilterChip({
"text-xs rounded-md px-2 py-1 border transition-colors",
active
? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)] border-[var(--color-accent-primary)]/50"
- : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]",
+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-hover)]",
)}
>
{children}
diff --git a/packages/ui/src/health/coverage-bar.tsx b/packages/ui/src/health/coverage-bar.tsx
index 6ffd47eb5..d586ce3fb 100644
--- a/packages/ui/src/health/coverage-bar.tsx
+++ b/packages/ui/src/health/coverage-bar.tsx
@@ -13,7 +13,7 @@ export function CoverageBar({ value, label, size = "md" }: CoverageBarProps) {
return (
<div className="flex items-center gap-2">
<div
- className={`relative flex-1 ${h} rounded-full bg-[var(--color-bg-muted)] overflow-hidden`}
+ className={`relative flex-1 ${h} rounded-full bg-[var(--color-bg-inset)] overflow-hidden`}
>
{has && (
<div
diff --git a/packages/ui/src/health/coverage-lede.tsx b/packages/ui/src/health/coverage-lede.tsx
index 157261d14..d6a104a9f 100644
--- a/packages/ui/src/health/coverage-lede.tsx
+++ b/packages/ui/src/health/coverage-lede.tsx
@@ -169,7 +169,7 @@ function BandSplit({
}) {
return (
<div className="space-y-1.5">
- <div className="flex h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-muted)]">
+ <div className="flex h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
{split.map((b) => (
<div
key={b.key}
diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsx
index 09e5906ee..e007ea026 100644
--- a/packages/ui/src/health/coverage-view.tsx
+++ b/packages/ui/src/health/coverage-view.tsx
@@ -399,7 +399,7 @@ function CoverageBody({
}}
placeholder="Filter path…"
aria-label="Filter files by path"
- className="w-48 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-xs focus:border-[var(--color-border-strong)] focus:outline-none sm:w-56"
+ className="w-48 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-xs focus:border-[var(--color-border-hover)] focus:outline-none sm:w-56"
/>
}
>
@@ -460,7 +460,7 @@ function NoCoverageState() {
actually costs something, and rolls the numbers up per directory. Nothing is
inferred: we read the lines your tests really executed.
</p>
- <pre className="w-fit overflow-x-auto rounded-md bg-[var(--color-bg-muted)] px-3 py-2 font-mono text-xs text-[var(--color-text-primary)]">
+ <pre className="w-fit overflow-x-auto rounded-md bg-[var(--color-bg-inset)] px-3 py-2 font-mono text-xs text-[var(--color-text-primary)]">
pytest --cov --cov-report=lcov{"\n"}
repowise coverage add coverage.lcov
</pre>
diff --git a/packages/ui/src/health/findings-view.tsx b/packages/ui/src/health/findings-view.tsx
index 26f5f31bb..9135907b9 100644
--- a/packages/ui/src/health/findings-view.tsx
+++ b/packages/ui/src/health/findings-view.tsx
@@ -407,7 +407,7 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
setOffset(0);
}}
placeholder="Filter path…"
- className="text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"
+ className="text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-hover)]"
/>
</div>
<FilterChip active={onlyHotspots} onClick={() => { setOnlyHotspots((v) => !v); setOffset(0); }}>
diff --git a/packages/ui/src/health/health-distribution-bar.tsx b/packages/ui/src/health/health-distribution-bar.tsx
index b451aa2f9..9cf4215a8 100644
--- a/packages/ui/src/health/health-distribution-bar.tsx
+++ b/packages/ui/src/health/health-distribution-bar.tsx
@@ -46,7 +46,7 @@ export function HealthDistributionBar({
return (
<div className="space-y-1.5">
<div
- className={`flex w-full ${h} overflow-hidden rounded-full bg-[var(--color-bg-muted)]`}
+ className={`flex w-full ${h} overflow-hidden rounded-full bg-[var(--color-bg-inset)]`}
title={ORDER.map(
(b) => `${BAND_LABEL[b]} ${distribution.bands[b].pct}%`,
).join(" · ")}
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index c60980c9b..a20e85a68 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -225,7 +225,7 @@ export function HealthFileDrawer({
className={`rounded border px-1.5 py-0.5 text-[10px] transition-colors ${
current === opt.value
? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"
- : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"
+ : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-hover)]"
}`}
>
{opt.label}
diff --git a/packages/ui/src/health/kpi-cards.tsx b/packages/ui/src/health/kpi-cards.tsx
index 6507aa460..ff8dad398 100644
--- a/packages/ui/src/health/kpi-cards.tsx
+++ b/packages/ui/src/health/kpi-cards.tsx
@@ -301,7 +301,7 @@ function TileShell({
"relative flex w-full flex-col rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4 text-left transition-colors";
if (onClick) {
return (
- <div className={`${cls} hover:border-[var(--color-border-strong)]`}>
+ <div className={`${cls} hover:border-[var(--color-border-hover)]`}>
{children}
<button
type="button"
diff --git a/packages/ui/src/health/module-coverage-list.tsx b/packages/ui/src/health/module-coverage-list.tsx
index 76df4755d..65834a9a9 100644
--- a/packages/ui/src/health/module-coverage-list.tsx
+++ b/packages/ui/src/health/module-coverage-list.tsx
@@ -111,7 +111,7 @@ export function ModuleCoverageList({ modules, onSelectModule }: ModuleCoverageLi
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Filter modules…"
- className="w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] py-1.5 pl-7 pr-2 text-xs focus:border-[var(--color-border-strong)] focus:outline-none"
+ className="w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] py-1.5 pl-7 pr-2 text-xs focus:border-[var(--color-border-hover)] focus:outline-none"
/>
</div>
@@ -144,7 +144,7 @@ export function ModuleCoverageList({ modules, onSelectModule }: ModuleCoverageLi
</button>
{expanded ? (
- <div className="divide-y divide-[var(--color-table-divider)] border-t border-[var(--color-table-divider)] bg-[var(--color-bg-muted)]/30">
+ <div className="divide-y divide-[var(--color-table-divider)] border-t border-[var(--color-table-divider)] bg-[var(--color-bg-inset)]/30">
{g.children.map((c) => {
const cPct = c.total_lines > 0 ? c.line_coverage_pct : null;
return (
diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsx
index a60fabd5c..2372ae07b 100644
--- a/packages/ui/src/health/refactoring-card.tsx
+++ b/packages/ui/src/health/refactoring-card.tsx
@@ -228,7 +228,7 @@ function StatusButton({
className={`text-[10px] rounded px-1.5 py-0.5 border transition-colors ${
isActive
? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)] border-[var(--color-accent-primary)]/50"
- : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"
+ : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-hover)]"
}`}
>
{label}
diff --git a/packages/ui/src/health/score-breakdown.tsx b/packages/ui/src/health/score-breakdown.tsx
index ebc906bfb..e1aab5b78 100644
--- a/packages/ui/src/health/score-breakdown.tsx
+++ b/packages/ui/src/health/score-breakdown.tsx
@@ -102,7 +102,7 @@ export function ScoreBreakdown({
{c.capped ? <span className="ml-1 text-[var(--color-warning)]" title="Raw deductions exceeded the cap; only the cap was subtracted.">(capped)</span> : null}
</span>
</div>
- <div className="mt-1.5 h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-muted)]">
+ <div className="mt-1.5 h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
<div
className={
cap != null
diff --git a/packages/ui/src/health/severity-distribution.tsx b/packages/ui/src/health/severity-distribution.tsx
index d4ae9afd5..303bb590f 100644
--- a/packages/ui/src/health/severity-distribution.tsx
+++ b/packages/ui/src/health/severity-distribution.tsx
@@ -32,7 +32,7 @@ export function SeverityDistribution({
return (
<div className="space-y-1.5">
<div
- className={`flex w-full ${h} overflow-hidden rounded-full bg-[var(--color-bg-muted)]`}
+ className={`flex w-full ${h} overflow-hidden rounded-full bg-[var(--color-bg-inset)]`}
title={ORDER.map((s) => `${SEVERITY_LABEL[s]} ${breakdown[s]}`).join(" · ")}
>
{ORDER.map((s) => {
diff --git a/packages/ui/src/health/triage-view.tsx b/packages/ui/src/health/triage-view.tsx
index 822ea9244..7d56c6ddb 100644
--- a/packages/ui/src/health/triage-view.tsx
+++ b/packages/ui/src/health/triage-view.tsx
@@ -225,7 +225,7 @@ export function TriageView({
onChange={(e) => setMapQuery(e.target.value)}
placeholder="Find a file in the map…"
aria-label="Find a file in the map"
- className="w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] py-1.5 pl-7 pr-2 text-xs focus:border-[var(--color-border-strong)] focus:outline-none"
+ className="w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] py-1.5 pl-7 pr-2 text-xs focus:border-[var(--color-border-hover)] focus:outline-none"
/>
</div>
diff --git a/packages/ui/src/overview/section.tsx b/packages/ui/src/overview/section.tsx
index 0825fe6ca..788d8d35f 100644
--- a/packages/ui/src/overview/section.tsx
+++ b/packages/ui/src/overview/section.tsx
@@ -11,6 +11,8 @@ export interface OverviewSectionProps {
/** Drop the top hairline — for the first section under a header that already
* closes with one. */
flush?: boolean;
+ /** Anchor target, for deep links that jump to one section of a page. */
+ id?: string;
className?: string;
children: React.ReactNode;
}
@@ -33,12 +35,16 @@ export function OverviewSection({
description,
action,
flush = false,
+ id,
className,
children,
}: OverviewSectionProps) {
return (
<section
+ {...(id ? { id } : {})}
+ // Deep-linked sections must not land under a sticky header.
className={cn(
+ id && "scroll-mt-24",
"flex flex-col gap-3",
!flush && "border-t border-[var(--color-border-default)] pt-6 sm:pt-8",
className,
diff --git a/packages/ui/src/refactoring/generate-code-panel.tsx b/packages/ui/src/refactoring/generate-code-panel.tsx
index cf213b559..aa0751113 100644
--- a/packages/ui/src/refactoring/generate-code-panel.tsx
+++ b/packages/ui/src/refactoring/generate-code-panel.tsx
@@ -150,7 +150,7 @@ function GeneratedResult({
<button
type="button"
onClick={onRegenerate}
- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2 py-1 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-strong)] hover:text-[var(--color-text-primary)]"
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2 py-1 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)]"
title="Generate again (bypasses the cache on the server only if the plan changed)"
>
<RotateCw className="h-3.5 w-3.5" />
@@ -192,7 +192,7 @@ function CopyButton({ text }: { text: string }) {
type="button"
onClick={copy}
disabled={!text}
- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2 py-1 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-strong)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2 py-1 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
>
{copied ? <Check className="h-3.5 w-3.5 text-[var(--color-success)]" /> : <Copy className="h-3.5 w-3.5" />}
{copied ? "Copied" : "Copy diff"}
diff --git a/packages/ui/src/refactoring/refactoring-board.tsx b/packages/ui/src/refactoring/refactoring-board.tsx
index a3c028f30..2f1adf53c 100644
--- a/packages/ui/src/refactoring/refactoring-board.tsx
+++ b/packages/ui/src/refactoring/refactoring-board.tsx
@@ -297,7 +297,7 @@ export function RefactoringBoard({
<button
type="button"
onClick={() => setVisibleCount((n) => n + PAGE_SIZE)}
- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] px-4 py-2 text-sm font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-strong)] hover:text-[var(--color-text-primary)]"
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] px-4 py-2 text-sm font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)]"
>
Show {Math.min(PAGE_SIZE, processed.length - visibleCount)} more
<span className="text-[var(--color-text-tertiary)]">
@@ -340,7 +340,7 @@ function FilterChip({
className={`rounded-full border px-2.5 py-0.5 text-xs font-medium transition-colors ${
active
? "border-[var(--color-accent-primary)] bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"
- : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:border-[var(--color-border-strong)] hover:text-[var(--color-text-primary)]"
+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)]"
}`}
>
{label}
diff --git a/packages/ui/src/refactoring/refactoring-plan-card.tsx b/packages/ui/src/refactoring/refactoring-plan-card.tsx
index 00709b582..e88505014 100644
--- a/packages/ui/src/refactoring/refactoring-plan-card.tsx
+++ b/packages/ui/src/refactoring/refactoring-plan-card.tsx
@@ -53,7 +53,7 @@ export function RefactoringPlanCard({
className={`group relative flex flex-col overflow-hidden rounded-2xl border bg-[var(--color-bg-surface)] transition-all ${
highlighted
? "border-[var(--color-accent-primary)] ring-1 ring-[var(--color-accent-primary)]/30"
- : "border-[var(--color-border-default)] hover:border-[var(--color-border-strong)] hover:shadow-sm"
+ : "border-[var(--color-border-default)] hover:border-[var(--color-border-hover)] hover:shadow-sm"
}`}
>
{/* type-colored rail — the at-a-glance differentiator */}
diff --git a/packages/ui/src/settings/index.ts b/packages/ui/src/settings/index.ts
index 649cfa9f1..08a964c4c 100644
--- a/packages/ui/src/settings/index.ts
+++ b/packages/ui/src/settings/index.ts
@@ -1,2 +1,3 @@
export * from "./general-form";
export * from "./provider-settings";
+export * from "./settings-primitives";
diff --git a/packages/ui/src/settings/settings-primitives.tsx b/packages/ui/src/settings/settings-primitives.tsx
new file mode 100644
index 000000000..44dccc2b9
--- /dev/null
+++ b/packages/ui/src/settings/settings-primitives.tsx
@@ -0,0 +1,276 @@
+"use client";
+
+/**
+ * The section-style settings vocabulary, shared by the global and per-repo
+ * settings pages so the two surfaces stop being two design systems.
+ *
+ * Both pages were built out of `Card`s — seven each, several holding a single
+ * field, three of them nesting another bordered box inside. A card means
+ * "a discrete object you can act on"; a preference is not that. Grouping is
+ * `OverviewSection` (a hairline and vertical rhythm), and inside a section a
+ * setting is a row: what it is on the left, the control on the right.
+ */
+
+import * as React from "react";
+import { Check, Copy, Loader2 } from "lucide-react";
+import { cn } from "../lib/cn";
+
+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`
+ * it stacks, because a 240px label column on a 390px viewport leaves the
+ * control nothing.
+ */
+export function SettingsRow({
+ label,
+ htmlFor,
+ hint,
+ children,
+ className,
+}: {
+ label: string;
+ /** 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;
+ className?: string;
+}) {
+ return (
+ <div
+ className={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",
+ 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>
+ {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>
+ );
+}
+
+/** A group of rows. Exists only to close the trailing hairline cleanly. */
+export function SettingsRows({
+ children,
+ className,
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return <div className={cn("flex flex-col", className)}>{children}</div>;
+}
+
+export type SaveState = "idle" | "saving" | "saved" | "error";
+
+/**
+ * The one save affordance.
+ *
+ * The pages ran two save models at once: three sections wrote on blur with no
+ * feedback, and the MCP tool list had an explicit Save button with dirty
+ * tracking. Nothing said which half you were in, so the list read as broken to
+ * anyone who had learned the page from the fields above it. Everything
+ * autosaves now, and says so here.
+ *
+ * Renders nothing at rest — rule 10. A permanent "Saved" is a badge every row
+ * carries.
+ */
+export function SaveIndicator({
+ state,
+ error,
+ className,
+}: {
+ state: SaveState;
+ error?: string | null;
+ className?: string;
+}) {
+ if (state === "idle") return null;
+
+ return (
+ <p
+ aria-live="polite"
+ className={cn(
+ "flex items-center gap-1.5 text-xs",
+ state === "error"
+ ? "text-[var(--color-error)]"
+ : "text-[var(--color-text-tertiary)]",
+ className,
+ )}
+ >
+ {state === "saving" && (
+ <>
+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />
+ Saving…
+ </>
+ )}
+ {state === "saved" && (
+ <>
+ <Check className="h-3 w-3 text-[var(--color-success)]" aria-hidden />
+ Saved
+ </>
+ )}
+ {state === "error" && (error ?? "Could not save")}
+ </p>
+ );
+}
+
+/**
+ * A machine-produced string you are meant to copy.
+ *
+ * Never truncates: the webhook URL is the one string on that page whose entire
+ * job is to be read, and an ellipsis in the middle of it reports a width
+ * decision as missing content. Long values scroll inside their own box, which
+ * is what the layout rules already require of wide content.
+ */
+export function CopyLine({
+ value,
+ label,
+ className,
+}: {
+ value: string;
+ /** Optional micro-label above the value. */
+ label?: string;
+ className?: string;
+}) {
+ const [copied, setCopied] = React.useState(false);
+ const timer = React.useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ React.useEffect(
+ () => () => {
+ if (timer.current) clearTimeout(timer.current);
+ },
+ [],
+ );
+
+ async function copy() {
+ try {
+ await navigator.clipboard.writeText(value);
+ setCopied(true);
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = setTimeout(() => setCopied(false), 2000);
+ } catch {
+ // Clipboard can be blocked by permissions; the value is selectable.
+ }
+ }
+
+ return (
+ <div className={cn("min-w-0", className)}>
+ {label && <p className={cn(SETTINGS_MICRO_LABEL, "mb-1.5")}>{label}</p>}
+ <div className="flex items-start gap-2">
+ <code className="min-w-0 flex-1 overflow-x-auto whitespace-pre rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-inset)] px-3 py-2 font-mono text-xs text-[var(--color-text-primary)]">
+ {value}
+ </code>
+ <button
+ type="button"
+ onClick={copy}
+ aria-label={copied ? "Copied" : `Copy ${label ?? "value"}`}
+ className="shrink-0 rounded-md p-2 text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ {copied ? (
+ <Check className="h-3.5 w-3.5 text-[var(--color-success)]" />
+ ) : (
+ <Copy className="h-3.5 w-3.5" />
+ )}
+ </button>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Environment variables a choice depends on, as a mono line rather than a
+ * dashed box. The box was a bordered container inside a bordered container,
+ * for two words and a pip install.
+ */
+export function EnvVarLine({
+ vars,
+ note,
+ className,
+}: {
+ vars: string[];
+ note?: React.ReactNode;
+ className?: string;
+}) {
+ if (vars.length === 0 && !note) return null;
+ return (
+ <p
+ className={cn(
+ "text-xs leading-relaxed text-[var(--color-text-tertiary)]",
+ className,
+ )}
+ >
+ {vars.length > 0 && (
+ <>
+ Needs{" "}
+ {vars.map((v, i) => (
+ <React.Fragment key={v}>
+ {i > 0 && ", "}
+ <code className="font-mono text-[var(--color-text-secondary)]">
+ {v}
+ </code>
+ </React.Fragment>
+ ))}
+ {note ? " · " : " on the server."}
+ </>
+ )}
+ {note}
+ </p>
+ );
+}
+
+/**
+ * A green/red state readout.
+ *
+ * Both pages signalled the same thing two ways: `--color-fresh` /
+ * `--color-outdated` in three components and `--color-success` /
+ * `--color-error` in two. The freshness pair carries doc-staleness semantics
+ * everywhere else in the app, so borrowing it for "the server answered" is the
+ * vocabulary drift the fixed-vocabulary table exists to stop. This is the only
+ * place either pair is spent on this surface.
+ */
+export function StatusLine({
+ status,
+ children,
+ className,
+}: {
+ status: "ok" | "error";
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <span
+ className={cn(
+ "inline-flex items-center gap-1.5 text-xs",
+ status === "ok"
+ ? "text-[var(--color-success)]"
+ : "text-[var(--color-error)]",
+ className,
+ )}
+ >
+ <span
+ aria-hidden
+ className={cn(
+ "h-1.5 w-1.5 shrink-0 rounded-full",
+ status === "ok"
+ ? "bg-[var(--color-success)]"
+ : "bg-[var(--color-error)]",
+ )}
+ />
+ {children}
+ </span>
+ );
+}
diff --git a/packages/ui/src/shared/markdown.tsx b/packages/ui/src/shared/markdown.tsx
new file mode 100644
index 000000000..aa1e23847
--- /dev/null
+++ b/packages/ui/src/shared/markdown.tsx
@@ -0,0 +1,257 @@
+"use client";
+
+/**
+ * The one themed markdown renderer.
+ *
+ * Used by chat replies, decision records, the graph doc panel and the artifact
+ * panel. It exists so none of those reach for `prose` — Tailwind Typography is
+ * banned on our markdown, because every element here is already themed through
+ * our tokens and the plugin only contributes damage (it prints literal
+ * backticks via `code::before`, and `prose-invert` is a static class that
+ * cannot follow the theme).
+ *
+ * Chat is a *reading* surface, not a chrome surface: an answer is read top to
+ * bottom the way a wiki page is, so it runs the reading scale from the design
+ * language (16px body, a real heading ladder) rather than the 12/14 chrome
+ * sizes it used to. Headings previously landed at 16/14/14 against 14px body,
+ * which is the "bolded body" failure — a heading that differs from the text
+ * around it by weight alone.
+ *
+ * The face stays sans. Serif is bounded to the named wiki reading surfaces so
+ * the mark keeps meaning "this is a document"; a reply is prose, not a document.
+ *
+ * `density="compact"` keeps the old chrome scale for consumers that render the
+ * same markdown inside a narrow panel, where 16px body would not fit the column
+ * it is given. One component, one prop — not a second renderer.
+ *
+ * Inline code is deliberately *not* accent-coloured. Nothing here resolves to a
+ * page, so an accent path would be decoration on something that does not
+ * respond — the exact anti-pattern rule 9 was written for, and the one the wiki
+ * renderer already fixed.
+ */
+
+import { lazy, Suspense, useMemo } from "react";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import type { Components } from "react-markdown";
+
+// Mermaid pulls a heavy renderer that is strictly client-side. Lazy-load it so
+// it never enters the chat bundle (or SSR pass) unless a reply actually contains
+// an inline ```mermaid block — parity with the wiki/docs reader.
+const MermaidDiagram = lazy(() =>
+ import("../wiki/mermaid-diagram").then((m) => ({ default: m.MermaidDiagram })),
+);
+
+const MICRO_LABEL =
+ "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
+
+export type MarkdownDensity = "reading" | "compact";
+
+interface Scale {
+ h1: string;
+ h2: string;
+ h3: string;
+ body: string;
+ list: string;
+ block: string;
+ code: string;
+ gap: string;
+ listIndent: string;
+ rule: string;
+}
+
+const SCALES: Record<MarkdownDensity, Scale> = {
+ reading: {
+ h1: "text-2xl mt-8 mb-3",
+ h2: "text-xl mt-7 mb-2.5",
+ h3: "text-lg mt-6 mb-2",
+ body: "text-base",
+ list: "text-[15.5px] space-y-1.5",
+ block: "my-4",
+ code: "text-sm",
+ gap: "mb-4",
+ listIndent: "ml-5",
+ rule: "my-6",
+ },
+ compact: {
+ h1: "text-base mt-4 mb-2",
+ h2: "text-sm mt-3 mb-1.5",
+ h3: "text-sm mt-2 mb-1",
+ body: "text-xs",
+ list: "text-xs space-y-1",
+ block: "my-2",
+ code: "text-[11px]",
+ gap: "mb-2",
+ listIndent: "ml-4",
+ rule: "my-3",
+ },
+};
+
+function buildComponents(s: Scale): Components {
+ return {
+ h1: ({ children }) => (
+ <h1
+ className={`${s.h1} font-semibold text-[var(--color-text-primary)]`}
+ >
+ {children}
+ </h1>
+ ),
+ h2: ({ children }) => (
+ <h2
+ className={`${s.h2} font-semibold text-[var(--color-text-primary)]`}
+ >
+ {children}
+ </h2>
+ ),
+ h3: ({ children }) => (
+ <h3
+ className={`${s.h3} font-semibold text-[var(--color-text-primary)]`}
+ >
+ {children}
+ </h3>
+ ),
+ p: ({ children }) => (
+ <p
+ className={`${s.body} ${s.gap} text-[var(--color-text-primary)] leading-relaxed`}
+ >
+ {children}
+ </p>
+ ),
+ ul: ({ children }) => (
+ <ul
+ className={`list-disc ${s.listIndent} ${s.list} ${s.gap} text-[var(--color-text-primary)]`}
+ >
+ {children}
+ </ul>
+ ),
+ ol: ({ children }) => (
+ <ol
+ className={`list-decimal ${s.listIndent} ${s.list} ${s.gap} text-[var(--color-text-primary)]`}
+ >
+ {children}
+ </ol>
+ ),
+ li: ({ children }) => <li className="leading-relaxed">{children}</li>,
+ code: ({ className, children, ...props }) => {
+ const isBlock = className?.includes("language-");
+ if (isBlock) {
+ const isMermaid = className?.includes("language-mermaid");
+ const fence = `${s.block} rounded-lg bg-[var(--color-bg-inset)] border border-[var(--color-border-default)] p-4 overflow-x-auto`;
+ if (isMermaid) {
+ const chart = String(children ?? "").replace(/\n$/, "");
+ return (
+ <Suspense
+ fallback={
+ <pre className={fence}>
+ <code
+ className={`${s.code} font-mono text-[var(--color-text-primary)]`}
+ >
+ {chart}
+ </code>
+ </pre>
+ }
+ >
+ <MermaidDiagram chart={chart} />
+ </Suspense>
+ );
+ }
+ return (
+ <pre className={fence}>
+ <code
+ className={`${s.code} font-mono text-[var(--color-text-primary)]`}
+ {...props}
+ >
+ {children}
+ </code>
+ </pre>
+ );
+ }
+ // 0.85em, relative: Geist Mono runs wider and taller than Geist at the
+ // same nominal size, so 1em mono inside 16px sans reads oversized.
+ return (
+ <code
+ className="rounded px-1 py-0.5 bg-[var(--color-bg-inset)] text-[var(--color-text-primary)] text-[0.85em] font-mono"
+ {...props}
+ >
+ {children}
+ </code>
+ );
+ },
+ pre: ({ children }) => <>{children}</>,
+ blockquote: ({ children }) => (
+ <blockquote
+ className={`${s.block} ${s.body} border-l-2 border-[var(--color-border-default)] pl-4 text-[var(--color-text-secondary)]`}
+ >
+ {children}
+ </blockquote>
+ ),
+ a: ({ href, children }) => (
+ <a
+ href={href}
+ className="text-[var(--color-accent-primary)] hover:underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {children}
+ </a>
+ ),
+ table: ({ children }) => (
+ <div className={`${s.block} overflow-x-auto`}>
+ <table className={`${s.code} w-full border-collapse`}>{children}</table>
+ </div>
+ ),
+ thead: ({ children }) => (
+ <thead className="border-b border-[var(--color-border-default)]">
+ {children}
+ </thead>
+ ),
+ th: ({ children }) => (
+ <th className={`text-left px-3 py-2 font-normal ${MICRO_LABEL}`}>
+ {children}
+ </th>
+ ),
+ tr: ({ children }) => (
+ <tr className="border-t border-[var(--color-border-default)]">
+ {children}
+ </tr>
+ ),
+ td: ({ children }) => (
+ <td className="px-3 py-2 text-[var(--color-text-primary)] tabular-nums">
+ {children}
+ </td>
+ ),
+ strong: ({ children }) => (
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {children}
+ </strong>
+ ),
+ hr: () => (
+ <hr className={`${s.rule} border-t border-[var(--color-border-default)]`} />
+ ),
+ };
+}
+
+export interface MarkdownProps {
+ content: string;
+ /** `compact` keeps chrome sizes for narrow panels. */
+ density?: MarkdownDensity;
+}
+
+export function Markdown({ content, density = "reading" }: MarkdownProps) {
+ const components = useMemo(
+ () => buildComponents(SCALES[density]),
+ [density],
+ );
+ return (
+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
+ {content}
+ </ReactMarkdown>
+ );
+}
+
+/**
+ * @deprecated Use `Markdown`. Kept because `@repowise-dev/ui/chat/chat-markdown`
+ * is imported by the hosted frontend in several places.
+ */
+export const ChatMarkdown = Markdown;
+export type ChatMarkdownDensity = MarkdownDensity;
diff --git a/packages/ui/src/stats/churn-ledger.tsx b/packages/ui/src/stats/churn-ledger.tsx
index 277a8bb36..61069e883 100644
--- a/packages/ui/src/stats/churn-ledger.tsx
+++ b/packages/ui/src/stats/churn-ledger.tsx
@@ -40,7 +40,7 @@ export function ChurnLedger({ data }: { data: StatsChurn }) {
)} were later deleted`}
>
<div
- className="relative shrink-0 bg-[var(--color-success-muted,rgba(47,125,82,0.12))]"
+ className="relative shrink-0 bg-[var(--color-success-muted)]"
style={{ width: `${standingPct}%` }}
>
<span className="absolute inset-0 flex items-center truncate px-3 font-mono text-[11px] uppercase tracking-[0.06em] text-[var(--color-success)]">
@@ -53,7 +53,7 @@ export function ChurnLedger({ data }: { data: StatsChurn }) {
// Hatching rather than a flat fill: the deleted share is a texture
// over the same track, not a separate quantity beside it.
background:
- "repeating-linear-gradient(-45deg, var(--color-error-muted, rgba(163,58,50,0.14)) 0 6px, transparent 6px 12px)",
+ "repeating-linear-gradient(-45deg, var(--color-error-muted) 0 6px, transparent 6px 12px)",
}}
>
<span className="absolute inset-0 flex items-center truncate px-3 font-mono text-[11px] uppercase tracking-[0.06em] text-[var(--color-error)]">
diff --git a/packages/ui/src/stats/punch-card.tsx b/packages/ui/src/stats/punch-card.tsx
index c80e6c364..80dc4fc35 100644
--- a/packages/ui/src/stats/punch-card.tsx
+++ b/packages/ui/src/stats/punch-card.tsx
@@ -222,7 +222,7 @@ export function PunchCard({
? "var(--color-accent-primary)"
: count > 0
? "var(--color-text-primary)"
- : "var(--color-bg-muted)",
+ : "var(--color-bg-inset)",
opacity: isHover
? 1
: count > 0
diff --git a/packages/ui/src/symbols/top-symbols-row.tsx b/packages/ui/src/symbols/top-symbols-row.tsx
index 72f1a1ea4..2d7cedb68 100644
--- a/packages/ui/src/symbols/top-symbols-row.tsx
+++ b/packages/ui/src/symbols/top-symbols-row.tsx
@@ -109,7 +109,7 @@ export function TopSymbolsRow({
onClick={onSelect ? () => onSelect(s) : undefined}
className={cn(
"group flex items-center gap-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1.5 text-left transition-colors",
- onSelect && "hover:border-[var(--color-accent-primary)] hover:bg-[var(--color-bg-hover)] cursor-pointer",
+ onSelect && "hover:border-[var(--color-accent-primary)] hover:bg-[var(--color-bg-wash-hover)] cursor-pointer",
)}
title={s.qualified_name || s.name}
aria-label={`Open symbol ${s.name}`}
diff --git a/packages/ui/src/workspace/dsm/dsm-matrix.tsx b/packages/ui/src/workspace/dsm/dsm-matrix.tsx
index 43257aa6a..6b93e37e1 100644
--- a/packages/ui/src/workspace/dsm/dsm-matrix.tsx
+++ b/packages/ui/src/workspace/dsm/dsm-matrix.tsx
@@ -81,7 +81,7 @@ function cellBackground(cell: DsmCell, isDiagonal: boolean, role?: NodeRole): st
// The diagonal is a service vs itself — repurpose it to surface the
// service's architecture role so the on-diagonal core block stands out.
if (role) return `color-mix(in srgb, ${roleStyle(role).color} 38%, transparent)`;
- return "var(--color-bg-subtle)";
+ return "var(--color-bg-wash)";
}
if (!cell.present) return "transparent";
if (cell.violation) return "color-mix(in srgb, var(--color-risk-high) 28%, transparent)";
diff --git a/packages/ui/styles/globals.css b/packages/ui/styles/globals.css
index a6ed14655..bfc9d62ed 100644
--- a/packages/ui/styles/globals.css
+++ b/packages/ui/styles/globals.css
@@ -236,6 +236,14 @@
plum-alpha on paper, lavender-alpha on dark (same idiom as canvas-dot). */
--color-bg-wash: rgba(36, 27, 44, 0.05);
--color-bg-wash-hover: rgba(36, 27, 44, 0.1);
+ /* Faint grounds for a success/error quantity — a filled bar segment, not a
+ status pill (rule 9 killed those). Referenced lazily off the themed
+ --color-success / --color-error, like --color-table-divider, so one
+ definition covers both themes. The churn ledger used to inline these as
+ hardcoded rgba fallbacks behind undefined token names, which meant a
+ paper-theme green sitting on the dark ramp. */
+ --color-success-muted: color-mix(in srgb, var(--color-success) 12%, transparent);
+ --color-error-muted: color-mix(in srgb, var(--color-error) 14%, transparent);
--color-border-subtle: var(--color-border-default);
/* Faint hairline for table row dividers — half the weight of a normal
border so rows whisper while the header rule still reads. References the
diff --git a/packages/web/src/app/repos/[id]/chat/page.tsx b/packages/web/src/app/repos/[id]/chat/page.tsx
index b92e99dd6..dbb5ff9cf 100644
--- a/packages/web/src/app/repos/[id]/chat/page.tsx
+++ b/packages/web/src/app/repos/[id]/chat/page.tsx
@@ -1,8 +1,6 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
-import { Hash } from "lucide-react";
import { getRepo } from "@/lib/api/repos";
-import { Badge } from "@repowise-dev/ui/ui/badge";
import { ChatInterface } from "@/components/chat/chat-interface";
interface Props {
@@ -20,6 +18,14 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
}
}
+/**
+ * Thin shell. The page used to render its own header — repo name, local path,
+ * branch and SHA — directly under the repo breadcrumb and directly above the
+ * chat's own control row, so three hairlines ran before the first word of
+ * content and the repo name appeared twice. The breadcrumb already names the
+ * repo; branch and SHA are orientation, so they ride the empty state's status
+ * line next to the file and doc counts, where the other figures already are.
+ */
export default async function RepoChatPage({ params, searchParams }: Props) {
const { id } = await params;
const { q } = await searchParams;
@@ -32,38 +38,14 @@ export default async function RepoChatPage({ params, searchParams }: Props) {
}
return (
- <div className="flex flex-col h-full">
- {/* Compact header */}
- <div className="px-4 pt-3 pb-2 flex items-center justify-between shrink-0 border-b border-[var(--color-border-default)]">
- <div className="min-w-0">
- <h1 className="text-sm font-semibold text-[var(--color-text-primary)] truncate">
- {repo.name}
- </h1>
- <p className="text-[10px] font-mono text-[var(--color-text-tertiary)] truncate">
- {repo.local_path}
- </p>
- </div>
- <div className="flex items-center gap-1.5 shrink-0 ml-3">
- {repo.head_commit && (
- <Badge variant="outline" className="text-[10px] h-5">
- <Hash className="h-2.5 w-2.5" />
- {repo.head_commit.slice(0, 7)}
- </Badge>
- )}
- <Badge variant="outline" className="text-[10px] h-5">
- {repo.default_branch}
- </Badge>
- </div>
- </div>
-
- {/* Chat interface fills remaining height */}
- <div className="flex-1 min-h-0">
- <ChatInterface
- repoId={id}
- repoName={repo.name}
- {...(q ? { initialQuestion: q } : {})}
- />
- </div>
+ <div className="flex h-full flex-col">
+ <ChatInterface
+ repoId={id}
+ repoName={repo.name}
+ defaultBranch={repo.default_branch}
+ {...(repo.head_commit ? { headCommit: repo.head_commit } : {})}
+ {...(q ? { initialQuestion: q } : {})}
+ />
</div>
);
}
diff --git a/packages/web/src/app/repos/[id]/decisions/[decisionId]/page.tsx b/packages/web/src/app/repos/[id]/decisions/[decisionId]/page.tsx
index d3ff41534..a0078e5ff 100644
--- a/packages/web/src/app/repos/[id]/decisions/[decisionId]/page.tsx
+++ b/packages/web/src/app/repos/[id]/decisions/[decisionId]/page.tsx
@@ -1,5 +1,7 @@
+import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getDecision } from "@/lib/api/decisions";
+import { stripMarkdown } from "@repowise-dev/ui/lib/format";
import { DecisionDetail } from "@/components/decisions/decision-detail";
export const revalidate = 30;
@@ -8,6 +10,24 @@ interface Props {
params: Promise<{ id: string; decisionId: string }>;
}
+export async function generateMetadata({ params }: Props): Promise<Metadata> {
+ const { id: repoId, decisionId } = await params;
+ try {
+ const decision = await getDecision(repoId, decisionId);
+ return { title: `${stripMarkdown(decision.title)} — Decision` };
+ } catch {
+ return { title: "Decision" };
+ }
+}
+
+/**
+ * One decision record.
+ *
+ * A reading surface: the body is context, rationale and rejected alternatives,
+ * which is prose someone reads through rather than scans. `--page-pad` and a
+ * 3xl measure, matching the reading column floor rather than the old bare
+ * `p-6` with no centring.
+ */
export default async function DecisionDetailPage({ params }: Props) {
const { id: repoId, decisionId } = await params;
@@ -19,7 +39,7 @@ export default async function DecisionDetailPage({ params }: Props) {
}
return (
- <div className="max-w-3xl p-6">
+ <div className="mx-auto w-full max-w-3xl p-[var(--page-pad)]">
<DecisionDetail decision={decision} repoId={repoId} />
</div>
);
diff --git a/packages/web/src/app/repos/[id]/decisions/page.tsx b/packages/web/src/app/repos/[id]/decisions/page.tsx
index 91d19543a..0bd70fdf8 100644
--- a/packages/web/src/app/repos/[id]/decisions/page.tsx
+++ b/packages/web/src/app/repos/[id]/decisions/page.tsx
@@ -1,21 +1,60 @@
+import type { Metadata } from "next";
+import Link from "next/link";
import { notFound } from "next/navigation";
-import { listDecisions } from "@/lib/api/decisions";
+import { PageShell } from "@repowise-dev/ui/shared/page-shell";
+import { OverviewSection, SectionLink } from "@repowise-dev/ui/overview";
+import { PageLede } from "@repowise-dev/ui/shared/page-lede";
+import {
+ DecisionConflicts,
+ GovernedFiles,
+ summarizeGovernance,
+} from "@repowise-dev/ui/decisions";
+import {
+ getDecision,
+ getDecisionCounts,
+ getDecisionGraph,
+ listDecisions,
+} from "@/lib/api/decisions";
import { ApiClientError } from "@/lib/api/client";
import { DecisionsTableWrapper } from "@/components/decisions/decisions-table-wrapper";
-import { DecisionGraphWrapper } from "@/components/decisions/decision-graph-wrapper";
export const revalidate = 30;
+export const metadata: Metadata = { title: "Decisions" };
+
+/** Rows the table holds at once. The server pages; this is one window. */
+const PAGE_SIZE = 50;
interface Props {
params: Promise<{ id: string }>;
}
+/**
+ * Architectural decisions.
+ *
+ * The page used to open with a title and go straight into a filter bar, then
+ * close with a React Flow canvas of the decision graph. Neither said the thing
+ * the data says loudest: most records here are unconfirmed *proposals* mined by
+ * the indexer, and only a handful are confirmed. That makes this a triage
+ * queue, not an archive, and the lede now says so.
+ *
+ * Every figure comes from `/decisions/counts`, a grouped COUNT. An earlier cut
+ * counted the rows it had fetched and printed "97 of 100" on a repository
+ * holding several hundred — a count nobody measured, on the surface whose whole
+ * job is to be trusted.
+ *
+ * The canvas is gone. See `decision-governance.tsx` for what its payload
+ * actually contained and why two lists beat it.
+ */
export default async function DecisionsPage({ params }: Props) {
const { id: repoId } = await params;
let decisions;
try {
- decisions = await listDecisions(repoId, { include_proposed: true, limit: 100 });
+ decisions = await listDecisions(repoId, {
+ include_proposed: true,
+ limit: PAGE_SIZE,
+ offset: 0,
+ });
} catch (err) {
if (err instanceof ApiClientError && err.status === 404) {
notFound();
@@ -24,20 +63,150 @@ export default async function DecisionsPage({ params }: Props) {
throw err;
}
+ // Counts degrade rather than 404 the page. `/decisions/counts` is newer than
+ // the rest of this route, so a frontend running ahead of its backend gets a
+ // 404 here — and folding that into the repo-missing branch above turned a
+ // missing *aggregate* into "Page not found" for a repository that exists.
+ const counts = await getDecisionCounts(repoId, {
+ include_proposed: true,
+ }).catch(() => undefined);
+
+ // Aggregated here, not in the browser: the graph payload runs to thousands of
+ // code edges and only a dozen rows of it survive to the page.
+ const graph = await getDecisionGraph(repoId).catch(() => undefined);
+
+ // Conflict endpoints routinely sit outside the graph's own node payload — on
+ // a live index every one of them did — so titles come from the rows we
+ // already have, and anything still unnamed is fetched by id. Conflicts are
+ // rare, so this stays a handful of requests.
+ const titles = new Map(decisions.map((d) => [d.id, d.title]));
+ const unresolved = [
+ ...new Set(
+ summarizeGovernance(graph, { titles })
+ .conflicts.flatMap((c) => [
+ ...(c.aTitle ? [] : [c.aId]),
+ ...(c.bTitle ? [] : [c.bId]),
+ ]),
+ ),
+ ];
+ if (unresolved.length > 0) {
+ const fetched = await Promise.all(
+ unresolved.map((id) =>
+ getDecision(repoId, id).then(
+ (d) => [id, d.title] as const,
+ () => null,
+ ),
+ ),
+ );
+ for (const row of fetched) if (row) titles.set(row[0], row[1]);
+ }
+
+ const { conflicts, governedFiles, governedFileTotal } = summarizeGovernance(
+ graph,
+ { topFiles: 12, titles },
+ );
+ // A pair still missing a title is dropped rather than shown as a hash.
+ const namedConflicts = conflicts.filter((c) => c.aTitle && c.bTitle);
+
+ // With counts we can state a measured total; without them we report only
+ // what this page actually loaded, and say so. Never a number nobody counted.
+ const total = counts?.total;
+ const proposed =
+ counts?.proposed ?? decisions.filter((d) => d.status === "proposed").length;
+ const active =
+ counts?.active ?? decisions.filter((d) => d.status === "active").length;
+ const queue = proposed > 0;
+ const denominator =
+ total !== undefined
+ ? `of ${total.toLocaleString()} recorded`
+ : `in the first ${decisions.length.toLocaleString()}`;
+
return (
- <div className="space-y-6 p-6">
- <div>
- <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">
- Architectural Decisions
- </h1>
- <p className="mt-1 text-sm text-[var(--color-text-tertiary)]">
- Why the codebase is built the way it is — constraints, tradeoffs, and rejected alternatives.
- </p>
- </div>
- {/* The table is the workhorse; the relationship graph is secondary and
- collapsed below it. */}
- <DecisionsTableWrapper repoId={repoId} initialData={decisions} />
- <DecisionGraphWrapper repoId={repoId} />
- </div>
+ <PageShell
+ title="Architectural decisions"
+ description="Why the codebase is built the way it is — constraints, tradeoffs, and the alternatives that were rejected."
+ >
+ <PageLede
+ label={queue ? "Awaiting review" : "Active decisions"}
+ value={(queue ? proposed : active).toLocaleString()}
+ unit={denominator}
+ layout="beside"
+ >
+ {queue ? (
+ <>
+ <p>
+ {proposed.toLocaleString()}{" "}
+ {total !== undefined
+ ? `of ${total.toLocaleString()} records are`
+ : `of the first ${decisions.length.toLocaleString()} records are`}{" "}
+ proposals mined from commits, comments and docs that nobody has
+ confirmed yet, against {active.toLocaleString()} marked active.
+ Until one is confirmed it is a guess about your codebase, not a
+ rule for it — so this page is a queue before it is an archive.
+ </p>
+ <p>
+ Confirming takes a click and changes no code. It marks the record
+ as something your team stands behind, which is what makes it worth
+ quoting back to an agent later.
+ </p>
+ </>
+ ) : (
+ <p>
+ {active.toLocaleString()}{" "}
+ {total !== undefined ? `of ${total.toLocaleString()} ` : ""}
+ decisions are confirmed as current, with nothing waiting on review.
+ New proposals appear here as the indexer mines them from commits,
+ comments and docs.
+ </p>
+ )}
+ </PageLede>
+
+ {namedConflicts.length > 0 && (
+ <OverviewSection
+ title="Conflicts"
+ description={`${namedConflicts.length} pair${
+ namedConflicts.length === 1 ? "" : "s"
+ } of decisions appear to contradict each other. Confirming one and deprecating the other resolves the pair.`}
+ >
+ <DecisionConflicts
+ conflicts={namedConflicts}
+ decisionHref={(id) => `/repos/${repoId}/decisions/${id}`}
+ LinkComponent={Link}
+ />
+ </OverviewSection>
+ )}
+
+ <OverviewSection
+ title="All decisions"
+ description="Confirmed rules first, then the proposals most likely to be real. Filter by status to work the queue, or by source to see where a record came from."
+ >
+ <DecisionsTableWrapper
+ repoId={repoId}
+ initialData={decisions}
+ {...(total !== undefined ? { initialTotal: total } : {})}
+ pageSize={PAGE_SIZE}
+ />
+ </OverviewSection>
+
+ {governedFiles.length > 0 && (
+ <OverviewSection
+ title="Most governed files"
+ description={`Of ${governedFileTotal.toLocaleString()} files carrying at least one decision, these have the most. Worth reading before you change one.`}
+ action={
+ <SectionLink href={`/repos/${repoId}/files`} LinkComponent={Link}>
+ All files
+ </SectionLink>
+ }
+ >
+ <GovernedFiles
+ files={governedFiles}
+ fileHref={(path) =>
+ `/repos/${repoId}/files?path=${encodeURIComponent(path)}`
+ }
+ LinkComponent={Link}
+ />
+ </OverviewSection>
+ )}
+ </PageShell>
);
}
diff --git a/packages/web/src/app/repos/[id]/settings/page.tsx b/packages/web/src/app/repos/[id]/settings/page.tsx
index 0351e5796..e27f9a64c 100644
--- a/packages/web/src/app/repos/[id]/settings/page.tsx
+++ b/packages/web/src/app/repos/[id]/settings/page.tsx
@@ -1,18 +1,15 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
-import { Settings } from "lucide-react";
-import { WebhookSection } from "@/components/settings/webhook-section";
-import { ProviderSettingsPanel } from "@/components/settings/provider-settings-panel";
+import { OverviewSection } from "@repowise-dev/ui/overview";
+import { PageShell } from "@repowise-dev/ui/shared/page-shell";
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 { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@repowise-dev/ui/ui/card";
-import { Separator } from "@repowise-dev/ui/ui/separator";
-import { PageShell } from "@repowise-dev/ui/shared/page-shell";
import { OperationsPanel } from "@/components/repos/operations-panel";
interface Props {
@@ -29,6 +26,18 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
}
}
+/**
+ * Per-repository settings.
+ *
+ * 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.
+ */
export default async function RepoSettingsPage({ params }: Props) {
const { id } = await params;
@@ -43,76 +52,70 @@ export default async function RepoSettingsPage({ params }: Props) {
return (
<PageShell
- className="max-w-2xl"
- icon={<Settings className="h-5 w-5 text-[var(--color-accent-primary)]" />}
- title="Repository Settings"
- description={`Manage ${repo.name}`}
+ title="Settings"
+ description={`Indexing, model keys and health for ${repo.name}. Server, webhook and editor configuration are shared across repositories.`}
+ className="max-w-3xl"
>
- <Card>
- <CardHeader>
- <CardTitle className="text-sm font-medium">General</CardTitle>
- <CardDescription>Name, branch, and path configuration</CardDescription>
- </CardHeader>
- <CardContent>
- <RepoSettingsForm repo={repo} />
- </CardContent>
- </Card>
+ <OverviewSection
+ title="General"
+ description="Where this repository lives and which branch is indexed."
+ flush
+ >
+ <RepoSettingsForm repo={repo} />
+ </OverviewSection>
- <Card>
- <CardHeader>
- <CardTitle className="text-sm font-medium">Sync & Indexing</CardTitle>
- <CardDescription>Trigger incremental sync or full re-indexing</CardDescription>
- </CardHeader>
- <CardContent className="pt-0">
- <OperationsPanel repoId={id} repoName={repo.name} />
- </CardContent>
- </Card>
+ <OverviewSection
+ title="Sync and indexing"
+ description="Pull recent commits into the existing index, or rebuild it from scratch."
+ >
+ <OperationsPanel repoId={id} repoName={repo.name} />
+ </OverviewSection>
- <Card id="provider">
- <CardHeader>
- <CardTitle className="text-sm font-medium">AI provider</CardTitle>
- <CardDescription>
- Add a model key to write documentation with AI. Keys are stored with this
- repository and used by generation from the UI or the CLI.
- </CardDescription>
- </CardHeader>
- <CardContent className="pt-0">
- <ProviderSettingsPanel repoId={id} />
- </CardContent>
- </Card>
+ <OverviewSection
+ id="provider"
+ title="AI provider"
+ description="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."
+ >
+ <ProviderSettingsPanel repoId={id} />
+ </OverviewSection>
- <Card>
- <CardHeader>
- <CardTitle className="text-sm font-medium">Refactoring code generation</CardTitle>
- <CardDescription>
- Opt in to turning refactoring plans into reviewable diffs with your configured model
- </CardDescription>
- </CardHeader>
- <CardContent className="pt-0">
- <RefactoringSettingsSection repoId={id} />
- </CardContent>
- </Card>
+ <OverviewSection
+ title="Refactoring code generation"
+ description="Opt in to turning refactoring plans into reviewable diffs with your configured model."
+ >
+ <RefactoringSettingsSection repoId={id} />
+ </OverviewSection>
- <Card>
- <CardHeader>
- <CardTitle className="text-sm font-medium">System Health</CardTitle>
- <CardDescription>
- Per-population drift: wiki pages vs page vectors, and decision records vs decision
- vectors
- </CardDescription>
- </CardHeader>
- <CardContent className="pt-0">
- <CoordinatorHealthPanel repoId={id} initial={coordinatorHealth} />
- </CardContent>
- </Card>
+ <OverviewSection
+ title="Index health"
+ description="Per-population drift: wiki pages against page vectors, and decision records against decision vectors. A gap means search is answering from a stale set."
+ >
+ <CoordinatorHealthPanel repoId={id} initial={coordinatorHealth} />
+ </OverviewSection>
- <Separator />
+ {/* 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)]">
+ Delete this repository
+ </h2>
+ <p className="max-w-[62ch] text-xs leading-relaxed text-[var(--color-text-tertiary)] [text-wrap:pretty]">
+ Removes the index and everything generated from it — pages, symbols,
+ decisions and history. Your source files are untouched. This cannot be
+ undone.
+ </p>
+ <div>
+ <DeleteRepoButton
+ repoId={id}
+ repoName={repo.name}
+ variant="button"
+ redirectTo="/"
+ />
+ </div>
+ </section>
- {/* Shared with global settings — interpolates the real server URL. */}
- <WebhookSection />
-
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Server connection and MCP configuration live in{" "}
+ <p className="border-t border-[var(--color-border-default)] pt-6 text-xs text-[var(--color-text-tertiary)]">
+ Server connection, webhooks, model defaults and MCP configuration are in{" "}
<Link
href="/settings"
className="text-[var(--color-accent-primary)] hover:underline"
@@ -121,23 +124,6 @@ export default async function RepoSettingsPage({ params }: Props) {
</Link>
.
</p>
-
- <Separator />
-
- <Card className="border-[var(--color-error)]/40 bg-[var(--color-error)]/5">
- <CardHeader>
- <CardTitle className="text-sm font-medium text-[var(--color-error)]">
- Danger Zone
- </CardTitle>
- <CardDescription>
- Permanently delete this repository and all its generated pages, symbols, and history.
- This cannot be undone.
- </CardDescription>
- </CardHeader>
- <CardContent>
- <DeleteRepoButton repoId={id} repoName={repo.name} variant="button" redirectTo="/" />
- </CardContent>
- </Card>
</PageShell>
);
}
diff --git a/packages/web/src/app/settings/page.tsx b/packages/web/src/app/settings/page.tsx
index ef424abae..89a5b39d0 100644
--- a/packages/web/src/app/settings/page.tsx
+++ b/packages/web/src/app/settings/page.tsx
@@ -1,4 +1,6 @@
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";
@@ -8,27 +10,41 @@ import { DisplaySection } from "@/components/settings/display-section";
export const metadata: Metadata = { title: "Settings" };
+/**
+ * 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.
+ *
+ * `max-w-3xl` 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 function SettingsPage() {
return (
- <div className="p-4 sm:p-6 max-w-2xl space-y-6">
- <div>
- <h1 className="text-xl font-semibold text-[var(--color-text-primary)]">Settings</h1>
- <p className="text-sm text-[var(--color-text-secondary)] mt-1">
- API connection, provider defaults, display, and integration config.
- </p>
- </div>
-
+ <PageShell
+ 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."
+ className="max-w-3xl"
+ >
<ConnectionSection />
<ProviderSection />
<DisplaySection />
- <WebhookSection />
<McpSection />
<McpToolsSection />
+ <WebhookSection />
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Per-repository options (sync, exclude patterns, deletion) live on each
- repo&apos;s own Settings page, reachable from its sidebar.
+ <p className="border-t border-[var(--color-border-default)] pt-6 text-xs text-[var(--color-text-tertiary)]">
+ Sync schedule, exclude patterns and deletion are per repository, on{" "}
+ <Link
+ href="/"
+ className="text-[var(--color-accent-primary)] hover:underline"
+ >
+ a repo&apos;s own settings page
+ </Link>
+ .
</p>
- </div>
+ </PageShell>
);
}
diff --git a/packages/web/src/app/workspace/sync-buttons.tsx b/packages/web/src/app/workspace/sync-buttons.tsx
index eb83ae4c1..5156d2fc5 100644
--- a/packages/web/src/app/workspace/sync-buttons.tsx
+++ b/packages/web/src/app/workspace/sync-buttons.tsx
@@ -59,7 +59,7 @@ export function SyncButton({
"inline-flex items-center gap-1.5 rounded-md text-xs font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed";
const variantClass =
variant === "primary"
- ? "bg-[var(--color-accent-primary)] text-[var(--color-bg-base)] hover:bg-[var(--color-accent-primary)]/90 px-3 py-1.5"
+ ? "bg-[var(--color-accent-primary)] text-[var(--color-text-on-accent)] hover:bg-[var(--color-accent-primary)]/90 px-3 py-1.5"
: "border border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] px-2.5 py-1";
return (
diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsx
index 2c7bd7edc..2d45a5d6a 100644
--- a/packages/web/src/components/chat/chat-interface.tsx
+++ b/packages/web/src/components/chat/chat-interface.tsx
@@ -15,11 +15,21 @@ import { ConversationHistory } from "./conversation-history";
interface ChatInterfaceProps {
repoId: string;
repoName?: string;
+ /** Branch shown in the empty-state status line. */
+ defaultBranch?: string;
+ /** HEAD SHA shown in the empty-state status line, abbreviated to 7. */
+ headCommit?: string;
/** Question to send immediately on mount (quick-ask deep links, `?q=`). */
initialQuestion?: string;
}
-export function ChatInterface({ repoId, repoName, initialQuestion }: ChatInterfaceProps) {
+export function ChatInterface({
+ repoId,
+ repoName,
+ defaultBranch,
+ headCommit,
+ initialQuestion,
+}: ChatInterfaceProps) {
const {
messages,
conversationId,
@@ -89,14 +99,22 @@ export function ChatInterface({ repoId, repoName, initialQuestion }: ChatInterfa
buildCitationHref={(s) => pageHref(repoId, s.pageId)}
modelSelectorSlot={<ModelSelector repoId={repoId} />}
statusSlot={
- stats ? (
- <span>
- {stats.file_count.toLocaleString()} files ·{" "}
- {Math.round(stats.doc_coverage_pct)}% documented
- {stats.symbol_count > 0 &&
- ` · ${stats.symbol_count.toLocaleString()} symbols indexed`}
- </span>
- ) : undefined
+ // Orientation, in one line: what was indexed, and which commit it was
+ // indexed from. The branch and SHA used to sit in a second page header
+ // that duplicated the breadcrumb; they belong with the other figures.
+ <span>
+ {[
+ stats ? `${stats.file_count.toLocaleString()} files` : null,
+ stats ? `${Math.round(stats.doc_coverage_pct)}% documented` : null,
+ stats && stats.symbol_count > 0
+ ? `${stats.symbol_count.toLocaleString()} symbols indexed`
+ : null,
+ defaultBranch,
+ headCommit ? headCommit.slice(0, 7) : null,
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+ </span>
}
sendDisabled={!anyConfigured}
sendDisabledReason={
diff --git a/packages/web/src/components/decisions/decision-graph-wrapper.tsx b/packages/web/src/components/decisions/decision-graph-wrapper.tsx
deleted file mode 100644
index 88eda3d37..000000000
--- a/packages/web/src/components/decisions/decision-graph-wrapper.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-"use client";
-
-import * as React from "react";
-import useSWR from "swr";
-import { useRouter } from "next/navigation";
-import { ChevronDown, ChevronRight, Network } from "lucide-react";
-import { DecisionGraphView } from "@repowise-dev/ui/decisions/decision-graph-view";
-import { getDecisionGraph } from "@/lib/api/decisions";
-
-interface DecisionGraphWrapperProps {
- repoId: string;
- /**
- * Graph-first: render the canvas as the primary surface (fetched immediately,
- * no collapse chrome). When false the graph stays a collapsible drill-down.
- */
- primary?: boolean;
-}
-
-/**
- * Decision-graph section. As the primary surface it fetches on mount and fills
- * a tall canvas; otherwise it is a collapsible that fetches once expanded.
- * Clicking a node navigates to that decision's detail page.
- */
-export function DecisionGraphWrapper({ repoId, primary = false }: DecisionGraphWrapperProps) {
- const router = useRouter();
- const [open, setOpen] = React.useState(primary);
-
- const { data, isLoading } = useSWR(
- open ? `decision-graph:${repoId}` : null,
- () => getDecisionGraph(repoId),
- { revalidateOnFocus: false },
- );
-
- if (primary) {
- return (
- <div className="h-[560px] rounded-lg border border-[var(--color-border-default)]">
- <DecisionGraphView
- graph={data}
- isLoading={isLoading}
- onSelectDecision={(id) => router.push(`/repos/${repoId}/decisions/${id}`)}
- />
- </div>
- );
- }
-
- return (
- <div className="rounded-lg border border-[var(--color-border-default)]">
- <button
- type="button"
- onClick={() => setOpen((o) => !o)}
- className="flex w-full items-center gap-2 px-4 py-3 text-left text-sm font-medium text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]"
- aria-expanded={open}
- >
- {open ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
- <Network className="h-4 w-4" />
- Decision graph
- <span className="text-xs font-normal text-[var(--color-text-tertiary)]">
- relationships, supersessions &amp; conflicts
- </span>
- </button>
- {open && (
- <div className="border-t border-[var(--color-border-default)] p-3">
- <div className="h-[520px]">
- <DecisionGraphView
- graph={data}
- isLoading={isLoading}
- onSelectDecision={(id) => router.push(`/repos/${repoId}/decisions/${id}`)}
- />
- </div>
- </div>
- )}
- </div>
- );
-}
diff --git a/packages/web/src/components/decisions/decisions-table-wrapper.tsx b/packages/web/src/components/decisions/decisions-table-wrapper.tsx
index 6496fce01..0afa66e6e 100644
--- a/packages/web/src/components/decisions/decisions-table-wrapper.tsx
+++ b/packages/web/src/components/decisions/decisions-table-wrapper.tsx
@@ -7,45 +7,143 @@ import {
DecisionsTable,
type DecisionsTableFilters,
} from "@repowise-dev/ui/decisions/decisions-table";
-import { listDecisions } from "@/lib/api/decisions";
+import { getDecisionCounts, listDecisions } from "@/lib/api/decisions";
import type { DecisionRecord } from "@repowise-dev/types/decisions";
interface DecisionsTableWrapperProps {
repoId: string;
initialData?: DecisionRecord[];
+ /** Measured total for the unfiltered set, from the server's COUNT. */
+ initialTotal?: number;
+ pageSize?: number;
}
+/**
+ * Data wrapper for the decisions table.
+ *
+ * Pages on the server. It used to pull `limit: 100` in one shot and render
+ * every row: on a repository with several hundred records that is ~920KB of
+ * JSON for a table nobody scrolls past the top of, and it still could not show
+ * the rest. The window is now `pageSize` rows and the count beside it comes
+ * from the aggregate endpoint, so "51–100 of 500" is measured on both sides.
+ */
export function DecisionsTableWrapper({
repoId,
initialData,
+ initialTotal,
+ pageSize = 50,
}: DecisionsTableWrapperProps) {
const [filters, setFilters] = React.useState<DecisionsTableFilters>({
status: "all",
source: "all",
});
+ const [page, setPage] = React.useState(0);
+
+ const status = filters.status !== "all" ? filters.status : undefined;
+ const source = filters.source !== "all" ? filters.source : undefined;
+
+ // A filter change invalidates the offset — page 3 of "all" is not page 3 of
+ // "active", and leaving it put lands the reader on an empty table.
+ const handleFiltersChange = React.useCallback((next: DecisionsTableFilters) => {
+ setFilters(next);
+ setPage(0);
+ }, []);
const { data, error, mutate, isLoading } = useSWR(
- [`/api/repos/${repoId}/decisions`, filters.status, filters.source],
+ [`/api/repos/${repoId}/decisions`, status, source, page, pageSize],
() =>
listDecisions(repoId, {
- status: filters.status !== "all" ? filters.status : undefined,
- source: filters.source !== "all" ? filters.source : undefined,
+ ...(status ? { status } : {}),
+ ...(source ? { source } : {}),
+ include_proposed: true,
+ limit: pageSize,
+ offset: page * pageSize,
+ }),
+ { fallbackData: page === 0 && !status && !source ? initialData : undefined },
+ );
+
+ // Counts follow the filters, because "of 500" beside a filtered table is the
+ // wrong denominator. Source is a server filter so it goes in the key; status
+ // is read off the returned per-status counts.
+ const { data: counts } = useSWR(
+ [`/api/repos/${repoId}/decisions/counts`, source],
+ () =>
+ getDecisionCounts(repoId, {
+ ...(source ? { source } : {}),
include_proposed: true,
- limit: 100,
}),
- { fallbackData: initialData },
);
+ const total = counts
+ ? filters.status === "all"
+ ? counts.total
+ : (counts[filters.status] ?? 0)
+ : !source && filters.status === "all"
+ ? initialTotal
+ : undefined;
+
+ const rows = data ?? [];
+ const first = page * pageSize + 1;
+ const last = page * pageSize + rows.length;
+ const hasNext =
+ total !== undefined ? last < total : rows.length === pageSize;
+
+ return (
+ <div className="space-y-4">
+ <DecisionsTable
+ decisions={data}
+ filters={filters}
+ onFiltersChange={handleFiltersChange}
+ repoId={repoId}
+ LinkComponent={Link}
+ error={error}
+ isLoading={isLoading}
+ onRetry={() => mutate()}
+ />
+
+ {(page > 0 || hasNext) && (
+ <div className="flex items-center justify-between gap-4 border-t border-[var(--color-border-default)] pt-3">
+ <p className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
+ {rows.length > 0 ? `${first}–${last}` : "0"}
+ {total !== undefined ? ` of ${total.toLocaleString()}` : ""}
+ </p>
+ <div className="flex items-center gap-2">
+ <PageButton
+ onClick={() => setPage((p) => Math.max(0, p - 1))}
+ disabled={page === 0 || isLoading}
+ >
+ Previous
+ </PageButton>
+ <PageButton
+ onClick={() => setPage((p) => p + 1)}
+ disabled={!hasNext || isLoading}
+ >
+ Next
+ </PageButton>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function PageButton({
+ onClick,
+ disabled,
+ children,
+}: {
+ onClick: () => void;
+ disabled: boolean;
+ children: React.ReactNode;
+}) {
return (
- <DecisionsTable
- decisions={data}
- filters={filters}
- onFiltersChange={setFilters}
- repoId={repoId}
- LinkComponent={Link}
- error={error}
- isLoading={isLoading}
- onRetry={() => mutate()}
- />
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={disabled}
+ className="rounded-md border border-[var(--color-border-default)] px-2.5 py-1 text-xs text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)] disabled:opacity-40 disabled:hover:border-[var(--color-border-default)] disabled:hover:text-[var(--color-text-secondary)]"
+ >
+ {children}
+ </button>
);
}
diff --git a/packages/web/src/components/repos/coordinator-health-panel.tsx b/packages/web/src/components/repos/coordinator-health-panel.tsx
index 74b3faaad..378c1d8f8 100644
--- a/packages/web/src/components/repos/coordinator-health-panel.tsx
+++ b/packages/web/src/components/repos/coordinator-health-panel.tsx
@@ -19,7 +19,9 @@ const STATUS_BADGE: Record<CoordinatorHealth["status"], string> = {
function StatRow({ label, value, help }: { label: string; value: string; help?: string }) {
return (
- <div className="flex items-center justify-between py-1.5 border-b border-[var(--color-border)] last:border-0">
+ // `--color-border` is defined in no stylesheet; the hairline this row
+ // claimed to have has never rendered. The token is `--color-border-default`.
+ <div className="flex items-center justify-between py-1.5 border-b border-[var(--color-border-default)] last:border-0">
<span
className={`text-xs text-[var(--color-text-secondary)] ${help ? "cursor-help underline decoration-dotted decoration-[var(--color-border-default)] underline-offset-2" : ""}`}
title={help}
diff --git a/packages/web/src/components/settings/connection-section.tsx b/packages/web/src/components/settings/connection-section.tsx
index d583da791..9225fe268 100644
--- a/packages/web/src/components/settings/connection-section.tsx
+++ b/packages/web/src/components/settings/connection-section.tsx
@@ -1,47 +1,69 @@
"use client";
import { useState, useEffect, useRef } from "react";
-import { CheckCircle, XCircle, Loader2 } from "lucide-react";
-import { toast } from "sonner";
+import { Loader2 } from "lucide-react";
import { config } from "@/lib/config";
import { getHealth } from "@/lib/api/health";
-import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@repowise-dev/ui/ui/card";
-import { Label } from "@repowise-dev/ui/ui/label";
+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 type { HealthResponse } from "@/lib/api/types";
import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
+/**
+ * Server connection, and the page's only connection test.
+ *
+ * `ProviderSection` used to ship a second "Server Connection" card with its own
+ * Test button hitting the same `/api/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.
+ */
export function ConnectionSection() {
const [apiUrl, setApiUrl] = useState("");
const [apiKey, setApiKey] = useState("");
const [testing, setTesting] = useState(false);
const [health, setHealth] = useState<HealthResponse | null>(null);
const [error, setError] = useState<string | null>(null);
-
- useEffect(() => {
- setApiUrl(config.getApiUrl());
- setApiKey(config.getApiKey());
- }, []);
+ const [saveState, setSaveState] = useState<SaveState>("idle");
const initialUrlRef = useRef("");
const initialKeyRef = useRef("");
+ const savedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
+ setApiUrl(config.getApiUrl());
+ setApiKey(config.getApiKey());
initialUrlRef.current = config.getApiUrl();
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) {
- initialUrlRef.current = apiUrl;
- initialKeyRef.current = apiKey;
- toast.success("Connection settings saved");
- }
+ 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);
}
async function testConnection() {
@@ -50,8 +72,7 @@ export function ConnectionSection() {
setHealth(null);
setError(null);
try {
- const h = await getHealth();
- setHealth(h);
+ setHealth(await getHealth());
} catch (e) {
setError(toFriendlyMessage(e, "Connection failed"));
} finally {
@@ -60,16 +81,18 @@ export function ConnectionSection() {
}
return (
- <Card>
- <CardHeader>
- <CardTitle className="text-base">API Connection</CardTitle>
- <CardDescription>
- Configure how the UI connects to your repowise server.
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="space-y-1.5">
- <Label htmlFor="api-url">Server URL</Label>
+ <OverviewSection
+ title="Server"
+ description="How this dashboard reaches your repowise server. Stored in this browser, not on the server."
+ flush
+ action={<SaveIndicator state={saveState} />}
+ >
+ <SettingsRows>
+ <SettingsRow
+ label="Server URL"
+ htmlFor="api-url"
+ hint="Leave blank to use the same origin, which is what a Next.js proxy setup wants."
+ >
<Input
id="api-url"
placeholder="http://localhost:7337"
@@ -78,52 +101,56 @@ export function ConnectionSection() {
onBlur={save}
className="font-mono"
/>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Leave blank to use the same origin (when proxied via Next.js).
- </p>
- </div>
+ </SettingsRow>
- <div className="space-y-1.5">
- <Label htmlFor="api-key">API Key</Label>
+ <SettingsRow
+ label="API key"
+ htmlFor="api-key"
+ hint="Only needed when REPOWISE_API_KEY is set on the server."
+ >
<Input
id="api-key"
type="password"
- placeholder="Optional — only required if REPOWISE_API_KEY is set on the server"
+ placeholder="Optional"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
onBlur={save}
className="font-mono"
/>
- </div>
+ </SettingsRow>
- <div className="flex items-center gap-3">
- <Button
- variant="outline"
- size="sm"
- onClick={testConnection}
- disabled={testing}
- >
- {testing ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- "Test Connection"
- )}
- </Button>
+ <SettingsRow
+ label="Connection"
+ hint="Checks that the server answers and reports what it is running."
+ >
+ <div className="flex flex-wrap items-center gap-3">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={testConnection}
+ disabled={testing}
+ >
+ {testing ? (
+ <>
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ Testing
+ </>
+ ) : (
+ "Test connection"
+ )}
+ </Button>
- {health && (
- <span className="flex items-center gap-1.5 text-sm text-[var(--color-fresh)]">
- <CheckCircle className="h-4 w-4" />
- Connected · v{health.version} · DB {health.db}
- </span>
- )}
- {error && (
- <span className="flex items-center gap-1.5 text-sm text-[var(--color-outdated)]">
- <XCircle className="h-4 w-4" />
- {error}
- </span>
- )}
- </div>
- </CardContent>
- </Card>
+ {health && (
+ <StatusLine status="ok">
+ <span className="tabular-nums">
+ Connected · v{health.version} · DB {health.db}
+ </span>
+ </StatusLine>
+ )}
+ {error && <StatusLine status="error">{error}</StatusLine>}
+ </div>
+ </SettingsRow>
+ </SettingsRows>
+ </OverviewSection>
);
}
diff --git a/packages/web/src/components/settings/display-section.tsx b/packages/web/src/components/settings/display-section.tsx
index bc795f616..d078b7df8 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, useState } from "react";
-import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@repowise-dev/ui/ui/card";
-import { Label } from "@repowise-dev/ui/ui/label";
+import { useEffect, useRef, useState } from "react";
+import { OverviewSection } from "@repowise-dev/ui/overview";
import {
Select,
SelectContent,
@@ -10,46 +9,66 @@ import {
SelectTrigger,
SelectValue,
} from "@repowise-dev/ui/ui/select";
+import {
+ SettingsRow,
+ SettingsRows,
+ SaveIndicator,
+ type SaveState,
+} from "@repowise-dev/ui/settings";
import { DEFAULT_WEEKEND_PRESET, WEEKEND_PRESETS } from "@repowise-dev/ui/stats";
import { config } from "@/lib/config";
/** Reader-local display preferences for the stats surfaces. */
export function DisplaySection() {
const [weekend, setWeekend] = useState(DEFAULT_WEEKEND_PRESET.id);
+ const [saveState, setSaveState] = useState<SaveState>("idle");
+ const savedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
// Read after mount so SSR and the first client render agree.
useEffect(() => {
setWeekend(config.getWeekend() || DEFAULT_WEEKEND_PRESET.id);
}, []);
+ useEffect(
+ () => () => {
+ if (savedTimer.current) clearTimeout(savedTimer.current);
+ },
+ [],
+ );
+
function handleChange(v: string) {
setWeekend(v);
config.setWeekend(v);
+ setSaveState("saved");
+ if (savedTimer.current) clearTimeout(savedTimer.current);
+ savedTimer.current = setTimeout(() => setSaveState("idle"), 2000);
}
return (
- <Card>
- <CardHeader>
- <CardTitle className="text-base">Display</CardTitle>
- <CardDescription>How stats are presented in this browser.</CardDescription>
- </CardHeader>
- <CardContent className="space-y-1.5">
- <Label>Weekend days</Label>
- <Select value={weekend} onValueChange={handleChange}>
- <SelectTrigger className="w-64">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {WEEKEND_PRESETS.map((p) => (
- <SelectItem key={p.id} value={p.id}>
- {p.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Drives the &ldquo;on weekends&rdquo; share on the coding-rhythm heatmap.
- </p>
- </CardContent>
- </Card>
+ <OverviewSection
+ title="Display"
+ description="How stats are presented in this browser. Nothing here changes the index."
+ action={<SaveIndicator state={saveState} />}
+ >
+ <SettingsRows>
+ <SettingsRow
+ label="Weekend days"
+ hint="Drives the “on weekends” share on the coding-rhythm heatmap."
+ >
+ <Select value={weekend} onValueChange={handleChange}>
+ <SelectTrigger className="w-full sm:w-64">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {WEEKEND_PRESETS.map((p) => (
+ <SelectItem key={p.id} value={p.id}>
+ {p.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+ </SettingsRows>
+ </OverviewSection>
);
}
diff --git a/packages/web/src/components/settings/mcp-section.tsx b/packages/web/src/components/settings/mcp-section.tsx
index 0521f08d7..1f9958158 100644
--- a/packages/web/src/components/settings/mcp-section.tsx
+++ b/packages/web/src/components/settings/mcp-section.tsx
@@ -1,9 +1,7 @@
"use client";
-import { useState } from "react";
-import { Copy, Check } from "lucide-react";
-import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@repowise-dev/ui/ui/card";
-import { Button } from "@repowise-dev/ui/ui/button";
+import { OverviewSection } from "@repowise-dev/ui/overview";
+import { CopyLine, SettingsRow, SettingsRows } from "@repowise-dev/ui/settings";
const MCP_CONFIG = JSON.stringify(
{
@@ -19,46 +17,19 @@ const MCP_CONFIG = JSON.stringify(
);
export function McpSection() {
- const [copied, setCopied] = useState(false);
-
- async function copy() {
- await navigator.clipboard.writeText(MCP_CONFIG);
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- }
-
return (
- <Card>
- <CardHeader>
- <CardTitle className="text-base">MCP Config</CardTitle>
- <CardDescription>
- Add to your Claude Code, Cursor, or Cline MCP config to enable AI-powered codebase Q&amp;A.
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-3">
- <div className="relative">
- <pre className="rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 text-xs font-mono text-[var(--color-text-secondary)] overflow-x-auto">
- {MCP_CONFIG}
- </pre>
- <Button
- variant="ghost"
- size="icon"
- onClick={copy}
- className="absolute right-2 top-2 h-7 w-7"
- >
- {copied ? (
- <Check className="h-3.5 w-3.5 text-[var(--color-fresh)]" />
- ) : (
- <Copy className="h-3.5 w-3.5" />
- )}
- </Button>
- </div>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Replace <code className="font-mono">/path/to/your/repo</code> with the local path
- of the repository you want to query. Index the repository first so there is
- documentation to serve.
- </p>
- </CardContent>
- </Card>
+ <OverviewSection
+ title="Editor config"
+ description="Paste this into Claude Code, Cursor or Cline to let the agent query this codebase. Replace the path with the repo you want served, and index it first so there is something to answer from."
+ >
+ <SettingsRows>
+ <SettingsRow
+ label="MCP server"
+ hint="Goes in your editor's MCP config file."
+ >
+ <CopyLine value={MCP_CONFIG} />
+ </SettingsRow>
+ </SettingsRows>
+ </OverviewSection>
);
}
diff --git a/packages/web/src/components/settings/mcp-tools-section.tsx b/packages/web/src/components/settings/mcp-tools-section.tsx
index 071d0f5db..eff733409 100644
--- a/packages/web/src/components/settings/mcp-tools-section.tsx
+++ b/packages/web/src/components/settings/mcp-tools-section.tsx
@@ -1,15 +1,7 @@
"use client";
-import { useCallback, useEffect, useMemo, useState } from "react";
-import {
- Card,
- CardContent,
- CardHeader,
- CardTitle,
- CardDescription,
-} from "@repowise-dev/ui/ui/card";
-import { Badge } from "@repowise-dev/ui/ui/badge";
-import { Button } from "@repowise-dev/ui/ui/button";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { OverviewSection } from "@repowise-dev/ui/overview";
import { Switch } from "@repowise-dev/ui/ui/switch";
import {
Select,
@@ -18,8 +10,15 @@ import {
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 { getMcpToolSurface, updateMcpTools } from "@/lib/api/mcp-tools";
+import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
import type { McpToolSurface } from "@/lib/api/types";
interface RepoOption {
@@ -31,17 +30,39 @@ function enabledNames(surface: McpToolSurface): Set<string> {
return new Set(surface.tools.filter((t) => t.enabled).map((t) => t.name));
}
+/** Selection as +/- deltas off the default set, so it survives a release that
+ * changes which tools are on by default. */
+function toDeltas(surface: McpToolSurface, enabled: Set<string>): string[] {
+ const defaults = new Set(
+ surface.tools.filter((t) => t.default).map((t) => t.name),
+ );
+ const added = [...enabled].filter((n) => !defaults.has(n)).sort();
+ const removed = [...defaults].filter((n) => !enabled.has(n)).sort();
+ return [...added.map((n) => `+${n}`), ...removed.map((n) => `-${n}`)];
+}
+
+/**
+ * Which tools the MCP server exposes.
+ *
+ * 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.
+ */
export function McpToolsSection() {
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 [saving, setSaving] = useState(false);
+ const [saveState, setSaveState] = useState<SaveState>("idle");
const [error, setError] = useState<string | null>(null);
- const [saved, setSaved] = useState(false);
- // Load the repo list once and pick a default (the primary, else the first).
+ const savedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // Guards against an older in-flight save landing after a newer one.
+ const saveSeq = useRef(0);
+
useEffect(() => {
listRepos()
.then((rows) => {
@@ -53,11 +74,18 @@ export function McpToolsSection() {
if (opts.length === 0) setLoading(false);
})
.catch((e) => {
- setError(String(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);
@@ -66,7 +94,7 @@ export function McpToolsSection() {
setSurface(s);
setEnabled(enabledNames(s));
})
- .catch((e) => setError(String(e)))
+ .catch((e) => setError(toFriendlyMessage(e, "Could not load tools")))
.finally(() => setLoading(false));
}, []);
@@ -74,74 +102,75 @@ export function McpToolsSection() {
if (repoId) loadSurface(repoId);
}, [repoId, loadSurface]);
- function toggle(name: string, on: boolean) {
- setSaved(false);
- setEnabled((prev) => {
- const next = new Set(prev);
- if (on) next.add(name);
- else next.delete(name);
- return next;
- });
- }
+ async function toggle(name: string, on: boolean) {
+ if (!surface || !repoId) return;
- const dirty = useMemo(() => {
- if (!surface) return false;
- const server = enabledNames(surface);
- if (server.size !== enabled.size) return true;
- for (const n of enabled) if (!server.has(n)) return true;
- return false;
- }, [surface, enabled]);
+ const next = new Set(enabled);
+ if (on) next.add(name);
+ else next.delete(name);
+ setEnabled(next);
- async function save() {
- if (!surface || !repoId) return;
- setSaving(true);
+ const seq = ++saveSeq.current;
+ setSaveState("saving");
setError(null);
- // Store the selection as +/- deltas off the default surface so it stays
- // correct if the default set changes in a future release.
- const defaults = new Set(
- surface.tools.filter((t) => t.default).map((t) => t.name),
- );
- const added = [...enabled].filter((n) => !defaults.has(n)).sort();
- const removed = [...defaults].filter((n) => !enabled.has(n)).sort();
- const tools = [...added.map((n) => `+${n}`), ...removed.map((n) => `-${n}`)];
try {
+ const deltas = toDeltas(surface, next);
const updated = await updateMcpTools({
repo_id: repoId,
- tools: tools.length ? tools : null,
+ tools: deltas.length ? deltas : null,
});
+ if (seq !== saveSeq.current) return;
setSurface(updated);
setEnabled(enabledNames(updated));
- setSaved(true);
+ setSaveState("saved");
+ if (savedTimer.current) clearTimeout(savedTimer.current);
+ savedTimer.current = setTimeout(() => setSaveState("idle"), 2000);
} catch (e) {
- setError(String(e));
- } finally {
- setSaving(false);
+ 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");
}
}
+ 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
+ ? "Workspace mode, so workspace-only tools are available."
+ : "Single-repo mode, so workspace-only tools are unavailable here.";
+ return `${on} of ${available.length} tools exposed. ${mode}`;
+ }, [surface, enabled]);
+
return (
- <Card>
- <CardHeader>
- <CardTitle className="text-base">MCP tool surface</CardTitle>
- <CardDescription>
- Choose which tools the MCP server exposes for a repo. Changes are saved
- to its <code className="font-mono">.repowise/config.yaml</code> and take
- effect the next time you start <code className="font-mono">repowise mcp</code>{" "}
- for that repo.
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- {repos.length === 0 && !loading && (
- <p className="text-sm text-[var(--color-text-tertiary)]">
- No indexed repos found. Add and index a repository first.
- </p>
- )}
-
- {repos.length > 1 && (
- <div className="flex items-center gap-2">
- <span className="text-sm text-[var(--color-text-secondary)]">Repo</span>
+ <OverviewSection
+ title="Tool surface"
+ // 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 ??
+ "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."
+ }
+ action={<SaveIndicator state={saveState} error={error} />}
+ >
+ {repos.length === 0 && !loading && (
+ <p className="text-sm text-[var(--color-text-tertiary)]">
+ Index a repository and its tool surface shows up here.
+ </p>
+ )}
+
+ {repos.length > 1 && (
+ <SettingsRows>
+ <SettingsRow
+ label="Repository"
+ hint="The surface is stored per repo."
+ >
<Select value={repoId ?? undefined} onValueChange={setRepoId}>
- <SelectTrigger className="w-56">
+ <SelectTrigger className="w-full sm:w-64">
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -152,74 +181,53 @@ export function McpToolsSection() {
))}
</SelectContent>
</Select>
- </div>
- )}
-
- {surface && !loading && (
- <>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- {surface.is_workspace
- ? "Workspace mode — workspace-only tools are available."
- : "Single-repo mode — workspace-only tools are unavailable here."}
- </p>
-
- <div className="divide-y divide-[var(--color-border-default)] rounded border border-[var(--color-border-default)]">
- {surface.tools.map((tool) => {
- const locked = tool.requires_workspace && !surface.is_workspace;
- return (
- <div
- key={tool.name}
- className="flex items-start gap-3 px-3 py-2.5"
- >
- <Switch
- checked={enabled.has(tool.name)}
- disabled={locked || saving}
- onCheckedChange={(v) => toggle(tool.name, v)}
- className="mt-0.5"
- />
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <code className="font-mono text-sm">{tool.name}</code>
- {tool.requires_workspace && (
- <Badge variant="outline" className="text-[10px]">
- workspace
- </Badge>
- )}
- {!tool.default && !tool.requires_workspace && (
- <Badge variant="outline" className="text-[10px]">
- opt-in
- </Badge>
- )}
- </div>
- {tool.description && (
- <p className="text-xs text-[var(--color-text-tertiary)] mt-0.5">
- {tool.description}
- </p>
- )}
- </div>
+ </SettingsRow>
+ </SettingsRows>
+ )}
+
+ {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)]">
+ workspace only
+ </span>
+ )}
</div>
- );
- })}
- </div>
-
- <div className="flex items-center gap-3">
- <Button onClick={save} disabled={!dirty || saving} size="sm">
- {saving ? "Saving…" : "Save"}
- </Button>
- {saved && !dirty && (
- <span className="text-sm text-[var(--color-fresh)]">Saved</span>
- )}
- {dirty && (
- <span className="text-xs text-[var(--color-text-tertiary)]">
- Unsaved changes
- </span>
- )}
- </div>
- </>
- )}
-
- {error && <p className="text-sm text-[var(--color-error)]">{error}</p>}
- </CardContent>
- </Card>
+ {tool.description && (
+ <p className="mt-0.5 text-xs leading-relaxed text-[var(--color-text-tertiary)]">
+ {tool.description}
+ </p>
+ )}
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </OverviewSection>
);
}
diff --git a/packages/web/src/components/settings/provider-section.tsx b/packages/web/src/components/settings/provider-section.tsx
index e0e3315fe..7a3bbaebe 100644
--- a/packages/web/src/components/settings/provider-section.tsx
+++ b/packages/web/src/components/settings/provider-section.tsx
@@ -1,11 +1,9 @@
"use client";
-import { useState, useEffect } from "react";
+import { useEffect, useRef, useState } from "react";
import { config } from "@/lib/config";
-import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@repowise-dev/ui/ui/card";
-import { Label } from "@repowise-dev/ui/ui/label";
+import { OverviewSection } from "@repowise-dev/ui/overview";
import { Input } from "@repowise-dev/ui/ui/input";
-import { Badge } from "@repowise-dev/ui/ui/badge";
import {
Select,
SelectContent,
@@ -13,6 +11,13 @@ import {
SelectTrigger,
SelectValue,
} from "@repowise-dev/ui/ui/select";
+import {
+ SettingsRow,
+ SettingsRows,
+ SaveIndicator,
+ EnvVarLine,
+ type SaveState,
+} from "@repowise-dev/ui/settings";
const PROVIDERS = ["gemini", "openai", "anthropic", "deepseek", "kimi", "opencode", "ollama", "litellm", "mock"] as const;
const EMBEDDERS = ["mock", "gemini", "openai", "openrouter", "ollama"] as const;
@@ -49,22 +54,29 @@ const EMBEDDER_ENV_VARS: Record<string, string[]> = {
mock: [],
};
-type TestStatus = "idle" | "testing" | "ok" | "error";
-
+/**
+ * Model and embedder defaults for init/sync triggered from the UI.
+ *
+ * This used to render a second card, "Server Connection", with its own Test
+ * button against the same `/api/health` that `ConnectionSection` already tests
+ * — a hand-rolled `<button>` painted with `--color-border`, a token defined in
+ * no stylesheet, reporting with literal ✓/✗ glyphs. It is gone; what it
+ * uniquely showed, the provider the *server* is configured with, is a line
+ * here where it belongs.
+ */
export function ProviderSection() {
const [provider, setProvider] = useState("gemini");
const [model, setModel] = useState("");
const [embedder, setEmbedder] = useState("mock");
- const [testStatus, setTestStatus] = useState<TestStatus>("idle");
- const [testError, setTestError] = useState("");
const [serverProvider, setServerProvider] = useState<string | null>(null);
- const [expanded, setExpanded] = useState<string | null>(null);
+ const [saveState, setSaveState] = useState<SaveState>("idle");
+
+ const savedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
setProvider(config.getProvider());
setModel(config.getModel());
setEmbedder(config.getEmbedder());
- // Fetch current server config from /api/health
fetch("/api/health")
.then((r) => r.json())
.then((data) => {
@@ -73,101 +85,93 @@ export function ProviderSection() {
.catch(() => {});
}, []);
+ useEffect(
+ () => () => {
+ if (savedTimer.current) clearTimeout(savedTimer.current);
+ },
+ [],
+ );
+
+ function flashSaved() {
+ setSaveState("saved");
+ if (savedTimer.current) clearTimeout(savedTimer.current);
+ savedTimer.current = setTimeout(() => setSaveState("idle"), 2000);
+ }
+
function handleProviderChange(v: string) {
setProvider(v);
config.setProvider(v);
- setTestStatus("idle");
+ flashSaved();
}
function handleEmbedderChange(v: string) {
setEmbedder(v);
config.setEmbedder(v);
+ flashSaved();
}
- async function handleTestConnection() {
- setTestStatus("testing");
- setTestError("");
- try {
- const res = await fetch("/api/health");
- const data = await res.json();
- if (res.ok && data.status === "healthy") {
- setTestStatus("ok");
- } else {
- setTestStatus("error");
- setTestError(data.status ?? "Server returned non-healthy status");
- }
- } catch (err) {
- setTestStatus("error");
- setTestError(String(err));
- }
+ function handleModelBlur() {
+ config.setModel(model);
+ flashSaved();
}
const providerInfo = PROVIDER_ENV_VARS[provider];
const embedderVars = EMBEDDER_ENV_VARS[embedder] ?? [];
return (
- <div className="space-y-4">
- <Card>
- <CardHeader>
- <CardTitle className="text-base">Provider &amp; Model</CardTitle>
- <CardDescription>
- Defaults used when triggering init or sync from the UI.
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="grid grid-cols-2 gap-4">
- <div className="space-y-1.5">
- <Label>Provider</Label>
- <Select value={provider} onValueChange={handleProviderChange}>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {PROVIDERS.map((p) => (
- <SelectItem key={p} value={p}>
- {p}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
-
- <div className="space-y-1.5">
- <Label htmlFor="model">Model</Label>
- <Input
- id="model"
- placeholder={MODEL_PLACEHOLDERS[provider] ?? "model name"}
- value={model}
- onChange={(e) => setModel(e.target.value)}
- onBlur={() => config.setModel(model)}
- className="font-mono"
- />
- </div>
- </div>
-
- {providerInfo && providerInfo.vars.length > 0 && (
- <div className="rounded-md border border-dashed p-3 space-y-1.5">
- <p className="text-xs font-medium text-[var(--color-text-secondary)]">
- Required env vars for {provider}:
- </p>
- <div className="flex flex-wrap gap-1.5">
- {providerInfo.vars.map((v) => (
- <code
- key={v}
- className="text-xs bg-[var(--color-bg-secondary)] px-1.5 py-0.5 rounded font-mono"
- >
- {v}
- </code>
+ <OverviewSection
+ title="Model defaults"
+ description={
+ serverProvider
+ ? `Used when you trigger init or sync from this dashboard. The server itself is currently configured with ${serverProvider}.`
+ : "Used when you trigger init or sync from this dashboard."
+ }
+ action={<SaveIndicator state={saveState} />}
+ >
+ <SettingsRows>
+ <SettingsRow
+ label="Provider"
+ hint={providerInfo?.installHint}
+ >
+ <div className="space-y-2">
+ <Select value={provider} onValueChange={handleProviderChange}>
+ <SelectTrigger className="w-full sm:w-64">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {PROVIDERS.map((p) => (
+ <SelectItem key={p} value={p}>
+ {p}
+ </SelectItem>
))}
- </div>
- <p className="text-xs text-[var(--color-text-tertiary)]">{providerInfo.installHint}</p>
- </div>
- )}
-
- <div className="space-y-1.5">
- <Label>Embedder</Label>
+ </SelectContent>
+ </Select>
+ {providerInfo && <EnvVarLine vars={providerInfo.vars} />}
+ </div>
+ </SettingsRow>
+
+ <SettingsRow
+ label="Model"
+ htmlFor="model"
+ hint="Leave blank to use the provider's default."
+ >
+ <Input
+ id="model"
+ placeholder={MODEL_PLACEHOLDERS[provider] ?? "model name"}
+ value={model}
+ onChange={(e) => setModel(e.target.value)}
+ onBlur={handleModelBlur}
+ className="font-mono sm:max-w-md"
+ />
+ </SettingsRow>
+
+ <SettingsRow
+ label="Embedder"
+ hint="What semantic search is built from. The mock embedder disables it."
+ >
+ <div className="space-y-2">
<Select value={embedder} onValueChange={handleEmbedderChange}>
- <SelectTrigger className="w-48">
+ <SelectTrigger className="w-full sm:w-64">
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -178,59 +182,40 @@ export function ProviderSection() {
))}
</SelectContent>
</Select>
- {embedderVars.length > 0 && (
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Requires{" "}
- {embedderVars.map((v) => (
- <code key={v} className="font-mono">{v}</code>
- ))}{" "}
- — set <code className="font-mono">REPOWISE_EMBEDDER={embedder}</code> on the server.
- </p>
- )}
- {embedder === "mock" && (
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Using mock embedder — semantic search disabled. Set{" "}
- <code className="font-mono">REPOWISE_EMBEDDER=gemini</code> or{" "}
- <code className="font-mono">REPOWISE_EMBEDDER=openai</code> for real RAG.
- </p>
- )}
- </div>
- </CardContent>
- </Card>
-
- <Card>
- <CardHeader>
- <CardTitle className="text-base">Server Connection</CardTitle>
- <CardDescription>
- Test that the repowise server is reachable and healthy.
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-3">
- {serverProvider && (
- <p className="text-sm text-[var(--color-text-secondary)]">
- Server configured with provider:{" "}
- <Badge variant="outline" className="font-mono text-xs">{serverProvider}</Badge>
- </p>
- )}
- <div className="flex items-center gap-3">
- <button
- onClick={handleTestConnection}
- disabled={testStatus === "testing"}
- className="text-sm px-3 py-1.5 rounded-md border border-[var(--color-border)] hover:bg-[var(--color-bg-secondary)] disabled:opacity-50 transition-colors"
- >
- {testStatus === "testing" ? "Testing…" : "Test connection"}
- </button>
- {testStatus === "ok" && (
- <span className="text-sm text-[var(--color-success)]">✓ Server healthy</span>
- )}
- {testStatus === "error" && (
- <span className="text-sm text-[var(--color-error)]">
- ✗ {testError || "Connection failed"}
- </span>
+ {embedder === "mock" ? (
+ <EnvVarLine
+ vars={[]}
+ note={
+ <>
+ Semantic search is off. Set{" "}
+ <code className="font-mono text-[var(--color-text-secondary)]">
+ REPOWISE_EMBEDDER=gemini
+ </code>{" "}
+ or{" "}
+ <code className="font-mono text-[var(--color-text-secondary)]">
+ REPOWISE_EMBEDDER=openai
+ </code>{" "}
+ on the server for real retrieval.
+ </>
+ }
+ />
+ ) : (
+ <EnvVarLine
+ vars={embedderVars}
+ note={
+ <>
+ Set{" "}
+ <code className="font-mono text-[var(--color-text-secondary)]">
+ REPOWISE_EMBEDDER={embedder}
+ </code>{" "}
+ on the server.
+ </>
+ }
+ />
)}
</div>
- </CardContent>
- </Card>
- </div>
+ </SettingsRow>
+ </SettingsRows>
+ </OverviewSection>
);
}
diff --git a/packages/web/src/components/settings/webhook-section.tsx b/packages/web/src/components/settings/webhook-section.tsx
index 79ec2f35e..f2d83722c 100644
--- a/packages/web/src/components/settings/webhook-section.tsx
+++ b/packages/web/src/components/settings/webhook-section.tsx
@@ -1,37 +1,8 @@
"use client";
import { useEffect, useState } from "react";
-import { Copy, Check } from "lucide-react";
-import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@repowise-dev/ui/ui/card";
-import { Button } from "@repowise-dev/ui/ui/button";
-
-function CopyField({ label, value }: { label: string; value: string }) {
- const [copied, setCopied] = useState(false);
-
- async function copy() {
- await navigator.clipboard.writeText(value);
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- }
-
- return (
- <div className="space-y-1">
- <p className="text-xs text-[var(--color-text-tertiary)]">{label}</p>
- <div className="flex items-center gap-2">
- <code className="flex-1 rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-1.5 text-xs font-mono text-[var(--color-text-secondary)] truncate">
- {value}
- </code>
- <Button variant="ghost" size="icon" onClick={copy} className="h-7 w-7 shrink-0">
- {copied ? (
- <Check className="h-3.5 w-3.5 text-[var(--color-fresh)]" />
- ) : (
- <Copy className="h-3.5 w-3.5" />
- )}
- </Button>
- </div>
- </div>
- );
-}
+import { OverviewSection } from "@repowise-dev/ui/overview";
+import { CopyLine, SettingsRow, SettingsRows } from "@repowise-dev/ui/settings";
/**
* Best-effort server URL for webhook registration: the configured API URL
@@ -53,36 +24,36 @@ export function WebhookSection() {
}, []);
return (
- <Card>
- <CardHeader>
- <CardTitle className="text-base">Webhook Config</CardTitle>
- <CardDescription>
- Register these URLs in GitHub or GitLab to trigger automatic re-sync on push.
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <CopyField label="GitHub Webhook URL" value={`${serverUrl}/api/webhooks/github`} />
- <CopyField label="GitLab Webhook URL" value={`${serverUrl}/api/webhooks/gitlab`} />
- <p className="text-xs text-[var(--color-text-tertiary)]">
- URLs use this dashboard&apos;s server address. If GitHub/GitLab can&apos;t
- reach it, substitute your server&apos;s public hostname.
- </p>
-
- <div className="rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 space-y-1">
- <p className="text-xs font-medium text-[var(--color-text-secondary)]">
- Required env vars on the server
- </p>
- <p className="text-xs font-mono text-[var(--color-text-tertiary)]">
- REPOWISE_GITHUB_WEBHOOK_SECRET=your-secret
- </p>
- <p className="text-xs font-mono text-[var(--color-text-tertiary)]">
- REPOWISE_GITLAB_WEBHOOK_TOKEN=your-token
- </p>
- <p className="text-xs text-[var(--color-text-tertiary)] mt-1">
- Omit these vars to skip signature verification during development.
- </p>
- </div>
- </CardContent>
- </Card>
+ <OverviewSection
+ title="Webhooks"
+ description="Register one of these in GitHub or GitLab and a push re-syncs the index. The URLs use this dashboard's address, so substitute a public hostname if the host cannot reach it."
+ >
+ <SettingsRows>
+ <SettingsRow label="GitHub" hint="Content type: application/json.">
+ <CopyLine value={`${serverUrl}/api/webhooks/github`} />
+ </SettingsRow>
+
+ <SettingsRow label="GitLab" hint="Push events.">
+ <CopyLine value={`${serverUrl}/api/webhooks/gitlab`} />
+ </SettingsRow>
+
+ <SettingsRow
+ label="Signature verification"
+ hint="Omit both to skip verification while developing locally."
+ >
+ <div className="space-y-1.5">
+ <p className="font-mono text-xs text-[var(--color-text-secondary)]">
+ REPOWISE_GITHUB_WEBHOOK_SECRET=your-secret
+ </p>
+ <p className="font-mono text-xs text-[var(--color-text-secondary)]">
+ REPOWISE_GITLAB_WEBHOOK_TOKEN=your-token
+ </p>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Set on the server, not here.
+ </p>
+ </div>
+ </SettingsRow>
+ </SettingsRows>
+ </OverviewSection>
);
}
diff --git a/packages/web/src/components/stats/people-tab.tsx b/packages/web/src/components/stats/people-tab.tsx
index 6a0d15b40..4f259e7dc 100644
--- a/packages/web/src/components/stats/people-tab.tsx
+++ b/packages/web/src/components/stats/people-tab.tsx
@@ -65,7 +65,7 @@ export function PeopleTab({ data, repoId }: { data: StatsHighlights; repoId: str
<p className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4 text-sm text-[var(--color-text-secondary)]">
Commit-hour habits need each commit&apos;s local timezone, which this index was built
before repowise captured. Run{" "}
- <code className="rounded bg-[var(--color-bg-muted)] px-1.5 py-0.5 font-mono text-xs">
+ <code className="rounded bg-[var(--color-bg-inset)] px-1.5 py-0.5 font-mono text-xs">
repowise update
</code>{" "}
to backfill it, no re-index required.
diff --git a/packages/web/src/components/zoom/zoom-breadcrumb.tsx b/packages/web/src/components/zoom/zoom-breadcrumb.tsx
index e46835fc1..b01546200 100644
--- a/packages/web/src/components/zoom/zoom-breadcrumb.tsx
+++ b/packages/web/src/components/zoom/zoom-breadcrumb.tsx
@@ -27,7 +27,7 @@ export function ZoomBreadcrumb({ chain, onCrumb }: ZoomBreadcrumbProps) {
<button
type="button"
onClick={() => onCrumb(root.id)}
- className="flex shrink-0 items-center gap-1 rounded px-1.5 py-1 hover:bg-[var(--color-bg-hover)] hover:text-[var(--color-text-primary)]"
+ className="flex shrink-0 items-center gap-1 rounded px-1.5 py-1 hover:bg-[var(--color-bg-wash-hover)] hover:text-[var(--color-text-primary)]"
title={root.name}
>
<Home className="h-3.5 w-3.5" />
@@ -46,7 +46,7 @@ export function ZoomBreadcrumb({ chain, onCrumb }: ZoomBreadcrumbProps) {
<button
type="button"
onClick={() => onCrumb(node.id)}
- className="max-w-[12rem] truncate rounded px-1.5 py-1 hover:bg-[var(--color-bg-hover)] hover:text-[var(--color-text-primary)]"
+ className="max-w-[12rem] truncate rounded px-1.5 py-1 hover:bg-[var(--color-bg-wash-hover)] hover:text-[var(--color-text-primary)]"
title={node.path || node.name}
>
{node.name}
diff --git a/packages/web/src/components/zoom/zoom-detail-panel.tsx b/packages/web/src/components/zoom/zoom-detail-panel.tsx
index 02d979710..5c19dc59c 100644
--- a/packages/web/src/components/zoom/zoom-detail-panel.tsx
+++ b/packages/web/src/components/zoom/zoom-detail-panel.tsx
@@ -76,7 +76,7 @@ export function ZoomDetailPanel({ node, repoId, onClose, onZoom }: ZoomDetailPan
type="button"
onClick={onClose}
aria-label="Close details"
- className="shrink-0 rounded p-1 text-[var(--color-text-muted)] hover:bg-[var(--color-bg-hover)] hover:text-[var(--color-text-primary)]"
+ className="shrink-0 rounded p-1 text-[var(--color-text-muted)] hover:bg-[var(--color-bg-wash-hover)] hover:text-[var(--color-text-primary)]"
>
<X className="h-4 w-4" />
</button>
@@ -129,7 +129,7 @@ export function ZoomDetailPanel({ node, repoId, onClose, onZoom }: ZoomDetailPan
{isFile && node.path && (
<Link
href={fileHref(repoId, node.path)}
- className="flex w-full items-center justify-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-3 py-1.5 text-xs font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"
+ className="flex w-full items-center justify-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-3 py-1.5 text-xs font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-bg-wash-hover)]"
>
<FileCode className="h-3.5 w-3.5" />
Open file page
diff --git a/packages/web/src/components/zoom/zoom-hint.tsx b/packages/web/src/components/zoom/zoom-hint.tsx
index 6b0248033..8e82477e2 100644
--- a/packages/web/src/components/zoom/zoom-hint.tsx
+++ b/packages/web/src/components/zoom/zoom-hint.tsx
@@ -59,7 +59,7 @@ export function ZoomHint() {
type="button"
onClick={dismiss}
aria-label="Dismiss hint"
- className="ml-1 shrink-0 rounded-full p-1 text-[var(--color-text-muted)] hover:bg-[var(--color-bg-hover)] hover:text-[var(--color-text-primary)]"
+ className="ml-1 shrink-0 rounded-full p-1 text-[var(--color-text-muted)] hover:bg-[var(--color-bg-wash-hover)] hover:text-[var(--color-text-primary)]"
>
<X className="h-3.5 w-3.5" />
</button>
diff --git a/packages/web/src/components/zoom/zoom-search.tsx b/packages/web/src/components/zoom/zoom-search.tsx
index 58bf85490..8085ca13c 100644
--- a/packages/web/src/components/zoom/zoom-search.tsx
+++ b/packages/web/src/components/zoom/zoom-search.tsx
@@ -115,7 +115,7 @@ export function ZoomSearch({ nodes, onPick }: ZoomSearchProps) {
}}
onMouseEnter={() => setActive(i)}
className={`flex w-full flex-col items-start px-2.5 py-1.5 text-left ${
- i === active ? "bg-[var(--color-bg-hover)]" : ""
+ i === active ? "bg-[var(--color-bg-wash-hover)]" : ""
}`}
>
<span className="font-medium text-[var(--color-text-primary)]">{node.name}</span>
diff --git a/tests/unit/server/test_decisions_counts.py b/tests/unit/server/test_decisions_counts.py
new file mode 100644
index 000000000..f4cde5787
--- /dev/null
+++ b/tests/unit/server/test_decisions_counts.py
@@ -0,0 +1,194 @@
+"""Tests for the decisions counts aggregate and priority ordering.
+
+Both exist because the decisions page reported "97 of 100" on a repository
+holding several hundred records: it counted the page it had fetched, and the
+list endpoint caps at 500. Counting rows is not measuring a total.
+"""
+
+from __future__ import annotations
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from tests.unit.server.conftest import create_test_repo
+
+
+async def _seed(
+ session_factory,
+ repo_id: str,
+ *,
+ title: str,
+ status: str,
+ confidence: float = 0.5,
+ source: str = "inline_marker",
+) -> str:
+ async with get_session(session_factory) as session:
+ rec = await crud.upsert_decision(
+ session,
+ repository_id=repo_id,
+ title=title,
+ status=status,
+ context="ctx",
+ decision="dec",
+ rationale="why",
+ source=source,
+ confidence=confidence,
+ )
+ return rec.id
+
+
+async def test_counts_are_measured_not_paged(client: AsyncClient, app) -> None:
+ """The total comes from a COUNT, so it is not bounded by the page size."""
+ repo = await create_test_repo(client)
+ sf = app.state.session_factory
+
+ for i in range(7):
+ await _seed(sf, repo["id"], title=f"Proposal {i}", status="proposed")
+ for i in range(2):
+ await _seed(sf, repo["id"], title=f"Rule {i}", status="active")
+ await _seed(sf, repo["id"], title="Old", status="superseded")
+
+ resp = await client.get(f"/api/repos/{repo['id']}/decisions/counts")
+ assert resp.status_code == 200
+ body = resp.json()
+
+ assert body == {
+ "total": 10,
+ "active": 2,
+ "proposed": 7,
+ "superseded": 1,
+ "deprecated": 0,
+ }
+
+ # And the total exceeds what a single small page would have reported.
+ page = await client.get(
+ f"/api/repos/{repo['id']}/decisions", params={"limit": 3}
+ )
+ assert len(page.json()) == 3
+ assert body["total"] == 10
+
+
+async def test_counts_zero_fill_absent_statuses(client: AsyncClient, app) -> None:
+ """The shape is stable even when a status has no rows."""
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"], title="Only one", status="active")
+
+ body = (await client.get(f"/api/repos/{repo['id']}/decisions/counts")).json()
+ assert body == {
+ "total": 1,
+ "active": 1,
+ "proposed": 0,
+ "superseded": 0,
+ "deprecated": 0,
+ }
+
+
+async def test_counts_respect_include_proposed(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ sf = app.state.session_factory
+ await _seed(sf, repo["id"], title="A rule", status="active")
+ await _seed(sf, repo["id"], title="A guess", status="proposed")
+
+ body = (
+ await client.get(
+ f"/api/repos/{repo['id']}/decisions/counts",
+ params={"include_proposed": "false"},
+ )
+ ).json()
+ assert body["total"] == 1
+ assert body["proposed"] == 0
+
+
+async def test_counts_route_is_not_shadowed_by_decision_id(
+ client: AsyncClient,
+) -> None:
+ """`/counts` must be declared above `/{decision_id}`.
+
+ FastAPI matches in declaration order, so below it the literal path is
+ looked up as a decision id and 404s.
+ """
+ repo = await create_test_repo(client)
+ resp = await client.get(f"/api/repos/{repo['id']}/decisions/counts")
+ assert resp.status_code == 200
+ assert "total" in resp.json()
+
+
+async def test_priority_sort_leads_with_confirmed_rules(
+ client: AsyncClient, app
+) -> None:
+ """Newest-first buried every active decision under fresh proposals."""
+ repo = await create_test_repo(client)
+ sf = app.state.session_factory
+
+ # Seeded oldest-first, so `recent` would invert this order entirely.
+ await _seed(sf, repo["id"], title="Confirmed rule", status="active", confidence=0.4)
+ await _seed(sf, repo["id"], title="Weak guess", status="proposed", confidence=0.2)
+ await _seed(sf, repo["id"], title="Strong guess", status="proposed", confidence=0.95)
+ await _seed(sf, repo["id"], title="Retired", status="superseded", confidence=0.9)
+
+ rows = (
+ await client.get(f"/api/repos/{repo['id']}/decisions")
+ ).json()
+ assert [r["title"] for r in rows] == [
+ "Confirmed rule",
+ "Strong guess",
+ "Weak guess",
+ "Retired",
+ ]
+
+
+async def test_recent_sort_is_still_available(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ sf = app.state.session_factory
+ await _seed(sf, repo["id"], title="First", status="active")
+ await _seed(sf, repo["id"], title="Second", status="proposed")
+
+ rows = (
+ await client.get(
+ f"/api/repos/{repo['id']}/decisions", params={"sort": "recent"}
+ )
+ ).json()
+ assert [r["title"] for r in rows] == ["Second", "First"]
+
+
+async def test_unknown_sort_is_rejected(client: AsyncClient) -> None:
+ repo = await create_test_repo(client)
+ resp = await client.get(
+ f"/api/repos/{repo['id']}/decisions", params={"sort": "sideways"}
+ )
+ assert resp.status_code == 422
+
+
+async def test_offset_pages_without_repeating_rows(
+ client: AsyncClient, app
+) -> None:
+ """Server-side paging: the table asks for a window, not the whole set."""
+ repo = await create_test_repo(client)
+ sf = app.state.session_factory
+ for i in range(5):
+ await _seed(sf, repo["id"], title=f"D{i}", status="proposed", confidence=1 - i / 10)
+
+ first = (
+ await client.get(
+ f"/api/repos/{repo['id']}/decisions", params={"limit": 2, "offset": 0}
+ )
+ ).json()
+ second = (
+ await client.get(
+ f"/api/repos/{repo['id']}/decisions", params={"limit": 2, "offset": 2}
+ )
+ ).json()
+
+ assert len(first) == 2
+ assert len(second) == 2
+ assert {r["id"] for r in first}.isdisjoint({r["id"] for r in second})