diff --git a/dashboard/e2e/integrations-connect.spec.ts b/dashboard/e2e/integrations-connect.spec.ts new file mode 100644 index 00000000..08c7a405 --- /dev/null +++ b/dashboard/e2e/integrations-connect.spec.ts @@ -0,0 +1,598 @@ +import { expect, test, type BrowserContext, type Page, type Route } from "@playwright/test"; +import fs from "node:fs"; +import path from "node:path"; + +// Settings, Integrations: the opened card, for every state it has, and a +// sign-in from the click to each way it can end. Every API call is answered +// here; nothing reaches a real backend. +// +// - One status per product: a team signed in to Confluence for Knowledge +// sees "Connected" on Confluence's card, what it is used for, and a switch +// (no second sign-in) to use it in runs too. +// - One pattern for every card: not connected (one sentence, one action, +// nothing about tools or history), signing in (progress, Cancel, and an +// outcome that always arrives), connected (who, when, what for, Manage, +// Disconnect), needs attention (the reason and one action). + +const SHOTS_DIR = process.env.E2E_SHOTS_DIR || path.join("test-results", "shots"); +const DAY = 86_400_000; +const ago = (ms: number) => new Date(Date.now() - ms).toISOString(); + +const FIGMA_DOES = "Extract design tokens, inspect components, and pull assets from Figma files."; +const FIGMA_READS = "Coderhelm reads your Figma files and the name of the account that signs in. It can't change anything in Figma."; +const CONFLUENCE_DOES = "Searches and reads Confluence pages. Optionally adds text to the end of pages you list."; + +type Json = Record; + +function plugin(id: string, name: string, over: Json = {}) { + return { + id, name, description: `${name} for agents.`, category: "Tools", tier: 1, icon: id, + credential_fields: [{ key: "api_token", label: "API token", placeholder: "tok_...", secret: true }], + docs_url: "https://example.com/docs", repo_url: "", default_prompt: "", recommended_permissions: "Read-only access", + remote_url: "", remote_key: false, key_unavailable: "", ...over, + }; +} + +const FIGMA_APP = { + authorize: "https://www.figma.com/oauth", token: "https://api.figma.com/v1/oauth/token", refresh: "https://api.figma.com/v1/oauth/refresh", + scopes: ["current_user:read", "file_content:read"], reads: FIGMA_READS, console: "https://www.figma.com/developers/apps", guide: "https://developers.figma.com/docs/rest-api/oauth-apps/", +}; + +function server(id: string, name: string, over: Json = {}) { + return { + id, name, url: `https://mcp.${id}.example/mcp`, catalog_id: "", auth: "oauth", sharing: "shared", header_name: "", has_key: false, + issuer: `https://auth.${id}.example`, registration: "dynamic", needs_client: false, has_client: true, scopes: [], status: "not_connected", status_reason: "", + status_at: "", my_connection: null, tools: [], skipped: [], tools_listed_at: "", awaiting_approval: [], changed_by: "", custom_prompt: "", + added_by: "ada@example.com", added_at: ago(9 * DAY), ...over, + }; +} + +const TOOLS = [ + { name: "query_documents", title: null, description: "Run a query and return the documents.", access: "read", allowed: true, approved: true, offerable: true }, + { name: "patch_document", title: null, description: "Change a document.", access: "write", allowed: false, approved: false, offerable: true }, +]; + +interface Card { + id: string; + section: string; + name: string; + does: string; + status: string; + reason: string; + action: string; + last_check: string; + manage_href: string; + detail: Json; + uses: Json[]; + how: string; + connected_by: string; + connected_at: string; +} + +function card(id: string, section: string, name: string, does: string, status: string, action: string, over: Json = {}): Card { + return { id, section, name, does, status, reason: "", action, last_check: "", manage_href: "", detail: {}, uses: [], how: "", connected_by: "", connected_at: "", ...over }; +} + +const usedFor = (id: "runs" | "knowledge", state: string, over: Json = {}) => ({ + id, label: id === "runs" ? "Runs and reviews" : "Knowledge", state, how: "", detail: "", action: null, ...over, +}); + +const knowledge = (kind: string, label: string, over: Json = {}) => ({ + kind, label, server_id: `ks-${kind.replace("_", "-")}`, personal: false, status: "connected", reason: "", + connected_by: "ada@example.com", connected_at: ago(2 * DAY), sources: 2, ...over, +}); + +const RUNS_READY = "The same sign-in can read pages during runs and reviews. Turn it on: no second sign-in."; + +/** The report: signed in to Confluence for Knowledge, no connection saved for runs. */ +function confluenceForKnowledge(over: Json = {}) { + return card("confluence", "docs", "Confluence", CONFLUENCE_DOES, "connected", "manage", { + reason: `Connected for Knowledge. ${RUNS_READY}`, + how: "the team's Atlassian sign-in", connected_by: "ada@example.com", connected_at: ago(2 * DAY), + uses: [ + usedFor("runs", "ready", { how: "the team's Atlassian sign-in", detail: RUNS_READY, action: { kind: "use_in_runs", label: "Use in runs too", href: "" } }), + usedFor("knowledge", "on", { how: "the team's Atlassian sign-in" }), + ], + detail: { kind: "confluence", connected: false, needs_name: false, knowledge: knowledge("confluence", "Confluence") }, + ...over, + }); +} + +/** The report: Figma with a sign-in through Coderhelm's app never finished, an older record for Figma's own server, and the old switch. */ +function figmaNotConnected() { + return card("figma", "docs", "Figma", FIGMA_DOES, "not_connected", "connect", { + uses: [usedFor("runs", "off")], + detail: { + plugin: plugin("figma", "Figma", { description: FIGMA_DOES, own_app: FIGMA_APP, credential_fields: [{ key: "api_token", label: "Personal Access Token", placeholder: "figd_...", secret: true }] }), + enabled: false, has_credentials: false, custom_prompt: "", coderhelm_app: true, + own_app_redirect_uri: "https://coderhelm.example.com/settings/integrations/mcp-callback/", + own_app: { id: "app-figma", source: "coderhelm", client_id: "", has_secret: false, status: "not_connected", status_reason: "", connected_by: "", connected_at: "", redirect_uri: "" }, + remote: null, knowledge: null, + unused: [{ id: "figma", name: "Figma", kind: "remote", note: "A sign-in through Figma's own server was started and never finished. Coderhelm doesn't use it." }], + }, + }); +} + +function figmaConnected(): Card { + const c = figmaNotConnected(); + const d = c.detail as { own_app: Json }; + d.own_app = { ...d.own_app, status: "connected", connected_by: "ada@example.com", connected_at: new Date().toISOString() }; + return { + ...c, status: "connected", action: "manage", reason: "Signed in with Coderhelm's app.", how: "Coderhelm's Figma app", + connected_by: "ada@example.com", connected_at: new Date().toISOString(), uses: [usedFor("runs", "on", { how: "Coderhelm's Figma app" })], + }; +} + +function sanityConnected(over: Json = {}) { + return card("sanity", "docs", "Sanity", "Query documents, read schemas, and manage content in Sanity.", "connected", "manage", { + last_check: ago(6 * DAY), how: "Sanity's own server", connected_by: "grace@example.com", connected_at: ago(8 * DAY), + reason: "Connected for runs and reviews. Knowledge can sync with this sign-in: add a source there.", + uses: [ + usedFor("runs", "on", { how: "Sanity's own server" }), + usedFor("knowledge", "ready", { how: "Sanity's own server", detail: "Knowledge can sync with this sign-in: add a source there.", action: { kind: "link", label: "Add a source in Knowledge", href: "/knowledge/" } }), + ], + detail: { + plugin: plugin("sanity", "Sanity", { remote_url: "https://mcp.sanity.io" }), enabled: false, has_credentials: false, custom_prompt: "", + remote: server("sanity", "Sanity", { catalog_id: "sanity", url: "https://mcp.sanity.io", status: "connected", tools: TOOLS, tools_listed_at: ago(6 * DAY), ...over }), + knowledge: null, unused: [], + }, + }); +} + +interface Backend { + items: Card[]; + calls: { method: string; path: string; body: Json | null }[]; + /** How the sign-in page answers: with a code, with the provider's refusal, or never. */ + signIn: "ok" | "declined" | "never"; + /** Seconds a started sign-in can still be finished in. */ + expires: number; + activity: Json[]; + /** Applied when a sign-in finishes. */ + onConnected: () => void; +} + +async function mockApi(context: BrowserContext, init: Partial = {}): Promise { + const db: Backend = { items: [], calls: [], signIn: "ok", expires: 600, activity: [], onConnected: () => {}, ...init }; + const json = (r: Route, body: unknown, status = 200) => r.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + await context.route((url) => url.hostname !== "localhost", (r) => r.abort()); + // The provider's sign-in page, which never answers in the "never" case. + await context.route((url) => url.hostname === "localhost" && url.pathname === "/provider-sign-in", (r) => + r.fulfill({ status: 200, contentType: "text/html", body: "Sign in

Sign in to continue

" }), + ); + await context.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (r) => { + const req = r.request(); + const p = new URL(req.url()).pathname; + const method = req.method(); + const body = req.postData() ? (JSON.parse(req.postData() as string) as Json) : null; + db.calls.push({ method, path: p, body }); + const authorize = () => + db.signIn === "never" ? "/provider-sign-in" : `/settings/integrations/mcp-callback/?state=app.s1&${db.signIn === "ok" ? "code=c1" : "error=access_denied"}`; + if (p === "/api/me") return json(r, { user_id: "u_1", team_id: "t_1", github_login: null, email: "ada@example.com", avatar_url: "", role: "admin", auth_provider: "email" }); + if (p === "/api/usage") return json(r, { month: "2026-01", tokens_in: 0, tokens_out: 0, total_runs: 0, total_tokens: 0, max_tokens: 0 }); + if (p === "/api/banners") return json(r, { banners: [] }); + if (p === "/api/teams") return json(r, { teams: [{ team_id: "t_1", org: "your-team", status: "active", current: true }] }); + if (p === "/api/integrations") return json(r, { can_edit: true, items: db.items, migrated: 0 }); + if (p === "/api/reviewer/org-config") return json(r, { instructions: "", web_domains: [] }); + if (p === "/api/mcp-servers" && method === "GET") return json(r, { servers: [], can_edit: true, redirect_uri: "http://localhost/settings/integrations/mcp-callback/" }); + if (/^\/api\/mcp-servers\/[\w-]+\/activity$/.test(p)) return json(r, { calls: db.activity }); + if (/^\/api\/mcp-servers\/[\w-]+\/sign-in$/.test(p) && method === "DELETE") return json(r, { cancelled: 1 }); + if (p === "/api/mcp-servers/apps/figma/coderhelm" && method === "POST") { + return json(r, { authorize_url: authorize(), server_id: "app-figma", expires_in: db.expires, own_app: { id: "app-figma", source: "coderhelm", client_id: "", has_secret: false, status: "not_connected", status_reason: "", connected_by: "", connected_at: "", redirect_uri: "" } }); + } + if (/^\/api\/mcp-servers\/[\w-]+\/connect$/.test(p)) return json(r, { authorize_url: authorize(), server_id: p.split("/")[3], expires_in: db.expires }); + if (p === "/api/knowledge/connectors/confluence/connect") return json(r, { authorize_url: authorize(), server_id: "ks-confluence", expires_in: db.expires }); + if (p === "/api/mcp-servers/oauth/callback") { + if (body?.error) { + return json(r, { + error: "Figma answered access_denied: access wasn't granted. Either Cancel was chosen on its sign-in page, or Figma doesn't let this account use Coderhelm's app. Start again, and ask an admin of Figma if it keeps happening.", + code: "access_denied", flow: "app", return_to: "", server_name: "Figma", catalog_id: "app:figma", + }, 400); + } + db.onConnected(); + return json(r, { server: { id: "app-figma", name: "Figma", catalog_id: "figma" }, tools_error: null, own_app: true, flow: "app", return_to: "" }); + } + if (p === "/api/connectors/confluence" && method === "PUT") { + db.onConnected(); + return json(r, { connector: { kind: "confluence", id: "confluence", label: "Confluence", connected: true, enabled: true, status: "ready", via: "sign_in", site: "https://example.atlassian.net" } }); + } + if (/^\/api\/mcp-servers\/[\w-]+\/connection$/.test(p) && method === "DELETE") { + db.items = db.items.map((i) => (i.id === "figma" ? figmaNotConnected() : i)); + return json(r, { server: server("app-figma", "Figma"), revoked: true }); + } + return json(r, { error: `not mocked: ${method} ${p}` }, 404); + }); + return db; +} + +const row = (page: Page, id: string) => page.getByTestId(`integration-${id}`); + +/** Opens a row from the keyboard, as its one control. */ +async function open(page: Page, id: string) { + const control = row(page, id).getByRole("button").first(); + await control.focus(); + await page.keyboard.press("Enter"); + await expect(row(page, id).getByTestId("integration-panel")).toBeVisible(); +} + +/** The opened card at desktop and phone width: no sideways scroll, and a picture of each. */ +async function shot(page: Page, id: string, name: string) { + fs.mkdirSync(SHOTS_DIR, { recursive: true }); + await page.addStyleTag({ content: "nextjs-portal{display:none!important}" }); + for (const width of [1280, 390]) { + await page.setViewportSize({ width, height: 900 }); + await page.waitForTimeout(150); + const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + expect(overflow, `no sideways scroll at ${width}px`).toBeLessThanOrEqual(0); + // The whole card, cut from the full page so the fixed top bar isn't drawn over it. + const box = await row(page, id).evaluate((el) => { + const r = el.getBoundingClientRect(); + return { x: r.left + window.scrollX, y: r.top + window.scrollY, width: r.width, height: r.height }; + }); + await page.screenshot({ path: path.join(SHOTS_DIR, `${name}-${width}.png`), fullPage: true, clip: box }); + } + await page.setViewportSize({ width: 1280, height: 900 }); +} + +// ── One status per product ─────────────────────────────────────────── + +test("Confluence signed in for Knowledge reads Connected, says what it is used for, and runs take one switch", async ({ page, context }) => { + const db = await mockApi(context, { items: [confluenceForKnowledge()] }); + db.onConnected = () => { + db.items = [ + confluenceForKnowledge({ + reason: "Used in runs and reviews, and in Knowledge. Agents read pages with the team's Atlassian sign-in.", + uses: [usedFor("runs", "on", { how: "the team's Atlassian sign-in" }), usedFor("knowledge", "on", { how: "the team's Atlassian sign-in" })], + detail: { kind: "confluence", id: "confluence", label: "Confluence", connected: true, enabled: true, status: "ready", via: "sign_in", site: "https://example.atlassian.net", spaces: [], knowledge: knowledge("confluence", "Confluence") }, + }), + ]; + }; + await page.goto("/settings/integrations"); + const r = row(page, "confluence"); + // Never "Not connected" for a product the team is signed in to. + await expect(r).toHaveAttribute("data-status", "connected"); + await expect(r.getByTestId("integration-status")).toHaveText("Connected"); + await expect(r.getByRole("button").first()).toHaveAccessibleName("Confluence, Connected. Manage"); + await open(page, "confluence"); + + const facts = r.getByTestId("connection-facts"); + await expect(facts).toContainText("Connected withThe team's Atlassian sign-in"); + await expect(facts).toContainText("Connected byada@example.com"); + await expect(facts).toContainText("Connected2 days ago"); + await expect(r.getByTestId("use-knowledge")).toHaveAttribute("data-state", "on"); + await expect(r.getByTestId("use-knowledge")).toContainText("On"); + const runs = r.getByTestId("use-runs"); + await expect(runs).toHaveAttribute("data-state", "ready"); + await expect(runs).toContainText(RUNS_READY); + // A token is another way, never beside the switch. + await expect(r.getByTestId("other-ways").locator("summary")).toHaveText("Other ways to connect"); + await expect(r.getByTestId("other-ways").getByLabel("API token", { exact: true })).toBeHidden(); + await expect(r.getByRole("link", { name: "Manage Confluence sources in Knowledge" })).toHaveAttribute("href", /\/knowledge\/?$/); + await shot(page, "confluence", "confluence-knowledge-only"); + + // One switch, no second sign-in: the same sign-in is saved for runs. + await runs.getByRole("button", { name: "Use in runs too" }).click(); + await expect(r.getByTestId("use-runs")).toHaveAttribute("data-state", "on"); + expect(db.calls.find((c) => c.method === "PUT" && c.path === "/api/connectors/confluence")?.body).toEqual({ via: "sign_in", enabled: true }); + expect(db.calls.some((c) => c.path.endsWith("/connect")), "nobody signed in again").toBe(false); + await expect(r.getByTestId("use-runs")).toContainText("with the team's Atlassian sign-in"); + // Its settings name no token, and writes aren't offered: the sign-in only reads. + await expect(r.getByTestId("confluence-via-sign-in")).toContainText("No token is needed, and it only reads."); + await expect(r.getByText("Allow agents to add text")).toHaveCount(0); + await expect(r.getByTestId("connector-remove")).toContainText("Stop using Confluence in runs"); + await shot(page, "confluence", "confluence-both-uses"); +}); + +test("a Knowledge sign-in that has to be renewed says why with one action, beside the use that still works", async ({ page, context }) => { + await mockApi(context, { + items: [ + confluenceForKnowledge({ + status: "needs_reconnect", action: "reconnect", + reason: "Runs and reviews still work. Knowledge: Atlassian ended the sign-in.", + how: "an API token", connected_by: "grace@example.com", + uses: [ + usedFor("runs", "on", { how: "an API token" }), + usedFor("knowledge", "attention", { how: "the team's Atlassian sign-in", detail: "Atlassian ended the sign-in.", action: { kind: "reconnect", label: "Reconnect", href: "" } }), + ], + detail: { + kind: "confluence", id: "confluence", label: "Confluence", connected: true, enabled: true, status: "ready", key_hint: "9f2c", site: "https://example.atlassian.net", email: "bot@example.com", + knowledge: knowledge("confluence", "Confluence", { status: "needs_reconnect", reason: "Atlassian ended the sign-in." }), + }, + }), + ], + }); + await page.goto("/settings/integrations"); + const r = row(page, "confluence"); + await expect(r.getByTestId("integration-status")).toHaveText("Needs reconnecting"); + await open(page, "confluence"); + const note = r.getByTestId("integration-attention"); + await expect(note).toContainText("Needs reconnecting"); + await expect(note).toContainText("Runs and reviews still work. Knowledge: Atlassian ended the sign-in."); + // One action, in the note; the use's row repeats no button. + await expect(note.getByRole("button", { name: "Sign in again" })).toBeVisible(); + await expect(r.getByTestId("use-knowledge").getByRole("button")).toHaveCount(0); + await expect(r.getByTestId("use-runs")).toHaveAttribute("data-state", "on"); + await shot(page, "confluence", "confluence-needs-attention"); +}); + +test("Google Drive signed in for Knowledge has a card: who, when, what for, and Disconnect", async ({ page, context }) => { + await mockApi(context, { + items: [ + card("google_drive", "docs", "Google Drive", "Syncs the folders, Docs, Sheets, Slides and PDFs you pick into Knowledge. It only reads.", "connected", "manage", { + manage_href: "/knowledge/", how: "the team's Google sign-in", connected_by: "ada@example.com", connected_at: ago(3 * DAY), + uses: [usedFor("knowledge", "on", { how: "the team's Google sign-in" })], + detail: { knowledge: knowledge("google_drive", "Google Drive", { sources: 1 }) }, + }), + ], + }); + await page.goto("/settings/integrations"); + const r = row(page, "google_drive"); + await expect(r.getByTestId("integration-does")).toHaveText("Folders, Docs, Sheets and PDFs, synced into Knowledge"); + await open(page, "google_drive"); + await expect(r.getByTestId("connection-facts")).toContainText("Used forKnowledge (1 source)"); + await expect(r.getByTestId("connection-facts")).toContainText("Connected byada@example.com"); + await expect(r.getByTestId("disconnect-knowledge")).toContainText("Its 1 source in Knowledge stop syncing until someone signs in again."); + await shot(page, "google_drive", "google-drive-connected"); +}); + +// ── Not connected ──────────────────────────────────────────────────── + +test("Figma not connected: one sentence, one action, what happens next, and nothing about tools or history", async ({ page, context }) => { + await mockApi(context, { items: [figmaNotConnected()] }); + await page.goto("/settings/integrations"); + await open(page, "figma"); + const r = row(page, "figma"); + const panel = r.getByTestId("integration-panel"); + await expect(panel.getByTestId("access")).toHaveText(FIGMA_READS); + // One primary action, and what happens next. + await expect(panel.getByRole("button", { name: "Sign in with Figma" })).toHaveCount(1); + await expect(panel.getByTestId("coderhelm-app-sign-in-note")).toHaveText("Opens Figma in a new tab. You come back here when done."); + // The button says what it does to a screen reader too. + const describedBy = await panel.getByRole("button", { name: "Sign in with Figma" }).getAttribute("aria-describedby"); + await expect(page.locator(`[id="${describedBy}"]`)).toHaveText("Opens Figma in a new tab. You come back here when done."); + // Nothing about tools, instructions or history; no server address; no second sign-in for the older record. + for (const gone of ["Recent tool calls", "Instructions agents follow", "Its tools are listed", "Stop using Figma's sign-in", "https://mcp.figma.com"]) { + await expect(panel.getByText(gone)).toHaveCount(0); + } + await expect(panel.getByRole("button", { name: "Connect", exact: true })).toHaveCount(0); + // The technical names wait behind Details. + await expect(panel.getByTestId("scopes")).toBeHidden(); + await panel.getByTestId("panel-details").locator("summary").click(); + await expect(panel.getByTestId("scopes")).toHaveText("current_user:read, file_content:read"); + await expect(panel.getByTestId("panel-details")).toContainText("Signs in atwww.figma.com"); + await panel.getByTestId("panel-details").locator("summary").click(); + // Every other way sits under one disclosure, closed. + const other = panel.getByTestId("other-ways"); + await expect(other.locator("summary")).toHaveText("Other ways to connect"); + await expect(other.getByTestId("way-own")).toBeHidden(); + await shot(page, "figma", "figma-not-connected"); + await other.locator("summary").click(); + await expect(other.getByTestId("way-own")).toContainText("Use your own Figma app"); + await expect(other.getByTestId("way-key")).toContainText("Use a key"); + // The older record is kept, said, and removed only by the person. + await expect(other.getByTestId("unused-record")).toContainText("A sign-in through Figma's own server was started and never finished. Coderhelm doesn't use it."); + await expect(other.getByTestId("unused-record").getByRole("button", { name: "Remove it" })).toBeVisible(); + await shot(page, "figma", "figma-other-ways"); +}); + +test("the old switch left on with no key is no dead end: the default sign-in, with the key among the other ways", async ({ page, context }) => { + const c = figmaNotConnected(); + (c.detail as Json).enabled = true; + await mockApi(context, { + items: [ + { + ...c, status: "needs_credentials", action: "add_credentials", reason: "Switched on, but no credentials are saved, so agents don't get it.", + uses: [usedFor("runs", "attention", { how: "a key", detail: "Switched on, but no credentials are saved, so agents don't get it.", action: { kind: "add_credentials", label: "Add credentials", href: "" } })], + }, + ], + }); + await page.goto("/settings/integrations"); + await open(page, "figma"); + const panel = row(page, "figma").getByTestId("integration-panel"); + await expect(panel.getByTestId("integration-attention")).toContainText("Switched on, but no credentials are saved, so agents don't get it."); + // One primary action: the sign-in. The key form is open among the other ways, and quiet. + await expect(panel.getByRole("button", { name: "Sign in with Figma", exact: true })).toHaveCount(1); + await expect(panel.getByTestId("way-key").getByLabel("Personal Access Token")).toBeVisible(); + await shot(page, "figma", "figma-switched-on-no-key"); +}); + +test("a server added by address, not connected: Connect and nothing else yet", async ({ page, context }) => { + await mockApi(context, { + items: [card("mcp:wiki", "mcp", "Team wiki", "A remote MCP server at mcp.wiki.example. Agents get only the tools you allow.", "not_connected", "connect", { detail: { remote: server("wiki", "Team wiki") } })], + }); + await page.goto("/settings/integrations"); + await open(page, "mcp:wiki"); + const panel = row(page, "mcp:wiki").getByTestId("integration-panel"); + await expect(panel.getByRole("button", { name: "Connect", exact: true })).toHaveCount(1); + await expect(panel.getByTestId("mcp-sign-in-note")).toHaveText("Opens Team wiki in a new tab. You come back here when done."); + await expect(panel.getByTestId("mcp-manage")).toHaveCount(0); + await expect(panel.getByText("Recent tool calls")).toHaveCount(0); + await expect(panel.getByTestId("mcp-disconnect")).toHaveCount(0); + // The address is a detail, and removing the server is the destructive end. + await expect(panel.getByText("https://mcp.wiki.example/mcp")).toBeHidden(); + await expect(panel.getByTestId("mcp-remove").getByRole("button", { name: "Remove server" })).toBeVisible(); + await shot(page, "mcp:wiki", "mcp-not-connected"); +}); + +// ── Signing in, and every way it ends ──────────────────────────────── + +test("signing in opens a new tab, shows it is waiting, and the card becomes Connected when the tab finishes", async ({ page, context }) => { + const db = await mockApi(context, { items: [figmaNotConnected()] }); + db.onConnected = () => { + db.items = [figmaConnected()]; + }; + await page.goto("/settings/integrations"); + await open(page, "figma"); + const r = row(page, "figma"); + const tab = context.waitForEvent("page"); + await r.getByRole("button", { name: "Sign in with Figma" }).click(); + const popup = await tab; + // The sign-in finished in the other tab, which closes itself. + await popup.waitForEvent("close"); + await expect(r).toHaveAttribute("data-status", "connected"); + await expect(r.getByTestId("connection-facts")).toContainText("Connected withCoderhelm's Figma app"); + await expect(r.getByTestId("connection-facts")).toContainText("Connected byada@example.com"); + await expect(r.getByTestId("connection-facts")).toContainText("Used forRuns and reviews"); + // This tab never left the page. + await expect(page).toHaveURL(/\/settings\/integrations\/?$/); + // Disconnect is last, worded and coloured as what it is, and asks first. + const danger = r.getByTestId("disconnect"); + await expect(danger).toContainText("Disconnect FigmaAgents stop using Figma until someone signs in again."); + await shot(page, "figma", "figma-connected"); + await danger.getByRole("button", { name: "Disconnect" }).click(); + const sure = page.getByTestId("confirm-dialog"); + await expect(sure).toContainText("Disconnect Figma?"); + await sure.getByRole("button", { name: "Disconnect" }).click(); + await expect(r).toHaveAttribute("data-status", "not_connected"); +}); + +test("while it waits the button says so, and Cancel ends it at once", async ({ page, context }) => { + const db = await mockApi(context, { items: [figmaNotConnected()], signIn: "never" }); + await page.goto("/settings/integrations"); + await open(page, "figma"); + const r = row(page, "figma"); + const tab = context.waitForEvent("page"); + await r.getByRole("button", { name: "Sign in with Figma" }).click(); + const popup = await tab; + const waiting = r.getByTestId("coderhelm-app-sign-in-button"); + await expect(waiting).toHaveText("Waiting for Figma…"); + await expect(waiting).toBeDisabled(); + await expect(waiting).toHaveAttribute("aria-busy", "true"); + await expect(r.getByTestId("coderhelm-app-sign-in-note")).toHaveText("Finish signing in in the Figma tab. This page updates on its own; the sign-in stays open for 10 minutes."); + await expect(r.getByTestId("coderhelm-app-sign-in-note")).toHaveAttribute("role", "status"); + await shot(page, "figma", "figma-signing-in"); + await r.getByRole("button", { name: "Cancel" }).click(); + await expect(r.getByTestId("coderhelm-app-sign-in")).toHaveAttribute("data-outcome", "cancelled"); + await expect(r.getByTestId("coderhelm-app-sign-in-note")).toHaveText("Sign-in cancelled. Nothing was connected."); + await expect(r.getByRole("button", { name: "Sign in with Figma" })).toBeEnabled(); + // The sign-in's link stops working, and its tab is closed. + await expect.poll(() => db.calls.some((c) => c.method === "DELETE" && c.path === "/api/mcp-servers/app-figma/sign-in")).toBe(true); + await expect.poll(() => popup.isClosed()).toBe(true); +}); + +test("declined at the provider: the card says why and offers Try again", async ({ page, context }) => { + await mockApi(context, { items: [figmaNotConnected()], signIn: "declined" }); + await page.goto("/settings/integrations"); + await open(page, "figma"); + const r = row(page, "figma"); + const tab = context.waitForEvent("page"); + await r.getByRole("button", { name: "Sign in with Figma" }).click(); + await (await tab).waitForEvent("close"); + const outcome = r.getByTestId("coderhelm-app-sign-in-outcome"); + await expect(r.getByTestId("coderhelm-app-sign-in")).toHaveAttribute("data-outcome", "declined"); + await expect(outcome).toContainText("Figma wasn't connected: access wasn't granted"); + await expect(outcome).toContainText("Figma answered access_denied: access wasn't granted."); + await expect(r.getByRole("button", { name: "Try again" })).toBeEnabled(); + await expect(r).toHaveAttribute("data-status", "not_connected"); + await shot(page, "figma", "figma-declined"); +}); + +test("a blocked pop-up is said, with the choice to sign in in this tab", async ({ page, context }) => { + const db = await mockApi(context, { items: [figmaNotConnected()] }); + db.onConnected = () => { + db.items = [figmaConnected()]; + }; + await page.addInitScript(() => { + window.open = () => null; + }); + await page.goto("/settings/integrations"); + await open(page, "figma"); + const r = row(page, "figma"); + await r.getByRole("button", { name: "Sign in with Figma" }).click(); + await expect(r.getByTestId("coderhelm-app-sign-in")).toHaveAttribute("data-outcome", "blocked"); + const outcome = r.getByTestId("coderhelm-app-sign-in-outcome"); + await expect(outcome).toContainText("Your browser blocked the sign-in tab"); + await expect(outcome).toContainText("Allow pop-ups for this site and try again, or sign in to Figma in this tab: you come back here when done."); + // Nothing was started while the tab was blocked. + expect(db.calls.some((c) => c.path === "/api/mcp-servers/apps/figma/coderhelm")).toBe(false); + await shot(page, "figma", "figma-popup-blocked"); + // In this tab: the callback page finishes it and comes back to the card. + await r.getByRole("button", { name: "Sign in in this tab" }).click(); + await expect(page).toHaveURL(/\/settings\/integrations\/#integration-figma$/); + await expect(row(page, "figma")).toHaveAttribute("data-status", "connected"); +}); + +test("a sign-in nobody finishes times out, says so, and cancels itself", async ({ page, context }) => { + const db = await mockApi(context, { items: [figmaNotConnected()], signIn: "never", expires: 2 }); + await page.goto("/settings/integrations"); + await open(page, "figma"); + const r = row(page, "figma"); + const tab = context.waitForEvent("page"); + await r.getByRole("button", { name: "Sign in with Figma" }).click(); + const popup = await tab; + await expect(r.getByTestId("coderhelm-app-sign-in")).toHaveAttribute("data-outcome", "timed_out"); + const outcome = r.getByTestId("coderhelm-app-sign-in-outcome"); + await expect(outcome).toContainText("The Figma sign-in wasn't finished in time"); + await expect(outcome).toContainText("Nothing was connected. A sign-in has to be finished within 2 seconds. Try again when you're ready."); + await expect(r.getByRole("button", { name: "Try again" })).toBeEnabled(); + await expect.poll(() => popup.isClosed()).toBe(true); + expect(db.calls.some((c) => c.method === "DELETE" && c.path === "/api/mcp-servers/app-figma/sign-in")).toBe(true); + await shot(page, "figma", "figma-timed-out"); +}); + +test("a sign-in the API can't start says why, with the button ready again", async ({ page, context }) => { + await mockApi(context, { items: [figmaNotConnected()] }); + await context.route("**/api/mcp-servers/apps/figma/coderhelm", (r) => + r.fulfill({ status: 400, contentType: "application/json", body: JSON.stringify({ error: "CoderHelm's app isn't set up on this install. Use your own app or a key instead." }) }), + ); + await page.goto("/settings/integrations"); + await open(page, "figma"); + const r = row(page, "figma"); + await r.getByRole("button", { name: "Sign in with Figma" }).click(); + await expect(r.getByTestId("coderhelm-app-sign-in")).toHaveAttribute("data-outcome", "failed"); + await expect(r.getByTestId("coderhelm-app-sign-in-outcome")).toContainText("The Figma sign-in couldn't start"); + await expect(r.getByRole("button", { name: "Try again" })).toBeEnabled(); +}); + +// ── Connected ──────────────────────────────────────────────────────── + +test("connected: who and when, what it is used for, and Manage shows only what has something in it", async ({ page, context }) => { + const db = await mockApi(context, { items: [sanityConnected()] }); + await page.goto("/settings/integrations"); + await open(page, "sanity"); + const r = row(page, "sanity"); + await expect(r.getByTestId("connection-facts")).toContainText("Connected withSanity's own server"); + await expect(r.getByTestId("connection-facts")).toContainText("Connected bygrace@example.com"); + await expect(r.getByTestId("connection-facts")).toContainText("Last checked6 days ago"); + await expect(r.getByTestId("use-runs")).toContainText("On"); + await expect(r.getByTestId("use-knowledge").getByRole("link", { name: "Add a source in Knowledge" })).toHaveAttribute("href", /\/knowledge\/?$/); + const manage = r.getByTestId("mcp-manage"); + await expect(manage.getByTestId("mcp-tool")).toHaveCount(2); + // No instructions and no calls yet: one link to add instructions, no empty boxes. + await expect(manage.getByText("Recent tool calls")).toHaveCount(0); + await expect(manage.getByRole("button", { name: "Add instructions agents follow with this server" })).toBeVisible(); + await expect(manage.getByLabel("Instructions")).toHaveCount(0); + await expect(r.getByTestId("disconnect")).toContainText("The tools you allowed stay picked."); + await shot(page, "sanity", "sanity-connected"); + + // With calls and instructions, both show. + db.items = [sanityConnected({ custom_prompt: "Read only the production dataset." })]; + db.activity = [ + { tool: "query_documents", actor: "coder, run 01J", ok: true, ms: 120, detail: "", at: ago(3_600_000) }, + { tool: "query_documents", actor: "plan chat (ada@example.com)", ok: false, ms: 80, detail: "The server answered 429.", at: ago(7_200_000) }, + ]; + await page.reload(); + await open(page, "sanity"); + await expect(row(page, "sanity").getByTestId("mcp-manage").locator("summary", { hasText: "Recent tool calls (2)" })).toBeVisible(); + await expect(row(page, "sanity").getByTestId("mcp-manage").locator("summary", { hasText: "Instructions agents follow with this server" })).toBeVisible(); + await shot(page, "sanity", "sanity-connected-with-history"); +}); + +test("the whole card works from the keyboard: open, reach the action, close", async ({ page, context }) => { + await mockApi(context, { items: [figmaNotConnected()] }); + await page.goto("/settings/integrations"); + const control = row(page, "figma").getByRole("button").first(); + await control.focus(); + await expect(control).toHaveAttribute("aria-expanded", "false"); + await page.keyboard.press("Enter"); + await expect(control).toHaveAttribute("aria-expanded", "true"); + // The next stop is the primary action; nothing else comes first. + await page.keyboard.press("Tab"); + await expect(row(page, "figma").getByRole("button", { name: "Sign in with Figma" })).toBeFocused(); + // Disclosures open from the keyboard. + await page.keyboard.press("Tab"); + await expect(row(page, "figma").getByTestId("panel-details").locator("summary")).toBeFocused(); + await page.keyboard.press("Tab"); + await expect(row(page, "figma").getByTestId("other-ways").locator("summary")).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(row(page, "figma").getByTestId("way-own")).toBeVisible(); +}); diff --git a/dashboard/e2e/integrations-page.spec.ts b/dashboard/e2e/integrations-page.spec.ts index d2f4a18e..980181cd 100644 --- a/dashboard/e2e/integrations-page.spec.ts +++ b/dashboard/e2e/integrations-page.spec.ts @@ -105,8 +105,10 @@ async function mockApi(page: Page, init: Partial = {}): Promise route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); const at = (min: Role) => LEVEL[db.role] >= LEVEL[min]; const forbidden = (r: Route) => json(r, { error: "Forbidden" }, 403); - await page.route((url) => url.hostname !== "localhost", (route) => route.abort()); - await page.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (r) => { + // On the context, so a sign-in opened in its own tab is answered here too. + const context = page.context(); + await context.route((url) => url.hostname !== "localhost", (route) => route.abort()); + await context.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (r) => { const req = r.request(); const p = new URL(req.url()).pathname; const method = req.method(); @@ -630,8 +632,9 @@ test("a saved webhook shows only as a hint, is tested without the page knowing i }); }); -test("Figma signs in with the team's own app, its redirect URL and scopes shown, a key still possible", async ({ page }) => { +test("Figma signs in with the team's own app, its redirect URL and scopes shown, a key still possible", async ({ page, context }) => { const db = await mockApi(page); + db.items = db.items.map((i) => (i.id === "figma" ? pluginCard("figma", "Figma", "docs", false, false) : i)); const figma = db.items.find((i) => i.id === "figma")!; (figma.detail as Record).own_app_redirect_uri = "https://coderhelm.example.com/settings/integrations/mcp-callback/"; (figma.detail as { plugin: Record }).plugin.own_app = { @@ -643,28 +646,33 @@ test("Figma signs in with the team's own app, its redirect URL and scopes shown, guide: "https://developers.figma.com/docs/rest-api/oauth-apps/", }; await page.goto("/settings/integrations#integration-figma"); + // Where Coderhelm has no app of its own, the team's own app is the default way. const panel = row(page, "figma").getByTestId("own-app"); - await expect(panel).toContainText("Use my own Figma app"); + await expect(panel).toBeVisible(); await expect(panel.getByTestId("own-app-redirect")).toHaveText("https://coderhelm.example.com/settings/integrations/mcp-callback/"); await expect(panel).toContainText("current_user:read, file_content:read"); await expect(panel.getByRole("link", { name: "www.figma.com/developers/apps" })).toHaveAttribute("href", "https://www.figma.com/developers/apps"); - // The key form waits behind its disclosure. - await expect(row(page, "figma").getByText("Use a key instead")).toBeVisible(); - const go = panel.getByRole("button", { name: "Save and connect with Figma" }); + // A key waits with the other ways to connect, behind one disclosure. + await expect(row(page, "figma").getByTestId("other-ways").locator("summary")).toHaveText("Other ways to connect"); + await expect(row(page, "figma").getByTestId("way-key")).toBeHidden(); + const go = panel.getByRole("button", { name: "Save and sign in with Figma" }); await expect(go).toBeDisabled(); await panel.getByLabel("Client ID").fill("client-1"); await panel.getByLabel("Client secret").fill("secret-1"); + const tab = context.waitForEvent("page"); await go.click(); - // Saved, then sent to Figma's sign-in, whose answer the callback page finishes. + // Saved, then Figma's sign-in opens in its own tab, whose answer the callback page finishes. + await (await tab).waitForEvent("close"); await expect.poll(() => db.calls.some((c) => c.path === "/api/mcp-servers/oauth/callback")).toBe(true); const saved = db.calls.find((c) => c.method === "PUT" && c.path === "/api/mcp-servers/apps/figma"); expect(saved?.body).toEqual({ client_id: "client-1", client_secret: "secret-1" }); expect(db.calls.some((c) => c.method === "POST" && c.path === "/api/mcp-servers/app-figma/connect")).toBe(true); - await expect(page).toHaveURL(/\/settings\/integrations\/#integration-figma$/); + await expect(page).toHaveURL(/\/settings\/integrations\/?#integration-figma$/); }); -test("Figma signs in with Coderhelm's app in one click; my own app and a key are the other choices", async ({ page }) => { +test("Figma signs in with Coderhelm's app in one click; my own app and a key are the other choices", async ({ page, context }) => { const db = await mockApi(page); + db.items = db.items.map((i) => (i.id === "figma" ? pluginCard("figma", "Figma", "docs", false, false) : i)); const figma = db.items.find((i) => i.id === "figma")!; const detail = figma.detail as Record & { plugin: Record }; detail.own_app_redirect_uri = "https://app.coderhelm.com/settings/integrations/mcp-callback/"; @@ -679,13 +687,17 @@ test("Figma signs in with Coderhelm's app in one click; my own app and a key are }; await page.goto("/settings/integrations#integration-figma"); const card = row(page, "figma"); - const ours = card.getByTestId("coderhelm-app"); - await expect(ours).toContainText("current_user:read, file_content:read"); - // The own app's steps and the key wait behind their disclosures. - await expect(card.getByText("Use my own Figma app", { exact: true }).first()).toBeVisible(); - await expect(card.getByText("Use a key instead", { exact: true })).toBeVisible(); + // What it will do in plain words; the scope names wait behind Details. + await expect(card.getByTestId("access")).toHaveText("Coderhelm reads Figma with this sign-in. It can't change anything in Figma."); + await expect(card.getByTestId("scopes")).toBeHidden(); + // The own app's steps and the key wait together, behind one disclosure. + await expect(card.getByTestId("other-ways").locator("summary")).toHaveText("Other ways to connect"); await expect(card.getByTestId("own-app")).toBeHidden(); - await ours.getByRole("button", { name: "Sign in with Figma" }).click(); + await expect(card.getByTestId("way-key")).toBeHidden(); + await expect(card.getByRole("button", { name: "Sign in with Figma" })).toHaveCount(1); + const tab = context.waitForEvent("page"); + await card.getByRole("button", { name: "Sign in with Figma" }).click(); + await (await tab).waitForEvent("close"); await expect.poll(() => db.calls.some((c) => c.path === "/api/mcp-servers/oauth/callback")).toBe(true); expect(db.calls.some((c) => c.method === "POST" && c.path === "/api/mcp-servers/apps/figma/coderhelm")).toBe(true); expect(db.calls.some((c) => c.method === "PUT" && c.path === "/api/mcp-servers/apps/figma")).toBe(false); diff --git a/dashboard/e2e/mcp-servers.spec.ts b/dashboard/e2e/mcp-servers.spec.ts index ac529a16..728933bf 100644 --- a/dashboard/e2e/mcp-servers.spec.ts +++ b/dashboard/e2e/mcp-servers.spec.ts @@ -108,8 +108,10 @@ function refresh(s: McpServer) { async function mockApi(page: Page, init: Partial = {}): Promise { const db: Backend = { role: "admin", me: "dana@example.com", admins: 1, servers: [], calls: [], ...init }; const json = (r: Route, body: unknown, status = 200) => r.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 (r) => { + // On the context, so a sign-in opened in its own tab is answered here too. + const context = page.context(); + await context.route((url) => url.hostname !== "localhost", (route) => route.abort()); + await context.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (r) => { const req = r.request(); const url = new URL(req.url()); const p = url.pathname; @@ -234,7 +236,7 @@ async function shot(page: Page, name: string) { const row = (page: Page, id: string) => page.getByTestId(`integration-${id}`); -test("adds a server that signs in with OAuth, comes back from the sign-in, and picks its tools", async ({ page }) => { +test("adds a server that signs in with OAuth, connects it in its own tab, and picks its tools", async ({ page, context }) => { const db = await mockApi(page); await page.goto("/settings/integrations"); const section = page.locator("#mcp-servers"); @@ -252,16 +254,24 @@ test("adds a server that signs in with OAuth, comes back from the sign-in, and p await expect(dialog.getByRole("group", { name: "Who signs in" })).toBeVisible(); await shot(page, "mcp-add-oauth"); - await dialog.getByRole("button", { name: "Add and connect" }).click(); - // Back from the sign-in page, on the server's own row with its tools. - await expect(page).toHaveURL(/\/settings\/integrations\/#integration-mcp:docs$/); + await dialog.getByRole("button", { name: "Add server" }).click(); + // Added, and opened on its own row: Connect is the one thing to do next, + // with nothing about tools or history yet. + await expect(page).toHaveURL(/\/settings\/integrations\/?#integration-mcp:docs$/); + const added = row(page, "mcp:docs").getByTestId("integration-panel"); + await expect(added.getByTestId("mcp-manage")).toHaveCount(0); + const tab = context.waitForEvent("page"); + await added.getByRole("button", { name: "Connect", exact: true }).click(); + // The sign-in finishes in its own tab, which closes; this page never left. + await (await tab).waitForEvent("close"); + await expect(row(page, "mcp:docs")).toHaveAttribute("data-status", "connected"); + await expect(page).toHaveURL(/\/settings\/integrations\/?#integration-mcp:docs$/); const callback = db.calls.find((c) => c.path === "/api/mcp-servers/oauth/callback"); expect(callback?.body).toEqual({ state: "state-docs", code: "code-1", iss: ISSUER }); const created = db.calls.find((c) => c.path === "/api/mcp-servers" && c.method === "POST"); expect(created?.body).toMatchObject({ url: "https://mcp.docs.example.com/mcp", name: "Docs", sharing: "shared" }); const panel = row(page, "mcp:docs").getByTestId("integration-panel"); - await expect(panel.getByTestId("mcp-status")).toContainText("Connected"); const picker = panel.getByTestId("mcp-tool-picker"); await expect(picker.getByTestId("mcp-tool")).toHaveCount(4); await expect(picker.locator('[data-tool="search_docs"]').getByTestId("mcp-tool-access")).toHaveText("Reads"); @@ -299,7 +309,9 @@ test("a server that takes a key checks it, keeps it sealed and never shows it ag expect(created?.body).toMatchObject({ header_name: "X-API-Key", header_value: KEY, name: "Search" }); const panel = row(page, "mcp:search").getByTestId("integration-panel"); - await expect(panel.getByTestId("mcp-status")).toContainText("Key in X-API-Key"); + // How it signs in is a detail, behind Details. + await panel.getByTestId("panel-details").locator("summary").click(); + await expect(panel.getByTestId("panel-details")).toContainText("A key, sent in the X-API-Key header"); await expect(page.locator("body")).not.toContainText(KEY); // A key server has no sign-in to start. await expect(panel.getByRole("button", { name: /^Connect/ })).toHaveCount(0); @@ -347,7 +359,7 @@ test("with two admins, newly allowed tools wait for the other admin", async ({ p expect(db.servers[0].tools.find((t) => t.name === "search_docs")?.approved).toBe(true); }); -test("a connection that needs reconnecting says why and reconnects", async ({ page }) => { +test("a connection that needs reconnecting says why and reconnects", async ({ page, context }) => { const why = "The sign-in server refused (invalid_grant: refresh token revoked). Reconnect to sign in again."; await mockApi(page, { servers: [server({ status: "needs_reconnect", status_reason: why, my_connection: { status: "needs_reconnect", status_reason: why, connected_at: "" } })], @@ -360,41 +372,51 @@ test("a connection that needs reconnecting says why and reconnects", async ({ pa await r.getByRole("button", { name: /^Docs, Needs reconnecting\. Reconnect/ }).click(); const panel = r.getByTestId("integration-panel"); await expect(panel.getByTestId("mcp-status-reason")).toHaveText(why); + // The reason and its one action sit together. + await expect(panel.getByTestId("mcp-attention")).toContainText("Needs reconnecting"); await shot(page, "mcp-needs-reconnect"); - await panel.getByRole("button", { name: "Reconnect" }).click(); - await expect(page).toHaveURL(/#integration-mcp:docs$/); + const tab = context.waitForEvent("page"); + await panel.getByTestId("mcp-attention").getByRole("button", { name: "Reconnect" }).click(); + await (await tab).waitForEvent("close"); await expect(row(page, "mcp:docs")).toHaveAttribute("data-status", "connected"); }); -test("a catalog server offers its vendor's sign-in first and keeps the key as a fallback", async ({ page }) => { +test("a catalog server offers its vendor's sign-in first and keeps the key as a fallback", async ({ page, context }) => { const db = await mockApi(page); await page.goto("/settings/integrations"); await row(page, "linear").getByRole("button", { name: /^Linear, Not connected/ }).click(); const panel = row(page, "linear").getByTestId("integration-panel"); - await expect(panel.getByTestId("oauth-offer")).toContainText("No key to paste"); - await expect(panel.getByText("Use a key instead")).toBeVisible(); + await expect(panel.getByTestId("access")).toHaveText( + "You sign in at Linear, then pick which of its tools agents may use. Agents get none until you do, and tools that only read are marked.", + ); + // A key is another way to connect, behind one disclosure. + await expect(panel.getByTestId("other-ways").locator("summary")).toHaveText("Other ways to connect"); await expect(panel.getByLabel("API key")).toBeHidden(); await shot(page, "mcp-catalog-oauth"); + const tab = context.waitForEvent("page"); await panel.getByRole("button", { name: "Sign in with Linear" }).click(); - await expect(page).toHaveURL(/#integration-linear$/); + await (await tab).waitForEvent("close"); expect(db.calls.find((c) => c.path === "/api/mcp-servers" && c.method === "POST")?.body).toEqual({ catalog_id: "linear" }); await expect(row(page, "linear")).toHaveAttribute("data-status", "connected"); await expect(row(page, "linear").getByTestId("integration-panel").getByTestId("mcp-tool-picker")).toBeVisible(); }); -test("a member connects their own account to a server each person signs in to", async ({ page }) => { +test("a member connects their own account to a server each person signs in to", async ({ page, context }) => { const db = await mockApi(page, { role: "member", me: "sam@example.com", servers: [server({ sharing: "personal", my_connection: null })] }); await page.goto("/settings/integrations"); const r = row(page, "mcp:docs"); await expect(r).toHaveAttribute("data-status", "not_connected"); await r.getByRole("button", { name: /^Docs, Not connected/ }).click(); const panel = r.getByTestId("integration-panel"); - await expect(panel.getByTestId("mcp-status-reason")).toHaveText("Each person connects their own account. You haven't yet."); + await expect(panel.getByTestId("mcp-status-reason")).toHaveText( + "Each person signs in to Docs with their own account. Agents use it for that person's work, with only the tools an admin allowed.", + ); // Members don't pick tools or remove servers. await expect(panel.getByRole("button", { name: "Save tools" })).toHaveCount(0); await expect(panel.getByRole("button", { name: /^Remove/ })).toHaveCount(0); + const tab = context.waitForEvent("page"); await panel.getByRole("button", { name: "Connect your account" }).click(); - await expect(page).toHaveURL(/#integration-mcp:docs$/); + await (await tab).waitForEvent("close"); expect(db.calls.some((c) => c.path === "/api/mcp-servers/oauth/callback")).toBe(true); await expect(row(page, "mcp:docs")).toHaveAttribute("data-status", "connected"); }); @@ -419,7 +441,7 @@ test("a key for a server whose vendor takes one connects to that server", async await page.goto("/settings/integrations"); await row(page, "linear").getByRole("button", { name: /^Linear, Not connected/ }).click(); const panel = row(page, "linear").getByTestId("integration-panel"); - await panel.getByText("Use a key instead").click(); + await panel.getByTestId("other-ways").locator("summary").click(); const form = panel.getByTestId("remote-key-form"); await form.getByLabel("API key").fill("lin_api_example"); await form.getByRole("button", { name: "Connect with this key" }).click(); @@ -454,7 +476,7 @@ test("a server no key works for says why, with no key form", async ({ page }) => const hosting = row(page, "hosting").getByTestId("integration-panel"); await expect(hosting.getByRole("button", { name: "Sign in with Hosting" })).toBeVisible(); await expect(hosting.getByTestId("key-unavailable")).toHaveText("Hosting's MCP server takes no key: use Sign in with Hosting."); - await expect(hosting.getByText("Use a key instead")).toHaveCount(0); + await expect(hosting.getByTestId("other-ways")).toHaveCount(0); await expect(hosting.locator("input")).toHaveCount(0); await row(page, "cache").getByRole("button", { name: /^Cache, Not connected/ }).click(); const cache = row(page, "cache").getByTestId("integration-panel"); diff --git a/dashboard/e2e/oauth-callback.spec.ts b/dashboard/e2e/oauth-callback.spec.ts index f39cc8d0..e1f78376 100644 --- a/dashboard/e2e/oauth-callback.spec.ts +++ b/dashboard/e2e/oauth-callback.spec.ts @@ -79,8 +79,11 @@ test("an expired knowledge state still reads as Knowledge from its tag", async ( test("a state from an older gateway (no kind) still finishes through the API", async ({ page }) => { const calls = await mockApi(page, () => ({ status: 200, body: { server: { id: "ks-notion", name: "Notion (knowledge)", catalog_id: "source:notion" }, tools_error: null } })); + // Knowledge reads ?connected= and takes it out of the address at once, so + // the arrival is caught as it happens rather than by polling the address. + const arrived = page.waitForURL(/\/knowledge\/\?connected=notion$/, { waitUntil: "commit" }); await page.goto("/settings/integrations/mcp-callback/?code=c1&state=plainrandomstate"); - await expect(page).toHaveURL(/\/knowledge\/\?connected=notion$/); + await arrived; expect(calls.callback).toHaveLength(1); }); diff --git a/dashboard/src/app/connections/page.tsx b/dashboard/src/app/connections/page.tsx index e57f3ff5..fd7f24e9 100644 --- a/dashboard/src/app/connections/page.tsx +++ b/dashboard/src/app/connections/page.tsx @@ -8,7 +8,7 @@ import { RoleGuard } from "@/components/role-guard"; import { Page, PageHeader } from "@/components/page"; import { BrandIcon } from "@/components/brand-icons"; import { AddMcpServerDialog, McpServerPanel } from "@/components/mcp-servers"; -import { PluginPanel } from "@/components/mcp-server-panel"; +import { CatalogPanel } from "@/components/mcp-server-panel"; import { Chip, List, ListError, ListSection, ListSkeleton, type Tone } from "@/components/list"; import { linkButton, secondaryButton } from "@/components/ui"; import { EmptyState } from "@/components/empty-state"; @@ -100,9 +100,9 @@ function ConnectionsPage() { {open === item.id && (
- {item.reason &&

{item.reason}

} - {remote && setOpen("") : undefined} />} - {!added && canEdit && setOpen("")} />} +

{item.does}

+ {added && remote && setOpen("")} />} + {!added && setOpen("")} />}

+ ) : null} + + )} + {item.status === "connected" && item.reason && uses.length < 2 && ( +

+ {item.reason} +

+ )} + {(saved || k) && } + {(saved || k) && uses.length > 1 && void act(u)} />} {c.kind === "confluence" && c.write_enabled && (c.write_pages?.length ?? 0) > 0 && ( -

Writes on: may add text to pages {c.write_pages?.join(", ")}.

+

Writes on: may add text to pages {c.write_pages?.join(", ")}.

)} - { - onSaved(); - }} - /> - {c.connected && (!viaApp || Boolean(c.updated_at)) && ( -

- + + {/* Not connected: what it needs and the one form. */} + {!saved && !k && canEdit && form(true)} + {/* Connected for Knowledge only: runs take one switch above; a token is the other way. */} + {!saved && k && canEdit && ( + + + {form(true)} + + + )} + {saved && canEdit && ( + + {form(true)} + + )} + {k && canEdit && ( +

+ Manage {k.label} sources in Knowledge

)} - + + {saved && canEdit && (!viaApp || Boolean(c.updated_at)) && ( + void remove()} + testId="connector-remove" + > + {viaApp + ? "Writes turn off and the page list and spaces are cleared. Agents keep reading through the Jira app." + : viaSignIn + ? "Agents stop reading pages during runs. Knowledge keeps syncing with the same sign-in." + : "Agents stop using it right away and the saved key is deleted."} + + )} + {k && canEdit && !k.personal && } +
+ ); +} + +/** A product that is only synced into Knowledge (Google Drive): its sign-in, seen where sign-ins are. */ +function KnowledgePanel({ item, canEdit, onChanged }: { item: Integration; canEdit: boolean; onChanged: () => Promise }) { + const k = knowledgeOf(item); + if (!k) return null; + const attention = item.status !== "connected" && item.status !== "not_connected"; + return ( +
+ {attention && {canEdit && }} + +

+ Manage {k.label} sources in Knowledge +

+ {canEdit && !k.personal && } +
); } diff --git a/dashboard/src/components/connections.tsx b/dashboard/src/components/connections.tsx index 4e2b9a9d..dcd15ca0 100644 --- a/dashboard/src/components/connections.tsx +++ b/dashboard/src/components/connections.tsx @@ -14,6 +14,8 @@ import { Select } from "@/components/select"; /** `via` of a Confluence connection that goes through the team's Coderhelm Jira app. */ export const JIRA_APP = "jira_app"; +/** `via` of a Confluence connection agents read with the Atlassian sign-in the team made for Knowledge. */ +export const SIGN_IN = "sign_in"; /** What a key-based connection needs, shown above its form. */ const NEEDS: Record = { @@ -34,7 +36,19 @@ const list = (s: string) => * New Relic, Confluence or OpenSearch: the key or password (sealed for the * team, never shown again) and what agents may read. Saving tests it. */ -export function ConnectorForm({ item, onSaved }: { item: Connector; onSaved: (c: Connector) => void }) { +export function ConnectorForm({ + item, + onSaved, + bare = false, + quiet = false, +}: { + item: Connector; + onSaved: (c: Connector) => void; + /** Inside a titled part of a card: no rule above it. */ + bare?: boolean; + /** Not the card's main action (settings of something already connected): its button is secondary. */ + quiet?: boolean; +}) { const k = item.kind as KeyConnectorKind; const [key, setKey] = useState(""); const [region, setRegion] = useState(item.region || "us"); @@ -59,6 +73,10 @@ export function ConnectorForm({ item, onSaved }: { item: Connector; onSaved: (c: // its own API token. const [useToken, setUseToken] = useState(false); const viaApp = k === "confluence" && item.via === JIRA_APP && !useToken; + // Confluence read with the team's Atlassian sign-in: no address, email or + // token either, and never a write (the sign-in only reads). + const viaSignIn = k === "confluence" && item.via === SIGN_IN && !useToken; + const noKey = viaApp || viaSignIn; // A new REST API, or another OpenSearch cluster, is named here; a saved one // keeps its name (it's its key). const naming = !item.connected && (k === "rest" || Boolean(item.needs_name)); @@ -76,7 +94,7 @@ export function ConnectorForm({ item, onSaved }: { item: Connector; onSaved: (c: if (k === "newrelic") Object.assign(body, { region, account_ids: list(accountIds) }); if (k === "confluence") { const writes = { spaces: list(spaces), write_enabled: writeEnabled, write_pages: writeEnabled ? list(writePages) : [] }; - Object.assign(body, viaApp ? { via: JIRA_APP, ...writes } : { via: "", site, email, ...writes }); + Object.assign(body, viaSignIn ? { via: SIGN_IN, spaces: list(spaces) } : viaApp ? { via: JIRA_APP, ...writes } : { via: "", site, email, ...writes }); } if (k === "opensearch") Object.assign(body, { site, email, indexes: list(indexes), hidden_fields: list(hiddenFields) }); if (k === "rest") Object.assign(body, { site, header_name: headerName, paths: list(paths), hidden_fields: list(hiddenFields) }); @@ -109,13 +127,23 @@ export function ConnectorForm({ item, onSaved }: { item: Connector; onSaved: (c: return (
{ e.preventDefault(); save(); }} > - {viaApp ? ( + {viaSignIn ? ( +
+

+ Agents read pages with the team's Atlassian sign-in{item.site ? ` on ${item.site}` : ""}, the one Knowledge syncs with. No token is + needed, and it only reads. +

+ +
+ ) : viaApp ? (

Connected through the Jira app{item.site ? ` on ${item.site}` : ""}. Agents read the pages the Coderhelm app can see there; no token @@ -139,7 +167,7 @@ export function ConnectorForm({ item, onSaved }: { item: Connector; onSaved: (c: : `How agents pick this one, like ${k === "rest" ? "billing or bookings" : "search or logs"}. It can't be changed later.`, k === "rest" ? "bookings" : "search", )} - {viaApp ? null : replacingKey ? ( + {noKey ? null : replacingKey ? ( - {!viaApp && ( + {!noKey && ( <> {text("site", "Confluence address", site, setSite, undefined, "https://yourcompany.atlassian.net")} {text("email", "Account email", email, setEmail, "The Atlassian account the token belongs to. Coderhelm sees what it can see.")} @@ -194,17 +222,19 @@ export function ConnectorForm({ item, onSaved }: { item: Connector; onSaved: (c: "Spaces", spaces, setSpaces, - `Space keys agents may read, like ENG. Leave empty for every space the ${viaApp ? "app" : "account"} can see.`, + `Space keys agents may read, like ENG. Leave empty for every space the ${viaSignIn ? "sign-in" : viaApp ? "app" : "account"} can see.`, "ENG, OPS", )} - - {writeEnabled && text("pages", "Writable page ids", writePages, setWritePages, "The number in the page's address, after /pages/.", "123456789")} + {!viaSignIn && ( + + )} + {writeEnabled && !viaSignIn && text("pages", "Writable page ids", writePages, setWritePages, "The number in the page's address, after /pages/.", "123456789")} )} {k === "opensearch" && ( @@ -265,7 +295,7 @@ export function ConnectorForm({ item, onSaved }: { item: Connector; onSaved: (c:

)}
-
diff --git a/dashboard/src/components/integration-panel.tsx b/dashboard/src/components/integration-panel.tsx new file mode 100644 index 00000000..e99f00e6 --- /dev/null +++ b/dashboard/src/components/integration-panel.tsx @@ -0,0 +1,309 @@ +"use client"; + +import Link from "next/link"; +import { useId, type ReactNode } from "react"; +import type { Integration, IntegrationUse, SignInStart } from "@/lib/api"; +import { timeAgo } from "@/lib/data-sources"; +import { INTEGRATION_STATUS } from "@/lib/integration-status"; +import { spanWords, useSignIn } from "@/lib/sign-in-flow"; +import { Callout } from "./callout"; +import { Disclosure } from "./disclosure"; +import { TechnicalDetails } from "./problem"; +import { buttonClass, dangerButton, linkButton, primaryButton, secondaryButton } from "./ui"; + +// The parts every opened card on Integrations is made of, so each one reads +// the same way whatever it connects: +// +// - Not connected: what Coderhelm will be able to do, one primary action, +// what happens next. Other ways to connect sit under one disclosure. +// Nothing about tools, instructions or history yet. +// - Signing in: the same button shows progress, with Cancel, and always +// ends in an outcome with its reason and the next step. +// - Connected: who connected it and when, when it was last checked, what it +// is used for; a Manage area whose parts hide when empty; Disconnect last, +// worded and coloured as the destructive action it is. +// - Needs attention: the plain reason and one action. + +/** A titled part of an opened card. */ +export function PanelSection({ title, children, testId }: { title: string; children: ReactNode; testId?: string }) { + const id = useId(); + return ( +
+

+ {title} +

+
{children}
+
+ ); +} + +function upperFirst(s: string): string { + return s ? s[0].toUpperCase() + s.slice(1) : s; +} + +/** One fact about a connection: a label and its value. */ +export interface Fact { + label: string; + value: ReactNode; +} + +/** Who connected it and when, how, and when it was last checked: only the facts there are. */ +export function ConnectionFacts({ item, extra = [] }: { item: Integration; extra?: Fact[] }) { + const facts: Fact[] = []; + if (item.how) facts.push({ label: "Connected with", value: upperFirst(item.how) }); + if (item.connected_by) facts.push({ label: "Connected by", value: {item.connected_by} }); + if (item.connected_at) facts.push({ label: "Connected", value: timeAgo(item.connected_at) }); + facts.push(...extra); + if (item.last_check) facts.push({ label: "Last checked", value: timeAgo(item.last_check) }); + if (facts.length === 0) return null; + return ( +
+ {facts.map((f) => ( +
+
{f.label}
+
{f.value}
+
+ ))} +
+ ); +} + +const USE_STATE: Record = { + on: { label: "On", dot: "bg-emerald-400", text: "text-zinc-200" }, + attention: { label: "Needs attention", dot: "bg-amber-400", text: "text-amber-300" }, + ready: { label: "Off", dot: "bg-zinc-600", text: "text-zinc-400" }, + needs: { label: "Not connected", dot: "bg-zinc-600", text: "text-zinc-400" }, + off: { label: "Off", dot: "bg-zinc-600", text: "text-zinc-400" }, +}; + +/** + * What the product is used for, one row per use: on (and with what), or + * what turning it on takes, with the one control that does it. `onAction` + * handles the actions the page performs (`use_in_runs`); links are links. + */ +export function UsesList({ + uses, + canEdit, + busy, + onAction, +}: { + uses: IntegrationUse[]; + canEdit: boolean; + busy?: string; + onAction?: (use: IntegrationUse) => void; +}) { + if (uses.length === 0) return null; + return ( + +
    + {uses.map((u) => { + const st = USE_STATE[u.state]; + const a = u.action; + // Signing in again, checking and adding a key are the card's one + // action above; a row offers only what is its own. + const own = a && (a.kind === "link" || a.kind === "use_in_runs"); + return ( +
  • +
    +

    + {u.label} + + + {u.state === "on" && u.how && with {u.how}} +

    + {u.detail && u.state !== "on" &&

    {u.detail}

    } +
    + {canEdit && own && a.kind === "link" && ( + + {a.label} + + )} + {canEdit && own && a.kind !== "link" && ( + + )} +
  • + ); + })} +
+
+ ); +} + +/** Needs attention: the plain reason and the one action that fixes it. */ +export function Attention({ item, children }: { item: Integration; children?: ReactNode }) { + if (item.status === "connected" || item.status === "not_connected") return null; + const label = INTEGRATION_STATUS[item.status].label; + return ( + + {item.reason &&

{item.reason}

} + {children &&
{children}
} +
+ ); +} + +/** + * The one sign-in control: a primary button that opens the sign-in page in + * a new tab, shows that it is waiting (with Cancel), and ends in an outcome + * that says why and what to do next. + */ +export function SignInControl({ + name, + ids, + label, + begin, + onConnected, + onReturn, + disabled, + variant = "primary", + testId = "sign-in", +}: { + /** The product, as people know it ("Figma"). */ + name: string; + /** The connection and catalog ids whose outcome is this control's. */ + ids: string[]; + label: string; + /** Asks the API where the sign-in page is. */ + begin: () => Promise; + onConnected: () => void | Promise; + onReturn?: () => void | Promise; + disabled?: boolean; + variant?: "primary" | "secondary"; + testId?: string; +}) { + const flow = useSignIn({ name, ids, onConnected, onReturn }); + const { state } = flow; + const noteId = useId(); + const busy = state.stage === "starting" || state.stage === "waiting"; + const outcome = state.stage === "ended" ? state.outcome : null; + const seconds = state.stage === "waiting" ? Math.max(1, Math.round((state.until - Date.now()) / 1000)) : 0; + return ( +
+
+ + {busy && ( + + )} + {outcome?.kind === "blocked" && ( + + )} +
+

+ {state.stage === "waiting" + ? `Finish signing in in the ${name} tab. This page updates on its own; the sign-in stays open for ${spanWords(seconds)}.` + : state.stage === "starting" + ? `Opening ${name} in a new tab…` + : outcome?.kind === "cancelled" + ? "Sign-in cancelled. Nothing was connected." + : `Opens ${name} in a new tab. You come back here when done.`} +

+ {outcome && outcome.kind !== "cancelled" && ( + +

{outcome.message}

+ {outcome.code && } +
+ )} +
+ ); +} + +/** The other ways to connect, behind one disclosure: never beside the default. */ +export function OtherWays({ children, open }: { children: ReactNode; open?: boolean }) { + return ( +
+ +
{children}
+
+
+ ); +} + +/** One of the other ways: a name, a line on when to pick it, and its form. */ +export function Way({ title, when, children, testId }: { title: string; when?: ReactNode; children: ReactNode; testId?: string }) { + const id = useId(); + return ( +
+

+ {title} +

+ {when &&

{when}

} +
{children}
+
+ ); +} + +/** The technical side (addresses, permission names), for whoever needs it. */ +export function PanelDetails({ rows }: { rows: Fact[] }) { + const shown = rows.filter((r) => r.value !== "" && r.value !== null && r.value !== undefined); + if (shown.length === 0) return null; + return ( +
+ +
+ {shown.map((f) => ( +
+
{f.label}
+
{f.value}
+
+ ))} +
+
+
+ ); +} + +/** The destructive end of a card: what goes, and the button that does it. */ +export function DangerRow({ + title, + children, + label, + onClick, + busy, + testId = "disconnect", +}: { + title: string; + /** What stops working and what is kept, in a sentence. */ + children: ReactNode; + label: string; + onClick: () => void; + busy?: boolean; + testId?: string; +}) { + return ( +
+
+

{title}

+

{children}

+
+ +
+ ); +} + +/** A link that reads as one, for "Manage sources in Knowledge". */ +export function PanelLink({ href, children }: { href: string; children: ReactNode }) { + return ( + + {children} + + ); +} diff --git a/dashboard/src/components/knowledge-connection.tsx b/dashboard/src/components/knowledge-connection.tsx new file mode 100644 index 00000000..a3c023fa --- /dev/null +++ b/dashboard/src/components/knowledge-connection.tsx @@ -0,0 +1,88 @@ +"use client"; + +import { useState } from "react"; +import type { KnowledgeSignIn, SignInStart } from "@/lib/api"; +import { errorMessage } from "@/lib/data-sources"; +import { knowledge as knowledgeApi, type SourceKind } from "@/lib/knowledge"; +import { useConfirm } from "./confirm-dialog"; +import { useToast } from "./toast"; +import { DangerRow, SignInControl } from "./integration-panel"; + +// The sign-in a team made so Knowledge can sync a product (Confluence, +// Notion, Google Drive; for Sanity, each person's own), as its card on +// Integrations shows it: renewing it and disconnecting it. + +/** Starts the Knowledge sign-in again: the team's, or this person's own. */ +export async function beginKnowledgeSignIn(k: KnowledgeSignIn): Promise { + const kind = k.kind as SourceKind; + if (k.personal) { + const r = await knowledgeApi.signIn(kind); + if (!r.authorize_url) throw new Error(`You are already signed in to ${k.label}.`); + return { authorize_url: r.authorize_url, server_id: k.server_id }; + } + return { server_id: k.server_id, ...(await knowledgeApi.connect(kind)) }; +} + +/** "Sign in again" for a Knowledge sign-in that stopped working. */ +export function KnowledgeSignInControl({ k, label = "Sign in again", onChanged }: { k: KnowledgeSignIn; label?: string; onChanged: () => void | Promise }) { + return ( + beginKnowledgeSignIn(k)} + onConnected={onChanged} + onReturn={onChanged} + testId="knowledge-sign-in" + /> + ); +} + +function sourcesWords(n: number): string { + return `${n} source${n === 1 ? "" : "s"}`; +} + +/** Disconnecting the team's Knowledge sign-in: what stops, and the button. */ +export function KnowledgeDisconnect({ + k, + beside = false, + onChanged, +}: { + k: KnowledgeSignIn; + /** The card also has a connection for runs with its own way out: this one names Knowledge. */ + beside?: boolean; + onChanged: () => void | Promise; +}) { + const [busy, setBusy] = useState(false); + const { confirm } = useConfirm(); + const { toast } = useToast(); + const go = async () => { + const ok = await confirm({ + title: `Disconnect ${k.label} from Knowledge?`, + message: + k.sources > 0 + ? `Its ${sourcesWords(k.sources)} in Knowledge stop syncing until someone signs in again. What is already synced stays.` + : `Coderhelm forgets the ${k.label} sign-in Knowledge syncs with, and revokes it where ${k.label} allows.`, + confirmLabel: "Disconnect", + destructive: true, + }); + if (!ok) return; + setBusy(true); + try { + await knowledgeApi.disconnect(k.kind as SourceKind); + toast(`${k.label} disconnected`); + await onChanged(); + } catch (e) { + toast(errorMessage(e, "Couldn't disconnect it."), "error"); + } finally { + setBusy(false); + } + }; + return ( + void go()} busy={busy} testId="disconnect-knowledge"> + {k.sources > 0 + ? `Coderhelm forgets the sign-in. Its ${sourcesWords(k.sources)} in Knowledge stop syncing until someone signs in again.` + : "Coderhelm forgets the sign-in. Nothing in Knowledge syncs from it yet."} + + ); +} diff --git a/dashboard/src/components/mcp-server-panel.tsx b/dashboard/src/components/mcp-server-panel.tsx index caf13976..2392822c 100644 --- a/dashboard/src/components/mcp-server-panel.tsx +++ b/dashboard/src/components/mcp-server-panel.tsx @@ -1,90 +1,418 @@ "use client"; -import { useState } from "react"; -import { api, type Integration, type McpServer, type OwnAppState, type PluginDef } from "@/lib/api"; +import { useEffect, useState, type ReactNode } from "react"; +import { api, type Integration, type KnowledgeSignIn, type McpServer, type OwnAppState, type PluginDef, type SignInStart } from "@/lib/api"; import { errorMessage } from "@/lib/data-sources"; +import { useCan } from "@/hooks/use-can"; import { Field, SecretInput } from "./field"; import { Disclosure } from "./disclosure"; import { MarkdownEditor } from "./markdown-editor"; import { useConfirm } from "./confirm-dialog"; import { useToast } from "./toast"; import { inputClass, linkButton, primaryButton, secondaryButton } from "./ui"; -import { connectCatalogServer, startMcpSignIn } from "./mcp-servers"; +import { McpManage, beginCatalogSignIn, viewerStatus } from "./mcp-servers"; import { CopyButton } from "./copy-button"; +import { Code } from "./settings/code"; import { HybridAppChoice } from "./hybrid-app-choice"; +import { KnowledgeDisconnect, KnowledgeSignInControl } from "./knowledge-connection"; +import { Attention, ConnectionFacts, DangerRow, OtherWays, PanelDetails, PanelLink, PanelSection, SignInControl, UsesList, Way, type Fact } from "./integration-panel"; -// A catalog MCP server (Sentry, Linear, Notion…), opened in place on -// Integrations and on Connections: signing in through the vendor's remote -// server when it has one, or a key, its instructions and turning it off. +// A catalog product (Figma, Sentry, Linear, Notion, Sanity…), opened in +// place on Integrations. One pattern whatever it connects with: +// +// - Not connected: what Coderhelm will be able to do, the one default way +// to connect (Coderhelm's app, else the vendor's own sign-in, else the +// team's own app, else a key), and every other way under "Other ways to +// connect". +// - Connected: who connected it and when, what it is used for, then Manage +// (tools, instructions, recent calls: each only when there is something), +// and Disconnect last. +// - Needs attention: the reason and one action. +// +// The card's status comes from the API, worked out from every record the +// team has for the product, so a sign-in made for Knowledge shows here too. -/** An MCP server: credentials (entered here, never shown again), its test, its instructions, and turning it off. */ -export function PluginPanel({ item, onChanged, onClose }: { item: Integration; onChanged: () => Promise; onClose: () => void }) { - const d = item.detail as { - plugin: PluginDef; - enabled: boolean; - has_credentials: boolean; - custom_prompt: string; - remote?: McpServer | null; - own_app?: OwnAppState | null; - own_app_redirect_uri?: string | null; - coderhelm_app?: boolean; - }; +type WayId = "ours" | "remote" | "own" | "key"; + +interface Unused { + id: string; + name: string; + kind: string; + note: string; +} + +interface Detail { + plugin: PluginDef; + enabled: boolean; + has_credentials: boolean; + custom_prompt: string; + remote?: McpServer | null; + own_app?: OwnAppState | null; + own_app_redirect_uri?: string | null; + coderhelm_app?: boolean; + knowledge?: KnowledgeSignIn | null; + unused?: Unused[]; +} + +function hostOf(url: string): string { + try { + return new URL(url).host; + } catch { + return url; + } +} + +/** What Coderhelm will be able to do, in a sentence, for the way a card connects by default. */ +function accessOf(p: PluginDef, way: WayId): string { + if (way === "ours" || way === "own") { + return p.own_app?.reads ?? `Coderhelm reads ${p.name} with this sign-in. It can't change anything in ${p.name}.`; + } + if (way === "remote") { + return `You sign in at ${p.name}, then pick which of its tools agents may use. Agents get none until you do, and tools that only read are marked.`; + } + const least = p.recommended_permissions ? ` Give it the least access that works: ${p.recommended_permissions.toLowerCase()}.` : ""; + return `Agents use ${p.name} with a key you paste here. It is sealed when saved and never shown again.${least}`; +} + +export function CatalogPanel({ + item, + canEdit, + onChanged, + onClose, +}: { + item: Integration; + canEdit: boolean; + onChanged: () => Promise; + onClose: () => void; +}) { + const d = item.detail as unknown as Detail; const p = d.plugin; - const keyForm = ; - // The vendor's MCP server takes only apps it approved, but its API takes - // Coderhelm's app or the team's own: sign in with one, or use a key. - if (p.own_app) { - const signedIn = d.own_app?.status === "connected"; - const mine = d.own_app && (d.own_app.source ?? "own") === "own" ? d.own_app : null; - const ownPanel = ; - if (d.coderhelm_app) { - // Coderhelm's app: one sign-in button; the team's own app and a key - // are the other choices, behind their disclosures. - const ours = d.own_app && d.own_app.source === "coderhelm" ? d.own_app : null; + const [remote, setRemote] = useState(d.remote ?? null); + useEffect(() => setRemote(d.remote ?? null), [d.remote]); + const { can } = useCan(); + const { toast } = useToast(); + const { confirm } = useConfirm(); + const [busy, setBusy] = useState(""); + + const own = d.own_app ?? null; + const ours = own && own.source === "coderhelm" ? own : null; + const mine = own && (own.source ?? "own") === "own" ? own : null; + const personalRemote = remote?.auth === "oauth" && remote.sharing === "personal"; + const mayConnectRemote = personalRemote ? can("mcp_connect") : canEdit; + const rv = remote ? viewerStatus(remote) : null; + const k = d.knowledge ?? null; + + // The ways this product can connect, the default first. + const ways: WayId[] = []; + if (p.own_app && d.coderhelm_app) ways.push("ours"); + if (p.remote_url || remote?.auth === "oauth") ways.push("remote"); + if (p.own_app) ways.push("own"); + // A key for a vendor's own server sets that server up, so it is offered until the server is. + if (p.credential_fields.length > 0 && !p.key_unavailable && !(p.remote_key && remote)) ways.push("key"); + // The way it is connected now, if it is. + const current: WayId | null = + own?.status === "connected" ? (ours ? "ours" : "own") : rv?.status === "connected" ? "remote" : d.enabled && d.has_credentials ? "key" : null; + const uses = item.uses ?? []; + const runs = uses.find((u) => u.id === "runs"); + // Whether agents have it: the API's word when it says, else the records'. + const runsOn = runs ? runs.state === "on" : current !== null; + // An admin takes the default way; a member only ever signs in their own account. + const primary: WayId | undefined = canEdit ? ways[0] : ways.includes("remote") && mayConnectRemote ? "remote" : undefined; + const ids = [p.id, `app-${p.id}`, `app:${p.id}`]; + + const act = async (label: string, fn: () => Promise) => { + setBusy(label); + try { + await fn(); + } catch (e) { + toast(errorMessage(e, "That didn't work."), "error"); + } finally { + setBusy(""); + } + }; + + const beginOurs = async (): Promise => { + const r = await api.connectCoderhelmApp(p.id); + return { ...r, server_id: r.server_id ?? r.own_app.id }; + }; + const beginRemote = async (): Promise => (remote ? { ...(await api.connectMcpServer(remote.id)), server_id: remote.id } : beginCatalogSignIn(p.id)); + + const signIn = (way: "ours" | "remote", label: string, variant: "primary" | "secondary" = "primary") => ( + + ); + + // A form is the main action only where it is the default way; among the other ways it is quiet. + const ownForm = (quiet: boolean) => ; + const keyForm = (quiet: boolean) => + p.remote_key && ways.includes("remote") && !d.enabled ? : ; + + // ── Needs attention: which part is broken, and its one action ────── + const fix = (): ReactNode => { + if (item.action === "reconnect") { + if (own && own.status !== "connected" && own.status !== "not_connected") { + return ours ? signIn("ours", "Sign in again") : ({ ...(await api.connectMcpServer(own.id)), server_id: own.id })} onConnected={onChanged} onReturn={onChanged} testId="own-app-sign-in" />; + } + if (rv && (rv.status === "needs_reconnect" || rv.status === "failed")) return mayConnectRemote ? signIn("remote", "Reconnect") : null; + if (k && k.status !== "connected") return ; + return null; + } + if (item.action === "check_again" && canEdit) { return ( -
- void onChanged()} /> - - - {ownPanel} - - - {keyForm} - -
+ + ); + } + return null; + }; + + // ── Other ways to connect ────────────────────────────────────────── + const others = (skip: WayId | null) => { + const parts: ReactNode[] = []; + if (!canEdit) return null; + for (const w of ways) { + if (w === skip) continue; + if (w === "ours") { + parts.push( + + {signIn("ours", `Sign in with ${p.name}`, "secondary")} + , + ); + } else if (w === "remote" && mayConnectRemote) { + parts.push( + + {signIn("remote", `Sign in with ${p.name}`, "secondary")} + , + ); + } else if (w === "own") { + parts.push( + + {ownForm(true)} + , + ); + } else if (w === "key") { + parts.push( + + {keyForm(true)} + , + ); + } + } + // Why no key works, when none does: with the other ways when there are + // some, else as a plain line (never a disclosure holding one sentence). + const noKey = p.key_unavailable ? ( +

+ {p.key_unavailable} +

+ ) : null; + for (const u of d.unused ?? []) { + parts.push( + +
+ +
+
, ); } + if (parts.length === 0) return noKey; return ( -
- void onChanged()} /> - {ownPanel} - - {keyForm} - -
+ + {parts} + {noKey} + ); - } - const noKey = p.key_unavailable ? ( -

- {p.key_unavailable} -

- ) : null; - if (!p.remote_url) return
{noKey ?? keyForm}
; - const hasKeys = p.credential_fields.length > 0; + }; + + // ── Details: the technical side ──────────────────────────────────── + const detailRows = (way: WayId | null): Fact[] => { + const app = p.own_app; + const viaApp = way === "ours" || way === "own"; + const address = way === "remote" ? (remote?.url ?? p.remote_url ?? "") : ""; + const scopes = viaApp ? (app?.scopes ?? []) : way === "remote" ? (remote?.scopes ?? []) : []; + return [ + { label: "Signs in at", value: viaApp && app ? hostOf(app.authorize) : way === "remote" && (remote?.issuer || address) ? hostOf(remote?.issuer || address) : "" }, + { label: "Server address", value: address ? {address} : "" }, + { label: "Permissions asked for", value: scopes.length ? {scopes.join(", ")} : "" }, + { label: "Who signs in", value: viaApp ? "One account for the team" : way === "remote" ? (personalRemote ? "Each person, with their own account" : "One account for the team") : "" }, + ]; + }; + + // ── Disconnect ───────────────────────────────────────────────────── + const disconnect = () => + act("disconnect", async () => { + if (current === "key") { + const ok = await confirm({ title: `Turn off ${p.name}?`, message: "Agents stop using it and its saved key is deleted.", confirmLabel: "Turn off", destructive: true }); + if (!ok) return; + await api.disablePlugin(p.id); + onClose(); + } else { + const id = current === "remote" ? remote!.id : own!.id; + const ok = await confirm({ + title: personalRemote && current === "remote" ? `Disconnect your ${p.name} account?` : `Disconnect ${p.name}?`, + message: `Coderhelm revokes the sign-in where ${p.name} allows it and forgets it. Agents stop using it until someone signs in again.`, + confirmLabel: "Disconnect", + destructive: true, + }); + if (!ok) return; + const r = await api.disconnectMcpServer(id); + toast(r.revoked ? "Disconnected and revoked" : "Disconnected"); + } + await onChanged(); + }); + const attention = item.status !== "connected" && item.status !== "not_connected"; + const connectedSomehow = uses.some((u) => u.state === "on") || current !== null; + const facts: Fact[] = uses.length < 2 && current ? [{ label: "Used for", value: "Runs and reviews" }] : []; + // The way agents would use that is set up and broken: its fix is the card's one action. + const stopped = (st: string | undefined) => !!st && st !== "connected" && st !== "not_connected"; + const brokenWay: WayId | null = + !attention || runsOn || (runs && runs.state !== "attention") + ? null + : stopped(own?.status) + ? ours + ? "ours" + : "own" + : stopped(rv?.status) + ? "remote" + : // Switched on with no key saved, where a sign-in exists: nothing is + // broken, it was never connected. The default way is offered, with + // the key among the other ways. + d.enabled && (d.has_credentials || ways[0] === "key" || ways.length === 0) + ? "key" + : null; + return ( -
- {!d.remote && } - {noKey} - {!noKey && hasKeys && !d.remote && ( - - {p.remote_key ? : keyForm} - +
+ {attention && {fix()}} + {/* A note the facts below don't already say ("No tools are allowed yet, so agents don't get it."). */} + {item.status === "connected" && item.reason && uses.length < 2 && current !== "ours" && current !== "own" && ( +

+ {item.reason} +

)} - {!noKey && hasKeys && d.remote && !p.remote_key && ( - - {keyForm} - + {connectedSomehow && } + {connectedSomehow && uses.length > 1 && } + + {/* Not connected for runs: what it will do, one action, what happens next. */} + {!runsOn && primary && !brokenWay && ( + + {p.own_app && canEdit && void onChanged()} />} +

+ {accessOf(p, primary)} +

+ {primary === "ours" && signIn("ours", `Sign in with ${p.name}`)} + {primary === "remote" && signIn("remote", personalRemote ? "Connect your account" : `Sign in with ${p.name}`)} + {primary === "own" && ownForm(false)} + {primary === "key" && keyForm(false)} + + {others(primary)} +
)} + {!runsOn && !primary && p.key_unavailable && ( +

+ {p.key_unavailable} +

+ )} + {brokenWay === "key" && canEdit && ( + + + + )} + {brokenWay && others(brokenWay)} + + {/* Connected: Manage, each part only when there is something in it. */} + {current === "remote" && remote && } + {current && current !== "remote" && canEdit && ( + + {d.enabled && } + {current === "key" && ( + + + + )} + {current === "ours" && signIn("ours", "Sign in again", "secondary")} + {current === "own" && ownForm(true)} + + )} + {runsOn && } + {runsOn && others(current)} + {k && canEdit && !k.personal && ( +

+ Manage {k.label} sources in Knowledge +

+ )} + + {/* Disconnect: last, and worded as what it is. */} + {current && (current === "remote" ? mayConnectRemote : canEdit) && ( + + {current === "key" ? "Agents stop using it and the saved key is deleted." : `Agents stop using ${p.name} until someone signs in again.${current === "remote" ? " The tools you allowed stay picked." : ""}`} + + )} + {k && canEdit && !k.personal && } +
+ ); +} + +function ConnectSection({ title, children }: { title: string; children: ReactNode }) { + if (title) { + return ( + + {children} + + ); + } + return ( +
+ {children}
); } @@ -132,7 +460,7 @@ function RemoteKeyForm({ plugin, onChanged }: { plugin: PluginDef; onChanged: ()

)}
-
@@ -140,122 +468,44 @@ function RemoteKeyForm({ plugin, onChanged }: { plugin: PluginDef; onChanged: () ); } -/** Signing in through the vendor's own remote server: no key to paste, and tools allowed one by one. */ -function OAuthOffer({ plugin }: { plugin: PluginDef }) { - const [busy, setBusy] = useState(false); - const { toast } = useToast(); - return ( -
-

- You sign in at {plugin.name} and choose which of its tools agents may use. No key to paste. -

-
- -
-
- ); -} - -/** Signing in with Coderhelm's own app with the vendor: nothing to create or paste. */ -function CoderhelmAppSignIn({ plugin, state }: { plugin: PluginDef; state: OwnAppState | null }) { - const [busy, setBusy] = useState(false); - const [error, setError] = useState(""); - const scopes = plugin.own_app?.scopes ?? []; - const go = async () => { - setBusy(true); - setError(""); - try { - const r = await api.connectCoderhelmApp(plugin.id); - window.location.assign(r.authorize_url); - } catch (e) { - setError(errorMessage(e, "Couldn't start the sign-in.")); - setBusy(false); - } - }; - return ( -
- {state?.status === "connected" ? ( -

- Signed in{state.connected_by ? ` by ${state.connected_by}` : ""} with Coderhelm's app. Agents read {plugin.name} with this sign-in. -

- ) : state?.status_reason ? ( -

- {state.status_reason} -

- ) : ( -

- You sign in at {plugin.name} and allow Coderhelm to read{scopes.length ? ` (${scopes.join(", ")})` : ""}. Nothing is changed in {plugin.name}. -

- )} - {error && ( -

- {error} -

- )} -
- -
-
- ); -} - /** The team's own OAuth app with the vendor: where to create it, its client id and secret, and signing in with it. */ -function OwnAppPanel({ plugin, state, redirectUri, onChanged }: { plugin: PluginDef; state: OwnAppState | null; redirectUri: string; onChanged: () => Promise }) { +function OwnAppForm({ + plugin, + state, + redirectUri, + ids, + quiet, + onChanged, +}: { + plugin: PluginDef; + state: OwnAppState | null; + redirectUri: string; + ids: string[]; + /** Among the other ways, or already signed in: not the card's main action. */ + quiet: boolean; + onChanged: () => Promise; +}) { const app = plugin.own_app!; const [clientId, setClientId] = useState(state?.client_id ?? ""); const [secret, setSecret] = useState(""); - const [busy, setBusy] = useState<"" | "save" | "connect" | "remove">(""); - const [error, setError] = useState(""); + const [busy, setBusy] = useState(false); const { toast } = useToast(); const { confirm } = useConfirm(); // The API names this install's callback; the page's own address is the same one. const redirect = redirectUri || state?.redirect_uri || `${window.location.origin}/settings/integrations/mcp-callback/`; const sameApp = !!state && clientId.trim() === state.client_id; const canSave = !!clientId.trim() && (!!secret.trim() || (sameApp && state!.has_secret)); + const unchanged = sameApp && !secret.trim(); - const connect = async (id: string) => { - setBusy("connect"); - try { - await startMcpSignIn(id); - } catch (e) { - setError(errorMessage(e, "Couldn't start the sign-in.")); - setBusy(""); - } - }; - const save = async (thenConnect: boolean) => { - setBusy("save"); - setError(""); - try { + // Saves what was typed (when it changed), then asks where the sign-in page is. + const begin = async (): Promise => { + let id = state?.id ?? ""; + if (!unchanged) { const r = await api.saveOwnApp(plugin.id, clientId.trim(), secret.trim()); setSecret(""); - if (thenConnect) { - await connect(r.own_app.id); - return; - } - toast(`Your ${plugin.name} app is saved`); - await onChanged(); - } catch (e) { - setError(errorMessage(e, "Couldn't save the app.")); - } finally { - setBusy((b) => (b === "save" ? "" : b)); + id = r.own_app.id; } + return { ...(await api.connectMcpServer(id)), server_id: id }; }; const remove = async () => { if (!state) return; @@ -266,7 +516,7 @@ function OwnAppPanel({ plugin, state, redirectUri, onChanged }: { plugin: Plugin destructive: true, }); if (!ok) return; - setBusy("remove"); + setBusy(true); try { await api.removeMcpServer(state.id); setClientId(""); @@ -274,19 +524,18 @@ function OwnAppPanel({ plugin, state, redirectUri, onChanged }: { plugin: Plugin } catch (e) { toast(errorMessage(e, "Couldn't remove it."), "error"); } finally { - setBusy(""); + setBusy(false); } }; return ( -
-

Use my own {plugin.name} app

+
{state?.status === "connected" ? ( -

- Signed in{state.connected_by ? ` by ${state.connected_by}` : ""}. Agents use {plugin.name} with this sign-in. +

+ Signed in{state.connected_by ? ` by ${state.connected_by}` : ""} with your own app. Agents use {plugin.name} with this sign-in.

) : state?.status_reason ? ( -

+

{state.status_reason}

) : null} @@ -310,66 +559,53 @@ function OwnAppPanel({ plugin, state, redirectUri, onChanged }: { plugin: Plugin
  • Publish it as a private app (no review needed), then paste its client id and secret here.
  • - { - e.preventDefault(); - void save(true); - }} - > - - {(props) => setClientId(e.target.value)} autoComplete="off" />} - - - {(props) => ( - setSecret(e.target.value)} - autoComplete="off" - /> - )} - - {error && ( -

    - {error} -

    + + {(props) => setClientId(e.target.value)} autoComplete="off" />} + + + {(props) => ( + setSecret(e.target.value)} + autoComplete="off" + /> )} -
    - {sameApp && !secret.trim() ? ( - - ) : ( - - )} - {state && ( - - )} -
    - +
    + + {state && ( +

    + +

    + )}
    ); } -/** An MCP server run with a key: credentials (entered here, never shown again), its test, its instructions, and turning it off. */ -function PluginKeyPanel({ item, onChanged, onClose }: { item: Integration; onChanged: () => Promise; onClose: () => void }) { - const d = item.detail as { plugin: PluginDef; enabled: boolean; has_credentials: boolean; custom_prompt: string }; +/** The key for a vendor's package: entered here, never shown again, and tested when saved. */ +function KeyFields({ item, quiet = false, onChanged }: { item: Integration; quiet?: boolean; onChanged: () => Promise }) { + const d = item.detail as unknown as Detail; const p = d.plugin; const [creds, setCreds] = useState>(() => Object.fromEntries(p.credential_fields.map((f) => [f.key, ""]))); - const [prompt, setPrompt] = useState(d.custom_prompt || p.default_prompt); const [saving, setSaving] = useState(false); const [error, setError] = useState(""); const { toast } = useToast(); - const { confirm } = useConfirm(); - const saveCreds = async () => { + const save = async () => { setSaving(true); setError(""); try { @@ -390,113 +626,110 @@ function PluginKeyPanel({ item, onChanged, onClose }: { item: Integration; onCha setSaving(false); } }; - const savePrompt = async () => { - try { - await api.updatePluginPrompt(p.id, prompt); - toast("Instructions saved"); - } catch (e) { - toast(errorMessage(e, "Couldn't save the instructions."), "error"); - } - }; - const turnOff = async () => { - const ok = await confirm({ - title: `Turn off ${p.name}?`, - message: "Agents stop using it and its saved credentials are deleted.", - confirmLabel: "Turn off", - destructive: true, - }); - if (!ok) return; - try { - await api.disablePlugin(p.id); - onClose(); - await onChanged(); - } catch (e) { - toast(errorMessage(e, "Couldn't turn it off."), "error"); - } - }; return ( -
    -
    { - e.preventDefault(); - saveCreds(); - }} - > -

    - {d.has_credentials ? "Credentials are saved. Enter new ones to replace them." : "Agents get this server once its credentials are saved."}{" "} - {p.recommended_permissions && <>Use the least access that works: {p.recommended_permissions.toLowerCase()}.}{" "} - - Where to get them - -

    - {p.credential_fields.map((f) => ( - - {(props) => - f.secret ? ( - setCreds((c) => ({ ...c, [f.key]: e.target.value }))} - autoComplete="off" - /> - ) : ( - setCreds((c) => ({ ...c, [f.key]: e.target.value }))} - autoComplete="off" - /> - ) - } - - ))} - {error && ( -

    - {error} -

    - )} -
    - -
    -
    - {d.enabled && ( - - - {(props) => ( - - )} +
    { + e.preventDefault(); + void save(); + }} + > +

    + {d.has_credentials ? "Credentials are saved. Enter new ones to replace them." : "Agents get this server once its credentials are saved."}{" "} + {p.recommended_permissions && <>Use the least access that works: {p.recommended_permissions.toLowerCase()}.}{" "} + + Where to get them + +

    + {p.credential_fields.map((f) => ( + + {(props) => + f.secret ? ( + setCreds((c) => ({ ...c, [f.key]: e.target.value }))} + autoComplete="off" + /> + ) : ( + setCreds((c) => ({ ...c, [f.key]: e.target.value }))} + autoComplete="off" + /> + ) + } -

    - -

    - - )} - {d.enabled && ( -

    - + ))} + {error && ( +

    + {error}

    )} -
    +
    + +
    + ); } +/** The instructions agents follow with a vendor's package. One link to add some when there are none. */ +function PackageInstructions({ item }: { item: Integration }) { + const d = item.detail as unknown as Detail; + const p = d.plugin; + const [prompt, setPrompt] = useState(d.custom_prompt || p.default_prompt); + const [adding, setAdding] = useState(false); + const { toast } = useToast(); + const has = !!(d.custom_prompt || p.default_prompt); + if (!has && !adding) { + return ( +

    + +

    + ); + } + return ( + + + {(props) => ( + + )} + +

    + +

    +
    + ); +} diff --git a/dashboard/src/components/mcp-servers.tsx b/dashboard/src/components/mcp-servers.tsx index 77c81adb..fe6a384f 100644 --- a/dashboard/src/components/mcp-servers.tsx +++ b/dashboard/src/components/mcp-servers.tsx @@ -1,7 +1,7 @@ "use client"; -import { useCallback, useEffect, useMemo, useState } from "react"; -import { api, type McpCall, type McpDetected, type McpServer, type McpStatus, type McpTool } from "@/lib/api"; +import { useEffect, useMemo, useState } from "react"; +import { api, type McpCall, type McpDetected, type McpServer, type McpStatus, type McpTool, type SignInStart } from "@/lib/api"; import { errorMessage, timeAgo } from "@/lib/data-sources"; import { Callout } from "./callout"; import { Code } from "./settings/code"; @@ -14,33 +14,21 @@ import { useConfirm } from "./confirm-dialog"; import { useToast } from "./toast"; import { useCan } from "@/hooks/use-can"; import { inputClass, linkButton, monoInputClass, primaryButton, secondaryButton, smallSecondaryButton } from "./ui"; +import { DangerRow, PanelDetails, PanelSection, SignInControl } from "./integration-panel"; // Remote MCP servers: added by address, signed in to with OAuth, a key or // nothing, their tools allowed one by one. Used on Settings → Integrations, // for servers added by address and for catalog servers connected through // their vendor's own remote server. -const STATUS: Record = { - connected: { label: "Connected", tone: "text-emerald-300" }, - needs_reconnect: { label: "Needs reconnect", tone: "text-amber-300" }, - failed: { label: "Not working", tone: "text-red-300" }, - not_connected: { label: "Not connected", tone: "text-zinc-400" }, -}; - const ACCESS: Record = { read: { label: "Reads", cls: "border-emerald-500/30 text-emerald-300", hint: "The server says this tool only reads." }, write: { label: "Writes", cls: "border-amber-500/30 text-amber-300", hint: "The server says this tool can change data." }, unknown: { label: "Not said", cls: "border-zinc-700 text-zinc-400", hint: "The server doesn't say whether this tool changes data." }, }; -/** Sends the browser to the server's sign-in page. */ -export async function startMcpSignIn(id: string) { - const r = await api.connectMcpServer(id); - window.location.assign(r.authorize_url); -} - -/** Connects a catalog server through its vendor's remote server (setting it up first if needed). */ -export async function connectCatalogServer(catalogId: string) { +/** Starts a catalog server's sign-in through its vendor's remote server (setting it up first if needed). */ +export async function beginCatalogSignIn(catalogId: string): Promise { let id = catalogId; try { id = (await api.addMcpServer({ catalog_id: catalogId })).server.id; @@ -51,7 +39,8 @@ export async function connectCatalogServer(catalogId: string) { if (!found) throw e; id = found.id; } - await startMcpSignIn(id); + const r = await api.connectMcpServer(id); + return { ...r, server_id: r.server_id ?? id }; } let meEmail: Promise | null = null; @@ -77,7 +66,7 @@ function hostOf(url: string): string { } /** The connection this person sees: their own on a personal server, the team's otherwise. */ -function viewerStatus(s: McpServer): { status: McpStatus; reason: string } { +export function viewerStatus(s: McpServer): { status: McpStatus; reason: string } { if (s.auth === "oauth" && s.sharing === "personal") { return s.my_connection ? { status: s.my_connection.status, reason: s.my_connection.status_reason } @@ -160,15 +149,13 @@ export function AddMcpServerDialog({ client_id: manual ? clientId.trim() : undefined, client_secret: manual && clientSecret.trim() ? clientSecret.trim() : undefined, }); - if (r.server.auth === "oauth") { - // Straight on to the sign-in page; the callback brings the person back. - await startMcpSignIn(r.server.id); - return; - } + // A server that signs in opens on its row, where Connect is the one + // thing to do next. onAdded(r.server); onOpenChange(false); } catch (e) { setError(errorMessage(e, "Couldn't add the server.")); + } finally { setBusy(false); } }; @@ -304,7 +291,7 @@ export function AddMcpServerDialog({ ) : ( )} @@ -315,6 +302,16 @@ export function AddMcpServerDialog({ // ── One server ────────────────────────────────────────────────────── +/** Who signs in to a server, or what it takes instead. */ +function signsIn(s: McpServer): string { + if (s.auth === "oauth") return s.sharing === "personal" ? "Each person, with their own account" : "One account for the team"; + return s.auth === "header" ? `A key, sent in the ${s.header_name} header` : "Nobody: it needs no sign-in"; +} + +/** + * A server added by address, opened on Integrations: connecting it, then + * its tools, instructions and calls, and disconnecting or removing it last. + */ export function McpServerPanel({ server, canEdit, @@ -328,7 +325,6 @@ export function McpServerPanel({ }) { const [s, setS] = useState(server); useEffect(() => setS(server), [server]); - const me = useMyEmail(); const { toast } = useToast(); const { confirm } = useConfirm(); const [busy, setBusy] = useState(""); @@ -338,7 +334,8 @@ export function McpServerPanel({ // A shared server is connected by whoever may change integrations; a // personal one by anyone who may connect their own account. const mayConnect = s.auth === "oauth" && (personal ? can("mcp_connect") : canEdit); - const st = STATUS[view.status]; + const connected = view.status === "connected"; + const noClient = s.needs_client && !s.has_client; const act = async (label: string, fn: () => Promise) => { setBusy(label); @@ -351,7 +348,6 @@ export function McpServerPanel({ } }; - const connect = () => act("connect", () => startMcpSignIn(s.id)); const disconnect = () => act("disconnect", async () => { const ok = await confirm({ @@ -382,74 +378,152 @@ export function McpServerPanel({ onRemoved?.(); await onChanged(); }); - const check = () => - act("check", async () => { - const r = await api.checkMcpServer(s.id); - setS(r.server); - toast(r.error ? r.error : `${r.server.tools.length} tools listed`, r.error ? "error" : "success"); - await onChanged(); - }); + + const signIn = mayConnect && ( + ({ ...(await api.connectMcpServer(s.id)), server_id: s.id })} + onConnected={onChanged} + onReturn={onChanged} + disabled={noClient} + testId="mcp-sign-in" + /> + ); + const details = ( + {s.url} }, + { label: "Signs in", value: signsIn(s) }, + { label: "Sign-in server", value: s.issuer ? hostOf(s.issuer) : "" }, + { label: "Permissions asked for", value: s.scopes.length ? s.scopes.join(", ") : "" }, + { label: "Added", value: s.added_at ? `${timeAgo(s.added_at)}${s.added_by ? ` by ${s.added_by}` : ""}` : "" }, + ]} + /> + ); return (
    -
    -

    - {s.url} -

    -

    - {st.label} - - {" · "} - {s.auth === "oauth" ? (personal ? "OAuth, each person signs in" : "OAuth, one account for the team") : s.auth === "header" ? `Key in ${s.header_name}` : "No sign-in"} - -

    - {view.reason && ( -

    - {view.reason} -

    - )} -
    - - {s.needs_client && !s.has_client && canEdit && } - - {(mayConnect || (s.auth === "header" && canEdit) || canEdit) && ( -
    - {mayConnect && view.status !== "connected" && ( - - )} - {mayConnect && view.status === "connected" && ( - - )} - {canEdit && (view.status === "connected" || s.auth !== "oauth") && ( - - )} -
    + {/* Needs attention: the reason and the one action. */} + {(view.status === "needs_reconnect" || view.status === "failed") && ( + +

    {view.reason || "The sign-in has to be renewed."}

    +
    {s.auth === "oauth" ? signIn : canEdit && }
    +
    )} - {s.auth === "header" && canEdit && } - - { setS(n); void onChanged(); }} /> + {/* Not connected: what happens, one action, what comes next. */} + {view.status === "not_connected" && ( + <> +

    + {personal + ? `Each person signs in to ${s.name} with their own account. Agents use it for that person's work, with only the tools an admin allowed.` + : `You sign in at ${hostOf(s.url)}, then pick which of its tools agents may use. Agents get none until you do.`} +

    + {noClient && canEdit && } + {signIn} + + )} - {canEdit && } - {canEdit && } + {/* Connected: its tools, instructions and calls. Nothing before that. */} + {connected && view.reason && ( +

    + {view.reason} +

    + )} + {connected && } + {details} - {canEdit && ( + {canEdit && (connected || s.auth !== "oauth") && mayConnect && ( + + {personal ? "Agents stop using your account. The server and its allowed tools stay." : "Agents stop using it until someone signs in again. The server and its allowed tools stay."} + + )} + {!canEdit && connected && mayConnect && (

    -

    )} + {canEdit && ( + + Every connection to it is revoked and forgotten, and agents lose its tools at once. + + )}
    ); } +/** Lists the server's tools again with the saved connection. */ +function CheckAgain({ server, onSaved, onChanged }: { server: McpServer; onSaved: (s: McpServer) => void; onChanged: () => Promise | void }) { + const [busy, setBusy] = useState(false); + const { toast } = useToast(); + return ( + + ); +} + +/** + * What an admin manages on a connected server: which tools agents get, the + * instructions agents follow with it, its key (when it uses one) and its + * recent calls. Each part shows only when there is something in it. + */ +export function McpManage({ + server, + canEdit, + onSaved, + onChanged, +}: { + server: McpServer; + canEdit: boolean; + onSaved: (s: McpServer) => void; + onChanged: () => Promise | void; +}) { + const me = useMyEmail(); + return ( + + { + onSaved(n); + void onChanged(); + }} + /> + {canEdit && } + {server.auth === "header" && canEdit && } + {canEdit && } + {canEdit && ( +
    + +
    + )} +
    + ); +} + function ClientForm({ server, onSaved }: { server: McpServer; onSaved: (s: McpServer) => void }) { const [id, setId] = useState(""); const [secret, setSecret] = useState(""); @@ -561,9 +635,11 @@ function ToolPicker({ server, canEdit, me, onSaved }: { server: McpServer; canEd const mineToApprove = canEdit && waiting.length > 0 && me !== "" && server.changed_by.toLowerCase() !== me; if (server.tools.length === 0) { + // Nothing to pick: said only once the server was asked and listed none. + if (!server.tools_listed_at) return null; return (

    - {server.tools_listed_at ? "The server lists no tools." : "Its tools are listed once it's connected."} + The server lists no tools.

    ); } @@ -681,9 +757,20 @@ function ToolPicker({ server, canEdit, me, onSaved }: { server: McpServer; canEd function PromptForm({ server, onSaved }: { server: McpServer; onSaved: (s: McpServer) => void }) { const [text, setText] = useState(server.custom_prompt); + const [adding, setAdding] = useState(false); const { toast } = useToast(); + // No instructions yet: one link to add some, never an empty box. + if (!server.custom_prompt && !adding) { + return ( +

    + +

    + ); + } return ( - + {(props) =>