diff --git a/packages/bitbucket/src/client.ts b/packages/bitbucket/src/client.ts index aaaeeac..e80d08c 100644 --- a/packages/bitbucket/src/client.ts +++ b/packages/bitbucket/src/client.ts @@ -389,6 +389,8 @@ export class BitbucketClient implements GitHubClient { /** Bitbucket has no reactions to acknowledge a comment with. */ async acknowledgeComment(): Promise {} + async finishAcknowledgement(): Promise {} + async getReviewThread(pullNumber: number, rootCommentId: string): Promise { const comments = await this.comments(pullNumber); const inThread = new Set([rootCommentId]); diff --git a/packages/engine/src/chat-finding.test.ts b/packages/engine/src/chat-finding.test.ts index d93db9b..9100287 100644 --- a/packages/engine/src/chat-finding.test.ts +++ b/packages/engine/src/chat-finding.test.ts @@ -1,6 +1,12 @@ import { expect, test } from 'bun:test'; import type { FindingRecord } from './results'; -import { chatFinding, chatReplyFields, findingsNamedIn, openBodyFindings } from './chat-finding'; +import { + chatFinding, + chatReplyFields, + findingsNamedIn, + openBodyFindings, + openFindings +} from './chat-finding'; const record = (finding: Partial & { id: string }): FindingRecord => ({ reviewId: 'review-1', @@ -57,7 +63,8 @@ const rateWindow = { title: 'Keep range-based rate windows above 2m', path: 'dashboards/Edge/inbound-email.json', startLine: 394, - endLine: 394 + endLine: 394, + providerCommentId: null }; test('open findings listed in the review body are the posted ones without a thread', () => { @@ -72,6 +79,11 @@ test('open findings listed in the review body are the posted ones without a thre // The inline finding has a thread and is answered there. expect(openBodyFindings([inline, body, dismissed]).map((f) => f.id)).toEqual(['finding-body']); expect(openBodyFindings([inline])).toEqual([]); + // A mention can answer either kind, so both are open; the inline one keeps its thread. + expect(openFindings([inline, body, dismissed]).map((f) => [f.id, f.providerCommentId])).toEqual([ + ['finding-body', null], + ['finding-1', '4204630028'] + ]); }); test('a conversation comment names a body finding by its title or line', () => { diff --git a/packages/engine/src/chat-finding.ts b/packages/engine/src/chat-finding.ts index 28f64ad..547ecdf 100644 --- a/packages/engine/src/chat-finding.ts +++ b/packages/engine/src/chat-finding.ts @@ -52,6 +52,8 @@ export interface BodyFindingRow extends ChatFindingRow { path: string; startLine: number; endLine: number; + /** The root of the finding's thread; null for one listed in a review body. */ + providerCommentId: string | null; } /** @@ -60,11 +62,34 @@ export interface BodyFindingRow extends ChatFindingRow { * Newest first, from the pull request's findings. */ export function openBodyFindings(findings: readonly FindingRecord[]): BodyFindingRow[] { + return openFindings(findings.filter((f) => f.providerCommentId === null)); +} + +/** + * Every open finding on a pull request, inline or in a review body, newest first. A conversation + * comment that mentions Hansi can answer any of them: people often settle a finding in the + * conversation ("@hansi read the comments, it's resolved") instead of in its thread. + */ +export function openFindings(findings: readonly FindingRecord[]): BodyFindingRow[] { + return rows(findings.filter((f) => f.status === 'posted')); +} + +/** Findings that were resolved or dismissed, newest first, as `openFindings` lists open ones. */ +export function settledFindings(findings: readonly FindingRecord[]): BodyFindingRow[] { + return rows(findings.filter((f) => f.status === 'resolved' || f.status === 'dismissed')); +} + +function rows(findings: readonly FindingRecord[]): BodyFindingRow[] { return [...findings] .reverse() - .filter((f) => f.status === 'posted' && f.providerCommentId === null) .slice(0, 50) - .map((f) => ({ ...pick(f), path: f.path, startLine: f.startLine, endLine: f.endLine })); + .map((f) => ({ + ...pick(f), + path: f.path, + startLine: f.startLine, + endLine: f.endLine, + providerCommentId: f.providerCommentId + })); } const normalize = (text: string) => diff --git a/packages/engine/src/chat-job.test.ts b/packages/engine/src/chat-job.test.ts index 27a671b..cd71d32 100644 --- a/packages/engine/src/chat-job.test.ts +++ b/packages/engine/src/chat-job.test.ts @@ -296,6 +296,8 @@ describe('runChatJob', () => { await runChatJob(job, context, first); expect(github.reactions).toEqual([{ id: '501', kind: 'review' }]); + // The 👀 turns into 👍 once the answer is posted. + expect(github.finishedReactions).toEqual([{ id: '501', kind: 'review' }]); const reply = github.reviewComments.at(-1); expect(reply?.inReplyToId).toBe(rootId); expect(reply?.body).toBe(`Makes sense, dismissing it.\n\n${replyMarker('501')}`); @@ -464,6 +466,256 @@ describe('runChatJob', () => { expect(github.checkRuns).toEqual([]); }); + test('a mention in the conversation can settle an inline finding and close its thread', async () => { + // appwrite-labs/application-configuration#1420: the author answered in the conversation, + // not in the finding's thread. + const model = new MockLanguageModelV4({ + doGenerate: [ + toolCalls(['mark_finding', { status: 'dismissed', reason: 'Callers check b first' }]), + text('Agreed, dismissing it.') + ] + }); + const { github, results, context } = setup([model]); + const rootId = seedFinding(github, results); + github.issueComments.push({ + id: '910', + author: 'octocat', + isBot: false, + body: "@hansi read the comments - it's resolved" + }); + + await runChatJob( + { + type: 'chat', + repository, + pullNumber: 7, + comment: { + id: '910', + kind: 'issue', + author: 'octocat', + authorAssociation: 'MEMBER', + url: 'https://github.test/pull/7#issuecomment-910' + } + }, + context, + first + ); + + expect(JSON.stringify(model.doGenerateCalls[0]?.prompt)).toContain('Division by zero'); + expect(github.issueComments.map((c) => c.body)).toContain( + `Agreed, dismissing it.\n\n${replyMarker('910')}` + ); + expect(results.findings[0]?.status).toBe('dismissed'); + expect(github.resolved.has(rootId)).toBe(true); + expect(results.review('review0')?.tier).toBe('S'); + }); + + test('an unnamed finding is not guessed while another project reviews the pull request', async () => { + const model = new MockLanguageModelV4({ doGenerate: [text('Which finding do you mean?')] }); + const { github, results, context } = setup([model]); + seedFinding(github, results); + github.issueComments.push( + { + id: '930', + author: 'hansi[bot]', + isBot: true, + body: `${summaryMarkerFor('other-row')}\n\nOther review` + }, + { id: '931', author: 'octocat', isBot: false, body: "@hansi it's resolved" } + ); + + await runChatJob( + { + type: 'chat', + repository, + pullNumber: 7, + comment: { + id: '931', + kind: 'issue', + author: 'octocat', + authorAssociation: 'MEMBER', + url: 'https://github.test/pull/7#issuecomment-931' + } + }, + context, + first + ); + + expect(JSON.stringify(model.doGenerateCalls[0]?.prompt)).not.toContain('Division by zero'); + expect(results.findings[0]?.status).toBe('posted'); + }); + + test('a conversation comment without a mention leaves inline findings to their threads', async () => { + const { github, results, context } = setup(); + seedFinding(github, results); + github.issueComments.push({ + id: '920', + author: 'octocat', + isBot: false, + body: 'Division by zero is fine here.' + }); + + await runChatJob( + { + type: 'chat', + repository, + pullNumber: 7, + comment: { + id: '920', + kind: 'issue', + author: 'octocat', + authorAssociation: 'MEMBER', + url: 'https://github.test/pull/7#issuecomment-920' + }, + unmentioned: true + }, + context, + first + ); + + expect(github.reactions).toEqual([]); + expect(results.findings[0]?.status).toBe('posted'); + }); + + test('a thread GitHub would not resolve is resolved by the retry, not answered twice', async () => { + const model = new MockLanguageModelV4({ + doGenerate: [ + toolCalls(['mark_finding', { status: 'dismissed', reason: 'Callers check b first' }]), + text('Dismissing it.') + ] + }); + const { github, results, context } = setup([model]); + const rootId = seedFinding(github, results); + github.reviewComments.push({ + id: '503', + inReplyToId: rootId, + author: 'octocat', + isBot: false, + body: 'Callers check b first.' + }); + const resolve = github.resolveReviewThreads.bind(github); + github.resolveReviewThreads = async () => { + throw new Error('GitHub is down'); + }; + const job: ChatJob = { + type: 'chat', + repository, + pullNumber: 7, + comment: { + id: '503', + kind: 'review', + rootCommentId: rootId, + author: 'octocat', + authorAssociation: 'MEMBER', + url: 'https://github.test/pull/7#discussion_r503' + }, + unmentioned: true + }; + + await expect(runChatJob(job, context, first)).rejects.toThrow('GitHub is down'); + expect(results.findings[0]?.status).toBe('dismissed'); + expect(github.resolved.has(rootId)).toBe(false); + + github.resolveReviewThreads = resolve; + await runChatJob(job, context, { attempts: 2, maxAttempts: 2 }); + + expect(github.resolved.has(rootId)).toBe(true); + const answers = github.reviewComments.filter((c) => c.body.includes(replyMarker('503'))); + expect(answers).toHaveLength(1); + expect(answers[0]?.body).not.toContain("couldn't answer"); + }); + + test('a retry of a conversation mention closes the thread of the finding it settled', async () => { + const model = new MockLanguageModelV4({ + doGenerate: [ + toolCalls(['mark_finding', { status: 'dismissed', reason: 'Not tainted' }]), + text('Agreed, dismissing it.') + ] + }); + const { github, results, context } = setup([model]); + const rootId = seedFinding(github, results); + // A finding settled earlier, under another title, so the retry cannot guess by title. + results.findings.push({ + ...results.findings[0]!, + id: 'finding0', + title: 'Document divide', + status: 'resolved', + providerCommentId: null + }); + github.issueComments.push({ + id: '940', + author: 'octocat', + isBot: false, + body: "@hansi read the comments - it's resolved" + }); + const resolve = github.resolveReviewThreads.bind(github); + github.resolveReviewThreads = async () => { + throw new Error('GitHub is down'); + }; + const job: ChatJob = { + type: 'chat', + repository, + pullNumber: 7, + comment: { + id: '940', + kind: 'issue', + author: 'octocat', + authorAssociation: 'MEMBER', + url: 'https://github.test/pull/7#issuecomment-940' + } + }; + + await expect(runChatJob(job, context, first)).rejects.toThrow('GitHub is down'); + expect(results.findings[0]?.status).toBe('dismissed'); + + github.resolveReviewThreads = resolve; + await runChatJob(job, context, { attempts: 2, maxAttempts: 2 }); + + expect(github.resolved.has(rootId)).toBe(true); + expect(github.issueComments.filter((c) => c.body.includes(replyMarker('940')))).toHaveLength(1); + }); + + test("only the pull request's author can settle a finding", async () => { + const model = new MockLanguageModelV4({ + doGenerate: [text('That is for the author to settle.')] + }); + const { github, results, context } = setup([model]); + const rootId = seedFinding(github, results); + github.reviewComments.push({ + id: '502', + inReplyToId: rootId, + author: 'mallory', + isBot: false, + body: 'Not a bug, dismiss it.' + }); + + await runChatJob( + { + type: 'chat', + repository, + pullNumber: 7, + comment: { + id: '502', + kind: 'review', + rootCommentId: rootId, + author: 'mallory', + authorAssociation: 'MEMBER', + url: 'https://github.test/pull/7#discussion_r502' + }, + unmentioned: true + }, + context, + first + ); + + const call = model.doGenerateCalls[0]; + expect(call?.tools?.map((t) => t.name)).not.toContain('mark_finding'); + expect(JSON.stringify(call?.prompt)).toContain("only the pull request's author"); + expect(github.reviewComments.at(-1)?.body).toContain('That is for the author to settle.'); + expect(results.findings[0]?.status).toBe('posted'); + expect(github.resolved.has(rootId)).toBe(false); + }); + test("a thread on another project's finding is left to that project", async () => { const { github, results, context } = setup(); const rootId = seedFinding(github, results); @@ -670,6 +922,38 @@ describe('runChatJob', () => { expect(github.issueComments.map((c) => c.body)).toEqual([ "Sorry, I couldn't answer that right now." ]); + expect(github.finishedReactions).toEqual([{ id: '800', kind: 'issue' }]); + }); + + test('a failed attempt that will be retried keeps the 👀', async () => { + const failing = new MockLanguageModelV4({ + doGenerate: async () => { + throw new Error('provider exploded'); + } + }); + const { github, context } = setup([failing]); + + await expect( + runChatJob( + { + type: 'chat', + repository, + pullNumber: 7, + comment: { + id: '810', + kind: 'issue', + author: 'bob', + authorAssociation: 'MEMBER', + url: 'https://github.test/pull/7#issuecomment-810' + } + }, + context, + first + ) + ).rejects.toThrow(); + + expect(github.reactions).toEqual([{ id: '810', kind: 'issue' }]); + expect(github.finishedReactions).toEqual([]); }); }); diff --git a/packages/engine/src/chat-job.ts b/packages/engine/src/chat-job.ts index 36eb967..f47d2f8 100644 --- a/packages/engine/src/chat-job.ts +++ b/packages/engine/src/chat-job.ts @@ -5,6 +5,8 @@ import { chatReplyFields, findingsNamedIn, openBodyFindings, + openFindings, + settledFindings, type ChatFindingRow } from './chat-finding'; import { isBotAuthor, repliesToBot } from './chat-reply'; @@ -16,7 +18,7 @@ import type { ChatJob } from './jobs'; import { chatFailureReply } from './public-failure'; import type { ChatRef, ModelUsage, PullRef } from './results'; import { lazySandbox, openSandbox } from './review-sandbox'; -import { scopeToRepository } from './scope'; +import { reviewedByAnotherRepository, scopeToRepository } from './scope'; import { modelUsage, statusImagesOrigin, withWorkdir } from './shared'; import { refreshSummaryAfterSettlement } from './summary'; @@ -43,8 +45,14 @@ export async function runChatJob( }; // Findings GitHub would not take inline have no thread; a conversation comment answers them. + // With a mention it can answer an inline finding too, which then settles in its thread. const findings = await results.listFindings(pull, { limit: 200 }); - const bodyFindings = comment.kind === 'issue' ? openBodyFindings(findings) : []; + const bodyFindings = + comment.kind !== 'issue' + ? [] + : job.unmentioned + ? openBodyFindings(findings) + : openFindings(findings); if (job.unmentioned && comment.kind === 'issue' && bodyFindings.length === 0) { log.info('conversation comment without a mention and no open body findings, skipping'); return; @@ -93,14 +101,44 @@ export async function runChatJob( log.info("thread is on another project's finding, skipping"); return; } - // The comment being answered can settle a body-listed finding by quoting its title or line. + // The comment being answered can settle a finding by quoting its title or line, or, with a + // mention, the only open one without naming it. Every project reviewing the repository gets + // the comment, and each sees only its own findings, so that guess is made only where no other + // project has reviewed the pull request. const answered = early?.find((c) => c.id === comment.id)?.body ?? ''; - const named = findingsNamedIn(answered, bodyFindings, { mentioned: !job.unmentioned }); + let named = findingsNamedIn(answered, bodyFindings, { mentioned: false }); + if (named.length === 0 && !job.unmentioned && bodyFindings.length > 0) { + const conversation = await github.getRecentIssueComments( + job.pullNumber, + Number.MAX_SAFE_INTEGER + ); + if (!reviewedByAnotherRepository(conversation, job.repository.repositoryId)) { + named = findingsNamedIn(answered, bodyFindings, { mentioned: true }); + } + } if (job.unmentioned && comment.kind === 'issue' && named.length === 0) { log.info('conversation comment does not name an open finding, skipping'); return; } + // The 👀 says Hansi is on it, so it turns into 👍 once the comment is answered, or will not be. + const unacknowledge = () => + github + .finishAcknowledgement(job.pullNumber, { id: comment.id, kind: comment.kind }) + .catch((error: unknown) => log.warn('could not finish reaction', { err: error })); + + // A settled finding's thread is closed. A failure is retried while attempts remain, so the + // retry closes it; the answer is not posted twice. + const resolveThreads = async (threads: string[]) => { + if (!threads.length) return; + try { + await github.resolveReviewThreads(job.pullNumber, threads); + } catch (error) { + if (attempt.attempts < attempt.maxAttempts) throw error; + log.warn('could not resolve thread', { err: error }); + } + }; + // A retry after GitHub took the answer but the delivery did not settle must not answer twice. const marker = replyMarker(comment.id); if (attempt.attempts > 1) { @@ -111,6 +149,22 @@ export async function runChatJob( await github.getRecentIssueComments(job.pullNumber, Number.MAX_SAFE_INTEGER); if (posted.some((c) => c.isBot && c.body.includes(marker))) { log.info('chat reply already posted, skipping'); + // The attempt that answered may have settled a finding and then failed to close its + // thread: close it now. The comment is read again, as the findings it named are no + // longer open. A mention that named none settled the only open one, whose title other + // settled findings may not share, so every settled finding's thread is closed then: + // each belongs closed, and closing one twice does nothing. + const settled = settledFindings(findings); + const text = posted.find((c) => c.id === comment.id)?.body ?? answered; + const named = findingsNamedIn(text, settled, { mentioned: false }); + const threads = + comment.kind === 'review' + ? settled.some((f) => f.providerCommentId === comment.rootCommentId) + ? [comment.rootCommentId!] + : [] + : threadsOf(named.length || job.unmentioned ? named : settled); + await resolveThreads(threads); + await unacknowledge(); return; } } @@ -160,6 +214,8 @@ export async function runChatJob( chatFinding(findings, comment.rootCommentId) ?? bodyFinding; const findingIds = finding ? (named.length ? named.map((f) => f.id) : [finding.id]) : []; + // Only the pull request's author settles a finding; anyone else gets an answer. + const byAuthor = comment.author.toLowerCase() === pr.author.toLowerCase(); let settled = false; const learnings = await results.listLearnings(job.repository); @@ -211,24 +267,24 @@ export async function runChatJob( sourceUrl: comment.url }); }, - onMarkFinding: finding - ? async (status, reason) => { - await results.updateFindings(pull, findingIds, { status, reason }); - settled = true; - } - : undefined, + onMarkFinding: + finding && byAuthor + ? async (status, reason) => { + await results.updateFindings(pull, findingIds, { status, reason }); + settled = true; + } + : undefined, sandbox: sandbox?.runner }).finally(() => sandbox?.close()); }); await reply(`${answer}\n\n${marker}`); - // A finding settled in the conversation (fixed, or intended) closes its thread after the answer. + await unacknowledge(); + // A finding settled in the conversation (fixed, or intended) closes its thread after the + // answer: the one replied in, or the threads of the inline findings a conversation comment + // named. if (settled) { - if (comment.rootCommentId) { - await github - .resolveReviewThreads(job.pullNumber, [comment.rootCommentId]) - .catch((error: unknown) => log.warn('could not resolve thread', { err: error })); - } + const threads = comment.rootCommentId ? [comment.rootCommentId] : threadsOf(named); // Keep the summary, grade, check run and approval in sync with the settled finding. await refreshSummaryAfterSettlement({ results, @@ -242,13 +298,17 @@ export async function runChatJob( }).catch((error: unknown) => log.warn('could not refresh summary after settlement', { err: error }) ); + await resolveThreads(threads); } log.info('chat reply posted'); } catch (error) { // Tell the person the answer failed, once retries are exhausted. The reply is fixed: // the error can name a provider or include request details, and it stays in the logs. const notice = chatFailureReply(attempt); - if (notice) await reply(notice).catch(() => {}); + if (notice) { + await reply(notice).catch(() => {}); + await unacknowledge(); + } throw error; } finally { if (usage.length) { @@ -259,6 +319,11 @@ export async function runChatJob( } } +/** The threads of inline findings, each once; findings listed in a review body have none. */ +function threadsOf(findings: readonly { providerCommentId: string | null }[]): string[] { + return [...new Set(findings.flatMap((f) => (f.providerCommentId ? [f.providerCommentId] : [])))]; +} + /** * A thread, oldest first, up to and including one comment. Ids are opaque, so the cut goes by * position; a thread without the comment is kept whole. diff --git a/packages/engine/src/github.ts b/packages/engine/src/github.ts index 52cea62..0b8d31f 100644 --- a/packages/engine/src/github.ts +++ b/packages/engine/src/github.ts @@ -140,6 +140,11 @@ export interface GitHubClient { pullNumber: number, comment: { id: string; kind: 'issue' | 'review' } ): Promise; + /** Swaps Hansi's 👀 on a comment for 👍 once it has been answered, where the provider can. */ + finishAcknowledgement( + pullNumber: number, + comment: { id: string; kind: 'issue' | 'review' } + ): Promise; /** A review comment thread: the root comment and its replies, oldest first. */ getReviewThread(pullNumber: number, rootCommentId: string): Promise; diff --git a/packages/engine/src/prompts.ts b/packages/engine/src/prompts.ts index 679c29a..363302f 100644 --- a/packages/engine/src/prompts.ts +++ b/packages/engine/src/prompts.ts @@ -208,7 +208,11 @@ function findingInstruction( reply: ChatReplyContext | undefined, policy: ChatReplyPolicy ): string { - if (!aboutFinding) return ''; + if (!aboutFinding) { + return reply?.finding + ? `\n- This conversation is about a finding you posted ("${reply.finding.title}"), but only the pull request's author can resolve or dismiss it, and the commenter is not the author. Answer them, and do not say the finding is resolved or dismissed.` + : ''; + } const finding = reply?.finding; const association = reply?.authorAssociation; if (policy.acceptReasonedDecline && finding && association) { diff --git a/packages/engine/src/review-job.test.ts b/packages/engine/src/review-job.test.ts index f4d1a75..69889be 100644 --- a/packages/engine/src/review-job.test.ts +++ b/packages/engine/src/review-job.test.ts @@ -368,6 +368,7 @@ describe('runReviewJob', () => { ); expect(github.reactions).toEqual([{ id: '55', kind: 'issue' }]); + expect(github.finishedReactions).toEqual([{ id: '55', kind: 'issue' }]); expect(github.issueComments.map((c) => c.body)).toEqual([ "This pull request is merged, so Hansi doesn't review it anymore." ]); diff --git a/packages/engine/src/review-job.ts b/packages/engine/src/review-job.ts index 03645c0..2bac84b 100644 --- a/packages/engine/src/review-job.ts +++ b/packages/engine/src/review-job.ts @@ -119,13 +119,36 @@ export async function runReviewJob( return; } - const outcome = await executeReview(job, context, ref, pull, attempt, signal); + let outcome: Outcome; + try { + outcome = await executeReview(job, context, ref, pull, attempt, signal); + } catch (error) { + // A retry reviews it again, so the 👀 stays until the last attempt. + if (attempt.attempts >= attempt.maxAttempts) await finishMentionAcknowledgement(job, context); + throw error; + } if (outcome.status === 'skipped') { await results.skipReview(ref, outcome.summary, outcome.headSha); } + await finishMentionAcknowledgement(job, context); log.info('review finished', { status: outcome.status }); } +/** Swaps the 👀 on the comment that asked for the review for 👍, once the review has ended. */ +async function finishMentionAcknowledgement(job: ReviewJob, context: EngineContext): Promise { + const asked = reviewMentionComment(job); + if (!asked) return; + try { + const { github } = scopeToRepository( + await context.github.forRepository(job.repository), + job.repository + ); + await github.finishAcknowledgement(job.pullNumber, asked); + } catch (error) { + context.log.warn('could not finish reaction', { err: error }); + } +} + /** * Records a skip. When a mention asked for the review, also posts the one-line explanation. * The reply uses the same comment path as a head that was already reviewed. diff --git a/packages/engine/src/scope.test.ts b/packages/engine/src/scope.test.ts index 402ee5c..ad1ddec 100644 --- a/packages/engine/src/scope.test.ts +++ b/packages/engine/src/scope.test.ts @@ -1,6 +1,11 @@ import { describe, expect, test } from 'bun:test'; import { SUMMARY_MARKER } from './format'; -import { reviewMarkerFor, scopeToRepository, summaryMarkerFor } from './scope'; +import { + reviewedByAnotherRepository, + reviewMarkerFor, + scopeToRepository, + summaryMarkerFor +} from './scope'; import { MemoryGitHub } from './testing'; // Two Appwrite projects reviewing one repository share the GitHub App: each sees only its own @@ -114,3 +119,13 @@ describe('scopeToRepository', () => { expect((await a.getPullRequest(7)).number).toBe(7); }); }); + +test("another row's summary on the pull request means another project reviews it", () => { + const own = { isBot: true, body: `${summaryMarkerFor('row1')}\n\n## Code review` }; + const other = { isBot: true, body: `${summaryMarkerFor('row2')}\n\n## Code review` }; + const quoted = { isBot: false, body: other.body }; + expect(reviewedByAnotherRepository([own], 'row1')).toBe(false); + expect(reviewedByAnotherRepository([own, quoted], 'row1')).toBe(false); + expect(reviewedByAnotherRepository([own, other], 'row1')).toBe(true); + expect(reviewedByAnotherRepository([{ isBot: true, body: SUMMARY_MARKER }], 'row1')).toBe(false); +}); diff --git a/packages/engine/src/scope.ts b/packages/engine/src/scope.ts index 412addf..4ac521a 100644 --- a/packages/engine/src/scope.ts +++ b/packages/engine/src/scope.ts @@ -15,6 +15,22 @@ export function summaryMarkerFor(repositoryId: string): string { return ``; } +const SUMMARY_MARKER_PREFIX = ` new' }], ['POST', `${REPO}/issues/comments/5/reactions`, { content: 'eyes' }], ['POST', `${PULL}/comments/5/replies`, { body: 'Done' }], + ['POST', `${REPO}/issues/comments/5/reactions`, { content: '+1' }], + ['DELETE', `${REPO}/issues/comments/5/reactions`, { content: 'eyes' }], ['POST', `${REPO}/pulls/comments/5/resolve`, undefined] ]); }); diff --git a/packages/gitea/src/client.ts b/packages/gitea/src/client.ts index bf73b10..5696f55 100644 --- a/packages/gitea/src/client.ts +++ b/packages/gitea/src/client.ts @@ -362,6 +362,13 @@ export class GiteaClient implements GitHubClient { ); } + async finishAcknowledgement(_pullNumber: number, comment: { id: string }): Promise { + const path = `${this.path}/issues/comments/${encodeURIComponent(comment.id)}/reactions`; + await this.api.request('POST', path, { body: { content: '+1' } }); + // Gitea removes the caller's own reaction with that content. + await this.api.request('DELETE', path, { body: { content: 'eyes' } }); + } + async getReviewThread(pullNumber: number, rootCommentId: string): Promise { const thread = (await this.threads(pullNumber)).find( (comments) => String(comments[0]!.id) === rootCommentId diff --git a/packages/github/src/client.ts b/packages/github/src/client.ts index 5766395..e26850e 100644 --- a/packages/github/src/client.ts +++ b/packages/github/src/client.ts @@ -149,6 +149,13 @@ export class OctokitGitHubClient implements GitHubClient { }); } + finishAcknowledgement(_pullNumber: number, comment: { id: string; kind: 'issue' | 'review' }) { + return pulls.finishAcknowledgement(this.octokit, this.ref, { + id: Number(comment.id), + kind: comment.kind + }); + } + async getReviewThread(pullNumber: number, rootCommentId: string): Promise { const thread = await pulls.getReviewThread( this.octokit, diff --git a/packages/github/src/pulls.test.ts b/packages/github/src/pulls.test.ts index ff42db8..34deb49 100644 --- a/packages/github/src/pulls.test.ts +++ b/packages/github/src/pulls.test.ts @@ -2,6 +2,7 @@ import { expect, test } from 'bun:test'; import type { Octokit } from 'octokit'; import { dismissChangeRequests, + finishAcknowledgement, getFailedChecks, getLinkedIssues, getPullRequest, @@ -347,3 +348,42 @@ test('isTrustedAuthor does not read the commit of a bot from a fork', async () = expect(await isTrustedAuthor(octokit, { owner: 'o', repo: 'r' }, fork)).toBe(false); expect(read).toBe(false); }); + +test("finishAcknowledgement adds 👍 and deletes the bot's own 👀", async () => { + const calls: string[] = []; + const reaction = + (name: string) => + async ({ comment_id, content }: { comment_id: number; content: string }) => { + calls.push(`${name} ${comment_id} ${content}`); + return { data: { id: content === 'eyes' ? 77 : 78 } }; + }; + const deletion = + (name: string) => + async ({ comment_id, reaction_id }: { comment_id: number; reaction_id: number }) => { + calls.push(`${name} ${comment_id} ${reaction_id}`); + return {}; + }; + const octokit = { + rest: { + reactions: { + createForIssueComment: reaction('create-issue'), + deleteForIssueComment: deletion('delete-issue'), + createForPullRequestReviewComment: reaction('create-review'), + deleteForPullRequestComment: deletion('delete-review') + } + } + } as unknown as Octokit; + const ref = { owner: 'o', repo: 'r' }; + + await finishAcknowledgement(octokit, ref, { id: 5, kind: 'issue' }); + await finishAcknowledgement(octokit, ref, { id: 6, kind: 'review' }); + + expect(calls).toEqual([ + 'create-issue 5 +1', + 'create-issue 5 eyes', + 'delete-issue 5 77', + 'create-review 6 +1', + 'create-review 6 eyes', + 'delete-review 6 77' + ]); +}); diff --git a/packages/github/src/pulls.ts b/packages/github/src/pulls.ts index ea2042f..5cb759d 100644 --- a/packages/github/src/pulls.ts +++ b/packages/github/src/pulls.ts @@ -523,6 +523,33 @@ export async function acknowledgeComment( } } +/** + * Swaps the bot's 👀 on a comment for 👍: done. Creating a reaction that already exists answers + * with the existing one, so the 👀's id is found without knowing the bot's login. + */ +export async function finishAcknowledgement( + octokit: Octokit, + ref: RepoRef, + comment: { id: number; kind: 'issue' | 'review' } +) { + const target = { ...ref, comment_id: comment.id }; + if (comment.kind === 'issue') { + await octokit.rest.reactions.createForIssueComment({ ...target, content: '+1' }); + const { data } = await octokit.rest.reactions.createForIssueComment({ + ...target, + content: 'eyes' + }); + await octokit.rest.reactions.deleteForIssueComment({ ...target, reaction_id: data.id }); + } else { + await octokit.rest.reactions.createForPullRequestReviewComment({ ...target, content: '+1' }); + const { data } = await octokit.rest.reactions.createForPullRequestReviewComment({ + ...target, + content: 'eyes' + }); + await octokit.rest.reactions.deleteForPullRequestComment({ ...target, reaction_id: data.id }); + } +} + /** The bot's marked comment on an issue, if one exists. */ export async function getMarkedComment( octokit: Octokit, diff --git a/packages/gitlab/src/client.test.ts b/packages/gitlab/src/client.test.ts index 84db1d1..45e1650 100644 --- a/packages/gitlab/src/client.test.ts +++ b/packages/gitlab/src/client.test.ts @@ -396,6 +396,27 @@ describe('GitLabClient', () => { expect(await github.getFileContent('missing.yml', 'base')).toBeNull(); }); + test('swaps only its own eyes for a thumbs up', async () => { + const { github } = await connect({ + [`POST ${MR}/notes/5/award_emoji`]: () => Response.json({}), + [`GET ${MR}/notes/5/award_emoji`]: () => + Response.json([ + { id: 1, name: 'eyes', user: { id: 1, username: 'ada' } }, + { id: 2, name: 'thumbsup', user: bot }, + { id: 3, name: 'eyes', user: bot } + ]), + [`DELETE ${MR}/notes/5/award_emoji/3`]: () => new Response(null, { status: 204 }) + }); + + await github.finishAcknowledgement(7, { id: '5', kind: 'issue' }); + + expect(seen.find((s) => s.method === 'POST')?.body).toEqual({ name: 'thumbsup' }); + expect(seen.map((s) => `${s.method} ${s.path}`).slice(-2)).toEqual([ + `GET ${MR}/notes/5/award_emoji`, + `DELETE ${MR}/notes/5/award_emoji/3` + ]); + }); + test('reacts with eyes and links only issues of this project', async () => { const { github } = await connect({ [`POST ${MR}/notes/5/award_emoji`]: () => Response.json({}), diff --git a/packages/gitlab/src/client.ts b/packages/gitlab/src/client.ts index 142bbce..bbb6cf6 100644 --- a/packages/gitlab/src/client.ts +++ b/packages/gitlab/src/client.ts @@ -404,6 +404,16 @@ export class GitLabClient implements GitHubClient { ); } + async finishAcknowledgement(pullNumber: number, comment: { id: string }): Promise { + const path = `${this.mergeRequestPath(pullNumber)}/notes/${encodeURIComponent(comment.id)}/award_emoji`; + await this.api.request('POST', path, { body: { name: 'thumbsup' } }); + const awards = await this.api.request<{ id: number; name: string; user: User }[]>('GET', path); + for (const award of awards) { + if (award.name !== 'eyes' || !this.isOwn(award.user)) continue; + await this.api.request('DELETE', `${path}/${award.id}`); + } + } + async getReviewThread(pullNumber: number, rootCommentId: string): Promise { const discussion = await this.api.request( 'GET', diff --git a/packages/origin/src/client.ts b/packages/origin/src/client.ts index 8b60bcc..d3c1f3a 100644 --- a/packages/origin/src/client.ts +++ b/packages/origin/src/client.ts @@ -370,6 +370,15 @@ export class OriginClient implements GitHubClient { ); } + /** Origin has no way to take a reaction back, so the 👍 joins the 👀. */ + async finishAcknowledgement(_pullNumber: number, comment: { id: string }): Promise { + await this.api.request( + 'POST', + `${this.path}/pulls/comments/${encodeURIComponent(comment.id)}/reactions`, + { emoji: '👍' } + ); + } + async getReviewThread(pullNumber: number, rootCommentId: string): Promise { const comments = await this.comments(pullNumber, { threadIds: [rootCommentId] }); return comments.map((comment) => this.threadComment(comment));