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(workspace): open contracts in a drawer, with search, paging and a needs-attention list (#2497)

Raghav Chamadiyaa982d6199583
diff --git a/packages/api-client/src/workspace.ts b/packages/api-client/src/workspace.ts
index abc6e7c61..07517c521 100644
--- a/packages/api-client/src/workspace.ts
+++ b/packages/api-client/src/workspace.ts
@@ -26,6 +26,12 @@ export async function getWorkspaceContracts(opts?: {
contract_type?: string;
repo?: string;
role?: string;
+ /** Every whitespace-separated term must appear in the id, file, symbol, repo or service. */
+ q?: string;
+ /** true: only contracts on a matched link; false: only those on none. */
+ linked?: boolean;
+ /** false omits the link rows; `total_links` is still counted. */
+ include_links?: boolean;
limit?: number;
offset?: number;
}): Promise<WorkspaceContractsResponse> {
@@ -33,6 +39,9 @@ export async function getWorkspaceContracts(opts?: {
if (opts?.contract_type) params.contract_type = opts.contract_type;
if (opts?.repo) params.repo = opts.repo;
if (opts?.role) params.role = opts.role;
+ if (opts?.q) params.q = opts.q;
+ if (opts?.linked != null) params.linked = String(opts.linked);
+ if (opts?.include_links === false) params.include_links = "false";
if (opts?.limit != null) params.limit = String(opts.limit);
if (opts?.offset != null) params.offset = String(opts.offset);
return apiGet<WorkspaceContractsResponse>("/api/workspace/contracts", params);
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index 9420f702c..6fe21fd8e 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -291,6 +291,32 @@ def _contract_link(lk: dict) -> WorkspaceContractLinkEntry:
)
+def _contract_haystack(c: dict) -> str:
+ return " ".join(
+ str(c.get(k) or "") for k in ("contract_id", "file_path", "symbol_name", "repo", "service")
+ ).lower()
+
+
+def _link_haystack(lk: dict) -> str:
+ return " ".join(
+ str(lk.get(k) or "")
+ for k in (
+ "contract_id",
+ "consumer_contract_id",
+ "provider_repo",
+ "provider_file",
+ "provider_symbol",
+ "consumer_repo",
+ "consumer_file",
+ "consumer_symbol",
+ )
+ ).lower()
+
+
+def _matches_terms(haystack: str, terms: list[str]) -> bool:
+ return all(t in haystack for t in terms)
+
+
# ---------------------------------------------------------------------------
# GET /api/workspace/contracts
# ---------------------------------------------------------------------------
@@ -305,6 +331,19 @@ async def get_contracts(
),
repo: str | None = Query(None, description="Filter by repo alias"),
role: str | None = Query(None, description="Filter: provider or consumer"),
+ q: str | None = Query(
+ None,
+ description="Case-insensitive search over id, file, symbol, repo and service. "
+ "Every whitespace-separated term must match.",
+ ),
+ linked: bool | None = Query(
+ None, description="true: only contracts on a matched link; false: only those on none"
+ ),
+ include_links: bool = Query(
+ True,
+ description="false omits the link rows (total_links is still counted), for a caller "
+ "paging the contract list that already holds the links",
+ ),
limit: int = Query(200, ge=1, le=1000),
offset: int = Query(0, ge=0),
):
@@ -333,6 +372,27 @@ async def get_contracts(
]
if role:
contracts = [c for c in contracts if c.get("role") == role]
+ if linked is not None:
+ # Keyed on the side each contract plays, from the unfiltered links, so a
+ # type or repo filter above cannot turn a linked contract into an unused one.
+ on_link = set()
+ for lk in getattr(enricher, "_contract_links", []):
+ cid = lk.get("contract_id")
+ on_link.add(("provider", lk.get("provider_repo"), lk.get("provider_file"), cid))
+ on_link.add(("consumer", lk.get("consumer_repo"), lk.get("consumer_file"), cid))
+ contracts = [
+ c
+ for c in contracts
+ if (
+ (c.get("role"), c.get("repo"), c.get("file_path"), c.get("contract_id"))
+ in on_link
+ )
+ == linked
+ ]
+ terms = (q or "").lower().split()
+ if terms:
+ contracts = [c for c in contracts if _matches_terms(_contract_haystack(c), terms)]
+ links = [lk for lk in links if _matches_terms(_link_haystack(lk), terms)]
total_contracts = len(contracts)
total_links = len(links)
@@ -348,7 +408,7 @@ async def get_contracts(
return WorkspaceContractsResponse(
contracts=[_contract_entry(c) for c in contracts_page],
- links=[_contract_link(lk) for lk in links],
+ links=[_contract_link(lk) for lk in links] if include_links else [],
total_contracts=total_contracts,
total_links=total_links,
by_type=by_type,
diff --git a/packages/ui/__tests__/workspace/contract-ai-prompt.test.ts b/packages/ui/__tests__/workspace/contract-ai-prompt.test.ts
new file mode 100644
index 000000000..fb701da0d
--- /dev/null
+++ b/packages/ui/__tests__/workspace/contract-ai-prompt.test.ts
@@ -0,0 +1,139 @@
+import { describe, it, expect } from "vitest";
+import {
+ MAX_PROMPT_ROWS,
+ buildContractAiPrompt,
+ buildOrphanProvidersAiPrompt,
+ buildUnmatchedConsumersAiPrompt,
+ type ContractPromptLink,
+} from "../../src/workspace/contract-ai-prompt.js";
+import type { ContractEntry } from "../../src/workspace/contract-facts.js";
+
+function contract(overrides: Partial<ContractEntry> = {}): ContractEntry {
+ return {
+ contract_id: "http::GET::/users/{param}",
+ contract_type: "http",
+ role: "provider",
+ repo: "users-api",
+ file_path: "src/routes/users.py",
+ symbol_name: "fastapi::get_user",
+ confidence: 0.85,
+ service: "users",
+ line: 42,
+ symbol_id: null,
+ meta: { method: "GET", path: "/users/{param}", framework: "fastapi", extraction_layer: "index" },
+ ...overrides,
+ };
+}
+
+const LINK: ContractPromptLink = {
+ match_type: "exact",
+ confidence: 0.65,
+ provider_repo: "users-api",
+ provider_file: "src/routes/users.py",
+ provider_symbol: "get_user",
+ consumer_repo: "web",
+ consumer_file: "src/api/users.ts",
+ consumer_symbol: "fetchUser",
+};
+
+describe("buildContractAiPrompt", () => {
+ it("carries the identity, location and how it was found", () => {
+ const prompt = buildContractAiPrompt({ contract: contract(), links: [LINK] });
+ expect(prompt).toContain("## Contract: GET /users/{param}");
+ expect(prompt).toContain("`http::GET::/users/{param}` (HTTP, provider)");
+ expect(prompt).toContain("`users-api` `src/routes/users.py:42`, service `users`");
+ expect(prompt).toContain("Framework: `fastapi`");
+ // The caller is named with its match basis.
+ expect(prompt).toContain("`web` `src/api/users.ts` `fetchUser` (exact match, 65%)");
+ expect(prompt).not.toContain("\u2014");
+ });
+
+ it("does not call an unlinked provider dead", () => {
+ const prompt = buildContractAiPrompt({ contract: contract(), links: [] });
+ expect(prompt).toContain("That is not proof it is unused");
+ expect(prompt).toContain("Do not delete anything in this pass");
+ });
+
+ it("names the host and the next step for an external consumer", () => {
+ const prompt = buildContractAiPrompt({
+ contract: contract({ role: "consumer", meta: { host: "api.github.com" } }),
+ links: [],
+ unmatchedReason: "external_host",
+ });
+ expect(prompt).toContain("Recorded reason: `external_host`");
+ expect(prompt).toContain("`api.github.com`");
+ expect(prompt).toContain("is a third party");
+ });
+
+ it("asks for the intended endpoint when no provider exists", () => {
+ const prompt = buildContractAiPrompt({
+ contract: contract({ role: "consumer" }),
+ links: [],
+ unmatchedReason: "no_provider",
+ });
+ expect(prompt).toContain("Find the endpoint this call intends");
+ });
+
+ it("lists breaking changes when the report has them", () => {
+ const prompt = buildContractAiPrompt({
+ contract: contract(),
+ links: [LINK],
+ breakingChanges: [{ severity: "breaking", kind: "removed_field", detail: "id was removed" }],
+ });
+ expect(prompt).toContain("## Breaking changes in the latest update");
+ expect(prompt).toContain("breaking: `removed_field`: id was removed");
+ });
+
+ it("steers the MCP flavor to repowise tools", () => {
+ const prompt = buildContractAiPrompt({ contract: contract(), links: [], flavor: "claude-code-mcp" });
+ expect(prompt).toContain("get_blast_radius");
+ expect(prompt).toContain("search_codebase");
+ });
+});
+
+describe("buildUnmatchedConsumersAiPrompt", () => {
+ const row = (i: number) => ({
+ repo: "web",
+ file_path: `src/api/r${i}.ts`,
+ contract_id: `http::GET::/r/${i}`,
+ contract_type: "http",
+ });
+
+ it("states the count, the reason and every listed call", () => {
+ const prompt = buildUnmatchedConsumersAiPrompt({ reason: "no_provider", rows: [row(1), row(2)] });
+ expect(prompt).toContain("## 2 client calls that resolve to no provider: no provider found");
+ expect(prompt).toContain("`no_provider`");
+ expect(prompt).toContain("1. `http::GET::/r/1` in `web` `src/api/r1.ts` (HTTP)");
+ expect(prompt).toContain("renamed (fix the call)");
+ });
+
+ it("caps the list and says how many it left out", () => {
+ const rows = Array.from({ length: MAX_PROMPT_ROWS + 3 }, (_, i) => row(i));
+ const prompt = buildUnmatchedConsumersAiPrompt({ reason: "no_provider", rows });
+ expect(prompt).toContain(`## ${MAX_PROMPT_ROWS + 3} client calls`);
+ expect(prompt).toContain("...and 3 more calls not listed");
+ expect(prompt).not.toContain(`/r/${MAX_PROMPT_ROWS}\``);
+ });
+
+ it("tells the agent there is little to do for external hosts", () => {
+ const prompt = buildUnmatchedConsumersAiPrompt({ reason: "external_host", rows: [row(1)] });
+ expect(prompt).toContain("## 1 client call that resolves to no provider");
+ expect(prompt).toContain("For the rest there is nothing to fix");
+ });
+});
+
+describe("buildOrphanProvidersAiPrompt", () => {
+ it("names the repo and type, lists providers and forbids deletion", () => {
+ const prompt = buildOrphanProvidersAiPrompt({
+ repo: "backend",
+ contractType: "data",
+ rows: [
+ { repo: "backend", file_path: "db/schema.sql", contract_id: "data::audit_log", contract_type: "data" },
+ ],
+ });
+ expect(prompt).toContain("## 1 table in `backend` with no caller in this workspace");
+ expect(prompt).toContain("1. `data::audit_log` in `db/schema.sql`");
+ expect(prompt).toContain("That is not proof they are unused");
+ expect(prompt).toContain("Never remove a provider on the strength of this list alone");
+ });
+});
diff --git a/packages/ui/__tests__/workspace/contract-attention.test.tsx b/packages/ui/__tests__/workspace/contract-attention.test.tsx
new file mode 100644
index 000000000..175c7ba36
--- /dev/null
+++ b/packages/ui/__tests__/workspace/contract-attention.test.tsx
@@ -0,0 +1,107 @@
+import { describe, it, expect, vi } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
+import type { OrphanProvider, UnmatchedConsumer } from "@repowise-dev/types/workspace";
+import { ContractAttention } from "../../src/workspace/contract-attention.js";
+import { groupOrphanProviders, parseContractId } from "../../src/workspace/contract-facts.js";
+
+const unmatched = (reason: UnmatchedConsumer["reason"], i: number): UnmatchedConsumer => ({
+ repo: "web",
+ file_path: `src/api/c${i}.ts`,
+ contract_id: `http::GET::/r/${reason}/${i}`,
+ contract_type: "http",
+ reason,
+});
+
+const orphan = (repo: string, type: string, i: number): OrphanProvider => ({
+ repo,
+ file_path: `src/p${i}.py`,
+ contract_id: `${type}::x${i}`,
+ contract_type: type,
+});
+
+describe("ContractAttention", () => {
+ it("opens actionable reasons first and keeps the rest closed", () => {
+ render(
+ <ContractAttention
+ unmatched={[unmatched("external_host", 1), unmatched("no_provider", 2)]}
+ orphanGroups={[]}
+ onSelect={() => {}}
+ browseHref={() => "#"}
+ />,
+ );
+ const headings = screen.getAllByRole("heading", { level: 4 }).map((h) => h.textContent);
+ expect(headings[0]).toContain("No provider found");
+ expect(screen.getByText("/r/no_provider/2")).toBeInTheDocument();
+ expect(screen.queryByText("/r/external_host/1")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Show the 1 call" }));
+ expect(screen.getByText("/r/external_host/1")).toBeInTheDocument();
+ });
+
+ it("opens a row in the drawer", () => {
+ const onSelect = vi.fn();
+ render(
+ <ContractAttention
+ unmatched={[unmatched("no_provider", 1)]}
+ orphanGroups={[]}
+ onSelect={onSelect}
+ browseHref={() => "#"}
+ />,
+ );
+ fireEvent.click(screen.getByText("/r/no_provider/1"));
+ expect(onSelect).toHaveBeenCalledWith({
+ repo: "web",
+ file_path: "src/api/c1.ts",
+ contract_id: "http::GET::/r/no_provider/1",
+ });
+ });
+
+ it("summarises providers with no caller per repository and type, largest first", () => {
+ render(
+ <ContractAttention
+ unmatched={[]}
+ orphanGroups={groupOrphanProviders(
+ [orphan("api", "http", 1), orphan("db", "data", 2), orphan("db", "data", 3)],
+ 1,
+ )}
+ onSelect={() => {}}
+ browseHref={(repo, type) => `/list?repo=${repo}&type=${type}`}
+ />,
+ );
+ expect(screen.getByText("3 providers have no caller in this workspace")).toBeInTheDocument();
+ const browse = screen.getAllByRole("link", { name: "Browse" });
+ expect(browse[0]).toHaveAttribute("href", "/list?repo=db&type=data");
+ expect(browse[1]).toHaveAttribute("href", "/list?repo=api&type=http");
+ });
+});
+
+describe("parseContractId", () => {
+ it("splits http, code and data ids", () => {
+ expect(parseContractId("http::GET::/a/{param}")).toEqual({
+ kind: "http",
+ method: "GET",
+ label: "/a/{param}",
+ qualifier: null,
+ });
+ expect(parseContractId("code::@scope/pkg::fn")).toEqual({
+ kind: "code",
+ method: null,
+ label: "fn",
+ qualifier: "@scope/pkg",
+ });
+ expect(parseContractId("data::users").label).toBe("users");
+ expect(parseContractId("plain").label).toBe("plain");
+ });
+});
+
+describe("groupOrphanProviders", () => {
+ it("counts every provider but keeps only a sample of rows", () => {
+ const groups = groupOrphanProviders(
+ [orphan("db", "data", 1), orphan("db", "data", 2), orphan("api", "http", 3)],
+ 1,
+ );
+ expect(groups.map((g) => [g.repo, g.contractType, g.count, g.rows.length])).toEqual([
+ ["db", "data", 2, 1],
+ ["api", "http", 1, 1],
+ ]);
+ });
+});
diff --git a/packages/ui/__tests__/workspace/contract-drawer.test.tsx b/packages/ui/__tests__/workspace/contract-drawer.test.tsx
index c4f0000eb..8ea917a29 100644
--- a/packages/ui/__tests__/workspace/contract-drawer.test.tsx
+++ b/packages/ui/__tests__/workspace/contract-drawer.test.tsx
@@ -81,7 +81,7 @@ function link(overrides: Partial<WorkspaceContractLinkEntry> = {}): WorkspaceCon
}
describe("ContractDrawer", () => {
- it("renders the contract identity, role, location and confidence", () => {
+ it("renders the contract identity, role, location and how it was found", () => {
render(
<ContractDrawer
contract={contract()}
@@ -90,44 +90,54 @@ describe("ContractDrawer", () => {
fullPageHref="/workspace/contracts/detail?id=x"
/>,
);
- expect(screen.getByText("GET /users/{id}")).toBeInTheDocument();
+ // The verb is its own label and the path wraps at its slashes.
+ expect(screen.getAllByText("GET").length).toBeGreaterThan(0);
expect(screen.getByText("http::GET::/users/{id}")).toBeInTheDocument();
- // Type and role share the eyebrow line, so they are read off it together.
- expect(screen.getByText(/HTTP contract/).textContent).toContain("Provider");
+ expect(screen.getByText("HTTP contract / Provider")).toBeInTheDocument();
expect(screen.getByText("users-api")).toBeInTheDocument();
- expect(screen.getByText("src/routes/users.ts")).toBeInTheDocument();
- expect(screen.getByText("line 42")).toBeInTheDocument();
+ // The file reads as a dim directory and its name, with the line after it.
+ expect(screen.getByText("users.ts").parentElement).toHaveAttribute(
+ "title",
+ "src/routes/users.ts:42",
+ );
expect(screen.getByText("92%")).toBeInTheDocument();
expect(screen.getByText("fastapi")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "AI prompt" })).toBeInTheDocument();
});
- it("links the file and the counterpart symbol with the supplied hrefs", () => {
+ it("links the file and the counterpart code, and swaps to the counterpart", () => {
const c = contract();
- const links = [link()];
+ const onSelectContract = vi.fn();
render(
<ContractDrawer
contract={c}
open
onOpenChange={() => {}}
- links={linksForContract(c, links)}
+ links={linksForContract(c, [link()])}
codeLinks={{
fileHref: (repo, file) => `/repos/${repo}/files/${file}`,
symbolHref: (repo, symbolId) => `/repos/${repo}/symbols/${symbolId}`,
}}
fullPageHref="/workspace/contracts/detail?id=x"
+ onSelectContract={onSelectContract}
/>,
);
- expect(screen.getByText("src/routes/users.ts").closest("a")).toHaveAttribute(
+ expect(screen.getByText("users.ts").closest("a")).toHaveAttribute(
"href",
"/repos/users-api/files/src/routes/users.ts",
);
- // The consumer bound to a symbol id, so its link goes to the symbol page.
- expect(screen.getByText("src/api/users-client.ts").closest("a")).toHaveAttribute(
+ // The consumer bound to a symbol id, so its code link goes to the symbol page.
+ expect(screen.getByRole("link", { name: "Code" })).toHaveAttribute(
"href",
"/repos/web-app/symbols/src/api/users-client.ts::fetchUser",
);
- expect(screen.getByText("web-app")).toBeInTheDocument();
expect(screen.getByText("fetchUser")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: /open the consumer in web-app/i }));
+ expect(onSelectContract).toHaveBeenCalledWith({
+ repo: "web-app",
+ file_path: "src/api/users-client.ts",
+ contract_id: "http::GET::/users/{id}",
+ });
expect(screen.getByRole("link", { name: "Open full page" })).toHaveAttribute(
"href",
"/workspace/contracts/detail?id=x",
@@ -153,16 +163,36 @@ describe("ContractDrawer", () => {
expect(screen.getByText("Required")).toBeInTheDocument();
});
- it("says nothing resolves when the contract has no links", () => {
+ it("says nothing resolves to a provider without calling it dead", () => {
render(<ContractDrawer contract={contract()} open onOpenChange={() => {}} links={[]} />);
- expect(screen.getByText("Callers")).toBeInTheDocument();
- expect(screen.getByText(/nothing in this workspace resolves/i)).toBeInTheDocument();
+ expect(screen.getByText("No caller found")).toBeInTheDocument();
+ expect(screen.getByText(/neither reading makes it dead code/i)).toBeInTheDocument();
+ });
+
+ it("names an unmatched consumer's reason and next step", () => {
+ render(
+ <ContractDrawer
+ contract={contract({ role: "consumer", meta: { host: "api.github.com" } })}
+ open
+ onOpenChange={() => {}}
+ unmatchedReason="external_host"
+ />,
+ );
+ expect(screen.getByText("Outside this workspace")).toBeInTheDocument();
+ expect(screen.getByText(/add its repository to the workspace/i)).toBeInTheDocument();
+ });
+
+ it("shows loading until a deep-linked contract arrives", () => {
+ render(
+ <ContractDrawer contract={null} pendingId="http::GET::/x" open onOpenChange={() => {}} loading />,
+ );
+ expect(screen.getByText("Loading contract...")).toBeInTheDocument();
});
it("fires the close callback from the close button", () => {
const onOpenChange = vi.fn();
render(<ContractDrawer contract={contract()} open onOpenChange={onOpenChange} />);
- fireEvent.click(screen.getByRole("button", { name: "Close contract" }));
+ fireEvent.click(screen.getByRole("button", { name: "Close panel" }));
expect(onOpenChange).toHaveBeenCalledWith(false);
});
});
diff --git a/packages/ui/__tests__/workspace/contract-links-table.test.tsx b/packages/ui/__tests__/workspace/contract-links-table.test.tsx
index e52f5f3e3..886384e15 100644
--- a/packages/ui/__tests__/workspace/contract-links-table.test.tsx
+++ b/packages/ui/__tests__/workspace/contract-links-table.test.tsx
@@ -1,5 +1,5 @@
-import { describe, it, expect } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { describe, it, expect, vi } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
import type { WorkspaceContractLinkEntry } from "@repowise-dev/types/workspace";
import { ContractLinksTable } from "../../src/workspace/contract-links-table.js";
@@ -7,7 +7,7 @@ function link(
overrides: Partial<WorkspaceContractLinkEntry> = {},
): WorkspaceContractLinkEntry {
return {
- contract_id: "GET /users/{id}",
+ contract_id: "http::GET::/users/{id}",
contract_type: "http",
match_type: "exact",
confidence: 0.9,
@@ -25,44 +25,66 @@ function link(
};
}
-describe("ContractLinksTable (virtualized)", () => {
- it("renders a row per link with key cells", () => {
- const links = [
- link(),
- link({
- contract_id: "POST /orders",
- provider_repo: "orders-api",
- consumer_repo: "checkout",
- }),
- ];
- render(<ContractLinksTable links={links} />);
- expect(screen.getByText("GET /users/{id}")).toBeInTheDocument();
- expect(screen.getByText("POST /orders")).toBeInTheDocument();
- expect(screen.getByText("users-api")).toBeInTheDocument();
- expect(screen.getByText("orders-api")).toBeInTheDocument();
+// The table and its stacked-card rendering are both in the DOM (CSS picks one),
+// so every cell appears twice.
+describe("ContractLinksTable", () => {
+ it("renders the method as a label and the path apart from it", () => {
+ render(
+ <ContractLinksTable
+ links={[
+ link(),
+ link({ contract_id: "http::POST::/orders", provider_repo: "orders-api", consumer_repo: "checkout" }),
+ ]}
+ />,
+ );
+ expect(screen.getAllByText("GET").length).toBeGreaterThan(0);
+ expect(screen.getAllByText("/users/{id}").length).toBeGreaterThan(0);
+ expect(screen.getAllByText("POST").length).toBeGreaterThan(0);
+ expect(screen.getAllByText("orders-api").length).toBeGreaterThan(0);
});
- it("renders the contract type badge and confidence percentage", () => {
- render(<ContractLinksTable links={[link({ confidence: 0.75 })]} />);
- expect(screen.getByText("HTTP")).toBeInTheDocument();
- expect(screen.getByText("75%")).toBeInTheDocument();
+ it("splits a file into a dim directory and its name, with the full path on hover", () => {
+ render(<ContractLinksTable links={[link()]} />);
+ const name = screen.getAllByText("users.ts")[0]!;
+ expect(name.parentElement).toHaveAttribute("title", "src/routes/users.ts");
+ expect(screen.getAllByText("users-client.ts").length).toBeGreaterThan(0);
});
- it("renders the socket contract type badge", () => {
- render(<ContractLinksTable links={[link({ contract_type: "socket" })]} />);
- expect(screen.getByText("Socket")).toBeInTheDocument();
+ it("renders the type and the confidence as a plain figure", () => {
+ render(<ContractLinksTable links={[link({ confidence: 0.75, contract_type: "socket" })]} />);
+ expect(screen.getAllByText("Socket").length).toBeGreaterThan(0);
+ expect(screen.getAllByText("75%").length).toBeGreaterThan(0);
});
- it("shows the provider and consumer file paths", () => {
- render(<ContractLinksTable links={[link()]} />);
- expect(screen.getByText("src/routes/users.ts")).toBeInTheDocument();
- expect(screen.getByText("src/api/users-client.ts")).toBeInTheDocument();
+ it("opens a link from the row", () => {
+ const onSelect = vi.fn();
+ const l = link();
+ render(<ContractLinksTable links={[l]} onSelect={onSelect} />);
+ fireEvent.click(screen.getAllByText("users.ts")[0]!);
+ expect(onSelect).toHaveBeenCalledWith(l);
});
it("shows the empty state when there are no links", () => {
render(<ContractLinksTable links={[]} />);
- expect(
- screen.getByText(/no matched contract links/i),
- ).toBeInTheDocument();
+ expect(screen.getByText(/no matched contract links/i)).toBeInTheDocument();
+ });
+});
+
+describe("ContractLinksTable order", () => {
+ it("puts the strongest links first, then sorts by contract", () => {
+ render(
+ <ContractLinksTable
+ links={[
+ link({ contract_id: "http::GET::/weak", confidence: 0.65 }),
+ link({ contract_id: "http::GET::/b", confidence: 0.9 }),
+ link({ contract_id: "http::GET::/a", confidence: 0.9 }),
+ ]}
+ />,
+ );
+ // The table body's identities in row order; the stacked cards repeat them outside tbody.
+ const ids = [...document.querySelectorAll("tbody [title^='http::']")].map((el) =>
+ el.getAttribute("title"),
+ );
+ expect(ids).toEqual(["http::GET::/a", "http::GET::/b", "http::GET::/weak"]);
});
});
diff --git a/packages/ui/__tests__/workspace/contract-tests-section.test.tsx b/packages/ui/__tests__/workspace/contract-tests-section.test.tsx
index 826392584..ecc0e5314 100644
--- a/packages/ui/__tests__/workspace/contract-tests-section.test.tsx
+++ b/packages/ui/__tests__/workspace/contract-tests-section.test.tsx
@@ -175,3 +175,19 @@ describe("ContractTestsSection", () => {
expect(screen.getByText("Test impact is unavailable.")).toBeTruthy();
});
});
+
+describe("ContractTestsSection compact", () => {
+ it("sets every heading below the drawer's h4 at micro-label scale", () => {
+ render(
+ <ContractTestsSection
+ result={response({ recommendations: [rec()], unresolved: [unresolved()] })}
+ contractId={CONTRACT}
+ compact
+ />,
+ );
+ expect(screen.getByRole("heading", { level: 4, name: "Tests to run" })).toBeInTheDocument();
+ const could = screen.getByRole("heading", { level: 5, name: "Could not determine" });
+ expect(could.className).toContain("text-[10px]");
+ expect(screen.getByRole("heading", { level: 5, name: "web" })).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 9b968f453..c11adfe79 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -71,6 +71,7 @@
"./overview": "./src/overview/index.ts",
"./overview/*": "./src/overview/*.tsx",
"./workspace": "./src/workspace/index.ts",
+ "./workspace/contract-ai-prompt": "./src/workspace/contract-ai-prompt.ts",
"./workspace/contract-facts": "./src/workspace/contract-facts.ts",
"./workspace/contract-type-label": "./src/workspace/contract-type-label.ts",
"./workspace/system-map": "./src/workspace/system-map/index.ts",
diff --git a/packages/ui/src/workspace/breaking-changes-view.tsx b/packages/ui/src/workspace/breaking-changes-view.tsx
index 4d574ac09..71193d0b0 100644
--- a/packages/ui/src/workspace/breaking-changes-view.tsx
+++ b/packages/ui/src/workspace/breaking-changes-view.tsx
@@ -11,10 +11,11 @@
* to avoid.
*/
+import type { ReactNode } from "react";
import { AlertTriangle } from "lucide-react";
import type { BreakingChange, BreakingChangeReport } from "@repowise-dev/types";
import { Card } from "../ui/card";
-import { EmptyState } from "../shared/empty-state";
+import { formatRelativeTimeOrNull } from "../lib/format";
import {
BreakingChangeRow,
breakingChangeKey,
@@ -33,10 +34,6 @@ export interface BreakingChangesViewProps {
onSelectNode?: (nodeId: string) => void;
}
-const NOT_RUN_TITLE = "Breaking-change detection has not run";
-const NOT_RUN_BODY =
- "Detection compares each update against the previously indexed contracts. Run a workspace update to produce a first result.";
-
export function BreakingChangesView({
report,
loading,
@@ -44,27 +41,32 @@ export function BreakingChangesView({
onSelectContract,
onSelectNode,
}: BreakingChangesViewProps) {
+ // Every state without findings is one quiet sentence. A tinted box around
+ // "nothing found" reads as the loudest thing on the page, and healthy is the
+ // state that should be quiet.
if (loading) {
- return (
- <Card className="px-3 py-4 text-xs text-[var(--color-text-tertiary)]">
- Checking the latest update…
- </Card>
- );
+ return <Quiet>Checking the latest update...</Quiet>;
}
// No report at all and a report with no timestamp are the same fact: nothing
// has been compared yet, so an empty change list is not an all-clear.
if (!report || !report.generated_at) {
- return <EmptyState className="p-6" title={NOT_RUN_TITLE} description={NOT_RUN_BODY} />;
+ return (
+ <Quiet>
+ Breaking-change detection has not run. It compares each update against the previously
+ indexed contracts, so the first result appears after the next workspace update.
+ </Quiet>
+ );
}
if (report.changes.length === 0) {
+ const when = formatRelativeTimeOrNull(report.generated_at, "");
return (
- <EmptyState
- className="p-6"
- title="No contract compatibility findings in the most recent update"
- description="No provider incompatibility or comparison uncertainty was found."
- />
+ <Quiet>
+ No contract compatibility findings in the most recent update
+ {when ? ` (${when})` : ""}: no provider changed in a way that breaks, or might break, a
+ linked consumer.
+ </Quiet>
);
}
@@ -88,3 +90,11 @@ export function BreakingChangesView({
</Card>
);
}
+
+function Quiet({ children }: { children: ReactNode }) {
+ return (
+ <p className="max-w-[68ch] text-xs leading-relaxed text-[var(--color-text-secondary)]">
+ {children}
+ </p>
+ );
+}
diff --git a/packages/ui/src/workspace/contract-ai-prompt.ts b/packages/ui/src/workspace/contract-ai-prompt.ts
new file mode 100644
index 000000000..e76ce294f
--- /dev/null
+++ b/packages/ui/src/workspace/contract-ai-prompt.ts
@@ -0,0 +1,367 @@
+/**
+ * Agent prompts for cross-repo contracts: one contract, a group of client
+ * calls that resolve to no provider, and a group of providers nothing calls.
+ *
+ * Same structure as the health builders (role, evidence, tasks, constraints,
+ * what to hand back) so an agent can act without asking first. The evidence is
+ * the extraction's reading, so every prompt tells the agent to verify it in the
+ * code before changing anything, and the absent-caller prompts say plainly that
+ * "no caller here" is not "dead".
+ */
+
+import type { AiPromptFlavor } from "../health/ai-prompt-builder";
+import {
+ contractHeading,
+ contractMetaEntries,
+ contractMetaLabel,
+ unmatchedReasonCopy,
+ type ContractEntry,
+} from "./contract-facts";
+import { contractTypeLabel } from "./contract-type-label";
+
+/** Rows listed in a group prompt before the rest are summarised as a count. */
+export const MAX_PROMPT_ROWS = 40;
+
+const PREAMBLE: Record<AiPromptFlavor, string> = {
+ generic:
+ "You are a senior engineer working across the repositories of one workspace. The contract evidence below was extracted statically by repowise: treat it as leads, not ground truth. Open the files it names and verify each item against the real code before you act. If an item is a false positive, say so and skip it.",
+ "claude-code":
+ "You are Claude Code working across the repositories of one workspace. The contract evidence below was extracted statically by repowise: treat it as leads to investigate, not commands. Use Read, Grep and Glob on the files it names, in every repository involved, before planning edits. Flag anything that turns out to be a false positive. Use TodoWrite for non-trivial steps.",
+ "claude-code-mcp":
+ "You are Claude Code working across the repositories of one workspace indexed by repowise, with its MCP tools available. The contract evidence below was extracted statically: treat it as leads, not commands. Pull what repowise already computed before re-reading by hand: `search_codebase` to find a route, table or symbol by name, `get_context([...])` for a file's skeleton, `get_symbol` for one body, `get_risk([...])` before editing, `get_why(...)` for the decision behind the current shape, and `get_blast_radius` for which services a change reaches. Fall back to Read / Grep only for what the index cannot serve. Flag false positives.",
+ cursor:
+ "Work across the repositories referenced below. The contract evidence was extracted statically by repowise: treat it as leads, not ground truth. Use @file and @codebase to read every file it names before editing, and skip and call out any false positives.",
+};
+
+function bullets(items: (string | null | undefined | false)[]): string {
+ return items
+ .filter(Boolean)
+ .map((s) => `- ${s}`)
+ .join("\n");
+}
+
+function join(sections: (string | null | undefined | false)[]): string {
+ return sections.filter((s) => s !== null && s !== undefined && s !== false && s !== "").join("\n");
+}
+
+function where(repo: string, file: string, line?: number | null): string {
+ return `\`${repo}\` \`${file}${line != null ? `:${line}` : ""}\``;
+}
+
+function more(hidden: number, noun: string): string | null {
+ return hidden > 0 ? `...and ${hidden} more ${noun} not listed. Handle these after the above.` : null;
+}
+
+// ---------------------------------------------------------------------------
+// One contract
+// ---------------------------------------------------------------------------
+
+/** The other side of one link, as the drawer has it. */
+export interface ContractPromptLink {
+ match_type: string;
+ confidence: number;
+ provider_repo: string;
+ provider_file: string;
+ provider_symbol: string;
+ consumer_repo: string;
+ consumer_file: string;
+ consumer_symbol: string;
+}
+
+export interface BuildContractPromptOptions {
+ contract: ContractEntry;
+ links: ContractPromptLink[];
+ /** Why a consumer matched nothing; null for providers and linked consumers. */
+ unmatchedReason?: string | null | undefined;
+ /** Findings from the latest breaking-change report on this contract. */
+ breakingChanges?: { severity: string; kind: string; detail: string }[];
+ flavor?: AiPromptFlavor;
+}
+
+export function buildContractAiPrompt({
+ contract,
+ links,
+ unmatchedReason = null,
+ breakingChanges = [],
+ flavor = "generic",
+}: BuildContractPromptOptions): string {
+ const isProvider = contract.role === "provider";
+ const heading = contractHeading(contract);
+ const found = contractMetaEntries(contract.meta).map(
+ ([k, v]) => `${contractMetaLabel(k)}: \`${v}\``,
+ );
+
+ const identity = bullets([
+ `Contract: \`${contract.contract_id}\` (${contractTypeLabel(contract.contract_type)}, ${isProvider ? "provider" : "consumer"})`,
+ `Where: ${where(contract.repo, contract.file_path, contract.line)}${contract.service ? `, service \`${contract.service}\`` : ""}`,
+ contract.symbol_name ? `Symbol: \`${contract.symbol_name}\`` : null,
+ `Extraction confidence: ${Math.round(contract.confidence * 100)}%`,
+ found.length > 0 ? `How it was found: ${found.join(", ")}` : null,
+ ]);
+
+ const counterparts = links.map((l) =>
+ isProvider
+ ? `${where(l.consumer_repo, l.consumer_file)} \`${l.consumer_symbol}\` (${l.match_type} match, ${Math.round(l.confidence * 100)}%)`
+ : `${where(l.provider_repo, l.provider_file)} \`${l.provider_symbol}\` (${l.match_type} match, ${Math.round(l.confidence * 100)}%)`,
+ );
+
+ let state: string;
+ let tasks: string[];
+ if (links.length > 0) {
+ state = isProvider
+ ? `${links.length} call ${links.length === 1 ? "site resolves" : "sites resolve"} to this contract:`
+ : `This call resolves to ${links.length === 1 ? "this provider" : `these ${links.length} providers`}:`;
+ tasks = isProvider
+ ? [
+ "Confirm each caller above really calls this contract (method, path or name, and payload).",
+ "Before changing the contract's shape or behaviour, list what each caller sends and expects back, and say which change would break which caller.",
+ "Name the tests in the calling repositories that exercise these calls, or say that none do.",
+ ]
+ : [
+ "Confirm the provider above is the endpoint this call is meant to reach.",
+ "Compare what the call sends and expects with what the provider accepts and returns; report any mismatch in fields, types, status codes or auth.",
+ ];
+ } else if (isProvider) {
+ state =
+ "Nothing in this workspace resolves to this contract. That is not proof it is unused: it may be called from outside the workspace, from the same service (excluded from matching), or by code written in a form extraction cannot follow (a dynamic URL, a generated client, reflection).";
+ tasks = [
+ "Search every repository for callers, including dynamic ones: string-built URLs, generated clients, config-driven routes, other packages importing it.",
+ "Check whether it is public API or consumed by something outside this workspace (a mobile app, a partner, a scheduled job).",
+ "Only if no caller exists and it is not public: propose deprecating or removing it, with the evidence. Do not delete anything in this pass.",
+ ];
+ } else {
+ const copy = unmatchedReasonCopy(unmatchedReason);
+ const host = typeof contract.meta?.host === "string" ? contract.meta.host : null;
+ state = `This call matched no provider. Recorded reason: \`${unmatchedReason ?? "none"}\` (${copy.title}). ${copy.meaning}${host ? ` Host: \`${host}\`.` : ""}`;
+ tasks =
+ unmatchedReason === "external_host"
+ ? [
+ `Confirm ${host ? `\`${host}\`` : "the host"} is a third party and not one of this workspace's own services behind a literal URL.`,
+ "If it is your own service, say which repository serves it so it can be added to the workspace; otherwise there is nothing to fix.",
+ ]
+ : unmatchedReason === "internal_only"
+ ? [
+ "Confirm the call is served from the same service that makes it. If so there is nothing to fix; say so and stop.",
+ ]
+ : [
+ "Find the endpoint this call intends. Search the providers for the same path with a different prefix, version, method or spelling.",
+ "If it was renamed, fix the call. If it was removed, say whether the call is dead and can go. If a service outside the workspace serves it, name it.",
+ "If a provider exists but is declared in a form extraction did not read (an unusual framework, a mounted router, a generated route), name the file and the pattern.",
+ ];
+ }
+
+ const breaking =
+ breakingChanges.length > 0
+ ? join([
+ "",
+ "## Breaking changes in the latest update",
+ "",
+ bullets(
+ breakingChanges.map(
+ (b) => `${b.severity}: \`${b.kind}\`${b.detail ? `: ${b.detail}` : ""}`,
+ ),
+ ),
+ ])
+ : null;
+
+ return join([
+ PREAMBLE[flavor],
+ "",
+ `## Contract: ${heading}`,
+ "",
+ identity,
+ "",
+ "## State",
+ "",
+ state,
+ counterparts.length > 0 ? bullets(counterparts) : null,
+ breaking,
+ "",
+ "## What to do",
+ "",
+ tasks.map((t, i) => `${i + 1}. ${t}`).join("\n"),
+ "",
+ "## Hard constraints",
+ "",
+ bullets([
+ "Verify in the code before acting. The evidence above is static extraction and can be wrong.",
+ "Keep the public contract stable unless the task explicitly calls for changing it.",
+ "Do not delete code on the strength of a missing caller alone.",
+ ]),
+ "",
+ "## What I expect back",
+ "",
+ "1. What you verified, with file and line for each claim.\n2. The change you made or propose, or why none is needed.\n3. Anything the extraction got wrong.",
+ ]);
+}
+
+// ---------------------------------------------------------------------------
+// Unmatched consumers, one reason at a time
+// ---------------------------------------------------------------------------
+
+export interface UnmatchedConsumerPromptRow {
+ repo: string;
+ file_path: string;
+ contract_id: string;
+ contract_type: string;
+}
+
+export interface BuildUnmatchedConsumersPromptOptions {
+ reason: string;
+ rows: UnmatchedConsumerPromptRow[];
+ flavor?: AiPromptFlavor;
+}
+
+export function buildUnmatchedConsumersAiPrompt({
+ reason,
+ rows,
+ flavor = "generic",
+}: BuildUnmatchedConsumersPromptOptions): string {
+ const copy = unmatchedReasonCopy(reason);
+ const shown = rows.slice(0, MAX_PROMPT_ROWS);
+ const n = rows.length;
+ const calls = `${n} client ${n === 1 ? "call" : "calls"}`;
+
+ const tasks =
+ reason === "external_host"
+ ? [
+ "For each call, confirm the host is a third party and not one of this workspace's own services behind a literal URL.",
+ "List any that are your own services, with the repository that serves them. For the rest there is nothing to fix.",
+ ]
+ : reason === "internal_only"
+ ? [
+ "Spot-check that each call is served from the same service that makes it. Report any that are not; the rest need nothing.",
+ ]
+ : [
+ "For each call, find the intended endpoint: search the providers for the same path with a different prefix, version, method or spelling.",
+ "Classify each as renamed (fix the call), removed (the call is dead and can go), served outside the workspace (name the service), or declared in a form extraction did not read (name the file and pattern).",
+ "Group calls that share a cause; one mount prefix or base URL often explains many.",
+ ];
+
+ return join([
+ PREAMBLE[flavor],
+ "",
+ `## ${calls} that ${n === 1 ? "resolves" : "resolve"} to no provider: ${copy.title.toLowerCase()}`,
+ "",
+ bullets([
+ `Reason recorded by the matcher: \`${reason}\`. ${copy.meaning}`,
+ "Source: repowise workspace contract extraction and matching.",
+ ]),
+ "",
+ "## Calls",
+ "",
+ shown
+ .map(
+ (r, i) =>
+ `${i + 1}. \`${r.contract_id}\` in ${where(r.repo, r.file_path)} (${contractTypeLabel(r.contract_type)})`,
+ )
+ .join("\n"),
+ more(n - shown.length, n - shown.length === 1 ? "call" : "calls"),
+ "",
+ "## What to do",
+ "",
+ tasks.map((t, i) => `${i + 1}. ${t}`).join("\n"),
+ "",
+ "## Hard constraints",
+ "",
+ bullets([
+ "Verify each call in the code before acting. A path built from variables may not be what extraction recorded.",
+ "Do not delete a call unless you have confirmed the endpoint it targets no longer exists anywhere.",
+ ]),
+ "",
+ "## What I expect back",
+ "",
+ "A table with one row per call: the contract id, the verdict (renamed, removed, external, undetected provider, false positive), the evidence (file and line), and the fix you made or propose.",
+ flavor === "claude-code-mcp"
+ ? "Use `search_codebase` with the path's distinctive segments to find near-miss providers before reading files by hand."
+ : null,
+ ]);
+}
+
+// ---------------------------------------------------------------------------
+// Providers nothing calls, one repository and type at a time
+// ---------------------------------------------------------------------------
+
+/** "3 HTTP routes", "1 table": the providers of one type, as a reader counts them. */
+export function providerNoun(contractType: string, n: number): string {
+ const one = n === 1;
+ switch (contractType) {
+ case "http":
+ return one ? "HTTP route" : "HTTP routes";
+ case "data":
+ return one ? "table" : "tables";
+ case "code":
+ return one ? "exported symbol" : "exported symbols";
+ default:
+ return `${contractTypeLabel(contractType)} ${one ? "contract" : "contracts"}`;
+ }
+}
+
+export interface OrphanProviderPromptRow {
+ repo: string;
+ file_path: string;
+ contract_id: string;
+ contract_type: string;
+}
+
+export interface BuildOrphanProvidersPromptOptions {
+ repo: string;
+ contractType: string;
+ rows: OrphanProviderPromptRow[];
+ /** Providers in the group when `rows` is a sample of them. */
+ total?: number;
+ flavor?: AiPromptFlavor;
+}
+
+export function buildOrphanProvidersAiPrompt({
+ repo,
+ contractType,
+ rows,
+ total,
+ flavor = "generic",
+}: BuildOrphanProvidersPromptOptions): string {
+ const shown = rows.slice(0, MAX_PROMPT_ROWS);
+ const n = Math.max(total ?? 0, rows.length);
+ const noun = providerNoun(contractType, n);
+
+ return join([
+ PREAMBLE[flavor],
+ "",
+ `## ${n} ${noun} in \`${repo}\` with no caller in this workspace`,
+ "",
+ bullets([
+ "No consumer in any repository of this workspace was resolved to these providers.",
+ "That is not proof they are unused. A caller may live outside the workspace, in the same service (excluded from matching), or in code extraction cannot follow: string-built URLs, generated clients, raw SQL assembled at runtime, dynamic imports.",
+ ]),
+ "",
+ "## Providers",
+ "",
+ shown
+ .map((r, i) => `${i + 1}. \`${r.contract_id}\` in \`${r.file_path}\``)
+ .join("\n"),
+ more(n - shown.length, n - shown.length === 1 ? "provider" : "providers"),
+ "",
+ "## What to do",
+ "",
+ [
+ "1. For each provider, search every repository for callers, including the dynamic forms above.",
+ "2. Mark each as used (name the caller and why extraction missed it), public or external (name the consumer), or unused (no caller anywhere).",
+ "3. For the unused ones, propose deprecation or removal with the evidence. Do not delete anything in this pass.",
+ "4. If many were missed for one reason (a client wrapper, a base URL, an ORM pattern), name the pattern so extraction can learn it.",
+ ].join("\n"),
+ "",
+ "## Hard constraints",
+ "",
+ bullets([
+ "Never remove a provider on the strength of this list alone.",
+ "Treat anything public, versioned or documented as used until shown otherwise.",
+ ]),
+ "",
+ "## What I expect back",
+ "",
+ "A table with one row per provider: the contract id, the verdict (used, external, unused), the evidence, and the proposed action.",
+ flavor === "claude-code-mcp"
+ ? `Start with \`get_dead_code\` and \`get_context\` on \`${repo}\` to see what the index already knows about these files, and \`get_why\` before proposing to remove anything.`
+ : null,
+ ]);
+}
diff --git a/packages/ui/src/workspace/contract-attention.tsx b/packages/ui/src/workspace/contract-attention.tsx
new file mode 100644
index 000000000..42df44a93
--- /dev/null
+++ b/packages/ui/src/workspace/contract-attention.tsx
@@ -0,0 +1,319 @@
+"use client";
+
+/**
+ * The contracts that need a reader's attention, from the extraction
+ * diagnostics the page already holds.
+ *
+ * Two lists with different weights. Client calls that resolve to no provider
+ * are grouped by the reason the matcher recorded, actionable reasons first and
+ * open; the reasons that need nothing (a third-party host, a call inside one
+ * service) start closed. Providers nothing calls are summarised per repository
+ * and type rather than listed, because most of them are ordinary exported code
+ * and a thousand rows would bury the few that matter; each summary row filters
+ * the full list below instead.
+ */
+
+import { memo, useMemo, useState, type ElementType } from "react";
+import type { OrphanProvider, UnmatchedConsumer } from "@repowise-dev/types/workspace";
+
+import { AiPromptButton } from "../health/ai-prompt-button";
+import { AiPromptModal } from "../health/ai-prompt-modal";
+import type { AiPromptFlavor } from "../health/ai-prompt-builder";
+import { formatNumber } from "../lib/format";
+import {
+ buildOrphanProvidersAiPrompt,
+ buildUnmatchedConsumersAiPrompt,
+ providerNoun,
+} from "./contract-ai-prompt";
+import { ContractIdentity, FilePathText } from "./contract-identity";
+import { sortUnmatchedReasons, unmatchedReasonCopy, type OrphanGroup } from "./contract-facts";
+import type { ContractRef } from "./contract-drawer";
+
+/** Rows an open group shows before "Show all". */
+const GROUP_PREVIEW = 5;
+/** Summary rows shown before "Show all". */
+const ORPHAN_PREVIEW = 8;
+
+export interface ContractAttentionProps {
+ unmatched: UnmatchedConsumer[];
+ /** From `groupOrphanProviders`, so the host can ship a sample per group. */
+ orphanGroups: OrphanGroup<OrphanProvider>[];
+ /** Open one consumer in the contract drawer. */
+ onSelect: (ref: ContractRef) => void;
+ /** Where the full list is filtered to one repository's unused providers of one type. */
+ browseHref: (repo: string, contractType: string) => string;
+ /** Router link for `browseHref`; defaults to a plain anchor. */
+ LinkComponent?: ElementType | undefined;
+}
+
+interface PromptState {
+ title: string;
+ description: string;
+ build: (flavor: AiPromptFlavor) => string;
+}
+
+export const ContractAttention = memo(function ContractAttention({
+ unmatched,
+ orphanGroups,
+ onSelect,
+ browseHref,
+ LinkComponent,
+}: ContractAttentionProps) {
+ const [prompt, setPrompt] = useState<PromptState | null>(null);
+
+ const groups = useMemo(() => {
+ const byReason = new Map<string, UnmatchedConsumer[]>();
+ for (const u of unmatched) {
+ const bucket = byReason.get(u.reason);
+ if (bucket) bucket.push(u);
+ else byReason.set(u.reason, [u]);
+ }
+ return sortUnmatchedReasons(
+ [...byReason.entries()].map(([reason, rows]) => ({ reason, rows, count: rows.length })),
+ );
+ }, [unmatched]);
+
+ const orphanTotal = orphanGroups.reduce((sum, g) => sum + g.count, 0);
+
+ if (unmatched.length === 0 && orphanTotal === 0) {
+ return (
+ <p className="text-xs text-[var(--color-text-secondary)]">
+ Every consumer matched a provider and every provider has a caller in this workspace.
+ </p>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-10">
+ {unmatched.length > 0 ? (
+ <div className="flex flex-col gap-4">
+ <SubHeading
+ title={`${formatNumber(unmatched.length)} client ${unmatched.length === 1 ? "call resolves" : "calls resolve"} to no provider`}
+ body="Grouped by the reason the matcher recorded. Open a row for the call site and the next step."
+ />
+ <div className="flex flex-col">
+ {groups.map((g) => (
+ <UnmatchedGroup
+ key={g.reason}
+ reason={g.reason}
+ rows={g.rows}
+ onSelect={onSelect}
+ onPrompt={() =>
+ setPrompt({
+ title: "AI prompt for these calls",
+ description: `${g.count} client ${g.count === 1 ? "call" : "calls"} recorded as ${unmatchedReasonCopy(g.reason).short}, with what to verify for each.`,
+ build: (flavor) =>
+ buildUnmatchedConsumersAiPrompt({ reason: g.reason, rows: g.rows, flavor }),
+ })
+ }
+ />
+ ))}
+ </div>
+ </div>
+ ) : null}
+
+ {orphanTotal > 0 ? (
+ <div className="flex flex-col gap-4">
+ <SubHeading
+ title={`${formatNumber(orphanTotal)} ${orphanTotal === 1 ? "provider has" : "providers have"} no caller in this workspace`}
+ body="Not the same as unused: a caller may be outside the workspace, in the same service, or written in a form extraction cannot follow. Most exported code looks like this."
+ />
+ <OrphanTable
+ groups={orphanGroups}
+ browseHref={browseHref}
+ LinkComponent={LinkComponent}
+ onPrompt={(g) =>
+ setPrompt({
+ title: "AI prompt for these providers",
+ description: `${g.count} ${providerNoun(g.contractType, g.count)} in ${g.repo} with no caller here, with how to tell used from unused.`,
+ build: (flavor) =>
+ buildOrphanProvidersAiPrompt({
+ repo: g.repo,
+ contractType: g.contractType,
+ rows: g.rows,
+ total: g.count,
+ flavor,
+ }),
+ })
+ }
+ />
+ </div>
+ ) : null}
+
+ <AiPromptModal
+ open={prompt !== null}
+ onOpenChange={(open) => {
+ if (!open) setPrompt(null);
+ }}
+ title={prompt?.title ?? "AI prompt"}
+ {...(prompt ? { description: prompt.description } : {})}
+ getPrompt={prompt?.build ?? null}
+ />
+ </div>
+ );
+});
+
+function SubHeading({ title, body }: { title: string; body: string }) {
+ return (
+ <div className="flex flex-col gap-1">
+ <h3 className="text-[15px] font-semibold text-[var(--color-text-primary)]">{title}</h3>
+ <p className="max-w-[72ch] text-xs leading-relaxed text-[var(--color-text-secondary)]">
+ {body}
+ </p>
+ </div>
+ );
+}
+
+function UnmatchedGroup({
+ reason,
+ rows,
+ onSelect,
+ onPrompt,
+}: {
+ reason: string;
+ rows: UnmatchedConsumer[];
+ onSelect: (ref: ContractRef) => void;
+ onPrompt: () => void;
+}) {
+ const copy = unmatchedReasonCopy(reason);
+ // Reasons with nothing to fix start closed: their rows are information, not work.
+ const [shown, setShown] = useState(copy.actionable ? Math.min(GROUP_PREVIEW, rows.length) : 0);
+ const hidden = rows.length - shown;
+
+ return (
+ <section className="border-t border-[var(--color-border-default)] py-4">
+ <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2">
+ <div className="min-w-0 flex-1">
+ <h4 className="flex items-baseline gap-2 text-xs font-medium text-[var(--color-text-primary)]">
+ {copy.title}
+ <span className="font-mono tabular-nums text-[var(--color-text-tertiary)]">
+ {formatNumber(rows.length)}
+ </span>
+ </h4>
+ <p className="mt-0.5 max-w-[72ch] text-xs leading-relaxed text-[var(--color-text-secondary)]">
+ {copy.meaning}
+ </p>
+ </div>
+ <AiPromptButton onClick={onPrompt} label="AI prompt" />
+ </div>
+
+ {shown > 0 ? (
+ <ul className="m-0 mt-3 flex list-none flex-col p-0">
+ {rows.slice(0, shown).map((u) => (
+ <li key={`${u.repo}|${u.file_path}|${u.contract_id}`}>
+ <button
+ type="button"
+ onClick={() =>
+ onSelect({ repo: u.repo, file_path: u.file_path, contract_id: u.contract_id })
+ }
+ className="grid w-full grid-cols-1 gap-x-4 gap-y-0.5 rounded-md px-2 py-1.5 text-left hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent-primary)] md:grid-cols-[minmax(0,5fr)_minmax(0,1fr)_minmax(0,5fr)]"
+ >
+ <ContractIdentity contractId={u.contract_id} />
+ <span className="text-xs text-[var(--color-text-secondary)]">{u.repo}</span>
+ <FilePathText path={u.file_path} />
+ </button>
+ </li>
+ ))}
+ </ul>
+ ) : null}
+
+ {hidden > 0 || shown > GROUP_PREVIEW ? (
+ <div className="mt-2 flex gap-4">
+ {hidden > 0 ? (
+ <button
+ type="button"
+ onClick={() => setShown(rows.length)}
+ className="text-xs font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ {shown === 0
+ ? `Show the ${formatNumber(rows.length)} ${rows.length === 1 ? "call" : "calls"}`
+ : `Show all ${formatNumber(rows.length)}`}
+ </button>
+ ) : null}
+ {shown > GROUP_PREVIEW ? (
+ <button
+ type="button"
+ onClick={() => setShown(GROUP_PREVIEW)}
+ className="text-xs font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ Show fewer
+ </button>
+ ) : null}
+ </div>
+ ) : null}
+ </section>
+ );
+}
+
+function OrphanTable({
+ groups,
+ browseHref,
+ LinkComponent,
+ onPrompt,
+}: {
+ groups: OrphanGroup<OrphanProvider>[];
+ browseHref: (repo: string, contractType: string) => string;
+ LinkComponent?: ElementType | undefined;
+ onPrompt: (group: OrphanGroup<OrphanProvider>) => void;
+}) {
+ const [all, setAll] = useState(false);
+ const shown = all ? groups : groups.slice(0, ORPHAN_PREVIEW);
+ const A = LinkComponent ?? "a";
+
+ return (
+ <div className="flex flex-col">
+ <table className="w-full border-collapse text-left">
+ <caption className="sr-only">Providers with no caller, per repository and type</caption>
+ <thead>
+ <tr className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ <th className="py-2 pr-3 font-normal">Repository</th>
+ <th className="py-2 pr-3 font-normal">Kind</th>
+ <th className="py-2 pr-3 text-right font-normal">No caller</th>
+ <th className="py-2 font-normal">
+ <span className="sr-only">Actions</span>
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {shown.map((g) => (
+ <tr key={`${g.repo}|${g.contractType}`} className="border-t border-[var(--color-border-default)]">
+ <td className="py-2 pr-3 text-xs font-medium text-[var(--color-text-primary)]">
+ {g.repo}
+ </td>
+ <td className="py-2 pr-3 text-xs text-[var(--color-text-secondary)]">
+ {providerNoun(g.contractType, 2)}
+ </td>
+ <td className="py-2 pr-3 text-right font-mono text-xs tabular-nums text-[var(--color-text-secondary)]">
+ {formatNumber(g.count)}
+ </td>
+ <td className="py-2">
+ <div className="flex items-center justify-end gap-3">
+ <A
+ href={browseHref(g.repo, g.contractType)}
+ className="text-xs font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ Browse
+ </A>
+ <AiPromptButton
+ variant="icon"
+ onClick={() => onPrompt(g)}
+ label={`AI prompt for ${g.repo} ${providerNoun(g.contractType, 2)} with no caller`}
+ />
+ </div>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {groups.length > ORPHAN_PREVIEW ? (
+ <button
+ type="button"
+ onClick={() => setAll((v) => !v)}
+ className="mt-2 self-start text-xs font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ {all ? "Show fewer" : `Show all ${formatNumber(groups.length)} groups`}
+ </button>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/ui/src/workspace/contract-drawer.tsx b/packages/ui/src/workspace/contract-drawer.tsx
index 3d12efdde..52fd677dd 100644
--- a/packages/ui/src/workspace/contract-drawer.tsx
+++ b/packages/ui/src/workspace/contract-drawer.tsx
@@ -1,231 +1,258 @@
"use client";
/**
- * One contract, as a right-hand drawer.
+ * One contract, as the shared right-hand panel.
*
- * The contracts table used to navigate away on a row click, which cost the
- * reader their filters and their scroll position to answer a question that
- * fits in a panel. The drawer answers it in place; the route it replaced is
- * still the shareable identity, so "Open full page" is always present and the
- * table keeps a modifier click on the contract id.
+ * Built on `AdaptivePanel` like every other drawer in the app, so it slides in
+ * from the right on desktop and becomes a bottom sheet on a phone. It answers
+ * what the contract is, where it lives, how extraction found it, what sits on
+ * the other side (or why nothing does and what to do about it), what changed,
+ * and which tests guard it. The detail route stays the shareable identity, so
+ * "Open full page" is always offered.
*
- * Presentation only. It knows a contract names a repo, a file and a symbol,
- * but not how the host routes to code, so href builders come in the same shape
- * `BreakingChangeRow` takes them.
+ * Presentation only. The host fetches the detail and the test impact when the
+ * panel opens, and supplies how it routes to code.
*/
import type { ReactNode } from "react";
+import { ExternalLink } from "lucide-react";
import type {
BreakingChange,
ContractSchema,
SchemaField,
WorkspaceContractLinkEntry,
+ WorkspaceTestImpactResponse,
} from "@repowise-dev/types/workspace";
-import { Sheet, SheetContent, SheetTitle } from "../ui/sheet";
+import { AdaptivePanel } from "../shared/adaptive-panel";
import {
BreakingChangeRow,
breakingChangeKey,
sortChangesBySeverity,
type BreakingChangeLinks,
} from "./breaking-change-row";
+import { ContractIdentity, FilePathText, distinctService } from "./contract-identity";
+import { ContractPromptButton } from "./contract-prompt-button";
+import { ContractTestsSection } from "./contract-tests-section";
import { contractTypeLabel } from "./contract-type-label";
import {
- contractHeading,
contractLede,
contractMetaEntries,
contractMetaLabel,
- contractMetaString,
flattenSchemaFields,
+ providerLinkedProse,
schemaFieldConstraints,
+ unlinkedProviderProse,
+ unmatchedConsumerProse,
+ unmatchedReasonCopy,
type ContractEntry,
} from "./contract-facts";
-/** `meta` keys the facts list already prints. */
-const FACT_META_KEYS = new Set(["method", "path", "framework", "client"]);
+/** The identity a contract is fetched and linked by. */
+export interface ContractRef {
+ repo: string;
+ file_path: string;
+ contract_id: string;
+}
export interface ContractDrawerProps {
+ /** The contract, once known. Null while a deep link is still loading. */
contract: ContractEntry | null;
open: boolean;
onOpenChange: (open: boolean) => void;
- /** The matched links this contract sits on. Use `linksForContract` to pick them. */
+ /** Title shown while `contract` is null, usually the requested id. */
+ pendingId?: string | undefined;
+ /** The detail answer is still loading; links and reason are not known yet. */
+ loading?: boolean | undefined;
+ /** The detail could not be read, worded by the host. */
+ error?: string | null | undefined;
+ /** The matched links this contract sits on. */
links?: WorkspaceContractLinkEntry[];
+ /** Why a consumer matched nothing, from the detail endpoint. */
+ unmatchedReason?: string | null | undefined;
/** Request and response fields, when a reader recovered them. */
schema?: ContractSchema | null | undefined;
/** Changes from the latest report that touch this contract id. */
breakingChanges?: BreakingChange[];
+ /** Consumer tests for a provider. Null when the host did not ask. */
+ testImpact?: WorkspaceTestImpactResponse | null | undefined;
+ testImpactLoading?: boolean | undefined;
+ testImpactError?: string | null | undefined;
/** How the host routes to code. A null return renders plain text. */
codeLinks?: BreakingChangeLinks | undefined;
/** The detail route for this contract. */
fullPageHref?: string | undefined;
+ /** Swap the panel to the other side of a link. */
+ onSelectContract?: ((ref: ContractRef) => void) | undefined;
}
export function ContractDrawer({
contract,
open,
onOpenChange,
+ pendingId,
+ loading = false,
+ error = null,
links = [],
+ unmatchedReason = null,
schema,
breakingChanges = [],
+ testImpact = null,
+ testImpactLoading = false,
+ testImpactError = null,
codeLinks,
fullPageHref,
+ onSelectContract,
}: ContractDrawerProps) {
+ const id = contract?.contract_id ?? pendingId ?? "";
+
return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent
- side="right"
- closeLabel="Close contract"
- // Wider than the nav sheet this primitive was written for: a request
- // path and a wrapping file path are what set the floor here.
- className="w-full max-w-[620px] sm:w-[92vw]"
- >
- {contract ? (
- <DrawerBody
- contract={contract}
- links={links}
- schema={schema ?? null}
- breakingChanges={breakingChanges}
- codeLinks={codeLinks}
- fullPageHref={fullPageHref}
- />
- ) : (
- <SheetTitle className="sr-only">Contract</SheetTitle>
- )}
- </SheetContent>
- </Sheet>
+ <AdaptivePanel
+ open={open}
+ onOpenChange={onOpenChange}
+ eyebrow={
+ contract
+ ? `${contractTypeLabel(contract.contract_type)} contract / ${
+ contract.role === "provider" ? "Provider" : "Consumer"
+ }`
+ : "Contract"
+ }
+ title={
+ // The panel's title style breaks anywhere; the identity opts back out
+ // so a path wraps at its slashes.
+ id ? <ContractIdentity contractId={id} size="title" /> : "Contract"
+ }
+ widthClassName="md:max-w-[600px]"
+ >
+ {contract ? (
+ <Body
+ contract={contract}
+ loading={loading}
+ error={error}
+ links={links}
+ unmatchedReason={unmatchedReason}
+ schema={schema ?? null}
+ breakingChanges={breakingChanges}
+ testImpact={testImpact}
+ testImpactLoading={testImpactLoading}
+ testImpactError={testImpactError}
+ codeLinks={codeLinks}
+ fullPageHref={fullPageHref}
+ onSelectContract={onSelectContract}
+ />
+ ) : (
+ <p className="px-4 py-4 text-xs text-[var(--color-text-tertiary)]">
+ {error ?? (loading ? "Loading contract..." : "This contract is not in the workspace.")}
+ </p>
+ )}
+
+ </AdaptivePanel>
);
}
-function DrawerBody({
+function Body({
contract,
+ loading,
+ error,
links,
+ unmatchedReason,
schema,
breakingChanges,
+ testImpact,
+ testImpactLoading,
+ testImpactError,
codeLinks,
fullPageHref,
+ onSelectContract,
}: {
contract: ContractEntry;
+ loading: boolean;
+ error: string | null;
links: WorkspaceContractLinkEntry[];
+ unmatchedReason: string | null;
schema: ContractSchema | null;
breakingChanges: BreakingChange[];
+ testImpact: WorkspaceTestImpactResponse | null;
+ testImpactLoading: boolean;
+ testImpactError: string | null;
codeLinks?: BreakingChangeLinks | undefined;
fullPageHref?: string | undefined;
+ onSelectContract?: ((ref: ContractRef) => void) | undefined;
}) {
const isProvider = contract.role === "provider";
- const meta = contract.meta ?? {};
- const method = contractMetaString(meta, "method");
- const path = contractMetaString(meta, "path");
- const frameworkName = contractMetaString(meta, "framework");
- const client = contractMetaString(meta, "client");
const fileHref = codeLinks?.fileHref?.(contract.repo, contract.file_path) ?? null;
- // What the facts above already print is dropped here, so the panel does not
- // say "fastapi" twice under two different headings.
- const metaEntries = contractMetaEntries(meta).filter(
- ([key]) => !FACT_META_KEYS.has(key),
- );
+ const symbolHref = contract.symbol_id
+ ? (codeLinks?.symbolHref?.(contract.repo, contract.symbol_id) ?? null)
+ : null;
+ const metaEntries = contractMetaEntries(contract.meta);
return (
<>
- <div className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12">
- <div className="text-[11px] text-[var(--color-text-secondary)]">
- {contractTypeLabel(contract.contract_type)} contract
- <span className="mx-2 text-[var(--color-border-hover)]">/</span>
- {isProvider ? "Provider" : "Consumer"}
+ <div className="flex min-h-0 flex-1 flex-col gap-6 px-4 py-4">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <p className="min-w-0 flex-1 text-[15px] leading-relaxed text-[var(--color-text-secondary)]">
+ {contractLede(contract)}
+ </p>
+ <ContractPromptButton
+ contract={contract}
+ links={links}
+ unmatchedReason={unmatchedReason}
+ breakingChanges={breakingChanges}
+ />
</div>
- <SheetTitle className="mt-0.5 break-words font-mono text-[15px] font-semibold text-[var(--color-text-primary)]">
- {contractHeading(contract)}
- </SheetTitle>
- <p className="mt-1.5 text-[12.5px] leading-relaxed text-[var(--color-text-secondary)]">
- {contractLede(contract)}
- </p>
- </div>
- <div className="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto px-5 py-5">
- <Facts>
- <Fact label="Contract id">
- <Mono>{contract.contract_id}</Mono>
- </Fact>
- {method ? (
- <Fact label="Method">
- <span className="text-xs">{method}</span>
+ <Section title="Where it lives">
+ <Facts>
+ <Fact label="Repository">
+ {contract.repo}
+ {contract.service ? (
+ <span className="text-[var(--color-text-tertiary)]">
+ {" "}
+ / <span className="font-mono text-xs">{contract.service}</span>
+ </span>
+ ) : null}
</Fact>
- ) : null}
- {path ? (
- <Fact label="Path">
- <Mono>{path}</Mono>
+ <Fact label="File">
+ {fileHref ? (
+ <a
+ href={fileHref}
+ className="rounded-sm hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <FilePathText path={contract.file_path} line={contract.line} accent />
+ </a>
+ ) : (
+ <FilePathText path={contract.file_path} line={contract.line} />
+ )}
</Fact>
- ) : null}
- <Fact label="Repository">
- <span className="text-xs">{contract.repo}</span>
- </Fact>
- <Fact label="File">
- {fileHref ? (
- <a href={fileHref} className="text-[var(--color-accent-primary)] hover:underline">
- <Mono>{contract.file_path}</Mono>
- </a>
- ) : (
- <Mono>{contract.file_path}</Mono>
- )}
- {contract.line != null ? (
- <span className="ml-2 text-xs tabular-nums text-[var(--color-text-tertiary)]">
- line {contract.line}
- </span>
+ {contract.symbol_name ? (
+ <Fact label="Symbol">
+ {symbolHref ? (
+ <a
+ href={symbolHref}
+ className="font-mono text-xs text-[var(--color-accent-primary)] [overflow-wrap:anywhere] hover:underline"
+ >
+ {contract.symbol_name}
+ </a>
+ ) : (
+ <Mono>{contract.symbol_name}</Mono>
+ )}
+ </Fact>
) : null}
- </Fact>
- {contract.service ? (
- <Fact label="Service">
- <span className="text-xs">{contract.service}</span>
- </Fact>
- ) : null}
- {frameworkName ? (
- <Fact label="Framework">
- <span className="text-xs">{frameworkName}</span>
- </Fact>
- ) : client ? (
- <Fact label="Client">
- <span className="text-xs">{client}</span>
+ <Fact label="Contract id">
+ <Mono>{contract.contract_id}</Mono>
</Fact>
- ) : null}
- <Fact label="Confidence">
- <span className="text-xs tabular-nums">{Math.round(contract.confidence * 100)}%</span>
- </Fact>
- </Facts>
-
- <Section title={isProvider ? "Callers" : "Served by"}>
- {links.length === 0 ? (
- <p className="text-[12.5px] leading-relaxed text-[var(--color-text-tertiary)]">
- {isProvider
- ? "Nothing in this workspace resolves to this contract. A call from inside the same repository and service is excluded by construction, and a call written in a form extraction could not follow looks the same from here."
- : "This call matched no declaration in the workspace. The full page names the reason recorded for it."}
- </p>
- ) : (
- <ul className="flex flex-col gap-2.5">
- {links.map((link) => (
- <CounterpartRow
- key={`${link.provider_repo}|${link.provider_file}|${link.consumer_repo}|${link.consumer_file}`}
- link={link}
- side={isProvider ? "consumer" : "provider"}
- codeLinks={codeLinks}
- />
- ))}
- </ul>
- )}
+ </Facts>
</Section>
- {schema && (schema.request_fields.length > 0 || schema.response_fields.length > 0) ? (
- <Section title="Shape">
- <p className="text-[12.5px] leading-relaxed text-[var(--color-text-tertiary)]">
- Recovered by the {schema.source} reader. Fields are what the declaration names, not
- what any one caller passes.
- </p>
- {schema.request_fields.length > 0 ? (
- <FieldList caption="Request" fields={schema.request_fields} />
- ) : null}
- {schema.response_fields.length > 0 ? (
- <FieldList caption="Response" fields={schema.response_fields} />
- ) : null}
- </Section>
- ) : null}
+ <Counterparts
+ contract={contract}
+ loading={loading}
+ error={error}
+ links={links}
+ unmatchedReason={unmatchedReason}
+ codeLinks={codeLinks}
+ onSelectContract={onSelectContract}
+ />
{breakingChanges.length > 0 ? (
<Section title="Breaking changes">
@@ -241,25 +268,65 @@ function DrawerBody({
</Section>
) : null}
- {metaEntries.length > 0 ? (
- <Section title="How it was found">
- <Facts>
- {metaEntries.map(([key, value]) => (
- <Fact key={key} label={contractMetaLabel(key)}>
- <Mono>{value}</Mono>
- </Fact>
- ))}
- </Facts>
+ {isProvider ? (
+ testImpactLoading ? (
+ <Section title="Tests to run">
+ <Quiet>Finding the tests in the calling repositories...</Quiet>
+ </Section>
+ ) : (
+ <ContractTestsSection
+ result={testImpact}
+ contractId={contract.contract_id}
+ error={testImpactError}
+ compact
+ />
+ )
+ ) : null}
+
+ {schema && (schema.request_fields.length > 0 || schema.response_fields.length > 0) ? (
+ <Section title="Shape">
+ <Quiet>
+ Recovered by the {schema.source} reader. Fields are what the declaration names, not
+ what any one caller passes.
+ </Quiet>
+ {schema.request_fields.length > 0 ? (
+ <FieldList caption="Request" fields={schema.request_fields} />
+ ) : null}
+ {schema.response_fields.length > 0 ? (
+ <FieldList caption="Response" fields={schema.response_fields} />
+ ) : null}
</Section>
) : null}
+
+ <Section title="How it was found">
+ <Facts>
+ <Fact label="Confidence">
+ <span className="font-mono text-xs tabular-nums">
+ {Math.round(contract.confidence * 100)}%
+ </span>
+ </Fact>
+ {metaEntries.map(([key, value]) => (
+ <Fact key={key} label={contractMetaLabel(key)}>
+ <Mono>{value}</Mono>
+ </Fact>
+ ))}
+ </Facts>
+ {contract.meta?.extraction_layer === "regex" ? (
+ <Quiet>
+ Found by a text pattern rather than the parsed symbol table, which is where recall is
+ least certain.
+ </Quiet>
+ ) : null}
+ </Section>
</div>
{fullPageHref ? (
- <div className="border-t border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-5 py-3">
+ <div className="sticky bottom-0 border-t border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-4 py-3">
<a
href={fullPageHref}
- className="text-xs font-medium text-[var(--color-accent-primary)] hover:underline"
+ className="inline-flex items-center gap-1.5 text-xs font-medium text-[var(--color-accent-primary)] hover:underline"
>
+ <ExternalLink className="h-3.5 w-3.5" aria-hidden />
Open full page
</a>
</div>
@@ -268,46 +335,150 @@ function DrawerBody({
);
}
-/** The other side of one matched link: where it lives and what code it is. */
+/** The other side of the contract, or why there is none and what to do next. */
+function Counterparts({
+ contract,
+ loading,
+ error,
+ links,
+ unmatchedReason,
+ codeLinks,
+ onSelectContract,
+}: {
+ contract: ContractEntry;
+ loading: boolean;
+ error: string | null;
+ links: WorkspaceContractLinkEntry[];
+ unmatchedReason: string | null;
+ codeLinks?: BreakingChangeLinks | undefined;
+ onSelectContract?: ((ref: ContractRef) => void) | undefined;
+}) {
+ const isProvider = contract.role === "provider";
+ const title = isProvider ? "Callers" : "Served by";
+
+ if (loading) {
+ return (
+ <Section title={title}>
+ <Quiet>Loading the links for this contract...</Quiet>
+ </Section>
+ );
+ }
+ if (error) {
+ return (
+ <Section title={title}>
+ <Quiet>{error}</Quiet>
+ </Section>
+ );
+ }
+ if (links.length === 0) {
+ return (
+ <Section title={isProvider ? "No caller found" : unmatchedReasonCopy(unmatchedReason).title}>
+ <Quiet>
+ {isProvider
+ ? unlinkedProviderProse(contract)
+ : unmatchedConsumerProse(unmatchedReason, contract)}
+ </Quiet>
+ </Section>
+ );
+ }
+
+ return (
+ <Section title={title}>
+ <Quiet>
+ {isProvider
+ ? providerLinkedProse(links, contract.repo)
+ : "This call resolves to the code that serves it. A match joins a call site to a declaration; it does not mean both were written against a shared schema."}
+ </Quiet>
+ <ul className="m-0 flex list-none flex-col p-0">
+ {links.map((link) => (
+ <CounterpartRow
+ key={`${link.consumer_contract_id ?? ""}|${link.provider_repo}|${link.provider_file}|${link.consumer_repo}|${link.consumer_file}`}
+ link={link}
+ side={isProvider ? "consumer" : "provider"}
+ codeLinks={codeLinks}
+ onSelectContract={onSelectContract}
+ />
+ ))}
+ </ul>
+ </Section>
+ );
+}
+
+/**
+ * One counterpart. The row swaps the panel to that contract, which is the one
+ * verb; the code link is a separate, smaller target beside it.
+ */
function CounterpartRow({
link,
side,
codeLinks,
+ onSelectContract,
}: {
link: WorkspaceContractLinkEntry;
side: "provider" | "consumer";
codeLinks?: BreakingChangeLinks | undefined;
+ onSelectContract?: ((ref: ContractRef) => void) | undefined;
}) {
const repo = side === "provider" ? link.provider_repo : link.consumer_repo;
const file = side === "provider" ? link.provider_file : link.consumer_file;
const symbol = side === "provider" ? link.provider_symbol : link.consumer_symbol;
+ const service = distinctService(
+ side === "provider" ? link.provider_service : link.consumer_service,
+ side === "provider" ? link.provider_file : link.consumer_file,
+ );
const symbolId = side === "provider" ? link.provider_symbol_id : link.consumer_symbol_id;
- // The symbol page is the better destination when the side bound to one; the
- // file page is the fallback, and plain text when the repo has no index.
- const href =
+ // A consumer bound through another name (a queue on an exchange) keeps its own id.
+ const id = side === "consumer" ? (link.consumer_contract_id ?? link.contract_id) : link.contract_id;
+ const codeHref =
(symbolId ? codeLinks?.symbolHref?.(repo, symbolId) : null) ??
codeLinks?.fileHref?.(repo, file) ??
null;
+ const content = (
+ <>
+ <span className="text-xs font-medium text-[var(--color-text-primary)]">
+ {repo}
+ {service ? (
+ <span className="font-mono font-normal text-[var(--color-text-tertiary)]"> / {service}</span>
+ ) : null}
+ </span>
+ <span className="block">
+ <FilePathText path={file} />
+ </span>
+ {symbol ? (
+ <span className="block font-mono text-[10px] text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
+ {symbol}
+ </span>
+ ) : null}
+ <span className="block text-[10px] text-[var(--color-text-tertiary)]">
+ {link.match_type} match,{" "}
+ <span className="font-mono tabular-nums">{Math.round(link.confidence * 100)}%</span>
+ </span>
+ </>
+ );
+
return (
- <li className="min-w-0">
- <div className="text-xs font-medium text-[var(--color-text-primary)]">{repo}</div>
- {href ? (
- <a href={href} className="text-[var(--color-accent-primary)] hover:underline">
- <Mono>{file}</Mono>
- </a>
+ <li className="flex items-start gap-2 border-t border-[var(--color-border-default)] py-2 first:border-t-0">
+ {onSelectContract ? (
+ <button
+ type="button"
+ onClick={() => onSelectContract({ repo, file_path: file, contract_id: id })}
+ className="-mx-1 min-w-0 flex-1 rounded-md px-1 py-0.5 text-left hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ aria-label={`Open the ${side} in ${repo}, ${file}`}
+ >
+ {content}
+ </button>
) : (
- <Mono>{file}</Mono>
+ <div className="min-w-0 flex-1">{content}</div>
)}
- {symbol ? (
- <div className="mt-0.5 text-[var(--color-text-tertiary)]">
- <Mono>{symbol}</Mono>
- </div>
+ {codeHref ? (
+ <a
+ href={codeHref}
+ className="shrink-0 pt-0.5 text-[10px] font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ Code
+ </a>
) : null}
- <div className="mt-0.5 text-[11px] text-[var(--color-text-tertiary)]">
- {link.match_type} match ·{" "}
- <span className="tabular-nums">{Math.round(link.confidence * 100)}%</span>
- </div>
</li>
);
}
@@ -329,7 +500,7 @@ function FieldList({ caption, fields }: { caption: string; fields: SchemaField[]
<span className="font-mono text-xs text-[var(--color-text-secondary)] [overflow-wrap:anywhere]">
{f.type}
</span>
- <span className="text-[11px] text-[var(--color-text-tertiary)]">
+ <span className="text-[10px] text-[var(--color-text-tertiary)]">
{schemaFieldConstraints(f)}
</span>
</li>
@@ -350,6 +521,14 @@ function Section({ title, children }: { title: string; children: ReactNode }) {
);
}
+function Quiet({ children }: { children: ReactNode }) {
+ return (
+ <p className="text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ {children}
+ </p>
+ );
+}
+
function Facts({ children }: { children: ReactNode }) {
return (
<dl className="m-0 grid grid-cols-1 gap-x-6 gap-y-2 sm:grid-cols-[max-content_minmax(0,1fr)]">
@@ -361,11 +540,11 @@ function Facts({ children }: { children: ReactNode }) {
function Fact({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="contents">
- <dt className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] sm:pt-1">
+ <dt className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] sm:pt-0.5">
{label}
</dt>
{/* min-w-0 or a long path refuses to shrink and pushes the panel wide. */}
- <dd className="m-0 min-w-0 text-[var(--color-text-secondary)]">{children}</dd>
+ <dd className="m-0 min-w-0 text-xs text-[var(--color-text-secondary)]">{children}</dd>
</div>
);
}
diff --git a/packages/ui/src/workspace/contract-facts.ts b/packages/ui/src/workspace/contract-facts.ts
index a9c4e16ac..f7fe7aa58 100644
--- a/packages/ui/src/workspace/contract-facts.ts
+++ b/packages/ui/src/workspace/contract-facts.ts
@@ -238,3 +238,200 @@ export function linksForContract<
l.consumer_file === contract.file_path,
);
}
+
+// ---------------------------------------------------------------------------
+// Identity parsed off the id, and the words each state is read in. Shared by
+// the list rows, the drawer, the detail page and the agent prompts, so every
+// surface names one contract and one state the same way.
+// ---------------------------------------------------------------------------
+
+/** A contract id split into the parts a reader scans for. */
+export interface ContractIdParts {
+ /** The id's leading type segment: `http`, `data`, `code`, `grpc`... */
+ kind: string;
+ /** HTTP verb, when the id carries one. `*` is kept as extraction wrote it. */
+ method: string | null;
+ /** Path, table, symbol or rpc: the part a reader recognises. */
+ label: string;
+ /** The package a `code` contract is exported from. */
+ qualifier: string | null;
+}
+
+/**
+ * Parse `http::GET::/path`, `data::table`, `code::pkg::symbol` and friends.
+ * Only rows that carry nothing but the id (links, diagnostics) need this; a
+ * full entry reads its `meta` instead through `contractHeading`.
+ */
+export function parseContractId(id: string): ContractIdParts {
+ const parts = id.split("::");
+ const kind = parts[0] ?? "";
+ if (parts.length < 2) return { kind: "", method: null, label: id, qualifier: null };
+ if (kind === "http" && parts.length >= 3) {
+ return { kind, method: parts[1] ?? null, label: parts.slice(2).join("::"), qualifier: null };
+ }
+ if (kind === "code" && parts.length >= 3) {
+ return {
+ kind,
+ method: null,
+ label: parts.slice(2).join("::"),
+ qualifier: parts[1] ?? null,
+ };
+ }
+ return { kind, method: null, label: parts.slice(1).join("::"), qualifier: null };
+}
+
+/** Why a consumer matched no provider, in words, with what to do about it. */
+export interface UnmatchedReasonCopy {
+ /** Heading for one consumer in this state. */
+ title: string;
+ /** Short label for counts: "54 no provider found". */
+ short: string;
+ /** One line for a group of consumers in this state. */
+ meaning: string;
+ /** Whether a reader has something to fix, which orders the groups. */
+ actionable: boolean;
+}
+
+export const UNMATCHED_REASONS: Record<string, UnmatchedReasonCopy> = {
+ no_provider: {
+ title: "No provider found",
+ short: "no provider found",
+ meaning:
+ "Nothing in the workspace declares these routes: a typo, a removed endpoint, a service outside the workspace, or a framework extraction does not read.",
+ actionable: true,
+ },
+ unlinked: {
+ title: "No link formed",
+ short: "unlinked",
+ meaning:
+ "A matching declaration exists in another service but no link was formed, which points at the matcher rather than the code.",
+ actionable: true,
+ },
+ internal_only: {
+ title: "Not a cross-repo link",
+ short: "internal to one service",
+ meaning:
+ "The only matching declaration is in the same repository and service, so the call never crosses a boundary. Nothing to fix.",
+ actionable: false,
+ },
+ external_host: {
+ title: "Outside this workspace",
+ short: "external host",
+ meaning:
+ "Calls to a literal third-party host, left out of matching on purpose. Nothing to fix unless the host is one of your own services.",
+ actionable: false,
+ },
+};
+
+const UNKNOWN_REASON: UnmatchedReasonCopy = {
+ title: "No provider found",
+ short: "no reason recorded",
+ meaning:
+ "These calls matched no declaration and no reason was recorded. Reasons come from the system graph, so rebuild it to get one.",
+ actionable: true,
+};
+
+export function unmatchedReasonCopy(reason: string | null | undefined): UnmatchedReasonCopy {
+ return (reason && UNMATCHED_REASONS[reason]) || UNKNOWN_REASON;
+}
+
+/** Actionable reasons first, then by size. */
+export function sortUnmatchedReasons<T extends { reason: string; count: number }>(
+ groups: T[],
+): T[] {
+ return groups
+ .slice()
+ .sort(
+ (a, b) =>
+ Number(unmatchedReasonCopy(b.reason).actionable) -
+ Number(unmatchedReasonCopy(a.reason).actionable) || b.count - a.count,
+ );
+}
+
+/** One consumer's unmatched state as a paragraph, with the concrete next step. */
+export function unmatchedConsumerProse(reason: string | null, contract: ContractEntry): string {
+ const host = contractMetaString(contract.meta, "host");
+ switch (reason) {
+ case "external_host":
+ return `This call goes to ${host ?? "a third-party host"}, which is not a service in this workspace. Calls to a literal external host are left out of matching on purpose, so there is nothing to link. If ${host ?? "that host"} is one of your own services, add its repository to the workspace.`;
+ case "internal_only":
+ return "The only declarations matching this call live in the same repository and the same service as the call itself, so it never crosses a boundary. Intra-service calls are left out of the link set on purpose: a link is a claim that two services depend on each other.";
+ case "no_provider":
+ return `Nothing in this workspace declares ${contractHeading(contract)}. Check for a typo in the path, an endpoint that was renamed or removed, a service outside these repositories, or a route declared in a form extraction does not recognise.`;
+ case "unlinked":
+ return "A declaration with this id exists in another service, but no link was formed between the two. That is rare, and it points at a gap in the matcher rather than at the code.";
+ default:
+ return "This call matched no declaration, and no reason was recorded for it. Reasons come from the system graph, so a workspace that has not built one reports the count without the explanation.";
+ }
+}
+
+/**
+ * A provider nothing calls. The expected state for most exported code, so it
+ * reads as a sentence and never as a warning.
+ */
+export function unlinkedProviderProse(contract: ContractEntry): string {
+ // A pair is skipped when the repository *and* the service both match, so
+ // the excluded set is not "everything in this repo" unless this declaration
+ // also sits outside a service.
+ const excluded = contract.service
+ ? `a call from inside ${contract.repo}/${contract.service}`
+ : `a call from elsewhere in ${contract.repo} that also sits outside any service`;
+ return `Nothing in this workspace resolves to this contract. It may be called from outside the workspace, or by code extraction cannot follow, and ${excluded} is excluded by construction. Neither reading makes it dead code.`;
+}
+
+/** How many call sites resolve to a provider, and from where. */
+export function providerLinkedProse(
+ links: { consumer_repo: string }[],
+ repo: string,
+): string {
+ const n = links.length;
+ const one = n === 1;
+ const repos = new Set(links.map((l) => l.consumer_repo));
+ const head = `${n} call ${one ? "site resolves" : "sites resolve"} to this contract`;
+ if (repos.size === 1 && repos.has(repo)) {
+ return `${head}, ${one ? "from" : "all from"} a different service inside ${repo}.`;
+ }
+ return `${head} across ${repos.size} ${repos.size === 1 ? "repository" : "repositories"}.`;
+}
+
+/**
+ * What a link's confidence is. It is the lower of the two sides' extraction
+ * confidence, so it names how each side was found, not how well they match.
+ */
+export const LINK_CONFIDENCE_NOTE =
+ "A link's confidence is the lower of its two sides' extraction confidence, so it says how each side was found, not how well they match. For example, exports and imports read from the symbol index score 90%, routes, tables and client calls 75 to 85%, SQL found in strings 70%, and calls through a helper recognised only by its name 65%.";
+
+/** Providers with no caller, for one repository and type. */
+export interface OrphanGroup<T> {
+ repo: string;
+ contractType: string;
+ /** Every provider in the group. */
+ count: number;
+ /** The first `keep` of them: enough for a prompt, not the whole list. */
+ rows: T[];
+}
+
+/**
+ * Group providers with no caller by repository and type, largest first.
+ *
+ * Runs on the server so the page ships counts and a prompt's worth of rows per
+ * group, not every provider: on a large workspace the full list is most of the
+ * payload and the page only ever shows a summary of it.
+ */
+export function groupOrphanProviders<T extends { repo: string; contract_type: string }>(
+ orphans: T[],
+ keep: number,
+): OrphanGroup<T>[] {
+ const byKey = new Map<string, OrphanGroup<T>>();
+ for (const o of orphans) {
+ const key = `${o.repo}\u0000${o.contract_type}`;
+ let group = byKey.get(key);
+ if (!group) {
+ group = { repo: o.repo, contractType: o.contract_type, count: 0, rows: [] };
+ byKey.set(key, group);
+ }
+ group.count += 1;
+ if (group.rows.length < keep) group.rows.push(o);
+ }
+ return [...byKey.values()].sort((a, b) => b.count - a.count || a.repo.localeCompare(b.repo));
+}
diff --git a/packages/ui/src/workspace/contract-identity.tsx b/packages/ui/src/workspace/contract-identity.tsx
new file mode 100644
index 000000000..c5bf1c31f
--- /dev/null
+++ b/packages/ui/src/workspace/contract-identity.tsx
@@ -0,0 +1,132 @@
+/**
+ * How a contract and a file read in a row. Paths get a break opportunity after
+ * each `/`, so they wrap between segments and a segment is split only when it
+ * alone is wider than its column. No `"use client"`: server and client rows
+ * both render them.
+ */
+
+import { Fragment } from "react";
+import { parseContractId } from "./contract-facts";
+
+/** A slash-separated string that wraps only after its slashes. */
+export function SlashBreaks({ text }: { text: string }) {
+ const segments = text.split("/");
+ return (
+ <>
+ {segments.map((segment, i) => (
+ <Fragment key={i}>
+ {segment}
+ {i < segments.length - 1 ? (
+ <>
+ /<wbr />
+ </>
+ ) : null}
+ </Fragment>
+ ))}
+ </>
+ );
+}
+
+const KIND_TAG: Record<string, string> = {
+ data: "TABLE",
+ grpc: "RPC",
+ topic: "TOPIC",
+ socket: "SOCKET",
+};
+
+/**
+ * The contract as a reader names it: the verb as a small mono label, then the
+ * path, table or symbol. `code` contracts carry their package underneath.
+ */
+export function ContractIdentity({
+ contractId,
+ size = "row",
+ className,
+}: {
+ contractId: string;
+ /** `title` sets the label at the drawer heading's 15px. */
+ size?: "row" | "title";
+ className?: string;
+}) {
+ const { kind, method, label, qualifier } = parseContractId(contractId);
+ // HTTP rows carry their verb; other non-code kinds carry the kind, so a
+ // table name never reads as a path with its verb missing.
+ const tag = method ? (method === "*" ? "ANY" : method) : KIND_TAG[kind] ?? null;
+ return (
+ <span
+ className={`inline-flex min-w-0 items-baseline gap-2 ${className ?? ""}`}
+ title={contractId}
+ >
+ {tag ? (
+ <span className="shrink-0 font-mono text-[10px] font-medium uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]">
+ {tag}
+ </span>
+ ) : null}
+ <span className="min-w-0 [word-break:normal] [overflow-wrap:break-word]">
+ <span
+ className={`font-mono text-[var(--color-text-primary)] ${
+ size === "title" ? "text-[15px] font-semibold" : "text-xs"
+ }`}
+ >
+ <SlashBreaks text={label} />
+ </span>
+ {qualifier ? (
+ <span className="block font-mono text-[10px] text-[var(--color-text-tertiary)]">
+ {qualifier}
+ </span>
+ ) : null}
+ </span>
+ </span>
+ );
+}
+
+/**
+ * A repo-relative file: the directory dim, the file name at reading weight,
+ * the line when known. The full path rides on `title`.
+ */
+export function FilePathText({
+ path,
+ line,
+ accent = false,
+}: {
+ path: string;
+ line?: number | null | undefined;
+ /** The file name in the link colour, for a path that is a link. */
+ accent?: boolean;
+}) {
+ const cut = path.lastIndexOf("/");
+ const dir = cut >= 0 ? path.slice(0, cut + 1) : "";
+ const name = cut >= 0 ? path.slice(cut + 1) : path;
+ return (
+ <span
+ className="font-mono text-xs [word-break:normal] [overflow-wrap:break-word]"
+ title={line != null ? `${path}:${line}` : path}
+ >
+ {dir ? (
+ <span className="text-[var(--color-text-tertiary)]">
+ <SlashBreaks text={dir} />
+ </span>
+ ) : null}
+ <span
+ className={
+ accent ? "text-[var(--color-accent-primary)]" : "text-[var(--color-text-secondary)]"
+ }
+ >
+ {name}
+ </span>
+ {line != null ? (
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">:{line}</span>
+ ) : null}
+ </span>
+ );
+}
+
+/**
+ * The service, unless the file path already says it. Services are usually a
+ * directory (`packages/api-client`), and printing one above a path that starts
+ * with it says the same thing twice.
+ */
+export function distinctService(service: string | null | undefined, file: string): string | null {
+ if (!service) return null;
+ return file === service || file.startsWith(`${service}/`) ? null : service;
+}
diff --git a/packages/ui/src/workspace/contract-links-table.tsx b/packages/ui/src/workspace/contract-links-table.tsx
index 3df9fe1a7..3f5bb5575 100644
--- a/packages/ui/src/workspace/contract-links-table.tsx
+++ b/packages/ui/src/workspace/contract-links-table.tsx
@@ -1,21 +1,112 @@
"use client";
+import { memo, useMemo } from "react";
import { ContractTypeBadge } from "./contract-type-badge";
+import { ContractIdentity, FilePathText, distinctService } from "./contract-identity";
+import { LINK_CONFIDENCE_NOTE } from "./contract-facts";
import { EmptyState } from "../shared/empty-state";
-import { VirtualizedTable } from "../shared/virtualized-table";
+import { InfoTip } from "../shared/info-tip";
+import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";
import type { WorkspaceContractLinkEntry } from "@repowise-dev/types/workspace";
interface ContractLinksTableProps {
links: WorkspaceContractLinkEntry[];
+ /** Open one link. The row is the verb; without this the rows are plain. */
+ onSelect?: ((link: WorkspaceContractLinkEntry) => void) | undefined;
}
-// Column-priority hide classes, mirroring the shared ResponsiveTable scale:
-// priority 2 hides below md (768px), priority 3 hides below lg (1024px). The
-// always-visible columns (priority 1) carry no hide class.
-const HIDE_BELOW_MD = "max-md:hidden";
-const HIDE_BELOW_LG = "max-lg:hidden";
+function Side({
+ repo,
+ service,
+ file,
+}: {
+ repo: string;
+ service: string | null;
+ file: string;
+}) {
+ const shownService = distinctService(service, file);
+ return (
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <span className="text-xs font-medium text-[var(--color-text-primary)]">
+ {repo}
+ {shownService ? (
+ <span className="font-mono font-normal text-[var(--color-text-tertiary)]">
+ {" "}
+ / {shownService}
+ </span>
+ ) : null}
+ </span>
+ <FilePathText path={file} />
+ </div>
+ );
+}
+
+const COLUMNS: ResponsiveColumn<WorkspaceContractLinkEntry>[] = [
+ {
+ key: "contract",
+ header: "Contract",
+ cellClassName: "min-w-[180px] max-w-[320px]",
+ render: (l) => <ContractIdentity contractId={l.contract_id} />,
+ },
+ {
+ key: "type",
+ header: "Type",
+ priority: 3,
+ render: (l) => <ContractTypeBadge type={l.contract_type} />,
+ },
+ {
+ key: "provider",
+ header: "Provider",
+ render: (l) => <Side repo={l.provider_repo} service={l.provider_service} file={l.provider_file} />,
+ },
+ {
+ key: "consumer",
+ header: "Consumer",
+ priority: 2,
+ render: (l) => <Side repo={l.consumer_repo} service={l.consumer_service} file={l.consumer_file} />,
+ },
+ {
+ key: "confidence",
+ // One explanation in the header instead of a bar per row: the figure is the
+ // weaker side's extraction confidence, so it repeats in long runs.
+ header: (
+ <span className="inline-flex items-center gap-1">
+ Confidence
+ <InfoTip content={LINK_CONFIDENCE_NOTE} label="What link confidence means" />
+ </span>
+ ),
+ mobileLabel: "Confidence",
+ align: "right",
+ priority: 3,
+ render: (l) => (
+ <span className="font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ {Math.round(l.confidence * 100)}%
+ </span>
+ ),
+ },
+];
+
+function linkKey(l: WorkspaceContractLinkEntry): string {
+ return `${l.contract_id}|${l.consumer_contract_id ?? ""}|${l.provider_repo}|${l.provider_file}|${l.consumer_repo}|${l.consumer_file}`;
+}
+
+/** Memoised so opening the drawer above it does not redraw every row. */
+export const ContractLinksTable = memo(function ContractLinksTable({
+ links,
+ onSelect,
+}: ContractLinksTableProps) {
+ // Strongest first, then by contract: the extraction order put a run of the
+ // weakest links on top, which read as if every link were weak.
+ const sorted = useMemo(
+ () =>
+ links
+ .slice()
+ .sort(
+ (a, b) => b.confidence - a.confidence || a.contract_id.localeCompare(b.contract_id),
+ ),
+ [links],
+ );
-export function ContractLinksTable({ links }: ContractLinksTableProps) {
if (links.length === 0) {
return (
<EmptyState
@@ -25,88 +116,17 @@ export function ContractLinksTable({ links }: ContractLinksTableProps) {
);
}
- const header = (
- <tr className="bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] text-xs uppercase tracking-wider">
- <th className="px-3 py-2 text-left font-medium">Contract</th>
- <th className={`px-3 py-2 text-left font-medium ${HIDE_BELOW_MD}`}>Type</th>
- <th className="px-3 py-2 text-left font-medium">Provider</th>
- <th className={`px-3 py-2 text-left font-medium ${HIDE_BELOW_MD}`}>Consumer</th>
- <th className={`px-3 py-2 text-left font-medium w-20 ${HIDE_BELOW_LG}`}>Confidence</th>
- </tr>
- );
-
- const renderRow = (link: WorkspaceContractLinkEntry) => (
- <tr className="border-t border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)]">
- <td className="px-3 py-2 text-left min-w-[140px] max-w-[280px]">
- <span
- className="text-xs font-mono text-[var(--color-text-secondary)] [overflow-wrap:anywhere]"
- title={link.contract_id}
- >
- {link.contract_id}
- </span>
- </td>
- <td className={`px-3 py-2 text-left ${HIDE_BELOW_MD}`}>
- <ContractTypeBadge type={link.contract_type} />
- </td>
- <td className="px-3 py-2 text-left">
- <div className="flex flex-col gap-0.5">
- <span className="text-xs font-medium text-[var(--color-text-primary)]">
- {link.provider_repo}
- </span>
- {/* No truncation: a path is exactly the string somebody is
- scanning for, and an ellipsis reports a layout decision as
- missing content. Wraps instead, as the contracts table does. */}
- <span className="text-xs font-mono text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
- {link.provider_file}
- </span>
- </div>
- </td>
- <td className={`px-3 py-2 text-left ${HIDE_BELOW_MD}`}>
- <div className="flex flex-col gap-0.5">
- <span className="text-xs font-medium text-[var(--color-text-primary)]">
- {link.consumer_repo}
- </span>
- {/* No truncation: a path is exactly the string somebody is
- scanning for, and an ellipsis reports a layout decision as
- missing content. Wraps instead, as the contracts table does. */}
- <span className="text-xs font-mono text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
- {link.consumer_file}
- </span>
- </div>
- </td>
- <td className={`px-3 py-2 text-left w-20 ${HIDE_BELOW_LG}`}>
- <div className="flex items-center gap-1.5">
- <div className="h-1.5 w-12 rounded-full bg-[var(--color-bg-inset)] overflow-hidden">
- <div
- className="h-full rounded-full transition-all"
- style={{
- width: `${Math.round(link.confidence * 100)}%`,
- backgroundColor:
- link.confidence >= 0.8
- ? "var(--color-confidence-fresh)"
- : link.confidence >= 0.6
- ? "var(--color-confidence-stale)"
- : "var(--color-confidence-outdated)",
- }}
- />
- </div>
- <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums">
- {Math.round(link.confidence * 100)}%
- </span>
- </div>
- </td>
- </tr>
- );
-
return (
- <VirtualizedTable<WorkspaceContractLinkEntry>
- rows={links}
- rowKey={(link) =>
- `${link.contract_id}|${link.consumer_contract_id ?? ""}|${link.provider_repo}|${link.provider_file}|${link.consumer_repo}|${link.consumer_file}`
- }
- header={header}
- renderRow={renderRow}
- aria-label="Cross-repo contract links"
+
+ <ResponsiveTable<WorkspaceContractLinkEntry>
+ columns={COLUMNS}
+ rows={sorted}
+ rowKey={linkKey}
+ onRowClick={onSelect}
+ virtualize={{ estimateRowHeight: 56, estimateCardHeight: 120, maxHeight: 560 }}
+ caption="Cross-repo contract links"
+ stacked="md"
+ bare
/>
);
-}
+});
diff --git a/packages/ui/src/workspace/contract-prompt-button.tsx b/packages/ui/src/workspace/contract-prompt-button.tsx
new file mode 100644
index 000000000..023fa4450
--- /dev/null
+++ b/packages/ui/src/workspace/contract-prompt-button.tsx
@@ -0,0 +1,35 @@
+"use client";
+
+import { useState } from "react";
+import { AiPromptButton } from "../health/ai-prompt-button";
+import { AiPromptModal } from "../health/ai-prompt-modal";
+import { buildContractAiPrompt, type BuildContractPromptOptions } from "./contract-ai-prompt";
+
+/**
+ * The AI prompt for one contract: the button and the dialog it opens. Used by
+ * the contract drawer and the contract detail page, so both hand an agent the
+ * same prompt.
+ */
+export function ContractPromptButton({
+ contract,
+ links,
+ unmatchedReason = null,
+ breakingChanges = [],
+}: Omit<BuildContractPromptOptions, "flavor">) {
+ const [open, setOpen] = useState(false);
+ return (
+ <>
+ <AiPromptButton onClick={() => setOpen(true)} label="AI prompt" />
+ <AiPromptModal
+ open={open}
+ onOpenChange={setOpen}
+ filePath={`${contract.repo}/${contract.file_path}`}
+ title="AI prompt for this contract"
+ description="The contract, where it lives, how it was found and what sits on the other side, written up so an agent can verify it and act."
+ getPrompt={(flavor) =>
+ buildContractAiPrompt({ contract, links, unmatchedReason, breakingChanges, flavor })
+ }
+ />
+ </>
+ );
+}
diff --git a/packages/ui/src/workspace/contract-tests-section.tsx b/packages/ui/src/workspace/contract-tests-section.tsx
index dd2479cb5..bb7a460f4 100644
--- a/packages/ui/src/workspace/contract-tests-section.tsx
+++ b/packages/ui/src/workspace/contract-tests-section.tsx
@@ -29,6 +29,8 @@ export interface ContractTestsSectionProps {
contractId: string;
/** A failed lookup, worded by the host. */
error?: string | null;
+ /** Panel scale for the contract drawer: a micro-label heading, 12px prose. */
+ compact?: boolean;
}
const VIA_WORDS: Record<string, string> = {
@@ -64,17 +66,34 @@ const SUMMARY_REASON_WORDS: Record<string, string> = {
const NONE_WORDS =
"The consumer repositories were analyzed and nothing reaches the call sites for this contract. That is an answer, not a failure: no test in another repository guards it.";
-export function ContractTestsSection({ result, contractId, error }: ContractTestsSectionProps) {
+export function ContractTestsSection({
+ result,
+ contractId,
+ error,
+ compact = false,
+}: ContractTestsSectionProps) {
// Null is "the host did not ask", which is a different fact from "the answer
// was empty" and gets no section at all.
if (!result && !error) return null;
return (
- <section className="mt-10 flex flex-col gap-3 border-t border-[var(--color-border-default)] pt-6 sm:mt-12 sm:pt-8">
- <h2 className="text-xl font-semibold tracking-tight text-[var(--color-text-primary)]">
- Tests to run
- </h2>
- <Body result={result} contractId={contractId} error={error ?? null} />
+ <section
+ className={
+ compact
+ ? "flex flex-col gap-2"
+ : "mt-10 flex flex-col gap-3 border-t border-[var(--color-border-default)] pt-6 sm:mt-12 sm:pt-8"
+ }
+ >
+ {compact ? (
+ <h4 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Tests to run
+ </h4>
+ ) : (
+ <h2 className="text-xl font-semibold tracking-tight text-[var(--color-text-primary)]">
+ Tests to run
+ </h2>
+ )}
+ <Body result={result} contractId={contractId} error={error ?? null} compact={compact} />
</section>
);
}
@@ -83,12 +102,14 @@ function Body({
result,
contractId,
error,
+ compact,
}: {
result: WorkspaceTestImpactResponse | null;
contractId: string;
error: string | null;
+ compact: boolean;
}) {
- if (error) return <Prose>{error}</Prose>;
+ if (error) return <Prose compact={compact}>{error}</Prose>;
if (!result) return null;
const rows = result.recommendations.filter((r) => r.contract_ids.includes(contractId));
@@ -100,21 +121,20 @@ function Body({
// lookup fall through to the analyzed-and-found-nothing wording.
const words = SUMMARY_REASON_WORDS[reason ?? ""] ?? NONE_WORDS;
const detail = reason === "lookup_failed" ? summaryDetail(result) : null;
- return <Prose>{detail ? `${words} (${detail})` : words}</Prose>;
+ return <Prose compact={compact}>{detail ? `${words} (${detail})` : words}</Prose>;
}
+ const RepoHeading = compact ? "h5" : "h3";
return (
<>
- <Prose>
+ <Prose compact={compact}>
Tests in the repositories that call this contract, found by walking each consumer&apos;s
own index from the call site. A measured row is a coverage map recording that the test ran
the code; an inferred row is a graph reaching it.
</Prose>
{groupByRepo(rows).map(([repo, repoRows]) => (
<div key={repo} className="flex flex-col gap-2">
- <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- {repo}
- </h3>
+ <RepoHeading className={MICRO_LABEL}>{repo}</RepoHeading>
<ul className="m-0 flex list-none flex-col gap-2 p-0">
{repoRows.map((row) => (
// One test id can appear once per provider repo it guards, so
@@ -140,18 +160,23 @@ function Body({
</ul>
</div>
))}
- {unresolved.length > 0 && <UnresolvedList rows={unresolved} />}
+ {unresolved.length > 0 && <UnresolvedList rows={unresolved} compact={compact} />}
</>
);
}
-function UnresolvedList({ rows }: { rows: WorkspaceUnresolvedLink[] }) {
+function UnresolvedList({ rows, compact }: { rows: WorkspaceUnresolvedLink[]; compact: boolean }) {
+ // In the drawer the section heading is an h4 micro-label, so this sits one
+ // level below it at the same scale.
+ const Heading = compact ? "h5" : "h3";
return (
<div className="flex flex-col gap-2">
- <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">
+ <Heading
+ className={compact ? MICRO_LABEL : "text-sm font-semibold text-[var(--color-text-primary)]"}
+ >
Could not determine
- </h3>
- <Prose>
+ </Heading>
+ <Prose compact={compact}>
These call sites were not answered either way, so treat them as unknown and not as
untested.
</Prose>
@@ -175,9 +200,16 @@ function UnresolvedList({ rows }: { rows: WorkspaceUnresolvedLink[] }) {
);
}
-function Prose({ children }: { children: ReactNode }) {
+const MICRO_LABEL =
+ "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
+
+function Prose({ children, compact }: { children: ReactNode; compact: boolean }) {
return (
- <p className="max-w-[68ch] text-base leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ <p
+ className={`max-w-[68ch] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty] ${
+ compact ? "text-xs" : "text-base"
+ }`}
+ >
{children}
</p>
);
diff --git a/packages/ui/src/workspace/contract-type-badge.tsx b/packages/ui/src/workspace/contract-type-badge.tsx
index 033ab76cc..87a40dbba 100644
--- a/packages/ui/src/workspace/contract-type-badge.tsx
+++ b/packages/ui/src/workspace/contract-type-badge.tsx
@@ -14,7 +14,7 @@ export { contractTypeLabel };
* token that repeats once per row tile into stripes down a table and outweigh
* the contract ids they label. Adding a sixth ground for the largest type
* would have made the loudest column the one carrying the least, and following
- * the colour goes nowhere — the type is what the filter already selects on. A
+ * the colour goes nowhere: the type is what the filter already selects on. A
* quiet word says the same thing, and a new type costs nothing.
*/
export function ContractTypeBadge({ type }: { type: string }) {
@@ -29,7 +29,7 @@ export function ContractTypeBadge({ type }: { type: string }) {
* Green for provider against amber for consumer broke two rules at once. Those
* hues are reserved for readouts that carry a health band, and neither role is
* one. And providers outnumber consumers by better than two to one, so the
- * green was the default state wearing the colour of a verdict — a mark every
+ * green was the default state wearing the colour of a verdict, and a mark every
* row carries says nothing.
*/
export function RoleBadge({ role }: { role: string }) {
diff --git a/packages/ui/src/workspace/index.ts b/packages/ui/src/workspace/index.ts
index d4992b291..a543cec9f 100644
--- a/packages/ui/src/workspace/index.ts
+++ b/packages/ui/src/workspace/index.ts
@@ -1,9 +1,13 @@
export * from "./breaking-change-row";
export * from "./breaking-changes-view";
export * from "./co-change-table";
+export * from "./contract-ai-prompt";
+export * from "./contract-attention";
export * from "./contract-drawer";
export * from "./contract-facts";
+export * from "./contract-identity";
export * from "./contract-links-table";
+export * from "./contract-prompt-button";
export * from "./contract-tests-section";
export * from "./contract-type-badge";
export * from "./cross-repo-summary";
diff --git a/packages/web/src/app/workspace/contracts/breaking-changes-section.tsx b/packages/web/src/app/workspace/contracts/breaking-changes-section.tsx
index 3cc7bd374..16f6f6280 100644
--- a/packages/web/src/app/workspace/contracts/breaking-changes-section.tsx
+++ b/packages/web/src/app/workspace/contracts/breaking-changes-section.tsx
@@ -1,30 +1,29 @@
"use client";
-import { useRouter } from "next/navigation";
import { BreakingChangesView } from "@repowise-dev/ui/workspace/breaking-changes-view";
+import { OverviewSection } from "@repowise-dev/ui/overview/section";
import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";
import { useWorkspaceBreakingChanges } from "@/lib/hooks/use-workspace";
-import { contractDetailHref } from "./contract-href";
+import { useOpenContract } from "./contract-drawer-host";
/**
* The breaking-change report on the contracts page.
*
* A client boundary because the report is fetched per view rather than at build
* time: it is written by the most recent workspace update, and a page cached for
- * 30 seconds would report a stale all-clear.
- *
- * The alias-to-repo-id map comes from the page, which already loads the
- * workspace. A change names a repo by its workspace alias; the per-repo routes
- * are keyed on the indexed repo id, and a repo that was never indexed has none,
- * so those references stay plain text instead of linking into a missing page.
+ * 30 seconds would report a stale all-clear. It owns its section heading so the
+ * explanation of what the list holds appears only when there is a list; with no
+ * findings the section is its heading and one sentence.
*/
export function BreakingChangesSection({
repoIds,
}: {
+ /** Repo alias to indexed repo id; a never-indexed repo's references stay text. */
repoIds: Record<string, string>;
}) {
- const router = useRouter();
+ const open = useOpenContract();
const { data, isLoading } = useWorkspaceBreakingChanges();
+ const hasFindings = (data?.changes.length ?? 0) > 0;
const prefixFor = (repo: string): string | null => {
const id = repoIds[repo];
@@ -32,28 +31,36 @@ export function BreakingChangesSection({
};
return (
- <BreakingChangesView
- report={data}
- loading={isLoading}
- links={{
- symbolHref: (repo, symbolId) => {
- const prefix = prefixFor(repo);
- return prefix ? symbolEntityPath(prefix, symbolId) : null;
- },
- fileHref: (repo, file) => {
- const prefix = prefixFor(repo);
- return prefix ? fileEntityPath(prefix, file) : null;
- },
- }}
- onSelectContract={(_contractId, change) =>
- router.push(
- contractDetailHref({
+ <OverviewSection
+ title="Breaking changes"
+ {...(hasFindings
+ ? {
+ description:
+ "Provider contracts that changed in the most recent workspace update, and the consumers linked to them. Breaking first, then warnings.",
+ }
+ : {})}
+ >
+ <BreakingChangesView
+ report={data}
+ loading={isLoading}
+ links={{
+ symbolHref: (repo, symbolId) => {
+ const prefix = prefixFor(repo);
+ return prefix ? symbolEntityPath(prefix, symbolId) : null;
+ },
+ fileHref: (repo, file) => {
+ const prefix = prefixFor(repo);
+ return prefix ? fileEntityPath(prefix, file) : null;
+ },
+ }}
+ onSelectContract={(_contractId, change) =>
+ open({
repo: change.provider_repo,
file_path: change.provider_file,
contract_id: change.contract_id,
- }),
- )
- }
- />
+ })
+ }
+ />
+ </OverviewSection>
);
}
diff --git a/packages/web/src/app/workspace/contracts/contract-drawer-host.tsx b/packages/web/src/app/workspace/contracts/contract-drawer-host.tsx
new file mode 100644
index 000000000..f4173162a
--- /dev/null
+++ b/packages/web/src/app/workspace/contracts/contract-drawer-host.tsx
@@ -0,0 +1,158 @@
+"use client";
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import useSWR from "swr";
+import { ContractDrawer, type ContractRef } from "@repowise-dev/ui/workspace/contract-drawer";
+import { asContractSchema, type ContractEntry } from "@repowise-dev/ui/workspace/contract-facts";
+import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";
+import { getWorkspaceContractDetail, getWorkspaceTestImpact } from "@/lib/api/workspace";
+import { useWorkspaceBreakingChanges } from "@/lib/hooks/use-workspace";
+import { contractDetailHref } from "./contract-href";
+
+/** Open the contract drawer. A row can pass itself so the panel paints before the fetch. */
+type OpenContract = (ref: ContractRef, row?: ContractEntry) => void;
+
+const OpenContext = createContext<OpenContract>(() => {});
+
+export function useOpenContract(): OpenContract {
+ return useContext(OpenContext);
+}
+
+/** The deep-link params the drawer owns; stripped from the URL when it closes. */
+const DEEP_LINK_PARAMS = ["contract", "repo", "file"] as const;
+
+/**
+ * The one contract drawer on the page, and the context every table uses to
+ * open it.
+ *
+ * A provider around server-rendered sections rather than a client page: the
+ * headings, prose and figures stay on the server, and only the rows that open
+ * the drawer are client leaves. The detail and the test impact are fetched
+ * when the drawer opens, one request each, keyed so reopening a contract costs
+ * nothing.
+ */
+export function ContractDrawerProvider({
+ children,
+ repoIds,
+ initial,
+}: {
+ children: ReactNode;
+ /** Repo alias to indexed repo id. A never-indexed repo has no entry. */
+ repoIds: Record<string, string>;
+ /** `?contract=&repo=&file=` on load. */
+ initial: ContractRef | null;
+}) {
+ const [selected, setSelected] = useState<{ ref: ContractRef; row?: ContractEntry } | null>(
+ initial ? { ref: initial } : null,
+ );
+ const ref = selected?.ref ?? null;
+
+ const detail = useSWR(
+ ref ? ["workspace:contract", ref.repo, ref.file_path, ref.contract_id] : null,
+ () =>
+ getWorkspaceContractDetail({
+ repo: ref!.repo,
+ file: ref!.file_path,
+ id: ref!.contract_id,
+ }),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
+ const contract = detail.data?.contract ?? selected?.row ?? null;
+ const isProvider = contract?.role === "provider";
+
+ // Only a provider has consumers whose tests guard it, and the lookup opens
+ // the consumer indexes, so a consumer never pays for it.
+ const tests = useSWR(
+ ref && isProvider ? ["workspace:test-impact", ref.repo, ref.file_path] : null,
+ () => getWorkspaceTestImpact(ref!.repo, [ref!.file_path]),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
+ // Same key as the section above, so this costs no second request.
+ const { data: breaking } = useWorkspaceBreakingChanges();
+
+ const open = useCallback<OpenContract>((next, row) => {
+ setSelected(row ? { ref: next, row } : { ref: next });
+ }, []);
+
+ // True until the drawer a deep link opened is closed. Only then are its
+ // params stripped: `contract` + `repo` without `file` is a list filter, and
+ // must survive closing a drawer opened from a row.
+ const deepLinkOpen = useRef(initial !== null);
+
+ const close = useCallback(() => {
+ setSelected(null);
+ if (!deepLinkOpen.current) return;
+ deepLinkOpen.current = false;
+ // So a reload does not reopen the drawer the reader just closed.
+ const url = new URL(window.location.href);
+ for (const p of DEEP_LINK_PARAMS) url.searchParams.delete(p);
+ window.history.replaceState(null, "", `${url.pathname}${url.search}${url.hash}`);
+ }, []);
+
+ const codeLinks = useMemo(
+ () => ({
+ symbolHref: (repo: string, symbolId: string) => {
+ const id = repoIds[repo];
+ return id ? symbolEntityPath(`/repos/${id}`, symbolId) : null;
+ },
+ fileHref: (repo: string, file: string) => {
+ const id = repoIds[repo];
+ return id ? fileEntityPath(`/repos/${id}`, file) : null;
+ },
+ }),
+ [repoIds],
+ );
+
+ const notFound =
+ detail.error && (detail.error as { status?: number }).status === 404
+ ? "This contract is not in the workspace any more. It may have been renamed or removed since the link was made."
+ : detail.error
+ ? "The contract could not be read. Try again, or open the full page."
+ : null;
+
+ return (
+ <OpenContext.Provider value={open}>
+ {children}
+ <ContractDrawer
+ open={ref !== null}
+ onOpenChange={(next) => {
+ if (!next) close();
+ }}
+ contract={contract}
+ pendingId={ref?.contract_id}
+ loading={detail.isLoading}
+ error={notFound}
+ links={detail.data?.links ?? []}
+ unmatchedReason={detail.data?.unmatched_reason ?? null}
+ schema={asContractSchema(detail.data?.contract_schema ?? null)}
+ breakingChanges={
+ ref
+ ? (breaking?.changes ?? []).filter(
+ (c) =>
+ c.contract_id === ref.contract_id &&
+ (!isProvider || (c.provider_repo === ref.repo && c.provider_file === ref.file_path)),
+ )
+ : []
+ }
+ testImpact={isProvider ? (tests.data ?? null) : null}
+ testImpactLoading={isProvider && tests.isLoading}
+ testImpactError={
+ tests.error
+ ? "Test impact could not be read. It is answered from the consumer repositories' own indexes, and that lookup failed."
+ : null
+ }
+ codeLinks={codeLinks}
+ fullPageHref={ref ? contractDetailHref(ref) : undefined}
+ onSelectContract={(next) => open(next)}
+ />
+ </OpenContext.Provider>
+ );
+}
diff --git a/packages/web/src/app/workspace/contracts/contract-filters.tsx b/packages/web/src/app/workspace/contracts/contract-filters.tsx
index 2f2a18da8..238cd3062 100644
--- a/packages/web/src/app/workspace/contracts/contract-filters.tsx
+++ b/packages/web/src/app/workspace/contracts/contract-filters.tsx
@@ -1,161 +1,205 @@
"use client";
-import { useRouter, useSearchParams } from "next/navigation";
-import { useCallback, useTransition } from "react";
-import { Filter } from "lucide-react";
+import { useRouter } from "next/navigation";
+import { useEffect, useRef, useState, useTransition } from "react";
+import { Search } from "lucide-react";
+import { PaginationControls } from "@repowise-dev/ui/shared/pagination-controls";
+import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";
import { contractTypeLabel } from "@repowise-dev/ui/workspace/contract-type-badge";
import { formatNumber } from "@repowise-dev/ui/lib/format";
+import { contractsListHref, type ContractListFilters } from "./contract-href";
-/**
- * Every type the extractors can emit, in the order the select lists them.
- * Which of them a workspace actually holds is a separate question — see
- * `typeOptions`.
- */
+/** Every type the extractors can emit, in tab order. */
const ALL_TYPES = ["http", "grpc", "socket", "topic", "data", "code"];
+/** Keystrokes settle for this long before the list is re-fetched. */
+const SEARCH_DEBOUNCE_MS = 300;
+
/**
- * The type options this workspace can act on.
- *
- * A control that cannot act must look like it, and three of the five options
- * this select used to offer could not return a row on any workspace here:
- * `grpc`, `socket` and `topic` are all zero, while `code` — the single largest
- * type — had no option at all. The distribution is already on the workspace
- * payload, so the control is built from it rather than from the vocabulary,
- * and the count goes on the label so a reader knows what a filter is worth
- * before spending a click on it.
- *
- * `byType` must be the workspace-wide breakdown, not the one on the contracts
- * response: that one is computed after the filters are applied, so selecting a
- * type would delete every other option and strand the reader inside it.
- *
- * With no breakdown available the full vocabulary comes back rather than an
- * empty select — an unfiltered list is a worse failure than an option that
- * returns nothing.
+ * The type tabs, from the workspace-wide distribution rather than the
+ * vocabulary: a tab that can never return a row is a control that cannot act.
+ * `byType` must be the unfiltered breakdown, or picking a type would delete
+ * every other tab. A type someone linked to stays, so the URL never selects a
+ * tab that is not drawn.
*/
-function typeOptions(byType: Record<string, number> | null | undefined, selected: string) {
- const present = byType
- ? ALL_TYPES.filter((t) => (byType[t] ?? 0) > 0)
- : ALL_TYPES;
- // A type the vocabulary does not name still gets an option when the
- // workspace holds one, so a new extractor is filterable before this list is.
+function typeTabs(byType: Record<string, number> | null, selected: string) {
+ const known = byType ? ALL_TYPES.filter((t) => (byType[t] ?? 0) > 0) : ALL_TYPES;
const extra = byType
? Object.keys(byType).filter((t) => !ALL_TYPES.includes(t) && byType[t]! > 0)
: [];
- const values = [...present, ...extra];
- // A type someone linked to directly stays selectable even when the workspace
- // holds none of it, or the select would render blank against its own URL.
+ const values = [...known, ...extra];
if (selected && !values.includes(selected)) values.push(selected);
+ const total = byType ? Object.values(byType).reduce((a, b) => a + b, 0) : null;
return [
- { value: "", label: "All types" },
- ...values.map((value) => ({
- value,
- label: byType?.[value]
- ? `${contractTypeLabel(value)} ${formatNumber(byType[value]!)}`
- : contractTypeLabel(value),
+ { id: "", label: "All", ...(total != null ? { badge: formatNumber(total) } : {}) },
+ ...values.map((t) => ({
+ id: t,
+ label: contractTypeLabel(t),
+ ...(byType?.[t] ? { badge: formatNumber(byType[t]!) } : {}),
})),
];
}
-const ROLE_OPTIONS = [
- { value: "", label: "All roles" },
- { value: "provider", label: "Providers" },
- { value: "consumer", label: "Consumers" },
-];
-
const SELECT_CLASS =
- "rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-sm text-[var(--color-text-primary)] outline-none focus:border-[var(--color-border-active)] disabled:opacity-60";
+ "rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2.5 py-1.5 text-xs text-[var(--color-text-primary)] outline-none focus-visible:border-[var(--color-border-active)] focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] disabled:opacity-60";
/**
- * The contracts table's filters.
- *
- * The only stateful thing on an otherwise server-rendered page, and it keeps
- * its state in the URL rather than in React: the page re-renders on the server
- * with the new filter, so a filtered view is linkable and the table's counts
- * come from the same request that drew the rows.
+ * The list's controls. State lives in the URL, so a filtered view is linkable
+ * and the server renders the rows and their count from the same request. Each
+ * axis has one control: type is the tab row, the rest narrow within it.
*/
-export function ContractFilters({
+export function ContractListControls({
+ filters,
repos,
byType,
}: {
+ filters: ContractListFilters;
repos: string[];
/** Workspace-wide contracts per type, from `contract_summary`. */
- byType?: Record<string, number> | null;
+ byType: Record<string, number> | null;
}) {
const router = useRouter();
- const params = useSearchParams();
const [pending, startTransition] = useTransition();
- const types = typeOptions(byType, params.get("type") ?? "");
+ const [text, setText] = useState(filters.q ?? "");
+ const current = useRef(filters);
+ current.current = filters;
- const set = useCallback(
- (key: string, value: string) => {
- const next = new URLSearchParams(params.toString());
- if (value) next.set(key, value);
- else next.delete(key);
- startTransition(() => {
- router.push(next.size > 0 ? `?${next.toString()}` : "/workspace/contracts");
- });
- },
- [params, router],
- );
+ // Follow the URL when something else changes it (Back, a Browse link). The
+ // box's own debounced write is recognised and skipped, so text typed while
+ // that write was in flight is never overwritten.
+ const urlQ = filters.q ?? "";
+ const ownWrite = useRef<string | null>(null);
+ useEffect(() => {
+ if (ownWrite.current === urlQ) {
+ ownWrite.current = null;
+ return;
+ }
+ setText(urlQ);
+ }, [urlQ]);
+
+ const go = (next: ContractListFilters) => {
+ // Any change of filter starts the list from its first page.
+ const href = contractsListHref({ ...next, page: undefined }).split("#")[0]!;
+ startTransition(() => router.replace(href, { scroll: false }));
+ };
+
+ useEffect(() => {
+ const q = text.trim();
+ if (q === (current.current.q ?? "")) return;
+ const id = window.setTimeout(() => {
+ ownWrite.current = q;
+ go({ ...current.current, q });
+ }, SEARCH_DEBOUNCE_MS);
+ return () => window.clearTimeout(id);
+ // `go` reads the latest filters through the ref; only the text schedules.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [text]);
return (
- <div className="flex flex-wrap items-center gap-3">
- <span className="flex items-center gap-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- <Filter className="h-3.5 w-3.5" aria-hidden />
- Filter
- </span>
+ <div className="flex flex-col gap-3">
+ <ViewTabs
+ aria-label="Contract type"
+ tabs={typeTabs(byType, filters.type ?? "")}
+ value={filters.type ?? ""}
+ onValueChange={(type) => go({ ...filters, type })}
+ />
+ <div className="flex flex-wrap items-center gap-2" aria-busy={pending}>
+ <label className="relative min-w-[220px] flex-1">
+ <span className="sr-only">Search contracts</span>
+ <Search
+ className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]"
+ aria-hidden
+ />
+ <input
+ type="search"
+ value={text}
+ onChange={(e) => setText(e.target.value)}
+ placeholder="Search path, table, file, symbol or service"
+ className={`${SELECT_CLASS} w-full pl-8`}
+ />
+ </label>
+
+ <label className="sr-only" htmlFor="contract-repo">
+ Repository
+ </label>
+ <select
+ id="contract-repo"
+ className={SELECT_CLASS}
+ value={filters.repo ?? ""}
+ onChange={(e) => go({ ...filters, repo: e.target.value })}
+ >
+ <option value="">All repositories</option>
+ {repos.map((r) => (
+ <option key={r} value={r}>
+ {r}
+ </option>
+ ))}
+ </select>
- <label className="sr-only" htmlFor="contract-type">
- Contract type
- </label>
- <select
- id="contract-type"
- className={SELECT_CLASS}
- disabled={pending}
- value={params.get("type") ?? ""}
- onChange={(e) => set("type", e.target.value)}
- >
- {types.map((o) => (
- <option key={o.value} value={o.value}>
- {o.label}
- </option>
- ))}
- </select>
+ <label className="sr-only" htmlFor="contract-role">
+ Role
+ </label>
+ <select
+ id="contract-role"
+ className={SELECT_CLASS}
+ value={filters.role ?? ""}
+ onChange={(e) => go({ ...filters, role: e.target.value })}
+ >
+ <option value="">Providers and consumers</option>
+ <option value="provider">Providers</option>
+ <option value="consumer">Consumers</option>
+ </select>
- <label className="sr-only" htmlFor="contract-repo">
- Repository
- </label>
- <select
- id="contract-repo"
- className={SELECT_CLASS}
- disabled={pending}
- value={params.get("repo") ?? ""}
- onChange={(e) => set("repo", e.target.value)}
- >
- <option value="">All repositories</option>
- {repos.map((r) => (
- <option key={r} value={r}>
- {r}
- </option>
- ))}
- </select>
+ <label className="sr-only" htmlFor="contract-linked">
+ Link
+ </label>
+ <select
+ id="contract-linked"
+ className={SELECT_CLASS}
+ value={filters.linked ?? ""}
+ onChange={(e) => go({ ...filters, linked: e.target.value })}
+ >
+ <option value="">Linked or not</option>
+ <option value="yes">On a matched link</option>
+ <option value="no">On no link</option>
+ </select>
- <label className="sr-only" htmlFor="contract-role">
- Role
- </label>
- <select
- id="contract-role"
- className={SELECT_CLASS}
- disabled={pending}
- value={params.get("role") ?? ""}
- onChange={(e) => set("role", e.target.value)}
- >
- {ROLE_OPTIONS.map((o) => (
- <option key={o.value} value={o.value}>
- {o.label}
- </option>
- ))}
- </select>
+ {pending ? (
+ <span className="text-[10px] text-[var(--color-text-tertiary)]" role="status">
+ Updating...
+ </span>
+ ) : null}
+ </div>
</div>
);
}
+
+/** Previous and next page of the list, keeping every filter. */
+export function ContractListPager({
+ filters,
+ page,
+ pageSize,
+ shown,
+ total,
+}: {
+ filters: ContractListFilters;
+ page: number;
+ pageSize: number;
+ shown: number;
+ total: number;
+}) {
+ const router = useRouter();
+ const to = (p: number) =>
+ router.push(contractsListHref({ ...filters, page: p }), { scroll: false });
+ const offset = (page - 1) * pageSize;
+ return (
+ <PaginationControls
+ offset={offset}
+ shown={shown}
+ total={total}
+ label="contracts"
+ onPrevious={page > 1 ? () => to(page - 1) : undefined}
+ onNext={offset + shown < total ? () => to(page + 1) : undefined}
+ />
+ );
+}
diff --git a/packages/web/src/app/workspace/contracts/contract-href.test.ts b/packages/web/src/app/workspace/contracts/contract-href.test.ts
index 1db715b22..0a7151bdb 100644
--- a/packages/web/src/app/workspace/contracts/contract-href.test.ts
+++ b/packages/web/src/app/workspace/contracts/contract-href.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { contractDetailHref } from "./contract-href";
+import { contractDetailHref, contractsListHref } from "./contract-href";
describe("contractDetailHref", () => {
it("carries all three parts of the identity", () => {
@@ -36,3 +36,18 @@ describe("contractDetailHref", () => {
expect(a).not.toBe(b);
});
});
+
+describe("contractsListHref", () => {
+ it("keeps only the filters that are set and lands on the list", () => {
+ expect(contractsListHref({ repo: "backend", type: "http", role: "provider", linked: "no" })).toBe(
+ "/workspace/contracts?type=http&repo=backend&role=provider&linked=no#all-contracts",
+ );
+ });
+
+ it("drops the first page and an empty search", () => {
+ expect(contractsListHref({ q: "", page: 1 })).toBe("/workspace/contracts#all-contracts");
+ expect(contractsListHref({ q: "chat", page: 3 })).toBe(
+ "/workspace/contracts?q=chat&page=3#all-contracts",
+ );
+ });
+});
diff --git a/packages/web/src/app/workspace/contracts/contract-href.ts b/packages/web/src/app/workspace/contracts/contract-href.ts
index fa00a80db..847d9bd93 100644
--- a/packages/web/src/app/workspace/contracts/contract-href.ts
+++ b/packages/web/src/app/workspace/contracts/contract-href.ts
@@ -22,3 +22,26 @@ export function contractDetailHref(contract: {
});
return `/workspace/contracts/detail?${params.toString()}`;
}
+
+/** The full list's filters, as the page reads them from the URL. */
+export interface ContractListFilters {
+ type?: string | undefined;
+ repo?: string | undefined;
+ role?: string | undefined;
+ /** `yes`: on a matched link. `no`: on none. */
+ linked?: string | undefined;
+ q?: string | undefined;
+ page?: number | undefined;
+}
+
+/** The list filtered, scrolled to the list. Empty values are left out. */
+export function contractsListHref(filters: ContractListFilters): string {
+ const params = new URLSearchParams();
+ for (const key of ["type", "repo", "role", "linked", "q"] as const) {
+ const value = filters[key];
+ if (value) params.set(key, value);
+ }
+ if (filters.page && filters.page > 1) params.set("page", String(filters.page));
+ const query = params.toString();
+ return `/workspace/contracts${query ? `?${query}` : ""}#all-contracts`;
+}
diff --git a/packages/web/src/app/workspace/contracts/contracts-table.tsx b/packages/web/src/app/workspace/contracts/contracts-table.tsx
index f16c0ebbb..071c4ae8a 100644
--- a/packages/web/src/app/workspace/contracts/contracts-table.tsx
+++ b/packages/web/src/app/workspace/contracts/contracts-table.tsx
@@ -1,158 +1,137 @@
"use client";
-import { useState, type MouseEvent } from "react";
+import { memo, useMemo, type MouseEvent } from "react";
+import { ResponsiveTable, type ResponsiveColumn } from "@repowise-dev/ui/shared/responsive-table";
+import { ContractTypeBadge, RoleBadge } from "@repowise-dev/ui/workspace/contract-type-badge";
import {
- ResponsiveTable,
- type ResponsiveColumn,
-} from "@repowise-dev/ui/shared";
-import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";
-import {
- ContractTypeBadge,
- RoleBadge,
-} from "@repowise-dev/ui/workspace/contract-type-badge";
-import { ContractDrawer } from "@repowise-dev/ui/workspace/contract-drawer";
-import { linksForContract } from "@repowise-dev/ui/workspace/contract-facts";
-import type { WorkspaceContractEntry, WorkspaceContractLinkEntry } from "@/lib/api/types";
-import { useWorkspaceBreakingChanges } from "@/lib/hooks/use-workspace";
+ ContractIdentity,
+ FilePathText,
+ distinctService,
+} from "@repowise-dev/ui/workspace/contract-identity";
+import { contractMetaString } from "@repowise-dev/ui/workspace/contract-facts";
+import type { WorkspaceContractEntry } from "@/lib/api/types";
+import { useOpenContract } from "./contract-drawer-host";
import { contractDetailHref } from "./contract-href";
type ContractRow = WorkspaceContractEntry & { _key: string };
-/**
- * The contracts table.
- *
- * This is a client boundary for a mechanical reason rather than a stateful
- * one: `ResponsiveTable` takes its columns as `render` functions, and a
- * function cannot cross the server-to-client boundary. Keeping the column
- * definitions on this side lets the page itself stay a server component that
- * passes nothing but rows.
- */
-const CONTRACT_COLUMNS: ResponsiveColumn<ContractRow>[] = [
+/** How extraction found the contract, as the word a developer would recognise. */
+function foundBy(c: WorkspaceContractEntry): string | null {
+ return contractMetaString(c.meta, "framework") ?? contractMetaString(c.meta, "client");
+}
+
+const TYPE_COLUMN: ResponsiveColumn<ContractRow> = {
+ key: "contract_type",
+ header: "Type",
+ priority: 3,
+ render: (c) => <ContractTypeBadge type={c.contract_type} />,
+};
+
+const COLUMNS: ResponsiveColumn<ContractRow>[] = [
{
key: "contract_id",
header: "Contract",
- // An anchor, so the detail route keeps its middle-click and its
- // open-in-new-tab. An unmodified click is cancelled and left to bubble to
- // the row, which opens the drawer instead of leaving the page.
+ cellClassName: "min-w-[180px] max-w-[340px]",
+ // An anchor to the detail route, so middle-click and open-in-new-tab work.
+ // An unmodified click is cancelled and bubbles to the row, which opens the
+ // drawer instead of leaving the page.
render: (c) => (
<a
href={contractDetailHref(c)}
onClick={(e: MouseEvent<HTMLAnchorElement>) => {
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) {
e.stopPropagation();
return;
}
e.preventDefault();
}}
- className="font-mono text-xs text-[var(--color-text-secondary)] [overflow-wrap:anywhere] hover:underline"
+ className="rounded-sm hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
>
- {c.contract_id}
+ <ContractIdentity contractId={c.contract_id} />
</a>
),
},
- {
- key: "contract_type",
- header: "Type",
- render: (c) => <ContractTypeBadge type={c.contract_type} />,
- },
{ key: "role", header: "Role", render: (c) => <RoleBadge role={c.role} /> },
{
key: "repo",
header: "Repository",
- render: (c) => (
- <span className="text-xs font-medium text-[var(--color-text-primary)]">{c.repo}</span>
- ),
+ priority: 2,
+ render: (c) => {
+ const service = distinctService(c.service, c.file_path);
+ return (
+ <span className="text-xs font-medium text-[var(--color-text-primary)]">
+ {c.repo}
+ {service ? (
+ <span className="block font-mono text-[10px] font-normal text-[var(--color-text-tertiary)]">
+ {service}
+ </span>
+ ) : null}
+ </span>
+ );
+ },
},
{
key: "file_path",
header: "File",
- priority: 2,
- render: (c) => (
- // No truncation: a path is exactly the string somebody is scanning for.
- <span className="font-mono text-xs text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
- {c.file_path}
- </span>
- ),
+ render: (c) => <FilePathText path={c.file_path} line={c.line} />,
},
{
- key: "confidence",
- header: "Confidence",
+ key: "found_by",
+ header: "Found by",
align: "right",
- render: (c) => (
- <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">
- {Math.round(c.confidence * 100)}%
- </span>
- ),
+ priority: 3,
+ render: (c) => {
+ const via = foundBy(c);
+ return (
+ <span className="whitespace-nowrap font-mono text-[10px] text-[var(--color-text-tertiary)]">
+ {via ? `${via} ` : ""}
+ <span className="tabular-nums">{Math.round(c.confidence * 100)}%</span>
+ </span>
+ );
+ },
},
];
-export function ContractsTable({
+/**
+ * The contracts table. A client leaf because its rows open the page's drawer;
+ * everything around it stays server-rendered. Memoised so opening the drawer
+ * or typing in the search box does not redraw the page of rows.
+ */
+export const ContractsTable = memo(function ContractsTable({
contracts,
- links = [],
- repoIds = {},
+ showType,
}: {
contracts: WorkspaceContractEntry[];
- /** The page's matched links, narrowed to the open contract by the drawer. */
- links?: WorkspaceContractLinkEntry[];
- /** Repo alias to indexed repo id. A never-indexed repo has no entry. */
- repoIds?: Record<string, string>;
+ /** False when a type tab is selected, since every row would repeat it. */
+ showType: boolean;
}) {
- const [selected, setSelected] = useState<WorkspaceContractEntry | null>(null);
- // The same report the section above renders, off the same SWR key, so
- // opening a row costs no second request.
- const { data: breaking } = useWorkspaceBreakingChanges();
-
- const prefixFor = (repo: string): string | null => {
- const id = repoIds[repo];
- return id ? `/repos/${id}` : null;
- };
+ const open = useOpenContract();
+ const columns = useMemo(
+ () => (showType ? [COLUMNS[0]!, TYPE_COLUMN, ...COLUMNS.slice(1)] : COLUMNS),
+ [showType],
+ );
+ const rows = useMemo(
+ () =>
+ contracts.map((c) => ({
+ ...c,
+ // `line` is part of the key because one file can call the same endpoint
+ // from two places.
+ _key: `${c.repo}|${c.file_path}|${c.contract_id}|${c.role}|${c.line ?? ""}`,
+ })),
+ [contracts],
+ );
return (
- <>
- <ResponsiveTable
- columns={CONTRACT_COLUMNS}
- // The row is the verb. No "View" column and no icon cluster: there is
- // exactly one thing a contract row does, and `ResponsiveTable` already
- // carries the focus ring and the Enter/Space handling for both the table
- // and the stacked-card rendering.
- onRowClick={(c) => setSelected(c)}
- rows={contracts.map((c) => ({
- // The contract identity, not the array index: an index renumbers every
- // row whenever a filter changes. `line` is part of the key because one
- // file can call the same endpoint from two places, which is a duplicate
- // React key without it.
- ...c,
- _key: `${c.repo}|${c.file_path}|${c.contract_id}|${c.line ?? ""}`,
- }))}
- rowKey={(c) => c._key}
- caption="All detected contracts"
- stacked="md"
- bare
- />
- <ContractDrawer
- contract={selected}
- open={selected !== null}
- onOpenChange={(open) => {
- if (!open) setSelected(null);
- }}
- links={selected ? linksForContract(selected, links) : []}
- breakingChanges={
- selected
- ? (breaking?.changes ?? []).filter((c) => c.contract_id === selected.contract_id)
- : []
- }
- codeLinks={{
- symbolHref: (repo, symbolId) => {
- const prefix = prefixFor(repo);
- return prefix ? symbolEntityPath(prefix, symbolId) : null;
- },
- fileHref: (repo, file) => {
- const prefix = prefixFor(repo);
- return prefix ? fileEntityPath(prefix, file) : null;
- },
- }}
- {...(selected ? { fullPageHref: contractDetailHref(selected) } : {})}
- />
- </>
+ <ResponsiveTable
+ columns={columns}
+ onRowClick={(c) =>
+ open({ repo: c.repo, file_path: c.file_path, contract_id: c.contract_id }, c)
+ }
+ rows={rows}
+ rowKey={(c) => c._key}
+ caption="Detected contracts"
+ stacked="md"
+ bare
+ />
);
-}
+});
diff --git a/packages/web/src/app/workspace/contracts/detail/contract-body.tsx b/packages/web/src/app/workspace/contracts/detail/contract-body.tsx
index ec6fb45fd..1c81ed70c 100644
--- a/packages/web/src/app/workspace/contracts/detail/contract-body.tsx
+++ b/packages/web/src/app/workspace/contracts/detail/contract-body.tsx
@@ -19,10 +19,14 @@ import {
contractMetaEntries,
contractMetaLabel,
flattenSchemaFields,
+ providerLinkedProse,
schemaFieldConstraints,
+ unlinkedProviderProse,
+ unmatchedConsumerProse,
+ unmatchedReasonCopy,
} from "@repowise-dev/ui/workspace/contract-facts";
import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
-import { formatNumber } from "@repowise-dev/ui/lib/format";
+import { ContractPromptButton } from "@repowise-dev/ui/workspace/contract-prompt-button";
/**
* One contract, read top to bottom.
@@ -74,6 +78,13 @@ export function ContractBody({ detail, repoIds, testImpact, testImpactError }: P
<p className="max-w-[68ch] text-base leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
{contractLede(contract)}
</p>
+ <div>
+ <ContractPromptButton
+ contract={contract}
+ links={links}
+ unmatchedReason={unmatchedReason}
+ />
+ </div>
</header>
<Section
@@ -100,7 +111,7 @@ export function ContractBody({ detail, repoIds, testImpact, testImpactError }: P
names the framework that matched, and shortening it would hide
the difference between a route declaration and a client call. */}
<span className="font-mono text-xs [overflow-wrap:anywhere]">
- {contract.symbol_name || "—"}
+ {contract.symbol_name || "None recorded"}
</span>
</Fact>
<Fact label="Confidence">
@@ -172,7 +183,7 @@ function LinkSection({
if (links.length === 0) {
return (
<Section
- title={isProvider ? "No caller found" : unmatchedTitle(unmatchedReason)}
+ title={isProvider ? "No caller found" : unmatchedReasonCopy(unmatchedReason).title}
description={
isProvider
? unlinkedProviderProse(contract)
@@ -182,15 +193,12 @@ function LinkSection({
);
}
- const otherRepos = new Set(links.map((l) => (isProvider ? l.consumer_repo : l.provider_repo)));
- const sameRepoOnly = otherRepos.size === 1 && otherRepos.has(contract.repo);
-
return (
<Section
title={isProvider ? "Callers" : "Served by"}
description={
isProvider
- ? providerLinkedProse(links.length, otherRepos.size, sameRepoOnly, contract.repo)
+ ? providerLinkedProse(links, contract.repo)
: "This call resolves to the code that serves it. A match joins a call site to a declaration; it does not mean the two were written against a shared schema."
}
>
@@ -199,80 +207,6 @@ function LinkSection({
);
}
-function providerLinkedProse(
- linkCount: number,
- repoCount: number,
- sameRepoOnly: boolean,
- repo: string,
-): string {
- const one = linkCount === 1;
- const head = `${countPhrase(linkCount, "call site", "call sites")} resolve${one ? "s" : ""} to this contract`;
- if (sameRepoOnly) {
- // Every provider in this state on a real workspace has exactly one caller,
- // so the singular is the sentence that actually ships.
- return `${head}, ${one ? `and it is inside ${repo}` : `all of them inside ${repo}`}. A pair is skipped only when the repository and the service are both the same, so ${one ? "that is a call" : "these are calls"} made from a different service in the same repository.`;
- }
- return `${head} across ${countPhrase(repoCount, "repository", "repositories")}.`;
-}
-
-/**
- * The state most contracts on this workspace are in, and the one most likely
- * to be misread.
- *
- * It is the expected condition for a route or an exported symbol in a small
- * workspace, so it gets a sentence rather than a colour: an unlinked provider
- * carries no health band, and green, amber and red are reserved for readouts
- * that do. A reader who correctly inferred a colour here would be taught a
- * rule that makes them wrong about the next mark they see.
- */
-function unlinkedProviderProse(contract: WorkspaceContractEntry): string {
- // A pair is skipped when the repository *and* the service both match, so the
- // excluded set is not "everything in this repo" unless this declaration sits
- // outside a service too. Naming the wrong set here would send somebody
- // looking for a caller the page had told them could not exist.
- const excluded = contract.service
- ? `a call made from inside ${contract.repo}/${contract.service}`
- : `a call made from elsewhere in ${contract.repo} that also sits outside any service`;
- return `Nothing in this workspace resolves to this contract. Read that as two possibilities rather than one. A call is joined to the code that serves it only when the two do not share both a repository and a service, so ${excluded} is excluded by construction and never appears here. And a call written in a form extraction could not follow looks exactly the same from this side. Neither reading makes this dead code.`;
-}
-
-/**
- * The heading names the state, not the absence.
- *
- * "No provider found" is true of only two of these. A call to a third party
- * and a call that never leaves its own service both matched nothing on
- * purpose, and heading them as a failure to find something invites the reader
- * to go looking for it.
- */
-function unmatchedTitle(reason: string | null): string {
- switch (reason) {
- case "external_host":
- return "Outside this workspace";
- case "internal_only":
- return "Not a cross-repo link";
- case "unlinked":
- return "No link formed";
- default:
- return "No provider found";
- }
-}
-
-function unmatchedConsumerProse(reason: string | null, contract: WorkspaceContractEntry): string {
- const host = typeof contract.meta?.host === "string" ? contract.meta.host : null;
- switch (reason) {
- case "external_host":
- return `This call goes to ${host ?? "a third-party host"}, which is not a service in this workspace. Calls to a literal external host are left out of matching on purpose, so there is nothing here to link it to and nothing to fix.`;
- case "internal_only":
- return `The only declarations matching this call live in the same repository and the same service as the call itself, so it never crosses a boundary. Intra-service calls are left out of the link set on purpose: a link is a claim that two services depend on each other.`;
- case "no_provider":
- return `Nothing in this workspace declares ${contract.contract_id}. Either it is served by something outside these repositories, or the declaration is written in a form extraction did not recognise.`;
- case "unlinked":
- return "A declaration with this id exists in another service, but no link was formed between the two. That is rare, and it points at a gap in the matcher rather than at the code.";
- default:
- return "This call matched no declaration, and no reason was recorded for it. Reasons come from the system graph, so a workspace that has not built one reports the count without the explanation.";
- }
-}
-
function LinkTable({
links,
side,
@@ -565,11 +499,3 @@ function FileRef({
</span>
);
}
-
-// ---------------------------------------------------------------------------
-// Copy
-// ---------------------------------------------------------------------------
-
-function countPhrase(n: number, one: string, many: string): string {
- return `${formatNumber(n)} ${n === 1 ? one : many}`;
-}
diff --git a/packages/web/src/app/workspace/contracts/detail/page.tsx b/packages/web/src/app/workspace/contracts/detail/page.tsx
index 155feafd0..6f2605b12 100644
--- a/packages/web/src/app/workspace/contracts/detail/page.tsx
+++ b/packages/web/src/app/workspace/contracts/detail/page.tsx
@@ -21,7 +21,7 @@ export async function generateMetadata({ searchParams }: Props): Promise<Metadat
if (!repo || !file || !id) return { title: "Contract" };
try {
const detail = await getWorkspaceContractDetail({ repo, file, id });
- return { title: `${contractHeading(detail.contract)} — Contract` };
+ return { title: `${contractHeading(detail.contract)} | Contract` };
} catch {
return { title: "Contract" };
}
@@ -37,7 +37,7 @@ export async function generateMetadata({ searchParams }: Props): Promise<Metadat
* The workspace payload comes along for one reason: contracts name their repo
* by alias, and a file link needs the indexed repo id. A repo that has never
* been indexed has no id, which is why the map is passed down whole rather
- * than resolved into hrefs here — the degrade belongs next to the link.
+ * than resolved into hrefs here: the degrade belongs next to the link.
*/
export default async function ContractDetailPage({ searchParams }: Props) {
const { repo, file, id } = await searchParams;
diff --git a/packages/web/src/app/workspace/contracts/links-table.tsx b/packages/web/src/app/workspace/contracts/links-table.tsx
new file mode 100644
index 000000000..8524aca20
--- /dev/null
+++ b/packages/web/src/app/workspace/contracts/links-table.tsx
@@ -0,0 +1,78 @@
+"use client";
+
+import { useCallback } from "react";
+import useSWR from "swr";
+import { OverviewSection } from "@repowise-dev/ui/overview/section";
+import { ContractLinksTable } from "@repowise-dev/ui/workspace/contract-links-table";
+import { formatNumber } from "@repowise-dev/ui/lib/format";
+import type { WorkspaceContractLinkEntry } from "@/lib/api/types";
+import { getWorkspaceContracts } from "@/lib/api/workspace";
+import { useOpenContract } from "./contract-drawer-host";
+
+/**
+ * The matched links, fetched here rather than on the server page.
+ *
+ * The page re-renders on every page turn and search, and carrying all links in
+ * that payload resent them each time. Keyed only on the filters that narrow
+ * links (type, repo, search), so paging and the role or link filters reuse the
+ * cached answer. A row opens the provider side in the drawer: its callers list
+ * this link among the rest, and each caller swaps the drawer to itself.
+ */
+export function LinksSection({
+ type,
+ repo,
+ q,
+}: {
+ type?: string | undefined;
+ repo?: string | undefined;
+ q?: string | undefined;
+}) {
+ const open = useOpenContract();
+ const { data, error, isLoading } = useSWR(
+ ["workspace:contract-links", type ?? "", repo ?? "", q ?? ""],
+ // limit=1: the endpoint pages contracts, not links, so this is the cheapest
+ // request that returns every matching link.
+ () => getWorkspaceContracts({ contract_type: type, repo, q, limit: 1 }),
+ { revalidateOnFocus: false },
+ );
+ const onSelect = useCallback(
+ (l: WorkspaceContractLinkEntry) =>
+ open({ repo: l.provider_repo, file_path: l.provider_file, contract_id: l.contract_id }),
+ [open],
+ );
+
+ const links = data?.links ?? [];
+ if (!isLoading && !error && links.length === 0) return null;
+ const filtered = Boolean(type || repo || q);
+
+ return (
+ <OverviewSection
+ title="Matched links"
+ {...(data ? { description: linksDescription(links, filtered) } : {})}
+ >
+ {error ? (
+ <p className="text-xs text-[var(--color-text-secondary)]">
+ The matched links could not be loaded. Reload to try again.
+ </p>
+ ) : !data ? (
+ <p className="text-xs text-[var(--color-text-secondary)]">Loading matched links...</p>
+ ) : (
+ <ContractLinksTable links={links} onSelect={onSelect} />
+ )}
+ </OverviewSection>
+ );
+}
+
+/** Name the match basis once, since it is the same word on nearly every row. */
+function linksDescription(links: { match_type: string }[], filtered: boolean): string {
+ const byType = new Map<string, number>();
+ for (const l of links) byType.set(l.match_type, (byType.get(l.match_type) ?? 0) + 1);
+ const basis =
+ byType.size === 1 && byType.has("exact")
+ ? `All ${formatNumber(links.length)} are exact matches.`
+ : [...byType.entries()].map(([t, n]) => `${formatNumber(n)} ${t}`).join(", ") + ".";
+ const head = filtered
+ ? `${formatNumber(links.length)} ${links.length === 1 ? "link matches" : "links match"} the type, repository and search.`
+ : "Every provider joined to the consumer that calls it, strongest first.";
+ return `${head} ${basis} Open a row for the provider and every caller.`;
+}
diff --git a/packages/web/src/app/workspace/contracts/needs-attention.tsx b/packages/web/src/app/workspace/contracts/needs-attention.tsx
new file mode 100644
index 000000000..d95c401ba
--- /dev/null
+++ b/packages/web/src/app/workspace/contracts/needs-attention.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import Link from "next/link";
+import type { OrphanProvider, UnmatchedConsumer } from "@repowise-dev/types/workspace";
+import type { OrphanGroup } from "@repowise-dev/ui/workspace/contract-facts";
+import { ContractAttention } from "@repowise-dev/ui/workspace/contract-attention";
+import { useOpenContract } from "./contract-drawer-host";
+import { contractsListHref } from "./contract-href";
+
+/** The attention lists, with rows that open the drawer and summaries that filter the list. */
+export function NeedsAttention({
+ unmatched,
+ orphanGroups,
+}: {
+ unmatched: UnmatchedConsumer[];
+ orphanGroups: OrphanGroup<OrphanProvider>[];
+}) {
+ const open = useOpenContract();
+ return (
+ <ContractAttention
+ unmatched={unmatched}
+ orphanGroups={orphanGroups}
+ onSelect={open}
+ browseHref={(repo, type) =>
+ contractsListHref({ repo, type, role: "provider", linked: "no" })
+ }
+ LinkComponent={Link}
+ />
+ );
+}
diff --git a/packages/web/src/app/workspace/contracts/page.tsx b/packages/web/src/app/workspace/contracts/page.tsx
index 4c773b17e..8b8ff126b 100644
--- a/packages/web/src/app/workspace/contracts/page.tsx
+++ b/packages/web/src/app/workspace/contracts/page.tsx
@@ -2,11 +2,15 @@ import type { Metadata } from "next";
import Link from "next/link";
import { Link2 } from "lucide-react";
import type { ExtractionDiagnostics } from "@repowise-dev/api-client/types";
-import { PageShell, EmptyState } from "@repowise-dev/ui/shared";
+import { PageShell } from "@repowise-dev/ui/shared";
import { PageLede } from "@repowise-dev/ui/shared/page-lede";
import { OverviewSection } from "@repowise-dev/ui/overview";
import { StatRibbon, type RibbonStat } from "@repowise-dev/ui/stats/stat-ribbon";
-import { ContractLinksTable } from "@repowise-dev/ui/workspace/contract-links-table";
+import {
+ groupOrphanProviders,
+ unmatchedReasonCopy,
+} from "@repowise-dev/ui/workspace/contract-facts";
+import { MAX_PROMPT_ROWS } from "@repowise-dev/ui/workspace/contract-ai-prompt";
import { formatNumber } from "@repowise-dev/ui/lib/format";
import {
getWorkspace,
@@ -14,106 +18,129 @@ import {
getWorkspaceDiagnostics,
} from "@/lib/api/workspace";
import { BreakingChangesSection } from "./breaking-changes-section";
-import { ContractFilters } from "./contract-filters";
+import { ContractDrawerProvider } from "./contract-drawer-host";
+import { ContractListControls, ContractListPager } from "./contract-filters";
+import { contractsListHref, type ContractListFilters } from "./contract-href";
import { ContractsTable } from "./contracts-table";
+import { LinksSection } from "./links-table";
+import { NeedsAttention } from "./needs-attention";
export const metadata: Metadata = { title: "Contracts" };
export const revalidate = 30;
-/** Rows the table draws. The server caps at 1,000; this is the page's own
- * window and it is always reported against the filtered total below. */
-const ROW_WINDOW = 200;
+/** Rows per page of the full list. The server caps a page at 1,000. */
+const PAGE_SIZE = 100;
type Props = {
- searchParams: Promise<{ type?: string; repo?: string; role?: string }>;
+ searchParams: Promise<{
+ type?: string;
+ repo?: string;
+ role?: string;
+ linked?: string;
+ q?: string;
+ page?: string;
+ contract?: string;
+ file?: string;
+ }>;
};
/**
- * Contracts detected across the workspace, and which of them matched.
+ * Contracts detected across the workspace, which of them matched, and which
+ * need a look.
*
- * The four `MetricCard`s this replaces could not be restyled into a ribbon,
- * because three of them were counting the wrong things. "Total Contracts" and
- * "Unmatched" were both derived from the contract rows, which arrive filtered
- * *and* paginated — so "Unmatched" was computed over one page of 200 and
- * reported as a workspace figure, and it moved whenever a filter changed. "By
- * Type" was arithmetically identical to "Total Contracts", since the sum of a
- * breakdown is the thing it breaks down.
+ * The figures come from `/api/workspace/diagnostics`, which knows the
+ * workspace-wide denominators, and deliberately do not move when the list is
+ * filtered. The list pages on the server, so every contract is reachable and
+ * the count beside it is the count of what the filters return.
*
- * The figures come from `/api/workspace/diagnostics` now, which is the
- * endpoint that already knows the denominators: how many providers and
- * consumers extraction found, how many linked, and why the rest did not. Those
- * are workspace-wide and deliberately do not move when the table is filtered.
+ * `?contract=&repo=&file=` opens the drawer on load (the System Map links here
+ * that way). While it is present `repo` names the drawer's contract, not a list
+ * filter, so a deep link never lands on a list narrowed by accident.
*/
export default async function ContractsPage({ searchParams }: Props) {
- const { type, repo, role } = await searchParams;
+ const sp = await searchParams;
+ const deepLink =
+ sp.contract && sp.repo && sp.file
+ ? { contract_id: sp.contract, repo: sp.repo, file_path: sp.file }
+ : null;
+ const filters: ContractListFilters = {
+ type: sp.type || undefined,
+ repo: deepLink ? undefined : sp.repo || undefined,
+ role: sp.role || undefined,
+ linked: sp.linked === "yes" || sp.linked === "no" ? sp.linked : undefined,
+ // A contract link without a file (an edge ref) cannot name one declaration,
+ // so it lands on the list searched for that id instead.
+ q: sp.q?.trim() || (!deepLink && sp.contract) || undefined,
+ };
+ const page = Math.max(1, Number.parseInt(sp.page ?? "1", 10) || 1);
const [ct, diag, ws] = await Promise.allSettled([
getWorkspaceContracts({
- contract_type: type || undefined,
- repo: repo || undefined,
- role: role || undefined,
- limit: ROW_WINDOW,
+ contract_type: filters.type,
+ repo: filters.repo,
+ role: filters.role,
+ q: filters.q,
+ ...(filters.linked ? { linked: filters.linked === "yes" } : {}),
+ // The links section fetches its own; resending them on every page turn
+ // was most of this request.
+ include_links: false,
+ limit: PAGE_SIZE,
+ offset: (page - 1) * PAGE_SIZE,
}),
- getWorkspaceDiagnostics(),
- getWorkspace(),
+ // Workspace-wide and unchanged by the filters, so a page turn or a search
+ // reuses them instead of refetching.
+ getWorkspaceDiagnostics({ next: { revalidate: 30 } }),
+ getWorkspace({ next: { revalidate: 30 } }),
]);
const data = ct.status === "fulfilled" ? ct.value : null;
const diagnostics = diag.status === "fulfilled" ? diag.value : null;
const workspace = ws.status === "fulfilled" ? ws.value : null;
const repos = workspace?.repos.map((r) => r.alias) ?? [];
- // The workspace-wide breakdown, not `data.by_type`: that one is counted
- // after the filters run, so picking a type would leave the select holding
- // only the type already picked.
+ // The workspace-wide breakdown, not `data.by_type`: that one is counted after
+ // the filters run, so picking a type would leave only the type already picked.
const byType = workspace?.contract_summary?.by_type ?? null;
- // Alias to indexed repo id, so the breaking-change rows can link a symbol or
- // a file into the repo that owns it. Repos that were never indexed have no
- // id and are left out; their references render as plain text.
+ const workspaceTotal = byType ? Object.values(byType).reduce((a, b) => a + b, 0) : null;
const repoIds: Record<string, string> = {};
- for (const repo of workspace?.repos ?? []) {
- if (repo.repo_id) repoIds[repo.alias] = repo.repo_id;
+ for (const r of workspace?.repos ?? []) {
+ if (r.repo_id) repoIds[r.alias] = r.repo_id;
}
const rows = data?.contracts ?? [];
- const links = data?.links ?? [];
- const filtered = Boolean(type || repo || role);
+ const total = data?.total_contracts ?? 0;
+ const filtered = Boolean(filters.type || filters.repo || filters.role || filters.linked || filters.q);
+ // The lede carries matched links, so the ribbon does not repeat it.
const ribbon: RibbonStat[] = [
{
label: "Providers",
- value: diagnostics ? formatNumber(diagnostics.total_providers) : "—",
- sub: "routes, topics and tables published",
+ value: diagnostics ? formatNumber(diagnostics.total_providers) : "",
+ sub: "routes, tables and exports published",
},
{
label: "Consumers",
- value: diagnostics ? formatNumber(diagnostics.total_consumers) : "—",
+ value: diagnostics ? formatNumber(diagnostics.total_consumers) : "",
sub: "call sites resolved to a contract",
},
- {
- label: "Matched links",
- value: diagnostics ? formatNumber(diagnostics.total_links) : "—",
- sub: "provider joined to consumer",
- },
{
label: "Unmatched consumers",
- value: diagnostics ? formatNumber(diagnostics.unmatched_consumers.length) : "—",
+ value: diagnostics ? formatNumber(diagnostics.unmatched_consumers.length) : "",
sub: unmatchedReasonSub(diagnostics),
},
{
- label: "Unused providers",
- value: diagnostics ? formatNumber(diagnostics.orphan_providers.length) : "—",
- sub: "nothing in the workspace calls them",
+ label: "Providers with no caller",
+ value: diagnostics ? formatNumber(diagnostics.orphan_providers.length) : "",
+ sub: "in this workspace; not the same as unused",
},
{
- // Extraction reporting on its own recall. The denominator is calls a
- // dialect located, so this is honest about what it covers and silent
- // about calls nothing recognised — it is not total recall.
+ // Extraction reporting on its own recall: the denominator is calls a
+ // dialect located, so it says nothing about calls nothing recognised.
label: "HTTP calls resolved",
value:
diagnostics?.http_consumer_coverage != null
? `${Math.floor(diagnostics.http_consumer_coverage * 100)}%`
- : "—",
+ : "",
sub: diagnostics?.http_consumers_unresolved
? `${formatNumber(diagnostics.http_consumers_unresolved)} located but not resolvable`
: "of the client calls extraction located",
@@ -124,87 +151,93 @@ export default async function ContractsPage({ searchParams }: Props) {
<PageShell
title="Contracts"
icon={<Link2 className="h-5 w-5 text-[var(--color-text-tertiary)]" />}
- description="Routes, topics and tables one repository publishes and another consumes."
+ description="Routes, tables and exports one repository publishes and another consumes."
>
<PageLede
label="Matched links"
- value={diagnostics ? formatNumber(diagnostics.total_links) : "—"}
+ value={diagnostics ? formatNumber(diagnostics.total_links) : "Unknown"}
unit="provider to consumer"
layout="beside"
>
{diagnostics ? (
<>
<p>
- Extraction found {formatNumber(diagnostics.total_providers)} providers and{" "}
- {formatNumber(diagnostics.total_consumers)} consumers across the workspace, and
- joined {formatNumber(diagnostics.total_links)} of them into cross-repo links. A
- link means a call site was resolved to the code that serves it, not that the two
- were declared against a shared schema.
+ Each link is a call site resolved to the route, table or export that serves it, in
+ another repository or service.
</p>
<p>
- {formatNumber(diagnostics.orphan_providers.length)} providers have no caller in
- this workspace. Read that against extraction&rsquo;s own coverage rather than on
- its own: an endpoint looks unused both when nothing calls it and when the call
- was written in a form this analysis could not follow.
- {diagnostics.http_consumers_unresolved > 0 ? (
- <>
- {" "}
- {formatNumber(diagnostics.http_consumers_unresolved)} HTTP client calls were
- located here but could not be resolved to an endpoint, so some of those
- providers are called by code this page cannot yet name.
- </>
- ) : null}
+ It is a match on the path or name, not proof both sides share a schema. Calls that
+ matched nothing and providers nothing calls are under Needs attention.
</p>
</>
) : (
<p>
- Extraction diagnostics are not available, so the totals below cannot be shown.
- Run a workspace sync to rebuild them.
+ Extraction diagnostics are not available, so the totals cannot be shown. Run a
+ workspace sync to rebuild them.
</p>
)}
</PageLede>
<StatRibbon stats={ribbon} />
- <OverviewSection
- title="Breaking changes"
- description="Provider contracts that changed in the most recent workspace update, and the consumers linked to them. Breaking first, then warnings."
- >
+ <ContractDrawerProvider repoIds={repoIds} initial={deepLink}>
<BreakingChangesSection repoIds={repoIds} />
- </OverviewSection>
- {links.length > 0 && (
+ {diagnostics ? (
+ <OverviewSection title="Needs attention">
+ <NeedsAttention
+ unmatched={diagnostics.unmatched_consumers}
+ // Counts plus a prompt's worth of rows per group, not all 1,000+.
+ orphanGroups={groupOrphanProviders(diagnostics.orphan_providers, MAX_PROMPT_ROWS)}
+ />
+ </OverviewSection>
+ ) : null}
+
+ <LinksSection type={filters.type} repo={filters.repo} q={filters.q} />
+
<OverviewSection
- title="Matched links"
- description={
- filtered
- ? "Links matching the current filter, provider on the left and consumer on the right."
- : "Every provider joined to the consumer that calls it, with the confidence of the match."
- }
+ id="all-contracts"
+ title="All detected contracts"
+ description={data ? listDescription(total, workspaceTotal, filtered) : undefined}
>
- <ContractLinksTable links={links} />
+ <ContractListControls filters={filters} repos={repos} byType={byType} />
+ {rows.length === 0 ? (
+ // One quiet sentence, like every other state with nothing in it.
+ <p className="text-xs leading-relaxed text-[var(--color-text-secondary)]">
+ {!data ? (
+ "The contract list could not be loaded. The API may be restarting; reload in a moment."
+ ) : total > 0 ? (
+ <>
+ Page {formatNumber(page)} is past the end of this list, which has{" "}
+ {formatNumber(total)} {total === 1 ? "contract" : "contracts"}.{" "}
+ <Link
+ href={contractsListHref({ ...filters, page: 1 })}
+ className="text-[var(--color-accent-primary)] hover:underline"
+ >
+ Go to the first page
+ </Link>
+ .
+ </>
+ ) : filtered ? (
+ "No contracts match these filters. Clear the search or a filter to widen the list."
+ ) : (
+ "No contracts detected. They are found during a workspace sync, by reading the routes each repository serves and the calls the others make."
+ )}
+ </p>
+ ) : (
+ <>
+ <ContractsTable contracts={rows} showType={!filters.type} />
+ <ContractListPager
+ filters={filters}
+ page={page}
+ pageSize={PAGE_SIZE}
+ shown={rows.length}
+ total={total}
+ />
+ </>
+ )}
</OverviewSection>
- )}
-
- <OverviewSection
- title="All detected contracts"
- description={tableDescription(rows.length, data?.total_contracts ?? 0, filtered)}
- action={<ContractFilters repos={repos} byType={byType} />}
- >
- {rows.length === 0 ? (
- <EmptyState
- className="p-6"
- title={filtered ? "No contracts match this filter" : "No contracts detected"}
- description={
- filtered
- ? "Clear a filter to widen the search."
- : "Contracts are detected during a workspace sync, by reading the routes each repository serves and the calls the others make."
- }
- />
- ) : (
- <ContractsTable contracts={rows} links={links} repoIds={repoIds} />
- )}
- </OverviewSection>
+ </ContractDrawerProvider>
<p className="text-xs text-[var(--color-text-tertiary)]">
Contracts are matched on path. Two routes that share a path are one contract here, so a
@@ -221,17 +254,14 @@ export default async function ContractsPage({ searchParams }: Props) {
);
}
-/**
- * Say the bound. The endpoint pages the rows but reports the unpaged total, so
- * without this the heading claims a number the table does not draw.
- */
-function tableDescription(shown: number, total: number, filtered: boolean): string {
- const scope = filtered ? "matching the current filter" : "detected across the workspace";
- if (total === 0) return `Every contract ${scope}.`;
- if (shown >= total) {
- return `All ${formatNumber(total)} ${total === 1 ? "contract" : "contracts"} ${scope}. One contract can be declared in several places, so a name may repeat.`;
+/** Say exactly what the list holds against the workspace it came from. */
+function listDescription(total: number, workspaceTotal: number | null, filtered: boolean): string {
+ const noun = total === 1 ? "contract" : "contracts";
+ if (!filtered) {
+ return `All ${formatNumber(total)} ${noun} detected across the workspace, ${PAGE_SIZE} to a page. One contract can be declared in several places, so a name may repeat.`;
}
- return `Showing ${formatNumber(shown)} of ${formatNumber(total)} contracts ${scope}. One contract can be declared in several places, so a name may repeat.`;
+ const of = workspaceTotal != null ? ` of ${formatNumber(workspaceTotal)}` : "";
+ return `${formatNumber(total)}${of} ${noun} match these filters.`;
}
/** Name why consumers went unmatched, since the count alone invites the wrong read. */
@@ -241,12 +271,5 @@ function unmatchedReasonSub(diagnostics: ExtractionDiagnostics | null): string {
.filter(([, n]) => n > 0)
.sort((a, b) => b[1] - a[1]);
if (reasons.length === 0) return "every consumer matched a provider";
- return reasons.map(([reason, n]) => `${n} ${REASON_LABEL[reason] ?? reason}`).join(", ");
+ return reasons.map(([reason, n]) => `${n} ${unmatchedReasonCopy(reason).short}`).join(", ");
}
-
-const REASON_LABEL: Record<string, string> = {
- no_provider: "no provider found",
- internal_only: "internal to one repo",
- external_host: "external host",
- unlinked: "unlinked",
-};
diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.py
index 18f636f50..3e96d0684 100644
--- a/tests/unit/server/test_workspace_router.py
+++ b/tests/unit/server/test_workspace_router.py
@@ -445,6 +445,54 @@ class TestGetContracts:
assert data["total_contracts"] == 0
assert data["total_links"] == 0
+ @pytest.mark.asyncio
+ async def test_search_matches_every_term_across_fields(self, tmp_path: Path) -> None:
+ """``q`` is case-insensitive and every term must match somewhere."""
+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=_make_enricher(tmp_path))
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ by_path = (await c.get("/api/workspace/contracts", params={"q": "USERS"})).json()
+ by_file_and_repo = (
+ await c.get("/api/workspace/contracts", params={"q": "client.ts frontend"})
+ ).json()
+ no_hit = (await c.get("/api/workspace/contracts", params={"q": "users grpc"})).json()
+ assert by_path["total_contracts"] == 2
+ assert by_path["total_links"] == 1
+ assert [r["file_path"] for r in by_file_and_repo["contracts"]] == ["client.ts"]
+ assert no_hit["total_contracts"] == 0
+ assert no_hit["total_links"] == 0
+
+ @pytest.mark.asyncio
+ async def test_filter_by_linked(self, tmp_path: Path) -> None:
+ """``linked`` splits contracts by whether their own side sits on a link."""
+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=_make_enricher(tmp_path))
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ yes = (await c.get("/api/workspace/contracts", params={"linked": "true"})).json()
+ no = (
+ await c.get(
+ "/api/workspace/contracts", params={"linked": "false", "role": "provider"}
+ )
+ ).json()
+ assert {(r["repo"], r["file_path"]) for r in yes["contracts"]} == {
+ ("backend", "routes.py"),
+ ("frontend", "client.ts"),
+ }
+ assert [r["contract_id"] for r in no["contracts"]] == ["grpc::Auth/Login"]
+
+ @pytest.mark.asyncio
+ async def test_include_links_false_omits_rows_but_keeps_the_count(self, tmp_path: Path) -> None:
+ """A pager that already holds the links can skip them; the total still counts."""
+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=_make_enricher(tmp_path))
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ data = (
+ await c.get("/api/workspace/contracts", params={"include_links": "false"})
+ ).json()
+ assert data["links"] == []
+ assert data["total_links"] == 1
+ assert data["total_contracts"] == 4
+
class TestContractWireFields:
"""The list endpoint carries everything but ``schema``."""