Skip to content
TypeScript

feat(mobile): play audio inline and open shared files in the viewer (#21353)

maria7bafc40c17ab
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
index d78fa318051..a5b8f7a44e3 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
@@ -10,6 +10,7 @@ public final class T3NativeControlsModule: Module {
private var filePresentation: T3NativeFilePresentation?
public func definition() -> ModuleDefinition {
+ Events("videoPlaybackChange")
Constants {
if #available(iOS 26.0, *) {
return [
@@ -247,10 +248,16 @@ public final class T3NativeControlsModule: Module {
userInfo: [NSLocalizedDescriptionKey: "The video preview is no longer available."]
)
}
- let presentation = T3NativeVideoPresentation(identifier: identifier, url: url, title: title) { [weak self] error in
- self?.videoPresentation = nil
- if let error { promise.reject(error) } else { promise.resolve(nil) }
- }
+ let presentation = T3NativeVideoPresentation(
+ identifier: identifier, url: url, title: title,
+ onPlaybackChange: { [weak self] isPlaying in
+ self?.sendEvent("videoPlaybackChange", ["identifier": identifier, "isPlaying": isPlaying])
+ },
+ completion: { [weak self] error in
+ self?.videoPresentation = nil
+ if let error { promise.reject(error) } else { promise.resolve(nil) }
+ }
+ )
videoPresentation = presentation
presentation.present(from: presenter, sources: presentationSources, sourceIdentifier: sourceIdentifier)
}
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift
index 388e12cb668..fa0fdcafa7c 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift
@@ -7,6 +7,7 @@ final class T3NativeVideoPresentation: NSObject, AVPlayerViewControllerDelegate,
private let controller = AVPlayerViewController()
private let completion: (Error?) -> Void
private var itemObservation: NSKeyValueObservation?
+ private var playbackObservation: NSKeyValueObservation?
private var backgroundObserver: NSObjectProtocol?
private var playbackError: Error?
private var presented = false
@@ -27,7 +28,8 @@ final class T3NativeVideoPresentation: NSObject, AVPlayerViewControllerDelegate,
private weak var fullScreenController: UIViewController?
private var embedded = false
- init(identifier: String, url: URL, title: String, completion: @escaping (Error?) -> Void) {
+ init(identifier: String, url: URL, title: String,
+ onPlaybackChange: @escaping (Bool) -> Void, completion: @escaping (Error?) -> Void) {
self.identifier = identifier
self.completion = completion
super.init()
@@ -38,6 +40,12 @@ final class T3NativeVideoPresentation: NSObject, AVPlayerViewControllerDelegate,
metadata.value = title as NSString
item.externalMetadata = [metadata]
controller.player = AVPlayer(playerItem: item)
+ playbackObservation = controller.player?.observe(\.timeControlStatus, options: [.new]) { player, _ in
+ // Waiting keeps the playback request alive through buffering and seeks.
+ if player.timeControlStatus != .waitingToPlayAtSpecifiedRate {
+ onPlaybackChange(player.timeControlStatus == .playing)
+ }
+ }
controller.delegate = self
controller.overrideUserInterfaceStyle = .dark
controller.allowsPictureInPicturePlayback = false
@@ -148,6 +156,7 @@ final class T3NativeVideoPresentation: NSObject, AVPlayerViewControllerDelegate,
controller.removeFromParent()
}
itemObservation = nil
+ playbackObservation = nil
controller.player = nil
if let backgroundObserver { NotificationCenter.default.removeObserver(backgroundObserver) }
backgroundObserver = nil
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index c99de977505..2206592f5b2 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -119,7 +119,7 @@
"expo-sqlite": "~58.0.13",
"expo-symbols": "~58.0.4",
"expo-updates": "~58.0.17",
- "expo-video": "~58.0.11",
+ "expo-video": "58.0.11",
"expo-web-browser": "~58.0.6",
"expo-widgets": "58.0.20",
"react": "catalog:",
@@ -179,6 +179,7 @@
"react-native-reanimated",
"@react-native-menu/menu",
"expo-audio",
+ "expo-video",
"expo-network"
]
}
diff --git a/apps/mobile/src/components/FilePreviewModal.tsx b/apps/mobile/src/components/FilePreviewModal.tsx
index fe2ebdfdfb2..77116c88001 100644
--- a/apps/mobile/src/components/FilePreviewModal.tsx
+++ b/apps/mobile/src/components/FilePreviewModal.tsx
@@ -12,6 +12,11 @@ import {
import { Keyboard } from "react-native";
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
+import {
+ downloadAndShareAttachment,
+ nativeViewerErrorMessage,
+ shareLocalAttachment,
+} from "../lib/attachmentDownload";
import { useRefreshAssetUrl } from "../state/assets";
import { filePreviewGallery, filePreviewKey, filePreviewName } from "../lib/filePreviewGallery";
import { FilePreviewGallery } from "./FilePreviewGallery";
@@ -122,6 +127,32 @@ function ResolvedFilePreview(props: {
[items, resolved],
);
const ready = selected && gallery.length === items.length;
+ const onOpenError = (error: unknown) => {
+ if (props.onOpenError) return props.onOpenError(error);
+ Dialog.alert("Could not open preview", nativeViewerErrorMessage(error), [
+ { text: "Cancel", style: "cancel" },
+ ...(selected?.kind === "document"
+ ? [
+ {
+ text: "Save or share",
+ onPress: () => {
+ const input = {
+ attachment: {
+ name: filePreviewName(selected),
+ mimeType: selected.mimeType ?? "application/octet-stream",
+ },
+ signal: new AbortController().signal,
+ };
+ const sharing = /^(file|content):/.test(selected.uri)
+ ? shareLocalAttachment({ ...input, uri: selected.uri })
+ : downloadAndShareAttachment({ ...input, url: selected.uri });
+ void sharing.catch(() => Dialog.alert("Could not share file", "Please try again."));
+ },
+ },
+ ]
+ : []),
+ ]);
+ };
return (
<>
{items.map((item) => (
@@ -137,7 +168,7 @@ function ResolvedFilePreview(props: {
<FilePreview
source={{ ...selected, gallery }}
onRequestClose={props.onRequestClose}
- onOpenError={props.onOpenError}
+ onOpenError={onOpenError}
/>
) : null}
</>
diff --git a/apps/mobile/src/components/MediaVideoPlayer.tsx b/apps/mobile/src/components/MediaVideoPlayer.tsx
index 709fcb96850..ec30709c1d6 100644
--- a/apps/mobile/src/components/MediaVideoPlayer.tsx
+++ b/apps/mobile/src/components/MediaVideoPlayer.tsx
@@ -1,7 +1,7 @@
import { useIsFocused } from "@react-navigation/native";
import { useEvent } from "expo";
import { useVideoPlayer, VideoView } from "expo-video";
-import { useEffect, useEffectEvent, useRef, useState } from "react";
+import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { AppState, Pressable, View } from "react-native";
import { AppActivityIndicator } from "./ui/AppActivityIndicator";
@@ -12,12 +12,14 @@ import { useMediaActions } from "../state/mediaActions";
import { type MediaActionsSource } from "../lib/mediaActionsSource";
import { useFullscreenVideoOpen, useMediaAudioSessionHold } from "../lib/videoAudioSession";
import { MediaActionsMenu } from "./MediaActionsMenu";
+import { createAudioPlaybackSession } from "../lib/audioSession";
function LoadedMediaVideo(props: {
readonly uri: string;
readonly resolvePlaybackUri?: () => Promise<string | null>;
readonly playRequested: boolean;
readonly paused: boolean;
+ readonly onPlaybackStart?: () => void;
}) {
const focused = useIsFocused();
const fullscreenVideoOpen = useFullscreenVideoOpen();
@@ -31,6 +33,38 @@ function LoadedMediaVideo(props: {
player.staysActiveInBackground = false;
player.bufferOptions = { preferredForwardBufferDuration: 5 };
});
+ const playback = useMemo(() => createAudioPlaybackSession(player, true), [player]);
+ const previousPlaybackRequested = useRef(false);
+ const onPlaybackStart = useEffectEvent(() => props.onPlaybackStart?.());
+ useEffect(() => {
+ const subscription = player.addListener("playingChange", ({ isPlaying }) => {
+ if (isPlaying && !active.current && !fullscreen.current) playback.pause();
+ else playback.playingChanged(isPlaying);
+ });
+ const requested = player.addListener("playbackRequestedChange", ({ isPlaybackRequested }) => {
+ const wasPlaybackRequested = previousPlaybackRequested.current;
+ previousPlaybackRequested.current = isPlaybackRequested;
+ if (!isPlaybackRequested) {
+ if (playback.requested) playback.pause();
+ } else if (!active.current && !fullscreen.current) playback.pause();
+ else {
+ if (!wasPlaybackRequested) onPlaybackStart();
+ playback.playingChanged(true);
+ }
+ });
+ const ended = player.addListener("playToEnd", () => playback.pause());
+ const failed = player.addListener("statusChange", ({ status }) => {
+ if (status === "error") playback.pause();
+ });
+ return () => {
+ subscription.remove();
+ requested.remove();
+ ended.remove();
+ failed.remove();
+ playback.pause();
+ previousPlaybackRequested.current = false;
+ };
+ }, [player, playback]);
const { status } = useEvent(player, "statusChange", { status: player.status });
const { isPlaying } = useEvent(player, "playingChange", { isPlaying: player.playing });
useMediaAudioSessionHold(isPlaying);
@@ -38,21 +72,22 @@ function LoadedMediaVideo(props: {
const uri = props.resolvePlaybackUri ? await props.resolvePlaybackUri() : props.uri;
if (signal.aborted) return;
if (uri === null) throw new Error("Video unavailable");
- player.pause();
+ playback.pause();
+ previousPlaybackRequested.current = false;
await player.replaceAsync({ uri, contentType: "progressive" });
- if (!signal.aborted && props.playRequested && active.current) player.play();
+ if (!signal.aborted && props.playRequested && active.current) await playback.play();
});
useEffect(() => {
active.current = focused && !paused && AppState.currentState === "active";
- if (!focused || paused || (!active.current && !fullscreen.current)) player.pause();
+ if (!focused || paused || (!active.current && !fullscreen.current)) playback.pause();
// RN reports both leaving the app and Android fullscreen as background; native handling distinguishes them.
const subscription = AppState.addEventListener("change", (state) => {
active.current = focused && !paused && state === "active";
- if (state === "inactive" || (state === "background" && !fullscreen.current)) player.pause();
+ if (state === "inactive" || (state === "background" && !fullscreen.current)) playback.pause();
});
return () => subscription.remove();
- }, [focused, player, paused]);
+ }, [focused, playback, paused]);
useEffect(() => {
const controller = new AbortController();
@@ -117,6 +152,7 @@ interface MediaVideoPlayerProps {
readonly expanded?: boolean;
readonly autoPlay?: boolean;
readonly paused?: boolean;
+ readonly onPlaybackStart?: () => void;
readonly actionsSource?: MediaActionsSource;
}
@@ -138,6 +174,7 @@ function MediaVideoPlayerContent(props: MediaVideoPlayerProps) {
resolvePlaybackUri={props.resolvePlaybackUri}
playRequested={!props.expanded || props.autoPlay === true}
paused={(props.paused ?? false) || mediaActions.sharing}
+ onPlaybackStart={props.onPlaybackStart}
/>
) : (
<MediaActionsMenu media={mediaActions} inModal={props.expanded} style={{ flex: 1 }}>
@@ -150,7 +187,10 @@ function MediaVideoPlayerContent(props: MediaVideoPlayerProps) {
accessibilityState={{ disabled: props.uri === null || props.unavailable === true }}
// Stays pressable so the long-press menu still opens on a failed or unsigned tile.
onPress={() => {
- if (props.uri !== null && !props.unavailable) setPlaybackUri(props.uri);
+ if (props.uri !== null && !props.unavailable) {
+ props.onPlaybackStart?.();
+ setPlaybackUri(props.uri);
+ }
}}
className="flex-1 items-center justify-center px-4"
>
diff --git a/apps/mobile/src/components/VideoPreviewModal.ios.tsx b/apps/mobile/src/components/VideoPreviewModal.ios.tsx
index 2c95bdca396..eede25a97f0 100644
--- a/apps/mobile/src/components/VideoPreviewModal.ios.tsx
+++ b/apps/mobile/src/components/VideoPreviewModal.ios.tsx
@@ -11,6 +11,12 @@ import { fullscreenVideoClosed, fullscreenVideoOpened } from "../lib/videoAudioS
import { mediaVideoPreviewUri, type VideoPreviewSource } from "../lib/videoPreviewSource";
import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets";
import { usePreparedConnection } from "../state/session";
+import {
+ acquireAudioSession,
+ activateAudioSession,
+ isAudioSessionOwner,
+ releaseAudioSession,
+} from "../lib/audioSession";
export type { VideoPreviewSource } from "../lib/videoPreviewSource";
@@ -22,6 +28,10 @@ const NativeControls = requireNativeModule<{
identifier: string,
): Promise<void>;
dismissVideo(identifier: string): Promise<void>;
+ addListener(
+ event: "videoPlaybackChange",
+ listener: (event: { identifier: string; isPlaying: boolean }) => void,
+ ): { remove(): void };
}>("T3NativeControls");
function NativeVideoPreview(props: {
@@ -71,6 +81,29 @@ function NativeVideoPreview(props: {
useEffect(() => {
if (localAttachment === null && playbackUrl === null) return;
const controller = new AbortController();
+ let token: ReturnType<typeof acquireAudioSession> | null = null;
+ const release = () => {
+ if (token) void releaseAudioSession(token).catch(() => {});
+ token = null;
+ };
+ const acquire = () => {
+ const next = acquireAudioSession("playback", () => {
+ release();
+ void NativeControls.dismissVideo(identifier).catch(() => {});
+ });
+ if (!isAudioSessionOwner(next)) {
+ void NativeControls.dismissVideo(identifier).catch(() => {});
+ return null;
+ }
+ token = next;
+ return next;
+ };
+ const subscription = NativeControls.addListener("videoPlaybackChange", (event) => {
+ if (event.identifier !== identifier || controller.signal.aborted) return;
+ if (event.isPlaying) {
+ if (!token) acquire();
+ } else release();
+ });
let ready = false;
void (async () => {
const file =
@@ -82,6 +115,13 @@ function NativeVideoPreview(props: {
file?.dispose();
return;
}
+ const current = acquire();
+ if (!current || !(await activateAudioSession(current, true)) || controller.signal.aborted) {
+ release();
+ file?.dispose();
+ if (!controller.signal.aborted) onRequestClose();
+ return;
+ }
ready = true;
const presented = await settlePromise(() =>
NativeControls.presentVideo(
@@ -93,9 +133,11 @@ function NativeVideoPreview(props: {
);
// Native completion follows dismissal, so local playback keeps its file lease.
file?.dispose();
+ release();
if (AsyncResult.isFailure(presented)) throw squashAtomCommandFailure(presented);
if (!controller.signal.aborted) onRequestClose();
})().catch((error: unknown) => {
+ release();
if (controller.signal.aborted) return;
// AVKit gives no retry, so re-mint now; the cached URL may simply have expired.
if (ready) void refreshAssetUrl();
@@ -111,6 +153,8 @@ function NativeVideoPreview(props: {
});
return () => {
controller.abort();
+ subscription.remove();
+ release();
void NativeControls.dismissVideo(identifier).catch(() => undefined);
};
}, [localAttachment, name, source.sourceIdentifier, playbackUrl, identifier]);
diff --git a/apps/mobile/src/components/ui/AppSymbol.tsx b/apps/mobile/src/components/ui/AppSymbol.tsx
index 2571a3cafd5..4b17bddd3c3 100644
--- a/apps/mobile/src/components/ui/AppSymbol.tsx
+++ b/apps/mobile/src/components/ui/AppSymbol.tsx
@@ -99,6 +99,7 @@ import IconPlug from "@tabler/icons-react-native/IconPlug";
import IconPhoto from "@tabler/icons-react-native/IconPhoto";
import IconPin from "@tabler/icons-react-native/IconPin";
import IconPinnedOff from "@tabler/icons-react-native/IconPinnedOff";
+import IconPlayerPause from "@tabler/icons-react-native/IconPlayerPause";
import IconPlayerPlay from "@tabler/icons-react-native/IconPlayerPlay";
import IconPlayerStopFilled from "@tabler/icons-react-native/IconPlayerStopFilled";
import IconPlus from "@tabler/icons-react-native/IconPlus";
@@ -240,6 +241,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = {
pin: IconPin,
"pin.slash": IconPinnedOff,
play: IconPlayerPlay,
+ pause: IconPlayerPause,
plus: IconPlus,
minus: IconMinus,
"slash.circle": IconBan,
diff --git a/apps/mobile/src/features/files/AttachmentFileScreen.tsx b/apps/mobile/src/features/files/AttachmentFileScreen.tsx
index 0cd13c511e7..a88b561fbec 100644
--- a/apps/mobile/src/features/files/AttachmentFileScreen.tsx
+++ b/apps/mobile/src/features/files/AttachmentFileScreen.tsx
@@ -1,19 +1,18 @@
import { Toolbar } from "../../components/ui/Toolbar";
import * as Dialog from "../../components/ui/Dialog";
-/* oxlint-disable react/no-array-index-key -- Captured table rows and columns have stable positions and may contain identical values. */
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
import type { MenuAction } from "@react-native-menu/menu";
import { EnvironmentId } from "@t3tools/contracts";
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
import { useEffect, useRef, useState } from "react";
-import { Platform, ScrollView, View } from "react-native";
+import { Platform, View } from "react-native";
import {
AndroidHeaderIconButton,
AndroidScreenHeader,
} from "../../components/ui/AndroidScreenHeader";
-import { AppText as Text } from "../../components/ui/AppText";
+import { DelimitedFilePreview } from "./DelimitedFilePreview";
import { AudioFilePreview } from "./AudioFilePreview";
import { Menu } from "../../components/ui/Menu";
import { EmptyState } from "../../components/ui/EmptyState";
@@ -89,41 +88,7 @@ function AttachmentDocumentBody(props: {
</FilePreviewNotice>
) : null}
{table && document.activeMode === "table" ? (
- <ScrollView className="flex-1">
- {table.truncated ? (
- <FilePreviewNotice>
- Table limited to the first 100 rows and 30 columns. Source shows the rest.
- </FilePreviewNotice>
- ) : null}
- <ScrollView horizontal>
- <View>
- {table.rows.map((row, rowIndex) => (
- <View
- key={rowIndex}
- className={rowIndex === 0 ? "flex-row bg-subtle" : "flex-row"}
- >
- {row.map((cell, columnIndex) => (
- <View
- key={columnIndex}
- className="w-48 border-r border-b border-border px-3 py-2"
- >
- <Text
- selectable
- className={
- rowIndex === 0
- ? "text-sm font-t3-semibold text-foreground"
- : "text-sm text-foreground"
- }
- >
- {cell}
- </Text>
- </View>
- ))}
- </View>
- ))}
- </View>
- </ScrollView>
- </ScrollView>
+ <DelimitedFilePreview table={table} />
) : document.activeMode === "markdown" && props.environmentId ? (
<FileMarkdownPreview
cwd=""
diff --git a/apps/mobile/src/features/files/AudioFilePreview.tsx b/apps/mobile/src/features/files/AudioFilePreview.tsx
index 02358055e2a..f9c92a5e201 100644
--- a/apps/mobile/src/features/files/AudioFilePreview.tsx
+++ b/apps/mobile/src/features/files/AudioFilePreview.tsx
@@ -1,9 +1,11 @@
import { Button } from "../../components/ui/Button";
-import { useAudioPlayer, useAudioPlayerStatus } from "expo-audio";
-import { useEffect, useState } from "react";
-import { View } from "react-native";
+import { useAudioPlayerStatus } from "expo-audio";
+import { useEffect, useMemo, useState } from "react";
+import { AppState, View } from "react-native";
import { AppText as Text } from "../../components/ui/AppText";
import { useFullscreenVideoOpen, useMediaAudioSessionHold } from "../../lib/videoAudioSession";
+import { createAudioPlaybackSession } from "../../lib/audioSession";
+import { usePlaybackAudioPlayer } from "../voice-input/usePlaybackAudioPlayer";
function timestamp(seconds: number) {
const value = Number.isFinite(seconds) ? Math.max(0, Math.floor(seconds)) : 0;
@@ -11,23 +13,33 @@ function timestamp(seconds: number) {
}
export function AudioFilePreview(props: { uri: string; onRetry: () => void }) {
- const player = useAudioPlayer({ uri: props.uri }, { updateInterval: 500 });
+ const player = usePlaybackAudioPlayer(props.uri);
const status = useAudioPlayerStatus(player);
+ const [playbackRequested, setPlaybackRequested] = useState(false);
+ const playback = useMemo(
+ () => createAudioPlaybackSession(player, false, setPlaybackRequested),
+ [player],
+ );
const [seekError, setSeekError] = useState(false);
// Video teardown deactivates the shared iOS session, which would stop this player.
useMediaAudioSessionHold(status.playing);
const fullscreenVideoOpen = useFullscreenVideoOpen();
useEffect(() => {
- if (fullscreenVideoOpen) player.pause();
- }, [fullscreenVideoOpen, player]);
- const seek = (seconds: number, play = false) => {
+ if (fullscreenVideoOpen || status.didJustFinish || status.error) playback.pause();
+ else playback.playingChanged(status.playing);
+ }, [fullscreenVideoOpen, status.didJustFinish, status.error, status.playing, playback]);
+ useEffect(() => {
+ const subscription = AppState.addEventListener("change", (state) => {
+ if (state !== "active") playback.pause();
+ });
+ return () => {
+ subscription.remove();
+ playback.pause();
+ };
+ }, [playback]);
+ const seek = (seconds: number) => {
setSeekError(false);
- void player
- .seekTo(seconds)
- .then(() => {
- if (play) player.play();
- })
- .catch(() => setSeekError(true));
+ void player.seekTo(seconds).catch(() => setSeekError(true));
};
return (
<View className="flex-1 items-center justify-center gap-5 p-6">
@@ -43,13 +55,23 @@ export function AudioFilePreview(props: { uri: string; onRetry: () => void }) {
onPress={() => seek(Math.max(0, status.currentTime - 15))}
/>
<Button
- label={!status.isLoaded ? "Loading…" : status.playing ? "Pause" : "Play"}
+ label={
+ playbackRequested || status.playing ? "Pause" : !status.isLoaded ? "Loading…" : "Play"
+ }
tone="secondary"
- disabled={!status.isLoaded}
+ disabled={!status.isLoaded && !playbackRequested}
onPress={() => {
- if (status.playing) player.pause();
- else if (status.didJustFinish || status.currentTime >= status.duration) seek(0, true);
- else player.play();
+ if (status.playing || playback.requested) playback.pause();
+ else {
+ setSeekError(false);
+ void playback
+ .play(
+ status.didJustFinish || status.currentTime >= status.duration
+ ? () => player.seekTo(0)
+ : undefined,
+ )
+ .catch(() => setSeekError(true));
+ }
}}
/>
<Button
diff --git a/apps/mobile/src/features/files/DelimitedFilePreview.tsx b/apps/mobile/src/features/files/DelimitedFilePreview.tsx
new file mode 100644
index 00000000000..7aa0128598a
--- /dev/null
+++ b/apps/mobile/src/features/files/DelimitedFilePreview.tsx
@@ -0,0 +1,41 @@
+/* oxlint-disable react/no-array-index-key -- Captured table cells have stable positions and may contain identical values. */
+import { ScrollView, View } from "react-native";
+import type { parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
+import { AppText as Text } from "../../components/ui/AppText";
+import { FilePreviewNotice } from "./FilePreviewFeedback";
+
+export function DelimitedFilePreview(props: {
+ readonly table: ReturnType<typeof parseDelimitedPreview>;
+}) {
+ return (
+ <ScrollView className="flex-1">
+ {props.table.truncated ? (
+ <FilePreviewNotice>
+ Table limited to the first 100 rows and 30 columns. Source shows the rest.
+ </FilePreviewNotice>
+ ) : null}
+ <ScrollView horizontal>
+ <View>
+ {props.table.rows.map((row, rowIndex) => (
+ <View key={rowIndex} className={rowIndex === 0 ? "flex-row bg-subtle" : "flex-row"}>
+ {row.map((cell, columnIndex) => (
+ <View key={columnIndex} className="w-48 border-r border-b border-border px-3 py-2">
+ <Text
+ selectable
+ className={
+ rowIndex === 0
+ ? "text-sm font-t3-semibold text-foreground"
+ : "text-sm text-foreground"
+ }
+ >
+ {cell}
+ </Text>
+ </View>
+ ))}
+ </View>
+ ))}
+ </View>
+ </ScrollView>
+ </ScrollView>
+ );
+}
diff --git a/apps/mobile/src/features/files/FileMarkdownPreview.tsx b/apps/mobile/src/features/files/FileMarkdownPreview.tsx
index a0a6fa74346..bbd805ca574 100644
--- a/apps/mobile/src/features/files/FileMarkdownPreview.tsx
+++ b/apps/mobile/src/features/files/FileMarkdownPreview.tsx
@@ -3,6 +3,7 @@ import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { resolveMobileMarkdownMediaSource } from "../../lib/markdownMediaSource";
import { getBrowseDirectoryPath } from "@t3tools/client-runtime/state/projects";
import { useState } from "react";
+import { StackActions, useNavigation } from "@react-navigation/native";
import { RefreshControl, ScrollView, View } from "react-native";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
@@ -15,8 +16,12 @@ import {
ThreadMarkdownImageUnavailable,
} from "../threads/ThreadMarkdownImage";
import { ThreadMarkdownVideo } from "../threads/ThreadMarkdownVideo";
-import { resolveMarkdownMediaPreview } from "../../lib/markdownMedia";
-import { normalizeNativeMarkdownUrl } from "../../lib/markdownLinks";
+import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "../../lib/markdownMedia";
+import {
+ normalizeNativeMarkdownUrl,
+ resolveMarkdownLinkPresentation,
+} from "../../lib/markdownLinks";
+import { AppText as Text } from "../../components/ui/AppText";
import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
import { useMarkdownImageSource } from "../../native/useMarkdownImageSource";
@@ -26,7 +31,7 @@ import {
type MarkdownImageRenderer,
type NativeMarkdownTextStyle,
} from "../../native/SelectableMarkdownText";
-import { resolveWorkspaceFilePath } from "./filePath";
+import { fileRoutePathSegments, resolveWorkspaceFilePath } from "./filePath";
interface MarkdownPreviewStyles {
readonly nativeTextStyle: NativeMarkdownTextStyle;
@@ -78,6 +83,7 @@ export function FileMarkdownPreview(props: {
readonly threadId: ThreadId | null;
readonly onRefresh?: () => Promise<void> | void;
}) {
+ const navigation = useNavigation();
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
const [expandedFile, setExpandedFile] = useState<FilePreviewSource | null>(null);
const [expandedVideo, setExpandedVideo] = useState<VideoPreviewSource | null>(null);
@@ -106,6 +112,24 @@ export function FileMarkdownPreview(props: {
captured: props.captured,
imageEmbed: true,
});
+ const fileLink = resolveMarkdownLinkPresentation(image.href);
+ if (
+ (preview && preview.kind !== "image" && preview.kind !== "video") ||
+ (!props.captured && fileLink.kind === "file" && fileLink.line !== undefined)
+ ) {
+ const name =
+ preview?.source.name ?? (fileLink.kind === "file" ? fileLink.label : "Open file");
+ return (
+ <Text
+ accessibilityRole="link"
+ accessibilityLabel={`Open ${name}`}
+ onPress={() => openMedia(image.href, true)}
+ style={{ color: styles.nativeTextStyle.linkColor }}
+ >
+ {name}
+ </Text>
+ );
+ }
if (media?.access === "direct") {
if (media.kind === "video") {
return (
@@ -169,7 +193,21 @@ export function FileMarkdownPreview(props: {
captured: props.captured,
imageEmbed,
});
- if (!media) return false;
+ if (!media || media.kind === "file") {
+ const fileLink = resolveMarkdownLinkPresentation(href);
+ if (props.captured || fileLink.kind !== "file") return false;
+ const params = {
+ environmentId: String(props.environmentId),
+ path: fileRoutePathSegments(resolveWorkspaceFilePath(markdownDirectory, fileLink.path)),
+ ...(fileLink.line ? { line: String(fileLink.line) } : {}),
+ };
+ if (props.threadId) {
+ navigation.navigate("ThreadFile", { ...params, threadId: String(props.threadId) });
+ } else {
+ navigation.dispatch(StackActions.push("NewTaskFile", { ...params, cwd: props.cwd }));
+ }
+ return true;
+ }
if (media.kind === "video") setExpandedVideo(media.source);
else setExpandedFile(media.source);
return true;
@@ -198,6 +236,18 @@ export function FileMarkdownPreview(props: {
<View className="mx-auto w-full max-w-[760px]">
<SelectableMarkdownText
markdown={props.markdown}
+ fileEmbedLabel={(href) =>
+ markdownFileEmbedLabel(
+ href,
+ {
+ environmentId: props.environmentId,
+ threadId: props.threadId ?? undefined,
+ workspaceRoot: markdownDirectory,
+ captured: props.captured,
+ },
+ false,
+ )
+ }
onLinkPress={onLinkPress}
renderImage={renderImage}
resolveImageSource={resolveImageSource}
diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
index 7df96335579..3f2255a56b1 100644
--- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
+++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
@@ -18,6 +18,8 @@ import {
import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
import { ScreenContent } from "../../components/ui/ScreenContent";
+import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
+import { DelimitedFilePreview } from "./DelimitedFilePreview";
import { AudioFilePreview } from "./AudioFilePreview";
import { EmptyState } from "../../components/ui/EmptyState";
import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
@@ -207,7 +209,8 @@ function defaultViewMode(path: string | null): FileViewMode {
(isWorkspaceBrowserPreviewPath(path) ||
isWorkspaceImagePreviewPath(path) ||
isVideoPreviewFile(path) ||
- isAudioPreviewFile(path))
+ isAudioPreviewFile(path) ||
+ filePreviewDelimiter({ name: path }) !== null)
? "preview"
: "source";
}
@@ -237,6 +240,7 @@ function FileContent(props: {
const reservedHeaderInset =
Platform.OS === "ios" && props.truncated ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
const isMarkdown = isMarkdownPreviewFile(props.relativePath);
+ const delimiter = filePreviewDelimiter({ name: props.relativePath });
const isBrowserFile = isWorkspaceBrowserPreviewPath(props.relativePath);
const isImageFile = isWorkspaceImagePreviewPath(props.relativePath);
const isVideoFile = isVideoPreviewFile(props.relativePath);
@@ -312,7 +316,9 @@ function FileContent(props: {
Preview limited to the first 1 MB of a truncated file.
</FilePreviewNotice>
) : null}
- {props.activeMode === "preview" && isMarkdown ? (
+ {props.activeMode === "preview" && delimiter ? (
+ <DelimitedFilePreview table={parseDelimitedPreview(props.fileContents, delimiter)} />
+ ) : props.activeMode === "preview" && isMarkdown ? (
<FileMarkdownPreview
cwd={props.cwd}
environmentId={props.environmentId}
@@ -638,11 +644,14 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
isBrowserFile ||
isImageFile ||
isVideoFile ||
- isAudioFile);
+ isAudioFile ||
+ filePreviewDelimiter({ name: relativePath }) !== null);
const activeMode =
relativePath !== null && modeOverride?.path === relativePath
? modeOverride.mode
- : defaultViewMode(relativePath);
+ : targetLine !== null && filePreviewDelimiter({ name: relativePath ?? "" }) !== null
+ ? "source"
+ : defaultViewMode(relativePath);
const resolvedActiveMode =
isVideoFile || isAudioFile ? "preview" : canPreview ? activeMode : "source";
const assetPreviewPath =
@@ -706,7 +715,9 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
relativePath !== null &&
!isVideoFile &&
!isAudioFile &&
- (resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
+ (resolvedActiveMode === "source" ||
+ isMarkdownPreviewFile(relativePath) ||
+ filePreviewDelimiter({ name: relativePath }) !== null);
const fileQuery = useEnvironmentQuery(
canReadFiles &&
environmentId !== null &&
@@ -777,8 +788,8 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
canToggleMode
? ({
id: "preview",
- title: "Preview",
- icon: "eye",
+ title: filePreviewDelimiter({ name: relativePath }) ? "Table" : "Preview",
+ icon: filePreviewDelimiter({ name: relativePath }) ? "tablecells" : "eye",
inline: true,
onPress: () => setModeOverride({ path: relativePath, mode: "preview" }),
} as const)
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index a292965a975..fc9a853e211 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -132,7 +132,8 @@ import { assetImageSource } from "../../lib/assetImageSource";
import { composerImageGallery } from "../../lib/composerImageGallery";
import { messageImageGallery } from "./messageImageGallery";
import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
-import { isPdfFile } from "../../lib/filePreview";
+import { inlineFilePreviewKind, isPdfFile } from "../../lib/filePreview";
+import { ThreadInlineFilePreview } from "./ThreadInlineFilePreview";
import { flattenThemeColor } from "../../lib/mobileTheme";
import { PresentationSource } from "../../components/ui/NativePresentation";
import { NativeScrollViewMarker } from "../../native/NativeScrollViewMarker";
@@ -159,9 +160,8 @@ import {
import { AppText as Text } from "../../components/ui/AppText";
import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
-import { VideoAttachmentTile } from "../../components/VideoAttachmentTile";
import { MediaVideoPlayer } from "../../components/MediaVideoPlayer";
-import { resolveMarkdownMediaPreview } from "../../lib/markdownMedia";
+import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "../../lib/markdownMedia";
import {
attachmentVideoPreviewSource,
mediaVideoPreviewUri,
@@ -584,7 +584,7 @@ function MessageAttachmentFile(props: {
readonly environmentId: EnvironmentId;
readonly attachment: ChatFileAttachment;
readonly onPressPreview: (source: FilePreviewSource) => void;
- readonly onPressVideo: (attachment: ChatFileAttachment, sourceIdentifier: string) => void;
+ readonly onPlaybackStart: () => void;
}) {
const sourceIdentifier = useId();
const navigation = useNavigation();
@@ -601,17 +601,6 @@ function MessageAttachmentFile(props: {
? "PDF"
: (attachment.name.match(/\.([a-z0-9]{1,8})$/i)?.[1]?.toUpperCase() ?? "File");
const sizeLabel = formatAttachmentSize(attachment.sizeBytes);
- const thumbnailUrl = useAssetUrl(
- props.environmentId,
- videoType === null
- ? null
- : {
- _tag: "attachment",
- attachmentId: attachment.id,
- fileName: attachment.name,
- mimeType: videoType,
- },
- );
const httpBaseUrl = Option.isSome(preparedConnection)
? preparedConnection.value.httpBaseUrl
: null;
@@ -677,22 +666,64 @@ function MessageAttachmentFile(props: {
})();
};
+ const openAttachment = () =>
+ isPdf
+ ? props.onPressPreview({
+ kind: "pdf",
+ name: attachment.name,
+ environmentId: props.environmentId,
+ resource: {
+ _tag: "attachment",
+ attachmentId: attachment.id,
+ fileName: attachment.name,
+ mimeType: "application/pdf",
+ },
+ sourceIdentifier,
+ })
+ : navigation.navigate("ThreadAttachment", {
+ environmentId: String(props.environmentId),
+ ...(selectedThread ? { threadId: String(selectedThread.id) } : {}),
+ attachmentId: attachment.id,
+ name: attachment.name,
+ mimeType: attachment.mimeType,
+ sizeBytes: String(attachment.sizeBytes),
+ });
+ const inlineKind = inlineFilePreviewKind(attachment);
+ if (inlineKind) {
+ return (
+ <PresentationSource identifier={sourceIdentifier}>
+ <ThreadInlineFilePreview
+ key={attachment.id}
+ source={{
+ kind: "document",
+ name: attachment.name,
+ mimeType: attachment.mimeType,
+ environmentId: props.environmentId,
+ resource: {
+ _tag: "attachment",
+ attachmentId: attachment.id,
+ fileName: attachment.name,
+ mimeType: attachment.mimeType,
+ disposition: "inline",
+ },
+ }}
+ sizeBytes={attachment.sizeBytes}
+ onOpen={openAttachment}
+ onPlaybackStart={props.onPlaybackStart}
+ onLongPress={() => shareFile(sourceIdentifier)}
+ />
+ </PresentationSource>
+ );
+ }
+
if (videoType !== null) {
- const sourceIdentifier = `attachment:${props.environmentId}:${attachment.id}`;
return (
- <VideoAttachmentTile
- name={attachment.name}
- sourceIdentifier={sourceIdentifier}
- thumbnailSource={thumbnailUrl}
- actionsSource={
- attachmentVideoPreviewSource(props.environmentId, attachment, sourceIdentifier)
- .actionsSource
- }
- disabled={opening || httpBaseUrl === null}
- onPress={(sourceIdentifier) => props.onPressVideo(attachment, sourceIdentifier)}
- className="my-1 rounded-2xl"
- style={{ width: 224, maxWidth: "100%", aspectRatio: 16 / 9 }}
- />
+ <View className="my-1" style={{ width: 224, maxWidth: "100%" }}>
+ <ThreadMarkdownVideo
+ source={attachmentVideoPreviewSource(props.environmentId, attachment, sourceIdentifier)}
+ onPlaybackStart={props.onPlaybackStart}
+ />
+ </View>
);
}
@@ -711,29 +742,7 @@ function MessageAttachmentFile(props: {
disabled={opening || httpBaseUrl === null}
className="min-w-0 flex-row items-center gap-3 rounded-xl border border-border bg-card p-3 active:bg-subtle"
onLongPress={() => shareFile(sourceIdentifier)}
- onPress={() =>
- isPdf
- ? props.onPressPreview({
- kind: "pdf",
- name: attachment.name,
- environmentId: props.environmentId,
- resource: {
- _tag: "attachment",
- attachmentId: attachment.id,
- fileName: attachment.name,
- mimeType: "application/pdf",
- },
- sourceIdentifier,
- })
- : navigation.navigate("ThreadAttachment", {
- environmentId: String(props.environmentId),
- ...(selectedThread ? { threadId: String(selectedThread.id) } : {}),
- attachmentId: attachment.id,
- name: attachment.name,
- mimeType: attachment.mimeType,
- sizeBytes: String(attachment.sizeBytes),
- })
- }
+ onPress={openAttachment}
>
<View className="h-12 w-10 shrink-0 items-center justify-center rounded-lg bg-subtle">
{opening ? (
@@ -767,7 +776,7 @@ function MessageAttachmentList(props: {
readonly attachments: ReadonlyArray<ChatAttachment>;
readonly environmentId: EnvironmentId;
readonly onPressPreview: (source: FilePreviewSource) => void;
- readonly onPressVideo: (attachment: ChatFileAttachment, sourceIdentifier: string) => void;
+ readonly onPlaybackStart: () => void;
}) {
return props.attachments.map((attachment) =>
isImageAttachment(attachment) ? (
@@ -786,7 +795,7 @@ function MessageAttachmentList(props: {
environmentId={props.environmentId}
attachment={attachment}
onPressPreview={props.onPressPreview}
- onPressVideo={props.onPressVideo}
+ onPlaybackStart={props.onPlaybackStart}
/>
) : (
<MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
@@ -832,6 +841,7 @@ interface MarkdownLinkHandlers {
readonly onFileContextMenuAction: (href: string, actionId: string) => void;
readonly onImagePress?: (href: string) => void;
readonly resolveImageSource?: MarkdownImageSourceResolver;
+ readonly fileEmbedLabel?: (href: string, standalone: boolean) => string | null;
readonly linkCustomization?: (href: string) => MarkdownLinkCustomization | undefined;
}
@@ -1262,7 +1272,7 @@ function renderFeedEntry(
readonly onToggleTurnFold: (runId: RunId) => void;
readonly onOpenTurnDiff: (checkpoint: ThreadCheckpointSummary) => void;
readonly onPressPreview: (source: FilePreviewSource) => void;
- readonly onPressVideo: (attachment: ChatFileAttachment, sourceIdentifier: string) => void;
+ readonly onPlaybackStart: () => void;
readonly markdownLinkHandlers: MarkdownLinkHandlers;
readonly renderMarkdownImage: MarkdownImageRenderer;
readonly renderViewedImage: MarkdownImageRenderer;
@@ -1297,7 +1307,7 @@ function renderFeedEntry(
attachments={attachments}
environmentId={props.environmentId}
onPressPreview={props.onPressPreview}
- onPressVideo={props.onPressVideo}
+ onPlaybackStart={props.onPlaybackStart}
/>
)}
/>
@@ -1646,7 +1656,7 @@ function renderFeedEntry(
environmentId={props.environmentId}
attachment={attachment}
onPressPreview={props.onPressPreview}
- onPressVideo={props.onPressVideo}
+ onPlaybackStart={props.onPlaybackStart}
/>
) : (
<MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
@@ -1779,7 +1789,7 @@ function renderFeedEntry(
attachments={attachments}
environmentId={props.environmentId}
onPressPreview={props.onPressPreview}
- onPressVideo={props.onPressVideo}
+ onPlaybackStart={props.onPlaybackStart}
/>
{showAssistantMeta && message.checkpointSummary ? (
<TurnDiffStat
@@ -2201,6 +2211,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const [expandedFile, setExpandedFile] = useState<FilePreviewSource | null>(null);
const [expandedVideo, setExpandedVideo] = useState<VideoPreviewSource | null>(null);
const markdownLinkRequest = useRef<AbortController | null>(null);
+ const onInlinePlaybackStart = () => {
+ markdownLinkRequest.current?.abort();
+ };
useFocusEffect(useCallback(() => () => markdownLinkRequest.current?.abort(), []));
const markdownLinkScope = JSON.stringify([
props.environmentId,
@@ -2297,7 +2310,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
workspaceRoot: props.workspaceRoot,
imageEmbed,
});
- if (media) {
+ if (media && media.kind !== "file") {
void Haptics.selectionAsync();
const openPreview = () => {
if (request.signal.aborted) return;
@@ -2419,6 +2432,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
workspaceRoot: props.workspaceRoot ?? null,
});
const markdownLinkHandlers: MarkdownLinkHandlers = {
+ fileEmbedLabel: (href, standalone) =>
+ markdownFileEmbedLabel(
+ href,
+ {
+ environmentId: props.environmentId,
+ threadId: props.threadId,
+ workspaceRoot: props.workspaceRoot,
+ },
+ standalone,
+ ),
onLinkPress: onMarkdownLinkPress,
linkCustomization: enrichedThreadLinkCustomization,
onImagePress: (href) => onMarkdownLinkPress(href, true),
@@ -2495,9 +2518,41 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
<ThreadMarkdownVideo
key={image.href}
source={{ ...media.source, name: image.alt ?? media.source.name }}
+ onPlaybackStart={onInlinePlaybackStart}
+ />
+ );
+ }
+ if (media?.kind === "audio") {
+ return (
+ <ThreadInlineFilePreview
+ key={image.href}
+ source={media.source}
+ onOpen={() => onMarkdownLinkPress(image.href, true)}
+ onPlaybackStart={onInlinePlaybackStart}
/>
);
}
+ const fileLink = resolveMarkdownLinkPresentation(image.href);
+ if (
+ (media && (media.kind === "pdf" || media.kind === "document" || media.kind === "file")) ||
+ (fileLink.kind === "file" && fileLink.line !== undefined)
+ ) {
+ const name = media?.source.name ?? (fileLink.kind === "file" ? fileLink.label : "Open file");
+ return (
+ <Text
+ accessibilityRole="link"
+ accessibilityLabel={`Open ${name}`}
+ onPress={() => onMarkdownLinkPress(image.href, true)}
+ style={{
+ color: markdownStyles.assistant.nativeTextStyle.linkColor,
+ fontSize: markdownStyles.assistant.nativeTextStyle.fontSize,
+ lineHeight: markdownStyles.assistant.nativeTextStyle.lineHeight,
+ }}
+ >
+ {name}
+ </Text>
+ );
+ }
const imageSource = classifyMarkdownImageSource(image.href, props.workspaceRoot ?? null);
if (imageSource._tag === "Direct") {
return (
@@ -2971,13 +3026,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
markdownLinkRequest.current?.abort();
setExpandedFile((current) => current ?? source);
};
- const onPressVideo = (attachment: ChatFileAttachment, sourceIdentifier: string) => {
- markdownLinkRequest.current?.abort();
- setExpandedVideo(
- (current) =>
- current ?? attachmentVideoPreviewSource(props.environmentId, attachment, sourceIdentifier),
- );
- };
// Without this, every row above the viewport is assumed to be
// estimatedItemSize tall, and scrolling up through unmeasured content
@@ -3061,7 +3109,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onToggleTurnFold,
onOpenTurnDiff,
onPressPreview,
- onPressVideo,
+ onPlaybackStart: onInlinePlaybackStart,
markdownLinkHandlers,
renderMarkdownImage,
renderViewedImage,
diff --git a/apps/mobile/src/features/threads/ThreadInlineFilePreview.tsx b/apps/mobile/src/features/threads/ThreadInlineFilePreview.tsx
new file mode 100644
index 00000000000..65ff9e0f371
--- /dev/null
+++ b/apps/mobile/src/features/threads/ThreadInlineFilePreview.tsx
@@ -0,0 +1,254 @@
+import { useIsFocused } from "@react-navigation/native";
+import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
+import { useAudioPlayerStatus } from "expo-audio";
+import { useCallback, useContext, useEffect, useRef, useState } from "react";
+import { AppState, Pressable, View } from "react-native";
+import type { FilePreviewSource } from "../../components/FilePreviewModal";
+import { filePreviewKey } from "../../lib/filePreviewGallery";
+import { PierreEntryIcon } from "../../components/PierreEntryIcon";
+import { AppText as Text } from "../../components/ui/AppText";
+import { SymbolView } from "../../components/ui/AppSymbol";
+import { useFullscreenVideoOpen, useMediaAudioSessionHold } from "../../lib/videoAudioSession";
+import { useRefreshAssetUrl } from "../../state/assets";
+import { ThreadMediaVisibleContext } from "./ThreadMarkdownVideo";
+import {
+ acquireAudioSession,
+ activateAudioSession,
+ isAudioSessionOwner,
+ pauseAudioPlayer,
+ releaseAudioSession,
+} from "../../lib/audioSession";
+import { usePlaybackAudioPlayer } from "../voice-input/usePlaybackAudioPlayer";
+
+type PreviewProps = {
+ readonly source: FilePreviewSource;
+ readonly sizeBytes?: number;
+ readonly onOpen: () => void;
+ readonly onPlaybackStart?: () => void;
+ readonly onLongPress?: () => void;
+};
+
+function FileCardHeader(props: PreviewProps) {
+ return (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={`Open ${props.source.name}`}
+ onPress={props.onOpen}
+ onLongPress={props.onLongPress}
+ className="h-[72px] flex-row items-center gap-3 p-3 active:bg-subtle"
+ >
+ <View className="h-12 w-10 shrink-0 items-center justify-center rounded-lg bg-subtle">
+ <PierreEntryIcon path={props.source.name ?? "file"} kind="file" size={26} />
+ </View>
+ <View className="min-w-0 flex-1 gap-1">
+ <Text className="text-sm font-t3-medium text-foreground" numberOfLines={1}>
+ {props.source.name}
+ </Text>
+ <Text className="text-xs text-foreground-muted" numberOfLines={1}>
+ Audio
+ {props.sizeBytes !== undefined ? ` · ${formatAttachmentSize(props.sizeBytes)}` : ""}
+ </Text>
+ </View>
+ <SymbolView name="chevron.right" size={12} tintColorClassName="accent-foreground-muted" />
+ </Pressable>
+ );
+}
+
+function timestamp(seconds: number) {
+ const value = Number.isFinite(seconds) ? Math.max(0, Math.floor(seconds)) : 0;
+ return `${Math.floor(value / 60)}:${String(value % 60).padStart(2, "0")}`;
+}
+
+function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise<string | null> }) {
+ // An empty source keeps native buffering off until the user explicitly plays.
+ const player = usePlaybackAudioPlayer(null);
+ const status = useAudioPlayerStatus(player);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState(false);
+ const active = useRef(true);
+ const requestGeneration = useRef(0);
+ const playRequested = useRef(false);
+ const audioToken = useRef<ReturnType<typeof acquireAudioSession> | null>(null);
+ const [playbackRequested, setPlaybackRequested] = useState(false);
+ const requestPlayback = useCallback((requested: boolean) => {
+ playRequested.current = requested;
+ setPlaybackRequested(requested);
+ if (!requested) {
+ requestGeneration.current += 1;
+ setLoading(false);
+ if (audioToken.current) {
+ void releaseAudioSession(audioToken.current).catch(() => {});
+ audioToken.current = null;
+ }
+ }
+ }, []);
+ useMediaAudioSessionHold(status.playing);
+ const fullscreenVideoOpen = useFullscreenVideoOpen();
+ useEffect(() => {
+ if (fullscreenVideoOpen || status.didJustFinish || status.error) {
+ // oxlint-disable-next-line react/set-state-in-effect -- Native completion and fullscreen takeover invalidate the pending playback request.
+ requestPlayback(false);
+ }
+ if (fullscreenVideoOpen) pauseAudioPlayer(player);
+ }, [fullscreenVideoOpen, status.didJustFinish, status.error, player, requestPlayback]);
+ useEffect(() => {
+ active.current = true;
+ const subscription = AppState.addEventListener("change", (state) => {
+ if (state !== "active") {
+ requestPlayback(false);
+ pauseAudioPlayer(player);
+ }
+ });
+ return () => {
+ active.current = false;
+ playRequested.current = false;
+ requestGeneration.current += 1;
+ if (audioToken.current) {
+ void releaseAudioSession(audioToken.current).catch(() => {});
+ audioToken.current = null;
+ }
+ subscription.remove();
+ };
+ }, [player, requestPlayback]);
+ const toggle = () => {
+ if (status.playing || playRequested.current) {
+ requestPlayback(false);
+ return pauseAudioPlayer(player);
+ }
+ const token = acquireAudioSession(
+ "playback",
+ () => {
+ requestPlayback(false);
+ pauseAudioPlayer(player);
+ },
+ () => {
+ try {
+ pauseAudioPlayer(player);
+ } catch {}
+ },
+ );
+ if (!isAudioSessionOwner(token)) return;
+ props.onPlaybackStart?.();
+ audioToken.current = token;
+ requestPlayback(true);
+ const generation = ++requestGeneration.current;
+ const isCurrentRequest = () =>
+ active.current &&
+ playRequested.current &&
+ requestGeneration.current === generation &&
+ isAudioSessionOwner(token);
+ setLoading(true);
+ setError(false);
+ void Promise.resolve()
+ .then(async () => {
+ if (!isCurrentRequest()) return;
+ if (!status.isLoaded || status.error) {
+ const uri = await props.resolveUri();
+ if (!isCurrentRequest() || AppState.currentState !== "active") return;
+ if (!uri) {
+ requestPlayback(false);
+ setError(true);
+ return;
+ }
+ player.replace({ uri });
+ } else if (status.didJustFinish || status.currentTime >= status.duration) {
+ await player.seekTo(0);
+ }
+ if (!isCurrentRequest() || AppState.currentState !== "active") return;
+ await activateAudioSession(token);
+ if (isCurrentRequest() && AppState.currentState === "active") player.play();
+ })
+ .catch(() => {
+ if (isCurrentRequest()) {
+ requestPlayback(false);
+ setError(true);
+ }
+ })
+ .finally(() => {
+ if (isCurrentRequest()) setLoading(false);
+ });
+ };
+ const progress =
+ status.duration > 0 ? Math.min(1, Math.max(0, status.currentTime / status.duration)) : 0;
+ const playing = playbackRequested || status.playing;
+ const busy = loading || (playbackRequested && status.isBuffering);
+ return (
+ <>
+ <FileCardHeader
+ {...props}
+ onOpen={() => {
+ requestPlayback(false);
+ pauseAudioPlayer(player);
+ props.onOpen();
+ }}
+ />
+ <View className="h-14 flex-row items-center gap-3 px-3 pb-2">
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={
+ playing ? "Pause audio" : error || status.error ? "Retry audio" : "Play audio"
+ }
+ accessibilityState={{ busy }}
+ onPress={toggle}
+ className="h-11 w-11 items-center justify-center rounded-lg bg-subtle"
+ >
+ <SymbolView
+ name={playing ? "pause" : "play"}
+ size={18}
+ tintColorClassName="accent-foreground"
+ />
+ </Pressable>
+ <View className="min-w-0 flex-1 gap-2">
+ <View
+ accessibilityRole="progressbar"
+ accessibilityValue={{ min: 0, max: status.duration || 0, now: status.currentTime }}
+ className="h-1 overflow-hidden rounded-full bg-subtle"
+ >
+ <View className="h-1 bg-foreground-muted" style={{ width: `${progress * 100}%` }} />
+ </View>
+ <Text className="text-xs text-foreground-muted" numberOfLines={1}>
+ {error || status.error
+ ? "Unavailable · tap play to retry"
+ : busy
+ ? "Loading…"
+ : `${timestamp(status.currentTime)} / ${status.isLoaded ? timestamp(status.duration) : "--:--"}`}
+ </Text>
+ </View>
+ </View>
+ </>
+ );
+}
+
+function VisibleFilePreview(props: PreviewProps) {
+ // Each mounted preview owns its source; feed streaming must not restart a fetch or player.
+ const [source] = useState(props.source);
+ const refresh = useRefreshAssetUrl(
+ "environmentId" in source ? source.environmentId : null,
+ "resource" in source ? source.resource : null,
+ );
+ const resolveUri = useCallback(
+ () => ("uri" in source ? Promise.resolve(source.uri) : refresh()),
+ [source, refresh],
+ );
+ return <InlineAudio {...props} resolveUri={resolveUri} />;
+}
+
+export function ThreadInlineFilePreview(props: PreviewProps) {
+ const visible = useContext(ThreadMediaVisibleContext);
+ const focused = useIsFocused();
+ return (
+ <View
+ className="my-1 overflow-hidden rounded-xl border border-border bg-card"
+ style={{ width: 280, maxWidth: "100%" }}
+ >
+ {visible && focused ? (
+ <VisibleFilePreview key={filePreviewKey(props.source)} {...props} />
+ ) : (
+ <>
+ <FileCardHeader {...props} />
+ <View className="h-14" />
+ </>
+ )}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx b/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx
index e01f6ae3b2a..11869a0fcb2 100644
--- a/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx
+++ b/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx
@@ -12,6 +12,7 @@ export const ThreadMediaVisibleContext = createContext(false);
export function ThreadMarkdownVideo(props: {
readonly source: MediaVideoPreviewSource;
readonly thumbnailVisible?: boolean;
+ readonly onPlaybackStart?: () => void;
}) {
const { source } = props;
const feedVisible = useContext(ThreadMediaVisibleContext);
@@ -38,6 +39,8 @@ export function ThreadMarkdownVideo(props: {
name={source.name}
thumbnailKey={thumbnailKey}
thumbnailVisible={visible}
+ paused={!visible}
+ onPlaybackStart={props.onPlaybackStart}
unavailable={"resource" in source && asset._tag === "Failure"}
actionsSource={source.actionsSource}
/>
diff --git a/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx b/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx
index a1660bb6f1f..fe768932978 100644
--- a/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx
+++ b/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx
@@ -3,8 +3,6 @@ import {
AudioModule,
RecordingPresets,
requestRecordingPermissionsAsync,
- setAudioModeAsync,
- setIsAudioActiveAsync,
type RecorderState,
type RecordingStatus,
} from "expo-audio";
@@ -40,6 +38,11 @@ import {
import { createLazyVoiceRecorder, type LazyVoiceRecorder } from "./lazyVoiceRecorder";
import { normalizeVoiceInputDecibels, VOICE_WAVEFORM_SAMPLE_COUNT } from "./voiceInputMetering";
import { VoiceInputSession } from "./voiceInputSession";
+import {
+ acquireAudioSession,
+ activateAudioSession,
+ releaseAudioSession,
+} from "../../lib/audioSession";
const INITIAL_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
const VOICE_METERING_INTERVAL_MS = 80;
@@ -55,32 +58,6 @@ const VOICE_RECORDING_OPTIONS = {
...(Platform.OS === "ios" ? IOS_RECORDING_OPTIONS : ANDROID_RECORDING_OPTIONS),
};
-async function releaseVoiceRecordingAudio(): Promise<void> {
- try {
- await setAudioModeAsync({ allowsRecording: false });
- } finally {
- // Expo never deactivates AVAudioSession after recording; do so to resume interrupted audio.
- await setIsAudioActiveAsync(false);
- }
-}
-
-async function configureVoiceRecordingAudio(): Promise<void> {
- try {
- await setAudioModeAsync({
- allowsRecording: true,
- interruptionMode: "doNotMix",
- playsInSilentMode: true,
- shouldPlayInBackground: false,
- });
- await setIsAudioActiveAsync(true);
- } catch (error) {
- try {
- await releaseVoiceRecordingAudio();
- } catch {}
- throw error;
- }
-}
-
const VoiceInputContext = createContext<ReturnType<typeof useVoiceInputRuntime> | null>(null);
export function VoiceInputProvider({ children }: { readonly children: ReactNode }) {
@@ -120,6 +97,7 @@ function useVoiceInputRuntime() {
const audioLevels = useSharedValue(audioLevelsRef.current);
const sessionRef = useRef<VoiceInputSession | null>(null);
const recorderRef = useRef<LazyVoiceRecorder<RecorderState> | null>(null);
+ const audioToken = useRef<ReturnType<typeof acquireAudioSession> | null>(null);
if (!sessionRef.current || !recorderRef.current) {
const recorder = createLazyVoiceRecorder({
@@ -156,8 +134,20 @@ function useVoiceInputRuntime() {
const permission = await requestRecordingPermissionsAsync();
return { granted: permission.granted, canAskAgain: permission.canAskAgain };
},
- configureRecording: configureVoiceRecordingAudio,
- releaseRecording: releaseVoiceRecordingAudio,
+ configureRecording: async () => {
+ const token = acquireAudioSession("recording");
+ audioToken.current = token;
+ try {
+ await activateAudioSession(token);
+ } catch (error) {
+ await releaseAudioSession(token).catch(() => {});
+ throw error;
+ }
+ },
+ releaseRecording: async () => {
+ if (audioToken.current) await releaseAudioSession(audioToken.current);
+ audioToken.current = null;
+ },
deleteRecording: (uri) => new File(uri).delete(),
onStateChange: (nextState) =>
setState({
diff --git a/apps/mobile/src/features/voice-input/usePlaybackAudioPlayer.ts b/apps/mobile/src/features/voice-input/usePlaybackAudioPlayer.ts
new file mode 100644
index 00000000000..a70452e921b
--- /dev/null
+++ b/apps/mobile/src/features/voice-input/usePlaybackAudioPlayer.ts
@@ -0,0 +1,14 @@
+import { useReleasingSharedObjectWithLifecycle } from "expo";
+import { createAudioPlayer } from "expo-audio";
+import { disposeAudioPlayer } from "../../lib/audioSession";
+
+export function usePlaybackAudioPlayer(uri: string | null) {
+ // Keep the native ref alive until any pending activation and release finish.
+ return useReleasingSharedObjectWithLifecycle(
+ {
+ factory: () => createAudioPlayer(uri, { updateInterval: 500 }),
+ release: disposeAudioPlayer,
+ },
+ [uri],
+ );
+}
diff --git a/apps/mobile/src/features/voice-input/voiceInputSession.test.ts b/apps/mobile/src/features/voice-input/voiceInputSession.test.ts
index b57aa0916c6..2c265820316 100644
--- a/apps/mobile/src/features/voice-input/voiceInputSession.test.ts
+++ b/apps/mobile/src/features/voice-input/voiceInputSession.test.ts
@@ -2,6 +2,22 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import type { PreparedVoiceTranscription } from "@t3tools/client-runtime/voice-input";
import { Atom, AtomRegistry } from "effect/reactivity";
import { resetVoiceInputGlobalsForTests } from "../../../../../packages/client-runtime/src/voice-input/controller";
+import {
+ acquireAudioSession,
+ activateAudioSession,
+ isAudioSessionOwner,
+ releaseAudioSession,
+} from "../../lib/audioSession";
+
+const audio = vi.hoisted(() => ({
+ setMode: vi.fn(async (_mode: unknown) => {}),
+ setActive: vi.fn(async (_active: boolean) => {}),
+}));
+vi.mock("expo-audio", () => ({
+ AudioModule: {},
+ setAudioModeAsync: audio.setMode,
+ setIsAudioActiveAsync: audio.setActive,
+}));
import {
createVoiceInputTarget,
@@ -18,7 +34,10 @@ function createTarget(
return createVoiceInputTarget(ownerKey, readText, commit, selection, () => () => {});
}
-function createSession() {
+function createSession(recordingAudio?: {
+ configureRecording: () => Promise<void>;
+ releaseRecording: () => Promise<void>;
+}) {
const recorder = {
uri: "file:///voice.m4a",
prepareToRecordAsync: vi.fn(async () => {}),
@@ -35,6 +54,7 @@ function createSession() {
requestPermission: async () => ({ granted: true, canAskAgain: true }),
configureRecording: async () => {},
releaseRecording: vi.fn(async () => {}),
+ ...recordingAudio,
deleteRecording: vi.fn(),
onStateChange: vi.fn(),
});
@@ -44,6 +64,77 @@ function createSession() {
describe("global voice input", () => {
beforeEach(() => resetVoiceInputGlobalsForTests());
+ it.each(["retry", "takeover"])(
+ "handles failed deactivation with %s without notifying a released owner",
+ async (action) => {
+ const pause = vi.fn();
+ const playback = acquireAudioSession("recording", pause);
+ await activateAudioSession(playback);
+ audio.setActive.mockRejectedValueOnce(new Error("Deactivation failed"));
+ await expect(releaseAudioSession(playback)).rejects.toThrow("Deactivation failed");
+ if (action === "retry") {
+ await releaseAudioSession(playback);
+ expect(audio.setActive).toHaveBeenLastCalledWith(false);
+ }
+ const recording = acquireAudioSession("recording");
+ expect(pause).not.toHaveBeenCalled();
+ await releaseAudioSession(recording);
+ vi.clearAllMocks();
+ },
+ );
+
+ it.each(["complete", "activation failure"])(
+ "protects recording from inline playback and releases its session after %s",
+ async (outcome) => {
+ const pause = vi.fn();
+ const playback = acquireAudioSession("playback", pause);
+ await activateAudioSession(playback);
+ let recording!: ReturnType<typeof acquireAudioSession>;
+ const { session, recorder } = createSession({
+ configureRecording: async () => {
+ recording = acquireAudioSession("recording");
+ try {
+ await activateAudioSession(recording);
+ } catch (error) {
+ await releaseAudioSession(recording);
+ throw error;
+ }
+ },
+ releaseRecording: () => releaseAudioSession(recording),
+ });
+ if (outcome === "activation failure") {
+ audio.setActive.mockRejectedValueOnce(new Error("Audio activation failed"));
+ }
+ await session.start(createTarget("first", () => "", vi.fn(), { start: 0, end: 0 }));
+ expect(pause).toHaveBeenCalledOnce();
+ expect(isAudioSessionOwner(playback)).toBe(false);
+ if (outcome === "complete") {
+ expect(recorder.record).toHaveBeenCalledOnce();
+ expect(session.controller.currentState.phase).toBe("recording");
+ audio.setMode.mockClear();
+ audio.setActive.mockClear();
+ await releaseAudioSession(playback);
+ const blockedPlayback = acquireAudioSession("playback");
+ expect(await activateAudioSession(blockedPlayback)).toBe(false);
+ await releaseAudioSession(blockedPlayback);
+ expect(audio.setMode).not.toHaveBeenCalled();
+ expect(audio.setActive).not.toHaveBeenCalled();
+ expect(isAudioSessionOwner(recording)).toBe(true);
+ await session.controller.stop();
+ } else {
+ expect(recorder.record).not.toHaveBeenCalled();
+ expect(session.controller.currentState.phase).toBe("error");
+ }
+ expect(audio.setActive).toHaveBeenLastCalledWith(false);
+ expect(isAudioSessionOwner(recording)).toBe(false);
+ const replay = acquireAudioSession("playback");
+ expect(await activateAudioSession(replay)).toBe(true);
+ expect(audio.setActive).toHaveBeenLastCalledWith(true);
+ await releaseAudioSession(replay);
+ vi.clearAllMocks();
+ },
+ );
+
it.each([
{ selection: { start: 6, end: 11 }, expected: "hello spoken text", cursor: 17 },
{ selection: { start: 6, end: 6 }, expected: "hello spoken text world", cursor: 18 },
diff --git a/apps/mobile/src/lib/audioSession.ts b/apps/mobile/src/lib/audioSession.ts
new file mode 100644
index 00000000000..7ebcd0bf726
--- /dev/null
+++ b/apps/mobile/src/lib/audioSession.ts
@@ -0,0 +1,158 @@
+import { AudioModule, setAudioModeAsync, setIsAudioActiveAsync } from "expo-audio";
+
+type AudioSessionToken = {
+ readonly kind: "playback" | "recording";
+ readonly onCancel?: () => void;
+ readonly onRelease?: () => void;
+ released: boolean;
+};
+
+let owner: AudioSessionToken | null = null;
+let pending = Promise.resolve();
+
+// Native session calls are async. Finish an old activation before releasing it
+// or configuring its successor, so it cannot reactivate a released session.
+function enqueue<T>(operation: () => Promise<T>): Promise<T> {
+ const result = pending.then(operation);
+ pending = result.then(
+ () => {},
+ () => {},
+ );
+ return result;
+}
+
+export function pauseAudioPlayer(player: { pause(deactivateSession?: boolean): void }): void {
+ // Expo Audio otherwise deactivates iOS's shared session 100 ms after pause,
+ // even when a video or recorder has already taken ownership.
+ if (owner && !owner.released) player.pause(false);
+ else player.pause();
+}
+
+export function disposeAudioPlayer(player: {
+ pause(deactivateSession?: boolean): void;
+ release(): void;
+}): void {
+ void enqueue(async () => {
+ try {
+ pauseAudioPlayer(player);
+ } finally {
+ player.release();
+ }
+ }).catch(() => {});
+}
+
+export function acquireAudioSession(
+ kind: AudioSessionToken["kind"],
+ onCancel?: () => void,
+ onRelease?: () => void,
+) {
+ const token: AudioSessionToken = { kind, onCancel, onRelease, released: false };
+ if (kind === "playback" && owner?.kind === "recording" && !owner.released) return token;
+ const previous = owner;
+ // Publish before cancelling the old player, including callbacks already queued by Expo.
+ AudioModule.setAudioSessionOwner?.(true);
+ owner = token;
+ if (previous && !previous.released) previous.onCancel?.();
+ return token;
+}
+
+export function isAudioSessionOwner(token: AudioSessionToken): boolean {
+ return owner === token && !token.released;
+}
+
+export function activateAudioSession(
+ token: AudioSessionToken,
+ nativePlayback = false,
+): Promise<boolean> {
+ return enqueue(async () => {
+ if (!isAudioSessionOwner(token)) return false;
+ // Video configures and activates its own native session, including moviePlayback on iOS.
+ if (nativePlayback) return true;
+ await setAudioModeAsync({
+ allowsRecording: token.kind === "recording",
+ interruptionMode: "doNotMix",
+ playsInSilentMode: true,
+ shouldPlayInBackground: false,
+ });
+ if (!isAudioSessionOwner(token)) return false;
+ await setIsAudioActiveAsync(true);
+ return isAudioSessionOwner(token);
+ });
+}
+
+export function releaseAudioSession(token: AudioSessionToken): Promise<void> {
+ token.released = true;
+ return enqueue(async () => {
+ if (owner !== token) return;
+ try {
+ if (token.kind === "recording") await setAudioModeAsync({ allowsRecording: false });
+ } finally {
+ if (owner === token) {
+ if (token.kind === "recording") await setIsAudioActiveAsync(false);
+ // Expo pause releases the native session without disabling its global playback gate.
+ // Repeat it after any pending activation, even if playback never started.
+ token.onRelease?.();
+ if (owner === token) {
+ AudioModule.setAudioSessionOwner?.(false);
+ owner = null;
+ }
+ }
+ }
+ });
+}
+
+export function createAudioPlaybackSession(
+ player: { play(): void; pause(deactivateSession?: boolean): void },
+ nativePlayback = false,
+ onRequestedChange?: (requested: boolean) => void,
+) {
+ let token: AudioSessionToken | null = null;
+ const stopPlayer = () => {
+ // useAudioPlayer/useVideoPlayer may have disposed the native ref during unmount.
+ try {
+ if (nativePlayback) player.pause();
+ else pauseAudioPlayer(player);
+ } catch {}
+ };
+ const pause = () => {
+ const previous = token;
+ token = null;
+ onRequestedChange?.(false);
+ stopPlayer();
+ if (previous) void releaseAudioSession(previous).catch(() => {});
+ };
+ const acquire = () => {
+ const next = acquireAudioSession("playback", pause, stopPlayer);
+ if (!isAudioSessionOwner(next)) {
+ stopPlayer();
+ return null;
+ }
+ token = next;
+ onRequestedChange?.(true);
+ return next;
+ };
+ return {
+ pause,
+ get requested() {
+ return token !== null;
+ },
+ async play(prepare?: () => Promise<void>) {
+ const current = token ?? acquire();
+ if (!current) return;
+ try {
+ await prepare?.();
+ if (!(await activateAudioSession(current, nativePlayback))) return;
+ if (token !== current || !isAudioSessionOwner(current)) return;
+ player.play();
+ } catch (error) {
+ if (token === current) pause();
+ throw error;
+ }
+ },
+ // A stopped clock is also reported during buffering and seeks. Native
+ // pause intent must call pause() separately from playingChange.
+ playingChanged(playing: boolean) {
+ if (playing && token === null) acquire();
+ },
+ };
+}
diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts
index a48a4bd1146..84f86f8998b 100644
--- a/apps/mobile/src/lib/filePreview.test.ts
+++ b/apps/mobile/src/lib/filePreview.test.ts
@@ -1,6 +1,1275 @@
-import { describe, expect, it } from "vite-plus/test";
+import { act, createElement, useEffect, useMemo, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
-import { isPdfFile } from "./filePreview";
+import { inlineFilePreviewKind, isPdfFile } from "./filePreview";
+import { ThreadInlineFilePreview } from "../features/threads/ThreadInlineFilePreview";
+import { AudioFilePreview } from "../features/files/AudioFilePreview";
+import { MediaVideoPlayer } from "../components/MediaVideoPlayer";
+import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
+import { acquireAudioSession, activateAudioSession, releaseAudioSession } from "./audioSession";
+import { ThreadFeed } from "../features/threads/ThreadFeed";
+import type { ThreadFeedEntry } from "./threadActivity";
+import type { MarkdownImageRenderer } from "../native/SelectableMarkdownText";
+
+const audio = vi.hoisted(() => ({
+ status: {
+ playing: false,
+ isLoaded: false,
+ error: null,
+ didJustFinish: false,
+ currentTime: 0,
+ duration: 10,
+ isBuffering: false,
+ },
+ player: {
+ play: vi.fn(),
+ pause: vi.fn((_deactivateSession?: boolean) => {}),
+ release: vi.fn(),
+ replace: vi.fn(),
+ seekTo: vi.fn(async () => {}),
+ },
+ refresh: vi.fn<() => Promise<string | null>>(),
+ setAudioMode: vi.fn(async (_mode: unknown) => {}),
+ setActive: vi.fn(async (_active: boolean) => {}),
+ setSessionOwner: vi.fn((_owned: boolean) => {}),
+ sessionOwned: false,
+ enabled: true,
+ played: vi.fn(),
+ video: {
+ playing: false,
+ playbackRequested: false,
+ status: "readyToPlay",
+ play: vi.fn(),
+ pause: vi.fn(),
+ replaceAsync: vi.fn(async (_source: unknown) => {}),
+ addListener: vi.fn(),
+ },
+ videoListeners: new Set<(event: { isPlaying: boolean }) => void>(),
+ videoStatusListeners: new Set<(event: { status: string }) => void>(),
+ videoEndListeners: new Set<() => void>(),
+ videoRequestListeners: new Set<(event: { isPlaybackRequested: boolean }) => void>(),
+ navigate: vi.fn(),
+ query: vi.fn(),
+}));
+vi.mock("expo-audio", () => ({
+ AudioModule: { setAudioSessionOwner: audio.setSessionOwner },
+ useAudioPlayer: () => audio.player,
+ createAudioPlayer: () => audio.player,
+ useAudioPlayerStatus: () => audio.status,
+ setAudioModeAsync: audio.setAudioMode,
+ setIsAudioActiveAsync: audio.setActive,
+}));
+vi.mock("@react-navigation/native", () => ({
+ useIsFocused: () => true,
+ useNavigation: () => ({ navigate: audio.navigate }),
+ useFocusEffect: (callback: () => (() => void) | undefined) => useEffect(callback, [callback]),
+}));
+vi.mock("react-native", () => ({
+ Platform: { OS: "android", select: (values: { android?: unknown }) => values.android },
+ StyleSheet: { create: (styles: unknown) => styles },
+ useWindowDimensions: () => ({ width: 390, height: 844, fontScale: 1 }),
+ Text: ({ children }: { children?: ReactNode }) => createElement("span", null, children),
+ AppState: { currentState: "active", addEventListener: () => ({ remove() {} }) },
+ View: ({ children }: { children?: ReactNode }) => createElement("div", null, children),
+ Pressable: (props: {
+ children?: ReactNode;
+ onPress: () => void;
+ disabled?: boolean;
+ accessibilityLabel?: string;
+ accessibilityState?: { busy: boolean };
+ }) =>
+ createElement(
+ "button",
+ {
+ onClick: props.onPress,
+ disabled: props.disabled,
+ "aria-label": props.accessibilityLabel,
+ "aria-busy": props.accessibilityState?.busy,
+ },
+ props.children,
+ ),
+}));
+vi.mock("../components/PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));
+vi.mock("../components/ui/AppText", () => ({
+ AppText: ({ children }: { children?: ReactNode }) => createElement("span", null, children),
+}));
+vi.mock("../components/ui/AppSymbol", () => ({ SymbolView: () => null }));
+vi.mock("../components/ui/Button", () => ({
+ Button: (props: { label: string; onPress(): void; disabled?: boolean }) =>
+ createElement("button", { onClick: props.onPress, disabled: props.disabled }, props.label),
+}));
+vi.mock("expo", () => ({
+ useEvent: (_player: unknown, _event: unknown, initial: unknown) => initial,
+ useReleasingSharedObjectWithLifecycle: (
+ lifecycle: {
+ factory: () => typeof audio.player;
+ release: (player: typeof audio.player) => void;
+ },
+ dependencies: ReadonlyArray<unknown>,
+ ) => {
+ const player = useMemo(lifecycle.factory, dependencies);
+ useEffect(() => () => lifecycle.release(player), [player]);
+ return player;
+ },
+}));
+vi.mock("expo-video", () => ({
+ useVideoPlayer: () => audio.video,
+ VideoView: () => null,
+}));
+vi.mock("../components/VideoThumbnailImage", () => ({ VideoThumbnailImage: () => null }));
+vi.mock("../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null }));
+vi.mock("../components/MediaActionsMenu", () => ({
+ MediaActionsMenu: ({ children }: { children?: ReactNode }) => children,
+}));
+vi.mock("../state/mediaActions", () => ({
+ useMediaActions: () => ({ sharing: false, actions: [] }),
+}));
+vi.mock("./videoAudioSession", () => ({
+ useMediaAudioSessionHold() {},
+ useFullscreenVideoOpen: () => false,
+}));
+vi.mock("../state/assets", () => ({
+ useRefreshAssetUrl: () => audio.refresh,
+ useAssetUrlState: () => ({ _tag: "Success", url: "https://example.com/clip.mp4" }),
+ assetEnvironment: {},
+}));
+vi.mock("../features/threads/ThreadMarkdownVideo", async (importOriginal) => {
+ const { createContext } = await import("react");
+ const actual = await importOriginal<typeof import("../features/threads/ThreadMarkdownVideo")>();
+ return {
+ ...actual,
+ ThreadMediaVisibleContext: createContext(true),
+ ThreadMarkdownVideo: (props: Parameters<typeof actual.ThreadMarkdownVideo>[0]) =>
+ createElement(actual.ThreadMarkdownVideo, { ...props, thumbnailVisible: true }),
+ };
+});
+
+vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
+ executeAtomQuery: (...args: unknown[]) => audio.query(...args),
+}));
+vi.mock("../state/projects", () => ({
+ projectEnvironment: {
+ searchEntries: (input: unknown) => input,
+ fileMetadata: (input: unknown) => input,
+ },
+}));
+vi.mock("../state/server", () => ({ serverEnvironment: {} }));
+vi.mock("../state/session", () => ({
+ readEnvironmentScope: () => true,
+ usePreparedConnection: () => ({ _tag: "Some", value: { httpBaseUrl: "https://example.com" } }),
+}));
+vi.mock("../state/atom-registry", () => ({ appAtomRegistry: {} }));
+vi.mock("../state/threads", () => ({ environmentThreadShells: {}, threadEnvironment: {} }));
+vi.mock("../state/entities", () => ({
+ useLiveThreadLinkLabels: (text: string) => text,
+ useThreadChipIcons: () => new Map(),
+}));
+vi.mock("../state/use-thread-selection", () => ({
+ useThreadSelection: () => ({ selectedThread: null }),
+}));
+vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
+vi.mock("../state/use-atom-command", () => ({}));
+vi.mock("../state/v2-item-support", () => ({}));
+vi.mock("../native/SelectableMarkdownText", () => ({
+ SelectableMarkdownText: (props: {
+ markdown: string;
+ onLinkPress(href: string): void;
+ renderImage?: MarkdownImageRenderer;
+ }) => {
+ const embed = props.markdown.match(/!\[([^\]]*)\]\(([^)]+)\)/);
+ return createElement(
+ "div",
+ null,
+ createElement("button", { onClick: () => props.onLinkPress("target.ts") }, props.markdown),
+ embed && props.renderImage?.({ href: embed[2]!, alt: embed[1]!, title: null }),
+ );
+ },
+}));
+vi.mock("@legendapp/list/keyboard", () => ({
+ KeyboardAwareLegendList: (props: {
+ data: ThreadFeedEntry[];
+ renderItem(info: { item: ThreadFeedEntry; index: number }): ReactNode;
+ }) =>
+ props.data.map((item, index) =>
+ createElement("div", { key: item.id }, props.renderItem({ item, index })),
+ ),
+}));
+vi.mock("@legendapp/list/react-native", () => ({
+ useViewabilityAmount: (callback: (token: { sizeVisible: number }) => void) =>
+ useEffect(() => callback({ sizeVisible: 1 }), [callback]),
+}));
+vi.mock("react-native-reanimated", () => {
+ const transition = { delay: () => transition, duration: () => transition };
+ return {
+ default: { View: ({ children }: { children?: ReactNode }) => children },
+ FadeIn: transition,
+ FadeInUp: transition,
+ };
+});
+vi.mock("react-native-safe-area-context", () => ({
+ useSafeAreaInsets: () => ({ top: 0, bottom: 0 }),
+}));
+vi.mock("expo-haptics", () => ({ selectionAsync: async () => {} }));
+vi.mock("expo-image", () => ({}));
+vi.mock("uniwind", () => ({}));
+vi.mock("../components/ui/Dialog", () => ({}));
+vi.mock("../components/ui/NativePresentation", () => ({
+ PresentationSource: ({ children }: { children?: ReactNode }) => children,
+}));
+vi.mock("../components/ui/Menu", () => ({
+ Menu: ({ children }: { children?: ReactNode }) => children,
+}));
+vi.mock("../components/FilePreviewGallery", () => ({
+ FilePreviewGallery: ({ children }: { children?: ReactNode }) => children,
+}));
+vi.mock("../components/FilePreviewModal", () => ({ FilePreviewModal: () => null }));
+vi.mock("../components/VideoPreviewModal", () => ({ VideoPreviewModal: () => null }));
+vi.mock("../components/ComposerContextSheet", () => ({}));
+vi.mock("../native/useOpenPullRequest", () => ({ useOpenPullRequest: () => vi.fn() }));
+vi.mock("../native/useMarkdownImageSource", () => ({ useMarkdownImageSource: () => vi.fn() }));
+vi.mock("../native/useEnrichedLinkVariants", () => ({
+ enrichedThreadLinkCustomization: () => undefined,
+ enrichedContextLinkCustomization: () => undefined,
+ withChipIcon: (value: unknown) => value,
+}));
+vi.mock("../native/NativeScrollViewMarker", () => ({
+ NativeScrollViewMarker: ({ children }: { children?: ReactNode }) => children,
+}));
+vi.mock("../native/NativeWorkspaceColumns", () => ({
+ useNativeWorkspaceColumnsSupported: () => false,
+}));
+vi.mock("../native/native-layout-metrics", () => ({ useDeviceType: () => "phone" }));
+vi.mock("../features/layout/workspace-content-width", () => ({
+ useWorkspaceSettledContentWidth: () => null,
+}));
+vi.mock("../features/settings/appearance/AppearancePreferencesProvider", () => ({
+ useAppearancePreferences: () => ({ appearance: { baseFontSize: 14 }, themeAppearance: "dark" }),
+}));
+vi.mock("./useUniwindTheme", () => ({
+ useUniwindTheme: () => new Proxy({}, { get: () => "#000000" }),
+}));
+vi.mock("./composerContextClipboard", () => ({}));
+vi.mock("./copyTextWithHaptic", () => ({}));
+vi.mock("./openExternalUrl", () => ({}));
+vi.mock("./attachmentDownload", () => ({}));
+vi.mock("./uuid", () => ({}));
+vi.mock("../features/threads/thread-context-divider", () => ({}));
+vi.mock("../features/threads/thread-handoff-row", () => ({}));
+vi.mock("../features/threads/ThreadGuestShareBar", () => ({ useThreadGuestShare: () => null }));
+vi.mock("../features/threads/SecretRequestCard", () => ({}));
+vi.mock("../features/threads/worktree-setup-card", () => ({}));
+vi.mock("../features/threads/CopyTextButton", () => ({ CopyTextButton: () => null }));
+vi.mock("../features/threads/thread-work-log", () => ({ THREAD_DISCLOSURE_TRANSITION_MS: 100 }));
+vi.mock("../features/threads/HtmlRenderWebView", () => ({}));
+vi.mock("../features/threads/McpAppWebView", () => ({}));
+vi.mock("../features/threads/thread-workflow-opening", () => ({ useWorkflowOpening: () => null }));
+vi.mock("../features/threads/useFileChipShare", () => ({ useFileChipShare: () => vi.fn() }));
+vi.mock("../features/threads/ThreadMarkdownImage", async () => {
+ const { createContext } = await import("react");
+ return { MarkdownImageAvailableWidthContext: createContext(390) };
+});
+vi.mock("../features/review/ReviewCommentCard", () => ({ useReviewCommentColors: () => ({}) }));
+vi.mock("../features/prompt-links/prompt-link-actions", () => ({}));
+vi.mock("@react-navigation/elements", async () => {
+ const { createContext } = await import("react");
+ return { HeaderHeightContext: createContext(0) };
+});
+
+describe("ThreadInlineFilePreview playback", () => {
+ let root: ReturnType<typeof createRoot> | undefined;
+ beforeEach(() => {
+ audio.sessionOwned = false;
+ audio.setSessionOwner.mockImplementation((owned) => {
+ audio.sessionOwned = owned;
+ });
+ audio.player.pause.mockReset();
+ audio.enabled = true;
+ audio.setActive.mockImplementation(async (enabled) => {
+ audio.enabled = enabled;
+ });
+ // Expo's play() silently does nothing while its global gate is disabled.
+ audio.player.play.mockImplementation(() => {
+ if (audio.enabled) audio.played();
+ });
+ audio.video.addListener.mockImplementation(
+ (event: string, listener: (event: { isPlaying: boolean }) => void) => {
+ if (event === "playbackRequestedChange") {
+ const requestListener = listener as unknown as (event: {
+ isPlaybackRequested: boolean;
+ }) => void;
+ audio.videoRequestListeners.add(requestListener);
+ return { remove: () => audio.videoRequestListeners.delete(requestListener) };
+ }
+ if (event === "statusChange") {
+ const statusListener = listener as unknown as (event: { status: string }) => void;
+ audio.videoStatusListeners.add(statusListener);
+ return { remove: () => audio.videoStatusListeners.delete(statusListener) };
+ }
+ if (event === "playToEnd") {
+ const endListener = listener as unknown as () => void;
+ audio.videoEndListeners.add(endListener);
+ return { remove: () => audio.videoEndListeners.delete(endListener) };
+ }
+ audio.videoListeners.add(listener);
+ return { remove: () => audio.videoListeners.delete(listener) };
+ },
+ );
+ audio.video.play.mockImplementation(() => {
+ audio.video.playing = true;
+ audio.video.playbackRequested = true;
+ for (const listener of audio.videoRequestListeners) listener({ isPlaybackRequested: true });
+ for (const listener of audio.videoListeners) listener({ isPlaying: audio.video.playing });
+ });
+ audio.video.pause.mockImplementation(() => {
+ const wasRequested = audio.video.playbackRequested;
+ const wasPlaying = audio.video.playing;
+ audio.video.playbackRequested = false;
+ audio.video.playing = false;
+ if (wasRequested) {
+ for (const listener of audio.videoRequestListeners)
+ listener({ isPlaybackRequested: false });
+ }
+ if (wasPlaying) {
+ for (const listener of audio.videoListeners) listener({ isPlaying: false });
+ }
+ });
+ });
+ afterEach(async () => {
+ await act(async () => root?.unmount());
+ root = undefined;
+ vi.clearAllMocks();
+ audio.refresh.mockReset();
+ audio.setAudioMode.mockReset();
+ audio.setActive.mockReset();
+ audio.video.status = "readyToPlay";
+ audio.status = {
+ playing: false,
+ isLoaded: false,
+ error: null,
+ didJustFinish: false,
+ currentTime: 0,
+ duration: 10,
+ isBuffering: false,
+ };
+ });
+
+ it.each(
+ (["user", "assistant"] as const).flatMap((role) =>
+ (["attachment", "markdown"] as const).flatMap((origin) =>
+ (["audio", "video"] as const).flatMap((kind) =>
+ (kind === "video"
+ ? ["initial play", "native resume", "continued playback"]
+ : ["initial play"]
+ ).map((playback) => ({
+ role,
+ origin,
+ kind,
+ playback,
+ outcome: playback === "continued playback" ? "preserves" : "cancels",
+ })),
+ ),
+ ),
+ ),
+ )(
+ "$outcome a pending file lookup on $role $origin $kind $playback",
+ async ({ role, origin, kind, playback }) => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const environmentId = EnvironmentId.make("environment-1");
+ const threadId = ThreadId.make("thread-1");
+ const messageId = MessageId.make("message-1");
+ const timestamp = "2026-10-20T00:00:00.000Z";
+ const name = kind === "audio" ? "clip.mp3" : "clip.mp4";
+ const mimeType = kind === "audio" ? "audio/mpeg" : "video/mp4";
+ const uri = `https://example.com/${name}`;
+ const feed: ThreadFeedEntry[] = [
+ {
+ type: "message",
+ id: messageId,
+ createdAt: timestamp,
+ message: {
+ id: messageId,
+ role,
+ text: `open target.ts${origin === "markdown" ? `\n\n![${name}](${uri})` : ""}`,
+ attachments:
+ origin === "attachment"
+ ? [{ type: "file", id: "clip", name, mimeType, sizeBytes: 12 }]
+ : [],
+ createdAt: timestamp,
+ updatedAt: timestamp,
+ runId: null,
+ streaming: false,
+ visibility: "local",
+ sourceThreadId: threadId,
+ },
+ },
+ ];
+ let finishLookup!: (value: unknown) => void;
+ const lookup = new Promise((resolve) => {
+ finishLookup = resolve;
+ });
+ audio.query
+ .mockResolvedValue({ _tag: "Success", value: { kind: "file" } })
+ .mockReturnValueOnce(lookup);
+ audio.refresh.mockResolvedValue(uri);
+ const container = document.createElement("div");
+ root = createRoot(container);
+ await act(async () =>
+ root!.render(
+ createElement(ThreadFeed, {
+ environmentId,
+ threadId,
+ threadTitle: "preview",
+ workspaceRoot: "/repo",
+ feed,
+ queuedMessages: [],
+ dispatchingMessageId: null,
+ onEditPendingMessage: null,
+ contentPresentation: { kind: "ready" },
+ agentLabel: "agent",
+ latestRun: null,
+ activeWorkStartedAt: null,
+ listRef: { current: null },
+ freeze: { value: false } as Parameters<typeof ThreadFeed>[0]["freeze"],
+ contentInsetEndAdjustment: { value: 0 } as Parameters<
+ typeof ThreadFeed
+ >[0]["contentInsetEndAdjustment"],
+ anchorMessageId: null,
+ submittedMessageId: null,
+ keyboardOffset: 0,
+ }),
+ ),
+ );
+ const link = Array.from(container.querySelectorAll("button")).find((button) =>
+ button.textContent?.startsWith("open target.ts"),
+ )!;
+ const playLabel = kind === "audio" ? "Play audio" : `Play ${name}`;
+ const play = () =>
+ container.querySelector<HTMLButtonElement>(`[aria-label="${playLabel}"]`)!.click();
+ if (playback !== "initial play") {
+ await act(async () => play());
+ expect(audio.video.playing).toBe(true);
+ if (playback === "native resume") {
+ await act(async () => audio.video.pause());
+ expect(audio.video.playing).toBe(false);
+ } else {
+ await act(async () => {
+ for (const listener of audio.videoRequestListeners)
+ listener({ isPlaybackRequested: true });
+ });
+ }
+ }
+ await act(async () => link.click());
+ const signal: AbortSignal = audio.query.mock.calls[0]![2].signal;
+ expect(signal.aborted).toBe(false);
+ expect(audio.navigate).not.toHaveBeenCalled();
+ await act(async () => {
+ if (playback === "native resume") {
+ // Native resume requests playback before buffering advances the clock.
+ audio.video.playbackRequested = true;
+ for (const listener of audio.videoRequestListeners)
+ listener({ isPlaybackRequested: true });
+ expect(audio.video.playing).toBe(false);
+ } else if (playback === "continued playback") {
+ for (const isPlaying of [false, true, false, true]) {
+ audio.video.playing = isPlaying;
+ for (const listener of audio.videoListeners) listener({ isPlaying });
+ for (const listener of audio.videoRequestListeners)
+ listener({ isPlaybackRequested: true });
+ }
+ expect(signal.aborted).toBe(false);
+ } else play();
+ });
+ expect(kind === "audio" ? audio.played : audio.video.play).toHaveBeenCalled();
+ expect(audio.sessionOwned).toBe(true);
+ await act(async () =>
+ finishLookup({
+ _tag: "Success",
+ value: { entries: [{ path: "src/target.ts", kind: "file" }] },
+ }),
+ );
+ if (playback === "continued playback") {
+ expect(audio.navigate).toHaveBeenCalledExactlyOnceWith("ThreadFile", {
+ environmentId,
+ threadId,
+ path: ["src", "target.ts"],
+ });
+ expect(signal.aborted).toBe(false);
+ } else {
+ expect(audio.navigate).not.toHaveBeenCalled();
+ expect(signal.aborted).toBe(true);
+ }
+ expect(container.querySelector(`[aria-label="${playLabel}"]`)).toBeNull();
+ if (kind === "audio")
+ expect(container.querySelector('[aria-label="Pause audio"]')).not.toBeNull();
+ else {
+ if (playback === "native resume") {
+ audio.video.playing = true;
+ for (const listener of audio.videoListeners) listener({ isPlaying: true });
+ }
+ expect(audio.video.playing).toBe(true);
+ }
+ },
+ );
+
+ it.each(
+ ["takeover", "pause", "finish"].flatMap((release) => [
+ ["inline", "video", release],
+ ["viewer", "video", release],
+ ["inline", "native video controls", release],
+ ["viewer", "native video controls", release],
+ ["inline", "recording", release],
+ ["viewer", "recording", release],
+ ]),
+ )(
+ "keeps the shared session active when %s audio yields to %s after %s",
+ async (source, successor, release) => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ audio.status = { ...audio.status, isLoaded: true };
+ const container = document.createElement("div");
+ root = createRoot(container);
+ const render = (playVideo = false, showAudio = true) =>
+ root!.render(
+ createElement(
+ "div",
+ null,
+ showAudio
+ ? source === "inline"
+ ? createElement(ThreadInlineFilePreview, {
+ source: {
+ kind: "document",
+ name: "sound.mp3",
+ uri: "https://example.com/sound.mp3",
+ },
+ onOpen() {},
+ })
+ : createElement(AudioFilePreview, {
+ uri: "https://example.com/sound.mp3",
+ onRetry() {},
+ })
+ : null,
+ createElement(MediaVideoPlayer, {
+ uri: "https://example.com/clip.mp4",
+ name: "clip.mp4",
+ thumbnailKey: "clip",
+ expanded: true,
+ autoPlay: playVideo,
+ }),
+ ),
+ );
+ await act(async () => render());
+ await act(async () =>
+ [...container.querySelectorAll("button")]
+ .find(
+ (button) =>
+ button.getAttribute("aria-label") === "Play audio" || button.textContent === "Play",
+ )!
+ .click(),
+ );
+ expect(audio.played).toHaveBeenCalledOnce();
+ let sessionActive = true;
+ const deactivated = vi.fn();
+ // Match expo-audio iOS: the queued callback checks ownership at execution time.
+ const queueDeactivation = () =>
+ setTimeout(() => {
+ if (audio.sessionOwned) return;
+ sessionActive = false;
+ audio.video.playing = false;
+ deactivated();
+ }, 100);
+ audio.setSessionOwner.mockImplementation((owned) => {
+ audio.sessionOwned = owned;
+ if (!owned) queueDeactivation();
+ });
+ audio.player.pause.mockImplementation((deactivateSession) => {
+ if (deactivateSession !== false) queueDeactivation();
+ });
+ vi.useFakeTimers();
+ let recording: ReturnType<typeof acquireAudioSession> | undefined;
+ try {
+ if (release === "pause") {
+ await act(async () =>
+ [...container.querySelectorAll("button")]
+ .find(
+ (button) =>
+ button.getAttribute("aria-label") === "Pause audio" ||
+ button.textContent === "Pause",
+ )!
+ .click(),
+ );
+ } else if (release === "finish") {
+ // Native completion queues deactivation before JS receives didJustFinish.
+ queueDeactivation();
+ audio.status = { ...audio.status, playing: false, didJustFinish: true };
+ await act(async () => render());
+ }
+ if (release !== "takeover") {
+ expect(vi.getTimerCount()).toBeGreaterThan(0);
+ await vi.advanceTimersByTimeAsync(50);
+ }
+ await act(async () => {
+ if (successor === "recording") {
+ recording = acquireAudioSession("recording");
+ await activateAudioSession(recording);
+ } else if (successor === "native video controls") audio.video.play();
+ else render(true);
+ });
+ if (successor !== "recording") expect(audio.video.playing).toBe(true);
+ expect(audio.player.pause).toHaveBeenCalled();
+ // Cleanup of the old native ref must not interrupt the successor either.
+ await act(async () => render(successor === "video", false));
+ await vi.advanceTimersByTimeAsync(200);
+ expect(sessionActive).toBe(true);
+ expect(deactivated).not.toHaveBeenCalled();
+ expect(audio.setActive).not.toHaveBeenCalledWith(false);
+ if (successor !== "recording") expect(audio.video.playing).toBe(true);
+ else
+ expect(audio.setAudioMode).toHaveBeenLastCalledWith(
+ expect.objectContaining({ allowsRecording: true }),
+ );
+ await act(async () => root!.unmount());
+ root = undefined;
+ if (recording) await releaseAudioSession(recording);
+ recording = undefined;
+ await vi.advanceTimersByTimeAsync(200);
+ expect(sessionActive).toBe(false);
+ } finally {
+ if (recording) await releaseAudioSession(recording);
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ audio.player.pause.mockReset();
+ }
+ },
+ );
+
+ it.each(["inline", "viewer"])("stops video before starting %s audio", async (source) => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ audio.status = { ...audio.status, isLoaded: true };
+ const container = document.createElement("div");
+ root = createRoot(container);
+ await act(async () =>
+ root!.render(
+ createElement(
+ "div",
+ null,
+ createElement(MediaVideoPlayer, {
+ uri: "https://example.com/clip.mp4",
+ name: "clip.mp4",
+ thumbnailKey: "clip",
+ expanded: true,
+ autoPlay: true,
+ }),
+ source === "inline"
+ ? createElement(ThreadInlineFilePreview, {
+ source: {
+ kind: "document",
+ name: "sound.mp3",
+ uri: "https://example.com/sound.mp3",
+ },
+ onOpen() {},
+ })
+ : createElement(AudioFilePreview, {
+ uri: "https://example.com/sound.mp3",
+ onRetry() {},
+ }),
+ ),
+ ),
+ );
+ expect(audio.video.playing).toBe(true);
+ audio.video.pause.mockClear();
+ await act(async () =>
+ [...container.querySelectorAll("button")]
+ .find(
+ (button) =>
+ button.getAttribute("aria-label") === "Play audio" || button.textContent === "Play",
+ )!
+ .click(),
+ );
+ expect(audio.video.playing).toBe(false);
+ expect(audio.video.pause.mock.invocationCallOrder[0]).toBeLessThan(
+ audio.player.play.mock.invocationCallOrder[0]!,
+ );
+ expect(audio.played).toHaveBeenCalledOnce();
+ expect(audio.setActive).toHaveBeenLastCalledWith(true);
+ });
+
+ it("plays inline, opens the file viewer, and yields viewer playback to recording", async () => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ audio.status = { ...audio.status, isLoaded: true };
+ const container = document.createElement("div");
+ root = createRoot(container);
+ const openViewer = () =>
+ root!.render(
+ createElement(AudioFilePreview, { uri: "https://example.com/sound.mp3", onRetry() {} }),
+ );
+ await act(async () =>
+ root!.render(
+ createElement(ThreadInlineFilePreview, {
+ source: { kind: "document", name: "sound.mp3", uri: "https://example.com/sound.mp3" },
+ onOpen: openViewer,
+ }),
+ ),
+ );
+ await act(async () =>
+ container.querySelector<HTMLButtonElement>('button[aria-label="Play audio"]')!.click(),
+ );
+ expect(audio.played).toHaveBeenCalledOnce();
+ await act(async () =>
+ container.querySelector<HTMLButtonElement>('button[aria-label="Open sound.mp3"]')!.click(),
+ );
+ expect(audio.enabled).toBe(true);
+ const play = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "Play",
+ )!;
+ await act(async () => play.click());
+ expect(audio.played).toHaveBeenCalledTimes(2);
+ audio.player.pause.mockClear();
+ let recording!: ReturnType<typeof acquireAudioSession>;
+ await act(async () => {
+ recording = acquireAudioSession("recording");
+ });
+ expect(audio.player.pause).toHaveBeenCalledOnce();
+ await activateAudioSession(recording);
+ await act(async () => play.click());
+ expect(audio.played).toHaveBeenCalledTimes(2);
+ await releaseAudioSession(recording);
+ await act(async () => play.click());
+ expect(audio.played).toHaveBeenCalledTimes(3);
+ expect(audio.enabled).toBe(true);
+ });
+
+ it.each(["pause", "unmount", "recording"])(
+ "does not restart the file viewer after %s during replay seeking",
+ async (action) => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ audio.status = { ...audio.status, isLoaded: true, didJustFinish: true, currentTime: 10 };
+ const seek = Promise.withResolvers<void>();
+ audio.player.seekTo.mockReturnValueOnce(seek.promise);
+ const container = document.createElement("div");
+ root = createRoot(container);
+ await act(async () =>
+ root!.render(
+ createElement(AudioFilePreview, { uri: "https://example.com/sound.mp3", onRetry() {} }),
+ ),
+ );
+ const play = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "Play",
+ )!;
+ await act(async () => play.click());
+ expect(play.textContent).toBe("Pause");
+ let recording: ReturnType<typeof acquireAudioSession> | undefined;
+ if (action === "pause") await act(async () => play.click());
+ else if (action === "recording") {
+ await act(async () => {
+ recording = acquireAudioSession("recording");
+ });
+ expect(play.textContent).toBe("Play");
+ await activateAudioSession(recording!);
+ } else {
+ await act(async () => root!.unmount());
+ root = undefined;
+ }
+ await act(async () => seek.resolve());
+ expect(audio.played).not.toHaveBeenCalled();
+ if (recording) await releaseAudioSession(recording);
+ },
+ );
+
+ it.each(["buffering", "seek"])(
+ "keeps file viewer ownership through %s and native resume",
+ async (transition) => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ audio.status = { ...audio.status, isLoaded: true };
+ const container = document.createElement("div");
+ root = createRoot(container);
+ const render = () =>
+ root!.render(
+ createElement(AudioFilePreview, {
+ uri: "https://example.com/sound.mp3",
+ onRetry() {},
+ }),
+ );
+ await act(async () => render());
+ await act(async () =>
+ [...container.querySelectorAll("button")]
+ .find((button) => button.textContent === "Play")!
+ .click(),
+ );
+ audio.status = { ...audio.status, playing: true };
+ await act(async () => render());
+ audio.player.pause.mockClear();
+ if (transition === "seek") {
+ await act(async () =>
+ [...container.querySelectorAll("button")]
+ .find((button) => button.textContent === "+15s")!
+ .click(),
+ );
+ expect(audio.player.seekTo).toHaveBeenCalledWith(10);
+ }
+ audio.status = { ...audio.status, playing: false, isBuffering: transition === "buffering" };
+ await act(async () => render());
+ expect(audio.player.pause).not.toHaveBeenCalled();
+ expect(
+ [...container.querySelectorAll("button")].map((button) => button.textContent),
+ ).toContain("Pause");
+ audio.status = { ...audio.status, playing: true, isBuffering: false };
+ await act(async () => render());
+ expect(audio.played).toHaveBeenCalledOnce();
+ let recording!: ReturnType<typeof acquireAudioSession>;
+ await act(async () => {
+ recording = acquireAudioSession("recording");
+ });
+ expect(audio.player.pause).toHaveBeenCalledOnce();
+ await releaseAudioSession(recording);
+ },
+ );
+
+ it.each(["pause", "pause while buffering", "pause while loading", "end", "error"])(
+ "releases file viewer ownership on %s",
+ async (action) => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ audio.status = { ...audio.status, isLoaded: true };
+ const container = document.createElement("div");
+ root = createRoot(container);
+ const render = () =>
+ root!.render(
+ createElement(AudioFilePreview, {
+ uri: "https://example.com/sound.mp3",
+ onRetry() {},
+ }),
+ );
+ await act(async () => render());
+ await act(async () =>
+ [...container.querySelectorAll("button")]
+ .find((button) => button.textContent === "Play")!
+ .click(),
+ );
+ audio.status = { ...audio.status, playing: true };
+ await act(async () => render());
+ if (action.startsWith("pause")) {
+ if (action !== "pause") {
+ audio.status = {
+ ...audio.status,
+ playing: false,
+ isBuffering: true,
+ isLoaded: action !== "pause while loading",
+ };
+ await act(async () => render());
+ }
+ await act(async () =>
+ [...container.querySelectorAll("button")]
+ .find((button) => button.textContent === "Pause")!
+ .click(),
+ );
+ } else {
+ audio.status = { ...audio.status, playing: false, didJustFinish: action === "end" };
+ if (action === "error") Object.assign(audio.status, { error: "Playback failed" });
+ await act(async () => render());
+ }
+ expect(audio.player.pause).toHaveBeenLastCalledWith();
+ audio.status = { ...audio.status, playing: false, isBuffering: false, isLoaded: true };
+ await act(async () => render());
+ expect(
+ [...container.querySelectorAll("button")].map((button) => button.textContent),
+ ).toContain("Play");
+ audio.player.pause.mockClear();
+ const recording = acquireAudioSession("recording");
+ expect(audio.player.pause).not.toHaveBeenCalled();
+ expect(audio.setActive).not.toHaveBeenCalledWith(false);
+ await releaseAudioSession(recording);
+ },
+ );
+
+ it.each(["buffering", "seek"])(
+ "keeps video ownership through %s and resume, including recording takeover during the next wait",
+ async (transition) => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ root = createRoot(document.createElement("div"));
+ await act(async () =>
+ root!.render(
+ createElement(MediaVideoPlayer, {
+ uri: "https://example.com/clip.mp4",
+ name: "clip.mp4",
+ thumbnailKey: "clip",
+ expanded: true,
+ autoPlay: true,
+ }),
+ ),
+ );
+ audio.video.pause.mockClear();
+ // iOS can keep readyToPlay during a seek's evaluatingBufferingRate wait.
+ if (transition === "buffering") {
+ audio.video.status = "loading";
+ for (const listener of audio.videoStatusListeners) listener({ status: "loading" });
+ }
+ audio.video.playing = false;
+ for (const listener of audio.videoListeners) listener({ isPlaying: false });
+ expect(audio.video.pause).not.toHaveBeenCalled();
+ // Buffer readiness can precede the native playing=true event.
+ audio.video.status = "readyToPlay";
+ for (const listener of audio.videoStatusListeners) listener({ status: "readyToPlay" });
+ expect(audio.video.pause).not.toHaveBeenCalled();
+ audio.video.playing = true;
+ for (const listener of audio.videoListeners) listener({ isPlaying: true });
+ expect(audio.video.play).toHaveBeenCalledOnce();
+ audio.video.playing = false;
+ for (const listener of audio.videoListeners) listener({ isPlaying: false });
+ const recording = acquireAudioSession("recording");
+ expect(audio.video.pause).toHaveBeenCalledOnce();
+ audio.video.play();
+ expect(audio.video.playing).toBe(false);
+ await releaseAudioSession(recording);
+ audio.video.play();
+ expect(audio.video.playing).toBe(true);
+ },
+ );
+
+ it.each(["pause", "pause while buffering", "end", "error"])(
+ "releases video ownership on %s",
+ async (action) => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ root = createRoot(document.createElement("div"));
+ await act(async () =>
+ root!.render(
+ createElement(MediaVideoPlayer, {
+ uri: "https://example.com/clip.mp4",
+ name: "clip.mp4",
+ thumbnailKey: "clip",
+ expanded: true,
+ autoPlay: true,
+ }),
+ ),
+ );
+ await act(async () => {
+ if (action.startsWith("pause")) {
+ if (action === "pause while buffering") {
+ audio.video.status = "loading";
+ audio.video.playing = false;
+ for (const listener of audio.videoListeners) listener({ isPlaying: false });
+ }
+ audio.video.pause();
+ } else if (action === "end") {
+ for (const listener of audio.videoEndListeners) listener();
+ } else {
+ audio.video.status = "error";
+ for (const listener of audio.videoStatusListeners) listener({ status: "error" });
+ }
+ });
+ audio.video.pause.mockClear();
+ const recording = acquireAudioSession("recording");
+ expect(audio.video.pause).not.toHaveBeenCalled();
+ await releaseAudioSession(recording);
+ },
+ );
+
+ it("keeps thread video playback and native controls working after audio releases", async () => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const recording = acquireAudioSession("recording");
+ await activateAudioSession(recording);
+ await releaseAudioSession(recording);
+ const modes = audio.setAudioMode.mock.calls.length;
+ const activations = audio.setActive.mock.calls.length;
+ const container = document.createElement("div");
+ root = createRoot(container);
+ await act(async () =>
+ root!.render(
+ createElement(MediaVideoPlayer, {
+ uri: "https://example.com/clip.mp4",
+ name: "clip.mp4",
+ thumbnailKey: "clip",
+ expanded: true,
+ autoPlay: true,
+ }),
+ ),
+ );
+ expect(audio.video.playing).toBe(true);
+ expect(audio.setAudioMode).toHaveBeenCalledTimes(modes);
+ expect(audio.setActive).toHaveBeenCalledTimes(activations);
+ audio.video.pause();
+ audio.video.play();
+ expect(audio.video.playing).toBe(true);
+ const takeover = acquireAudioSession("recording");
+ expect(audio.video.playing).toBe(false);
+ await activateAudioSession(takeover);
+ audio.video.play();
+ expect(audio.video.playing).toBe(false);
+ await releaseAudioSession(takeover);
+ audio.video.play();
+ expect(audio.video.playing).toBe(true);
+ await act(async () => root!.unmount());
+ root = undefined;
+ expect(audio.video.playing).toBe(false);
+ });
+
+ it.each(["play", "cancel", "unmount", "mode failure", "activation failure"])(
+ "reactivates audio after voice release and honors %s during activation",
+ async (intent) => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const recording = acquireAudioSession("recording");
+ await activateAudioSession(recording);
+ await releaseAudioSession(recording);
+ vi.clearAllMocks();
+ let activate: () => void = () => {};
+ if (intent === "mode failure") {
+ audio.setAudioMode.mockRejectedValueOnce(new Error("Playback mode unavailable"));
+ } else if (intent === "activation failure") {
+ audio.setActive.mockRejectedValueOnce(new Error("Audio session unavailable"));
+ } else {
+ audio.setActive.mockImplementationOnce(
+ () => new Promise((resolve) => (activate = resolve)),
+ );
+ }
+ audio.status = { ...audio.status, isLoaded: true };
+ const container = document.createElement("div");
+ root = createRoot(container);
+ act(() =>
+ root!.render(
+ createElement(ThreadInlineFilePreview, {
+ source: { kind: "document", name: "sound.mp3", uri: "https://example.com/sound.mp3" },
+ onOpen() {},
+ }),
+ ),
+ );
+ const button = container.querySelector<HTMLButtonElement>('button[aria-label="Play audio"]')!;
+ await act(async () => button.click());
+ expect(audio.setAudioMode).toHaveBeenLastCalledWith({
+ allowsRecording: false,
+ playsInSilentMode: true,
+ interruptionMode: "doNotMix",
+ shouldPlayInBackground: false,
+ });
+ expect(audio.player.play).not.toHaveBeenCalled();
+ if (intent.endsWith("failure")) {
+ expect(container.textContent).toContain("Unavailable · tap play to retry");
+ expect(button.getAttribute("aria-label")).toBe("Retry audio");
+ expect(audio.setActive).not.toHaveBeenCalledWith(false);
+ return;
+ }
+ expect(audio.setActive).toHaveBeenLastCalledWith(true);
+ expect(audio.setAudioMode.mock.invocationCallOrder[0]).toBeLessThan(
+ audio.setActive.mock.invocationCallOrder[0]!,
+ );
+ if (intent === "cancel") await act(async () => button.click());
+ else if (intent === "unmount") {
+ act(() => root!.unmount());
+ root = undefined;
+ expect(audio.player.release).not.toHaveBeenCalled();
+ }
+ await act(async () => activate());
+ if (intent === "play") {
+ expect(audio.player.play).toHaveBeenCalledOnce();
+ expect(button.getAttribute("aria-label")).toBe("Pause audio");
+ } else {
+ expect(audio.player.play).not.toHaveBeenCalled();
+ expect(audio.setActive).toHaveBeenLastCalledWith(true);
+ expect(audio.player.pause).toHaveBeenCalled();
+ if (intent === "unmount") {
+ expect(audio.player.release).toHaveBeenCalledOnce();
+ expect(audio.player.pause.mock.invocationCallOrder[0]).toBeLessThan(
+ audio.player.release.mock.invocationCallOrder[0]!,
+ );
+ }
+ if (intent === "cancel") expect(button.getAttribute("aria-label")).toBe("Play audio");
+ }
+ },
+ );
+
+ it.each(["playing", "URL pending", "mode pending", "activation pending"])(
+ "yields to recording while %s and plays again after recording stops",
+ async (phase) => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const url = Promise.withResolvers<string>();
+ const native = Promise.withResolvers<void>();
+ audio.refresh.mockReturnValueOnce(url.promise);
+ audio.status = { ...audio.status, isLoaded: phase !== "URL pending" };
+ if (phase === "mode pending") audio.setAudioMode.mockReturnValueOnce(native.promise);
+ if (phase === "activation pending") audio.setActive.mockReturnValueOnce(native.promise);
+ const container = document.createElement("div");
+ root = createRoot(container);
+ act(() =>
+ root!.render(
+ createElement(ThreadInlineFilePreview, {
+ source: {
+ kind: "document",
+ name: "sound.mp3",
+ environmentId: EnvironmentId.make("environment-1"),
+ resource: {
+ _tag: "workspace-file",
+ threadId: ThreadId.make("thread-1"),
+ path: "/repo/sound.mp3",
+ },
+ },
+ onOpen() {},
+ }),
+ ),
+ );
+ const button = container.querySelector<HTMLButtonElement>('button[aria-label="Play audio"]')!;
+ await act(async () => button.click());
+ expect(audio.player.play).toHaveBeenCalledTimes(phase === "playing" ? 1 : 0);
+ expect(audio.refresh).toHaveBeenCalledTimes(phase === "URL pending" ? 1 : 0);
+ let recording!: ReturnType<typeof acquireAudioSession>;
+ await act(async () => {
+ recording = acquireAudioSession("recording");
+ });
+ expect(audio.player.pause).toHaveBeenCalled();
+ expect(button.getAttribute("aria-label")).toBe("Play audio");
+ native.resolve();
+ await activateAudioSession(recording);
+ expect(audio.setAudioMode).toHaveBeenLastCalledWith({
+ allowsRecording: true,
+ interruptionMode: "doNotMix",
+ playsInSilentMode: true,
+ shouldPlayInBackground: false,
+ });
+ const modeCalls = audio.setAudioMode.mock.calls.length;
+ const activationCalls = audio.setActive.mock.calls.length;
+ await act(async () => url.resolve("https://example.com/sound.mp3"));
+ await act(async () => button.click());
+ expect(audio.setAudioMode).toHaveBeenCalledTimes(modeCalls);
+ expect(audio.setActive).toHaveBeenCalledTimes(activationCalls);
+ expect(audio.setActive).not.toHaveBeenCalledWith(false);
+ expect(audio.player.play).toHaveBeenCalledTimes(phase === "playing" ? 1 : 0);
+ await releaseAudioSession(recording);
+ audio.status = { ...audio.status, isLoaded: true };
+ // Refresh the native status before the next tap.
+ await act(async () =>
+ root!.render(
+ createElement(ThreadInlineFilePreview, {
+ source: { kind: "document", name: "sound.mp3", uri: "https://example.com/sound.mp3" },
+ onOpen() {},
+ }),
+ ),
+ );
+ const replay = container.querySelector<HTMLButtonElement>('button[aria-label="Play audio"]')!;
+ await act(async () => replay.click());
+ expect(audio.player.play).toHaveBeenCalledTimes(phase === "playing" ? 2 : 1);
+ expect(audio.setAudioMode).toHaveBeenLastCalledWith({
+ allowsRecording: false,
+ interruptionMode: "doNotMix",
+ playsInSilentMode: true,
+ shouldPlayInBackground: false,
+ });
+ expect(audio.setActive).toHaveBeenLastCalledWith(true);
+ },
+ );
+
+ it.each(["cancel", "unmount", "replay, stale first", "replay, latest first"])(
+ "honors the latest audio intent after %s during URL resolution",
+ async (intent) => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const container = document.createElement("div");
+ root = createRoot(container);
+ const resolutions: Array<(uri: string) => void> = [];
+ audio.refresh.mockImplementation(() => new Promise((resolve) => resolutions.push(resolve)));
+ act(() =>
+ root!.render(
+ createElement(ThreadInlineFilePreview, {
+ source: {
+ kind: "document",
+ name: "sound.mp3",
+ environmentId: EnvironmentId.make("environment-1"),
+ resource: {
+ _tag: "workspace-file",
+ threadId: ThreadId.make("thread-1"),
+ path: "/repo/sound.mp3",
+ },
+ },
+ onOpen() {},
+ }),
+ ),
+ );
+ const button = container.querySelector<HTMLButtonElement>('button[aria-label="Play audio"]')!;
+ await act(async () => button.click());
+ if (intent !== "unmount") {
+ await act(async () => button.click());
+ expect(button.getAttribute("aria-label")).toBe("Play audio");
+ }
+ const replay = intent.startsWith("replay");
+ if (replay) {
+ await act(async () => button.click());
+ expect(button.getAttribute("aria-label")).toBe("Pause audio");
+ expect(audio.refresh).toHaveBeenCalledTimes(2);
+ } else if (intent === "unmount") {
+ act(() => root!.unmount());
+ root = undefined;
+ }
+ const latestFirst = intent === "replay, latest first";
+ if (latestFirst) await act(async () => resolutions[1]!("https://example.com/latest.mp3"));
+ await act(async () => resolutions[0]!("https://example.com/stale.mp3"));
+ expect(audio.player.play).toHaveBeenCalledTimes(latestFirst ? 1 : 0);
+ expect(audio.player.replace).toHaveBeenCalledTimes(latestFirst ? 1 : 0);
+ if (replay) {
+ expect(button.getAttribute("aria-label")).toBe("Pause audio");
+ if (!latestFirst) {
+ expect(container.textContent).toContain("Loading…");
+ await act(async () => resolutions[1]!("https://example.com/latest.mp3"));
+ }
+ expect(audio.player.replace).toHaveBeenCalledExactlyOnceWith({
+ uri: "https://example.com/latest.mp3",
+ });
+ expect(audio.player.play).toHaveBeenCalledOnce();
+ }
+ },
+ );
+
+ it.each([false, true])(
+ "cancels a second tap while buffering with isLoaded=%s",
+ async (isLoaded) => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const container = document.createElement("div");
+ root = createRoot(container);
+ audio.status = { ...audio.status, isLoaded, isBuffering: isLoaded };
+ let resolve: (uri: string) => void = () => {};
+ audio.refresh.mockImplementation(
+ () =>
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const preview = createElement(ThreadInlineFilePreview, {
+ source: {
+ kind: "document",
+ name: "sound.mp3",
+ environmentId: EnvironmentId.make("environment-1"),
+ resource: {
+ _tag: "workspace-file",
+ threadId: ThreadId.make("thread-1"),
+ path: "/repo/sound.mp3",
+ },
+ },
+ onOpen() {},
+ });
+ act(() => root!.render(preview));
+ const button = container.querySelector<HTMLButtonElement>('button[aria-label="Play audio"]')!;
+ await act(async () => button.click());
+ expect(audio.player.play).toHaveBeenCalledTimes(isLoaded ? 1 : 0);
+ expect(button.disabled).toBe(false);
+ expect(button.getAttribute("aria-label")).toBe("Pause audio");
+ expect(button.getAttribute("aria-busy")).toBe("true");
+ await act(async () => button.click());
+ expect(audio.player.pause).toHaveBeenCalled();
+ expect(button.getAttribute("aria-label")).toBe("Play audio");
+ expect(button.getAttribute("aria-busy")).toBe("false");
+ if (!isLoaded) await act(async () => resolve("https://example.com/sound.mp3"));
+ expect(audio.player.play).toHaveBeenCalledTimes(isLoaded ? 1 : 0);
+ if (!isLoaded) {
+ expect(audio.player.replace).not.toHaveBeenCalled();
+ audio.refresh.mockResolvedValue("https://example.com/sound.mp3");
+ }
+ await act(async () => button.click());
+ expect(audio.player.play).toHaveBeenCalledTimes(isLoaded ? 2 : 1);
+ audio.status = { ...audio.status, isLoaded: true, didJustFinish: true, currentTime: 10 };
+ await act(async () =>
+ root!.render(createElement(ThreadInlineFilePreview, { ...preview.props })),
+ );
+ expect(button.getAttribute("aria-label")).toBe("Play audio");
+ await act(async () => button.click());
+ expect(audio.player.seekTo).toHaveBeenCalledWith(0);
+ expect(audio.player.play).toHaveBeenCalledTimes(isLoaded ? 3 : 2);
+ },
+ );
+});
describe("PDF preview detection", () => {
it.each([
@@ -12,3 +1281,25 @@ describe("PDF preview detection", () => {
expect(isPdfFile(file)).toBe(expected);
});
});
+
+describe("inline file previews", () => {
+ it.each([
+ [{ name: "sound.MP3" }, "audio"],
+ [{ name: "sound", mimeType: "audio/wav" }, "audio"],
+ [{ name: "report.PDF", mimeType: "text/plain" }, null],
+ [{ name: "report.csv" }, null],
+ [{ name: "report.tsv" }, null],
+ [{ name: "report", mimeType: "text/csv; charset=utf-8" }, null],
+ [{ name: "report.csv", mimeType: "image/png" }, null],
+ [{ name: "image.png" }, null],
+ [{ name: "clip.mp4" }, null],
+ [{ name: "file.zip" }, null],
+ [{ name: "report.docx" }, null],
+ [{ name: "report.xlsx" }, null],
+ [{ name: "report.pptx" }, null],
+ [{ name: "download", mimeType: "application/pdf" }, null],
+ [{ name: "sound.mp3", mimeType: "application/pdf" }, null],
+ ])("classifies %j as %s", (file, expected) => {
+ expect(inlineFilePreviewKind(file)).toBe(expected);
+ });
+});
diff --git a/apps/mobile/src/lib/filePreview.ts b/apps/mobile/src/lib/filePreview.ts
index 82d62ebb52e..78189172a58 100644
--- a/apps/mobile/src/lib/filePreview.ts
+++ b/apps/mobile/src/lib/filePreview.ts
@@ -1,3 +1,9 @@
+import { filePreviewKind } from "@t3tools/shared/filePreview";
+
+export function inlineFilePreviewKind(file: { readonly name: string; readonly mimeType?: string }) {
+ return filePreviewKind(file) === "audio" ? "audio" : null;
+}
+
export function isPdfFile(file: { readonly name: string; readonly mimeType?: string }): boolean {
const mimeType = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase();
if (mimeType && mimeType !== "application/octet-stream") return mimeType === "application/pdf";
diff --git a/apps/mobile/src/lib/markdownDocument.ts b/apps/mobile/src/lib/markdownDocument.ts
index f1ff9e51826..91c447401ca 100644
--- a/apps/mobile/src/lib/markdownDocument.ts
+++ b/apps/mobile/src/lib/markdownDocument.ts
@@ -351,3 +351,56 @@ export function markdownWithTableBreaks(markdown: string): string {
export function parseMarkdownDocument(markdown: string): Root {
return parser.parse(markdownWithHtml(markdown));
}
+
+/** Native media slots only cover standalone images; nested file embeds must become links. */
+export function markdownWithFileEmbeds(
+ markdown: string,
+ label: (href: string, standalone: boolean) => string | null,
+): { markdown: string; fileHrefs: ReadonlySet<string> } {
+ const fileHrefs = new Set<string>();
+ if (!markdown.includes("![")) return { markdown, fileHrefs };
+ const root = parser.parse(markdown);
+ const topLevelBlocks = new Set<MarkdownNode>(root.children);
+ const definitions = new Map<string, string>();
+ const collect = (node: MarkdownNode) => {
+ if (node.type === "definition") {
+ const identifier = node.identifier.toUpperCase();
+ if (!definitions.has(identifier)) definitions.set(identifier, node.url);
+ }
+ if ("children" in node) node.children.forEach(collect);
+ };
+ collect(root);
+ const edits: Array<{ start: number; end: number; content: string }> = [];
+ const visit = (node: MarkdownNode, standalone = false, insideLink = false) => {
+ if (node.type === "image" || node.type === "imageReference") {
+ const href =
+ node.type === "image" ? node.url : definitions.get(node.identifier.toUpperCase());
+ const name = href === undefined ? null : label(href, standalone);
+ const start = node.position?.start.offset;
+ const end = node.position?.end.offset;
+ if (href !== undefined && name !== null && start !== undefined && end !== undefined) {
+ const text = name.replace(/[\\[\]`*_~|&<>]/g, "\\$&");
+ const url = href.replace(/[\\&]/g, "\\$&").replace(/</g, "%3C").replace(/>/g, "%3E");
+ edits.push({ start, end, content: insideLink ? text : `[${text}](<${url}>)` });
+ fileHrefs.add(href);
+ }
+ }
+ if ("children" in node)
+ node.children.forEach((child) =>
+ visit(
+ child,
+ node.type === "paragraph" && node.children.length === 1 && topLevelBlocks.has(node),
+ insideLink || node.type === "link" || node.type === "linkReference",
+ ),
+ );
+ };
+ visit(root);
+ const parts: string[] = [];
+ let offset = 0;
+ for (const edit of edits) {
+ parts.push(markdown.slice(offset, edit.start), edit.content);
+ offset = edit.end;
+ }
+ parts.push(markdown.slice(offset));
+ return { markdown: parts.join(""), fileHrefs };
+}
diff --git a/apps/mobile/src/lib/markdownHtml.test.ts b/apps/mobile/src/lib/markdownHtml.test.ts
index cded1331b75..e27cf812ed4 100644
--- a/apps/mobile/src/lib/markdownHtml.test.ts
+++ b/apps/mobile/src/lib/markdownHtml.test.ts
@@ -1,6 +1,16 @@
import { describe, expect, it } from "vite-plus/test";
-import { markdownHtmlContent, markdownWithHtml, parseMarkdownDocument } from "./markdownDocument";
+import {
+ markdownHtmlContent,
+ markdownWithHtml,
+ markdownWithFileEmbeds,
+ parseMarkdownDocument,
+ type MarkdownNode,
+} from "./markdownDocument";
import { markdownImageSources } from "./markdownImageSources";
+import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "./markdownMedia";
+import { resolveMarkdownLinkPresentation } from "./markdownLinks";
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
describe("HTML in native Markdown", () => {
it("preserves screenshot URLs and captions from GitHub HTML image embeds", () => {
@@ -95,3 +105,194 @@ describe("HTML in native Markdown", () => {
expect(markdownWithHtml('Run <a href="javascript:alert(1)">this</a> now')).toBe("Run this now");
});
});
+
+describe("file embeds in native thread and file Markdown", () => {
+ const input = {
+ environmentId: EnvironmentId.make("environment-1"),
+ threadId: ThreadId.make("thread-1"),
+ workspaceRoot: "/repo",
+ };
+ const assets = (markdown: string) => {
+ const result: MarkdownNode[] = [];
+ const visit = (node: MarkdownNode) => {
+ if (node.type === "link" || node.type === "image") result.push(node);
+ if ("children" in node) node.children.forEach(visit);
+ };
+ visit(parseMarkdownDocument(markdown));
+ return result;
+ };
+
+ it.each([
+ [
+ "[![sheet](./report.csv)](https://example.com/download)",
+ "report.csv",
+ "https://example.com/download",
+ ],
+ ["[![report](./report.pdf)](./report.pdf)", "report.pdf", "./report.pdf"],
+ [
+ "[![sheet][f]][download]\n\n[f]: ./report.csv\n[download]: https://example.com/download",
+ "report.csv",
+ "https://example.com/download",
+ ],
+ ])("keeps the enclosing link for %s", async (source, filename, target) => {
+ const converted = markdownWithFileEmbeds(source, (href, standalone) =>
+ markdownFileEmbedLabel(href, input, standalone),
+ );
+ expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
+ {
+ type: "Paragraph",
+ children: [
+ {
+ type: "Link",
+ attributes: { url: target },
+ children: [{ type: "Text", content: filename }],
+ },
+ ],
+ },
+ ]);
+ });
+
+ it.each(["f", "F", "File Label", "file label"])(
+ "uses the first reference definition for %s",
+ async (identifier) => {
+ const source = `![sheet][${identifier}]\n\n[${identifier.toLowerCase()}]: ./report.csv\n[${identifier.toUpperCase()}]: ./report.xlsx`;
+ const converted = markdownWithFileEmbeds(source, (href, standalone) =>
+ markdownFileEmbedLabel(href, input, standalone),
+ );
+ expect(converted.fileHrefs).toEqual(new Set(["./report.csv"]));
+ expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
+ {
+ type: "Paragraph",
+ children: [
+ {
+ type: "Link",
+ attributes: { url: "./report.csv" },
+ children: [{ type: "Text", content: "report.csv" }],
+ },
+ ],
+ },
+ ]);
+ expect((await parseMarkdown(source)).children).toMatchObject([
+ { type: "Paragraph", children: [{ type: "Image", attributes: { url: "./report.csv" } }] },
+ ]);
+ },
+ );
+
+ it.each([
+ "report.csv",
+ "report.tsv",
+ "report.pdf",
+ "report.docx",
+ "report.xlsx",
+ "report.pptx",
+ "report.unknown",
+ "main.tf",
+ "schema.prisma",
+ "index.astro",
+ "main.zig",
+ "Containerfile",
+ "sound.mp3",
+ "clip.mp4",
+ ])("uses filename links throughout prose, lists, and tables for %s", (name) => {
+ for (const href of [
+ `./${name}`,
+ `/tmp/${name}`,
+ `file:///tmp/${name}`,
+ `https://cdn.example.com/${name}?signature=a%2fb`,
+ ]) {
+ if (name === "Containerfile" && href.startsWith("https:")) continue;
+ for (const source of [
+ `download: ![sheet](<${href}>)`,
+ `- ![sheet](<${href}>)`,
+ `| file |\n| --- |\n| ![sheet](<${href}>) |`,
+ `download: ![sheet][file]\n\n[file]: <${href}>`,
+ `download: <img src="${href}" alt="sheet">`,
+ ]) {
+ const converted = markdownWithFileEmbeds(markdownWithHtml(source), (url, standalone) =>
+ markdownFileEmbedLabel(url, input, standalone),
+ );
+ const image = href.startsWith("https:") && /\.(unknown|tf|prisma|astro|zig)$/.test(name);
+ if (image) expect(converted.markdown).toBe(markdownWithHtml(source));
+ else
+ expect(assets(converted.markdown)).toMatchObject([
+ { type: "link", url: href, children: [{ type: "text", value: name }] },
+ ]);
+ expect(converted.fileHrefs.has(href)).toBe(!image);
+ const preview = resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true });
+ if (
+ !href.startsWith("https:") &&
+ !name.endsWith(".pdf") &&
+ !name.endsWith(".mp3") &&
+ !name.endsWith(".mp4")
+ ) {
+ expect(preview?.kind).toBe("file");
+ expect(resolveMarkdownLinkPresentation(href)).toMatchObject({ kind: "file" });
+ }
+ }
+ }
+ });
+
+ it("retains standalone audio players and image/video embeds in threads", () => {
+ const source =
+ "![sound](./sound.mp3)\n\n![image](./image.png)\n\n![clip](./clip.mp4)\n\ninline ![photo](./photo.png)";
+ const converted = markdownWithFileEmbeds(source, (href, standalone) =>
+ markdownFileEmbedLabel(href, input, standalone),
+ );
+ expect(converted.markdown).toBe(source);
+ expect(converted.fileHrefs.size).toBe(0);
+ expect(resolveMarkdownMediaPreview("./sound.mp3", input)?.kind).toBe("audio");
+ });
+
+ it("uses audio filenames in file previews and draft workspaces", () => {
+ const draft = { ...input, threadId: undefined, workspaceRoot: "/repo/docs" };
+ const converted = markdownWithFileEmbeds("![sound](./sound.mp3)", (href) =>
+ markdownFileEmbedLabel(href, draft, false),
+ );
+ expect(assets(converted.markdown)).toMatchObject([
+ { type: "link", url: "./sound.mp3", children: [{ value: "sound.mp3" }] },
+ ]);
+ expect(resolveMarkdownMediaPreview("./sound.mp3", draft)?.source).toMatchObject({
+ resource: { _tag: "draft-workspace-file", cwd: "/repo/docs", path: "/repo/docs/./sound.mp3" },
+ });
+ });
+
+ it("keeps captured images on the image path and documents on filename links", () => {
+ const captured = { ...input, captured: true };
+ const converted = markdownWithFileEmbeds(
+ "![photo](./photo.png)\n\n![clip](./clip.mp4)\n\n![sheet](./report.csv)",
+ (href, standalone) => markdownFileEmbedLabel(href, captured, standalone),
+ );
+ expect(assets(converted.markdown)).toMatchObject([
+ { type: "image", url: "./photo.png" },
+ { type: "image", url: "./clip.mp4" },
+ { type: "link", url: "./report.csv", children: [{ value: "report.csv" }] },
+ ]);
+ expect(resolveMarkdownMediaPreview("./report.csv", captured)).toBeNull();
+ });
+
+ it("preserves table structure and filename punctuation", () => {
+ const source = "| file |\n| --- |\n| ![sheet](./report%5B1%5D%26%7C.csv) |";
+ const converted = markdownWithFileEmbeds(source, (href, standalone) =>
+ markdownFileEmbedLabel(href, input, standalone),
+ );
+ expect(parseMarkdownDocument(converted.markdown).children[0]?.type).toBe("table");
+ expect(assets(converted.markdown)).toMatchObject([
+ { type: "link", url: "./report%5B1%5D%26%7C.csv", children: [{ value: "report[1]&|.csv" }] },
+ ]);
+ });
+
+ it("keeps authored positions, signed URLs, and code examples literal", () => {
+ const href = "https://cdn.example.com/report%23one%2520.csv?name=&lt;&signature=a%2fb";
+ const source = `![report](<${href.replaceAll("&", "\\&")}>)\n\n![source](./main.tf#L42C3)\n\n\`![sheet](./literal.csv)\`\n\n\`\`\`md\n![sheet](./fenced.csv)\n\`\`\``;
+ const converted = markdownWithFileEmbeds(source, (url, standalone) =>
+ markdownFileEmbedLabel(url, input, standalone),
+ );
+ expect(assets(converted.markdown)).toMatchObject([
+ { type: "link", url: href, children: [{ value: "report#one%20.csv" }] },
+ { type: "link", url: "./main.tf#L42C3", children: [{ value: "main.tf · L42:C3" }] },
+ ]);
+ expect(converted.markdown).toContain("`![sheet](./literal.csv)`");
+ expect(converted.markdown).toContain("```md\n![sheet](./fenced.csv)\n```");
+ expect(converted.fileHrefs.has(href)).toBe(true);
+ });
+});
diff --git a/apps/mobile/src/lib/markdownMedia.test.ts b/apps/mobile/src/lib/markdownMedia.test.ts
index ef7cca31114..a991c246b30 100644
--- a/apps/mobile/src/lib/markdownMedia.test.ts
+++ b/apps/mobile/src/lib/markdownMedia.test.ts
@@ -2,6 +2,7 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { resolveMarkdownMediaPreview } from "./markdownMedia";
+import { resolveMarkdownLinkPresentation } from "./markdownLinks";
const input = {
environmentId: EnvironmentId.make("environment-1"),
@@ -35,9 +36,9 @@ describe("resolveMarkdownMediaPreview", () => {
});
it.each([
- ["/tmp/frame%23one.png:12", "/tmp/frame#one.png"],
- ["/tmp/frame%3Fone.png:12:3", "/tmp/frame?one.png"],
- ["/tmp/frame%2523one.png:12", "/tmp/frame%23one.png"],
+ ["/tmp/frame%23one.png", "/tmp/frame#one.png"],
+ ["/tmp/frame%3Fone.png", "/tmp/frame?one.png"],
+ ["/tmp/frame%2523one.png", "/tmp/frame%23one.png"],
["file://server/share/frame.png", "\\\\server\\share\\frame.png", "\\\\server\\share"],
["\\\\server\\share\\frame.png", "\\\\server\\share\\frame.png", "\\\\server\\share"],
])("keeps encoded filename and UNC semantics for %s", (href, path, workspaceRoot = "/repo") => {
@@ -69,7 +70,7 @@ describe("resolveMarkdownMediaPreview", () => {
});
});
- it.each(["./image.png", "./report.pdf"])(
+ it.each(["./image.png", "./report.pdf", "./sound.mp3"])(
"uses the draft workspace when no thread exists: %s",
(href) => {
expect(
@@ -82,11 +83,208 @@ describe("resolveMarkdownMediaPreview", () => {
it("keeps captured host media unavailable while allowing direct media", () => {
const captured = { ...input, captured: true };
- for (const href of ["./image.png", "./clip.mp4", "./report.pdf"]) {
+ for (const href of ["./image.png", "./clip.mp4", "./report.pdf", "./sound.mp3"]) {
expect(resolveMarkdownMediaPreview(href, captured)).toBeNull();
}
expect(resolveMarkdownMediaPreview("https://cdn.example.com/report.pdf", captured)?.kind).toBe(
"pdf",
);
});
+
+ it.each([["/tmp/sound%23one.mp3", "audio", "audio/mpeg", "/tmp/sound#one.mp3"]])(
+ "opens an authored embed through the host: %s",
+ (href, kind, mimeType, path) => {
+ expect(resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true })).toMatchObject({
+ kind,
+ source: {
+ kind: "document",
+ name: path.split("/").at(-1),
+ mimeType,
+ environmentId: input.environmentId,
+ resource: { _tag: "media-file", threadId: input.threadId, path },
+ },
+ });
+ },
+ );
+
+ it.each([
+ ["sound%20one.mp3", "audio"],
+ ["report%20one.csv", "document"],
+ ["report.tsv", "document"],
+ ["report.docx", "document"],
+ ["report.xlsx", "document"],
+ ["report.pptx", "document"],
+ ["report.unknown", "image"],
+ ])("preserves direct signed embeds: %s", (name, kind) => {
+ const href = `https://cdn.example.com/${name}?signature=a%2fb`;
+ expect(resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true })).toMatchObject({
+ kind,
+ source: { uri: href, name: decodeURIComponent(name) },
+ });
+ });
+
+ it.each([
+ "https://docs.example.com/guide.html",
+ "https://example.com/index.php?topic=files",
+ "https://example.com/report.unknown",
+ "https://example.com/main.tf",
+ "https://example.com/schema.prisma",
+ "https://example.com/chart.php?id=1",
+ "http://example.com/chart.php?id=1",
+ "//example.com/chart.php?id=1",
+ "https://example.com/chart?format=png",
+ "http://example.com/chart?format=png",
+ "//example.com/chart?format=png",
+ ])("keeps ordinary remote links in the browser: %s", (href) => {
+ expect(resolveMarkdownMediaPreview(href, input)).toBeNull();
+ expect(resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true })).toMatchObject({
+ kind: "image",
+ source: { uri: href.startsWith("//") ? `https:${href}` : href },
+ });
+ });
+
+ it.each([
+ "javascript:report.csv",
+ "data:text/csv,a,b",
+ "ftp://server/report.csv",
+ "~/report.csv",
+ ])("rejects blocked document links and embeds: %s", (href) => {
+ expect(resolveMarkdownMediaPreview(href, input)).toBeNull();
+ expect(resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true })).toBeNull();
+ });
+
+ it.each([
+ "src/main.ts",
+ "src/main.tsx",
+ "report.txt",
+ "report.md",
+ "report.html",
+ "package.json",
+ "report.csv",
+ "report.tsv",
+ "LICENSE",
+ "Dockerfile",
+ "main.tf",
+ "schema.prisma",
+ "index.astro",
+ "main.zig",
+ "Containerfile",
+ ])("routes text and table links and embeds to the file screen: %s", (name) => {
+ for (const href of [name, "./" + name, "/tmp/" + name, "file:///tmp/" + name]) {
+ for (const imageEmbed of [false, true]) {
+ expect(resolveMarkdownMediaPreview(href, { ...input, imageEmbed })).toMatchObject({
+ kind: "file",
+ source: { name: name.split("/").at(-1) },
+ });
+ }
+ expect(resolveMarkdownLinkPresentation(href)).toMatchObject({ kind: "file" });
+ }
+ });
+
+ it.each(["doc", "docx", "xls", "xlsx", "ppt", "pptx", "unknown", "zip"])(
+ "keeps main's source reader for host %s links and embeds",
+ (extension) => {
+ const name = `report.${extension}`;
+ for (const href of [name, `./${name}`, `/tmp/${name}`, `file:///tmp/${name}`]) {
+ for (const imageEmbed of [false, true]) {
+ expect(resolveMarkdownMediaPreview(href, { ...input, imageEmbed })).toMatchObject({
+ kind: "file",
+ source: {
+ name,
+ mimeType: "text/plain",
+ },
+ });
+ expect(
+ resolveMarkdownMediaPreview(href, {
+ ...input,
+ threadId: undefined,
+ imageEmbed,
+ })?.kind,
+ ).toBe("file");
+ expect(resolveMarkdownLinkPresentation(href)).toMatchObject({ kind: "file" });
+ }
+ }
+ },
+ );
+
+ it.each(["report.csv", "report.tsv", "report.docx", "report.xlsx", "report.unknown"])(
+ "preserves draft, captured, and encoded document paths: %s",
+ (name) => {
+ const href = `/tmp/one%23two%2520.${name.split(".").at(-1)}`;
+ const preview = resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true });
+ expect(preview?.source).toMatchObject({
+ name: `one#two%20.${name.split(".").at(-1)}`,
+ resource: { path: decodeURIComponent(href) },
+ });
+ expect(
+ resolveMarkdownMediaPreview(href, { ...input, threadId: undefined })?.source,
+ ).toMatchObject({ resource: { _tag: "draft-workspace-file", cwd: "/repo" } });
+ expect(resolveMarkdownMediaPreview(href, { ...input, captured: true })).toBeNull();
+ expect(
+ resolveMarkdownMediaPreview(href, { ...input, threadId: undefined, workspaceRoot: null }),
+ ).toBeNull();
+ },
+ );
+
+ it.each([
+ ["src/main.ts:42", "/repo/src/main.ts", 42],
+ ["src/main.ts#L42C3", "/repo/src/main.ts", 42],
+ ["report.csv:142:3", "/repo/report.csv", 142],
+ ["/tmp/report.pdf:12#page=2", "/tmp/report.pdf", 12],
+ ["file:///tmp/sound.mp3#L12", "/tmp/sound.mp3", 12],
+ ["/tmp/frame%23one.png:12", "/tmp/frame#one.png", 12],
+ ["/tmp/frame%3Fone.png:12:3", "/tmp/frame?one.png", 12],
+ ["/tmp/frame%2523one.png:12", "/tmp/frame%23one.png", 12],
+ ["./clip.mp4#L12C3", "/repo/./clip.mp4", 12],
+ ["src/main.ts%3A42%3A3", "/repo/src/main.ts", 42],
+ ])("keeps positioned links on the file route: %s", (href, path, line) => {
+ expect(resolveMarkdownMediaPreview(href, input)).toBeNull();
+ const presentation = resolveMarkdownLinkPresentation(href);
+ expect(presentation).toMatchObject({ kind: "file", line });
+ if (presentation.kind === "file") {
+ expect(
+ presentation.path.startsWith("/") ? presentation.path : "/repo/" + presentation.path,
+ ).toBe(path);
+ }
+ });
+
+ it.each(["mp3", "wav", "m4a", "ogg", "oga", "aac", "aiff", "flac", "opus"])(
+ "resolves audio embeds as audio rather than images: %s",
+ (extension) => {
+ expect(
+ resolveMarkdownMediaPreview("/tmp/sound." + extension, { ...input, imageEmbed: true }),
+ ).toMatchObject({
+ kind: "audio",
+ source: { kind: "document", resource: { _tag: "media-file" } },
+ });
+ },
+ );
+
+ it("does not authorize local files without thread or draft context", () => {
+ expect(
+ resolveMarkdownMediaPreview("/tmp/report.pdf", {
+ ...input,
+ threadId: undefined,
+ workspaceRoot: null,
+ }),
+ ).toBeNull();
+ expect(resolveMarkdownMediaPreview("report.pdf", { ...input, workspaceRoot: null })).toBeNull();
+ });
+
+ it("decodes document filenames once and preserves image and video embeds", () => {
+ expect(resolveMarkdownMediaPreview("/tmp/report%23one%2520.pdf", input)).toMatchObject({
+ kind: "pdf",
+ source: {
+ name: "report#one%20.pdf",
+ mimeType: "application/pdf",
+ resource: { path: "/tmp/report#one%20.pdf" },
+ },
+ });
+ expect(
+ resolveMarkdownMediaPreview("/tmp/image.png", { ...input, imageEmbed: true })?.kind,
+ ).toBe("image");
+ expect(resolveMarkdownMediaPreview("/tmp/clip.mp4", { ...input, imageEmbed: true })?.kind).toBe(
+ "video",
+ );
+ });
});
diff --git a/apps/mobile/src/lib/markdownMedia.ts b/apps/mobile/src/lib/markdownMedia.ts
index cb67a30dd2f..06d12256e28 100644
--- a/apps/mobile/src/lib/markdownMedia.ts
+++ b/apps/mobile/src/lib/markdownMedia.ts
@@ -2,20 +2,37 @@ import {
classifyMarkdownImageSource,
markdownImageSourceFragment,
} from "@t3tools/client-runtime/markdown-images";
+import {
+ audioMimeTypeFromExtension,
+ mediaMimeTypeFromExtension,
+} from "@t3tools/shared/filePreview";
import { splitFilePathPosition } from "@t3tools/shared/fileLinks";
+import { parseMarkdownFileLink } from "@t3tools/shared/markdownLinks";
import {
mediaFileReference,
mediaUrlReference,
mediaReferenceFileName,
} from "@t3tools/client-runtime/media-reference";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
-import { normalizeNativeMarkdownUrl } from "./markdownLinks";
+import { normalizeNativeMarkdownUrl, resolveMarkdownLinkPresentation } from "./markdownLinks";
import { resolveMobileMarkdownMediaSource } from "./markdownMediaSource";
import type { FilePreviewSource } from "../components/FilePreviewModal";
import type { MediaVideoPreviewSource } from "./videoPreviewSource";
import type { MediaActionsSource } from "./mediaActionsSource";
+const DOCUMENT_MIME_TYPES: Readonly<Record<string, string>> = {
+ ".pdf": "application/pdf",
+ ".csv": "text/csv",
+ ".tsv": "text/tab-separated-values",
+ ".doc": "application/msword",
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ ".xls": "application/vnd.ms-excel",
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ ".ppt": "application/vnd.ms-powerpoint",
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+};
+
export function resolveMarkdownMediaPreview(
href: string,
input: {
@@ -27,10 +44,13 @@ export function resolveMarkdownMediaPreview(
},
):
| { readonly kind: "image"; readonly source: FilePreviewSource }
- | { readonly kind: "pdf"; readonly source: FilePreviewSource }
+ | { readonly kind: "pdf" | "audio" | "document" | "file"; readonly source: FilePreviewSource }
| { readonly kind: "video"; readonly source: MediaVideoPreviewSource }
| null {
+ if (parseMarkdownFileLink(href)?.line !== undefined) return null;
const classified = classifyMarkdownImageSource(href, input.workspaceRoot);
+ if (classified._tag === "Direct" && /^data:(?!image\/|video\/)/i.test(classified.uri))
+ return null;
if (classified._tag !== "Blocked") {
const path =
classified._tag === "Direct" ? classified.uri : splitFilePathPosition(classified.path).path;
@@ -39,12 +59,37 @@ export function resolveMarkdownMediaPreview(
? mediaUrlReference(path)
: mediaFileReference(path, input.workspaceRoot);
const name = reference && mediaReferenceFileName(reference);
- if (name && /\.pdf$/i.test(name)) {
- const common = { kind: "pdf" as const, name, mimeType: "application/pdf" };
+ const extension = name?.slice(name.lastIndexOf(".")).toLowerCase() ?? "";
+ const isFile = classified._tag === "WorkspaceFile" || /^\.[a-z0-9]+$/i.test(extension);
+ if (
+ name &&
+ isFile &&
+ mediaMimeTypeFromExtension(extension) === null &&
+ (classified._tag !== "Direct" ||
+ Object.hasOwn(DOCUMENT_MIME_TYPES, extension) ||
+ audioMimeTypeFromExtension(extension) !== null)
+ ) {
+ const audioMimeType = audioMimeTypeFromExtension(extension);
+ const kind = audioMimeType
+ ? "audio"
+ : extension === ".pdf"
+ ? "pdf"
+ : classified._tag === "WorkspaceFile"
+ ? "file"
+ : "document";
+ const mimeType =
+ audioMimeType ??
+ (kind === "file" ? "text/plain" : DOCUMENT_MIME_TYPES[extension]) ??
+ "application/octet-stream";
+ const common = {
+ kind: kind === "pdf" ? ("pdf" as const) : ("document" as const),
+ name,
+ mimeType,
+ };
if (classified._tag === "Direct") {
const uri = normalizeNativeMarkdownUrl(path);
return {
- kind: "pdf",
+ kind,
source: {
...common,
uri,
@@ -65,7 +110,7 @@ export function resolveMarkdownMediaPreview(
: null;
if (!resource) return null;
return {
- kind: "pdf",
+ kind,
source: {
...common,
environmentId: input.environmentId,
@@ -111,3 +156,25 @@ export function resolveMarkdownMediaPreview(
? { kind, source: { type: "media", name, mimeType, ...target, actionsSource } }
: { kind, source: { kind, name, ...target, actionsSource } };
}
+
+export function markdownFileEmbedLabel(
+ href: string,
+ input: Parameters<typeof resolveMarkdownMediaPreview>[1],
+ standalone: boolean,
+): string | null {
+ const media = resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true });
+ if (media) {
+ if (
+ media.kind === "image" ||
+ ((media.kind === "video" || media.kind === "audio") && standalone)
+ )
+ return null;
+ return media.source.name ?? null;
+ }
+ const file = resolveMarkdownLinkPresentation(href);
+ if (file.kind === "file" && file.line === undefined) {
+ if (mediaMimeTypeFromExtension(file.path.slice(file.path.lastIndexOf("."))) !== null)
+ return null;
+ }
+ return file.kind === "file" ? file.label : null;
+}
diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsx
index 4dc1a4284cb..c3ee0dc3e37 100644
--- a/apps/mobile/src/native/EnrichedMarkdownText.tsx
+++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx
@@ -5,6 +5,7 @@ import {
formatComposerContextReference,
} from "@t3tools/shared/composerContextReferences";
import {
+ markdownWithFileEmbeds,
markdownWithHtml,
markdownWithInlineFileLinks,
markdownWithTableBreaks,
@@ -153,18 +154,18 @@ function enrichedStyle(
}
export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
- const { renderImage, resolveImageSource } = props;
+ const { renderImage, resolveImageSource, fileEmbedLabel } = props;
const { themeAppearance, mathRenderingEnabled } = useAppearancePreferences();
- const markdown = useMemo(
- () =>
- markdownWithTableBreaks(
- markdownWithInlineFileLinks(
- markdownWithHtml(props.markdown),
- ENRICHED_INLINE_FILE_LINK_REGEX,
- ),
- ),
- [props.markdown],
- );
+ const { markdown, fileHrefs } = useMemo(() => {
+ const content = markdownWithInlineFileLinks(
+ markdownWithHtml(props.markdown),
+ ENRICHED_INLINE_FILE_LINK_REGEX,
+ );
+ const files = fileEmbedLabel
+ ? markdownWithFileEmbeds(content, fileEmbedLabel)
+ : { markdown: content, fileHrefs: new Set<string>() };
+ return { ...files, markdown: markdownWithTableBreaks(files.markdown) };
+ }, [props.markdown, fileEmbedLabel]);
const [parsedLinkUrls, setParsedLinkUrls] = useState<ReadonlyArray<string>>([]);
const onLinksChange = useCallback((links: MarkdownLinkOccurrence[]) => {
const urls = [...new Set(links.map((link) => link.url))];
@@ -191,16 +192,21 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
: parsedLinkUrls,
[parsedLinkUrls, skillLinkKey],
);
- const { linkVariants, linkPillContent } = useEnrichedLinkVariants(linkUrls, props);
+ const { linkVariants, linkPillContent } = useEnrichedLinkVariants(linkUrls, props, fileHrefs);
const linkRecognition = useMemo(() => ({ text: skillRegex ?? undefined }), [skillRegex]);
const [activeMenu, setActiveMenu] = useState<{
url: string;
menu: NonNullable<ReturnType<NonNullable<typeof props.fileContextMenu>>>;
} | null>(null);
- const { fileContextMenu, onLinkPress, onFileContextMenuAction } = props;
+ const { fileContextMenu, onFileContextMenuAction } = props;
+ const onLinkPress = useCallback(
+ (url: string) =>
+ (fileHrefs.has(url) ? (props.onImagePress ?? props.onLinkPress) : props.onLinkPress)?.(url),
+ [fileHrefs, props.onImagePress, props.onLinkPress],
+ );
const performMenuAction = useCallback(
(url: string, actionId: string) => {
- if (actionId === "enriched-open-link") onLinkPress?.(url);
+ if (actionId === "enriched-open-link") onLinkPress(url);
else if (actionId === "enriched-copy-link") copyTextWithHaptic(url);
else if (actionId === "enriched-share-link") void Share.share({ message: url });
else onFileContextMenuAction?.(url, actionId);
@@ -209,7 +215,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
);
const linkContextMenuItems = useMemo(
() =>
- Platform.OS === "ios" && (fileContextMenu || onLinkPress)
+ Platform.OS === "ios" && (fileContextMenu || props.onLinkPress || props.onImagePress)
? Object.fromEntries(
linkUrls.map((url) => {
const menu = fileContextMenu?.(url) ?? {
@@ -231,7 +237,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
}),
)
: undefined,
- [linkUrls, fileContextMenu, onLinkPress, performMenuAction],
+ [linkUrls, fileContextMenu, props.onLinkPress, props.onImagePress, performMenuAction],
);
const selectionClipboard = useMemo(() => {
const fragment = decodeComposerContextFragment(props.contextClipboardFragment);
@@ -330,7 +336,9 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
enableTaskListItemToggle={false}
enableCodeBlockWrapToggle
spoilerOverlay="solid"
- onLinkPress={props.onLinkPress ? ({ url }) => props.onLinkPress?.(url) : undefined}
+ onLinkPress={
+ props.onLinkPress || props.onImagePress ? ({ url }) => onLinkPress(url) : undefined
+ }
onLinkLongPress={onLinkLongPress}
linkContextMenuItems={linkContextMenuItems}
linkPillContent={linkPillContent}
diff --git a/apps/mobile/src/native/SelectableMarkdownText.types.ts b/apps/mobile/src/native/SelectableMarkdownText.types.ts
index e6c7d118117..ddb40d22db3 100644
--- a/apps/mobile/src/native/SelectableMarkdownText.types.ts
+++ b/apps/mobile/src/native/SelectableMarkdownText.types.ts
@@ -73,6 +73,7 @@ export interface SelectableMarkdownTextProps {
readonly linkCustomization?: (href: string) => MarkdownLinkCustomization | undefined;
readonly contextClipboardFragment?: string;
readonly renderImage?: MarkdownImageRenderer;
+ readonly fileEmbedLabel?: (href: string, standalone: boolean) => string | null;
readonly resolveImageSource?: MarkdownImageSourceResolver;
readonly onImagePress?: (href: string) => void;
readonly marginTop?: number;
diff --git a/apps/mobile/src/native/useEnrichedLinkVariants.ts b/apps/mobile/src/native/useEnrichedLinkVariants.ts
index 6776eccdbbd..789b3a0baeb 100644
--- a/apps/mobile/src/native/useEnrichedLinkVariants.ts
+++ b/apps/mobile/src/native/useEnrichedLinkVariants.ts
@@ -9,7 +9,7 @@ import { contextChipIconSource } from "../lib/contextChipIconSource";
import { markdownFileIconSource } from "../lib/markdownFileIcons";
import { markdownLinkIcon } from "../lib/markdownLinkIcons";
import { useUniwindTheme } from "../lib/useUniwindTheme";
-import { resolveMarkdownLinkPresentation } from "../lib/markdownLinks";
+import { resolveMarkdownFileIcon, resolveMarkdownLinkPresentation } from "../lib/markdownLinks";
import type {
MarkdownLinkCustomization,
SelectableMarkdownTextProps,
@@ -92,18 +92,26 @@ function presentation(
export function useEnrichedLinkVariants(
urls: ReadonlyArray<string>,
props: SelectableMarkdownTextProps,
+ fileHrefs: ReadonlySet<string>,
) {
- const { linkCustomization, skills, textStyle } = props;
+ const { linkCustomization, skills, textStyle, fileEmbedLabel } = props;
const theme = useUniwindTheme();
const links = useMemo(() => {
const byUrl = new Map<string, MarkdownLinkCustomization>();
for (const url of urls) {
if (byUrl.has(url)) continue;
- const value = presentation(url, { linkCustomization, skills, textStyle });
+ const label = fileHrefs.has(url) ? fileEmbedLabel?.(url, false) : null;
+ const value = label
+ ? {
+ label,
+ color: textStyle.fileTextColor,
+ icon: markdownFileIconSource(resolveMarkdownFileIcon(label)),
+ }
+ : presentation(url, { linkCustomization, skills, textStyle });
if (value) byUrl.set(url, value);
}
return byUrl;
- }, [urls, linkCustomization, skills, textStyle]);
+ }, [urls, linkCustomization, skills, textStyle, fileHrefs, fileEmbedLabel]);
const chipForegrounds = useMemo(
() =>
new Map(
diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts
index 6313768d045..3c4a8bf4000 100644
--- a/apps/mobile/vite.config.ts
+++ b/apps/mobile/vite.config.ts
@@ -2,6 +2,7 @@ import { defineConfig } from "vite-plus";
import "vite-plus/test/config";
const reactTests = [
+ "src/lib/filePreview.test.ts",
"src/features/diffs/nativeReviewDiffSurface.test.tsx",
"src/features/pull-requests/usePullRequestDiff.test.tsx",
"src/components/ui/Dialog.android.test.tsx",
diff --git a/patches/[email protected] b/patches/[email protected]
index 381737da226..8a644111bce 100644
--- a/patches/[email protected]
+++ b/patches/[email protected]
@@ -23,3 +23,107 @@ index 198fe6d..5b39611 100644
"url": recorder.url.absoluteString
])
}
+diff --git a/ios/AudioModule.swift b/ios/AudioModule.swift
+--- a/ios/AudioModule.swift
++++ b/ios/AudioModule.swift
+@@ -6,6 +6,7 @@
+
+ private let sessionQueue = DispatchQueue(label: "expo.modules.audio.session", qos: .userInitiated)
+ private var sessionIsActive = false
++ private var hasAudioSessionOwner = false
+ private var audioSessionActivityKeepers = Set<String>()
+ private let audioEnabled = OSAllocatedUnfairLock(initialState: true)
+
+@@ -41,6 +42,16 @@
+ try setIsAudioActive(isActive)
+ }
+
++ // Video shares AVAudioSession but is absent from this module's registry.
++ Function("setAudioSessionOwner") { (owned: Bool) in
++ self.sessionQueue.sync {
++ self.hasAudioSessionOwner = owned
++ if !owned {
++ self.deactivateSession()
++ }
++ }
++ }
++
+ AsyncFunction("requestRecordingPermissionsAsync") { (promise: Promise) in
+ #if os(iOS)
+ appContext?.permissions?.askForPermission(
+@@ -259,9 +259,9 @@
+ }
+ }
+
+- Function("pause") { player in
++ Function("pause") { (player: AudioPlayer, deactivateSession: Bool?) in
+ player.ref.pause()
+- if !player.keepAudioSessionActive {
++ if deactivateSession != false && !player.keepAudioSessionActive {
+ self.deactivateSession()
+ }
+ }
+@@ -957,6 +967,7 @@
+ sessionQueue.asyncAfter(deadline: .now() + .milliseconds(100)) { [weak self] in
+ guard let self,
+ self.sessionIsActive,
++ !self.hasAudioSessionOwner,
+ self.audioSessionActivityKeepers.isEmpty,
+ !self.isSessionInUse else {
+ return
+diff --git a/src/AudioModule.types.ts b/src/AudioModule.types.ts
+--- a/src/AudioModule.types.ts
++++ b/src/AudioModule.types.ts
+@@ -27,6 +27,8 @@
+ */
+ export declare class NativeAudioModule extends NativeModule {
+ setIsAudioActiveAsync(active: boolean): Promise<void>;
++ /** iOS only: protect the shared session from delayed expo-audio deactivation. */
++ setAudioSessionOwner?(owned: boolean): void;
+ setAudioModeAsync(category: Partial<AudioMode>): Promise<void>;
+ requestRecordingPermissionsAsync(): Promise<PermissionResponse>;
+ requestNotificationPermissionsAsync(): Promise<PermissionResponse>;
+@@ -175,8 +175,9 @@
+
+ /**
+ * Pauses the player.
++ * @param deactivateSession On iOS, pass false when handing the shared session to another player.
+ */
+- pause(): void;
++ pause(deactivateSession?: boolean): void;
+
+ /**
+ * Replaces the current audio source with a new one.
+diff --git a/build/AudioModule.types.d.ts b/build/AudioModule.types.d.ts
+--- a/build/AudioModule.types.d.ts
++++ b/build/AudioModule.types.d.ts
+@@ -6,6 +6,8 @@
+ */
+ export declare class NativeAudioModule extends NativeModule {
+ setIsAudioActiveAsync(active: boolean): Promise<void>;
++ /** iOS only: protect the shared session from delayed expo-audio deactivation. */
++ setAudioSessionOwner?(owned: boolean): void;
+ setAudioModeAsync(category: Partial<AudioMode>): Promise<void>;
+ requestRecordingPermissionsAsync(): Promise<PermissionResponse>;
+ requestNotificationPermissionsAsync(): Promise<PermissionResponse>;
+@@ -135,8 +135,9 @@
+ play(): void;
+ /**
+ * Pauses the player.
++ * @param deactivateSession On iOS, pass false when handing the shared session to another player.
+ */
+- pause(): void;
++ pause(deactivateSession?: boolean): void;
+ /**
+ * Replaces the current audio source with a new one.
+ */
+diff --git a/android/src/main/java/expo/modules/audio/AudioModule.kt b/android/src/main/java/expo/modules/audio/AudioModule.kt
+--- a/android/src/main/java/expo/modules/audio/AudioModule.kt
++++ b/android/src/main/java/expo/modules/audio/AudioModule.kt
+@@ -678,5 +678,5 @@
+ }
+
+- Function("pause") { player: AudioPlayer ->
++ Function("pause") { player: AudioPlayer, /* deactivateSession - iOS only */ _: Boolean? ->
+ runOnMain {
+ player.isPaused = false
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 00000000000..bb7936e4285
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,93 @@
+diff --git a/android/src/main/java/expo/modules/video/player/VideoPlayer.kt b/android/src/main/java/expo/modules/video/player/VideoPlayer.kt
+index 7ccce96..b6f30df 100644
+--- a/android/src/main/java/expo/modules/video/player/VideoPlayer.kt
++++ b/android/src/main/java/expo/modules/video/player/VideoPlayer.kt
+@@ -265,6 +265,10 @@ class VideoPlayer(val context: Context, appContext: AppContext, source: VideoSou
+ var keepScreenOnWhilePlaying by VideoPlayerKeepAwake(this, appContext)
+
+ private val playerListener = object : Player.Listener {
++ override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {
++ emit("playbackRequestedChange", mapOf("isPlaybackRequested" to playWhenReady))
++ }
++
+ override fun onIsPlayingChanged(isPlaying: Boolean) {
+ [email protected] = isPlaying
+ }
+diff --git a/ios/VideoPlayerObserver.swift b/ios/VideoPlayerObserver.swift
+index adf5820..ce69210 100644
+--- a/ios/VideoPlayerObserver.swift
++++ b/ios/VideoPlayerObserver.swift
+@@ -46,6 +46,7 @@ private actor ObserverTaskManager {
+ protocol VideoPlayerObserverDelegate: AnyObject {
+ func onStatusChanged(player: AVPlayer, oldStatus: PlayerStatus?, newStatus: PlayerStatus, error: Exception?)
+ func onIsPlayingChanged(player: AVPlayer, oldIsPlaying: Bool?, newIsPlaying: Bool)
++ func onPlaybackRequestedChanged(player: AVPlayer, requested: Bool)
+ func onRateChanged(player: AVPlayer, oldRate: Float?, newRate: Float)
+ func onVolumeChanged(player: AVPlayer, oldVolume: Float?, newVolume: Float)
+ func onPlayedToEnd(player: AVPlayer)
+@@ -66,6 +67,7 @@ protocol VideoPlayerObserverDelegate: AnyObject {
+ extension VideoPlayerObserverDelegate {
+ func onStatusChanged(player: AVPlayer, oldStatus: PlayerStatus?, newStatus: PlayerStatus, error: Exception?) {}
+ func onIsPlayingChanged(player: AVPlayer, oldIsPlaying: Bool?, newIsPlaying: Bool) {}
++ func onPlaybackRequestedChanged(player: AVPlayer, requested: Bool) {}
+ func onRateChanged(player: AVPlayer, oldRate: Float?, newRate: Float) {}
+ func onVolumeChanged(player: AVPlayer, oldVolume: Float?, newVolume: Float) {}
+ func onPlayedToEnd(player: AVPlayer) {}
+@@ -497,6 +499,12 @@ class VideoPlayerObserver: VideoSourceLoaderListener {
+ }
+
+ private func onTimeControlStatusChanged(_ player: AVPlayer, _ change: NSKeyValueObservedChange<AVPlayer.TimeControlStatus>) {
++ // Waiting (including evaluatingBufferingRate) preserves the native play request.
++ let requested = player.timeControlStatus != .paused && player.status != .failed && player.currentItem?.status != .failed
++ delegates.forEach { delegate in
++ delegate.value?.onPlaybackRequestedChanged(player: player, requested: requested)
++ }
++
+ // iOS changes timeControlStatus after an error, so we need to check for errors.
+ if player.status == .failed || player.currentItem?.status == .failed {
+ isPlaying = false
+diff --git a/ios/VideoPlayer.swift b/ios/VideoPlayer.swift
+index 3c2fde4..ef43248 100644
+--- a/ios/VideoPlayer.swift
++++ b/ios/VideoPlayer.swift
+@@ -396,6 +396,12 @@ internal final class VideoPlayer: SharedRef<AVPlayer>, Hashable, VideoPlayerObse
+ VideoManager.shared.setAppropriateAudioSessionOrWarn()
+ }
+
++ func onPlaybackRequestedChanged(player: AVPlayer, requested: Bool) {
++ if self.appContext != nil {
++ self.emit(event: "playbackRequestedChange", payload: ["isPlaybackRequested": requested])
++ }
++ }
++
+ func onRateChanged(player: AVPlayer, oldRate: Float?, newRate: Float) {
+ if #available(iOS 16.0, tvOS 16.0, *) {
+ if player.defaultRate != playbackRate {
+diff --git a/src/VideoPlayerEvents.types.ts b/src/VideoPlayerEvents.types.ts
+index c53b082..2d5fbcb 100644
+--- a/src/VideoPlayerEvents.types.ts
++++ b/src/VideoPlayerEvents.types.ts
+@@ -11,6 +11,9 @@ import type {
+ * Handlers for events which can be emitted by the player.
+ */
+ export type VideoPlayerEvents = {
++ /** Native play/pause intent, preserved while buffering or seeking. */
++ playbackRequestedChange(payload: { isPlaybackRequested: boolean }): void;
++
+ /**
+ * Handler for an event emitted when the status of the player changes.
+ */
+diff --git a/build/VideoPlayerEvents.types.d.ts b/build/VideoPlayerEvents.types.d.ts
+index 9c7eaea..25b8799 100644
+--- a/build/VideoPlayerEvents.types.d.ts
++++ b/build/VideoPlayerEvents.types.d.ts
+@@ -3,6 +3,9 @@ import type { PlayerError, SubtitleTrack, VideoPlayerStatus, VideoSource, VideoT
+ * Handlers for events which can be emitted by the player.
+ */
+ export type VideoPlayerEvents = {
++ /** Native play/pause intent, preserved while buffering or seeking. */
++ playbackRequestedChange(payload: { isPlaybackRequested: boolean }): void;
++
+ /**
+ * Handler for an event emitted when the status of the player changes.
+ */
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 072482613ce..6776ca3dc5f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -361,10 +361,11 @@ patchedDependencies:
[email protected]: bea1b6c0c0b23157fd5f439a1d7feff430f28ac1621ba135d8a13eeec60ccacd
[email protected]: a28c2dfcfc2b90d6c6247e199e6537391db9ecd941854c650910d607442512d3
[email protected]: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4
- [email protected]: 2c2f8c73a23d48804c8b537b8cd73c25eb331aa47d82eaa481c6766cb81e5add
+ [email protected]: 530af071088a809fe1a97ce2b2269c78335fbb5dcd3893d6937ff5c304c85a0a
[email protected]: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7
[email protected]: cd09b6d1744dde4efa081b5619ebcff38877d98f7502a51cab121629dece8237
[email protected]: 61a9741dc6166fdbb5baa2e489275a65dd21aa11d2c915f490a1b337a4468e76
+ [email protected]: e80ec3ef8c4af50a607beea1c0917e71ba679844efdb702b45d17a5f03cf466c
[email protected]: 8bf49067f93742855e15f29559ac75c8b50230b47069060993c9ea01dac11171
[email protected]: afe6b2c89e1eaddfd3c90cf2723f12c9a17d513e65beff51653781486013251c
[email protected]: 9ad23a530e45d9f83cba1da8654fe16d5af8b59d5c73d5c7a7c91fd25b9be1d8
@@ -625,7 +626,7 @@ importers:
expo-audio:
specifier: 58.0.9
expo-auth-session:
specifier: ~58.0.13
@@ -717,8 +718,8 @@ importers:
specifier: ~58.0.17
expo-video:
- specifier: ~58.0.11
+ specifier: 58.0.11
expo-web-browser:
specifier: ~58.0.6
@@ -18404,7 +18405,7 @@ snapshots:
- supports-color
- typescript
dependencies:
expo: 58.0.14(277a83826bb26ba15256633fefeb0bc2)
@@ -18723,7 +18724,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
expo: 58.0.14(277a83826bb26ba15256633fefeb0bc2)
react: 19.3.0
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 39b020f1988..2c990c203df 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -359,6 +359,7 @@ patchedDependencies: