@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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