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