From 1fed5b2d634f31578caafb6f2a7c9488dab3c26a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 22:49:57 +0000 Subject: [PATCH] CONTRACT: feat(ui-sdk,ui-server,ui-react): serve on-demand GitHub detail pages and avatars outside the model's context Two internal ui-server routes give the chat's GitHub components what a host GitHub tool result left out (#3796): - `GET /api/sessions/:id/github/:owner/:repo/:number/:part?cursor=` pages an object's `comments`, `reviews`, `review-comments`, `commits`, `files` or `checks`, at most 30 items a page, with an opaque cursor, under the tools' dedicated `BRAIN_UI_GITHUB_TOOLS_TOKEN` and the fixed API origin. - `GET /api/sessions/:id/github/avatars/:login?size=` serves a login's avatar from the brain's own origin, fetched from GitHub's avatar host without any credential, accepted only as PNG, JPEG, GIF or WebP by its bytes within a 512 KiB and 1024-pixel cap, with `nosniff`, and kept in a bounded in-memory LRU cache that evicts and never grows. Every failure is an empty 404. Authority is bounded: the caller must be the chat's owner account (any of its logins, by the safety route's same-account rule), and only an object or login that a successful `brain_github_*` result in the session's recorded history returned is served. Anything else is 403 or 404 and sends nothing upstream. Page items reuse the tools' contract types; each `html_url` passes `githubDirectUrl` for its kind and identity or is `null`. Failures are typed (`unavailable`, `rate_limited` with `reset_at`, `not_found`, `forbidden`, `upstream_error`). Nothing either route serves is added to the conversation, journaled as turn input or recorded as taint. The SDK adds the detail part list, page size, review-comment, changed-file and check-run item schemas, the page schema and the detail error schema. The host's GitHub GET and payload shaping are shared with the new module, and a spent rate limit now carries its reset time internally. ui-react adds the internal `fetchGithubDetailPage` and `githubAvatarUrl` helpers. The HTTP inventory, the integration-contract index and package-API component, the API report and a changeset are updated. Refs #3796 Co-Authored-By: Claude Opus 5.5 --- .changeset/3796-github-detail-pages.md | 7 + api-report/ui-sdk.txt | 366 ++++++++++++++++ docs/http-api.md | 78 +++- docs/integration-contract.md | 14 + docs/integration-contract/package-api.md | 19 + packages/ui-react/src/lib/github-details.ts | 65 +++ .../ui-react/tests/github-details.test.ts | 41 ++ packages/ui-sdk/src/tool-contracts/github.ts | 101 +++++ packages/ui-server/src/app.ts | 15 + packages/ui-server/src/github/details.ts | 389 ++++++++++++++++++ packages/ui-server/src/github/host.ts | 120 +++--- .../ui-server/src/routes/github-details.ts | 102 +++++ .../tests/fixtures/github-host-fixture.ts | 4 +- .../ui-server/tests/github-details.test.ts | 388 +++++++++++++++++ .../ui-server/tests/ws-github-details.test.ts | 130 ++++++ 15 files changed, 1784 insertions(+), 55 deletions(-) create mode 100644 .changeset/3796-github-detail-pages.md create mode 100644 packages/ui-react/src/lib/github-details.ts create mode 100644 packages/ui-react/tests/github-details.test.ts create mode 100644 packages/ui-server/src/github/details.ts create mode 100644 packages/ui-server/src/routes/github-details.ts create mode 100644 packages/ui-server/tests/github-details.test.ts create mode 100644 packages/ui-server/tests/ws-github-details.test.ts diff --git a/.changeset/3796-github-detail-pages.md b/.changeset/3796-github-detail-pages.md new file mode 100644 index 0000000000..f4d6607891 --- /dev/null +++ b/.changeset/3796-github-detail-pages.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-react": patch +--- + +The chat's GitHub components can load what a GitHub tool result left out without putting it in the model's context (#3796). Two internal routes serve it to the chat's owner account only, for an issue or pull request a GitHub tool result in that session returned: `GET /api/sessions/:id/github/:owner/:repo/:number/:part` pages its `comments`, `reviews`, `review-comments`, `commits`, `files` or `checks`, at most 30 items a page with a cursor, under the dedicated `BRAIN_UI_GITHUB_TOOLS_TOKEN`; and `GET /api/sessions/:id/github/avatars/:login` serves the avatar of a user in those results from the brain's own origin, fetched without credentials, accepted only as PNG, JPEG, GIF or WebP by its bytes within a byte and pixel cap, and kept in a bounded in-memory cache. Every direct link passes `githubDirectUrl` or is `null`. Failures are typed, and a spent rate limit names its reset time. Nothing either route serves is added to the conversation, journaled as turn input or recorded as taint. The SDK adds the page, item and error schemas; ui-react adds the internal `fetchGithubDetailPage` and `githubAvatarUrl` helpers. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 65f18c1420..fc97cfee95 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -805,9 +805,18 @@ export "./client" (./src/client/index.ts) GITHUB_API_ORIGIN GITHUB_AUTHOR_ASSOCIATIONS GITHUB_AUTHOR_SCHEMA + GITHUB_CHANGED_FILE_SCHEMA + GITHUB_CHANGED_FILE_STATUSES GITHUB_CHECKS_SCHEMA + GITHUB_CHECK_CONCLUSIONS + GITHUB_CHECK_RUN_SCHEMA GITHUB_COMMENT_SCHEMA GITHUB_COMMIT_SCHEMA + GITHUB_DETAIL_ERROR_RESPONSE_SCHEMA + GITHUB_DETAIL_ERROR_SCHEMA + GITHUB_DETAIL_PAGE_SCHEMA + GITHUB_DETAIL_PAGE_SIZE + GITHUB_DETAIL_PARTS GITHUB_ERROR_CODES GITHUB_ERROR_SCHEMA GITHUB_ISSUE_COMMENT_CONTRACT @@ -831,6 +840,7 @@ export "./client" (./src/client/index.ts) GITHUB_READ_TOOL_NAMES GITHUB_REPO_PATTERN GITHUB_RESULT_SCHEMAS + GITHUB_REVIEW_COMMENT_SCHEMA GITHUB_REVIEW_DECISION_SCHEMA GITHUB_REVIEW_SCHEMA GITHUB_REVIEW_STATES @@ -845,9 +855,14 @@ export "./client" (./src/client/index.ts) type GetCurrentLocationInput type GetSearchContentInput type GithubAuthor + type GithubChangedFile + type GithubCheckRun type GithubChecks type GithubComment type GithubCommit + type GithubDetailError + type GithubDetailPage + type GithubDetailPart type GithubError type GithubErrorCode type GithubIssue @@ -865,6 +880,7 @@ export "./client" (./src/client/index.ts) type GithubPullRequest type GithubReadToolName type GithubReview + type GithubReviewComment type GithubReviewDecision type GithubSearchItem type GithubToolCall @@ -1296,6 +1312,7 @@ export "./client" (./src/client/index.ts) githubSearchUrl isBillingMode isFailureOutcome + isGithubDetailPart isGithubRepositoryName isGithubSearchUrl isGithubToolName @@ -2660,9 +2677,18 @@ export "./server" (./src/server/index.ts) GITHUB_API_ORIGIN GITHUB_AUTHOR_ASSOCIATIONS GITHUB_AUTHOR_SCHEMA + GITHUB_CHANGED_FILE_SCHEMA + GITHUB_CHANGED_FILE_STATUSES GITHUB_CHECKS_SCHEMA + GITHUB_CHECK_CONCLUSIONS + GITHUB_CHECK_RUN_SCHEMA GITHUB_COMMENT_SCHEMA GITHUB_COMMIT_SCHEMA + GITHUB_DETAIL_ERROR_RESPONSE_SCHEMA + GITHUB_DETAIL_ERROR_SCHEMA + GITHUB_DETAIL_PAGE_SCHEMA + GITHUB_DETAIL_PAGE_SIZE + GITHUB_DETAIL_PARTS GITHUB_ERROR_CODES GITHUB_ERROR_SCHEMA GITHUB_ISSUE_COMMENT_CONTRACT @@ -2686,6 +2712,7 @@ export "./server" (./src/server/index.ts) GITHUB_READ_TOOL_NAMES GITHUB_REPO_PATTERN GITHUB_RESULT_SCHEMAS + GITHUB_REVIEW_COMMENT_SCHEMA GITHUB_REVIEW_DECISION_SCHEMA GITHUB_REVIEW_SCHEMA GITHUB_REVIEW_STATES @@ -2702,9 +2729,14 @@ export "./server" (./src/server/index.ts) type GetCurrentLocationInput type GetSearchContentInput type GithubAuthor + type GithubChangedFile + type GithubCheckRun type GithubChecks type GithubComment type GithubCommit + type GithubDetailError + type GithubDetailPage + type GithubDetailPart type GithubError type GithubErrorCode type GithubIssue @@ -2722,6 +2754,7 @@ export "./server" (./src/server/index.ts) type GithubPullRequest type GithubReadToolName type GithubReview + type GithubReviewComment type GithubReviewDecision type GithubSearchItem type GithubToolCall @@ -3234,6 +3267,7 @@ export "./server" (./src/server/index.ts) isBillingMode isCompletedAutonomousToolCall isFailureOutcome + isGithubDetailPart isGithubRepositoryName isGithubSearchUrl isGithubToolName @@ -3423,9 +3457,18 @@ export "./tool-contracts" (./src/tool-contracts/index.ts) GITHUB_API_ORIGIN GITHUB_AUTHOR_ASSOCIATIONS GITHUB_AUTHOR_SCHEMA + GITHUB_CHANGED_FILE_SCHEMA + GITHUB_CHANGED_FILE_STATUSES GITHUB_CHECKS_SCHEMA + GITHUB_CHECK_CONCLUSIONS + GITHUB_CHECK_RUN_SCHEMA GITHUB_COMMENT_SCHEMA GITHUB_COMMIT_SCHEMA + GITHUB_DETAIL_ERROR_RESPONSE_SCHEMA + GITHUB_DETAIL_ERROR_SCHEMA + GITHUB_DETAIL_PAGE_SCHEMA + GITHUB_DETAIL_PAGE_SIZE + GITHUB_DETAIL_PARTS GITHUB_ERROR_CODES GITHUB_ERROR_SCHEMA GITHUB_ISSUE_COMMENT_CONTRACT @@ -3449,6 +3492,7 @@ export "./tool-contracts" (./src/tool-contracts/index.ts) GITHUB_READ_TOOL_NAMES GITHUB_REPO_PATTERN GITHUB_RESULT_SCHEMAS + GITHUB_REVIEW_COMMENT_SCHEMA GITHUB_REVIEW_DECISION_SCHEMA GITHUB_REVIEW_SCHEMA GITHUB_REVIEW_STATES @@ -3461,9 +3505,14 @@ export "./tool-contracts" (./src/tool-contracts/index.ts) type GetCurrentLocationInput type GetSearchContentInput type GithubAuthor + type GithubChangedFile + type GithubCheckRun type GithubChecks type GithubComment type GithubCommit + type GithubDetailError + type GithubDetailPage + type GithubDetailPart type GithubError type GithubErrorCode type GithubIssue @@ -3481,6 +3530,7 @@ export "./tool-contracts" (./src/tool-contracts/index.ts) type GithubPullRequest type GithubReadToolName type GithubReview + type GithubReviewComment type GithubReviewDecision type GithubSearchItem type GithubToolCall @@ -3588,6 +3638,7 @@ export "./tool-contracts" (./src/tool-contracts/index.ts) githubBoundedList githubDirectUrl githubSearchUrl + isGithubDetailPart isGithubRepositoryName isGithubSearchUrl isGithubToolName @@ -8113,6 +8164,25 @@ signatures (every public export and the types it is made of) is_bot: z.ZodBoolean; login: z.ZodNullable; }, z.core.$strict>; + GITHUB_CHANGED_FILE_SCHEMA (packages/ui-sdk/src/tool-contracts/github.ts) + const GITHUB_CHANGED_FILE_SCHEMA: z.ZodObject<{ + additions: z.ZodNumber; + changes: z.ZodNumber; + deletions: z.ZodNumber; + filename: z.ZodString; + previous_filename: z.ZodNullable; + status: z.ZodEnum<{ + added: "added"; + changed: "changed"; + copied: "copied"; + modified: "modified"; + removed: "removed"; + renamed: "renamed"; + unchanged: "unchanged"; + }>; + }, z.core.$strict>; + GITHUB_CHANGED_FILE_STATUSES (packages/ui-sdk/src/tool-contracts/github.ts) + const GITHUB_CHANGED_FILE_STATUSES: readonly ["added", "removed", "modified", "renamed", "copied", "changed", "unchanged"]; GITHUB_CHECKS_SCHEMA (packages/ui-sdk/src/tool-contracts/github.ts) const GITHUB_CHECKS_SCHEMA: z.ZodNullable>; + GITHUB_CHECK_CONCLUSIONS (packages/ui-sdk/src/tool-contracts/github.ts) + const GITHUB_CHECK_CONCLUSIONS: readonly ["success", "failure", "neutral", "cancelled", "skipped", "timed_out", "action_required", "stale", "startup_failure", "error", "pending"]; + GITHUB_CHECK_RUN_SCHEMA (packages/ui-sdk/src/tool-contracts/github.ts) + const GITHUB_CHECK_RUN_SCHEMA: z.ZodObject<{ + completed_at: z.ZodNullable; + conclusion: z.ZodNullable>; + name: z.ZodString; + source: z.ZodEnum<{ + check_run: "check_run"; + status: "status"; + }>; + started_at: z.ZodNullable; + state: z.ZodEnum<{ + failed: "failed"; + passed: "passed"; + running: "running"; + skipped: "skipped"; + }>; + }, z.core.$strict>; GITHUB_COMMENT_SCHEMA (packages/ui-sdk/src/tool-contracts/github.ts) const GITHUB_COMMENT_SCHEMA: z.ZodObject<{ author: z.ZodObject<{ @@ -8157,6 +8258,229 @@ signatures (every public export and the types it is made of) message_truncated: z.ZodBoolean; sha: z.ZodString; }, z.core.$strict>; + GITHUB_DETAIL_ERROR_RESPONSE_SCHEMA (packages/ui-sdk/src/tool-contracts/github.ts) + const GITHUB_DETAIL_ERROR_RESPONSE_SCHEMA: z.ZodObject<{ + error: z.ZodObject<{ + code: z.ZodEnum<{ + approval_declined: "approval_declined"; + forbidden: "forbidden"; + invalid_input: "invalid_input"; + not_found: "not_found"; + policy_denied: "policy_denied"; + rate_limited: "rate_limited"; + unavailable: "unavailable"; + upstream_error: "upstream_error"; + }>; + message: z.ZodString; + reason: z.ZodNullable; + reset_at: z.ZodNullable; + }, z.core.$strict>; + }, z.core.$strict>; + GITHUB_DETAIL_ERROR_SCHEMA (packages/ui-sdk/src/tool-contracts/github.ts) + const GITHUB_DETAIL_ERROR_SCHEMA: z.ZodObject<{ + code: z.ZodEnum<{ + approval_declined: "approval_declined"; + forbidden: "forbidden"; + invalid_input: "invalid_input"; + not_found: "not_found"; + policy_denied: "policy_denied"; + rate_limited: "rate_limited"; + unavailable: "unavailable"; + upstream_error: "upstream_error"; + }>; + message: z.ZodString; + reason: z.ZodNullable; + reset_at: z.ZodNullable; + }, z.core.$strict>; + GITHUB_DETAIL_PAGE_SCHEMA (packages/ui-sdk/src/tool-contracts/github.ts) + const GITHUB_DETAIL_PAGE_SCHEMA: z.ZodDiscriminatedUnion<[z.ZodObject<{ + fetched_at: z.ZodISODateTime; + items: z.ZodArray>; + is_bot: z.ZodBoolean; + login: z.ZodNullable; + }, z.core.$strict>; + body: z.ZodNullable; + body_length: z.ZodNumber; + body_truncated: z.ZodBoolean; + created_at: z.ZodISODateTime; + html_url: z.ZodNullable; + id: z.ZodNumber; + updated_at: z.ZodISODateTime; + }, z.core.$strict>>; + kind: z.ZodLiteral<"detail_page">; + next_cursor: z.ZodNullable; + number: z.ZodNumber; + part: z.ZodLiteral<"comments">; + repository: z.ZodString; + total_count: z.ZodNullable; + }, z.core.$strict>, z.ZodObject<{ + fetched_at: z.ZodISODateTime; + items: z.ZodArray>; + is_bot: z.ZodBoolean; + login: z.ZodNullable; + }, z.core.$strict>; + body: z.ZodNullable; + body_length: z.ZodNumber; + body_truncated: z.ZodBoolean; + html_url: z.ZodNullable; + id: z.ZodNumber; + state: z.ZodEnum<{ + approved: "approved"; + changes_requested: "changes_requested"; + commented: "commented"; + dismissed: "dismissed"; + pending: "pending"; + }>; + submitted_at: z.ZodNullable; + }, z.core.$strict>>; + kind: z.ZodLiteral<"detail_page">; + next_cursor: z.ZodNullable; + number: z.ZodNumber; + part: z.ZodLiteral<"reviews">; + repository: z.ZodString; + total_count: z.ZodNullable; + }, z.core.$strict>, z.ZodObject<{ + fetched_at: z.ZodISODateTime; + items: z.ZodArray>; + is_bot: z.ZodBoolean; + login: z.ZodNullable; + }, z.core.$strict>; + body: z.ZodNullable; + body_length: z.ZodNumber; + body_truncated: z.ZodBoolean; + created_at: z.ZodISODateTime; + html_url: z.ZodNullable; + id: z.ZodNumber; + in_reply_to_id: z.ZodNullable; + line: z.ZodNullable; + path: z.ZodString; + review_id: z.ZodNullable; + updated_at: z.ZodISODateTime; + }, z.core.$strict>>; + kind: z.ZodLiteral<"detail_page">; + next_cursor: z.ZodNullable; + number: z.ZodNumber; + part: z.ZodLiteral<"review-comments">; + repository: z.ZodString; + total_count: z.ZodNullable; + }, z.core.$strict>, z.ZodObject<{ + fetched_at: z.ZodISODateTime; + items: z.ZodArray; + }, z.core.$strict>>; + author_name: z.ZodNullable; + authored_at: z.ZodNullable; + html_url: z.ZodNullable; + message: z.ZodString; + message_truncated: z.ZodBoolean; + sha: z.ZodString; + }, z.core.$strict>>; + kind: z.ZodLiteral<"detail_page">; + next_cursor: z.ZodNullable; + number: z.ZodNumber; + part: z.ZodLiteral<"commits">; + repository: z.ZodString; + total_count: z.ZodNullable; + }, z.core.$strict>, z.ZodObject<{ + fetched_at: z.ZodISODateTime; + items: z.ZodArray; + status: z.ZodEnum<{ + added: "added"; + changed: "changed"; + copied: "copied"; + modified: "modified"; + removed: "removed"; + renamed: "renamed"; + unchanged: "unchanged"; + }>; + }, z.core.$strict>>; + kind: z.ZodLiteral<"detail_page">; + next_cursor: z.ZodNullable; + number: z.ZodNumber; + part: z.ZodLiteral<"files">; + repository: z.ZodString; + total_count: z.ZodNullable; + }, z.core.$strict>, z.ZodObject<{ + fetched_at: z.ZodISODateTime; + items: z.ZodArray; + conclusion: z.ZodNullable>; + name: z.ZodString; + source: z.ZodEnum<{ + check_run: "check_run"; + status: "status"; + }>; + started_at: z.ZodNullable; + state: z.ZodEnum<{ + failed: "failed"; + passed: "passed"; + running: "running"; + skipped: "skipped"; + }>; + }, z.core.$strict>>; + kind: z.ZodLiteral<"detail_page">; + next_cursor: z.ZodNullable; + number: z.ZodNumber; + part: z.ZodLiteral<"checks">; + repository: z.ZodString; + total_count: z.ZodNullable; + }, z.core.$strict>], "part">; + GITHUB_DETAIL_PAGE_SIZE (packages/ui-sdk/src/tool-contracts/github.ts) + const GITHUB_DETAIL_PAGE_SIZE: 30; + GITHUB_DETAIL_PARTS (packages/ui-sdk/src/tool-contracts/github.ts) + const GITHUB_DETAIL_PARTS: readonly ["comments", "reviews", "review-comments", "commits", "files", "checks"]; GITHUB_ERROR_CODES (packages/ui-sdk/src/tool-contracts/github.ts) const GITHUB_ERROR_CODES: readonly ["invalid_input", "unavailable", "not_found", "forbidden", "rate_limited", "upstream_error", "policy_denied", "approval_declined"]; GITHUB_ERROR_SCHEMA (packages/ui-sdk/src/tool-contracts/github.ts) @@ -9261,6 +9585,34 @@ signatures (every public export and the types it is made of) }>; }, z.core.$strict>]>; }; + GITHUB_REVIEW_COMMENT_SCHEMA (packages/ui-sdk/src/tool-contracts/github.ts) + const GITHUB_REVIEW_COMMENT_SCHEMA: z.ZodObject<{ + author: z.ZodObject<{ + author_association: z.ZodNullable>; + is_bot: z.ZodBoolean; + login: z.ZodNullable; + }, z.core.$strict>; + body: z.ZodNullable; + body_length: z.ZodNumber; + body_truncated: z.ZodBoolean; + created_at: z.ZodISODateTime; + html_url: z.ZodNullable; + id: z.ZodNumber; + in_reply_to_id: z.ZodNullable; + line: z.ZodNullable; + path: z.ZodString; + review_id: z.ZodNullable; + updated_at: z.ZodISODateTime; + }, z.core.$strict>; GITHUB_REVIEW_DECISION_SCHEMA (packages/ui-sdk/src/tool-contracts/github.ts) const GITHUB_REVIEW_DECISION_SCHEMA: z.ZodObject<{ reviewer: z.ZodObject<{ @@ -9425,12 +9777,22 @@ signatures (every public export and the types it is made of) export type GetSearchContentInput = z.infer; GithubAuthor (packages/ui-sdk/src/tool-contracts/github.ts) export type GithubAuthor = z.infer; + GithubChangedFile (packages/ui-sdk/src/tool-contracts/github.ts) + export type GithubChangedFile = z.infer; + GithubCheckRun (packages/ui-sdk/src/tool-contracts/github.ts) + export type GithubCheckRun = z.infer; GithubChecks (packages/ui-sdk/src/tool-contracts/github.ts) export type GithubChecks = z.infer; GithubComment (packages/ui-sdk/src/tool-contracts/github.ts) export type GithubComment = z.infer; GithubCommit (packages/ui-sdk/src/tool-contracts/github.ts) export type GithubCommit = z.infer; + GithubDetailError (packages/ui-sdk/src/tool-contracts/github.ts) + export type GithubDetailError = z.infer; + GithubDetailPage (packages/ui-sdk/src/tool-contracts/github.ts) + export type GithubDetailPage = z.infer; + GithubDetailPart (packages/ui-sdk/src/tool-contracts/github.ts) + export type GithubDetailPart = (typeof GITHUB_DETAIL_PARTS)[number]; GithubError (packages/ui-sdk/src/tool-contracts/github.ts) export type GithubError = z.infer; GithubErrorCode (packages/ui-sdk/src/tool-contracts/github.ts) @@ -9477,6 +9839,8 @@ signatures (every public export and the types it is made of) export type GithubReadToolName = typeof GITHUB_TOOL_NAMES.read | typeof GITHUB_TOOL_NAMES.search; GithubReview (packages/ui-sdk/src/tool-contracts/github.ts) export type GithubReview = z.infer; + GithubReviewComment (packages/ui-sdk/src/tool-contracts/github.ts) + export type GithubReviewComment = z.infer; GithubReviewDecision (packages/ui-sdk/src/tool-contracts/github.ts) export type GithubReviewDecision = z.infer; GithubSearchItem (packages/ui-sdk/src/tool-contracts/github.ts) @@ -19866,6 +20230,8 @@ signatures (every public export and the types it is made of) export function isCompletedAutonomousToolCall(mode: AutonomousTurnOptions | undefined, toolName: string, input: unknown): boolean; isFailureOutcome (packages/ui-sdk/src/protocol.ts) export function isFailureOutcome(outcome: ActivitySpanOutcome | string | null | undefined): boolean; + isGithubDetailPart (packages/ui-sdk/src/tool-contracts/github.ts) + const isGithubDetailPart: (value: string) => value is GithubDetailPart; isGithubRepositoryName (packages/ui-sdk/src/tool-contracts/github.ts) export function isGithubRepositoryName(owner: string, repo: string): boolean; isGithubSearchUrl (packages/ui-sdk/src/tool-contracts/github.ts) diff --git a/docs/http-api.md b/docs/http-api.md index e99ec0ce6b..2dada13dd5 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -10,7 +10,7 @@ compatibility guarantee. Authentication requirements are a separate property. A public liveness probe can be supported; an authenticated settings route can be internal. -The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion, individual safety-review, safety-recording recovery and live-persona routes (whose `/api/settings/voice` also carries the live-service default) mounted by `createApp`: 187 unique declared +The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion, individual safety-review, safety-recording recovery, GitHub detail-page and live-persona routes (whose `/api/settings/voice` also carries the live-service default) mounted by `createApp`: 189 unique declared method/path pairs, plus the conditional SPA fallback. It describes the current implementation, including limitations, rather than a proposed redesign. Unknown response fields must be tolerated. There is no HTTP API revision @@ -159,6 +159,8 @@ client code has a gap. Source owners are listed after the table. | GET | `/api/sessions/:id/safety` | S | Read bounded revisioned host safety evidence | Authenticated principal of the history owner's account (#3952); immutable records, snapshot aggregate/high-water, scoped cursor, explicit coverage/unavailable, no mutation (#3604). | | POST | `/api/sessions/:id/safety/reviews/prepare` | S | Prepare review of one finalized safety occurrence | Live password-mode human owner, exact Origin and bounded JSON; host-issued body/brain/principal/generation-bound handle (#3603). | | POST | `/api/sessions/:id/safety/reviews/:requestId/commit` | S | Commit or read back one individual safe verdict | Live owner rechecked on the acquired FULL transaction and final response; immutable receipt plus fresh aggregate, no bulk clear or standing rule (#3603). | +| GET | `/api/sessions/:id/github/:owner/:repo/:number/:part` | I | Page one part of a GitHub object a session's GitHub tool result returned | Chat GitHub components (#3796, #3795); owner account only, display data never provider context, no compatibility guarantee. | +| GET | `/api/sessions/:id/github/avatars/:login` | I | Serve the avatar of a login in a session's GitHub results from this origin | Chat GitHub components (#3796, #3795); owner account only, magic-byte image check, bounded in-memory cache, every failure 404. | | GET | `/api/sessions/:id/attachment-reads` | S | Read a session's recorded attachment reads, outcome and scope only | Sent-row read states (#3589, #3155); preserve the session and message-reference filters, no text and no provider path. | | GET | `/api/sessions/:id/recovery` | S | Read a session's latest accepted work and pending interactions | Trackers and independent session clients (#964, D52); preserve the revision ordering, Activity terminal proof, honest unknown and the no-execution boundary. | | POST | `/api/queue` | S | Queue authenticated CLI intake without filing content | CLI and independent intake clients; preserve explicit key, provenance and queue receipt. | @@ -220,7 +222,7 @@ Authentication factories live in [auth.ts](../packages/ui-server/src/middleware/ [passkeys.ts](../packages/ui-server/src/middleware/passkeys.ts) and [principals.ts](../packages/ui-server/src/middleware/principals.ts). [app.ts](../packages/ui-server/src/app.ts) owns prefixing and middleware order. -All 187 declared endpoints are mounted regardless of backend, renderer or +All 189 declared endpoints are mounted regardless of backend, renderer or speech-provider availability: unavailable capabilities return the responses below rather than removing their handlers. Only static serving is conditional. @@ -1381,6 +1383,78 @@ asserts the isolation and both accepted behaviours. In a split topology, where the client is served from another origin, `frame-ancestors 'self'` refuses the preview frame; the new-tab link is not subject to framing rules. + + +## GitHub detail pages and avatars (internal, 0.45.0, #3796) + +Two internal routes let the chat's GitHub components load what a +[host GitHub tool](integration-contract/mcp.md#host-github-tools-additive-0450-3797) +result left out, without putting it in the model's context. Their raw paths +and payloads carry no compatibility guarantee; their authority and disclosure +rules are security properties pinned by +`packages/ui-server/tests/github-details.test.ts` and +`packages/ui-server/tests/ws-github-details.test.ts`. The paired client is +`fetchGithubDetailPage` and `githubAvatarUrl` in `ui-react` +(`packages/ui-react/src/lib/github-details.ts`). + +**Authority.** The caller must be the chat's owner account: any login of the +principal the chat's ownership records name, by the safety route's +same-account rule (#3952). A delegated agent, another account or a chat whose +ownership is unknown gets 403 (`forbidden`, `not_owner`). The route then reads +the session's recorded history from its owning backend and serves only an +object (`owner/repo#number`, compared without case) that a successful +`brain_github_*` result in it returned: an issue or pull request read, a search +item, or a write's created object. Anything else, a retired chat included, is +404 (`not_found`, `not_in_session`) and sends nothing to GitHub. It is not a +GitHub proxy: each part maps to one fixed path under `https://api.github.com`, +called with `BRAIN_UI_GITHUB_TOOLS_TOKEN` and never `GITHUB_TOKEN`. + +**Display data only.** A response is never added to the session's provider +conversation, not journaled as turn input, and records no taint or other +governance event. Reading details changes nothing the next turn sends. + +### `GET /api/sessions/:id/github/:owner/:repo/:number/:part?cursor=` + +`part` is one of `comments`, `reviews`, `review-comments`, `commits`, `files` +or `checks`; anything else is 400 (`invalid_input`, `part`). Every part but +`comments` belongs to a pull request; asked of an issue it is 404 +(`not_found`, `not_pull_request`). `cursor` is the previous page's +`next_cursor`, opaque; a cursor this host did not issue is 400 +(`invalid_input`, `cursor`). `200` returns `GITHUB_DETAIL_PAGE_SCHEMA` +`{ kind: "detail_page", repository, number, part, items, total_count, +next_cursor, fetched_at }` with `Cache-Control: no-store`. A page holds at +most `GITHUB_DETAIL_PAGE_SIZE` (30) items, oldest first, in the tools' +contract types: `GithubComment`, `GithubReview`, `GithubReviewComment`, +`GithubCommit`, `GithubChangedFile` (a summary, never a diff or content) and +`GithubCheckRun` (check runs, then the head commit's statuses). Untrusted text +is marked as in the tools' payloads. Every `html_url` is taken from GitHub and +passes `githubDirectUrl` for its kind, the session's object and the item's own +id or sha, or is `null`; the route never builds one. + +Failures are `{ error: { code, reason, message, reset_at } }` +(`GITHUB_DETAIL_ERROR_RESPONSE_SCHEMA`), with the tools' codes: 503 +`unavailable` (`no_credential` or `credential_rejected`), 429 `rate_limited` +with `reset_at` and `Retry-After` when GitHub names the reset, 404 or 403 +`not_found` / `forbidden` with reason `github` when GitHub no longer shows the +object to the credential, and 502 `upstream_error`. A revoked or expired +login gets the guard's 401. + +### `GET /api/sessions/:id/github/avatars/:login?size=` + +Serves the avatar of a login that appears in the session's GitHub results, or +in a detail page served for that session, so the browser never contacts +GitHub. The host fetches `https://avatars.githubusercontent.com/` at the +smallest of 32, 64, 128 or 256 pixels covering `size`, with no credential or +cookie, following redirects only within that host. It accepts only PNG, JPEG, +GIF or WebP judged by the bytes, not the upstream content type, up to 512 KiB +and 1024 pixels a side, and answers them with their sniffed type, +`X-Content-Type-Options: nosniff`, `Content-Security-Policy: default-src +'none'; sandbox` and `Cache-Control: private, max-age=3600`. Images are kept +in a bounded in-memory cache (256 entries, 8 MiB, six hours) that evicts its +least recently used entry and never writes to disk, `brain.db` or the brain. +Every failure, including a login not in the session and a caller who does not +own it, is an empty 404, and the component shows initials. + ## Untrusted file marks (internal, #2673) The four `/api/files/untrusted` operations are protected, internal UI diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 2295bbe33a..41d3734c2d 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -47,6 +47,20 @@ shape changes. See [the package API](integration-contract/package-api.md#start-card-persona-choice-3698). This ships in a minor. +## GitHub detail-page types (additive, 0.45.0, #3796) + +`@schlessera/brain-ui-sdk/tool-contracts` adds the detail-page part list, +the page-size bound, the review-comment, changed-file and check-run item +schemas, the page schema and the detail error schema with `reset_at`, which +the two new internal ui-server routes return to the chat's GitHub components: +`GET /api/sessions/:id/github/:owner/:repo/:number/:part` and +`GET /api/sessions/:id/github/avatars/:login`. The routes are internal (`I`) +with no compatibility guarantee; nothing they serve enters the +provider-facing conversation. See +[the package API](integration-contract/package-api.md#github-detail-page-types-additive-0450-3796) +and [the HTTP API](http-api.md#github-detail-pages-internal-0450-3796). +This ships in a minor. + ## Host GitHub tools (additive, 0.45.0, #3797) Both first-party backends' interactive sessions gain two host-executed read diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 7ba487b7b8..aac21fd9fc 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -546,6 +546,25 @@ input and forwards `{ tool, input }` to the optional new [the MCP component](mcp.md#host-github-tools-additive-0450-3797). No existing export changes. +## GitHub detail-page types (additive, 0.45.0, #3796) + +`@schlessera/brain-ui-sdk/tool-contracts` (re-exported from `/server`) adds +the item and page types the internal +[GitHub detail route](../http-api.md#github-detail-pages-internal-0450-3796) +returns: `GITHUB_DETAIL_PARTS` with `isGithubDetailPart` and the +`GithubDetailPart` type, `GITHUB_DETAIL_PAGE_SIZE` (30), +`GITHUB_REVIEW_COMMENT_SCHEMA`, `GITHUB_CHANGED_FILE_SCHEMA` with +`GITHUB_CHANGED_FILE_STATUSES`, `GITHUB_CHECK_RUN_SCHEMA` with +`GITHUB_CHECK_CONCLUSIONS`, `GITHUB_DETAIL_PAGE_SCHEMA` (one page per part, in +the existing comment, review and commit types and the three new ones), +`GITHUB_DETAIL_ERROR_SCHEMA` (the tools' error plus a nullable `reset_at`) and +`GITHUB_DETAIL_ERROR_RESPONSE_SCHEMA`, and the matching types +`GithubReviewComment`, `GithubChangedFile`, `GithubCheckRun`, +`GithubDetailPage` and `GithubDetailError`. Text GitHub users wrote is marked +untrusted as in the tool payloads. The route's raw path and payload stay +internal; these exports are the types a client binds to. No existing export +changes. + ## Package entry points **Breaking pre-1.0 export curation (#534, ruled on #343 question 1).** Each diff --git a/packages/ui-react/src/lib/github-details.ts b/packages/ui-react/src/lib/github-details.ts new file mode 100644 index 0000000000..d636ad9227 --- /dev/null +++ b/packages/ui-react/src/lib/github-details.ts @@ -0,0 +1,65 @@ +import { + GITHUB_DETAIL_ERROR_RESPONSE_SCHEMA, GITHUB_DETAIL_PAGE_SCHEMA, parseGithubRepository, + type GithubDetailError, type GithubDetailPage, type GithubDetailPart, +} from "@schlessera/brain-ui-sdk/tool-contracts"; +import type { BrainUiServices } from "../root.js"; + +/** How long one detail request may take before it counts as no answer. */ +const DETAIL_CALL_TIMEOUT_MS = 20_000; + +interface GithubDetailRequest { + sessionId: string; + /** `owner/repo`, as the tool result named it. */ + repository: string; + number: number; + part: GithubDetailPart; + /** The previous page's `next_cursor`; omitted for the first page. */ + cursor?: string | null; + signal?: AbortSignal; +} + +type GithubDetailResult = { ok: true; page: GithubDetailPage } | { ok: false; error: GithubDetailError }; + +const failed = (code: GithubDetailError["code"], reason: string | null, message: string): GithubDetailResult => + ({ ok: false, error: { code, reason, message, reset_at: null } }); + +/** + * One page of a GitHub object's detail (#3796), for the chat's GitHub + * components. Display data only: the host never adds it to the conversation. + * Nothing is cached here; a component keeps what it loaded for its lifetime. + * Every failure resolves to the host's typed error, or `upstream_error` when + * the host did not answer with one. + */ +export async function fetchGithubDetailPage(root: Pick, input: GithubDetailRequest): Promise { + const repository = parseGithubRepository(input.repository); + if (!repository || !Number.isSafeInteger(input.number) || input.number < 1) return failed("invalid_input", "object", "That is not a GitHub issue or pull request."); + const path = [input.sessionId, "github", repository.owner, repository.repo, String(input.number), input.part].map(encodeURIComponent).join("/"); + const query = input.cursor ? `?${new URLSearchParams({ cursor: input.cursor })}` : ""; + const timeout = AbortSignal.timeout(DETAIL_CALL_TIMEOUT_MS); + let response: Response; + try { + response = await root.request(`${root.apiBase()}/sessions/${path}${query}`, { cache: "no-store", + signal: input.signal ? AbortSignal.any([input.signal, timeout]) : timeout }); + } catch { + return failed("upstream_error", input.signal?.aborted ? "cancelled" : "network", "The host did not answer."); + } + const json: unknown = await response.json().catch(() => undefined); + if (response.ok) { + const page = GITHUB_DETAIL_PAGE_SCHEMA.safeParse(json); + if (page.success && page.data.part === input.part && page.data.number === input.number) return { ok: true, page: page.data }; + return failed("upstream_error", "malformed", "The host answered with something that is not a detail page."); + } + const error = GITHUB_DETAIL_ERROR_RESPONSE_SCHEMA.safeParse(json); + if (error.success) return { ok: false, error: error.data.error }; + if (response.status === 401) return failed("unavailable", "authentication", "Sign in again to load more."); + return failed("upstream_error", `http_${response.status}`, "The host could not load this."); +} + +/** + * The same-origin URL of a GitHub user's avatar in this session (#3796). The + * browser never contacts GitHub; any failure is a 404, so a component falls + * back to initials. + */ +export function githubAvatarUrl(apiBase: string, sessionId: string, login: string, size = 64): string { + return `${apiBase}/sessions/${encodeURIComponent(sessionId)}/github/avatars/${encodeURIComponent(login)}?size=${Math.max(1, Math.min(9999, Math.round(size)))}`; +} diff --git a/packages/ui-react/tests/github-details.test.ts b/packages/ui-react/tests/github-details.test.ts new file mode 100644 index 0000000000..f3fc428305 --- /dev/null +++ b/packages/ui-react/tests/github-details.test.ts @@ -0,0 +1,41 @@ +/** + * The GitHub detail client (#3796): one request per call to the host's + * internal route, the page or the host's typed error back, and a + * same-origin avatar URL. No caching and no GitHub origin anywhere. + */ +import { describe, expect, test } from "bun:test"; +import type { GithubDetailPage } from "@schlessera/brain-ui-sdk/tool-contracts"; +import { fetchGithubDetailPage, githubAvatarUrl } from "../src/lib/github-details.js"; + +const page: GithubDetailPage = { kind: "detail_page", repository: "odysseus/ithaca", number: 8, part: "files", total_count: null, next_cursor: "2", + fetched_at: "2026-07-12T12:00:00.000Z", items: [{ filename: "bow/string.ts", previous_filename: null, status: "modified", additions: 3, deletions: 1, changes: 4 }] }; + +function root(answer: () => Response) { + const urls: string[] = []; + return { urls, root: { apiBase: () => "/api", request: async (url: string) => { urls.push(url); return answer(); } } }; +} + +describe("fetchGithubDetailPage", () => { + test("asks the host's route for one part and returns the parsed page; each call asks again", async () => { + const t = root(() => Response.json(page)); + const input = { sessionId: "sess ithaca", repository: "odysseus/ithaca", number: 8, part: "files" as const, cursor: "2" }; + expect(await fetchGithubDetailPage(t.root, input), "GITHUB_CLIENT_PAGE").toEqual({ ok: true, page }); + await fetchGithubDetailPage(t.root, { ...input, cursor: null }); + expect(t.urls, "GITHUB_CLIENT_NO_CACHE").toEqual(["/api/sessions/sess%20ithaca/github/odysseus/ithaca/8/files?cursor=2", "/api/sessions/sess%20ithaca/github/odysseus/ithaca/8/files"]); + }); + + test("returns the host's typed error, and a non-answer as upstream_error", async () => { + const limited = { code: "rate_limited" as const, reason: "github", message: "Spent.", reset_at: "2026-07-12T12:10:00.000Z" }; + expect(await fetchGithubDetailPage(root(() => Response.json({ error: limited }, { status: 429 })).root, + { sessionId: "s", repository: "odysseus/ithaca", number: 7, part: "comments" }), "GITHUB_CLIENT_TYPED_ERROR").toEqual({ ok: false, error: limited }); + const garbled = await fetchGithubDetailPage(root(() => new Response("", { status: 200 })).root, { sessionId: "s", repository: "odysseus/ithaca", number: 7, part: "comments" }); + expect(garbled).toMatchObject({ ok: false, error: { code: "upstream_error", reason: "malformed" } }); + const refused = root(() => Response.json(page)); + expect(await fetchGithubDetailPage(refused.root, { sessionId: "s", repository: "../ithaca", number: 7, part: "comments" })).toMatchObject({ ok: false, error: { code: "invalid_input" } }); + expect(refused.urls, "GITHUB_CLIENT_INVALID_SENDS_NOTHING").toEqual([]); + }); +}); + +test("githubAvatarUrl is same-origin and encodes the login", () => { + expect(githubAvatarUrl("/api", "sess-ithaca", "herald[bot]", 40)).toBe("/api/sessions/sess-ithaca/github/avatars/herald%5Bbot%5D?size=40"); +}); diff --git a/packages/ui-sdk/src/tool-contracts/github.ts b/packages/ui-sdk/src/tool-contracts/github.ts index eab0105317..18b460324c 100644 --- a/packages/ui-sdk/src/tool-contracts/github.ts +++ b/packages/ui-sdk/src/tool-contracts/github.ts @@ -541,3 +541,104 @@ export function isGithubSearchUrl(value: unknown, scope: { owner: string; repo: if (!scope && url.searchParams.get("type") !== "issues") return false; return url.searchParams.get("q") === q; } + +// ------------------------------------------------- display detail pages + +/** + * The parts of one issue or pull request the chat components may page on + * demand through the host's display-only detail route (#3796). The route + * serves only an object a GitHub tool result in that session returned, and + * its pages never enter the provider-facing conversation. + */ +export const GITHUB_DETAIL_PARTS = ["comments", "reviews", "review-comments", "commits", "files", "checks"] as const; +export type GithubDetailPart = (typeof GITHUB_DETAIL_PARTS)[number]; +export const isGithubDetailPart = (value: string): value is GithubDetailPart => (GITHUB_DETAIL_PARTS as readonly string[]).includes(value); + +/** Items in one detail page, at most: the page-size bound. */ +export const GITHUB_DETAIL_PAGE_SIZE = 30; + +/** A comment on a pull request's diff, with the line it was made on. */ +export const GITHUB_REVIEW_COMMENT_SCHEMA = z.strictObject({ + id: z.number().int().positive(), + /** The review it belongs to, when GitHub names one. */ + review_id: z.number().int().positive().nullable(), + /** The comment it answers, when it is a reply. */ + in_reply_to_id: z.number().int().positive().nullable(), + author: GITHUB_AUTHOR_SCHEMA, + /** The file it was made on. */ + path: untrusted(1024), + /** The line in the diff's new version, or null for an outdated or file-level comment. */ + line: z.number().int().positive().nullable(), + created_at: timestamp, + updated_at: timestamp, + ...bodyFields(GITHUB_LIMITS.commentBodyChars), + html_url: directUrl, +}); + +export const GITHUB_CHANGED_FILE_STATUSES = ["added", "removed", "modified", "renamed", "copied", "changed", "unchanged"] as const; +/** One changed file of a pull request: a summary, never its diff or content. */ +export const GITHUB_CHANGED_FILE_SCHEMA = z.strictObject({ + filename: untrusted(1024), + /** The name before a rename or copy. */ + previous_filename: untrusted(1024).nullable(), + status: z.enum(GITHUB_CHANGED_FILE_STATUSES), + additions: count, + deletions: count, + changes: count, +}); + +export const GITHUB_CHECK_CONCLUSIONS = ["success", "failure", "neutral", "cancelled", "skipped", "timed_out", "action_required", "stale", + "startup_failure", "error", "pending"] as const; +/** + * One check run or commit status on the head commit. `state` is the bucket + * the payload's `checks` counts use; `conclusion` is GitHub's own word for a + * finished run or a status's state, or null while a run has none. + */ +export const GITHUB_CHECK_RUN_SCHEMA = z.strictObject({ + source: z.enum(["check_run", "status"]), + /** The check run's name or the status's context. */ + name: untrusted(256), + state: z.enum(["passed", "failed", "running", "skipped"]), + conclusion: z.enum(GITHUB_CHECK_CONCLUSIONS).nullable(), + started_at: timestamp.nullable(), + completed_at: timestamp.nullable(), +}); + +const detailPage = (part: Part, item: Item) => z.strictObject({ + kind: z.literal("detail_page"), + repository: z.string().max(141), + number: z.number().int().positive(), + part: z.literal(part), + items: z.array(item).max(GITHUB_DETAIL_PAGE_SIZE), + /** The total GitHub reports, or null where it reports none. */ + total_count: count.nullable(), + /** Opaque: pass it back as `cursor` for the next page; null on the last one. */ + next_cursor: z.string().max(256).nullable(), + fetched_at: timestamp, +}); + +/** One page of a part, oldest first, in the same item types the tool payloads use. */ +export const GITHUB_DETAIL_PAGE_SCHEMA = z.discriminatedUnion("part", [ + detailPage("comments", GITHUB_COMMENT_SCHEMA), + detailPage("reviews", GITHUB_REVIEW_SCHEMA), + detailPage("review-comments", GITHUB_REVIEW_COMMENT_SCHEMA), + detailPage("commits", GITHUB_COMMIT_SCHEMA), + detailPage("files", GITHUB_CHANGED_FILE_SCHEMA), + detailPage("checks", GITHUB_CHECK_RUN_SCHEMA), +]); + +/** + * Why a detail page was not served. The code is one of the tools' own; + * `reason` says more: `not_in_session` (no GitHub result in this session + * returned the object), `not_owner`, `part` or `cursor` (refused input), + * `no_credential`, `credential_rejected`. `reset_at` is when a spent rate + * limit resets, and null otherwise. + */ +export const GITHUB_DETAIL_ERROR_SCHEMA = GITHUB_ERROR_SCHEMA.extend({ reset_at: timestamp.nullable() }); +export const GITHUB_DETAIL_ERROR_RESPONSE_SCHEMA = z.strictObject({ error: GITHUB_DETAIL_ERROR_SCHEMA }); + +export type GithubReviewComment = z.infer; +export type GithubChangedFile = z.infer; +export type GithubCheckRun = z.infer; +export type GithubDetailPage = z.infer; +export type GithubDetailError = z.infer; diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 3e9893ca01..9cd57cf316 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -46,6 +46,10 @@ import { APIFY_AUTHORITY_SETTING, apifyBrainId, createApifyAuthority, governance import { createApifyRoutes } from "./routes/apify.js"; import { createApifyHost } from "./apify/host.js"; import { createGithubToolsHost } from "./github/host.js"; +import { createGithubDetails } from "./github/details.js"; +import { resolveChat } from "./ws/chat-lifecycle.js"; +import { createGithubDetailRoutes } from "./routes/github-details.js"; +import { sameAccount } from "./middleware/account-partition.js"; import { createApifyPolicyEdits } from "./apify/settings.js"; import { apifyBudgetSource } from "./apify/budget-liability.js"; import { declaredContentRenderers } from "./brain/content-renderers.js"; @@ -1175,6 +1179,17 @@ export async function createApp(options: CreateAppOptions = {}): Promise host.prepareHistory(id, messages), settled: () => host.historySettled(), retired: target => host.catalog.chatRetired?.(target) === true })); + // GitHub detail pages and avatars for the chat components (#3796): display + // data under the tools' dedicated credential, never provider context. + app.route("/api", createGithubDetailRoutes({ details: createGithubDetails({ token: githubToolsTokenSource() }), + principalValid: principal => host.isPrincipalValid(principal), + owns: (principal, sessionId) => { const chat = resolveChat(db, { sessionId }); return !("refused" in chat) && sameAccount(db, chat.principalId, principal.id); }, + retired: sessionId => host.catalog.chatRetired?.({ sessionId }) === true, + history: async sessionId => { + const stored = db.query("SELECT backend_id AS backendId FROM sessions WHERE id = ?").get(sessionId) as { backendId: string | null } | null; + return (await registry.getBackendForSession(stored?.backendId ?? null)).getHistory(sessionId); + }, + settled: () => host.historySettled() })); // Explicit local chat deletion (#3230), on a catalog that can retire chats. if (host.catalog.retireChat && host.catalog.cleanChatStore) { const chatDeletion = host.chatDeletion = createChatDeletion({ catalog: host.catalog, backends: () => registry.getBackends(), diff --git a/packages/ui-server/src/github/details.ts b/packages/ui-server/src/github/details.ts new file mode 100644 index 0000000000..112c093df6 --- /dev/null +++ b/packages/ui-server/src/github/details.ts @@ -0,0 +1,389 @@ +/** + * On-demand GitHub detail pages and the avatar proxy for the chat components + * (#3796, epic #3791). Display data only: nothing here reaches a turn, the + * provider-facing conversation, the turn journal or the session's taint. + * + * Bounded authority. A page is served only for an object (`owner/repo#n`) + * that a host GitHub tool result in that session returned, read from the + * session's own recorded history; an avatar only for a login that appears in + * those results or in a page served for that session. It is not a GitHub + * proxy: the paths are fixed per part, under the fixed API origin, with the + * tools' dedicated credential (`BRAIN_UI_GITHUB_TOOLS_TOKEN`, no fallback). + * + * Items use the tools' contract types, and every direct link passes the + * contract's validator for its kind and identity, else it is null. Nothing + * here builds a GitHub URL a component may open. + * + * Avatars come from GitHub's avatar host without any credential. Only PNG, + * JPEG, GIF and WebP pass, judged by their bytes, within a byte and a pixel + * cap, and they are kept in a bounded in-memory cache that evicts and never + * grows: nothing is written to disk, `brain.db` or the brain. + */ +import { + GITHUB_DETAIL_PAGE_SIZE, GITHUB_LIMITS, GITHUB_RESULT_SCHEMAS, GITHUB_TOOL_NAMES, BRIDGE_MCP_PREFIX, githubDirectUrl, parseGithubRepository, + type GithubAuthor, type GithubChangedFile, type GithubCheckRun, type GithubComment, type GithubCommit, type GithubDetailPage, type GithubDetailPart, + type GithubLinkScope, type GithubReview, type GithubReviewComment, type GithubToolName, type GithubUser, +} from "@schlessera/brain-ui-sdk/tool-contracts"; +import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { + GithubRefusal, LOGIN, SHA, array, author, body, comment, commit, cut, githubGet, integer, nextLink, record, review, text, time, requiredTime, + type GithubTransport, type Json, +} from "./host.js"; + +/** The host that serves avatars, and the only one an avatar request reaches. */ +const GITHUB_AVATAR_ORIGIN = "https://avatars.githubusercontent.com"; +/** The sizes an avatar is fetched at; a request takes the smallest that covers it. */ +const GITHUB_AVATAR_SIZES = [32, 64, 128, 256] as const; +const GITHUB_AVATAR_LIMITS = Object.freeze({ + /** One image, bytes. */ + bytes: 512 * 1024, + /** One image's width and height, pixels. */ + pixels: 1024, + /** The cache: entries and bytes held at most, and how long one is kept. */ + entries: 256, + cacheBytes: 8 * 1024 * 1024, + ttlMs: 6 * 60 * 60 * 1000, +}); + +/** The objects and logins a session's GitHub tool results returned. */ +interface GithubSessionScope { + /** `owner/repo#n`, lower-cased, to whether it is a pull request (null when no result said). */ + objects: Map; + /** Lower-cased logins. */ + logins: Set; +} + +const objectKey = (repository: string, number: number) => `${repository.toLowerCase()}#${number}`; + +function toolName(name: string): GithubToolName | null { + const bare = name.startsWith(BRIDGE_MCP_PREFIX) ? name.slice(BRIDGE_MCP_PREFIX.length) : name; + return (Object.values(GITHUB_TOOL_NAMES) as string[]).includes(bare) ? bare as GithubToolName : null; +} + +/** + * What the session's recorded GitHub tool results returned. Only a result + * that parses as the tool's own successful envelope counts: an error, a + * truncated or edited output, or another tool's text names nothing. + */ +export function githubSessionScope(messages: readonly SessionHistoryMessage[]): GithubSessionScope { + const scope: GithubSessionScope = { objects: new Map(), logins: new Set() }; + const login = (user: GithubUser | GithubAuthor | null | undefined) => { if (user?.login) scope.logins.add(user.login.toLowerCase()); }; + const object = (repository: string, number: number, pullRequest: boolean | null) => { + const key = objectKey(repository, number), known = scope.objects.get(key); + if (!known || known.pullRequest === null) scope.objects.set(key, { repository, number, pullRequest }); + }; + for (const message of messages) { + for (const call of message.toolCalls ?? []) { + const tool = toolName(call.name); + if (!tool || call.isError || typeof call.output !== "string" || call.output.length > 4_000_000) continue; + let raw: unknown; + try { raw = JSON.parse(call.output); } catch { continue; } + const parsed = GITHUB_RESULT_SCHEMAS[tool].safeParse(raw); + if (!parsed.success || !parsed.data.ok) continue; + const result = parsed.data.result; + switch (result.kind) { + case "issue": case "pull_request": { + object(result.repository, result.number, result.kind === "pull_request"); + login(result.author); + for (const item of result.comments.items) login(item.author); + if (result.kind === "pull_request") { + login(result.merged_by); + for (const user of result.requested_reviewers) login(user); + for (const item of result.reviews.items) login(item.author); + for (const item of result.review_decisions) login(item.reviewer); + for (const item of result.commits.items) login(item.author); + } + break; + } + case "search": + for (const item of result.items) { object(result.repository, item.number, item.kind === "pull_request"); login(item.author); } + break; + case "issue_created": case "comment_created": + object(result.repository, result.number, null); + break; + } + } + } + return scope; +} + +/** A refused cursor or part, before anything is sent. */ +export class GithubDetailInputError extends Error { + constructor(readonly reason: "part" | "cursor" | "not_pull_request", message: string) { super(message); } +} + +export interface GithubDetailsOptions extends GithubTransport { + /** The tools' dedicated credential; undefined answers `unavailable`. */ + token: () => string | undefined; + /** @internal Test seam for the avatar host; production uses the global fetch. */ + avatarFetch?: typeof fetch; + /** @internal Test bounds; production uses {@link GITHUB_AVATAR_LIMITS}. */ + avatarLimits?: Partial>; +} + +interface GithubAvatar { bytes: Uint8Array; type: "image/png" | "image/jpeg" | "image/gif" | "image/webp" } + +export interface GithubDetails { + /** One page of `part`, or a {@link GithubRefusal} / {@link GithubDetailInputError}. */ + page(sessionId: string, object: { repository: string; number: number; pullRequest: boolean | null }, part: GithubDetailPart, + cursor: string | null, signal?: AbortSignal): Promise; + /** Whether `login` appeared in a page served for this session. */ + servedLogin(sessionId: string, login: string): boolean; + /** The avatar, or null for any failure. */ + avatar(login: string, size: number, signal?: AbortSignal): Promise; + /** @internal What the avatar cache holds now. */ + avatarCache(): { entries: number; bytes: number }; +} + +/** The cursor of a part: a page number, and for checks which source it pages. */ +function parseCursor(part: GithubDetailPart, cursor: string | null): { source: "runs" | "statuses"; page: number } { + if (cursor === null) return { source: "runs", page: 1 }; + const match = part === "checks" ? /^(runs|statuses):([1-9][0-9]{0,3})$/.exec(cursor) : /^()([1-9][0-9]{0,3})$/.exec(cursor); + if (!match) throw new GithubDetailInputError("cursor", "The cursor is not one this host issued."); + return { source: match[1] === "statuses" ? "statuses" : "runs", page: Number(match[2]) }; +} + +function reviewComment(value: Json, scope: GithubLinkScope, fallback: string): GithubReviewComment | null { + const id = integer(value.id); + if (!id) return null; + const line = integer(value.line); + return { id, review_id: integer(value.pull_request_review_id) || null, in_reply_to_id: integer(value.in_reply_to_id) || null, + author: author(value.user, value.author_association), path: cut(text(value.path) ?? "", 1024).text, line: line && line > 0 ? line : null, + created_at: requiredTime(value.created_at, fallback), updated_at: requiredTime(value.updated_at, requiredTime(value.created_at, fallback)), + ...body(value.body, GITHUB_LIMITS.commentBodyChars), html_url: githubDirectUrl(value.html_url, scope, { kind: "review_comment", id }) }; +} + +const FILE_STATUSES = new Set(["added", "removed", "modified", "renamed", "copied", "changed", "unchanged"]); +function changedFile(value: Json): GithubChangedFile | null { + const filename = text(value.filename), status = text(value.status); + if (!filename || !status || !FILE_STATUSES.has(status)) return null; + const previous = text(value.previous_filename); + return { filename: cut(filename, 1024).text, previous_filename: previous ? cut(previous, 1024).text : null, status: status as GithubChangedFile["status"], + additions: integer(value.additions) ?? 0, deletions: integer(value.deletions) ?? 0, changes: integer(value.changes) ?? 0 }; +} + +const RUN_CONCLUSIONS = new Set(["success", "failure", "neutral", "cancelled", "skipped", "timed_out", "action_required", "stale", "startup_failure"]); +function checkRun(value: Json): GithubCheckRun { + const completed = value.status === "completed"; + const conclusion = completed && RUN_CONCLUSIONS.has(String(value.conclusion)) ? value.conclusion as GithubCheckRun["conclusion"] : null; + // The same buckets as the payload's `checks` counts. + const state = !completed ? "running" : conclusion === "success" || conclusion === "neutral" ? "passed" : conclusion === "skipped" ? "skipped" : "failed"; + return { source: "check_run", name: cut(text(value.name) ?? "", 256).text, state, conclusion, + started_at: time(value.started_at), completed_at: completed ? time(value.completed_at) : null }; +} +function commitStatus(value: Json): GithubCheckRun { + const raw = String(value.state); + const conclusion = (["success", "failure", "error", "pending"] as const).find(state => state === raw) ?? null; + const state = conclusion === "success" ? "passed" : conclusion === "pending" ? "running" : "failed"; + return { source: "status", name: cut(text(value.context) ?? "", 256).text, state, conclusion, + started_at: time(value.created_at), completed_at: conclusion && conclusion !== "pending" ? time(value.updated_at) : null }; +} + +/** The image's type and size, judged by its bytes alone, or null. */ +export function sniffImage(bytes: Uint8Array): { type: GithubAvatar["type"]; width: number; height: number } | null { + const at = (index: number) => bytes[index] ?? -1; + const be16 = (index: number) => (at(index) << 8) | at(index + 1); + const le16 = (index: number) => at(index) | (at(index + 1) << 8); + const be32 = (index: number) => ((at(index) << 24) >>> 0) + (at(index + 1) << 16) + (at(index + 2) << 8) + at(index + 3); + const ascii = (index: number, value: string) => [...value].every((char, offset) => at(index + offset) === char.charCodeAt(0)); + if (bytes.length >= 24 && [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((byte, index) => at(index) === byte) && ascii(12, "IHDR")) + return { type: "image/png", width: be32(16), height: be32(20) }; + if (bytes.length >= 10 && (ascii(0, "GIF87a") || ascii(0, "GIF89a"))) return { type: "image/gif", width: le16(6), height: le16(8) }; + if (bytes.length >= 30 && ascii(0, "RIFF") && ascii(8, "WEBP")) { + if (ascii(12, "VP8 ") && at(23) === 0x9d && at(24) === 0x01 && at(25) === 0x2a) return { type: "image/webp", width: le16(26) & 0x3fff, height: le16(28) & 0x3fff }; + if (ascii(12, "VP8L") && at(20) === 0x2f) { + const bits = at(21) | (at(22) << 8) | (at(23) << 16) | (at(24) << 24); + return { type: "image/webp", width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 }; + } + if (ascii(12, "VP8X")) return { type: "image/webp", width: (at(24) | (at(25) << 8) | (at(26) << 16)) + 1, height: (at(27) | (at(28) << 8) | (at(29) << 16)) + 1 }; + return null; + } + if (bytes.length >= 4 && at(0) === 0xff && at(1) === 0xd8 && at(2) === 0xff) { + // Walk the markers to the first start-of-frame, which carries the size. + let index = 2; + while (index + 9 < bytes.length) { + if (at(index) !== 0xff) return null; + const marker = at(index + 1); + if (marker === 0xff) { index++; continue; } + if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { index += 2; continue; } + const length = be16(index + 2); + if (length < 2) return null; + if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) + return { type: "image/jpeg", width: be16(index + 7), height: be16(index + 5) }; + if (marker === 0xd9 || marker === 0xda) return null; + index += 2 + length; + } + } + return null; +} + +/** The whole body, or null once it passes `max` bytes. */ +async function boundedBody(response: Response, max: number): Promise | null> { + const declared = Number(response.headers.get("content-length")); + if (Number.isFinite(declared) && declared > max) { await response.body?.cancel().catch(() => {}); return null; } + if (!response.body) return new Uint8Array(); + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > max) { await reader.cancel().catch(() => {}); return null; } + chunks.push(value); + } + const out = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { out.set(chunk, offset); offset += chunk.byteLength; } + return out; +} + +export function createGithubDetails(options: GithubDetailsOptions): GithubDetails { + const now = options.now ?? Date.now; + const limits = { ...GITHUB_AVATAR_LIMITS, ...options.avatarLimits }; + const get = (token: string, path: string, signal?: AbortSignal) => githubGet(options, token, path, signal); + /** Logins of the pages served per session: bounded, oldest session dropped first. */ + const served = new Map>(); + const avatars = new Map(); + let cachedBytes = 0; + + function remember(sessionId: string, logins: Iterable) { + let set = served.get(sessionId); + if (set) served.delete(sessionId); + else set = new Set(); + served.set(sessionId, set); + for (const login of logins) if (set.size < 2_000) set.add(login.toLowerCase()); + while (served.size > 200) served.delete(served.keys().next().value!); + } + + const items = (json: unknown) => array(json).map(record).filter((item): item is Json => item !== null); + + async function page(sessionId: string, object: { repository: string; number: number; pullRequest: boolean | null }, part: GithubDetailPart, + cursor: string | null, signal?: AbortSignal): Promise { + const { source, page: at } = parseCursor(part, cursor); + if (part !== "comments" && object.pullRequest === false) + throw new GithubDetailInputError("not_pull_request", "Only a pull request has this part."); + const token = options.token(); + if (!token) throw new GithubRefusal("unavailable", "no_credential", "This host has no GitHub credential for its GitHub tools (BRAIN_UI_GITHUB_TOOLS_TOKEN). GITHUB_TOKEN is never used for them."); + const parsed = parseGithubRepository(object.repository)!; + const name = `${parsed.owner}/${parsed.repo}`, scope: GithubLinkScope = { owner: parsed.owner, repo: parsed.repo, number: object.number }; + const fetchedAt = new Date(now()).toISOString(); + const size = GITHUB_DETAIL_PAGE_SIZE, query = `per_page=${size}&page=${at}`; + const base = { kind: "detail_page" as const, repository: name, number: object.number, fetched_at: fetchedAt }; + const listed = async (path: string) => { + const { json, response } = await get(token, `${path}?${query}`, signal); + return { raw: items(json).slice(0, size), next: nextLink(response) ? String(at + 1) : null }; + }; + const logins = (list: Array<{ author: GithubUser | GithubAuthor | null }>) => list.flatMap(item => item.author?.login ? [item.author.login] : []); + let result: GithubDetailPage; + switch (part) { + case "comments": { + const { raw, next } = await listed(`/repos/${name}/issues/${object.number}/comments`); + const list = raw.map(item => comment(item, scope, fetchedAt)).filter((item): item is GithubComment => item !== null); + remember(sessionId, logins(list)); + result = { ...base, part, items: list, total_count: null, next_cursor: next }; + break; + } + case "reviews": { + const { raw, next } = await listed(`/repos/${name}/pulls/${object.number}/reviews`); + const list = raw.map(item => review(item, scope)).filter((item): item is GithubReview => item !== null); + remember(sessionId, logins(list)); + result = { ...base, part, items: list, total_count: null, next_cursor: next }; + break; + } + case "review-comments": { + const { raw, next } = await listed(`/repos/${name}/pulls/${object.number}/comments`); + const list = raw.map(item => reviewComment(item, scope, fetchedAt)).filter((item): item is GithubReviewComment => item !== null); + remember(sessionId, logins(list)); + result = { ...base, part, items: list, total_count: null, next_cursor: next }; + break; + } + case "commits": { + const { raw, next } = await listed(`/repos/${name}/pulls/${object.number}/commits`); + const list = raw.map(item => commit(item, scope)).filter((item): item is GithubCommit => item !== null); + remember(sessionId, logins(list)); + result = { ...base, part, items: list, total_count: null, next_cursor: next }; + break; + } + case "files": { + const { raw, next } = await listed(`/repos/${name}/pulls/${object.number}/files`); + result = { ...base, part, items: raw.map(changedFile).filter((item): item is GithubChangedFile => item !== null), total_count: null, next_cursor: next }; + break; + } + case "checks": { + const pull = record((await get(token, `/repos/${name}/pulls/${object.number}`, signal)).json); + const sha = text(record(pull?.head)?.sha); + if (!sha || !SHA.test(sha)) throw new GithubRefusal("upstream_error", "malformed", "GitHub returned an unexpected pull request."); + if (source === "runs") { + const { json, response } = await get(token, `/repos/${name}/commits/${sha}/check-runs?${query}`, signal); + const runs = array(record(json)?.check_runs).map(record).filter((item): item is Json => item !== null).slice(0, size).map(checkRun); + result = { ...base, part, items: runs, total_count: null, next_cursor: nextLink(response) ? `runs:${at + 1}` : "statuses:1" }; + } else { + const status = record((await get(token, `/repos/${name}/commits/${sha}/status?${query}`, signal)).json); + const statuses = array(status?.statuses).map(record).filter((item): item is Json => item !== null).slice(0, size).map(commitStatus); + const total = integer(status?.total_count); + result = { ...base, part, items: statuses, total_count: null, next_cursor: total !== null && at * size < total ? `statuses:${at + 1}` : null }; + } + break; + } + } + return result; + } + + function drop(key: string) { + const entry = avatars.get(key); + if (entry) { avatars.delete(key); cachedBytes -= entry.avatar.bytes.byteLength; } + } + function evict() { + const cutoff = now() - limits.ttlMs; + for (const [key, entry] of [...avatars]) if (entry.at < cutoff) drop(key); + // Insertion order is age: a hit re-inserts, so the first key is the least recently used. + while (avatars.size > limits.entries || cachedBytes > limits.cacheBytes) drop(avatars.keys().next().value!); + } + + async function avatar(login: string, size: number, signal?: AbortSignal): Promise { + if (!LOGIN.test(login)) return null; + const fitted = GITHUB_AVATAR_SIZES.find(candidate => candidate >= size) ?? GITHUB_AVATAR_SIZES.at(-1)!; + const key = `${login.toLowerCase()}@${fitted}`; + const hit = avatars.get(key); + if (hit && hit.at >= now() - limits.ttlMs) { avatars.delete(key); avatars.set(key, hit); return hit.avatar; } + let url = new URL(`/${encodeURIComponent(login)}`, GITHUB_AVATAR_ORIGIN); + url.search = new URLSearchParams({ size: String(fitted) }).toString(); + try { + for (let hop = 0; hop < 3; hop++) { + if (url.origin !== GITHUB_AVATAR_ORIGIN) return null; + const timeout = AbortSignal.timeout(options.timeoutMs ?? 20_000); + // No credential of any kind: no token, no cookie. + const response = await (options.avatarFetch ?? fetch)(url, { method: "GET", redirect: "manual", credentials: "omit", + signal: signal ? AbortSignal.any([signal, timeout]) : timeout, headers: { accept: "image/png,image/jpeg,image/gif,image/webp", "user-agent": "brain-ui" } }); + if (response.status >= 300 && response.status < 400 && response.headers.get("location")) { + await response.body?.cancel().catch(() => {}); + url = new URL(response.headers.get("location")!, url); + continue; + } + if (!response.ok) { await response.body?.cancel().catch(() => {}); return null; } + const bytes = await boundedBody(response, limits.bytes); + if (!bytes) return null; + // The upstream content type is not believed: the bytes decide. + const image = sniffImage(bytes); + if (!image || image.width < 1 || image.height < 1 || image.width > limits.pixels || image.height > limits.pixels) return null; + const result: GithubAvatar = { bytes, type: image.type }; + drop(key); + avatars.set(key, { avatar: result, at: now() }); + cachedBytes += bytes.byteLength; + evict(); + return result; + } + return null; + } catch { + return null; + } + } + + return { + page, + servedLogin: (sessionId, login) => served.get(sessionId)?.has(login.toLowerCase()) ?? false, + avatar, + avatarCache: () => ({ entries: avatars.size, bytes: cachedBytes }), + }; +} diff --git a/packages/ui-server/src/github/host.ts b/packages/ui-server/src/github/host.ts index 084d97275a..00dcefa6d9 100644 --- a/packages/ui-server/src/github/host.ts +++ b/packages/ui-server/src/github/host.ts @@ -48,25 +48,26 @@ export interface GithubToolsHost { call(turn: GithubToolsTurn, call: GithubToolCall): Promise; } -class GithubRefusal extends Error { - constructor(readonly code: GithubErrorCode, readonly reason: string | null, message: string) { super(message); } +/** A typed refusal; `resetAt` is when a spent rate limit resets, when GitHub says. */ +export class GithubRefusal extends Error { + constructor(readonly code: GithubErrorCode, readonly reason: string | null, message: string, readonly resetAt: string | null = null) { super(message); } } -type Json = Record; -const record = (value: unknown): Json | null => value && typeof value === "object" && !Array.isArray(value) ? value as Json : null; -const array = (value: unknown): unknown[] => Array.isArray(value) ? value : []; -const text = (value: unknown): string | null => typeof value === "string" ? value : null; -const integer = (value: unknown): number | null => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null; +export type Json = Record; +export const record = (value: unknown): Json | null => value && typeof value === "object" && !Array.isArray(value) ? value as Json : null; +export const array = (value: unknown): unknown[] => Array.isArray(value) ? value : []; +export const text = (value: unknown): string | null => typeof value === "string" ? value : null; +export const integer = (value: unknown): number | null => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null; const flag = (value: unknown): boolean => value === true; -const LOGIN = /^[A-Za-z0-9-]{1,39}(?:\[bot\])?$/; -const SHA = /^[0-9a-f]{40}$/; +export const LOGIN = /^[A-Za-z0-9-]{1,39}(?:\[bot\])?$/; +export const SHA = /^[0-9a-f]{40}$/; const COLOR = /^[0-9a-fA-F]{6}$/; const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/; -const time = (value: unknown): string | null => typeof value === "string" && ISO.test(value) && !Number.isNaN(Date.parse(value)) ? value : null; -const requiredTime = (value: unknown, fallback: string): string => time(value) ?? fallback; +export const time = (value: unknown): string | null => typeof value === "string" && ISO.test(value) && !Number.isNaN(Date.parse(value)) ? value : null; +export const requiredTime = (value: unknown, fallback: string): string => time(value) ?? fallback; /** Cut at `max` characters without splitting a surrogate pair. */ -function cut(value: string, max: number): { text: string; truncated: boolean } { +export function cut(value: string, max: number): { text: string; truncated: boolean } { if (value.length <= max) return { text: value, truncated: false }; let end = max; const code = value.charCodeAt(end - 1); @@ -79,10 +80,10 @@ function user(value: unknown): GithubUser { const login = text(raw?.login); return { login: login && LOGIN.test(login) ? login : null, is_bot: raw?.type === "Bot" || (login?.endsWith("[bot]") ?? false) }; } -function author(value: unknown, association: unknown): GithubAuthor { +export function author(value: unknown, association: unknown): GithubAuthor { return { ...user(value), author_association: (GITHUB_AUTHOR_ASSOCIATIONS as readonly unknown[]).includes(association) ? association as GithubAuthor["author_association"] : null }; } -function body(value: unknown, max: number) { +export function body(value: unknown, max: number) { const raw = text(value) ?? ""; const { text: kept, truncated } = cut(raw, max); return { body: raw.length ? kept : null, body_length: raw.length, body_truncated: truncated }; @@ -99,7 +100,7 @@ function labels(value: unknown) { const stateReason = (value: unknown) => (["completed", "not_planned", "reopened", "duplicate"] as const).find(reason => reason === value) ?? null; const state = (value: unknown): "open" | "closed" => value === "open" ? "open" : "closed"; -function comment(value: Json, scope: GithubLinkScope, fallback: string): GithubComment | null { +export function comment(value: Json, scope: GithubLinkScope, fallback: string): GithubComment | null { const id = integer(value.id); if (!id) return null; return { id, author: author(value.user, value.author_association), created_at: requiredTime(value.created_at, fallback), @@ -108,7 +109,7 @@ function comment(value: Json, scope: GithubLinkScope, fallback: string): GithubC } const REVIEW_STATES: Record = { APPROVED: "approved", CHANGES_REQUESTED: "changes_requested", COMMENTED: "commented", DISMISSED: "dismissed", PENDING: "pending" }; -function review(value: Json, scope: GithubLinkScope): GithubReview | null { +export function review(value: Json, scope: GithubLinkScope): GithubReview | null { const id = integer(value.id), reviewState = REVIEW_STATES[String(value.state)]; if (!id || !reviewState) return null; return { id, author: author(value.user, value.author_association), state: reviewState, submitted_at: time(value.submitted_at), @@ -132,7 +133,7 @@ export function reviewDecisions(reviews: readonly GithubReview[]): GithubReviewD return [...latest.values()]; } -function commit(value: Json, scope: GithubLinkScope): GithubCommit | null { +export function commit(value: Json, scope: GithubLinkScope): GithubCommit | null { const sha = text(value.sha); if (!sha || !SHA.test(sha)) return null; const detail = record(value.commit), recorded = record(detail?.author); @@ -144,7 +145,7 @@ function commit(value: Json, scope: GithubLinkScope): GithubCommit | null { } /** The `rel="next"` target of a Link header, when GitHub names one. */ -function nextLink(response: Response): string | null { +export function nextLink(response: Response): string | null { const header = response.headers.get("link"); if (!header) return null; for (const part of header.split(",")) { @@ -154,43 +155,58 @@ function nextLink(response: Response): string | null { return null; } -export function createGithubToolsHost(options: GithubToolsHostOptions): GithubToolsHost { - const now = options.now ?? Date.now; - const timeoutMs = options.timeoutMs ?? 20_000; +/** + * When a spent rate limit resets: `x-ratelimit-reset` (epoch seconds), else + * `retry-after` (seconds from now), else unknown. + */ +function rateLimitReset(response: Response, now: () => number): string | null { + const reset = Number(response.headers.get("x-ratelimit-reset")); + if (Number.isSafeInteger(reset) && reset > 0 && reset < 1e11) return new Date(reset * 1000).toISOString(); + const after = Number(response.headers.get("retry-after")); + if (Number.isSafeInteger(after) && after >= 0 && after < 1e7) return new Date(now() + after * 1000).toISOString(); + return null; +} - /** One GET against the fixed API origin. Redirects are followed only within it. */ - async function get(token: string, path: string, signal: AbortSignal | undefined): Promise<{ json: unknown; response: Response }> { - let url = new URL(path, GITHUB_API_ORIGIN); - for (let hop = 0; hop < 4; hop++) { - if (url.origin !== GITHUB_API_ORIGIN) throw new GithubRefusal("upstream_error", "redirect", "GitHub redirected outside its API."); - const timeout = AbortSignal.timeout(timeoutMs); - let response: Response; - try { - response = await (options.fetch ?? fetch)(url, { method: "GET", redirect: "manual", - signal: signal ? AbortSignal.any([signal, timeout]) : timeout, - headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28", "user-agent": "brain-ui" } }); - } catch { - if (signal?.aborted) throw new GithubRefusal("upstream_error", "cancelled", "The turn ended before GitHub answered."); - throw new GithubRefusal("upstream_error", timeout.aborted ? "timeout" : "network", timeout.aborted ? "GitHub did not answer in time." : "GitHub could not be reached."); - } - if (response.status >= 300 && response.status < 400 && response.headers.get("location")) { - url = new URL(response.headers.get("location")!, url); - continue; - } - if (!response.ok) { - const limited = response.headers.get("x-ratelimit-remaining") === "0" || response.status === 429; - if (limited) throw new GithubRefusal("rate_limited", null, "GitHub's rate limit for the host credential is spent; try again later."); - if (response.status === 401) throw new GithubRefusal("unavailable", "credential_rejected", "GitHub rejected the host's GitHub tools credential."); - if (response.status === 404 || response.status === 410) throw new GithubRefusal("not_found", null, "GitHub has no such issue or repository, or the host's credential cannot see it."); - if (response.status === 403) throw new GithubRefusal("forbidden", null, "The host's GitHub credential is not permitted to read this."); - if (response.status === 422) throw new GithubRefusal("invalid_input", "github_validation", "GitHub refused the search."); - throw new GithubRefusal("upstream_error", `http_${response.status}`, `GitHub answered ${response.status}.`); - } - try { return { json: await response.json(), response }; } - catch { throw new GithubRefusal("upstream_error", "malformed", "GitHub returned malformed JSON."); } +/** How a GET reaches the API: the test seam, the clock and one request's limit. */ +export interface GithubTransport { fetch?: typeof fetch; now?: () => number; timeoutMs?: number } + +/** One GET against the fixed API origin with the host credential. Redirects are followed only within it. */ +export async function githubGet(transport: GithubTransport, token: string, path: string, signal: AbortSignal | undefined): Promise<{ json: unknown; response: Response }> { + let url = new URL(path, GITHUB_API_ORIGIN); + for (let hop = 0; hop < 4; hop++) { + if (url.origin !== GITHUB_API_ORIGIN) throw new GithubRefusal("upstream_error", "redirect", "GitHub redirected outside its API."); + const timeout = AbortSignal.timeout(transport.timeoutMs ?? 20_000); + let response: Response; + try { + response = await (transport.fetch ?? fetch)(url, { method: "GET", redirect: "manual", + signal: signal ? AbortSignal.any([signal, timeout]) : timeout, + headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28", "user-agent": "brain-ui" } }); + } catch { + if (signal?.aborted) throw new GithubRefusal("upstream_error", "cancelled", "The turn ended before GitHub answered."); + throw new GithubRefusal("upstream_error", timeout.aborted ? "timeout" : "network", timeout.aborted ? "GitHub did not answer in time." : "GitHub could not be reached."); + } + if (response.status >= 300 && response.status < 400 && response.headers.get("location")) { + url = new URL(response.headers.get("location")!, url); + continue; + } + if (!response.ok) { + const limited = response.headers.get("x-ratelimit-remaining") === "0" || response.status === 429; + if (limited) throw new GithubRefusal("rate_limited", null, "GitHub's rate limit for the host credential is spent; try again later.", rateLimitReset(response, transport.now ?? Date.now)); + if (response.status === 401) throw new GithubRefusal("unavailable", "credential_rejected", "GitHub rejected the host's GitHub tools credential."); + if (response.status === 404 || response.status === 410) throw new GithubRefusal("not_found", null, "GitHub has no such issue or repository, or the host's credential cannot see it."); + if (response.status === 403) throw new GithubRefusal("forbidden", null, "The host's GitHub credential is not permitted to read this."); + if (response.status === 422) throw new GithubRefusal("invalid_input", "github_validation", "GitHub refused the search."); + throw new GithubRefusal("upstream_error", `http_${response.status}`, `GitHub answered ${response.status}.`); } - throw new GithubRefusal("upstream_error", "redirect", "GitHub redirected too many times."); + try { return { json: await response.json(), response }; } + catch { throw new GithubRefusal("upstream_error", "malformed", "GitHub returned malformed JSON."); } } + throw new GithubRefusal("upstream_error", "redirect", "GitHub redirected too many times."); +} + +export function createGithubToolsHost(options: GithubToolsHostOptions): GithubToolsHost { + const now = options.now ?? Date.now; + const get = (token: string, path: string, signal: AbortSignal | undefined) => githubGet(options, token, path, signal); /** A path below the API origin from a `next` link, only when it stays there. */ const relative = (link: string) => { diff --git a/packages/ui-server/src/routes/github-details.ts b/packages/ui-server/src/routes/github-details.ts new file mode 100644 index 0000000000..0b2eb5e2bc --- /dev/null +++ b/packages/ui-server/src/routes/github-details.ts @@ -0,0 +1,102 @@ +import { Hono, type Context } from "hono"; +import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { isGithubDetailPart, isGithubRepositoryName, type GithubDetailError, type GithubErrorCode } from "@schlessera/brain-ui-sdk/tool-contracts"; + +import type { AppEnv } from "../app-env.js"; +import type { Principal } from "../db/principals.js"; +import { GithubDetailInputError, githubSessionScope, type GithubDetails } from "../github/details.js"; +import { GithubRefusal, LOGIN } from "../github/host.js"; + +export interface GithubDetailRouteDeps { + details: GithubDetails; + principalValid: (principal: Principal) => boolean; + /** Whether the caller is the chat's owner account (any of its logins). */ + owns: (principal: Principal, sessionId: string) => boolean; + /** Whether the chat is retired (#3230): it has nothing left to show. */ + retired: (sessionId: string) => boolean; + /** The session's recorded history, as its owning backend replays it. */ + history: (sessionId: string) => Promise; + /** Settles once catalog writes submitted before it have committed. */ + settled?: () => Promise; +} + +const SESSION_ID = /^[A-Za-z0-9._:-]{1,256}$/; +const STATUS: Partial> = { + invalid_input: 400, forbidden: 403, not_found: 404, rate_limited: 429, unavailable: 503, upstream_error: 502, +}; + +function refuse(c: Context, code: GithubErrorCode, reason: string | null, message: string, resetAt: string | null = null) { + const error: GithubDetailError = { code, reason, message, reset_at: resetAt }; + if (code === "rate_limited" && resetAt) c.header("Retry-After", String(Math.max(0, Math.ceil((Date.parse(resetAt) - Date.now()) / 1000)))); + return c.json({ error }, STATUS[code] ?? 502); +} + +/** + * The on-demand GitHub detail pages and the avatar proxy (#3796), internal + * routes for the chat components. Owner-authenticated, read-only and never + * provider context: a response is not added to the conversation, not + * journaled as turn input, and does not taint the session. + * + * - `GET /sessions/:id/github/:owner/:repo/:number/:part?cursor=` pages one + * part of an object a GitHub tool result in that session returned. + * - `GET /sessions/:id/github/avatars/:login?size=` serves the avatar of a + * login in those results from this origin; every failure is a bare 404. + */ +export function createGithubDetailRoutes(deps: GithubDetailRouteDeps): Hono { + /** Authentication, then ownership, then the chat's recorded scope; null when it may be read. */ + async function admit(c: Context, sessionId: string) { + const principal = c.get("principal"); + if (!principal || !deps.principalValid(principal)) return { refusal: c.json({ error: "Authentication required", authRequired: true }, 401) }; + if (!SESSION_ID.test(sessionId)) return { refusal: refuse(c, "invalid_input", "session", "That is not a session id.") }; + await deps.settled?.(); + if (!deps.owns(principal, sessionId)) return { refusal: refuse(c, "forbidden", "not_owner", "Only the chat's owner can read its GitHub details.") }; + if (deps.retired(sessionId)) return { refusal: refuse(c, "not_found", "not_in_session", "This host has no such session.") }; + let history: SessionHistoryMessage[]; + try { history = await deps.history(sessionId); } + catch { return { refusal: refuse(c, "not_found", "not_in_session", "This session's history could not be read.") }; } + if (!deps.principalValid(principal)) return { refusal: c.json({ error: "Authentication required", authRequired: true }, 401) }; + return { refusal: null, principal, scope: githubSessionScope(history) }; + } + + return new Hono() + .get("/sessions/:id/github/avatars/:login", async (c) => { + const notFound = () => { c.header("Cache-Control", "no-store"); return c.body(null, 404); }; + const sessionId = c.req.param("id"), login = c.req.param("login"); + const rawSize = c.req.query("size") ?? "64"; + if (!LOGIN.test(login) || !/^[1-9][0-9]{0,3}$/.test(rawSize)) return notFound(); + const admitted = await admit(c, sessionId); + if (admitted.refusal) return admitted.refusal.status === 401 ? admitted.refusal : notFound(); + const lower = login.toLowerCase(); + if (!admitted.scope.logins.has(lower) && !deps.details.servedLogin(sessionId, lower)) return notFound(); + const image = await deps.details.avatar(login, Number(rawSize), c.req.raw.signal); + if (!image || !deps.principalValid(admitted.principal)) return notFound(); + return new Response(image.bytes, { status: 200, headers: { + "Content-Type": image.type, "Content-Length": String(image.bytes.byteLength), "X-Content-Type-Options": "nosniff", + "Content-Security-Policy": "default-src 'none'; sandbox", "Cache-Control": "private, max-age=3600", + } }); + }) + .get("/sessions/:id/github/:owner/:repo/:number/:part", async (c) => { + c.header("Cache-Control", "no-store"); + const sessionId = c.req.param("id"), owner = c.req.param("owner"), repo = c.req.param("repo"); + const rawNumber = c.req.param("number"), part = c.req.param("part"), cursor = c.req.query("cursor") ?? null; + if (!isGithubDetailPart(part)) return refuse(c, "invalid_input", "part", "That part is not one of comments, reviews, review-comments, commits, files or checks."); + if (!isGithubRepositoryName(owner, repo) || !/^[1-9][0-9]{0,9}$/.test(rawNumber) || Number(rawNumber) > 2_147_483_647) + return refuse(c, "invalid_input", "object", "That is not a GitHub issue or pull request."); + if (cursor !== null && cursor.length > 64) return refuse(c, "invalid_input", "cursor", "The cursor is not one this host issued."); + const admitted = await admit(c, sessionId); + if (admitted.refusal) return admitted.refusal; + // Bounded authority: only an object this session's GitHub results returned. + const object = admitted.scope.objects.get(`${owner.toLowerCase()}/${repo.toLowerCase()}#${Number(rawNumber)}`); + if (!object) return refuse(c, "not_found", "not_in_session", "No GitHub result in this session returned that issue or pull request."); + try { + const page = await deps.details.page(sessionId, object, part, cursor, c.req.raw.signal); + if (!deps.principalValid(admitted.principal)) return c.json({ error: "Authentication required", authRequired: true }, 401); + return c.json(page); + } catch (error) { + if (error instanceof GithubDetailInputError) + return error.reason === "not_pull_request" ? refuse(c, "not_found", error.reason, error.message) : refuse(c, "invalid_input", error.reason, error.message); + if (error instanceof GithubRefusal) return refuse(c, error.code, error.reason ?? "github", error.message, error.resetAt); + return refuse(c, "upstream_error", null, "The GitHub read failed."); + } + }); +} diff --git a/packages/ui-server/tests/fixtures/github-host-fixture.ts b/packages/ui-server/tests/fixtures/github-host-fixture.ts index 2c5fbab6d0..2068c3f159 100644 --- a/packages/ui-server/tests/fixtures/github-host-fixture.ts +++ b/packages/ui-server/tests/fixtures/github-host-fixture.ts @@ -72,7 +72,9 @@ export function fakeGithub(options: FakeGithubOptions = {}): FakeGithub { case "/repos/odysseus/ithaca/issues/8": return json(pullIssue); case "/repos/odysseus/ithaca/issues/7/comments": { const all = Array.from({ length: commentCount }, (_, index) => issueComment(7, 9000 + index, "issues")); - return json(all.slice((page - 1) * perPage, page * perPage)); + // GitHub names the next page in a Link header. + return json(all.slice((page - 1) * perPage, page * perPage), page * perPage < commentCount + ? { headers: { link: `<${API}/issues/7/comments?per_page=${perPage}&page=${page + 1}>; rel="next"` } } : undefined); } case "/repos/odysseus/ithaca/issues/8/comments": return json([issueComment(8, 9101, "pull")]); case "/repos/odysseus/ithaca/pulls/8": return json(pull); diff --git a/packages/ui-server/tests/github-details.test.ts b/packages/ui-server/tests/github-details.test.ts new file mode 100644 index 0000000000..2c776a89c9 --- /dev/null +++ b/packages/ui-server/tests/github-details.test.ts @@ -0,0 +1,388 @@ +/** + * The GitHub detail pages and avatar proxy (#3796) against loopback stand-ins + * for the GitHub API and the avatar host: only an object a GitHub tool result + * in the session returned, only for the chat's owner, only the fixed parts, + * pages in the tools' contract types bounded to the page size, direct links + * that pass the validator or are null, typed failures, and avatars judged by + * their bytes, sent no credential and cached within a bound. + * + * Keyless and offline: both stand-ins listen on loopback after the network + * preload; the token is a synthetic sentinel. + */ +import { afterEach, describe, expect, test } from "bun:test"; +import { Hono } from "hono"; +import { GITHUB_DETAIL_ERROR_RESPONSE_SCHEMA, GITHUB_DETAIL_PAGE_SCHEMA, type GithubDetailPage, type GithubIssue, type GithubToolResult } from "@schlessera/brain-ui-sdk/tool-contracts"; +import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +import type { AppEnv } from "../src/app-env.js"; +import type { Principal } from "../src/db/principals.js"; +import { createGithubDetails, githubSessionScope, sniffImage, type GithubDetailsOptions } from "../src/github/details.js"; +import { createGithubToolsHost } from "../src/github/host.js"; +import { createGithubDetailRoutes, type GithubDetailRouteDeps } from "../src/routes/github-details.js"; +import { COMMIT_SHAS, GITHUB_TOOLS_SENTINEL, fakeGithub, standInFetch, type FakeGithub, type FakeGithubOptions } from "./fixtures/github-host-fixture.js"; + +const SESSION = "sess-ithaca-details"; +const OTHER = "sess-aiaia"; +const NOW = Date.parse("2026-07-12T12:00:00Z"); +const WEB = "https://github.com/odysseus/ithaca"; +const owner = { id: "principal-penelope", kind: "owner" } as Principal; +const stranger = { id: "principal-suitor", kind: "agent" } as Principal; + +const stops: Array<{ stop(): void }> = []; +afterEach(() => { for (const fake of stops.splice(0)) fake.stop(); }); + +// ------------------------------------------------------------ stand-ins + +/** A PNG header naming `width` x `height`, padded to `bytes`. */ +function png(width: number, height: number, bytes = 64): Uint8Array { + const out = new Uint8Array(Math.max(bytes, 33)); + out.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52]); + new DataView(out.buffer).setUint32(16, width); + new DataView(out.buffer).setUint32(20, height); + out.set([8, 6, 0, 0, 0], 24); + return out; +} + +interface FakeAvatars { origin: string; seen: Array<{ path: string; search: string; authorization: string | null; cookie: string | null }>; stop(): void } +function fakeAvatars(): FakeAvatars { + const seen: FakeAvatars["seen"] = []; + const asPng = (body: BodyInit) => new Response(body, { headers: { "content-type": "image/png" } }); + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch(request) { + const url = new URL(request.url); + seen.push({ path: url.pathname, search: url.search, authorization: request.headers.get("authorization"), cookie: request.headers.get("cookie") }); + switch (url.pathname) { + case "/penelope": case "/telemachus": case "/herald%5Bbot%5D": case "/eumaeus": return asPng(png(64, 64)); + // Labelled PNG, but not one by its bytes. + case "/circe": return asPng(''); + case "/siren": return asPng("Come closer"); + // Over the byte cap, and over the pixel cap. + case "/cyclops": return asPng(png(64, 64, 600 * 1024)); + case "/polyphemus": return asPng(png(4096, 4096)); + default: return new Response("Not Found", { status: 404 }); + } + } }); + const result = { origin: `http://127.0.0.1:${server.port}`, seen, stop: () => { void server.stop(true); } }; + stops.push(result); + return result; +} +function avatarFetch(fake: Pick): typeof fetch { + return ((input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + if (url.origin !== "https://avatars.githubusercontent.com") throw new Error(`avatar left its host: ${url.href}`); + return fetch(new URL(`${url.pathname}${url.search}`, fake.origin), init); + }) as typeof fetch; +} + +const comment = (id: number, html_url: string) => ({ id, html_url, user: { login: "eumaeus", type: "User" }, author_association: "CONTRIBUTOR", + body: `Comment ${id}: the swineherd keeps watch.`, created_at: "2026-07-03T09:00:00Z", updated_at: "2026-07-03T09:00:00Z" }); +const linked = (body: unknown, next: boolean) => Response.json(body, next ? { headers: { link: '; rel="next"' } } : undefined); + +/** + * The standard stand-in, then, once the tool results are recorded (`detail` + * set), the detail endpoints and the test's own overrides. + */ +function github(options: FakeGithubOptions & { comments?: number } = {}): FakeGithub & { detail: boolean } { + const total = options.comments ?? 45; + const state = { detail: false }; + const fake = fakeGithub({ ...options, comments: undefined, override: (path, search) => { + if (!state.detail) return undefined; + const custom = options.override?.(path, search); + if (custom) return custom; + const page = Number(search.get("page") ?? "1"), perPage = Number(search.get("per_page") ?? "30"); + if (path === "/repos/odysseus/ithaca/issues/7/comments") { + const all = Array.from({ length: total }, (_, index) => comment(9000 + index, `${WEB}/issues/7#issuecomment-${9000 + index}`)); + return linked(all.slice((page - 1) * perPage, page * perPage), page * perPage < total); + } + if (path === "/repos/odysseus/ithaca/pulls/8/commits") { + // Ignores per_page on purpose: the host still returns at most a page. + const shas = Array.from({ length: 40 }, (_, index) => String(index).padStart(40, "0")); + const all = shas.map(sha => ({ sha, html_url: `${WEB}/commit/${sha}`, author: { login: "telemachus", type: "User" }, + commit: { message: `Wax ${sha.slice(-2)}`, author: { name: "Telemachus", date: "2026-07-04T09:00:00Z" } } })); + return linked(page === 1 ? all : all.slice(30 * (page - 1), 30 * page), page === 1); + } + if (path === "/repos/odysseus/ithaca/pulls/8/comments") return Response.json([ + { id: 801, pull_request_review_id: 501, in_reply_to_id: null, user: { login: "penelope", type: "User" }, author_association: "OWNER", path: "bow/string.ts", line: 12, + body: "Tighter.", created_at: "2026-07-05T09:00:00Z", updated_at: "2026-07-05T09:00:00Z", html_url: `${WEB}/pull/8#discussion_r801` }, + { id: 802, pull_request_review_id: null, in_reply_to_id: 801, user: { login: "telemachus", type: "User" }, author_association: "COLLABORATOR", path: "bow/string.ts", line: null, + body: "Done.", created_at: "2026-07-05T10:00:00Z", updated_at: "2026-07-05T10:00:00Z", html_url: `${WEB}/pull/8#discussion_r999` }, + ]); + if (path === "/repos/odysseus/ithaca/pulls/8/files") return Response.json([ + { filename: "bow/string.ts", status: "modified", additions: 100, deletions: 7, changes: 107, patch: "@@ the diff never leaves @@" }, + { filename: "bow/wax.ts", previous_filename: "bow/tallow.ts", status: "renamed", additions: 20, deletions: 0, changes: 20 }, + ]); + return undefined; + } }); + stops.push(fake); + return Object.defineProperty(fake, "detail", { get: () => state.detail, set: (value: boolean) => { state.detail = value; } }) as FakeGithub & { detail: boolean }; +} + +// ------------------------------------------------------------- history + +/** What the real host's tools returned, as the session's history records it. */ +async function toolResults(fake: FakeGithub): Promise { + const host = createGithubToolsHost({ token: () => GITHUB_TOOLS_SENTINEL, fetch: standInFetch(fake), now: () => NOW, untrusted: async () => {} }); + const turn = { turnId: "turn-ithaca", principalId: owner.id, sessionId: () => SESSION }; + const results = [ + await host.call(turn, { tool: "brain_github_issue_read", input: { repository: "odysseus/ithaca", number: 7 } }), + await host.call(turn, { tool: "brain_github_issue_read", input: { repository: "odysseus/ithaca", number: 8 } }), + ]; + for (const result of results) if (!result.ok) throw new Error(JSON.stringify(result)); + return results; +} +function history(results: GithubToolResult[], names: string[] = results.map(() => "mcp__brain-ui__brain_github_issue_read")): SessionHistoryMessage[] { + return [{ role: "user", content: "Look up the suitors", toolCalls: [] }, + { role: "assistant", content: "", toolCalls: results.map((result, index) => ({ id: `call-${index}`, name: names[index]!, input: {}, output: JSON.stringify(result), isError: !result.ok })) }]; +} + +/** A read of #7 whose comment authors are the avatar cases. */ +function avatarResult(base: GithubToolResult): GithubToolResult { + const issue = structuredClone((base as Extract).result) as GithubIssue; + issue.comments.items = ["circe", "siren", "cyclops", "polyphemus", "telemachus"].map((login, index) => ({ ...issue.comments.items[0]!, id: 7000 + index, + html_url: null, author: { login, is_bot: false, author_association: "NONE" } })); + return { ok: true, tool: "brain_github_issue_read", result: issue }; +} + +// ---------------------------------------------------------------- app + +interface Harness { + fake: FakeGithub & { detail: boolean }; + avatars: FakeAvatars; + details: ReturnType; + get(path: string, as?: Principal): Promise; + json(path: string, as?: Principal): Promise<{ status: number; body: T }>; + histories: Record; +} + +async function harness(options: { github?: FakeGithubOptions & { comments?: number }; details?: Partial; routes?: Partial; } = {}): Promise { + const fake = github(options.github), avatars = fakeAvatars(); + const results = await toolResults(fake); + fake.detail = true; + const histories: Record = { [SESSION]: history([...results, avatarResult(results[0]!)]), [OTHER]: [] }; + const details = createGithubDetails({ token: () => GITHUB_TOOLS_SENTINEL, fetch: standInFetch(fake), avatarFetch: avatarFetch(avatars), now: () => NOW, ...options.details }); + const app = new Hono(); + const principals: Record = { [owner.id]: owner, [stranger.id]: stranger }; + app.use("*", async (c, next) => { const id = c.req.header("x-principal"); if (id && principals[id]) c.set("principal", principals[id]); await next(); }); + app.route("/api", createGithubDetailRoutes({ details, principalValid: () => true, + owns: (principal, sessionId) => principal.kind === "owner" && sessionId in histories, + retired: () => false, history: async sessionId => histories[sessionId] ?? [], ...options.routes })); + const get = (path: string, as: Principal = owner) => Promise.resolve(app.fetch(new Request(`http://localhost/api${path}`, { headers: { "x-principal": as.id } }))); + return { fake, avatars, details, histories, get, + async json(path: string, as?: Principal) { const response = await get(path, as); return { status: response.status, body: await response.json() as T }; } }; +} + +const pageOf = (body: unknown) => GITHUB_DETAIL_PAGE_SCHEMA.parse(body); +const errorOf = (body: unknown) => GITHUB_DETAIL_ERROR_RESPONSE_SCHEMA.parse(body).error; +const detailPath = (number: number, part: string, cursor?: string) => `/sessions/${SESSION}/github/odysseus/ithaca/${number}/${part}${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ""}`; +const detailRequests = (fake: FakeGithub) => fake.seen.filter(request => /\/(comments|commits|reviews|files|check-runs|status)$/.test(request.path) || request.path.endsWith("/pulls/8")); + +// --------------------------------------------------------------- tests + +describe("paging an object the session returned", () => { + test("the owner pages an issue's comments with cursors, each page bounded and in the contract's types", async () => { + const t = await harness(); + t.fake.seen.length = 0; + const first = await t.json(detailPath(7, "comments")); + expect(first.status, JSON.stringify(first.body)).toBe(200); + const one = pageOf(first.body) as Extract; + expect(one, "GITHUB_DETAIL_COMMENTS_PAGE_ONE").toMatchObject({ kind: "detail_page", repository: "odysseus/ithaca", number: 7, part: "comments", next_cursor: "2", total_count: null }); + expect(one.items.map(item => item.id)).toEqual(Array.from({ length: 30 }, (_, index) => 9000 + index)); + expect(one.items[0]).toMatchObject({ author: { login: "eumaeus", is_bot: false, author_association: "CONTRIBUTOR" }, html_url: `${WEB}/issues/7#issuecomment-9000` }); + const second = pageOf((await t.json(detailPath(7, "comments", one.next_cursor!))).body) as Extract; + expect(second.items.map(item => item.id), "GITHUB_DETAIL_COMMENTS_PAGE_TWO").toEqual(Array.from({ length: 15 }, (_, index) => 9030 + index)); + expect(second.next_cursor, "GITHUB_DETAIL_LAST_PAGE").toBeNull(); + const asked = t.fake.seen.filter(request => request.path.endsWith("/comments")); + expect(asked.map(request => request.search), "GITHUB_DETAIL_PAGE_SIZE_ASKED").toEqual(["?per_page=30&page=1", "?per_page=30&page=2"]); + for (const request of t.fake.seen) expect(request.authorization, "GITHUB_DETAIL_DEDICATED_CREDENTIAL").toBe(`Bearer ${GITHUB_TOOLS_SENTINEL}`); + }); + + test("a pull request's commits page with cursors, and an upstream page larger than asked is cut to the bound", async () => { + const t = await harness(); + const one = pageOf((await t.json(detailPath(8, "commits"))).body) as Extract; + expect(one.items.length, "GITHUB_DETAIL_PAGE_SIZE_BOUND").toBe(30); + expect(one.next_cursor).toBe("2"); + expect(one.items[0]).toMatchObject({ author: { login: "telemachus" }, author_name: "Telemachus", message: "Wax 00" }); + expect(new Set(one.items.map(item => item.sha)).size).toBe(30); + const two = pageOf((await t.json(detailPath(8, "commits", "2"))).body) as Extract; + expect(two.items.length, "GITHUB_DETAIL_COMMITS_PAGE_TWO").toBe(10); + expect(two.next_cursor).toBeNull(); + }); + + test("reviews, review comments, files and checks each page in their own types; files carry no diff", async () => { + const t = await harness(); + const reviews = pageOf((await t.json(detailPath(8, "reviews"))).body) as Extract; + expect(reviews.items.map(item => [item.id, item.state])).toEqual([[501, "approved"], [502, "commented"], [503, "changes_requested"], [504, "dismissed"]]); + const files = (await t.json(detailPath(8, "files"))).body; + expect(JSON.stringify(files), "GITHUB_DETAIL_FILES_SUMMARY_ONLY").not.toContain("the diff never leaves"); + expect((pageOf(files) as Extract).items).toEqual([ + { filename: "bow/string.ts", previous_filename: null, status: "modified", additions: 100, deletions: 7, changes: 107 }, + { filename: "bow/wax.ts", previous_filename: "bow/tallow.ts", status: "renamed", additions: 20, deletions: 0, changes: 20 }]); + const runs = pageOf((await t.json(detailPath(8, "checks"))).body) as Extract; + expect(runs.items.map(item => item.state), "GITHUB_DETAIL_CHECK_RUNS").toEqual(["passed", "failed", "running", "skipped"]); + expect(runs.next_cursor).toBe("statuses:1"); + const statuses = pageOf((await t.json(detailPath(8, "checks", "statuses:1"))).body) as Extract; + expect(statuses.items, "GITHUB_DETAIL_COMMIT_STATUSES").toEqual([{ source: "status", name: "", state: "passed", conclusion: "success", started_at: null, completed_at: null }]); + expect(statuses.next_cursor).toBeNull(); + }); +}); + +describe("refusals", () => { + test("an object no GitHub result in the session returned is 404 and nothing is sent", async () => { + const t = await harness(); + t.fake.seen.length = 0; + // #7 is real and readable: only the other session returned it. + for (const path of [`/sessions/${OTHER}/github/odysseus/ithaca/7/comments`, `/sessions/${SESSION}/github/odysseus/ithaca/9/comments`, `/sessions/${SESSION}/github/circe/aiaia/7/comments`]) { + const refused = await t.json(path); + expect(refused.status, `GITHUB_DETAIL_NOT_IN_SESSION ${path}`).toBe(404); + expect(errorOf(refused.body), `GITHUB_DETAIL_NOT_IN_SESSION_REASON ${path}`).toMatchObject({ code: "not_found", reason: "not_in_session" }); + } + expect(detailRequests(t.fake), "GITHUB_DETAIL_NOTHING_SENT_OUTSIDE_SESSION").toEqual([]); + }); + + test("a session the caller does not own is 403, and a part outside the fixed set is 400", async () => { + const t = await harness(); + t.fake.seen.length = 0; + const foreign = await t.json(detailPath(7, "comments"), stranger); + expect(foreign.status, "GITHUB_DETAIL_NOT_OWNER").toBe(403); + expect(errorOf(foreign.body)).toMatchObject({ code: "forbidden", reason: "not_owner" }); + for (const part of ["timeline", "events", "diff", "COMMENTS"]) { + const refused = await t.json(detailPath(7, part)); + expect(refused.status, `GITHUB_DETAIL_PART_REFUSED ${part}`).toBe(400); + expect(errorOf(refused.body)).toMatchObject({ code: "invalid_input", reason: "part" }); + } + for (const cursor of ["0", "abc", "runs:1", "../2"]) expect((await t.get(detailPath(7, "comments", cursor))).status, `GITHUB_DETAIL_CURSOR_REFUSED ${cursor}`).toBe(400); + expect((await t.get(detailPath(7, "commits"))).status, "GITHUB_DETAIL_ISSUE_HAS_NO_COMMITS").toBe(404); + expect((await t.get("/sessions/sess-ithaca-details/github/odysseus/ithaca/7/comments", { id: "nobody" } as Principal)).status, "GITHUB_DETAIL_AUTH").toBe(401); + expect(detailRequests(t.fake)).toEqual([]); + }); + + test("without the credential the route answers unavailable, and a spent rate limit names its reset time", async () => { + const t = await harness({ details: { token: () => undefined } }); + t.fake.seen.length = 0; + const missing = await t.json(detailPath(7, "comments")); + expect(missing.status).toBe(503); + expect(errorOf(missing.body), "GITHUB_DETAIL_NO_CREDENTIAL").toMatchObject({ code: "unavailable", reason: "no_credential", reset_at: null }); + expect(t.fake.seen).toEqual([]); + + const reset = Math.floor(NOW / 1000) + 600; + const limited = await harness({ github: { override: path => path.endsWith("/comments") + ? Response.json({ message: "API rate limit exceeded" }, { status: 403, headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) } }) : undefined } }); + const response = await limited.get(detailPath(7, "comments")); + expect(response.status).toBe(429); + expect(response.headers.get("retry-after")).not.toBeNull(); + expect(errorOf(await response.json()), "GITHUB_DETAIL_RATE_LIMIT_RESET").toEqual({ code: "rate_limited", reason: "github", + message: "GitHub's rate limit for the host credential is spent; try again later.", reset_at: new Date(reset * 1000).toISOString() }); + }); + + test("access revoked upstream and an upstream failure are distinct typed errors", async () => { + const revoked = await harness({ github: { override: path => path.endsWith("/comments") ? Response.json({ message: "Not Found" }, { status: 404 }) : undefined } }); + const gone = await revoked.json(detailPath(7, "comments")); + expect([gone.status, errorOf(gone.body).code, errorOf(gone.body).reason], "GITHUB_DETAIL_UPSTREAM_NOT_FOUND").toEqual([404, "not_found", "github"]); + const broken = await harness({ github: { override: path => path.endsWith("/comments") ? new Response("down", { status: 503 }) : undefined } }); + const failed = await broken.json(detailPath(7, "comments")); + expect([failed.status, errorOf(failed.body).code, errorOf(failed.body).reason], "GITHUB_DETAIL_UPSTREAM_ERROR").toEqual([502, "upstream_error", "http_503"]); + }); +}); + +describe("direct links", () => { + test("a page item whose upstream html_url fails the validator is returned with null, a conforming one unchanged", async () => { + const t = await harness({ github: { override: path => { + if (path !== "/repos/odysseus/ithaca/issues/7/comments") return undefined; + return Response.json([ + comment(1, `${WEB}/issues/7#issuecomment-1`), + comment(2, "https://github.com.evil.example/odysseus/ithaca/issues/7#issuecomment-2"), + comment(3, "https://github.com/circe/aiaia/issues/7#issuecomment-3"), + comment(4, `${WEB}/issues/8#issuecomment-4`), + comment(5, `${WEB}/issues/7#issuecomment-55`), + comment(6, "http://github.com/odysseus/ithaca/issues/7#issuecomment-6"), + ]); + } } }); + const page = pageOf((await t.json(detailPath(7, "comments"))).body) as Extract; + expect(page.items.map(item => [item.id, item.html_url]), "GITHUB_DETAIL_LINKS_VALIDATED").toEqual([ + [1, `${WEB}/issues/7#issuecomment-1`], [2, null], [3, null], [4, null], [5, null], [6, null]]); + const reviews = pageOf((await t.json(detailPath(8, "reviews"))).body) as Extract; + expect(reviews.items.find(item => item.id === 504)!.html_url, "GITHUB_DETAIL_REVIEW_OTHER_HOST").toBeNull(); + expect(reviews.items.find(item => item.id === 501)!.html_url).toBe(`${WEB}/pull/8#pullrequestreview-501`); + const comments = pageOf((await t.json(detailPath(8, "review-comments"))).body) as Extract; + expect(comments.items.map(item => [item.id, item.html_url]), "GITHUB_DETAIL_REVIEW_COMMENT_ID_MISMATCH").toEqual([[801, `${WEB}/pull/8#discussion_r801`], [802, null]]); + expect(comments.items[1]).toMatchObject({ review_id: null, in_reply_to_id: 801, line: null, path: "bow/string.ts" }); + }); + + test("a commit whose html_url names another sha is null", async () => { + const t = await harness({ github: { override: path => path === "/repos/odysseus/ithaca/pulls/8/commits" ? Response.json([ + { sha: COMMIT_SHAS[0], html_url: `${WEB}/commit/${COMMIT_SHAS[0]}`, author: null, commit: { message: "Wax", author: { name: "Telemachus", date: "2026-07-04T09:00:00Z" } } }, + { sha: COMMIT_SHAS[1], html_url: `${WEB}/commit/${COMMIT_SHAS[0]}`, author: null, commit: { message: "Wax", author: { name: "Telemachus", date: "2026-07-04T09:00:00Z" } } }, + ]) : undefined } }); + const page = pageOf((await t.json(detailPath(8, "commits"))).body) as Extract; + expect(page.items.map(item => item.html_url), "GITHUB_DETAIL_COMMIT_SHA_MISMATCH").toEqual([`${WEB}/commit/${COMMIT_SHAS[0]}`, null]); + }); +}); + +describe("the session's GitHub scope", () => { + test("is read from the tools' own successful results under either backend's name, and nothing else", async () => { + const fake = github(), results = await toolResults(fake); + const scope = githubSessionScope(history(results, ["brain_github_issue_read", "mcp__brain-ui__brain_github_issue_read"])); + expect([...scope.objects.keys()].sort(), "GITHUB_SCOPE_BOTH_NAMES").toEqual(["odysseus/ithaca#7", "odysseus/ithaca#8"]); + expect(scope.objects.get("odysseus/ithaca#8")!.pullRequest).toBe(true); + expect([...scope.logins].sort(), "GITHUB_SCOPE_LOGINS").toEqual(["herald[bot]", "penelope", "telemachus"]); + const refused: GithubToolResult = { ok: false, tool: "brain_github_issue_read", error: { code: "not_found", reason: null, message: "No." } }; + const forged = history(results, ["WebFetch", "mcp__other__brain_github_issue_read"]); + expect(githubSessionScope([...forged, ...history([refused])]).objects.size, "GITHUB_SCOPE_ONLY_TOOL_RESULTS").toBe(0); + }); +}); + +describe("the avatar proxy", () => { + test("serves a login in the session's results from this origin, judged by its bytes, cached, and with no credential upstream", async () => { + const t = await harness(); + const first = await t.get(`/sessions/${SESSION}/github/avatars/penelope?size=40`); + expect(first.status, "GITHUB_AVATAR_SERVED").toBe(200); + expect(first.headers.get("content-type")).toBe("image/png"); + expect(first.headers.get("x-content-type-options"), "GITHUB_AVATAR_NOSNIFF").toBe("nosniff"); + expect(new Uint8Array(await first.arrayBuffer())).toEqual(png(64, 64)); + expect((await t.get(`/sessions/${SESSION}/github/avatars/Penelope?size=64`)).status, "GITHUB_AVATAR_CACHED").toBe(200); + expect(t.avatars.seen, "GITHUB_AVATAR_ONE_FETCH").toEqual([{ path: "/penelope", search: "?size=64", authorization: null, cookie: null }]); + expect((await t.get(`/sessions/${SESSION}/github/avatars/herald[bot]`)).status, "GITHUB_AVATAR_BOT").toBe(200); + for (const request of t.avatars.seen) expect([request.authorization, request.cookie], "GITHUB_AVATAR_NO_CREDENTIAL").toEqual([null, null]); + }); + + test("a login not in the session's results, another owner and every refused image are 404", async () => { + const t = await harness(); + for (const login of ["circe", "siren", "cyclops", "polyphemus"]) { + const response = await t.get(`/sessions/${SESSION}/github/avatars/${login}`); + expect(response.status, `GITHUB_AVATAR_REFUSED ${login}`).toBe(404); + expect(await response.text()).toBe(""); + } + expect(t.details.avatarCache().entries, "GITHUB_AVATAR_REFUSED_NOT_CACHED").toBe(0); + t.avatars.seen.length = 0; + expect((await t.get(`/sessions/${SESSION}/github/avatars/athena`)).status, "GITHUB_AVATAR_NOT_IN_SESSION").toBe(404); + expect((await t.get(`/sessions/${OTHER}/github/avatars/penelope`)).status, "GITHUB_AVATAR_OTHER_SESSION").toBe(404); + expect((await t.get(`/sessions/${SESSION}/github/avatars/penelope`, stranger)).status, "GITHUB_AVATAR_NOT_OWNER").toBe(404); + expect(t.avatars.seen, "GITHUB_AVATAR_NOTHING_FETCHED_OUTSIDE_SESSION").toEqual([]); + }); + + test("a login first seen in a served detail page gets its avatar", async () => { + const t = await harness(); + expect((await t.get(`/sessions/${SESSION}/github/avatars/eumaeus`)).status).toBe(404); + expect((await t.get(detailPath(7, "comments"))).status).toBe(200); + expect((await t.get(`/sessions/${SESSION}/github/avatars/eumaeus`)).status, "GITHUB_AVATAR_FROM_DETAIL_PAGE").toBe(200); + }); + + test("a full cache evicts its oldest entry and never grows", async () => { + const t = await harness({ details: { avatarLimits: { entries: 2 } } }); + for (const login of ["penelope", "telemachus", "herald[bot]"]) expect((await t.get(`/sessions/${SESSION}/github/avatars/${encodeURIComponent(login)}`)).status).toBe(200); + expect(t.details.avatarCache(), "GITHUB_AVATAR_CACHE_BOUNDED").toEqual({ entries: 2, bytes: 2 * png(64, 64).byteLength }); + t.avatars.seen.length = 0; + expect((await t.get(`/sessions/${SESSION}/github/avatars/herald%5Bbot%5D`)).status).toBe(200); + expect(t.avatars.seen, "GITHUB_AVATAR_NEWEST_KEPT").toEqual([]); + expect((await t.get(`/sessions/${SESSION}/github/avatars/penelope`)).status).toBe(200); + expect(t.avatars.seen.map(request => request.path), "GITHUB_AVATAR_OLDEST_EVICTED").toEqual(["/penelope"]); + expect(t.details.avatarCache().entries).toBe(2); + }); + + test("the byte sniffer knows the four allowed formats and nothing else", () => { + const gif = new Uint8Array([...new TextEncoder().encode("GIF89a"), 32, 0, 16, 0]); + const jpeg = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0, 4, 0, 0, 0xff, 0xc0, 0, 17, 8, 0, 48, 0, 40, 3, 0, 0, 0, 0]); + const webp = new Uint8Array(30); webp.set(new TextEncoder().encode("RIFF"), 0); webp.set(new TextEncoder().encode("WEBPVP8X"), 8); webp.set([39, 0, 0, 19, 0, 0], 24); + expect([sniffImage(png(64, 32)), sniffImage(gif), sniffImage(jpeg), sniffImage(webp)]).toEqual([ + { type: "image/png", width: 64, height: 32 }, { type: "image/gif", width: 32, height: 16 }, { type: "image/jpeg", width: 40, height: 48 }, { type: "image/webp", width: 40, height: 20 }]); + for (const text of ["", "", "BM6", "%PDF-1.7"]) expect(sniffImage(new TextEncoder().encode(text.padEnd(40, " ")))).toBeNull(); + }); +}); diff --git a/packages/ui-server/tests/ws-github-details.test.ts b/packages/ui-server/tests/ws-github-details.test.ts new file mode 100644 index 0000000000..ede10ab9df --- /dev/null +++ b/packages/ui-server/tests/ws-github-details.test.ts @@ -0,0 +1,130 @@ +/** + * The GitHub detail pages through the real app (#3796): createApp mounts the + * route with the tools' dedicated credential; the chat's owner account reads + * an object its turn's GitHub tool returned, a delegated agent does not; and + * any number of detail reads leave the session as they found it: no taint, + * nothing recorded on the host for the conversation, and the next turn's + * request to the backend the same as a session's that read nothing. + * + * Keyless and offline: the fixed API origin is routed to a loopback fake + * after the network preload; the token is a synthetic sentinel. + */ +import { installFixtureNativeStartupViews } from "./helpers/fixture-native-startup.js"; +installFixtureNativeStartupViews(); +import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; +import { expect, test } from "bun:test"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { resolve } from "node:path"; +import { generateSignedCookie } from "hono/cookie"; +import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +import type { StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import { GITHUB_DETAIL_PAGE_SCHEMA } from "@schlessera/brain-ui-sdk/tool-contracts"; +import { createFixtureBrain } from "../../../scripts/captures/core-fixture.js"; +import { createApp } from "../src/app.js"; +import { resolveServerConfig } from "../src/config/env.js"; +import { createStaticBackendRegistry } from "../src/agent/backend.js"; +import { createRecordingObservability } from "../src/observability/index.js"; +import { createWsHandlers } from "../src/ws/connection.js"; +import type { WSContext } from "../src/ws/clients.js"; +import { makeFakeBackend } from "./helpers/fake-backend.js"; +import { createPrincipal, type Principal } from "../src/db/principals.js"; +import { queryGovernanceEvents } from "../src/governance/events.js"; +import { GITHUB_TOOLS_SENTINEL, fakeGithub, routeGithubApi } from "./fixtures/github-host-fixture.js"; + +const SECRET = "odysseus-github-details-cookie-secret-0123"; + +test("the owner account pages a turn's GitHub object; detail reads leave the session's history, taint and next turn unchanged", async () => { + const root = await mkdtemp(resolve(tmpdir(), "odysseus-github-details-")), brain = resolve(root, "brain"); + await createFixtureBrain(resolve(import.meta.dir, "../../.."), brain); + const fake = fakeGithub({ comments: 45 }), restore = routeGithubApi(fake); + const previous = process.env.BRAIN_UI_GITHUB_TOOLS_TOKEN; + process.env.BRAIN_UI_GITHUB_TOOLS_TOKEN = GITHUB_TOOLS_SENTINEL; + const histories: Record = {}; + const requests: StartTurnRequest[] = []; + let finished = 0; + const backend = makeFakeBackend({ id: "claude", histories, startTurn: async request => { + requests.push(request); + const { bridge } = request; + await bridge.inputSafety!.ready("claude", 1); + const sessionId = request.sessionId ?? `sess-ithaca-${requests.length}`; + bridge.emit({ type: "session_info", sessionId, isNew: !request.sessionId }); + try { + if (!request.sessionId) { + const result = await bridge.github!({ tool: "brain_github_issue_read", input: { repository: "odysseus/ithaca", number: 7 } }); + histories[sessionId] = [{ role: "user", content: request.prompt, toolCalls: [] }, + { role: "assistant", content: "The suitors drain the stores.", toolCalls: [{ id: "read-7", name: "mcp__brain-ui__brain_github_issue_read", + input: { repository: "odysseus/ithaca", number: 7 }, output: JSON.stringify(result), isError: !result.ok }] }]; + } + } finally { + bridge.emit({ type: "result", sessionId, outcome: "success", durationMs: 1, numTurns: 1, isError: false }); + finished++; + } + } }); + const native = createNativeJournalFixture(brain, root), broker = native.serve(); + const app = await createApp({ config: resolveServerConfig({ BRAIN_UI_NATIVE_BRAIN_SOCKET: broker.socketPath, BRAIN_PATH: brain, DB_PATH: resolve(root, "ui.db"), HOST: "127.0.0.1", + AUTH_MODE: "password", NODE_ENV: "test", BRAIN_UI_PASSWORD_HASH: await Bun.password.hash("the bow only Odysseus can string"), + COOKIE_SECRET: SECRET, BRAIN_UI_MODEL_DISCOVERY: "0", BRAIN_UI_PRICING_DISCOVERY: "0" }), + registry: createStaticBackendRegistry([backend], backend.id), observability: createRecordingObservability() }); + try { + const owner = createPrincipal(app.db, { authMethod: "password", label: "Penelope's loom", ttlSeconds: 600 }); + const phone = createPrincipal(app.db, { authMethod: "password", label: "Penelope's phone", ttlSeconds: 600 }); + const agent = createPrincipal(app.db, { authMethod: "delegated", label: "Suitor agent", createdBy: owner.id, ttlSeconds: 600 }); + const cookie = async (principal: Principal) => (await generateSignedCookie("brain_ui_session", principal.id, SECRET)).split(";")[0]!; + const get = async (path: string, principal: Principal) => app.fetch(new Request(`http://localhost/api${path}`, { headers: { cookie: await cookie(principal) } })); + async function chat(text: string, sessionId?: string) { + const before = finished, handlers = createWsHandlers(app.wsHost, owner), sent: string[] = []; + const ws = { send: (frame: string) => { sent.push(frame); }, close() {}, readyState: 1 } as WSContext; + await handlers.onOpen(undefined as never, ws); + handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text, requestId: `details-${requests.length}`, ...(sessionId ? { sessionId } : {}) }) } as MessageEvent, ws); + const until = Date.now() + 45_000; + while (finished === before || app.isTurnActive()) { if (Date.now() > until) throw new Error(`turn did not finish: ${sent.join("\n")}`); await Bun.sleep(10); } + handlers.onClose({ code: 1000 } as CloseEvent, ws); + } + + // Two sessions take the same turns; only the first reads details in between. + await chat("Look up the suitors issue"); + await chat("Look up the suitors issue"); + const [read, control] = ["sess-ithaca-1", "sess-ithaca-2"]; + const taints = (sessionId: string) => queryGovernanceEvents(app.db, { sessionId, kinds: ["taint"], limit: 50 }).map(event => event.id); + const readTaints = taints(read); + expect(readTaints.length, "GITHUB_TOOL_READ_TAINTS").toBe(1); + const historyBefore = JSON.stringify(await (await get(`/sessions/${read}`, owner)).json()); + + const path = `/sessions/${read}/github/odysseus/ithaca/7/comments`; + let cursor: string | null = null, items = 0; + for (let reads = 0; reads < 3; reads++) { + const response = await get(cursor ? `${path}?cursor=${cursor}` : path, reads === 1 ? phone : owner); + expect(response.status, `GITHUB_DETAIL_APP_PAGE ${reads}`).toBe(200); + expect(response.headers.get("cache-control")).toBe("no-store"); + const page = GITHUB_DETAIL_PAGE_SCHEMA.parse(await response.json()); + items += page.items.length; + cursor = page.next_cursor; + if (!cursor) break; + } + expect(items, "GITHUB_DETAIL_APP_ALL_COMMENTS").toBe(45); + expect((await get(`/sessions/${read}/github/penelope/troy/7/comments`, owner)).status, "GITHUB_DETAIL_APP_NOT_IN_SESSION").toBe(404); + expect((await get(path, agent)).status, "GITHUB_DETAIL_APP_AGENT_NOT_OWNER").toBe(403); + expect((await get(`/sessions/${read}/github/odysseus/ithaca/7/timeline`, owner)).status, "GITHUB_DETAIL_APP_PART").toBe(400); + + expect(taints(read), "GITHUB_DETAIL_READS_NEVER_TAINT").toEqual(readTaints); + expect(JSON.stringify(await (await get(`/sessions/${read}`, owner)).json()), "GITHUB_DETAIL_HISTORY_UNCHANGED").toBe(historyBefore); + + // The next turn: the backend is handed exactly what the session that read nothing is handed. + await chat("And the bow?", read); + await chat("And the bow?", control); + const handed = (request: StartTurnRequest) => JSON.stringify({ prompt: request.prompt, attachments: request.attachments ?? null, profileId: request.profileId ?? null, + thinkingLevel: request.thinkingLevel ?? null, budgetContext: request.budgetContext ?? null, sessionBudgetLimits: request.sessionBudgetLimits ?? null, + client: request.client ?? null, posture: request.posture ?? null, noGrantSurface: request.noGrantSurface ?? null, enforceAllowedTools: request.enforceAllowedTools ?? null }); + const [next, controlNext] = [requests.at(-2)!, requests.at(-1)!]; + expect([next.sessionId, controlNext.sessionId]).toEqual([read, control]); + expect(handed(next), "GITHUB_DETAIL_NEXT_TURN_UNCHANGED").toBe(handed(controlNext)); + expect(next.prompt, "GITHUB_DETAIL_NEVER_IN_PROMPT").not.toContain("Comment 9044"); + expect(taints(read).length, "GITHUB_DETAIL_NO_LATER_TAINT").toBe(1); + } finally { + await app.close(); broker.close(); await native.close(); + restore(); fake.stop(); + if (previous === undefined) delete process.env.BRAIN_UI_GITHUB_TOOLS_TOKEN; else process.env.BRAIN_UI_GITHUB_TOOLS_TOKEN = previous; + await rm(root, { recursive: true, force: true }); + } +}, 90_000);