diff --git a/dashboard/e2e/knowledge-bedrock.spec.ts b/dashboard/e2e/knowledge-bedrock.spec.ts new file mode 100644 index 00000000..9e562347 --- /dev/null +++ b/dashboard/e2e/knowledge-bedrock.spec.ts @@ -0,0 +1,252 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; + +// A Bedrock knowledge base connected in place: the tile in the add flow, +// pasting an ARN (hosted) or picking one of the install's own (self-hosted), +// the test search's failures in plain words (with the one-click grant), and +// the base page that says it is searched live and holds no files. Every API +// call is answered here; nothing reaches a real backend or AWS. + +const ARN = "arn:aws:bedrock:us-east-1:111122223333:knowledge-base/ABCDE12345"; +const OWN_ARN = "arn:aws:bedrock:us-east-1:444455556666:knowledge-base/RUNBOOKS01"; + +const LIMITS = { + max_file_bytes: 25 * 1024 * 1024, + max_files: 500, + extensions: ["pdf", "md"], + agents: [{ key: "coder", label: "Coder" }], + read_roles: ["viewer", "member", "admin"], +}; + +interface Mock { + /** A self-hosted install listing its own account. */ + install: boolean; + /** What each POST /api/knowledge with `connect` answers, in turn. */ + answers: { status: number; body: Record }[]; + /** What a connection check answers. */ + check: { status: number; body: Record }; + bases: Record[]; + bodies: Record[]; + calls: string[]; +} + +const remoteBase = (over: Record = {}) => ({ + id: "kb_aws", + name: "Runbooks in AWS", + description: "", + read_role: "viewer", + attach_team: true, + agents: [], + authoritative: false, + created_at: "2026-11-08T10:00:00Z", + updated_at: "2026-11-08T10:00:00Z", + files: 0, + ready: 0, + processing: 0, + failed: 0, + uploads: 0, + synced: 0, + kinds: [], + sources: [], + backend: { kind: "remote", provider: "bedrock_kb", label: "Bedrock knowledge base", target: ARN, region: "us-east-1", account: "111122223333", access: "account", hybrid: true }, + ...over, +}); + +async function mockApi(page: Page, init: Partial = {}): Promise { + const db: Mock = { + install: false, + answers: [], + check: { status: 200, body: { ok: true, hybrid: true, checked_at: "2026-11-08T10:05:00Z" } }, + bases: [], + bodies: [], + calls: [], + ...init, + }; + 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}`); + 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: null, email: "admin@example.com", avatar_url: "", role: "admin" }); + if (p === "/api/usage") return json(route, { month: "2026-11", 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: db.bases, can_manage: true, limits: LIMITS }); + if (p === "/api/knowledge" && method === "POST") { + const a = db.answers.shift() ?? { status: 200, body: {} }; + if (a.status !== 200) return json(route, a.body, a.status); + const b = remoteBase({ name: body.name, ...(db.install ? { backend: { ...remoteBase().backend, target: OWN_ARN, account: "444455556666", access: "install" } } : {}) }); + db.bases.push(b); + return json(route, { base: b, source: null, setup: null }); + } + if (p === "/api/knowledge/bedrock") { + return json(route, { + install: db.install, + install_account: db.install ? "444455556666" : "", + region: "us-east-1", + bases: db.install + ? [ + { arn: OWN_ARN, id: "RUNBOOKS01", name: "Ops runbooks", description: "On-call and incident runbooks", status: "ACTIVE", updated_at: "2026-11-01T00:00:00Z" }, + { arn: "arn:aws:bedrock:us-east-1:444455556666:knowledge-base/POLICIES01", id: "POLICIES01", name: "Policies", description: "", status: "ACTIVE", updated_at: "2026-10-01T00:00:00Z" }, + ] + : null, + list_error: null, + accounts: db.install ? [] : [{ account: "111122223333", region: "us-east-1" }], + connected: db.bases.map((b) => (b.backend as { target: string }).target), + }); + } + if (p === "/api/knowledge/connectors") return json(route, { connectors: [], visibility_note: "" }); + const one = p.match(/^\/api\/knowledge\/([^/]+)$/); + if (one && method === "GET") { + const b = db.bases.find((x) => x.id === one[1]); + if (!b) return json(route, { error: "No such knowledge base." }, 404); + return json(route, { base: b, files: [], sources: [], can_manage: true, limits: LIMITS, visibility_note: "" }); + } + if (/^\/api\/knowledge\/[^/]+\/check$/.test(p)) return json(route, db.check.body, db.check.status); + return json(route, { error: `Not mocked: ${method} ${p}` }, 404); + }); + return db; +} + +test.describe("a Bedrock knowledge base, connected in place", () => { + test("hosted: paste the ARN, the role's refusal comes back in plain words with the grant, then it connects", async ({ page }) => { + const db = await mockApi(page, { + answers: [ + { + status: 400, + body: { + error: "The role in your account does not allow Retrieve on this knowledge base.", + fix: "Give the role bedrock:Retrieve and bedrock:GetDocumentContent on this knowledge base (the CoderHelmLogReader update does it), then try again.", + code: "access", + grant: { url: "https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/quickcreate?stackName=CoderHelmLogReaderUpdate-abcd1234-kb0a1b2c", stack_name: "CoderHelmLogReaderUpdate-abcd1234-kb0a1b2c", account: "111122223333" }, + }, + }, + ], + }); + await page.goto("/knowledge/"); + await page.getByTestId("start-knowledge").click(); + const flow = page.getByTestId("add-flow"); + const tile = flow.getByTestId("tile-bedrock_kb"); + await expect(tile).toContainText("Bedrock knowledge base"); + await expect(tile).toContainText("searched live in your AWS account, nothing copied"); + await tile.click(); + await expect(page.getByTestId("flow-step")).toHaveAttribute("data-step", "bedrock"); + // Hosted: nothing to list, the ARN is pasted. + await expect(flow.getByTestId("bedrock-list")).toHaveCount(0); + const input = flow.getByTestId("bedrock-arn"); + await input.fill("arn:aws:bedrock:us-east-1:111122223333:agent/ABCDE12345"); + await expect(flow.getByTestId("bedrock-arn-bad")).toContainText("That isn't a knowledge base ARN"); + await expect(page.getByTestId("flow-continue")).toBeDisabled(); + // An account nobody connected is said before anything is sent. + await input.fill("arn:aws:bedrock:us-east-1:999988887777:knowledge-base/ABCDE12345"); + await expect(flow.getByTestId("bedrock-account-missing")).toContainText("AWS account 999988887777 isn't connected"); + await input.fill(ARN); + await expect(flow.getByTestId("bedrock-account-missing")).toHaveCount(0); + await page.getByTestId("flow-continue").click(); + + await expect(page.getByTestId("connect-summary")).toContainText("Connected in place: searched live in your AWS account, nothing copied."); + await expect(page.getByTestId("visibility-note")).toContainText("sees what a search of it returns"); + await page.getByTestId("flow-name").fill("Runbooks in AWS"); + await page.getByTestId("flow-finish").click(); + const problem = page.getByTestId("connect-problem"); + await expect(problem).toHaveAttribute("data-code", "access"); + await expect(problem).toContainText("The role in your account does not allow Retrieve on this knowledge base."); + await expect(problem.getByTestId("connect-grant")).toHaveAttribute("href", /stackName=CoderHelmLogReaderUpdate-abcd1234-kb0a1b2c/); + await expect(problem).toContainText("Sign in to AWS account 111122223333"); + const sent = db.bodies.find((b) => b.call === "POST /api/knowledge")!; + expect(sent.connect).toEqual({ provider: "bedrock_kb", target: ARN }); + expect(sent.source).toBeUndefined(); + + // After the update stack, connecting again works and opens the base. + await page.getByTestId("flow-finish").click(); + await expect(page).toHaveURL(/\/knowledge\/base\/\?id=kb_aws/); + await expect(page.getByTestId("connected-line")).toHaveText("Connected in place: searched live in your AWS account, nothing copied"); + }); + + test("self-hosted: the install's own knowledge bases are listed, and an unapplied access stack is said plainly", async ({ page }) => { + await mockApi(page, { + install: true, + answers: [ + { + status: 400, + body: { + error: "This install's permission limit doesn't allow searching Bedrock knowledge bases yet: the release that searches them needs a permission change an AWS admin hasn't applied.", + fix: "An AWS admin applies the pending permission change: Settings, System, Version, Permissions (one link to the AWS console). Nothing else waits on it.", + code: "boundary", + grant: null, + }, + }, + ], + }); + await page.goto("/knowledge/"); + await page.getByTestId("start-knowledge").click(); + await page.getByTestId("tile-bedrock_kb").click(); + const list = page.getByTestId("bedrock-list"); + await expect(list).toContainText("In this install's account (us-east-1)"); + await expect(list.getByTestId("bedrock-option")).toHaveCount(2); + await list.getByTestId("bedrock-option").filter({ hasText: "Ops runbooks" }).click(); + await expect(page.getByTestId("bedrock-arn")).toHaveValue(OWN_ARN); + await page.getByTestId("flow-continue").click(); + // Named after the knowledge base picked. + await expect(page.getByTestId("flow-name")).toHaveValue("Ops runbooks"); + await page.getByTestId("flow-finish").click(); + const problem = page.getByTestId("connect-problem"); + await expect(problem).toHaveAttribute("data-code", "boundary"); + await expect(problem).toContainText("an AWS admin hasn't applied"); + await expect(problem).toContainText("Settings, System, Version, Permissions"); + await expect(problem.getByTestId("connect-grant")).toHaveCount(0); + }); + + test("the base page: searched live, no files, no adding, and a connection check", async ({ page }) => { + const db = await mockApi(page, { bases: [remoteBase()] }); + await page.goto("/knowledge/"); + await expect(page.getByTestId("knowledge-size")).toHaveText("Connected in place, searched live in AWS"); + await page.goto("/knowledge/base/?id=kb_aws"); + const card = page.getByTestId("connected-in-place"); + await expect(card.getByTestId("connected-line")).toHaveText("Connected in place: searched live in your AWS account, nothing copied"); + await expect(card.getByTestId("connected-arn")).toHaveText(ARN); + await expect(card.getByTestId("connected-access")).toContainText("CoderHelmLogReader role in that account, with your team's private ID"); + // No file list, no uploads, no adding apps. + await expect(page.getByTestId("items")).toHaveCount(0); + await expect(page.getByTestId("items-empty")).toHaveCount(0); + await expect(page.getByTestId("uploads-card")).toHaveCount(0); + await expect(page.getByTestId("add-source")).toHaveCount(0); + await expect(page.getByTestId("upload-input")).toHaveCount(0); + + await card.getByTestId("check-connection").click(); + await expect(card.getByTestId("check-ok")).toContainText("The connection works."); + expect(db.calls).toContain("POST /api/knowledge/kb_aws/check"); + // A check that fails says why and what to do. + db.check = { status: 400, body: { error: "The role in your account does not allow Retrieve on this knowledge base.", fix: "Give the role bedrock:Retrieve.", code: "access", grant: null } }; + await card.getByTestId("check-connection").click(); + await expect(card.getByTestId("connect-problem")).toContainText("does not allow Retrieve on this knowledge base"); + }); + + test("adding to an existing knowledge base never offers Bedrock (it is a whole base, connected in place)", async ({ page }) => { + await mockApi(page, { + bases: [{ ...remoteBase(), id: "kb_local", name: "Handbook", backend: { kind: "local" } }], + }); + await page.goto("/knowledge/base/?id=kb_local"); + await page.getByTestId("add-source").click(); + await expect(page.getByTestId("choose-step")).toBeVisible(); + await expect(page.getByTestId("tile-bedrock_kb")).toHaveCount(0); + }); + + test("phone width: the connected page and the ARN step never scroll sideways", async ({ page }) => { + await page.setViewportSize({ width: 375, height: 800 }); + await mockApi(page, { bases: [remoteBase()] }); + await page.goto("/knowledge/base/?id=kb_aws"); + await expect(page.getByTestId("connected-in-place")).toBeVisible(); + const over = () => page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + expect(await over()).toBeLessThanOrEqual(0); + await page.goto("/knowledge/"); + await page.getByTestId("new-knowledge").click(); + await page.getByTestId("tile-bedrock_kb").click(); + await page.getByTestId("bedrock-arn").fill(ARN); + expect(await over()).toBeLessThanOrEqual(0); + }); +}); diff --git a/dashboard/src/app/knowledge/base/page.tsx b/dashboard/src/app/knowledge/base/page.tsx index 5a63e502..7ac874db 100644 --- a/dashboard/src/app/knowledge/base/page.tsx +++ b/dashboard/src/app/knowledge/base/page.tsx @@ -5,11 +5,12 @@ import { useRouter, useSearchParams } from "next/navigation"; import { Page, PageHeader, Section } from "@/components/page"; import { Chip, ListError, MoreMenu } from "@/components/list"; import { Modal } from "@/components/modal"; +import { Code } from "@/components/settings/code"; import { useConfirm } from "@/components/confirm-dialog"; import { useToast } from "@/components/toast"; import { useCan } from "@/hooks/use-can"; import { buttonClass, focusRing, inputClass, linkButton, primaryButton, secondaryButton } from "@/components/ui"; -import { AddFlow } from "@/components/knowledge/add-flow"; +import { AddFlow, ConnectProblemNote } from "@/components/knowledge/add-flow"; import { SourceLogo } from "@/components/knowledge/logos"; import { Picker } from "@/components/knowledge/picker"; import { SourceCard } from "@/components/knowledge/source-card"; @@ -17,6 +18,8 @@ import { errorMessage } from "@/lib/data-sources"; import { KIND_LABEL, READ_SENTENCE, + connectProblem, + connectedInPlace, fileSize, itemWord, knowledge, @@ -27,6 +30,7 @@ import { type AddKind, type Base, type BaseInput, + type ConnectProblem, type Item, type KnowledgeLimits, type Selected, @@ -38,6 +42,10 @@ import { BaseForm } from "../base-form"; // One knowledge base: the apps it stays in sync with (each with whether it // is up to date and the one thing to do when it isn't), its uploaded files, // and every page in it with a search box. Drop files anywhere to add them. +// +// A base connected in place (a Bedrock knowledge base) has no files here: it +// says so, where it lives and how it is reached, and can check its +// connection with one test search. export default function BasePage() { return ( @@ -63,6 +71,8 @@ function BaseView() { const { confirm } = useConfirm(); const { can } = useCan(); const canManage = can("knowledge_manage"); + const [checking, setChecking] = useState(false); + const [checked, setChecked] = useState<{ ok: true; at: string } | { ok: false; problem: ConnectProblem } | null>(null); const [base, setBase] = useState(null); const [items, setItems] = useState(null); const [sources, setSources] = useState([]); @@ -272,11 +282,25 @@ function BaseView() { } }; + const checkConnection = async () => { + setChecking(true); + try { + const r = await knowledge.check(id); + setChecked({ ok: true, at: r.checked_at }); + } catch (e) { + setChecked({ ok: false, problem: connectProblem(e, "Couldn't check the connection.") }); + } finally { + setChecking(false); + } + }; + const removeBase = async () => { if (!base) return; const ok = await confirm({ title: `Delete ${base.name}?`, - message: "Everything in it is removed from Coderhelm. Nothing changes in the apps it came from. This can't be undone.", + message: connectedInPlace(base) + ? "It is disconnected from Coderhelm: Chat and the agents stop searching it. Nothing changes in your AWS account." + : "Everything in it is removed from Coderhelm. Nothing changes in the apps it came from. This can't be undone.", confirmLabel: "Delete knowledge base", destructive: true, }); @@ -325,6 +349,9 @@ function BaseView() { ); }, [items, q, filter]); const uploadsCount = (items ?? []).filter((f) => !f.source_id).length; + const inPlace = connectedInPlace(base); + // Files go only to bases kept here. + const canUpload = canManage && !inPlace; if (error && !base) { return ( @@ -342,17 +369,17 @@ function BaseView() { const onDrop = (e: React.DragEvent) => { e.preventDefault(); setDragging(false); - if (canManage) upload(Array.from(e.dataTransfer.files)); + if (canUpload) upload(Array.from(e.dataTransfer.files)); }; return (
{ - if (canManage && e.dataTransfer.types.includes("Files")) setDragging(true); + if (canUpload && e.dataTransfer.types.includes("Files")) setDragging(true); }} onDragOver={(e) => { - if (canManage) e.preventDefault(); + if (canUpload) e.preventDefault(); }} onDragLeave={(e) => { if (e.currentTarget === e.target) setDragging(false); @@ -367,7 +394,7 @@ function BaseView() { status={base?.authoritative ? Source of truth : undefined} lead={base?.description || undefined} actions={ - canManage ? ( + canUpload ? ( @@ -377,8 +404,8 @@ function BaseView() { canManage ? [ { label: "Settings", onSelect: () => setSettings(true) }, - { label: "Upload files", onSelect: () => fileRef.current?.click() }, - { label: "Delete knowledge base", onSelect: removeBase, danger: true }, + ...(inPlace ? [] : [{ label: "Upload files", onSelect: () => fileRef.current?.click() }]), + { label: inPlace ? "Disconnect knowledge base" : "Delete knowledge base", onSelect: removeBase, danger: true }, ] : undefined } @@ -394,6 +421,8 @@ function BaseView() {

)} + {!inPlace && ( + <> + + )} {problems.length > 0 && (
@@ -433,6 +464,14 @@ function BaseView() {
)} + {inPlace && ( +
+ +
+ )} + + {!inPlace && ( + <>
    {sources.map((s) => ( @@ -569,6 +608,8 @@ function BaseView() { )}
+ + )} {dragging && (
@@ -581,7 +622,7 @@ function BaseView() { )}
- {canManage && base && ( + {canUpload && base && ( { @@ -645,6 +686,70 @@ function BaseView() { ); } +/** A base connected in place: where it lives, how it is reached, and a check of the connection. */ +function ConnectedCard({ + base, + canManage, + checking, + checked, + onCheck, +}: { + base: Base & { backend: Extract, { kind: "remote" }> }; + canManage: boolean; + checking: boolean; + checked: { ok: true; at: string } | { ok: false; problem: ConnectProblem } | null; + onCheck: () => void; +}) { + const b = base.backend; + return ( +
+
+ +
+

{b.label}

+

+ Connected in place: searched live in your AWS account, nothing copied +

+
+
+
+
Knowledge base
+
+ {b.target} +
+
Where
+
+ AWS account {b.account}, {b.region} +
+
Searched with
+
+ {b.access === "install" + ? "This install's own role, read-only" + : "The CoderHelmLogReader role in that account, with your team's private ID, read-only"} +
+
Search
+
{b.hybrid ? "Hybrid: meaning and exact words" : "By meaning (this vector store has no keyword search)"}
+
+

+ Chat and the agents it is attached to search it whenever they need it, so documents you add in Bedrock count as soon as Bedrock has them. Nothing is stored here, and deleting it here changes nothing in AWS. +

+ {canManage && ( +
+ + {checked?.ok && ( +

+ Searched it just now. The connection works. +

+ )} + {checked && !checked.ok && } +
+ )} +
+ ); +} + function ItemRow({ f, kind, canManage, onReplace, onDelete }: { f: Item; kind: AddKind; canManage: boolean; onReplace: () => void; onDelete: () => void }) { const failed = f.status === "failed"; const working = f.status === "processing" || f.status === "uploading"; diff --git a/dashboard/src/app/knowledge/page.tsx b/dashboard/src/app/knowledge/page.tsx index cc0cf884..d6fa0ae3 100644 --- a/dashboard/src/app/knowledge/page.tsx +++ b/dashboard/src/app/knowledge/page.tsx @@ -10,7 +10,7 @@ import { useCan } from "@/hooks/use-can"; import { buttonClass, focusRing, primaryButton } from "@/components/ui"; import { AddFlow } from "@/components/knowledge/add-flow"; import { LogoStack, SourceLogo } from "@/components/knowledge/logos"; -import { KIND_LABEL, READ_SHORT, baseHealth, itemWord, knowledge, type AddKind, type Base, type KnowledgeLimits, type SourceKind } from "@/lib/knowledge"; +import { KIND_LABEL, READ_SHORT, baseHealth, itemWord, knowledge, type AddKind, type Base, type KnowledgeLimits, type SourceKind, connectedInPlace } from "@/lib/knowledge"; // Knowledge: what the team's answers come from. Each knowledge base holds // pages from the apps the team already uses (kept up to date on their own) @@ -161,8 +161,9 @@ function Empty({ canManage, onStart }: { canManage: boolean; onStart: (k?: AddKi function BaseCard({ b }: { b: Base }) { const health = baseHealth(b); - // Apps first, uploads last. - const kinds = b.kinds?.length ? [...b.kinds.filter((k) => k !== "upload"), ...b.kinds.filter((k) => k === "upload")] : ["upload"]; + const inPlace = connectedInPlace(b); + // Apps first, uploads last; a base connected in place shows where it lives. + const kinds = inPlace ? ["bedrock_kb"] : b.kinds?.length ? [...b.kinds.filter((k) => k !== "upload"), ...b.kinds.filter((k) => k === "upload")] : ["upload"]; const apps = kinds.filter((k) => k !== "upload"); const size = [(b.synced ?? 0) ? itemWord(apps.length === 1 ? apps[0] : "page", b.synced) : "", b.uploads ? itemWord("upload", b.uploads) : ""].filter(Boolean).join(" and "); return ( @@ -179,7 +180,7 @@ function BaseCard({ b }: { b: Base }) {

{b.name}

{b.description &&

{b.description}

}
-

{size || "Nothing in it yet"}

+

{inPlace ? "Connected in place, searched live in AWS" : size || "Nothing in it yet"}

{health && (

diff --git a/dashboard/src/components/knowledge/add-flow.tsx b/dashboard/src/components/knowledge/add-flow.tsx index de673f2d..66cc7fef 100644 --- a/dashboard/src/components/knowledge/add-flow.tsx +++ b/dashboard/src/components/knowledge/add-flow.tsx @@ -8,8 +8,10 @@ import { Select } from "@/components/select"; import { buttonClass, focusRing, inputClass, linkButton, primaryButton, secondaryButton } from "@/components/ui"; import { errorMessage } from "@/lib/data-sources"; import { + KB_ARN, KIND_LABEL, READ_SENTENCE, + connectProblem, fileSize, itemWord, knowledge, @@ -21,6 +23,8 @@ import { uploadToSignedUrl, type AddKind, type Base, + type BedrockStart, + type ConnectProblem, type Connector, type Item, type KnowledgeLimits, @@ -52,8 +56,13 @@ import { AskAdmin, ConfluenceSteps, ConnectLoading, IntegrationsLink, NoTokenPat // on this install, Notion and Confluence connect with a pasted token right // here (admins and owners), and Google Drive says its sign-in isn't set up // and who can set it up (with the steps for a platform admin). +// +// A Bedrock knowledge base is connected in place, only as a new knowledge +// base: paste its ARN (a self-hosted install also lists its own account's), +// name it, and one test search runs before anything is saved. It is then +// searched live in the team's AWS account; nothing is copied. -type Step = "choose" | "connect" | "pick" | "upload" | "name" | "progress"; +type Step = "choose" | "connect" | "pick" | "upload" | "bedrock" | "name" | "progress"; export type FlowMode = { kind: "create" } | { kind: "add"; base: Base }; @@ -116,6 +125,9 @@ export function AddFlow({ /** An app was chosen before the connections loaded: decide its step when they arrive. */ const [deciding, setDeciding] = useState(false); const [tokenNote, setTokenNote] = useState(""); + const [arn, setArn] = useState(""); + const [arnName, setArnName] = useState(""); + const [problem, setProblem] = useState(null); const { can, me } = useCan(); const canSaveToken = can("integrations"); const installAdmin = me?.platform_admin === true; @@ -129,9 +141,9 @@ export function AddFlow({ setSeenKey(openKey); if (openKey !== null) { const first = startWith ?? null; - setStep(first === null ? "choose" : first === "upload" ? "upload" : "connect"); + setStep(first === null ? "choose" : first === "upload" ? "upload" : first === "bedrock_kb" ? "bedrock" : "connect"); setKind(first); - setDeciding(first !== null && first !== "upload"); + setDeciding(first !== null && first !== "upload" && first !== "bedrock_kb"); setConnectors(null); setLoadError(null); setPicked([]); @@ -146,6 +158,9 @@ export function AddFlow({ setVia("team"); setWaiting(false); setTokenNote(""); + setArn(""); + setArnName(""); + setProblem(null); } } @@ -182,7 +197,7 @@ export function AddFlow({ // Chosen while loading: go on once the connections are here. useEffect(() => { - if (!deciding || !connectors || !kind || kind === "upload") return; + if (!deciding || !connectors || !kind || kind === "upload" || kind === "bedrock_kb") return; setDeciding(false); setStep(stepFor(connectors.find((x) => x.kind === kind))); // eslint-disable-next-line react-hooks/exhaustive-deps @@ -197,6 +212,11 @@ export function AddFlow({ setStep("upload"); return; } + if (k === "bedrock_kb") { + setProblem(null); + setStep("bedrock"); + return; + } setVia("team"); // The app's own step at once; a placeholder there until we know which. if (!connectors) { @@ -217,7 +237,7 @@ export function AddFlow({ // Signs in with your own account in a small window, then shows who you're // connected as. The flow stays where it is. const memberSignIn = async () => { - if (!kind || kind === "upload") return; + if (!kind || kind === "upload" || kind === "bedrock_kb") return; setError(null); setWaiting(true); try { @@ -243,7 +263,7 @@ export function AddFlow({ }; const signIn = async () => { - if (!kind || kind === "upload") return; + if (!kind || kind === "upload" || kind === "bedrock_kb") return; setBusy(true); setError(null); try { @@ -259,10 +279,34 @@ export function AddFlow({ const afterPick = () => { if (!kind) return; - if (!named) setName(suggestName(kind, picked, files.map((f) => f.file))); + if (!named) setName(kind === "bedrock_kb" ? arnName || KIND_LABEL.bedrock_kb : suggestName(kind, picked, files.map((f) => f.file))); + setProblem(null); setStep("name"); }; + // Connected in place: one test search, then the base exists and opens. + const connectBedrock = async () => { + setBusy(true); + setProblem(null); + try { + const r = await knowledge.create({ + name: name.trim() || arnName || KIND_LABEL.bedrock_kb, + description: "", + read_role: readRole, + attach_team: true, + agents: [], + authoritative: false, + connect: { provider: "bedrock_kb", target: arn.trim() }, + }); + onOpenChange(false); + onDone(r.base.id); + } catch (e) { + setProblem(connectProblem(e, "That didn't work. Try again.")); + } finally { + setBusy(false); + } + }; + const addFiles = (list: File[]) => { const bad: string[] = []; const ok: LocalUpload[] = []; @@ -290,6 +334,7 @@ export function AddFlow({ const finish = async () => { if (!kind) return; + if (kind === "bedrock_kb") return connectBedrock(); setBusy(true); setError(null); try { @@ -333,10 +378,12 @@ export function AddFlow({ ? deciding ? label : `Connect ${label}` - : step === "pick" && kind && kind !== "upload" + : step === "pick" && kind && kind !== "upload" && kind !== "bedrock_kb" ? PICK_TITLE[kind] : step === "upload" ? "Upload files" + : step === "bedrock" + ? "Connect a Bedrock knowledge base" : step === "name" ? creating ? "Name your knowledge base" @@ -352,7 +399,8 @@ export function AddFlow({ const back = () => { setError(null); setDeciding(false); - if (step === "name") setStep(kind === "upload" ? "upload" : "pick"); + setProblem(null); + if (step === "name") setStep(kind === "upload" ? "upload" : kind === "bedrock_kb" ? "bedrock" : "pick"); else if (step === "pick" && conn?.member_sign_in) setStep("connect"); else setStep("choose"); }; @@ -373,9 +421,14 @@ export function AddFlow({ Continue )} + {step === "bedrock" && ( + + )} {step === "name" && ( )}

@@ -385,12 +438,12 @@ export function AddFlow({
{step === "choose" && ( - choose(k)} /> + choose(k)} creating={creating} /> )} - {step === "connect" && kind && kind !== "upload" && deciding && } + {step === "connect" && kind && kind !== "upload" && kind !== "bedrock_kb" && deciding && } - {step === "connect" && kind && kind !== "upload" && !deciding && conn?.member_sign_in && ( + {step === "connect" && kind && kind !== "upload" && kind !== "bedrock_kb" && !deciding && conn?.member_sign_in && ( )} - {step === "connect" && kind && kind !== "upload" && !deciding && !conn?.member_sign_in && ( + {step === "connect" && kind && kind !== "upload" && kind !== "bedrock_kb" && !deciding && !conn?.member_sign_in && ( )} - {step === "pick" && kind && kind !== "upload" && tokenNote && ( + {step === "pick" && kind && kind !== "upload" && kind !== "bedrock_kb" && tokenNote && (

{tokenNote}

)} - {step === "pick" && kind && kind !== "upload" && } + {step === "pick" && kind && kind !== "upload" && kind !== "bedrock_kb" && } + + {step === "bedrock" && ( + { + setArn(v); + setArnName(listedName ?? ""); + setNamed(false); + }} + /> + )} {step === "upload" && setFiles((f) => f.filter((x) => x.key !== k))} error={error} />} @@ -430,10 +494,19 @@ export function AddFlow({
-

- {kind === "upload" - ? `${files.length} file${files.length === 1 ? "" : "s"} to upload` - : `${picked.length} ${picked.length === 1 ? "item" : "items"} from ${label}${picked.some((p) => p.include_children) && kind !== "web" ? ", with everything inside" : ""}`} +

+ {kind === "bedrock_kb" ? ( + + Connected in place: searched live in your AWS account, nothing copied. + + {arn.trim()} + + + ) : kind === "upload" ? ( + `${files.length} file${files.length === 1 ? "" : "s"} to upload` + ) : ( + `${picked.length} ${picked.length === 1 ? "item" : "items"} from ${label}${picked.some((p) => p.include_children) && kind !== "web" ? ", with everything inside" : ""}` + )}

{creating && ( @@ -479,7 +552,7 @@ export function AddFlow({ )}
)} - {via === "sign_in" && kind !== "upload" && ( + {via === "sign_in" && kind !== "upload" && kind !== "bedrock_kb" && (

It stays up to date through your {label} sign-in, checking for changes every 15 minutes. If your sign-in stops working, any admin can sign in again.

@@ -490,7 +563,11 @@ export function AddFlow({ - {note || "Everyone who can read this knowledge base can read what you add, even if they can't open it in the app it comes from."} + + {kind === "bedrock_kb" + ? "Everyone who can read this knowledge base sees what a search of it returns, even documents they couldn't open where they came from. Agents it is attached to search it for anyone who starts a run." + : note || "Everyone who can read this knowledge base can read what you add, even if they can't open it in the app it comes from."} +

)} {error && ( @@ -498,6 +575,7 @@ export function AddFlow({ {error}

)} + {problem && }
)} @@ -523,11 +601,14 @@ function ChooseStep({ loadError, onRetry, onChoose, + creating, }: { connectors: Connector[] | null; loadError: string | null; onRetry: () => void; onChoose: (k: AddKind) => void; + /** A new knowledge base: it can also be a Bedrock one, connected in place. */ + creating: boolean; }) { return (
@@ -579,6 +660,146 @@ function ChooseStep({ PDF, Word, Markdown, text, spreadsheets or web pages + {creating && ( + + )} +
+ ); +} + +/** Paste a knowledge base's ARN, or (self-hosted) pick one of the install account's. */ +function BedrockStep({ arn, onArn }: { arn: string; onArn: (arn: string, listedName?: string) => void }) { + const [start, setStart] = useState(null); + const [loadError, setLoadError] = useState(null); + useEffect(() => { + let stop = false; + knowledge + .bedrock() + .then((r) => !stop && setStart(r)) + .catch((e) => !stop && setLoadError(errorMessage(e, "Couldn't load your AWS accounts."))); + return () => { + stop = true; + }; + }, []); + const trimmed = arn.trim(); + const bad = trimmed !== "" && !KB_ARN.test(trimmed); + const taken = !!start?.connected.includes(trimmed); + const account = KB_ARN.test(trimmed) ? trimmed.split(":")[4] : ""; + const reachable = !account || account === start?.install_account || !!start?.accounts.some((a) => a.account === account); + return ( +
+

+ Coderhelm searches the knowledge base live in your AWS account whenever Chat or an agent needs it. Nothing is copied, and Bedrock does its own search, so its embedding model and vector store don't matter. +

+ {start?.install && ( +
+

In this install's account ({start.region})

+ {start.bases === null ? ( + start.list_error && ( +

+ {start.list_error.message} {start.list_error.fix} +

+ ) + ) : start.bases.length === 0 ? ( +

+ No knowledge bases in this account and region. Paste the ARN of one elsewhere below. +

+ ) : ( +
    + {start.bases.map((b) => { + const on = trimmed === b.arn; + const used = start.connected.includes(b.arn); + return ( +
  • + +
  • + ); + })} +
+ )} +
+ )} + + {bad && ( +

+ That isn't a knowledge base ARN. It looks like arn:aws:bedrock:us-east-1:111122223333:knowledge-base/ABCDE12345. +

+ )} + {taken && ( +

+ That knowledge base is already connected. +

+ )} + {start && !reachable && ( +

+ AWS account {account} isn't connected to Coderhelm. Connect it on{" "} + + Integrations, AWS + {" "} + first: Coderhelm searches with that account's read-only CoderHelmLogReader role and your team's private ID. +

+ )} + {loadError &&

{loadError}

} +
+ ); +} + +/** Why connecting failed, what to do, and the update that grants the role access when that is all it lacks. */ +export function ConnectProblemNote({ problem }: { problem: ConnectProblem }) { + return ( +
+

{problem.message}

+ {problem.fix &&

{problem.fix}

} + {problem.grant && ( +
+ + Open the update in AWS + +

+ Sign in to AWS account {problem.grant.account} and create the stack {problem.grant.stack_name}. It lets the CoderHelmLogReader role search this knowledge base and the others you connected there, read-only. Then connect again. +

+
+ )}
); } diff --git a/dashboard/src/components/knowledge/logos.tsx b/dashboard/src/components/knowledge/logos.tsx index dbd5baa4..879d7177 100644 --- a/dashboard/src/components/knowledge/logos.tsx +++ b/dashboard/src/components/knowledge/logos.tsx @@ -67,6 +67,17 @@ export function SourceLogo({ kind, size = "md", className = "" }: { kind: AddKin , ); + case "bedrock_kb": + // A knowledge base in Amazon Bedrock: stacked records in AWS's orange + // (a plain mark, not Amazon's logo). + return tile( + "bg-[#FF9900]/15 ring-1 ring-[#FF9900]/40 text-[#FFB547]", + , + ); default: return tile( "bg-emerald-500/15 ring-1 ring-emerald-400/30 text-emerald-300", diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index 3c077eef..1c675dec 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -21,7 +21,14 @@ export function httpErrorMessage(status: number): string { /** A failed request, with its HTTP status for pages that branch on it. */ export class ApiError extends Error { - constructor(message: string, readonly status: number, readonly code?: string, readonly url?: string) { + constructor( + message: string, + readonly status: number, + readonly code?: string, + readonly url?: string, + /** The whole JSON answer, for a page that shows more than the message (a fix, a link). */ + readonly body?: Record, + ) { super(message); this.name = "ApiError"; } @@ -47,8 +54,10 @@ export async function request(path: string, options?: RequestInit): Promise | undefined; try { const parsed = body ? JSON.parse(body) : {}; + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) parsedBody = parsed; serverMsg = parsed.error || ""; serverCode = typeof parsed.code === "string" ? parsed.code : undefined; serverUrl = typeof parsed.url === "string" ? parsed.url : undefined; @@ -62,7 +71,7 @@ export async function request(path: string, options?: RequestInit): Promise | null | undefined): b is Base & { backend: Extract } { + return b?.backend?.kind === "remote"; } export interface Item extends KnowledgeFile { @@ -181,7 +255,7 @@ export const knowledge = { request<{ base: Base; files: Item[]; sources: Source[]; can_manage: boolean; limits: KnowledgeLimits; visibility_note: string }>( `/api/knowledge/${e(id)}`, ), - create: (input: BaseInput & { source?: SourceInput }) => + create: (input: BaseInput & { source?: SourceInput; connect?: { provider: "bedrock_kb"; target: string } }) => request<{ base: Base; source: Source | null; setup: WebhookSetup | null }>("/api/knowledge", post(input)), update: (id: string, input: BaseInput) => request<{ base: Base }>(`/api/knowledge/${e(id)}`, put(input)), remove: (id: string) => request<{ ok: boolean }>(`/api/knowledge/${e(id)}`, { method: "DELETE" }), @@ -191,6 +265,10 @@ export const knowledge = { request<{ file: Item }>(`/api/knowledge/${e(id)}/files/${e(fileId)}/uploaded`, { method: "POST" }), removeFile: (id: string, fileId: string) => request<{ ok: boolean }>(`/api/knowledge/${e(id)}/files/${e(fileId)}`, { method: "DELETE" }), + /** One test search of a base connected in place, now. */ + check: (id: string) => request<{ ok: boolean; hybrid: boolean; checked_at: string }>(`/api/knowledge/${e(id)}/check`, { method: "POST" }), + /** Connecting a Bedrock knowledge base: the install's own list (self-hosted) and the team's AWS accounts. */ + bedrock: () => request("/api/knowledge/bedrock"), connectors: () => request<{ connectors: Connector[]; visibility_note: string }>("/api/knowledge/connectors"), connect: (kind: SourceKind) => request<{ authorize_url: string }>(`/api/knowledge/connectors/${e(kind)}/connect`, { method: "POST" }), /** Your own sign-in for an app (Sanity): already signed in, or where to send the sign-in window. */ @@ -230,6 +308,7 @@ export const KIND_LABEL: Record = { github: "GitHub", web: "Website", upload: "Files", + bedrock_kb: "Bedrock knowledge base", }; /** What one item of a kind is called: "page", "document", "file". */ diff --git a/dashboard/src/lib/openapi-fields.ts b/dashboard/src/lib/openapi-fields.ts index 42de6520..95f95bb3 100644 --- a/dashboard/src/lib/openapi-fields.ts +++ b/dashboard/src/lib/openapi-fields.ts @@ -2,7 +2,7 @@ // docs/api/openapi.json. Do not edit; run `npm run openapi:fields` instead. /** The platform commit this was generated from. */ -export const OPENAPI_REF = "7a14dce62aabf4827fc6ecdd14b578f930143b2e"; +export const OPENAPI_REF = "bb81e2c5e8aa6a7eb152dbd602bc5406abc84aee"; /** The fields each public API schema has. */ export interface OpenApiFields { diff --git a/docs/content/docs/concepts/knowledge-sources.mdx b/docs/content/docs/concepts/knowledge-sources.mdx index 2e8db339..a96d1dd5 100644 --- a/docs/content/docs/concepts/knowledge-sources.mdx +++ b/docs/content/docs/concepts/knowledge-sources.mdx @@ -1,6 +1,6 @@ --- title: Knowledge sources -description: Bring pages in from Notion, Confluence, Google Drive, Sanity, GitHub and websites, and keep them up to date on their own. +description: Bring pages in from Notion, Confluence, Google Drive, Sanity, GitHub and websites, and keep them up to date on their own, or connect a Bedrock knowledge base in place. --- A knowledge base can hold pages from the apps your team already writes in, next to the files you upload. You pick what to bring in once; Coderhelm keeps it up to date, removes what is deleted, and Chat and the agents cite each page with a link back to where it lives. @@ -80,6 +80,25 @@ Pages from an app follow the knowledge base's own setting, exactly like uploaded - A Sanity source added by signing in syncs with that person's own sign-in, and says so. If they leave the team, it stops and asks any admin to sign in again; their sign-in is never used after they leave. - Sign-ins are sealed with your install's encryption key for one team and one connection, renewed before they expire, revoked when you disconnect, and never sent to the browser or to a model. +## Bedrock knowledge bases, connected in place + +If your team already has a knowledge base in Amazon Bedrock, connect it in place instead of copying it. Coderhelm searches it live in your AWS account whenever Chat or an agent needs it, and copies nothing: no documents, no passages, no vectors. Bedrock turns each question into a search itself, so it doesn't matter which embedding model or vector store the knowledge base was built with. + +1. Connect the AWS account the knowledge base lives in, on **Settings**, **Integrations**, **AWS**. It creates the read-only `CoderHelmLogReader` role, which Coderhelm takes on with your team's private ID. +2. On the **Knowledge** page, choose **New knowledge base**, then **Bedrock knowledge base**, and paste its ARN (it looks like `arn:aws:bedrock:us-east-1:111122223333:knowledge-base/ABCDE12345`). Coderhelm runs one test search before anything is saved. +3. If the role can't search it yet, the dialog says "The role in your account does not allow Retrieve on this knowledge base" and offers one link: an update stack in that account that lets the role search exactly the knowledge bases you connected there (`bedrock:Retrieve` and `bedrock:GetDocumentContent` on their ARNs, and nothing else new). Create the stack, then connect again. + +The knowledge base's page then says **Connected in place: searched live in your AWS account, nothing copied** instead of listing files. It takes no uploads and no synced apps; you add documents in Bedrock as before, and they are searchable as soon as Bedrock has them. + +- **Searching.** Coderhelm asks for Bedrock's hybrid search (meaning and exact words) where your vector store supports it, and Bedrock's ranking joins the ranking of your other knowledge bases, so one answer can cite both. At most three passages come from one document. +- **Citations.** A citation names the document and links to it: the original page for a web, Confluence or SharePoint source, or the object in the S3 console for an S3 document (it opens only for people who can sign in to that AWS account). +- **When it can't be searched.** Your other knowledge bases still answer, and Chat says which one couldn't be searched and why. +- **Who can read it.** Like any knowledge base, everyone who can read it in Coderhelm sees what the search returns, even documents they couldn't open where they came from. Agents search the knowledge bases attached to them, so anyone who can start a run reaches them too. + +Coderhelm never asks you to name its own account in a Bedrock resource policy: a grant to a shared role would let anyone who learned your knowledge base's ARN search it through another team. Access always goes through your own role and your team's private ID. + +Running your own install? A knowledge base in the install's own account needs no role at all, and the dialog lists them for you: see [Knowledge sources](/self-host/knowledge-sources#bedrock-knowledge-bases-connected-in-place) in the self-hosting guide. + ## Citations A passage from a synced page is cited like one from an uploaded file, with its place in the page and the page's last edit date, and the citation links to the original page in Notion, Confluence, Drive, GitHub or on your site. diff --git a/docs/platform.lock.json b/docs/platform.lock.json index 5faad682..61c4eded 100644 --- a/docs/platform.lock.json +++ b/docs/platform.lock.json @@ -1,4 +1,4 @@ { "repo": "CoderHelm/coderhelm-platform", - "ref": "c46b4578e7713015f2b56086a165063f2be1a0fd" + "ref": "bb81e2c5e8aa6a7eb152dbd602bc5406abc84aee" } diff --git a/src/content/site.ts b/src/content/site.ts index ee366eb7..85f5d0e0 100644 --- a/src/content/site.ts +++ b/src/content/site.ts @@ -31,7 +31,7 @@ export const SITE = { "Self-hosting: runs in your own AWS account as one CloudFormation stack, installed from the browser at https://docs.coderhelm.com/self-host/install/ or from a terminal. Releases are published at https://github.com/CoderHelm/coderhelm-platform/releases. One press of Update installs the newest release, or it installs itself in a maintenance window, on the Stable channel or the nightly Beta channel. Updates never wait for an AWS admin: extra permissions a release can use are a separate, optional step. Admins are emailed only when they need to act or something went wrong, plus an optional weekly digest. A hybrid install makes one choice for the whole install: CoderHelm's apps (easiest, the default) or fully private. With CoderHelm's apps, Jira, Notion, Confluence, Google Drive, Figma and every app CoderHelm adds later work with no setup; a tool with its own app set up always uses it, and GitHub has its own choice. License: FSL-1.1-ALv2 (each release becomes Apache 2.0 two years after it ships).", "Models: Claude. Hosted teams use their own Anthropic API key; self-hosted installs use Amazon Bedrock in their own account or each team's Anthropic API key. Admins can set monthly token limits: one for new tokens, one for cache reads and one for cache writes.", "Chat: answers questions about the team's repositories and knowledge. It reads the code itself (overview, files, code search, code graph) and cites real file paths and lines.", - "Knowledge sources: Notion, Confluence, Google Drive, Sanity, GitHub, websites and uploaded files, kept in sync.", + "Knowledge sources: Notion, Confluence, Google Drive, Sanity, GitHub, websites and uploaded files, kept in sync. An Amazon Bedrock knowledge base can be connected in place: searched live in your AWS account, read-only, nothing copied.", "API: a public REST API with team API keys, described at https://docs.coderhelm.com/openapi.json. Outbound webhooks tell your systems what CoderHelm did, signed the Standard Webhooks way and retried for about a day.", "Logs: reads the CloudWatch log groups you choose through a read only role every six hours, lists what it finds, and can open a fix pull request for new findings on its own.", "Works with: GitHub (GitHub App), Jira (Forge app), Microsoft Teams, AWS (CloudWatch alarms through SNS, CloudWatch Logs, PostgreSQL, Redshift), GraphQL APIs, Playwright, JUnit and Cucumber reports, and 17 MCP servers.", @@ -56,6 +56,7 @@ export const SITE = { "AI plans that turn a description into ordered issues", "Chat that reads your repositories and cites file paths and lines", "Knowledge from Notion, Confluence, Google Drive, Sanity, GitHub, websites and files", + "Connect your Bedrock knowledge base, searched in place in your AWS account", "Agent permissions: allow, ask or deny, with approvals", "Custom roles and monthly token limits", "Public REST API with team API keys", @@ -203,6 +204,7 @@ const home: Page = { items: [ "It reads everything you can see; type @ to narrow a question to one repository or knowledge collection", "Knowledge from Notion, Confluence, Google Drive, Sanity, GitHub, websites and files, kept in sync", + "Connect your Bedrock knowledge base: searched in place in your AWS account, nothing copied", "When nothing in your sources supports an answer, it says so", ], },