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): thread rows share one clock and cache SVGs instead of per-row effects (#25612)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 15:27 UTC
a4fbea86537af2afc7405417e63701555f267b07
9 files changed
+303
-204
apps/mobile/src/features/threads/CopyTextButton.tsx
+7
-19
@@ -1,8 +1,9 @@
1
import * as Dialog from "../../components/ui/Dialog";
2
import { SymbolView } from "../../components/ui/AppSymbol";
3
-import { memo, useEffect, useRef, useState } from "react";
3
+import { memo, useState } from "react";
4
import { Pressable, type ColorValue } from "react-native";
5
6
+import { useDeadlinePassed } from "../../lib/clock";
7
import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic";
8
9
const COPY_FEEDBACK_DURATION_MS = 1200;
@@ -20,17 +21,11 @@ export const CopyTextButton = memo(function CopyTextButton(props: {
21
readonly iconSize?: number;
22
readonly buttonSize?: number;
23
}) {
23
- const [copied, setCopied] = useState(false);
24
- const resetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
25
-
26
- useEffect(
27
- () => () => {
28
- if (resetTimeoutRef.current) {
29
- clearTimeout(resetTimeoutRef.current);
30
- }
31
- },
32
- [],
24
+ const [copiedAtMs, setCopiedAtMs] = useState<number | null>(null);
25
+ const feedbackEnded = useDeadlinePassed(
26
+ copiedAtMs === null ? null : copiedAtMs + COPY_FEEDBACK_DURATION_MS,
27
);
28
+ const copied = copiedAtMs !== null && !feedbackEnded;
29
30
return (
31
<Pressable
@@ -50,14 +45,7 @@ export const CopyTextButton = memo(function CopyTextButton(props: {
45
Dialog.alert("Could not copy", "Try again.");
46
return;
47
}
53
- setCopied(true);
54
- if (resetTimeoutRef.current) {
55
- clearTimeout(resetTimeoutRef.current);
56
- }
57
- resetTimeoutRef.current = setTimeout(() => {
58
- setCopied(false);
59
- resetTimeoutRef.current = null;
60
- }, COPY_FEEDBACK_DURATION_MS);
48
+ setCopiedAtMs(Date.now());
49
}}
50
style={({ pressed }) => ({
51
width: props.buttonSize ?? 30,
apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx
+54
@@ -36,6 +36,11 @@ vi.mock("../../components/ui/NativePresentation", () => ({
36
vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: [] }) }));
37
vi.mock("../../state/assets", () => ({ useAssetUrlState: vi.fn() }));
38
39
+import { RegistryContext } from "@effect/atom-react";
40
+import { AtomRegistry } from "effect/reactivity";
41
+import { fetch } from "expo/fetch";
42
+import { parse } from "react-native-svg";
43
+
44
import { ThreadMarkdownImageView } from "./ThreadMarkdownImage";
45
46
it("retries a failed image once its URI comes back through null", async () => {
@@ -64,3 +69,52 @@ it("retries a failed image once its URI comes back through null", async () => {
69
await act(async () => root.unmount());
70
}
71
});
72
+
73
+it("fetches a failed SVG again on the next mount but keeps a parsed one", async () => {
74
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
75
+ // Microtask scheduling lets act() flush an unmounted atom's removal before the next render.
76
+ const registry = AtomRegistry.make({
77
+ scheduleTask: (task) => {
78
+ queueMicrotask(task);
79
+ return () => {};
80
+ },
81
+ });
82
+ const fetchSvg = vi.mocked(fetch);
83
+ vi.mocked(parse).mockReturnValue({ props: {} } as ReturnType<typeof parse>);
84
+ const container = document.createElement("div");
85
+ const root = createRoot(container);
86
+ const uri = "https://example.test/a.svg";
87
+ const view = (mounted: boolean) => (
88
+ <RegistryContext.Provider value={registry}>
89
+ {mounted ? (
90
+ <ThreadMarkdownImageView
91
+ uri={uri}
92
+ sourceKey="attachment:svg"
93
+ unavailable={false}
94
+ alt={null}
95
+ format="svg"
96
+ onPressPreview={() => {}}
97
+ />
98
+ ) : null}
99
+ </RegistryContext.Provider>
100
+ );
101
+ try {
102
+ fetchSvg.mockRejectedValueOnce(new Error("offline"));
103
+ await act(async () => root.render(view(true)));
104
+ await vi.waitFor(() => expect(container.textContent).toContain("Image unavailable"));
105
+
106
+ await act(async () => root.render(view(false)));
107
+ fetchSvg.mockResolvedValue({ ok: true, status: 200, text: async () => "<svg />" } as never);
108
+ await act(async () => root.render(view(true)));
109
+ await vi.waitFor(() => expect(container.textContent).not.toContain("Image unavailable"));
110
+ expect(fetchSvg).toHaveBeenCalledTimes(2);
111
+
112
+ await act(async () => root.render(view(false)));
113
+ await act(async () => root.render(view(true)));
114
+ expect(container.textContent).not.toContain("Image unavailable");
115
+ expect(fetchSvg).toHaveBeenCalledTimes(2);
116
+ } finally {
117
+ await act(async () => root.unmount());
118
+ registry.dispose();
119
+ }
120
+});
apps/mobile/src/features/threads/ThreadMarkdownImage.tsx
+108
-87
@@ -1,7 +1,11 @@
1
+import { useAtomValue } from "@effect/atom-react";
2
import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets";
3
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
4
+import * as Data from "effect/Data";
5
+import * as Effect from "effect/Effect";
6
+import { AsyncResult, Atom } from "effect/reactivity";
7
import { Image } from "expo-image";
4
-import { createContext, useContext, useEffect, useEffectEvent, useId, useState } from "react";
8
+import { createContext, useContext, useId, useState } from "react";
9
import { fetch } from "expo/fetch";
10
import { parse, SvgAst, type JsxAST } from "react-native-svg";
11
import { Pressable, StyleSheet, View, type ViewStyle } from "react-native";
@@ -25,6 +29,58 @@ import {
29
/** Use known feed width immediately; later image measurement would move already-positioned rows. */
30
export const MarkdownImageAvailableWidthContext = createContext(0);
31
32
+type ImageSize = { readonly width: number; readonly height: number };
33
+
34
+class SvgLoadError extends Data.TaggedError("SvgLoadError")<{ readonly cause: unknown }> {}
35
+
36
+async function readSvgXml(uri: string, signal: AbortSignal): Promise<string> {
37
+ if (uri.startsWith("data:image/svg+xml")) {
38
+ const comma = uri.indexOf(",");
39
+ if (comma < 0) throw new Error("SVG data URI has no content");
40
+ const content = decodeURIComponent(uri.slice(comma + 1));
41
+ return uri.slice(0, comma).includes(";base64")
42
+ ? new TextDecoder().decode(
43
+ Uint8Array.from(atob(content), (character) => character.charCodeAt(0)),
44
+ )
45
+ : content;
46
+ }
47
+ // expo/fetch, not the runtime HttpClient: it is the one that reads file:// URIs.
48
+ const response = await fetch(uri, { signal });
49
+ if (!response.ok && !(response.status === 0 && uri.startsWith("file://")))
50
+ throw new Error(`SVG request failed: ${response.status}`);
51
+ return response.text();
52
+}
53
+
54
+type SvgDocument = { readonly ast: JsxAST; readonly size: ImageSize | null };
55
+
56
+// Feed rows unmount as they scroll away. Only parsed documents outlive their
57
+// readers (for the row that scrolls back); a failed load is dropped with its last
58
+// reader so the next mount fetches again.
59
+const parsedSvgDocumentAtom = Atom.family((_uri: string) =>
60
+ Atom.make<SvgDocument | null>(null).pipe(
61
+ Atom.setIdleTTL(60_000),
62
+ Atom.withLabel("mobile:thread-markdown-svg-parsed"),
63
+ ),
64
+);
65
+
66
+const svgDocumentAtom = Atom.family((uri: string) =>
67
+ Atom.make((get) => {
68
+ const parsed = parsedSvgDocumentAtom(uri);
69
+ const cached = get(parsed);
70
+ if (cached !== null) return Effect.succeed(cached);
71
+ return Effect.tryPromise({
72
+ try: async (signal): Promise<SvgDocument> => {
73
+ const ast = parse(await readSvgXml(uri, signal));
74
+ if (!ast) throw new Error("SVG has no root element");
75
+ return { ast, size: resolveSvgImageSize(ast.props) };
76
+ },
77
+ catch: (cause) => new SvgLoadError({ cause }),
78
+ }).pipe(Effect.tap((document) => Effect.sync(() => get.set(parsed, document))));
79
+ }).pipe(Atom.withLabel("mobile:thread-markdown-svg")),
80
+);
81
+
82
+const noSvgDocumentAtom = Atom.make(AsyncResult.initial<SvgDocument, SvgLoadError>());
83
+
84
export function ThreadMarkdownImageView(props: {
85
readonly uri: string | null;
86
readonly sourceKey: string;
@@ -45,12 +101,14 @@ export function ThreadMarkdownImageView(props: {
101
measuredWidth > 0 && contextWidth > 0
102
? Math.min(contextWidth, measuredWidth)
103
: contextWidth || measuredWidth;
104
+ const svg = useAtomValue(
105
+ props.format === "svg" && props.uri !== null ? svgDocumentAtom(props.uri) : noSvgDocumentAtom,
106
+ );
107
+ const svgDocument = AsyncResult.isSuccess(svg) ? svg.value : null;
108
// Keyed by source so a new source drops the previous image's decoded dimensions.
49
- const [decoded, setDecoded] = useState<{
50
- sourceKey: string;
51
- size: { width: number; height: number };
52
- } | null>(null);
53
- const decodedSize = decoded?.sourceKey === props.sourceKey ? decoded.size : null;
109
+ const [decoded, setDecoded] = useState<{ sourceKey: string; size: ImageSize } | null>(null);
110
+ const decodedSize =
111
+ svgDocument?.size ?? (decoded?.sourceKey === props.sourceKey ? decoded.size : null);
112
// A failure belongs to one URI; any URI change, including through null, retries.
113
const [failure, setFailure] = useState({ uri: props.uri, failed: false });
114
if (failure.uri !== props.uri) setFailure({ uri: props.uri, failed: false });
@@ -65,7 +123,9 @@ export function ThreadMarkdownImageView(props: {
123
availableWidth,
124
});
125
const failed =
68
- props.unavailable || (props.uri !== null && failure.uri === props.uri && failure.failed);
126
+ props.unavailable ||
127
+ (props.uri !== null && failure.uri === props.uri && failure.failed) ||
128
+ AsyncResult.isFailure(svg);
129
const placeholderWidth: ViewStyle["width"] =
130
availableWidth > 0 ? Math.min(availableWidth, MARKDOWN_IMAGE_MAX_WIDTH) : "100%";
131
const frameStyle: ViewStyle = displaySize ?? { width: placeholderWidth, aspectRatio: 16 / 9 };
@@ -123,13 +183,16 @@ export function ThreadMarkdownImageView(props: {
183
className="items-center justify-center overflow-hidden rounded-[10px] bg-md-code-bg"
184
style={frameStyle}
185
>
126
- <ThreadMarkdownImageRequest
127
- key={props.sourceKey}
128
- uri={props.uri}
129
- format={props.format}
130
- onLoad={(size) => setDecoded({ sourceKey: props.sourceKey, size })}
131
- onError={() => setFailure({ uri: props.uri, failed: true })}
132
- />
186
+ {props.format === "svg" ? (
187
+ <ThreadMarkdownSvg ast={svgDocument?.ast ?? null} />
188
+ ) : (
189
+ <ThreadMarkdownImageRequest
190
+ key={props.sourceKey}
191
+ uri={props.uri}
192
+ onLoad={(size) => setDecoded({ sourceKey: props.sourceKey, size })}
193
+ onError={() => setFailure({ uri: props.uri, failed: true })}
194
+ />
195
+ )}
196
</View>
197
</Pressable>
198
</MediaActionsMenu>
@@ -146,89 +209,47 @@ export function ThreadMarkdownImageView(props: {
209
210
function ThreadMarkdownImageRequest(props: {
211
readonly uri: string;
149
- readonly onLoad: (sourceSize: { width: number; height: number }) => void;
212
+ readonly onLoad: (sourceSize: ImageSize) => void;
213
readonly onError: () => void;
151
- readonly format?: "svg";
214
}) {
215
const [loaded, setLoaded] = useState(false);
216
217
return (
218
<>
157
- {props.format === "svg" ? (
158
- <ThreadMarkdownSvg
159
- uri={props.uri}
160
- onLoad={(size) => {
161
- setLoaded(true);
162
- if (size) props.onLoad(size);
163
- }}
164
- onError={props.onError}
165
- />
166
- ) : (
167
- <Image
168
- source={{ uri: props.uri }}
169
- contentFit="contain"
170
- cachePolicy="memory-disk"
171
- accessible={false}
172
- onLoad={(event) => {
173
- setLoaded(true);
174
- props.onLoad(event.source);
175
- }}
176
- onError={props.onError}
177
- style={{ width: "100%", height: "100%", opacity: loaded ? 1 : 0 }}
178
- />
179
- )}
180
- {loaded ? null : (
181
- <View
182
- pointerEvents="none"
183
- style={[StyleSheet.absoluteFill, { alignItems: "center", justifyContent: "center" }]}
184
- >
185
- <Text className="text-xs text-foreground-muted">Loading image…</Text>
186
- </View>
187
- )}
219
+ <Image
220
+ source={{ uri: props.uri }}
221
+ contentFit="contain"
222
+ cachePolicy="memory-disk"
223
+ accessible={false}
224
+ onLoad={(event) => {
225
+ setLoaded(true);
226
+ props.onLoad(event.source);
227
+ }}
228
+ onError={props.onError}
229
+ style={{ width: "100%", height: "100%", opacity: loaded ? 1 : 0 }}
230
+ />
231
+ {loaded ? null : <ThreadMarkdownImageLoading />}
232
</>
233
);
234
}
235
192
-function ThreadMarkdownSvg(props: {
193
- readonly uri: string;
194
- readonly onLoad: (size: { width: number; height: number } | null) => void;
195
- readonly onError: () => void;
196
-}) {
197
- const [ast, setAst] = useState<JsxAST | null>(null);
198
- const onLoad = useEffectEvent(props.onLoad);
199
- const onError = useEffectEvent(props.onError);
200
- useEffect(() => {
201
- const controller = new AbortController();
202
- const load = async () => {
203
- if (props.uri.startsWith("data:image/svg+xml")) {
204
- const comma = props.uri.indexOf(",");
205
- if (comma < 0) throw new Error("SVG data URI has no content");
206
- const content = decodeURIComponent(props.uri.slice(comma + 1));
207
- return props.uri.slice(0, comma).includes(";base64")
208
- ? new TextDecoder().decode(
209
- Uint8Array.from(atob(content), (character) => character.charCodeAt(0)),
210
- )
211
- : content;
212
- }
213
- const response = await fetch(props.uri, { signal: controller.signal });
214
- if (!response.ok && !(response.status === 0 && props.uri.startsWith("file://")))
215
- throw new Error(`SVG request failed: ${response.status}`);
216
- return response.text();
217
- };
218
- void load()
219
- .then((xml) => {
220
- const parsed = parse(xml);
221
- if (!parsed) throw new Error("SVG has no root element");
222
- if (controller.signal.aborted) return;
223
- setAst(parsed);
224
- onLoad(resolveSvgImageSize(parsed.props));
225
- })
226
- .catch(() => {
227
- if (!controller.signal.aborted) onError();
228
- });
229
- return () => controller.abort();
230
- }, [props.uri]);
231
- return <SvgAst ast={ast} override={{ width: "100%", height: "100%", accessible: false }} />;
236
+function ThreadMarkdownImageLoading() {
237
+ return (
238
+ <View
239
+ pointerEvents="none"
240
+ style={[StyleSheet.absoluteFill, { alignItems: "center", justifyContent: "center" }]}
241
+ >
242
+ <Text className="text-xs text-foreground-muted">Loading image…</Text>
243
+ </View>
244
+ );
245
+}
246
+
247
+function ThreadMarkdownSvg(props: { readonly ast: JsxAST | null }) {
248
+ return props.ast === null ? (
249
+ <ThreadMarkdownImageLoading />
250
+ ) : (
251
+ <SvgAst ast={props.ast} override={{ width: "100%", height: "100%", accessible: false }} />
252
+ );
253
}
254
255
export function ThreadMarkdownImage(props: {
apps/mobile/src/features/threads/thread-list-v2-items.tsx
+9
-15
@@ -28,7 +28,7 @@ import {
28
import { AuthOrchestrationOperateScope, type EnvironmentMachineKind } from "@t3tools/contracts";
29
import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
30
import type { MenuAction } from "@react-native-menu/menu";
31
-import { memo, useCallback, useEffect, useMemo, useState, type ComponentProps } from "react";
31
+import { memo, useCallback, useMemo, useState, type ComponentProps } from "react";
32
import { Pressable, useWindowDimensions, View } from "react-native";
33
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
34
@@ -39,6 +39,7 @@ import { Menu } from "../../components/ui/Menu";
39
import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
40
import { ProjectFavicon } from "../../components/ProjectFavicon";
41
import { ProviderIcon, ProviderInstanceIcon } from "../../components/ProviderIcon";
42
+import { useNowAfter } from "../../lib/clock";
43
import { cn } from "../../lib/cn";
44
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
45
import { useUniwindTheme } from "../../lib/useUniwindTheme";
@@ -712,22 +713,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
713
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
714
715
const canUnsettle = variant === "slim";
715
- // Keep time in state; cached render-time reads freeze the gate and trigger 50ms expiry loops.
716
- const [snoozeGateClock, setSnoozeGateClock] = useState(() => ({ thread, now: Date.now() }));
717
- // oxlint-disable-next-line react/purity -- Reseeds the snooze gate clock only in the render-phase adjustment that runs when the thread changes.
718
- if (snoozeGateClock.thread !== thread) setSnoozeGateClock({ thread, now: Date.now() });
719
- const snoozeGateNow = new Date(snoozeGateClock.now).toISOString();
716
+ // The gate's only time-dependent edge is the queued-turn grace window, so its
717
+ // expiry is known without a clock: evaluate at the message's own timestamp.
718
+ // A gate held by runtime status has no expiry, and no clock tick opens it.
719
const snoozeGateExpiryMs = props.snoozeSupported
721
- ? resolveThreadListV2SnoozeGateExpiryMs(thread, { now: snoozeGateNow })
720
+ ? resolveThreadListV2SnoozeGateExpiryMs(thread, { now: thread.latestUserMessageAt ?? "" })
721
: null;
723
- useEffect(() => {
724
- // A gate still closed past its expiry is held by runtime status, not time,
725
- // so no clock tick can open it.
726
- if (snoozeGateExpiryMs === null || snoozeGateExpiryMs <= snoozeGateClock.now) return;
727
- const delayMs = Math.min(snoozeGateExpiryMs - Date.now() + 50, 2_147_483_647);
728
- const id = setTimeout(() => setSnoozeGateClock({ thread, now: Date.now() }), delayMs);
729
- return () => clearTimeout(id);
730
- }, [snoozeGateExpiryMs, snoozeGateClock.now, thread]);
722
+ // The window is inclusive, so wake just past it.
723
+ const snoozeGateNowMs = useNowAfter(snoozeGateExpiryMs === null ? null : snoozeGateExpiryMs + 1);
724
+ const snoozeGateNow = new Date(snoozeGateNowMs).toISOString();
725
const swipeActions = resolveThreadListV2SwipeActions({
726
variant,
727
settlementSupported: props.settlementSupported,
apps/mobile/src/features/threads/use-visible-second-clock.ts
+18
-21
@@ -1,27 +1,24 @@
1
import { useIsFocused } from "@react-navigation/native";
2
-import { useEffect, useLayoutEffect, useState } from "react";
3
-import { AppState } from "react-native";
2
+import { secondTick } from "@t3tools/client-runtime/clock";
3
+import { useSyncExternalStore } from "react";
4
5
-/** Hidden retained routes stay mounted; gate intervals to avoid background re-renders. */
5
+import { useAppActive } from "../../lib/appState";
6
+
7
+const subscribeNever = () => () => undefined;
8
+
9
+/**
10
+ * Retained routes stay mounted when hidden, so an ungated tick would keep
11
+ * re-rendering them. Every visible label shares one module-level tick.
12
+ */
13
export function useVisibleSecondClock(enabled: boolean): number {
14
const focused = useIsFocused();
8
- const [appActive, setAppActive] = useState(() => AppState.currentState === "active");
9
- const [nowMs, setNowMs] = useState(() => Date.now());
10
- useEffect(() => {
11
- const subscription = AppState.addEventListener("change", (state) =>
12
- setAppActive(state === "active"),
13
- );
14
- // oxlint-disable-next-line react/set-state-in-effect -- Syncs state the listener missed.
15
- setAppActive(AppState.currentState === "active");
16
- return () => subscription.remove();
17
- }, []);
15
+ const appActive = useAppActive();
16
const ticking = enabled && focused && appActive;
19
- useLayoutEffect(() => {
20
- if (!ticking) return;
21
- // oxlint-disable-next-line react/set-state-in-effect -- Resuming reads the clock that stood still.
22
- setNowMs(Date.now());
23
- const intervalId = setInterval(() => setNowMs(Date.now()), 1_000);
24
- return () => clearInterval(intervalId);
25
- }, [ticking]);
26
- return nowMs;
17
+ // While paused the snapshot still reads the shared tick, so resuming shows
18
+ // the current second rather than the one the clock stopped on.
19
+ return useSyncExternalStore(
20
+ ticking ? secondTick.subscribe : subscribeNever,
21
+ secondTick.getSnapshot,
22
+ secondTick.getSnapshot,
23
+ );
24
}
apps/mobile/src/lib/clock.ts
+17
-1
@@ -1,5 +1,5 @@
1
import { deadlineStore, minuteTick } from "@t3tools/client-runtime/clock";
2
-import { useSyncExternalStore } from "react";
2
+import { useState, useSyncExternalStore } from "react";
3
4
/** Re-renders once when `deadlineMs` (epoch ms) is reached; `null` never passes. */
5
export function useDeadlinePassed(deadlineMs: number | null): boolean {
@@ -7,6 +7,22 @@ export function useDeadlinePassed(deadlineMs: number | null): boolean {
7
return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
8
}
9
10
+/**
11
+ * `Date.now()` captured at mount and re-read when `deadlineMs` changes or
12
+ * passes, so comparisons against the deadline flip exactly once.
13
+ */
14
+export function useNowAfter(deadlineMs: number | null): number {
15
+ const passed = useDeadlinePassed(deadlineMs);
16
+ const [snapshot, setSnapshot] = useState(() => ({ deadlineMs, passed, nowMs: Date.now() }));
17
+ if (snapshot.deadlineMs !== deadlineMs || snapshot.passed !== passed) {
18
+ // oxlint-disable-next-line react/purity -- Re-reads the clock only in the render-phase adjustment that runs when the deadline changes or passes.
19
+ const next = { deadlineMs, passed, nowMs: Date.now() };
20
+ setSnapshot(next);
21
+ return next.nowMs;
22
+ }
23
+ return snapshot.nowMs;
24
+}
25
+
26
/**
27
* `minuteTick`'s UTC `YYYY-MM-DDTHH:mm` as epoch ms. The snapshot carries no
28
* offset, and `Date.parse` reads offset-less date-times as local time.
apps/mobile/src/state/thread-pr-presentation.ts
+17
@@ -131,3 +131,20 @@ export function resolveThreadPrBadgeAction(pr: ThreadPrPresentation) {
131
? { kind: "list" as const, accessibilityLabel: `Show ${pr.accessibilityLabel}` }
132
: { kind: "open" as const, accessibilityLabel: `Open ${pr.accessibilityLabel}` };
133
}
134
+
135
+/** Records `value` as the newest entry, evicting the least recently answered beyond `limit`. */
136
+export function rememberBounded<V>(
137
+ current: ReadonlyMap<string, V>,
138
+ key: string,
139
+ value: V,
140
+ limit: number,
141
+): ReadonlyMap<string, V> {
142
+ const next = new Map(current);
143
+ next.delete(key);
144
+ next.set(key, value);
145
+ for (const oldest of next.keys()) {
146
+ if (next.size <= limit) break;
147
+ next.delete(oldest);
148
+ }
149
+ return next;
150
+}
apps/mobile/src/state/use-thread-pr.test.ts
+19
-1
@@ -1,7 +1,11 @@
1
import { ProjectId, type ThreadPullRequestLink } from "@t3tools/contracts";
2
import { describe, expect, it } from "vite-plus/test";
3
4
-import { presentThreadLinkedPullRequests, resolveThreadPrSource } from "./thread-pr-presentation";
4
+import {
5
+ presentThreadLinkedPullRequests,
6
+ rememberBounded,
7
+ resolveThreadPrSource,
8
+} from "./thread-pr-presentation";
9
10
function linkedPr(
11
number: number,
@@ -117,3 +121,17 @@ describe("resolveThreadPrSource compatibility", () => {
121
).toMatchObject({ linkedPresentation: { number: 3, state: null }, pullRequestRef: null });
122
});
123
});
124
+
125
+describe("rememberBounded", () => {
126
+ it("moves a re-answered entry to the newest slot and evicts the oldest past the limit", () => {
127
+ let snapshots: ReadonlyMap<string, number> = new Map();
128
+ snapshots = rememberBounded(snapshots, "a", 1, 2);
129
+ snapshots = rememberBounded(snapshots, "b", 2, 2);
130
+ snapshots = rememberBounded(snapshots, "a", 3, 2);
131
+ snapshots = rememberBounded(snapshots, "c", 4, 2);
132
+ expect([...snapshots]).toEqual([
133
+ ["a", 3],
134
+ ["c", 4],
135
+ ]);
136
+ });
137
+});
apps/mobile/src/state/use-thread-pr.ts
+54
-60
@@ -1,37 +1,61 @@
1
import { useAtomValue } from "@effect/atom-react";
2
-import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3
import {
4
createLinkedPullRequestSummaryAtomFamily,
5
pullRequestDetailToVcsStatus,
6
} from "@t3tools/client-runtime/state/pull-requests";
7
+import type { EnvironmentId, PullRequestSummary } from "@t3tools/contracts";
8
+import * as Effect from "effect/Effect";
9
import { Atom } from "effect/reactivity";
9
-import { useCallback, useEffect, useMemo } from "react";
10
+import { useMemo } from "react";
11
12
import { connectionAtomRuntime } from "../connection/runtime";
12
-import { appAtomRegistry } from "./atom-registry";
13
import { serverEnvironment } from "./server";
14
import { useEnvironmentQuery } from "./query";
15
import {
16
+ rememberBounded,
17
resolveThreadPrSource,
18
presentThreadPr,
19
type ThreadPrPresentation,
20
} from "./thread-pr-presentation";
21
21
-const pullRequestSummaryAtom = createLinkedPullRequestSummaryAtomFamily(connectionAtomRuntime);
22
-const MAX_THREAD_PR_SNAPSHOTS = 500;
22
+const MAX_PULL_REQUEST_SNAPSHOTS = 500;
23
24
-interface ThreadPrSnapshot {
25
- readonly identity: string;
26
- readonly presentation: ThreadPrPresentation;
27
-}
28
-
29
-// Bound the cache across row virtualization instead of retaining live atoms for every past thread or PR.
30
-const threadPrSnapshotsAtom = Atom.make<ReadonlyMap<string, ThreadPrSnapshot>>(new Map()).pipe(
24
+// One bounded cache survives row virtualization (the summary query is dropped once idle) without
25
+// retaining one live atom for every pull request ever seen.
26
+const pullRequestSnapshotsAtom = Atom.make<ReadonlyMap<string, PullRequestSummary>>(new Map()).pipe(
27
Atom.keepAlive,
28
Atom.withLabel("mobile:thread-pr-snapshots"),
29
);
30
31
+function snapshotKey(
32
+ environmentId: EnvironmentId,
33
+ reference: { readonly projectId: string; readonly repository: string; readonly number: number },
34
+): string {
35
+ return JSON.stringify([
36
+ environmentId,
37
+ reference.projectId,
38
+ reference.repository,
39
+ reference.number,
40
+ ]);
41
+}
42
+
43
+const pullRequestSummaryAtom = createLinkedPullRequestSummaryAtomFamily(
44
+ connectionAtomRuntime,
45
+ undefined,
46
+ ({ environmentId, input }, summary, registry) =>
47
+ Effect.sync(() =>
48
+ registry.update(pullRequestSnapshotsAtom, (current) =>
49
+ rememberBounded(
50
+ current,
51
+ snapshotKey(environmentId, input),
52
+ summary,
53
+ MAX_PULL_REQUEST_SNAPSHOTS,
54
+ ),
55
+ ),
56
+ ),
57
+);
58
+
59
export {
60
presentThreadPr,
61
type ThreadPr,
@@ -55,16 +79,11 @@ export function useThreadPr(thread: EnvironmentThreadShell): ThreadPrPresentatio
79
),
80
[thread.pullRequests, thread.linkedPullRequest, thread.branchPullRequest, supportsLinks],
81
);
58
- const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
59
- const snapshotIdentity = JSON.stringify(pullRequestRef);
60
- const snapshotEntry = useAtomValue(
61
- threadPrSnapshotsAtom,
62
- useCallback(
63
- (current: ReadonlyMap<string, ThreadPrSnapshot>) => current.get(threadKey),
64
- [threadKey],
65
- ),
82
+ const key = pullRequestRef === null ? null : snapshotKey(thread.environmentId, pullRequestRef);
83
+ // Select this row's entry so answers for other pull requests do not re-render it.
84
+ const snapshot = useAtomValue(pullRequestSnapshotsAtom, (current) =>
85
+ key === null ? undefined : current.get(key),
86
);
67
- const snapshot = snapshotEntry?.identity === snapshotIdentity ? snapshotEntry.presentation : null;
87
const pullRequestSummary = useEnvironmentQuery(
88
pullRequestRef === null
89
? null
@@ -77,43 +96,18 @@ export function useThreadPr(thread: EnvironmentThreadShell): ThreadPrPresentatio
96
},
97
}),
98
);
80
-
81
- const live = useMemo<ThreadPrPresentation | null | undefined>(() => {
82
- if (pullRequestRef === null) return null;
83
- const summary = pullRequestSummary.data;
84
- return summary === null
85
- ? undefined
86
- : presentThreadPr(pullRequestDetailToVcsStatus(summary), {
87
- kind: summary.provider,
88
- name: summary.provider,
89
- baseUrl: "",
90
- });
91
- }, [pullRequestRef, pullRequestSummary.data]);
92
-
93
- useEffect(() => {
94
- if (live === undefined) return;
95
- appAtomRegistry.modify(threadPrSnapshotsAtom, (current) => {
96
- const existing = current.get(threadKey);
97
- if (live === null) {
98
- if (existing === undefined) return [false, current];
99
- const next = new Map(current);
100
- next.delete(threadKey);
101
- return [true, next];
102
- }
103
- if (existing?.identity === snapshotIdentity && existing.presentation === live) {
104
- return [false, current];
105
- }
106
- const next = new Map(current);
107
- next.delete(threadKey);
108
- next.set(threadKey, { identity: snapshotIdentity, presentation: live });
109
- while (next.size > MAX_THREAD_PR_SNAPSHOTS) {
110
- const oldestKey = next.keys().next().value;
111
- if (oldestKey === undefined) break;
112
- next.delete(oldestKey);
113
- }
114
- return [true, next];
115
- });
116
- }, [live, snapshotIdentity, threadKey]);
117
-
118
- return linkedPresentation ?? (live === undefined ? snapshot : live);
99
+ const summary = pullRequestRef === null ? undefined : (pullRequestSummary.data ?? snapshot);
100
+ // Rows pass `pr` into callbacks; a fresh object per render would invalidate them.
101
+ const summaryPresentation = useMemo(
102
+ () =>
103
+ summary === undefined
104
+ ? null
105
+ : presentThreadPr(pullRequestDetailToVcsStatus(summary), {
106
+ kind: summary.provider,
107
+ name: summary.provider,
108
+ baseUrl: "",
109
+ }),
110
+ [summary],
111
+ );
112
+ return linkedPresentation ?? summaryPresentation;
113
}