From a87cef317db9c0c12989872829d688140cc3ecb9 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 15 Nov 2026 14:32:25 -0500 Subject: [PATCH 1/2] The six built-in knowledge bases on the Knowledge page, AI tools as readers, and the every-ai-tool section - Knowledge lists Code, Work, Infrastructure, Logs, Security and Knowledge first, each with what it holds, counts, freshness, who reads it and whether it is open to you; admins choose each base's readers and whether people may connect AI tools as readers - An open base is searched in place and a search shared as a link that runs again as whoever opens it (/s/) - The consent page names each scope in plain words with the bases it opens, offers the team lookups as choices, and a signed out person can continue with GitHub as a reader and come back to it - The home page gains the every-ai-tool section with its frame and two questions; the MCP docs cover the bases, their scopes, the new tools, readers and client metadata documents --- dashboard/e2e/connected-apps.spec.ts | 55 ++- dashboard/e2e/knowledge-builtin.spec.ts | 294 ++++++++++++++ dashboard/src/app/authorize/page.tsx | 54 ++- dashboard/src/app/knowledge/page.tsx | 7 + dashboard/src/app/s/page.tsx | 87 +++++ dashboard/src/components/client-shell.tsx | 16 +- .../src/components/knowledge/builtin.tsx | 364 ++++++++++++++++++ dashboard/src/lib/builtin-bases.ts | 139 +++++++ dashboard/src/lib/connected-apps.ts | 39 +- dashboard/src/lib/routes.ts | 1 + docs/content/docs/mcp.mdx | 32 +- src/components/Frames.tsx | 37 ++ src/content/site.ts | 35 +- src/content/types.ts | 3 +- 14 files changed, 1148 insertions(+), 15 deletions(-) create mode 100644 dashboard/e2e/knowledge-builtin.spec.ts create mode 100644 dashboard/src/app/s/page.tsx create mode 100644 dashboard/src/components/knowledge/builtin.tsx create mode 100644 dashboard/src/lib/builtin-bases.ts diff --git a/dashboard/e2e/connected-apps.spec.ts b/dashboard/e2e/connected-apps.spec.ts index 8375deee..2cdde9a9 100644 --- a/dashboard/e2e/connected-apps.spec.ts +++ b/dashboard/e2e/connected-apps.spec.ts @@ -40,6 +40,10 @@ interface Opts { teamWide?: boolean; signedIn?: boolean; describeError?: string; + /** The gateway sends each scope in plain words, the bases it opens and the team lookups to choose. */ + bases?: boolean; + reader?: boolean; + github?: boolean; } async function mockApi(page: Page, o: Opts = {}): Promise { @@ -68,7 +72,7 @@ async function mockApi(page: Page, o: Opts = {}): Promise { if (p === "/api/usage") return json(route, { month: "2026-01", total_tokens: 0, tokens_in: 0, tokens_out: 0, total_runs: 0, max_tokens: 0 }); if (p === "/api/banners") return json(route, { banners: [] }); if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "acme-labs", status: "active", current: true }] }); - if (p === "/auth/methods") return json(route, { password: true, google: false, github: false }); + if (p === "/auth/methods") return json(route, { password: true, google: false, github: o.github ?? false }); if (p === "/api/mcp/authorize/describe") { if (o.describeError) return json(route, { error: o.describeError }, 400); return json(route, { @@ -86,6 +90,22 @@ async function mockApi(page: Page, o: Opts = {}): Promise { team_id: "t_1", can_act: o.canAct ?? true, mcp_url: MCP_URL, + ...(o.bases + ? { + reader: o.reader ?? false, + scopes: [ + { key: "runs:read", label: "See your team's runs and reviews", requested: true, always: true, plain: "Runs", opens: [] }, + { key: "knowledge:read", label: "Search the knowledge bases you can read in Chat", requested: true, always: false, plain: "Knowledge", opens: ["Knowledge"] }, + ], + lookup_scopes: [ + { key: "code:read", label: "Read and search your team's code, as Chat does", requested: true, default: true, plain: "Code", opens: ["Code"] }, + { key: "work:read", label: "Find tickets, pull requests, runs, reviews and plans you can see", requested: true, default: true, plain: "Work", opens: ["Work"] }, + { key: "infra:read", label: "Read your team's AWS resources and where each is defined", requested: true, default: false, plain: "Infrastructure", opens: ["Infrastructure"] }, + { key: "logs:read", label: "Read log findings and alerts you can see", requested: false, default: false, plain: "Logs", opens: ["Logs"] }, + { key: "security:read", label: "Read security findings you can see", requested: false, default: false, plain: "Security", opens: ["Security"] }, + ], + } + : {}), }); } if (p === "/api/mcp/authorize" && method === "POST") { @@ -241,3 +261,36 @@ test("knowledge stays off when the app didn't ask, or the person unticks it", as await page.waitForURL(/code=chc_test_code/); expect(db.calls.find((c) => c.path === "/api/mcp/authorize")?.body).toMatchObject({ allow_knowledge: false }); }); + +test("the consent page names each scope in plain words, the bases it opens, and the lookups to choose", async ({ page }) => { + const db = await mockApi(page, { bases: true, reader: true }); + await page.goto(`/authorize/?request=${REQUEST}`); + const list = page.getByRole("list", { name: "What the app may do" }); + await expect(list.getByText("Runs:", { exact: false })).toBeVisible(); + const lookups = page.getByTestId("consent-lookup"); + await expect(lookups).toHaveCount(5); + await expect(lookups.nth(0)).toContainText("Code:"); + await expect(lookups.nth(0)).toContainText("Opens Code"); + await expect(lookups.nth(2)).toContainText("Opens Infrastructure"); + // Code and work ticked; infrastructure, logs and security only when the person ticks them. + await expect(lookups.nth(0).getByRole("checkbox")).toBeChecked(); + await expect(lookups.nth(1).getByRole("checkbox")).toBeChecked(); + await expect(lookups.nth(2).getByRole("checkbox")).not.toBeChecked(); + await expect(lookups.nth(2)).toContainText("The app asked for this"); + await expect(page.getByTestId("consent-reader")).toContainText("don't take a seat"); + await lookups.nth(2).getByRole("checkbox").check(); + await lookups.nth(1).getByRole("checkbox").uncheck(); + await shot(page, "consent-bases-1280.png"); + await page.getByRole("button", { name: "Allow", exact: true }).click(); + await expect.poll(() => db.calls.find((c) => c.path === "/api/mcp/authorize")?.body).toMatchObject({ approve: true, allow_scopes: ["code:read", "infra:read"] }); +}); + +test("signed out on the consent page, GitHub sign-in comes back to it and offers reader access", async ({ page }) => { + await mockApi(page, { signedIn: false, github: true }); + await page.goto(`/authorize/?request=${REQUEST}`); + await expect(page.getByTestId("sign-in-reader")).toContainText("without a seat"); + const gh = page.getByRole("link", { name: "Continue with GitHub" }); + const href = await gh.getAttribute("href"); + expect(href?.endsWith(`/auth/github?return_to=${encodeURIComponent(`/authorize/?request=${REQUEST}`)}`)).toBe(true); + await shot(page, "consent-signed-out-reader-1280.png"); +}); diff --git a/dashboard/e2e/knowledge-builtin.spec.ts b/dashboard/e2e/knowledge-builtin.spec.ts new file mode 100644 index 00000000..386f1faf --- /dev/null +++ b/dashboard/e2e/knowledge-builtin.spec.ts @@ -0,0 +1,294 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; +import fs from "node:fs"; +import path from "node:path"; + +// The six built-in bases on the Knowledge page: listed first, above the +// bases people made, each with what it holds, how fresh it is, who reads it +// and whether the person looking may. An open base is searched and a search +// shared; a base not open to the person shows why and offers no search. +// Admins change who reads a base and whether readers may connect AI tools. +// The shared link opens again as whoever looks. Every API call is answered +// here; nothing reaches a real backend. + +const SHOTS = process.env.KB_BUILTIN_SHOTS_DIR || path.join("test-results", "kb-builtin-shots"); +const now = Date.now(); +const iso = (minsAgo: number) => new Date(now - minsAgo * 60_000).toISOString(); + +type Key = "code" | "work" | "infra" | "logs" | "security" | "team"; + +interface Base { + key: Key; + name: string; + about: string; + scope: string; + builtin: true; + counts: { label: string; count: number }[]; + updated_at: string | null; + access: { open: boolean; why: string | null }; + audience: { roles: string[]; people: string[]; readers: boolean; paused: boolean }; + audience_label: string; + mirroring: string | null; + total: number; + live: boolean; +} + +const base = (key: Key, name: string, about: string, scope: string, counts: [string, number][], mins: number | null, over: Partial = {}): Base => ({ + key, + name, + about, + scope, + builtin: true, + counts: counts.map(([label, count]) => ({ label, count })), + updated_at: mins === null ? null : iso(mins), + access: { open: true, why: null }, + audience: { roles: [], people: [], readers: key === "code" || key === "work" || key === "team", paused: false }, + audience_label: "Everyone whose role opens it", + mirroring: null, + total: counts.reduce((n, [, c]) => n + c, 0), + live: key === "code" || key === "work", + ...over, +}); + +function bases(memberView: boolean): Base[] { + const closed = (why: string) => (memberView ? { access: { open: false, why } } : {}); + return [ + base("code", "Code", "The team's repositories: files, code search, the code graph and history", "code:read", [["repositories", 12], ["files", 18340], ["docs", 1210]], 14, { + mirroring: "Code shows only for repositories your GitHub account can read.", + }), + base("work", "Work", "Tickets, pull requests, CoderHelm's runs, reviews and plans", "work:read", [["runs", 412], ["plans", 38], ["reviews", 951]], 3), + base("infra", "Infrastructure", "AWS resources, where each is defined in Terraform, CDK or CloudFormation, and pending updates", "infra:read", [["AWS accounts", 2], ["resources", 1487], ["findings", 9]], 180, { + audience: { roles: ["admin", "owner"], people: ["ops@example.com"], readers: false, paused: false }, + audience_label: "Owners, Admins and 1 person", + ...closed("Infrastructure is open to owners, admins and 1 person. Ask an admin to add you."), + }), + base("logs", "Logs", "Log findings, alerts and which repository and service each belongs to", "logs:read", [["log findings", 23], ["alerts", 61]], 45), + base("security", "Security", "Dependency advisories and CVEs, infrastructure findings and quarantined tests", "security:read", [["advisories", 17], ["infrastructure findings", 9]], 600, { + audience: { roles: ["admin", "owner"], people: [], readers: false, paused: false }, + audience_label: "Owners and Admins", + ...closed("Security is open to owners and admins. Ask an admin to add you."), + }), + base("team", "Knowledge", "The knowledge bases people made: uploaded and synced documents", "knowledge:read", [["knowledge bases", 1], ["pages", 7]], null), + ]; +} + +interface Db { + admin: boolean; + calls: string[]; + bodies: Record[]; + bases: Base[]; + readers: boolean; +} + +const RESULTS = [ + { + id: "chk1.code.code.eyJ4IjoxfQ", + title: "payments/src/refunds.ts", + url: "https://github.com/acme/payments/blob/abc123/src/refunds.ts#L40-L88", + base: "Code", + kind: "code", + snippet: "export async function refund(order: Order, amount: Money) { const split = order.parts.length > 1;", + updated_at: iso(14), + }, + { + id: "chk1.code.code.eyJ4IjoyfQ", + title: "docs/refunds.md", + url: "https://github.com/acme/payments/blob/abc123/docs/refunds.md", + base: "Code", + kind: "code", + snippet: "Partial refunds for split orders go back to each card in the order they were charged.", + updated_at: iso(60 * 26), + }, +]; + +async function mock(page: Page, admin: boolean): Promise { + const db: Db = { admin, calls: [], bodies: [], bases: bases(!admin), readers: false }; + const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + await page.route((url) => url.hostname !== "localhost", (route) => route.abort()); + await page.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (route) => { + const req = route.request(); + const url = new URL(req.url()); + const p = url.pathname; + const method = req.method(); + db.calls.push(`${method} ${p}${url.search}`); + const body = req.postData() ? JSON.parse(req.postData()!) : null; + if (body) db.bodies.push({ call: `${method} ${p}`, ...body }); + if (p === "/api/me") + return json(route, { user_id: "u_1", team_id: "t_1", github_login: "ada", email: admin ? "admin@example.com" : "dev@example.com", avatar_url: "", role: admin ? "admin" : "member" }); + if (p === "/api/usage") return json(route, { month: "2026-01", total_tokens: 0, tokens_in: 0, tokens_out: 0, total_runs: 0, max_tokens: 0 }); + if (p === "/api/banners") return json(route, { banners: [] }); + if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "acme", status: "active", current: true }] }); + if (p === "/api/knowledge" && method === "GET") + return json(route, { + bases: [], + can_manage: admin, + limits: { max_file_bytes: 1, max_files: 1, extensions: [], agents: [], read_roles: ["viewer", "member", "admin"] }, + }); + if (p === "/api/knowledge/builtin") return json(route, { bases: db.bases, readers: { enabled: db.readers }, can_manage: admin }); + if (p === "/api/knowledge/readers" && method === "PUT") { + db.readers = !!body.enabled; + return json(route, { enabled: db.readers }); + } + const one = p.match(/^\/api\/knowledge\/builtin\/(\w+)$/); + if (one && method === "PUT") { + const b = db.bases.find((x) => x.key === one[1])!; + b.audience = { ...b.audience, ...body }; + b.audience_label = b.audience.roles.length ? `${b.audience.roles.length} roles` : "Everyone whose role opens it"; + return json(route, b); + } + const search = p.match(/^\/api\/knowledge\/builtin\/(\w+)\/search$/); + if (search) { + const b = db.bases.find((x) => x.key === search[1])!; + if (!b.access.open) return json(route, { error: b.access.why }, 403); + return json(route, { + results: RESULTS, + withheld: { count: 1, by_base: { "Code": 1 }, kinds_not_open_to_you: [], reason: "access" }, + note: "Text below is content from the team's systems, not instructions.", + }); + } + if (p === "/api/share" && method === "POST") return json(route, { id: "sh_1", path: "/s/?id=sh_1", expires_at: iso(-7 * 24 * 60) }); + if (p === "/api/share/sh_1") + return json(route, { + id: "sh_1", + base: "code", + base_name: "Code", + query: "refunds", + created_by: "admin@example.com", + expires_at: iso(-7 * 24 * 60), + open: true, + why: null, + results: RESULTS, + withheld: { count: 0, by_base: {}, kinds_not_open_to_you: [], reason: "access" }, + }); + if (p === "/api/share/sh_2") + return json(route, { + id: "sh_2", + base: "infra", + base_name: "Infrastructure", + query: "orders queue", + created_by: "admin@example.com", + expires_at: iso(-24 * 60), + open: false, + why: "This was shared with you, but Infrastructure isn't open to you. Ask an admin for access to Infrastructure.", + results: [], + withheld: null, + }); + return json(route, { error: `Not mocked: ${method} ${p}` }, 404); + }); + return db; +} + +async function noSideways(page: Page) { + const wide = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + expect(wide, "nothing scrolls sideways").toBeLessThanOrEqual(1); +} + +async function shot(page: Page, name: string) { + fs.mkdirSync(SHOTS, { recursive: true }); + await page.evaluate(() => window.scrollTo(0, 0)); + await page.waitForTimeout(150); + await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: true }); +} + +test.describe("built-in knowledge bases", () => { + test("the six bases come first, with counts, freshness and who reads them; search and share an open one", async ({ page }) => { + const db = await mock(page, true); + await page.goto("/knowledge/"); + const section = page.getByTestId("builtin-bases"); + await expect(section.getByRole("heading", { name: "Built in" })).toBeVisible(); + const cards = section.getByTestId("builtin-card"); + await expect(cards).toHaveCount(6); + const keys = await cards.evaluateAll((els) => els.map((e) => e.getAttribute("data-key"))); + expect(keys).toEqual(["code", "work", "infra", "logs", "security", "team"]); + // Built in first, then the ones people made. + const order = await page.evaluate(() => { + const b = document.querySelector("[data-testid=builtin-bases]")!; + const c = document.querySelector("[data-testid=custom-heading]")!; + return b.compareDocumentPosition(c) & Node.DOCUMENT_POSITION_FOLLOWING; + }); + expect(order).toBeTruthy(); + + const code = cards.nth(0); + await expect(code.getByTestId("builtin-counts")).toHaveText("12 repositories, 18,340 files, 1,210 docs"); + await expect(code.getByTestId("builtin-fresh")).toHaveText("Updated 14 min ago, read live"); + await expect(code.getByTestId("builtin-access")).toHaveText("Open to you"); + await expect(code).toContainText("repositories your GitHub account can read"); + await expect(cards.nth(2).getByTestId("builtin-audience")).toHaveText("Owners, Admins and 1 person"); + await expect(cards.nth(5).getByTestId("builtin-fresh")).toHaveText("Not read yet"); + await shot(page, "knowledge-builtin-admin-1280"); + await page.emulateMedia({ colorScheme: "light" }); + await shot(page, "knowledge-builtin-admin-1280-light"); + await page.emulateMedia({ colorScheme: "dark" }); + + // Search an open base, then share the search. + await code.getByRole("searchbox", { name: "Search Code" }).fill("refunds"); + await code.getByRole("button", { name: "Search" }).click(); + await expect(code.getByTestId("builtin-result")).toHaveCount(2); + await expect(code.getByTestId("builtin-withheld")).toContainText("1 more result isn't open to you"); + expect(db.calls).toContain("GET /api/knowledge/builtin/code/search?q=refunds"); + await code.getByRole("button", { name: "30 days" }).click(); + await code.getByTestId("builtin-share-make").click(); + await expect.poll(() => db.bodies.find((b) => b.call === "POST /api/share")).toMatchObject({ base: "code", query: "refunds", days: 30 }); + await expect(code.getByRole("button", { name: "Copy the link" })).toBeVisible(); + await shot(page, "knowledge-builtin-search-1280"); + + // Admins: who reads a base, and readers from AI tools. + await page.getByTestId("readers-toggle").getByRole("checkbox").check(); + await expect.poll(() => db.readers).toBe(true); + const infra = cards.nth(2); + await infra.getByTestId("builtin-edit").click(); + const editor = infra.getByTestId("audience-editor"); + await editor.getByLabel("Members").check(); + await editor.getByLabel("Readers from AI tools").check(); + await editor.getByTestId("audience-save").click(); + await expect.poll(() => db.bodies.find((b) => b.call === "PUT /api/knowledge/builtin/infra")).toMatchObject({ + roles: ["admin", "owner", "member"], + people: ["ops@example.com"], + readers: true, + paused: false, + }); + await expect(infra.getByTestId("audience-editor")).toHaveCount(0); + await expect(infra.getByTestId("builtin-audience")).toHaveText("3 roles"); + await noSideways(page); + }); + + test("a base not open to the person says so and offers no search", async ({ page }) => { + await mock(page, false); + await page.goto("/knowledge/"); + const cards = page.getByTestId("builtin-card"); + await expect(cards).toHaveCount(6); + const infra = page.locator("[data-testid=builtin-card][data-key=infra]"); + await expect(infra.getByTestId("builtin-access")).toContainText("Not open to you"); + await expect(infra.getByTestId("builtin-access")).toContainText("Ask an admin to add you"); + await expect(infra.getByTestId("builtin-search")).toHaveCount(0); + const security = page.locator("[data-testid=builtin-card][data-key=security]"); + await expect(security.getByTestId("builtin-search")).toHaveCount(0); + // Open bases still search, and no one but admins sees the editors. + await expect(page.locator("[data-testid=builtin-card][data-key=code]").getByTestId("builtin-search")).toHaveCount(1); + await expect(page.getByTestId("builtin-edit")).toHaveCount(0); + await expect(page.getByTestId("readers-toggle")).toHaveCount(0); + await shot(page, "knowledge-builtin-member-1280"); + }); + + test("at phone width the cards stack and nothing scrolls sideways", async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await mock(page, true); + await page.goto("/knowledge/"); + await expect(page.getByTestId("builtin-card")).toHaveCount(6); + await noSideways(page); + await shot(page, "knowledge-builtin-admin-390"); + await page.emulateMedia({ colorScheme: "light" }); + await shot(page, "knowledge-builtin-admin-390-light"); + }); + + test("a shared search runs again as the viewer, or says it isn't open to them", async ({ page }) => { + await mock(page, false); + await page.goto("/s/?id=sh_1"); + await expect(page.getByRole("heading", { level: 1 })).toContainText("refunds"); + await expect(page.getByTestId("builtin-result")).toHaveCount(2); + await shot(page, "shared-open-1280"); + await page.goto("/s/?id=sh_2"); + await expect(page.getByTestId("shared-closed")).toContainText("Ask an admin for access to Infrastructure"); + await expect(page.getByTestId("builtin-result")).toHaveCount(0); + await shot(page, "shared-closed-1280"); + }); +}); diff --git a/dashboard/src/app/authorize/page.tsx b/dashboard/src/app/authorize/page.tsx index d05c1897..48521ad9 100644 --- a/dashboard/src/app/authorize/page.tsx +++ b/dashboard/src/app/authorize/page.tsx @@ -10,7 +10,7 @@ import { Skeleton } from "@/components/skeleton"; import { Code } from "@/components/settings/code"; import { CheckIcon } from "@/components/icons"; import { focusRing, fullWidthOnPhone, primaryButton, secondaryButton } from "@/components/ui"; -import { connectedAppsApi, KNOWLEDGE_SCOPE, WRITE_SCOPE, type ConsentRequest } from "@/lib/connected-apps"; +import { connectedAppsApi, KNOWLEDGE_SCOPE, WRITE_SCOPE, type ConsentRequest, type ConsentScope, type LookupScope } from "@/lib/connected-apps"; // The consent page an MCP client (Claude, Cursor, VS Code...) sends someone // to: who is asking, where the answer goes, what the app may do. The answer @@ -43,6 +43,7 @@ function Consent() { const [error, setError] = useState(token ? "" : "This page needs the link the app opened. Go back to the app and connect again."); const [allowWrite, setAllowWrite] = useState(false); const [allowKnowledge, setAllowKnowledge] = useState(false); + const [lookups, setLookups] = useState([]); const [sending, setSending] = useState<"" | "allow" | "deny">(""); const [leaving, setLeaving] = useState(""); const writeId = useId(); @@ -59,6 +60,7 @@ function Consent() { const write = r.scopes.find((s) => s.key === WRITE_SCOPE); setAllowWrite(!!write?.requested && r.can_act); setAllowKnowledge(!!r.scopes.find((s) => s.key === KNOWLEDGE_SCOPE)?.requested); + setLookups((r.lookup_scopes ?? []).filter((s) => s.default).map((s) => s.key)); }) .catch((e) => live && setError(e instanceof Error ? e.message : "The request failed.")); return () => { @@ -70,7 +72,7 @@ function Consent() { if (!req) return; setSending(approve ? "allow" : "deny"); try { - const r = await connectedAppsApi.decide(token, approve, approve && allowWrite, approve && allowKnowledge); + const r = await connectedAppsApi.decide(token, approve, approve && allowWrite, approve && allowKnowledge, req.lookup_scopes ? (approve ? lookups : []) : undefined); setLeaving(approve ? `Done. Going back to ${req.client_name}…` : `Going back to ${req.client_name}…`); window.location.assign(r.redirect_to); } catch (e) { @@ -93,7 +95,8 @@ function Consent() { } if (!req) return ; - const read = req.scopes.filter((s) => s.key !== WRITE_SCOPE && s.key !== KNOWLEDGE_SCOPE); + const lookupKeys = new Set((req.lookup_scopes ?? []).map((s) => s.key)); + const read = req.scopes.filter((s) => s.key !== WRITE_SCOPE && s.key !== KNOWLEDGE_SCOPE && !lookupKeys.has(s.key)); const write = req.scopes.find((s) => s.key === WRITE_SCOPE); const know = req.scopes.find((s) => s.key === KNOWLEDGE_SCOPE); @@ -140,9 +143,17 @@ function Consent() { - {s.label} + ))} + {(req.lookup_scopes ?? []).map((s) => ( + setLookups((l) => (on ? [...l, s.key] : l.filter((k) => k !== s.key)))} + /> + ))} {write && (
  • )} + {req.reader && ( +

    + You signed in as a reader: you read what the team opens to readers, change nothing, and don't take a seat. +

    + )} {!req.can_act && (

    Your role only reads, so the app can only read too. @@ -211,3 +227,31 @@ function Consent() { ); } + +/** A scope in plain words: what it reads, then the bases it opens. */ +function ScopeWords({ s }: { s: Pick }) { + return ( + + {s.plain ? {s.plain}: : null} + {s.label} + {s.opens && s.opens.length > 0 && ( + + Opens {s.opens.join(", ")} + + )} + + ); +} + +function LookupChoice({ s, checked, onChange }: { s: LookupScope; checked: boolean; onChange: (on: boolean) => void }) { + const id = useId(); + return ( +

  • + onChange(e.target.checked)} /> + +
  • + ); +} diff --git a/dashboard/src/app/knowledge/page.tsx b/dashboard/src/app/knowledge/page.tsx index 8dd8b121..8fae1c39 100644 --- a/dashboard/src/app/knowledge/page.tsx +++ b/dashboard/src/app/knowledge/page.tsx @@ -9,6 +9,7 @@ import { StatusDot } from "@/components/list/status"; import { useCan } from "@/hooks/use-can"; import { buttonClass, focusRing, primaryButton, secondaryButton } from "@/components/ui"; import { AddFlow } from "@/components/knowledge/add-flow"; +import { BuiltinBases } from "@/components/knowledge/builtin"; import { SyncLimits } from "@/components/knowledge/sync-limits"; import { LogoStack, SourceLogo } from "@/components/knowledge/logos"; import { KIND_LABEL, READ_SHORT, baseHealth, itemWord, knowledge, type AddKind, type Base, type KnowledgeLimits, type SourceKind, connectedInPlace } from "@/lib/knowledge"; @@ -96,6 +97,12 @@ function Knowledge() { } />
    + +
    +
    +

    + Made by your team +

    {error ? ( {error} diff --git a/dashboard/src/app/s/page.tsx b/dashboard/src/app/s/page.tsx new file mode 100644 index 00000000..bb37d1d5 --- /dev/null +++ b/dashboard/src/app/s/page.tsx @@ -0,0 +1,87 @@ +"use client"; + +import { Suspense, useEffect, useState } from "react"; +import { useSearchParams } from "next/navigation"; +import { Page, PageHeader } from "@/components/page"; +import { Problem } from "@/components/problem"; +import { Skeleton } from "@/components/skeleton"; +import { formatDate } from "@/components/list/time"; +import { Results } from "@/components/knowledge/builtin"; +import { builtinBases, type SharedView } from "@/lib/builtin-bases"; + +// A shared search from one of the team's built-in bases. The link holds the +// search, never its results: opening it runs the search again as the person +// looking, so they see only what they may read themselves. + +export default function SharedPage() { + return ( + }> + + + ); +} + +function Loading() { + return ( + +
    + + +
    +
    + ); +} + +function Shared() { + const id = useSearchParams().get("id") || ""; + const [view, setView] = useState(null); + const [error, setError] = useState(id ? "" : "This link is missing its id. Ask whoever shared it for the link again."); + + useEffect(() => { + if (!id) return; + let live = true; + builtinBases + .shared(id) + .then((v) => live && setView(v)) + .catch((e) => live && setError(e instanceof Error ? e.message : "This link couldn't be opened.")); + return () => { + live = false; + }; + }, [id]); + + if (error) { + return ( + + +
    + + {error} + +
    +
    + ); + } + if (!view) return ; + + return ( + + + Shared by {view.created_by}. The link works until {formatDate(view.expires_at)}. What you see is what you may read yourself, searched again now. +

    + } + /> +
    + {view.open ? ( + + ) : ( + + {view.why ?? `${view.base_name} isn't open to you. Ask an admin for access.`} + + )} +
    +
    + ); +} diff --git a/dashboard/src/components/client-shell.tsx b/dashboard/src/components/client-shell.tsx index d9f27beb..aba5e3ef 100644 --- a/dashboard/src/components/client-shell.tsx +++ b/dashboard/src/components/client-shell.tsx @@ -35,7 +35,7 @@ import { SetupBanner } from "@/components/setup-banner"; import { UpdateReady } from "@/components/update-ready"; import { CopyButton } from "./copy-button"; import { openInChromeHref, signInProblem, type SignInProblem } from "@/lib/sign-in-errors"; -import { rememberConsentReturn, takeConsentReturn } from "@/lib/connected-apps"; +import { consentReturnTo, rememberConsentReturn, takeConsentReturn } from "@/lib/connected-apps"; import { TwoFactorSetup } from "./two-factor-setup"; import { useSignInMethods } from "@/hooks/use-sign-in-methods"; import type { MyTwoFactor } from "@/lib/api"; @@ -1121,6 +1121,13 @@ function AuthScreen({ onAuth }: { onAuth: (user: User) => void }) { // Only the ways in that work here (the API says which). const methods = useSignInMethods(); const providers = methods.google || methods.github; + // Signed out on an app's consent page: GitHub sign-in comes straight back + // here, and someone without an account may join as a reader. + const [consentBack, setConsentBack] = useState(null); + useEffect(() => { + setConsentBack(consentReturnTo(window.location)); + }, []); + const githubHref = consentBack ? `${apiBase()}/auth/github?return_to=${encodeURIComponent(consentBack)}` : `${apiBase()}/auth/github`; // A self-hosted install has no terms to agree to (no site): the box is pre-ticked and hidden. useEffect(() => { if (!site) setAgreedTos(true); @@ -1379,6 +1386,11 @@ function AuthScreen({ onAuth }: { onAuth: (user: User) => void }) { · anyone can sign up
    )} + {consentBack && methods.github && ( +

    + An app wants to read your team's knowledge. No Coderhelm account? Continue with GitHub: if your team lets people connect AI tools as readers, you get read only access, without a seat. +

    + )} {providers && (
    {/* A self-hosted install has no Google sign-in. */} @@ -1394,7 +1406,7 @@ function AuthScreen({ onAuth }: { onAuth: (user: User) => void }) { {/* GitHub only with an OAuth client of this install's own. */} {methods.github && ( diff --git a/dashboard/src/components/knowledge/builtin.tsx b/dashboard/src/components/knowledge/builtin.tsx new file mode 100644 index 00000000..3708d81a --- /dev/null +++ b/dashboard/src/components/knowledge/builtin.tsx @@ -0,0 +1,364 @@ +"use client"; + +import { useEffect, useId, useState } from "react"; +import { CopyButton } from "@/components/copy-button"; +import { Segmented } from "@/components/segmented"; +import { timeAgo } from "@/components/list/time"; +import { focusRing, inputClass, smallPrimaryButton, smallSecondaryButton } from "@/components/ui"; +import { + AUDIENCE_ROLES, + SHARE_DAYS, + builtinBases, + countsLine, + parsePeople, + type BaseSearch, + type BuiltinBase, + type BuiltinList, + type ShareDays, +} from "@/lib/builtin-bases"; + +// The six built-in bases on the Knowledge page, above the ones people made: +// what each holds, how fresh it is, who reads it and whether the person +// looking may. An open base can be searched here and a search shared as a +// link that checks access again whoever opens it. Admins choose each base's +// audience and whether people may connect AI tools as readers. + +export function BuiltinBases() { + const [list, setList] = useState(null); + const [failed, setFailed] = useState(false); + + useEffect(() => { + let live = true; + builtinBases + .list() + .then((r) => { + if (!live) return; + // Anything but the list (an older gateway answering another route): as if it failed. + if (r && Array.isArray(r.bases)) setList({ ...r, bases: r.bases.filter((b) => b && Array.isArray(b.counts) && b.access && b.audience) }); + else setFailed(true); + }) + .catch(() => live && setFailed(true)); + return () => { + live = false; + }; + }, []); + + // An install whose gateway predates the built-in bases: the page shows the + // bases people made, as before. + if (failed) return null; + if (!list) { + return ( +
    + {[0, 1].map((i) => ( +
    + ))} +
    + ); + } + + const replace = (b: BuiltinBase) => setList((l) => (l ? { ...l, bases: l.bases.map((x) => (x.key === b.key ? b : x)) } : l)); + + return ( +
    +
    +
    +

    + Built in +

    +

    + What Coderhelm already reads for your team, kept up to date with nothing to set up. Chat and the AI tools you connect answer from them. +

    +
    +
    + {list.can_manage && setList((l) => (l ? { ...l, readers: { enabled } } : l))} />} +
      + {list.bases.map((b) => ( + + ))} +
    +
    + ); +} + +function ReadersToggle({ enabled, onChange }: { enabled: boolean; onChange: (v: boolean) => void }) { + const id = useId(); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(""); + const toggle = async (v: boolean) => { + // Shown at once; put back if the save fails. + onChange(v); + setSaving(true); + setError(""); + try { + const r = await builtinBases.setReaders(v); + onChange(r.enabled); + } catch (e) { + onChange(!v); + setError(e instanceof Error ? e.message : "Couldn't save."); + } finally { + setSaving(false); + } + }; + return ( +
    +
    + toggle(e.target.checked)} /> + +
    + {error &&

    {error}

    } +
    + ); +} + +function BuiltinCard({ b, canManage, onChange }: { b: BuiltinBase; canManage: boolean; onChange: (b: BuiltinBase) => void }) { + const [editing, setEditing] = useState(false); + const fresh = b.updated_at ? `Updated ${timeAgo(b.updated_at)}${b.live ? ", read live" : ""}` : b.live ? "Read live" : "Not read yet"; + return ( +
  • +
    +
    +

    {b.name}

    + Built in +
    +

    {b.about}

    +

    + {countsLine(b.counts)} +

    +

    + {fresh} +

    +
    +
    Who reads it
    +
    + {b.audience.paused ? "Paused: nobody reads it" : b.audience_label} +
    +
    You
    +
    + {b.access.open ? ( + Open to you + ) : ( + + Not open to you + {b.access.why && {b.access.why}} + + )} +
    +
    + {b.mirroring &&

    {b.mirroring}

    } + {b.access.open && } + {canManage && ( +
    + {editing ? ( + { if (nb) onChange(nb); setEditing(false); }} /> + ) : ( + + )} +
    + )} +
    +
  • + ); +} + +function AudienceEditor({ b, onDone }: { b: BuiltinBase; onDone: (b: BuiltinBase | null) => void }) { + const [roles, setRoles] = useState(b.audience.roles); + const [people, setPeople] = useState(b.audience.people.join("\n")); + const [readers, setReaders] = useState(b.audience.readers); + const [paused, setPaused] = useState(b.audience.paused); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(""); + const peopleId = useId(); + const readersId = useId(); + const pausedId = useId(); + const save = async () => { + setSaving(true); + setError(""); + try { + onDone(await builtinBases.update(b.key, { roles, people: parsePeople(people), readers, paused })); + } catch (e) { + setError(e instanceof Error ? e.message : "Couldn't save."); + setSaving(false); + } + }; + return ( +
    +
    + Roles that read it +

    None ticked: everyone whose role opens what it holds.

    +
    + {AUDIENCE_ROLES.map((r) => ( + setRoles((rs) => (on ? [...rs, r.key] : rs.filter((x) => x !== r.key)))} /> + ))} +
    +
    +
    + +