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

main
ts 421 lines 14.8 KB
Raw
1 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2 import {
3 editHeldPullRequestListEntries,
4 pullRequestHostAnswer,
5 pullRequestPendingEditsFor,
6 } from "@t3tools/client-runtime/state/pull-requests";
7 import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
8 import {
9 executeAtomQuery,
10 runAtomCommand,
11 squashAtomCommandFailure,
12 } from "@t3tools/client-runtime/state/runtime";
13 import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
14 import * as Cause from "effect/Cause";
15 import * as Effect from "effect/Effect";
16 import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
17 import { msg, useMessages } from "gt-react-native";
18 import { use, useMemo, useState } from "react";
19 import { environmentCatalog } from "../../connection/catalog";
20 import { m } from "../../i18n/messages";
21 import {
22 composerPullRequests,
23 pullRequestListPagesFamily,
24 pullRequestListPagesKey,
25 pullRequestListStatsFamily,
26 } from "../../state/pull-requests";
27 import {
28 appendPullRequestListPage,
29 mergeEnvironmentPullRequestPages,
30 nextPullRequestListInput,
31 patchPullRequestListEntry,
32 pullRequestListHead,
33 shownPullRequestListPages,
34 pullRequestStatKey as statKey,
35 scopedPullRequestListKey,
36 withShownPullRequestStats,
37 type EnvironmentPullRequestListEntry,
38 type PullRequestListPages,
39 } from "./pullRequestList";
40
41 type ListTarget = { readonly environmentId: EnvironmentId; readonly input: PullRequestListInput };
42 type Read = <A>(atom: Atom.Atom<A>) => A;
43
44 /** The head the list query holds now, cached or answered. */
45 function currentHead(read: Read, target: ListTarget) {
46 return AsyncResult.getOrElse(
47 read(pullRequestHostAnswer(composerPullRequests.list(target))),
48 () => null,
49 );
50 }
51
52 function currentPages(read: Read, target: ListTarget): PullRequestListPages | null {
53 return shownPullRequestListPages(
54 read(pullRequestListPagesFamily(pullRequestListPagesKey(target))),
55 currentHead(read, target),
56 );
57 }
58
59 const sourcesFamily = Atom.family((key: string) => {
60 const targets: readonly ListTarget[] = JSON.parse(key);
61 return Atom.make((get) =>
62 targets.map((target) => {
63 const pages = currentPages(get, target);
64 return {
65 target,
66 result: get(composerPullRequests.list(target)),
67 pages:
68 pages === null
69 ? null
70 : {
71 ...pages,
72 entries: editHeldPullRequestListEntries(target.input, pages.entries, (entry) =>
73 get(pullRequestPendingEditsFor(target.environmentId, entry)),
74 ),
75 },
76 stats: get(pullRequestListStatsFamily(target.environmentId)),
77 };
78 }),
79 );
80 });
81
82 function continuations(registry: AtomRegistry.AtomRegistry, targets: readonly ListTarget[]) {
83 return targets.flatMap((target) => {
84 const pages = currentPages((atom) => registry.get(atom), target);
85 const input = pages && nextPullRequestListInput(pages, target.input);
86 return pages && input ? [{ target, pages, input }] : [];
87 });
88 }
89
90 async function loadNextPages(
91 registry: AtomRegistry.AtomRegistry,
92 targets: readonly ListTarget[],
93 retry: boolean,
94 signal: AbortSignal,
95 ) {
96 const responses = await Promise.allSettled(
97 continuations(registry, targets).map(async ({ target, pages, input }) => {
98 const response = await executeAtomQuery(
99 registry,
100 pullRequestHostAnswer(composerPullRequests.list({ ...target, input })),
101 {
102 signal,
103 refresh: retry,
104 reportFailure: false,
105 },
106 );
107 if (signal.aborted) return;
108 if (response._tag === "Failure") throw squashAtomCommandFailure(response);
109 if (response.value.errors.length)
110 throw new Error(response.value.errors.map((error) => error.message).join("\n"));
111 const pagesAtom = pullRequestListPagesFamily(pullRequestListPagesKey(target));
112 const next = appendPullRequestListPage(
113 currentPages((atom) => registry.get(atom), target) ?? pages,
114 response.value,
115 input,
116 );
117 registry.set(pagesAtom, next);
118 if (
119 input.cursors &&
120 Object.keys(next.nextCursors).length &&
121 JSON.stringify(Object.entries(input.cursors).sort()) ===
122 JSON.stringify(Object.entries(next.nextCursors).sort())
123 )
124 throw new Error(m(msg("Couldn't advance the list. Try again.")));
125 }),
126 );
127 return requestErrors(responses);
128 }
129
130 async function refreshHeads(
131 registry: AtomRegistry.AtomRegistry,
132 targets: readonly ListTarget[],
133 signal: AbortSignal,
134 ) {
135 const responses = await Promise.allSettled(
136 targets.map(async (target) => {
137 await runAtomCommand(
138 registry,
139 composerPullRequests.invalidate,
140 { environmentId: target.environmentId, input: {} },
141 { reportFailure: false },
142 );
143 if (signal.aborted) return;
144 const response = await executeAtomQuery(
145 registry,
146 pullRequestHostAnswer(composerPullRequests.list(target)),
147 {
148 refresh: true,
149 signal,
150 reportFailure: false,
151 },
152 );
153 if (signal.aborted) return;
154 if (response._tag === "Failure") throw squashAtomCommandFailure(response);
155 registry.set(
156 pullRequestListPagesFamily(pullRequestListPagesKey(target)),
157 pullRequestListHead(null, response.value),
158 );
159 }),
160 );
161 return requestErrors(responses);
162 }
163
164 // One load of each kind per list scope. The atoms are not kept alive, so leaving a scope (a
165 // filter change, unmount) interrupts its load and aborts the requests.
166 const pageLoadFamily = Atom.family((scopeKey: string) => {
167 const targets: readonly ListTarget[] = JSON.parse(scopeKey);
168 return Atom.fn((retry: boolean, get) =>
169 Effect.promise((signal) => loadNextPages(get.registry, targets, retry, signal)),
170 );
171 });
172 const refreshLoadFamily = Atom.family((scopeKey: string) => {
173 const targets: readonly ListTarget[] = JSON.parse(scopeKey);
174 return Atom.fn((_: void, get) =>
175 Effect.promise((signal) => refreshHeads(get.registry, targets, signal)),
176 );
177 });
178
179 // Changes when any of the scope's environments brings up a new session.
180 const sessionsFamily = Atom.family((scopeKey: string) =>
181 Atom.make((get) =>
182 (JSON.parse(scopeKey) as readonly ListTarget[])
183 .map(({ environmentId }) => get(environmentCatalog.sessionGenerationAtom(environmentId)))
184 .join(),
185 ),
186 );
187
188 const settledError = (result: AsyncResult.AsyncResult<string | null, never>) =>
189 AsyncResult.isSuccess(result) && !result.waiting ? result.value : null;
190
191 export function usePullRequestList(targets: readonly ListTarget[]) {
192 const messages = useMessages();
193 const registry = use(RegistryContext);
194 const scopeKey = JSON.stringify(targets);
195 const sources = useAtomValue(sourcesFamily(scopeKey));
196 const pageAtom = pageLoadFamily(scopeKey);
197 const refreshAtom = refreshLoadFamily(scopeKey);
198 const page = useAtomValue(pageAtom);
199 const refresh = useAtomValue(refreshAtom);
200 const loadError = settledError(page);
201
202 // A page or refresh asked for while an environment was unreachable fails at once, and its
203 // error stops loading on scroll. Once it is back, ask for the page again; a refresh's error is
204 // stale by then because the list queries re-run on reconnect.
205 // A listener alone does not compute the atom, so nothing would follow the connections.
206 useAtomMount(sessionsFamily(scopeKey));
207 useAtomSubscribe(sessionsFamily(scopeKey), () => {
208 const pageResult = registry.get(pageAtom);
209 const refreshResult = registry.get(refreshAtom);
210 if (settledError(refreshResult) !== null) registry.set(refreshAtom, Atom.Reset);
211 else if (settledError(pageResult) !== null && !refreshResult.waiting)
212 registry.set(pageAtom, true);
213 });
214
215 // Read from the registry, not the render: a second onEndReached before React re-renders must
216 // see the load the first one started.
217 const loadMore = (retry = false) => {
218 const pageResult = registry.get(pageAtom);
219 const refreshResult = registry.get(refreshAtom);
220 if (pageResult.waiting || refreshResult.waiting) return;
221 if (!retry && settledError(pageResult)) return;
222 if (!continuations(registry, targets).length) return;
223 registry.set(refreshAtom, Atom.Reset);
224 registry.set(pageAtom, retry);
225 };
226
227 const onRefresh = () => {
228 if (!targets.length || registry.get(refreshAtom).waiting) return;
229 registry.set(pageAtom, Atom.Reset);
230 registry.set(refreshAtom, undefined);
231 };
232
233 const data = useMemo(
234 () =>
235 mergeEnvironmentPullRequestPages(
236 sources.flatMap(({ target, pages, stats }) =>
237 pages
238 ? [
239 {
240 environmentId: target.environmentId,
241 pages: {
242 ...pages,
243 entries: pages.entries.map((entry) => {
244 const stat = stats.stats.get(statKey(entry));
245 return stat
246 ? { ...entry, additions: stat.additions, deletions: stat.deletions }
247 : entry;
248 }),
249 },
250 },
251 ]
252 : [],
253 ),
254 ),
255 [sources],
256 );
257 const [visible, setVisible] = useState<{
258 key: string;
259 rows: readonly EnvironmentPullRequestListEntry[];
260 }>({ key: scopeKey, rows: [] });
261 const onViewableItemsChanged = ({
262 viewableItems,
263 }: {
264 viewableItems: readonly { item: EnvironmentPullRequestListEntry; isViewable: boolean }[];
265 }) => {
266 const rows = viewableItems.filter((token) => token.isViewable).map((token) => token.item);
267 setVisible((previous) =>
268 previous.key === scopeKey &&
269 previous.rows.map(scopedPullRequestListKey).join() ===
270 rows.map(scopedPullRequestListKey).join()
271 ? previous
272 : { key: scopeKey, rows },
273 );
274 };
275 const visibleRows =
276 visible.key === scopeKey && visible.rows.length ? visible.rows : data.entries.slice(0, 8);
277 // Visible rows carry the cached-answer overlay below. Decide which still need stats on the rows
278 // without it, so a cached answer shown offline does not unmount the query that holds it.
279 const withoutCachedOverlay = new Map(
280 data.entries.map((row) => [scopedPullRequestListKey(row), row]),
281 );
282 const statsKey = JSON.stringify(
283 targets.flatMap(({ environmentId }) => {
284 const refs = visibleRows
285 .filter((row) => {
286 const base = withoutCachedOverlay.get(scopedPullRequestListKey(row)) ?? row;
287 return row.environmentId === environmentId && base.additions + base.deletions === 0;
288 })
289 .map(({ projectId, host, repository, number }) => ({
290 projectId,
291 host,
292 repository,
293 number,
294 }));
295 return refs.length ? [{ environmentId, input: { refs } }] : [];
296 }),
297 );
298 const statsAtom = useMemo(() => {
299 const queries: readonly Parameters<typeof composerPullRequests.listStats>[0][] =
300 JSON.parse(statsKey);
301 return Atom.make((get) =>
302 queries.map((target) => ({
303 environmentId: target.environmentId,
304 result: get(composerPullRequests.listStats(target)),
305 })),
306 );
307 }, [statsKey]);
308 const counts = useAtomValue(statsAtom);
309 // Server answers land in pullRequestListStatsFamily; these cover a cached answer, which is
310 // all an offline environment has. Scrolling makes a new stats query, which has no answer until
311 // its cached rows load, so each environment keeps the answer it showed until the new one lands.
312 const [shown, setShown] = useState({ counts, answers: answeredStats(counts, []) });
313 if (shown.counts !== counts) setShown({ counts, answers: answeredStats(counts, shown.answers) });
314 const entries = useMemo(
315 () => withShownPullRequestStats(data.entries, shown.answers),
316 [data.entries, shown.answers],
317 );
318
319 const updateEntry = (
320 entry: EnvironmentPullRequestListEntry,
321 patch: Partial<EnvironmentPullRequestListEntry>,
322 ) => {
323 const target = targets.find((target) => target.environmentId === entry.environmentId);
324 if (!target) return;
325 const pagesAtom = pullRequestListPagesFamily(pullRequestListPagesKey(target));
326 const read = <A>(atom: Atom.Atom<A>) => registry.get(atom);
327 const patched = patchPullRequestListEntry(
328 read(pagesAtom),
329 currentHead(read, target),
330 entry,
331 patch,
332 Date.now(),
333 );
334 if (patched) registry.set(pagesAtom, patched);
335 registry.refresh(composerPullRequests.list(target));
336 };
337 const errors = useMemo(
338 () =>
339 sources.flatMap(({ target, result }) => {
340 if (result._tag !== "Failure") return [];
341 const cause = Cause.squash(result.cause);
342 return [
343 {
344 environmentId: target.environmentId,
345 projectTitle: "",
346 message:
347 cause instanceof Error
348 ? (errorDisplayMessage(cause, messages) ?? cause.message)
349 : messages(msg("Couldn't load pull requests.")),
350 },
351 ];
352 }),
353 [sources, messages],
354 );
355 const listing = useMemo(
356 () => ({ ...data, entries, errors: [...data.errors, ...errors] }),
357 [data, entries, errors],
358 );
359 return {
360 data: listing,
361 entries,
362 error: errors.map((error) => error.message).join("\n") || null,
363 isPending: sources.some(({ result }) => result.waiting) && !data.entries.length,
364 continued: data.continued,
365 loadMore,
366 onRefresh,
367 onViewableItemsChanged,
368 updateEntry,
369 refreshing: refresh.waiting,
370 loadingMore: page.waiting,
371 loadMoreError: loadError,
372 hasMore: sources.some(
373 ({ pages, target }) => pages && nextPullRequestListInput(pages, target.input),
374 ),
375 };
376 }
377
378 function requestErrors(results: readonly PromiseSettledResult<unknown>[]) {
379 return (
380 results
381 .flatMap((result) =>
382 result.status === "rejected"
383 ? [
384 result.reason instanceof Error
385 ? (errorDisplayMessage(result.reason, m) ?? result.reason.message)
386 : m(msg("Couldn't load pull requests.")),
387 ]
388 : [],
389 )
390 .join("\n") || null
391 );
392 }
393
394 type StatsAnswer = {
395 readonly environmentId: EnvironmentId;
396 readonly stats: readonly PullRequestDiffStat[];
397 };
398
399 /** Each environment's newest stats answer, or the one it had while its query has none. */
400 function answeredStats(
401 counts: readonly {
402 readonly environmentId: EnvironmentId;
403 readonly result: AsyncResult.AsyncResult<
404 { readonly stats: readonly PullRequestDiffStat[] },
405 unknown
406 >;
407 }[],
408 previous: readonly StatsAnswer[],
409 ): readonly StatsAnswer[] {
410 const next = counts.flatMap(({ environmentId, result }) => {
411 const kept = previous.find((answer) => answer.environmentId === environmentId);
412 if (!AsyncResult.isSuccess(result)) return kept ? [kept] : [];
413 return kept?.stats === result.value.stats
414 ? [kept]
415 : [{ environmentId, stats: result.value.stats }];
416 });
417 return next.length === previous.length &&
418 next.every((answer, index) => answer === previous[index])
419 ? previous
420 : next;
421 }