Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/3795-github-tool-cards.md
Original file line number Diff line number Diff line change
@@ -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.
236 changes: 236 additions & 0 deletions packages/ui-react/src/components/chat/renderers/github-mapping.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
// 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<string, string> = {
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<GithubReview["state"], GitHubReviewState> = {
approved: "approved",
changes_requested: "changes-requested",
commented: "commented",
dismissed: "dismissed",
// An unsubmitted draft review is not a request for review: it reads as not reported.
pending: null,
};

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: each latest decision, then each requested reviewer.
* GitHub lists a reviewer as requested again after a re-request, so a
* requested reviewer reads as requested even with an earlier decision: that
* decision is no longer the pending answer.
*/
export function reviewerRows(pr: GithubPullRequest, avatarFor: AvatarFor) {
const requested = new Set(pr.requested_reviewers.map((r) => r.login));
return [
...pr.review_decisions
.filter((d) => d.reviewer.login === null || !requested.has(d.reviewer.login))
.map((d) => ({ person: person(d.reviewer, avatarFor), state: reviewState(d.state), time: ago(d.submitted_at, pr.fetched_at) })),
...pr.requested_reviewers.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 }),
};
}
113 changes: 113 additions & 0 deletions packages/ui-react/src/components/chat/renderers/github-tools.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// 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 { awaitsDecision, type ToolCall } from "../../../stores/chat-state.js";
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 ? <ClampedPre text={tool.output} isError={tool.isError} /> : null);

/** The card a write tool's approval row shows: exactly what will be posted (W1, W4). */
function writeInput<T>(schema: { safeParse: (v: unknown) => { success: boolean; data?: T } }, Preview: ComponentType<{ input: T }>) {
return function WriteInput({ tool }: { tool: ToolCallView }) {
// Only while the approval waits. The approval row never receives an
// output, so after a decision a draft would keep reading "not posted";
// the original call's row shows what happened instead.
// A restored approval the host already closed (`readOnly`) waits for nothing.
if (!awaitsDecision(tool as ToolCall)) return null;
const parsed = schema.safeParse(tool.input);
return parsed.success && parsed.data ? <Preview input={parsed.data} /> : null;
};
}

const okOnly = <R,>(payload: GithubToolResult, pick: (p: Extract<GithubToolResult, { ok: true }>) => 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,
}),
],
};

/** The bare GitHub tool name behind any backend's spelling, or null. */
function githubToolName(name: string): string | null {
const bare = name.replace(/^mcp__brain[-_]ui__/, "");
return bare === GITHUB_TOOL_NAMES.create || bare === GITHUB_TOOL_NAMES.comment ? bare : null;
}

/**
* A GitHub write's approval header: where it goes, never the draft as one
* JSON line; the draft renders below as W1 or W4. The buttons say what
* happens, in the design's words.
*/
export function githubApproval(tool: Pick<ToolCallView, "name" | "input">): { target: string; allowLabel: string; denyLabel: string } | null {
const name = githubToolName(tool.name);
if (!name) return null;
const input = (tool.input ?? {}) as { repository?: unknown; number?: unknown };
const repository = typeof input.repository === "string" ? input.repository : "GitHub";
return name === GITHUB_TOOL_NAMES.create
? { target: repository, allowLabel: "Post issue", denyLabel: "Don't post" }
: { target: typeof input.number === "number" ? `${repository} #${input.number}` : repository, allowLabel: "Post comment", denyLabel: "Don't post" };
}
2 changes: 2 additions & 0 deletions packages/ui-react/src/components/chat/renderers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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);
Expand Down
Loading
Loading