Open History to see the last commit
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;
124}
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()];
166}
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 = (input: ProviderRepositoryRef & { readonly sha: string | null | undefined }) =>
329 input.sha
330 ? Cache.get(checkRuns, `${input.cwd}\n${input.repository}\n${input.sha}`)
331 : Effect.succeed({ checks: [], truncated: false });
332
333 const readPatch = (cwd: string, path: string) =>
334 readPages({ cwd, operation: "getDiff", path }, OriginFileListSchema, (page) => page.files).pipe(
335 Effect.map((page) => ({
336 patch: originFilesPatch(page.items),
337 // Origin leaves out the hunks of files too large to show.
338 truncated: page.truncated || page.items.some((file) => file.patch == null),
339 nextCursor: null,
340 })),
341 );
342 const versionKey = (pullRequest: OriginPullRequest) => {
343 const head = pullRequest.version?.headSha ?? pullRequest.head.sha;
344 const base = pullRequest.version?.baseSha ?? pullRequest.base.sha;
345 return head && base ? `${base}...${head}` : null;
346 };
347 // Keyed by `cwd, repository, number, base...head` for a pull request's patch, or by
348 // `cwd, repository, , commit` for one commit's.
349 const patches = yield* Cache.makeWith(
350 (key: string) => {
351 const [cwd = "", repository = "", number = "", commits = ""] = key.split("\n");
352 if (number === "")
353 return readPatch(
354 cwd,
355 `${OriginCli.originRepositoryPath(repository)}/commits/${encodeURIComponent(commits)}/files`,
356 ).pipe(Effect.map((patch) => ({ ...patch, pinned: true })));
357 // `/files` always answers for the newest version, so a push during the read must not be
358 // kept under the version the key names.
359 return readPatch(cwd, pullPath(repository, Number(number), "/files")).pipe(
360 Effect.flatMap((patch) =>
361 recover(
362 cli
363 .api(
364 { cwd, operation: "getPullRequest", path: pullPath(repository, Number(number)) },
365 OriginPullRequestSchema,
366 )
367 .pipe(Effect.map(versionKey)),
368 null,
369 ).pipe(Effect.map((version) => ({ ...patch, pinned: version === commits }))),
370 ),
371 );
372 },
373 {
374 capacity: 64,
375 timeToLive: (exit) => (Exit.isSuccess(exit) && exit.value.pinned ? "1 hour" : 0),
376 },
377 );
378
379 // Every pull request into a branch compares against the same tip, so it is read once a moment.
380 const baseTips = yield* Cache.makeWith(
381 (key: string) => {
382 const [cwd = "", repository = "", branch = ""] = key.split("\n");
383 return cli
384 .api(
385 {
386 cwd,
387 operation: "getBaseTip",
388 path: `${OriginCli.originRepositoryPath(repository)}/git/ref/${encodeURIComponent(`heads/${branch}`)}`,
389 },
390 OriginGitRefSchema,
391 )
392 .pipe(Effect.map((ref) => ref.object?.sha ?? null));
393 },
394 { capacity: 64, timeToLive: (exit) => (Exit.isSuccess(exit) ? "2 seconds" : 0) },
395 );
396
397 // Whether a head merges cleanly into a base never changes, and `/mergeability` counts ten times
398 // against the rate limit, so a definite answer is kept for that pair of commits.
399 const mergeabilities = yield* Cache.makeWith(
400 (key: string) => {
401 const [cwd = "", repository = "", number = "", head = ""] = key.split("\n");
402 return cli
403 .api(
404 {
405 cwd,
406 operation: "getMergeability",
407 path: pullPath(
408 repository,
409 Number(number),
410 `/mergeability?${new URLSearchParams({ expectedHeadSha: head })}`,
411 ),
412 },
413 OriginMergeabilitySchema,
414 )
415 .pipe(
416 Effect.map((answer): PullRequestMergeability =>
417 // A head pushed since the key was made answers for other commits.
418 answer.headSha && answer.headSha !== head
419 ? "unknown"
420 : (answer.blockers ?? []).some((blocker) => blocker.kind === "merge_conflict")
421 ? "conflicting"
422 : answer.verdict === "mergeable"
423 ? "mergeable"
424 : "unknown",
425 ),
426 );
427 },
428 {
429 capacity: 256,
430 timeToLive: (exit) => (Exit.isSuccess(exit) && exit.value !== "unknown" ? "1 hour" : 0),
431 },
432 );
433
434 /**
435 * Origin prepares a merge for every version, against the base as it stood then. While that is
436 * still the base's tip, the prepared merge is the answer, for one ref read; once the base has
437 * moved, only `/mergeability` knows.
438 */
439 const mergeabilityOf = (
440 input: ProviderRepositoryRef & { readonly number: number },
441 pullRequest: OriginPullRequest,
442 ): Effect.Effect<PullRequestMergeability, OriginCli.OriginCliError> => {
443 if (originState(pullRequest) !== "open" || !pullRequest.head.sha)
444 return Effect.succeed("unknown");
445 return recover(
446 Cache.get(baseTips, `${input.cwd}\n${input.repository}\n${pullRequest.base.ref}`),
447 null,
448 ).pipe(
449 // Without the base's tip there is nothing to judge a merge against.
450 Effect.flatMap((tip) =>
451 tip === null
452 ? Effect.succeed("unknown" as const)
453 : tip ===
454 (pullRequest.version?.potentialMergeCommit?.baseSha ?? pullRequest.version?.baseSha)
455 ? Effect.succeed(preparedMergeability(pullRequest))
456 : recover(
457 Cache.get(
458 mergeabilities,
459 `${input.cwd}\n${input.repository}\n${input.number}\n${pullRequest.head.sha}\n${tip}\n${pullRequest.base.ref}`,
460 ),
461 "unknown",
462 ),
463 ),
464 );
465 };
466
467 // Avatars only change when someone replaces their picture, so each actor's is read once per
468 // server. An actor the CLI reports without one is cached as "" so it is not asked about again.
469 const avatarCache = new Map<string, string>();
470 let avatarRead: Fiber.Fiber<OriginAvatars> | null = null;
471 const avatarsFor = Effect.fn("OriginPullRequestProvider.avatarsFor")(function* (
472 cwd: string,
473 actors: ReadonlyArray<Parameters<typeof originActorId>[0]>,
474 args: ReadonlyArray<string>,
475 ) {
476 if (
477 actors.every((actor) => {
478 const id = originActorId(actor);
479 return id === null || avatarCache.has(id);
480 })
481 )
482 return avatarCache;
483 if (avatarRead !== null) yield* Fiber.join(avatarRead);
484 const missing = actors
485 .map(originActorId)
486 .filter((id): id is string => id !== null && !avatarCache.has(id));
487 return missing.length > 0 ? yield* readAvatars(cwd, args, missing) : avatarCache;
488 });
489 const readAvatars = (
490 cwd: string,
491 args: ReadonlyArray<string>,
492 ids: ReadonlyArray<string> = [],
493 ): Effect.Effect<OriginAvatars> =>
494 cli.execute({ cwd, operation: "readAvatars", args }).pipe(
495 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown))),
496 Effect.map((json) => {
497 for (const [id, url] of originAvatars(json)) avatarCache.set(id, url);
498 for (const id of ids) if (!avatarCache.has(id)) avatarCache.set(id, "");
499 return avatarCache;
500 }),
501 // A picture is decoration: a failed read leaves initials rather than failing the page.
502 Effect.orElseSucceed(() => avatarCache),
503 );
504 const initialAvatars = Effect.fnUntraced(function* (cwd: string, args: ReadonlyArray<string>) {
505 if (avatarCache.size > 0) return avatarCache;
506 if (avatarRead === null)
507 avatarRead = yield* Effect.forkIn(
508 readAvatars(cwd, args).pipe(
509 Effect.ensuring(
510 Effect.sync(() => {
511 avatarRead = null;
512 }),
513 ),
514 ),
515 scope,
516 );
517 return yield* Fiber.join(avatarRead);
518 });
519
520 /** `origin pr view` arguments that print `fields` for one pull request, avatars included. */
521 const viewArgs = (
522 input: { readonly repository: string; readonly number: number },
523 fields: string,
524 ) => ["pr", "view", String(input.number), "-R", input.repository, "--json", fields];
525
526 // Nothing reads a write's answer, so it is not decoded: a body this version cannot read must not
527 // turn a write that landed into a failure the user retries.
528 const write = (
529 input: { readonly cwd: string },
530 operation: string,
531 method: "POST" | "PATCH",
532 path: string,
533 body: unknown,
534 ) =>
535 cli
536 .api({ cwd: input.cwd, operation, method, path, body }, Schema.Unknown)
537 .pipe(Effect.asVoid, Effect.mapError(fail(operation)));
538
539 const recover = <A>(
540 read: Effect.Effect<A, OriginCli.OriginCliError>,
541 fallback: A,
542 keepNotFound = false,
543 ) =>
544 read.pipe(
545 Effect.catchIf(
546 (error) =>
547 error.reason !== "rate-limited" &&
548 error.reason !== "unauthenticated" &&
549 !(keepNotFound && error.reason === "not-found"),
550 () => Effect.succeed(fallback),
551 ),
552 );
553
554 // Origin pages by a token longer than the service's cursor can carry, so the cursor names it by
555 // hash. A cursor from before a restart, or one evicted since, fails and asks for a refresh.
556 const pageTokens = new Map<string, string>();
557 const pageTokenKey = (token: string) => {
558 const key = `${(Hash.string(token) >>> 0).toString(36)}-${token.length}`;
559 pageTokens.delete(key);
560 pageTokens.set(key, token);
561 if (pageTokens.size > 256) pageTokens.delete(pageTokens.keys().next().value ?? "");
562 return key;
563 };
564
565 // Origin merges a stacked pull request together with every open one below it, which the panel
566 // does not show, so those merges are left to Origin.
567 const refuseStackedMerge = Effect.fn("OriginPullRequestProvider.refuseStackedMerge")(function* (
568 input: ProviderRepositoryRef & { readonly number: number },
569 ) {
570 const read = (number: number) =>
571 getPull({ ...input, number }).pipe(Effect.mapError(fail("runAction")));
572 const parent = (yield* read(input.number)).stack?.parentPullRequest?.number;
573 if (parent == null) return;
574 if (originState(yield* read(Number(parent))) !== "open") return;
575 return yield* unsupported(
576 "runAction",
577 `This pull request is stacked on #${parent}. Merge #${parent} first, or merge the stack on Cursor Origin.`,
578 );
579 });
580
581 const provider: PullRequestProviderApi = {
582 kind: SourceControlProviderKind.make("cursor-origin"),
583 capabilities: CAPABILITIES,
584
585 getViewer: Effect.fn("OriginPullRequestProvider.getViewer")(
586 function* (input) {
587 if (avatarCache.size === 0 && avatarRead === null) {
588 // The first list follows sign-in, so its pictures can be read while sign-in is checked.
589 yield* Effect.forkIn(
590 cli.resolveRepository({ cwd: input.cwd }).pipe(
591 Effect.flatMap((repository) =>
592 initialAvatars(input.cwd, [
593 "pr",
594 "list",
595 "-R",
596 repository,
597 "-s",
598 "all",
599 "-L",
600 String(PAGE_SIZE),
601 "--json",
602 "author",
603 ]),
604 ),
605 Effect.ignore,
606 ),
607 scope,
608 );
609 }
610 return yield* cli.viewer(input.cwd);
611 },
612 Effect.mapError(fail("getViewer")),
613 ),
614
615 listChangeRequests: Effect.fn("OriginPullRequestProvider.listChangeRequests")(
616 function* (input) {
617 const limit = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
618 const resume = input.cursor?.resumeAfter;
619 const pageToken = resume === undefined ? undefined : pageTokens.get(resume);
620 if (resume !== undefined && pageToken === undefined)
621 return yield* new OriginCli.OriginCliError({
622 operation: EXPIRED_LIST_POSITION,
623 cwd: input.cwd,
624 reason: "failed",
625 detail: "This list position has expired. Refresh the list to load more pull requests.",
626 });
627 const query = new URLSearchParams({
628 state: input.state,
629 pageSize: String(limit),
630 sortBy: "updated",
631 ...(input.involvement === "authored" ? { author: input.viewer } : {}),
632 ...(pageToken === undefined ? {} : { pageToken }),
633 });
634 const avatarArgs = [
635 "pr",
636 "list",
637 "-R",
638 input.repository,
639 "-s",
640 input.state,
641 "-L",
642 String(limit),
643 "--json",
644 "author",
645 ];
646 // Share a sign-in's read, or start the pictures alongside the first list.
647 const [page] = yield* Effect.all(
648 [
649 cli.api(
650 {
651 cwd: input.cwd,
652 operation: "listChangeRequests",
653 path: `${OriginCli.originRepositoryPath(input.repository)}/pulls?${query}`,
654 },
655 OriginPullRequestListSchema,
656 ),
657 initialAvatars(input.cwd, avatarArgs),
658 ],
659 { concurrency: "unbounded" },
660 );
661 const pullRequests = page.pullRequests ?? [];
662 for (const pullRequest of pullRequests)
663 remember(pullKey({ ...input, number: pullRequest.number }), pullRequest);
664 // `origin pr list` only reads the first page, so later pages use the pictures already read.
665 const avatars =
666 input.cursor === undefined
667 ? yield* avatarsFor(
668 input.cwd,
669 pullRequests.map((pullRequest) => pullRequest.author),
670 avatarArgs,
671 )
672 : avatarCache;
673 const next = page.nextPageToken || null;
674 return {
675 items: pullRequests.map((pullRequest) => toProviderChangeRequest(pullRequest, avatars)),
676 truncated: next !== null,
677 continues: next !== null,
678 ...(next === null ? {} : { resumeAfter: pageTokenKey(next) }),
679 };
680 },
681 Effect.mapError((error) =>
682 // The list shows only a failure's access hint, and this one needs its refresh advice.
683 error.operation === EXPIRED_LIST_POSITION
684 ? new PullRequestProviderError({
685 provider: SourceControlProviderKind.make("cursor-origin"),
686 operation: "listChangeRequests",
687 reason: "failed",
688 detail: error.detail,
689 accessHint: error.detail,
690 cause: error,
691 })
692 : fail("listChangeRequests")(error),
693 ),
694 ),
695
696 // One read: linked threads poll this, and the full detail costs four.
697 getChangeRequestSummary: (input) =>
698 getPull(input).pipe(
699 Effect.map((pullRequest) => {
700 const summary = toProviderChangeRequest(pullRequest, avatarCache);
701 return {
702 number: summary.number,
703 title: summary.title,
704 url: summary.url,
705 headBranch: summary.headBranch,
706 baseBranch: summary.baseBranch,
707 state: summary.state,
708 isDraft: summary.isDraft,
709 closedAt: summary.closedAt ?? null,
710 mergedAt: summary.mergedAt ?? null,
711 updatedAt: summary.updatedAt,
712 author: summary.author,
713 additions: summary.additions,
714 deletions: summary.deletions,
715 changedFiles: pullRequest.changedFiles ?? 0,
716 };
717 }),
718 Effect.mapError(fail("getChangeRequestSummary")),
719 ),
720
721 getChangeRequestChecks: (input) =>
722 withPull(input, (pullRequest) => listChecks({ ...input, sha: pullRequest.head.sha })).pipe(
723 Effect.map(([pullRequest, { checks }]) => ({ state: originState(pullRequest), checks })),
724 Effect.mapError(fail("getChangeRequestChecks")),
725 ),
726
727 getChangeRequest: Effect.fn("OriginPullRequestProvider.getChangeRequest")(
728 function* (input) {
729 const [[pullRequest, [checkRead, avatars, mergeability]], repository] = yield* Effect.all(
730 [
731 withPull(input, (pullRequest) =>
732 Effect.all(
733 [
734 recover(listChecks({ ...input, sha: pullRequest.head.sha }), {
735 checks: [],
736 truncated: false,
737 }),
738 avatarsFor(input.cwd, [pullRequest.author], viewArgs(input, "author")),
739 mergeabilityOf(input, pullRequest),
740 ],
741 { concurrency: "unbounded" },
742 ),
743 ),
744 getRepositorySettings(input.cwd, input.repository),
745 ],
746 { concurrency: "unbounded" },
747 );
748 const { checks, truncated } = checkRead;
749 const rollup = checksState(checks);
750 const detail: ProviderChangeRequestDetail = {
751 ...toProviderChangeRequest(pullRequest, avatars),
752 mergeability,
753 // Checks past the last page read are unknown, so all-green ones read are not a pass.
754 checksState: truncated && rollup === "passing" ? "pending" : rollup,
755 headSha: pullRequest.head.sha ?? null,
756 body: pullRequest.body ?? "",
757 changedFiles: pullRequest.changedFiles ?? 0,
758 reviewers: [],
759 checks,
760 mergeCapabilities: {
761 merge: repository?.allowMergeCommit ?? true,
762 squash: repository?.allowSquashMerge ?? true,
763 rebase: false,
764 },
765 viewerPermissions: VIEWER_PERMISSIONS,
766 };
767 return detail;
768 },
769 Effect.mapError(fail("getChangeRequest")),
770 ),
771
772 getChangeRequestActivity: (input) => {
773 // A part that cannot be read shows as empty and truncated rather than failing the rest.
774 const part = (operation: string, suffix: string) => ({
775 cwd: input.cwd,
776 operation,
777 path: pullPath(input.repository, input.number, suffix),
778 });
779 const unread = { items: [], truncated: true };
780 return Effect.all(
781 [
782 recover(
783 readPages(
784 part("listComments", "/comments"),
785 OriginCommentListSchema,
786 (page) => page.comments,
787 ),
788 unread,
789 true,
790 ),
791 recover(
792 readPages(
793 part("listReviews", "/reviews"),
794 OriginReviewListSchema,
795 (page) => page.reviews,
796 ),
797 unread,
798 true,
799 ),
800 recover(
801 readPages(
802 part("listCommits", "/commits"),
803 OriginCommitListSchema,
804 (page) => page.commits,
805 ),
806 unread,
807 true,
808 ),
809 // The detail is read alongside, so this is usually its cached answer.
810 recover(getPull(input), null),
811 ],
812 { concurrency: 4 },
813 ).pipe(
814 Effect.flatMap(([comments, reviews, commits, pullRequest]) =>
815 avatarsFor(
816 input.cwd,
817 [
818 ...comments.items.map((comment) => comment.author),
819 ...reviews.items.map((review) => review.author),
820 ],
821 viewArgs(input, "author,reviews,comments"),
822 ).pipe(
823 Effect.map(
824 (avatars) =>
825 [comments, reviews, commits, avatars, pullRequest?.head.sha ?? null] as const,
826 ),
827 ),
828 ),
829 Effect.mapError(fail("getChangeRequestActivity")),
830 Effect.map(
831 ([comments, reviews, commits, avatars, headSha]): ProviderChangeRequestActivity => {
832 const discussion: PullRequestComment[] = comments.items
833 .filter((comment) => !isThreadComment(comment))
834 .map((comment) => ({
835 id: comment.id,
836 kind: "issue-comment",
837 author: originActor(comment.author, avatars),
838 body: comment.body ?? "",
839 createdAt: comment.createdAt,
840 editedAt: editedAt(comment),
841 url: null,
842 path: null,
843 reviewState: null,
844 }));
845 const reviewComments: PullRequestComment[] = reviews.items.map((review) => ({
846 id: review.id,
847 kind: "review",
848 author: originActor(review.author, avatars),
849 body: review.body ?? "",
850 createdAt: review.submittedAt,
851 url: null,
852 path: null,
853 reviewState: review.dismissal?.dismissedAt
854 ? "DISMISSED"
855 : review.verdict === "approve"
856 ? "APPROVED"
857 : review.verdict === "request_changes"
858 ? "CHANGES_REQUESTED"
859 : "COMMENTED",
860 }));
861 const all = [...discussion, ...reviewComments].toSorted((left, right) =>
862 left.createdAt.localeCompare(right.createdAt),
863 );
864 return {
865 comments: all,
866 commentCount: all.length,
867 commentsTruncated: comments.truncated || reviews.truncated,
868 reviewThreadsTruncated: comments.truncated,
869 reviewThreads: toThreads(comments.items, avatars, headSha),
870 commits: commits.items.map((commit) => ({
871 oid: commit.sha,
872 messageHeadline: commit.commit.message.split("\n")[0] ?? "",
873 committedDate:
874 commit.commit.committer?.date ?? commit.commit.author?.date ?? UNKNOWN_TIME,
875 ...(commit.stats?.additions == null ? {} : { additions: commit.stats.additions }),
876 ...(commit.stats?.deletions == null ? {} : { deletions: commit.stats.deletions }),
877 })),
878 };
879 },
880 ),
881 );
882 },
883
884 getViewerPermissions: () => Effect.succeed(VIEWER_PERMISSIONS),
885
886 // A version's patch never changes, and the files read counts five times against the rate limit, so
887 // a patch is kept by the commits it compares; the pull request read that names them is the
888 // one the detail is already making.
889 getDiff: (input) =>
890 (input.commit === undefined
891 ? getPull(input).pipe(
892 Effect.flatMap((pullRequest) => {
893 const version = versionKey(pullRequest);
894 return version
895 ? Cache.get(
896 patches,
897 `${input.cwd}\n${input.repository}\n${input.number}\n${version}`,
898 )
899 : readPatch(input.cwd, pullPath(input.repository, input.number, "/files"));
900 }),
901 )
902 : Cache.get(patches, `${input.cwd}\n${input.repository}\n\n${input.commit}`)
903 ).pipe(
904 Effect.map(({ patch, truncated, nextCursor }) => ({ patch, truncated, nextCursor })),
905 Effect.mapError(fail("getDiff")),
906 ),
907
908 listReviewerCandidates: () =>
909 unsupported("listReviewerCandidates", "Cursor Origin does not list reviewer candidates."),
910 setReviewerRequest: () =>
911 unsupported(
912 "setReviewerRequest",
913 "Requesting reviewers is not supported for Cursor Origin yet.",
914 ),
915 setReaction: () =>
916 unsupported("setReaction", "Reactions are not supported for Cursor Origin yet."),
917
918 runAction: (input) => {
919 const path = pullPath(input.repository, input.number);
920 const action = (() => {
921 switch (input.action) {
922 case "merge":
923 return refuseStackedMerge(input).pipe(
924 Effect.andThen(
925 write(input, "runAction", "POST", `${path}/merge`, {
926 mergeMethod: input.mergeMethod === "squash" ? "squash" : "merge",
927 }),
928 ),
929 );
930 case "close":
931 return write(input, "runAction", "PATCH", path, { state: "closed" });
932 case "reopen":
933 return write(input, "runAction", "PATCH", path, { state: "open" });
934 case "ready":
935 return write(input, "runAction", "PATCH", path, { draft: false });
936 case "draft":
937 return write(input, "runAction", "PATCH", path, { draft: true });
938 default:
939 return null;
940 }
941 })();
942 return action === null
943 ? unsupported("runAction", `Cursor Origin does not support ${input.action}.`)
944 : action.pipe(
945 Effect.ensuring(forgetPull(input)),
946 // A merge moves its base, which every other pull request into it compares against.
947 Effect.ensuring(input.action === "merge" ? Cache.invalidateAll(baseTips) : Effect.void),
948 );
949 },
950
951 updateChangeRequest: (input) =>
952 write(input, "updateChangeRequest", "PATCH", pullPath(input.repository, input.number), {
953 ...(input.title === undefined ? {} : { title: input.title }),
954 ...(input.body === undefined ? {} : { body: input.body }),
955 }).pipe(Effect.ensuring(forgetPull(input))),
956
957 comment: (input) =>
958 write(input, "comment", "POST", pullPath(input.repository, input.number, "/comments"), {
959 body: input.body,
960 }).pipe(Effect.ensuring(forgetPull(input))),
961
962 updateComment: (input) =>
963 write(
964 input,
965 "updateComment",
966 "PATCH",
967 `${OriginCli.originRepositoryPath(input.repository)}/pulls/comments/${encodeURIComponent(input.commentId)}`,
968 { body: input.body },
969 ).pipe(Effect.ensuring(forgetPull(input))),
970
971 submitReview: (input) =>
972 write(input, "submitReview", "POST", pullPath(input.repository, input.number, "/reviews"), {
973 verdict: input.verdict === "request-changes" ? "request_changes" : input.verdict,
974 body: input.body,
975 comments: input.comments.map((comment) => {
976 const side =
977 comment.position.kind === "deleted"
978 ? "left"
979 : comment.position.kind === "added"
980 ? "right"
981 : comment.position.side;
982 const line =
983 comment.position.kind === "deleted"
984 ? comment.position.oldLine
985 : comment.position.kind === "added"
986 ? comment.position.newLine
987 : side === "left"
988 ? comment.position.oldLine
989 : comment.position.newLine;
990 return {
991 body: comment.body,
992 inline: { path: comment.path, side, startLine: line, endLine: line },
993 };
994 }),
995 }).pipe(Effect.ensuring(forgetPull(input))),
996
997 replyToThread: (input) =>
998 write(input, "replyToThread", "POST", pullPath(input.repository, input.number, "/comments"), {
999 body: input.body,
1000 threadId: input.threadId,
1001 }).pipe(Effect.ensuring(forgetPull(input))),
1002
1003 setThreadResolution: (input) =>
1004 write(
1005 input,
1006 "setThreadResolution",
1007 "PATCH",
1008 `${OriginCli.originRepositoryPath(input.repository)}/pulls/threads/${encodeURIComponent(input.threadId)}`,
1009 { resolved: input.resolved },
1010 ).pipe(Effect.ensuring(forgetPull(input))),
1011 };
1012
1013 return provider;
1014});