From 7e4f0053d6aca0ab54a148d06a3b8e647266f1bd Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 16:59:41 +0000 Subject: [PATCH] CONTRACT: feat(ui-sdk, ui-server, ui-react): per-review line-comment count, so each review gets its own "Show n line comments" (#4147) The shared review payload gains an optional, nullable `line_comments`, and GITHUB_LIMITS gains `reviewComments` (100). A pull request read counts each review's line comments from one bounded page of its review comments, grouped by pull_request_review_id, and reports null for every review rather than a partial total when the page is cut short, a comment names no review or is malformed, GitHub's own total disagrees, or the credential cannot read them. Detail-page reviews carry null; a legacy result without the field reads as unknown. The chat shows "Show n line comments" on each review with a known positive count. Its press mounts that review's section, which loads #3796's review-comments part filtered to the review, follows sparse pages at most four per press and stops at the known count. The PR-wide section is retired when every review in a complete list is counted; it remains, filtered to the comments no counted review reaches, when a review's count is unknown or the result does not carry every review. Co-Authored-By: Claude Opus 5.5 --- .changeset/4147-review-line-comment-counts.md | 7 + api-report/ui-sdk.txt | 6 + docs/integration-contract.md | 13 ++ docs/integration-contract/mcp.md | 27 ++++ docs/integration-contract/package-api.md | 9 ++ .../chat/renderers/github-mapping.ts | 23 +++ .../chat/tool-cards/github-cards.tsx | 138 ++++++++++++++---- .../tests/browser/github-tools.layout.tsx | 64 +++++++- .../tests/render/github-tools.test.tsx | 137 +++++++++++++++++ packages/ui-sdk/src/tool-contracts/github.ts | 13 ++ .../ui-sdk/tests/github-tool-contract.test.ts | 15 ++ packages/ui-server/src/github/host.ts | 36 ++++- .../tests/fixtures/github-host-fixture.ts | 14 ++ .../ui-server/tests/github-details.test.ts | 2 + .../ui-server/tests/github-tools-host.test.ts | 58 ++++++++ 15 files changed, 531 insertions(+), 31 deletions(-) create mode 100644 .changeset/4147-review-line-comment-counts.md diff --git a/.changeset/4147-review-line-comment-counts.md b/.changeset/4147-review-line-comment-counts.md new file mode 100644 index 0000000000..2e4267858d --- /dev/null +++ b/.changeset/4147-review-line-comment-counts.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-react": patch +--- + +Each review in a GitHub pull request read now says how many line comments it has (#4147), and the chat shows "Show n line comments" on that review. The SDK's review schema gains an optional `line_comments` (an exact count, or `null` for unknown; a result recorded earlier has none and reads as unknown), and `GITHUB_LIMITS.reviewComments` (100). The host counts from one bounded page of the pull request's review comments and gives every review `null` rather than a partial total when that page is cut short, a comment names no review, or GitHub's own total disagrees. In the chat, pressing a review's control loads only that review's comments through the detail route, following sparse pages a bounded number per press; a pull request whose reviews are not all counted, or not all in the result, still offers the other line comments in one section. Nothing loaded reaches the conversation. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index e8f7df7efe..6da80e96d0 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -8431,6 +8431,7 @@ signatures (every public export and the types it is made of) body_truncated: z.ZodBoolean; html_url: z.ZodNullable; id: z.ZodNumber; + line_comments: z.ZodOptional>; state: z.ZodEnum<{ approved: "approved"; changes_requested: "changes_requested"; @@ -8853,6 +8854,7 @@ signatures (every public export and the types it is made of) body_truncated: z.ZodBoolean; html_url: z.ZodNullable; id: z.ZodNumber; + line_comments: z.ZodOptional>; state: z.ZodEnum<{ approved: "approved"; changes_requested: "changes_requested"; @@ -9067,6 +9069,7 @@ signatures (every public export and the types it is made of) queryChars: 256; refChars: 255; requestedReviewers: 30; + reviewComments: 100; reviews: 100; searchDefault: 10; searchMax: 30; @@ -9217,6 +9220,7 @@ signatures (every public export and the types it is made of) body_truncated: z.ZodBoolean; html_url: z.ZodNullable; id: z.ZodNumber; + line_comments: z.ZodOptional>; state: z.ZodEnum<{ approved: "approved"; changes_requested: "changes_requested"; @@ -9535,6 +9539,7 @@ signatures (every public export and the types it is made of) body_truncated: z.ZodBoolean; html_url: z.ZodNullable; id: z.ZodNumber; + line_comments: z.ZodOptional>; state: z.ZodEnum<{ approved: "approved"; changes_requested: "changes_requested"; @@ -9734,6 +9739,7 @@ signatures (every public export and the types it is made of) body_truncated: z.ZodBoolean; html_url: z.ZodNullable; id: z.ZodNumber; + line_comments: z.ZodOptional>; state: z.ZodEnum<{ approved: "approved"; changes_requested: "changes_requested"; diff --git a/docs/integration-contract.md b/docs/integration-contract.md index a42312786c..82200ad7f6 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,19 @@ same-commit update of the index or relevant authoritative component. How they ar The reasoning is in [decisions/contract-versioning.md](decisions/contract-versioning.md). +## Per-review line-comment counts (additive, 0.45.0, #4147) + +Each review in a `brain_github_issue_read` pull request result gains +`line_comments`: the exact number of line comments on that review, or `null` +when the host could not establish one. The host counts them from one bounded +page of the pull request's review comments and never reports a partial total. +A review in an internal detail page carries `null`, and a result recorded +before 0.45.0 has no field, which reads as `null`. +`GITHUB_LIMITS` gains `reviewComments` (100), the page the count is taken from. +Field names, inputs and existing meanings are unchanged. See +[the MCP component](integration-contract/mcp.md#per-review-line-comment-counts-additive-0450-4147). +This ships in a minor. + ## Extraction classifier setting (additive, 0.45.0, #4088) The governance policy gains optional `taint.classifier`, `off` (the default) or diff --git a/docs/integration-contract/mcp.md b/docs/integration-contract/mcp.md index 3aa007ba61..7178d75a0f 100644 --- a/docs/integration-contract/mcp.md +++ b/docs/integration-contract/mcp.md @@ -1539,6 +1539,33 @@ any GitHub text returns, the session's taint is recorded with the new source `github_result` ([governance events](../http-api.md)); if that record cannot be written, the text is withheld. +### Per-review line-comment counts (additive, 0.45.0, #4147) + +Each item of a pull request's `reviews` gains `line_comments`, a nonnegative +integer or `null`: + +- A number is the exact total of line comments (review comments) on that + review, zero included. The host takes it from one request for the pull + request's review comments, at most `GITHUB_LIMITS.reviewComments` (100), and + groups them by GitHub's `pull_request_review_id`. +- `null` means unknown. Every review's count is `null` when that page is not + the whole collection (GitHub names a next page), when any comment is + malformed or names no review, when the page disagrees with the pull + request's own `review_comments` total, or when the credential cannot read + review comments (`forbidden`, `not_found`). Other failures of that request + fail the read with their usual typed error. There is never a partial total, + and zero is reported only when the complete page has none. +- A pull request with no reviews in its result makes no extra request, and an + issue read is unchanged. +- A review in a `reviews` detail page ([#3796](../http-api.md#github-detail-pages-internal-0450-3796)) + carries `null`: the page counts nothing. +- The field is optional in `GITHUB_REVIEW_SCHEMA`, so a result recorded before + it existed still parses; a consumer reads its absence as `null`. Negative, + fractional or non-numeric values are refused. + +The count is metadata on new results only; it adds no tool, input or request +the model can make. + ### GitHub data routing (additive, 0.45.0, #4029) GitHub is the provider-policy recipient `github` diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index f89e97f33d..eb89804d74 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -701,6 +701,15 @@ input and forwards `{ tool, input }` to the optional new [the MCP component](mcp.md#host-github-tools-additive-0450-3797). No existing export changes. +## Per-review line-comment counts (additive, 0.45.0, #4147) + +`@schlessera/brain-ui-sdk/tool-contracts` adds the optional, nullable +`line_comments` field to `GITHUB_REVIEW_SCHEMA` (and so to `GithubReview` and +every payload and detail page that holds a review), and +`GITHUB_LIMITS.reviewComments` (100). Shapes and the counting rules are in +[the MCP component](mcp.md#per-review-line-comment-counts-additive-0450-4147). +No existing export changes. + ## GitHub detail-page types (additive, 0.45.0, #3796) `@schlessera/brain-ui-sdk/tool-contracts` (re-exported from `/server`) adds diff --git a/packages/ui-react/src/components/chat/renderers/github-mapping.ts b/packages/ui-react/src/components/chat/renderers/github-mapping.ts index 040cf7d905..b19bd22456 100644 --- a/packages/ui-react/src/components/chat/renderers/github-mapping.ts +++ b/packages/ui-react/src/components/chat/renderers/github-mapping.ts @@ -182,6 +182,29 @@ export function commentProps(comment: GithubComment | GithubReviewComment, scope }; } +/** + * A review's known, positive line-comment count (#4147), or `null`. Zero, + * unknown (`null`) and a result recorded before the count existed (absent) + * all show no "Show n line comments". + */ +export function lineCommentCount(review: GithubReview): number | null { + const count = review.line_comments; + return typeof count === "number" && Number.isSafeInteger(count) && count > 0 ? count : null; +} + +/** + * Which line comments the per-review controls reach (#4147). `counted` holds + * every review whose total the host established, zero included: its line + * comments, if any, load on that review. `remainder` is true when some line + * comments may belong to no counted review: a review in the result whose + * count is unknown or absent, or reviews the result does not carry at all. + * Only then does the pull request offer them in one section of its own. + */ +export function lineCommentCoverage(pr: GithubPullRequest): { counted: ReadonlySet; remainder: boolean } { + const counted = new Set(pr.reviews.items.filter((r) => typeof r.line_comments === "number").map((r) => r.id)); + return { counted, remainder: pr.reviews.has_more || counted.size < pr.reviews.items.length }; +} + export function reviewProps(review: GithubReview, scope: GithubLinkScope | null, fetchedAt: string, avatarFor: AvatarFor) { return { reviewer: person(review.author, avatarFor), diff --git a/packages/ui-react/src/components/chat/tool-cards/github-cards.tsx b/packages/ui-react/src/components/chat/tool-cards/github-cards.tsx index 059a5a9328..26c7eadfeb 100644 --- a/packages/ui-react/src/components/chat/tool-cards/github-cards.tsx +++ b/packages/ui-react/src/components/chat/tool-cards/github-cards.tsx @@ -22,14 +22,17 @@ import { ListRow, UntrustedText, type GitHubDetailState, + type GitHubReviewProps, type GitHubThreadItem, } from "@schlessera/brain-ui-kit"; +import { GITHUB_DETAIL_PAGE_SIZE, GITHUB_LIMITS } from "@schlessera/brain-ui-sdk/tool-contracts"; import type { GithubChangedFile, GithubCheckRun, GithubComment as GithubCommentPayload, GithubCommit, GithubDetailError, + GithubDetailPage, GithubDetailPart, GithubError, GithubIssue, @@ -52,6 +55,8 @@ import { directLink, issueState, knownTotal, + lineCommentCount, + lineCommentCoverage, person, pullState, resultRow, @@ -134,17 +139,41 @@ function detailErrorState(error: GithubDetailError | GithubError & { reset_at?: return { state: "error", refusal: error.message }; } +/** + * A part read for some of its items only: one review's line comments, say + * (#4147). Only kept items are held or drawn. A page that keeps none is + * followed within the same press, at most `pages` pages per press, so a + * press shows something or stops at a truthful "Load more"; nothing drains + * the part unasked. + */ +interface DetailFilter { + keep: (item: DetailItem) => boolean; + pages: number; + /** The exact number there are: paging stops once that many are kept, and "Load more" counts against it. */ + total?: number; +} + +/** + * Pages one press may read for line comments. A known count proves the pull + * request had at most `GITHUB_LIMITS.reviewComments` when it was read, which + * is this many detail pages; the section for comments no count covers keeps + * the same bound per press. + */ +const LINE_COMMENT_PAGES = Math.ceil(GITHUB_LIMITS.reviewComments / GITHUB_DETAIL_PAGE_SIZE); + /** * One on-demand part of one object. Nothing is fetched until `load`; `more` * appends the next page; `retry` repeats the last request. The pages are * display-only state of this card: nothing here reaches the chat store, the * socket or the model. */ -function useDetail(repository: string, number: number, part: GithubDetailPart) { +function useDetail(repository: string, number: number, part: GithubDetailPart, filter?: DetailFilter) { const root = useBrainUiRoot(); const sessionId = useRootStore("chat", (s) => s.activeSessionId); const [detail, setDetail] = useState({ state: "idle", items: [], next: null, total: null }); const last = useRef(null); + const filtered = useRef(filter); + filtered.current = filter; const fetchPage = useCallback( async (cursor: string | null, append: boolean) => { @@ -156,17 +185,33 @@ function useDetail(repository: string, number: number, part: GithubDetailPart) { } // A new request starts clean: no earlier failure's status or reset time survives it. setDetail((d) => ({ ...d, state: "loading", refusal: undefined, errorStatus: undefined, resetAt: undefined, resetIn: undefined })); - const answer = await fetchGithubDetailPage(root, { sessionId, repository, number, part, cursor }); - if (!answer.ok) { - setDetail((d) => ({ ...d, ...detailErrorState(answer.error) })); - return; + const filter = filtered.current; + const kept: DetailItem[] = []; + let at = cursor; + let read = 0; + let page: GithubDetailPage; + for (;;) { + const answer = await fetchGithubDetailPage(root, { sessionId, repository, number, part, cursor: at }); + if (!answer.ok) { + // Only pages that kept nothing were followed, so no row is lost; a retry repeats this page. + last.current = at; + setDetail((d) => ({ ...d, ...detailErrorState(answer.error) })); + return; + } + page = answer.page; + read += 1; + const items = page.items as DetailItem[]; + kept.push(...(filter ? items.filter(filter.keep) : items)); + at = page.next_cursor; + if (!filter || kept.length > 0 || !at || read >= filter.pages) break; } - const page = answer.page; + const answered = page; setDetail((d) => { - const items = append ? [...d.items, ...(page.items as DetailItem[])] : (page.items as DetailItem[]); + const items = append ? [...d.items, ...kept] : kept; + const next = filter?.total !== undefined && items.length >= filter.total ? null : answered.next_cursor; // Empty only when nothing is left to load: a page with no items can // still point on (the checks part's runs end by pointing at statuses). - return { state: items.length === 0 && !page.next_cursor ? "empty" : "loaded", items, next: page.next_cursor, total: page.total_count, pages: (d.pages ?? 0) + 1 }; + return { state: items.length === 0 && !next ? "empty" : "loaded", items, next, total: filter ? (filter.total ?? null) : answered.total_count, pages: (d.pages ?? 0) + read }; }); }, [root, sessionId, repository, number, part], @@ -202,7 +247,7 @@ function DetailPart(p: { repository: string; number: number; part: GithubDetailPart; - object: "issue" | "pull request"; + object: "issue" | "pull request" | "review"; idleLabel: string; row: (item: DetailItem, index: number) => ReactNode; /** @@ -215,8 +260,10 @@ function DetailPart(p: { shownCount?: number; /** Load when the section first mounts (a tab's first open), not on a press. */ autoLoad?: boolean; + /** Keep only some items; such a section follows its own pages, bounded per press. */ + filter?: DetailFilter; }) { - const { detail, load, more, retry } = useDetail(p.repository, p.number, p.part); + const { detail, load, more, retry } = useDetail(p.repository, p.number, p.part, p.filter); const started = useRef(false); useEffect(() => { if (!p.autoLoad || started.current) return; @@ -224,6 +271,8 @@ function DetailPart(p: { load(); }, [p.autoLoad, load]); const rows = p.shown ? detail.items.filter((item) => !p.shown!(item)) : detail.items; + // A filtered section follows its own pages, bounded per press (`useDetail`). + const filtered = p.filter !== undefined; // A page that adds nothing on screen (empty, or only rows the result // already shows) is followed to the next, so one press always shows // something new or ends the list. The result carries at most one page of @@ -232,8 +281,8 @@ function DetailPart(p: { useEffect(() => { const before = seen.current; seen.current = { pages: detail.pages ?? 0, rows: rows.length }; - if (detail.state === "loaded" && detail.next && (detail.pages ?? 0) > before.pages && rows.length === before.rows) more(); - }, [detail.pages, detail.state, detail.next, rows.length, more]); + if (!filtered && detail.state === "loaded" && detail.next && (detail.pages ?? 0) > before.pages && rows.length === before.rows) more(); + }, [filtered, detail.pages, detail.state, detail.next, rows.length, more]); if (detail.refusal) { const refused = (
@@ -295,10 +344,17 @@ function outcomeUnknown(error: GithubError): boolean { // Read // --------------------------------------------------------------------------- -function threadItems(comments: GithubCommentPayload[], reviews: GithubReview[], scope: ReturnType, fetchedAt: string, avatarFor: AvatarFor): GitHubThreadItem[] { +function threadItems( + comments: GithubCommentPayload[], + reviews: GithubReview[], + scope: ReturnType, + fetchedAt: string, + avatarFor: AvatarFor, + lineComments?: (review: GithubReview) => Partial, +): GitHubThreadItem[] { const timed: { at: string; item: GitHubThreadItem }[] = [ ...comments.map((c) => ({ at: c.created_at, item: { kind: "comment" as const, id: `c${c.id}`, ...commentProps(c, scope, fetchedAt, avatarFor) } })), - ...reviews.map((r) => ({ at: r.submitted_at ?? "", item: { kind: "review" as const, id: `r${r.id}`, ...reviewProps(r, scope, fetchedAt, avatarFor) } })), + ...reviews.map((r) => ({ at: r.submitted_at ?? "", item: { kind: "review" as const, id: `r${r.id}`, ...reviewProps(r, scope, fetchedAt, avatarFor), ...lineComments?.(r) } })), ]; return timed.sort((a, b) => a.at.localeCompare(b.at)).map((t) => t.item); } @@ -387,10 +443,37 @@ function PullRequestCard({ pr }: { pr: GithubPullRequest }) { const earlier = commentTotal !== null ? commentTotal - pr.comments.items.length : null; const state = pullState(pr); + // Line comments load on demand (#3796's review-comments part), per review + // (#4147): "Show n line comments" on each review with a known count, which + // mounts that review's section, filtered to its own comments. + const [openedReviews, setOpenedReviews] = useState>(() => new Set()); + const lineCommentRow = (item: DetailItem, i: number) => ; + const reviewLineComments = (review: GithubReview): Partial => { + const count = lineCommentCount(review); + if (count === null) return {}; + return { + lineComments: count, + onShowLineComments: () => setOpenedReviews((o) => (o.has(review.id) ? o : new Set([...o, review.id]))), + children: openedReviews.has(review.id) ? ( + (item as GithubReviewComment).review_id === review.id, pages: LINE_COMMENT_PAGES, total: count }} + row={lineCommentRow} + /> + ) : undefined, + }; + }; + const coverage = lineCommentCoverage(pr); + const conversation = ( ) : null, )} - {/* Line comments load on demand (#3796's review-comments part). The - payload carries no per-review count, so this is one section for the - pull request rather than a "Show n line comments" per review. */} - {pr.reviews.items.length > 0 ? ( + {/* Line comments no review's own control reaches (#4147): those of a + review whose count is unknown, or of reviews the result does not + carry. Absent when every review in a complete list has its count. */} + {coverage.remainder ? ( ) : null} diff --git a/packages/ui-react/tests/browser/github-tools.layout.tsx b/packages/ui-react/tests/browser/github-tools.layout.tsx index abd0c761a2..6e5aa4d586 100644 --- a/packages/ui-react/tests/browser/github-tools.layout.tsx +++ b/packages/ui-react/tests/browser/github-tools.layout.tsx @@ -8,7 +8,9 @@ * - each on-demand section fetches only after the reader acts, through * #3796's route, and renders its typed errors (here, rate limited); * - loading detail changes nothing the model sees: the chat store is - * byte-identical before and after. + * byte-identical before and after; + * - a review's "Show n line comments" loads only after its press, and only + * that review's comments, under it (#4147). * * The detail route is answered by the root's `request`, the one seam every * #3796 call goes through, so no network is involved; avatars are real @@ -57,9 +59,38 @@ const FILES_PAGE = { }; const RESET = new Date(Date.now() + 12 * 60_000).toISOString().replace(/\.\d{3}Z$/, "Z"); +/** Two reviews with known counts (#4147), and one page holding both reviews' line comments. */ +const REVIEW_A = 9101, REVIEW_B = 9102; +const countedReview = (id: number, login: string, count: number, day: number) => ({ + id, + author: { login, is_bot: false, author_association: "MEMBER" as const }, + state: "commented" as const, + submitted_at: `2026-07-0${day}T09:00:00Z`, + body: `Review by ${login}.`, + body_length: 11 + login.length, + body_truncated: false, + html_url: `https://github.com/ithaca/hall/pull/412#pullrequestreview-${id}`, + line_comments: count, +}); +const lineComment = (id: number, review: number) => ({ + id, + review_id: review, + in_reply_to_id: null, + author: { login: "eurycleia", is_bot: false, author_association: "MEMBER" as const }, + path: "armoury/bow.md", + line: 3, + created_at: "2026-07-05T09:00:00Z", + updated_at: "2026-07-05T09:00:00Z", + body: `Line note ${id} on review ${review}.`, + body_length: 30, + body_truncated: false, + html_url: `https://github.com/ithaca/hall/pull/412#discussion_r${id}`, +}); +const LINE_COMMENTS_PAGE = { ...FILES_PAGE, part: "review-comments", items: [lineComment(801, REVIEW_A), lineComment(802, REVIEW_B), lineComment(803, REVIEW_A)], total_count: null }; + const methods: string[] = []; /** Mounts a PR read result; returns the detail-route calls the root's `request` saw. */ -function mountPullRequest() { +function mountPullRequest(over: Record = {}) { const calls: string[] = []; methods.length = 0; root = createBrainUiRoot({ @@ -69,6 +100,7 @@ function mountPullRequest() { calls.push(path); methods.push(init?.method ?? "GET"); if (path.endsWith("/files")) return Response.json(FILES_PAGE); + if (path.endsWith("/review-comments")) return Response.json(LINE_COMMENTS_PAGE); if (path.endsWith("/checks")) return Response.json({ error: { code: "rate_limited", reason: "github", message: "GitHub's request limit is used up.", reset_at: RESET } }, { status: 429 }); return Response.json({}, { status: 404 }); @@ -77,7 +109,7 @@ function mountPullRequest() { root.stores.chat.setState({ activeSessionId: "session-odysseus" }); registerBuiltinRenderers(root.renderers); const name = visibleToolName(GITHUB_TOOL_NAMES.read, "claude"); - const tool: ToolCallView = { id: "g1", name, input: { repository: "ithaca/hall", number: 412 }, output: JSON.stringify(envelope("read", pull({ body: HOSTILE_BODY, body_length: HOSTILE_BODY.length }))), isError: false }; + const tool: ToolCallView = { id: "g1", name, input: { repository: "ithaca/hall", number: 412 }, output: JSON.stringify(envelope("read", pull({ body: HOSTILE_BODY, body_length: HOSTILE_BODY.length, ...over }))), isError: false }; const Output = (root.renderers.resolve(tool, "claude") ?? resolveToolRenderer(tool, "claude"))!.Output!; host = document.createElement("div"); host.style.cssText = "width:680px;padding:16px;background:var(--bk-color-canvas);color:var(--bk-color-ink)"; @@ -150,3 +182,29 @@ test("nothing leaves the brain's origin, links ask first, and detail loads only expect(log.some((url) => url.includes("/github/avatars/")), "positive control: the log sees the avatar requests").toBe(true); expect(foreign(log), "no request left the brain's origin").toEqual([]); }); + +test("a review's line comments load on its press, under it, and never another review's (#4147)", async () => { + await page.viewport(900, 900); + const calls = mountPullRequest({ reviews: { items: [countedReview(REVIEW_A, "eurycleia", 2, 3), countedReview(REVIEW_B, "argos", 1, 4)], total_count: 2, has_more: false } }); + const history = JSON.stringify(root!.stores.chat.getState()); + const review = (login: string) => host!.querySelector(`[data-github-review][aria-label="Review by @${login}"]`)!; + const show = (login: string) => [...review(login).querySelectorAll("button")].find((b) => /^Show \d+ line comments?$/.test(b.textContent ?? "")); + expect(show("eurycleia")?.textContent).toBe("Show 2 line comments"); + expect(show("argos")?.textContent).toBe("Show 1 line comment"); + expect(host!.textContent, "the PR-wide section is retired").not.toMatch(/Show line comments/); + expect(detailCalls(calls), "no detail page before the reader acts").toEqual([]); + + await userEvent.click(show("eurycleia")!); + await expect.poll(() => review("eurycleia").textContent).toContain("Line note 803 on review 9101."); + expect(review("eurycleia").textContent).toContain("Line note 801 on review 9101."); + expect(host!.textContent, "another review's comment is not drawn").not.toContain("Line note 802"); + expect(detailCalls(calls)).toEqual(["/api/sessions/session-odysseus/github/ithaca/hall/412/review-comments"]); + expect(show("argos"), "the other review is still idle").toBeTruthy(); + + await userEvent.click(show("argos")!); + await expect.poll(() => review("argos").textContent).toContain("Line note 802 on review 9102."); + expect(review("argos").textContent).not.toContain("Line note 801"); + expect(review("eurycleia").textContent).not.toContain("Line note 802"); + expect(methods.every((m) => m === "GET"), "only reads").toBe(true); + expect(JSON.stringify(root!.stores.chat.getState()), "loading line comments changes nothing the model's turn is built from").toBe(history); +}); diff --git a/packages/ui-react/tests/render/github-tools.test.tsx b/packages/ui-react/tests/render/github-tools.test.tsx index 22a6905a7f..fb8692e31e 100644 --- a/packages/ui-react/tests/render/github-tools.test.tsx +++ b/packages/ui-react/tests/render/github-tools.test.tsx @@ -589,3 +589,140 @@ describe("the approval card", () => { expect(getByRole("button", { name: /Post comment/ })).toBeTruthy(); }); }); + +describe("line comments per review (#4147)", () => { + const base = pull().reviews.items[0]!; + const review = (id: number, login: string, line_comments: number | null | undefined, days: number) => { + const { line_comments: _absent, ...rest } = { ...base, line_comments: undefined }; + return { + ...rest, + id, + author: author(login), + state: "commented" as const, + submitted_at: `2026-07-0${days}T09:00:00Z`, + body: `Review by ${login}.`, + body_length: 10 + login.length, + html_url: `https://github.com/ithaca/hall/pull/412#pullrequestreview-${id}`, + ...(line_comments === undefined ? {} : { line_comments }), + }; + }; + const reviews = (items: ReturnType[], more = false) => ({ reviews: { items, total_count: more ? null : items.length, has_more: more } }); + const lineComment = (id: number, reviewId: number | null, login = "eurycleia") => ({ + id, + review_id: reviewId, + in_reply_to_id: null, + author: author(login), + path: "armoury/bow.md", + line: 3, + created_at: "2026-07-05T09:00:00Z", + updated_at: "2026-07-05T09:00:00Z", + body: `Line note ${id} on review ${reviewId}.`, + body_length: 30, + body_truncated: false, + html_url: `https://github.com/ithaca/hall/pull/412#discussion_r${id}`, + }); + const reviewComments = () => requested.filter((u) => u.includes("/review-comments")); + const article = (view: ReturnType, login: string) => within(view.container).getByRole("article", { name: `Review by @${login}` }); + const press = async (target: HTMLElement) => { + await act(async () => fireEvent.click(target)); + await act(async () => {}); + await act(async () => {}); + }; + + test("each known positive count shows its own control; zero, unknown and a legacy review show none, and nothing loads unasked", () => { + const view = output("read", envelope("read", pull(reviews([review(9101, "eurycleia", 2, 3), review(9102, "argos", 1, 4), review(9103, "mentor", 0, 5), review(9104, "medon", null, 6)])))); + expect(within(article(view, "eurycleia")).getByRole("button", { name: "Show 2 line comments" })).toBeTruthy(); + expect(within(article(view, "argos")).getByRole("button", { name: "Show 1 line comment" })).toBeTruthy(); + for (const login of ["mentor", "medon"]) expect(within(article(view, login)).queryByRole("button", { name: /line comment/ }), `no control for ${login}`).toBeNull(); + const legacy = output("read", envelope("read", pull())); + expect(within(article(legacy, "eurycleia")).queryByRole("button", { name: /Show \d+ line comment/ }), "a result recorded before the count shows no count control").toBeNull(); + expect(reviewComments(), "no detail request before the reader acts").toEqual([]); + }); + + test("the PR-wide section is retired when every review in a complete list has its count", () => { + const view = output("read", envelope("read", pull(reviews([review(9101, "eurycleia", 2, 3), review(9103, "mentor", 0, 5)])))); + expect(view.queryByRole("button", { name: /^Show line comments/ }), "LINE_COMMENTS_GLOBAL_FALLBACK_RETIRED").toBeNull(); + }); + + test("a review's press loads only its own comments, under it, and another review's never appear", async () => { + // The page names a next one: the review's two are all there are, so nothing more is read. + answer = () => page("review-comments", [lineComment(801, 9101), lineComment(802, 9102, "argos"), lineComment(803, 9101)], "2"); + const view = output("read", envelope("read", pull(reviews([review(9101, "eurycleia", 2, 3), review(9102, "argos", 1, 4)])))); + await press(within(article(view, "eurycleia")).getByRole("button", { name: "Show 2 line comments" })); + expect(reviewComments(), "one request after the press").toHaveLength(1); + const own = article(view, "eurycleia"); + expect(own.textContent).toContain("Line note 801 on review 9101."); + expect(own.textContent).toContain("Line note 803 on review 9101."); + expect(view.container.textContent, "LINE_COMMENTS_FILTERED_TO_REVIEW").not.toContain("Line note 802"); + expect(within(own).queryByRole("button", { name: /Load more/ }), "LINE_COMMENTS_STOP_AT_COUNT").toBeNull(); + expect(within(article(view, "argos")).getByRole("button", { name: "Show 1 line comment" }), "the other review is still idle").toBeTruthy(); + }); + + test("a sparse page is followed within one press, never past its bound, and 'Load more' says what is shown", async () => { + // Every page names a next one and holds only another review's comments. + answer = (url) => { + const at = Number(new URL(url, "http://x").searchParams.get("cursor") ?? "1"); + return page("review-comments", [lineComment(900 + at, 9102, "argos")], String(at + 1)); + }; + const view = output("read", envelope("read", pull(reviews([review(9101, "eurycleia", 2, 3), review(9102, "argos", 9, 4)])))); + await press(within(article(view, "eurycleia")).getByRole("button", { name: "Show 2 line comments" })); + expect(reviewComments(), "LINE_COMMENTS_FOLLOW_BOUNDED").toHaveLength(4); + const own = article(view, "eurycleia"); + expect(own.textContent).not.toContain("Line note 90"); + expect(within(own).getByRole("button", { name: /Load more/ }).textContent, "a truthful continuation, not 'none'").toContain("0 of 2 shown"); + await press(within(own).getByRole("button", { name: /Load more/ })); + expect(reviewComments(), "the next press reads the next bounded run").toHaveLength(8); + expect(reviewComments()[4], "it continues from where the last stopped").toContain("cursor=5"); + }); + + test("a sparse run that finds the review's comments stops there", async () => { + answer = (url) => (url.includes("cursor=2") ? page("review-comments", [lineComment(811, 9101)], "3") : page("review-comments", [lineComment(810, 9102, "argos")], "2")); + const view = output("read", envelope("read", pull(reviews([review(9101, "eurycleia", 3, 3), review(9102, "argos", 1, 4)])))); + await press(within(article(view, "eurycleia")).getByRole("button", { name: "Show 3 line comments" })); + expect(reviewComments()).toHaveLength(2); + const own = article(view, "eurycleia"); + expect(own.textContent).toContain("Line note 811 on review 9101."); + expect(view.container.textContent).not.toContain("Line note 810"); + expect(within(own).getByRole("button", { name: /Load more/ }).textContent).toContain("1 of 3 shown"); + }); + + test("a review whose comments are gone reads as empty, and one review's failure stays on that review", async () => { + answer = () => page("review-comments", [lineComment(820, 9102, "argos")]); + const view = output("read", envelope("read", pull(reviews([review(9101, "eurycleia", 2, 3), review(9102, "argos", 1, 4)])))); + await press(within(article(view, "eurycleia")).getByRole("button", { name: "Show 2 line comments" })); + expect(article(view, "eurycleia").textContent, "LINE_COMMENTS_EMPTY_FOR_REVIEW").toContain("GitHub returned no line comments for this review."); + answer = () => Response.json({ error: { code: "rate_limited", reason: "github", message: "Limited.", reset_at: null } }, { status: 429 }); + await press(within(article(view, "argos")).getByRole("button", { name: "Show 1 line comment" })); + expect(article(view, "argos").textContent).toContain("request limit is used up"); + expect(article(view, "eurycleia").textContent, "the first review keeps its own state").toContain("GitHub returned no line comments for this review."); + expect(article(view, "eurycleia").textContent).not.toContain("request limit"); + answer = () => page("review-comments", [lineComment(821, 9102, "argos")]); + await press(within(article(view, "argos")).getByRole("button", { name: /Try again/ })); + expect(article(view, "argos").textContent, "a retry loads that review's comments").toContain("Line note 821 on review 9102."); + }); + + test("line comments still load when the result carries none of the PR's reviews, or a review's count is unknown", async () => { + answer = () => page("review-comments", [lineComment(830, 9201, "argos"), lineComment(831, 9101)]); + const none = output("read", envelope("read", pull(reviews([], true)))); + await press(none.getByRole("button", { name: "Show line comments" })); + expect(none.container.textContent, "LINE_COMMENTS_WITHOUT_CARRIED_REVIEWS").toContain("Line note 830 on review 9201."); + cleanup(); + requested.length = 0; + const partly = output("read", envelope("read", pull(reviews([review(9101, "eurycleia", 1, 3), review(9102, "argos", null, 4)])))); + await press(partly.getByRole("button", { name: "Show line comments of other reviews" })); + expect(partly.container.textContent, "a review with an unknown count is reached").toContain("Line note 830 on review 9201."); + expect(partly.container.textContent, "a counted review's comments stay on that review").not.toContain("Line note 831"); + }); + + test("loading line comments leaves the chat store and the 'Brain read' line as they were", async () => { + answer = () => page("review-comments", [lineComment(840, 9101)]); + const view = output("read", envelope("read", pull(reviews([review(9101, "eurycleia", 1, 3)])))); + const store = roots.at(-1)!.stores.chat; + const before = JSON.stringify(store.getState()); + const brainRead = view.container.textContent?.match(/Brain read[^.]*\./)?.[0]; + await press(within(article(view, "eurycleia")).getByRole("button", { name: "Show 1 line comment" })); + expect(view.container.textContent).toContain("Line note 840 on review 9101."); + expect(JSON.stringify(store.getState()), "LINE_COMMENTS_DISPLAY_ONLY").toBe(before); + expect(view.container.textContent?.match(/Brain read[^.]*\./)?.[0]).toBe(brainRead); + }); +}); diff --git a/packages/ui-sdk/src/tool-contracts/github.ts b/packages/ui-sdk/src/tool-contracts/github.ts index d99031c63b..fcde2b8bc8 100644 --- a/packages/ui-sdk/src/tool-contracts/github.ts +++ b/packages/ui-sdk/src/tool-contracts/github.ts @@ -65,6 +65,11 @@ export const GITHUB_LIMITS = Object.freeze({ /** Items returned per bounded list. */ comments: 30, reviews: 100, + /** + * Line comments a pull request read counts per review (#4147): one page of + * them. Past it, every review's `line_comments` is null (unknown). + */ + reviewComments: 100, commits: 30, labels: 30, requestedReviewers: 30, @@ -208,6 +213,14 @@ export const GITHUB_REVIEW_SCHEMA = z.strictObject({ submitted_at: timestamp.nullable(), ...bodyFields(GITHUB_LIMITS.commentBodyChars), html_url: directUrl, + /** + * How many line comments the review has (#4147): an exact total counted + * from the pull request's review comments, or null when the host could not + * establish one (more than one bounded page, a comment that names no + * review, or a page it could not read). Absent on a result recorded before + * 0.45.0, which reads as null. Never a partial count. + */ + line_comments: count.nullable().optional(), }); /** The latest review state per reviewer: a later comment never hides an approval, a request for changes or a dismissal. */ diff --git a/packages/ui-sdk/tests/github-tool-contract.test.ts b/packages/ui-sdk/tests/github-tool-contract.test.ts index acac259ca0..b1e0dd225e 100644 --- a/packages/ui-sdk/tests/github-tool-contract.test.ts +++ b/packages/ui-sdk/tests/github-tool-contract.test.ts @@ -85,6 +85,21 @@ describe("payloads", () => { expect(solid(props(pull.reviews!).items!.items!).properties!.state!.enum, "GITHUB_REVIEW_STATES_INCLUDE_DISMISSED").toContain("dismissed"); }); + test("a review's line-comment count is a nonnegative integer or null, and a review recorded without one still parses (#4147)", () => { + const review = { id: 501, author: { login: "penelope", is_bot: false, author_association: "OWNER" }, state: "approved", submitted_at: "2026-07-03T09:00:00Z", + body: null, body_length: 0, body_truncated: false, html_url: null }; + const schema = GITHUB_PULL_REQUEST_SCHEMA.shape.reviews.shape.items.element; + for (const count of [0, 1, 100]) expect(schema.parse({ ...review, line_comments: count }).line_comments, `GITHUB_LINE_COMMENTS_EXACT ${count}`).toBe(count); + expect(schema.parse({ ...review, line_comments: null }).line_comments, "GITHUB_LINE_COMMENTS_UNKNOWN").toBeNull(); + expect(schema.safeParse(review).success, "GITHUB_LINE_COMMENTS_LEGACY_ABSENT").toBe(true); + for (const bad of [-1, 1.5, "3", Number.NaN, Number.POSITIVE_INFINITY, true, {}]) + expect(schema.safeParse({ ...review, line_comments: bad }).success, `GITHUB_LINE_COMMENTS_REFUSED ${String(bad)}`).toBe(false); + const field = props(solid(props(pull.reviews!).items!.items!)).line_comments!; + expect(solid(field).type, "GITHUB_LINE_COMMENTS_INTEGER").toBe("integer"); + expect(nullable(field), "GITHUB_LINE_COMMENTS_NULLABLE").toBe(true); + expect(solid(props(pull.reviews!).items!.items!).required ?? [], "GITHUB_LINE_COMMENTS_OPTIONAL_FOR_LEGACY").not.toContain("line_comments"); + }); + test("checks are counts or null, and null is distinct from zero", () => { const checks = GITHUB_PULL_REQUEST_SCHEMA.shape.checks; expect(Object.keys(props(solid(json(checks)))).sort()).toEqual(["failed", "passed", "running", "skipped"]); diff --git a/packages/ui-server/src/github/host.ts b/packages/ui-server/src/github/host.ts index 4a66757116..19e85905d6 100644 --- a/packages/ui-server/src/github/host.ts +++ b/packages/ui-server/src/github/host.ts @@ -173,7 +173,28 @@ 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), - ...body(value.body, GITHUB_LIMITS.commentBodyChars), html_url: githubDirectUrl(value.html_url, scope, { kind: "review", id }) }; + ...body(value.body, GITHUB_LIMITS.commentBodyChars), html_url: githubDirectUrl(value.html_url, scope, { kind: "review", id }), line_comments: null }; +} + +/** + * Each review's line-comment count (#4147), from one page of a pull request's + * review comments: the review id to its total, or null (every count unknown). + * Exact only when that page is the whole collection, every comment validates + * and names its review, and GitHub's own total, when it gives one, agrees. A + * page cut short, a comment without a review, a malformed one or a mismatch + * gives no partial total and no invented zero. + */ +function lineCommentCounts(json: unknown, hasNext: boolean, reported: number | null): Map | null { + if (hasNext || !Array.isArray(json) || json.length > GITHUB_LIMITS.reviewComments) return null; + if (reported !== null && reported !== json.length) return null; + const counts = new Map(), ids = new Set(); + for (const raw of json) { + const item = record(raw), id = integer(item?.id), reviewId = integer(item?.pull_request_review_id); + if (!id || !reviewId || ids.has(id)) return null; + ids.add(id); + counts.set(reviewId, (counts.get(reviewId) ?? 0) + 1); + } + return counts; } /** @@ -324,6 +345,17 @@ export function createGithubToolsHost(options: GithubToolsHostOptions): GithubTo return reported ? counts : null; } + /** {@link lineCommentCounts} over one bounded request; a credential that cannot read review comments leaves every count unknown. */ + async function reviewCommentCounts(token: string, repo: string, number: number, reported: number | null, signal?: AbortSignal) { + try { + const { json, response } = await get(token, `/repos/${repo}/pulls/${number}/comments?per_page=${GITHUB_LIMITS.reviewComments}`, signal); + return lineCommentCounts(json, nextLink(response) !== null, reported); + } catch (error) { + if (error instanceof GithubRefusal && ["forbidden", "not_found"].includes(error.code)) return null; + throw error; + } + } + async function read(token: string, input: GithubIssueReadInput, signal?: AbortSignal): Promise { const { owner, repo } = parseGithubRepository(input.repository)!; const name = `${owner}/${repo}`, base = `/repos/${name}/issues/${input.number}`; @@ -348,6 +380,8 @@ export function createGithubToolsHost(options: GithubToolsHostOptions): GithubTo const reviews = array(reviewPage.json).map(record).filter((item): item is Json => item !== null).map(item => review(item, scope)) .filter((item): item is GithubReview => item !== null); const reviewsMore = nextLink(reviewPage.response) !== null; + const counts = reviews.length ? await reviewCommentCounts(token, name, input.number, integer(pull.review_comments), signal) : null; + for (const item of reviews) item.line_comments = counts ? counts.get(item.id) ?? 0 : null; const commitPage = await get(token, `/repos/${name}/pulls/${input.number}/commits?per_page=${GITHUB_LIMITS.commits}`, signal); const commits = array(commitPage.json).map(record).filter((item): item is Json => item !== null).map(item => commit(item, scope)) .filter((item): item is GithubCommit => item !== null); diff --git a/packages/ui-server/tests/fixtures/github-host-fixture.ts b/packages/ui-server/tests/fixtures/github-host-fixture.ts index 4d27afed75..f7d6d3b1f5 100644 --- a/packages/ui-server/tests/fixtures/github-host-fixture.ts +++ b/packages/ui-server/tests/fixtures/github-host-fixture.ts @@ -20,6 +20,7 @@ const at = (day: number) => `2026-07-${String(day).padStart(2, "0")}T09:00:00Z`; const penelope = { login: "penelope", type: "User" }; const telemachus = { login: "telemachus", type: "User" }; const herald = { login: "herald[bot]", type: "Bot" }; +const DEFAULT_REVIEW_COMMENTS = [{ review: 501 }, { review: 501 }, { review: 503 }]; const label = (name: string) => ({ id: name.length, name, color: "d4c5f9", description: `${name} on Ithaca`, default: false }); export interface FakeGithubOptions { @@ -28,6 +29,12 @@ export interface FakeGithubOptions { /** Override one path's response. */ override?: (path: string, search: URLSearchParams) => Response | undefined; checks?: "mixed" | "none"; + /** + * Line comments on pull request #8 (#4147), each naming its review; the + * stand-in pages them like GitHub does. Defaults to two on review 501 and + * one on 503. + */ + reviewComments?: Array<{ review: number | null }>; } export interface FakeGithub { @@ -54,6 +61,7 @@ export function fakeGithub(options: FakeGithubOptions = {}): FakeGithub { pull_request: { url: `${API}/pulls/8`, html_url: `${WEB}/pull/8`, merged_at: null } }; const pull = { number: 8, draft: false, merged: false, merged_at: null, merged_by: null, merge_commit_sha: MERGE_SHA, head: { ref: "bow/string-it", sha: HEAD_SHA }, base: { ref: "main" }, requested_reviewers: [penelope], commits: 2, + review_comments: (options.reviewComments ?? DEFAULT_REVIEW_COMMENTS).length, additions: 120, deletions: 7, changed_files: 4, html_url: `${WEB}/pull/8` }; const reviews = [ { id: 501, user: penelope, state: "APPROVED", author_association: "OWNER", body: "Only Odysseus can string it.", submitted_at: at(3), html_url: `${WEB}/pull/8#pullrequestreview-501` }, @@ -61,6 +69,9 @@ export function fakeGithub(options: FakeGithubOptions = {}): FakeGithub { { id: 503, user: telemachus, state: "CHANGES_REQUESTED", author_association: "COLLABORATOR", body: "", submitted_at: at(5), html_url: `${WEB}/pull/8#pullrequestreview-503` }, { id: 504, user: telemachus, state: "DISMISSED", author_association: "COLLABORATOR", body: null, submitted_at: at(6), html_url: `https://github.com.evil.example/odysseus/ithaca/pull/8#pullrequestreview-504` }, ]; + const reviewComments = (options.reviewComments ?? DEFAULT_REVIEW_COMMENTS).map(({ review }, index) => ({ id: 801 + index, pull_request_review_id: review, + in_reply_to_id: null, user: index % 2 ? telemachus : penelope, author_association: index % 2 ? "COLLABORATOR" : "OWNER", path: "bow/string.ts", line: 10 + index, + body: `Line comment ${801 + index}: the knot slips.`, created_at: at(3), updated_at: at(3), html_url: `${WEB}/pull/8#discussion_r${801 + index}` })); const commits = COMMIT_SHAS.map((sha, index) => ({ sha, html_url: `${WEB}/commit/${sha}`, author: index ? null : telemachus, commit: { message: `Wax the string ${index + 1}`, author: { name: "Telemachus", date: at(2 + index) } } })); const json = (body: unknown, init?: ResponseInit) => Response.json(body, init); @@ -100,6 +111,9 @@ export function fakeGithub(options: FakeGithubOptions = {}): FakeGithub { case "/repos/odysseus/ithaca/issues/8/comments": return json([issueComment(8, 9101, "pull")]); case "/repos/odysseus/ithaca/pulls/8": return json(pull); case "/repos/odysseus/ithaca/pulls/8/reviews": return json(reviews); + case "/repos/odysseus/ithaca/pulls/8/comments": + return json(reviewComments.slice((page - 1) * perPage, page * perPage), page * perPage < reviewComments.length + ? { headers: { link: `<${API}/pulls/8/comments?per_page=${perPage}&page=${page + 1}>; rel="next"` } } : undefined); case "/repos/odysseus/ithaca/pulls/8/commits": return json(commits); case `/repos/odysseus/ithaca/commits/${HEAD_SHA}/check-runs`: return json(options.checks === "none" ? { total_count: 0, check_runs: [] } : { total_count: 4, check_runs: [ diff --git a/packages/ui-server/tests/github-details.test.ts b/packages/ui-server/tests/github-details.test.ts index bd93ad55ec..a4e9a19d54 100644 --- a/packages/ui-server/tests/github-details.test.ts +++ b/packages/ui-server/tests/github-details.test.ts @@ -301,6 +301,8 @@ describe("direct links", () => { 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`); + // A display page counts nothing: its reviews satisfy the shared schema with an unknown count (#4147). + expect(reviews.items.map(item => item.line_comments), "GITHUB_DETAIL_REVIEW_COUNT_UNKNOWN").toEqual(reviews.items.map(() => null)); 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" }); diff --git a/packages/ui-server/tests/github-tools-host.test.ts b/packages/ui-server/tests/github-tools-host.test.ts index ac40f23ecd..de2962c714 100644 --- a/packages/ui-server/tests/github-tools-host.test.ts +++ b/packages/ui-server/tests/github-tools-host.test.ts @@ -101,6 +101,64 @@ describe("issue and pull request reads", () => { expect(pull.comments.items[0]!.html_url).toBe("https://github.com/odysseus/ithaca/pull/8#issuecomment-9101"); }); + describe("each review's line-comment count (#4147)", () => { + const READ_PR = { tool: "brain_github_issue_read", input: { repository: "odysseus/ithaca", number: 8 } } as const; + const PULL_WITHOUT_TOTAL = { number: 8, head: { ref: "bow/string-it", sha: HEAD_SHA }, base: { ref: "main" }, requested_reviewers: [], commits: 2 }; + async function counts(options: FakeGithubOptions) { + const { fake, github } = host(options); + const result = parsed(await github.call(turn, READ_PR)); + if (!result.ok) throw new Error(JSON.stringify(result)); + const asked = fake.seen.filter(request => request.path === "/repos/odysseus/ithaca/pulls/8/comments"); + return { counts: (result.result as GithubPullRequest).reviews.items.map(review => [review.id, review.line_comments]), asked }; + } + + test("a complete collection gives every review its exact total, a genuine zero included, in one bounded request", async () => { + const { counts: got, asked } = await counts({ reviewComments: [{ review: 501 }, { review: 503 }, { review: 501 }, { review: 999 }] }); + expect(got, "GITHUB_LINE_COMMENTS_EXACT_PER_REVIEW").toEqual([[501, 2], [502, 0], [503, 1], [504, 0]]); + expect(asked.map(request => new URLSearchParams(request.search).get("per_page")), "GITHUB_LINE_COMMENTS_ONE_REQUEST").toEqual(["100"]); + }); + + test("more than one page leaves every count unknown, never a partial total, and asks no second page", async () => { + const many = Array.from({ length: 101 }, (_, index) => ({ review: index % 2 ? 501 : 503 })); + // GitHub's own total is left out, so only the page's next link can say the page is not the whole collection. + const { counts: got, asked } = await counts({ reviewComments: many, override: path => path === "/repos/odysseus/ithaca/pulls/8" ? Response.json(PULL_WITHOUT_TOTAL) : undefined }); + expect(got, "GITHUB_LINE_COMMENTS_CAPPED_UNKNOWN").toEqual([[501, null], [502, null], [503, null], [504, null]]); + expect(asked, "GITHUB_LINE_COMMENTS_NO_DRAIN").toHaveLength(1); + }); + + test("a comment that names no review, or a malformed one, leaves every count unknown", async () => { + for (const review of [null, 0, -3, 1.5]) { + const { counts: got } = await counts({ reviewComments: [{ review: 501 }, { review: review as number }] }); + expect(got, `GITHUB_LINE_COMMENTS_UNVALIDATED_MEMBERSHIP ${review}`).toEqual([[501, null], [502, null], [503, null], [504, null]]); + } + const { counts: malformed } = await counts({ override: path => path === "/repos/odysseus/ithaca/pulls/8/comments" + ? Response.json([{ id: 801, pull_request_review_id: 501 }, { id: 802, pull_request_review_id: 501 }, { pull_request_review_id: 503 }]) : undefined }); + expect(malformed, "GITHUB_LINE_COMMENTS_MALFORMED_ITEM").toEqual([[501, null], [502, null], [503, null], [504, null]]); + const { counts: notList } = await counts({ override: path => path === "/repos/odysseus/ithaca/pulls/8/comments" ? Response.json({ message: "odd" }) : undefined }); + expect(notList, "GITHUB_LINE_COMMENTS_NOT_A_LIST").toEqual([[501, null], [502, null], [503, null], [504, null]]); + }); + + test("a page that disagrees with GitHub's own total is not exact", async () => { + const { counts: got } = await counts({ override: path => path === "/repos/odysseus/ithaca/pulls/8" ? Response.json({ ...PULL_WITHOUT_TOTAL, review_comments: 5 }) : undefined }); + expect(got, "GITHUB_LINE_COMMENTS_TOTAL_MISMATCH").toEqual([[501, null], [502, null], [503, null], [504, null]]); + }); + + test("a credential that cannot read review comments leaves the counts unknown; other failures fail the read as before", async () => { + const { counts: got } = await counts({ override: path => path === "/repos/odysseus/ithaca/pulls/8/comments" ? Response.json({ message: "no" }, { status: 403 }) : undefined }); + expect(got, "GITHUB_LINE_COMMENTS_FORBIDDEN_UNKNOWN").toEqual([[501, null], [502, null], [503, null], [504, null]]); + const { github } = host({ override: path => path === "/repos/odysseus/ithaca/pulls/8/comments" ? Response.json({ message: "boom" }, { status: 502 }) : undefined }); + expect(parsed(await github.call(turn, READ_PR)), "GITHUB_LINE_COMMENTS_TYPED_ERROR").toMatchObject({ ok: false, error: { code: "upstream_error", reason: "http_502" } }); + }); + + test("a pull request without reviews, and an issue, ask for no review comments", async () => { + const { counts: none, asked } = await counts({ override: path => path === "/repos/odysseus/ithaca/pulls/8/reviews" ? Response.json([]) : undefined }); + expect([none, asked], "GITHUB_LINE_COMMENTS_NOT_ASKED_WITHOUT_REVIEWS").toEqual([[], []]); + const { fake, github } = host(); + expect((await github.call(turn, { tool: "brain_github_issue_read", input: { repository: "odysseus/ithaca", number: 7 } })).ok).toBe(true); + expect(fake.seen.map(request => request.path), "GITHUB_ISSUE_READ_UNCHANGED").toEqual(["/repos/odysseus/ithaca/issues/7", "/repos/odysseus/ithaca/issues/7/comments"]); + }); + }); + test("no reported checks is null, never zero; a credential without checks access is null too", async () => { for (const options of [{ checks: "none" as const }, { override: (path: string) => path.includes("/check-runs") ? Response.json({ message: "no" }, { status: 403 }) : undefined }]) { const { github } = host(options);