@devries-cameron20 / t3code-1 / commits / 1e2f88fde7
Fork 0

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

fix(files): load PDFs in browser previews (#21095)

Yash Singh committed Oct 18, 2026 at 23:43 UTC 1e2f88fde7cb9da832c88d11eb7188afca6f8810
32 files changed +1333 -173
apps/desktop/src/electron/ElectronProtocol.test.ts
+1
@@ -322,6 +322,7 @@ describe("ElectronProtocol", () => {
322 ]);
323 assert.deepEqual(directives["media-src"], ["'self'", "t3code:", "blob:", "http:", "https:"]);
324 assert.deepEqual(directives["frame-src"], ["'self'", "blob:", "http:", "https:"]);
325 + assert.deepEqual(directives["object-src"], ["'self'", "blob:", "http:", "https:"]);
326 assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
327 });
328 });
apps/desktop/src/electron/ElectronProtocol.ts
+1
@@ -95,6 +95,7 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
95 `font-src 'self' ${input.scheme}: data:`,
96 "worker-src 'self' blob:",
97 "frame-src 'self' blob: http: https:",
98 + "object-src 'self' blob: http: https:",
99 "form-action 'self'",
100 ].join("; ");
101 }
apps/mobile/app.config.ts
+1
@@ -317,6 +317,7 @@ const config: ExpoConfig = {
317 },
318 plugins: [
319 "expo-asset",
320 + "react-native-pdf-jsi",
321 [
322 "expo-font",
323 {
apps/mobile/package.json
+4
@@ -58,6 +58,7 @@
58 "@noble/curves": "catalog:",
59 "@pierre/diffs": "catalog:",
60 "@react-native-ai/apple": "0.12.0",
61 + "@react-native-async-storage/async-storage": "3.1.1",
62 "@react-native-menu/menu": "^2.0.0",
63 "@react-navigation/elements": "2.9.45",
64 "@react-navigation/native": "7.5.1",
@@ -123,10 +124,13 @@
124 "react": "catalog:",
125 "react-dom": "catalog:",
126 "react-native": "0.88.0",
127 + "react-native-blob-util": "0.25.1",
128 "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.15.tgz",
129 "react-native-gesture-handler": "~3.3.0",
130 "react-native-image-viewing": "^0.2.2",
131 "react-native-keyboard-controller": "1.22.7",
132 + "react-native-nitro-modules": "0.37.1",
133 + "react-native-pdf-jsi": "5.0.0",
134 "react-native-reanimated": "4.7.1",
135 "react-native-safe-area-context": "~5.10.1",
136 "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.27.tgz",
apps/mobile/src/components/FilePreview.tsx
+32
@@ -2,12 +2,43 @@ import * as Dialog from "./ui/Dialog";
2 import { useEffect, useEffectEvent } from "react";
3 import { Modal, Pressable, View } from "react-native";
4 import ImageViewing from "react-native-image-viewing";
5 +import { useSafeAreaInsets } from "react-native-safe-area-context";
6
7 import { openAttachmentInViewer } from "../lib/attachmentDownload";
8 import type { ResolvedFilePreviewSource } from "./FilePreviewModal.types";
9 import { MediaImagePreview } from "./MediaImagePreview";
10 +import { PdfPreview } from "./PdfPreview";
11 +import { ControlPill } from "./ui/ControlPill";
12 import { AppText as Text } from "./ui/AppText";
13
14 +function PdfDocumentPreview(props: {
15 + readonly source: ResolvedFilePreviewSource;
16 + readonly onRequestClose: () => void;
17 +}) {
18 + const insets = useSafeAreaInsets();
19 + return (
20 + <Modal
21 + animationType="slide"
22 + onRequestClose={props.onRequestClose}
23 + statusBarTranslucent
24 + navigationBarTranslucent
25 + >
26 + <View
27 + className="flex-1 bg-card"
28 + style={{ paddingTop: insets.top, paddingBottom: insets.bottom }}
29 + >
30 + <View className="flex-row items-center gap-3 border-b border-border px-4 py-2">
31 + <Text className="flex-1 font-t3-semibold text-foreground" numberOfLines={1}>
32 + {props.source.name ?? "PDF"}
33 + </Text>
34 + <ControlPill label="Close" variant="pill" onPress={props.onRequestClose} />
35 + </View>
36 + <PdfPreview uri={props.source.uri} />
37 + </View>
38 + </Modal>
39 + );
40 +}
41 +
42 function DocumentPreview(props: {
43 readonly source: ResolvedFilePreviewSource;
44 readonly onRequestClose: () => void;
@@ -71,6 +102,7 @@ export function FilePreview(props: {
102 readonly onRequestClose: () => void;
103 readonly onOpenError?: (error: unknown) => void;
104 }) {
105 + if (props.source.kind === "pdf") return <PdfDocumentPreview {...props} />;
106 if (props.source.kind !== "image") return <DocumentPreview {...props} />;
107 if (props.source.actionsSource) return <MediaImagePreview {...props} />;
108 return (
apps/mobile/src/components/PdfPreview.android.tsx new
+80
@@ -0,0 +1,80 @@
1 +import { useEffect, useRef, useState } from "react";
2 +import { View } from "react-native";
3 +import Pdf from "react-native-pdf-jsi";
4 +
5 +import { FilePreviewLoading, FilePreviewNotice } from "../features/files/FilePreviewFeedback";
6 +import { pdfInitialPage, pdfLinkUrl, preparePdfPreview } from "../lib/pdfPreview";
7 +import { tryOpenExternalUrl } from "../lib/openExternalUrl";
8 +import { ControlPill } from "./ui/ControlPill";
9 +
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 +
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]);
36 +
37 + if (error) {
38 + return (
39 + <View className="flex-1 gap-4 bg-card">
40 + <FilePreviewNotice title="Could not load PDF">{error}</FilePreviewNotice>
41 + <View className="items-center">
42 + <ControlPill label="Try again" variant="pill" onPress={props.onRetry} />
43 + </View>
44 + </View>
45 + );
46 + }
47 + if (localUri === null) return <FilePreviewLoading message="Loading PDF..." background="card" />;
48 +
49 + return (
50 + <Pdf
51 + source={{ uri: localUri }}
52 + page={pdfInitialPage(props.uri)}
53 + fitPolicy={0}
54 + trustAllCerts={false}
55 + enableAnnotationRendering
56 + enableDoubleTapZoom
57 + onPressLink={(href) => {
58 + const url = pdfLinkUrl(href, props.uri);
59 + if (url !== null) void tryOpenExternalUrl(url, "file-preview");
60 + }}
61 + onError={() => {
62 + cached.current?.dispose();
63 + cached.current = null;
64 + setError("The PDF could not be rendered. It may be damaged or password protected.");
65 + }}
66 + style={{ flex: 1, width: "100%" }}
67 + />
68 + );
69 +}
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/PdfPreview.tsx new
+29
@@ -0,0 +1,29 @@
1 +import { useState } from "react";
2 +import { View } from "react-native";
3 +import { WebView } from "react-native-webview";
4 +
5 +import { FilePreviewLoading, FilePreviewNotice } from "../features/files/FilePreviewFeedback";
6 +
7 +export function PdfPreview(props: { readonly uri: string }) {
8 + const [error, setError] = useState<string | null>(null);
9 + return (
10 + <View className="flex-1 bg-card">
11 + {error ? <FilePreviewNotice title="Could not load PDF">{error}</FilePreviewNotice> : null}
12 + <WebView
13 + source={{ uri: props.uri }}
14 + originWhitelist={["*"]}
15 + automaticallyAdjustContentInsets={false}
16 + contentInsetAdjustmentBehavior="never"
17 + startInLoadingState
18 + onError={(event) =>
19 + setError(event.nativeEvent.description || "The PDF could not be loaded.")
20 + }
21 + onHttpError={(event) =>
22 + setError(`The server returned HTTP ${event.nativeEvent.statusCode}.`)
23 + }
24 + renderLoading={() => <FilePreviewLoading message="Loading PDF..." background="card" />}
25 + style={{ flex: 1, backgroundColor: "transparent" }}
26 + />
27 + </View>
28 + );
29 +}
apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx
+12 -8
@@ -3,13 +3,9 @@ import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
3 import * as Dialog from "../../components/ui/Dialog";
4 import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
5 import { createNativeStackNavigator } from "@react-navigation/native-stack";
6 -import {
7 - EnvironmentId,
8 - FILL_PREVIEW_VIEWPORT,
9 - ThreadId,
10 - type PreviewSessionSnapshot,
11 -} from "@t3tools/contracts";
12 -import { normalizePreviewUrl } from "@t3tools/shared/preview";
6 +import { EnvironmentId, ThreadId, type PreviewSessionSnapshot } from "@t3tools/contracts";
7 +import { normalizePreviewUrl, previewPdfAssetUrl } from "@t3tools/shared/preview";
8 +import * as Option from "effect/Option";
9 import { useCallback, useEffect, useRef, useState } from "react";
10 import { AppState, Platform, TextInput, View } from "react-native";
11 import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -18,6 +14,7 @@ import { ControlPill } from "../../components/ui/ControlPill";
14 import { AppBar } from "../../components/ui/AppBar";
15
16 import { useThreadServerBrowserTabs } from "../../state/preview";
17 +import { usePreparedConnection } from "../../state/session";
18 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
19 import { BrowserTabMenu } from "./BrowserTabMenu";
20 import { browserTabTitle, browserTabUrl, latestBrowserTab } from "./browserTabs";
@@ -79,6 +76,8 @@ function BrowserPreviewScreen({
76 }) {
77 const insets = useSafeAreaInsets();
78 const { themeVariables } = useAppearancePreferences();
79 + const prepared = usePreparedConnection(environmentId);
80 + const httpBaseUrl = Option.isSome(prepared) ? prepared.value.httpBaseUrl : null;
81 const focused = useIsFocused();
82 const [foreground, setForeground] = useState(AppState.currentState !== "background");
83 const [selectedTabId, setSelectedTabId] = useState(initialTabId);
@@ -88,6 +87,8 @@ function BrowserPreviewScreen({
87 const streamRef = useRef<PreviewStreamRef>(null);
88 const { tabs, loaded } = useThreadServerBrowserTabs({ environmentId, threadId, enabled: true });
89 const tab = tabs.find((entry) => entry.tabId === selectedTabId) ?? latestBrowserTab(tabs);
90 + const pdfUri =
91 + tab?.navStatus._tag === "Success" ? previewPdfAssetUrl(tab.navStatus.url, httpBaseUrl) : null;
92 const tabId = tab?.tabId ?? null;
93 if (tabId !== null && tabId !== selectedTabId) {
94 setPictureInPicture(NO_PICTURE_IN_PICTURE);
@@ -121,7 +122,9 @@ function BrowserPreviewScreen({
122 options={{ headerBackVisible: false }}
123 actions={
124 // Android WebView cannot play video in picture in picture.
124 - Platform.OS === "ios" && pictureInPicture.supported
125 + Platform.OS === "ios" &&
126 + pictureInPicture.supported &&
127 + (pictureInPicture.active || pdfUri === null)
128 ? [
129 {
130 accessibilityLabel: pictureInPicture.active
@@ -181,6 +184,7 @@ function BrowserPreviewScreen({
184 environmentId={environmentId}
185 threadId={threadId}
186 tabId={tab.tabId}
187 + pdfUri={pdfUri}
188 ref={streamRef}
189 interactive
190 background={themeVariables["--color-sheet-solid"]}
apps/mobile/src/features/browser/PreviewStreamWebView.tsx
+89 -79
@@ -25,6 +25,7 @@ import { WebView } from "react-native-webview";
25 import * as Clipboard from "expo-clipboard";
26
27 import { AppText } from "../../components/ui/AppText";
28 +import { PdfPreview } from "../../components/PdfPreview";
29 import { downloadAndShareAttachment } from "../../lib/attachmentDownload";
30 import { beginForegroundHandoff } from "../../lib/foreground-handoff";
31 import { usePreviewStreamAccess } from "../../state/preview";
@@ -56,6 +57,7 @@ type NativeStreamBridge = {
57 /** True while frames show, so commands reach the page. Pass a stable function. */
58 readonly onStreamingChange?: (streaming: boolean) => void;
59 readonly compact?: boolean;
60 + readonly pdfUri?: string | null;
61 };
62
63 async function sendFilesToPage(chooser: PreviewStreamFileChooser, pick: boolean) {
@@ -223,6 +225,7 @@ function PreviewStreamDocumentView({
225 configuration,
226 background,
227 compact,
228 + pdfUri,
229 onUnauthorized,
230 onGone,
231 onViewport,
@@ -337,87 +340,94 @@ function PreviewStreamDocumentView({
340 ) : null}
341 </View>
342 ) : null}
340 - <WebView<object>
341 - ref={webView}
342 - source={source}
343 - originWhitelist={["*"]}
344 - scrollEnabled={false}
345 - bounces={false}
346 - mixedContentMode="always"
347 - allowUniversalAccessFromFileURLs
348 - contentInsetAdjustmentBehavior="never"
349 - setSupportMultipleWindows={false}
350 - allowsInlineMediaPlayback
351 - allowsPictureInPictureMediaPlayback
352 - mediaPlaybackRequiresUserAction={false}
353 - style={{ flex: 1, backgroundColor: background }}
354 - onError={() => fail("Browser viewer could not load. Reconnect to try again.")}
355 - onHttpError={() => fail("Browser viewer could not load. Reconnect to try again.")}
356 - onContentProcessDidTerminate={processTerminated}
357 - onRenderProcessGone={processTerminated}
358 - onShouldStartLoadWithRequest={(request) =>
359 - request.url === "about:blank" || request.url === source.baseUrl
360 - }
361 - onMessage={(event) => {
362 - if (!active.current || failed.current) return;
363 - const message = previewStreamMessage(event.nativeEvent.data);
364 - if (message === null) return;
365 - switch (message.type) {
366 - case "control": {
367 - setControl(message);
368 - const previousDialog = dialogRef.current;
369 - dialogRef.current = message.dialog;
370 - setPromptText((draft) => previewPromptText(previousDialog, message.dialog, draft));
371 - onControl?.(message);
372 - return;
373 - }
374 - case "unauthorized":
375 - if (!onUnauthorized()) {
376 - fail("This session can't open the browser stream. Reconnect to try again.");
377 - }
378 - return;
379 - case "gone":
380 - setGone(true);
381 - fail("This tab was closed.");
382 - onGone?.();
383 - return;
384 - case "hostSetup":
385 - setHostSetup({ need: message.need, command: message.command });
386 - fail(previewStreamHostSetupMessage(message));
387 - return;
388 - case "viewport":
389 - onViewport?.(message);
390 - return;
391 - case "clipboard":
392 - void Clipboard.setStringAsync(message.text).catch(() => undefined);
393 - return;
394 - case "download":
395 - offerDownload(message);
396 - return;
397 - case "fileChooser":
398 - setFileChooser(message.chooser);
399 - return;
400 - case "pictureInPicture":
401 - onPictureInPicture?.(message, message.detail);
402 - return;
403 - case "status":
404 - setStarted(true);
405 - if (message.status === "error") {
406 - fail(message.detail ?? "Browser stream failed.");
343 + <View className="relative flex-1">
344 + <WebView<object>
345 + ref={webView}
346 + source={source}
347 + originWhitelist={["*"]}
348 + scrollEnabled={false}
349 + bounces={false}
350 + mixedContentMode="always"
351 + allowUniversalAccessFromFileURLs
352 + contentInsetAdjustmentBehavior="never"
353 + setSupportMultipleWindows={false}
354 + allowsInlineMediaPlayback
355 + allowsPictureInPictureMediaPlayback
356 + mediaPlaybackRequiresUserAction={false}
357 + style={{ flex: 1, backgroundColor: background }}
358 + onError={() => fail("Browser viewer could not load. Reconnect to try again.")}
359 + onHttpError={() => fail("Browser viewer could not load. Reconnect to try again.")}
360 + onContentProcessDidTerminate={processTerminated}
361 + onRenderProcessGone={processTerminated}
362 + onShouldStartLoadWithRequest={(request) =>
363 + request.url === "about:blank" || request.url === source.baseUrl
364 + }
365 + onMessage={(event) => {
366 + if (!active.current || failed.current) return;
367 + const message = previewStreamMessage(event.nativeEvent.data);
368 + if (message === null) return;
369 + switch (message.type) {
370 + case "control": {
371 + setControl(message);
372 + const previousDialog = dialogRef.current;
373 + dialogRef.current = message.dialog;
374 + setPromptText((draft) => previewPromptText(previousDialog, message.dialog, draft));
375 + onControl?.(message);
376 return;
377 }
409 - setStatus(message.status);
410 - if (message.status === "connecting") {
411 - // Dialogs may have closed and reopened while this viewer was disconnected.
412 - dialogRef.current = null;
413 - setControl(null);
414 - onControl?.(null);
415 - }
416 - onStreamingChange?.(message.status === "streaming");
417 - if (message.status === "streaming") onStreaming();
418 - }
419 - }}
420 - />
378 + case "unauthorized":
379 + if (!onUnauthorized()) {
380 + fail("This session can't open the browser stream. Reconnect to try again.");
381 + }
382 + return;
383 + case "gone":
384 + setGone(true);
385 + fail("This tab was closed.");
386 + onGone?.();
387 + return;
388 + case "hostSetup":
389 + setHostSetup({ need: message.need, command: message.command });
390 + fail(previewStreamHostSetupMessage(message));
391 + return;
392 + case "viewport":
393 + onViewport?.(message);
394 + return;
395 + case "clipboard":
396 + void Clipboard.setStringAsync(message.text).catch(() => undefined);
397 + return;
398 + case "download":
399 + offerDownload(message);
400 + return;
401 + case "fileChooser":
402 + setFileChooser(message.chooser);
403 + return;
404 + case "pictureInPicture":
405 + onPictureInPicture?.(message, message.detail);
406 + return;
407 + case "status":
408 + setStarted(true);
409 + if (message.status === "error") {
410 + fail(message.detail ?? "Browser stream failed.");
411 + return;
412 + }
413 + setStatus(message.status);
414 + if (message.status === "connecting") {
415 + // Dialogs may have closed and reopened while this viewer was disconnected.
416 + dialogRef.current = null;
417 + setControl(null);
418 + onControl?.(null);
419 + }
420 + onStreamingChange?.(message.status === "streaming");
421 + if (message.status === "streaming") onStreaming();
422 + }
423 + }}
424 + />
425 + {pdfUri ? (
426 + <View className="absolute inset-0">
427 + <PdfPreview key={pdfUri} uri={pdfUri} />
428 + </View>
429 + ) : null}
430 + </View>
431 {!compact && fileChooser && control?.controller === "you" ? (
432 <View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4">
433 <AppText className="text-sm text-secondary-foreground">
apps/mobile/src/features/browser/ThreadBrowserFloat.tsx
+10
@@ -1,5 +1,7 @@
1 import { useIsFocused } from "@react-navigation/native";
2 import type { EnvironmentId, PreviewSessionSnapshot, ThreadId } from "@t3tools/contracts";
3 +import { previewPdfAssetUrl } from "@t3tools/shared/preview";
4 +import * as Option from "effect/Option";
5 import { useCallback, useEffect, useRef, useState } from "react";
6 import { AppState, Pressable, View } from "react-native";
7 import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
@@ -8,6 +10,7 @@ import { SymbolView } from "../../components/ui/AppSymbol";
10 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
11 import { browserTabTitle } from "./browserTabs";
12 import { PreviewStreamWebView } from "./PreviewStreamWebView";
13 +import { usePreparedConnection } from "../../state/session";
14
15 const PLAYER_LONG_SIDE = 184;
16 const PLAYER_ENTERING = FadeIn.duration(180).reduceMotion(ReduceMotion.System);
@@ -77,6 +80,8 @@ function FloatingBrowserPlayer(props: {
80 readonly onClose: () => void;
81 }) {
82 const { themeVariables } = useAppearancePreferences();
83 + const prepared = usePreparedConnection(props.environmentId);
84 + const httpBaseUrl = Option.isSome(prepared) ? prepared.value.httpBaseUrl : null;
85 const [viewport, setViewport] = useState<{ width: number; height: number } | null>(null);
86 const aspect = Math.min(Math.max(viewport ? viewport.width / viewport.height : 16 / 10, 0.5), 2);
87 const width = aspect >= 1 ? PLAYER_LONG_SIDE : Math.round(PLAYER_LONG_SIDE * aspect);
@@ -101,6 +106,11 @@ function FloatingBrowserPlayer(props: {
106 environmentId={props.environmentId}
107 threadId={props.threadId}
108 tabId={props.tab.tabId}
109 + pdfUri={
110 + props.tab.navStatus._tag === "Success"
111 + ? previewPdfAssetUrl(props.tab.navStatus.url, httpBaseUrl)
112 + : null
113 + }
114 interactive={false}
115 background={background}
116 compact
apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx
+86 -36
@@ -1,57 +1,107 @@
1 -import { useState } from "react";
2 -import { View } from "react-native";
1 +import { useEffect, useState } from "react";
2 +import { BackHandler, Platform, View } from "react-native";
3 import { WebView } from "react-native-webview";
4 +import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
5
6 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
7 import { AppText as Text } from "../../components/ui/AppText";
8 import { FilePreviewLoading } from "./FilePreviewFeedback";
9 import { LoadingStrip } from "../../components/ui/LoadingStrip";
10 +import { PdfPreview } from "../../components/PdfPreview";
11 +import { ControlPill } from "../../components/ui/ControlPill";
12 +import { isPdfPreviewUri } from "../../lib/pdfPreview";
13 +import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
14
15 export function WorkspaceFileWebPreview(props: { readonly uri: string | null }) {
16 + if (props.uri === null) {
17 + return <FilePreviewLoading message="Preparing preview..." background="card" />;
18 + }
19 + return <DocumentWebPreview key={props.uri} uri={props.uri} />;
20 +}
21 +
22 +function DocumentWebPreview(props: { readonly uri: string }) {
23 + const insets = useSafeAreaInsets();
24 + const columnMetrics = useNativeColumnLayoutMetrics();
25 + const pdfTopInset = Platform.OS === "ios" ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
26 const [loadProgress, setLoadProgress] = useState(0);
27 const [loadError, setLoadError] = useState<string | null>(null);
28 + const [linkedPdf, setLinkedPdf] = useState<string | null>(null);
29
14 - if (props.uri === null) {
15 - return <FilePreviewLoading message="Preparing preview..." background="card" />;
30 + useEffect(() => {
31 + if (linkedPdf === null) return;
32 + const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
33 + setLinkedPdf(null);
34 + return true;
35 + });
36 + return () => subscription.remove();
37 + }, [linkedPdf]);
38 +
39 + if (isPdfPreviewUri(props.uri)) {
40 + return (
41 + <View className="flex-1" style={{ paddingTop: pdfTopInset }}>
42 + <PdfPreview uri={props.uri} />
43 + </View>
44 + );
45 }
46
47 return (
48 <View className="relative flex-1 bg-card">
20 - {loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}
21 - {loadError ? (
22 - <View className="border-b border-border bg-card px-4 py-2">
23 - <Text className="text-xs font-t3-bold text-foreground">Preview failed</Text>
24 - <Text className="mt-0.5 text-xs leading-snug text-foreground-muted">{loadError}</Text>
49 + {linkedPdf ? (
50 + <View className="flex-1" style={{ paddingTop: pdfTopInset }}>
51 + <PdfPreview key={linkedPdf} uri={linkedPdf} />
52 + <SafeAreaView edges={["bottom"]} className="border-t border-border px-4 py-2">
53 + <ControlPill
54 + label="Back to document"
55 + variant="pill"
56 + onPress={() => setLinkedPdf(null)}
57 + />
58 + </SafeAreaView>
59 </View>
60 ) : null}
27 - <WebView
28 - source={{ uri: props.uri }}
29 - originWhitelist={["*"]}
30 - allowsBackForwardNavigationGestures
31 - allowsFullscreenVideo
32 - setSupportMultipleWindows={false}
33 - startInLoadingState
34 - onLoadProgress={(event) => {
35 - setLoadProgress(event.nativeEvent.progress);
36 - }}
37 - onLoadStart={() => {
38 - setLoadProgress(0.05);
39 - setLoadError(null);
40 - }}
41 - onLoadEnd={() => {
42 - setLoadProgress(0);
43 - }}
44 - onError={(event) => {
45 - setLoadProgress(0);
46 - setLoadError(event.nativeEvent.description || "The file could not be rendered.");
47 - }}
48 - renderLoading={() => (
49 - <View className="absolute inset-0 items-center justify-center bg-card">
50 - <AppActivityIndicator />
61 + <View className="flex-1" style={linkedPdf ? { display: "none" } : undefined}>
62 + {loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}
63 + {loadError ? (
64 + <View className="border-b border-border bg-card px-4 py-2">
65 + <Text className="text-xs font-t3-bold text-foreground">Preview failed</Text>
66 + <Text className="mt-0.5 text-xs leading-snug text-foreground-muted">{loadError}</Text>
67 </View>
52 - )}
53 - style={{ flex: 1, backgroundColor: "transparent" }}
54 - />
68 + ) : null}
69 + <WebView
70 + source={{ uri: props.uri }}
71 + originWhitelist={["*"]}
72 + allowsBackForwardNavigationGestures
73 + allowsFullscreenVideo
74 + setSupportMultipleWindows={false}
75 + onShouldStartLoadWithRequest={(request) => {
76 + if (request.isTopFrame !== false && isPdfPreviewUri(request.url)) {
77 + setLinkedPdf(request.url);
78 + return false;
79 + }
80 + return true;
81 + }}
82 + startInLoadingState
83 + onLoadProgress={(event) => {
84 + setLoadProgress(event.nativeEvent.progress);
85 + }}
86 + onLoadStart={() => {
87 + setLoadProgress(0.05);
88 + setLoadError(null);
89 + }}
90 + onLoadEnd={() => {
91 + setLoadProgress(0);
92 + }}
93 + onError={(event) => {
94 + setLoadProgress(0);
95 + setLoadError(event.nativeEvent.description || "The file could not be rendered.");
96 + }}
97 + renderLoading={() => (
98 + <View className="absolute inset-0 items-center justify-center bg-card">
99 + <AppActivityIndicator />
100 + </View>
101 + )}
102 + style={{ flex: 1, backgroundColor: "transparent" }}
103 + />
104 + </View>
105 </View>
106 );
107 }
apps/mobile/src/lib/pdfPreview.test.ts new
+134
@@ -0,0 +1,134 @@
1 +import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2 +
3 +const mocks = vi.hoisted(() => ({
4 + download: vi.fn(),
5 + dispose: vi.fn(),
6 + read: vi.fn(),
7 + close: vi.fn(),
8 +}));
9 +vi.mock("./attachmentDownload", () => ({ downloadAttachmentForPreview: mocks.download }));
10 +vi.mock("expo-file-system", () => ({
11 + File: class {
12 + open() {
13 + return { readBytes: mocks.read, close: mocks.close };
14 + }
15 + },
16 + FileMode: { ReadOnly: "r" },
17 +}));
18 +
19 +import { isPdfPreviewUri, pdfInitialPage, pdfLinkUrl, preparePdfPreview } from "./pdfPreview";
20 +
21 +beforeEach(() => {
22 + vi.resetAllMocks();
23 + mocks.download.mockResolvedValue({ uri: "file:///cache/preview.pdf", dispose: mocks.dispose });
24 + mocks.read.mockResolvedValue(new TextEncoder().encode("%PDF-"));
25 +});
26 +
27 +describe("PDF navigation", () => {
28 + it("resolves web links against the original PDF rather than its download cache", () => {
29 + expect(
30 + pdfLinkUrl("../next.pdf#page=2", "https://environment.test/api/assets/token/files/a.pdf"),
31 + ).toBe("https://environment.test/api/assets/token/next.pdf#page=2");
32 + expect(pdfLinkUrl("https://example.com/?q=one#section", "file:///cache/preview.pdf")).toBe(
33 + "https://example.com/?q=one#section",
34 + );
35 + });
36 +
37 + it.each([
38 + "",
39 + "javascript:alert(1)",
40 + "data:text/html,hello",
41 + "file:///private/a.pdf",
42 + "intent://open",
43 + "https://[",
44 + ])("ignores unsupported or invalid PDF links: %s", (href) => {
45 + expect(pdfLinkUrl(href, "https://environment.test/a.pdf")).toBeNull();
46 + });
47 +
48 + it("recognizes signed PDF links with queries and page fragments", () => {
49 + expect(
50 + isPdfPreviewUri("https://environment.test/api/assets/token/Syllabus.PDF?x=1#page=8"),
51 + ).toBe(true);
52 + expect(isPdfPreviewUri("file:///local/document.pdf")).toBe(true);
53 + expect(isPdfPreviewUri("https://environment.test/index.html?file=syllabus.pdf")).toBe(false);
54 + expect(isPdfPreviewUri("invalid")).toBe(false);
55 + });
56 +
57 + it("keeps valid page destinations and rejects invalid page numbers", () => {
58 + expect(pdfInitialPage("https://environment.test/a.pdf#page=8&zoom=100")).toBe(8);
59 + for (const fragment of [
60 + "",
61 + "#page=0",
62 + "#page=-2",
63 + "#page=1.5",
64 + "#page=NaN",
65 + "#page=Infinity",
66 + ]) {
67 + expect(pdfInitialPage(`file:///a.pdf${fragment}`)).toBe(1);
68 + }
69 + });
70 +});
71 +
72 +describe("preparing native PDFs", () => {
73 + it("downloads from the selected environment without sending the page fragment", async () => {
74 + const signal = new AbortController().signal;
75 + const result = await preparePdfPreview("https://remote.test/a.pdf?token=secret#page=8", signal);
76 + expect(mocks.download).toHaveBeenCalledWith({
77 + url: "https://remote.test/a.pdf?token=secret",
78 + attachment: { name: "preview.pdf", mimeType: "application/pdf" },
79 + signal,
80 + });
81 + expect(result?.uri).toBe("file:///cache/preview.pdf");
82 + expect(mocks.close).toHaveBeenCalledOnce();
83 + expect(mocks.dispose).not.toHaveBeenCalled();
84 + result?.dispose();
85 + expect(mocks.dispose).toHaveBeenCalledOnce();
86 + });
87 +
88 + it("rejects an HTML response and removes the download", async () => {
89 + mocks.read.mockResolvedValue(new TextEncoder().encode("<html"));
90 + await expect(
91 + preparePdfPreview("https://remote.test/a.pdf", new AbortController().signal),
92 + ).rejects.toThrow("did not return a PDF");
93 + expect(mocks.close).toHaveBeenCalledOnce();
94 + expect(mocks.dispose).toHaveBeenCalledOnce();
95 + });
96 +
97 + it("closes and removes the cached file when reading fails", async () => {
98 + mocks.read.mockRejectedValue(new Error("read failed"));
99 + await expect(
100 + preparePdfPreview("https://remote.test/a.pdf", new AbortController().signal),
101 + ).rejects.toThrow("read failed");
102 + expect(mocks.close).toHaveBeenCalledOnce();
103 + expect(mocks.dispose).toHaveBeenCalledOnce();
104 + });
105 +
106 + it("opens local files without downloading or deleting the caller's file", async () => {
107 + const result = await preparePdfPreview(
108 + "file:///draft.pdf#page=3",
109 + new AbortController().signal,
110 + );
111 + expect(result?.uri).toBe("file:///draft.pdf");
112 + result?.dispose();
113 + expect(mocks.download).not.toHaveBeenCalled();
114 + expect(mocks.dispose).not.toHaveBeenCalled();
115 + });
116 +
117 + it("removes a download if the preview is dismissed during validation", async () => {
118 + const controller = new AbortController();
119 + mocks.read.mockImplementation(async () => {
120 + controller.abort();
121 + return new TextEncoder().encode("%PDF-");
122 + });
123 + expect(await preparePdfPreview("https://remote.test/a.pdf", controller.signal)).toBeNull();
124 + expect(mocks.dispose).toHaveBeenCalledOnce();
125 + });
126 +
127 + it("does no work for an already dismissed preview", async () => {
128 + const controller = new AbortController();
129 + controller.abort();
130 + expect(await preparePdfPreview("https://remote.test/a.pdf", controller.signal)).toBeNull();
131 + expect(mocks.download).not.toHaveBeenCalled();
132 + expect(mocks.read).not.toHaveBeenCalled();
133 + });
134 +});
apps/mobile/src/lib/pdfPreview.ts new
+58
@@ -0,0 +1,58 @@
1 +import { downloadAttachmentForPreview } from "./attachmentDownload";
2 +
3 +export function isPdfPreviewUri(uri: string): boolean {
4 + try {
5 + return /\.pdf$/i.test(new URL(uri).pathname);
6 + } catch {
7 + return false;
8 + }
9 +}
10 +
11 +export function pdfInitialPage(uri: string): number {
12 + const page = Number(new URLSearchParams(uri.split("#", 2)[1]).get("page"));
13 + return Number.isSafeInteger(page) && page > 0 ? page : 1;
14 +}
15 +
16 +export function pdfLinkUrl(href: string, sourceUri: string): string | null {
17 + if (href.trim().length === 0) return null;
18 + try {
19 + const url = new URL(href, sourceUri);
20 + return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
21 + } catch {
22 + return null;
23 + }
24 +}
25 +
26 +export async function preparePdfPreview(uri: string, signal: AbortSignal) {
27 + if (signal.aborted) return null;
28 + const source = uri.split("#", 1)[0]!;
29 + const cached = /^(file|content):/.test(source)
30 + ? { uri: source, dispose: () => {} }
31 + : await downloadAttachmentForPreview({
32 + url: source,
33 + attachment: { name: "preview.pdf", mimeType: "application/pdf" },
34 + signal,
35 + });
36 + if (cached === null) return null;
37 + try {
38 + const { File, FileMode } = await import("expo-file-system");
39 + const handle = new File(cached.uri).open(FileMode.ReadOnly);
40 + try {
41 + const header = await handle.readBytes(5);
42 + if (String.fromCharCode(...header) !== "%PDF-") {
43 + throw new Error("The server did not return a PDF. Check the connection and try again.");
44 + }
45 + } finally {
46 + handle.close();
47 + }
48 + if (signal.aborted) {
49 + cached.dispose();
50 + return null;
51 + }
52 + return cached;
53 + } catch (error) {
54 + cached.dispose();
55 + if (signal.aborted) return null;
56 + throw error;
57 + }
58 +}
apps/mobile/src/native/NativeHeaderToolbar.test.tsx new
+101
@@ -0,0 +1,101 @@
1 +// @vitest-environment jsdom
2 +import type { NativeStackHeaderItem } from "@react-navigation/native-stack";
3 +import { act } from "react";
4 +import { createRoot, type Root } from "react-dom/client";
5 +import { afterEach, expect, it, vi } from "vite-plus/test";
6 +
7 +const harness = vi.hoisted(() => ({
8 + params: { path: ["first", "guide.pdf"] },
9 + renderedItems: [] as NativeStackHeaderItem[],
10 + setOptionsCalls: 0,
11 + openedDocuments: [] as string[],
12 +}));
13 +
14 +// Native headers retain the actions materialized when navigation applies options.
15 +vi.mock("@react-navigation/native", () => {
16 + const navigation = {
17 + setOptions(options: {
18 + unstable_headerLeftItems?: () => NativeStackHeaderItem[];
19 + unstable_headerRightItems?: () => NativeStackHeaderItem[];
20 + unstable_headerToolbarItems?: () => NativeStackHeaderItem[];
21 + }) {
22 + harness.setOptionsCalls += 1;
23 + harness.renderedItems =
24 + options.unstable_headerLeftItems?.() ??
25 + options.unstable_headerRightItems?.() ??
26 + options.unstable_headerToolbarItems?.() ??
27 + [];
28 + },
29 + };
30 + return {
31 + useNavigation: () => navigation,
32 + useRoute: () => ({ key: "file", name: "ThreadFile", params: harness.params }),
33 + };
34 +});
35 +
36 +import { NativeHeaderToolbar } from "./NativeHeaderToolbar";
37 +
38 +let root: Root | null = null;
39 +type Placement = "left" | "right" | "bottom";
40 +
41 +function DocumentToolbar(props: { readonly path: string; readonly placement: Placement }) {
42 + return (
43 + <NativeHeaderToolbar placement={props.placement}>
44 + <NativeHeaderToolbar.Menu title="File actions" icon="ellipsis">
45 + <NativeHeaderToolbar.MenuAction onPress={() => harness.openedDocuments.push(props.path)}>
46 + Open PDF
47 + </NativeHeaderToolbar.MenuAction>
48 + </NativeHeaderToolbar.Menu>
49 + </NativeHeaderToolbar>
50 + );
51 +}
52 +
53 +function renderDocument(path: string, placement: Placement) {
54 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
55 + harness.params = { path: path.split("/") };
56 + root ??= createRoot(document.createElement("div"));
57 + act(() => root!.render(<DocumentToolbar path={path} placement={placement} />));
58 +}
59 +
60 +function openRenderedDocument() {
61 + const menu = harness.renderedItems[0];
62 + if (menu?.type !== "menu") throw new Error("Expected the native file menu");
63 + const action = menu.menu.items[0];
64 + if (action?.type !== "action") throw new Error("Expected the native Open PDF action");
65 + action.onPress?.();
66 +}
67 +
68 +afterEach(() => {
69 + act(() => root?.unmount());
70 + root = null;
71 + harness.renderedItems = [];
72 + harness.setOptionsCalls = 0;
73 + harness.openedDocuments = [];
74 + vi.unstubAllGlobals();
75 +});
76 +
77 +it.each(["left", "right", "bottom"] as const)(
78 + "updates the %s header action when switching between documents with the same name",
79 + (placement) => {
80 + renderDocument("first/guide.pdf", placement);
81 + openRenderedDocument();
82 + renderDocument("second/guide.pdf", placement);
83 + openRenderedDocument();
84 +
85 + expect(harness.openedDocuments).toEqual(["first/guide.pdf", "second/guide.pdf"]);
86 + },
87 +);
88 +
89 +it.each(["left", "right", "bottom"] as const)(
90 + "does not reapply %s header options for equivalent document renders",
91 + (placement) => {
92 + renderDocument("first/guide.pdf", placement);
93 + const applied = harness.setOptionsCalls;
94 + renderDocument("first/guide.pdf", placement);
95 + renderDocument("first/guide.pdf", placement);
96 +
97 + expect(harness.setOptionsCalls).toBe(applied);
98 + openRenderedDocument();
99 + expect(harness.openedDocuments).toEqual(["first/guide.pdf"]);
100 + },
101 +);
apps/mobile/src/native/NativeHeaderToolbar.tsx
+20 -26
@@ -1,4 +1,4 @@
1 -import { useNavigation, type ParamListBase } from "@react-navigation/native";
1 +import { useNavigation, useRoute, type ParamListBase } from "@react-navigation/native";
2 import type {
3 NativeStackHeaderItem,
4 NativeStackHeaderItemMenu,
@@ -17,6 +17,7 @@ import {
17 import type { ColorValue } from "react-native";
18 import type { HeaderBarButtonSearchBarPlacementItem } from "react-native-screens";
19 import { NativeWorkspaceTabActivityContext } from "./v5-workspace-context";
20 +import { NativeStackScreenOptions } from "./StackHeader";
21
22 function useNativeStackNavigation(): NativeStackNavigationProp<ParamListBase> | null {
23 return useNavigation<NativeStackNavigationProp<ParamListBase>>();
@@ -225,33 +226,15 @@ function NativeHeaderToolbarRoot(props: {
226 readonly children?: ReactNode;
227 }) {
228 const navigation = useNativeStackNavigation();
229 + const route = useRoute();
230 const tabActivity = use(NativeWorkspaceTabActivityContext);
229 - const tabActive = tabActivity?.active ?? true;
231 const isTabActive = tabActivity?.isActive;
232 const items = useMemo(() => collectToolbarItems(props.children), [props.children]);
232 -
233 - // Update items in place. Clearing them on every render causes UIKit to run a
234 - // second transition and detach custom views while the stack is animating.
235 - useLayoutEffect(() => {
236 - if (!navigation || !tabActive) {
237 - return;
238 - }
239 - if (props.placement === "bottom") {
240 - navigation.setOptions({
241 - unstable_headerToolbarItems: () => items,
242 - } as NativeStackOptionsWithToolbar);
243 - return;
244 - }
245 - // UIKit's search placement item belongs to the toolbar, never a header group.
246 - const headerItems = items.filter(
247 - (item): item is NativeStackHeaderItem => item.type !== "searchBarPlacement",
248 - );
249 - if (props.placement === "left") {
250 - navigation.setOptions({ unstable_headerLeftItems: () => headerItems });
251 - return;
252 - }
253 - navigation.setOptions({ unstable_headerRightItems: () => headerItems });
254 - }, [items, navigation, props.placement, tabActive]);
233 + // UIKit's search placement item belongs to the toolbar, never a header group.
234 + const headerItems = useMemo(
235 + () => items.filter((item): item is NativeStackHeaderItem => item.type !== "searchBarPlacement"),
236 + [items],
237 + );
238
239 useLayoutEffect(() => {
240 if (!navigation) return;
@@ -269,7 +252,18 @@ function NativeHeaderToolbarRoot(props: {
252 };
253 }, [navigation, props.placement, isTabActive]);
254
272 - return null;
255 + return (
256 + <NativeStackScreenOptions
257 + optionsVersion={[items, route.params]}
258 + options={
259 + props.placement === "bottom"
260 + ? { unstable_headerToolbarItems: () => items }
261 + : props.placement === "left"
262 + ? { unstable_headerLeftItems: () => headerItems }
263 + : { unstable_headerRightItems: () => headerItems }
264 + }
265 + />
266 + );
267 }
268
269 function NativeHeaderToolbarButton(_props: {
apps/mobile/src/native/StackHeader.tsx
-2
@@ -7,8 +7,6 @@ import { use, useEffect, useLayoutEffect, useMemo, useRef } from "react";
7 import { NativeWorkspaceTabActivityContext } from "./v5-workspace-context";
8 import type { ColorValue } from "react-native";
9
10 -export { NativeHeaderToolbar } from "./NativeHeaderToolbar";
11 -
10 export {
11 nativeHeaderScrollEdgeEffects,
12 nativeTopScrollEdgeEffect,
apps/server/src/preview/PdfDocumentNavigation.test.ts new
+163
@@ -0,0 +1,163 @@
1 +import type { CDPSession } from "playwright-core";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3 +
4 +import { installPdfDocumentNavigation } from "./PdfDocumentNavigation.ts";
5 +
6 +const source = "https://environment.test/api/assets/signed-token/files/Study%20guide.PDF";
7 +
8 +function fixture(nativePdfViewer = false) {
9 + const completed = Promise.withResolvers<{ method: string; params: Record<string, unknown> }>();
10 + let paused: (event: {
11 + requestId: string;
12 + frameId: string;
13 + request: { url: string; method: string };
14 + responseStatusCode: number;
15 + responseHeaders: Array<{ name: string; value: string }>;
16 + }) => void = () => {
17 + throw new Error("Navigation handler was not installed");
18 + };
19 + const send = vi.fn(async (method: string, params: Record<string, unknown> = {}) => {
20 + if (method === "Runtime.evaluate") return { result: { value: nativePdfViewer } };
21 + if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
22 + if (
23 + method === "Fetch.fulfillRequest" ||
24 + method === "Fetch.continueRequest" ||
25 + method === "Fetch.failRequest"
26 + ) {
27 + completed.resolve({ method, params });
28 + }
29 + return {};
30 + });
31 + const cdp = {
32 + send,
33 + on: (_name: string, listener: typeof paused) => {
34 + paused = listener;
35 + },
36 + } as unknown as CDPSession;
37 + return {
38 + cdp,
39 + send,
40 + navigate: (
41 + url = source,
42 + frameId = "main",
43 + method = "GET",
44 + status = 200,
45 + contentType = "application/pdf",
46 + ) => {
47 + paused({
48 + requestId: "request-1",
49 + frameId,
50 + request: { url, method },
51 + responseStatusCode: status,
52 + responseHeaders: [{ name: "Content-Type", value: contentType }],
53 + });
54 + return completed.promise;
55 + },
56 + };
57 +}
58 +
59 +describe("PDF document navigation", () => {
60 + it("keeps native PDF rendering when the browser supports it", async () => {
61 + const test = fixture(true);
62 + await installPdfDocumentNavigation(test.cdp);
63 + expect(test.send.mock.calls.map(([method]) => method)).toEqual(["Runtime.evaluate"]);
64 + });
65 +
66 + it("commits the PDF URL for client rendering without redirects or server-side PDF rendering", async () => {
67 + const test = fixture();
68 + await installPdfDocumentNavigation(test.cdp);
69 + const { method, params } = await test.navigate();
70 + expect(method).toBe("Fetch.fulfillRequest");
71 + expect(params).toMatchObject({ responseCode: 200, requestId: "request-1" });
72 + expect(params.responseHeaders).toEqual([
73 + { name: "Content-Type", value: "text/html; charset=utf-8" },
74 + { name: "Cache-Control", value: "no-store" },
75 + { name: "Content-Security-Policy", value: "default-src 'none'; sandbox" },
76 + { name: "X-Content-Type-Options", value: "nosniff" },
77 + ]);
78 + expect(Buffer.from(String(params.body), "base64").toString()).toBe(
79 + "<!doctype html><html><head><title>Study guide.PDF</title></head><body><h1>Study guide.PDF</h1><p>This PDF is displayed in the connected client.</p></body></html>",
80 + );
81 + expect(test.send).toHaveBeenCalledWith("Fetch.enable", {
82 + patterns: [
83 + { urlPattern: "*/api/assets/*", resourceType: "Document", requestStage: "Response" },
84 + ],
85 + });
86 + });
87 +
88 + it.each([401, 403, 404, 410, 500])(
89 + "fails unavailable PDF assets with HTTP %s",
90 + async (status) => {
91 + const test = fixture();
92 + await installPdfDocumentNavigation(test.cdp);
93 + expect(await test.navigate(source, "main", "GET", status)).toEqual({
94 + method: "Fetch.failRequest",
95 + params: { requestId: "request-1", errorReason: "Failed" },
96 + });
97 + expect(test.send.mock.calls.some(([method]) => method === "Fetch.fulfillRequest")).toBe(
98 + false,
99 + );
100 + },
101 + );
102 +
103 + it("rejects a non-PDF response instead of committing a successful PDF tab", async () => {
104 + const test = fixture();
105 + await installPdfDocumentNavigation(test.cdp);
106 + expect(await test.navigate(source, "main", "GET", 200, "text/html")).toMatchObject({
107 + method: "Fetch.failRequest",
108 + });
109 + });
110 +
111 + it("allows redirects to reach their asset response", async () => {
112 + const test = fixture();
113 + await installPdfDocumentNavigation(test.cdp);
114 + expect(await test.navigate(source, "main", "GET", 302)).toMatchObject({
115 + method: "Fetch.continueRequest",
116 + });
117 + });
118 +
119 + it("accepts a partial PDF response", async () => {
120 + const test = fixture();
121 + await installPdfDocumentNavigation(test.cdp);
122 + expect(
123 + await test.navigate(source, "main", "GET", 206, "Application/PDF; charset=binary"),
124 + ).toMatchObject({
125 + method: "Fetch.fulfillRequest",
126 + });
127 + });
128 +
129 + it.each([
130 + ["https://environment.test/api/assets/token/index.html", "main", "GET"],
131 + ["https://example.com/paper.pdf", "main", "GET"],
132 + [source, "subframe", "GET"],
133 + [source, "main", "POST"],
134 + ])("leaves other browser requests alone: %s, %s, %s", async (url, frameId, method) => {
135 + const test = fixture();
136 + await installPdfDocumentNavigation(test.cdp);
137 + expect(await test.navigate(url, frameId, method)).toEqual({
138 + method: "Fetch.continueRequest",
139 + params: { requestId: "request-1" },
140 + });
141 + });
142 +
143 + it("escapes filenames in the browser document", async () => {
144 + const test = fixture();
145 + await installPdfDocumentNavigation(test.cdp);
146 + const result = await test.navigate(
147 + "https://environment.test/api/assets/token/%3Cscript%3E.pdf",
148 + );
149 + expect(Buffer.from(String(result.params.body), "base64").toString()).toContain(
150 + "<title>&lt;script>.pdf</title>",
151 + );
152 + });
153 +
154 + it("resumes navigation when committing the document fails", async () => {
155 + const test = fixture();
156 + await installPdfDocumentNavigation(test.cdp);
157 + test.send.mockRejectedValueOnce(new Error("Tab closed"));
158 + expect(await test.navigate()).toEqual({
159 + method: "Fetch.continueRequest",
160 + params: { requestId: "request-1" },
161 + });
162 + });
163 +});
apps/server/src/preview/PdfDocumentNavigation.ts new
+72
@@ -0,0 +1,72 @@
1 +import { constVoid } from "effect/Function";
2 +import type { CDPSession } from "playwright-core";
3 +
4 +const escapeHtml = (value: string) =>
5 + value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;");
6 +
7 +export const isPdfAssetUrl = (url: string) => {
8 + const { pathname } = new URL(url);
9 + return pathname.startsWith("/api/assets/") && /\.pdf$/i.test(pathname);
10 +};
11 +
12 +export async function installPdfDocumentNavigation(cdp: CDPSession) {
13 + const nativeViewer = await cdp.send("Runtime.evaluate", {
14 + expression: "navigator.pdfViewerEnabled",
15 + returnByValue: true,
16 + });
17 + if (nativeViewer.result?.value === true) return;
18 + const { frameTree } = await cdp.send("Page.getFrameTree");
19 + // The shell cannot open PDFs. Commit a document at the original URL so the
20 + // client can embed its signed bytes while Back and Forward keep working.
21 + cdp.on("Fetch.requestPaused", (event) => {
22 + const { requestId, request, frameId } = event;
23 + const proceed = () => cdp.send("Fetch.continueRequest", { requestId });
24 + void (async () => {
25 + if (
26 + request.method !== "GET" ||
27 + frameId !== frameTree.frame.id ||
28 + !isPdfAssetUrl(request.url)
29 + ) {
30 + await proceed();
31 + return;
32 + }
33 + const status = event.responseStatusCode;
34 + if (status === undefined || (status >= 300 && status < 400)) {
35 + await proceed();
36 + return;
37 + }
38 + const contentType = event.responseHeaders
39 + ?.find((header) => header.name.toLowerCase() === "content-type")
40 + ?.value.split(";", 1)[0]
41 + ?.trim()
42 + .toLowerCase();
43 + if (status < 200 || status >= 300 || contentType !== "application/pdf") {
44 + // Reach the browser's requestfailed path instead of committing a successful PDF tab.
45 + await cdp.send("Fetch.failRequest", { requestId, errorReason: "Failed" });
46 + return;
47 + }
48 + const name = escapeHtml(
49 + decodeURIComponent(new URL(request.url).pathname.split("/").at(-1) ?? "PDF"),
50 + );
51 + await cdp.send("Fetch.fulfillRequest", {
52 + requestId,
53 + responseCode: 200,
54 + responseHeaders: [
55 + { name: "Content-Type", value: "text/html; charset=utf-8" },
56 + { name: "Cache-Control", value: "no-store" },
57 + { name: "Content-Security-Policy", value: "default-src 'none'; sandbox" },
58 + { name: "X-Content-Type-Options", value: "nosniff" },
59 + ],
60 + body: Buffer.from(
61 + `<!doctype html><html><head><title>${name}</title></head><body><h1>${name}</h1><p>This PDF is displayed in the connected client.</p></body></html>`,
62 + ).toString("base64"),
63 + });
64 + })().catch(() => proceed().catch(constVoid));
65 + });
66 + // Only document navigations pause; the client's PDF fetch gets the original bytes.
67 + await cdp.send("Fetch.enable", {
68 + patterns: [
69 + { urlPattern: "*/api/assets/*", resourceType: "Document", requestStage: "Response" },
70 + ],
71 + });
72 +}
apps/server/src/preview/ServerBrowser.test.ts
+38
@@ -908,6 +908,44 @@ it.live("a popup becomes the agent's own tab and keeps its opener page", () =>
908 ).pipe(Effect.provide(layer)),
909 );
910
911 +it.live.each([
912 + { url: "https://environment.test/api/assets/token/guide.pdf", pdf: true },
913 + { url: "https://example.com/sign-in", pdf: false },
914 +])("an adopted popup at $url recovers only PDF asset navigation", ({ url, pdf }) =>
915 + Effect.scoped(
916 + Effect.gen(function* () {
917 + const browser = yield* ServerBrowser.ServerBrowser;
918 + const manager = yield* Manager.PreviewManager;
919 + const events = yield* manager.subscribeEvents;
920 + const opened = yield* manager.open({ threadId: scope.thread.threadId, runtime: "server" });
921 + const viewer = yield* browser.attachViewer(viewerInput(opened.tabId, true));
922 + yield* viewer.input({ type: "takeControl" });
923 + const popup = makeContext();
924 + yield* Effect.promise(() => popup.page.goto(url));
925 + popup.page.goto.mockClear();
926 + popup.page.reload.mockImplementationOnce(async () => {
927 + popup.page.emit("load");
928 + });
929 + contexts[0]!.page.emit("popup", popup.page);
930 + let shown = yield* Queue.take(viewer.output);
931 + while (shown._tag !== "popup") shown = yield* Queue.take(viewer.output);
932 + yield* browser.attachViewer(viewerInput(shown.tabId, true));
933 + expect(popup.page.goto).not.toHaveBeenCalled();
934 + expect(popup.page.reload).toHaveBeenCalledTimes(pdf ? 1 : 0);
935 + if (pdf) {
936 + let event = yield* PubSub.take(events);
937 + while (event.type !== "navigated" || event.tabId !== shown.tabId) {
938 + event = yield* PubSub.take(events);
939 + }
940 + const session = (yield* manager.list({ threadId: scope.thread.threadId })).sessions.find(
941 + (entry) => entry.tabId === shown.tabId,
942 + );
943 + expect(session?.navStatus).toMatchObject({ _tag: "Success", url });
944 + }
945 + }),
946 + ).pipe(Effect.provide(layer)),
947 +);
948 +
949 it.live("a tab opened to a file the browser cannot show reports the file to download", () =>
950 Effect.scoped(
951 Effect.gen(function* () {
apps/server/src/preview/ServerBrowser.ts
+13 -5
@@ -82,6 +82,7 @@ import * as PreviewBrowser from "./PreviewBrowser.ts";
82 import * as PreviewBrowserHost from "./PreviewBrowserHost.ts";
83 import { presentAsChrome, ServerBrowserContexts } from "./ServerBrowserContexts.ts";
84 import { BrowserControlInterrupted, SessionControl } from "./SessionControl.ts";
85 +import { installPdfDocumentNavigation, isPdfAssetUrl } from "./PdfDocumentNavigation.ts";
86
87 const SERVER_HOST_CLIENT_ID = SERVER_BROWSER_AUTOMATION_CLIENT_ID;
88 const RENDER_SCALE = 2;
@@ -736,6 +737,7 @@ const make = Effect.gen(function* () {
737 if (!desktop) await prepareContext(context);
738 const page = adopted?.page ?? desktop?.page ?? (await context.newPage());
739 const cdp = await context.newCDPSession(page);
740 + await installPdfDocumentNavigation(cdp);
741 // The desktop's page is already a normal browser. A popup's first request
742 // went out before it became a tab; everything after presents as Chrome.
743 if (!desktop) await presentAsChrome(cdp, host);
@@ -885,11 +887,17 @@ const make = Effect.gen(function* () {
887 page.on("crash", () => dropTab(tab, true));
888 tabs.set(key, tab);
889 reportLiveTabs();
888 - // A popup is already loading its own URL, and the desktop loads its tab's.
889 - if (!adopted && !desktop && snapshot.navStatus._tag === "Loading") {
890 - tab.initialNavigation = page
891 - .goto(snapshot.navStatus.url, { waitUntil: "commit", timeout: NAVIGATION_TIMEOUT_MS })
892 - .then(constVoid);
890 + // Existing desktop and popup PDFs can start loading before interception attaches.
891 + if (
892 + snapshot.navStatus._tag === "Loading" &&
893 + ((!adopted && !desktop) || isPdfAssetUrl(snapshot.navStatus.url))
894 + ) {
895 + const options = { waitUntil: "commit", timeout: NAVIGATION_TIMEOUT_MS } as const;
896 + tab.initialNavigation = (
897 + (desktop || adopted) && page.url() === snapshot.navStatus.url
898 + ? page.reload(options)
899 + : page.goto(snapshot.navStatus.url, options)
900 + ).then(constVoid);
901
902 void tab.initialNavigation.catch(constVoid);
903 }
apps/web/src/browser/ServerBrowserSurface.tsx
+14 -4
@@ -147,6 +147,7 @@ export function ServerBrowserSurface(props: {
147 readonly onControl?: (control: PreviewStreamControl | null) => void;
148 readonly onPopup?: (tabId: string) => void;
149 readonly className?: string;
150 + readonly pdfUrl?: string | null;
151 readonly ref?: Ref<ServerBrowserHandle>;
152 }) {
153 const {
@@ -161,6 +162,7 @@ export function ServerBrowserSurface(props: {
162 onControl,
163 onPopup,
164 className,
165 + pdfUrl = null,
166 ref,
167 } = props;
168 const access = usePreviewStreamAccess(environmentId);
@@ -307,9 +309,9 @@ export function ServerBrowserSurface(props: {
309 reload: (options) =>
310 send({ type: "reload", ...(options?.ignoreCache ? { ignoreCache: true } : {}) }),
311 viewport: (setting) => send({ type: "viewport", setting }),
310 - canvas: () => (hasFrameRef.current ? canvasRef.current : null),
312 + canvas: () => (!pdfUrl && hasFrameRef.current ? canvasRef.current : null),
313 }),
312 - [send],
314 + [pdfUrl, send],
315 );
316
317 useEffect(() => {
@@ -734,6 +736,14 @@ export function ServerBrowserSurface(props: {
736 ) : null}
737 </div>
738 <div className="relative min-h-0 flex-1">
739 + {pdfUrl ? (
740 + <embed
741 + src={pdfUrl}
742 + type="application/pdf"
743 + title="PDF document"
744 + className="absolute inset-0 z-10 size-full border-0"
745 + />
746 + ) : null}
747 <canvas
748 ref={canvasRef}
749 className="block size-full touch-none object-contain"
@@ -744,7 +754,7 @@ export function ServerBrowserSurface(props: {
754 onMouseDown={(event) => event.preventDefault()}
755 onContextMenu={(event) => event.preventDefault()}
756 />
747 - {agentCursor && control?.controller !== "you" ? (
757 + {!pdfUrl && agentCursor && control?.controller !== "you" ? (
758 <AgentCursorMark
759 {...agentCursor}
760 controller={control?.controller === "agent" ? "agent" : "none"}
@@ -760,7 +770,7 @@ export function ServerBrowserSurface(props: {
770 autoComplete="off"
771 autoCorrect="off"
772 spellCheck={false}
763 - disabled={control?.controller !== "you"}
773 + disabled={pdfUrl !== null || control?.controller !== "you"}
774 defaultValue={INPUT_SENTINEL}
775 // The caret must sit after the sentinel for a deletion to have something to delete.
776 onFocus={(event) => resetInput(event.currentTarget)}
apps/web/src/browser/serverPictureInPicture.test.ts new
+90
@@ -0,0 +1,90 @@
1 +import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
3 +
4 +import { applyPreviewServerSnapshot, resetPreviewStateForTests } from "~/previewStateStore";
5 +import { closeServerPictureInPicture, openServerPictureInPicture } from "./serverPictureInPicture";
6 +
7 +vi.mock("~/state/previewStream", () => ({
8 + readPreviewStreamAccess: async () => ({}),
9 +}));
10 +vi.mock("@t3tools/client-runtime/preview/server-browser-stream", () => ({
11 + createPreviewFramePainter: () => ({ paint: vi.fn(), stop: vi.fn() }),
12 + createPreviewStreamClient: () => ({ stop: vi.fn() }),
13 +}));
14 +
15 +const ref = {
16 + environmentId: EnvironmentId.make("environment"),
17 + threadId: ThreadId.make("thread"),
18 +};
19 +const stopTrack = vi.fn();
20 +const exitPictureInPicture = vi.fn(async () => {});
21 +
22 +function navigate(url: string, tabId = "tab") {
23 + applyPreviewServerSnapshot(ref, {
24 + threadId: ref.threadId,
25 + tabId,
26 + navStatus: { _tag: "Success", url, title: "Document" },
27 + canGoBack: true,
28 + canGoForward: false,
29 + updatedAt: new Date().toISOString(),
30 + });
31 +}
32 +
33 +beforeEach(() => {
34 + vi.clearAllMocks();
35 + resetPreviewStateForTests();
36 + const video = {
37 + style: { cssText: "" },
38 + readyState: 4,
39 + play: async () => {},
40 + addEventListener: vi.fn(),
41 + removeEventListener: vi.fn(),
42 + remove: vi.fn(),
43 + requestPictureInPicture: vi.fn(async () => {}),
44 + };
45 + vi.stubGlobal("HTMLMediaElement", { HAVE_METADATA: 1 });
46 + vi.stubGlobal("document", {
47 + pictureInPictureEnabled: true,
48 + pictureInPictureElement: video,
49 + exitPictureInPicture,
50 + body: { append: vi.fn() },
51 + createElement: (tag: string) =>
52 + tag === "video"
53 + ? video
54 + : {
55 + getContext: () => ({ fillRect: vi.fn() }),
56 + captureStream: () => ({ getTracks: () => [{ stop: stopTrack }] }),
57 + },
58 + });
59 + navigate("https://environment.test/api/assets/token/index.html");
60 +});
61 +
62 +afterEach(() => {
63 + closeServerPictureInPicture();
64 + resetPreviewStateForTests();
65 + vi.unstubAllGlobals();
66 +});
67 +
68 +it("closes the video window and stream when its tab becomes a client-rendered PDF", async () => {
69 + await openServerPictureInPicture({ ...ref, tabId: "tab", seed: null });
70 + navigate("https://environment.test/api/assets/token/guide.PDF#page=2");
71 + expect(exitPictureInPicture).toHaveBeenCalledOnce();
72 + expect(stopTrack).toHaveBeenCalledOnce();
73 +});
74 +
75 +it("keeps PiP for ordinary navigation and PDFs in another tab", async () => {
76 + await openServerPictureInPicture({ ...ref, tabId: "tab", seed: null });
77 + navigate("https://environment.test/api/assets/token/guide.pdf", "another-tab");
78 + navigate("https://example.com/paper.pdf");
79 + navigate("https://environment.test/api/assets/token/next.html");
80 + expect(exitPictureInPicture).not.toHaveBeenCalled();
81 + expect(stopTrack).not.toHaveBeenCalled();
82 +});
83 +
84 +it("stops observing navigation when a PiP session closes", async () => {
85 + await openServerPictureInPicture({ ...ref, tabId: "tab", seed: null });
86 + closeServerPictureInPicture();
87 + navigate("https://environment.test/api/assets/token/guide.pdf");
88 + expect(exitPictureInPicture).toHaveBeenCalledOnce();
89 + expect(stopTrack).toHaveBeenCalledOnce();
90 +});
apps/web/src/browser/serverPictureInPicture.ts
+24 -3
@@ -3,10 +3,14 @@ import {
3 createPreviewStreamClient,
4 type PreviewStreamClient,
5 } from "@t3tools/client-runtime/preview/server-browser-stream";
6 -import type { EnvironmentId } from "@t3tools/contracts";
6 +import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
7 +import { scopedThreadKey } from "@t3tools/client-runtime/environment";
8 +import { previewPdfAssetUrl } from "@t3tools/shared/preview";
9 import { useSyncExternalStore } from "react";
10
11 import { readPreviewStreamAccess } from "~/state/previewStream";
12 +import { previewStateAtom, type ThreadPreviewState } from "~/previewStateStore";
13 +import { appAtomRegistry } from "~/rpc/atomRegistry";
14
15 interface WebKitVideo {
16 webkitSetPresentationMode?: (mode: string) => void;
@@ -62,7 +66,7 @@ export function closeServerPictureInPicture(): void {
66 /** Open during user activation, seeding the video with the currently visible frame. */
67 export async function openServerPictureInPicture(input: {
68 readonly environmentId: EnvironmentId;
65 - readonly threadId: string;
69 + readonly threadId: ThreadId;
70 readonly tabId: string;
71 readonly seed: HTMLCanvasElement | null;
72 }): Promise<void> {
@@ -90,6 +94,7 @@ export async function openServerPictureInPicture(input: {
94 let stopped = false;
95 let refusals = 0;
96 let retryTimer: ReturnType<typeof setTimeout> | null = null;
97 + let stopWatchingPreview = () => {};
98 const onLeave = () => {
99 if (active === current) closeServerPictureInPicture();
100 };
@@ -136,6 +141,7 @@ export async function openServerPictureInPicture(input: {
141 key: serverPictureInPictureKey(input.threadId, input.tabId),
142 stop: () => {
143 stopped = true;
144 + stopWatchingPreview();
145 if (retryTimer !== null) clearTimeout(retryTimer);
146 client?.stop();
147 painter.stop();
@@ -172,5 +178,20 @@ export async function openServerPictureInPicture(input: {
178 onLeave();
179 throw error;
180 }
175 - if (active === current) void connect(false);
181 + if (active === current) {
182 + const atom = previewStateAtom(scopedThreadKey(input));
183 + const closeForPdf = (state: ThreadPreviewState) => {
184 + const navigation = state.sessions[input.tabId]?.navStatus;
185 + if (
186 + navigation?._tag === "Success" &&
187 + previewPdfAssetUrl(navigation.url, navigation.url) !== null
188 + ) {
189 + onLeave();
190 + }
191 + };
192 + // PDFs render in the client and cannot appear in the server's video stream.
193 + stopWatchingPreview = appAtomRegistry.subscribe(atom, closeForPdf);
194 + closeForPdf(appAtomRegistry.get(atom));
195 + if (active === current) void connect(false);
196 + }
197 }
apps/web/src/components/files/BrowserDocumentFrame.tsx
+5 -8
@@ -34,8 +34,6 @@ import { readLocalApi } from "~/localApi";
34 import { cn } from "~/lib/utils";
35 import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";
36
37 -const PDF_VIEWER_FRAGMENT = "#toolbar=0&view=FitH";
38 -
37 /**
38 * The page reports the keys, and a page script can report any key it likes,
39 * so only commands that change what the reader sees are here, never one that
@@ -65,8 +63,7 @@ export const isPdfPreviewFile = (path: string): boolean =>
63
64 /**
65 * HTML runs in a sandboxed frame with an opaque origin, so a page cannot reach
68 - * the app's session or storage. The built-in PDF viewer needs an unsandboxed
69 - * frame; a PDF runs no scripts.
66 + * the app's session or storage. PDFs use the browser's native viewer.
67 */
68 export function BrowserDocumentFrame(props: {
69 readonly src: string;
@@ -77,12 +74,12 @@ export function BrowserDocumentFrame(props: {
74 }) {
75 const className = "min-h-0 flex-1 border-0 bg-white";
76 return props.pdf ? (
80 - // oxlint-disable-next-line react/iframe-missing-sandbox -- the built-in PDF viewer needs an unsandboxed frame.
81 - <iframe
77 + <embed
78 key={props.src}
83 - src={`${props.src}${PDF_VIEWER_FRAGMENT}`}
79 + src={props.src}
80 + type="application/pdf"
81 title={props.title}
85 - className={className}
82 + className="min-h-0 w-full flex-1 border-0"
83 />
84 ) : props.htmlRender ? (
85 <HtmlRenderDocument
apps/web/src/components/preview/PreviewView.tsx
+10 -1
@@ -18,7 +18,11 @@ import {
18 PREVIEW_ZOOM_LEVELS,
19 type PreviewAdjustInput,
20 } from "@t3tools/contracts";
21 -import { normalizePreviewUrl, resolveAddressBarInput } from "@t3tools/shared/preview";
21 +import {
22 + normalizePreviewUrl,
23 + resolveAddressBarInput,
24 + previewPdfAssetUrl,
25 +} from "@t3tools/shared/preview";
26 import { useEffect, useEffectEvent, useRef, useState } from "react";
27
28 import {
@@ -997,6 +1001,11 @@ export function PreviewView({
1001 environmentId={threadRef.environmentId}
1002 threadId={threadRef.threadId}
1003 tabId={snapshot.tabId}
1004 + pdfUrl={
1005 + navStatus._tag === "Success"
1006 + ? previewPdfAssetUrl(url, environmentHttpBaseUrl)
1007 + : null
1008 + }
1009 visible={visible}
1010 onFirstFrame={() => setServerFrameTabId(runtimeTabId)}
1011 onControl={(control) =>
apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx
+11 -1
@@ -1,6 +1,8 @@
1 "use client";
2
3 import { FILL_PREVIEW_VIEWPORT, type ScopedThreadRef } from "@t3tools/contracts";
4 +import { previewPdfAssetUrl } from "@t3tools/shared/preview";
5 +import { useEnvironmentHttpBaseUrl } from "~/state/environments";
6 import { PanelRightIcon, PictureInPicture2, XIcon } from "lucide-react";
7 import {
8 type PointerEvent as ReactPointerEvent,
@@ -114,6 +116,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, miniPlayer }: Props) {
116 }
117
118 function BrowserMiniPlayer({ threadRef, tabId, miniPlayer }: Props & { readonly tabId: string }) {
119 + const httpBaseUrl = useEnvironmentHttpBaseUrl(threadRef.environmentId);
120 const previewState = useThreadPreviewState(threadRef);
121 const snapshot = previewState.sessions[tabId] ?? null;
122 const runtimeTabId = previewRuntimeTabId(threadRef, previewState.serverEpoch, tabId);
@@ -171,8 +174,14 @@ function BrowserMiniPlayer({ threadRef, tabId, miniPlayer }: Props & { readonly
174 };
175
176 if (!snapshot) return null;
177 + const pdfUrl =
178 + snapshot.navStatus._tag === "Success"
179 + ? previewPdfAssetUrl(snapshot.navStatus.url, httpBaseUrl)
180 + : null;
181 const poppedOut = serverTab ? serverPictureInPicture : Boolean(desktopOverlay?.pictureInPicture);
175 - const canPopOut = serverTab ? supportsServerPictureInPicture() : true;
182 + const canPopOut = serverTab
183 + ? poppedOut || (pdfUrl === null && supportsServerPictureInPicture())
184 + : true;
185
186 return (
187 <MiniPlayerShell
@@ -219,6 +228,7 @@ function BrowserMiniPlayer({ threadRef, tabId, miniPlayer }: Props & { readonly
228 environmentId={threadRef.environmentId}
229 threadId={threadRef.threadId}
230 tabId={tabId}
231 + pdfUrl={pdfUrl}
232 visible
233 followSize={false}
234 controlPosition="bottom"
packages/shared/src/preview.test.ts
+55
@@ -6,8 +6,63 @@ import {
6 normalizePreviewUrl,
7 PreviewUrlNormalizationError,
8 resolveAddressBarInput,
9 + previewPdfAssetUrl,
10 } from "./preview.ts";
11
12 +describe("previewPdfAssetUrl", () => {
13 + it.each([
14 + "http://localhost:6497",
15 + "https://host.tailnet.test",
16 + "https://environment.tunnel.test",
17 + ])("loads PDF bytes through the client's connection at %s", (base) => {
18 + expect(
19 + previewPdfAssetUrl(
20 + "http://127.0.0.1:14537/api/assets/signed-token/Study%20guide.PDF?revision=2#page=8",
21 + base,
22 + ),
23 + ).toBe(`${base}/api/assets/signed-token/Study%20guide.PDF?revision=2#page=8`);
24 + });
25 +
26 + it.each([
27 + "http://localhost:6497/api/assets/token/index.html",
28 + "https://example.com/paper.pdf",
29 + "file:///api/assets/token/paper.pdf",
30 + "javascript:alert(1)",
31 + "invalid",
32 + ])("leaves non-asset documents on their browser session: %s", (url) => {
33 + expect(previewPdfAssetUrl(url, "https://environment.test")).toBeNull();
34 + });
35 +
36 + it("waits for the environment connection", () => {
37 + expect(previewPdfAssetUrl("http://localhost/api/assets/token/paper.pdf", null)).toBeNull();
38 + });
39 +
40 + it.each(["another-environment.test", "127.0.0.2.example.com", "128.0.0.1"])(
41 + "preserves matching PDF URLs on unrelated host %s",
42 + (host) => {
43 + const source = `https://${host}/api/assets/token/guide.pdf?revision=2#page=3`;
44 + expect(previewPdfAssetUrl(source, "https://environment.test")).toBe(source);
45 + },
46 + );
47 +
48 + it("keeps URLs from the connected environment", () => {
49 + const source = "https://environment.test/api/assets/token/guide.pdf#page=2";
50 + expect(previewPdfAssetUrl(source, "https://environment.test")).toBe(source);
51 + });
52 +
53 + it.each(["127.0.0.2", "127.255.255.254", "localhost.", "[::1]", "0.0.0.0"])(
54 + "remaps local assets on %s through the client connection",
55 + (host) => {
56 + expect(
57 + previewPdfAssetUrl(
58 + `http://${host}:14537/api/assets/token/guide.pdf?revision=2#page=3`,
59 + "https://remote.test",
60 + ),
61 + ).toBe("https://remote.test/api/assets/token/guide.pdf?revision=2#page=3");
62 + },
63 + );
64 +});
65 +
66 describe("resolveAddressBarInput", () => {
67 it("opens what users type as addresses", () => {
68 expect(resolveAddressBarInput("localhost:5173")).toBe("http://localhost:5173/");
packages/shared/src/preview.ts
+29
@@ -1,8 +1,37 @@
1 import * as Schema from "effect/Schema";
2
3 +import { isLocalLoopbackHost } from "./hostClassification.ts";
4 +
5 const TAB_ID_PREFIX = "tab_";
6 let nextPreviewTabSequence = 0;
7
8 +export function previewPdfAssetUrl(rawUrl: string, httpBaseUrl: string | null): string | null {
9 + if (httpBaseUrl === null) return null;
10 + try {
11 + const url = new URL(rawUrl);
12 + const baseUrl = new URL(httpBaseUrl);
13 + if (
14 + (url.protocol !== "http:" && url.protocol !== "https:") ||
15 + !url.pathname.startsWith("/api/assets/") ||
16 + !/\.pdf$/i.test(url.pathname)
17 + ) {
18 + return null;
19 + }
20 + if (
21 + url.origin !== baseUrl.origin &&
22 + !isLocalLoopbackHost(url.hostname) &&
23 + url.hostname !== "0.0.0.0"
24 + ) {
25 + return url.href;
26 + }
27 + // The browser may run on the host's loopback address. Fetch signed bytes
28 + // through this client's environment connection, including remote routes.
29 + return new URL(`${url.pathname}${url.search}${url.hash}`, baseUrl).href;
30 + } catch {
31 + return null;
32 + }
33 +}
34 +
35 export function newPreviewTabId(): string {
36 nextPreviewTabSequence += 1;
37 return `${TAB_ID_PREFIX}${nextPreviewTabSequence.toString(36)}`;
patches/react-native-pdf-jsi@5.0.0.patch new
+23
@@ -0,0 +1,23 @@
1 +diff --git a/android/build.gradle b/android/build.gradle
2 +--- a/android/build.gradle
3 ++++ b/android/build.gradle
4 +@@ -128,7 +128,7 @@
5 + buildTypes {
6 + release {
7 + minifyEnabled false
8 +- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
9 ++ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
10 +
11 + externalNativeBuild {
12 + cmake {
13 +diff --git a/android/src/main/java/org/wonday/pdf/RNPDFPackage.java b/android/src/main/java/org/wonday/pdf/RNPDFPackage.java
14 +--- a/android/src/main/java/org/wonday/pdf/RNPDFPackage.java
15 ++++ b/android/src/main/java/org/wonday/pdf/RNPDFPackage.java
16 +@@ -11,3 +11,7 @@
17 + public class RNPDFPackage implements ReactPackage {
18 +
19 ++ static {
20 ++ System.loadLibrary("NitroPdfJsi");
21 ++ }
22 ++
23 + @Override
pnpm-lock.yaml
+100
@@ -180,6 +180,7 @@ patchedDependencies:
180 node-pty@1.2.0-beta.15: f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651
181 react-native-gesture-handler@3.3.0: abe20e1d1c23549297cbbc818e14fe479b41455930d9663135d6b40fe359b626
182 react-native-keyboard-controller@1.22.7: f28d08f1233e3cce8b9324b4357d2b10f1ee040b8051bc87235b0fb95069b9bb
183 + react-native-pdf-jsi@5.0.0: 6f52854210f61bef499850ebd498229a111bc34ec5b2a4925e644f2f48f42760
184 react-native-webview@14.0.1: 81caa279ec3dc1f81209062133b66e8f824e13f106cca57f1fa732a72c2ab378
185
186 importers:
@@ -353,6 +354,9 @@ importers:
354 '@react-native-ai/apple':
355 specifier: 0.12.0
356 version: 0.12.0(patch_hash=2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))
357 + '@react-native-async-storage/async-storage':
358 + specifier: 3.1.1
359 + version: 3.1.1(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
360 '@react-native-menu/menu':
361 specifier: ^2.0.0
362 version: 2.0.0(patch_hash=a4866ecfcd44f318043de839d20110c17e14909004900f002ffe12050376f2ba)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
@@ -548,6 +552,9 @@ importers:
552 react-native:
553 specifier: 0.88.0
554 version: 0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6)
555 + react-native-blob-util:
556 + specifier: 0.25.1
557 + version: 0.25.1(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
558 react-native-enriched-markdown:
559 specifier: file:deps/react-native-enriched-markdown-1.2.0-t3.15.tgz
560 version: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz(katex@0.16.47)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
@@ -560,6 +567,12 @@ importers:
567 react-native-keyboard-controller:
568 specifier: 1.22.7
569 version: 1.22.7(patch_hash=f28d08f1233e3cce8b9324b4357d2b10f1ee040b8051bc87235b0fb95069b9bb)(react-native-reanimated@4.7.1(react-native-worklets@0.13.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
570 + react-native-nitro-modules:
571 + specifier: 0.37.1
572 + version: 0.37.1(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
573 + react-native-pdf-jsi:
574 + specifier: 5.0.0
575 + version: 5.0.0(patch_hash=6f52854210f61bef499850ebd498229a111bc34ec5b2a4925e644f2f48f42760)(cf7d6840207b805fdc65940b34f32bb4)
576 react-native-reanimated:
577 specifier: 4.7.1
578 version: 4.7.1(react-native-worklets@0.13.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
@@ -5505,6 +5518,12 @@ packages:
5518 peerDependencies:
5519 react-native: '>=0.76.0'
5520
5521 + '@react-native-async-storage/async-storage@3.1.1':
5522 + resolution: {integrity: sha512-z+PnLz1n6ECKhgoHZHkfc+dijXZEyZnNFSajbtE0NEbsJhmX8x9GlOeiMQIKX2E4DUqPSgfIh4FYBv1M49KgPQ==}
5523 + peerDependencies:
5524 + react: '*'
5525 + react-native: '*'
5526 +
5527 '@react-native-masked-view/masked-view@0.3.2':
5528 resolution: {integrity: sha512-XwuQoW7/GEgWRMovOQtX3A4PrXhyaZm0lVUiY8qJDvdngjLms9Cpdck6SmGAUNqQwcj2EadHC1HwL0bEyoa/SQ==}
5529 peerDependencies:
@@ -5579,6 +5598,9 @@ packages:
5598 resolution: {integrity: sha512-iPV2HNXlPs7xQDBJJGIjkH0x2psZwJeRIEpfSqxgqLaO5eEfE2Ccicfz2OBHBcIC5jKGGa4IoI/e26zMNDuTMQ==}
5599 engines: {node: ^22.13.0 || ^24.3.0 || >= 26.0.0}
5600
5601 + '@react-native/normalize-color@2.1.0':
5602 + resolution: {integrity: sha512-Z1jQI2NpdFJCVgpY+8Dq/Bt3d+YUi1928Q+/CZm/oh66fzM0RUl54vvuXlPJKybH4pdCZey1eDTPaLHkMPNgWA==}
5603 +
5604 '@react-native/normalize-colors@0.88.0':
5605 resolution: {integrity: sha512-eZCu3tGAQCfvMCPQJVY4dmoMX8ZZYBvqIGHX7lwOYyzNK+Dl8e5ky7ZoXub1Rq75oSrQXNNmSP2CDjNNXXZpFQ==}
5606
@@ -8369,6 +8391,9 @@ packages:
8391 resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}
8392 engines: {node: '>= 0.8'}
8393
8394 + deprecated-react-native-prop-types@2.3.0:
8395 + resolution: {integrity: sha512-pWD0voFtNYxrVqvBMYf5gq3NA2GCpfodS1yNynTPc93AYA/KEMGeWDqqeUB6R2Z9ZofVhks2aeJXiuQqKNpesA==}
8396 +
8397 dequal@2.0.3:
8398 resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}
8399 engines: {node: '>=6'}
@@ -9544,6 +9569,9 @@ packages:
9569 idb-keyval@6.2.1:
9570 resolution: {integrity: sha512-8Sb3veuYCyrZL+VBt9LJfZjLUPWVvqn8tG28VqYNFCo43KHcKuq+b4EiXGeuaLAQWL2YmyDgMp2aSpH9JHsEQg==}
9571
9572 + idb@8.0.3:
9573 + resolution: {integrity: sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==}
9574 +
9575 ignore@5.3.2:
9576 resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
9577 engines: {node: '>= 4'}
@@ -10993,6 +11021,9 @@ packages:
11021 resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==}
11022 engines: {node: '>= 6'}
11023
11024 + prop-types@15.8.1:
11025 + resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}
11026 +
11027 proper-lockfile@4.1.2:
11028 resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}
11029
@@ -11108,6 +11139,9 @@ packages:
11139 react:
11140 optional: true
11141
11142 + react-is@16.13.1:
11143 + resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
11144 +
11145 react-is@17.0.2:
11146 resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==}
11147
@@ -11123,6 +11157,12 @@ packages:
11157 '@types/react': '>=18'
11158 react: '>=18'
11159
11160 + react-native-blob-util@0.25.1:
11161 + resolution: {integrity: sha512-HMzab2SL8h48pvfufji0TKdet/jnNvamxYmYyNqTV5YOge00V28ycdc3S4leHjGXMJ1+fS2j2SrQ3aG5pzbx1w==}
11162 + peerDependencies:
11163 + react: '*'
11164 + react-native: '*'
11165 +
11166 react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz:
11167 resolution: {integrity: sha512-p9o8zNoVoNwqdlG8a9Fvhj0RFUjmpE6VecwOVsO6a8Alj2HPfCDzeLBq0SFn2KdUYX32MC2fH1gJJs/HyfP5Mg==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz}
11168 version: 1.2.0-t3.15
@@ -11159,6 +11199,21 @@ packages:
11199 react-native: '*'
11200 react-native-reanimated: '>=3.0.0'
11201
11202 + react-native-nitro-modules@0.37.1:
11203 + resolution: {integrity: sha512-KpW6EQVQ/bfegpCGxN9Be+ndvsfj56t4IESEvCASu9gWpJa/NDfHpIeIwCOvZQ3eXmLEj6YD4wCLqcC1FJPr2w==}
11204 + peerDependencies:
11205 + react: '*'
11206 + react-native: '*'
11207 +
11208 + react-native-pdf-jsi@5.0.0:
11209 + resolution: {integrity: sha512-yemeI1tWRfG0IUbUcc/aD757kBI0qCLqFZJ6pTd4eAIsnuNwpqahAviUj7C3JG2Ddl5LEElwwFx49nUi1RXZmg==}
11210 + peerDependencies:
11211 + '@react-native-async-storage/async-storage': '>=1.17.0'
11212 + react: '*'
11213 + react-native: '*'
11214 + react-native-blob-util: '>=0.13.7'
11215 + react-native-nitro-modules: ^0.37.1
11216 +
11217 react-native-reanimated@4.7.1:
11218 resolution: {integrity: sha512-HviDFSZ6V4KTRsrLS6hRbBJ4j63l/L8a5az0EoWdJwaMLYnBNyYISTDxwXpEYkMbAbLzCMCviIdiOxXHYQWcNA==}
11219 peerDependencies:
@@ -16194,6 +16249,12 @@ snapshots:
16249 react-native: 0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6)
16250 zod: 4.4.3
16251
16252 + '@react-native-async-storage/async-storage@3.1.1(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)':
16253 + dependencies:
16254 + idb: 8.0.3
16255 + react: 19.3.0
16256 + react-native: 0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6)
16257 +
16258 '@react-native-masked-view/masked-view@0.3.2(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)':
16259 dependencies:
16260 react: 19.3.0
@@ -16331,6 +16392,8 @@ snapshots:
16392 - supports-color
16393 - utf-8-validate
16394
16395 + '@react-native/normalize-color@2.1.0': {}
16396 +
16397 '@react-native/normalize-colors@0.88.0': {}
16398
16399 '@react-native/virtualized-lists@0.88.0(@types/react@19.3.0)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)':
@@ -19089,6 +19152,12 @@ snapshots:
19152
19153 depd@2.0.0: {}
19154
19155 + deprecated-react-native-prop-types@2.3.0:
19156 + dependencies:
19157 + '@react-native/normalize-color': 2.1.0
19158 + invariant: 2.2.4
19159 + prop-types: 15.8.1
19160 +
19161 dequal@2.0.3: {}
19162
19163 destr@2.0.5: {}
@@ -20409,6 +20478,8 @@ snapshots:
20478 idb-keyval@6.2.1:
20479 optional: true
20480
20481 + idb@8.0.3: {}
20482 +
20483 ignore@5.3.2: {}
20484
20485 ignore@7.0.5: {}
@@ -22264,6 +22335,12 @@ snapshots:
22335 kleur: 3.0.3
22336 sisteransi: 1.0.5
22337
22338 + prop-types@15.8.1:
22339 + dependencies:
22340 + loose-envify: 1.4.0
22341 + object-assign: 4.1.1
22342 + react-is: 16.13.1
22343 +
22344 proper-lockfile@4.1.2:
22345 dependencies:
22346 graceful-fs: 4.2.11
@@ -22414,6 +22491,8 @@ snapshots:
22491 optionalDependencies:
22492 react: 19.3.0
22493
22494 + react-is@16.13.1: {}
22495 +
22496 react-is@17.0.2: {}
22497
22498 react-is@18.3.1: {}
@@ -22438,6 +22517,12 @@ snapshots:
22517 transitivePeerDependencies:
22518 - supports-color
22519
22520 + react-native-blob-util@0.25.1(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0):
22521 + dependencies:
22522 + base-64: 1.0.0
22523 + react: 19.3.0
22524 + react-native: 0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6)
22525 +
22526 react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz(katex@0.16.47)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0):
22527 dependencies:
22528 react: 19.3.0
@@ -22469,6 +22554,21 @@ snapshots:
22554 react-native-is-edge-to-edge: 1.3.1(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
22555 react-native-reanimated: 4.7.1(react-native-worklets@0.13.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
22556
22557 + react-native-nitro-modules@0.37.1(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0):
22558 + dependencies:
22559 + react: 19.3.0
22560 + react-native: 0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6)
22561 +
22562 + react-native-pdf-jsi@5.0.0(patch_hash=6f52854210f61bef499850ebd498229a111bc34ec5b2a4925e644f2f48f42760)(cf7d6840207b805fdc65940b34f32bb4):
22563 + dependencies:
22564 + '@react-native-async-storage/async-storage': 3.1.1(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
22565 + crypto-js: 4.2.0
22566 + deprecated-react-native-prop-types: 2.3.0
22567 + react: 19.3.0
22568 + react-native: 0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6)
22569 + react-native-blob-util: 0.25.1(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
22570 + react-native-nitro-modules: 0.37.1(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
22571 +
22572 react-native-reanimated@4.7.1(react-native-worklets@0.13.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0):
22573 dependencies:
22574 react: 19.3.0
pnpm-workspace.yaml
+1
@@ -333,6 +333,7 @@ patchedDependencies:
333 node-pty@1.2.0-beta.15: patches/node-pty@1.2.0-beta.15.patch
334 react-native-gesture-handler@3.3.0: patches/react-native-gesture-handler@3.3.0.patch
335 react-native-keyboard-controller@1.22.7: patches/react-native-keyboard-controller@1.22.7.patch
336 + react-native-pdf-jsi@5.0.0: patches/react-native-pdf-jsi@5.0.0.patch
337 # Android: a nested WebView hands a vertical drag to its scrolling parent at the page's edge.
338 react-native-webview@14.0.1: patches/react-native-webview@14.0.1.patch
339 "@expo/ui@58.0.20": patches/@expo__ui@58.0.20.patch
third-party-licenses.config.json
+27
@@ -150,6 +150,33 @@
150 }
151 ],
152 "packageOverrides": [
153 + {
154 + "name": "@react-native-async-storage/async-storage",
155 + "version": "3.1.1",
156 + "sourceUrl": "https://github.com/react-native-async-storage/async-storage",
157 + "generatedNotice": {
158 + "licenseId": "MIT",
159 + "copyrights": ["Copyright (c) 2025 Krzysztof Borowy"]
160 + }
161 + },
162 + {
163 + "name": "deprecated-react-native-prop-types",
164 + "version": "2.3.0",
165 + "sourceUrl": "https://github.com/facebookarchive/react-native-deprecated-modules",
166 + "generatedNotice": {
167 + "licenseId": "MIT",
168 + "copyrights": ["Copyright (c) Meta Platforms, Inc. and affiliates."]
169 + }
170 + },
171 + {
172 + "name": "@react-native/normalize-color",
173 + "version": "2.1.0",
174 + "sourceUrl": "https://github.com/facebook/react-native",
175 + "generatedNotice": {
176 + "licenseId": "MIT",
177 + "copyrights": ["Copyright (c) Meta Platforms, Inc. and affiliates."]
178 + }
179 + },
180 {
181 "name": "@bufbuild/protobuf",
182 "version": "1.10.0",