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