From 002a51e1dd13b094550610488f03266fb46fffac Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 07:23:59 +0000 Subject: [PATCH 1/8] feat(ui-react): render the host GitHub tools as the ui-kit GitHub components (#3795) One bound renderer per #3791 tool, registered for every backend spelling, maps #3797's payloads onto #3800's components unchanged: issue and pull request reads, search, and the write tools' approval and result views (W1-W4). Absent fields read as absent; every direct link is re-checked with #3797's githubDirectUrl or isGithubSearchUrl; avatars come only from #3796's brain-origin route. On-demand sections load through #3796's client only after the reader acts, map its typed errors to S4-S7, and never reach the model. Tab sections are keyed, so one tab's loaded rows cannot leak into the next. Co-Authored-By: Claude Opus 5.5 --- .changeset/3795-github-tool-cards.md | 16 + .../chat/renderers/github-mapping.ts | 228 ++++++++ .../chat/renderers/github-tools.tsx | 88 ++++ .../src/components/chat/renderers/index.ts | 2 + .../chat/tool-cards/github-cards.tsx | 489 ++++++++++++++++++ .../tests/browser/github-tools.layout.tsx | 150 ++++++ packages/ui-react/tests/github-fixtures.ts | 158 ++++++ .../tests/registration-on-mount-harness.ts | 1 + .../tests/registration-on-mount.test.tsx | 8 +- .../ui-react/tests/render/github-tools-dom.ts | 20 + .../tests/render/github-tools.test.tsx | 263 ++++++++++ 11 files changed, 1421 insertions(+), 2 deletions(-) create mode 100644 .changeset/3795-github-tool-cards.md create mode 100644 packages/ui-react/src/components/chat/renderers/github-mapping.ts create mode 100644 packages/ui-react/src/components/chat/renderers/github-tools.tsx create mode 100644 packages/ui-react/src/components/chat/tool-cards/github-cards.tsx create mode 100644 packages/ui-react/tests/browser/github-tools.layout.tsx create mode 100644 packages/ui-react/tests/github-fixtures.ts create mode 100644 packages/ui-react/tests/render/github-tools-dom.ts create mode 100644 packages/ui-react/tests/render/github-tools.test.tsx diff --git a/.changeset/3795-github-tool-cards.md b/.changeset/3795-github-tool-cards.md new file mode 100644 index 0000000000..ae5ea3ce48 --- /dev/null +++ b/.changeset/3795-github-tool-cards.md @@ -0,0 +1,16 @@ +--- +"@schlessera/brain-ui-react": minor +--- + +The host GitHub tools' results now render as the dedicated ui-kit GitHub components instead of raw tool output, on every backend and under every spelling of the tool names: + +- **Reads:** an issue or pull request read and an issue search render as their own components. +- **Writes:** the issue and comment tools show exactly what will be posted on their approval card, then the posted object, or why nothing was posted. + +The mapping is honest: + +- Absent checks, unknown review states and deleted authors read as absent. +- Every direct GitHub link is re-checked with the tool contract's validator before it renders. +- Avatars come only from the brain's own avatar route. + +On-demand parts of a pull request or issue (earlier comments, commits, files, checks, line comments) load only when the reader asks. They load through the session's detail route, show their loading, empty, error, rate-limited and unavailable states, and never reach the model. diff --git a/packages/ui-react/src/components/chat/renderers/github-mapping.ts b/packages/ui-react/src/components/chat/renderers/github-mapping.ts new file mode 100644 index 0000000000..9fec3c3f03 --- /dev/null +++ b/packages/ui-react/src/components/chat/renderers/github-mapping.ts @@ -0,0 +1,228 @@ +// Maps the host GitHub tools' payloads (#3797) onto the ui-kit GitHub +// components' props (#3800). Pure: no React, no fetch. +// +// The mapping is honest (#3795): +// - A `null` or absent field maps to the component's absent state, never to +// zero or passing. +// - Every direct link is re-checked with #3797's `githubDirectUrl` against the +// object it belongs to. A URL that fails, or a `null`, passes as absent, so +// the slot shows no link. Nothing here builds, rewrites or repairs a URL. +// - An avatar is a brain-origin #3796 avatar-route URL, and only for a login +// in this result. + +import { + githubDirectUrl, + isGithubSearchUrl, + parseGithubRepository, + type GithubAuthor, + type GithubChecks, + type GithubComment, + type GithubCommit, + type GithubIssue, + type GithubIssueSearchPayload, + type GithubLinkScope, + type GithubLinkTarget, + type GithubPullRequest, + type GithubReview, + type GithubReviewComment, + type GithubSearchItem, + type GithubUser, +} from "@schlessera/brain-ui-sdk/tool-contracts"; +import type { GitHubPerson, GitHubResult, GitHubReviewState } from "@schlessera/brain-ui-kit"; + +/** Builds a brain-origin avatar URL for a login, or nothing when there is no session to scope it. */ +export type AvatarFor = (login: string) => string | null; + +const ASSOCIATION: Record = { + OWNER: "owner", + MEMBER: "member", + COLLABORATOR: "collaborator", + CONTRIBUTOR: "contributor", + FIRST_TIME_CONTRIBUTOR: "first-time contributor", + FIRST_TIMER: "first-timer", + MANNEQUIN: "mannequin", + NONE: "none", +}; + +/** A person in the kit's terms. A deleted account (`login: null`) stays `@ghost` and fetches nothing. */ +export function person(user: GithubUser | GithubAuthor, avatarFor: AvatarFor): GitHubPerson { + const association = "author_association" in user && user.author_association ? (ASSOCIATION[user.author_association] ?? null) : null; + return { + login: user.login, + association, + bot: user.is_bot, + avatarSrc: user.login === null ? null : avatarFor(user.login), + }; +} + +/** The object a link must point into. `null` when the repository name does not parse, so no link renders. */ +export function scopeOf(repository: string, number: number): GithubLinkScope | null { + const parsed = parseGithubRepository(repository); + return parsed ? { owner: parsed.owner, repo: parsed.repo, number } : null; +} + +/** A direct link's URL after #3797's validator, or `null` (no link). */ +export function directLink(url: string | null | undefined, scope: GithubLinkScope | null, target: GithubLinkTarget): string | null { + if (!url || !scope) return null; + return githubDirectUrl(url, scope, target); +} + +/** The search footnote's link after #3797's search-URL check, or `null`. */ +export function searchLink(payload: GithubIssueSearchPayload): string | null { + const repo = parseGithubRepository(payload.repository); + if (!payload.search_url || !repo) return null; + return isGithubSearchUrl(payload.search_url, { owner: repo.owner, repo: repo.repo }, payload.search_query) ? payload.search_url : null; +} + +/** "3 d ago", anchored to when the host fetched the result, never to the reader's clock. */ +export function ago(at: string | null, fetchedAt: string): string | undefined { + if (!at) return undefined; + const ms = Date.parse(fetchedAt) - Date.parse(at); + if (!Number.isFinite(ms)) return undefined; + const minutes = Math.max(0, Math.round(ms / 60_000)); + if (minutes < 1) return "just now"; + if (minutes < 60) return `${minutes} min ago`; + const hours = Math.round(minutes / 60); + if (hours < 24) return `${hours} h ago`; + const days = Math.round(hours / 24); + if (days < 60) return `${days} d ago`; + return `${Math.round(days / 30)} mo ago`; +} + +/** The PR's state in the kit's words. Merged and draft take precedence over open and closed. */ +export function pullState(pr: GithubPullRequest): "open" | "draft" | "merged" | "closed" { + if (pr.merged) return "merged"; + if (pr.state === "closed") return "closed"; + return pr.draft ? "draft" : "open"; +} + +/** The issue's state in the kit's words. Closed as not planned or duplicate reads not planned. */ +export function issueState(issue: GithubIssue): "open" | "completed" | "not-planned" { + if (issue.state === "open") return "open"; + return issue.state_reason === "not_planned" || issue.state_reason === "duplicate" ? "not-planned" : "completed"; +} + +const REVIEW_STATE: Record = { + approved: "approved", + changes_requested: "changes-requested", + commented: "commented", + dismissed: "dismissed", + pending: "review-requested", +}; + +function reviewState(state: GithubReview["state"] | null | undefined): GitHubReviewState { + return state ? REVIEW_STATE[state] : null; +} + +/** + * The reviews fact: changes requested and approved, from each reviewer's latest + * decision. With no decisions and no reviews reported at all, `null` (absent). + */ +export function reviewCounts(pr: GithubPullRequest): { changesRequested: number; approved: number } | null { + if (pr.review_decisions.length === 0 && pr.reviews.total_count === null) return null; + return { + changesRequested: pr.review_decisions.filter((d) => d.state === "changes_requested").length, + approved: pr.review_decisions.filter((d) => d.state === "approved").length, + }; +} + +/** One row per reviewer: the latest decision, then requested reviewers with no review yet. */ +export function reviewerRows(pr: GithubPullRequest, avatarFor: AvatarFor) { + const decided = new Set(pr.review_decisions.map((d) => d.reviewer.login)); + return [ + ...pr.review_decisions.map((d) => ({ person: person(d.reviewer, avatarFor), state: reviewState(d.state), time: ago(d.submitted_at, pr.fetched_at) })), + ...pr.requested_reviewers.filter((r) => !decided.has(r.login)).map((r) => ({ person: person(r, avatarFor), state: "review-requested" as GitHubReviewState })), + ]; +} + +/** Checks as the payload states them: `null` stays `null` ("None reported"). */ +export function checks(value: GithubChecks): { passed: number; failed: number; running: number; skipped: number } | null { + return value === null ? null : { ...value }; +} + +/** A known total, or `null` when the payload does not state one. */ +export function knownTotal(list: { items: unknown[]; total_count: number | null; has_more: boolean }): number | null { + if (list.total_count !== null) return list.total_count; + return list.has_more ? null : list.items.length; +} + +/** "Brain read: …": what the tool result itself carried. It never grows when the reader loads detail. */ +export function brainRead(object: GithubIssue | GithubPullRequest): string { + const parts: string[] = [object.body ? "description" : "no description"]; + if (object.kind === "pull_request") { + if (object.reviews.items.length) parts.push(`${object.reviews.items.length} ${object.reviews.items.length === 1 ? "review" : "reviews"}`); + } + const shown = object.comments.items.length; + const total = knownTotal(object.comments); + if (shown) parts.push(total !== null && total > shown ? `latest ${shown} of ${total} comments` : `${shown} ${shown === 1 ? "comment" : "comments"}`); + if (object.kind === "pull_request") { + if (object.commits.items.length) parts.push(`${object.commits.items.length} ${object.commits.items.length === 1 ? "commit" : "commits"}`); + if (object.checks !== null) parts.push("checks summary"); + } + return `${parts.join(", ")}.`; +} + +/** A comment's props, with its own direct link re-checked against the object it belongs to. */ +export function commentProps(comment: GithubComment | GithubReviewComment, scope: GithubLinkScope | null, fetchedAt: string, avatarFor: AvatarFor) { + const isReviewComment = "review_id" in comment; + return { + author: person(comment.author, avatarFor), + time: ago(comment.created_at, fetchedAt), + body: comment.body ?? "", + bodyTruncated: comment.body_truncated, + htmlUrl: directLink(comment.html_url, scope, { kind: isReviewComment ? "review_comment" : "comment", id: comment.id }), + }; +} + +export function reviewProps(review: GithubReview, scope: GithubLinkScope | null, fetchedAt: string, avatarFor: AvatarFor) { + return { + reviewer: person(review.author, avatarFor), + state: reviewState(review.state), + time: ago(review.submitted_at, fetchedAt), + body: review.body, + htmlUrl: directLink(review.html_url, scope, { kind: "review", id: review.id }), + }; +} + +export function commitProps(commit: GithubCommit, scope: GithubLinkScope | null, fetchedAt: string, avatarFor: AvatarFor) { + const subject = commit.message.split("\n")[0] ?? ""; + return { + sha: commit.sha.slice(0, 7), + subject, + message: commit.message_truncated ? `${commit.message}\n…` : commit.message, + author: commit.author ? person(commit.author, avatarFor) : null, + time: ago(commit.authored_at, fetchedAt), + htmlUrl: directLink(commit.html_url, scope, { kind: "commit", sha: commit.sha }), + }; +} + +/** One search row. Its link is re-checked against the row's own number. */ +export function resultRow(item: GithubSearchItem, repository: string): GitHubResult { + const state: GitHubResult["state"] = + item.kind === "pull_request" + ? item.merged_at + ? "merged" + : item.state === "closed" + ? "closed" + : item.draft + ? "draft" + : "open" + : item.state === "open" + ? "open" + : item.state_reason === "not_planned" || item.state_reason === "duplicate" + ? "not-planned" + : "completed"; + const facts = [ + ...item.labels.items.slice(0, 3).map((label) => label.name), + `${item.comments} ${item.comments === 1 ? "comment" : "comments"}`, + ]; + return { + kind: item.kind === "pull_request" ? "pr" : "issue", + number: item.number, + state, + title: item.title, + facts, + summary: item.excerpt, + htmlUrl: directLink(item.html_url, scopeOf(repository, item.number), { kind: item.kind }), + }; +} diff --git a/packages/ui-react/src/components/chat/renderers/github-tools.tsx b/packages/ui-react/src/components/chat/renderers/github-tools.tsx new file mode 100644 index 0000000000..227f65889e --- /dev/null +++ b/packages/ui-react/src/components/chat/renderers/github-tools.tsx @@ -0,0 +1,88 @@ +// The host GitHub tools (#3791), rendered as the ui-kit GitHub components +// (#3795, design #3795 revision 2, components #3800). +// +// GLOBAL like the chat UI's own tools: every backend exposes the same +// contracts under its own spelling, so `bind()` registers the Pi name, the +// Claude MCP name and the legacy spelling for each. A refusal is part of the +// result schema, so it reaches the card and is drawn in the result's own +// words. Only output that is not a result envelope at all (an exception's +// message) reaches the fallback. + +import type { RendererPack, ToolCallView } from "@schlessera/brain-ui-sdk/client"; +import { + GITHUB_ISSUE_COMMENT_CONTRACT, + GITHUB_ISSUE_COMMENT_INPUT_SCHEMA, + GITHUB_ISSUE_CREATE_CONTRACT, + GITHUB_ISSUE_CREATE_INPUT_SCHEMA, + GITHUB_ISSUE_READ_CONTRACT, + GITHUB_ISSUE_SEARCH_CONTRACT, + GITHUB_RESULT_SCHEMAS, + GITHUB_TOOL_NAMES, + type GithubToolResult, +} from "@schlessera/brain-ui-sdk/tool-contracts"; +import { GitPullRequest, Search, SquarePen, MessageSquarePlus } from "lucide-react"; +import type { ComponentType } from "react"; +import { ClampedPre } from "../tool-views.js"; +import { + GithubCommentCard, + GithubCommentPreview, + GithubCreateCard, + GithubCreatePreview, + GithubReadCard, + GithubSearchCard, +} from "../tool-cards/github-cards.js"; +import { bind } from "./bind.js"; + +/** Each contract with its result envelope as the payload `bind()` parses. */ +const READ = { ...GITHUB_ISSUE_READ_CONTRACT, payload: GITHUB_RESULT_SCHEMAS[GITHUB_TOOL_NAMES.read] }; +const SEARCH = { ...GITHUB_ISSUE_SEARCH_CONTRACT, payload: GITHUB_RESULT_SCHEMAS[GITHUB_TOOL_NAMES.search] }; +const CREATE = { ...GITHUB_ISSUE_CREATE_CONTRACT, payload: GITHUB_RESULT_SCHEMAS[GITHUB_TOOL_NAMES.create] }; +const COMMENT = { ...GITHUB_ISSUE_COMMENT_CONTRACT, payload: GITHUB_RESULT_SCHEMAS[GITHUB_TOOL_NAMES.comment] }; + +/** Output that is not a result envelope: the words as they came. */ +const Fallback = ({ tool }: { tool: ToolCallView }) => (tool.output ? : null); + +/** The card a write tool's approval row shows: exactly what will be posted (W1, W4). */ +function writeInput(schema: { safeParse: (v: unknown) => { success: boolean; data?: T } }, Preview: ComponentType<{ input: T }>) { + return function WriteInput({ tool }: { tool: ToolCallView }) { + // Only the approval row: the original call's row shows its result instead. + if (tool.status !== "pending_approval" && tool.status !== "approved" && tool.status !== "denied") return null; + const parsed = schema.safeParse(tool.input); + return parsed.success && parsed.data ? : null; + }; +} + +const okOnly = (payload: GithubToolResult, pick: (p: Extract) => R | null): R | null => (payload.ok ? pick(payload) : null); + +export const githubToolPack: RendererPack = { + renderers: [ + ...bind(READ, GithubReadCard, { + icon: GitPullRequest, + label: "GitHub", + summary: (p) => okOnly(p, (r) => (r.tool === GITHUB_TOOL_NAMES.read ? `${r.result.repository} #${r.result.number}` : null)), + meta: (p) => (p.ok ? null : p.error.message), + Fallback, + }), + ...bind(SEARCH, GithubSearchCard, { + icon: Search, + label: "GitHub search", + summary: (p) => okOnly(p, (r) => (r.tool === GITHUB_TOOL_NAMES.search ? `“${r.result.query}” in ${r.result.repository}` : null)), + meta: (p) => (p.ok ? null : p.error.message), + Fallback, + }), + ...bind(CREATE, GithubCreateCard, { + icon: SquarePen, + label: "GitHub issue", + summary: (p) => okOnly(p, (r) => (r.tool === GITHUB_TOOL_NAMES.create ? `${r.result.repository} #${r.result.number}` : null)), + Input: writeInput(GITHUB_ISSUE_CREATE_INPUT_SCHEMA, GithubCreatePreview), + Fallback, + }), + ...bind(COMMENT, GithubCommentCard, { + icon: MessageSquarePlus, + label: "GitHub comment", + summary: (p) => okOnly(p, (r) => (r.tool === GITHUB_TOOL_NAMES.comment ? `${r.result.repository} #${r.result.number}` : null)), + Input: writeInput(GITHUB_ISSUE_COMMENT_INPUT_SCHEMA, GithubCommentPreview), + Fallback, + }), + ], +}; diff --git a/packages/ui-react/src/components/chat/renderers/index.ts b/packages/ui-react/src/components/chat/renderers/index.ts index 2935b4e7fc..95804e56a9 100644 --- a/packages/ui-react/src/components/chat/renderers/index.ts +++ b/packages/ui-react/src/components/chat/renderers/index.ts @@ -9,6 +9,7 @@ import { piToolPack } from "./pi-tools.js"; import { genericToolPack, GENERIC_RENDERER } from "./generic.js"; import { brainUiToolPack } from "./brain-ui-tools.js"; import { apifyToolPack } from "./apify-tools.js"; +import { githubToolPack } from "./github-tools.js"; /** * Register the built-in packs (idempotent). @@ -21,6 +22,7 @@ import { apifyToolPack } from "./apify-tools.js"; export function registerBuiltinRenderers(registry: ToolRendererRegistry = defaultToolRendererRegistry): void { registry.register(brainUiToolPack); registry.register(apifyToolPack); + registry.register(githubToolPack); registry.register(claudeToolPack); registry.register(piToolPack); registry.register(genericToolPack); diff --git a/packages/ui-react/src/components/chat/tool-cards/github-cards.tsx b/packages/ui-react/src/components/chat/tool-cards/github-cards.tsx new file mode 100644 index 0000000000..dc0c4bae03 --- /dev/null +++ b/packages/ui-react/src/components/chat/tool-cards/github-cards.tsx @@ -0,0 +1,489 @@ +// The host GitHub tools' results as the ui-kit GitHub components (#3795). +// +// The components are #3800's, used unchanged. This file maps payloads onto +// them (through `../renderers/github-mapping.ts`) and owns the one fetch they +// trigger: on-demand detail pages through #3796's client, only after the +// reader acts. What loads is display-only and never reaches the model. + +import { Fragment, useCallback, useRef, useState, type ReactNode } from "react"; +import { + Callout, + GitHubComment, + GitHubCommitRow, + GitHubDetailSection, + GitHubIssue, + GitHubPullRequest, + GitHubRef, + GitHubResultList, + GitHubStateChip, + GitHubThread, + GitHubWriteNotice, + ListRow, + UntrustedText, + type GitHubDetailState, + type GitHubThreadItem, +} from "@schlessera/brain-ui-kit"; +import type { + GithubChangedFile, + GithubCheckRun, + GithubComment as GithubCommentPayload, + GithubCommit, + GithubDetailError, + GithubDetailPart, + GithubError, + GithubIssue, + GithubIssueCommentInput, + GithubIssueCreateInput, + GithubIssueSearchPayload, + GithubPullRequest, + GithubReview, + GithubReviewComment, + GithubToolResult, +} from "@schlessera/brain-ui-sdk/tool-contracts"; +import { useBrainUiRoot, useRootStore } from "../../../root-context.js"; +import { fetchGithubDetailPage, githubAvatarUrl } from "../../../lib/github-details.js"; +import { + ago, + brainRead, + checks, + commentProps, + commitProps, + directLink, + issueState, + knownTotal, + person, + pullState, + resultRow, + reviewCounts, + reviewerRows, + reviewProps, + scopeOf, + searchLink, + type AvatarFor, +} from "../renderers/github-mapping.js"; + +/** Brain-origin avatar URLs for this session, or none (initials) without a session. */ +function useAvatarFor(): AvatarFor { + const root = useBrainUiRoot(); + const sessionId = useRootStore("chat", (s) => s.activeSessionId); + return useCallback((login: string) => (sessionId ? githubAvatarUrl(root.apiBase(), sessionId, login) : null), [root, sessionId]); +} + +// --------------------------------------------------------------------------- +// On-demand detail (#3796) +// --------------------------------------------------------------------------- + +type DetailItem = GithubCommentPayload | GithubReview | GithubReviewComment | GithubCommit | GithubChangedFile | GithubCheckRun; + +interface Detail { + state: GitHubDetailState; + items: DetailItem[]; + next: string | null; + total: number | null; + errorStatus?: number | string; + resetAt?: string; + resetIn?: string; +} + +/** The S4–S7 state a detail route error reads as. */ +function detailErrorState(error: GithubDetailError | GithubError & { reset_at?: string | null }, now = Date.now()): Omit { + if (error.code === "rate_limited") { + const reset = error.reset_at ? new Date(error.reset_at) : null; + if (!reset || Number.isNaN(reset.getTime())) return { state: "rate-limited" }; + const minutes = Math.max(1, Math.ceil((reset.getTime() - now) / 60_000)); + return { + state: "rate-limited", + resetAt: reset.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" }), + resetIn: `${minutes} min`, + }; + } + if (error.code === "unavailable" && error.reason === "no_credential") return { state: "no-credential" }; + if (error.code === "not_found" || error.code === "forbidden") return { state: "gone" }; + const status = error.reason?.match(/^http_(\d{3})$/)?.[1]; + return { state: "error", ...(status ? { errorStatus: Number(status) } : {}) }; +} + +/** + * One on-demand part of one object. Nothing is fetched until `load`; `more` + * appends the next page; `retry` repeats the last request. The pages are + * display-only state of this card: nothing here reaches the chat store, the + * socket or the model. + */ +function useDetail(repository: string, number: number, part: GithubDetailPart) { + const root = useBrainUiRoot(); + const sessionId = useRootStore("chat", (s) => s.activeSessionId); + const [detail, setDetail] = useState({ state: "idle", items: [], next: null, total: null }); + const last = useRef(null); + + const fetchPage = useCallback( + async (cursor: string | null, append: boolean) => { + last.current = cursor; + if (!sessionId) { + setDetail((d) => ({ ...d, state: "error" })); + return; + } + setDetail((d) => ({ ...d, state: "loading" })); + const answer = await fetchGithubDetailPage(root, { sessionId, repository, number, part, cursor }); + if (!answer.ok) { + setDetail((d) => ({ ...d, ...detailErrorState(answer.error) })); + return; + } + const page = answer.page; + setDetail((d) => { + const items = append ? [...d.items, ...(page.items as DetailItem[])] : (page.items as DetailItem[]); + return { state: items.length === 0 ? "empty" : "loaded", items, next: page.next_cursor, total: page.total_count }; + }); + }, + [root, sessionId, repository, number, part], + ); + + return { + detail, + load: () => void fetchPage(null, false), + more: () => void fetchPage(detail.next, true), + retry: () => void fetchPage(last.current, last.current !== null), + }; +} + +const NOUN: Record = { + comments: "comments", + reviews: "reviews", + "review-comments": "line comments", + commits: "commits", + files: "files", + checks: "checks", +}; + +function moreLabel(detail: Detail): string | undefined { + if (!detail.next) return undefined; + const of = detail.total !== null ? ` of ${detail.total}` : ""; + return `Load more · ${detail.items.length}${of} shown`; +} + +/** A detail section wired to #3796, rendering its rows with `row`. */ +function DetailPart(p: { + repository: string; + number: number; + part: GithubDetailPart; + object: "issue" | "pull request"; + idleLabel: string; + row: (item: DetailItem, index: number) => ReactNode; +}) { + const { detail, load, more, retry } = useDetail(p.repository, p.number, p.part); + return ( + + {detail.items.length ? detail.items.map((item, i) => p.row(item, i)) : undefined} + + ); +} + +// --------------------------------------------------------------------------- +// Refusals +// --------------------------------------------------------------------------- + +/** A tool refusal in the result's own words. */ +function GithubRefusal({ error }: { error: GithubError }) { + return ; +} + +/** True for an upstream failure after which a write may still have happened. */ +function outcomeUnknown(error: GithubError): boolean { + return error.code === "upstream_error" && error.reason !== "malformed" && error.reason !== "redirect"; +} + +// --------------------------------------------------------------------------- +// Read +// --------------------------------------------------------------------------- + +function threadItems(comments: GithubCommentPayload[], reviews: GithubReview[], scope: ReturnType, fetchedAt: string, avatarFor: AvatarFor): GitHubThreadItem[] { + const timed: { at: string; item: GitHubThreadItem }[] = [ + ...comments.map((c) => ({ at: c.created_at, item: { kind: "comment" as const, id: `c${c.id}`, ...commentProps(c, scope, fetchedAt, avatarFor) } })), + ...reviews.map((r) => ({ at: r.submitted_at ?? "", item: { kind: "review" as const, id: `r${r.id}`, ...reviewProps(r, scope, fetchedAt, avatarFor) } })), + ]; + return timed.sort((a, b) => a.at.localeCompare(b.at)).map((t) => t.item); +} + +function commentRow(scope: ReturnType, fetchedAt: string, avatarFor: AvatarFor) { + return (item: DetailItem, i: number) => ; +} + +function IssueCard({ issue }: { issue: GithubIssue }) { + const avatarFor = useAvatarFor(); + const scope = scopeOf(issue.repository, issue.number); + const total = knownTotal(issue.comments); + const earlier = total !== null ? total - issue.comments.items.length : null; + return ( + l.name)} + body={issue.body} + bodyLength={issue.body_length} + bodyTruncated={issue.body_truncated} + brainRead={brainRead(issue)} + > + 0) ? ( + 0 ? `Load ${earlier} earlier comments` : "Load earlier comments"} + row={commentRow(scope, issue.fetched_at, avatarFor)} + /> + ) : undefined + } + /> + + ); +} + +const PR_TABS = ["Conversation", "Commits", "Files", "Checks"] as const; + +function PullRequestCard({ pr }: { pr: GithubPullRequest }) { + const avatarFor = useAvatarFor(); + const [tab, setTab] = useState(0); + const scope = scopeOf(pr.repository, pr.number); + const commentTotal = knownTotal(pr.comments); + const commitTotal = knownTotal(pr.commits); + const checkTotal = pr.checks ? pr.checks.passed + pr.checks.failed + pr.checks.running + pr.checks.skipped : undefined; + const earlier = commentTotal !== null ? commentTotal - pr.comments.items.length : null; + const state = pullState(pr); + + const conversation = ( + 0) ? ( + 0 ? `Load ${earlier} earlier comments` : "Load earlier comments"} + row={commentRow(scope, pr.fetched_at, avatarFor)} + /> + ) : undefined + } + /> + ); + + const commits = ( +
+ {pr.commits.items.map((c) => ( + + ))} + {pr.commits.has_more ? ( + } + /> + ) : null} +
+ ); + + const files = ( + { + const file = item as GithubChangedFile; + return ; + }} + /> + ); + + const checkRows = ( + { + const run = item as GithubCheckRun; + return ( +
+ + +
+ ); + }} + /> + ); + + return ( + l.name)} + reviews={reviewCounts(pr)} + checks={checks(pr.checks)} + size={{ files: pr.changes.changed_files, additions: pr.changes.additions, deletions: pr.changes.deletions }} + commits={commitTotal} + reviewers={reviewerRows(pr, avatarFor)} + body={pr.body} + bodyLength={pr.body_length} + bodyTruncated={pr.body_truncated} + merge={state === "merged" ? { by: pr.merged_by ? person(pr.merged_by, avatarFor) : null, into: pr.base_ref, sha: pr.merge_commit_sha?.slice(0, 7) ?? null, time: ago(pr.merged_at, pr.fetched_at) } : undefined} + brainRead={brainRead(pr)} + tabs={{ + items: [ + { label: PR_TABS[0], ...(commentTotal !== null ? { count: commentTotal } : {}) }, + { label: PR_TABS[1], ...(commitTotal !== null ? { count: commitTotal } : {}) }, + { label: PR_TABS[2], count: pr.changes.changed_files }, + { label: PR_TABS[3], ...(checkTotal !== undefined ? { count: checkTotal } : {}) }, + ], + active: tab, + onSelect: setTab, + }} + > + {/* Files and Checks mount, and so load, only when their tab is opened. + Keyed by tab: the tabs' sections sit in the same place in the tree, + and without a key React would hand one tab's loaded rows to the next. */} + {tab === 0 ? conversation : tab === 1 ? commits : tab === 2 ? files : checkRows} + {/* Line comments load on demand (#3796's review-comments part). The + payload carries no per-review count, so this is one section for the + pull request rather than a "Show n line comments" per review. */} + {tab === 0 && pr.reviews.items.length > 0 ? ( + } + /> + ) : null} + + ); +} + +/** `brain_github_issue_read`'s result. */ +export function GithubReadCard(result: GithubToolResult) { + if (!result.ok) return ; + if (result.tool !== "brain_github_issue_read") return null; + return result.result.kind === "pull_request" ? : ; +} + +/** `brain_github_issue_search`'s result. */ +export function GithubSearchCard(result: GithubToolResult) { + if (!result.ok) return ; + if (result.tool !== "brain_github_issue_search") return null; + const search: GithubIssueSearchPayload = result.result; + return ( + resultRow(item, search.repository))} + incomplete={search.incomplete_results} + searchUrl={searchLink(search)} + /> + ); +} + +// --------------------------------------------------------------------------- +// Write (W1–W4) +// --------------------------------------------------------------------------- + +/** W3: a write that did not happen, or whose outcome is unknown; otherwise the refusal's own words. */ +function WriteRefusal({ error }: { error: GithubError }) { + if (error.code === "approval_declined") return ; + if (outcomeUnknown(error)) return ; + return ; +} + +/** `brain_github_issue_create`'s result: W2 when posted, W3 otherwise. */ +export function GithubCreateCard(result: GithubToolResult) { + if (!result.ok) return ; + if (result.tool !== "brain_github_issue_create") return null; + const created = result.result; + const scope = scopeOf(created.repository, created.number); + return ( + + ); +} + +/** `brain_github_issue_comment`'s result: the target and that the comment is posted (W4's result). */ +export function GithubCommentCard(result: GithubToolResult) { + if (!result.ok) return ; + if (result.tool !== "brain_github_issue_comment") return null; + const posted = result.result; + const scope = scopeOf(posted.repository, posted.number); + return ( +
+ + +
+ ); +} + +/** W1: the issue Brain asks to post, as it will look. */ +export function GithubCreatePreview({ input }: { input: GithubIssueCreateInput }) { + return ( + + ); +} + +/** W4: the target and the comment Brain asks to post, as it will read. */ +export function GithubCommentPreview({ input }: { input: GithubIssueCommentInput }) { + return ( +
+
+ + +
+ +
+ ); +} diff --git a/packages/ui-react/tests/browser/github-tools.layout.tsx b/packages/ui-react/tests/browser/github-tools.layout.tsx new file mode 100644 index 0000000000..a82bfc46b4 --- /dev/null +++ b/packages/ui-react/tests/browser/github-tools.layout.tsx @@ -0,0 +1,150 @@ +/** + * The GitHub tool cards in a real browser (#3795): + * + * - while the components render (avatars, an open interstitial, loaded detail + * sections) no request leaves the brain's own origin; + * - an untrusted https link opens only after the interstitial shows its full + * address; + * - each on-demand section fetches only after the reader acts, through + * #3796's route, and renders its typed errors (here, rate limited); + * - loading detail changes nothing the model sees: the chat store is + * byte-identical before and after. + * + * The detail route is answered by the root's `request`, the one seam every + * #3796 call goes through, so no network is involved; avatars are real + * requests to the page's own origin. + */ +import { afterEach, expect, test } from "vitest"; +import { commands, page, userEvent } from "vitest/browser"; +import { flushSync } from "react-dom"; +import { createRoot, type Root } from "react-dom/client"; +import { visibleToolName, type ToolCallView } from "@schlessera/brain-ui-sdk/client"; +import { GITHUB_TOOL_NAMES } from "@schlessera/brain-ui-sdk/tool-contracts"; +import { resolveToolRenderer } from "../../../ui-sdk/src/client/renderers.js"; +import { registerBuiltinRenderers } from "../../src/components/chat/renderers/index.js"; +import { BrainUiProvider } from "../../src/root-context.js"; +import { createBrainUiRoot, type BrainUiRoot } from "../../src/root.js"; +import { FETCHED, HOSTILE_BODY, envelope, pull } from "../github-fixtures.js"; + +declare module "vitest/browser" { + interface BrowserCommands { + startRequestLog: () => Promise; + requestLog: (options?: { settle: boolean }) => Promise; + } +} + +let host: HTMLDivElement | undefined; +let renderer: Root | undefined; +let root: BrainUiRoot | undefined; +afterEach(() => { + if (renderer) flushSync(() => renderer!.unmount()); + root?.dispose(); + host?.remove(); + renderer = undefined; + root = undefined; + host = undefined; +}); + +const FILES_PAGE = { + kind: "detail_page", + repository: "ithaca/hall", + number: 412, + part: "files", + items: [{ filename: "armoury/bow.md", previous_filename: null, status: "modified", additions: 12, deletions: 3, changes: 15 }], + total_count: 1, + next_cursor: null, + fetched_at: FETCHED, +}; +const RESET = new Date(Date.now() + 12 * 60_000).toISOString().replace(/\.\d{3}Z$/, "Z"); + +/** Mounts a PR read result; returns the detail-route calls the root's `request` saw. */ +function mountPullRequest() { + const calls: string[] = []; + root = createBrainUiRoot({ + storage: null, + request: async (url) => { + const path = String(url); + calls.push(path); + if (path.endsWith("/files")) return Response.json(FILES_PAGE); + if (path.endsWith("/checks")) + return Response.json({ error: { code: "rate_limited", reason: "github", message: "GitHub's request limit is used up.", reset_at: RESET } }, { status: 429 }); + return Response.json({}, { status: 404 }); + }, + }); + root.stores.chat.setState({ activeSessionId: "session-odysseus" }); + registerBuiltinRenderers(root.renderers); + const name = visibleToolName(GITHUB_TOOL_NAMES.read, "claude"); + const tool: ToolCallView = { id: "g1", name, input: { repository: "ithaca/hall", number: 412 }, output: JSON.stringify(envelope("read", pull({ body: HOSTILE_BODY, body_length: HOSTILE_BODY.length }))), isError: false }; + const Output = (root.renderers.resolve(tool, "claude") ?? resolveToolRenderer(tool, "claude"))!.Output!; + host = document.createElement("div"); + host.style.cssText = "width:680px;padding:16px;background:var(--bk-color-canvas);color:var(--bk-color-ink)"; + document.body.append(host); + renderer = createRoot(host); + flushSync(() => renderer!.render()); + return calls; +} + +const tabNamed = (name: string) => [...host!.querySelectorAll("[role='tab']")].find((t) => t.textContent?.startsWith(name))!; +const buttonStarting = (text: string) => [...host!.querySelectorAll("button, [role='button']")].find((b) => b.textContent?.trim().includes(text)); +const detailCalls = (calls: string[]) => calls.filter((url) => /\/github\/ithaca\/hall\/412\//.test(url)); +const foreign = (urls: string[]) => urls.filter((url) => !url.startsWith(location.origin) && !url.startsWith("data:")); + +test("nothing leaves the brain's origin, links ask first, and detail loads only when asked", async () => { + await page.viewport(900, 900); + await commands.startRequestLog(); + const calls = mountPullRequest(); + const history = JSON.stringify(root!.stores.chat.getState()); + + // Avatars are real requests, to this origin only (positive control for the log). + await expect.poll(() => host!.querySelectorAll("img").length).toBeGreaterThan(0); + for (const img of host!.querySelectorAll("img")) expect(new URL(img.src).origin, "avatar from the brain's origin").toBe(location.origin); + expect(detailCalls(calls), "no detail page before the reader acts").toEqual([]); + + // An untrusted https link opens nothing until the interstitial shows its full address. + const navigated: string[] = []; + const stop = (event: MouseEvent) => { + const anchor = (event.target as Element | null)?.closest?.("a[href]") as HTMLAnchorElement | null; + if (anchor && !anchor.matches("[data-github-link]")) { + navigated.push(anchor.href); + event.preventDefault(); + } + }; + document.addEventListener("click", stop, true); + try { + await userEvent.click(host!.querySelector("button[data-untrusted-link]")!); + const gate = document.querySelector("dialog[data-untrusted-gate]")!; + expect(gate.open, "the interstitial is open").toBe(true); + expect(navigated, "nothing navigated on activation").toEqual([]); + expect(gate.querySelector("[data-untrusted-gate-address]")?.textContent).toBe("https://ithaca-steward.example/r?id=7"); + await userEvent.click(gate.querySelector("a[data-untrusted-open]")!); + expect(navigated, "only Open navigates, to the address shown").toEqual(["https://ithaca-steward.example/r?id=7"]); + } finally { + document.removeEventListener("click", stop, true); + } + + // Files: the tab mounts its section idle; the reader's press loads it. + await userEvent.click(tabNamed("Files")); + await expect.poll(() => tabNamed("Files").getAttribute("aria-selected")).toBe("true"); + expect(detailCalls(calls), "opening the tab shows the section, it does not fetch").toEqual([]); + await expect.poll(() => buttonStarting("Show files"), { message: host!.querySelector("[role='tabpanel']")?.textContent ?? "" }).toBeTruthy(); + await userEvent.click(buttonStarting("Show files")!); + await expect.poll(() => host!.textContent).toContain("armoury/bow.md"); + expect(detailCalls(calls)).toEqual(["/api/sessions/session-odysseus/github/ithaca/hall/412/files"]); + + // Checks: a typed rate-limit error reads as S5, with its reset time. + await userEvent.click(tabNamed("Checks")); + await expect.poll(() => buttonStarting("Show checks")).toBeTruthy(); + await userEvent.click(buttonStarting("Show checks")!); + await expect.poll(() => host!.querySelector("[data-github-detail]")?.getAttribute("data-github-detail")).toBe("rate-limited"); + expect(host!.textContent).toMatch(/It resets at \d{2}:\d{2} \(in 1[12] min\)/); + + // Loaded detail is display-only: the chat state the model's history comes from is unchanged. + expect(JSON.stringify(root!.stores.chat.getState()), "loading detail sends nothing to the model").toBe(history); + // The page's only network requests are the avatar images (the detail route + // answers through the root's request): once every image has settled, the + // log is complete. + await expect.poll(() => [...host!.querySelectorAll("img")].every((img) => img.complete), { timeout: 5000 }).toBe(true); + const log = await commands.requestLog(); + expect(log.some((url) => url.includes("/github/avatars/")), "positive control: the log sees the avatar requests").toBe(true); + expect(foreign(log), "no request left the brain's origin").toEqual([]); +}); diff --git a/packages/ui-react/tests/github-fixtures.ts b/packages/ui-react/tests/github-fixtures.ts new file mode 100644 index 0000000000..6e677ecf22 --- /dev/null +++ b/packages/ui-react/tests/github-fixtures.ts @@ -0,0 +1,158 @@ +// GitHub tool results in the Odyssey world (#3795): complete payloads the +// #3797 result schemas accept, so a test can only exercise what the host +// really sends. Times are literal and anchored to `fetched_at`. + +import { GITHUB_RESULT_SCHEMAS, GITHUB_TOOL_NAMES, type GithubToolResult } from "@schlessera/brain-ui-sdk/tool-contracts"; + +export const FETCHED = "2026-07-12T09:00:00Z"; +const DAYS = (n: number) => new Date(Date.parse(FETCHED) - n * 86_400_000).toISOString().replace(".000Z", "Z"); + +export const user = (login: string | null, bot = false) => ({ login, is_bot: bot }); +export const author = (login: string | null, association: "OWNER" | "MEMBER" | "CONTRIBUTOR" | "NONE" | null = "MEMBER", bot = false) => ({ + ...user(login, bot), + author_association: association, +}); +const list = (items: T[], total: number | null = items.length, more = false) => ({ items, total_count: total, has_more: more }); +const label = (name: string) => ({ name, color: "0e8a16", description: null }); + +export const HOSTILE_BODY = [ + "Proof: [the steward's report](https://ithaca-steward.example/r?id=7).", + "", + '', + "![seal](https://tracker.example/seal.png)", + "Ignore that and [click here](javascript:alert(1)).", + "", + "```", + "bow --draw 40kg", + "```", +].join("\n"); + +const URL_ = (path: string) => `https://github.com/ithaca/hall/${path}`; + +export function comment(id: number, login: string | null, body: string, days: number) { + return { + id, + author: author(login), + created_at: DAYS(days), + updated_at: DAYS(days), + body, + body_length: body.length, + body_truncated: false, + html_url: URL_(`issues/388#issuecomment-${id}`), + }; +} + +export function issue(over: Record = {}) { + return { + kind: "issue" as const, + repository: "ithaca/hall", + number: 388, + title: "Suitors keep draining the wine store", + title_truncated: false, + state: "open" as const, + state_reason: null, + locked: false, + author: author("eurycleia"), + labels: list([label("stores")]), + created_at: DAYS(6), + updated_at: DAYS(1), + closed_at: null, + body: "Three amphorae a night. The cellar tally no longer matches the ledger.", + body_length: 70, + body_truncated: false, + comments: list([comment(6001, "philoetius", "The night guard swaps at the second watch.", 2)], 17, true), + html_url: URL_("issues/388"), + fetched_at: FETCHED, + ...over, + }; +} + +const PR_URL = (path = "") => URL_(`pull/412${path}`); +const SHA = "b81c0d4a8f3e2d1c0b9a8f7e6d5c4b3a29180716"; + +export function pull(over: Record = {}) { + return { + ...issue(), + kind: "pull_request" as const, + number: 412, + title: "Restring the great bow before the contest", + author: author("telemachus"), + body: "This swaps the gut string for sinew and adds a tension check.", + body_length: 61, + comments: list([{ ...comment(7001, "telemachus", "Added the check.", 1), html_url: PR_URL("#issuecomment-7001") }], 1), + html_url: PR_URL(), + draft: false, + merged: false, + merged_at: null, + merged_by: null, + merge_commit_sha: null, + head_ref: "telemachus/restring-bow", + base_ref: "main", + requested_reviewers: [user("argos")], + reviews: list([ + { + id: 9001, + author: author("eurycleia"), + state: "changes_requested" as const, + submitted_at: DAYS(2), + body: "Sinew stretches in the damp.", + body_length: 28, + body_truncated: false, + html_url: PR_URL("#pullrequestreview-9001"), + }, + ]), + review_decisions: [{ reviewer: user("eurycleia"), state: "changes_requested" as const, submitted_at: DAYS(2) }], + checks: { passed: 7, failed: 1, running: 0, skipped: 0 }, + changes: { changed_files: 6, additions: 128, deletions: 41 }, + commits: list( + [{ sha: SHA, author: user("telemachus"), author_name: "Telemachus", authored_at: DAYS(3), message: "Add tension check before axe test", message_truncated: false, html_url: URL_(`commit/${SHA}`) }], + 4, + true, + ), + ...over, + }; +} + +export function search(over: Record = {}) { + return { + kind: "search" as const, + repository: "ithaca/hall", + query: "bow is:open", + search_query: "repo:ithaca/hall bow is:open", + total_count: 143, + incomplete_results: false, + has_more: true, + items: [ + { + kind: "issue" as const, + number: 409, + title: "Bow string frays after twelve shots", + state: "open" as const, + state_reason: null, + draft: null, + merged_at: null, + comments: 3, + author: author("telemachus"), + labels: list([label("bow")]), + created_at: DAYS(4), + updated_at: DAYS(1), + excerpt: "After the twelfth axe the string shows wear.", + html_url: URL_("issues/409"), + }, + ], + search_url: "https://github.com/ithaca/hall/issues?q=repo%3Aithaca%2Fhall+bow+is%3Aopen", + fetched_at: FETCHED, + ...over, + }; +} + +/** A tool result envelope, validated against the tool's real result schema. */ +export function envelope(tool: keyof typeof GITHUB_TOOL_NAMES, result: unknown): GithubToolResult { + const name = GITHUB_TOOL_NAMES[tool]; + return GITHUB_RESULT_SCHEMAS[name].parse({ ok: true, tool: name, result }) as GithubToolResult; +} + +export function refusal(tool: keyof typeof GITHUB_TOOL_NAMES, code: string, reason: string | null, message: string): GithubToolResult { + const name = GITHUB_TOOL_NAMES[tool]; + return GITHUB_RESULT_SCHEMAS[name].parse({ ok: false, tool: name, error: { code, reason, message } }) as GithubToolResult; +} diff --git a/packages/ui-react/tests/registration-on-mount-harness.ts b/packages/ui-react/tests/registration-on-mount-harness.ts index 391f2bee24..3eb81ffa62 100644 --- a/packages/ui-react/tests/registration-on-mount-harness.ts +++ b/packages/ui-react/tests/registration-on-mount-harness.ts @@ -3,6 +3,7 @@ export { resolveToolRenderer } from "../../ui-sdk/src/client/renderers.js"; export { ToolCallTimeline } from "../src/components/chat/tool-call-timeline.js"; export { registerBuiltinRenderers } from "../src/components/chat/renderers/index.js"; export { brainUiToolPack } from "../src/components/chat/renderers/brain-ui-tools.js"; +export { githubToolPack } from "../src/components/chat/renderers/github-tools.js"; export { apifyToolPack } from "../src/components/chat/renderers/apify-tools.js"; export { claudeToolPack } from "../src/components/chat/renderers/claude-tools.js"; export { piToolPack } from "../src/components/chat/renderers/pi-tools.js"; diff --git a/packages/ui-react/tests/registration-on-mount.test.tsx b/packages/ui-react/tests/registration-on-mount.test.tsx index 8c9ba1f2a2..9768e2ba20 100644 --- a/packages/ui-react/tests/registration-on-mount.test.tsx +++ b/packages/ui-react/tests/registration-on-mount.test.tsx @@ -197,7 +197,10 @@ if (!childMode) { // name rather than by which backend owns the session. // The Apify pack (#3163) is global too: its approval cards carry fixed // names, and its results arrive under either backend's tool spelling. + // So is the GitHub pack (#3795): the host GitHub tools are one contract + // per tool under each backend's spelling. expect(distinct.map((pack) => pack.backend ?? "global")).toEqual([ + "global", "global", "global", "claude", @@ -206,8 +209,9 @@ if (!childMode) { ]); expect(distinct[0]).toBe(harness.brainUiToolPack); expect(distinct[1]).toBe(harness.apifyToolPack); - expect(distinct[2]).toBe(harness.claudeToolPack); - expect(distinct[3]).toBe(harness.piToolPack); + expect(distinct[2]).toBe(harness.githubToolPack); + expect(distinct[3]).toBe(harness.claudeToolPack); + expect(distinct[4]).toBe(harness.piToolPack); // A pack rebuilt per call would show up as a sixth distinct object above. // The repeats must still reach the registry (no module latch), so every // pack was handed over more than once. diff --git a/packages/ui-react/tests/render/github-tools-dom.ts b/packages/ui-react/tests/render/github-tools-dom.ts new file mode 100644 index 0000000000..ac9e361fa5 --- /dev/null +++ b/packages/ui-react/tests/render/github-tools-dom.ts @@ -0,0 +1,20 @@ +// happy-dom registration for the GitHub tool render tests; a sibling of +// `dom.ts` for the reason `ask-user-dom.ts` states: that module's body runs +// once per process, so each render test file registers its own DOM and +// unregisters it in `afterAll`. Import it FIRST, before any component module. +import { GlobalRegistrator } from "@happy-dom/global-registrator"; + +export function registerGithubToolsDom(): void { + if (!GlobalRegistrator.isRegistered) { + GlobalRegistrator.register(); + } + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; +} + +registerGithubToolsDom(); + +export async function unregisterGithubToolsDom(): Promise { + if (GlobalRegistrator.isRegistered) { + await GlobalRegistrator.unregister(); + } +} diff --git a/packages/ui-react/tests/render/github-tools.test.tsx b/packages/ui-react/tests/render/github-tools.test.tsx new file mode 100644 index 0000000000..ffad5370c5 --- /dev/null +++ b/packages/ui-react/tests/render/github-tools.test.tsx @@ -0,0 +1,263 @@ +// The host GitHub tools' results as the ui-kit GitHub components (#3795): +// every spelling on every backend, the fallback, honest absent states, direct +// links only after #3797's validator, untrusted bodies end to end, and the +// write views W1–W4. Props-only, keyless, mounted in happy-dom. +import { registerGithubToolsDom, unregisterGithubToolsDom } from "./github-tools-dom.js"; + +registerGithubToolsDom(); + +import { afterAll, afterEach, describe, expect, test } from "bun:test"; +import { act, cleanup, fireEvent, render as mount } from "@testing-library/react"; +import type { ReactElement } from "react"; +import { visibleToolName, type ToolCallView } from "@schlessera/brain-ui-sdk/client"; +import { GITHUB_TOOL_NAMES } from "@schlessera/brain-ui-sdk/tool-contracts"; +import { resetToolRenderers, resolveToolRenderer } from "../../../ui-sdk/src/client/renderers.js"; +import { registerBuiltinRenderers } from "../../src/components/chat/renderers/index.js"; +import { createBrainUiRoot } from "../../src/root.js"; +import { BrainUiProvider } from "../../src/root-context.js"; +import { HOSTILE_BODY, author, envelope, issue, pull, refusal, search } from "../github-fixtures.js"; + +const roots: ReturnType[] = []; +const requested: string[] = []; +afterEach(async () => { + await act(async () => { + cleanup(); + for (const root of roots.splice(0)) root.dispose(); + }); + requested.length = 0; +}); +afterAll(async () => { + await act(async () => cleanup()); + resetToolRenderers(); + await unregisterGithubToolsDom(); +}); + +function render(ui: ReactElement) { + const root = createBrainUiRoot({ + storage: null, + request: async (url) => { + requested.push(String(url)); + return new Response("{}", { status: 404 }); + }, + }); + roots.push(root); + return mount({ui}); +} + +type Tool = keyof typeof GITHUB_TOOL_NAMES; +const spellings = (tool: Tool) => + [ + [visibleToolName(GITHUB_TOOL_NAMES[tool], "claude"), "claude"], + [visibleToolName(GITHUB_TOOL_NAMES[tool], "pi"), "pi"], + [`mcp__brain_ui__${GITHUB_TOOL_NAMES[tool]}`, "claude"], + ] as const; + +function call(name: string, output: unknown, over: Partial = {}): ToolCallView { + return { id: "g1", name, input: {}, ...(output === undefined ? {} : { output: typeof output === "string" ? output : JSON.stringify(output) }), isError: false, ...over }; +} + +function output(tool: Tool, result: unknown, backend: "claude" | "pi" = "pi") { + registerBuiltinRenderers(); + const name = visibleToolName(GITHUB_TOOL_NAMES[tool], backend); + const renderer = resolveToolRenderer(call(name, undefined), backend)!; + const Output = renderer.Output!; + return render(); +} + +describe("binding", () => { + test("every tool resolves under every spelling, on both backends, to its GitHub renderer", () => { + registerBuiltinRenderers(); + const labels: Record = { read: "GitHub", search: "GitHub search", create: "GitHub issue", comment: "GitHub comment" }; + for (const tool of Object.keys(GITHUB_TOOL_NAMES) as Tool[]) { + for (const [name, backend] of spellings(tool)) { + expect(resolveToolRenderer(call(name, undefined), backend)?.label, `${name} on ${backend}`).toBe(labels[tool]); + } + } + }); + + test("each read result renders its dedicated component on both backends", () => { + for (const backend of ["claude", "pi"] as const) { + expect(output("read", envelope("read", issue()), backend).container.querySelector("[data-github-issue]"), `issue on ${backend}`).not.toBeNull(); + expect(output("read", envelope("read", pull()), backend).container.querySelector("[data-github-pr]"), `PR on ${backend}`).not.toBeNull(); + expect(output("search", envelope("search", search()), backend).container.querySelector("[data-github-results]"), `search on ${backend}`).not.toBeNull(); + } + }); + + test("output that is not a result envelope falls back to its own words", () => { + const { container } = output("read", "GitHub tool host failed: socket closed"); + expect(container.querySelector("[data-github-issue], [data-github-pr]")).toBeNull(); + expect(container.textContent).toContain("socket closed"); + }); + + test("a refusal is drawn in its own words", () => { + const { container } = output("read", refusal("read", "unavailable", "no_credential", "This host has no GitHub credential for these tools.")); + expect(container.textContent).toContain("This host has no GitHub credential"); + }); + + test("the summary names the object, and nothing for an unparsed result", () => { + registerBuiltinRenderers(); + const name = visibleToolName(GITHUB_TOOL_NAMES.read, "pi"); + const renderer = resolveToolRenderer(call(name, undefined), "pi")!; + expect(renderer.summary?.(call(name, envelope("read", pull())))).toBe("ithaca/hall #412"); + expect(renderer.summary?.(call(name, "not json"))).toBeNull(); + }); +}); + +describe("absent is absent", () => { + test("no checks read 'None reported', never passing or zero", () => { + const fact = output("read", envelope("read", pull({ checks: null }))).container.querySelector("[data-github-fact='checks']")!; + expect(fact.textContent).toBe("Checks—None reported"); + }); + + test("no review reported reads 'Not reported'", () => { + const pr = pull({ review_decisions: [], reviews: { items: [], total_count: null, has_more: true } }); + expect(output("read", envelope("read", pr)).container.querySelector("[data-github-fact='reviews']")!.textContent).toBe("Reviews—Not reported"); + }); + + test("a deleted author reads as @ghost and asks for no avatar", () => { + const { container } = output("read", envelope("read", issue({ author: author(null, null) }))); + expect(container.textContent).toContain("@ghost"); + expect(container.querySelector("[data-github-issue] header img, [data-github-issue] img[src*='/avatars/null']")).toBeNull(); + }); +}); + +describe("direct links pass #3797's validator or render nowhere", () => { + const links = (container: HTMLElement) => [...container.querySelectorAll("a[data-github-link]")].map((a) => a.getAttribute("href")); + + test("valid canonical, comment, review, commit and search URLs each render as a direct link", () => { + const pr = output("read", envelope("read", pull())); + expect(links(pr.container)).toEqual(expect.arrayContaining([ + "https://github.com/ithaca/hall/pull/412", + "https://github.com/ithaca/hall/pull/412#issuecomment-7001", + "https://github.com/ithaca/hall/pull/412#pullrequestreview-9001", + ])); + fireEvent.click(pr.getByRole("tab", { name: /Commits/ })); + expect(links(pr.container)).toContain("https://github.com/ithaca/hall/commit/b81c0d4a8f3e2d1c0b9a8f7e6d5c4b3a29180716"); + const found = output("search", envelope("search", search())); + expect(links(found.container)).toContain("https://github.com/ithaca/hall/issues?q=repo%3Aithaca%2Fhall+bow+is%3Aopen"); + }); + + for (const [label, swap] of [ + ["another host", (u: string) => u.replace("https://github.com/", "https://github.com.evil.example/")], + ["another owner and repository", (u: string) => u.replace("/ithaca/hall/", "/circe/aeaea/")], + ["another number", (u: string) => u.replace("/pull/412", "/pull/413")], + ["http", (u: string) => u.replace("https:", "http:")], + ] as const) { + test(`a URL on ${label} renders no direct link in its slot, and nothing else changes`, () => { + const base = pull(); + const swapped = pull({ + html_url: swap(base.html_url), + comments: { ...base.comments, items: base.comments.items.map((c) => ({ ...c, html_url: swap(c.html_url) })) }, + reviews: { ...base.reviews, items: base.reviews.items.map((r) => ({ ...r, html_url: swap(r.html_url) })) }, + commits: { ...base.commits, items: base.commits.items.map((c) => ({ ...c, html_url: swap(c.html_url.replace("/commit/", "/pull/412/commits/")) })) }, + }); + const pr = output("read", envelope("read", swapped)); + expect(links(pr.container), "no direct link in any slot").toEqual([]); + expect(pr.container.textContent).toContain("Restring the great bow before the contest"); + fireEvent.click(pr.getByRole("tab", { name: /Commits/ })); + expect(links(pr.container), "no commit link").toEqual([]); + }); + } + + test("a search URL for another query or repository renders no search link", () => { + for (const searchUrl of ["https://github.com/ithaca/hall/issues?q=other", "https://github.com/circe/aeaea/issues?q=repo%3Aithaca%2Fhall+bow+is%3Aopen", null]) { + const found = output("search", envelope("search", search({ search_url: searchUrl }))); + expect(links(found.container).filter((h) => h?.includes("?q="))).toEqual([]); + } + }); +}); + +describe("untrusted text, end to end through a tool result", () => { + test("HTML, script and images stay text; javascript: is inert; the code block shows; https asks first", () => { + const pwned = globalThis as { __pwned?: boolean }; + pwned.__pwned = false; + const { container } = output("read", envelope("read", issue({ body: HOSTILE_BODY, body_length: HOSTILE_BODY.length }))); + const body = container.querySelector("[data-github-issue] [data-untrusted-text]")!; + expect(body.querySelector("script, img, iframe, object, embed"), "no interpreted HTML or content image").toBeNull(); + expect(body.textContent).toContain("