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

OriginPullRequestProvider.ts

1,016 lines38.2 KB

1import * as Cache from "effect/Cache";
2import * as Effect from "effect/Effect";
3import * as Exit from "effect/Exit";
4import * as Fiber from "effect/Fiber";
5import * as Hash from "effect/Hash";
6import * as Option from "effect/Option";
7import * as Result from "effect/Result";
8import * as Schema from "effect/Schema";
9import type {
10 PullRequestCapabilities,
11 PullRequestComment,
12 PullRequestMergeability,
13 PullRequestReviewThread,
14 PullRequestViewerPermissions,
15} from "@t3tools/contracts";
16import { SourceControlProviderKind } from "@t3tools/contracts";
17import {
18 PullRequestProviderError,
19 type ProviderChangeRequest,
20 type ProviderChangeRequestActivity,
21 type ProviderChangeRequestDetail,
22 type ProviderRepositoryRef,
23 type PullRequestProviderApi,
24} from "@t3tools/source-control-core/server/PullRequestProvider";
25​
26import * as OriginCli from "./OriginCli.ts";
27import {
28 checksState,
29 originActor,
30 originActorId,
31 originAvatars,
32 originCheck,
33 OriginGitRefSchema,
34 OriginMergeabilitySchema,
35 preparedMergeability,
36 OriginCheckRunListSchema,
37 OriginCommentListSchema,
38 OriginCommitListSchema,
39 OriginFileListSchema,
40 originFilesPatch,
41 OriginPullRequestListSchema,
42 OriginPullRequestSchema,
43 OriginRepositorySchema,
44 OriginReviewListSchema,
45 originState,
46 originUpdatedAt,
47 type OriginAvatars,
48 type OriginComment,
49 type OriginPullRequest,
50 UNKNOWN_TIME,
51} from "./originPullRequests.ts";
52​
53const CAPABILITIES: PullRequestCapabilities = {
54 diff: true,
55 comment: true,
56 actions: ["merge", "ready", "draft", "close", "reopen"],
57 // Origin merges with a merge commit or a squash; it has no rebase merge.
58 mergeMethods: ["merge", "squash"],
59 search: false,
60 reactions: false,
61 review: {
62 inlineComment: true,
63 reply: true,
64 resolve: true,
65 verdicts: ["comment", "approve", "request-changes"],
66 },
67 // Origin can request reviewers, but lists no candidates to pick from.
68 reviewers: { request: false, listCandidates: false },
69 edit: { changeRequest: true, comment: true },
70};
71​
72/**
73 * Origin reports no per-viewer permission on a pull request, so everything the host can do is
74 * offered and Origin explains any refusal itself.
75 */
76const VIEWER_PERMISSIONS: PullRequestViewerPermissions = {
77 actions: CAPABILITIES.actions,
78 comment: true,
79 resolve: true,
80 verdicts: CAPABILITIES.review.verdicts,
81 requestReviewers: false,
82};
83​
84const PAGE_SIZE = 100;
85const EXPIRED_LIST_POSITION = "listChangeRequests.resume";
86/** Bounds each paged read, so one very long pull request cannot stall its detail. */
87const MAX_PAGES = 10;
88​
89const unsupported = (operation: string, detail: string) =>
90 Effect.fail(
91 new PullRequestProviderError({
92 provider: SourceControlProviderKind.make("cursor-origin"),
93 operation,
94 reason: "failed",
95 detail,
96 }),
97 );
98​
99function toProviderChangeRequest(pullRequest: OriginPullRequest, avatars?: OriginAvatars) {
100 return {
101 number: pullRequest.number,
102 title: pullRequest.title,
103 url: pullRequest.webUrl,
104 author: originActor(pullRequest.author, avatars),
105 headBranch: pullRequest.head.ref,
106 baseBranch: pullRequest.base.ref,
107 state: originState(pullRequest),
108 isDraft: pullRequest.draft === true,
109 // A listing cannot afford the base comparison the detail makes, so it does not guess.
110 mergeability: "unknown",
111 additions: pullRequest.additions ?? 0,
112 deletions: pullRequest.deletions ?? 0,
113 createdAt: pullRequest.createdAt?.trim() || originUpdatedAt(pullRequest),
114 closedAt: pullRequest.closedAt?.trim() || null,
115 mergedAt: pullRequest.mergedAt?.trim() || null,
116 updatedAt: originUpdatedAt(pullRequest),
117 reviewRequestLogins: [],
118 labels: (pullRequest.labels ?? []).map((label) => ({
119 name: label.name,
120 color: label.color?.replace(/^#/u, "") || "888888",
121 description: label.description ?? null,
122 })),
123 } satisfies ProviderChangeRequest;
125​
126const isThreadComment = (comment: OriginComment) => Boolean(comment.thread?.path);
127const editedAt = (comment: OriginComment) =>
128 comment.updatedAt && comment.updatedAt !== comment.createdAt ? comment.updatedAt : null;
129​
130function toThreads(
131 comments: ReadonlyArray<OriginComment>,
132 avatars: OriginAvatars,
133 headSha: string | null,
134): PullRequestReviewThread[] {
135 const threads = new Map<string, PullRequestReviewThread>();
136 for (const comment of comments) {
137 const thread = comment.thread;
138 if (!thread?.path) continue;
139 const line = thread.endLine ?? thread.startLine ?? null;
140 const existing = threads.get(thread.id) ?? {
141 id: thread.id,
142 path: thread.path,
143 line: line !== null && line > 0 ? line : null,
144 side: thread.side === "left" ? ("left" as const) : ("right" as const),
145 isResolved: Boolean(thread.resolvedAt),
146 // Origin anchors a thread to the version it was left on and does not move it forward.
147 isOutdated: Boolean(headSha && thread.version?.headSha && thread.version.headSha !== headSha),
148 comments: [],
149 };
150 threads.set(thread.id, {
151 ...existing,
152 comments: [
153 ...existing.comments,
154 {
155 id: comment.id,
156 author: originActor(comment.author, avatars),
157 body: comment.body ?? "",
158 createdAt: comment.createdAt,
159 editedAt: editedAt(comment),
160 url: null,
161 },
162 ],
163 });
164 }
165 return [...threads.values()];
167​
168export const make = Effect.gen(function* () {
169 const cli = yield* OriginCli.OriginCli;
170 const scope = yield* Effect.scope;
171​
172 const fail = (operation: string) => (error: OriginCli.OriginCliError) =>
173 new PullRequestProviderError({
174 provider: SourceControlProviderKind.make("cursor-origin"),
175 operation,
176 reason: error.reason === "invalid-response" ? "failed" : error.reason,
177 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
178 detail: error.detail,
179 cause: error,
180 });
181​
182 // A repository's merge settings change rarely, and every detail read asks for them.
183 const repositorySettings = yield* Cache.makeWith(
184 (key: string) => {
185 const [cwd = "", repository = ""] = key.split("\n");
186 return recover(
187 cli.api(
188 { cwd, operation: "getRepository", path: OriginCli.originRepositoryPath(repository) },
189 OriginRepositorySchema,
190 ),
191 null,
192 );
193 },
194 {
195 capacity: 64,
196 timeToLive: (exit) => (Exit.isSuccess(exit) && exit.value !== null ? "5 minutes" : 0),
197 },
198 );
199 const getRepositorySettings = (cwd: string, repository: string) =>
200 Cache.get(repositorySettings, `${cwd}\n${repository}`);
201​
202 const pullPath = (repository: string, number: number, suffix = "") =>
203 `${OriginCli.originRepositoryPath(repository)}/pulls/${number}${suffix}`;
204​
205 // The last version of each pull request a listing or a read returned, most recent last. Reads
206 // that hang off its head and base start from it alongside the fresh read of the pull request,
207 // and are redone only when it has moved since.
208 const lastSeen = new Map<string, OriginPullRequest>();
209 const remember = (key: string, pullRequest: OriginPullRequest) => {
210 lastSeen.delete(key);
211 lastSeen.set(key, pullRequest);
212 if (lastSeen.size > 1024) lastSeen.delete(lastSeen.keys().next().value ?? "");
213 };
214 const sameBasis = (seen: OriginPullRequest, current: OriginPullRequest) =>
215 seen.head.sha === current.head.sha &&
216 seen.base.ref === current.base.ref &&
217 seen.base.sha === current.base.sha &&
218 seen.version?.headSha === current.version?.headSha &&
219 seen.version?.baseSha === current.version?.baseSha &&
220 seen.version?.potentialMergeCommit?.baseSha ===
221 current.version?.potentialMergeCommit?.baseSha &&
222 seen.version?.potentialMergeCommit?.state === current.version?.potentialMergeCommit?.state &&
223 seen.draft === current.draft &&
224 originState(seen) === originState(current);
225​
226 // Opening a pull request reads its detail and its checks at once, and both start from the pull
227 // request itself. Reads within a second share one request; this package's own writes drop it.
228 const pullKey = (input: ProviderRepositoryRef & { readonly number: number }) =>
229 `${input.cwd}\n${input.repository}\n${input.number}`;
230 const pulls = yield* Cache.makeWith(
231 (key: string) => {
232 const [cwd = "", repository = "", number = ""] = key.split("\n");
233 return cli
234 .api(
235 { cwd, operation: "getPullRequest", path: pullPath(repository, Number(number)) },
236 OriginPullRequestSchema,
237 )
238 .pipe(Effect.tap((pullRequest) => Effect.sync(() => remember(key, pullRequest))));
239 },
240 { capacity: 256, timeToLive: (exit) => (Exit.isSuccess(exit) ? "1 second" : 0) },
241 );
242 const getPull = (input: ProviderRepositoryRef & { readonly number: number }) =>
243 Cache.get(pulls, pullKey(input));
244 const forgetPull = (input: ProviderRepositoryRef & { readonly number: number }) =>
245 Cache.invalidate(pulls, pullKey(input)).pipe(
246 Effect.andThen(Effect.sync(() => lastSeen.delete(pullKey(input)))),
247 );
248​
249 /** `dependents` of the fresh pull request, started early from the last-seen version. */
250 const withPull = Effect.fn("OriginPullRequestProvider.withPull")(function* <A>(
251 input: ProviderRepositoryRef & { readonly number: number },
252 dependents: (pullRequest: OriginPullRequest) => Effect.Effect<A, OriginCli.OriginCliError>,
253 ) {
254 const seen = lastSeen.get(pullKey(input));
255 const [pullRequest, early] = yield* Effect.all(
256 [
257 getPull(input),
258 seen === undefined ? Effect.succeedNone : Effect.asSome(Effect.result(dependents(seen))),
259 ],
260 { concurrency: "unbounded" },
261 );
262 if (seen !== undefined && Option.isSome(early)) {
263 const guess = early.value;
264 // A refused or rate-limited account fails the fresh read too; asking again spends quota.
265 if (
266 Result.isFailure(guess) &&
267 (guess.failure.reason === "rate-limited" || guess.failure.reason === "unauthenticated")
268 )
269 return yield* guess.failure;
270 // A guess that fails, say for a head since force-pushed away, is only a missed head start.
271 if (sameBasis(seen, pullRequest))
272 return [pullRequest, yield* Effect.fromResult(guess)] as const;
273 }
274 return [pullRequest, yield* dependents(pullRequest)] as const;
275 });
276​
277 /** Reads every page of a list endpoint, up to `MAX_PAGES`. */
278 const readPages = Effect.fn("OriginPullRequestProvider.readPages")(function* <
279 S extends Schema.Codec<
280 { readonly nextPageToken?: string | null | undefined },
281 unknown,
282 never,
283 never
284 >,
285 A,
286 >(
287 input: { readonly cwd: string; readonly operation: string; readonly path: string },
288 schema: S,
289 items: (page: S["Type"]) => ReadonlyArray<A> | null | undefined,
290 ) {
291 const all: A[] = [];
292 const tokens = new Set<string>();
293 let token: string | null | undefined;
294 for (let page = 0; page < MAX_PAGES; page++) {
295 const query = new URLSearchParams({
296 pageSize: String(PAGE_SIZE),
297 ...(token ? { pageToken: token } : {}),
298 });
299 const result = yield* cli.api({ ...input, path: `${input.path}?${query}` }, schema);
300 all.push(...(items(result) ?? []));
301 token = result.nextPageToken;
302 if (!token) return { items: all, truncated: false };
303 // A page token seen before would only read the same pages again.
304 if (tokens.has(token)) return { items: all, truncated: true };
305 tokens.add(token);
306 }
307 return { items: all, truncated: true };
308 });
309​
310 // The detail and the checks tab both list the head commit's check runs, usually together.
311 const checkRuns = yield* Cache.makeWith(
312 (key: string) => {
313 const [cwd = "", repository = "", sha = ""] = key.split("\n");
314 return readPages(
315 {
316 cwd,
317 operation: "listChecks",
318 path: `${OriginCli.originRepositoryPath(repository)}/commits/${encodeURIComponent(sha)}/check-runs`,
319 },
320 OriginCheckRunListSchema,
321 (page) => page.checkRuns,
322 ).pipe(
323 Effect.map((page) => ({ checks: page.items.map(originCheck), truncated: page.truncated })),
324 );
325 },
326 { capacity: 256, timeToLive: (exit) => (Exit.isSuccess(exit) ? "1 second" : 0) },
327 );
328 const listChecks = (
329 input: ProviderRepositoryRef & { readonly sha: string | null | undefined },
330 ) =>
331 input.sha
332 ? Cache.get(checkRuns, `${input.cwd}\n${input.repository}\n${input.sha}`)
333 : Effect.succeed({ checks: [], truncated: false });
334​
335 const readPatch = (cwd: string, path: string) =>
336 readPages({ cwd, operation: "getDiff", path }, OriginFileListSchema, (page) => page.files).pipe(
337 Effect.map((page) => ({
338 patch: originFilesPatch(page.items),
339 // Origin leaves out the hunks of files too large to show.
340 truncated: page.truncated || page.items.some((file) => file.patch == null),
341 nextCursor: null,
342 })),
343 );
344 const versionKey = (pullRequest: OriginPullRequest) => {
345 const head = pullRequest.version?.headSha ?? pullRequest.head.sha;
346 const base = pullRequest.version?.baseSha ?? pullRequest.base.sha;
347 return head && base ? `${base}...${head}` : null;
348 };
349 // Keyed by `cwd, repository, number, base...head` for a pull request's patch, or by
350 // `cwd, repository, , commit` for one commit's.
351 const patches = yield* Cache.makeWith(
352 (key: string) => {
353 const [cwd = "", repository = "", number = "", commits = ""] = key.split("\n");
354 if (number === "")
355 return readPatch(
356 cwd,
357 `${OriginCli.originRepositoryPath(repository)}/commits/${encodeURIComponent(commits)}/files`,
358 ).pipe(Effect.map((patch) => ({ ...patch, pinned: true })));
359 // `/files` always answers for the newest version, so a push during the read must not be
360 // kept under the version the key names.
361 return readPatch(cwd, pullPath(repository, Number(number), "/files")).pipe(
362 Effect.flatMap((patch) =>
363 recover(
364 cli
365 .api(
366 { cwd, operation: "getPullRequest", path: pullPath(repository, Number(number)) },
367 OriginPullRequestSchema,
368 )
369 .pipe(Effect.map(versionKey)),
370 null,
371 ).pipe(Effect.map((version) => ({ ...patch, pinned: version === commits }))),
372 ),
373 );
374 },
375 {
376 capacity: 64,
377 timeToLive: (exit) => (Exit.isSuccess(exit) && exit.value.pinned ? "1 hour" : 0),
378 },
379 );
380​
381 // Every pull request into a branch compares against the same tip, so it is read once a moment.
382 const baseTips = yield* Cache.makeWith(
383 (key: string) => {
384 const [cwd = "", repository = "", branch = ""] = key.split("\n");
385 return cli
386 .api(
387 {
388 cwd,
389 operation: "getBaseTip",
390 path: `${OriginCli.originRepositoryPath(repository)}/git/ref/${encodeURIComponent(`heads/${branch}`)}`,
391 },
392 OriginGitRefSchema,
393 )
394 .pipe(Effect.map((ref) => ref.object?.sha ?? null));
395 },
396 { capacity: 64, timeToLive: (exit) => (Exit.isSuccess(exit) ? "2 seconds" : 0) },
397 );
398​
399 // Whether a head merges cleanly into a base never changes, and `/mergeability` counts ten times
400 // against the rate limit, so a definite answer is kept for that pair of commits.
401 const mergeabilities = yield* Cache.makeWith(
402 (key: string) => {
403 const [cwd = "", repository = "", number = "", head = ""] = key.split("\n");
404 return cli
405 .api(
406 {
407 cwd,
408 operation: "getMergeability",
409 path: pullPath(
410 repository,
411 Number(number),
412 `/mergeability?${new URLSearchParams({ expectedHeadSha: head })}`,
413 ),
414 },
415 OriginMergeabilitySchema,
416 )
417 .pipe(
418 Effect.map((answer): PullRequestMergeability =>
419 // A head pushed since the key was made answers for other commits.
420 answer.headSha && answer.headSha !== head
421 ? "unknown"
422 : (answer.blockers ?? []).some((blocker) => blocker.kind === "merge_conflict")
423 ? "conflicting"
424 : answer.verdict === "mergeable"
425 ? "mergeable"
426 : "unknown",
427 ),
428 );
429 },
430 {
431 capacity: 256,
432 timeToLive: (exit) => (Exit.isSuccess(exit) && exit.value !== "unknown" ? "1 hour" : 0),
433 },
434 );
435​
436 /**
437 * Origin prepares a merge for every version, against the base as it stood then. While that is
438 * still the base's tip, the prepared merge is the answer, for one ref read; once the base has
439 * moved, only `/mergeability` knows.
440 */
441 const mergeabilityOf = (
442 input: ProviderRepositoryRef & { readonly number: number },
443 pullRequest: OriginPullRequest,
444 ): Effect.Effect<PullRequestMergeability, OriginCli.OriginCliError> => {
445 if (originState(pullRequest) !== "open" || !pullRequest.head.sha)
446 return Effect.succeed("unknown");
447 return recover(
448 Cache.get(baseTips, `${input.cwd}\n${input.repository}\n${pullRequest.base.ref}`),
449 null,
450 ).pipe(
451 // Without the base's tip there is nothing to judge a merge against.
452 Effect.flatMap((tip) =>
453 tip === null
454 ? Effect.succeed("unknown" as const)
455 : tip ===
456 (pullRequest.version?.potentialMergeCommit?.baseSha ?? pullRequest.version?.baseSha)
457 ? Effect.succeed(preparedMergeability(pullRequest))
458 : recover(
459 Cache.get(
460 mergeabilities,
461 `${input.cwd}\n${input.repository}\n${input.number}\n${pullRequest.head.sha}\n${tip}\n${pullRequest.base.ref}`,
462 ),
463 "unknown",
464 ),
465 ),
466 );
467 };
468​
469 // Avatars only change when someone replaces their picture, so each actor's is read once per
470 // server. An actor the CLI reports without one is cached as "" so it is not asked about again.
471 const avatarCache = new Map<string, string>();
472 let avatarRead: Fiber.Fiber<OriginAvatars> | null = null;
473 const avatarsFor = Effect.fn("OriginPullRequestProvider.avatarsFor")(function* (
474 cwd: string,
475 actors: ReadonlyArray<Parameters<typeof originActorId>[0]>,
476 args: ReadonlyArray<string>,
477 ) {
478 if (
479 actors.every((actor) => {
480 const id = originActorId(actor);
481 return id === null || avatarCache.has(id);
482 })
483 )
484 return avatarCache;
485 if (avatarRead !== null) yield* Fiber.join(avatarRead);
486 const missing = actors
487 .map(originActorId)
488 .filter((id): id is string => id !== null && !avatarCache.has(id));
489 return missing.length > 0 ? yield* readAvatars(cwd, args, missing) : avatarCache;
490 });
491 const readAvatars = (
492 cwd: string,
493 args: ReadonlyArray<string>,
494 ids: ReadonlyArray<string> = [],
495 ): Effect.Effect<OriginAvatars> =>
496 cli.execute({ cwd, operation: "readAvatars", args }).pipe(
497 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown))),
498 Effect.map((json) => {
499 for (const [id, url] of originAvatars(json)) avatarCache.set(id, url);
500 for (const id of ids) if (!avatarCache.has(id)) avatarCache.set(id, "");
501 return avatarCache;
502 }),
503 // A picture is decoration: a failed read leaves initials rather than failing the page.
504 Effect.orElseSucceed(() => avatarCache),
505 );
506 const initialAvatars = Effect.fnUntraced(function* (cwd: string, args: ReadonlyArray<string>) {
507 if (avatarCache.size > 0) return avatarCache;
508 if (avatarRead === null)
509 avatarRead = yield* Effect.forkIn(
510 readAvatars(cwd, args).pipe(
511 Effect.ensuring(
512 Effect.sync(() => {
513 avatarRead = null;
514 }),
515 ),
516 ),
517 scope,
518 );
519 return yield* Fiber.join(avatarRead);
520 });
521​
522 /** `origin pr view` arguments that print `fields` for one pull request, avatars included. */
523 const viewArgs = (
524 input: { readonly repository: string; readonly number: number },
525 fields: string,
526 ) => ["pr", "view", String(input.number), "-R", input.repository, "--json", fields];
527​
528 // Nothing reads a write's answer, so it is not decoded: a body this version cannot read must not
529 // turn a write that landed into a failure the user retries.
530 const write = (
531 input: { readonly cwd: string },
532 operation: string,
533 method: "POST" | "PATCH",
534 path: string,
535 body: unknown,
536 ) =>
537 cli
538 .api({ cwd: input.cwd, operation, method, path, body }, Schema.Unknown)
539 .pipe(Effect.asVoid, Effect.mapError(fail(operation)));
540​
541 const recover = <A>(
542 read: Effect.Effect<A, OriginCli.OriginCliError>,
543 fallback: A,
544 keepNotFound = false,
545 ) =>
546 read.pipe(
547 Effect.catchIf(
548 (error) =>
549 error.reason !== "rate-limited" &&
550 error.reason !== "unauthenticated" &&
551 !(keepNotFound && error.reason === "not-found"),
552 () => Effect.succeed(fallback),
553 ),
554 );
555​
556 // Origin pages by a token longer than the service's cursor can carry, so the cursor names it by
557 // hash. A cursor from before a restart, or one evicted since, fails and asks for a refresh.
558 const pageTokens = new Map<string, string>();
559 const pageTokenKey = (token: string) => {
560 const key = `${(Hash.string(token) >>> 0).toString(36)}-${token.length}`;
561 pageTokens.delete(key);
562 pageTokens.set(key, token);
563 if (pageTokens.size > 256) pageTokens.delete(pageTokens.keys().next().value ?? "");
564 return key;
565 };
566​
567 // Origin merges a stacked pull request together with every open one below it, which the panel
568 // does not show, so those merges are left to Origin.
569 const refuseStackedMerge = Effect.fn("OriginPullRequestProvider.refuseStackedMerge")(function* (
570 input: ProviderRepositoryRef & { readonly number: number },
571 ) {
572 const read = (number: number) =>
573 getPull({ ...input, number }).pipe(Effect.mapError(fail("runAction")));
574 const parent = (yield* read(input.number)).stack?.parentPullRequest?.number;
575 if (parent == null) return;
576 if (originState(yield* read(Number(parent))) !== "open") return;
577 return yield* unsupported(
578 "runAction",
579 `This pull request is stacked on #${parent}. Merge #${parent} first, or merge the stack on Cursor Origin.`,
580 );
581 });
582​
583 const provider: PullRequestProviderApi = {
584 kind: SourceControlProviderKind.make("cursor-origin"),
585 capabilities: CAPABILITIES,
586​
587 getViewer: Effect.fn("OriginPullRequestProvider.getViewer")(
588 function* (input) {
589 if (avatarCache.size === 0 && avatarRead === null) {
590 // The first list follows sign-in, so its pictures can be read while sign-in is checked.
591 yield* Effect.forkIn(
592 cli.resolveRepository({ cwd: input.cwd }).pipe(
593 Effect.flatMap((repository) =>
594 initialAvatars(input.cwd, [
595 "pr",
596 "list",
597 "-R",
598 repository,
599 "-s",
600 "all",
601 "-L",
602 String(PAGE_SIZE),
603 "--json",
604 "author",
605 ]),
606 ),
607 Effect.ignore,
608 ),
609 scope,
610 );
611 }
612 return yield* cli.viewer(input.cwd);
613 },
614 Effect.mapError(fail("getViewer")),
615 ),
616​
617 listChangeRequests: Effect.fn("OriginPullRequestProvider.listChangeRequests")(
618 function* (input) {
619 const limit = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
620 const resume = input.cursor?.resumeAfter;
621 const pageToken = resume === undefined ? undefined : pageTokens.get(resume);
622 if (resume !== undefined && pageToken === undefined)
623 return yield* new OriginCli.OriginCliError({
624 operation: EXPIRED_LIST_POSITION,
625 cwd: input.cwd,
626 reason: "failed",
627 detail: "This list position has expired. Refresh the list to load more pull requests.",
628 });
629 const query = new URLSearchParams({
630 state: input.state,
631 pageSize: String(limit),
632 sortBy: "updated",
633 ...(input.involvement === "authored" ? { author: input.viewer } : {}),
634 ...(pageToken === undefined ? {} : { pageToken }),
635 });
636 const avatarArgs = [
637 "pr",
638 "list",
639 "-R",
640 input.repository,
641 "-s",
642 input.state,
643 "-L",
644 String(limit),
645 "--json",
646 "author",
647 ];
648 // Share a sign-in's read, or start the pictures alongside the first list.
649 const [page] = yield* Effect.all(
650 [
651 cli.api(
652 {
653 cwd: input.cwd,
654 operation: "listChangeRequests",
655 path: `${OriginCli.originRepositoryPath(input.repository)}/pulls?${query}`,
656 },
657 OriginPullRequestListSchema,
658 ),
659 initialAvatars(input.cwd, avatarArgs),
660 ],
661 { concurrency: "unbounded" },
662 );
663 const pullRequests = page.pullRequests ?? [];
664 for (const pullRequest of pullRequests)
665 remember(pullKey({ ...input, number: pullRequest.number }), pullRequest);
666 // `origin pr list` only reads the first page, so later pages use the pictures already read.
667 const avatars =
668 input.cursor === undefined
669 ? yield* avatarsFor(
670 input.cwd,
671 pullRequests.map((pullRequest) => pullRequest.author),
672 avatarArgs,
673 )
674 : avatarCache;
675 const next = page.nextPageToken || null;
676 return {
677 items: pullRequests.map((pullRequest) => toProviderChangeRequest(pullRequest, avatars)),
678 truncated: next !== null,
679 continues: next !== null,
680 ...(next === null ? {} : { resumeAfter: pageTokenKey(next) }),
681 };
682 },
683 Effect.mapError((error) =>
684 // The list shows only a failure's access hint, and this one needs its refresh advice.
685 error.operation === EXPIRED_LIST_POSITION
686 ? new PullRequestProviderError({
687 provider: SourceControlProviderKind.make("cursor-origin"),
688 operation: "listChangeRequests",
689 reason: "failed",
690 detail: error.detail,
691 accessHint: error.detail,
692 cause: error,
693 })
694 : fail("listChangeRequests")(error),
695 ),
696 ),
697​
698 // One read: linked threads poll this, and the full detail costs four.
699 getChangeRequestSummary: (input) =>
700 getPull(input).pipe(
701 Effect.map((pullRequest) => {
702 const summary = toProviderChangeRequest(pullRequest, avatarCache);
703 return {
704 number: summary.number,
705 title: summary.title,
706 url: summary.url,
707 headBranch: summary.headBranch,
708 baseBranch: summary.baseBranch,
709 state: summary.state,
710 isDraft: summary.isDraft,
711 closedAt: summary.closedAt ?? null,
712 mergedAt: summary.mergedAt ?? null,
713 updatedAt: summary.updatedAt,
714 author: summary.author,
715 additions: summary.additions,
716 deletions: summary.deletions,
717 changedFiles: pullRequest.changedFiles ?? 0,
718 };
719 }),
720 Effect.mapError(fail("getChangeRequestSummary")),
721 ),
722​
723 getChangeRequestChecks: (input) =>
724 withPull(input, (pullRequest) => listChecks({ ...input, sha: pullRequest.head.sha })).pipe(
725 Effect.map(([pullRequest, { checks }]) => ({ state: originState(pullRequest), checks })),
726 Effect.mapError(fail("getChangeRequestChecks")),
727 ),
728​
729 getChangeRequest: Effect.fn("OriginPullRequestProvider.getChangeRequest")(
730 function* (input) {
731 const [[pullRequest, [checkRead, avatars, mergeability]], repository] = yield* Effect.all(
732 [
733 withPull(input, (pullRequest) =>
734 Effect.all(
735 [
736 recover(listChecks({ ...input, sha: pullRequest.head.sha }), {
737 checks: [],
738 truncated: false,
739 }),
740 avatarsFor(input.cwd, [pullRequest.author], viewArgs(input, "author")),
741 mergeabilityOf(input, pullRequest),
742 ],
743 { concurrency: "unbounded" },
744 ),
745 ),
746 getRepositorySettings(input.cwd, input.repository),
747 ],
748 { concurrency: "unbounded" },
749 );
750 const { checks, truncated } = checkRead;
751 const rollup = checksState(checks);
752 const detail: ProviderChangeRequestDetail = {
753 ...toProviderChangeRequest(pullRequest, avatars),
754 mergeability,
755 // Checks past the last page read are unknown, so all-green ones read are not a pass.
756 checksState: truncated && rollup === "passing" ? "pending" : rollup,
757 headSha: pullRequest.head.sha ?? null,
758 body: pullRequest.body ?? "",
759 changedFiles: pullRequest.changedFiles ?? 0,
760 reviewers: [],
761 checks,
762 mergeCapabilities: {
763 merge: repository?.allowMergeCommit ?? true,
764 squash: repository?.allowSquashMerge ?? true,
765 rebase: false,
766 },
767 viewerPermissions: VIEWER_PERMISSIONS,
768 };
769 return detail;
770 },
771 Effect.mapError(fail("getChangeRequest")),
772 ),
773​
774 getChangeRequestActivity: (input) => {
775 // A part that cannot be read shows as empty and truncated rather than failing the rest.
776 const part = (operation: string, suffix: string) => ({
777 cwd: input.cwd,
778 operation,
779 path: pullPath(input.repository, input.number, suffix),
780 });
781 const unread = { items: [], truncated: true };
782 return Effect.all(
783 [
784 recover(
785 readPages(
786 part("listComments", "/comments"),
787 OriginCommentListSchema,
788 (page) => page.comments,
789 ),
790 unread,
791 true,
792 ),
793 recover(
794 readPages(
795 part("listReviews", "/reviews"),
796 OriginReviewListSchema,
797 (page) => page.reviews,
798 ),
799 unread,
800 true,
801 ),
802 recover(
803 readPages(
804 part("listCommits", "/commits"),
805 OriginCommitListSchema,
806 (page) => page.commits,
807 ),
808 unread,
809 true,
810 ),
811 // The detail is read alongside, so this is usually its cached answer.
812 recover(getPull(input), null),
813 ],
814 { concurrency: 4 },
815 ).pipe(
816 Effect.flatMap(([comments, reviews, commits, pullRequest]) =>
817 avatarsFor(
818 input.cwd,
819 [
820 ...comments.items.map((comment) => comment.author),
821 ...reviews.items.map((review) => review.author),
822 ],
823 viewArgs(input, "author,reviews,comments"),
824 ).pipe(
825 Effect.map(
826 (avatars) =>
827 [comments, reviews, commits, avatars, pullRequest?.head.sha ?? null] as const,
828 ),
829 ),
830 ),
831 Effect.mapError(fail("getChangeRequestActivity")),
832 Effect.map(
833 ([comments, reviews, commits, avatars, headSha]): ProviderChangeRequestActivity => {
834 const discussion: PullRequestComment[] = comments.items
835 .filter((comment) => !isThreadComment(comment))
836 .map((comment) => ({
837 id: comment.id,
838 kind: "issue-comment",
839 author: originActor(comment.author, avatars),
840 body: comment.body ?? "",
841 createdAt: comment.createdAt,
842 editedAt: editedAt(comment),
843 url: null,
844 path: null,
845 reviewState: null,
846 }));
847 const reviewComments: PullRequestComment[] = reviews.items.map((review) => ({
848 id: review.id,
849 kind: "review",
850 author: originActor(review.author, avatars),
851 body: review.body ?? "",
852 createdAt: review.submittedAt,
853 url: null,
854 path: null,
855 reviewState: review.dismissal?.dismissedAt
856 ? "DISMISSED"
857 : review.verdict === "approve"
858 ? "APPROVED"
859 : review.verdict === "request_changes"
860 ? "CHANGES_REQUESTED"
861 : "COMMENTED",
862 }));
863 const all = [...discussion, ...reviewComments].toSorted((left, right) =>
864 left.createdAt.localeCompare(right.createdAt),
865 );
866 return {
867 comments: all,
868 commentCount: all.length,
869 commentsTruncated: comments.truncated || reviews.truncated,
870 reviewThreadsTruncated: comments.truncated,
871 reviewThreads: toThreads(comments.items, avatars, headSha),
872 commits: commits.items.map((commit) => ({
873 oid: commit.sha,
874 messageHeadline: commit.commit.message.split("\n")[0] ?? "",
875 committedDate:
876 commit.commit.committer?.date ?? commit.commit.author?.date ?? UNKNOWN_TIME,
877 ...(commit.stats?.additions == null ? {} : { additions: commit.stats.additions }),
878 ...(commit.stats?.deletions == null ? {} : { deletions: commit.stats.deletions }),
879 })),
880 };
881 },
882 ),
883 );
884 },
885​
886 getViewerPermissions: () => Effect.succeed(VIEWER_PERMISSIONS),
887​
888 // A version's patch never changes, and the files read counts five times against the rate limit, so
889 // a patch is kept by the commits it compares; the pull request read that names them is the
890 // one the detail is already making.
891 getDiff: (input) =>
892 (input.commit === undefined
893 ? getPull(input).pipe(
894 Effect.flatMap((pullRequest) => {
895 const version = versionKey(pullRequest);
896 return version
897 ? Cache.get(
898 patches,
899 `${input.cwd}\n${input.repository}\n${input.number}\n${version}`,
900 )
901 : readPatch(input.cwd, pullPath(input.repository, input.number, "/files"));
902 }),
903 )
904 : Cache.get(patches, `${input.cwd}\n${input.repository}\n\n${input.commit}`)
905 ).pipe(
906 Effect.map(({ patch, truncated, nextCursor }) => ({ patch, truncated, nextCursor })),
907 Effect.mapError(fail("getDiff")),
908 ),
909​
910 listReviewerCandidates: () =>
911 unsupported("listReviewerCandidates", "Cursor Origin does not list reviewer candidates."),
912 setReviewerRequest: () =>
913 unsupported(
914 "setReviewerRequest",
915 "Requesting reviewers is not supported for Cursor Origin yet.",
916 ),
917 setReaction: () =>
918 unsupported("setReaction", "Reactions are not supported for Cursor Origin yet."),
919​
920 runAction: (input) => {
921 const path = pullPath(input.repository, input.number);
922 const action = (() => {
923 switch (input.action) {
924 case "merge":
925 return refuseStackedMerge(input).pipe(
926 Effect.andThen(
927 write(input, "runAction", "POST", `${path}/merge`, {
928 mergeMethod: input.mergeMethod === "squash" ? "squash" : "merge",
929 }),
930 ),
931 );
932 case "close":
933 return write(input, "runAction", "PATCH", path, { state: "closed" });
934 case "reopen":
935 return write(input, "runAction", "PATCH", path, { state: "open" });
936 case "ready":
937 return write(input, "runAction", "PATCH", path, { draft: false });
938 case "draft":
939 return write(input, "runAction", "PATCH", path, { draft: true });
940 default:
941 return null;
942 }
943 })();
944 return action === null
945 ? unsupported("runAction", `Cursor Origin does not support ${input.action}.`)
946 : action.pipe(
947 Effect.ensuring(forgetPull(input)),
948 // A merge moves its base, which every other pull request into it compares against.
949 Effect.ensuring(input.action === "merge" ? Cache.invalidateAll(baseTips) : Effect.void),
950 );
951 },
952​
953 updateChangeRequest: (input) =>
954 write(input, "updateChangeRequest", "PATCH", pullPath(input.repository, input.number), {
955 ...(input.title === undefined ? {} : { title: input.title }),
956 ...(input.body === undefined ? {} : { body: input.body }),
957 }).pipe(Effect.ensuring(forgetPull(input))),
958​
959 comment: (input) =>
960 write(input, "comment", "POST", pullPath(input.repository, input.number, "/comments"), {
961 body: input.body,
962 }).pipe(Effect.ensuring(forgetPull(input))),
963​
964 updateComment: (input) =>
965 write(
966 input,
967 "updateComment",
968 "PATCH",
969 `${OriginCli.originRepositoryPath(input.repository)}/pulls/comments/${encodeURIComponent(input.commentId)}`,
970 { body: input.body },
971 ).pipe(Effect.ensuring(forgetPull(input))),
972​
973 submitReview: (input) =>
974 write(input, "submitReview", "POST", pullPath(input.repository, input.number, "/reviews"), {
975 verdict: input.verdict === "request-changes" ? "request_changes" : input.verdict,
976 body: input.body,
977 comments: input.comments.map((comment) => {
978 const side =
979 comment.position.kind === "deleted"
980 ? "left"
981 : comment.position.kind === "added"
982 ? "right"
983 : comment.position.side;
984 const line =
985 comment.position.kind === "deleted"
986 ? comment.position.oldLine
987 : comment.position.kind === "added"
988 ? comment.position.newLine
989 : side === "left"
990 ? comment.position.oldLine
991 : comment.position.newLine;
992 return {
993 body: comment.body,
994 inline: { path: comment.path, side, startLine: line, endLine: line },
995 };
996 }),
997 }).pipe(Effect.ensuring(forgetPull(input))),
998​
999 replyToThread: (input) =>
1000 write(input, "replyToThread", "POST", pullPath(input.repository, input.number, "/comments"), {
1001 body: input.body,
1002 threadId: input.threadId,
1003 }).pipe(Effect.ensuring(forgetPull(input))),
1004​
1005 setThreadResolution: (input) =>
1006 write(
1007 input,
1008 "setThreadResolution",
1009 "PATCH",
1010 `${OriginCli.originRepositoryPath(input.repository)}/pulls/threads/${encodeURIComponent(input.threadId)}`,
1011 { resolved: input.resolved },
1012 ).pipe(Effect.ensuring(forgetPull(input))),
1013 };
1014​
1015 return provider;
1016});