Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubPullRequestProvider.ts

842 lines31.2 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage";
3import * as Cache from "effect/Cache";
4import * as Duration from "effect/Duration";
5import * as Equal from "effect/Equal";
6import * as Exit from "effect/Exit";
7import * as Hash from "effect/Hash";
8import * as Effect from "effect/Effect";
9import type {
10 PullRequestActor,
11 PullRequestCapabilities,
12 PullRequestCheck,
13 PullRequestReaction,
14 PullRequestViewerPermissions,
15} from "@t3tools/contracts";
16​
17import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
18import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
19import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
20import {
21 PullRequestProviderError,
22 type PullRequestProviderFailure,
23 type ProviderChangeRequestActivity,
24 type ProviderChangeRequestDetail,
25 type PullRequestProviderApi,
26 type ProviderRepositoryRef,
27} from "@t3tools/source-control-core/server/PullRequestProvider";
28import type { GitHubCredentialSource } from "./GitHubCredentials.ts";
29import type {
30 GitHubRepositoryAccess,
31 GitHubViewerAccess,
32 GitHubWorkflowRunApproval,
33} from "./gitHubPullRequestJson.ts";
34import { definition } from "../shared/definition.ts";
35​
36/**
37 * `review-requested:<viewer>` search rows include the viewer's team requests, which name no login,
38 * so record the viewer as requested. Search rows only: the listing fallback cannot tell whether the
39 * viewer belongs to a requested team.
40 */
41function withViewerRequested<T extends { readonly reviewRequestLogins: ReadonlyArray<string> }>(
42 item: T,
43 input: { readonly involvement: string; readonly viewer: string },
44): T {
45 const viewer = input.viewer.toLowerCase();
46 return input.involvement === "reviewing" &&
47 !item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer)
48 ? { ...item, reviewRequestLogins: [...item.reviewRequestLogins, input.viewer] }
49 : item;
51​
52const CAPABILITIES: PullRequestCapabilities = {
53 diff: true,
54 comment: true,
55 actions: [...definition.changeRequestActions],
56 mergeMethods: ["merge", "squash", "rebase"],
57 deleteBranch: true,
58 updateMethods: ["merge", "rebase"],
59 search: true,
60 reactions: true,
61 mentions: true,
62 referenceSigils: ["#"],
63 viewedFiles: "host",
64 review: {
65 inlineComment: true,
66 rangeComment: true,
67 reply: true,
68 resolve: true,
69 verdicts: ["comment", "approve", "request-changes"],
70 },
71 reviewers: { request: true, listCandidates: true, searchCandidates: true },
72 edit: { changeRequest: true, comment: true, maintainerEdits: true },
73 stacks: true,
74 stackActions: true,
75 stackAutoMerge: true,
76 labels: true,
77 // Statuses and check runs land on the head commit itself and are read whole, so an empty list
78 // after a push is CI that never started rather than a read that saw nothing.
79 checksAlwaysReport: true,
80 withheldFileDiff: true,
81};
82​
83const UNAVAILABLE_REQUIREMENT = {
84 missing:
85 "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI (https://cli.github.com/) and run `gh auth login`.",
86 unauthenticated:
87 "GitHub has no working credential for this host. Run `gh auth login`, or check the account and hosts in Settings → Source control & issues.",
88};
89​
90/**
91 * Asking somebody else for a review needs write access, which is the one thing here an author
92 * cannot do on their own pull request: GitHub shows an outside contributor the reviewer control
93 * and refuses the request behind it.
94 */
95export function gitHubViewerPermissions(
96 access: GitHubViewerAccess & Pick<GitHubRepositoryAccess, "autoMergeAllowed">,
97): PullRequestViewerPermissions {
98 return {
99 ...(access.canWrite ? { stackRebase: true } : {}),
100 actions: [
101 ...(access.canDeleteBranch === true ? (["delete-branch"] as const) : []),
102 // Keep disabling available if the repository has since turned auto-merge off.
103 ...(access.canWrite
104 ? ([
105 "merge",
106 ...(access.autoMergeAllowed && access.canMergeNow !== true
107 ? (["enable-auto-merge"] as const)
108 : []),
109 "disable-auto-merge",
110 "revert",
111 "approve-workflows",
112 ] as const)
113 : []),
114 ...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
115 ...(access.canUpdateBranch === true ? (["update-branch"] as const) : []),
116 ],
117 comment: true,
118 resolve: access.canWrite || access.didAuthor,
119 // Authors may comment on their own PRs, but GitHub rejects their approvals and change requests.
120 verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
121 requestReviewers: access.canWrite,
122 ...(access.canUpdateBranch === true ? { updateMethods: CAPABILITIES.updateMethods } : {}),
123 labels: access.canTriage,
124 };
126​
127function gitHubProviderFailure(
128 error: GitHubPullRequestApi.GitHubPullRequestApiError,
129): PullRequestProviderFailure {
130 switch (error._tag) {
131 case "GitHubCliMissingError":
132 return { reason: "missing-tool" };
133 case "GitHubNotSignedInError":
134 case "GitHubHostDisabledError":
135 case "SettingsSecretUnresolvedError":
136 case "GitHubApiAuthenticationError":
137 return { reason: "unauthenticated" };
138 case "GitHubApiRateLimitError":
139 return {
140 reason: "rate-limited",
141 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
142 };
143 case "SourceControlRateLimitPausedError":
144 return { reason: "rate-limited", retryAt: error.retryAt };
145 case "GitHubApiResponseError":
146 return {
147 reason: GitHubRequestPolicy.isForbiddenResponse(error) ? "forbidden" : "failed",
148 };
149 case "GitHubApiNotFoundError":
150 return error.credential === undefined || error.credential === "app"
151 ? { reason: "not-found" }
152 : { reason: "not-found", accessHint: REPOSITORY_ACCESS_HINTS[error.credential] };
153 default:
154 return { reason: "failed" };
155 }
157​
158const REPOSITORY_ACCESS_HINTS: Record<Exclude<GitHubCredentialSource, "app">, string> = {
159 settings:
160 "Your saved GitHub token can't see it. Give it access, or change it in Settings → Source control & issues.",
161 env: "The server's environment token can't see it. Give it access, or unset it.",
162 gh: "Your gh login can't see it. Give it access, or save a token in Settings → Source control & issues.",
163};
164​
165function withAvatar(
166 actor: PullRequestActor | null,
167 avatarsByLogin: ReadonlyMap<string, string>,
168 host: string,
169 botLogins?: ReadonlySet<string>,
170): PullRequestActor | null {
171 if (actor === null) return actor;
172 if (botLogins?.has(actor.login)) actor = { ...actor, isBot: true };
173 if (actor.avatarUrl !== null) return actor;
174 const avatarUrl = avatarsByLogin.get(actor.login) ?? loginAvatarUrl(actor.login, host);
175 return avatarUrl === null ? actor : { ...actor, avatarUrl };
177​
178const workflowRunIdOf = (url: string | null) =>
179 url?.match(/\/actions\/runs\/(\d+)(?:\/|$)/)?.[1] ?? null;
180​
181function withWorkflowApprovals(
182 checks: ReadonlyArray<PullRequestCheck>,
183 runs: ReadonlyArray<GitHubWorkflowRunApproval>,
184 unavailable: boolean,
185): ReadonlyArray<PullRequestCheck> {
186 const representedRunIds = new Set<number>();
187 for (const check of checks) {
188 if (check.status !== "action-required" || check.url === null) continue;
189 const id = workflowRunIdOf(check.url);
190 if (id !== null) representedRunIds.add(Number(id));
191 }
192 const approvalChecks = runs
193 .filter((run) => !representedRunIds.has(run.id))
194 .map((run): PullRequestCheck => ({
195 name: run.name,
196 status: "action-required",
197 description: "A maintainer must approve this workflow before it can run.",
198 url: run.url,
199 }));
200 return [
201 ...checks,
202 ...approvalChecks,
203 ...(unavailable
204 ? [
205 {
206 name: "Workflow approval status",
207 status: "action-required" as const,
208 description: "GitHub could not determine whether workflows are awaiting approval.",
209 url: null,
210 placeholder: true,
211 },
212 ]
213 : []),
214 ];
216​
217// GitHub adds a run's check runs only as its jobs start, so a queued run can have none yet.
218function withUnfinishedWorkflowRuns(
219 checks: ReadonlyArray<PullRequestCheck>,
220 runs: ReadonlyArray<GitHubWorkflowRunApproval>,
221): ReadonlyArray<PullRequestCheck> {
222 const runningRunIds = new Set<number>();
223 for (const check of checks) {
224 if (check.status !== "pending" && check.status !== "action-required") continue;
225 const id = workflowRunIdOf(check.url);
226 if (id !== null) runningRunIds.add(Number(id));
227 }
228 return [
229 ...checks,
230 ...runs
231 .filter((run) => !runningRunIds.has(run.id))
232 .map((run): PullRequestCheck => ({
233 name: run.name,
234 status: "pending",
235 description: "This workflow run has not finished.",
236 url: run.url,
237 })),
238 ];
240​
241/** App logins have no profile page; guessed avatar URLs 404. */
242export function loginAvatarUrl(login: string, host: string): string | null {
243 return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
245​
246// Whether search covers a repository changes only when the repository is renamed or moved.
247const SEARCH_COVERAGE_TTL = Duration.hours(1);
248const SEARCH_COVERAGE_CAPACITY = 4096;
249const SEARCH_COVERAGE_CONCURRENCY = 4;
250​
251/**
252 * Whether GitHub search covers a repository. `cwd` only says where to ask, so equality ignores
253 * it and `lookup`, and every checkout of a repository shares one answer.
254 */
255class SearchCoverage {
256 readonly key: string;
257 readonly lookup: Effect.Effect<boolean, GitHubPullRequestApi.GitHubPullRequestApiError>;
258​
259 constructor(
260 host: string,
261 repository: string,
262 lookup: Effect.Effect<boolean, GitHubPullRequestApi.GitHubPullRequestApiError>,
263 ) {
264 this.key = `${host.toLowerCase()}\n${repository.trim().toLowerCase()}`;
265 this.lookup = lookup;
266 }
267​
268 [Equal.symbol](that: unknown): boolean {
269 return that instanceof SearchCoverage && that.key === this.key;
270 }
271 [Hash.symbol](): number {
272 return Hash.string(this.key);
273 }
275​
276const rendersEmpty = (body: string): boolean =>
277 body.replace(/<!--[\s\S]*?-->/g, "").trim().length === 0;
278​
279export const make = Effect.gen(function* () {
280 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
281​
282 // GitHub does not index every repository for search: a renamed one answers for its old name
283 // with silence rather than with an error. Where search has any pull request for a repository it
284 // covers it, so its silence on a page is a real empty answer; any other the caller reads on its
285 // own. A failed check is not kept.
286 const searchCoverage = yield* Cache.makeWith((request: SearchCoverage) => request.lookup, {
287 capacity: SEARCH_COVERAGE_CAPACITY,
288 timeToLive: (exit) => (Exit.isSuccess(exit) ? SEARCH_COVERAGE_TTL : Duration.zero),
289 });
290 const coverageOf = (
291 input: Parameters<NonNullable<PullRequestProviderApi["listChangeRequestsAcross"]>>[0],
292 repository: string,
293 ) =>
294 new SearchCoverage(
295 input.host,
296 repository,
297 Effect.suspend(() =>
298 cli.searchPullRequests({
299 cwd: input.cwd,
300 host: input.host,
301 repositories: [repository],
302 state: "all",
303 involvement: "all",
304 viewer: input.viewer,
305 limit: 1,
306 }),
307 ).pipe(Effect.map((batch) => batch.items.length > 0)),
308 );
309 const unresolvedBySearch = Effect.fn("GitHubPullRequestProvider.unresolvedBySearch")(function* (
310 input: Parameters<NonNullable<PullRequestProviderApi["listChangeRequestsAcross"]>>[0],
311 batch: GitHubPullRequestApi.GitHubPullRequestSearchBatch,
312 ) {
313 // A repository a page has rows for is covered without asking.
314 yield* Effect.forEach(
315 batch.items,
316 (item) => Cache.set(searchCoverage, coverageOf(input, item.repository), true),
317 { discard: true },
318 );
319 const answered = new Set(batch.items.map((item) => item.repository.trim().toLowerCase()));
320 const silent = input.repositories.filter(
321 (repository) => !answered.has(repository.trim().toLowerCase()),
322 );
323 // A truncated first slice can be silent about a covered repository whose rows are just
324 // older than the cut, so it vouches for none. Past the first slice silence from a covered
325 // repository means its rows are older rather than absent.
326 if (input.cursor === undefined && batch.truncated) return silent;
327 return yield* Effect.filter(
328 silent,
329 (repository) =>
330 Cache.get(searchCoverage, coverageOf(input, repository)).pipe(
331 Effect.map((covered) => !covered),
332 Effect.orElseSucceed(() => true),
333 ),
334 { concurrency: SEARCH_COVERAGE_CONCURRENCY },
335 );
336 });
337​
338 const fail = (operation: string) => (error: GitHubPullRequestApi.GitHubPullRequestApiError) =>
339 new PullRequestProviderError({
340 provider: SourceControlProviderKind.make("github"),
341 operation,
342 ...gitHubProviderFailure(error),
343 detail: error.message,
344 cause: error,
345 });
346​
347 const readChecks = (input: ProviderRepositoryRef & { readonly number: number }) =>
348 cli.getPullRequestDetail(input).pipe(
349 Effect.flatMap((pullRequest) =>
350 (pullRequest.state !== "open"
351 ? Effect.succeed({
352 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
353 unavailable: false,
354 })
355 : pullRequest.headSha == null || pullRequest.headRepositoryOwner == null
356 ? Effect.succeed({
357 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
358 unavailable: true,
359 })
360 : cli
361 .listWorkflowRunsRequiringApproval({
362 ...input,
363 headSha: pullRequest.headSha,
364 headBranch: pullRequest.headBranch,
365 headRepositoryOwner: pullRequest.headRepositoryOwner,
366 isCrossRepository: pullRequest.isCrossRepository === true,
367 })
368 .pipe(
369 Effect.matchEffect({
370 onFailure: (error) =>
371 error._tag === "GitHubApiRateLimitError" ||
372 error._tag === "SourceControlRateLimitPausedError"
373 ? Effect.fail(error)
374 : Effect.succeed({
375 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
376 unavailable: true,
377 }),
378 onSuccess: (runs) => Effect.succeed({ runs, unavailable: false }),
379 }),
380 )
381 ).pipe(
382 Effect.zip(
383 pullRequest.state !== "open" || pullRequest.headSha == null
384 ? Effect.succeed([] as ReadonlyArray<GitHubWorkflowRunApproval>)
385 : cli.listUnfinishedWorkflowRuns({ ...input, headSha: pullRequest.headSha }).pipe(
386 Effect.catchIf(
387 (error) =>
388 error._tag !== "GitHubApiRateLimitError" &&
389 error._tag !== "SourceControlRateLimitPausedError",
390 () => Effect.succeed([] as ReadonlyArray<GitHubWorkflowRunApproval>),
391 ),
392 ),
393 { concurrent: true },
394 ),
395 Effect.map(([workflowApprovals, unfinishedRuns]) => ({
396 ...pullRequest,
397 author: withAvatar(pullRequest.author, new Map(), input.host),
398 checks: withWorkflowApprovals(
399 withUnfinishedWorkflowRuns(pullRequest.checks, unfinishedRuns),
400 workflowApprovals.runs,
401 workflowApprovals.unavailable,
402 ),
403 ...(workflowApprovals.unavailable
404 ? {}
405 : { workflowApprovalsRequired: workflowApprovals.runs.length }),
406 })),
407 ),
408 ),
409 );
410​
411 const provider: PullRequestProviderApi = {
412 kind: SourceControlProviderKind.make("github"),
413 capabilities: CAPABILITIES,
414 unavailableRequirement: UNAVAILABLE_REQUIREMENT,
415 readsPublicHostWithoutCheckout: true,
416 batchesReads: true,
417 mergeMessageRewrite: removeAgentCredits,
418 getRoutingIdentity: (input) =>
419 cli.getRoutingIdentity(input).pipe(Effect.mapError(fail("routeIdentity"))),
420 withVerifiedCredential: (input, use) =>
421 cli
422 .withVerifiedCredential(input, (identity) => use(identity).pipe(Effect.result))
423 .pipe(Effect.mapError(fail("routeIdentity")), Effect.flatMap(Effect.fromResult)),
424​
425 getViewer: (input) =>
426 cli
427 .getViewerLogin({ cwd: input.cwd, host: input.host ?? "github.com" })
428 .pipe(Effect.mapError(fail("getViewer"))),
429​
430 listChangeRequests: (input) =>
431 cli
432 .listPullRequests({
433 cwd: input.cwd,
434 repository: input.repository,
435 host: input.host,
436 state: input.state,
437 involvement: input.involvement,
438 viewer: input.viewer,
439 limit: input.limit,
440 query: input.query,
441 cursor: input.cursor,
442 filters: input.filters,
443 })
444 .pipe(
445 Effect.mapError(fail("listChangeRequests")),
446 Effect.map((page) => ({
447 ...page,
448 items: page.items.map((item) => ({
449 ...(page.continues ? withViewerRequested(item, input) : item),
450 author: withAvatar(item.author, new Map<string, string>(), input.host),
451 })),
452 })),
453 ),
454​
455 listChangeRequestsAcross: (input) =>
456 cli
457 .searchPullRequests({
458 cwd: input.cwd,
459 host: input.host,
460 repositories: input.repositories,
461 state: input.state,
462 involvement: input.involvement,
463 viewer: input.viewer,
464 limit: input.limit,
465 query: input.query,
466 cursor: input.cursor,
467 filters: input.filters,
468 })
469 .pipe(
470 Effect.mapError(fail("listChangeRequestsAcross")),
471 Effect.flatMap((batch) =>
472 Effect.map(unresolvedBySearch(input, batch), (unresolved) => ({
473 truncated: batch.truncated,
474 items: batch.items.map((item) => ({
475 ...withViewerRequested(item, input),
476 author: withAvatar(item.author, new Map<string, string>(), input.host),
477 })),
478 unresolved,
479 })),
480 ),
481 ),
482​
483 listChangeRequestStats: (input) =>
484 cli
485 .listPullRequestStats({
486 cwd: input.cwd,
487 host: input.host,
488 changeRequests: input.changeRequests,
489 })
490 .pipe(Effect.mapError(fail("listChangeRequestStats"))),
491​
492 getChangeRequestSummary: (input) =>
493 cli.getPullRequestSummary(input).pipe(
494 Effect.map((summary) => ({
495 ...summary,
496 ...(summary.author === undefined
497 ? {}
498 : { author: withAvatar(summary.author, new Map(), input.host) }),
499 })),
500 Effect.mapError(fail("getChangeRequestSummary")),
501 ),
502​
503 getChangeRequestStack: (input) =>
504 cli.getPullRequestStack(input).pipe(Effect.mapError(fail("getChangeRequestStack"))),
505​
506 getChangeRequestWatchFingerprint: (input) =>
507 cli
508 .getPullRequestWatchFingerprint(input)
509 .pipe(Effect.mapError(fail("getChangeRequestWatchFingerprint"))),
510​
511 changeRequestEvents: (input) => cli.pullRequestEvents(input),
512​
513 getChangeRequestPreview: (input) =>
514 cli.getPullRequestPreview(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),
515​
516 getChangeRequestChecks: (input) =>
517 cli.revalidateChecks(input, readChecks(input)).pipe(
518 Effect.map(({ state, checks, workflowApprovalsRequired }) => ({
519 state,
520 checks,
521 ...(workflowApprovalsRequired === undefined ? {} : { workflowApprovalsRequired }),
522 })),
523 Effect.mapError(fail("getChangeRequestChecks")),
524 ),
525​
526 getChangeRequest: (input) =>
527 readChecks(input).pipe(
528 Effect.map((pullRequest): ProviderChangeRequestDetail => ({
529 ...pullRequest,
530 author: withAvatar(pullRequest.author, new Map<string, string>(), input.host),
531 reviewers: [
532 ...pullRequest.reviewRequestLogins.map((login) => ({
533 login,
534 name: null,
535 avatarUrl: null,
536 })),
537 ...pullRequest.reviewRequestTeams,
538 ],
539 mergeCapabilities: pullRequest.viewerAccess.mergeCapabilities,
540 viewerPermissions: {
541 ...gitHubViewerPermissions({
542 ...pullRequest.viewerAccess,
543 canUpdateBranch: pullRequest.comparison?.viewerCanUpdate === true,
544 }),
545 maintainerEdits: pullRequest.canEditMaintainerEdits,
546 },
547 baseComparison:
548 pullRequest.comparison === null || pullRequest.comparison.behindBy === null
549 ? "unknown"
550 : pullRequest.comparison.behindBy > 0
551 ? "behind"
552 : "up-to-date",
553 ...(pullRequest.comparison?.behindBy == null
554 ? {}
555 : { behindBy: pullRequest.comparison.behindBy }),
556 })),
557 Effect.mapError(fail("getChangeRequest")),
558 ),
559​
560 getChangeRequestActivity: (input) => {
561 const threadRead = cli.listReviewThreadComments(input).pipe(
562 Effect.catchIf(
563 (error) =>
564 error._tag !== "GitHubApiRateLimitError" &&
565 error._tag !== "SourceControlRateLimitPausedError",
566 () =>
567 Effect.succeed({
568 comments: [],
569 dismissalsByReviewId: new Map<string, string>(),
570 reactions: [],
571 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
572 editedAtById: new Map<string, string>(),
573 reviewThreads: [],
574 commentCount: 0,
575 truncated: true,
576 reviewThreadsTruncated: true,
577 reviewers: [],
578 avatarsByLogin: new Map<string, string>(),
579 botLogins: new Set<string>(),
580 commits: [],
581 viewer: { canUpdate: true, didAuthor: false },
582 }),
583 ),
584 );
585 return Effect.all([cli.getPullRequestActivity(input), threadRead], {
586 concurrency: 2,
587 }).pipe(
588 Effect.mapError(fail("getChangeRequestActivity")),
589 Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => {
590 const commitStats = new Map(
591 pullRequest.commits.map(({ oid, additions, deletions, changedFiles }) => [
592 oid,
593 {
594 ...(additions === undefined ? {} : { additions, deletions }),
595 ...(changedFiles === undefined ? {} : { changedFiles }),
596 },
597 ]),
598 );
599 return {
600 author: withAvatar(
601 pullRequest.author,
602 reviewThreads.avatarsByLogin,
603 input.host,
604 reviewThreads.botLogins,
605 ),
606 reviewers: reviewThreads.reviewers,
607 reactions: reviewThreads.reactions,
608 commits: (reviewThreads.commits.length > 0
609 ? reviewThreads.commits
610 : pullRequest.commits
611 ).map((commit) => ({
612 ...commit,
613 ...commitStats.get(commit.oid),
614 authors: commit.authors?.map(
615 (author) =>
616 withAvatar(
617 author,
618 reviewThreads.avatarsByLogin,
619 input.host,
620 reviewThreads.botLogins,
621 ) ?? author,
622 ),
623 })),
624 comments: [...pullRequest.comments, ...reviewThreads.comments]
625 .map((comment) => ({
626 ...comment,
627 // Dismissal reasons live on timeline events; HTML-only bot reviews need that fallback too.
628 body:
629 comment.kind === "review" &&
630 comment.reviewState?.toUpperCase() === "DISMISSED" &&
631 rendersEmpty(comment.body)
632 ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
633 : comment.body,
634 author: withAvatar(
635 comment.author,
636 reviewThreads.avatarsByLogin,
637 input.host,
638 reviewThreads.botLogins,
639 ),
640 reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
641 editedAt: reviewThreads.editedAtById.get(comment.id) ?? comment.editedAt ?? null,
642 }))
643 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
644 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
645 commentsTruncated: pullRequest.truncated || reviewThreads.truncated,
646 reviewThreadsTruncated: reviewThreads.reviewThreadsTruncated,
647 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
648 ...thread,
649 comments: thread.comments.map((comment) => ({
650 ...comment,
651 author: withAvatar(
652 comment.author,
653 reviewThreads.avatarsByLogin,
654 input.host,
655 reviewThreads.botLogins,
656 ),
657 })),
658 })),
659 };
660 }),
661 );
662 },
663​
664 getReviewThreadComments: (input) =>
665 cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),
666​
667 getViewerPermissions: (input) => {
668 const lightAccess = cli
669 .getViewerAccess({ ...input, allowReserve: true })
670 .pipe(Effect.map((access) => gitHubViewerPermissions(access)));
671 if (input.includeUpdateBranch === false) {
672 return lightAccess.pipe(Effect.mapError(fail("getViewerPermissions")));
673 }
674 return cli.getPullRequestDetail(input).pipe(
675 Effect.provideService(SourceControlRateLimit.Interactive, true),
676 Effect.map((pullRequest) =>
677 gitHubViewerPermissions({
678 ...pullRequest.viewerAccess,
679 canUpdateBranch:
680 pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true,
681 }),
682 ),
683 Effect.catchIf(
684 (error) =>
685 error._tag !== "GitHubApiRateLimitError" &&
686 error._tag !== "SourceControlRateLimitPausedError",
687 () => lightAccess,
688 ),
689 Effect.mapError(fail("getViewerPermissions")),
690 );
691 },
692​
693 getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
694​
695 getDiffFileContents: (input) =>
696 cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
697​
698 getFilesViewed: (input) =>
699 cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),
700​
701 getFileStats: (input) =>
702 cli.getPullRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),
703 setFilesViewed: (input) =>
704 cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),
705​
706 listReviewerCandidates: (input) =>
707 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
708​
709 setReviewerRequest: (input) =>
710 cli
711 .setReviewerRequest({
712 cwd: input.cwd,
713 repository: input.repository,
714 host: input.host,
715 number: input.number,
716 reviewers: input.reviewers,
717 requested: input.requested,
718 })
719 .pipe(Effect.mapError(fail("setReviewerRequest"))),
720​
721 listLabelCandidates: (input) =>
722 cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
723​
724 listRepositoryLabels: (input) =>
725 cli.listRepositoryLabels(input).pipe(Effect.mapError(fail("listRepositoryLabels"))),
726​
727 searchRepositoryAuthors: (input) =>
728 cli.searchRepositoryAuthors(input).pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
729​
730 searchRepositoryReferences: (input) =>
731 cli
732 .searchRepositoryReferences(input)
733 .pipe(Effect.mapError(fail("searchRepositoryReferences"))),
734​
735 setLabels: (input) =>
736 cli
737 .setLabels({
738 cwd: input.cwd,
739 repository: input.repository,
740 host: input.host,
741 number: input.number,
742 labels: input.labels,
743 applied: input.applied,
744 })
745 .pipe(Effect.mapError(fail("setLabels"))),
746​
747 runAction: (input) =>
748 cli
749 .runPullRequestAction({
750 cwd: input.cwd,
751 repository: input.repository,
752 host: input.host,
753 number: input.number,
754 action: input.action,
755 ...(input.removeAgentCreditsOnMerge === true ? { removeAgentCreditsOnMerge: true } : {}),
756 ...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }),
757 ...(input.expectedStackHeads === undefined
758 ? {}
759 : { expectedStackHeads: input.expectedStackHeads }),
760 ...(input.expectedHeadSha === undefined
761 ? {}
762 : { expectedHeadSha: input.expectedHeadSha }),
763 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
764 ...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
765 })
766 .pipe(Effect.mapError(fail("runAction"))),
767​
768 getCheckLogs: (input) => cli.readCheckLogs(input).pipe(Effect.mapError(fail("getCheckLogs"))),
769 rerunChecks: (input) => cli.rerunChecks(input).pipe(Effect.mapError(fail("rerunChecks"))),
770​
771 updateChangeRequest: (input) =>
772 cli
773 .updatePullRequest({
774 ...(input.maintainerCanModify === undefined
775 ? {}
776 : { maintainerCanModify: input.maintainerCanModify }),
777 cwd: input.cwd,
778 repository: input.repository,
779 host: input.host,
780 number: input.number,
781 ...(input.title === undefined ? {} : { title: input.title }),
782 ...(input.body === undefined ? {} : { body: input.body }),
783 })
784 .pipe(Effect.mapError(fail("updateChangeRequest"))),
785​
786 comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
787​
788 updateComment: (input) =>
789 cli
790 .updateComment({
791 cwd: input.cwd,
792 repository: input.repository,
793 host: input.host,
794 number: input.number,
795 commentId: input.commentId,
796 kind: input.kind,
797 body: input.body,
798 })
799 .pipe(Effect.mapError(fail("updateComment"))),
800​
801 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
802​
803 replyToThread: (input) =>
804 cli
805 .replyToReviewThread({
806 cwd: input.cwd,
807 repository: input.repository,
808 host: input.host,
809 number: input.number,
810 threadId: input.threadId,
811 body: input.body,
812 })
813 .pipe(Effect.mapError(fail("replyToThread"))),
814​
815 setReaction: (input) =>
816 cli
817 .setReaction({
818 cwd: input.cwd,
819 repository: input.repository,
820 host: input.host,
821 number: input.number,
822 ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
823 content: input.content,
824 reacted: input.reacted,
825 })
826 .pipe(Effect.mapError(fail("setReaction"))),
827​
828 setThreadResolution: (input) =>
829 cli
830 .setReviewThreadResolution({
831 cwd: input.cwd,
832 repository: input.repository,
833 host: input.host,
834 number: input.number,
835 threadId: input.threadId,
836 resolved: input.resolved,
837 })
838 .pipe(Effect.mapError(fail("setThreadResolution"))),
839 };
840​
841 return provider;
842});