Open History to see the last commit
1import { findProjectOnChangeRequestHost } from "@t3tools/client-runtime/change-request-links";
2import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
3import { scopeProjectRef } from "@t3tools/client-runtime/environment";
4import { useAtomValue } from "@effect/atom-react";
5import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
6import {
7 applyPullRequestSummaryEdits,
8 comparePullRequestSummaries,
9 createLinkedPullRequestSummaryAtomFamily,
10 newestPullRequestSummary,
11 createPullRequestEnvironmentAtoms,
12 createPullRequestStackAtomFamily,
13 pullRequestPendingEditsFor,
14 pullRequestHostAnswer,
15 type PullRequestPendingEdit,
16} from "@t3tools/client-runtime/state/pull-requests";
17
18export { newestPullRequestSummary };
19import {
20 PullRequestListResult,
21 PullRequestOperationError,
22 PullRequestUnavailableError,
23 type EnvironmentId,
24 type ProjectId,
25 type PullRequestChecksState,
26 type PullRequestFilesViewedResult,
27 type PullRequestListInput,
28 type PullRequestFilterOptionsInput,
29 type PullRequestListStatsInput,
30 type PullRequestDetail,
31 type PullRequestListEntry,
32 type PullRequestRef,
33 type PullRequestSummary,
34 type RepositoryIdentity,
35 type ThreadPullRequestLink,
36} from "@t3tools/contracts";
37import {
38 resolveThreadPullRequestBadge,
39 threadPullRequestKeyOf,
40 visibleThreadPullRequests,
41} from "@t3tools/client-runtime/thread-pull-requests";
42import * as Cause from "effect/Cause";
43import * as Clock from "effect/Clock";
44import * as Effect from "effect/Effect";
45import * as Option from "effect/Option";
46import * as Schema from "effect/Schema";
47import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
48
49import { connectionAtomRuntime } from "../connection/runtime";
50import { appAtomRegistry } from "../rpc/atomRegistry";
51import {
52 UNDATED_PULL_REQUEST_UPDATED_AT,
53 mergePullRequestLists,
54 type EnvironmentPullRequestStat,
55 type MergedPullRequestList,
56} from "../components/pullRequest/pullRequestList.logic";
57import {
58 readPullRequestDetailSnapshot,
59 writePullRequestDetailSnapshot,
60} from "../components/pullRequest/pullRequestDetail.logic";
61import { pullRequestChecksState } from "../components/pullRequest/pullRequestPresentation";
62import { useGuideRunStore } from "../components/pullRequest/guide/guideRunStore";
63import { formatEnvironmentQueryError } from "./query";
64import { environmentProjects } from "./projects";
65import { environmentThreadShells } from "./threads";
66
67export interface ObservedPullRequestSummary {
68 readonly summary: PullRequestSummary;
69 /** Client arrival time, the only ordering older servers leave us for same-dated snapshots. */
70 readonly observedAt: number;
71}
72
73/** A stored snapshot carries no edit, so a shared summary dated the same wins over it. */
74export function newestDisplayedPullRequestSummary(
75 detail: PullRequestSummary | null,
76 fromSnapshot: boolean,
77 shared: PullRequestSummary | null,
78 reference: PullRequestRef,
79 edits: ReadonlyArray<PullRequestPendingEdit>,
80): PullRequestSummary | null {
81 // With no shared summary the snapshot is all there is, and no answer applied its edits yet.
82 return applyPullRequestSummaryEdits(
83 reference,
84 fromSnapshot
85 ? newestPullRequestSummary(detail, shared)
86 : newestPullRequestSummary(shared, detail),
87 edits,
88 );
89}
90
91export function pullRequestListEntryToSummary(entry: PullRequestListEntry): PullRequestSummary {
92 return {
93 provider: entry.provider,
94 projectId: entry.projectId,
95 repository: entry.repository,
96 number: entry.number,
97 title: entry.title,
98 url: entry.url,
99 state: entry.state,
100 isDraft: entry.isDraft,
101 headBranch: entry.headBranch,
102 baseBranch: entry.baseBranch,
103 updatedAt: entry.updatedAt,
104 ...(entry.observedAt === undefined ? {} : { observedAt: entry.observedAt }),
105 author: entry.author,
106 ...(entry.reviewDecision === undefined ? {} : { reviewDecision: entry.reviewDecision }),
107 ...(entry.checksState === undefined ? {} : { checksState: entry.checksState }),
108 mergeability: entry.mergeability,
109 };
110}
111
112function projectRepositoryIdentity(
113 get: <A>(atom: Atom.Atom<A>) => A,
114 environmentId: EnvironmentId,
115 reference: PullRequestRef,
116) {
117 return get(environmentProjects.projectAtom(scopeProjectRef(environmentId, reference.projectId)))
118 ?.repositoryIdentity;
119}
120
121export function pullRequestObservationReference(
122 reference: PullRequestRef,
123 identity: RepositoryIdentity | null | undefined,
124): PullRequestRef {
125 const host = identity?.provider
126 ? sourceControlClients.changeRequestHost(identity, identity.provider)
127 : null;
128 const selector = identity?.provider
129 ? sourceControlClients.get(identity.provider).repositorySelector?.(identity)
130 : undefined;
131 if (selector !== undefined && !reference.repository.includes("/")) {
132 if (
133 selector?.toLowerCase() !== reference.repository.toLowerCase() ||
134 (reference.host !== undefined && reference.host.toLowerCase() !== host)
135 )
136 return reference;
137 const [projectHost, ...path] = identity?.canonicalKey.split("/") ?? [];
138 if (projectHost && path.length > 0) {
139 return { ...reference, host: projectHost, repository: path.join("/") };
140 }
141 }
142 return host === null || reference.host !== undefined ? reference : { ...reference, host };
143}
144
145function pullRequestSummaryKey(environmentId: EnvironmentId, reference: PullRequestRef): string {
146 return JSON.stringify([
147 environmentId,
148 reference.projectId,
149 reference.host === undefined
150 ? [reference.repository.toLowerCase(), reference.number]
151 : threadPullRequestKeyOf({ ...reference, host: reference.host }),
152 ]);
153}
154
155function checkoutObservationKey(
156 registry: AtomRegistry.AtomRegistry,
157 environmentId: EnvironmentId,
158 reference: PullRequestRef,
159): string {
160 return pullRequestSummaryKey(
161 environmentId,
162 pullRequestObservationReference(
163 reference,
164 projectRepositoryIdentity((atom) => registry.get(atom), environmentId, reference),
165 ),
166 );
167}
168
169export function newestPullRequestObservation(
170 current: ObservedPullRequestSummary | null,
171 incoming: ObservedPullRequestSummary | null,
172): ObservedPullRequestSummary | null {
173 if (current === null) return incoming;
174 if (incoming === null) return current;
175 let order = comparePullRequestSummaries(current.summary, incoming.summary);
176 if (
177 order === 0 &&
178 current.summary.observedAt === undefined &&
179 incoming.summary.observedAt === undefined
180 ) {
181 order = incoming.observedAt - current.observedAt;
182 }
183 if (!(order > 0)) return current;
184 // A sparse summary must not erase known status, or carry old detail stats into a new list read.
185 return {
186 ...incoming,
187 summary: {
188 ...incoming.summary,
189 isDraft: incoming.summary.isDraft ?? current.summary.isDraft,
190 mergeability: incoming.summary.mergeability ?? current.summary.mergeability,
191 reviewDecision:
192 incoming.summary.reviewDecision === undefined
193 ? current.summary.reviewDecision
194 : incoming.summary.reviewDecision,
195 checksState:
196 incoming.summary.checksState === undefined
197 ? current.summary.checksState
198 : incoming.summary.checksState,
199 },
200 };
201}
202
203export interface ObservedPullRequestChecks {
204 readonly checksState: PullRequestChecksState | null;
205 /** Server read time, when the server reports one. */
206 readonly readAt: number | undefined;
207 /** Client arrival time. */
208 readonly observedAt: number;
209}
210
211/**
212 * Checks are reread far more often than the rest of a pull request, so they keep their own
213 * freshness: a checks read must not carry old metadata forward, and a list read must not take
214 * back newer checks.
215 */
216export interface PullRequestObservations {
217 readonly metadata: ObservedPullRequestSummary | null;
218 readonly checks: ObservedPullRequestChecks | null;
219}
220
221const noObservations: PullRequestObservations = { metadata: null, checks: null };
222
223const pullRequestObservationsAtom = Atom.family((key: string) =>
224 Atom.make<PullRequestObservations>(noObservations).pipe(
225 Atom.setIdleTTL(5 * 60_000),
226 Atom.withLabel(`web-pull-requests:observations:${key}`),
227 ),
228);
229
230export function observePullRequestChecks(
231 current: PullRequestObservations,
232 incoming: ObservedPullRequestChecks,
233): PullRequestObservations {
234 const previous = current.checks;
235 const newer =
236 previous === null ||
237 (previous.readAt !== undefined && incoming.readAt !== undefined
238 ? incoming.readAt >= previous.readAt
239 : incoming.observedAt >= previous.observedAt);
240 return newer ? { ...current, checks: incoming } : current;
241}
242
243export function observePullRequestMetadata(
244 current: PullRequestObservations,
245 incoming: ObservedPullRequestSummary,
246): PullRequestObservations {
247 const metadata = newestPullRequestObservation(current.metadata, incoming);
248 const next = metadata === current.metadata ? current : { ...current, metadata };
249 const { checksState } = incoming.summary;
250 return checksState === undefined
251 ? next
252 : observePullRequestChecks(next, {
253 checksState,
254 readAt: incoming.summary.observedAt,
255 observedAt: incoming.observedAt,
256 });
257}
258
259const summariesWithChecks = new WeakMap<PullRequestSummary, PullRequestSummary>();
260
261/**
262 * One object per metadata and checks state: checks are reread often, and every sidebar row on the
263 * pull request re-renders for a new summary.
264 */
265export function observedPullRequestSummary(
266 observations: PullRequestObservations,
267): PullRequestSummary | null {
268 const { metadata, checks } = observations;
269 if (metadata === null) return null;
270 if (checks === null) return metadata.summary;
271 const cached = summariesWithChecks.get(metadata.summary);
272 if (cached?.checksState === checks.checksState) return cached;
273 const summary = { ...metadata.summary, checksState: checks.checksState };
274 summariesWithChecks.set(metadata.summary, summary);
275 return summary;
276}
277
278function recordObservation(
279 registry: AtomRegistry.AtomRegistry,
280 key: string,
281 observe: (current: PullRequestObservations) => PullRequestObservations,
282): void {
283 registry.modify(pullRequestObservationsAtom(key), (previous) => {
284 const next = observe(previous);
285 return next === previous ? [false, previous] : [true, next];
286 });
287}
288
289function observePullRequestSummary(
290 registry: AtomRegistry.AtomRegistry,
291 key: string,
292 summary: PullRequestSummary,
293 observedAt: number,
294): void {
295 recordObservation(registry, key, (current) =>
296 observePullRequestMetadata(current, { summary, observedAt }),
297 );
298}
299
300// Reading localStorage throws where the browser blocks storage; that must not break the page.
301function snapshotStorage(): Storage | undefined {
302 if (typeof window === "undefined") return undefined;
303 try {
304 return window.localStorage;
305 } catch {
306 return undefined;
307 }
308}
309
310type ListAnswerStorage = Pick<Storage, "getItem" | "setItem" | "removeItem" | "key" | "length">;
311
312const LIST_SCOPE_INDEX_KEY = "t3.pullRequests.listScopes";
313const LIST_SCOPE_KEY_PREFIX = "t3.pullRequests.listScope:";
314const LEGACY_SNAPSHOT_KEY_PREFIX = "t3.pullRequests.list:";
315const LIST_ANSWER_MAX_ENTRIES = 99;
316/**
317 * A scope holds a page of rows per environment, so only the scopes visited most recently are
318 * kept. Eviction drops a whole scope, never one environment's answer, so a restored list is never
319 * missing environments that did answer.
320 */
321const LIST_SCOPE_MAX_KEPT = 8;
322const listScopeCodec = Schema.fromJsonString(
323 Schema.Record(Schema.String, Schema.toCodecJson(PullRequestListResult)),
324);
325const decodeListScope = Schema.decodeUnknownOption(listScopeCodec);
326const encodeListScope = Schema.encodeOption(listScopeCodec);
327const decodeListScopeIndex = Schema.decodeUnknownOption(
328 Schema.fromJsonString(Schema.Array(Schema.String)),
329);
330const sweptStorages = new WeakSet<ListAnswerStorage>();
331
332/**
333 * The project assignment is left out: a cold start asks before the project shells load, when
334 * every environment is asked for all of its projects, while the answers were remembered after
335 * overlapping projects were split between environments. Each environment's answer covers only
336 * its assigned projects, so the scope's answers together still cover the whole scope.
337 */
338const listScopeKey = ({ projectIds: _projectIds, ...scope }: PullRequestListInput) =>
339 `${LIST_SCOPE_KEY_PREFIX}${JSON.stringify(scope)}`;
340
341function readListScope(storage: ListAnswerStorage | undefined, key: string) {
342 let raw: string | null = null;
343 try {
344 raw = storage?.getItem(key) ?? null;
345 } catch {}
346 return Option.getOrElse(decodeListScope(raw), (): Record<string, PullRequestListResult> => ({}));
347}
348
349/** The single composite snapshot this replaced is never read again. */
350function sweepLegacySnapshots(storage: ListAnswerStorage): void {
351 if (sweptStorages.has(storage)) return;
352 sweptStorages.add(storage);
353 const legacy: string[] = [];
354 for (let index = 0; index < storage.length; index++) {
355 const key = storage.key(index);
356 if (key?.startsWith(LEGACY_SNAPSHOT_KEY_PREFIX)) legacy.push(key);
357 }
358 for (const key of legacy) storage.removeItem(key);
359}
360
361/**
362 * Keeps what a cold start can show before the host answers again. Searches, continuation pages
363 * and grown pages are never shown that way, so only first-page reads are kept. Failures and
364 * cursors are dropped: they describe the moment of the read, and a restored list must not
365 * continue from it.
366 */
367export function rememberPullRequestListAnswer(
368 storage: ListAnswerStorage | undefined,
369 target: EnvironmentQueryTarget<PullRequestListInput>,
370 answer: PullRequestListResult,
371): void {
372 const { input } = target;
373 if (storage === undefined || input.query !== undefined || input.cursors !== undefined) return;
374 if (input.limit !== undefined && input.limit > LIST_ANSWER_MAX_ENTRIES) return;
375 const key = listScopeKey(input);
376 try {
377 sweepLegacySnapshots(storage);
378 const scope = readListScope(storage, key);
379 // An answer for some projects replaces only their rows. A repository this environment no
380 // longer owns stays covered until the environment that took it over answers; the next answer
381 // for all of the environment's projects, which every cold start asks for, drops them.
382 const assigned = input.projectIds === undefined ? undefined : new Set(input.projectIds);
383 const retained =
384 assigned === undefined
385 ? []
386 : (scope[target.environmentId]?.entries ?? []).filter(
387 (entry) => !assigned.has(entry.projectId),
388 );
389 const encoded = encodeListScope({
390 ...scope,
391 [target.environmentId]: {
392 ...answer,
393 // The fresh rows come first, so retained rows only fill what is left of the page.
394 entries: [...answer.entries, ...retained].slice(0, LIST_ANSWER_MAX_ENTRIES),
395 errors: [],
396 nextCursors: {},
397 },
398 });
399 if (Option.isNone(encoded)) return;
400 const index = Option.getOrElse(
401 decodeListScopeIndex(storage.getItem(LIST_SCOPE_INDEX_KEY)),
402 () => [],
403 );
404 const kept = [key, ...index.filter((held) => held !== key)];
405 for (const evicted of kept.slice(LIST_SCOPE_MAX_KEPT)) storage.removeItem(evicted);
406 storage.setItem(key, encoded.value);
407 storage.setItem(LIST_SCOPE_INDEX_KEY, JSON.stringify(kept.slice(0, LIST_SCOPE_MAX_KEPT)));
408 } catch {}
409}
410
411/**
412 * The kept answers for these reads, merged the way live answers are. An environment without a
413 * kept answer is left out rather than failing the restore: one whose projects were all assigned
414 * to another environment was never asked, and its pull requests are in that environment's answer.
415 */
416export function restorePullRequestList(
417 storage: ListAnswerStorage | undefined,
418 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
419): MergedPullRequestList | null {
420 const scopes = new Map<string, Record<string, PullRequestListResult>>();
421 const answers: Array<readonly [EnvironmentId, PullRequestListResult]> = [];
422 for (const target of targets) {
423 const key = listScopeKey(target.input);
424 const scope = scopes.get(key) ?? readListScope(storage, key);
425 scopes.set(key, scope);
426 const answer = scope[target.environmentId];
427 if (answer !== undefined) answers.push([target.environmentId, answer]);
428 }
429 const merged = mergePullRequestLists(answers);
430 if (merged === null) return null;
431 // Answers kept before the projects were reassigned between environments can overlap.
432 const seen = new Set<string>();
433 const entries = merged.entries.filter((entry) => {
434 const key = `${entry.host}:${entry.repository}#${entry.number}`;
435 if (seen.has(key)) return false;
436 seen.add(key);
437 return true;
438 });
439 return { ...merged, entries };
440}
441
442export function restoredPullRequestList(
443 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
444): MergedPullRequestList | null {
445 return restorePullRequestList(snapshotStorage(), targets);
446}
447
448const filesViewedAnswerListeners = new Map<
449 string,
450 Set<(answer: PullRequestFilesViewedResult) => void>
451>();
452
453function filesViewedAnswerKey({ environmentId, input }: EnvironmentQueryTarget<PullRequestRef>) {
454 return JSON.stringify([
455 environmentId,
456 input.projectId,
457 input.host,
458 input.expectedAccountId,
459 input.allowStale,
460 input.repository,
461 input.number,
462 ]);
463}
464
465export function subscribePullRequestFilesViewedAnswers(
466 target: EnvironmentQueryTarget<PullRequestRef>,
467 onAnswer: (answer: PullRequestFilesViewedResult) => void,
468) {
469 const key = filesViewedAnswerKey(target);
470 let listeners = filesViewedAnswerListeners.get(key);
471 if (listeners === undefined) filesViewedAnswerListeners.set(key, (listeners = new Set()));
472 listeners.add(onAnswer);
473 return () => {
474 listeners.delete(onAnswer);
475 if (listeners.size === 0) filesViewedAnswerListeners.delete(key);
476 };
477}
478
479// Answers are stamped on arrival: older servers leave no other ordering for same-dated reads.
480export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connectionAtomRuntime, {
481 acceptedEdit: ({ environmentId, input }, edit, registry) =>
482 Effect.map(Clock.currentTimeMillis, (observedAt) => {
483 const reference = pullRequestObservationReference(
484 input,
485 projectRepositoryIdentity((atom) => registry.get(atom), environmentId, input),
486 );
487 const saved = registry.get(
488 savedPullRequestSummaryAtom(savedPullRequestKey(environmentId, reference)),
489 );
490 recordObservation(registry, pullRequestSummaryKey(environmentId, reference), (current) => {
491 const summary = applyPullRequestSummaryEdits(
492 input,
493 newestPullRequestSummary(saved, observedPullRequestSummary(current)),
494 [edit],
495 );
496 return summary === null ? current : { ...current, metadata: { summary, observedAt } };
497 });
498 }),
499 filesViewed: (target, answer) =>
500 Effect.sync(() => {
501 for (const listener of filesViewedAnswerListeners.get(filesViewedAnswerKey(target)) ?? [])
502 listener(answer);
503 }),
504 list: ({ environmentId, input }, answer, registry) =>
505 Effect.map(Clock.currentTimeMillis, (observedAt) => {
506 rememberPullRequestListAnswer(snapshotStorage(), { environmentId, input }, answer);
507 for (const entry of answer.entries) {
508 observePullRequestSummary(
509 registry,
510 checkoutObservationKey(registry, environmentId, entry),
511 pullRequestListEntryToSummary(entry),
512 observedAt,
513 );
514 }
515 }),
516 detail: ({ environmentId, input }, detail, registry) =>
517 Effect.map(Clock.currentTimeMillis, (at) => {
518 // Only fresh reads seed the cold-start snapshot; a stale one could replace a newer record.
519 if (input.allowStale === false) {
520 writePullRequestDetailSnapshot(snapshotStorage(), environmentId, input, detail);
521 }
522 observePullRequestSummary(
523 registry,
524 checkoutObservationKey(registry, environmentId, input),
525 { ...detail, checksState: pullRequestChecksState(detail.checks) },
526 at,
527 );
528 }),
529 checks: ({ environmentId, input }, checks, registry) =>
530 Effect.map(Clock.currentTimeMillis, (observedAt) => {
531 if (checks === null) return;
532 recordObservation(
533 registry,
534 checkoutObservationKey(registry, environmentId, input),
535 (current) =>
536 observePullRequestChecks(current, {
537 checksState: pullRequestChecksState(checks.checks),
538 readAt: checks.observedAt,
539 observedAt,
540 }),
541 );
542 }),
543 // Covers runs started elsewhere (another client, an agent) as well as this client's own.
544 reviewGuide: ({ environmentId, input }, guide) =>
545 Effect.map(Clock.currentTimeMillis, (since) => {
546 if (guide.run?._tag !== "Running") return;
547 useGuideRunStore.getState().watch({
548 environmentId,
549 reference: input,
550 title: null,
551 previousGuideAt: guide.guide?.generatedAt ?? null,
552 previousFailedAt: null,
553 since,
554 answeredRunning: true,
555 });
556 }),
557});
558
559export const linkedPullRequestDetailAtom = createLinkedPullRequestSummaryAtomFamily(
560 connectionAtomRuntime,
561 pullRequestEnvironment.refreshes,
562 ({ environmentId, input }, summary, registry) =>
563 Effect.map(Clock.currentTimeMillis, (observedAt) =>
564 observePullRequestSummary(
565 registry,
566 checkoutObservationKey(registry, environmentId, input),
567 summary,
568 observedAt,
569 ),
570 ),
571);
572
573export function threadPullRequestLinkToSummary(
574 link: ThreadPullRequestLink,
575 projectId: ProjectId,
576): PullRequestSummary | null {
577 if (link.snapshot === null) return null;
578 return {
579 ...link.snapshot,
580 provider: (
581 sourceControlClients.findByChangeRequestUrl(link.url) ?? sourceControlClients.get(undefined)
582 ).kind,
583 projectId,
584 repository: link.repository,
585 number: link.number,
586 url: link.url,
587 // Undated links supply fallback fields and can still establish a final merged state.
588 updatedAt: link.snapshot.updatedAt ?? UNDATED_PULL_REQUEST_UPDATED_AT,
589 };
590}
591
592function savedPullRequestKey(
593 environmentId: EnvironmentId,
594 reference: Pick<PullRequestRef, "host" | "repository" | "number">,
595): string {
596 return reference.host === undefined
597 ? ""
598 : `${environmentId}:${threadPullRequestKeyOf({ ...reference, host: reference.host })}`;
599}
600
601const savedPullRequestSummariesAtom = Atom.make((get) => {
602 const summaries = new Map<string, PullRequestSummary>();
603 for (const thread of get(environmentThreadShells.threadShellsAtom)) {
604 for (const link of visibleThreadPullRequests(thread.pullRequests)) {
605 const summary = threadPullRequestLinkToSummary(link, thread.projectId);
606 if (summary === null) continue;
607 const key = savedPullRequestKey(thread.environmentId, link);
608 summaries.set(key, newestPullRequestSummary(summaries.get(key) ?? null, summary) ?? summary);
609 }
610 }
611 return summaries;
612});
613
614const savedPullRequestSummaryAtom = Atom.family((key: string) =>
615 Atom.make((get) => get(savedPullRequestSummariesAtom).get(key) ?? null).pipe(
616 Atom.withEquality((previous, next) => JSON.stringify(previous) === JSON.stringify(next)),
617 Atom.setIdleTTL(5 * 60_000),
618 ),
619);
620
621export function observedPullRequestTitle(
622 registry: AtomRegistry.AtomRegistry,
623 environmentId: EnvironmentId,
624 reference: PullRequestRef,
625): string | null {
626 return (
627 registry.get(
628 pullRequestObservationsAtom(checkoutObservationKey(registry, environmentId, reference)),
629 ).metadata?.summary.title ?? null
630 );
631}
632
633function restoreSharedPullRequestDetail(
634 environmentId: EnvironmentId,
635 reference: PullRequestRef,
636 observationReference: PullRequestRef,
637 identity: RepositoryIdentity | null | undefined,
638): PullRequestSummary | null {
639 const storage = snapshotStorage();
640 let detail = readPullRequestDetailSnapshot(storage, environmentId, reference);
641 if (!identity?.provider || observationReference.host === undefined) return detail;
642
643 const provider = sourceControlClients.get(identity.provider);
644 const hosted = { ...observationReference, host: observationReference.host };
645 // A hostless cache entry can predate a change to the checkout's remote, so share only its own.
646 const matches = (cached: PullRequestDetail | null): cached is PullRequestDetail => {
647 const link =
648 cached === null ? undefined : sourceControlClients.parseChangeRequestUrl(cached.url)?.link;
649 return link !== undefined && threadPullRequestKeyOf(link) === threadPullRequestKeyOf(hosted);
650 };
651 if (!matches(detail)) detail = null;
652 const [projectHost, ...projectPath] = identity.canonicalKey.split("/");
653 if (!projectHost || projectPath.length === 0) return detail;
654 const ownKey = threadPullRequestKeyOf({
655 host: projectHost,
656 repository: projectPath.join("/"),
657 number: reference.number,
658 });
659 if (threadPullRequestKeyOf(hosted) !== ownKey) return detail;
660
661 const checkout = {
662 ...reference,
663 host: provider.checkoutChangeRequestHost(identity) ?? undefined,
664 repository: sourceControlClients.repositorySelector(identity) ?? hosted.repository,
665 };
666 // Each cache key still uses the original RPC selector.
667 for (const alternate of [hosted, checkout]) {
668 const cached = readPullRequestDetailSnapshot(storage, environmentId, alternate);
669 if (matches(cached) && newestPullRequestSummary(detail, cached) === cached) detail = cached;
670 }
671 return detail;
672}
673
674const emptyPullRequestSummaryAtom = Atom.make(null);
675
676const sharedPullRequestSummaries = Atom.family((key: string) => {
677 const [environmentId, reference, restoreDetail] = JSON.parse(key) as [
678 EnvironmentId,
679 PullRequestRef,
680 boolean,
681 ];
682 return Atom.make((get) => {
683 const identity = projectRepositoryIdentity(get, environmentId, reference);
684 const observationReference = pullRequestObservationReference(reference, identity);
685 const observed = observedPullRequestSummary(
686 get(pullRequestObservationsAtom(pullRequestSummaryKey(environmentId, observationReference))),
687 );
688 const saved = get(
689 savedPullRequestSummaryAtom(savedPullRequestKey(environmentId, observationReference)),
690 );
691 const cached = restoreDetail
692 ? restoreSharedPullRequestDetail(environmentId, reference, observationReference, identity)
693 : null;
694 const remembered = newestPullRequestSummary(saved, cached);
695 const summary = newestPullRequestSummary(remembered, observed);
696 const withDraft =
697 summary !== null && summary.isDraft === undefined && remembered?.isDraft !== undefined
698 ? { ...summary, isDraft: remembered.isDraft }
699 : summary;
700 return applyPullRequestSummaryEdits(
701 reference,
702 withDraft,
703 get(pullRequestPendingEditsFor(environmentId, reference)),
704 );
705 }).pipe(Atom.withEquality((previous, next) => JSON.stringify(previous) === JSON.stringify(next)));
706});
707
708/** Reconciles list, detail, checks and linked-summary answers with the thread's saved link. */
709export function sharedPullRequestSummaryAtom(
710 environmentId: EnvironmentId | null,
711 reference: PullRequestRef | null,
712 restoreDetail = false,
713): Atom.Atom<PullRequestSummary | null> {
714 if (environmentId === null || reference === null) return emptyPullRequestSummaryAtom;
715 const { projectId, host, repository, number } = reference;
716 return sharedPullRequestSummaries(
717 JSON.stringify([environmentId, { projectId, host, repository, number }, restoreDetail]),
718 );
719}
720
721export function useSharedPullRequestSummary(
722 environmentId: EnvironmentId | null,
723 reference: PullRequestRef | null,
724 options: { readonly restoreDetail?: boolean } = {},
725): PullRequestSummary | null {
726 return useAtomValue(
727 sharedPullRequestSummaryAtom(environmentId, reference, options.restoreDetail),
728 );
729}
730type LinkedPullRequestIdentity = Pick<ThreadPullRequestLink, "host" | "repository" | "number">;
731
732export function linkedThreadPullRequestReference(
733 projects: ReadonlyArray<EnvironmentProject>,
734 environmentId: EnvironmentId,
735 threadProjectId: ProjectId | null,
736 { host, repository, number }: LinkedPullRequestIdentity,
737): PullRequestRef | null {
738 const link = { host, repository, number };
739 const candidates = projects.filter((project) => project.environmentId === environmentId);
740 const own = candidates.find((candidate) => candidate.id === threadProjectId);
741 const ordered =
742 own === undefined ? candidates : [own, ...candidates.filter((candidate) => candidate !== own)];
743 const projectId = findProjectOnChangeRequestHost(ordered, link)?.id ?? threadProjectId;
744 return projectId === null ? null : { projectId, ...link };
745}
746
747const linkedThreadPullRequestSummaries = Atom.family((key: string) => {
748 const [environmentId, projectId, link] = JSON.parse(key) as [
749 EnvironmentId,
750 ProjectId | null,
751 LinkedPullRequestIdentity,
752 ];
753 return Atom.make((get) =>
754 get(
755 sharedPullRequestSummaryAtom(
756 environmentId,
757 linkedThreadPullRequestReference(
758 get(environmentProjects.projectsAtom),
759 environmentId,
760 projectId,
761 link,
762 ),
763 true,
764 ),
765 ),
766 );
767});
768
769function linkedThreadPullRequestSummaryAtom(
770 environmentId: EnvironmentId | null,
771 projectId: ProjectId | null,
772 link: LinkedPullRequestIdentity | null,
773) {
774 if (environmentId === null || link === null) return emptyPullRequestSummaryAtom;
775 const { host, repository, number } = link;
776 return linkedThreadPullRequestSummaries(
777 JSON.stringify([environmentId, projectId, { host, repository, number }]),
778 );
779}
780
781export function useLinkedThreadPullRequestSummary(
782 environmentId: EnvironmentId | null,
783 projectId: ProjectId | null,
784 link: LinkedPullRequestIdentity | null,
785) {
786 return useAtomValue(linkedThreadPullRequestSummaryAtom(environmentId, projectId, link));
787}
788
789const emptyThreadPullRequestBadge = Atom.make(null);
790const threadPullRequestBadges = Atom.family((key: string) => {
791 const [environmentId, projectId, links] = JSON.parse(key) as [
792 EnvironmentId,
793 ProjectId,
794 ReadonlyArray<ThreadPullRequestLink>,
795 ];
796 return Atom.make((get) =>
797 resolveThreadPullRequestBadge(
798 links,
799 (link) =>
800 get(linkedThreadPullRequestSummaryAtom(environmentId, projectId, link)) ?? link.snapshot,
801 ),
802 ).pipe(Atom.withEquality((previous, next) => JSON.stringify(previous) === JSON.stringify(next)));
803});
804
805export function useSharedThreadPullRequestBadge(
806 environmentId: EnvironmentId,
807 projectId: ProjectId | undefined,
808 links: ReadonlyArray<ThreadPullRequestLink> | undefined,
809) {
810 return useAtomValue(
811 projectId === undefined || !links?.length
812 ? emptyThreadPullRequestBadge
813 : threadPullRequestBadges(JSON.stringify([environmentId, projectId, links])),
814 );
815}
816
817export const pullRequestStackAtom = createPullRequestStackAtomFamily(
818 connectionAtomRuntime,
819 pullRequestEnvironment.refreshes,
820);
821
822export interface EnvironmentQueryTarget<Input> {
823 readonly environmentId: EnvironmentId;
824 readonly input: Input;
825}
826
827interface EnvironmentQueryError {
828 readonly environmentId: EnvironmentId;
829 readonly message: string;
830}
831
832interface MergedEnvironmentQueryView<Input, A> {
833 readonly observations: ReadonlyArray<readonly [EnvironmentId, A, number]>;
834 readonly values: ReadonlyArray<readonly [EnvironmentId, A]>;
835 readonly error: EnvironmentQueryError | null;
836 /** Targets whose latest read failed, even when an earlier answer is still shown. */
837 readonly failed: ReadonlyArray<EnvironmentQueryTarget<Input>>;
838 readonly isPending: boolean;
839}
840
841const failedListObservedAt = new WeakMap<object, number>();
842const isUnavailableList = Schema.is(PullRequestUnavailableError);
843const isFailedList = Schema.is(PullRequestOperationError);
844
845export function observeFailedPullRequestList(
846 result: AsyncResult.Failure<PullRequestListResult, unknown>,
847): { readonly value: PullRequestListResult; readonly observedAt: number } | undefined {
848 if (result.waiting) return undefined;
849 const error = Option.getOrNull(Cause.findErrorOption(result.cause));
850 if ((!isUnavailableList(error) && !isFailedList(error)) || error.listResult === undefined) {
851 return undefined;
852 }
853 let observedAt = failedListObservedAt.get(result.cause);
854 if (observedAt === undefined) {
855 observedAt = Date.now();
856 failedListObservedAt.set(result.cause, observedAt);
857 }
858 return { value: error.listResult, observedAt };
859}
860
861// Use one derived atom for variable fan-out; unreachable environments must not hide other rows.
862function createMergedEnvironmentQuery<Input, A>(
863 label: string,
864 atomFor: (
865 target: EnvironmentQueryTarget<Input>,
866 ) => Atom.Atom<AsyncResult.AsyncResult<A, unknown>>,
867 observeFailure?: (
868 result: AsyncResult.Failure<A, unknown>,
869 ) => { readonly value: A; readonly observedAt: number } | undefined,
870) {
871 const family = Atom.family((key: string) =>
872 Atom.make((get): MergedEnvironmentQueryView<Input, A> => {
873 const targets = JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>;
874 const values: Array<readonly [EnvironmentId, A]> = [];
875 const observations: Array<readonly [EnvironmentId, A, number]> = [];
876 const pendingEnvironments = new Set<EnvironmentId>();
877 const failed: Array<EnvironmentQueryTarget<Input>> = [];
878 let error: EnvironmentQueryError | null = null;
879 let isPending = false;
880 for (const target of targets) {
881 const result = get(atomFor(target));
882 isPending ||= result.waiting;
883 if (result.waiting) pendingEnvironments.add(target.environmentId);
884 if (result._tag === "Failure" && error === null) {
885 error = {
886 environmentId: target.environmentId,
887 message: formatEnvironmentQueryError(result.cause),
888 };
889 }
890 const value = AsyncResult.getOrElse(result, () => null);
891 if (value !== null) values.push([target.environmentId, value]);
892 if (result._tag === "Failure") failed.push(target);
893 if (result._tag === "Success") {
894 observations.push([target.environmentId, result.value, result.timestamp]);
895 } else if (result._tag === "Failure") {
896 const observation = observeFailure?.(result);
897 if (observation !== undefined) {
898 observations.push([target.environmentId, observation.value, observation.observedAt]);
899 }
900 }
901 }
902 return {
903 values,
904 error,
905 failed,
906 isPending,
907 // Another batch can still find a readable checkout on this environment.
908 observations: observations.filter(
909 ([environmentId]) => !pendingEnvironments.has(environmentId),
910 ),
911 };
912 }).pipe(Atom.withLabel(`${label}:${key}`)),
913 );
914 const empty = Atom.make<MergedEnvironmentQueryView<Input, A>>({
915 observations: [],
916 values: [],
917 error: null,
918 failed: [],
919 isPending: false,
920 }).pipe(Atom.withLabel(`${label}:empty`));
921 return function useMergedQuery(targets: ReadonlyArray<EnvironmentQueryTarget<Input>>) {
922 const key = JSON.stringify(targets);
923 const view = useAtomValue(targets.length === 0 ? empty : family(key));
924 const refresh = (override?: ReadonlyArray<EnvironmentQueryTarget<Input>>) => {
925 const refreshTargets =
926 override ?? (JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>);
927 for (const atom of new Set(refreshTargets.map(atomFor))) {
928 appAtomRegistry.refresh(atom);
929 }
930 };
931 // Retry reloads only failed environments, so a read still in flight elsewhere is not restarted.
932 const retry = () => {
933 for (const atom of new Set(
934 (JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>).map(atomFor),
935 )) {
936 const result = appAtomRegistry.get(atom);
937 if (result._tag === "Failure" && !result.waiting) appAtomRegistry.refresh(atom);
938 }
939 };
940 return { ...view, refresh, retry };
941 };
942}
943
944const usePullRequestHostListsQuery = createMergedEnvironmentQuery(
945 "web-pull-requests:host-list",
946 (target: EnvironmentQueryTarget<PullRequestListInput>) =>
947 pullRequestHostAnswer(pullRequestEnvironment.list(target)),
948 observeFailedPullRequestList,
949);
950
951const usePullRequestListsQuery = createMergedEnvironmentQuery(
952 "web-pull-requests:list",
953 pullRequestEnvironment.list,
954 observeFailedPullRequestList,
955);
956
957const usePullRequestStatsQuery = createMergedEnvironmentQuery(
958 "web-pull-requests:list-stats",
959 pullRequestEnvironment.listStats,
960);
961
962const usePullRequestFilterOptionsQuery = createMergedEnvironmentQuery(
963 "web-pull-requests:filter-options",
964 pullRequestEnvironment.filterOptions,
965);
966
967const usePullRequestTurnRefreshQuery = createMergedEnvironmentQuery(
968 "web-pull-requests:turn-refreshes",
969 ({ environmentId }: EnvironmentQueryTarget<Readonly<Record<string, never>>>) =>
970 pullRequestEnvironment.refreshes({ environmentId, input: {} }),
971);
972
973export function usePullRequestTurnRefreshes(
974 environmentIds: ReadonlyArray<EnvironmentId>,
975): ReadonlyArray<readonly [EnvironmentId, number]> {
976 return usePullRequestTurnRefreshQuery(
977 environmentIds.map((environmentId) => ({ environmentId, input: {} })),
978 ).values;
979}
980
981export function usePullRequestTurnRefresh(environmentId: EnvironmentId): number | null {
982 const result = useAtomValue(pullRequestEnvironment.refreshes({ environmentId, input: {} }));
983 return AsyncResult.getOrElse(result, () => null);
984}
985
986export interface MergedPullRequestListView {
987 readonly data: MergedPullRequestList | null;
988 readonly error: EnvironmentQueryError | null;
989 readonly failed: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>;
990 readonly isPending: boolean;
991 readonly observations: ReadonlyArray<readonly [EnvironmentId, PullRequestListResult, number]>;
992 readonly refresh: (targets?: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>) => void;
993 readonly retry: () => void;
994}
995
996// Merge inside each hook: the React Compiler memoizes it on `query.values` only there, and
997// PullRequestsPage sets state when the merged list's identity changes.
998export function usePullRequestList(
999 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
1000): MergedPullRequestListView {
1001 const query = usePullRequestListsQuery(targets);
1002 const data = mergePullRequestLists(query.values);
1003 return {
1004 data,
1005 error: query.error,
1006 failed: query.failed,
1007 isPending: query.isPending,
1008 observations: query.observations,
1009 refresh: query.refresh,
1010 retry: query.retry,
1011 };
1012}
1013
1014export function usePullRequestHostList(
1015 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
1016): MergedPullRequestListView {
1017 const query = usePullRequestHostListsQuery(targets);
1018 const data = mergePullRequestLists(query.values);
1019 return {
1020 data,
1021 error: query.error,
1022 failed: query.failed,
1023 isPending: query.isPending,
1024 observations: query.observations,
1025 refresh: query.refresh,
1026 retry: query.retry,
1027 };
1028}
1029
1030export function usePullRequestListStats(
1031 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
1032): {
1033 readonly stats: ReadonlyArray<EnvironmentPullRequestStat> | null;
1034 readonly isPending: boolean;
1035 readonly refresh: (
1036 targets?: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
1037 ) => void;
1038} {
1039 const query = usePullRequestStatsQuery(targets);
1040 const stats =
1041 query.values.length === 0
1042 ? null
1043 : query.values.flatMap(([environmentId, result]) =>
1044 result.stats.map((stat) => ({ ...stat, environmentId })),
1045 );
1046 return { stats, isPending: query.isPending, refresh: query.refresh };
1047}
1048
1049export function usePullRequestFilterOptions(
1050 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestFilterOptionsInput>>,
1051) {
1052 const query = usePullRequestFilterOptionsQuery(targets);
1053 return {
1054 labels: query.values.flatMap(([, options]) => options.labels),
1055 authors: query.values.flatMap(([, options]) => options.authors),
1056 references: query.values.flatMap(([, options]) => options.references),
1057 error: query.error,
1058 isPending: query.isPending,
1059 };
1060}