Skip to content

Commit 6b0a32b

Browse files
fix(mobile): failed SVG loads retry on remount and thread PR badges keep their identity
Only a parsed SVG document outlives its readers; a failed load is dropped with its last reader so the next mount fetches again. useThreadPr memoizes its presentation on the summary so rows' PR callbacks stay stable. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2b408d4 commit 6b0a32b

3 files changed

Lines changed: 89 additions & 20 deletions

File tree

‎apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ vi.mock("../../components/ui/NativePresentation", () => ({
3636
vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: [] }) }));
3737
vi.mock("../../state/assets", () => ({ useAssetUrlState: vi.fn() }));
3838

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+
3944
import { ThreadMarkdownImageView } from "./ThreadMarkdownImage";
4045

4146
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 () => {
6469
await act(async () => root.unmount());
6570
}
6671
});
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‎

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,24 +51,35 @@ async function readSvgXml(uri: string, signal: AbortSignal): Promise<string> {
5151
return response.text();
5252
}
5353

54-
// Feed rows unmount as they scroll away; the idle TTL keeps a parsed document
55-
// for the row that scrolls back instead of fetching it again.
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+
5666
const svgDocumentAtom = Atom.family((uri: string) =>
57-
Atom.make(
58-
Effect.tryPromise({
59-
try: async (signal) => {
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> => {
6073
const ast = parse(await readSvgXml(uri, signal));
6174
if (!ast) throw new Error("SVG has no root element");
6275
return { ast, size: resolveSvgImageSize(ast.props) };
6376
},
6477
catch: (cause) => new SvgLoadError({ cause }),
65-
}),
66-
).pipe(Atom.setIdleTTL(60_000), Atom.withLabel("mobile:thread-markdown-svg")),
78+
}).pipe(Effect.tap((document) => Effect.sync(() => get.set(parsed, document))));
79+
}).pipe(Atom.withLabel("mobile:thread-markdown-svg")),
6780
);
6881

69-
const noSvgDocumentAtom = Atom.make(
70-
AsyncResult.initial<{ readonly ast: JsxAST; readonly size: ImageSize | null }, SvgLoadError>(),
71-
);
82+
const noSvgDocumentAtom = Atom.make(AsyncResult.initial<SvgDocument, SvgLoadError>());
7283

7384
export function ThreadMarkdownImageView(props: {
7485
readonly uri: string | null;

‎apps/mobile/src/state/use-thread-pr.ts‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -96,14 +96,18 @@ export function useThreadPr(thread: EnvironmentThreadShell): ThreadPrPresentatio
9696
},
9797
}),
9898
);
99-
if (linkedPresentation !== null) return linkedPresentation;
100-
if (pullRequestRef === null) return null;
101-
const summary = pullRequestSummary.data ?? snapshot;
102-
return summary === undefined
103-
? null
104-
: presentThreadPr(pullRequestDetailToVcsStatus(summary), {
105-
kind: summary.provider,
106-
name: summary.provider,
107-
baseUrl: "",
108-
});
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;
109113
}

0 commit comments

Comments
 (0)