diff --git a/.changeset/4154-comment-preview-author.md b/.changeset/4154-comment-preview-author.md new file mode 100644 index 0000000000..870b32c1fb --- /dev/null +++ b/.changeset/4154-comment-preview-author.md @@ -0,0 +1,17 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-kit": minor +"@schlessera/brain-ui-react": minor +--- + +A GitHub comment's approval card now says who would post the comment and whether it goes on an issue or a pull request, when the host can verify each: + +- **Who posts it:** the account the host's GitHub tools credential posts as. The host looks it up for that same credential and never shows one credential's account for another. +- **Where it goes:** the target's kind, read from GitHub for the card's own repository and number. This lookup asks the turn's data routing first, as a read does. +- **When the host cannot verify a fact:** the card shows "The host's GitHub account" and `owner/repo #number`, with no kind and no link. It never shows `@ghost` or a guessed kind, and the approval works as before. + +These facts are only shown on the card. The approved content, the check that the approval was not edited, the tool's result and what the model sees are unchanged. + +- **Wire and server SDK:** `tool_approval_request` and `PermissionRequest` gain the optional `display` field (`ApprovalDisplay`). +- **Kit:** `GitHubComment` in `preview` accepts no `author`, shows its whole draft and keeps the "Brain's draft · not posted" caption. `GitHubRef` accepts `kind: null`. diff --git a/api-report/ui-kit.txt b/api-report/ui-kit.txt index 1971aae4f7..5dfbfccd80 100644 --- a/api-report/ui-kit.txt +++ b/api-report/ui-kit.txt @@ -1332,15 +1332,21 @@ signatures (every public export and the types it is made of) } GitHubComment (packages/ui-kit/src/github/GitHubComment.tsx) export function GitHubComment(p: GitHubCommentProps): import("react").JSX.Element; - GitHubCommentProps (packages/ui-kit/src/github/GitHubComment.tsx) - export interface GitHubCommentProps { - author: GitHubPerson; + GitHubCommentBase (packages/ui-kit/src/github/GitHubComment.tsx) + interface GitHubCommentBase { time?: string; body: string; htmlUrl?: string | null; bodyTruncated?: boolean; - preview?: boolean; } + GitHubCommentProps (packages/ui-kit/src/github/GitHubComment.tsx) + export type GitHubCommentProps = GitHubCommentBase & ({ + author: GitHubPerson; + preview?: boolean; + } | { + author?: null; + preview: true; + }); GitHubCommitRow (packages/ui-kit/src/github/GitHubCommitRow.tsx) export function GitHubCommitRow(p: GitHubCommitRowProps): import("react").JSX.Element; GitHubCommitRowProps (packages/ui-kit/src/github/GitHubCommitRow.tsx) @@ -1482,7 +1488,7 @@ signatures (every public export and the types it is made of) export function GitHubRef(p: GitHubRefProps): import("react").JSX.Element; GitHubRefProps (packages/ui-kit/src/github/GitHubRef.tsx) export interface GitHubRefProps { - kind: "pr" | "issue"; + kind: "pr" | "issue" | null; repo: string; number?: number | null; htmlUrl?: string | null; diff --git a/api-report/ui-react.txt b/api-report/ui-react.txt index 4ec2b83cb1..f0138dccda 100644 --- a/api-report/ui-react.txt +++ b/api-report/ui-react.txt @@ -908,6 +908,7 @@ signatures (every public export and the types it is made of) approvalKind?: "tool" | "command" | "policy" | "actor"; approvalRememberable?: false; approvalDescription?: string; + approvalDisplay?: ApprovalDisplay; restored?: true; approvalTurnId?: string; readOnly?: RestoredApprovalClosure; diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 6da80e96d0..22d7a985a1 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -52,6 +52,7 @@ export "." (./src/index.ts) type ApifySpendScopeRead type ApifyUnresolvedRunRead type ApprovalChannel + type ApprovalDisplay type AskAnswerBinding type AskUserAnnotation type AskUserFormAnswer @@ -201,6 +202,7 @@ export "." (./src/index.ts) type FirstRequestCacheUsage type GeoCoords type GeoRequestOptions + type GithubApprovalDisplay type GovernedStatus type GovernedUnavailableReason type GraphBrokenLink @@ -602,6 +604,7 @@ export "./client" (./src/client/index.ts) type ApifyToolResult type ApifyUnresolvedRunRead type ApprovalChannel + type ApprovalDisplay type AskAnswerBinding type AskUserAnnotation type AskUserFormAnswer @@ -860,6 +863,7 @@ export "./client" (./src/client/index.ts) type GeoRequestOptions type GetCurrentLocationInput type GetSearchContentInput + type GithubApprovalDisplay type GithubAuthor type GithubChangedFile type GithubCheckRun @@ -1680,6 +1684,7 @@ export "./protocol" (./src/protocol.ts) type ApifySpendScopeRead type ApifyUnresolvedRunRead type ApprovalChannel + type ApprovalDisplay type AskAnswerBinding type AskUserAnnotation type AskUserFormAnswer @@ -1826,6 +1831,7 @@ export "./protocol" (./src/protocol.ts) type FirstRequestCacheUsage type GeoCoords type GeoRequestOptions + type GithubApprovalDisplay type GovernedStatus type GovernedUnavailableReason type GraphBrokenLink @@ -2156,6 +2162,7 @@ export "./schemas" (./src/schemas.ts) MAX_PROMPT_CHARS MAX_SERVER_FRAME_BYTES type ParseFrameResult + approvalDisplaySchema attachmentFileSchema attachmentLimitsSchema classifySessionRecoveryResponse @@ -2424,6 +2431,7 @@ export "./server" (./src/server/index.ts) type ApifyToolResult type ApifyUnresolvedRunRead type ApprovalChannel + type ApprovalDisplay type AskAnswerBinding type AskUserAnnotation type AskUserFormAnswer @@ -2750,6 +2758,7 @@ export "./server" (./src/server/index.ts) type GeoRequestOptions type GetCurrentLocationInput type GetSearchContentInput + type GithubApprovalDisplay type GithubAuthor type GithubChangedFile type GithubCheckRun @@ -4690,6 +4699,10 @@ signatures (every public export and the types it is made of) } ApprovalChannel (packages/ui-sdk/src/protocol.ts) export type ApprovalChannel = "card" | "voice"; + ApprovalDisplay (packages/ui-sdk/src/protocol.ts) + export interface ApprovalDisplay { + github?: GithubApprovalDisplay; + } AskAnswerBinding (packages/ui-sdk/src/protocol.ts) export interface AskAnswerBinding { submissionId?: string; @@ -9866,6 +9879,17 @@ signatures (every public export and the types it is made of) export type GetCurrentLocationInput = z.infer; GetSearchContentInput (packages/ui-sdk/src/tool-contracts/web.ts) export type GetSearchContentInput = z.infer; + GithubApprovalDisplay (packages/ui-sdk/src/protocol.ts) + export interface GithubApprovalDisplay { + poster: { + login: string; + is_bot: boolean; + } | null; + target: { + kind: "issue" | "pull_request"; + html_url: string | null; + } | null; + } GithubAuthor (packages/ui-sdk/src/tool-contracts/github.ts) export type GithubAuthor = z.infer; GithubChangedFile (packages/ui-sdk/src/tool-contracts/github.ts) @@ -11281,6 +11305,7 @@ signatures (every public export and the types it is made of) description?: string; kind?: "tool" | "command" | "policy" | "actor"; outsideEnforcedAllowlist?: boolean; + display?: import("../protocol.js").ApprovalDisplay; } PermissionScenario (packages/ui-sdk/src/testing/index.ts) export type PermissionScenario = "mutation" | "shortcut" | "command"; @@ -13737,6 +13762,7 @@ signatures (every public export and the types it is made of) description?: string; kind?: "tool" | "command" | "policy" | "actor"; rememberable?: boolean; + display?: ApprovalDisplay; } ServerToolInputDelta (packages/ui-sdk/src/protocol.ts) export interface ServerToolInputDelta extends SessionScoped { @@ -15341,6 +15367,22 @@ signatures (every public export and the types it is made of) } apifyOperationOf (packages/common/src/apify-operations.ts) export function apifyOperationOf(name: string): ApifyOperation | undefined; + approvalDisplaySchema (packages/ui-sdk/src/schemas.ts) + const approvalDisplaySchema: z.ZodObject<{ + github: z.ZodCatch>>; + target: z.ZodCatch; + kind: z.ZodEnum<{ + issue: "issue"; + pull_request: "pull_request"; + }>; + }, z.core.$loose>>>; + }, z.core.$loose>>>; + }, z.core.$loose>; assertLiveConversationProvider (packages/ui-sdk/src/server/conversation.ts) export function assertLiveConversationProvider(provider: LiveConversationProvider): void; assertLiveConversationSession (packages/ui-sdk/src/server/conversation.ts) @@ -24067,6 +24109,21 @@ signatures (every public export and the types it is made of) type: z.ZodLiteral<"tool_result">; }, z.core.$loose>, z.ZodObject<{ description: z.ZodOptional; + display: z.ZodCatch>>; + target: z.ZodCatch; + kind: z.ZodEnum<{ + issue: "issue"; + pull_request: "pull_request"; + }>; + }, z.core.$loose>>>; + }, z.core.$loose>>>; + }, z.core.$loose>>>; input: z.ZodRecord; kind: z.ZodOptional; + display: z.ZodCatch>>; + target: z.ZodCatch; + kind: z.ZodEnum<{ + issue: "issue"; + pull_request: "pull_request"; + }>; + }, z.core.$loose>>>; + }, z.core.$loose>>>; + }, z.core.$loose>>>; input: z.ZodRecord; kind: z.ZodOptional + +### Approval display facts (additive, 0.45.0, #4154) + +`tool_approval_request` optionally carries `display: ApprovalDisplay`, facts +the host verified for the card and nothing else. Today it has one member, +`github`, on a `brain_github_issue_comment` card: +`{ poster: { login, is_bot } | null, target: { kind: "issue" | "pull_request", html_url } | null }` +(`GithubApprovalDisplay`, `packages/ui-sdk/src/protocol.ts:1324-1327`). +`poster` is the account the host's GitHub tools credential posts as, resolved +for that same credential; `target` is the kind of the object at the card's own +repository and number, read from GitHub for exactly that repository and +number, with its `html_url` validated by the contract or `null`. + +- **Display only.** `input` stays exactly what is approved and sent; the answer + is compared with it alone, and a client never sends `display` back. The + facts grant no authority and never enter a tool input or result, the system + prompt or provider-facing history. +- **Unknown is neutral.** An absent `display`, an absent `github` or a `null` + fact is unknown. A client shows its neutral state ("The host's GitHub + account"; `repository #number` with no kind and no link) and the approval + works as before. Clients validate the shape + (`approvalDisplaySchema`, `packages/ui-sdk/src/schemas.ts:1386-1391`); + a fact that fails it reads as `null`, never as a refused card. +- **Re-delivery.** A pending card re-delivered after a reconnect carries the + host's facts for it again; a client replaces what it had. + +How the host resolves the facts, and when each is `null`, is in +[the MCP component](mcp.md#github-writes-additive-0450-3798). + ### Claude title-helper accounting (#2052) No WebSocket field changes. Root result/live usage remains completed main/child diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 2e766c59d7..c9b0e0195d 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -151,7 +151,7 @@ and [operational recovery](../inbox-recovery.md) remain binding. There is no general delete operation: `createSessionRoutes` only lists/reads (`createSessionRoutes`, `packages/ui-server/src/routes/sessions.ts:27-175`). `AgentBackend` exposes native list/read and read-only storage roots, not deletion -(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:826-882`). A storage root +(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:832-888`). A storage root is not removal authority. Future supported package/HTTP/wire changes need their actual contract assessment and a CONTRACT commit; additive capability negotiation ships in a minor. The approved retention exception is recorded before runtime diff --git a/docs/process/test-waits.md b/docs/process/test-waits.md index 2a5bebac5d..71fb309bce 100644 --- a/docs/process/test-waits.md +++ b/docs/process/test-waits.md @@ -231,8 +231,8 @@ case observes that later effect through its retained native window. The history and queue receiving observer is only a barrier for the current synchronous production handlers, not a generic asynchronous-handler completion claim: `session_history` and scoped `status` update the chat store synchronously -(`session_history`, `packages/ui-react/src/hooks/websocket-handlers/chat.ts:442-462`; -`status`, `packages/ui-react/src/hooks/websocket-handlers/chat.ts:463-488`), while +(`session_history`, `packages/ui-react/src/hooks/websocket-handlers/chat.ts:443-463`; +`status`, `packages/ui-react/src/hooks/websocket-handlers/chat.ts:464-489`), while queue adoption updates the follow-up/draft stores synchronously (`function queueReport(`, `packages/ui-react/src/ws-client/follow-ups.ts:85-94`). Native protocol completion, committed store state and the retained observation window serve diff --git a/packages/ui-kit/src/github/GitHubComment.tsx b/packages/ui-kit/src/github/GitHubComment.tsx index d0cbc1bdaf..587e55d973 100644 --- a/packages/ui-kit/src/github/GitHubComment.tsx +++ b/packages/ui-kit/src/github/GitHubComment.tsx @@ -1,8 +1,8 @@ import { UntrustedText } from "../evidence/UntrustedText.js"; -import { GitHubIdentity } from "./GitHubIdentity.js"; +import { GitHubHostAccount, GitHubIdentity, HOST_ACCOUNT } from "./GitHubIdentity.js"; import { GitHubStateChip } from "./GitHubStateChip.js"; import { GitHubLink, type GitHubPerson } from "./shared.js"; -import { DRAFT_SOURCE } from "./object-parts.js"; +import { DRAFT_CAPTION, DRAFT_SOURCE } from "./object-parts.js"; /** * `GitHubComment` — one comment: the identity row, then the body behind a @@ -11,9 +11,16 @@ import { DRAFT_SOURCE } from "./object-parts.js"; * * `htmlUrl` adds the comment's own direct `GitHub ↗` (D3). In `preview` the * comment is not posted yet (W4): the row says so and there is no link. + * + * A preview's `author` is the account the host verified it would post as; + * absent, the row names "The host's GitHub account" and no login (#4154). + * `login: null` keeps its meaning, a deleted account (`@ghost`), and is + * for posted comments. A preview shows its whole draft: what is approved is + * what is posted, so the posted comments' bound does not cut it. It also + * carries the draft caption, "Brain's draft · not posted", as W1 does: the + * poster says whose account would post it, the caption says who wrote it. */ -export interface GitHubCommentProps { - author: GitHubPerson; +interface GitHubCommentBase { /** "2 d ago". The kit never computes a time. */ time?: string; body: string; @@ -21,29 +28,37 @@ export interface GitHubCommentProps { htmlUrl?: string | null; /** The payload cut the body before it reached Brain. */ bodyTruncated?: boolean; - preview?: boolean; } +export type GitHubCommentProps = GitHubCommentBase & + ( + | { author: GitHubPerson; preview?: boolean } + /** A preview whose poster the host could not verify. */ + | { author?: null; preview: true } + ); + /** The comment body's hard bound, from the design's truncation table. */ export const COMMENT_MAX_CHARS = 10_000; export function GitHubComment(p: GitHubCommentProps) { - const login = p.author.login === null ? "@ghost" : `@${p.author.login}`; + const author = p.author ?? null; + const login = author === null ? null : author.login === null ? "@ghost" : `@${author.login}`; + const by = login ?? HOST_ACCOUNT.replace(/^The/, "the"); + const meta = p.preview ? : p.time; return ( -
+
- : p.time} /> - {p.preview ? null : } + {author ? : } + {p.preview ? null : }
diff --git a/packages/ui-kit/src/github/GitHubIdentity.tsx b/packages/ui-kit/src/github/GitHubIdentity.tsx index ad5339d02f..4363738051 100644 --- a/packages/ui-kit/src/github/GitHubIdentity.tsx +++ b/packages/ui-kit/src/github/GitHubIdentity.tsx @@ -108,6 +108,30 @@ export function GitHubIdentity(p: GitHubIdentityProps) { ); } +/** What a preview names when the host could not verify who would post (#4154). */ +export const HOST_ACCOUNT = "The host's GitHub account"; + +/** + * The poster of a comment not posted yet, when the host could not verify + * which account its credential posts as (#4154). It names no login: not + * `@ghost`, which means a deleted account, and no login the kit could + * guess. The avatar is an empty circle with a solid edge, so it reads + * neither as a person nor as the ghost's dashed one, and loads nothing. + */ +export function GitHubHostAccount(p: { meta?: ReactNode }) { + return ( + + + ); +} + /** * `GitHubParticipants` — up to four overlapping 20px faces, then `+n`, then * the count in words. The stack is decoration; "4 people" carries the count. diff --git a/packages/ui-kit/src/github/GitHubRef.tsx b/packages/ui-kit/src/github/GitHubRef.tsx index bd69caca1d..7ed82c7d6d 100644 --- a/packages/ui-kit/src/github/GitHubRef.tsx +++ b/packages/ui-kit/src/github/GitHubRef.tsx @@ -10,9 +10,13 @@ import { Field, GitHubLink, META, type GitHubState } from "./shared.js"; * With `title` (and usually `state`) it is the compact target row a comment * approval names its target with (W4): state, ref, title, `GitHub ↗`. * The kit never builds the URL; with no `htmlUrl` there is no link. + * + * `kind: null` is a target whose kind nobody verified (#4154): it reads + * `ithaca/hall #412`, claiming neither issue nor pull request, with no state + * chip and no link, whatever `htmlUrl` says. */ export interface GitHubRefProps { - kind: "pr" | "issue"; + kind: "pr" | "issue" | null; /** "owner/name". */ repo: string; /** Absent for an issue that is not posted yet. */ @@ -23,15 +27,21 @@ export interface GitHubRefProps { state?: GitHubState; } +const KIND = { pr: "PR", issue: "Issue" } as const; + export function GitHubRef(p: GitHubRefProps) { - const text = `${p.kind === "pr" ? "PR" : "Issue"} · ${p.repo}${p.number ? ` #${p.number}` : ""}`; + const kind = p.kind ? KIND[p.kind] : null; + const ref = `${p.repo}${p.number ? ` #${p.number}` : ""}`; + const text = kind ? `${kind} · ${ref}` : ref; + // An unverified kind has no verified link either. + const href = p.kind ? p.htmlUrl : null; if (p.title !== undefined) { return (
- {p.state ? : null} + {p.state && p.kind ? : null} {p.repo} {p.number ? ` #${p.number}` : ""} @@ -39,17 +49,18 @@ export function GitHubRef(p: GitHubRefProps) { {p.title} - +
); } return ( <> - - {p.kind === "pr" ? "PR" : "Issue"} · {p.repo} + + {kind ? `${kind} · ` : null} + {p.repo} {p.number ? ` #${p.number}` : ""} - + ); } diff --git a/packages/ui-kit/src/github/object-parts.tsx b/packages/ui-kit/src/github/object-parts.tsx index fff51a935a..b2950148a9 100644 --- a/packages/ui-kit/src/github/object-parts.tsx +++ b/packages/ui-kit/src/github/object-parts.tsx @@ -67,6 +67,8 @@ export function Labels({ labels }: { labels: string[] }) { /** Where a not-posted draft's links say they come from: it is not on GitHub yet. */ export const DRAFT_SOURCE = { source: "this draft", sourcePhrase: "in this draft" } as const; +/** The caption every not-posted draft carries: Brain wrote it, and it is not on GitHub (W1, W4). */ +export const DRAFT_CAPTION = "Brain's draft · not posted"; /** * An issue or pull request body. A read or posted body keeps the design's @@ -83,7 +85,7 @@ export function Body(p: { body?: string | null; author: string; bodyLength?: num return ( +
+ +
+ {p.poster ? : } + + ); +} + +const neutralPlay = (expected: { poster: boolean; kind: "issue" | "pr" | null }) => + async ({ canvas, canvasElement }: { canvas: { getByText: (t: string | RegExp) => HTMLElement; queryByText: (t: string | RegExp) => HTMLElement | null; getByRole: (role: string, o?: object) => HTMLElement }; canvasElement: HTMLElement }) => { + await expect(canvas.getByText("Not posted")).toBeVisible(); + await expect(canvas.getByText("Brain's draft · not posted"), "the draft says Brain wrote it, whoever would post it").toBeVisible(); + await expect(canvasElement.textContent, "an unverified poster is never the deleted-account ghost").not.toContain("@ghost"); + const comment = canvas.getByRole("article"); + if (expected.poster) { + await expect(comment).toHaveAccessibleName("Comment not posted by @ithaca-brain"); + } else { + await expect(canvas.getByText("The host's GitHub account")).toBeVisible(); + await expect(comment).toHaveAccessibleName("Comment not posted by the host's GitHub account"); + await expect(comment.querySelector("img"), "the host account loads no avatar").toBeNull(); + } + const ref = canvasElement.querySelector("[data-github-ref]")!; + if (expected.kind) { + await expect(ref.textContent).toBe(`${expected.kind === "pr" ? "PR" : "Issue"} · ithaca/hall #388`); + await expect(canvas.getByRole("link", { name: `${expected.kind === "pr" ? "PR" : "Issue"} · ithaca/hall #388 on GitHub, opens in a new tab` })).toBeVisible(); + } else { + await expect(ref.textContent, "an unverified kind claims neither").toBe("ithaca/hall #388"); + await expect(canvasElement.querySelector("a"), "an unverified kind has no link").toBeNull(); + } + }; + +/** W4, the poster unknown, on an issue. */ +export const W4UnknownPoster = meta.story({ ...desktop, render: () => , play: neutralPlay({ poster: false, kind: "issue" }) }); +export const W4UnknownPosterNarrow = W4UnknownPoster.extend({ ...narrow }); + +/** W4, the target's kind unknown, the poster known. */ +export const W4UnknownTarget = meta.story({ ...desktop, render: () => , play: neutralPlay({ poster: true, kind: null }) }); +export const W4UnknownTargetNarrow = W4UnknownTarget.extend({ ...narrow }); + +/** W4, nothing verified: both neutral states together. */ +export const W4NothingVerified = meta.story({ ...desktop, render: () => , play: neutralPlay({ poster: false, kind: null }) }); +export const W4NothingVerifiedNarrow = W4NothingVerified.extend({ ...narrow }); + +/** W4 on a pull request, both verified. */ +export const W4PullRequest = meta.story({ ...desktop, render: () => , play: neutralPlay({ poster: true, kind: "pr" }) }); +export const W4PullRequestNarrow = W4PullRequest.extend({ ...narrow }); + +/** W4 with the poster unknown on a pull request. */ +export const W4UnknownPosterPullRequest = meta.story({ ...desktop, render: () => , play: neutralPlay({ poster: false, kind: "pr" }) }); +export const W4UnknownPosterPullRequestNarrow = W4UnknownPosterPullRequest.extend({ ...narrow }); + +/** A preview shows its whole draft: the posted comments' 10,000-character bound does not cut what is approved (#4154). */ +export const W4LongDraft = meta.story({ + ...narrow, + render: () => , + play: async ({ canvas }) => { + await expect(canvas.queryByText("Truncated"), "a draft is never shown cut").toBeNull(); + await userEvent.click(canvas.getByRole("button", { name: "Show whole comment" })); + await expect(canvas.getByText(/The last line of the draft\./)).toBeVisible(); + }, +}); diff --git a/packages/ui-kit/tests/github-neutral-states.test.tsx b/packages/ui-kit/tests/github-neutral-states.test.tsx new file mode 100644 index 0000000000..9eccd27932 --- /dev/null +++ b/packages/ui-kit/tests/github-neutral-states.test.tsx @@ -0,0 +1,93 @@ +/** + * The GitHub kit's neutral states for what a host could not verify (#4154), + * as markup: a preview comment with no verified poster, and a target with no + * verified kind. What only a browser can answer (the 320px layout, both + * themes, the clamp's expand control, the a11y gate) is the W4 stories' in + * `stories/github/GitHubWrite.stories.tsx`. + */ +import { describe, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import type { ReactElement } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; + +import { ghost, telemachus } from "../fixtures/github.js"; +import { COMMENT_MAX_CHARS, GitHubComment } from "../src/github/GitHubComment.js"; +import { GitHubRef } from "../src/github/GitHubRef.js"; + +function draw(element: ReactElement): Document { + const { document } = new Window(); + document.body.innerHTML = renderToStaticMarkup(element); + return document as unknown as Document; +} + +const ISSUE_URL = "https://github.com/ithaca/hall/issues/388"; + +describe("a preview with no verified poster", () => { + test("names the host's GitHub account, never @ghost or any login, and loads no avatar", () => { + const doc = draw(); + const article = doc.querySelector("article")!; + expect(article.getAttribute("aria-label"), "KIT_HOST_ACCOUNT_NAME").toBe("Comment not posted by the host's GitHub account"); + expect(doc.body.textContent, "KIT_HOST_ACCOUNT_SHOWN").toContain("The host's GitHub account"); + expect(doc.body.textContent, "KIT_HOST_ACCOUNT_NOT_GHOST").not.toContain("ghost"); + expect(doc.body.textContent).not.toContain("@"); + expect(doc.querySelector("img")).toBeNull(); + expect(doc.querySelector("[data-avatar-state='ghost']"), "not the deleted account's dashed avatar").toBeNull(); + expect(doc.body.textContent, "still not posted").toContain("Not posted"); + expect(doc.querySelector("a"), "a preview has no link").toBeNull(); + }); + + test("a verified poster and a deleted posted author keep their meanings", () => { + expect(draw().querySelector("article")!.getAttribute("aria-label")).toBe("Comment not posted by @telemachus"); + const posted = draw(); + expect(posted.querySelector("article")!.getAttribute("aria-label"), "KIT_GHOST_IS_DELETED").toBe("Comment by @ghost"); + expect(posted.body.textContent).toContain("account deleted"); + }); + + test("a preview renders its whole draft; a posted comment keeps its bound", () => { + const body = `${"a".repeat(COMMENT_MAX_CHARS)}THE-END`; + const preview = draw(); + expect(preview.body.textContent, "KIT_PREVIEW_EXACT_BODY").toContain("THE-END"); + expect(preview.body.textContent).not.toContain("Truncated"); + const posted = draw(); + expect(posted.body.textContent, "the posted bound is unchanged").not.toContain("THE-END"); + expect(posted.body.textContent).toContain("Truncated"); + }); +}); + +describe("a preview's draft provenance (#4154 review)", () => { + test("every preview says Brain drafted it, whoever would post it; a posted comment does not", () => { + for (const element of [, ]) { + const doc = draw(element); + expect(doc.body.textContent, "KIT_PREVIEW_DRAFT_PROVENANCE").toContain("Brain's draft · not posted"); + } + const posted = draw(); + expect(posted.body.textContent, "a posted comment is not Brain's draft").not.toContain("Brain's draft"); + }); +}); + +describe("a target with no verified kind", () => { + test("reads repository #number, claims neither kind and has no link, whatever URL it is handed", () => { + for (const element of [ + , + , + ]) { + const doc = draw(element); + expect(doc.querySelector("[data-github-ref]")!.textContent, "KIT_UNKNOWN_KIND_TEXT").toBe("ithaca/hall #388"); + expect(doc.querySelector("a"), "KIT_UNKNOWN_KIND_NO_LINK").toBeNull(); + } + }); + + test("as the compact target row it shows no state chip and no link", () => { + const doc = draw(); + expect(doc.body.textContent).not.toMatch(/Issue|PR|Open/); + expect(doc.querySelector("a"), "KIT_UNKNOWN_KIND_ROW_NO_LINK").toBeNull(); + expect(doc.body.textContent).toContain("Suitors keep draining the wine store"); + }); + + test("a verified kind keeps its word and its link", () => { + const issue = draw(); + expect(issue.querySelector("[data-github-ref]")!.textContent).toBe("Issue · ithaca/hall #388"); + expect(issue.querySelector("a")!.getAttribute("href")).toBe(ISSUE_URL); + expect(draw().querySelector("[data-github-ref]")!.textContent).toBe("PR · ithaca/hall #412"); + }); +}); diff --git a/packages/ui-kit/tests/visual/__screenshots__/subjects.visual.tsx/github-write-comment-chromium-linux.png b/packages/ui-kit/tests/visual/__screenshots__/subjects.visual.tsx/github-write-comment-chromium-linux.png index 255334c896..02adb4bb47 100644 Binary files a/packages/ui-kit/tests/visual/__screenshots__/subjects.visual.tsx/github-write-comment-chromium-linux.png and b/packages/ui-kit/tests/visual/__screenshots__/subjects.visual.tsx/github-write-comment-chromium-linux.png differ diff --git a/packages/ui-kit/tests/visual/__screenshots__/subjects.visual.tsx/github-write-comment-light-chromium-linux.png b/packages/ui-kit/tests/visual/__screenshots__/subjects.visual.tsx/github-write-comment-light-chromium-linux.png index 9ec7d0c8ac..b01dab6d8f 100644 Binary files a/packages/ui-kit/tests/visual/__screenshots__/subjects.visual.tsx/github-write-comment-light-chromium-linux.png and b/packages/ui-kit/tests/visual/__screenshots__/subjects.visual.tsx/github-write-comment-light-chromium-linux.png differ diff --git a/packages/ui-react/src/components/chat/renderers/github-tools.tsx b/packages/ui-react/src/components/chat/renderers/github-tools.tsx index 09af207d4e..166f92eda3 100644 --- a/packages/ui-react/src/components/chat/renderers/github-tools.tsx +++ b/packages/ui-react/src/components/chat/renderers/github-tools.tsx @@ -9,6 +9,7 @@ // message) reaches the fallback. import type { RendererPack, ToolCallView } from "@schlessera/brain-ui-sdk/client"; +import type { ApprovalDisplay } from "@schlessera/brain-ui-sdk/protocol"; import { GITHUB_ISSUE_COMMENT_CONTRACT, GITHUB_ISSUE_COMMENT_INPUT_SCHEMA, @@ -43,8 +44,11 @@ const COMMENT = { ...GITHUB_ISSUE_COMMENT_CONTRACT, payload: GITHUB_RESULT_SCHEM /** 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 }>) { +/** + * The card a write tool's approval row shows: exactly what will be posted + * (W1, W4), with the host's display-only facts for it (#4154). + */ +function writeInput(schema: { safeParse: (v: unknown) => { success: boolean; data?: T } }, Preview: ComponentType<{ input: T; display?: ApprovalDisplay }>) { 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"; @@ -52,7 +56,8 @@ function writeInput(schema: { safeParse: (v: unknown) => { success: boolean; // 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 ? : null; + const display = (tool as ToolCall).approvalDisplay; + return parsed.success && parsed.data ? : null; }; } 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 index 26c7eadfeb..bd99d896f6 100644 --- a/packages/ui-react/src/components/chat/tool-cards/github-cards.tsx +++ b/packages/ui-react/src/components/chat/tool-cards/github-cards.tsx @@ -20,11 +20,11 @@ import { GitHubThread, GitHubWriteNotice, ListRow, - UntrustedText, type GitHubDetailState, type GitHubReviewProps, type GitHubThreadItem, } from "@schlessera/brain-ui-kit"; +import type { ApprovalDisplay } from "@schlessera/brain-ui-sdk/protocol"; import { GITHUB_DETAIL_PAGE_SIZE, GITHUB_LIMITS } from "@schlessera/brain-ui-sdk/tool-contracts"; import type { GithubChangedFile, @@ -677,25 +677,16 @@ export function GithubCommentCard(result: GithubToolResult) { const htmlUrl = directLink(posted.html_url, scope, { kind: "comment", id: posted.comment_id }); // The comment tool posts on issues and pull requests alike; only the // validated URL says which (`/pull/` or `/issues/`). Without one, the - // target is named without claiming either. + // kit's unknown kind names the target without claiming either. const kind = htmlUrl ? (new URL(htmlUrl).pathname.split("/")[3] === "pull" ? "pr" : "issue") : null; return (
- {kind ? : } +
); } -/** A comment's target when its kind is unknown: `owner/repo #n`, claiming neither issue nor pull request. */ -function Target({ repository, number }: { repository: string; number: number }) { - return ( - - {repository} #{number} - - ); -} - /** W1: the issue Brain asks to post, as it will look. */ export function GithubCreatePreview({ input }: { input: GithubIssueCreateInput }) { return ( @@ -703,16 +694,29 @@ export function GithubCreatePreview({ input }: { input: GithubIssueCreateInput } ); } -/** W4: the target and the comment Brain asks to post, as it will read. */ -export function GithubCommentPreview({ input }: { input: GithubIssueCommentInput }) { +/** + * W4: the target row above the comment Brain asks to post, as it will read. + * + * Who would post it and what the target is come only from the host's + * display facts (#4154), never from the model's input: an unverified poster + * is the kit's "host's GitHub account", an unverified kind its neutral + * `repository #number`, each independent of the other. The target's link + * passes the contract's validator for this repository and number, or is + * absent. The poster asks for no avatar: the avatar route serves only + * logins a tool result named. + */ +export function GithubCommentPreview({ input, display }: { input: GithubIssueCommentInput; display?: ApprovalDisplay }) { + const facts = display?.github; + const target = facts?.target ?? null; + const kind = target ? (target.kind === "pull_request" ? "pr" : "issue") : null; + const htmlUrl = target ? directLink(target.html_url, scopeOf(input.repository, input.number), { kind: target.kind }) : null; + const poster = facts?.poster ? { login: facts.poster.login, bot: facts.poster.is_bot, association: null, avatarSrc: null } : null; return (
-
- - {/* The approval names a number, not whether it is an issue or a pull request (#4154). */} - +
+
- + {poster ? : }
); } diff --git a/packages/ui-react/src/hooks/websocket-handlers/chat.ts b/packages/ui-react/src/hooks/websocket-handlers/chat.ts index 1239b76fcb..83fb82e1c1 100644 --- a/packages/ui-react/src/hooks/websocket-handlers/chat.ts +++ b/packages/ui-react/src/hooks/websocket-handlers/chat.ts @@ -348,7 +348,8 @@ export const chatFrameHandlers = { msg.description, msg.kind, msg.rememberable, - context.frameTurnId + context.frameTurnId, + msg.display ); }, tool_result: (msg, context) => { diff --git a/packages/ui-react/src/stores/chat-slices/approvals.ts b/packages/ui-react/src/stores/chat-slices/approvals.ts index 05a9959726..902a144f30 100644 --- a/packages/ui-react/src/stores/chat-slices/approvals.ts +++ b/packages/ui-react/src/stores/chat-slices/approvals.ts @@ -19,7 +19,7 @@ type ApprovalsSliceSlice = Pick + requestToolApproval: (key, toolUseId, toolName, input, description, kind, rememberable, turnId, display) => mutateBuffer(key, (chat) => { const msgs = [...chat.messages]; const request = (previous: ToolCall | undefined, restored: boolean): ToolCall => ({ @@ -32,6 +32,8 @@ export function createApprovalsSlice(ctx: ChatSliceContext): ApprovalsSliceSlice ...(kind === "policy" && POLICY_CHANGE_REVIEW_SCHEMA.safeParse(input.policyReview).success ? { policyChange: POLICY_CHANGE_REVIEW_SCHEMA.parse(input.policyReview) } : {}), ...(rememberable === false ? { approvalRememberable: false } : {}), ...(description ? { approvalDescription: description } : {}), + // Display only (#4154): a re-delivery carries the host's facts again, so they are never older than the card. + ...(display ? { approvalDisplay: display } : {}), // A card already pending keeps what it was; anything else is // restored when it lands on a message no live turn is streaming. ...((previous?.status === "pending_approval" ? previous.restored : restored) diff --git a/packages/ui-react/src/stores/chat-state.ts b/packages/ui-react/src/stores/chat-state.ts index 30faaa76e4..4cdda3cfa4 100644 --- a/packages/ui-react/src/stores/chat-state.ts +++ b/packages/ui-react/src/stores/chat-state.ts @@ -20,6 +20,7 @@ import type { ThinkingLevel, StateRoomObservation, TurnJournalSummary, + ApprovalDisplay, } from "@schlessera/brain-ui-sdk/protocol"; import type { StoreApi } from "zustand/vanilla"; import type { StatsSection } from "../lib/stats/compose-stats.js"; @@ -189,6 +190,13 @@ export interface ToolCall { * runtime's own text and is not drawn. */ approvalDescription?: string; + /** + * Facts the host verified for this card's display only (#4154): who a + * GitHub comment would be posted as, and the kind of its target. Never + * part of `input`, never sent back with the answer, never shown to the + * model. Absent means unknown, and the card shows its neutral state. + */ + approvalDisplay?: ApprovalDisplay; /** * The host re-delivered this pending approval after the transcript was * rebuilt from history (#964, D52 §4 R3): it is the original request, @@ -470,7 +478,9 @@ export interface ChatState { kind?: "tool" | "command" | "policy" | "actor", rememberable?: boolean, /** The host turn the request belongs to, from the frame. */ - turnId?: string + turnId?: string, + /** Display-only facts the host verified for the card (#4154). */ + display?: ApprovalDisplay ) => void; applyVoicePermission: (receipt: VoicePermissionReceipt) => void; resolveToolApproval: (key: ChatKey, toolUseId: string, approved: boolean) => void; diff --git a/packages/ui-react/tests/render/github-tools.test.tsx b/packages/ui-react/tests/render/github-tools.test.tsx index fb8692e31e..8d60f4964c 100644 --- a/packages/ui-react/tests/render/github-tools.test.tsx +++ b/packages/ui-react/tests/render/github-tools.test.tsx @@ -10,6 +10,7 @@ import { afterAll, afterEach, describe, expect, test } from "bun:test"; import { act, cleanup, fireEvent, render as mount, within } from "@testing-library/react"; import type { ReactElement } from "react"; import { visibleToolName, type ToolCallView } from "@schlessera/brain-ui-sdk/client"; +import type { ApprovalDisplay } from "@schlessera/brain-ui-sdk/protocol"; 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"; @@ -220,12 +221,13 @@ describe("untrusted text, end to end through a tool result", () => { }); describe("write views W1–W4", () => { - function approval(tool: "create" | "comment", input: Record) { + function approval(tool: "create" | "comment", input: Record, approvalDisplay?: ApprovalDisplay) { registerBuiltinRenderers(); const name = visibleToolName(GITHUB_TOOL_NAMES[tool], "claude"); const renderer = resolveToolRenderer(call(name, undefined), "claude")!; const Input = renderer.Input!; - return render(); + const tool_ = { ...call(name, undefined, { input, status: "pending_approval" }), ...(approvalDisplay ? { approvalDisplay } : {}) } as ToolCallView; + return render(); } test("W1: the issue approval shows exactly what will be posted, not posted, with no link", () => { @@ -257,6 +259,67 @@ describe("write views W1–W4", () => { expect(container.textContent).toContain("ithaca/hall #388"); expect(container.textContent).toContain("Filed #401 for the key log."); expect(container.textContent, "the approval names a number, not its kind").not.toMatch(/Issue ·|PR ·/); + // With no host facts at all, both neutral states (#4154). + expect(container.textContent, "W4_NO_FACTS_HOST_ACCOUNT").toContain("The host's GitHub account"); + expect(container.textContent, "W4_NO_FACTS_NEVER_GHOST").not.toContain("@ghost"); + expect(container.querySelector("a"), "W4_NO_FACTS_NO_LINK").toBeNull(); + }); + + describe("W4 names only what the host verified (#4154)", () => { + const input = { repository: "ithaca/hall", number: 388, body: "Filed #401 for the key log." }; + const poster = { login: "ithaca-brain", is_bot: false }; + const targets = { + issue: { kind: "issue", html_url: "https://github.com/ithaca/hall/issues/388" }, + pr: { kind: "pull_request", html_url: "https://github.com/ithaca/hall/pull/388" }, + unknown: null, + } as const; + for (const known of [true, false]) { + for (const [label, target] of Object.entries(targets)) { + test(`${known ? "a verified" : "an unknown"} poster on ${label === "unknown" ? "an unverified target" : `a verified ${label}`}`, () => { + const { container, getByRole } = approval("comment", input, { github: { poster: known ? poster : null, target } }); + const comment = getByRole("article"); + expect(comment.getAttribute("aria-label"), `W4_POSTER ${known} ${label}`).toBe(known ? "Comment not posted by @ithaca-brain" : "Comment not posted by the host's GitHub account"); + expect(container.textContent, `W4_NEVER_GHOST ${known} ${label}`).not.toContain("@ghost"); + expect(comment.querySelector("img"), "the poster asks for no avatar").toBeNull(); + const ref = container.querySelector("[data-github-target] [data-github-ref]")!; + const links = [...container.querySelectorAll("a")].map((a) => a.getAttribute("href")); + if (target) { + const word = target.kind === "pull_request" ? "PR" : "Issue"; + expect(ref.textContent, `W4_KIND ${known} ${label}`).toBe(`${word} · ithaca/hall #388`); + expect(links, `W4_TARGET_LINK ${known} ${label}`).toEqual([target.html_url]); + } else { + expect(ref.textContent, `W4_UNKNOWN_KIND ${known} ${label}`).toBe("ithaca/hall #388"); + expect(links, `W4_UNKNOWN_KIND_NO_LINK ${known}`).toEqual([]); + } + expect(container.textContent).toContain("Not posted"); + expect(container.textContent, `W4_DRAFT_PROVENANCE ${known} ${label}`).toContain("Brain's draft · not posted"); + expect(container.textContent).toContain("Filed #401 for the key log."); + }); + } + } + + test("a target link that does not point at this repository and number renders nowhere, and the kind stays", () => { + for (const html_url of ["https://github.com/ithaca/hall/issues/389", "https://github.com/circe/aiaia/issues/388", "https://github.com.evil.example/ithaca/hall/issues/388"]) { + const { container, unmount } = approval("comment", input, { github: { poster, target: { kind: "issue", html_url } } }); + expect(container.querySelector("a"), `W4_TARGET_LINK_VALIDATED ${html_url}`).toBeNull(); + expect(container.querySelector("[data-github-ref]")!.textContent).toBe("Issue · ithaca/hall #388"); + unmount(); + } + }); + + test("the model's input never supplies the facts: a poster or kind in it is ignored", () => { + const { container } = approval("comment", { ...input, poster: "penelope", kind: "pull_request" } as Record); + expect(container.textContent).not.toContain("penelope"); + expect(container.textContent, "W4_INPUT_NOT_FACTS").not.toMatch(/Issue ·|PR ·/); + }); + + test("the whole draft shows, past the posted comments' 10,000-character bound", () => { + const body = `${"The tally of the wine store. ".repeat(400)}The last line.`; + // The clamp is layout (the kit's story proves it in a browser); what is rendered is the whole draft. + const { container } = approval("comment", { ...input, body }, { github: { poster, target: targets.issue } }); + expect(container.textContent, "W4_EXACT_BODY").toContain("The last line."); + expect(container.textContent).not.toContain("Truncated"); + }); }); test("a posted comment names its target's kind from its validated URL, and claims neither without one", () => { diff --git a/packages/ui-react/tests/restored-approval-store.test.ts b/packages/ui-react/tests/restored-approval-store.test.ts index c38acc5e69..78c17ecfb0 100644 --- a/packages/ui-react/tests/restored-approval-store.test.ts +++ b/packages/ui-react/tests/restored-approval-store.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import type { ClientMessage, ServerMessage, SessionRecovery, SessionRecoveryLatest, SessionRecoveryPending } from "@schlessera/brain-ui-sdk/protocol"; import { createBrainUiRoot, type BrainUiRoot } from "../src/root.js"; import { pendingApprovals, type ToolCall } from "../src/stores/chat-state.js"; +import { replyToToolApproval } from "../src/lib/tool-approval.js"; import { trackerViews } from "../src/stores/tracker-state.js"; // A restored approval card follows the host's recovery envelope (#1072, @@ -348,3 +349,31 @@ describe("without the capability", () => { expect(card(r, A).readOnly).toBeUndefined(); }); }); + +describe("an approval's display facts (#4154)", () => { + const comment = { repository: "odysseus/ithaca", number: 7, body: "The stores are counted again." }; + const github = (login: string | null) => ({ github: { poster: login ? { login, is_bot: false } : null, target: { kind: "issue" as const, html_url: "https://github.com/odysseus/ithaca/issues/7" } } }); + const raise = (r: BrainUiRoot, display?: Record) => frame(r, { + type: "tool_approval_request", sessionId: A, turnId: "turn-2", toolUseId: "github-1", toolName: "brain_github_issue_comment", + input: comment, kind: "command", ...(display ? { display } : {}), + }); + + test("ride the card beside its unchanged input, and a re-delivery carries the host's current facts", async () => { + const r = root(); + hello(r, false); + r.stores.chat.getState().setActiveSession(A); + frame(r, { type: "session_history", sessionId: A, messages: [{ role: "user", content: "Tell the hall the stores are counted", toolCalls: [] }] }); + raise(r, github("ithaca-brain")); + expect(card(r, A, "brain_github_issue_comment").approvalDisplay, "APPROVAL_DISPLAY_STORED").toEqual(github("ithaca-brain")); + expect(card(r, A, "brain_github_issue_comment").input, "APPROVAL_DISPLAY_NOT_IN_INPUT").toEqual(comment); + // A reconnect after the host's credential changed: the old poster is not kept. + raise(r, github(null)); + expect(card(r, A, "brain_github_issue_comment").approvalDisplay, "APPROVAL_DISPLAY_REDELIVERED").toEqual(github(null)); + raise(r); + expect(card(r, A, "brain_github_issue_comment").approvalDisplay, "APPROVAL_DISPLAY_ABSENT_IS_UNKNOWN").toBeUndefined(); + raise(r, github("ithaca-brain")); + const answers: ClientMessage[] = []; + expect(replyToToolApproval(r, A, (message) => { answers.push(message); return true; }, "github-1", true), "positive control: the card is answered").toBe(true); + expect(answers, "APPROVAL_DISPLAY_NEVER_SENT_BACK").toEqual([{ type: "tool_approval", toolUseId: "github-1", channel: "card" }]); + }); +}); diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 657f3f13e1..59a6e0a114 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -1298,6 +1298,32 @@ export interface ServerToolApprovalRequest extends SessionScoped { * refusal whatever the client sends. */ rememberable?: boolean; + /** + * Facts the host verified for the card's display only (additive, #4154). + * They never change what is approved: `input` stays the exact content, + * and the answer is compared with it alone. They grant no authority and + * never reach the model. Absent, or a fact `null`, means unknown: the + * card shows its neutral state instead and the approval works as before. + */ + display?: ApprovalDisplay; +} + +/** Host-verified facts an approval card may show (#4154). Display only. */ +export interface ApprovalDisplay { + /** A GitHub comment approval: who would post it, and on what. */ + github?: GithubApprovalDisplay; +} + +/** + * What the host verified about a GitHub comment approval (#4154). `poster` + * is the account the host's GitHub tools credential posts as, resolved for + * that same credential; `target` is the kind of the object at the card's + * repository and number, read from GitHub for that same repository and + * number. Either is `null` when it could not be verified. + */ +export interface GithubApprovalDisplay { + poster: { login: string; is_bot: boolean } | null; + target: { kind: "issue" | "pull_request"; html_url: string | null } | null; } export interface ServerResultMessage { diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index 3799250425..452cd2e509 100644 --- a/packages/ui-sdk/src/schemas.ts +++ b/packages/ui-sdk/src/schemas.ts @@ -110,6 +110,7 @@ import type { ServerTextDelta, ServerThinkingDelta, ServerToolApprovalRequest, + ApprovalDisplay, ServerToolInputDelta, ServerToolResult, ServerToolUseComplete, @@ -1377,6 +1378,18 @@ export const serverToolResultSchema = z.looseObject({ ...sessionScoped, }) satisfies z.ZodType; +/** + * Display-only facts on an approval (#4154). A fact that fails this shape is + * dropped, never the card: unknown display reads as the neutral state, and + * the approval itself is unaffected. + */ +export const approvalDisplaySchema = z.looseObject({ + github: z.looseObject({ + poster: z.looseObject({ login: z.string().regex(/^[A-Za-z0-9-]{1,39}(?:\[bot\])?$/), is_bot: z.boolean() }).nullable().catch(null), + target: z.looseObject({ kind: z.enum(["issue", "pull_request"]), html_url: z.string().max(2048).nullable() }).nullable().catch(null), + }).optional().catch(undefined), +}) satisfies z.ZodType; + export const serverToolApprovalRequestSchema = z.looseObject({ type: z.literal("tool_approval_request"), toolUseId: z.string().max(MAX_ID_CHARS), @@ -1385,6 +1398,7 @@ export const serverToolApprovalRequestSchema = z.looseObject({ description: z.string().optional(), kind: z.enum(["tool", "command", "policy", "actor"]).optional(), rememberable: z.boolean().optional(), + display: approvalDisplaySchema.optional().catch(undefined), ...sessionScoped, }) satisfies z.ZodType; diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts index a648a86877..3d8b80ce15 100644 --- a/packages/ui-sdk/src/server/backend.ts +++ b/packages/ui-sdk/src/server/backend.ts @@ -138,6 +138,12 @@ export interface PermissionRequest { * @experimental */ outsideEnforcedAllowlist?: boolean; + /** + * Host-verified facts the card shows, display only (#4154). Sent with the + * approval frame; never part of `input`, never compared with the answer, + * never authority. + */ + display?: import("../protocol.js").ApprovalDisplay; } export interface AskUserResult { diff --git a/packages/ui-sdk/tests/server-schemas.test.ts b/packages/ui-sdk/tests/server-schemas.test.ts index d65298663c..6f40161387 100644 --- a/packages/ui-sdk/tests/server-schemas.test.ts +++ b/packages/ui-sdk/tests/server-schemas.test.ts @@ -424,6 +424,36 @@ test("policy approval and live/replay receipts survive the validated additive bo expect(parse({ ...frames[1], policyChange: { ...policyChange, baseHash: undefined } }).ok).toBe(false); }); +describe("approval display facts (#4154)", () => { + const card = { type: "tool_approval_request", toolUseId: "github-1", toolName: "brain_github_issue_comment", kind: "command", + input: { repository: "odysseus/ithaca", number: 7, body: "Counted." }, sessionId: "s1", turnId: "turn-1" } as const; + const display = { github: { poster: { login: "ithaca-brain", is_bot: false }, target: { kind: "pull_request", html_url: "https://github.com/odysseus/ithaca/pull/7" } } }; + + test("verified facts and unknown ones survive the boundary as sent", () => { + for (const frame of [{ ...card, display }, { ...card, display: { github: { poster: null, target: null } } }, card]) { + const result = parse(frame); + expect(result.ok, "APPROVAL_DISPLAY_PARSES").toBe(true); + if (result.ok) expect(result.message).toEqual(frame as ServerMessage); + } + }); + + test("a fact that fails its shape reads as unknown, and the card itself still arrives", () => { + for (const [label, broken, expected] of [ + ["an invalid login", { github: { ...display.github, poster: { login: "not a login", is_bot: false } } }, { github: { poster: null, target: display.github.target } }], + ["an unknown kind", { github: { ...display.github, target: { kind: "discussion", html_url: null } } }, { github: { poster: display.github.poster, target: null } }], + ["a github entry that is not an object", { github: "Issue" }, {}], + ["display that is not an object", "PR", undefined], + ] as const) { + const result = parse({ ...card, display: broken }); + expect(result.ok, `APPROVAL_DISPLAY_NEVER_DROPS_THE_CARD ${label}`).toBe(true); + if (result.ok && result.message.type === "tool_approval_request") { + expect(result.message.display, `APPROVAL_DISPLAY_BROKEN_IS_UNKNOWN ${label}`).toEqual(expected as never); + expect(result.message.input, label).toEqual(card.input); + } + } + }); +}); + describe("live-service roster (#3616)", () => { const profile = (providerId: string) => ({ providerId, capabilities: { nonblockingWork: "supported", manualEndpoint: "supported", finalTranscript: "unproven", remoteOutputCancelAck: "unproven", exactPermissionSpeech: "unproven", echoIsolatedInput: "unproven", outputWordAlignment: "unproven" }, disclosure: { voiceService: `Fictional ${providerId}`, destinations: ["Microphone audio goes to the fictional voice service."] } }); diff --git a/packages/ui-server/src/github/host.ts b/packages/ui-server/src/github/host.ts index 19e85905d6..9ae55290b1 100644 --- a/packages/ui-server/src/github/host.ts +++ b/packages/ui-server/src/github/host.ts @@ -24,7 +24,9 @@ * are not routed: the per-use card, which shows the exact body, and the * allow-list are their gate (maintainer ruling, 2026-11-16). */ +import { createHash } from "node:crypto"; import { githubWriteAllowance } from "@schlessera/brain-common/internal/governance-policy"; +import type { GithubApprovalDisplay } from "@schlessera/brain-ui-sdk/protocol"; import type { PermissionDecision, PermissionRequest } from "@schlessera/brain-ui-sdk/server"; import type { RecipientRoutingRefusal } from "../web-tools/routing.js"; import { @@ -101,6 +103,8 @@ export interface GithubToolsHostOptions { now?: () => number; /** One request's limit, milliseconds. */ timeoutMs?: number; + /** The whole of one approval card's display lookup, milliseconds (#4154); never more than `timeoutMs`. */ + displayTimeoutMs?: number; report?: (message: string) => void; } @@ -285,11 +289,73 @@ export async function githubGet(transport: GithubTransport, token: string, path: throw new GithubRefusal("upstream_error", "redirect", "GitHub redirected too many times."); } +/** How long a comment card waits for its display facts before showing the neutral state (#4154). */ +const GITHUB_DISPLAY_TIMEOUT_MS = 3_000; +/** How long a verified poster is reused for the same credential. */ +export const GITHUB_POSTER_TTL_MS = 10 * 60_000; +/** How long a failed poster lookup is not repeated for the same credential, so a failing credential costs one request a minute. */ +export const GITHUB_POSTER_RETRY_MS = 60_000; + export function createGithubToolsHost(options: GithubToolsHostOptions): GithubToolsHost { const now = options.now ?? Date.now; const timeoutMs = options.timeoutMs ?? 20_000; const get = (token: string, path: string, signal: AbortSignal | undefined) => githubGet(options, token, path, signal); + // Display facts for a comment card (#4154). They are shown on the card + // only: never part of its input, never compared with the answer, never + // returned to the model. Every failure is `null`, the neutral state. + const displayTimeoutMs = Math.min(options.displayTimeoutMs ?? GITHUB_DISPLAY_TIMEOUT_MS, timeoutMs); + const display = { fetch: options.fetch, now: options.now, timeoutMs: displayTimeoutMs } satisfies GithubTransport; + /** The credential an entry was resolved for, as a digest: the token itself is never kept here. */ + const credentialKey = (token: string) => createHash("sha256").update(token).digest("hex"); + /** + * The one poster entry, for one credential. A lookup for any other + * credential replaces it and never reads it, so one credential's identity + * is never shown for another. Concurrent cards share its one request. + */ + let poster: { key: string; at: number; ttl: number; value: Promise } | null = null; + function verifiedPoster(token: string): Promise { + const key = credentialKey(token), at = now(); + if (poster && poster.key === key && at - poster.at < poster.ttl) return poster.value; + const entry: NonNullable = { key, at, ttl: GITHUB_POSTER_TTL_MS, value: Promise.resolve(null) }; + entry.value = githubGet(display, token, "/user", AbortSignal.timeout(displayTimeoutMs)).then(({ json }) => { + const found = user(json); + if (found.login) return { login: found.login, is_bot: found.is_bot }; + entry.ttl = GITHUB_POSTER_RETRY_MS; + return null; + }, () => { + entry.ttl = GITHUB_POSTER_RETRY_MS; + return null; + }); + poster = entry; + return entry.value; + } + /** A credential GitHub rejected keeps no identity. */ + const forgetPoster = (token: string) => { if (poster?.key === credentialKey(token)) poster = null; }; + + /** + * The kind of the object at exactly this repository and number. The + * request sends model-chosen text before the card, so it asks the turn's + * data routing (G2) first, as a read does; a refusal leaves the kind + * unknown and changes nothing else about the write. + */ + async function verifiedTarget(turn: GithubToolsTurn, token: string, repository: string, number: number): Promise { + try { + if (await turn.routing(GITHUB_RECIPIENT) !== null) return null; + const { owner, repo } = parseGithubRepository(repository)!; + const name = `${owner}/${repo}`; + const deadline = AbortSignal.timeout(displayTimeoutMs); + const { json } = await githubGet(display, token, `/repos/${name}/issues/${number}`, turn.signal ? AbortSignal.any([turn.signal, deadline]) : deadline); + const found = record(json); + // Bound to the card's own repository and number: a transferred issue or another object is unknown. + if (!found || integer(found.number) !== number || String(found.repository_url).toLowerCase() !== `${GITHUB_API_ORIGIN}/repos/${name}`.toLowerCase()) return null; + const kind = record(found.pull_request) ? "pull_request" as const : "issue" as const; + return { kind, html_url: githubDirectUrl(found.html_url, { owner, repo, number }, { kind }) }; + } catch { + return null; + } + } + /** A path below the API origin from a `next` link, only when it stays there. */ const relative = (link: string) => { const url = new URL(link); @@ -478,7 +544,7 @@ export function createGithubToolsHost(options: GithubToolsHostOptions): GithubTo } const input = GITHUB_ISSUE_COMMENT_INPUT_SCHEMA.parse(call.input); const payload: Json = { body: input.body }; - return { repository: input.repository, path: `/repos/${input.repository}/issues/${input.number}/comments`, payload, + return { repository: input.repository, number: input.number, path: `/repos/${input.repository}/issues/${input.number}/comments`, payload, card: { repository: input.repository, number: input.number, ...payload } as Json, target: `${input.repository}#${input.number}`, describe: `Post this comment on ${input.repository}#${input.number} on GitHub` }; } @@ -521,7 +587,11 @@ export function createGithubToolsHost(options: GithubToolsHostOptions): GithubTo } const token = options.token(); if (!token) return noCredential(tool); + // A comment card names who would post it and on what, when the host can verify both (#4154). + const shown = prepared.number !== undefined ? await Promise.all([verifiedPoster(token), verifiedTarget(turn, token, prepared.repository, prepared.number)]) + .then(([posterFact, targetFact]) => ({ github: { poster: posterFact, target: targetFact } })) : undefined; const decision = await ctx.requestPermission({ toolUseId: `github-${crypto.randomUUID()}`, toolName: visible, kind: "command", input: prepared.card, + ...(shown ? { display: shown } : {}), description: `${prepared.describe}, exactly as shown. It is sent once, in your name, through the host's GitHub credential, and cannot be undone from here.` + (tainted ? " This conversation has read untrusted input; its content may have been shaped by it." : "") }); // An edited card is a different write: it is refused, and the call must be made again as wanted, which rechecks it. @@ -538,7 +608,13 @@ export function createGithubToolsHost(options: GithubToolsHostOptions): GithubTo } if (!await decide("approved")) return refusal(tool, "unavailable", "recording_unavailable", "The approval could not be recorded, so nothing was sent."); const { owner, repo } = parseGithubRepository(prepared.repository)!; - const created = record(await post(token, prepared.path, prepared.payload, turn.signal)); + let answered: unknown; + try { answered = await post(token, prepared.path, prepared.payload, turn.signal); } + catch (error) { + if (error instanceof GithubRefusal && error.reason === "credential_rejected") forgetPoster(token); + throw error; + } + const created = record(answered); if (tool === GITHUB_TOOL_NAMES.create) { const number = integer(created?.number); if (!created || !number) throw new GithubRefusal("upstream_error", "malformed", "GitHub accepted the issue but returned an unexpected answer."); diff --git a/packages/ui-server/src/ws/frames.ts b/packages/ui-server/src/ws/frames.ts index e49e755cc7..bfc6bbbd53 100644 --- a/packages/ui-server/src/ws/frames.ts +++ b/packages/ui-server/src/ws/frames.ts @@ -50,6 +50,8 @@ export function approvalRequestFrame( description: req.description, ...(req.kind ? { kind: req.kind } : {}), ...(req.kind === "policy" || req.outsideEnforcedAllowlist || (!hasGrantStore && req.kind !== "actor") ? { rememberable: false } : {}), + // Display-only facts the host verified (#4154); a re-delivery carries the same ones. + ...(req.display ? { display: req.display } : {}), }; } diff --git a/packages/ui-server/tests/fixtures/github-host-fixture.ts b/packages/ui-server/tests/fixtures/github-host-fixture.ts index f7d6d3b1f5..e8ca6854ac 100644 --- a/packages/ui-server/tests/fixtures/github-host-fixture.ts +++ b/packages/ui-server/tests/fixtures/github-host-fixture.ts @@ -5,11 +5,14 @@ * combined status and issue search). It records every request with the * authorization it carried, and a write's body. Writes (#3798): an issue * filed in any repository, and a comment on any issue, answer 201 like - * GitHub, so a refusal proves itself by what never arrived. Keyless: the - * token is a synthetic sentinel. + * GitHub, so a refusal proves itself by what never arrived. `/user` names + * the account a credential posts as (#4154). Keyless: the token is a + * synthetic sentinel. */ export const GITHUB_TOOLS_SENTINEL = "odysseus-github-tools-sentinel-token"; export const GENERIC_GITHUB_SENTINEL = "odysseus-generic-github-sentinel-token"; +/** The login `/user` answers for any credential: the account the host's GitHub tools post as. */ +export const GITHUB_TOOLS_POSTER = "ithaca-brain"; export const HEAD_SHA = "1111111111111111111111111111111111111111"; export const MERGE_SHA = "2222222222222222222222222222222222222222"; export const COMMIT_SHAS = ["3333333333333333333333333333333333333333", "4444444444444444444444444444444444444444"] as const; @@ -121,6 +124,8 @@ export function fakeGithub(options: FakeGithubOptions = {}): FakeGithub { { status: "in_progress", conclusion: null }, { status: "completed", conclusion: "skipped" }] }); case `/repos/odysseus/ithaca/commits/${HEAD_SHA}/status`: return json(options.checks === "none" ? { state: "pending", total_count: 0, statuses: [] } : { state: "success", total_count: 1, statuses: [{ state: "success" }] }); + // The account the host credential posts as (#4154). + case "/user": return json({ login: GITHUB_TOOLS_POSTER, type: "User" }); case "/search/issues": return json({ total_count: 57, incomplete_results: false, items: [ { ...issue, body: " The stores run low. " }, pullIssue, diff --git a/packages/ui-server/tests/github-write-tools.test.ts b/packages/ui-server/tests/github-write-tools.test.ts index 85dd4cf001..4d216ce5cf 100644 --- a/packages/ui-server/tests/github-write-tools.test.ts +++ b/packages/ui-server/tests/github-write-tools.test.ts @@ -9,8 +9,8 @@ import { afterEach, describe, expect, test } from "bun:test"; import { GITHUB_RESULT_SCHEMAS, type GithubToolCall, type GithubToolResult } from "@schlessera/brain-ui-sdk/tool-contracts"; import type { PermissionDecision, PermissionRequest } from "@schlessera/brain-ui-sdk/server"; -import { createGithubToolsHost, type GithubOutwardAction, type GithubToolsHostOptions, type GithubToolsTurn, type GithubWriteTurn } from "../src/github/host.js"; -import { GITHUB_TOOLS_SENTINEL, fakeGithub, standInFetch, type FakeGithub, type FakeGithubOptions } from "./fixtures/github-host-fixture.js"; +import { GITHUB_POSTER_RETRY_MS, GITHUB_POSTER_TTL_MS, createGithubToolsHost, type GithubOutwardAction, type GithubToolsHostOptions, type GithubToolsTurn, type GithubWriteTurn } from "../src/github/host.js"; +import { GITHUB_TOOLS_POSTER, GITHUB_TOOLS_SENTINEL, fakeGithub, standInFetch, type FakeGithub, type FakeGithubOptions } from "./fixtures/github-host-fixture.js"; const stops: FakeGithub[] = []; afterEach(() => { for (const fake of stops.splice(0)) fake.stop(); }); @@ -24,10 +24,11 @@ interface Harness { } function harness(answer: (request: PermissionRequest) => PermissionDecision | Promise = () => ({ behavior: "allow" }), - options: { repositories?: readonly string[] | null; host?: Partial; github?: FakeGithubOptions } = {}): Harness { + options: { repositories?: readonly string[] | null; host?: Partial; github?: FakeGithubOptions; wrap?: (base: typeof fetch) => typeof fetch } = {}): Harness { const fake = fakeGithub(options.github); stops.push(fake); const cards: PermissionRequest[] = [], recorded: GithubOutwardAction[] = []; - const github = createGithubToolsHost({ token: () => GITHUB_TOOLS_SENTINEL, fetch: standInFetch(fake), now: () => Date.parse("2026-07-12T12:00:00Z"), + const base = standInFetch(fake); + const github = createGithubToolsHost({ token: () => GITHUB_TOOLS_SENTINEL, fetch: options.wrap ? options.wrap(base) : base, now: () => Date.parse("2026-07-12T12:00:00Z"), untrusted: async () => {}, ...options.host }); return { fake, cards, recorded, call: (call, overrides = {}, turnOverrides = {}) => { const write: GithubWriteTurn = { @@ -213,7 +214,13 @@ describe("data routing (G2, #4029) does not gate writes", () => { expect(routed.cards.map(card => [card.toolName, card.input]), "GITHUB_WRITE_CARD_UNCHANGED_UNDER_ROUTING").toEqual(plain.cards.map(card => [card.toolName, card.input])); expect(routed.cards).toHaveLength(2); expect(writes(routed.fake).map(request => [request.path, request.body]), "GITHUB_WRITE_SENT_UNDER_ROUTING").toEqual(writes(plain.fake).map(request => [request.path, request.body])); - expect(asked, "GITHUB_WRITE_NEVER_ASKS_ROUTING").toEqual([]); + // The write's gate never asks: only the comment card's display lookup + // does, before it sends the repository and number (#4154), and a refusal + // leaves the target's kind unknown and sends GitHub no lookup for it. + expect(asked, "GITHUB_WRITE_ROUTING_ONLY_FOR_DISPLAY").toEqual(["github"]); + expect(routed.cards[1]!.display?.github?.target, "GITHUB_ROUTED_TARGET_UNKNOWN").toBeNull(); + expect(routed.fake.seen.filter(request => request.method === "GET" && request.path === "/repos/odysseus/ithaca/issues/7"), "GITHUB_ROUTED_NO_TARGET_LOOKUP").toEqual([]); + expect(plain.cards[1]!.display?.github?.target, "positive control: an admitted turn verifies the target").toEqual({ kind: "issue", html_url: "https://github.com/odysseus/ithaca/issues/7" }); }); }); @@ -237,3 +244,161 @@ describe("postures that never approve", () => { expect(h.fake.seen).toEqual([]); }); }); + +describe("a comment card's display facts (#4154)", () => { + const PULL = { ...COMMENT, input: { ...COMMENT.input, number: 8 } } as const satisfies GithubToolCall; + const lookups = (fake: FakeGithub, path: string) => fake.seen.filter(request => request.method === "GET" && request.path === path).length; + /** A fetch whose answer to `path` is `answer`, given the credential the request carried; everything else reaches the stand-in. */ + const answering = (path: string, answer: (authorization: string | null, init?: RequestInit) => Response | Promise) => (base: typeof fetch) => + ((input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + return url.pathname === path ? Promise.resolve(answer(new Headers(init?.headers).get("authorization"), init)) : base(input, init); + }) as typeof fetch; + /** Never answers; rejects only when its request is aborted, as fetch does. */ + const silent = (_: string | null, init?: RequestInit) => new Promise((_, reject) => { + init?.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), { once: true }); + }); + + test("the card names the verified poster and the target's kind, for an issue and for a pull request", async () => { + const h = harness(); + await h.call(COMMENT); + await h.call(PULL); + expect(h.cards.map(card => card.display), "GITHUB_DISPLAY_VERIFIED").toEqual([ + { github: { poster: { login: GITHUB_TOOLS_POSTER, is_bot: false }, target: { kind: "issue", html_url: "https://github.com/odysseus/ithaca/issues/7" } } }, + { github: { poster: { login: GITHUB_TOOLS_POSTER, is_bot: false }, target: { kind: "pull_request", html_url: "https://github.com/odysseus/ithaca/pull/8" } } }, + ]); + expect(lookups(h.fake, "/user"), "GITHUB_POSTER_CACHED_FOR_ITS_CREDENTIAL").toBe(1); + expect(h.fake.seen.filter(request => request.path === "/user").every(request => request.authorization === `Bearer ${GITHUB_TOOLS_SENTINEL}`), "looked up with the posting credential").toBe(true); + }); + + test("an issue card carries no display facts and looks nothing up", async () => { + const h = harness(); + await h.call(CREATE); + expect(h.cards[0]!.display, "GITHUB_CREATE_NO_DISPLAY").toBeUndefined(); + expect(h.fake.seen.filter(request => request.method === "GET"), "GITHUB_CREATE_NO_LOOKUP").toEqual([]); + }); + + test("display facts change nothing approved, recorded, sent or returned to the model", async () => { + const h = harness(); + const result = await h.call(PULL); + const card = h.cards[0]!; + expect(card.display?.github?.poster?.login, "positive control: the card has the facts").toBe(GITHUB_TOOLS_POSTER); + expect(Object.keys(card.input).sort(), "GITHUB_DISPLAY_NOT_IN_INPUT").toEqual(["body", "number", "repository"]); + expect(JSON.parse(h.recorded[0]!.payload.input), "GITHUB_DISPLAY_NOT_RECORDED").toEqual(card.input); + expect(writes(h.fake).map(request => JSON.parse(request.body!)), "GITHUB_DISPLAY_NOT_SENT").toEqual([{ body: "The stores are counted again." }]); + const returned = JSON.stringify(result); + expect(returned.includes(GITHUB_TOOLS_POSTER) || returned.includes("pull_request") || returned.includes("display"), `GITHUB_DISPLAY_NOT_RETURNED ${returned}`).toBe(false); + expect(parsed(result), "the result envelope is the contract's").toEqual(result); + }); + + test("an approval that echoes the card is compared with its input alone, so display facts never make it 'edited'", async () => { + const h = harness(request => ({ behavior: "allow", updatedInput: { ...request.input } })); + expect((await h.call(COMMENT)).ok, "GITHUB_DISPLAY_NOT_COMPARED").toBe(true); + const smuggled = harness(request => ({ behavior: "allow", updatedInput: { ...request.input, display: request.display } })); + expect(await smuggled.call(COMMENT), "GITHUB_DISPLAY_IN_ANSWER_IS_AN_EDIT").toMatchObject({ ok: false, error: { reason: "edited" } }); + expect(writes(smuggled.fake)).toEqual([]); + }); + + for (const [label, answer] of [ + ["a rejected credential", () => Response.json({ message: "Bad credentials" }, { status: 401 })], + ["a credential that may not read its user", () => Response.json({ message: "Resource not accessible by integration" }, { status: 403 })], + ["a spent rate limit", () => Response.json({ message: "rate limited" }, { status: 403, headers: { "x-ratelimit-remaining": "0" } })], + ["a server error", () => new Response("no", { status: 502 })], + ["malformed JSON", () => new Response("{", { status: 200 })], + ["no login", () => Response.json({ type: "User" })], + ["an invalid login", () => Response.json({ login: "not a login", type: "User" })], + ["no answer before the deadline", silent], + ] as const) { + test(`${label} leaves the poster unknown, and the comment is still approved and sent once`, async () => { + const h = harness(undefined, { wrap: answering("/user", answer), host: { displayTimeoutMs: 50 } }); + const result = await h.call(COMMENT); + expect(h.cards[0]!.display?.github, `GITHUB_POSTER_NEUTRAL ${label}`).toEqual({ poster: null, target: { kind: "issue", html_url: "https://github.com/odysseus/ithaca/issues/7" } }); + expect(result.ok, `GITHUB_UNKNOWN_POSTER_STILL_WRITES ${label}`).toBe(true); + expect(writes(h.fake)).toHaveLength(1); + }); + } + + for (const [label, answer] of [ + ["no such object", () => Response.json({ message: "Not Found" }, { status: 404 })], + ["a spent rate limit", () => Response.json({ message: "rate limited" }, { status: 429 })], + ["an object moved to another repository", () => Response.json({ number: 7, repository_url: "https://api.github.com/repos/circe/aiaia", html_url: "https://github.com/circe/aiaia/issues/7" })], + ["another number", () => Response.json({ number: 9, repository_url: "https://api.github.com/repos/odysseus/ithaca", html_url: "https://github.com/odysseus/ithaca/issues/9" })], + ["malformed JSON", () => new Response("[", { status: 200 })], + ["no answer before the deadline", silent], + ] as const) { + test(`${label} leaves the target's kind unknown, and the comment is still approved and sent once`, async () => { + const h = harness(undefined, { wrap: answering("/repos/odysseus/ithaca/issues/7", answer), host: { displayTimeoutMs: 50 } }); + const result = await h.call(COMMENT); + expect(h.cards[0]!.display?.github, `GITHUB_TARGET_NEUTRAL ${label}`).toEqual({ poster: { login: GITHUB_TOOLS_POSTER, is_bot: false }, target: null }); + expect(result.ok, `GITHUB_UNKNOWN_TARGET_STILL_WRITES ${label}`).toBe(true); + expect(writes(h.fake)).toHaveLength(1); + }); + } + + test("a lookup that never answers holds the card for the display deadline only", async () => { + const h = harness(undefined, { wrap: base => answering("/repos/odysseus/ithaca/issues/7", silent)(answering("/user", silent)(base)), host: { displayTimeoutMs: 50 } }); + const started = performance.now(); + await h.call(COMMENT); + expect(h.cards[0]!.display?.github, "GITHUB_SILENT_NEUTRAL").toEqual({ poster: null, target: null }); + // A hang watchdog, not a timing claim: the lookups end at their own deadline, far below one request's 20 s. + expect(performance.now() - started, "GITHUB_DISPLAY_BOUNDED").toBeLessThan(10_000); + }); + + test("a rotated credential is never shown another credential's poster, and a failure for it reads unknown", async () => { + let token = "odysseus-credential-one"; + const logins: Record = { + "Bearer odysseus-credential-one": Response.json({ login: "penelope", type: "User" }), + "Bearer odysseus-credential-two": Response.json({ login: "telemachus", type: "User" }), + }; + const seen: (string | null)[] = []; + const h = harness(undefined, { host: { token: () => token }, wrap: answering("/user", authorization => { + seen.push(authorization); + return logins[authorization ?? ""]?.clone() ?? Response.json({ message: "Bad credentials" }, { status: 401 }); + }) }); + await h.call(COMMENT); + token = "odysseus-credential-two"; + await h.call(COMMENT); + token = "odysseus-credential-three"; + await h.call(COMMENT); + token = "odysseus-credential-one"; + await h.call(COMMENT); + expect(h.cards.map(card => card.display?.github?.poster?.login ?? null), "GITHUB_POSTER_BOUND_TO_CREDENTIAL").toEqual(["penelope", "telemachus", null, "penelope"]); + expect(seen, "each credential is looked up with itself, and a replaced entry is looked up again").toEqual([ + "Bearer odysseus-credential-one", "Bearer odysseus-credential-two", "Bearer odysseus-credential-three", "Bearer odysseus-credential-one"]); + expect(writes(h.fake).map(request => request.authorization), "each comment is posted with the credential its card was resolved for").toEqual([ + "Bearer odysseus-credential-one", "Bearer odysseus-credential-two", "Bearer odysseus-credential-three", "Bearer odysseus-credential-one"]); + }); + + test("a failed lookup is not repeated until its retry time, and a verified poster is reused until its own", async () => { + let clock = Date.parse("2026-07-12T12:00:00Z"); + let fail = true; + const h = harness(undefined, { host: { now: () => clock }, wrap: answering("/user", () => fail + ? Response.json({ message: "rate limited" }, { status: 429 }) + : Response.json({ login: GITHUB_TOOLS_POSTER, type: "User" })) }); + let asked = 0; + const poster = async () => { await h.call(COMMENT); asked++; return h.cards.at(-1)!.display?.github?.poster?.login ?? null; }; + expect(await poster()).toBeNull(); + fail = false; + expect(await poster(), "GITHUB_FAILED_LOOKUP_NOT_REPEATED").toBeNull(); + clock += GITHUB_POSTER_RETRY_MS; + expect(await poster(), "GITHUB_FAILED_LOOKUP_RETRIED_AFTER_ITS_TIME").toBe(GITHUB_TOOLS_POSTER); + fail = true; + clock += GITHUB_POSTER_TTL_MS - 1; + expect(await poster(), "GITHUB_POSTER_REUSED_WITHIN_TTL").toBe(GITHUB_TOOLS_POSTER); + clock += 1; + expect(await poster(), "GITHUB_POSTER_EXPIRES").toBeNull(); + expect(asked).toBe(5); + }); + + test("a credential GitHub rejects on the write keeps no identity for the next card", async () => { + let reject = false; + const h = harness(undefined, { wrap: base => ((input: RequestInfo | URL, init?: RequestInit) => reject && init?.method === "POST" + ? Promise.resolve(Response.json({ message: "Bad credentials" }, { status: 401 })) : base(input, init)) as typeof fetch }); + await h.call(COMMENT); + reject = true; + expect(await h.call(COMMENT)).toMatchObject({ ok: false, error: { reason: "credential_rejected" } }); + reject = false; + await h.call(COMMENT); + expect(lookups(h.fake, "/user"), "GITHUB_REJECTED_CREDENTIAL_FORGOTTEN").toBe(2); + }); +}); diff --git a/packages/ui-server/tests/ws-allowlist-enforcement.test.ts b/packages/ui-server/tests/ws-allowlist-enforcement.test.ts index 06eb12d35b..d4df7dee91 100644 --- a/packages/ui-server/tests/ws-allowlist-enforcement.test.ts +++ b/packages/ui-server/tests/ws-allowlist-enforcement.test.ts @@ -257,7 +257,7 @@ describe("the approval frame says whether a grant can be kept", () => { closeDb(); }); - type Card = { toolUseId?: string; rememberable?: boolean; turnId?: string }; + type Card = { toolUseId?: string; rememberable?: boolean; turnId?: string; input?: unknown; display?: unknown }; const cardsIn = (sent: ServerMessage[]) => sent.filter((f) => f.type === "tool_approval_request") as Card[]; @@ -316,6 +316,27 @@ describe("the approval frame says whether a grant can be kept", () => { expect(cardsIn(reconnected.sent)).toHaveLength(1); for (const card of [...cardsIn(client.sent), ...cardsIn(reconnected.sent)]) { expect("rememberable" in card).toBe(false); + expect("display" in card, "no display facts unless the host verified some").toBe(false); + } + controls[0]!.finish(); + }); + + test("a card's display facts (#4154) ride its frame, first time and re-delivered, beside an unchanged input", async () => { + const { backend, controls } = permissionBackend(); + setBackendForTests(backend); + setToolPermissionsForTests(memoryGrants().tp); + const { host, client } = await startTurn(controls); + const display = { github: { poster: { login: "ithaca-brain", is_bot: false }, target: { kind: "issue" as const, html_url: "https://github.com/odysseus/ithaca/issues/7" } } }; + const input = { repository: "odysseus/ithaca", number: 7, body: "Counted." }; + void controls[0]!.request({ toolName: "mcp_proxy_tool", input, kind: "command", display }, "t23"); + await waitFor(() => host.coordinator.pendingApprovals.size === 1); + const reconnected = fakeClient(); + await createWsHandlers(host, testPrincipal()).onOpen(openEvt, reconnected.ws); + const cards = [...cardsIn(client.sent), ...cardsIn(reconnected.sent)]; + expect(cards, "APPROVAL_DISPLAY_FIRST_AND_REDELIVERED").toHaveLength(2); + for (const card of cards) { + expect(card.display, "APPROVAL_DISPLAY_ON_FRAME").toEqual(display); + expect(card.input, "APPROVAL_DISPLAY_NOT_IN_INPUT").toEqual(input); } controls[0]!.finish(); }); diff --git a/packages/ui-server/tests/ws-github.test.ts b/packages/ui-server/tests/ws-github.test.ts index d9f514d415..48a8450408 100644 --- a/packages/ui-server/tests/ws-github.test.ts +++ b/packages/ui-server/tests/ws-github.test.ts @@ -32,7 +32,7 @@ import type { WSContext } from "../src/ws/clients.js"; import { makeFakeBackend } from "./helpers/fake-backend.js"; import { createPrincipal } from "../src/db/principals.js"; import { GOVERNANCE_EVENT_SCHEMAS, queryGovernanceEvents } from "../src/governance/events.js"; -import { GENERIC_GITHUB_SENTINEL, GITHUB_TOOLS_SENTINEL, fakeGithub, routeGithubApi } from "./fixtures/github-host-fixture.js"; +import { GENERIC_GITHUB_SENTINEL, GITHUB_TOOLS_POSTER, GITHUB_TOOLS_SENTINEL, fakeGithub, routeGithubApi } from "./fixtures/github-host-fixture.js"; const SESSION = "sess-ithaca-github"; @@ -157,6 +157,27 @@ for (const backendId of ["pi", "claude"] as const) test(`a ${backendId} turn fil } finally { await rm(outcome.root, { recursive: true, force: true }); } }, 60_000); +for (const backendId of ["pi", "claude"] as const) test(`a ${backendId} comment card carries the host's verified poster and target kind, and nothing the model receives does (#4154)`, async () => { + const results: GithubToolResult[] = []; + const comment = { repository: "odysseus/ithaca", number: 8, body: "The bow is strung." }; + const outcome = await hostedTurn(backendId, { BRAIN_UI_GITHUB_TOOLS_TOKEN: GITHUB_TOOLS_SENTINEL }, async github => { + results.push(await github("brain_github_issue_comment", comment)); + }, { policy: POLICY, answer: () => ({ type: "tool_approval" }) }); + try { + expect(results[0], "GITHUB_APP_COMMENT_POSTED").toMatchObject({ ok: true, result: { kind: "comment_created", number: 8 } }); + expect(outcome.cards.map(card => [card.input, card.display]), "GITHUB_APP_COMMENT_DISPLAY").toEqual([[comment, + { github: { poster: { login: GITHUB_TOOLS_POSTER, is_bot: false }, target: { kind: "pull_request", html_url: "https://github.com/odysseus/ithaca/pull/8" } } }]]); + expect(JSON.stringify(results), "GITHUB_APP_DISPLAY_NOT_RETURNED").not.toContain(GITHUB_TOOLS_POSTER); + const elsewhere = outcome.sent.filter(text => (JSON.parse(text) as { type: string }).type !== "tool_approval_request"); + expect(elsewhere.filter(text => text.includes(GITHUB_TOOLS_POSTER)), "GITHUB_APP_DISPLAY_ONLY_ON_THE_CARD").toEqual([]); + expect(outcome.outward.map(event => JSON.parse(String(event.payload.input))), "GITHUB_APP_DISPLAY_NOT_RECORDED").toEqual([comment]); + // The two lookups run together, so their order is not a fact; the one write follows both. + const requests = outcome.fake.seen.map(request => `${request.method} ${request.path}`); + expect([...requests.slice(0, 2)].sort(), "GITHUB_APP_DISPLAY_LOOKUPS").toEqual(["GET /repos/odysseus/ithaca/issues/8", "GET /user"]); + expect(requests.slice(2), "GITHUB_APP_THEN_ONE_WRITE").toEqual(["POST /repos/odysseus/ithaca/issues/8/comments"]); + } finally { await rm(outcome.root, { recursive: true, force: true }); } +}, 60_000); + test("without a governance policy entry a write is refused before any card and sends nothing", async () => { const results: GithubToolResult[] = []; const outcome = await hostedTurn("claude", { BRAIN_UI_GITHUB_TOOLS_TOKEN: GITHUB_TOOLS_SENTINEL }, async github => {