@devries-cameron20 / t3code Mirror · read-only / commits / 977a18823c
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 22, 15:45 UTC

refactor(mobile): pull request list records answers where they land (#25373)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 26, 2026 at 15:43 UTC 977a18823cf8e067476193e29947e2d3950a25f2
5 files changed +334 -153
apps/mobile/src/features/pull-requests/pullRequestList.test.ts
+48
@@ -13,12 +13,15 @@ import {
13 mergeEnvironmentPullRequestPages,
14 nextPullRequestListInput,
15 PR_LIST_PAGE_SIZE,
16 + patchPullRequestListEntry,
17 pullRequestFilterChoices,
18 pullRequestLabelColors,
19 pullRequestListHead,
20 pullRequestListInput,
21 scopedPullRequestListKey,
22 + shownPullRequestListPages,
23 pullRequestListRowsAreEqual,
24 + withShownPullRequestStats,
25 withoutScratchProjectScope,
26 } from "./pullRequestList";
27
@@ -115,6 +118,14 @@ describe("mobile PR list pagination", () => {
118 mergePullRequestListEntries([entry(1)], [entry(2, { host: "enterprise.test" }), entry(2)]),
119 ).toHaveLength(3);
120 });
121 + it("patches a row that only the list head supplies, and keeps it while that head is current", () => {
122 + const head = page([entry(2), entry(1)], { repo: "first" });
123 + const patched = patchPullRequestListEntry(null, head, entry(1), { state: "merged" }, 5);
124 + expect(shownPullRequestListPages(patched, head)?.entries.map((row) => row.state)).toEqual([
125 + "open",
126 + "merged",
127 + ]);
128 + });
129 it("refreshes the head without dropping older loaded pages or rewinding their cursor", () => {
130 const first = pullRequestListHead(null, page([entry(3)], { repo: "first" }));
131 const continued = appendPullRequestListPage(first, page([entry(2)], { repo: "second" }), {
@@ -387,3 +398,40 @@ describe("pullRequestFilterChoices", () => {
398 expect(rows[50]).toBe("label-from-host");
399 });
400 });
401 +
402 +describe("shown PR diff stats", () => {
403 + const cups = EnvironmentId.make("cups");
404 + const stat = (number: number, additions: number, deletions: number) => ({
405 + projectId: "project" as PullRequestListEntry["projectId"],
406 + repository: "org/repo",
407 + number,
408 + additions,
409 + deletions,
410 + });
411 + const rows = [
412 + { ...entry(1), environmentId: cups },
413 + { ...entry(2, { additions: 4, deletions: 1 }), environmentId: cups },
414 + ];
415 +
416 + it("keeps the same list when the answers change no row", () => {
417 + expect(withShownPullRequestStats(rows, [])).toBe(rows);
418 + expect(withShownPullRequestStats(rows, [{ environmentId: cups, stats: [stat(1, 0, 0)] }])).toBe(
419 + rows,
420 + );
421 + expect(withShownPullRequestStats(rows, [{ environmentId: cups, stats: [stat(2, 9, 9)] }])).toBe(
422 + rows,
423 + );
424 + });
425 +
426 + it("fills only rows without stats, in their own environment", () => {
427 + const filled = withShownPullRequestStats(rows, [
428 + { environmentId: EnvironmentId.make("mbp"), stats: [stat(1, 7, 7)] },
429 + { environmentId: cups, stats: [stat(1, 3, 2), stat(2, 9, 9)] },
430 + ]);
431 + expect(filled.map(({ additions, deletions }) => [additions, deletions])).toEqual([
432 + [3, 2],
433 + [4, 1],
434 + ]);
435 + expect(filled[1]).toBe(rows[1]);
436 + });
437 +});
apps/mobile/src/features/pull-requests/pullRequestList.ts
+61
@@ -3,6 +3,7 @@ import {
3 ProjectId,
4 resolvePullRequestAuthorFilter,
5 type EnvironmentId,
6 + type PullRequestDiffStat,
7 type PullRequestListEntry,
8 type PullRequestListInput,
9 type PullRequestListResult,
@@ -45,6 +46,38 @@ export type EnvironmentPullRequestListEntry = PullRequestListEntry & {
46 export const scopedPullRequestListKey = (entry: EnvironmentPullRequestListEntry) =>
47 `${entry.environmentId}:${pullRequestListKey(entry)}`;
48
49 +export const pullRequestStatKey = (
50 + row: Pick<PullRequestDiffStat, "projectId" | "repository" | "number">,
51 +) => `${row.projectId}:${row.repository}:${row.number}`;
52 +
53 +/**
54 + * Fills rows that have no diff stat yet from the stats answers on screen. Returns `entries`
55 + * itself when no row changes, so the list keeps its identity across renders.
56 + */
57 +export function withShownPullRequestStats(
58 + entries: readonly EnvironmentPullRequestListEntry[],
59 + answers: readonly {
60 + readonly environmentId: EnvironmentId;
61 + readonly stats: readonly PullRequestDiffStat[];
62 + }[],
63 +): readonly EnvironmentPullRequestListEntry[] {
64 + const shown = new Map(
65 + answers.flatMap(({ environmentId, stats }) =>
66 + stats.map((row) => [`${environmentId}:${pullRequestStatKey(row)}`, row] as const),
67 + ),
68 + );
69 + if (!shown.size) return entries;
70 + let changed = false;
71 + const next = entries.map((entry) => {
72 + const stat = shown.get(`${entry.environmentId}:${pullRequestStatKey(entry)}`);
73 + if (!stat || entry.additions + entry.deletions !== 0) return entry;
74 + if (stat.additions + stat.deletions === 0) return entry;
75 + changed = true;
76 + return { ...entry, additions: stat.additions, deletions: stat.deletions };
77 + });
78 + return changed ? next : entries;
79 +}
80 +
81 export function pullRequestListRowsAreEqual(
82 previous: EnvironmentPullRequestListEntry,
83 next: EnvironmentPullRequestListEntry,
@@ -143,6 +176,34 @@ export function pullRequestListHead(
176 };
177 }
178
179 +/** The recorded pages with the current list head on top; before any answer is recorded, the head alone. */
180 +export function shownPullRequestListPages(
181 + recorded: PullRequestListPages | null,
182 + head: PullRequestListResult | null,
183 +): PullRequestListPages | null {
184 + return head ? pullRequestListHead(recorded, head) : recorded;
185 +}
186 +
187 +export function patchPullRequestListEntry(
188 + recorded: PullRequestListPages | null,
189 + head: PullRequestListResult | null,
190 + entry: PullRequestListEntry,
191 + patch: Partial<PullRequestListEntry>,
192 + observedAt: number,
193 +): PullRequestListPages | null {
194 + const pages = shownPullRequestListPages(recorded, head);
195 + return (
196 + pages && {
197 + ...pages,
198 + entries: pages.entries.map((row) =>
199 + pullRequestListKey(row) === pullRequestListKey(entry)
200 + ? { ...row, ...patch, observedAt }
201 + : row,
202 + ),
203 + }
204 + );
205 +}
206 +
207 export function pullRequestListInput(
208 controls: PullRequestListControls,
209 query: string,
apps/mobile/src/features/pull-requests/usePullRequestList.ts
+180 -152
@@ -1,155 +1,172 @@
1 import { RegistryContext, useAtomValue } from "@effect/atom-react";
2 import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3 -import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
3 +import type { EnvironmentId, PullRequestListInput } from "@t3tools/contracts";
4 import * as Cause from "effect/Cause";
5 +import * as Effect from "effect/Effect";
6 import * as Option from "effect/Option";
6 -import { AsyncResult, Atom } from "effect/reactivity";
7 -import { use, useCallback, useEffect, useMemo, useRef, useState, useLayoutEffect } from "react";
8 -import { composerPullRequests } from "../../state/pull-requests";
7 +import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
8 +import { use, useCallback, useMemo, useState } from "react";
9 +import {
10 + composerPullRequests,
11 + pullRequestListPagesFamily,
12 + pullRequestListPagesKey,
13 + pullRequestListStatsFamily,
14 +} from "../../state/pull-requests";
15 import {
16 appendPullRequestListPage,
17 mergeEnvironmentPullRequestPages,
18 nextPullRequestListInput,
19 + patchPullRequestListEntry,
20 pullRequestListHead,
14 - pullRequestListKey,
21 + shownPullRequestListPages,
22 + pullRequestStatKey as statKey,
23 scopedPullRequestListKey,
24 + withShownPullRequestStats,
25 type EnvironmentPullRequestListEntry,
26 type PullRequestListPages,
27 } from "./pullRequestList";
28
20 -const pagesFamily = Atom.family((_key: string) =>
21 - Atom.make<PullRequestListPages | null>(null).pipe(Atom.setIdleTTL(5 * 60_000)),
22 -);
23 -const statsFamily = Atom.family((_environmentId: string) =>
24 - Atom.make<ReadonlyMap<string, PullRequestDiffStat>>(new Map()).pipe(Atom.setIdleTTL(5 * 60_000)),
25 -);
26 -const statKey = (row: Pick<PullRequestDiffStat, "projectId" | "repository" | "number">) =>
27 - `${row.projectId}:${row.repository}:${row.number}`;
28 -
29 type ListTarget = { readonly environmentId: EnvironmentId; readonly input: PullRequestListInput };
30 +type Read = <A>(atom: Atom.Atom<A>) => A;
31 +
32 +/** The head the list query holds now, cached or answered. */
33 +function currentHead(read: Read, target: ListTarget) {
34 + return Option.getOrNull(AsyncResult.value(read(composerPullRequests.list(target))));
35 +}
36 +
37 +function currentPages(read: Read, target: ListTarget): PullRequestListPages | null {
38 + return shownPullRequestListPages(
39 + read(pullRequestListPagesFamily(pullRequestListPagesKey(target))),
40 + currentHead(read, target),
41 + );
42 +}
43 +
44 const sourcesFamily = Atom.family((key: string) => {
45 const targets: readonly ListTarget[] = JSON.parse(key);
46 return Atom.make((get) =>
33 - targets.map((target) => {
34 - const result = get(composerPullRequests.list(target));
35 - const head = Option.getOrNull(AsyncResult.value(result));
36 - const cached = get(pagesFamily(JSON.stringify(target)));
37 - return {
38 - target,
39 - result,
40 - pages: head ? pullRequestListHead(cached, head) : cached,
41 - stats: get(statsFamily(target.environmentId)),
42 - };
43 - }),
47 + targets.map((target) => ({
48 + target,
49 + result: get(composerPullRequests.list(target)),
50 + pages: currentPages(get, target),
51 + stats: get(pullRequestListStatsFamily(target.environmentId)),
52 + })),
53 );
54 });
55
47 -export function usePullRequestList(targets: readonly ListTarget[]) {
48 - const registry = use(RegistryContext);
49 - const scopeKey = JSON.stringify(targets);
50 - const activeScope = useRef(scopeKey);
51 - const sources = useAtomValue(sourcesFamily(scopeKey));
52 - const requests = useRef<{ page?: AbortController; refresh?: AbortController }>({});
53 - const [loading, setLoading] = useState({
54 - key: scopeKey,
55 - page: false,
56 - refresh: false,
57 - error: null as string | null,
56 +function continuations(registry: AtomRegistry.AtomRegistry, targets: readonly ListTarget[]) {
57 + return targets.flatMap((target) => {
58 + const pages = currentPages((atom) => registry.get(atom), target);
59 + const input = pages && nextPullRequestListInput(pages, target.input);
60 + return pages && input ? [{ target, pages, input }] : [];
61 });
59 - const state = loading.key === scopeKey ? loading : { page: false, refresh: false, error: null };
60 - useLayoutEffect(() => {
61 - activeScope.current = scopeKey;
62 - return () => {
63 - requests.current.page?.abort();
64 - requests.current.refresh?.abort();
65 - requests.current = {};
66 - };
67 - }, [scopeKey, activeScope]);
68 - useEffect(() => {
69 - for (const { target, pages } of sources)
70 - if (pages) registry.set(pagesFamily(JSON.stringify(target)), pages);
71 - }, [registry, sources]);
62 +}
63 +
64 +async function loadNextPages(
65 + registry: AtomRegistry.AtomRegistry,
66 + targets: readonly ListTarget[],
67 + retry: boolean,
68 + signal: AbortSignal,
69 +) {
70 + const responses = await Promise.allSettled(
71 + continuations(registry, targets).map(async ({ target, pages, input }) => {
72 + const response = await executeAtomQuery(
73 + registry,
74 + composerPullRequests.list({ ...target, input }),
75 + {
76 + signal,
77 + refresh: retry,
78 + reportFailure: false,
79 + },
80 + );
81 + if (signal.aborted) return;
82 + if (response._tag === "Failure") throw squashAtomCommandFailure(response);
83 + if (response.value.errors.length)
84 + throw new Error(response.value.errors.map((error) => error.message).join("\n"));
85 + const pagesAtom = pullRequestListPagesFamily(pullRequestListPagesKey(target));
86 + const next = appendPullRequestListPage(
87 + currentPages((atom) => registry.get(atom), target) ?? pages,
88 + response.value,
89 + input,
90 + );
91 + registry.set(pagesAtom, next);
92 + if (
93 + input.cursors &&
94 + Object.keys(next.nextCursors).length &&
95 + JSON.stringify(Object.entries(input.cursors).sort()) ===
96 + JSON.stringify(Object.entries(next.nextCursors).sort())
97 + )
98 + throw new Error("Couldn't advance the list. Try again.");
99 + }),
100 + );
101 + return requestErrors(responses);
102 +}
103
73 - const loadMore = useCallback(
74 - async (retry = false) => {
75 - if (requests.current.page || requests.current.refresh || (!retry && state.error)) return;
76 - const continuations = targets.flatMap((target) => {
77 - const pagesAtom = pagesFamily(JSON.stringify(target));
78 - const pages = registry.get(pagesAtom);
79 - const input = pages && nextPullRequestListInput(pages, target.input);
80 - return pages && input ? [{ target, pagesAtom, pages, input }] : [];
104 +async function refreshHeads(
105 + registry: AtomRegistry.AtomRegistry,
106 + targets: readonly ListTarget[],
107 + signal: AbortSignal,
108 +) {
109 + const responses = await Promise.allSettled(
110 + targets.map(async (target) => {
111 + await composerPullRequests.invalidate.run(registry, {
112 + environmentId: target.environmentId,
113 + input: {},
114 });
82 - if (!continuations.length) return;
83 - const controller = new AbortController();
84 - requests.current.page = controller;
85 - setLoading({ key: scopeKey, page: true, refresh: false, error: null });
86 - const responses = await Promise.allSettled(
87 - continuations.map(async ({ target, pagesAtom, pages, input }) => {
88 - const response = await executeAtomQuery(
89 - registry,
90 - composerPullRequests.list({ ...target, input }),
91 - {
92 - signal: controller.signal,
93 - refresh: retry,
94 - reportFailure: false,
95 - },
96 - );
97 - if (controller.signal.aborted || activeScope.current !== scopeKey) return;
98 - if (response._tag === "Failure") throw squashAtomCommandFailure(response);
99 - if (response.value.errors.length)
100 - throw new Error(response.value.errors.map((error) => error.message).join("\n"));
101 - const next = appendPullRequestListPage(
102 - registry.get(pagesAtom) ?? pages,
103 - response.value,
104 - input,
105 - );
106 - registry.set(pagesAtom, next);
107 - if (
108 - input.cursors &&
109 - Object.keys(next.nextCursors).length &&
110 - JSON.stringify(Object.entries(input.cursors).sort()) ===
111 - JSON.stringify(Object.entries(next.nextCursors).sort())
112 - )
113 - throw new Error("Couldn't advance the list. Try again.");
114 - }),
115 + if (signal.aborted) return;
116 + const response = await executeAtomQuery(registry, composerPullRequests.list(target), {
117 + refresh: true,
118 + signal,
119 + reportFailure: false,
120 + });
121 + if (signal.aborted) return;
122 + if (response._tag === "Failure") throw squashAtomCommandFailure(response);
123 + registry.set(
124 + pullRequestListPagesFamily(pullRequestListPagesKey(target)),
125 + pullRequestListHead(null, response.value),
126 );
116 - if (requests.current.page === controller) delete requests.current.page;
117 - if (!controller.signal.aborted && activeScope.current === scopeKey)
118 - setLoading({ key: scopeKey, page: false, refresh: false, error: requestErrors(responses) });
119 - },
120 - [targets, registry, scopeKey, state.error, activeScope],
127 + }),
128 );
129 + return requestErrors(responses);
130 +}
131
123 - const onRefresh = async () => {
124 - if (!targets.length || requests.current.refresh) return;
125 - requests.current.page?.abort();
126 - delete requests.current.page;
127 - const controller = new AbortController();
128 - requests.current.refresh = controller;
129 - setLoading({ key: scopeKey, page: false, refresh: true, error: null });
130 - const responses = await Promise.allSettled(
131 - targets.map(async (target) => {
132 - await composerPullRequests.invalidate.run(registry, {
133 - environmentId: target.environmentId,
134 - input: {},
135 - });
136 - if (controller.signal.aborted) return;
137 - const response = await executeAtomQuery(registry, composerPullRequests.list(target), {
138 - refresh: true,
139 - signal: controller.signal,
140 - reportFailure: false,
141 - });
142 - if (controller.signal.aborted || activeScope.current !== scopeKey) return;
143 - if (response._tag === "Failure") throw squashAtomCommandFailure(response);
144 - registry.set(
145 - pagesFamily(JSON.stringify(target)),
146 - pullRequestListHead(null, response.value),
147 - );
148 - }),
149 - );
150 - if (requests.current.refresh === controller) delete requests.current.refresh;
151 - if (!controller.signal.aborted && activeScope.current === scopeKey)
152 - setLoading({ key: scopeKey, page: false, refresh: false, error: requestErrors(responses) });
132 +// One load of each kind per list scope. The atoms are not kept alive, so leaving a scope (a
133 +// filter change, unmount) interrupts its load and aborts the requests.
134 +const pageLoadFamily = Atom.family((scopeKey: string) =>
135 + Atom.fn((retry: boolean, get) =>
136 + Effect.promise((signal) => loadNextPages(get.registry, JSON.parse(scopeKey), retry, signal)),
137 + ),
138 +);
139 +const refreshLoadFamily = Atom.family((scopeKey: string) =>
140 + Atom.fn((_: void, get) =>
141 + Effect.promise((signal) => refreshHeads(get.registry, JSON.parse(scopeKey), signal)),
142 + ),
143 +);
144 +
145 +const settledError = (result: AsyncResult.AsyncResult<string | null, never>) =>
146 + AsyncResult.isSuccess(result) && !result.waiting ? result.value : null;
147 +
148 +export function usePullRequestList(targets: readonly ListTarget[]) {
149 + const registry = use(RegistryContext);
150 + const scopeKey = JSON.stringify(targets);
151 + const sources = useAtomValue(sourcesFamily(scopeKey));
152 + const pageAtom = pageLoadFamily(scopeKey);
153 + const refreshAtom = refreshLoadFamily(scopeKey);
154 + const page = useAtomValue(pageAtom);
155 + const refresh = useAtomValue(refreshAtom);
156 + // Starting one kind of load clears the other, so at most one holds an error.
157 + const loadError = settledError(refresh) ?? settledError(page);
158 +
159 + const loadMore = (retry = false) => {
160 + if (page.waiting || refresh.waiting || (!retry && loadError)) return;
161 + if (!continuations(registry, targets).length) return;
162 + registry.set(refreshAtom, Atom.Reset);
163 + registry.set(pageAtom, retry);
164 + };
165 +
166 + const onRefresh = () => {
167 + if (!targets.length || refresh.waiting) return;
168 + registry.set(pageAtom, Atom.Reset);
169 + registry.set(refreshAtom, undefined);
170 };
171
172 const data = useMemo(
@@ -199,10 +216,18 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
216 );
217 const visibleRows =
218 visible.key === scopeKey && visible.rows.length ? visible.rows : data.entries.slice(0, 8);
219 + // Visible rows carry the cached-answer overlay below. Decide which still need stats on the rows
220 + // without it, so a cached answer shown offline does not unmount the query that holds it.
221 + const withoutCachedOverlay = new Map(
222 + data.entries.map((row) => [scopedPullRequestListKey(row), row]),
223 + );
224 const statsKey = JSON.stringify(
225 targets.flatMap(({ environmentId }) => {
226 const refs = visibleRows
205 - .filter((row) => row.environmentId === environmentId && row.additions + row.deletions === 0)
227 + .filter((row) => {
228 + const base = withoutCachedOverlay.get(scopedPullRequestListKey(row)) ?? row;
229 + return row.environmentId === environmentId && base.additions + base.deletions === 0;
230 + })
231 .map(({ projectId, host, repository, number }) => ({
232 projectId,
233 host,
@@ -223,33 +248,33 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
248 );
249 }, [statsKey]);
250 const counts = useAtomValue(statsAtom);
226 - useEffect(() => {
227 - for (const { environmentId, result } of counts) {
228 - if (result._tag !== "Success" || result.waiting) continue;
229 - registry.update(statsFamily(environmentId), (previous) => {
230 - const next = new Map(previous);
231 - for (const row of result.value.stats) next.set(statKey(row), row);
232 - return next;
233 - });
234 - }
235 - }, [registry, counts]);
251 + // Server answers land in pullRequestListStatsFamily; these cover a cached answer, which is
252 + // all an offline environment has.
253 + const entries = useMemo(
254 + () =>
255 + withShownPullRequestStats(
256 + data.entries,
257 + counts.flatMap(({ environmentId, result }) =>
258 + AsyncResult.isSuccess(result) ? [{ environmentId, stats: result.value.stats }] : [],
259 + ),
260 + ),
261 + [data.entries, counts],
262 + );
263
264 const updateEntry = useCallback(
265 (entry: EnvironmentPullRequestListEntry, patch: Partial<EnvironmentPullRequestListEntry>) => {
266 const target = targets.find((target) => target.environmentId === entry.environmentId);
267 if (!target) return;
241 - registry.update(pagesFamily(JSON.stringify(target)), (previous) =>
242 - previous
243 - ? {
244 - ...previous,
245 - entries: previous.entries.map((row) =>
246 - pullRequestListKey(row) === pullRequestListKey(entry)
247 - ? { ...row, ...patch, observedAt: Date.now() }
248 - : row,
249 - ),
250 - }
251 - : previous,
268 + const pagesAtom = pullRequestListPagesFamily(pullRequestListPagesKey(target));
269 + const read = <A>(atom: Atom.Atom<A>) => registry.get(atom);
270 + const patched = patchPullRequestListEntry(
271 + read(pagesAtom),
272 + currentHead(read, target),
273 + entry,
274 + patch,
275 + Date.now(),
276 );
277 + if (patched) registry.set(pagesAtom, patched);
278 registry.refresh(composerPullRequests.list(target));
279 },
280 [registry, targets],
@@ -269,10 +294,13 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
294 }),
295 [sources],
296 );
272 - const listing = useMemo(() => ({ ...data, errors: [...data.errors, ...errors] }), [data, errors]);
297 + const listing = useMemo(
298 + () => ({ ...data, entries, errors: [...data.errors, ...errors] }),
299 + [data, entries, errors],
300 + );
301 return {
302 data: listing,
275 - entries: data.entries,
303 + entries,
304 error: errors.map((error) => error.message).join("\n") || null,
305 isPending: sources.some(({ result }) => result.waiting) && !data.entries.length,
306 continued: data.continued,
@@ -280,9 +308,9 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
308 onRefresh,
309 onViewableItemsChanged,
310 updateEntry,
283 - refreshing: state.refresh,
284 - loadingMore: state.page,
285 - loadMoreError: state.error,
311 + refreshing: refresh.waiting,
312 + loadingMore: page.waiting,
313 + loadMoreError: loadError,
314 hasMore: sources.some(
315 ({ pages, target }) => pages && nextPullRequestListInput(pages, target.input),
316 ),
apps/mobile/src/state/pull-requests.ts
+41 -1
@@ -2,9 +2,49 @@ import {
2 createPullRequestEnvironmentAtoms,
3 createPullRequestStackAtomFamily,
4 } from "@t3tools/client-runtime/state/pull-requests";
5 +import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
6 +import * as Effect from "effect/Effect";
7 +import { Atom } from "effect/reactivity";
8 import { connectionAtomRuntime } from "../connection/runtime";
9 +import {
10 + pullRequestListHead,
11 + pullRequestStatKey,
12 + type PullRequestListPages,
13 +} from "../features/pull-requests/pullRequestList";
14 +
15 +export const pullRequestListPagesKey = (target: {
16 + readonly environmentId: EnvironmentId;
17 + readonly input: PullRequestListInput;
18 +}) => JSON.stringify([target.environmentId, target.input]);
19 +
20 +/** The pages loaded past each listing's head, keyed by {@link pullRequestListPagesKey}. */
21 +export const pullRequestListPagesFamily = Atom.family((_key: string) =>
22 + Atom.make<PullRequestListPages | null>(null).pipe(Atom.setIdleTTL(5 * 60_000)),
23 +);
24 +
25 +/** Diff stats each environment has answered so far, so rows keep them when they scroll away. */
26 +export const pullRequestListStatsFamily = Atom.family((_environmentId: string) =>
27 + Atom.make<ReadonlyMap<string, PullRequestDiffStat>>(new Map()).pipe(Atom.setIdleTTL(5 * 60_000)),
28 +);
29
7 -export const composerPullRequests = createPullRequestEnvironmentAtoms(connectionAtomRuntime);
30 +export const composerPullRequests = createPullRequestEnvironmentAtoms(connectionAtomRuntime, {
31 + list: (target, value, registry) =>
32 + target.input.cursors === undefined
33 + ? Effect.sync(() =>
34 + registry.update(pullRequestListPagesFamily(pullRequestListPagesKey(target)), (previous) =>
35 + pullRequestListHead(previous, value),
36 + ),
37 + )
38 + : Effect.void,
39 + listStats: (target, value, registry) =>
40 + Effect.sync(() =>
41 + registry.update(pullRequestListStatsFamily(target.environmentId), (previous) => {
42 + const next = new Map(previous);
43 + for (const row of value.stats) next.set(pullRequestStatKey(row), row);
44 + return next;
45 + }),
46 + ),
47 +});
48 export const pullRequestStackAtom = createPullRequestStackAtomFamily(
49 connectionAtomRuntime,
50 composerPullRequests.refreshes,
packages/client-runtime/src/state/pullRequests.ts
+4
@@ -14,6 +14,8 @@ import {
14 type PullRequestActor,
15 type PullRequestActionInput,
16 type PullRequestListInput,
17 + type PullRequestListStatsInput,
18 + type PullRequestListStatsResult,
19 type PullRequestDetail,
20 type PullRequestDiffInput,
21 type PullRequestRef,
@@ -144,6 +146,7 @@ export function createLinkedPullRequestSummaryAtomFamily<R, E>(
146 /** Lets a client record what each answer says where it lands, rather than watching the data. */
147 export interface PullRequestAnswerHandlers {
148 readonly list?: QueryAnswerHandler<PullRequestListInput, PullRequestListResult>;
149 + readonly listStats?: QueryAnswerHandler<PullRequestListStatsInput, PullRequestListStatsResult>;
150 readonly detail?: QueryAnswerHandler<PullRequestRef, PullRequestDetail>;
151 readonly checks?: QueryAnswerHandler<PullRequestRef, PullRequestChecks | null>;
152 readonly reviewGuide?: QueryAnswerHandler<PullRequestRef, PullRequestReviewGuideResult>;
@@ -357,6 +360,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
360 tag: WS_METHODS.pullRequestsListStats,
361 staleTimeMs: 60_000,
362 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
363 + ...(onAnswer.listStats === undefined ? {} : { onAnswer: onAnswer.listStats }),
364 }),
365 filterOptions: createEnvironmentRpcQueryAtomFamily(runtime, {
366 label: "environment-data:pull-requests:filter-options",