From a402d3b26286590c1eed8aa78f27161e1bdf5d1c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 09:27:18 +0000 Subject: [PATCH] Record what settled each finding and the reactions on it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Findings already move to resolved or dismissed, but not what settled them, so a finding fixed in a later commit could not be told from one the author said was fixed in its thread, or one a maintainer declined by resolving the thread. Each settlement now carries `settlement`: commit, chat or thread. The 👍 and 👎 on a finding's comment are read with the review threads GitHub already returns at the start of every review, and again after a chat answer, and stored where they changed through the new updateReactions sink call. A failure to store them only logs. Together they let Appwrite tell which findings were useful. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F3M7tvvVXXtaPKh5pzVnt3 Co-authored-by: Torsten Dittmann <1759475+TorstenDittmann@users.noreply.github.com> --- packages/appwrite/src/results.test.ts | 54 +++++++++++++ packages/appwrite/src/results.ts | 37 +++++++-- packages/engine/src/chat-job.test.ts | 2 +- packages/engine/src/chat-job.ts | 9 ++- packages/engine/src/github.ts | 2 + packages/engine/src/resolved-threads.test.ts | 26 ++++++- packages/engine/src/resolved-threads.ts | 82 ++++++++++++++++++-- packages/engine/src/results.ts | 27 ++++++- packages/engine/src/review-job.test.ts | 76 ++++++++++++++++++ packages/engine/src/review-job.ts | 8 +- packages/engine/src/testing.ts | 32 +++++++- packages/github/src/pulls.test.ts | 48 ++++++++++++ packages/github/src/pulls.ts | 22 +++++- 13 files changed, 399 insertions(+), 26 deletions(-) diff --git a/packages/appwrite/src/results.test.ts b/packages/appwrite/src/results.test.ts index e4eb4c3..5fc4156 100644 --- a/packages/appwrite/src/results.test.ts +++ b/packages/appwrite/src/results.test.ts @@ -155,6 +155,60 @@ describe('AppwriteResultsSink', () => { ]); }); + test('reads and records what settled a finding and its reactions', async () => { + const sink = new AppwriteResultsSink( + serve((request) => + new URL(request.url).pathname.endsWith('/findings') + ? Response.json({ + findings: [ + { id: 'open', providerCommentId: 41, settlement: '', upvotes: 0, downvotes: 0 }, + { id: 'fixed', providerCommentId: 'cmt_1', settlement: 'commit', upvotes: 2 }, + { id: 'old', providerCommentId: null } + ] + }) + : new Response(null, { status: 204 }) + ) + ); + const pull = { projectId: 'project-1', repositoryId: 'repo-1', pullNumber: 7 }; + + expect(await sink.listFindings(pull)).toEqual([ + { id: 'open', providerCommentId: '41', settlement: null, upvotes: 0, downvotes: 0 }, + { id: 'fixed', providerCommentId: 'cmt_1', settlement: 'commit', upvotes: 2 }, + { id: 'old', providerCommentId: null } + ] as never); + await sink.updateFindings(pull, ['open'], { + status: 'resolved', + reason: 'Fixed by abc1234', + settlement: 'commit' + }); + const reactions = Array.from({ length: 101 }, (_, i) => ({ + id: `f${i}`, + upvotes: 1, + downvotes: i % 2 + })); + await sink.updateReactions(pull, reactions); + await sink.updateReactions(pull, []); + + expect(requests.slice(1).map((r) => `${r.method} ${r.path}`)).toEqual([ + 'PATCH /v1/reviews/repositories/repo-1/pulls/7/findings/status', + 'PATCH /v1/reviews/repositories/repo-1/pulls/7/findings/reactions', + 'PATCH /v1/reviews/repositories/repo-1/pulls/7/findings/reactions' + ]); + expect(requests[1]?.body).toEqual({ + projectId: 'project-1', + findingIds: ['open'], + status: 'resolved', + reason: 'Fixed by abc1234', + settlement: 'commit' + }); + const sent = requests + .slice(2) + .map((r) => r.body as { projectId: string; reactions: unknown[] }); + expect(sent.map((body) => body.reactions.length)).toEqual([100, 1]); + expect(sent[0]?.projectId).toBe('project-1'); + expect(sent[0]?.reactions[1]).toEqual({ findingId: 'f1', upvotes: 1, downvotes: 1 }); + }); + test('sends events in batches Appwrite takes, with ISO times', async () => { const sink = new AppwriteResultsSink(serve()); const at = new Date('2026-10-27T12:00:00Z'); diff --git a/packages/appwrite/src/results.ts b/packages/appwrite/src/results.ts index 59ec060..091655a 100644 --- a/packages/appwrite/src/results.ts +++ b/packages/appwrite/src/results.ts @@ -1,6 +1,8 @@ import type { ChatRef, + FindingReactions, FindingRecord, + FindingSettlement, FindingStatus, ModelUsage, PullRef, @@ -39,22 +41,30 @@ export class AppwriteResultsSink implements ResultsSink { async listFindings(pull: PullRef, options: { limit?: number } = {}): Promise { const { findings } = await this.api.request<{ - findings: (Omit & { + findings: (Omit & { providerCommentId: number | string | null; + settlement?: FindingSettlement | '' | null; })[]; }>('GET', `${pullPath(pull)}/findings`, { projectId: pull.projectId, limit: options.limit }); - // GitHub's comment ids come back as numbers; the engine keys every provider's by string. - return findings.map((finding) => - typeof finding.providerCommentId === 'number' - ? { ...finding, providerCommentId: String(finding.providerCommentId) } - : (finding as FindingRecord) - ); + return findings.map(({ providerCommentId, settlement, ...finding }) => ({ + ...finding, + // GitHub's comment ids come back as numbers; the engine keys every provider's by string. + providerCommentId: + typeof providerCommentId === 'number' ? String(providerCommentId) : providerCommentId, + // Appwrite keeps an open finding's settlement empty; one from before has none. + ...(settlement === undefined ? {} : { settlement: settlement || null }) + })); } async updateFindings( pull: PullRef, ids: string[], - update: { status: FindingStatus; reason: string; from?: FindingStatus } + update: { + status: FindingStatus; + reason: string; + from?: FindingStatus; + settlement?: FindingSettlement; + } ) { if (ids.length === 0) return; await this.api.request('PATCH', `${pullPath(pull)}/findings/status`, { @@ -64,6 +74,17 @@ export class AppwriteResultsSink implements ResultsSink { }); } + async updateReactions(pull: PullRef, reactions: ({ id: string } & FindingReactions)[]) { + for (let start = 0; start < reactions.length; start += BATCH) { + await this.api.request('PATCH', `${pullPath(pull)}/findings/reactions`, { + projectId: pull.projectId, + reactions: reactions + .slice(start, start + BATCH) + .map(({ id, upvotes, downvotes }) => ({ findingId: id, upvotes, downvotes })) + }); + } + } + async listLearnings(repository: { projectId: string; repositoryId: string }) { const { learnings } = await this.api.request<{ learnings: string[] }>( 'GET', diff --git a/packages/engine/src/chat-job.test.ts b/packages/engine/src/chat-job.test.ts index 4400c4a..e150980 100644 --- a/packages/engine/src/chat-job.test.ts +++ b/packages/engine/src/chat-job.test.ts @@ -193,7 +193,7 @@ describe('runChatJob', () => { sourceUrl: 'https://github.test/pull/7#discussion_r501' } ]); - expect(results.findings[0]?.status).toBe('dismissed'); + expect(results.findings[0]).toMatchObject({ status: 'dismissed', settlement: 'chat' }); expect(github.resolved.has(rootId)).toBe(true); // The summary is rebuilt without the finding, and the change request withdrawn. expect(github.summary()).toContain('Divides.'); diff --git a/packages/engine/src/chat-job.ts b/packages/engine/src/chat-job.ts index 4ef66b2..9c97d34 100644 --- a/packages/engine/src/chat-job.ts +++ b/packages/engine/src/chat-job.ts @@ -15,6 +15,7 @@ import { filesUrl } from './github'; import type { ChatJob } from './jobs'; import { chatFailureReply } from './public-failure'; import type { ChatRef, ModelUsage, PullRef } from './results'; +import { recordFindingReactions } from './resolved-threads'; import { lazySandbox, openSandbox } from './review-sandbox'; import { scopeToRepository } from './scope'; import { modelUsage, withWorkdir } from './shared'; @@ -213,7 +214,11 @@ export async function runChatJob( }, onMarkFinding: finding ? async (status, reason) => { - await results.updateFindings(pull, findingIds, { status, reason }); + await results.updateFindings(pull, findingIds, { + status, + reason, + settlement: 'chat' + }); settled = true; } : undefined, @@ -242,6 +247,8 @@ export async function runChatJob( log.warn('could not refresh summary after settlement', { err: error }) ); } + // Someone answering a finding has often reacted to it as well. + await recordFindingReactions(results, github, pull, findings, log); log.info('chat reply posted'); } catch (error) { // Tell the person the answer failed, once retries are exhausted. The reply is fixed: diff --git a/packages/engine/src/github.ts b/packages/engine/src/github.ts index 52cea62..582dda7 100644 --- a/packages/engine/src/github.ts +++ b/packages/engine/src/github.ts @@ -60,6 +60,8 @@ export interface ReviewThread { resolvedBy: string | null; /** Database id of the thread's first comment, which is how findings are linked. */ rootCommentId: string | undefined; + /** 👍 and 👎 on the first comment. Absent where the client does not read reactions. */ + reactions?: { upvotes: number; downvotes: number }; } export interface LinkedIssueRef { diff --git a/packages/engine/src/resolved-threads.test.ts b/packages/engine/src/resolved-threads.test.ts index fb9ea61..33e058b 100644 --- a/packages/engine/src/resolved-threads.test.ts +++ b/packages/engine/src/resolved-threads.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'bun:test'; -import { threadsResolvedByPeople } from './resolved-threads'; +import { reactionChanges, threadsResolvedByPeople } from './resolved-threads'; const thread = (rootCommentId: string, resolvedBy: string | null, isResolved = true) => ({ id: `T${rootCommentId}`, @@ -31,3 +31,27 @@ test('a resolved thread whose resolver GitHub no longer knows is skipped', () => threadsResolvedByPeople([{ id: 'a', providerCommentId: '1' }], [thread('1', null)], 'x[bot]') ).toEqual([]); }); + +test('reactions are written only where they changed', () => { + const findings = [ + { id: 'new-vote', providerCommentId: '1', upvotes: 0, downvotes: 0 }, + { id: 'same', providerCommentId: '2', upvotes: 2, downvotes: 1 }, + // Read from an Appwrite that does not keep reactions yet. + { id: 'never-stored', providerCommentId: '3' }, + { id: 'unreacted', providerCommentId: '4' }, + { id: 'body-only', providerCommentId: null }, + { id: 'no-reactions-read', providerCommentId: '5', upvotes: 1, downvotes: 0 } + ]; + const threads = [ + { ...thread('1', null, false), reactions: { upvotes: 0, downvotes: 1 } }, + { ...thread('2', null, false), reactions: { upvotes: 2, downvotes: 1 } }, + { ...thread('3', null, false), reactions: { upvotes: 1, downvotes: 0 } }, + { ...thread('4', null, false), reactions: { upvotes: 0, downvotes: 0 } }, + // A provider whose client does not read reactions. + thread('5', null, false) + ]; + expect(reactionChanges(findings, threads)).toEqual([ + { id: 'new-vote', upvotes: 0, downvotes: 1 }, + { id: 'never-stored', upvotes: 1, downvotes: 0 } + ]); +}); diff --git a/packages/engine/src/resolved-threads.ts b/packages/engine/src/resolved-threads.ts index 1280d88..427f220 100644 --- a/packages/engine/src/resolved-threads.ts +++ b/packages/engine/src/resolved-threads.ts @@ -1,6 +1,6 @@ import type { Log } from './context'; import type { GitHubConnection, ReviewThread } from './github'; -import type { FindingRecord, PullRef, ResultsSink } from './results'; +import type { FindingReactions, FindingRecord, PullRef, ResultsSink } from './results'; /** * Open findings whose GitHub thread a person resolved, with who resolved it. @@ -26,22 +26,47 @@ export function threadsResolvedByPeople( } /** - * Dismisses open findings whose thread someone with write access resolved on GitHub. + * Findings whose comment's reactions differ from what was stored, with the counts read now. + * Only threads whose client read reactions count, so a provider without them writes nothing. + */ +export function reactionChanges( + findings: readonly Pick[], + threads: readonly ReviewThread[] +): ({ id: string } & FindingReactions)[] { + const byRoot = new Map( + threads.flatMap((t) => + t.rootCommentId && t.reactions ? [[t.rootCommentId, t.reactions] as const] : [] + ) + ); + return findings.flatMap((f) => { + const reactions = f.providerCommentId ? byRoot.get(f.providerCommentId) : undefined; + if (!reactions) return []; + if (reactions.upvotes === (f.upvotes ?? 0) && reactions.downvotes === (f.downvotes ?? 0)) { + return []; + } + return [{ id: f.id, upvotes: reactions.upvotes, downvotes: reactions.downvotes }]; + }); +} + +/** + * Brings the pull request's findings in step with their threads on GitHub: dismisses open + * findings whose thread someone with write access resolved, and stores the 👍 and 👎 on every + * posted finding's comment, settled ones included, since people react after the fact too. * * Resolving the thread is how a maintainer closes a discussion. Without this, the next review * still saw the finding as open, checked whether the code "fixed" it, and kept it open, so the * grade, the summary, and the verdict ignored the decision. Dismissed findings are also not * reported again. Returns how many findings it dismissed. */ -export async function dismissFindingsResolvedOnGitHub( +export async function syncFindingsWithThreads( results: ResultsSink, { github, app }: GitHubConnection, pull: PullRef, findings: readonly FindingRecord[], log: Log ): Promise { - const open = findings.filter((f) => f.status === 'posted' && f.providerCommentId !== null); - if (open.length === 0) return 0; + const posted = findings.filter((f) => f.status !== 'dropped' && f.providerCommentId !== null); + if (posted.length === 0) return 0; let threads: ReviewThread[]; try { @@ -50,6 +75,10 @@ export async function dismissFindingsResolvedOnGitHub( log.warn('could not read review threads', { err: error }); return 0; } + + await storeReactions(results, pull, posted, threads, log); + + const open = posted.filter((f) => f.status === 'posted'); const candidates = threadsResolvedByPeople( open.map((f) => ({ id: f.id, providerCommentId: f.providerCommentId! })), threads, @@ -68,10 +97,51 @@ export async function dismissFindingsResolvedOnGitHub( await results.updateFindings(pull, [findingId], { status: 'dismissed', reason: `Thread resolved on GitHub by @${resolvedBy}`, - from: 'posted' + from: 'posted', + settlement: 'thread' }); dismissed++; } if (dismissed) log.info('dismissed findings whose thread was resolved on GitHub', { dismissed }); return dismissed; } + +/** + * Stores the 👍 and 👎 on the pull request's posted findings, e.g. after answering in a thread, + * where people react too. Never throws: reactions are a signal for the Console, not for the job. + */ +export async function recordFindingReactions( + results: ResultsSink, + github: GitHubConnection['github'], + pull: PullRef, + findings: readonly FindingRecord[], + log: Log +): Promise { + const posted = findings.filter((f) => f.status !== 'dropped' && f.providerCommentId !== null); + if (posted.length === 0) return; + try { + await storeReactions( + results, + pull, + posted, + await github.listReviewThreads(pull.pullNumber), + log + ); + } catch (error) { + log.warn('could not read review threads', { err: error }); + } +} + +async function storeReactions( + results: ResultsSink, + pull: PullRef, + findings: readonly FindingRecord[], + threads: readonly ReviewThread[], + log: Log +): Promise { + const reactions = reactionChanges(findings, threads); + if (reactions.length === 0) return; + await results + .updateReactions(pull, reactions) + .catch((error: unknown) => log.warn('could not store finding reactions', { err: error })); +} diff --git a/packages/engine/src/results.ts b/packages/engine/src/results.ts index 412d1f1..9c726e8 100644 --- a/packages/engine/src/results.ts +++ b/packages/engine/src/results.ts @@ -35,6 +35,19 @@ export interface ReviewRecord { */ export type FindingStatus = 'posted' | 'dropped' | 'resolved' | 'dismissed'; +/** + * What settled a finding: a later `commit` that fixed it, the `chat` in its thread (the author + * said it is fixed, or it was declined), or a maintainer resolving its `thread` without a change. + * Together with the status this is the finding's outcome, which tells whether it was useful. + */ +export type FindingSettlement = 'commit' | 'chat' | 'thread'; + +/** 👍 and 👎 on the comment a finding was posted as. */ +export interface FindingReactions { + upvotes: number; + downvotes: number; +} + /** A finding of a completed review of the pull request, as stored. */ export interface FindingRecord { id: string; @@ -51,6 +64,11 @@ export interface FindingRecord { dropReason: string | null; /** The GitHub comment it was posted as: the root of its thread. Null when it has none. */ providerCommentId: string | null; + /** What settled it. Absent while open, and on findings settled before it was recorded. */ + settlement?: FindingSettlement | null; + /** Reactions on its comment when last read. Absent on an Appwrite that does not keep them. */ + upvotes?: number; + downvotes?: number; /** ISO 8601. */ createdAt: string; } @@ -130,8 +148,15 @@ export interface ResultsSink { updateFindings( pull: PullRef, ids: string[], - update: { status: FindingStatus; reason: string; from?: FindingStatus } + update: { + status: FindingStatus; + reason: string; + from?: FindingStatus; + settlement?: FindingSettlement; + } ): Promise; + /** Stores the reactions on findings' comments, by finding id. */ + updateReactions(pull: PullRef, reactions: ({ id: string } & FindingReactions)[]): Promise; /** Team preferences remembered from conversations, oldest first. */ listLearnings(repository: { projectId: string; repositoryId: string }): Promise; createLearning( diff --git a/packages/engine/src/review-job.test.ts b/packages/engine/src/review-job.test.ts index 5f5cf94..dd6dab7 100644 --- a/packages/engine/src/review-job.test.ts +++ b/packages/engine/src/review-job.test.ts @@ -219,6 +219,7 @@ describe('runReviewJob', () => { const root = github.reviewComments[0]!.id; github.resolved.add(root); github.resolvedBy.set(root, 'maintainer'); + github.votes.set(root, { upvotes: 0, downvotes: 1 }); github.pullRequest = { ...github.pullRequest, headSha: rerun }; results.queue({ id: 'review2', trigger: 'synchronize' }); @@ -238,6 +239,81 @@ describe('runReviewJob', () => { expect(github.summary()).toContain('Tier S'); expect(github.reviews[0]?.state).toBe('DISMISSED'); expect(results.review('review2')).toMatchObject({ tier: 'S', verdict: 'comment' }); + // The maintainer settled it without a change, and their 👎 is stored with it. + expect(results.findings.find((f) => f.status !== 'dropped')).toMatchObject({ + status: 'dismissed', + settlement: 'thread', + upvotes: 0, + downvotes: 1 + }); + }); + + test('a finding a later commit fixes is recorded as settled by that commit', async () => { + const model = new MockLanguageModelV4({ + doGenerate: [ + toolCall('submit_review', { + summary: 'Divides for real.', + findings: [finding], + tier: 'B', + tier_reason: 'Division by zero is not handled.', + walkthrough: [{ path: 'src/math.ts', change: 'Returns a / b.' }] + }), + toolCall('submit_verdicts', { + verdicts: [{ id: 'F1', keep: true, reason: 'b is not checked' }] + }), + toolCall('submit_review', { + summary: 'Guards b.', + findings: [], + resolved: ['finding-1'], + tier: 'S', + walkthrough: [{ path: 'src/math.ts', change: 'Throws on b = 0.' }] + }) + ] + }); + const { github, results, context } = setup([model]); + const mathPatch = (body: string) => ({ + path: 'src/math.ts', + patch: `@@ -1,3 +1,3 @@\n export function divide(a, b) {\n- return 0;\n${body}\n }` + }); + github.patches = [mathPatch('+ return a / b;')]; + results.queue({ id: 'review1' }); + await runReviewJob(job(), context, first); + const root = github.reviewComments[0]!.id; + // The author likes the finding before fixing it. + github.votes.set(root, { upvotes: 1, downvotes: 0 }); + + const run = (...args: string[]) => git(args, { cwd: remote }); + await run('checkout', '--quiet', headSha); + await writeFile( + join(remote, 'src/math.ts'), + 'export function divide(a, b) {\n if (b === 0) throw new Error();\n return a / b;\n}\n' + ); + await run('commit', '--quiet', '-am', 'guard b'); + const fixed = (await run('rev-parse', 'HEAD')).trim(); + await run('checkout', '--quiet', baseSha); + try { + await run('update-ref', 'refs/pull/7/head', fixed); + github.patches = [mathPatch('+ if (b === 0) throw new Error();\n+ return a / b;')]; + github.pullRequest = { ...github.pullRequest, headSha: fixed }; + results.queue({ id: 'review2', trigger: 'synchronize' }); + await runReviewJob( + job({ reviewId: 'review2', headSha: fixed, trigger: { kind: 'synchronize' } }), + context, + first + ); + } finally { + await run('update-ref', 'refs/pull/7/head', headSha); + } + + expect(results.findings.find((f) => f.id === 'finding-1')).toMatchObject({ + status: 'resolved', + dropReason: `Fixed by ${fixed.slice(0, 7)}`, + settlement: 'commit', + upvotes: 1, + downvotes: 0 + }); + // Read at the start of the second review; nothing changed since, so not written again. + expect(results.reactionWrites).toEqual([[{ id: 'finding-1', upvotes: 1, downvotes: 0 }]]); }); test('a push that reverts a file the stale review saw still gets a verdict', async () => { diff --git a/packages/engine/src/review-job.ts b/packages/engine/src/review-job.ts index ae0a472..fa95973 100644 --- a/packages/engine/src/review-job.ts +++ b/packages/engine/src/review-job.ts @@ -42,7 +42,7 @@ import { } from './mention-ack'; import { checkRunProgress, createReviewProgress } from './progress'; import { REVIEW_FAILURE_SUMMARY } from './public-failure'; -import { dismissFindingsResolvedOnGitHub } from './resolved-threads'; +import { syncFindingsWithThreads } from './resolved-threads'; import { scopeToRepository } from './scope'; import type { FindingOutcome, @@ -305,7 +305,8 @@ async function executeReview( // On a push, review only what this pull request itself changed since the last review. // A merge of the base branch is not that: its files belong to main, not to the PR. // A thread a maintainer resolved on GitHub settles its finding before the history is read. - await dismissFindingsResolvedOnGitHub( + // Reactions on the findings' comments are stored on the way. + await syncFindingsWithThreads( results, connection, pull, @@ -448,7 +449,8 @@ async function executeReview( if (result.resolved.length) { await results.updateFindings(pull, result.resolved, { status: 'resolved', - reason: `Fixed by ${pr.headSha.slice(0, 7)}` + reason: `Fixed by ${pr.headSha.slice(0, 7)}`, + settlement: 'commit' }); const fixed = history.rows.filter((f) => result.resolved.includes(f.id)); // Close their threads on GitHub too. Quietly: the summary lists what was fixed. diff --git a/packages/engine/src/testing.ts b/packages/engine/src/testing.ts index 8758d3c..5a55e67 100644 --- a/packages/engine/src/testing.ts +++ b/packages/engine/src/testing.ts @@ -13,7 +13,9 @@ import type { } from './github'; import type { ChatRef, + FindingReactions, FindingRecord, + FindingSettlement, FindingStatus, ModelUsage, PullRef, @@ -78,13 +80,35 @@ export class MemoryResultsSink implements ResultsSink { async updateFindings( _pull: PullRef, ids: string[], - update: { status: FindingStatus; reason: string; from?: FindingStatus } + update: { + status: FindingStatus; + reason: string; + from?: FindingStatus; + settlement?: FindingSettlement; + } ): Promise { for (const finding of this.findings) { if (!ids.includes(finding.id)) continue; if (update.from && finding.status !== update.from) continue; finding.status = update.status; finding.dropReason = update.reason; + if (update.settlement) finding.settlement = update.settlement; + } + } + + /** Every reactions write, in order, to tell an unchanged count was not written again. */ + readonly reactionWrites: ({ id: string } & FindingReactions)[][] = []; + + async updateReactions( + _pull: PullRef, + reactions: ({ id: string } & FindingReactions)[] + ): Promise { + this.reactionWrites.push(reactions.map((reaction) => ({ ...reaction }))); + for (const { id, upvotes, downvotes } of reactions) { + const finding = this.findings.find((f) => f.id === id); + if (!finding) continue; + finding.upvotes = upvotes; + finding.downvotes = downvotes; } } @@ -415,10 +439,14 @@ export class MemoryGitHub implements GitHubClient, GitHubClientFactory { resolvedBy: this.resolved.has(comment.id) ? (this.resolvedBy.get(comment.id) ?? null) : null, - rootCommentId: comment.id + rootCommentId: comment.id, + reactions: this.votes.get(comment.id) ?? { upvotes: 0, downvotes: 0 } })); } + /** 👍 and 👎 on a thread's root comment, by its id. */ + readonly votes = new Map(); + /** Who resolved a thread, by its root comment, when a person did. */ readonly resolvedBy = new Map(); diff --git a/packages/github/src/pulls.test.ts b/packages/github/src/pulls.test.ts index ff42db8..3d0715e 100644 --- a/packages/github/src/pulls.test.ts +++ b/packages/github/src/pulls.test.ts @@ -6,6 +6,7 @@ import { getLinkedIssues, getPullRequest, isTrustedAuthor, + listReviewThreads, resolveReviewThreads, startCheckRun } from './pulls'; @@ -47,6 +48,53 @@ test('resolves only open threads that start with the given comments, across page expect(count).toBe(2); }); +test("reads the 👍 and 👎 on each thread's first comment", async () => { + const group = (content: string, totalCount: number) => ({ content, reactors: { totalCount } }); + const octokit = { + graphql: async (query: string) => { + expect(query).toContain('reactionGroups'); + return { + repository: { + pullRequest: { + reviewThreads: { + pageInfo: { hasNextPage: false, endCursor: null }, + nodes: [ + { + ...thread('T1', 11), + comments: { + nodes: [ + { + databaseId: 11, + reactionGroups: [ + group('THUMBS_UP', 3), + group('EYES', 1), + group('THUMBS_DOWN', 1) + ] + } + ] + } + }, + { + ...thread('T2', 22), + comments: { nodes: [{ databaseId: 22, reactionGroups: [] }] } + }, + thread('T3', 33) + ] + } + } + } + }; + } + } as unknown as Octokit; + + const threads = await listReviewThreads(octokit, { owner: 'o', repo: 'r' }, 1); + expect(threads.map((t) => t.reactions)).toEqual([ + { upvotes: 3, downvotes: 1 }, + { upvotes: 0, downvotes: 0 }, + undefined + ]); +}); + test('does nothing without comments to resolve', async () => { const octokit = { graphql: () => Promise.reject(new Error('should not be called')) }; expect( diff --git a/packages/github/src/pulls.ts b/packages/github/src/pulls.ts index ea2042f..84e3990 100644 --- a/packages/github/src/pulls.ts +++ b/packages/github/src/pulls.ts @@ -410,7 +410,12 @@ interface ReviewThreadsPage { id: string; isResolved: boolean; resolvedBy?: { login: string } | null; - comments: { nodes: { databaseId: number }[] }; + comments: { + nodes: { + databaseId: number; + reactionGroups?: { content: string; reactors: { totalCount: number } }[]; + }[]; + }; }[]; }; } | null; @@ -424,6 +429,8 @@ export interface ReviewThread { resolvedBy: string | null; /** Database id of the thread's first comment, which is how findings are linked. */ rootCommentId: number | undefined; + /** 👍 and 👎 on the first comment. */ + reactions?: { upvotes: number; downvotes: number }; } /** Every review thread on a pull request. GitHub only exposes threads through GraphQL. */ @@ -440,7 +447,10 @@ export async function listReviewThreads( pullRequest(number: $number) { reviewThreads(first: 100, after: $cursor) { pageInfo { hasNextPage endCursor } - nodes { id isResolved resolvedBy { login } comments(first: 1) { nodes { databaseId } } } + nodes { + id isResolved resolvedBy { login } + comments(first: 1) { nodes { databaseId reactionGroups { content reactors { totalCount } } } } + } } } } @@ -450,11 +460,17 @@ export async function listReviewThreads( const connection = page.repository.pullRequest?.reviewThreads; if (!connection) break; for (const thread of connection.nodes) { + const root = thread.comments.nodes[0]; + const count = (content: string) => + root?.reactionGroups?.find((group) => group.content === content)?.reactors.totalCount ?? 0; threads.push({ id: thread.id, isResolved: thread.isResolved, resolvedBy: thread.resolvedBy?.login ?? null, - rootCommentId: thread.comments.nodes[0]?.databaseId + rootCommentId: root?.databaseId, + ...(root?.reactionGroups + ? { reactions: { upvotes: count('THUMBS_UP'), downvotes: count('THUMBS_DOWN') } } + : {}) }); } if (!connection.pageInfo.hasNextPage) break;