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): media previews share file leases and close on blur in one place (#25527)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 11:53 UTC
220eb73524ca7882d53b6a12c824ccbcd97ad279
13 files changed
+621
-477
apps/mobile/src/components/ComposerContextAttachment.tsx
+10
-25
@@ -5,10 +5,13 @@ import * as Dialog from "./ui/Dialog";
5
import type { ComposerContextRecord, EnvironmentId } from "@t3tools/contracts";
6
import { Pressable, View } from "react-native";
7
import { Image } from "expo-image";
8
-import { useEffect, useId, useState } from "react";
8
+import { useId, useState } from "react";
9
import type { DraftComposerAttachment } from "../lib/composerImages";
10
import { composerAttachmentInlineUri, isFileBackedComposerAttachment } from "../lib/composerImages";
11
-import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
11
+import {
12
+ loadLocalAttachmentPreview,
13
+ useLocalAttachmentPreview,
14
+} from "../lib/localAttachmentPreview";
15
import { downloadAndShareAttachment } from "../lib/attachmentDownload";
16
import { assetImageSource } from "../lib/assetImageSource";
17
import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets";
@@ -35,31 +38,13 @@ export function ComposerContextAttachment(props: {
38
const remoteEnvironmentId = local || inlineUri ? null : (props.environmentId ?? null);
39
const asset = useAssetUrlState(remoteEnvironmentId, resource);
40
const refresh = useRefreshAssetUrl(remoteEnvironmentId, resource);
38
- const [localUri, setLocalUri] = useState<string | null>(null);
39
- const [error, setError] = useState<string | null>(null);
41
+ const localPreview = useLocalAttachmentPreview(local ?? null);
42
+ const error = localPreview.error ? "The local file is unavailable. Attach it again." : null;
43
const [sharing, setSharing] = useState(false);
44
const [previewOpen, setPreviewOpen] = useState(false);
42
- useEffect(() => {
43
- if (!local) return;
44
- const controller = new AbortController();
45
- let dispose: (() => void) | undefined;
46
- void loadLocalAttachmentPreview(local, controller.signal)
47
- .then((preview) => {
48
- if (!preview) return;
49
- if (controller.signal.aborted) return preview.dispose();
50
- dispose = preview.dispose;
51
- setLocalUri(preview.uri);
52
- setError(null);
53
- })
54
- .catch(() => {
55
- if (!controller.signal.aborted) setError("The local file is unavailable. Attach it again.");
56
- });
57
- return () => {
58
- controller.abort();
59
- dispose?.();
60
- };
61
- }, [local]);
62
- const uri = local ? localUri : (inlineUri ?? (asset._tag === "Success" ? asset.url : null));
45
+ const uri = local
46
+ ? localPreview.uri
47
+ : (inlineUri ?? (asset._tag === "Success" ? asset.url : null));
48
const share = async () => {
49
if (sharing) return;
50
setSharing(true);
apps/mobile/src/components/FilePreviewModal.tsx
+103
-148
@@ -1,15 +1,5 @@
1
import * as Dialog from "./ui/Dialog";
2
-import { useNavigation } from "@react-navigation/native";
3
-import {
4
- useCallback,
5
- useContext,
6
- useEffect,
7
- useEffectEvent,
8
- useState,
9
- useSyncExternalStore,
10
- useMemo,
11
-} from "react";
12
-import { Keyboard } from "react-native";
2
+import { useContext, useEffect, useEffectEvent, useState } from "react";
3
4
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
5
import {
@@ -17,7 +7,8 @@ import {
7
nativeViewerErrorMessage,
8
shareLocalAttachment,
9
} from "../lib/attachmentDownload";
20
-import { useRefreshAssetUrl } from "../state/assets";
10
+import { usePreviewPresentation } from "../lib/previewPresentation";
11
+import { refreshAssetUrl } from "../state/assets";
12
import { filePreviewGallery, filePreviewKey, filePreviewName } from "../lib/filePreviewGallery";
13
import { FilePreviewGallery } from "./FilePreviewGallery";
14
import { FilePreview } from "./FilePreview";
@@ -33,77 +24,47 @@ export type {
24
ResolvedFilePreviewSource,
25
} from "./FilePreviewModal.types";
26
36
-function PreviewItemResolver(props: {
37
- readonly source: FilePreviewItem;
38
- readonly onResolved: (source: ResolvedFilePreviewSource) => void;
39
- readonly onRequestClose: () => void;
40
- readonly onOpenError?: (error: unknown) => void;
41
-}) {
42
- const { source } = props;
43
- const environmentId = "environmentId" in source ? source.environmentId : null;
44
- const refreshAssetUrl = useRefreshAssetUrl(
45
- environmentId,
46
- "resource" in source ? source.resource : null,
47
- );
48
- // Resolve once per presentation; background URL refreshes must not reopen the native viewer.
49
- const [uri, setUri] = useState<string | null>("uri" in source ? source.uri : null);
50
- const onRequestClose = useEffectEvent(props.onRequestClose);
51
- const onResolutionError = useEffectEvent((error: unknown, fallbackMessage: string) => {
52
- if (props.onOpenError) props.onOpenError(error);
53
- else Dialog.alert("Could not open preview", fallbackMessage);
54
- onRequestClose();
55
- });
56
- useEffect(() => Keyboard.dismiss(), []);
57
- useEffect(() => {
58
- if (environmentId === null || uri !== null) return;
59
- let cancelled = false;
60
- // Refresh expired URLs before handing them to Quick Look or ACTION_VIEW, which retain them.
61
- void refreshAssetUrl()
62
- .then((url) => {
63
- if (cancelled) return;
64
- if (!url) throw new Error("Reconnect to this environment and try again.");
65
- setUri(url + (source.srcFragment ?? ""));
66
- })
67
- .catch((error: unknown) => {
68
- if (cancelled) return;
69
- onResolutionError(
70
- error,
71
- "Reconnect to this environment and try again. The file may have been moved or deleted.",
72
- );
73
- });
74
- return () => {
75
- cancelled = true;
76
- };
77
- }, [environmentId, uri, refreshAssetUrl, source.srcFragment]);
78
- useEffect(() => {
79
- if (!("attachment" in source)) return;
80
- const controller = new AbortController();
81
- let release: (() => void) | undefined;
82
- void loadLocalAttachmentPreview(source.attachment, controller.signal)
83
- .then((file) => {
84
- if (!file) return;
85
- if (controller.signal.aborted) {
86
- file.dispose();
87
- return;
88
- }
89
- release = file.dispose;
90
- setUri(file.uri);
91
- })
92
- .catch((error: unknown) => {
93
- if (controller.signal.aborted) return;
94
- onResolutionError(error, "Attach the file again and retry.");
95
- });
96
- return () => {
97
- controller.abort();
98
- release?.();
99
- };
100
- }, [source]);
27
+class PreviewResolutionError extends Error {
28
+ constructor(
29
+ override readonly cause: unknown,
30
+ readonly fallbackMessage: string,
31
+ ) {
32
+ super(fallbackMessage, { cause });
33
+ }
34
+}
35
102
- const onResolved = useEffectEvent(props.onResolved);
103
- useEffect(() => {
104
- if (uri !== null) onResolved({ ...source, name: filePreviewName(source), uri });
105
- }, [uri, source]);
106
- return null;
36
+interface ResolvedPreviewItem {
37
+ readonly source: ResolvedFilePreviewSource;
38
+ readonly dispose?: () => void;
39
+}
40
+
41
+async function resolvePreviewItem(
42
+ item: FilePreviewItem,
43
+ signal: AbortSignal,
44
+): Promise<ResolvedPreviewItem | null> {
45
+ const name = filePreviewName(item);
46
+ if ("attachment" in item) {
47
+ const file = await loadLocalAttachmentPreview(item.attachment, signal).catch(
48
+ (error: unknown) => {
49
+ throw new PreviewResolutionError(error, "Attach the file again and retry.");
50
+ },
51
+ );
52
+ return file && { source: { ...item, name, uri: file.uri }, dispose: file.dispose };
53
+ }
54
+ if (!("environmentId" in item)) return { source: { ...item, name } };
55
+ // Refresh expired URLs before handing them to Quick Look or ACTION_VIEW, which retain them.
56
+ const url = await refreshAssetUrl(item.environmentId, item.resource, signal)
57
+ .then((value) => {
58
+ if (!value) throw new Error("Reconnect to this environment and try again.");
59
+ return value;
60
+ })
61
+ .catch((error: unknown) => {
62
+ throw new PreviewResolutionError(
63
+ error,
64
+ "Reconnect to this environment and try again. The file may have been moved or deleted.",
65
+ );
66
+ });
67
+ return { source: { ...item, name, uri: url + (item.srcFragment ?? "") } };
68
}
69
70
function ResolvedFilePreview(props: {
@@ -113,25 +74,60 @@ function ResolvedFilePreview(props: {
74
}) {
75
// Freeze the group at opening; streaming messages and URL refreshes must not reopen the viewer.
76
const [items] = useState(() => filePreviewGallery(props.source, []));
116
- const [resolved, setResolved] = useState<Record<string, ResolvedFilePreviewSource>>({});
117
- const onResolved = useCallback((item: ResolvedFilePreviewSource, key: string) => {
118
- setResolved((current) => ({ ...current, [key]: item }));
119
- }, []);
120
- const selected = resolved[filePreviewKey(props.source)];
121
- const gallery = useMemo(
122
- () =>
123
- items.flatMap((item) => {
124
- const value = resolved[filePreviewKey(item)];
125
- return value ? [value] : [];
126
- }),
127
- [items, resolved],
77
+ const selectedKey = filePreviewKey(props.source);
78
+ const [gallery, setGallery] = useState<readonly ResolvedFilePreviewSource[] | null>(() =>
79
+ items.every((item) => "uri" in item)
80
+ ? items.map((item) => ({ ...item, name: filePreviewName(item) }))
81
+ : null,
82
);
129
- const ready = selected && gallery.length === items.length;
83
+ const onResolutionError = useEffectEvent((error: PreviewResolutionError) => {
84
+ if (props.onOpenError) props.onOpenError(error.cause);
85
+ else Dialog.alert("Could not open preview", error.fallbackMessage);
86
+ props.onRequestClose();
87
+ });
88
+ // Resolves once per presentation and holds local file leases until it closes.
89
+ useEffect(() => {
90
+ if (items.every((item) => "uri" in item)) return;
91
+ const controller = new AbortController();
92
+ // The first failure closes the preview at once and cancels the rest of the gallery.
93
+ const fail = (error: unknown) => {
94
+ if (controller.signal.aborted) return;
95
+ controller.abort();
96
+ onResolutionError(
97
+ error instanceof PreviewResolutionError
98
+ ? error
99
+ : new PreviewResolutionError(error, "Try again."),
100
+ );
101
+ };
102
+ const resolving = Promise.allSettled(
103
+ items.map((item) =>
104
+ resolvePreviewItem(item, controller.signal).catch((error: unknown) => {
105
+ fail(error);
106
+ throw error;
107
+ }),
108
+ ),
109
+ );
110
+ void resolving.then((settled) => {
111
+ if (controller.signal.aborted) return;
112
+ const sources = settled.flatMap((item) =>
113
+ item.status === "fulfilled" && item.value ? [item.value.source] : [],
114
+ );
115
+ if (sources.length === items.length) setGallery(sources);
116
+ });
117
+ return () => {
118
+ controller.abort();
119
+ void resolving.then((settled) => {
120
+ for (const item of settled) if (item.status === "fulfilled") item.value?.dispose?.();
121
+ });
122
+ };
123
+ }, [items]);
124
+ const selected = gallery?.[items.findIndex((item) => filePreviewKey(item) === selectedKey)];
125
+ if (!gallery || !selected) return null;
126
const onOpenError = (error: unknown) => {
127
if (props.onOpenError) return props.onOpenError(error);
128
Dialog.alert("Could not open preview", nativeViewerErrorMessage(error), [
129
{ text: "Cancel", style: "cancel" },
134
- ...(selected?.kind === "document"
130
+ ...(selected.kind === "document"
131
? [
132
{
133
text: "Save or share",
@@ -154,24 +150,11 @@ function ResolvedFilePreview(props: {
150
]);
151
};
152
return (
157
- <>
158
- {items.map((item) => (
159
- <PreviewItemResolver
160
- key={filePreviewKey(item)}
161
- source={item}
162
- onResolved={(value) => onResolved(value, filePreviewKey(item))}
163
- onRequestClose={props.onRequestClose}
164
- onOpenError={props.onOpenError}
165
- />
166
- ))}
167
- {ready ? (
168
- <FilePreview
169
- source={{ ...selected, gallery }}
170
- onRequestClose={props.onRequestClose}
171
- onOpenError={onOpenError}
172
- />
173
- ) : null}
174
- </>
153
+ <FilePreview
154
+ source={{ ...selected, gallery }}
155
+ onRequestClose={props.onRequestClose}
156
+ onOpenError={onOpenError}
157
+ />
158
);
159
}
160
@@ -182,41 +165,13 @@ export function FilePreviewModal(props: {
165
readonly onOpenError?: (error: unknown) => void;
166
}) {
167
const group = useContext(FilePreviewGallery);
185
- const source = useMemo(
186
- () =>
187
- props.source === null
188
- ? null
189
- : {
190
- ...props.source,
191
- gallery: filePreviewGallery(props.source, group),
192
- },
193
- [props.source, group],
194
- );
195
- const navigation = useNavigation();
196
- const subscribeToFocus = useCallback(
197
- (listener: () => void) => {
198
- const offFocus = navigation.addListener("focus", listener);
199
- const offBlur = navigation.addListener("blur", listener);
200
- return () => {
201
- offFocus();
202
- offBlur();
203
- };
204
- },
205
- [navigation],
206
- );
207
- // The legacy envelope's focus context may describe a different route than this v5 card.
208
- const isFocused = useSyncExternalStore(
209
- subscribeToFocus,
210
- navigation.isFocused,
211
- navigation.isFocused,
212
- );
213
- const hasSource = props.source !== null;
214
- const onRequestClose = useEffectEvent(props.onRequestClose);
215
- useEffect(() => {
216
- if (!isFocused && hasSource) onRequestClose();
217
- }, [isFocused, hasSource]);
168
+ const source =
169
+ props.source === null
170
+ ? null
171
+ : { ...props.source, gallery: filePreviewGallery(props.source, group) };
172
+ usePreviewPresentation(source && filePreviewKey(source), props.onRequestClose);
173
219
- if (!source || !isFocused) return null;
174
+ if (!source) return null;
175
return (
176
<ResolvedFilePreview
177
key={filePreviewKey(source)}
apps/mobile/src/components/PdfPreview.android.tsx
+48
-41
@@ -1,4 +1,8 @@
1
-import { useEffect, useRef, useState } from "react";
1
+import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2
+import * as Effect from "effect/Effect";
3
+import * as Option from "effect/Option";
4
+import { Atom, AsyncResult } from "effect/reactivity";
5
+import { useState } from "react";
6
import { View } from "react-native";
7
import Pdf from "react-native-pdf-jsi";
8
@@ -7,39 +11,55 @@ import { pdfInitialPage, pdfLinkUrl, preparePdfPreview } from "../lib/pdfPreview
11
import { tryOpenExternalUrl } from "../lib/openExternalUrl";
12
import { ControlPill } from "./ui/ControlPill";
13
10
-function NativePdfPreview(props: { readonly uri: string; readonly onRetry: () => void }) {
11
- const [localUri, setLocalUri] = useState<string | null>(null);
12
- const [error, setError] = useState<string | null>(null);
13
- const cached = useRef<Awaited<ReturnType<typeof preparePdfPreview>>>(null);
14
+const preparedPdfAtom = Atom.family((uri: string) =>
15
+ Atom.make(
16
+ // The downloaded copy lives as long as a viewer reads it; Retry refreshes the atom,
17
+ // which closes the scope and discards the copy before downloading again. Acquisition
18
+ // stays interruptible so closing the viewer aborts the download.
19
+ Effect.acquireRelease(
20
+ Effect.tryPromise({
21
+ try: (signal) => {
22
+ const prepared = preparePdfPreview(uri, signal);
23
+ // An interrupt can land after the copy exists but before acquireRelease owns it.
24
+ signal.addEventListener("abort", () => {
25
+ void prepared.then(
26
+ (file) => file?.dispose(),
27
+ () => undefined,
28
+ );
29
+ });
30
+ return prepared;
31
+ },
32
+ catch: (cause) => (cause instanceof Error ? cause.message : "The PDF could not be loaded."),
33
+ }).pipe(
34
+ Effect.flatMap((file) => (file === null ? Effect.interrupt : Effect.succeed(file))),
35
+ Effect.interruptible,
36
+ ),
37
+ (file) => Effect.sync(file.dispose),
38
+ ),
39
+ ).pipe(Atom.withLabel(`android-pdf-preview:${uri}`)),
40
+);
41
15
- useEffect(() => {
16
- const controller = new AbortController();
17
- void preparePdfPreview(props.uri, controller.signal)
18
- .then((file) => {
19
- if (controller.signal.aborted) file?.dispose();
20
- else {
21
- cached.current = file;
22
- setLocalUri(file?.uri ?? null);
23
- }
24
- })
25
- .catch((cause: unknown) => {
26
- if (!controller.signal.aborted) {
27
- setError(cause instanceof Error ? cause.message : "The PDF could not be loaded.");
28
- }
29
- });
30
- return () => {
31
- controller.abort();
32
- cached.current?.dispose();
33
- cached.current = null;
34
- };
35
- }, [props.uri]);
42
+export function PdfPreview(props: { readonly uri: string }) {
43
+ const atom = preparedPdfAtom(props.uri);
44
+ const prepared = useAtomValue(atom);
45
+ const refresh = useAtomRefresh(atom);
46
+ // A render failure belongs to the downloaded copy that failed; Retry replaces it.
47
+ const [unrenderable, setUnrenderable] = useState<unknown>(null);
48
+ const file = prepared._tag === "Success" && !prepared.waiting ? prepared.value : null;
49
+ const error =
50
+ file !== null && unrenderable === file
51
+ ? "The PDF could not be rendered. It may be damaged or password protected."
52
+ : prepared._tag === "Failure" && !prepared.waiting
53
+ ? Option.getOrElse(AsyncResult.error(prepared), () => "The PDF could not be loaded.")
54
+ : null;
55
+ const localUri = file?.uri ?? null;
56
57
if (error) {
58
return (
59
<View className="flex-1 gap-4 bg-card">
60
<FilePreviewNotice title="Could not load PDF">{error}</FilePreviewNotice>
61
<View className="items-center">
42
- <ControlPill label="Try again" variant="pill" onPress={props.onRetry} />
62
+ <ControlPill label="Try again" variant="pill" onPress={refresh} />
63
</View>
64
</View>
65
);
@@ -59,22 +79,9 @@ function NativePdfPreview(props: { readonly uri: string; readonly onRetry: () =>
79
if (url !== null) void tryOpenExternalUrl(url, "file-preview");
80
}}
81
onError={() => {
62
- cached.current?.dispose();
63
- cached.current = null;
64
- setError("The PDF could not be rendered. It may be damaged or password protected.");
82
+ setUnrenderable(file);
83
}}
84
style={{ flex: 1, width: "100%" }}
85
/>
86
);
87
}
70
-
71
-export function PdfPreview(props: { readonly uri: string }) {
72
- const [attempt, setAttempt] = useState(0);
73
- return (
74
- <NativePdfPreview
75
- key={`${props.uri}:${attempt}`}
76
- uri={props.uri}
77
- onRetry={() => setAttempt((value) => value + 1)}
78
- />
79
- );
80
-}
apps/mobile/src/components/VideoPreviewModal.ios.tsx
+33
-53
@@ -1,15 +1,14 @@
1
import * as Dialog from "./ui/Dialog";
2
-import { useIsFocused } from "@react-navigation/native";
2
import { requireNativeModule } from "expo";
3
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4
import { AsyncResult } from "effect/reactivity";
6
-import { useEffect, useEffectEvent, useId, useState } from "react";
7
-import { Keyboard } from "react-native";
5
+import { useEffect, useEffectEvent, useId } from "react";
6
7
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
8
+import { usePreviewPresentation, videoPreviewKey } from "../lib/previewPresentation";
9
import { fullscreenVideoClosed, fullscreenVideoOpened } from "../lib/videoAudioSession";
10
import { mediaVideoPreviewUri, type VideoPreviewSource } from "../lib/videoPreviewSource";
12
-import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets";
11
+import { refreshAssetUrl } from "../state/assets";
12
import { usePreparedConnection } from "../state/session";
13
import {
14
acquireAudioSession,
@@ -44,43 +43,29 @@ function NativeVideoPreview(props: {
43
const onRequestClose = useEffectEvent(props.onRequestClose);
44
const environmentId =
45
source.type === "media" && "environmentId" in source ? source.environmentId : null;
47
- const resource = source.type === "media" && "resource" in source ? source.resource : null;
46
const preparedConnection = usePreparedConnection(environmentId);
49
- const assetUrl = useAssetUrlState(environmentId, resource);
50
- const refreshAssetUrl = useEffectEvent(useRefreshAssetUrl(environmentId, resource));
47
const name = source.type === "media" ? source.name : source.attachment.name;
52
- // The first minted URL is kept so a background refresh does not restart playback.
53
- const resolvedUrl =
54
- source.type === "media"
55
- ? mediaVideoPreviewUri(source, assetUrl._tag === "Success" ? assetUrl.url : null)
56
- : null;
57
- const [playbackUrl, setPlaybackUrl] = useState<string | null>(resolvedUrl);
58
- const loadError =
59
- resource !== null && playbackUrl === null
60
- ? preparedConnection._tag === "None"
48
+ // Mints a fresh URL for each presentation: AVKit retains the URL and offers no retry,
49
+ // so a cached link that expired while the app was suspended would fail to play.
50
+ const resolvePlaybackUrl = useEffectEvent(async (): Promise<string> => {
51
+ if (source.type !== "media") throw new Error("Could not load this video.");
52
+ if (!("resource" in source)) return source.uri;
53
+ const url = await refreshAssetUrl(source.environmentId, source.resource);
54
+ const playbackUrl = mediaVideoPreviewUri(source, url);
55
+ if (playbackUrl !== null) return playbackUrl;
56
+ throw new Error(
57
+ preparedConnection._tag === "None"
58
? "Reconnect to this environment and open the video again."
62
- : assetUrl._tag === "Failure"
63
- ? "Could not load this video. Check the connection and try again."
64
- : null
65
- : null;
59
+ : "Could not load this video. Check the connection and try again.",
60
+ );
61
+ });
62
+ const reauthorize = useEffectEvent(() => {
63
+ if (source.type === "media" && "resource" in source) {
64
+ void refreshAssetUrl(source.environmentId, source.resource);
65
+ }
66
+ });
67
67
- useEffect(() => Keyboard.dismiss(), []);
68
useEffect(() => {
69
- fullscreenVideoOpened();
70
- return () => fullscreenVideoClosed();
71
- }, []);
72
- useEffect(() => {
73
- // oxlint-disable-next-line react/set-state-in-effect -- The native player latches the first resolved URL to keep its playback session.
74
- if (playbackUrl === null && resolvedUrl !== null) setPlaybackUrl(resolvedUrl);
75
- }, [playbackUrl, resolvedUrl]);
76
- useEffect(() => {
77
- if (!loadError) return;
78
- Dialog.alert("Could not open video", loadError);
79
- onRequestClose();
80
- }, [loadError]);
81
-
82
- useEffect(() => {
83
- if (localAttachment === null && playbackUrl === null) return;
69
const controller = new AbortController();
70
let token: ReturnType<typeof acquireAudioSession> | null = null;
71
const release = () => {
@@ -106,12 +91,14 @@ function NativeVideoPreview(props: {
91
} else release();
92
});
93
let ready = false;
94
+ fullscreenVideoOpened();
95
void (async () => {
96
const file =
97
localAttachment !== null
98
? await loadLocalAttachmentPreview(localAttachment, controller.signal)
99
: null;
100
if (localAttachment !== null && !file) return;
101
+ const uri = file?.uri ?? (await resolvePlaybackUrl());
102
if (controller.signal.aborted) {
103
file?.dispose();
104
return;
@@ -125,12 +112,7 @@ function NativeVideoPreview(props: {
112
}
113
ready = true;
114
const presented = await settlePromise(() =>
128
- NativeControls.presentVideo(
129
- file?.uri ?? playbackUrl!,
130
- name,
131
- source.sourceIdentifier ?? "",
132
- identifier,
133
- ),
115
+ NativeControls.presentVideo(uri, name, source.sourceIdentifier ?? "", identifier),
116
);
117
// Native completion follows dismissal, so local playback keeps its file lease.
118
file?.dispose();
@@ -140,8 +122,8 @@ function NativeVideoPreview(props: {
122
})().catch((error: unknown) => {
123
release();
124
if (controller.signal.aborted) return;
143
- // AVKit gives no retry, so re-mint now; the cached URL may simply have expired.
144
- if (ready) void refreshAssetUrl();
125
+ // AVKit gives no retry, so re-mint now; the minted URL may already be unusable.
126
+ if (ready) reauthorize();
127
Dialog.alert(
128
"Could not open video",
129
ready
@@ -154,11 +136,12 @@ function NativeVideoPreview(props: {
136
});
137
return () => {
138
controller.abort();
139
+ fullscreenVideoClosed();
140
subscription.remove();
141
release();
142
void NativeControls.dismissVideo(identifier).catch(() => undefined);
143
};
161
- }, [localAttachment, name, source.sourceIdentifier, playbackUrl, identifier]);
144
+ }, [localAttachment, name, source.sourceIdentifier, identifier]);
145
146
return null;
147
}
@@ -167,13 +150,10 @@ export function VideoPreviewModal(props: {
150
readonly source: VideoPreviewSource | null;
151
readonly onRequestClose: () => void;
152
}) {
170
- const isFocused = useIsFocused();
171
- const hasSource = props.source !== null;
172
- const onRequestClose = useEffectEvent(props.onRequestClose);
173
- useEffect(() => {
174
- if (!isFocused && hasSource) onRequestClose();
175
- }, [isFocused, hasSource]);
176
-
177
- if (!props.source || !isFocused) return null;
153
+ usePreviewPresentation(
154
+ props.source === null ? null : videoPreviewKey(props.source),
155
+ props.onRequestClose,
156
+ );
157
+ if (!props.source) return null;
158
return <NativeVideoPreview source={props.source} onRequestClose={props.onRequestClose} />;
159
}
apps/mobile/src/components/VideoPreviewModal.tsx
+13
-48
@@ -1,11 +1,10 @@
1
-import { useIsFocused } from "@react-navigation/native";
1
import { videoMimeType } from "@t3tools/shared/video";
3
-import { useEffect, useEffectEvent, useState } from "react";
4
-import { Keyboard, Modal, Pressable, View } from "react-native";
2
+import { Modal, Pressable, View } from "react-native";
3
import { useSafeAreaInsets } from "react-native-safe-area-context";
4
5
import { AppActivityIndicator } from "./ui/AppActivityIndicator";
8
-import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
6
+import { useLocalAttachmentPreview } from "../lib/localAttachmentPreview";
7
+import { usePreviewPresentation, videoPreviewKey } from "../lib/previewPresentation";
8
import { useMediaActions } from "../state/mediaActions";
9
import { type MediaActionsSource } from "../lib/mediaActionsSource";
10
import {
@@ -56,40 +55,9 @@ function useMediaPlayback(source: MediaVideoPreviewSource): PlaybackState {
55
56
function useLocalPlayback(source: LocalVideoPreviewSource): PlaybackState {
57
const { attachment } = source;
59
- const [uri, setUri] = useState<string | null>(null);
60
- const [error, setError] = useState<string | null>(null);
61
- // Keep the file lease across metadata updates while Android is playing it.
62
- const loadAttachment = useEffectEvent((signal: AbortSignal) =>
63
- loadLocalAttachmentPreview(attachment, signal),
64
- );
65
- const { id: attachmentId, fileUri } = attachment;
66
- useEffect(() => {
67
- // oxlint-disable-next-line react/set-state-in-effect -- A new attachment clears the previous attachment's result before loading.
68
- setUri(null);
69
- setError(null);
70
- const controller = new AbortController();
71
- const loading = loadAttachment(controller.signal);
72
- void loading.then(
73
- (file) => {
74
- if (file === null) return;
75
- if (controller.signal.aborted) file.dispose();
76
- else setUri(file.uri);
77
- },
78
- (cause: unknown) => {
79
- if (!controller.signal.aborted) {
80
- setError(cause instanceof Error ? cause.message : "Could not load this video.");
81
- }
82
- },
83
- );
84
- return () => {
85
- controller.abort();
86
- void loading.then(
87
- (file) => file?.dispose(),
88
- () => undefined,
89
- );
90
- };
91
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A different attachment restarts the load even when it resolves to the same cached file URI.
92
- }, [attachmentId, fileUri]);
58
+ const preview = useLocalAttachmentPreview(attachment);
59
+ const { uri } = preview;
60
+ const error = preview.error ? preview.error.message || "Could not load this video." : null;
61
const mimeType = videoMimeType(attachment) ?? attachment.mimeType;
62
return {
63
uri,
@@ -137,7 +105,6 @@ function OpenVideoPreviewModal(props: {
105
const insets = useSafeAreaInsets();
106
const mediaActions = useMediaActions(playback.actionsSource, props.onRequestClose);
107
140
- useEffect(() => Keyboard.dismiss(), []);
108
return (
109
<Modal
110
visible
@@ -208,23 +175,21 @@ export function VideoPreviewModal(props: {
175
readonly source: VideoPreviewSource | null;
176
readonly onRequestClose: () => void;
177
}) {
211
- const isFocused = useIsFocused();
212
- const hasSource = props.source !== null;
213
- const { onRequestClose } = props;
214
- useEffect(() => {
215
- if (!isFocused && hasSource) onRequestClose();
216
- }, [isFocused, hasSource, onRequestClose]);
178
+ usePreviewPresentation(
179
+ props.source === null ? null : videoPreviewKey(props.source),
180
+ props.onRequestClose,
181
+ );
182
const { source } = props;
218
- if (source === null || !isFocused) return null;
183
+ if (source === null) return null;
184
return source.type === "local" ? (
185
<LocalPreviewModal
221
- key={`local:${source.attachment.id}:${source.attachment.fileUri}`}
186
+ key={videoPreviewKey(source)}
187
source={source}
188
onRequestClose={props.onRequestClose}
189
/>
190
) : (
191
<MediaPreviewModal
227
- key={mediaVideoThumbnailKey(source)}
192
+ key={videoPreviewKey(source)}
193
source={source}
194
onRequestClose={props.onRequestClose}
195
/>
apps/mobile/src/components/VideoThumbnailImage.tsx
+34
-19
@@ -1,38 +1,53 @@
1
+import { useAtomValue } from "@effect/atom-react";
2
+import * as Effect from "effect/Effect";
3
+import { Atom, AsyncResult } from "effect/reactivity";
4
import { Image } from "expo-image";
5
import { useIsFocused } from "@react-navigation/native";
6
import type { VideoThumbnail } from "expo-video";
4
-import { useEffect, useState } from "react";
7
import { StyleSheet } from "react-native";
8
9
import type { DraftComposerFileAttachment } from "../lib/composerImages";
10
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
11
import { cachedVideoThumbnail, loadVideoThumbnail } from "../lib/videoThumbnails";
12
13
+interface VideoThumbnailTarget {
14
+ readonly cacheKey: string;
15
+ readonly source: string | DraftComposerFileAttachment;
16
+}
17
+
18
+// Plain-object keys compare structurally (Effect `Equal`/`Hash`).
19
+const videoThumbnailAtom = Atom.family((target: VideoThumbnailTarget) =>
20
+ Atom.make(
21
+ Effect.promise((signal) =>
22
+ loadVideoThumbnail(
23
+ target.cacheKey,
24
+ async (sourceSignal) =>
25
+ typeof target.source === "string"
26
+ ? { uri: target.source, dispose: () => undefined }
27
+ : loadLocalAttachmentPreview(target.source, sourceSignal),
28
+ signal,
29
+ ),
30
+ ),
31
+ ).pipe(Atom.withLabel(`video-thumbnail:${target.cacheKey}`)),
32
+);
33
+
34
+const noVideoThumbnail = Atom.make(AsyncResult.initial<VideoThumbnail | null>()).pipe(
35
+ Atom.withLabel("video-thumbnail:none"),
36
+);
37
+
38
export function VideoThumbnailImage(props: {
39
readonly cacheKey: string;
40
readonly source: string | DraftComposerFileAttachment | null;
41
readonly contentFit?: "cover" | "contain";
42
}) {
43
const { cacheKey, source } = props;
44
+ // Extraction runs only while the screen is focused; leaving it interrupts the load.
45
const isFocused = useIsFocused();
18
- const [loaded, setLoaded] = useState<{ key: string; thumbnail: VideoThumbnail } | null>(null);
19
- const thumbnail = loaded?.key === cacheKey ? loaded.thumbnail : cachedVideoThumbnail(cacheKey);
20
-
21
- useEffect(() => {
22
- if (!source || !isFocused) return;
23
- const controller = new AbortController();
24
- void loadVideoThumbnail(
25
- cacheKey,
26
- async (signal) =>
27
- typeof source === "string"
28
- ? { uri: source, dispose: () => undefined }
29
- : loadLocalAttachmentPreview(source, signal),
30
- controller.signal,
31
- ).then((thumbnail) => {
32
- if (thumbnail && !controller.signal.aborted) setLoaded({ key: cacheKey, thumbnail });
33
- });
34
- return () => controller.abort();
35
- }, [cacheKey, source, isFocused]);
46
+ const loaded = useAtomValue(
47
+ source && isFocused ? videoThumbnailAtom({ cacheKey, source }) : noVideoThumbnail,
48
+ );
49
+ const thumbnail =
50
+ (loaded._tag === "Success" ? loaded.value : null) ?? cachedVideoThumbnail(cacheKey);
51
52
return thumbnail ? (
53
<Image
apps/mobile/src/features/files/AttachmentFileScreen.tsx
+4
-5
@@ -5,7 +5,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native"
5
import type { MenuAction } from "@react-native-menu/menu";
6
import { EnvironmentId } from "@t3tools/contracts";
7
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
8
-import { useEffect, useRef, useState } from "react";
8
+import { useRef, useState } from "react";
9
import { Platform, View } from "react-native";
10
11
import {
@@ -165,12 +165,11 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
165
if (navigation.canGoBack()) navigation.goBack();
166
};
167
const { uri, resource } = document;
168
- useEffect(() => {
169
- if (nativeViewer !== "pending" || !uri) return;
170
- // oxlint-disable-next-line react/set-state-in-effect -- Presenting the viewer waits on the resolved file.
168
+ // A file only the native viewer can show opens it as soon as the file resolves.
169
+ if (nativeViewer === "pending" && uri) {
170
setNativeViewer("open");
171
setNativeOpen(true);
173
- }, [nativeViewer, uri]);
172
+ }
173
// Mint a fresh URL: cached URLs may expire in the background before Quick Look or ACTION_VIEW opens.
174
const nativeSource = ((): FilePreviewSource | null => {
175
const kind = nativeKind ?? "document";
apps/mobile/src/lib/attachmentDocument.ts
+93
-110
@@ -1,18 +1,21 @@
1
-import { AsyncResult } from "effect/reactivity";
1
+import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2
+import { Atom, AsyncResult } from "effect/reactivity";
3
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4
import * as Dialog from "../components/ui/Dialog";
5
import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
5
-import type { EnvironmentId } from "@t3tools/contracts";
6
+import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
7
import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
8
import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
9
import { fetch } from "expo/fetch";
10
import { File } from "expo-file-system";
11
+import * as Effect from "effect/Effect";
12
+import * as Option from "effect/Option";
13
import { useEffect, useRef, useState } from "react";
14
15
import type { FileBackedComposerAttachment } from "./composerImages";
13
-import { loadLocalAttachmentPreview } from "./localAttachmentPreview";
16
+import { localAttachmentPreviewAtom, localAttachmentPreviewState } from "./localAttachmentPreview";
17
import { downloadAndShareAttachment, shareLocalAttachment } from "./attachmentDownload";
15
-import { useRefreshAssetUrl } from "../state/assets";
18
+import { refreshAssetUrl, useFreshAssetUrl, useRefreshAssetUrl } from "../state/assets";
19
import { attachmentDocumentPresentation } from "./attachmentDocumentPresentation";
20
21
const isLocalUri = (uri: string) => /^(file|content):/.test(uri);
@@ -20,6 +23,55 @@ const isLocalUri = (uri: string) => /^(file|content):/.test(uri);
23
/** Signed asset URLs live for an hour; treat anything older than this as worth re-minting. */
24
const STALE_URL_MS = 5 * 60_000;
25
26
+interface AttachmentTextKey {
27
+ readonly uri: string;
28
+ /** When a remote `uri` was signed; null for local files. */
29
+ readonly authorizedAt: number | null;
30
+ readonly environmentId: EnvironmentId | null;
31
+ readonly resource: AssetResource;
32
+ readonly sizeBytes: number;
33
+ readonly revision: number;
34
+}
35
+
36
+async function readAttachmentText(key: AttachmentTextKey, signal: AbortSignal) {
37
+ if (isLocalUri(key.uri)) {
38
+ return readFilePreviewResponse({ ok: true, body: new File(key.uri).readableStream() }, signal);
39
+ }
40
+ // Reauthorize before source reads; the opening URL may have expired.
41
+ let target = key.uri;
42
+ if (key.authorizedAt === null || Date.now() - key.authorizedAt > STALE_URL_MS) {
43
+ const refreshed =
44
+ key.environmentId === null
45
+ ? null
46
+ : await refreshAssetUrl(key.environmentId, key.resource, signal);
47
+ if (!refreshed) throw new Error("Reconnect to this environment and try again.");
48
+ target = refreshed;
49
+ }
50
+ const response = await fetch(target, {
51
+ signal,
52
+ headers: {
53
+ ...(key.sizeBytes > 0 ? { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } : {}),
54
+ ...(key.revision > 0 ? { "Cache-Control": "no-cache" } : {}),
55
+ },
56
+ });
57
+ return readFilePreviewResponse(response, signal);
58
+}
59
+
60
+// Plain-object keys compare structurally (Effect `Equal`/`Hash`). Unmounting the
61
+// last reader interrupts the read, which aborts the fetch.
62
+const attachmentTextAtom = Atom.family((key: AttachmentTextKey) =>
63
+ Atom.make(
64
+ Effect.tryPromise({
65
+ try: (signal) => readAttachmentText(key, signal),
66
+ catch: (cause) => (cause instanceof Error ? cause : new Error("Could not read this file.")),
67
+ }),
68
+ ).pipe(Atom.withLabel("attachment-text")),
69
+);
70
+
71
+const noAttachmentText = Atom.make(
72
+ AsyncResult.initial<{ text: string; truncated: boolean }, Error>(),
73
+).pipe(Atom.withLabel("attachment-text:none"));
74
+
75
/** Captured bytes never resolve against the workspace. */
76
export function useAttachmentDocument(input: {
77
readonly name: string;
@@ -42,117 +94,45 @@ export function useAttachmentDocument(input: {
94
};
95
const environmentId = input.attachment ? null : input.environmentId;
96
const refresh = useRefreshAssetUrl(environmentId, resource);
45
- const [localUri, setLocalUri] = useState<string | null>(null);
46
- const [remoteUri, setRemoteUri] = useState<string | null>(null);
47
- const [content, setContent] = useState<{ text: string; truncated: boolean } | null>(null);
48
- const table = content && delimiter ? parseDelimitedPreview(content.text, delimiter) : null;
49
- const [error, setError] = useState<string | null>(null);
50
- const [contentError, setContentError] = useState<string | null>(null);
51
- const textReadUrl = useRef<{ uri: string; authorizedAt: number } | null>(null);
97
const [rendered, setRendered] = useState(true);
98
+ const [revision, setRevision] = useState(0);
99
+ const [sharing, setSharing] = useState(false);
100
+ const attachment = input.attachment;
101
+ const localPreviewAtom = localAttachmentPreviewAtom(attachment);
102
+ const localPreview = localAttachmentPreviewState(useAtomValue(localPreviewAtom));
103
+ const refreshLocalPreview = useAtomRefresh(localPreviewAtom);
104
+ const remote = useFreshAssetUrl(environmentId, attachment ? null : resource, revision);
105
+ const remoteUrl = AsyncResult.isSuccess(remote) && !remote.waiting ? remote.value : null;
106
+ const uri = attachment ? localPreview.uri : (remoteUrl?.url ?? null);
107
+ const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
108
+ const text = useAtomValue(
109
+ uri && needsText
110
+ ? attachmentTextAtom({
111
+ uri,
112
+ authorizedAt: remoteUrl?.authorizedAt ?? null,
113
+ environmentId,
114
+ resource,
115
+ sizeBytes: input.sizeBytes,
116
+ revision,
117
+ })
118
+ : noAttachmentText,
119
+ );
120
+ const content = AsyncResult.isSuccess(text) ? text.value : null;
121
+ const contentError = AsyncResult.isFailure(text)
122
+ ? (Option.getOrNull(AsyncResult.error(text))?.message ?? "Could not read this file.")
123
+ : null;
124
+ const table = content && delimiter ? parseDelimitedPreview(content.text, delimiter) : null;
125
const presentation = attachmentDocumentPresentation({
126
kind,
127
hasTable: table !== null,
128
hasEnvironment: input.environmentId !== null,
129
rendered,
130
});
59
- const [revision, setRevision] = useState(0);
60
- const [sharing, setSharing] = useState(false);
61
- const uri = input.attachment ? localUri : remoteUri;
62
- const attachment = input.attachment;
63
- useEffect(() => {
64
- if (attachment) return;
65
- let cancelled = false;
66
- // Await a fresh signed URL: cached links can expire while the client is suspended.
67
- // oxlint-disable-next-line react/set-state-in-effect -- A new preview request clears its previous URL and error.
68
- setRemoteUri(null);
69
- setError(null);
70
- textReadUrl.current = null;
71
- void refresh()
72
- .then((url) => {
73
- if (cancelled) return;
74
- if (!url) throw new Error("Reconnect to this environment and try again.");
75
- textReadUrl.current = { uri: url, authorizedAt: Date.now() };
76
- setRemoteUri(url);
77
- })
78
- .catch((cause: unknown) => {
79
- if (!cancelled)
80
- setError(cause instanceof Error ? cause.message : "The attachment is unavailable.");
81
- });
82
- return () => {
83
- cancelled = true;
84
- };
85
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reauthorize the remote file.
86
- }, [attachment, refresh, revision]);
87
- useEffect(() => {
88
- if (!attachment) return;
89
- // Clear old attachment bytes or a failed load could share them under the new name.
90
- // oxlint-disable-next-line react/set-state-in-effect -- A new attachment invalidates the last one.
91
- setLocalUri(null);
92
- setContent(null);
93
- setContentError(null);
94
- const controller = new AbortController();
95
- let release: (() => void) | undefined;
96
- void loadLocalAttachmentPreview(attachment, controller.signal)
97
- .then((file) => {
98
- if (!file) return;
99
- if (controller.signal.aborted) return file.dispose();
100
- release = file.dispose;
101
- setLocalUri(file.uri);
102
- setError(null);
103
- })
104
- .catch((cause: unknown) => {
105
- if (!controller.signal.aborted)
106
- setError(cause instanceof Error ? cause.message : "The local file is unavailable.");
107
- });
108
- return () => {
109
- controller.abort();
110
- release?.();
111
- };
112
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reacquire a local file lease after a failed load.
113
- }, [attachment, revision]);
114
- const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
115
- const sizeBytes = input.sizeBytes;
116
- useEffect(() => {
117
- if (!uri || !needsText) return;
118
- const controller = new AbortController();
119
- // oxlint-disable-next-line react/set-state-in-effect -- A new external resource must clear the previous response before loading.
120
- setContent(null);
121
- setContentError(null);
122
- const response = isLocalUri(uri)
123
- ? Promise.resolve().then(() => ({ ok: true, body: new File(uri).readableStream() }))
124
- : (async () => {
125
- // Reauthorize before source reads; the opening URL may have expired.
126
- const authorized = textReadUrl.current;
127
- let target = authorized?.uri ?? uri;
128
- if (!authorized || Date.now() - authorized.authorizedAt > STALE_URL_MS) {
129
- const refreshed = await refresh();
130
- if (!refreshed) throw new Error("Reconnect to this environment and try again.");
131
- target = refreshed;
132
- if (!controller.signal.aborted) {
133
- // Keep the source-read URL and its age together without restarting active media.
134
- textReadUrl.current = { uri: refreshed, authorizedAt: Date.now() };
135
- }
136
- }
137
- return fetch(target, {
138
- signal: controller.signal,
139
- headers: {
140
- ...(sizeBytes > 0 ? { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } : {}),
141
- ...(revision > 0 ? { "Cache-Control": "no-cache" } : {}),
142
- },
143
- });
144
- })();
145
- void response
146
- .then((value) => readFilePreviewResponse(value, controller.signal))
147
- .then((value) => {
148
- if (!controller.signal.aborted) setContent(value);
149
- })
150
- .catch((cause: unknown) => {
151
- if (!controller.signal.aborted)
152
- setContentError(cause instanceof Error ? cause.message : "Could not read this file.");
153
- });
154
- return () => controller.abort();
155
- }, [uri, needsText, revision, sizeBytes, refresh]);
131
+ const error = attachment
132
+ ? localPreview.error && (localPreview.error.message || "The local file is unavailable.")
133
+ : AsyncResult.isFailure(remote)
134
+ ? (Option.getOrNull(AsyncResult.error(remote))?.message ?? "The attachment is unavailable.")
135
+ : null;
136
const share = async () => {
137
if (!uri || sharing) return;
138
setSharing(true);
@@ -185,12 +165,15 @@ export function useAttachmentDocument(input: {
165
resource,
166
content,
167
table,
188
- error: error ?? (needsText ? contentError : null),
168
+ error: error ?? contentError,
169
needsText,
170
rendered,
171
setRendered,
172
revision,
193
- retry: () => setRevision((value) => value + 1),
173
+ retry: () => {
174
+ setRevision((value) => value + 1);
175
+ if (attachment) refreshLocalPreview();
176
+ },
177
share,
178
sharing,
179
};
apps/mobile/src/lib/localAttachmentPreview.test.ts
+56
-1
@@ -24,7 +24,14 @@ vi.mock("expo-file-system", () => ({
24
},
25
}));
26
27
-import { loadLocalAttachmentPreview } from "./localAttachmentPreview";
27
+import { AtomRegistry, type AsyncResult } from "effect/reactivity";
28
+
29
+import {
30
+ loadLocalAttachmentPreview,
31
+ localAttachmentPreviewAtom,
32
+ type LocalAttachmentPreviewState,
33
+ localAttachmentPreviewState,
34
+} from "./localAttachmentPreview";
35
36
const attachment = {
37
type: "file" as const,
@@ -93,3 +100,51 @@ describe("loadLocalAttachmentPreview", () => {
100
},
101
);
102
});
103
+
104
+describe("localAttachmentPreviewAtom", () => {
105
+ const settled = (
106
+ registry: AtomRegistry.AtomRegistry,
107
+ target: typeof attachment,
108
+ ): { state: Promise<LocalAttachmentPreviewState>; unsubscribe: () => void } => {
109
+ const atom = localAttachmentPreviewAtom(target);
110
+ const { promise, resolve } = Promise.withResolvers<LocalAttachmentPreviewState>();
111
+ const onChange = (result: AsyncResult.AsyncResult<unknown, unknown>) => {
112
+ if (result._tag !== "Initial") resolve(localAttachmentPreviewState(registry.get(atom)));
113
+ };
114
+ const unsubscribe = registry.subscribe(atom, onChange, { immediate: true });
115
+ return { state: promise, unsubscribe };
116
+ };
117
+
118
+ it("shares one lease per file and releases it when the last reader leaves", async () => {
119
+ const released = Promise.withResolvers<void>();
120
+ const release = vi.fn(() => released.resolve());
121
+ mocks.retain.mockReturnValueOnce(release);
122
+ const registry = AtomRegistry.make();
123
+ const first = settled(registry, attachment);
124
+ // A metadata update on the same draft file reads the same lease.
125
+ const renamed = settled(registry, { ...attachment, name: "renamed.mov" });
126
+ expect((await first.state).uri).toContain("/Documents/");
127
+ expect((await renamed.state).uri).toBe((await first.state).uri);
128
+ expect(mocks.retain).toHaveBeenCalledTimes(1);
129
+ first.unsubscribe();
130
+ expect(release).not.toHaveBeenCalled();
131
+ renamed.unsubscribe();
132
+ // The scope finalizer runs on the Effect scheduler; await the release itself.
133
+ await released.promise;
134
+ expect(release).toHaveBeenCalledTimes(1);
135
+ registry.dispose();
136
+ });
137
+
138
+ it("reports a missing file as an error", async () => {
139
+ mocks.exists.mockReturnValue(false);
140
+ const registry = AtomRegistry.make();
141
+ const reader = settled(registry, { ...attachment, id: "missing" });
142
+ const state = await reader.state;
143
+ expect(state.uri).toBeNull();
144
+ expect(state.error?.message).toBe(
145
+ "This attachment is no longer available. Attach the file again.",
146
+ );
147
+ reader.unsubscribe();
148
+ registry.dispose();
149
+ });
150
+});
apps/mobile/src/lib/localAttachmentPreview.ts
+72
@@ -1,4 +1,10 @@
1
+import { useAtomValue } from "@effect/atom-react";
2
import { videoMimeType } from "@t3tools/shared/video";
3
+import * as Effect from "effect/Effect";
4
+import * as Equal from "effect/Equal";
5
+import * as Hash from "effect/Hash";
6
+import * as Option from "effect/Option";
7
+import { Atom, AsyncResult } from "effect/reactivity";
8
9
import type { FileBackedComposerAttachment } from "./composerImages";
10
import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
@@ -59,3 +65,69 @@ export async function loadLocalAttachmentPreview(
65
throw new Error("This attachment is no longer available. Attach the file again.", { cause });
66
}
67
}
68
+
69
+/**
70
+ * Keyed by file identity only: a metadata update on the same draft must not
71
+ * dispose the lease of a file a viewer is still showing.
72
+ */
73
+class LocalAttachmentPreviewKey implements Equal.Equal {
74
+ constructor(readonly attachment: FileBackedComposerAttachment) {}
75
+ [Equal.symbol](that: unknown): boolean {
76
+ return (
77
+ that instanceof LocalAttachmentPreviewKey &&
78
+ that.attachment.id === this.attachment.id &&
79
+ that.attachment.fileUri === this.attachment.fileUri
80
+ );
81
+ }
82
+ [Hash.symbol](): number {
83
+ return Hash.string(`${this.attachment.id}\u0000${this.attachment.fileUri}`);
84
+ }
85
+}
86
+
87
+const localAttachmentPreviewFamily = Atom.family((key: LocalAttachmentPreviewKey) =>
88
+ Atom.make(
89
+ // The lease lives as long as the atom: unmounting the last reader (or a
90
+ // refresh) closes the scope and releases the file.
91
+ Effect.acquireRelease(
92
+ Effect.tryPromise({
93
+ try: (signal) => loadLocalAttachmentPreview(key.attachment, signal),
94
+ catch: (cause) =>
95
+ cause instanceof Error ? cause : new Error("The local file is unavailable."),
96
+ }).pipe(Effect.flatMap((file) => (file === null ? Effect.interrupt : Effect.succeed(file)))),
97
+ (file) => Effect.sync(file.dispose),
98
+ ),
99
+ ).pipe(Atom.withLabel(`local-attachment-preview:${key.attachment.id}`)),
100
+);
101
+
102
+const noLocalAttachmentPreview = Atom.make(
103
+ AsyncResult.initial<AttachmentPreviewFile, Error>(),
104
+).pipe(Atom.withLabel("local-attachment-preview:none"));
105
+
106
+export function localAttachmentPreviewAtom(
107
+ attachment: FileBackedComposerAttachment | null,
108
+): Atom.Atom<AsyncResult.AsyncResult<AttachmentPreviewFile, Error>> {
109
+ return attachment === null
110
+ ? noLocalAttachmentPreview
111
+ : localAttachmentPreviewFamily(new LocalAttachmentPreviewKey(attachment));
112
+}
113
+
114
+export interface LocalAttachmentPreviewState {
115
+ readonly uri: string | null;
116
+ readonly error: Error | null;
117
+}
118
+
119
+export function localAttachmentPreviewState(
120
+ result: AsyncResult.AsyncResult<AttachmentPreviewFile, Error>,
121
+): LocalAttachmentPreviewState {
122
+ return {
123
+ // A refresh has already released the previous lease while it reacquires.
124
+ uri: result._tag === "Success" && !result.waiting ? result.value.uri : null,
125
+ error: result._tag === "Failure" ? Option.getOrNull(AsyncResult.error(result)) : null,
126
+ };
127
+}
128
+
129
+export function useLocalAttachmentPreview(
130
+ attachment: FileBackedComposerAttachment | null,
131
+): LocalAttachmentPreviewState {
132
+ return localAttachmentPreviewState(useAtomValue(localAttachmentPreviewAtom(attachment)));
133
+}
apps/mobile/src/lib/previewPresentation.ts
new
+38
@@ -0,0 +1,38 @@
1
+import { useNavigation } from "@react-navigation/native";
2
+import { useEffect, useEffectEvent } from "react";
3
+import { Keyboard } from "react-native";
4
+
5
+import { mediaVideoThumbnailKey, type VideoPreviewSource } from "./videoPreviewSource";
6
+
7
+/** Identity of a video preview: a different file is a new presentation. */
8
+export function videoPreviewKey(source: VideoPreviewSource): string {
9
+ return source.type === "local"
10
+ ? `local:${source.attachment.id}:${source.attachment.fileUri}`
11
+ : mediaVideoThumbnailKey(source);
12
+}
13
+
14
+/**
15
+ * A full-screen preview owns the screen while it is open: each presented
16
+ * source dismisses the keyboard, and the preview closes when its route loses
17
+ * focus, so navigating away never leaves a native viewer or modal behind.
18
+ * `presentationKey` is the presented source's identity, or null when closed.
19
+ */
20
+export function usePreviewPresentation(
21
+ presentationKey: string | null,
22
+ onRequestClose: () => void,
23
+): void {
24
+ // The v5 card host sits inside a legacy presentation envelope whose focus context
25
+ // can describe a different route. The preview belongs to this navigation route.
26
+ const navigation = useNavigation();
27
+ const close = useEffectEvent(onRequestClose);
28
+ // oxlint-disable-next-line t3code/react-effect-budget -- Navigation blur is an external event and the open state belongs to the caller.
29
+ useEffect(() => {
30
+ if (presentationKey === null) return;
31
+ Keyboard.dismiss();
32
+ if (!navigation.isFocused()) {
33
+ close();
34
+ return;
35
+ }
36
+ return navigation.addListener("blur", () => close());
37
+ }, [presentationKey, navigation]);
38
+}
apps/mobile/src/lib/useMediaVideoPlayback.test.tsx
+37
-27
@@ -1,3 +1,5 @@
1
+import { RegistryContext } from "@effect/atom-react";
2
+import { AtomRegistry } from "effect/reactivity";
3
import { act, type ReactNode } from "react";
4
import { createRoot } from "react-dom/client";
5
import type { AppStateStatus } from "react-native";
@@ -158,38 +160,43 @@ function setup(kind: "thread" | "PR", compact = false) {
160
mocks.thumbnail.mockReset().mockResolvedValue(null);
161
const container = document.createElement("div");
162
const root = createRoot(container);
163
+ // Configured like the app's registry: the React default keeps unmounted atoms for 400ms,
164
+ // which would hold thumbnail loads open across renders and tests.
165
+ const registry = AtomRegistry.make();
166
const environmentId = EnvironmentId.make("test");
167
return {
168
render(visible = true) {
169
act(() =>
170
root.render(
166
- kind === "thread" ? (
167
- <ThreadMediaVisibleContext value={visible}>
168
- <ThreadMarkdownVideo
169
- source={{
170
- type: "media",
171
- name: "clip.mp4",
172
- mimeType: "video/mp4",
173
- environmentId,
174
- resource: {
175
- _tag: "github-media",
176
- cwd: "/project",
177
- url: "https://github.com/user-attachments/assets/video",
178
- },
179
- }}
180
- />
181
- </ThreadMediaVisibleContext>
182
- ) : (
183
- <PullRequestMediaContext value={{ environmentId, cwd: "/project" }}>
184
- <PullRequestMediaVisibleContext value={visible}>
185
- <PullRequestMedia
186
- url="https://github.com/user-attachments/assets/video"
187
- kind="video"
188
- compact={compact}
171
+ <RegistryContext.Provider value={registry}>
172
+ {kind === "thread" ? (
173
+ <ThreadMediaVisibleContext value={visible}>
174
+ <ThreadMarkdownVideo
175
+ source={{
176
+ type: "media",
177
+ name: "clip.mp4",
178
+ mimeType: "video/mp4",
179
+ environmentId,
180
+ resource: {
181
+ _tag: "github-media",
182
+ cwd: "/project",
183
+ url: "https://github.com/user-attachments/assets/video",
184
+ },
185
+ }}
186
/>
190
- </PullRequestMediaVisibleContext>
191
- </PullRequestMediaContext>
192
- ),
187
+ </ThreadMediaVisibleContext>
188
+ ) : (
189
+ <PullRequestMediaContext value={{ environmentId, cwd: "/project" }}>
190
+ <PullRequestMediaVisibleContext value={visible}>
191
+ <PullRequestMedia
192
+ url="https://github.com/user-attachments/assets/video"
193
+ kind="video"
194
+ compact={compact}
195
+ />
196
+ </PullRequestMediaVisibleContext>
197
+ </PullRequestMediaContext>
198
+ )}
199
+ </RegistryContext.Provider>,
200
),
201
);
202
},
@@ -215,6 +222,7 @@ function setup(kind: "thread" | "PR", compact = false) {
222
},
223
[Symbol.dispose]() {
224
act(() => root.unmount());
225
+ registry.dispose();
226
},
227
};
228
}
@@ -263,14 +271,16 @@ it.each([false, true])(
271
"stops inactive PR thumbnail requests (compact: %s) and restarts on return",
272
async (compact) => {
273
using screen = setup("PR", compact);
274
+ mocks.thumbnail.mockReturnValue(new Promise(() => {}));
275
screen.render(false);
276
expect(mocks.thumbnail).not.toHaveBeenCalled();
277
await act(async () => screen.render(true));
278
expect(mocks.thumbnail).toHaveBeenCalledTimes(1);
279
const signal = mocks.thumbnail.mock.calls[0]![2];
280
expect(signal.aborted).toBe(false);
281
+ const aborted = new Promise((resolve) => signal.addEventListener("abort", resolve));
282
screen.render(false);
273
- expect(signal.aborted).toBe(true);
283
+ await act(() => aborted);
284
expect(mocks.thumbnail).toHaveBeenCalledTimes(1);
285
await act(async () => screen.render(true));
286
expect(mocks.thumbnail).toHaveBeenCalledTimes(2);
apps/mobile/src/state/assets.ts
+80
@@ -7,12 +7,16 @@ import {
7
createProjectFaviconUrlAtomFamily,
8
EMPTY_ASSET_URL_ATOM,
9
} from "@t3tools/client-runtime/state/assets";
10
+import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
11
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
12
+import * as Effect from "effect/Effect";
13
+import { Atom, AsyncResult } from "effect/reactivity";
14
import { useCallback } from "react";
15
16
import { connectionAtomRuntime } from "../connection/runtime";
17
import { projectFaviconDatabaseCache } from "../lib/projectFaviconDatabaseCache";
18
import { type AssetUrlState, deriveAssetUrlState } from "./asset-url-state";
19
+import { appAtomRegistry } from "./atom-registry";
20
import { environmentProjectCloneListAtom } from "./projectClones";
21
import { environmentSession, usePreparedConnection } from "./session";
22
import { useEnvironmentPresentation } from "./presentation";
@@ -92,3 +96,79 @@ export function useRefreshAssetUrl(
96
return state._tag === "Success" ? state.url : null;
97
}, [createUrl, environmentId, httpBaseUrl, resource]);
98
}
99
+
100
+/** {@link useRefreshAssetUrl} for async tasks that resolve several resources at once. */
101
+export async function refreshAssetUrl(
102
+ environmentId: EnvironmentId,
103
+ resource: AssetResource,
104
+ signal?: AbortSignal,
105
+): Promise<string | null> {
106
+ const connectionAtom = environmentSession.preparedConnectionValueAtom(environmentId);
107
+ if (appAtomRegistry.get(connectionAtom)._tag === "None") return null;
108
+ const atom = assetEnvironment.createUrl({ environmentId, input: { resource } });
109
+ const result = await executeAtomQuery(appAtomRegistry, atom, {
110
+ label: atom.label?.[0] ?? "asset url",
111
+ refresh: true,
112
+ reportFailure: false,
113
+ ...(signal ? { signal } : {}),
114
+ });
115
+ // The query can wait through a reconnect; resolve against the connection that answered it.
116
+ const connection = appAtomRegistry.get(connectionAtom);
117
+ if (connection._tag === "None") return null;
118
+ const state = assetUrlStateFromResult(result, connection.value.httpBaseUrl);
119
+ return state._tag === "Success" ? state.url : null;
120
+}
121
+
122
+export interface AuthorizedAssetUrl {
123
+ readonly url: string;
124
+ readonly authorizedAt: number;
125
+}
126
+
127
+interface FreshAssetUrlKey {
128
+ readonly environmentId: EnvironmentId | null;
129
+ readonly resource: AssetResource;
130
+ /** A reconnect changes the base URL, and any URL minted against the old one is unusable. */
131
+ readonly httpBaseUrl: string | null;
132
+ /** Bumped by Retry so a file replaced on disk is reauthorized. */
133
+ readonly revision: number;
134
+}
135
+
136
+// Plain-object keys compare structurally (Effect `Equal`/`Hash`).
137
+const freshAssetUrlFamily = Atom.family((key: FreshAssetUrlKey) =>
138
+ Atom.make(
139
+ Effect.tryPromise({
140
+ try: async (signal): Promise<AuthorizedAssetUrl> => {
141
+ const url =
142
+ key.environmentId === null
143
+ ? null
144
+ : await refreshAssetUrl(key.environmentId, key.resource, signal);
145
+ if (!url) throw new Error("Reconnect to this environment and try again.");
146
+ return { url, authorizedAt: Date.now() };
147
+ },
148
+ catch: (cause) =>
149
+ cause instanceof Error ? cause : new Error("The attachment is unavailable."),
150
+ }),
151
+ ).pipe(Atom.withLabel("fresh-asset-url")),
152
+);
153
+
154
+const noFreshAssetUrl = Atom.make(AsyncResult.initial<AuthorizedAssetUrl, Error>()).pipe(
155
+ Atom.withLabel("fresh-asset-url:none"),
156
+);
157
+
158
+/**
159
+ * A signed URL minted when the reader mounts, not a cached one: cached links can
160
+ * expire while the client is suspended.
161
+ */
162
+export function useFreshAssetUrl(
163
+ environmentId: EnvironmentId | null,
164
+ resource: AssetResource | null,
165
+ revision: number,
166
+): AsyncResult.AsyncResult<AuthorizedAssetUrl, Error> {
167
+ const connection = usePreparedConnection(environmentId);
168
+ const httpBaseUrl = connection._tag === "Some" ? connection.value.httpBaseUrl : null;
169
+ return useAtomValue(
170
+ resource === null
171
+ ? noFreshAssetUrl
172
+ : freshAssetUrlFamily({ environmentId, resource, httpBaseUrl, revision }),
173
+ );
174
+}