TypeScript
fix(files): load PDFs in browser previews (#21095)
Yash Singh1e2f88fde7cb
diff --git a/apps/desktop/src/electron/ElectronProtocol.test.ts b/apps/desktop/src/electron/ElectronProtocol.test.tsindex 315f6b5510a..4c9da1dd925 100644--- a/apps/desktop/src/electron/ElectronProtocol.test.ts+++ b/apps/desktop/src/electron/ElectronProtocol.test.ts@@ -322,6 +322,7 @@ describe("ElectronProtocol", () => {]);assert.deepEqual(directives["media-src"], ["'self'", "t3code:", "blob:", "http:", "https:"]);assert.deepEqual(directives["frame-src"], ["'self'", "blob:", "http:", "https:"]);+ assert.deepEqual(directives["object-src"], ["'self'", "blob:", "http:", "https:"]);assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);});});diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.tsindex 21cf8994800..9abe17d7751 100644--- a/apps/desktop/src/electron/ElectronProtocol.ts+++ b/apps/desktop/src/electron/ElectronProtocol.ts@@ -95,6 +95,7 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat`font-src 'self' ${input.scheme}: data:`,"worker-src 'self' blob:","frame-src 'self' blob: http: https:",+ "object-src 'self' blob: http: https:","form-action 'self'",].join("; ");}diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.tsindex b0bda47dc32..d1d0398e094 100644--- a/apps/mobile/app.config.ts+++ b/apps/mobile/app.config.ts@@ -317,6 +317,7 @@ const config: ExpoConfig = {},plugins: ["expo-asset",+ "react-native-pdf-jsi",["expo-font",{diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex e0c3567b725..fc6eada47d6 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -58,6 +58,7 @@"@noble/curves": "catalog:","@pierre/diffs": "catalog:","@react-native-ai/apple": "0.12.0",+ "@react-native-async-storage/async-storage": "3.1.1","@react-native-menu/menu": "^2.0.0","@react-navigation/elements": "2.9.45","@react-navigation/native": "7.5.1",@@ -123,10 +124,13 @@"react": "catalog:","react-dom": "catalog:","react-native": "0.88.0",+ "react-native-blob-util": "0.25.1","react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.15.tgz","react-native-gesture-handler": "~3.3.0","react-native-image-viewing": "^0.2.2","react-native-keyboard-controller": "1.22.7",+ "react-native-nitro-modules": "0.37.1",+ "react-native-pdf-jsi": "5.0.0","react-native-reanimated": "4.7.1","react-native-safe-area-context": "~5.10.1","react-native-screens": "file:deps/react-native-screens-5.0.0-t3.27.tgz",diff --git a/apps/mobile/src/components/FilePreview.tsx b/apps/mobile/src/components/FilePreview.tsxindex 4bce87c3b13..179b48d1610 100644--- a/apps/mobile/src/components/FilePreview.tsx+++ b/apps/mobile/src/components/FilePreview.tsx@@ -2,12 +2,43 @@ import * as Dialog from "./ui/Dialog";import { useEffect, useEffectEvent } from "react";import { Modal, Pressable, View } from "react-native";import ImageViewing from "react-native-image-viewing";+import { useSafeAreaInsets } from "react-native-safe-area-context";import { openAttachmentInViewer } from "../lib/attachmentDownload";import type { ResolvedFilePreviewSource } from "./FilePreviewModal.types";import { MediaImagePreview } from "./MediaImagePreview";+import { PdfPreview } from "./PdfPreview";+import { ControlPill } from "./ui/ControlPill";import { AppText as Text } from "./ui/AppText";+function PdfDocumentPreview(props: {+ readonly source: ResolvedFilePreviewSource;+ readonly onRequestClose: () => void;+}) {+ const insets = useSafeAreaInsets();+ return (+ <Modal+ animationType="slide"+ onRequestClose={props.onRequestClose}+ statusBarTranslucent+ navigationBarTranslucent+ >+ <View+ className="flex-1 bg-card"+ style={{ paddingTop: insets.top, paddingBottom: insets.bottom }}+ >+ <View className="flex-row items-center gap-3 border-b border-border px-4 py-2">+ <Text className="flex-1 font-t3-semibold text-foreground" numberOfLines={1}>+ {props.source.name ?? "PDF"}+ </Text>+ <ControlPill label="Close" variant="pill" onPress={props.onRequestClose} />+ </View>+ <PdfPreview uri={props.source.uri} />+ </View>+ </Modal>+ );+}+function DocumentPreview(props: {readonly source: ResolvedFilePreviewSource;readonly onRequestClose: () => void;@@ -71,6 +102,7 @@ export function FilePreview(props: {readonly onRequestClose: () => void;readonly onOpenError?: (error: unknown) => void;}) {+ if (props.source.kind === "pdf") return <PdfDocumentPreview {...props} />;if (props.source.kind !== "image") return <DocumentPreview {...props} />;if (props.source.actionsSource) return <MediaImagePreview {...props} />;return (diff --git a/apps/mobile/src/components/PdfPreview.android.tsx b/apps/mobile/src/components/PdfPreview.android.tsxnew file mode 100644index 00000000000..5492c4ce7c6--- /dev/null+++ b/apps/mobile/src/components/PdfPreview.android.tsx@@ -0,0 +1,80 @@+import { useEffect, useRef, useState } from "react";+import { View } from "react-native";+import Pdf from "react-native-pdf-jsi";++import { FilePreviewLoading, FilePreviewNotice } from "../features/files/FilePreviewFeedback";+import { pdfInitialPage, pdfLinkUrl, preparePdfPreview } from "../lib/pdfPreview";+import { tryOpenExternalUrl } from "../lib/openExternalUrl";+import { ControlPill } from "./ui/ControlPill";++function NativePdfPreview(props: { readonly uri: string; readonly onRetry: () => void }) {+ const [localUri, setLocalUri] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const cached = useRef<Awaited<ReturnType<typeof preparePdfPreview>>>(null);++ useEffect(() => {+ const controller = new AbortController();+ void preparePdfPreview(props.uri, controller.signal)+ .then((file) => {+ if (controller.signal.aborted) file?.dispose();+ else {+ cached.current = file;+ setLocalUri(file?.uri ?? null);+ }+ })+ .catch((cause: unknown) => {+ if (!controller.signal.aborted) {+ setError(cause instanceof Error ? cause.message : "The PDF could not be loaded.");+ }+ });+ return () => {+ controller.abort();+ cached.current?.dispose();+ cached.current = null;+ };+ }, [props.uri]);++ if (error) {+ return (+ <View className="flex-1 gap-4 bg-card">+ <FilePreviewNotice title="Could not load PDF">{error}</FilePreviewNotice>+ <View className="items-center">+ <ControlPill label="Try again" variant="pill" onPress={props.onRetry} />+ </View>+ </View>+ );+ }+ if (localUri === null) return <FilePreviewLoading message="Loading PDF..." background="card" />;++ return (+ source={{ uri: localUri }}+ page={pdfInitialPage(props.uri)}+ fitPolicy={0}+ trustAllCerts={false}+ enableAnnotationRendering+ enableDoubleTapZoom+ onPressLink={(href) => {+ const url = pdfLinkUrl(href, props.uri);+ if (url !== null) void tryOpenExternalUrl(url, "file-preview");+ }}+ onError={() => {+ cached.current?.dispose();+ cached.current = null;+ setError("The PDF could not be rendered. It may be damaged or password protected.");+ }}+ style={{ flex: 1, width: "100%" }}+ />+ );+}++export function PdfPreview(props: { readonly uri: string }) {+ const [attempt, setAttempt] = useState(0);+ return (+ <NativePdfPreview+ key={`${props.uri}:${attempt}`}+ uri={props.uri}+ onRetry={() => setAttempt((value) => value + 1)}+ />+ );+}diff --git a/apps/mobile/src/components/PdfPreview.tsx b/apps/mobile/src/components/PdfPreview.tsxnew file mode 100644index 00000000000..07ad774d570--- /dev/null+++ b/apps/mobile/src/components/PdfPreview.tsx@@ -0,0 +1,29 @@+import { useState } from "react";+import { View } from "react-native";+import { WebView } from "react-native-webview";++import { FilePreviewLoading, FilePreviewNotice } from "../features/files/FilePreviewFeedback";++export function PdfPreview(props: { readonly uri: string }) {+ const [error, setError] = useState<string | null>(null);+ return (+ <View className="flex-1 bg-card">+ {error ? <FilePreviewNotice title="Could not load PDF">{error}</FilePreviewNotice> : null}+ <WebView+ source={{ uri: props.uri }}+ originWhitelist={["*"]}+ automaticallyAdjustContentInsets={false}+ contentInsetAdjustmentBehavior="never"+ startInLoadingState+ onError={(event) =>+ setError(event.nativeEvent.description || "The PDF could not be loaded.")+ }+ onHttpError={(event) =>+ setError(`The server returned HTTP ${event.nativeEvent.statusCode}.`)+ }+ renderLoading={() => <FilePreviewLoading message="Loading PDF..." background="card" />}+ style={{ flex: 1, backgroundColor: "transparent" }}+ />+ </View>+ );+}diff --git a/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx b/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsxindex b8d41d19850..4db00762add 100644--- a/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx+++ b/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx@@ -3,13 +3,9 @@ import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";import * as Dialog from "../../components/ui/Dialog";import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";import { createNativeStackNavigator } from "@react-navigation/native-stack";-import {- EnvironmentId,- FILL_PREVIEW_VIEWPORT,- ThreadId,- type PreviewSessionSnapshot,-} from "@t3tools/contracts";-import { normalizePreviewUrl } from "@t3tools/shared/preview";+import { EnvironmentId, ThreadId, type PreviewSessionSnapshot } from "@t3tools/contracts";+import { normalizePreviewUrl, previewPdfAssetUrl } from "@t3tools/shared/preview";+import * as Option from "effect/Option";import { useCallback, useEffect, useRef, useState } from "react";import { AppState, Platform, TextInput, View } from "react-native";import { useSafeAreaInsets } from "react-native-safe-area-context";@@ -18,6 +14,7 @@ import { ControlPill } from "../../components/ui/ControlPill";import { AppBar } from "../../components/ui/AppBar";import { useThreadServerBrowserTabs } from "../../state/preview";+import { usePreparedConnection } from "../../state/session";import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";import { BrowserTabMenu } from "./BrowserTabMenu";import { browserTabTitle, browserTabUrl, latestBrowserTab } from "./browserTabs";@@ -79,6 +76,8 @@ function BrowserPreviewScreen({}) {const insets = useSafeAreaInsets();const { themeVariables } = useAppearancePreferences();+ const prepared = usePreparedConnection(environmentId);+ const httpBaseUrl = Option.isSome(prepared) ? prepared.value.httpBaseUrl : null;const focused = useIsFocused();const [foreground, setForeground] = useState(AppState.currentState !== "background");const [selectedTabId, setSelectedTabId] = useState(initialTabId);@@ -88,6 +87,8 @@ function BrowserPreviewScreen({const streamRef = useRef<PreviewStreamRef>(null);const { tabs, loaded } = useThreadServerBrowserTabs({ environmentId, threadId, enabled: true });const tab = tabs.find((entry) => entry.tabId === selectedTabId) ?? latestBrowserTab(tabs);+ const pdfUri =+ tab?.navStatus._tag === "Success" ? previewPdfAssetUrl(tab.navStatus.url, httpBaseUrl) : null;const tabId = tab?.tabId ?? null;if (tabId !== null && tabId !== selectedTabId) {setPictureInPicture(NO_PICTURE_IN_PICTURE);@@ -121,7 +122,9 @@ function BrowserPreviewScreen({options={{ headerBackVisible: false }}actions={// Android WebView cannot play video in picture in picture.- Platform.OS === "ios" && pictureInPicture.supported+ Platform.OS === "ios" &&+ pictureInPicture.supported &&+ (pictureInPicture.active || pdfUri === null)? [{accessibilityLabel: pictureInPicture.active@@ -181,6 +184,7 @@ function BrowserPreviewScreen({environmentId={environmentId}threadId={threadId}tabId={tab.tabId}+ pdfUri={pdfUri}ref={streamRef}interactivebackground={themeVariables["--color-sheet-solid"]}diff --git a/apps/mobile/src/features/browser/PreviewStreamWebView.tsx b/apps/mobile/src/features/browser/PreviewStreamWebView.tsxindex bff1ce2e583..5737e45067e 100644--- a/apps/mobile/src/features/browser/PreviewStreamWebView.tsx+++ b/apps/mobile/src/features/browser/PreviewStreamWebView.tsx@@ -25,6 +25,7 @@ import { WebView } from "react-native-webview";import * as Clipboard from "expo-clipboard";import { AppText } from "../../components/ui/AppText";+import { PdfPreview } from "../../components/PdfPreview";import { downloadAndShareAttachment } from "../../lib/attachmentDownload";import { beginForegroundHandoff } from "../../lib/foreground-handoff";import { usePreviewStreamAccess } from "../../state/preview";@@ -56,6 +57,7 @@ type NativeStreamBridge = {/** True while frames show, so commands reach the page. Pass a stable function. */readonly onStreamingChange?: (streaming: boolean) => void;readonly compact?: boolean;+ readonly pdfUri?: string | null;};async function sendFilesToPage(chooser: PreviewStreamFileChooser, pick: boolean) {@@ -223,6 +225,7 @@ function PreviewStreamDocumentView({configuration,background,compact,+ pdfUri,onUnauthorized,onGone,onViewport,@@ -337,87 +340,94 @@ function PreviewStreamDocumentView({) : null}</View>) : null}- <WebView<object>- ref={webView}- source={source}- originWhitelist={["*"]}- scrollEnabled={false}- bounces={false}- mixedContentMode="always"- allowUniversalAccessFromFileURLs- contentInsetAdjustmentBehavior="never"- setSupportMultipleWindows={false}- allowsInlineMediaPlayback- allowsPictureInPictureMediaPlayback- mediaPlaybackRequiresUserAction={false}- style={{ flex: 1, backgroundColor: background }}- onError={() => fail("Browser viewer could not load. Reconnect to try again.")}- onHttpError={() => fail("Browser viewer could not load. Reconnect to try again.")}- onContentProcessDidTerminate={processTerminated}- onRenderProcessGone={processTerminated}- onShouldStartLoadWithRequest={(request) =>- request.url === "about:blank" || request.url === source.baseUrl- }- onMessage={(event) => {- if (!active.current || failed.current) return;- const message = previewStreamMessage(event.nativeEvent.data);- if (message === null) return;- switch (message.type) {- case "control": {- setControl(message);- const previousDialog = dialogRef.current;- dialogRef.current = message.dialog;- setPromptText((draft) => previewPromptText(previousDialog, message.dialog, draft));- onControl?.(message);- return;- }- case "unauthorized":- if (!onUnauthorized()) {- fail("This session can't open the browser stream. Reconnect to try again.");- }- return;- case "gone":- setGone(true);- fail("This tab was closed.");- onGone?.();- return;- case "hostSetup":- setHostSetup({ need: message.need, command: message.command });- fail(previewStreamHostSetupMessage(message));- return;- case "viewport":- onViewport?.(message);- return;- case "clipboard":- void Clipboard.setStringAsync(message.text).catch(() => undefined);- return;- case "download":- offerDownload(message);- return;- case "fileChooser":- setFileChooser(message.chooser);- return;- case "pictureInPicture":- onPictureInPicture?.(message, message.detail);- return;- case "status":- setStarted(true);- if (message.status === "error") {- fail(message.detail ?? "Browser stream failed.");+ <View className="relative flex-1">+ <WebView<object>+ ref={webView}+ source={source}+ originWhitelist={["*"]}+ scrollEnabled={false}+ bounces={false}+ mixedContentMode="always"+ allowUniversalAccessFromFileURLs+ contentInsetAdjustmentBehavior="never"+ setSupportMultipleWindows={false}+ allowsInlineMediaPlayback+ allowsPictureInPictureMediaPlayback+ mediaPlaybackRequiresUserAction={false}+ style={{ flex: 1, backgroundColor: background }}+ onError={() => fail("Browser viewer could not load. Reconnect to try again.")}+ onHttpError={() => fail("Browser viewer could not load. Reconnect to try again.")}+ onContentProcessDidTerminate={processTerminated}+ onRenderProcessGone={processTerminated}+ onShouldStartLoadWithRequest={(request) =>+ request.url === "about:blank" || request.url === source.baseUrl+ }+ onMessage={(event) => {+ if (!active.current || failed.current) return;+ const message = previewStreamMessage(event.nativeEvent.data);+ if (message === null) return;+ switch (message.type) {+ case "control": {+ setControl(message);+ const previousDialog = dialogRef.current;+ dialogRef.current = message.dialog;+ setPromptText((draft) => previewPromptText(previousDialog, message.dialog, draft));+ onControl?.(message);return;}- setStatus(message.status);- if (message.status === "connecting") {- // Dialogs may have closed and reopened while this viewer was disconnected.- dialogRef.current = null;- setControl(null);- onControl?.(null);- }- onStreamingChange?.(message.status === "streaming");- if (message.status === "streaming") onStreaming();- }- }}- />+ case "unauthorized":+ if (!onUnauthorized()) {+ fail("This session can't open the browser stream. Reconnect to try again.");+ }+ return;+ case "gone":+ setGone(true);+ fail("This tab was closed.");+ onGone?.();+ return;+ case "hostSetup":+ setHostSetup({ need: message.need, command: message.command });+ fail(previewStreamHostSetupMessage(message));+ return;+ case "viewport":+ onViewport?.(message);+ return;+ case "clipboard":+ void Clipboard.setStringAsync(message.text).catch(() => undefined);+ return;+ case "download":+ offerDownload(message);+ return;+ case "fileChooser":+ setFileChooser(message.chooser);+ return;+ case "pictureInPicture":+ onPictureInPicture?.(message, message.detail);+ return;+ case "status":+ setStarted(true);+ if (message.status === "error") {+ fail(message.detail ?? "Browser stream failed.");+ return;+ }+ setStatus(message.status);+ if (message.status === "connecting") {+ // Dialogs may have closed and reopened while this viewer was disconnected.+ dialogRef.current = null;+ setControl(null);+ onControl?.(null);+ }+ onStreamingChange?.(message.status === "streaming");+ if (message.status === "streaming") onStreaming();+ }+ }}+ />+ {pdfUri ? (+ <View className="absolute inset-0">+ <PdfPreview key={pdfUri} uri={pdfUri} />+ </View>+ ) : null}+ </View>{!compact && fileChooser && control?.controller === "you" ? (<View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4"><AppText className="text-sm text-secondary-foreground">diff --git a/apps/mobile/src/features/browser/ThreadBrowserFloat.tsx b/apps/mobile/src/features/browser/ThreadBrowserFloat.tsxindex 60b7344f29e..3cc5eb951b6 100644--- a/apps/mobile/src/features/browser/ThreadBrowserFloat.tsx+++ b/apps/mobile/src/features/browser/ThreadBrowserFloat.tsx@@ -1,5 +1,7 @@import { useIsFocused } from "@react-navigation/native";import type { EnvironmentId, PreviewSessionSnapshot, ThreadId } from "@t3tools/contracts";+import { previewPdfAssetUrl } from "@t3tools/shared/preview";+import * as Option from "effect/Option";import { useCallback, useEffect, useRef, useState } from "react";import { AppState, Pressable, View } from "react-native";import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";@@ -8,6 +10,7 @@ import { SymbolView } from "../../components/ui/AppSymbol";import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";import { browserTabTitle } from "./browserTabs";import { PreviewStreamWebView } from "./PreviewStreamWebView";+import { usePreparedConnection } from "../../state/session";const PLAYER_LONG_SIDE = 184;const PLAYER_ENTERING = FadeIn.duration(180).reduceMotion(ReduceMotion.System);@@ -77,6 +80,8 @@ function FloatingBrowserPlayer(props: {readonly onClose: () => void;}) {const { themeVariables } = useAppearancePreferences();+ const prepared = usePreparedConnection(props.environmentId);+ const httpBaseUrl = Option.isSome(prepared) ? prepared.value.httpBaseUrl : null;const [viewport, setViewport] = useState<{ width: number; height: number } | null>(null);const aspect = Math.min(Math.max(viewport ? viewport.width / viewport.height : 16 / 10, 0.5), 2);const width = aspect >= 1 ? PLAYER_LONG_SIDE : Math.round(PLAYER_LONG_SIDE * aspect);@@ -101,6 +106,11 @@ function FloatingBrowserPlayer(props: {environmentId={props.environmentId}threadId={props.threadId}tabId={props.tab.tabId}+ pdfUri={+ props.tab.navStatus._tag === "Success"+ ? previewPdfAssetUrl(props.tab.navStatus.url, httpBaseUrl)+ : null+ }interactive={false}background={background}compactdiff --git a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsxindex d22ff07084b..432f2eb36bd 100644--- a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx+++ b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx@@ -1,57 +1,107 @@-import { useState } from "react";-import { View } from "react-native";+import { useEffect, useState } from "react";+import { BackHandler, Platform, View } from "react-native";import { WebView } from "react-native-webview";+import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";import { AppText as Text } from "../../components/ui/AppText";import { FilePreviewLoading } from "./FilePreviewFeedback";import { LoadingStrip } from "../../components/ui/LoadingStrip";+import { PdfPreview } from "../../components/PdfPreview";+import { ControlPill } from "../../components/ui/ControlPill";+import { isPdfPreviewUri } from "../../lib/pdfPreview";+import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";export function WorkspaceFileWebPreview(props: { readonly uri: string | null }) {+ if (props.uri === null) {+ return <FilePreviewLoading message="Preparing preview..." background="card" />;+ }+ return <DocumentWebPreview key={props.uri} uri={props.uri} />;+}++function DocumentWebPreview(props: { readonly uri: string }) {+ const insets = useSafeAreaInsets();+ const columnMetrics = useNativeColumnLayoutMetrics();+ const pdfTopInset = Platform.OS === "ios" ? (columnMetrics?.safeArea.top ?? insets.top) : 0;const [loadProgress, setLoadProgress] = useState(0);const [loadError, setLoadError] = useState<string | null>(null);+ const [linkedPdf, setLinkedPdf] = useState<string | null>(null);- if (props.uri === null) {- return <FilePreviewLoading message="Preparing preview..." background="card" />;+ useEffect(() => {+ if (linkedPdf === null) return;+ const subscription = BackHandler.addEventListener("hardwareBackPress", () => {+ setLinkedPdf(null);+ return true;+ });+ return () => subscription.remove();+ }, [linkedPdf]);++ if (isPdfPreviewUri(props.uri)) {+ return (+ <View className="flex-1" style={{ paddingTop: pdfTopInset }}>+ <PdfPreview uri={props.uri} />+ </View>+ );}return (<View className="relative flex-1 bg-card">- {loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}- {loadError ? (- <View className="border-b border-border bg-card px-4 py-2">- <Text className="text-xs font-t3-bold text-foreground">Preview failed</Text>- <Text className="mt-0.5 text-xs leading-snug text-foreground-muted">{loadError}</Text>+ {linkedPdf ? (+ <View className="flex-1" style={{ paddingTop: pdfTopInset }}>+ <PdfPreview key={linkedPdf} uri={linkedPdf} />+ <SafeAreaView edges={["bottom"]} className="border-t border-border px-4 py-2">+ <ControlPill+ label="Back to document"+ variant="pill"+ onPress={() => setLinkedPdf(null)}+ />+ </SafeAreaView></View>) : null}- <WebView- source={{ uri: props.uri }}- originWhitelist={["*"]}- allowsBackForwardNavigationGestures- allowsFullscreenVideo- setSupportMultipleWindows={false}- startInLoadingState- onLoadProgress={(event) => {- setLoadProgress(event.nativeEvent.progress);- }}- onLoadStart={() => {- setLoadProgress(0.05);- setLoadError(null);- }}- onLoadEnd={() => {- setLoadProgress(0);- }}- onError={(event) => {- setLoadProgress(0);- setLoadError(event.nativeEvent.description || "The file could not be rendered.");- }}- renderLoading={() => (- <View className="absolute inset-0 items-center justify-center bg-card">- <AppActivityIndicator />+ <View className="flex-1" style={linkedPdf ? { display: "none" } : undefined}>+ {loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}+ {loadError ? (+ <View className="border-b border-border bg-card px-4 py-2">+ <Text className="text-xs font-t3-bold text-foreground">Preview failed</Text>+ <Text className="mt-0.5 text-xs leading-snug text-foreground-muted">{loadError}</Text></View>- )}- style={{ flex: 1, backgroundColor: "transparent" }}- />+ ) : null}+ <WebView+ source={{ uri: props.uri }}+ originWhitelist={["*"]}+ allowsBackForwardNavigationGestures+ allowsFullscreenVideo+ setSupportMultipleWindows={false}+ onShouldStartLoadWithRequest={(request) => {+ if (request.isTopFrame !== false && isPdfPreviewUri(request.url)) {+ setLinkedPdf(request.url);+ return false;+ }+ return true;+ }}+ startInLoadingState+ onLoadProgress={(event) => {+ setLoadProgress(event.nativeEvent.progress);+ }}+ onLoadStart={() => {+ setLoadProgress(0.05);+ setLoadError(null);+ }}+ onLoadEnd={() => {+ setLoadProgress(0);+ }}+ onError={(event) => {+ setLoadProgress(0);+ setLoadError(event.nativeEvent.description || "The file could not be rendered.");+ }}+ renderLoading={() => (+ <View className="absolute inset-0 items-center justify-center bg-card">+ <AppActivityIndicator />+ </View>+ )}+ style={{ flex: 1, backgroundColor: "transparent" }}+ />+ </View></View>);}diff --git a/apps/mobile/src/lib/pdfPreview.test.ts b/apps/mobile/src/lib/pdfPreview.test.tsnew file mode 100644index 00000000000..7e5559d3ef7--- /dev/null+++ b/apps/mobile/src/lib/pdfPreview.test.ts@@ -0,0 +1,134 @@+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";++const mocks = vi.hoisted(() => ({+ download: vi.fn(),+ dispose: vi.fn(),+ read: vi.fn(),+ close: vi.fn(),+}));+vi.mock("./attachmentDownload", () => ({ downloadAttachmentForPreview: mocks.download }));+vi.mock("expo-file-system", () => ({+ File: class {+ open() {+ return { readBytes: mocks.read, close: mocks.close };+ }+ },+ FileMode: { ReadOnly: "r" },+}));++import { isPdfPreviewUri, pdfInitialPage, pdfLinkUrl, preparePdfPreview } from "./pdfPreview";++beforeEach(() => {+ vi.resetAllMocks();+ mocks.download.mockResolvedValue({ uri: "file:///cache/preview.pdf", dispose: mocks.dispose });+ mocks.read.mockResolvedValue(new TextEncoder().encode("%PDF-"));+});++describe("PDF navigation", () => {+ it("resolves web links against the original PDF rather than its download cache", () => {+ expect(+ pdfLinkUrl("../next.pdf#page=2", "https://environment.test/api/assets/token/files/a.pdf"),+ ).toBe("https://environment.test/api/assets/token/next.pdf#page=2");+ expect(pdfLinkUrl("https://example.com/?q=one#section", "file:///cache/preview.pdf")).toBe(+ "https://example.com/?q=one#section",+ );+ });++ it.each([+ "",+ "javascript:alert(1)",+ "data:text/html,hello",+ "file:///private/a.pdf",+ "intent://open",+ "https://[",+ ])("ignores unsupported or invalid PDF links: %s", (href) => {+ expect(pdfLinkUrl(href, "https://environment.test/a.pdf")).toBeNull();+ });++ it("recognizes signed PDF links with queries and page fragments", () => {+ expect(+ isPdfPreviewUri("https://environment.test/api/assets/token/Syllabus.PDF?x=1#page=8"),+ ).toBe(true);+ expect(isPdfPreviewUri("file:///local/document.pdf")).toBe(true);+ expect(isPdfPreviewUri("https://environment.test/index.html?file=syllabus.pdf")).toBe(false);+ expect(isPdfPreviewUri("invalid")).toBe(false);+ });++ it("keeps valid page destinations and rejects invalid page numbers", () => {+ expect(pdfInitialPage("https://environment.test/a.pdf#page=8&zoom=100")).toBe(8);+ for (const fragment of [+ "",+ "#page=0",+ "#page=-2",+ "#page=1.5",+ "#page=NaN",+ "#page=Infinity",+ ]) {+ expect(pdfInitialPage(`file:///a.pdf${fragment}`)).toBe(1);+ }+ });+});++describe("preparing native PDFs", () => {+ it("downloads from the selected environment without sending the page fragment", async () => {+ const signal = new AbortController().signal;+ const result = await preparePdfPreview("https://remote.test/a.pdf?token=secret#page=8", signal);+ expect(mocks.download).toHaveBeenCalledWith({+ url: "https://remote.test/a.pdf?token=secret",+ attachment: { name: "preview.pdf", mimeType: "application/pdf" },+ signal,+ });+ expect(result?.uri).toBe("file:///cache/preview.pdf");+ expect(mocks.close).toHaveBeenCalledOnce();+ expect(mocks.dispose).not.toHaveBeenCalled();+ result?.dispose();+ expect(mocks.dispose).toHaveBeenCalledOnce();+ });++ it("rejects an HTML response and removes the download", async () => {+ mocks.read.mockResolvedValue(new TextEncoder().encode("<html"));+ await expect(+ preparePdfPreview("https://remote.test/a.pdf", new AbortController().signal),+ ).rejects.toThrow("did not return a PDF");+ expect(mocks.close).toHaveBeenCalledOnce();+ expect(mocks.dispose).toHaveBeenCalledOnce();+ });++ it("closes and removes the cached file when reading fails", async () => {+ mocks.read.mockRejectedValue(new Error("read failed"));+ await expect(+ preparePdfPreview("https://remote.test/a.pdf", new AbortController().signal),+ ).rejects.toThrow("read failed");+ expect(mocks.close).toHaveBeenCalledOnce();+ expect(mocks.dispose).toHaveBeenCalledOnce();+ });++ it("opens local files without downloading or deleting the caller's file", async () => {+ const result = await preparePdfPreview(+ "file:///draft.pdf#page=3",+ new AbortController().signal,+ );+ expect(result?.uri).toBe("file:///draft.pdf");+ result?.dispose();+ expect(mocks.download).not.toHaveBeenCalled();+ expect(mocks.dispose).not.toHaveBeenCalled();+ });++ it("removes a download if the preview is dismissed during validation", async () => {+ const controller = new AbortController();+ mocks.read.mockImplementation(async () => {+ controller.abort();+ return new TextEncoder().encode("%PDF-");+ });+ expect(await preparePdfPreview("https://remote.test/a.pdf", controller.signal)).toBeNull();+ expect(mocks.dispose).toHaveBeenCalledOnce();+ });++ it("does no work for an already dismissed preview", async () => {+ const controller = new AbortController();+ controller.abort();+ expect(await preparePdfPreview("https://remote.test/a.pdf", controller.signal)).toBeNull();+ expect(mocks.download).not.toHaveBeenCalled();+ expect(mocks.read).not.toHaveBeenCalled();+ });+});diff --git a/apps/mobile/src/lib/pdfPreview.ts b/apps/mobile/src/lib/pdfPreview.tsnew file mode 100644index 00000000000..aa7ac6e57d9--- /dev/null+++ b/apps/mobile/src/lib/pdfPreview.ts@@ -0,0 +1,58 @@+import { downloadAttachmentForPreview } from "./attachmentDownload";++export function isPdfPreviewUri(uri: string): boolean {+ try {+ return /\.pdf$/i.test(new URL(uri).pathname);+ } catch {+ return false;+ }+}++export function pdfInitialPage(uri: string): number {+ const page = Number(new URLSearchParams(uri.split("#", 2)[1]).get("page"));+ return Number.isSafeInteger(page) && page > 0 ? page : 1;+}++export function pdfLinkUrl(href: string, sourceUri: string): string | null {+ if (href.trim().length === 0) return null;+ try {+ const url = new URL(href, sourceUri);+ return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;+ } catch {+ return null;+ }+}++export async function preparePdfPreview(uri: string, signal: AbortSignal) {+ if (signal.aborted) return null;+ const source = uri.split("#", 1)[0]!;+ const cached = /^(file|content):/.test(source)+ ? { uri: source, dispose: () => {} }+ : await downloadAttachmentForPreview({+ url: source,+ attachment: { name: "preview.pdf", mimeType: "application/pdf" },+ signal,+ });+ if (cached === null) return null;+ try {+ const { File, FileMode } = await import("expo-file-system");+ const handle = new File(cached.uri).open(FileMode.ReadOnly);+ try {+ const header = await handle.readBytes(5);+ if (String.fromCharCode(...header) !== "%PDF-") {+ throw new Error("The server did not return a PDF. Check the connection and try again.");+ }+ } finally {+ handle.close();+ }+ if (signal.aborted) {+ cached.dispose();+ return null;+ }+ return cached;+ } catch (error) {+ cached.dispose();+ if (signal.aborted) return null;+ throw error;+ }+}diff --git a/apps/mobile/src/native/NativeHeaderToolbar.test.tsx b/apps/mobile/src/native/NativeHeaderToolbar.test.tsxnew file mode 100644index 00000000000..a811d7f797a--- /dev/null+++ b/apps/mobile/src/native/NativeHeaderToolbar.test.tsx@@ -0,0 +1,101 @@+// @vitest-environment jsdom+import type { NativeStackHeaderItem } from "@react-navigation/native-stack";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, expect, it, vi } from "vite-plus/test";++const harness = vi.hoisted(() => ({+ params: { path: ["first", "guide.pdf"] },+ renderedItems: [] as NativeStackHeaderItem[],+ setOptionsCalls: 0,+ openedDocuments: [] as string[],+}));++// Native headers retain the actions materialized when navigation applies options.+vi.mock("@react-navigation/native", () => {+ const navigation = {+ setOptions(options: {+ unstable_headerLeftItems?: () => NativeStackHeaderItem[];+ unstable_headerRightItems?: () => NativeStackHeaderItem[];+ unstable_headerToolbarItems?: () => NativeStackHeaderItem[];+ }) {+ harness.setOptionsCalls += 1;+ harness.renderedItems =+ options.unstable_headerLeftItems?.() ??+ options.unstable_headerRightItems?.() ??+ options.unstable_headerToolbarItems?.() ??+ [];+ },+ };+ return {+ useNavigation: () => navigation,+ useRoute: () => ({ key: "file", name: "ThreadFile", params: harness.params }),+ };+});++import { NativeHeaderToolbar } from "./NativeHeaderToolbar";++let root: Root | null = null;+type Placement = "left" | "right" | "bottom";++function DocumentToolbar(props: { readonly path: string; readonly placement: Placement }) {+ return (+ <NativeHeaderToolbar placement={props.placement}>+ <NativeHeaderToolbar.Menu title="File actions" icon="ellipsis">+ <NativeHeaderToolbar.MenuAction onPress={() => harness.openedDocuments.push(props.path)}>+ Open PDF+ </NativeHeaderToolbar.MenuAction>+ </NativeHeaderToolbar.Menu>+ </NativeHeaderToolbar>+ );+}++function renderDocument(path: string, placement: Placement) {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ harness.params = { path: path.split("/") };+ root ??= createRoot(document.createElement("div"));+ act(() => root!.render(<DocumentToolbar path={path} placement={placement} />));+}++function openRenderedDocument() {+ const menu = harness.renderedItems[0];+ if (menu?.type !== "menu") throw new Error("Expected the native file menu");+ const action = menu.menu.items[0];+ if (action?.type !== "action") throw new Error("Expected the native Open PDF action");+ action.onPress?.();+}++afterEach(() => {+ act(() => root?.unmount());+ root = null;+ harness.renderedItems = [];+ harness.setOptionsCalls = 0;+ harness.openedDocuments = [];+ vi.unstubAllGlobals();+});++it.each(["left", "right", "bottom"] as const)(+ "updates the %s header action when switching between documents with the same name",+ (placement) => {+ renderDocument("first/guide.pdf", placement);+ openRenderedDocument();+ renderDocument("second/guide.pdf", placement);+ openRenderedDocument();++ expect(harness.openedDocuments).toEqual(["first/guide.pdf", "second/guide.pdf"]);+ },+);++it.each(["left", "right", "bottom"] as const)(+ "does not reapply %s header options for equivalent document renders",+ (placement) => {+ renderDocument("first/guide.pdf", placement);+ const applied = harness.setOptionsCalls;+ renderDocument("first/guide.pdf", placement);+ renderDocument("first/guide.pdf", placement);++ expect(harness.setOptionsCalls).toBe(applied);+ openRenderedDocument();+ expect(harness.openedDocuments).toEqual(["first/guide.pdf"]);+ },+);diff --git a/apps/mobile/src/native/NativeHeaderToolbar.tsx b/apps/mobile/src/native/NativeHeaderToolbar.tsxindex 04b4ef64a8d..2e6e7059880 100644--- a/apps/mobile/src/native/NativeHeaderToolbar.tsx+++ b/apps/mobile/src/native/NativeHeaderToolbar.tsx@@ -1,4 +1,4 @@-import { useNavigation, type ParamListBase } from "@react-navigation/native";+import { useNavigation, useRoute, type ParamListBase } from "@react-navigation/native";import type {NativeStackHeaderItem,NativeStackHeaderItemMenu,@@ -17,6 +17,7 @@ import {import type { ColorValue } from "react-native";import type { HeaderBarButtonSearchBarPlacementItem } from "react-native-screens";import { NativeWorkspaceTabActivityContext } from "./v5-workspace-context";+import { NativeStackScreenOptions } from "./StackHeader";function useNativeStackNavigation(): NativeStackNavigationProp<ParamListBase> | null {return useNavigation<NativeStackNavigationProp<ParamListBase>>();@@ -225,33 +226,15 @@ function NativeHeaderToolbarRoot(props: {readonly children?: ReactNode;}) {const navigation = useNativeStackNavigation();+ const route = useRoute();const tabActivity = use(NativeWorkspaceTabActivityContext);- const tabActive = tabActivity?.active ?? true;const isTabActive = tabActivity?.isActive;const items = useMemo(() => collectToolbarItems(props.children), [props.children]);-- // Update items in place. Clearing them on every render causes UIKit to run a- // second transition and detach custom views while the stack is animating.- useLayoutEffect(() => {- if (!navigation || !tabActive) {- return;- }- if (props.placement === "bottom") {- navigation.setOptions({- unstable_headerToolbarItems: () => items,- } as NativeStackOptionsWithToolbar);- return;- }- // UIKit's search placement item belongs to the toolbar, never a header group.- const headerItems = items.filter(- (item): item is NativeStackHeaderItem => item.type !== "searchBarPlacement",- );- if (props.placement === "left") {- navigation.setOptions({ unstable_headerLeftItems: () => headerItems });- return;- }- navigation.setOptions({ unstable_headerRightItems: () => headerItems });- }, [items, navigation, props.placement, tabActive]);+ // UIKit's search placement item belongs to the toolbar, never a header group.+ const headerItems = useMemo(+ () => items.filter((item): item is NativeStackHeaderItem => item.type !== "searchBarPlacement"),+ [items],+ );useLayoutEffect(() => {if (!navigation) return;@@ -269,7 +252,18 @@ function NativeHeaderToolbarRoot(props: {};}, [navigation, props.placement, isTabActive]);- return null;+ return (+ <NativeStackScreenOptions+ optionsVersion={[items, route.params]}+ options={+ props.placement === "bottom"+ ? { unstable_headerToolbarItems: () => items }+ : props.placement === "left"+ ? { unstable_headerLeftItems: () => headerItems }+ : { unstable_headerRightItems: () => headerItems }+ }+ />+ );}function NativeHeaderToolbarButton(_props: {diff --git a/apps/mobile/src/native/StackHeader.tsx b/apps/mobile/src/native/StackHeader.tsxindex a90eca161c7..3b1fb0be06f 100644--- a/apps/mobile/src/native/StackHeader.tsx+++ b/apps/mobile/src/native/StackHeader.tsx@@ -7,8 +7,6 @@ import { use, useEffect, useLayoutEffect, useMemo, useRef } from "react";import { NativeWorkspaceTabActivityContext } from "./v5-workspace-context";import type { ColorValue } from "react-native";-export { NativeHeaderToolbar } from "./NativeHeaderToolbar";-export {nativeHeaderScrollEdgeEffects,nativeTopScrollEdgeEffect,diff --git a/apps/server/src/preview/PdfDocumentNavigation.test.ts b/apps/server/src/preview/PdfDocumentNavigation.test.tsnew file mode 100644index 00000000000..dd5cff006ce--- /dev/null+++ b/apps/server/src/preview/PdfDocumentNavigation.test.ts@@ -0,0 +1,163 @@+import type { CDPSession } from "playwright-core";+import { describe, expect, it, vi } from "vite-plus/test";++import { installPdfDocumentNavigation } from "./PdfDocumentNavigation.ts";++const source = "https://environment.test/api/assets/signed-token/files/Study%20guide.PDF";++function fixture(nativePdfViewer = false) {+ const completed = Promise.withResolvers<{ method: string; params: Record<string, unknown> }>();+ let paused: (event: {+ requestId: string;+ frameId: string;+ request: { url: string; method: string };+ responseStatusCode: number;+ responseHeaders: Array<{ name: string; value: string }>;+ }) => void = () => {+ throw new Error("Navigation handler was not installed");+ };+ const send = vi.fn(async (method: string, params: Record<string, unknown> = {}) => {+ if (method === "Runtime.evaluate") return { result: { value: nativePdfViewer } };+ if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };+ if (+ method === "Fetch.fulfillRequest" ||+ method === "Fetch.continueRequest" ||+ method === "Fetch.failRequest"+ ) {+ completed.resolve({ method, params });+ }+ return {};+ });+ const cdp = {+ send,+ on: (_name: string, listener: typeof paused) => {+ paused = listener;+ },+ } as unknown as CDPSession;+ return {+ cdp,+ send,+ navigate: (+ url = source,+ frameId = "main",+ method = "GET",+ status = 200,+ contentType = "application/pdf",+ ) => {+ paused({+ requestId: "request-1",+ frameId,+ request: { url, method },+ responseStatusCode: status,+ responseHeaders: [{ name: "Content-Type", value: contentType }],+ });+ return completed.promise;+ },+ };+}++describe("PDF document navigation", () => {+ it("keeps native PDF rendering when the browser supports it", async () => {+ const test = fixture(true);+ await installPdfDocumentNavigation(test.cdp);+ expect(test.send.mock.calls.map(([method]) => method)).toEqual(["Runtime.evaluate"]);+ });++ it("commits the PDF URL for client rendering without redirects or server-side PDF rendering", async () => {+ const test = fixture();+ await installPdfDocumentNavigation(test.cdp);+ const { method, params } = await test.navigate();+ expect(method).toBe("Fetch.fulfillRequest");+ expect(params).toMatchObject({ responseCode: 200, requestId: "request-1" });+ expect(params.responseHeaders).toEqual([+ { name: "Content-Type", value: "text/html; charset=utf-8" },+ { name: "Cache-Control", value: "no-store" },+ { name: "Content-Security-Policy", value: "default-src 'none'; sandbox" },+ { name: "X-Content-Type-Options", value: "nosniff" },+ ]);+ expect(Buffer.from(String(params.body), "base64").toString()).toBe(+ "<!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>",+ );+ expect(test.send).toHaveBeenCalledWith("Fetch.enable", {+ patterns: [+ { urlPattern: "*/api/assets/*", resourceType: "Document", requestStage: "Response" },+ ],+ });+ });++ it.each([401, 403, 404, 410, 500])(+ "fails unavailable PDF assets with HTTP %s",+ async (status) => {+ const test = fixture();+ await installPdfDocumentNavigation(test.cdp);+ expect(await test.navigate(source, "main", "GET", status)).toEqual({+ method: "Fetch.failRequest",+ params: { requestId: "request-1", errorReason: "Failed" },+ });+ expect(test.send.mock.calls.some(([method]) => method === "Fetch.fulfillRequest")).toBe(+ false,+ );+ },+ );++ it("rejects a non-PDF response instead of committing a successful PDF tab", async () => {+ const test = fixture();+ await installPdfDocumentNavigation(test.cdp);+ expect(await test.navigate(source, "main", "GET", 200, "text/html")).toMatchObject({+ method: "Fetch.failRequest",+ });+ });++ it("allows redirects to reach their asset response", async () => {+ const test = fixture();+ await installPdfDocumentNavigation(test.cdp);+ expect(await test.navigate(source, "main", "GET", 302)).toMatchObject({+ method: "Fetch.continueRequest",+ });+ });++ it("accepts a partial PDF response", async () => {+ const test = fixture();+ await installPdfDocumentNavigation(test.cdp);+ expect(+ await test.navigate(source, "main", "GET", 206, "Application/PDF; charset=binary"),+ ).toMatchObject({+ method: "Fetch.fulfillRequest",+ });+ });++ it.each([+ ["https://environment.test/api/assets/token/index.html", "main", "GET"],+ ["https://example.com/paper.pdf", "main", "GET"],+ [source, "subframe", "GET"],+ [source, "main", "POST"],+ ])("leaves other browser requests alone: %s, %s, %s", async (url, frameId, method) => {+ const test = fixture();+ await installPdfDocumentNavigation(test.cdp);+ expect(await test.navigate(url, frameId, method)).toEqual({+ method: "Fetch.continueRequest",+ params: { requestId: "request-1" },+ });+ });++ it("escapes filenames in the browser document", async () => {+ const test = fixture();+ await installPdfDocumentNavigation(test.cdp);+ const result = await test.navigate(+ "https://environment.test/api/assets/token/%3Cscript%3E.pdf",+ );+ expect(Buffer.from(String(result.params.body), "base64").toString()).toContain(+ "<title><script>.pdf</title>",+ );+ });++ it("resumes navigation when committing the document fails", async () => {+ const test = fixture();+ await installPdfDocumentNavigation(test.cdp);+ test.send.mockRejectedValueOnce(new Error("Tab closed"));+ expect(await test.navigate()).toEqual({+ method: "Fetch.continueRequest",+ params: { requestId: "request-1" },+ });+ });+});diff --git a/apps/server/src/preview/PdfDocumentNavigation.ts b/apps/server/src/preview/PdfDocumentNavigation.tsnew file mode 100644index 00000000000..4fc01f437cf--- /dev/null+++ b/apps/server/src/preview/PdfDocumentNavigation.ts@@ -0,0 +1,72 @@+import { constVoid } from "effect/Function";+import type { CDPSession } from "playwright-core";++const escapeHtml = (value: string) =>+ value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<");++export const isPdfAssetUrl = (url: string) => {+ const { pathname } = new URL(url);+ return pathname.startsWith("/api/assets/") && /\.pdf$/i.test(pathname);+};++export async function installPdfDocumentNavigation(cdp: CDPSession) {+ const nativeViewer = await cdp.send("Runtime.evaluate", {+ expression: "navigator.pdfViewerEnabled",+ returnByValue: true,+ });+ if (nativeViewer.result?.value === true) return;+ const { frameTree } = await cdp.send("Page.getFrameTree");+ // The shell cannot open PDFs. Commit a document at the original URL so the+ // client can embed its signed bytes while Back and Forward keep working.+ cdp.on("Fetch.requestPaused", (event) => {+ const { requestId, request, frameId } = event;+ const proceed = () => cdp.send("Fetch.continueRequest", { requestId });+ void (async () => {+ if (+ request.method !== "GET" ||+ frameId !== frameTree.frame.id ||+ !isPdfAssetUrl(request.url)+ ) {+ await proceed();+ return;+ }+ const status = event.responseStatusCode;+ if (status === undefined || (status >= 300 && status < 400)) {+ await proceed();+ return;+ }+ const contentType = event.responseHeaders+ ?.find((header) => header.name.toLowerCase() === "content-type")+ ?.value.split(";", 1)[0]+ ?.trim()+ .toLowerCase();+ if (status < 200 || status >= 300 || contentType !== "application/pdf") {+ // Reach the browser's requestfailed path instead of committing a successful PDF tab.+ await cdp.send("Fetch.failRequest", { requestId, errorReason: "Failed" });+ return;+ }+ const name = escapeHtml(+ decodeURIComponent(new URL(request.url).pathname.split("/").at(-1) ?? "PDF"),+ );+ await cdp.send("Fetch.fulfillRequest", {+ requestId,+ responseCode: 200,+ responseHeaders: [+ { name: "Content-Type", value: "text/html; charset=utf-8" },+ { name: "Cache-Control", value: "no-store" },+ { name: "Content-Security-Policy", value: "default-src 'none'; sandbox" },+ { name: "X-Content-Type-Options", value: "nosniff" },+ ],+ body: Buffer.from(+ `<!doctype html><html><head><title>${name}</title></head><body><h1>${name}</h1><p>This PDF is displayed in the connected client.</p></body></html>`,+ ).toString("base64"),+ });+ })().catch(() => proceed().catch(constVoid));+ });+ // Only document navigations pause; the client's PDF fetch gets the original bytes.+ await cdp.send("Fetch.enable", {+ patterns: [+ { urlPattern: "*/api/assets/*", resourceType: "Document", requestStage: "Response" },+ ],+ });+}diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.tsindex 861fc063a86..b21b7314362 100644--- a/apps/server/src/preview/ServerBrowser.test.ts+++ b/apps/server/src/preview/ServerBrowser.test.ts@@ -908,6 +908,44 @@ it.live("a popup becomes the agent's own tab and keeps its opener page", () =>).pipe(Effect.provide(layer)),);+it.live.each([+ { url: "https://environment.test/api/assets/token/guide.pdf", pdf: true },+ { url: "https://example.com/sign-in", pdf: false },+])("an adopted popup at $url recovers only PDF asset navigation", ({ url, pdf }) =>+ Effect.scoped(+ Effect.gen(function* () {+ const browser = yield* ServerBrowser.ServerBrowser;+ const manager = yield* Manager.PreviewManager;+ const events = yield* manager.subscribeEvents;+ const opened = yield* manager.open({ threadId: scope.thread.threadId, runtime: "server" });+ const viewer = yield* browser.attachViewer(viewerInput(opened.tabId, true));+ yield* viewer.input({ type: "takeControl" });+ const popup = makeContext();+ yield* Effect.promise(() => popup.page.goto(url));+ popup.page.goto.mockClear();+ popup.page.reload.mockImplementationOnce(async () => {+ popup.page.emit("load");+ });+ contexts[0]!.page.emit("popup", popup.page);+ let shown = yield* Queue.take(viewer.output);+ while (shown._tag !== "popup") shown = yield* Queue.take(viewer.output);+ yield* browser.attachViewer(viewerInput(shown.tabId, true));+ expect(popup.page.goto).not.toHaveBeenCalled();+ expect(popup.page.reload).toHaveBeenCalledTimes(pdf ? 1 : 0);+ if (pdf) {+ let event = yield* PubSub.take(events);+ while (event.type !== "navigated" || event.tabId !== shown.tabId) {+ event = yield* PubSub.take(events);+ }+ const session = (yield* manager.list({ threadId: scope.thread.threadId })).sessions.find(+ (entry) => entry.tabId === shown.tabId,+ );+ expect(session?.navStatus).toMatchObject({ _tag: "Success", url });+ }+ }),+ ).pipe(Effect.provide(layer)),+);+it.live("a tab opened to a file the browser cannot show reports the file to download", () =>Effect.scoped(Effect.gen(function* () {diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.tsindex 0f134133acc..3fcd1ea8309 100644--- a/apps/server/src/preview/ServerBrowser.ts+++ b/apps/server/src/preview/ServerBrowser.ts@@ -82,6 +82,7 @@ import * as PreviewBrowser from "./PreviewBrowser.ts";import * as PreviewBrowserHost from "./PreviewBrowserHost.ts";import { presentAsChrome, ServerBrowserContexts } from "./ServerBrowserContexts.ts";import { BrowserControlInterrupted, SessionControl } from "./SessionControl.ts";+import { installPdfDocumentNavigation, isPdfAssetUrl } from "./PdfDocumentNavigation.ts";const SERVER_HOST_CLIENT_ID = SERVER_BROWSER_AUTOMATION_CLIENT_ID;const RENDER_SCALE = 2;@@ -736,6 +737,7 @@ const make = Effect.gen(function* () {if (!desktop) await prepareContext(context);const page = adopted?.page ?? desktop?.page ?? (await context.newPage());const cdp = await context.newCDPSession(page);+ await installPdfDocumentNavigation(cdp);// The desktop's page is already a normal browser. A popup's first request// went out before it became a tab; everything after presents as Chrome.if (!desktop) await presentAsChrome(cdp, host);@@ -885,11 +887,17 @@ const make = Effect.gen(function* () {page.on("crash", () => dropTab(tab, true));tabs.set(key, tab);reportLiveTabs();- // A popup is already loading its own URL, and the desktop loads its tab's.- if (!adopted && !desktop && snapshot.navStatus._tag === "Loading") {- tab.initialNavigation = page- .goto(snapshot.navStatus.url, { waitUntil: "commit", timeout: NAVIGATION_TIMEOUT_MS })- .then(constVoid);+ // Existing desktop and popup PDFs can start loading before interception attaches.+ if (+ snapshot.navStatus._tag === "Loading" &&+ ((!adopted && !desktop) || isPdfAssetUrl(snapshot.navStatus.url))+ ) {+ const options = { waitUntil: "commit", timeout: NAVIGATION_TIMEOUT_MS } as const;+ tab.initialNavigation = (+ (desktop || adopted) && page.url() === snapshot.navStatus.url+ ? page.reload(options)+ : page.goto(snapshot.navStatus.url, options)+ ).then(constVoid);void tab.initialNavigation.catch(constVoid);}diff --git a/apps/web/src/browser/ServerBrowserSurface.tsx b/apps/web/src/browser/ServerBrowserSurface.tsxindex 45dad35db16..27ae15e5e79 100644--- a/apps/web/src/browser/ServerBrowserSurface.tsx+++ b/apps/web/src/browser/ServerBrowserSurface.tsx@@ -147,6 +147,7 @@ export function ServerBrowserSurface(props: {readonly onControl?: (control: PreviewStreamControl | null) => void;readonly onPopup?: (tabId: string) => void;readonly className?: string;+ readonly pdfUrl?: string | null;readonly ref?: Ref<ServerBrowserHandle>;}) {const {@@ -161,6 +162,7 @@ export function ServerBrowserSurface(props: {onControl,onPopup,className,+ pdfUrl = null,ref,} = props;const access = usePreviewStreamAccess(environmentId);@@ -307,9 +309,9 @@ export function ServerBrowserSurface(props: {reload: (options) =>send({ type: "reload", ...(options?.ignoreCache ? { ignoreCache: true } : {}) }),viewport: (setting) => send({ type: "viewport", setting }),- canvas: () => (hasFrameRef.current ? canvasRef.current : null),+ canvas: () => (!pdfUrl && hasFrameRef.current ? canvasRef.current : null),}),- [send],+ [pdfUrl, send],);useEffect(() => {@@ -734,6 +736,14 @@ export function ServerBrowserSurface(props: {) : null}</div><div className="relative min-h-0 flex-1">+ {pdfUrl ? (+ <embed+ src={pdfUrl}+ type="application/pdf"+ title="PDF document"+ className="absolute inset-0 z-10 size-full border-0"+ />+ ) : null}<canvasref={canvasRef}className="block size-full touch-none object-contain"@@ -744,7 +754,7 @@ export function ServerBrowserSurface(props: {onMouseDown={(event) => event.preventDefault()}onContextMenu={(event) => event.preventDefault()}/>- {agentCursor && control?.controller !== "you" ? (+ {!pdfUrl && agentCursor && control?.controller !== "you" ? (<AgentCursorMark{...agentCursor}controller={control?.controller === "agent" ? "agent" : "none"}@@ -760,7 +770,7 @@ export function ServerBrowserSurface(props: {autoComplete="off"autoCorrect="off"spellCheck={false}- disabled={control?.controller !== "you"}+ disabled={pdfUrl !== null || control?.controller !== "you"}defaultValue={INPUT_SENTINEL}// The caret must sit after the sentinel for a deletion to have something to delete.onFocus={(event) => resetInput(event.currentTarget)}diff --git a/apps/web/src/browser/serverPictureInPicture.test.ts b/apps/web/src/browser/serverPictureInPicture.test.tsnew file mode 100644index 00000000000..629294a5f58--- /dev/null+++ b/apps/web/src/browser/serverPictureInPicture.test.ts@@ -0,0 +1,90 @@+import { EnvironmentId, ThreadId } from "@t3tools/contracts";+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";++import { applyPreviewServerSnapshot, resetPreviewStateForTests } from "~/previewStateStore";+import { closeServerPictureInPicture, openServerPictureInPicture } from "./serverPictureInPicture";++vi.mock("~/state/previewStream", () => ({+ readPreviewStreamAccess: async () => ({}),+}));+vi.mock("@t3tools/client-runtime/preview/server-browser-stream", () => ({+ createPreviewFramePainter: () => ({ paint: vi.fn(), stop: vi.fn() }),+ createPreviewStreamClient: () => ({ stop: vi.fn() }),+}));++const ref = {+ environmentId: EnvironmentId.make("environment"),+ threadId: ThreadId.make("thread"),+};+const stopTrack = vi.fn();+const exitPictureInPicture = vi.fn(async () => {});++function navigate(url: string, tabId = "tab") {+ applyPreviewServerSnapshot(ref, {+ threadId: ref.threadId,+ tabId,+ navStatus: { _tag: "Success", url, title: "Document" },+ canGoBack: true,+ canGoForward: false,+ updatedAt: new Date().toISOString(),+ });+}++beforeEach(() => {+ vi.clearAllMocks();+ resetPreviewStateForTests();+ const video = {+ style: { cssText: "" },+ readyState: 4,+ play: async () => {},+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ remove: vi.fn(),+ requestPictureInPicture: vi.fn(async () => {}),+ };+ vi.stubGlobal("HTMLMediaElement", { HAVE_METADATA: 1 });+ vi.stubGlobal("document", {+ pictureInPictureEnabled: true,+ pictureInPictureElement: video,+ exitPictureInPicture,+ body: { append: vi.fn() },+ createElement: (tag: string) =>+ tag === "video"+ ? video+ : {+ getContext: () => ({ fillRect: vi.fn() }),+ captureStream: () => ({ getTracks: () => [{ stop: stopTrack }] }),+ },+ });+ navigate("https://environment.test/api/assets/token/index.html");+});++afterEach(() => {+ closeServerPictureInPicture();+ resetPreviewStateForTests();+ vi.unstubAllGlobals();+});++it("closes the video window and stream when its tab becomes a client-rendered PDF", async () => {+ await openServerPictureInPicture({ ...ref, tabId: "tab", seed: null });+ navigate("https://environment.test/api/assets/token/guide.PDF#page=2");+ expect(exitPictureInPicture).toHaveBeenCalledOnce();+ expect(stopTrack).toHaveBeenCalledOnce();+});++it("keeps PiP for ordinary navigation and PDFs in another tab", async () => {+ await openServerPictureInPicture({ ...ref, tabId: "tab", seed: null });+ navigate("https://environment.test/api/assets/token/guide.pdf", "another-tab");+ navigate("https://example.com/paper.pdf");+ navigate("https://environment.test/api/assets/token/next.html");+ expect(exitPictureInPicture).not.toHaveBeenCalled();+ expect(stopTrack).not.toHaveBeenCalled();+});++it("stops observing navigation when a PiP session closes", async () => {+ await openServerPictureInPicture({ ...ref, tabId: "tab", seed: null });+ closeServerPictureInPicture();+ navigate("https://environment.test/api/assets/token/guide.pdf");+ expect(exitPictureInPicture).toHaveBeenCalledOnce();+ expect(stopTrack).toHaveBeenCalledOnce();+});diff --git a/apps/web/src/browser/serverPictureInPicture.ts b/apps/web/src/browser/serverPictureInPicture.tsindex fed507cab70..fda9ec7fa72 100644--- a/apps/web/src/browser/serverPictureInPicture.ts+++ b/apps/web/src/browser/serverPictureInPicture.ts@@ -3,10 +3,14 @@ import {createPreviewStreamClient,type PreviewStreamClient,} from "@t3tools/client-runtime/preview/server-browser-stream";-import type { EnvironmentId } from "@t3tools/contracts";+import type { EnvironmentId, ThreadId } from "@t3tools/contracts";+import { scopedThreadKey } from "@t3tools/client-runtime/environment";+import { previewPdfAssetUrl } from "@t3tools/shared/preview";import { useSyncExternalStore } from "react";import { readPreviewStreamAccess } from "~/state/previewStream";+import { previewStateAtom, type ThreadPreviewState } from "~/previewStateStore";+import { appAtomRegistry } from "~/rpc/atomRegistry";interface WebKitVideo {webkitSetPresentationMode?: (mode: string) => void;@@ -62,7 +66,7 @@ export function closeServerPictureInPicture(): void {/** Open during user activation, seeding the video with the currently visible frame. */export async function openServerPictureInPicture(input: {readonly environmentId: EnvironmentId;- readonly threadId: string;+ readonly threadId: ThreadId;readonly tabId: string;readonly seed: HTMLCanvasElement | null;}): Promise<void> {@@ -90,6 +94,7 @@ export async function openServerPictureInPicture(input: {let stopped = false;let refusals = 0;let retryTimer: ReturnType<typeof setTimeout> | null = null;+ let stopWatchingPreview = () => {};const onLeave = () => {if (active === current) closeServerPictureInPicture();};@@ -136,6 +141,7 @@ export async function openServerPictureInPicture(input: {key: serverPictureInPictureKey(input.threadId, input.tabId),stop: () => {stopped = true;+ stopWatchingPreview();if (retryTimer !== null) clearTimeout(retryTimer);client?.stop();painter.stop();@@ -172,5 +178,20 @@ export async function openServerPictureInPicture(input: {onLeave();throw error;}- if (active === current) void connect(false);+ if (active === current) {+ const atom = previewStateAtom(scopedThreadKey(input));+ const closeForPdf = (state: ThreadPreviewState) => {+ const navigation = state.sessions[input.tabId]?.navStatus;+ if (+ navigation?._tag === "Success" &&+ previewPdfAssetUrl(navigation.url, navigation.url) !== null+ ) {+ onLeave();+ }+ };+ // PDFs render in the client and cannot appear in the server's video stream.+ stopWatchingPreview = appAtomRegistry.subscribe(atom, closeForPdf);+ closeForPdf(appAtomRegistry.get(atom));+ if (active === current) void connect(false);+ }}diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsxindex 8bd44e6e112..bb5ca593f64 100644--- a/apps/web/src/components/files/BrowserDocumentFrame.tsx+++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx@@ -34,8 +34,6 @@ import { readLocalApi } from "~/localApi";import { cn } from "~/lib/utils";import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";-const PDF_VIEWER_FRAGMENT = "#toolbar=0&view=FitH";-/*** The page reports the keys, and a page script can report any key it likes,* so only commands that change what the reader sees are here, never one that@@ -65,8 +63,7 @@ export const isPdfPreviewFile = (path: string): boolean =>/*** HTML runs in a sandboxed frame with an opaque origin, so a page cannot reach- * the app's session or storage. The built-in PDF viewer needs an unsandboxed- * frame; a PDF runs no scripts.+ * the app's session or storage. PDFs use the browser's native viewer.*/export function BrowserDocumentFrame(props: {readonly src: string;@@ -77,12 +74,12 @@ export function BrowserDocumentFrame(props: {}) {const className = "min-h-0 flex-1 border-0 bg-white";return props.pdf ? (- // oxlint-disable-next-line react/iframe-missing-sandbox -- the built-in PDF viewer needs an unsandboxed frame.- <iframe+ <embedkey={props.src}- src={`${props.src}${PDF_VIEWER_FRAGMENT}`}+ src={props.src}+ type="application/pdf"title={props.title}- className={className}+ className="min-h-0 w-full flex-1 border-0"/>) : props.htmlRender ? (<HtmlRenderDocumentdiff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsxindex 85b743763f2..5ffbb09cbe6 100644--- a/apps/web/src/components/preview/PreviewView.tsx+++ b/apps/web/src/components/preview/PreviewView.tsx@@ -18,7 +18,11 @@ import {PREVIEW_ZOOM_LEVELS,type PreviewAdjustInput,} from "@t3tools/contracts";-import { normalizePreviewUrl, resolveAddressBarInput } from "@t3tools/shared/preview";+import {+ normalizePreviewUrl,+ resolveAddressBarInput,+ previewPdfAssetUrl,+} from "@t3tools/shared/preview";import { useEffect, useEffectEvent, useRef, useState } from "react";import {@@ -997,6 +1001,11 @@ export function PreviewView({environmentId={threadRef.environmentId}threadId={threadRef.threadId}tabId={snapshot.tabId}+ pdfUrl={+ navStatus._tag === "Success"+ ? previewPdfAssetUrl(url, environmentHttpBaseUrl)+ : null+ }visible={visible}onFirstFrame={() => setServerFrameTabId(runtimeTabId)}onControl={(control) =>diff --git a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsxindex 1764fea23df..2155d6f0d19 100644--- a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx+++ b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx@@ -1,6 +1,8 @@"use client";import { FILL_PREVIEW_VIEWPORT, type ScopedThreadRef } from "@t3tools/contracts";+import { previewPdfAssetUrl } from "@t3tools/shared/preview";+import { useEnvironmentHttpBaseUrl } from "~/state/environments";import { PanelRightIcon, PictureInPicture2, XIcon } from "lucide-react";import {type PointerEvent as ReactPointerEvent,@@ -114,6 +116,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, miniPlayer }: Props) {}function BrowserMiniPlayer({ threadRef, tabId, miniPlayer }: Props & { readonly tabId: string }) {+ const httpBaseUrl = useEnvironmentHttpBaseUrl(threadRef.environmentId);const previewState = useThreadPreviewState(threadRef);const snapshot = previewState.sessions[tabId] ?? null;const runtimeTabId = previewRuntimeTabId(threadRef, previewState.serverEpoch, tabId);@@ -171,8 +174,14 @@ function BrowserMiniPlayer({ threadRef, tabId, miniPlayer }: Props & { readonly};if (!snapshot) return null;+ const pdfUrl =+ snapshot.navStatus._tag === "Success"+ ? previewPdfAssetUrl(snapshot.navStatus.url, httpBaseUrl)+ : null;const poppedOut = serverTab ? serverPictureInPicture : Boolean(desktopOverlay?.pictureInPicture);- const canPopOut = serverTab ? supportsServerPictureInPicture() : true;+ const canPopOut = serverTab+ ? poppedOut || (pdfUrl === null && supportsServerPictureInPicture())+ : true;return (<MiniPlayerShell@@ -219,6 +228,7 @@ function BrowserMiniPlayer({ threadRef, tabId, miniPlayer }: Props & { readonlyenvironmentId={threadRef.environmentId}threadId={threadRef.threadId}tabId={tabId}+ pdfUrl={pdfUrl}visiblefollowSize={false}controlPosition="bottom"diff --git a/packages/shared/src/preview.test.ts b/packages/shared/src/preview.test.tsindex afa4f531c17..b08c9b12423 100644--- a/packages/shared/src/preview.test.ts+++ b/packages/shared/src/preview.test.ts@@ -6,8 +6,63 @@ import {normalizePreviewUrl,PreviewUrlNormalizationError,resolveAddressBarInput,+ previewPdfAssetUrl,} from "./preview.ts";+describe("previewPdfAssetUrl", () => {+ it.each([+ "http://localhost:6497",+ "https://host.tailnet.test",+ "https://environment.tunnel.test",+ ])("loads PDF bytes through the client's connection at %s", (base) => {+ expect(+ previewPdfAssetUrl(+ "http://127.0.0.1:14537/api/assets/signed-token/Study%20guide.PDF?revision=2#page=8",+ base,+ ),+ ).toBe(`${base}/api/assets/signed-token/Study%20guide.PDF?revision=2#page=8`);+ });++ it.each([+ "http://localhost:6497/api/assets/token/index.html",+ "https://example.com/paper.pdf",+ "file:///api/assets/token/paper.pdf",+ "javascript:alert(1)",+ "invalid",+ ])("leaves non-asset documents on their browser session: %s", (url) => {+ expect(previewPdfAssetUrl(url, "https://environment.test")).toBeNull();+ });++ it("waits for the environment connection", () => {+ expect(previewPdfAssetUrl("http://localhost/api/assets/token/paper.pdf", null)).toBeNull();+ });++ it.each(["another-environment.test", "127.0.0.2.example.com", "128.0.0.1"])(+ "preserves matching PDF URLs on unrelated host %s",+ (host) => {+ const source = `https://${host}/api/assets/token/guide.pdf?revision=2#page=3`;+ expect(previewPdfAssetUrl(source, "https://environment.test")).toBe(source);+ },+ );++ it("keeps URLs from the connected environment", () => {+ const source = "https://environment.test/api/assets/token/guide.pdf#page=2";+ expect(previewPdfAssetUrl(source, "https://environment.test")).toBe(source);+ });++ it.each(["127.0.0.2", "127.255.255.254", "localhost.", "[::1]", "0.0.0.0"])(+ "remaps local assets on %s through the client connection",+ (host) => {+ expect(+ previewPdfAssetUrl(+ `http://${host}:14537/api/assets/token/guide.pdf?revision=2#page=3`,+ "https://remote.test",+ ),+ ).toBe("https://remote.test/api/assets/token/guide.pdf?revision=2#page=3");+ },+ );+});+describe("resolveAddressBarInput", () => {it("opens what users type as addresses", () => {expect(resolveAddressBarInput("localhost:5173")).toBe("http://localhost:5173/");diff --git a/packages/shared/src/preview.ts b/packages/shared/src/preview.tsindex 15f423a0618..5da5f66b44c 100644--- a/packages/shared/src/preview.ts+++ b/packages/shared/src/preview.ts@@ -1,8 +1,37 @@import * as Schema from "effect/Schema";+import { isLocalLoopbackHost } from "./hostClassification.ts";+const TAB_ID_PREFIX = "tab_";let nextPreviewTabSequence = 0;+export function previewPdfAssetUrl(rawUrl: string, httpBaseUrl: string | null): string | null {+ if (httpBaseUrl === null) return null;+ try {+ const url = new URL(rawUrl);+ const baseUrl = new URL(httpBaseUrl);+ if (+ (url.protocol !== "http:" && url.protocol !== "https:") ||+ !url.pathname.startsWith("/api/assets/") ||+ !/\.pdf$/i.test(url.pathname)+ ) {+ return null;+ }+ if (+ url.origin !== baseUrl.origin &&+ !isLocalLoopbackHost(url.hostname) &&+ url.hostname !== "0.0.0.0"+ ) {+ return url.href;+ }+ // The browser may run on the host's loopback address. Fetch signed bytes+ // through this client's environment connection, including remote routes.+ return new URL(`${url.pathname}${url.search}${url.hash}`, baseUrl).href;+ } catch {+ return null;+ }+}+export function newPreviewTabId(): string {nextPreviewTabSequence += 1;return `${TAB_ID_PREFIX}${nextPreviewTabSequence.toString(36)}`;diff --git a/patches/[email protected] b/patches/[email protected]new file mode 100644index 00000000000..fae81c54646--- /dev/null+++ b/patches/[email protected]@@ -0,0 +1,23 @@+diff --git a/android/build.gradle b/android/build.gradle+--- a/android/build.gradle++++ b/android/build.gradle+@@ -128,7 +128,7 @@+ buildTypes {+ release {+ minifyEnabled false+- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'++ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'++ externalNativeBuild {+ cmake {+diff --git a/android/src/main/java/org/wonday/pdf/RNPDFPackage.java b/android/src/main/java/org/wonday/pdf/RNPDFPackage.java+--- a/android/src/main/java/org/wonday/pdf/RNPDFPackage.java++++ b/android/src/main/java/org/wonday/pdf/RNPDFPackage.java+@@ -11,3 +11,7 @@+ public class RNPDFPackage implements ReactPackage {+++ static {++ System.loadLibrary("NitroPdfJsi");++ }+++ @Overridediff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 741001ee908..01e7f2be6dc 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -180,6 +180,7 @@ patchedDependencies:[email protected]: f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651[email protected]: abe20e1d1c23549297cbbc818e14fe479b41455930d9663135d6b40fe359b626[email protected]: f28d08f1233e3cce8b9324b4357d2b10f1ee040b8051bc87235b0fb95069b9bb+ [email protected]: 6f52854210f61bef499850ebd498229a111bc34ec5b2a4925e644f2f48f42760[email protected]: 81caa279ec3dc1f81209062133b66e8f824e13f106cca57f1fa732a72c2ab378importers:@@ -353,6 +354,9 @@ importers:'@react-native-ai/apple':specifier: 0.12.0version: 0.12.0(patch_hash=2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))+ '@react-native-async-storage/async-storage':+ specifier: 3.1.1+ version: 3.1.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])'@react-native-menu/menu':specifier: ^2.0.0version: 2.0.0(patch_hash=a4866ecfcd44f318043de839d20110c17e14909004900f002ffe12050376f2ba)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])@@ -548,6 +552,9 @@ importers:react-native:specifier: 0.88.0version: 0.88.0(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])+ react-native-blob-util:+ specifier: 0.25.1+ version: 0.25.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])react-native-enriched-markdown:specifier: file:deps/react-native-enriched-markdown-1.2.0-t3.15.tgzversion: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])@@ -560,6 +567,12 @@ importers:react-native-keyboard-controller:specifier: 1.22.7version: 1.22.7(patch_hash=f28d08f1233e3cce8b9324b4357d2b10f1ee040b8051bc87235b0fb95069b9bb)([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ react-native-nitro-modules:+ specifier: 0.37.1+ version: 0.37.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ react-native-pdf-jsi:+ specifier: 5.0.0+ version: 5.0.0(patch_hash=6f52854210f61bef499850ebd498229a111bc34ec5b2a4925e644f2f48f42760)(cf7d6840207b805fdc65940b34f32bb4)react-native-reanimated:specifier: 4.7.1version: 4.7.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])@@ -5505,6 +5518,12 @@ packages:peerDependencies:react-native: '>=0.76.0'+ '@react-native-async-storage/[email protected]':+ resolution: {integrity: sha512-z+PnLz1n6ECKhgoHZHkfc+dijXZEyZnNFSajbtE0NEbsJhmX8x9GlOeiMQIKX2E4DUqPSgfIh4FYBv1M49KgPQ==}+ peerDependencies:+ react: '*'+ react-native: '*'+'@react-native-masked-view/[email protected]':resolution: {integrity: sha512-XwuQoW7/GEgWRMovOQtX3A4PrXhyaZm0lVUiY8qJDvdngjLms9Cpdck6SmGAUNqQwcj2EadHC1HwL0bEyoa/SQ==}peerDependencies:@@ -5579,6 +5598,9 @@ packages:resolution: {integrity: sha512-iPV2HNXlPs7xQDBJJGIjkH0x2psZwJeRIEpfSqxgqLaO5eEfE2Ccicfz2OBHBcIC5jKGGa4IoI/e26zMNDuTMQ==}engines: {node: ^22.13.0 || ^24.3.0 || >= 26.0.0}+ '@react-native/[email protected]':+ resolution: {integrity: sha512-Z1jQI2NpdFJCVgpY+8Dq/Bt3d+YUi1928Q+/CZm/oh66fzM0RUl54vvuXlPJKybH4pdCZey1eDTPaLHkMPNgWA==}+'@react-native/[email protected]':resolution: {integrity: sha512-eZCu3tGAQCfvMCPQJVY4dmoMX8ZZYBvqIGHX7lwOYyzNK+Dl8e5ky7ZoXub1Rq75oSrQXNNmSP2CDjNNXXZpFQ==}@@ -8369,6 +8391,9 @@ packages:resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}engines: {node: '>= 0.8'}+ resolution: {integrity: sha512-pWD0voFtNYxrVqvBMYf5gq3NA2GCpfodS1yNynTPc93AYA/KEMGeWDqqeUB6R2Z9ZofVhks2aeJXiuQqKNpesA==}+resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}engines: {node: '>=6'}@@ -9544,6 +9569,9 @@ packages:resolution: {integrity: sha512-8Sb3veuYCyrZL+VBt9LJfZjLUPWVvqn8tG28VqYNFCo43KHcKuq+b4EiXGeuaLAQWL2YmyDgMp2aSpH9JHsEQg==}+ resolution: {integrity: sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==}+resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}engines: {node: '>= 4'}@@ -10993,6 +11021,9 @@ packages:resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==}engines: {node: '>= 6'}+ resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}+resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}@@ -11108,6 +11139,9 @@ packages:react:optional: true+ resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}+resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==}@@ -11123,6 +11157,12 @@ packages:'@types/react': '>=18'react: '>=18'+ resolution: {integrity: sha512-HMzab2SL8h48pvfufji0TKdet/jnNvamxYmYyNqTV5YOge00V28ycdc3S4leHjGXMJ1+fS2j2SrQ3aG5pzbx1w==}+ peerDependencies:+ react: '*'+ react-native: '*'+react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz:resolution: {integrity: sha512-p9o8zNoVoNwqdlG8a9Fvhj0RFUjmpE6VecwOVsO6a8Alj2HPfCDzeLBq0SFn2KdUYX32MC2fH1gJJs/HyfP5Mg==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz}version: 1.2.0-t3.15@@ -11159,6 +11199,21 @@ packages:react-native: '*'react-native-reanimated: '>=3.0.0'+ resolution: {integrity: sha512-KpW6EQVQ/bfegpCGxN9Be+ndvsfj56t4IESEvCASu9gWpJa/NDfHpIeIwCOvZQ3eXmLEj6YD4wCLqcC1FJPr2w==}+ peerDependencies:+ react: '*'+ react-native: '*'++ resolution: {integrity: sha512-yemeI1tWRfG0IUbUcc/aD757kBI0qCLqFZJ6pTd4eAIsnuNwpqahAviUj7C3JG2Ddl5LEElwwFx49nUi1RXZmg==}+ peerDependencies:+ '@react-native-async-storage/async-storage': '>=1.17.0'+ react: '*'+ react-native: '*'+ react-native-blob-util: '>=0.13.7'+ react-native-nitro-modules: ^0.37.1+resolution: {integrity: sha512-HviDFSZ6V4KTRsrLS6hRbBJ4j63l/L8a5az0EoWdJwaMLYnBNyYISTDxwXpEYkMbAbLzCMCviIdiOxXHYQWcNA==}peerDependencies:@@ -16194,6 +16249,12 @@ snapshots:react-native: 0.88.0(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])zod: 4.4.3+ '@react-native-async-storage/[email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])':+ dependencies:+ idb: 8.0.3+ react: 19.3.0+ react-native: 0.88.0(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])+'@react-native-masked-view/[email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:react: 19.3.0@@ -16331,6 +16392,8 @@ snapshots:- supports-color- utf-8-validate+ '@react-native/[email protected]': {}+'@react-native/[email protected]': {}'@react-native/[email protected](@types/[email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])':@@ -19089,6 +19152,12 @@ snapshots:+ dependencies:+ '@react-native/normalize-color': 2.1.0+ invariant: 2.2.4+ prop-types: 15.8.1+@@ -20409,6 +20478,8 @@ snapshots:optional: true+ [email protected]: {}+@@ -22264,6 +22335,12 @@ snapshots:kleur: 3.0.3sisteransi: 1.0.5+ dependencies:+ loose-envify: 1.4.0+ object-assign: 4.1.1+ react-is: 16.13.1+dependencies:graceful-fs: 4.2.11@@ -22414,6 +22491,8 @@ snapshots:optionalDependencies:react: 19.3.0+ [email protected]: {}+@@ -22438,6 +22517,12 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):+ dependencies:+ base-64: 1.0.0+ react: 19.3.0+ react-native: 0.88.0(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])+react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):dependencies:react: 19.3.0@@ -22469,6 +22554,21 @@ snapshots:react-native-is-edge-to-edge: 1.3.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])react-native-reanimated: 4.7.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ [email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):+ dependencies:+ react: 19.3.0+ react-native: 0.88.0(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])++ [email protected](patch_hash=6f52854210f61bef499850ebd498229a111bc34ec5b2a4925e644f2f48f42760)(cf7d6840207b805fdc65940b34f32bb4):+ dependencies:+ '@react-native-async-storage/async-storage': 3.1.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ crypto-js: 4.2.0+ deprecated-react-native-prop-types: 2.3.0+ react: 19.3.0+ react-native: 0.88.0(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])+ react-native-blob-util: 0.25.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ react-native-nitro-modules: 0.37.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+[email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):dependencies:react: 19.3.0diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 24f6b7b292e..bb94794604b 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -333,6 +333,7 @@ patchedDependencies:[email protected]: patches/[email protected][email protected]: patches/[email protected][email protected]: patches/[email protected]+ [email protected]: patches/[email protected]# Android: a nested WebView hands a vertical drag to its scrolling parent at the page's edge.[email protected]: patches/[email protected]"@expo/[email protected]": patches/@[email protected]diff --git a/third-party-licenses.config.json b/third-party-licenses.config.jsonindex f247cf5c17c..25a2b74f849 100644--- a/third-party-licenses.config.json+++ b/third-party-licenses.config.json@@ -150,6 +150,33 @@}],"packageOverrides": [+ {+ "name": "@react-native-async-storage/async-storage",+ "version": "3.1.1",+ "sourceUrl": "https://github.com/react-native-async-storage/async-storage",+ "generatedNotice": {+ "licenseId": "MIT",+ "copyrights": ["Copyright (c) 2025 Krzysztof Borowy"]+ }+ },+ {+ "name": "deprecated-react-native-prop-types",+ "version": "2.3.0",+ "sourceUrl": "https://github.com/facebookarchive/react-native-deprecated-modules",+ "generatedNotice": {+ "licenseId": "MIT",+ "copyrights": ["Copyright (c) Meta Platforms, Inc. and affiliates."]+ }+ },+ {+ "name": "@react-native/normalize-color",+ "version": "2.1.0",+ "sourceUrl": "https://github.com/facebook/react-native",+ "generatedNotice": {+ "licenseId": "MIT",+ "copyrights": ["Copyright (c) Meta Platforms, Inc. and affiliates."]+ }+ },{"name": "@bufbuild/protobuf","version": "1.10.0",