TypeScript
feat(mobile): add video playback with native iOS controls (#8919)
Julius Marminge31c1c5996f88
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swiftindex 6aa8fa6bb15..4f907386072 100644--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift@@ -3,9 +3,43 @@ import Securityimport UIKitpublic final class T3NativeControlsModule: Module {+ private let presentationSources = T3PresentationSources()+ private var videoPresentation: T3NativeVideoPresentation?+public func definition() -> ModuleDefinition {Name("T3NativeControls")+ AsyncFunction("presentVideo") { (url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) in+ try self.presentVideo(+ url: url,+ title: title,+ sourceIdentifier: sourceIdentifier,+ identifier: identifier,+ promise: promise+ )+ }.runOnQueue(.main)++ AsyncFunction("dismissVideo") { (identifier: String) in+ self.dismissVideo(identifier: identifier)+ }.runOnQueue(.main)++ OnDestroy {+ let presentation = self.videoPresentation+ DispatchQueue.main.async { presentation?.dismiss() }+ }++ View(T3PresentationSourceView.self) {+ ViewName("PresentationSource")+ Prop("identifier") { (view: T3PresentationSourceView, identifier: String) in+ view.sources = self.presentationSources+ view.identifier = identifier+ }+ }++ AsyncFunction("shareFileFromSource") { (url: URL, title: String, identifier: String, promise: Promise) in+ try self.shareFile(url: url, title: title, sourceIdentifier: identifier, promise: promise)+ }.runOnQueue(.main)+Function("getShowcasePairingUrl") {let arguments = ProcessInfo.processInfo.argumentsguard@@ -101,4 +135,47 @@ public final class T3NativeControlsModule: Module {try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)}}++ private func presentVideo(url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) throws {+ let isPlayableURL = url.isFileURL+ ? FileManager.default.isReadableFile(atPath: url.path)+ : (["https", "http"].contains(url.scheme?.lowercased() ?? "") && url.host != nil)+ guard videoPresentation == nil,+ let presenter = appContext?.utilities?.currentViewController(),+ isPlayableURL+ else {+ throw NSError(+ domain: "T3NativeVideo",+ code: 2,+ 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) }+ }+ videoPresentation = presentation+ presentation.present(from: presenter, sources: presentationSources, sourceIdentifier: sourceIdentifier)+ }++ private func dismissVideo(identifier: String) {+ if videoPresentation?.identifier == identifier { videoPresentation?.dismiss() }+ }++ private func shareFile(url: URL, title: String, sourceIdentifier: String, promise: Promise) throws {+ guard let presenter = appContext?.utilities?.currentViewController() else {+ throw NSError(+ domain: "T3NativePresentation",+ code: 2,+ userInfo: [NSLocalizedDescriptionKey: "The presenting screen is no longer open."]+ )+ }+ try presentFileShare(+ url: url,+ title: title,+ source: presentationSources.view(for: sourceIdentifier),+ presenter: presenter,+ promise: promise+ )+ }}diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swiftnew file mode 100644index 00000000000..f537e8704dc--- /dev/null+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift@@ -0,0 +1,75 @@+import ExpoModulesCore+import UIKit++final class T3PresentationSources {+ private class Entry {+ weak var view: UIView?+ init(_ view: UIView) { self.view = view }+ }++ private var entries: [String: Entry] = [:]++ func register(_ view: UIView, identifier: String) {+ entries[identifier] = Entry(view)+ }++ func remove(_ view: UIView, identifier: String) {+ if entries[identifier]?.view == nil || entries[identifier]?.view === view {+ entries.removeValue(forKey: identifier)+ }+ }++ func view(for identifier: String) -> UIView? {+ // Use the child bounds, not the wrapper's potentially stretched layout bounds.+ entries[identifier]?.view?.subviews.first+ }+}++final class T3PresentationSourceView: ExpoView {+ weak var sources: T3PresentationSources?+ var identifier = "" {+ didSet {+ sources?.remove(self, identifier: oldValue)+ if !identifier.isEmpty { sources?.register(self, identifier: identifier) }+ }+ }++ deinit {+ sources?.remove(self, identifier: identifier)+ }+}++func presentFileShare(+ url: URL,+ title: String,+ source: UIView?,+ presenter: UIViewController,+ promise: Promise+) throws {+ guard url.isFileURL, FileManager.default.isReadableFile(atPath: url.path) else {+ throw NSError(+ domain: "T3NativePresentation",+ code: 1,+ userInfo: [NSLocalizedDescriptionKey: "The file is no longer available."]+ )+ }++ guard let origin = source ?? presenter.view else {+ throw NSError(+ domain: "T3NativePresentation",+ code: 2,+ userInfo: [NSLocalizedDescriptionKey: "The presenting screen is no longer open."]+ )+ }++ let activity = UIActivityViewController(activityItems: [url], applicationActivities: nil)+ activity.title = title+ activity.overrideUserInterfaceStyle = source?.traitCollection.userInterfaceStyle+ ?? presenter.traitCollection.userInterfaceStyle+ activity.completionWithItemsHandler = { _, _, _, _ in promise.resolve(nil) }+ activity.modalPresentationStyle = .popover+ activity.popoverPresentationController?.sourceView = origin+ activity.popoverPresentationController?.sourceRect = source?.bounds+ ?? CGRect(x: origin.bounds.midX, y: origin.bounds.maxY, width: 0, height: 0)+ presenter.present(activity, animated: true)+}diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swiftnew file mode 100644index 00000000000..74d2f1c7551--- /dev/null+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift@@ -0,0 +1,167 @@+import AVKit+import UIKit++final class T3NativeVideoPresentation: NSObject, AVPlayerViewControllerDelegate,+ UIAdaptivePresentationControllerDelegate {+ let identifier: String+ private let controller = AVPlayerViewController()+ private let completion: (Error?) -> Void+ private var itemObservation: NSKeyValueObservation?+ private var backgroundObserver: NSObjectProtocol?+ private var playbackError: Error?+ private var presented = false+ private var dismissRequested = false+ private var finished = false+ private struct AudioSessionConfiguration {+ let category: AVAudioSession.Category+ let mode: AVAudioSession.Mode+ let options: AVAudioSession.CategoryOptions++ init(_ session: AVAudioSession) {+ category = session.category+ mode = session.mode+ options = session.categoryOptions+ }+ }+ private var previousAudioSession: AudioSessionConfiguration?+ private weak var fullScreenController: UIViewController?+ private var embedded = false++ init(identifier: String, url: URL, title: String, completion: @escaping (Error?) -> Void) {+ self.identifier = identifier+ self.completion = completion+ super.init()++ let item = AVPlayerItem(url: url)+ let metadata = AVMutableMetadataItem()+ metadata.identifier = .commonIdentifierTitle+ metadata.value = title as NSString+ item.externalMetadata = [metadata]+ controller.player = AVPlayer(playerItem: item)+ controller.delegate = self+ controller.overrideUserInterfaceStyle = .dark+ controller.allowsPictureInPicturePlayback = false++ itemObservation = item.observe(\.status, options: [.initial, .new]) { [weak self] item, _ in+ guard item.status == .failed else { return }+ DispatchQueue.main.async {+ guard let self else { return }+ self.playbackError = item.error ?? NSError(+ domain: "T3NativeVideo",+ code: 1,+ userInfo: [NSLocalizedDescriptionKey: "This video couldn't be played on this device."]+ )+ self.dismiss()+ }+ }+ backgroundObserver = NotificationCenter.default.addObserver(+ forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main+ ) { [weak self] _ in self?.controller.player?.pause() }+ }++ func present(from presenter: UIViewController, sources: T3PresentationSources, sourceIdentifier: String) {+ let audioSession = AVAudioSession.sharedInstance()+ previousAudioSession = AudioSessionConfiguration(audioSession)+ do {+ try audioSession.setCategory(.playback, mode: .moviePlayback)+ } catch {+ NSLog("T3 video audio session: %@", error.localizedDescription)+ }+ // AVKit exposes programmatic inline-to-full-screen entry through this selector.+ // This is the same guarded entry point used by expo-video's enterFullscreen().+ let enterFullScreen = NSSelectorFromString("enterFullScreenAnimated:completionHandler:")+ if let source = sources.view(for: sourceIdentifier), source.window != nil,+ controller.responds(to: enterFullScreen) {+ // AVKit owns the transition from its inline view to full screen. Using a+ // separate UIKit zoom transition prevents its native Close action from exiting.+ var responder: UIResponder? = source+ while let current = responder, !(current is UIViewController) { responder = current.next }+ let parent = responder as? UIViewController ?? presenter+ embedded = true+ parent.addChild(controller)+ controller.view.frame = source.bounds+ controller.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]+ source.addSubview(controller.view)+ controller.didMove(toParent: parent)+ controller.view.layoutIfNeeded()+ controller.perform(enterFullScreen, with: true, with: nil)+ controller.player?.play()+ } else {+ presenter.present(controller, animated: true) { [self] in+ presented = true+ if dismissRequested {+ dismiss()+ } else if UIApplication.shared.applicationState == .active {+ controller.player?.play()+ }+ }+ controller.presentationController?.delegate = self+ }+ }++ func dismiss() {+ dismissRequested = true+ guard !finished else { return }+ guard presented else {+ if embedded && fullScreenController == nil { finish() }+ return+ }+ (fullScreenController ?? controller).dismiss(animated: true) { [self] in finish() }+ }++ func playerViewController(+ _ playerViewController: AVPlayerViewController,+ willBeginFullScreenPresentationWithAnimationCoordinator coordinator: UIViewControllerTransitionCoordinator+ ) {+ fullScreenController = coordinator.viewController(forKey: .to)+ coordinator.animate(alongsideTransition: nil) { [weak self] context in+ guard let self else { return }+ if context.isCancelled {+ finish()+ } else {+ presented = true+ if dismissRequested { dismiss() }+ }+ }+ }++ func playerViewController(+ _ playerViewController: AVPlayerViewController,+ willEndFullScreenPresentationWithAnimationCoordinator coordinator: UIViewControllerTransitionCoordinator+ ) {+ coordinator.animate(alongsideTransition: nil) { [weak self] context in+ if !context.isCancelled { self?.finish() }+ }+ }++ func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {+ finish()+ }++ private func finish() {+ guard !finished else { return }+ finished = true+ controller.player?.pause()+ if embedded {+ controller.willMove(toParent: nil)+ controller.view.removeFromSuperview()+ controller.removeFromParent()+ }+ itemObservation = nil+ controller.player = nil+ if let backgroundObserver { NotificationCenter.default.removeObserver(backgroundObserver) }+ backgroundObserver = nil+ let audioSession = AVAudioSession.sharedInstance()+ if let previousAudioSession, audioSession.category == .playback,+ audioSession.mode == .moviePlayback, audioSession.categoryOptions.isEmpty {+ // AVPlayer owns activation. Deactivating the shared session here could+ // stop another player or recorder that was active before this preview.+ try? audioSession.setCategory(+ previousAudioSession.category,+ mode: previousAudioSession.mode,+ options: previousAudioSession.options+ )+ }+ completion(playbackError)+ }+}diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex 3fcb1f76f3d..488ca3e16b2 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -85,6 +85,7 @@"expo-crypto": "~57.0.2","expo-dev-client": "~57.0.16","expo-device": "~57.0.1",+ "expo-document-picker": "~57.0.1","expo-file-system": "~57.0.6","expo-font": "~57.0.2","expo-glass-effect": "~57.0.1",@@ -102,6 +103,7 @@"expo-sqlite": "~57.0.2","expo-symbols": "~57.0.2","expo-updates": "~57.0.19",+ "expo-video": "~57.0.3","expo-web-browser": "~57.0.2","expo-widgets": "~57.0.15","punycode": "^2.3.1",diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsxindex 3b8017fb181..b18777c0226 100644--- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx+++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx@@ -1,8 +1,12 @@import { SymbolView } from "../components/AppSymbol";-import { Image, Pressable, ScrollView, View } from "react-native";+import { videoMimeType } from "@t3tools/shared/video";+import { useEffect, useRef, useState } from "react";+import { Alert, Image, Pressable, ScrollView, View } from "react-native";import { AppText as Text } from "./AppText";-import type { DraftComposerAttachment } from "../lib/composerImages";+import type { DraftComposerAttachment, DraftComposerFileAttachment } from "../lib/composerImages";+import { VideoAttachmentTile } from "./VideoAttachmentTile";+import { loadLocalVideoPreview } from "../lib/localVideoPreview";export interface ComposerAttachmentStripProps {/** Attachments to display. */@@ -11,6 +15,10 @@ export interface ComposerAttachmentStripProps {readonly onRemove: (imageId: string) => void;/** Called when the user taps on an image thumbnail to preview it. */readonly onPressImage?: (previewUri: string) => void;+ readonly onPressVideo?: (+ attachment: DraftComposerFileAttachment,+ sourceIdentifier: string,+ ) => void;/** Image thumbnail size in points. Defaults to 72. */readonly imageSize?: number;/** Border radius of each image thumbnail. Defaults to 16. */@@ -19,6 +27,130 @@ export interface ComposerAttachmentStripProps {readonly removeButtonPlacement?: "overlay" | "gutter";}+export function ComposerAttachmentThumbnail(props: {+ readonly attachment: DraftComposerAttachment;+ readonly size: number;+ readonly borderRadius: number;+ readonly compact?: boolean;+ readonly onPressImage?: (previewUri: string) => void;+ readonly onPressVideo?: (+ attachment: DraftComposerFileAttachment,+ sourceIdentifier: string,+ ) => void;+}) {+ const { attachment } = props;+ const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };+ if (attachment.type === "image") {+ return (+ <Pressable+ onPress={props.onPressImage ? () => props.onPressImage?.(attachment.previewUri) : undefined}+ >+ <Image+ source={{ uri: attachment.previewUri }}+ style={style}+ className="bg-subtle"+ resizeMode="cover"+ />+ </Pressable>+ );+ }+ const onPressVideo = props.onPressVideo;+ if (onPressVideo && videoMimeType(attachment) !== null) {+ return (+ <ComposerVideoAttachment {...props} attachment={attachment} onPressVideo={onPressVideo} />+ );+ }+ return (+ <View+ className={+ props.compact+ ? "items-center justify-center bg-subtle"+ : "items-center justify-center gap-1 bg-subtle px-2"+ }+ style={style}+ >+ <SymbolView+ name="doc.text"+ size={props.compact ? 15 : 22}+ tintColor="#a3a3a3"+ type="monochrome"+ />+ {!props.compact ? (+ <Text className="w-full text-center text-2xs text-foreground" numberOfLines={1}>+ {attachment.name}+ </Text>+ ) : null}+ </View>+ );+}++function ComposerVideoAttachment(props: {+ readonly attachment: DraftComposerFileAttachment;+ readonly size: number;+ readonly borderRadius: number;+ readonly compact?: boolean;+ readonly onPressVideo: (+ attachment: DraftComposerFileAttachment,+ sourceIdentifier: string,+ ) => void;+}) {+ const { attachment } = props;+ const sourceIdentifier = `draft:${attachment.id}`;+ const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };+ const shareRef = useRef<AbortController | null>(null);+ const [sharing, setSharing] = useState(false);+ useEffect(+ () => () => {+ shareRef.current?.abort();+ shareRef.current = null;+ },+ [],+ );++ const onShare = () => {+ if (shareRef.current) return;+ const controller = new AbortController();+ shareRef.current = controller;+ setSharing(true);+ void (async () => {+ const preview = await loadLocalVideoPreview(attachment, controller.signal);+ if (!preview) return;+ try {+ await preview.share(controller.signal, sourceIdentifier);+ } finally {+ preview.dispose();+ }+ })()+ .catch((error: unknown) => {+ if (!controller.signal.aborted) {+ Alert.alert(+ "Could not share video",+ error instanceof Error ? error.message : "Try again.",+ );+ }+ })+ .finally(() => {+ if (shareRef.current === controller) {+ shareRef.current = null;+ setSharing(false);+ }+ });+ };++ return (+ <VideoAttachmentTile+ name={attachment.name}+ sourceIdentifier={sourceIdentifier}+ thumbnailSource={attachment}+ compact={props.compact}+ onPress={() => props.onPressVideo(attachment, sourceIdentifier)}+ onShare={onShare}+ disabled={sharing}+ style={style}+ />+ );+}+/*** Attachment thumbnails used by the thread composer and the new-task draft screen.*/@@ -49,38 +181,13 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {paddingRight: removeButtonGutter,}}>- {attachment.type === "image" ? (- <Pressable- onPress={- props.onPressImage ? () => props.onPressImage!(attachment.previewUri) : undefined- }- >- <Image- source={{ uri: attachment.previewUri }}- style={{- width: size,- height: size,- borderRadius: radius,- }}- className="bg-subtle"- resizeMode="cover"- />- </Pressable>- ) : (- <View- className="items-center justify-center gap-1 bg-subtle px-2"- style={{- width: size,- height: size,- borderRadius: radius,- }}- >- <SymbolView name="doc.text" size={22} tintColor="#a3a3a3" type="monochrome" />- <Text className="w-full text-center text-2xs text-foreground" numberOfLines={1}>- {attachment.name}- </Text>- </View>- )}+ <ComposerAttachmentThumbnail+ attachment={attachment}+ size={size}+ borderRadius={radius}+ onPressImage={props.onPressImage}+ onPressVideo={props.onPressVideo}+ /><PressableclassName="absolute h-[22px] w-[22px] items-center justify-center rounded-[11px] bg-black/55"style={{diff --git a/apps/mobile/src/components/NativePresentation.ios.tsx b/apps/mobile/src/components/NativePresentation.ios.tsxnew file mode 100644index 00000000000..b93578dde60--- /dev/null+++ b/apps/mobile/src/components/NativePresentation.ios.tsx@@ -0,0 +1,12 @@+import { requireNativeView } from "expo";+import type { ComponentType } from "react";+import type { PresentationSourceProps } from "./NativePresentation";++const NativeSource: ComponentType<PresentationSourceProps> = requireNativeView(+ "T3NativeControls",+ "PresentationSource",+);++export function PresentationSource(props: PresentationSourceProps) {+ return <NativeSource {...props} collapsableChildren={false} />;+}diff --git a/apps/mobile/src/components/NativePresentation.tsx b/apps/mobile/src/components/NativePresentation.tsxnew file mode 100644index 00000000000..d48b8839540--- /dev/null+++ b/apps/mobile/src/components/NativePresentation.tsx@@ -0,0 +1,13 @@+import type { ReactElement } from "react";+import { View, type ViewProps } from "react-native";++export interface PresentationSourceProps extends ViewProps {+ readonly children: ReactElement;+ /** Stable across remounts so dismissal can find a recycled attachment thumbnail. */+ readonly identifier: string;+}++/** Registers the view as an iOS zoom or share-sheet origin. */+export function PresentationSource({ identifier: _identifier, ...props }: PresentationSourceProps) {+ return <View {...props} />;+}diff --git a/apps/mobile/src/components/VideoAttachmentMenu.tsx b/apps/mobile/src/components/VideoAttachmentMenu.tsxnew file mode 100644index 00000000000..301d6503a50--- /dev/null+++ b/apps/mobile/src/components/VideoAttachmentMenu.tsx@@ -0,0 +1,53 @@+import type { ReactElement } from "react";+import { Platform, type PressableProps } from "react-native";++import { ControlPillMenu } from "./ControlPill";+import { PresentationSource } from "./NativePresentation";++export function VideoAttachmentMenu(props: {+ readonly sourceIdentifier: string;+ readonly onOpen: () => void;+ readonly onShare?: () => void;+ readonly disabled?: boolean;+ readonly children: ReactElement<PressableProps>;+}) {+ return (+ <PresentationSource+ identifier={props.sourceIdentifier}+ accessible={Platform.OS === "ios"}+ accessibilityRole="button"+ accessibilityLabel={props.children.props.accessibilityLabel}+ accessibilityHint={props.children.props.accessibilityHint}+ accessibilityState={{ disabled: props.disabled ?? false }}+ onAccessibilityTap={() => {+ if (!props.disabled) props.onOpen();+ }}+ accessibilityActions={props.onShare ? [{ name: "share", label: "Save or share video" }] : []}+ onAccessibilityAction={({ nativeEvent }) => {+ if (nativeEvent.actionName === "share" && !props.disabled) props.onShare?.();+ }}+ >+ {Platform.OS === "ios" && props.onShare ? (+ <ControlPillMenu+ shouldOpenOnLongPress+ style={{ alignSelf: "flex-start" }}+ actions={[+ {+ id: "share",+ title: "Save or share video",+ image: "square.and.arrow.up",+ attributes: { disabled: props.disabled ?? false },+ },+ ]}+ onPressAction={({ nativeEvent }) => {+ if (nativeEvent.event === "share") props.onShare?.();+ }}+ >+ {props.children}+ </ControlPillMenu>+ ) : (+ props.children+ )}+ </PresentationSource>+ );+}diff --git a/apps/mobile/src/components/VideoAttachmentTile.tsx b/apps/mobile/src/components/VideoAttachmentTile.tsxnew file mode 100644index 00000000000..6f582ac5f00--- /dev/null+++ b/apps/mobile/src/components/VideoAttachmentTile.tsx@@ -0,0 +1,66 @@+import { Platform, Pressable, View, type StyleProp, type ViewStyle } from "react-native";++import { cn } from "../lib/cn";+import type { DraftComposerFileAttachment } from "../lib/composerImages";+import { SymbolView } from "./AppSymbol";+import { AppText } from "./AppText";+import { VideoAttachmentMenu } from "./VideoAttachmentMenu";+import { VideoThumbnailImage } from "./VideoThumbnailImage";++export function VideoAttachmentTile(props: {+ readonly name: string;+ readonly sourceIdentifier: string;+ readonly thumbnailSource: string | DraftComposerFileAttachment | null;+ readonly compact?: boolean;+ readonly onPress: (sourceIdentifier: string) => void;+ readonly onShare?: () => void;+ readonly disabled?: boolean;+ readonly className?: string;+ readonly style?: StyleProp<ViewStyle>;+}) {+ return (+ <VideoAttachmentMenu+ sourceIdentifier={props.sourceIdentifier}+ onOpen={() => props.onPress(props.sourceIdentifier)}+ onShare={props.onShare}+ disabled={props.disabled}+ >+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={`Play ${props.name}`}+ accessibilityHint={+ Platform.OS === "ios" && props.onShare+ ? "Touch and hold for save and share options"+ : undefined+ }+ accessibilityState={{ disabled: props.disabled ?? false }}+ disabled={props.disabled}+ onPress={() => props.onPress(props.sourceIdentifier)}+ className={cn("items-center justify-center overflow-hidden bg-black/80", props.className)}+ style={props.style}+ >+ <VideoThumbnailImage cacheKey={props.sourceIdentifier} source={props.thumbnailSource} />+ <View+ className={cn(+ "items-center justify-center rounded-full bg-black/45",+ props.compact ? "size-6" : "size-12",+ )}+ >+ <SymbolView+ name="play"+ size={props.compact ? 15 : 24}+ tintColor="#ffffff"+ type="monochrome"+ />+ </View>+ {!props.compact ? (+ <View className="absolute inset-x-0 bottom-0 bg-black/55 px-2 py-1.5">+ <AppText className="text-center text-xs text-white" numberOfLines={1}>+ {props.name}+ </AppText>+ </View>+ ) : null}+ </Pressable>+ </VideoAttachmentMenu>+ );+}diff --git a/apps/mobile/src/components/VideoPreviewModal.ios.tsx b/apps/mobile/src/components/VideoPreviewModal.ios.tsxnew file mode 100644index 00000000000..4b2cfe27e6f--- /dev/null+++ b/apps/mobile/src/components/VideoPreviewModal.ios.tsx@@ -0,0 +1,121 @@+import { useIsFocused } from "@react-navigation/native";+import { videoMimeType } from "@t3tools/shared/video";+import { requireNativeModule } from "expo";+import { useEffect, useEffectEvent, useId, useState } from "react";+import { Alert, Keyboard } from "react-native";++import { loadLocalVideoPreview } from "../lib/localVideoPreview";+import { useAssetUrlState } from "../state/assets";+import { usePreparedConnection } from "../state/session";+import type { VideoPreviewSource } from "./VideoPreviewModal";++export type { VideoPreviewSource } from "./VideoPreviewModal";++const NativeControls = requireNativeModule<{+ presentVideo(+ uri: string,+ title: string,+ sourceIdentifier: string,+ identifier: string,+ ): Promise<void>;+ dismissVideo(identifier: string): Promise<void>;+}>("T3NativeControls");++function NativeVideoPreview(props: {+ readonly source: VideoPreviewSource;+ readonly onRequestClose: () => void;+}) {+ const { source } = props;+ const { attachment } = source;+ const identifier = useId();+ const onRequestClose = useEffectEvent(props.onRequestClose);+ const environmentId = source.type === "remote" ? source.environmentId : null;+ const preparedConnection = usePreparedConnection(environmentId);+ const mimeType = videoMimeType(attachment) ?? attachment.mimeType;+ const assetUrl = useAssetUrlState(+ environmentId,+ source.type === "remote"+ ? { _tag: "attachment", attachmentId: attachment.id, fileName: attachment.name, mimeType }+ : null,+ );+ const [playbackUrl, setPlaybackUrl] = useState<string | null>(() =>+ assetUrl._tag === "Success" ? assetUrl.url : null,+ );+ const loadError =+ source.type === "remote" && playbackUrl === null+ ? preparedConnection._tag === "None"+ ? "Reconnect to this environment and open the video again."+ : assetUrl._tag === "Failure"+ ? "Could not load this video. Check the connection and try again."+ : null+ : null;++ useEffect(() => Keyboard.dismiss(), []);+ useEffect(() => {+ if (playbackUrl === null && assetUrl._tag === "Success") setPlaybackUrl(assetUrl.url);+ }, [playbackUrl, assetUrl]);+ useEffect(() => {+ if (!loadError) return;+ Alert.alert("Could not open video", loadError);+ onRequestClose();+ }, [loadError]);++ useEffect(() => {+ if (source.type === "remote" && playbackUrl === null) return;+ const controller = new AbortController();+ let ready = false;+ void (async () => {+ const file =+ source.type === "local"+ ? await loadLocalVideoPreview(source.attachment, controller.signal)+ : null;+ if (source.type === "local" && !file) return;+ try {+ if (controller.signal.aborted) return;+ ready = true;+ await NativeControls.presentVideo(+ file?.uri ?? playbackUrl!,+ attachment.name,+ source.sourceIdentifier ?? "",+ identifier,+ );+ if (!controller.signal.aborted) onRequestClose();+ } finally {+ // Native completion follows dismissal, so local playback keeps its file lease.+ file?.dispose();+ }+ })().catch((error: unknown) => {+ if (controller.signal.aborted) return;+ Alert.alert(+ "Could not open video",+ ready+ ? "This video couldn't be loaded or played. Check the connection, or touch and hold the attachment to save or share the original."+ : error instanceof Error+ ? error.message+ : "Could not load this video.",+ );+ onRequestClose();+ });+ return () => {+ controller.abort();+ void NativeControls.dismissVideo(identifier).catch(() => undefined);+ };+ }, [source, attachment.name, playbackUrl, identifier]);++ return null;+}++export function VideoPreviewModal(props: {+ readonly source: VideoPreviewSource | null;+ readonly onRequestClose: () => void;+}) {+ const isFocused = useIsFocused();+ const hasSource = props.source !== null;+ const onRequestClose = useEffectEvent(props.onRequestClose);+ useEffect(() => {+ if (!isFocused && hasSource) onRequestClose();+ }, [isFocused, hasSource]);++ if (!props.source || !isFocused) return null;+ return <NativeVideoPreview source={props.source} onRequestClose={props.onRequestClose} />;+}diff --git a/apps/mobile/src/components/VideoPreviewModal.tsx b/apps/mobile/src/components/VideoPreviewModal.tsxnew file mode 100644index 00000000000..190f5c7b01b--- /dev/null+++ b/apps/mobile/src/components/VideoPreviewModal.tsx@@ -0,0 +1,258 @@+import { useIsFocused } from "@react-navigation/native";+import type { ChatFileAttachment, EnvironmentId } from "@t3tools/contracts";+import { videoMimeType } from "@t3tools/shared/video";+import { useEvent } from "expo";+import { useVideoPlayer, VideoView } from "expo-video";+import { useEffect, useRef, useState } from "react";+import {+ ActivityIndicator,+ AppState,+ Keyboard,+ Modal,+ Pressable,+ StyleSheet,+ View,+} from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";++import {+ downloadAttachmentForPreview,+ type AttachmentPreviewFile,+} from "../lib/attachmentDownload";+import type { DraftComposerFileAttachment } from "../lib/composerImages";+import { loadLocalVideoPreview } from "../lib/localVideoPreview";+import { useAssetUrlState } from "../state/assets";+import { usePreparedConnection } from "../state/session";+import { SymbolView } from "./AppSymbol";+import { AppText } from "./AppText";++export type VideoPreviewSource = (+ | { readonly type: "local"; readonly attachment: DraftComposerFileAttachment }+ | {+ readonly type: "remote";+ readonly environmentId: EnvironmentId;+ readonly attachment: ChatFileAttachment;+ }+) & { readonly sourceIdentifier?: string };++function VideoPlayback(props: { readonly file: AttachmentPreviewFile }) {+ const player = useVideoPlayer(props.file.uri, (player) => {+ player.staysActiveInBackground = false;+ if (AppState.currentState === "active") player.play();+ });+ const { status } = useEvent(player, "statusChange", { status: player.status });+ const shareControllerRef = useRef<AbortController | null>(null);+ const [sharing, setSharing] = useState(false);+ const [shareError, setShareError] = useState<string | null>(null);++ useEffect(+ () => () => {+ shareControllerRef.current?.abort();+ shareControllerRef.current = null;+ },+ [],+ );++ const onShare = () => {+ if (shareControllerRef.current) return;+ player.pause();+ const controller = new AbortController();+ shareControllerRef.current = controller;+ setSharing(true);+ setShareError(null);+ void props.file+ .share(controller.signal)+ .catch((error: unknown) => {+ if (!controller.signal.aborted) {+ setShareError(error instanceof Error ? error.message : "Could not share this video.");+ }+ })+ .finally(() => {+ if (shareControllerRef.current === controller) {+ shareControllerRef.current = null;+ setSharing(false);+ }+ });+ };++ return (+ <>+ <View className="flex-1 items-center justify-center">+ {status === "error" ? (+ <AppText className="px-6 text-center text-base text-white/80">+ This video couldn't be played on this device. You can save or share the original file.+ </AppText>+ ) : (+ <>+ <VideoView+ player={player}+ style={StyleSheet.absoluteFill}+ nativeControls+ contentFit="contain"+ fullscreenOptions={{ enable: true }}+ allowsPictureInPicture={false}+ />+ {status === "loading" ? (+ <ActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />+ ) : null}+ </>+ )}+ </View>+ <Pressable+ accessibilityRole="button"+ accessibilityLabel="Save or share video"+ accessibilityState={{ disabled: sharing, busy: sharing }}+ disabled={sharing}+ onPress={onShare}+ className="mx-4 my-3 min-h-12 items-center justify-center rounded-xl bg-white/15 px-4"+ >+ <AppText className="font-t3-medium text-base text-white">+ {sharing ? "Opening share sheet..." : "Save or share video"}+ </AppText>+ </Pressable>+ {shareError ? (+ <AppText accessibilityRole="alert" className="px-4 pb-3 text-sm text-white/80">+ {shareError}+ </AppText>+ ) : null}+ </>+ );+}++function OpenVideoPreviewModal(props: {+ readonly source: VideoPreviewSource;+ readonly onRequestClose: () => void;+}) {+ const { source } = props;+ const { attachment } = source;+ const insets = useSafeAreaInsets();+ const environmentId = source.type === "remote" ? source.environmentId : null;+ const preparedConnection = usePreparedConnection(environmentId);+ const fileUri = source.type === "local" ? source.attachment.fileUri : null;+ const mimeType = videoMimeType(attachment) ?? attachment.mimeType;+ const assetUrl = useAssetUrlState(+ environmentId,+ source.type === "remote"+ ? { _tag: "attachment", attachmentId: attachment.id, fileName: attachment.name, mimeType }+ : null,+ );+ const [downloadUrl, setDownloadUrl] = useState<string | null>(null);+ const [file, setFile] = useState<AttachmentPreviewFile | null>(null);+ const [failure, setFailure] = useState<string | null>(null);++ useEffect(() => Keyboard.dismiss(), []);+ useEffect(() => {+ if (environmentId !== null && downloadUrl === null && assetUrl._tag === "Success") {+ setDownloadUrl(assetUrl.url);+ }+ }, [environmentId, downloadUrl, assetUrl]);++ useEffect(() => {+ if (source.type === "remote" && downloadUrl === null) return;+ const controller = new AbortController();+ let preview: AttachmentPreviewFile | null = null;+ setFile(null);+ setFailure(null);+ const loading =+ source.type === "local"+ ? loadLocalVideoPreview(source.attachment, controller.signal)+ : downloadAttachmentForPreview({+ url: downloadUrl!,+ attachment: { name: attachment.name, mimeType },+ signal: controller.signal,+ });+ void loading.then(+ (loaded) => {+ if (controller.signal.aborted) {+ loaded?.dispose();+ return;+ }+ preview = loaded;+ setFile(loaded);+ },+ (error: unknown) => {+ if (!controller.signal.aborted) {+ setFailure(error instanceof Error ? error.message : "Could not load this video.");+ }+ },+ );+ return () => {+ controller.abort();+ preview?.dispose();+ };+ }, [source.type, environmentId, attachment.id, attachment.name, mimeType, fileUri, downloadUrl]);++ const loadError =+ failure ??+ (environmentId !== null && downloadUrl === null+ ? preparedConnection._tag === "None"+ ? "This environment is disconnected. Reconnect and open the video again."+ : assetUrl._tag === "Failure"+ ? "Could not load this video. Check the connection to this environment and try again."+ : null+ : null);++ return (+ <Modal+ visible+ animationType="fade"+ presentationStyle="fullScreen"+ onRequestClose={props.onRequestClose}+ statusBarTranslucent+ navigationBarTranslucent+ >+ <View+ className="flex-1 bg-black"+ style={{ paddingTop: insets.top, paddingBottom: insets.bottom }}+ >+ <View className="min-h-14 flex-row items-center gap-3 pl-4 pr-2">+ <AppText className="flex-1 font-t3-medium text-base text-white" numberOfLines={2}>+ {attachment.name}+ </AppText>+ <Pressable+ accessibilityRole="button"+ accessibilityLabel="Close video"+ onPress={props.onRequestClose}+ className="size-12 items-center justify-center"+ >+ <SymbolView name="xmark" size={20} tintColor="#ffffff" type="monochrome" />+ </Pressable>+ </View>+ {file ? (+ <VideoPlayback key={file.uri} file={file} />+ ) : (+ <View className="flex-1 items-center justify-center gap-3 px-6">+ {loadError ? (+ <AppText accessibilityRole="alert" className="text-center text-base text-white/80">+ {loadError}+ </AppText>+ ) : (+ <>+ <ActivityIndicator color="#ffffff" />+ <AppText className="text-sm text-white/80">Loading video...</AppText>+ </>+ )}+ </View>+ )}+ </View>+ </Modal>+ );+}++export function VideoPreviewModal(props: {+ readonly source: VideoPreviewSource | null;+ readonly onRequestClose: () => void;+}) {+ const isFocused = useIsFocused();+ const hasSource = props.source !== null;+ useEffect(() => {+ if (!isFocused && hasSource) props.onRequestClose();+ }, [isFocused, hasSource, props.onRequestClose]);+ const { source } = props;+ if (source === null || !isFocused) return null;+ const key =+ source.type === "local"+ ? `local:${source.attachment.id}:${source.attachment.fileUri}`+ : `remote:${source.environmentId}:${source.attachment.id}`;+ return <OpenVideoPreviewModal key={key} source={source} onRequestClose={props.onRequestClose} />;+}diff --git a/apps/mobile/src/components/VideoThumbnailImage.tsx b/apps/mobile/src/components/VideoThumbnailImage.tsxnew file mode 100644index 00000000000..5af33499e4d--- /dev/null+++ b/apps/mobile/src/components/VideoThumbnailImage.tsx@@ -0,0 +1,45 @@+import { Image } from "expo-image";+import { useIsFocused } from "@react-navigation/native";+import type { VideoThumbnail } from "expo-video";+import { useEffect, useState } from "react";+import { StyleSheet } from "react-native";++import type { DraftComposerFileAttachment } from "../lib/composerImages";+import { loadLocalVideoPreview } from "../lib/localVideoPreview";+import { cachedVideoThumbnail, loadVideoThumbnail } from "../lib/videoThumbnails";++export function VideoThumbnailImage(props: {+ readonly cacheKey: string;+ readonly source: string | DraftComposerFileAttachment | null;+}) {+ const { cacheKey, source } = props;+ const isFocused = useIsFocused();+ const [loaded, setLoaded] = useState<{ key: string; thumbnail: VideoThumbnail } | null>(null);+ const thumbnail = loaded?.key === cacheKey ? loaded.thumbnail : cachedVideoThumbnail(cacheKey);++ useEffect(() => {+ if (!source || !isFocused) return;+ const controller = new AbortController();+ void loadVideoThumbnail(+ cacheKey,+ async (signal) =>+ typeof source === "string"+ ? { uri: source, dispose: () => undefined }+ : loadLocalVideoPreview(source, signal),+ controller.signal,+ ).then((thumbnail) => {+ if (thumbnail && !controller.signal.aborted) setLoaded({ key: cacheKey, thumbnail });+ });+ return () => controller.abort();+ }, [cacheKey, source, isFocused]);++ return thumbnail ? (+ <Image+ source={thumbnail}+ style={StyleSheet.absoluteFill}+ contentFit="cover"+ recyclingKey={cacheKey}+ accessible={false}+ />+ ) : null;+}diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsxindex 96ce039b5e0..96445146e15 100644--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx@@ -35,6 +35,7 @@ import {import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";+import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";import { ProviderIcon } from "../../components/ProviderIcon";import { SymbolView } from "../../components/AppSymbol";import { AppText as Text } from "../../components/AppText";@@ -60,6 +61,7 @@ import {convertPastedImagesToAttachments,pickComposerFiles,pickComposerMedia,+ type DraftComposerFileAttachment,} from "../../lib/composerImages";import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";import {@@ -164,6 +166,23 @@ export function NewTaskDraftScreen(props: {const promptInputRef = useRef<ComposerEditorHandle>(null);const loadedBranchesProjectKeyRef = useRef<string | null>(null);const [isComposerFocused, setIsComposerFocused] = useState(false);+ const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);+ const wasFocusedBeforeVideoRef = useRef(false);+ const openVideoPreview = useCallback(+ (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {+ wasFocusedBeforeVideoRef.current = isComposerFocused;+ setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });+ },+ [isComposerFocused],+ );+ const closeVideoPreview = useCallback(() => {+ setPreviewVideo(null);+ if (wasFocusedBeforeVideoRef.current) {+ setTimeout(() => {+ if (navigation.isFocused()) promptInputRef.current?.focus();+ }, 100);+ }+ }, [navigation]);const settingsSheetPresentation = useThreadSettingsSheetPresentation({editorRef: promptInputRef,isEditorFocused: isComposerFocused,@@ -1193,6 +1212,9 @@ export function NewTaskDraftScreen(props: {? () => undefined: flow.removeAttachment}+ onPressVideo={+ isComposerInteractionLocked || voiceInput.isBusy ? undefined : openVideoPreview+ }/></View>) : null}@@ -1296,6 +1318,7 @@ export function NewTaskDraftScreen(props: {</ComposerDictationToolbar></Animated.View></ComposerSurface>+ <VideoPreviewModal source={previewVideo} onRequestClose={closeVideoPreview} /></View>);diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsxindex b792ecd51e2..e1549cef96c 100644--- a/apps/mobile/src/features/threads/ThreadComposer.tsx+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx@@ -19,7 +19,7 @@ import {useState,type RefObject,} from "react";-import { ActivityIndicator, Image, Platform, Pressable, View, type ViewStyle } from "react-native";+import { ActivityIndicator, Platform, Pressable, View, type ViewStyle } from "react-native";import ImageViewing from "react-native-image-viewing";import Animated, {FadeIn,@@ -37,9 +37,12 @@ import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/reimport { scopedThreadKey } from "../../lib/scopedEntities";import { AppText as Text } from "../../components/AppText";-import { SymbolView } from "../../components/AppSymbol";import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";-import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";+import {+ ComposerAttachmentStrip,+ ComposerAttachmentThumbnail,+} from "../../components/ComposerAttachmentStrip";+import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";import { GlassSurface } from "../../components/GlassSurface";import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";import {@@ -48,7 +51,10 @@ import {ComposerToolbarRow,} from "../../components/ComposerToolbar";import { ProviderIcon } from "../../components/ProviderIcon";-import type { DraftComposerAttachment } from "../../lib/composerImages";+import type {+ DraftComposerAttachment,+ DraftComposerFileAttachment,+} from "../../lib/composerImages";import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";import type { RemoteClientConnectionState } from "../../lib/connection";@@ -306,6 +312,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerconst { onExpandedChange } = props;const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);+ const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;const showStopAction =!hasContent &&@@ -368,6 +375,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerconst onPressImage = useCallback((uri: string) => {wasExpandedBeforePreviewRef.current = isFocused;+ setPreviewVideo(null);setPreviewImageUri(uri);},[isFocused],@@ -375,10 +383,22 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerconst closePreview = useCallback(() => {setPreviewImageUri(null);+ setPreviewVideo(null);if (wasExpandedBeforePreviewRef.current) {- setTimeout(() => inputRef.current?.focus(), 100);+ setTimeout(() => {+ if (navigation.isFocused()) inputRef.current?.focus();+ }, 100);}- }, [inputRef]);+ }, [inputRef, navigation]);++ const onPressVideo = useCallback(+ (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {+ wasExpandedBeforePreviewRef.current = isFocused;+ setPreviewImageUri(null);+ setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });+ },+ [isFocused],+ );const onEditorFocusChange = props.onEditorFocusChange;const handleFocus = useCallback(() => {@@ -600,6 +620,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerattachments={props.draftAttachments}onRemove={voiceInput.isBusy ? () => undefined : props.onRemoveDraftImage}onPressImage={voiceInput.isBusy ? undefined : onPressImage}+ onPressVideo={voiceInput.isBusy ? undefined : onPressVideo}/></Animated.View>) : null}@@ -645,27 +666,17 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer</Animated.View>{!isExpanded && props.draftAttachments.length > 0 ? (<View className="flex-row gap-1 pl-1">- {props.draftAttachments.slice(0, 3).map((attachment) =>- attachment.type === "image" ? (- <Pressable- key={attachment.id}- onPress={() => onPressImage(attachment.previewUri)}- >- <Image- source={{ uri: attachment.previewUri }}- className="size-[30px] rounded-lg bg-subtle"- resizeMode="cover"- />- </Pressable>- ) : (- <View- key={attachment.id}- className="size-[30px] items-center justify-center rounded-lg bg-subtle"- >- <SymbolView name="doc.text" size={15} tintColor="#a3a3a3" type="monochrome" />- </View>- ),- )}+ {props.draftAttachments.slice(0, 3).map((attachment) => (+ <ComposerAttachmentThumbnail+ key={attachment.id}+ attachment={attachment}+ size={30}+ borderRadius={8}+ compact+ onPressImage={onPressImage}+ onPressVideo={onPressVideo}+ />+ ))}{props.draftAttachments.length > 3 ? (<View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong"><Text className="text-foreground-muted text-2xs font-t3-bold">@@ -807,6 +818,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer) : null}</Animated.View>+ <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} /><ImageViewingimages={previewImageUri ? [{ uri: previewImageUri }] : []}imageIndex={0}diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex 1da3f35cb59..24af8238903 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -23,6 +23,7 @@ import {splitCodexArtifactTemplateMarkdown,} from "@t3tools/client-runtime/codex-markdown-directives";import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";+import { videoMimeType } from "@t3tools/shared/video";import { SymbolView, type AppSymbolName } from "../../components/AppSymbol";import { HeaderHeightContext } from "@react-navigation/elements";import { useFocusEffect, useNavigation } from "@react-navigation/native";@@ -88,6 +89,8 @@ import {} from "../../native/SelectableMarkdownText";import { AppText as Text } from "../../components/AppText";+import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";+import { VideoAttachmentTile } from "../../components/VideoAttachmentTile";import { CopyTextButton } from "../../components/CopyTextButton";import {parseReviewCommentMessageSegments,@@ -246,12 +249,25 @@ function isFileAttachment(attachment: ChatAttachment): attachment is ChatFileAttfunction MessageAttachmentFile(props: {readonly environmentId: EnvironmentId;readonly attachment: ChatFileAttachment;+ readonly onPressVideo: (attachment: ChatFileAttachment, sourceIdentifier: string) => void;}) {const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {reportFailure: false,});const preparedConnection = usePreparedConnection(props.environmentId);const { attachment } = props;+ const videoType = videoMimeType(attachment);+ 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;@@ -268,6 +284,69 @@ function MessageAttachmentFile(props: {}, [props.environmentId, attachment.id, httpBaseUrl]),);+ const shareFile = (sourceIdentifier?: string) => {+ if (httpBaseUrl === null || openingRef.current) return;+ const controller = new AbortController();+ openingRef.current = controller;+ setOpening(true);+ void (async () => {+ try {+ const result = await createAssetUrl({+ environmentId: props.environmentId,+ input: {+ resource: {+ _tag: "attachment",+ attachmentId: attachment.id,+ fileName: attachment.name,+ mimeType: attachment.mimeType,+ },+ },+ });+ if (controller.signal.aborted) return;+ if (result._tag === "Failure") {+ throw squashAtomCommandFailure(result);+ }+ const url = resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);+ if (url === null) {+ throw new Error("The attachment could not be opened.");+ }+ await downloadAndShareAttachment({+ url,+ attachment,+ signal: controller.signal,+ sourceIdentifier,+ });+ } catch (error) {+ if (!controller.signal.aborted) {+ Alert.alert(+ "Could not open attachment",+ error instanceof Error ? error.message : "The attachment is unavailable.",+ );+ }+ } finally {+ if (openingRef.current === controller) {+ openingRef.current = null;+ setOpening(false);+ }+ }+ })();+ };++ if (videoType !== null) {+ return (+ <VideoAttachmentTile+ name={attachment.name}+ sourceIdentifier={`attachment:${props.environmentId}:${attachment.id}`}+ thumbnailSource={thumbnailUrl}+ disabled={opening || httpBaseUrl === null}+ onPress={(sourceIdentifier) => props.onPressVideo(attachment, sourceIdentifier)}+ onShare={() => shareFile(`attachment:${props.environmentId}:${attachment.id}`)}+ className="my-1 rounded-2xl"+ style={{ width: 224, maxWidth: "100%", aspectRatio: 16 / 9 }}+ />+ );+ }+return (<PressableaccessibilityRole="button"@@ -275,48 +354,7 @@ function MessageAttachmentFile(props: {accessibilityState={{ disabled: opening || httpBaseUrl === null, busy: opening }}disabled={opening || httpBaseUrl === null}className="flex-row items-center gap-2 py-1"- onPress={() => {- if (httpBaseUrl === null || openingRef.current) return;- const controller = new AbortController();- openingRef.current = controller;- setOpening(true);- void (async () => {- try {- const result = await createAssetUrl({- environmentId: props.environmentId,- input: {- resource: {- _tag: "attachment",- attachmentId: attachment.id,- fileName: attachment.name,- mimeType: attachment.mimeType,- },- },- });- if (controller.signal.aborted) return;- if (result._tag === "Failure") {- throw squashAtomCommandFailure(result);- }- const url = resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);- if (url === null) {- throw new Error("The attachment could not be opened.");- }- await downloadAndShareAttachment({ url, attachment, signal: controller.signal });- } catch (error) {- if (!controller.signal.aborted) {- Alert.alert(- "Could not open attachment",- error instanceof Error ? error.message : "The attachment is unavailable.",- );- }- } finally {- if (openingRef.current === controller) {- openingRef.current = null;- setOpening(false);- }- }- })();- }}+ onPress={() => shareFile()}>{opening ? (<ActivityIndicator size="small" />@@ -1227,6 +1265,7 @@ function renderFeedEntry(readonly onToggleWorkRow: (rowId: string) => void;readonly onToggleTurnFold: (turnId: TurnId) => void;readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;+ readonly onPressVideo: (attachment: ChatFileAttachment, sourceIdentifier: string) => void;readonly onMarkdownLinkPress: (href: string) => void;readonly renderMarkdownImage: MarkdownImageRenderer;readonly iconSubtleColor: string | import("react-native").ColorValue;@@ -1344,6 +1383,7 @@ function renderFeedEntry(key={attachment.id}environmentId={props.environmentId}attachment={attachment}+ onPressVideo={props.onPressVideo}/>) : (<MessageAttachmentUnknown key={attachment.id} name={attachment.name} />@@ -1404,6 +1444,7 @@ function renderFeedEntry(key={attachment.id}environmentId={props.environmentId}attachment={attachment}+ onPressVideo={props.onPressVideo}/>) : (<MessageAttachmentUnknown key={attachment.id} name={attachment.name} />@@ -1769,6 +1810,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {uri: string;headers?: Record<string, string>;} | null>(null);+ const [expandedVideo, setExpandedVideo] = useState<VideoPreviewSource | null>(null);+ useEffect(() => {+ setExpandedVideo(null);+ }, [props.environmentId, props.threadId, props.contentPresentation.kind]);const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;const contentHorizontalPadding = deriveCenteredContentHorizontalPadding({viewportWidth,@@ -2243,6 +2288,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {setExpandedImage({ uri, headers });}, []);+ const onPressVideo = useCallback(+ (attachment: ChatFileAttachment, sourceIdentifier: string) => {+ setExpandedVideo(+ (current) =>+ current ?? {+ type: "remote",+ environmentId: props.environmentId,+ attachment,+ sourceIdentifier,+ },+ );+ },+ [props.environmentId],+ );// Rows whose height is known before they ever render. Without this, every// row above the viewport is assumed to be estimatedItemSize tall, and@@ -2292,6 +2351,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {onToggleWorkRow,onToggleTurnFold,onPressImage,+ onPressVideo,onMarkdownLinkPress,renderMarkdownImage,iconSubtleColor,@@ -2320,6 +2380,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {onCopyWorkRow,onMarkdownLinkPress,onPressImage,+ onPressVideo,onToggleTurnFold,onToggleWorkGroup,onToggleWorkRow,@@ -2503,6 +2564,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {) : null}</View>+ <VideoPreviewModal source={expandedVideo} onRequestClose={() => setExpandedVideo(null)} /><ImageViewingimages={expandedImagediff --git a/apps/mobile/src/lib/attachmentDownload.test.ts b/apps/mobile/src/lib/attachmentDownload.test.tsindex b0dd934bd4f..78e182e74f6 100644--- a/apps/mobile/src/lib/attachmentDownload.test.ts+++ b/apps/mobile/src/lib/attachmentDownload.test.ts@@ -4,7 +4,9 @@ const mocks = vi.hoisted(() => ({directories: new Set<string>(),deleted: vi.fn(),download: vi.fn(),+ copy: vi.fn(),share: vi.fn(),+ shareFromSource: vi.fn(),available: vi.fn(),uuid: vi.fn(),}));@@ -46,8 +48,12 @@ vi.mock("expo-file-system", () => {static downloadFileAsync = mocks.download;readonly uri: string;- constructor(directory: Directory, name: string) {- this.uri = `${directory.uri}/${encodeURIComponent(name)}`;+ constructor(source: Directory | string, name?: string) {+ this.uri = typeof source === "string" ? source : `${source.uri}/${encodeURIComponent(name!)}`;+ }++ async copy(destination: File): Promise<void> {+ await mocks.copy(this.uri, destination.uri);}}@@ -60,8 +66,13 @@ vi.mock("expo-sharing", () => ({}));vi.mock("./uuid", () => ({ uuidv4: mocks.uuid }));+vi.mock("./shareFileFromSource", () => ({ shareFileFromSource: mocks.shareFromSource }));-import { downloadAndShareAttachment } from "./attachmentDownload";+import {+ downloadAndShareAttachment,+ downloadAttachmentForPreview,+ shareLocalAttachment,+} from "./attachmentDownload";import { isForegroundHandoffActive } from "./foreground-handoff";const NOW = 1_787_990_400_000;@@ -76,11 +87,15 @@ beforeEach(() => {mocks.directories.clear();mocks.deleted.mockReset();mocks.download.mockReset();+ mocks.copy.mockReset();mocks.share.mockReset();+ mocks.shareFromSource.mockReset();mocks.available.mockReset();mocks.uuid.mockReset();mocks.download.mockImplementation(async (_url: string, file: { uri: string }) => file);+ mocks.copy.mockResolvedValue(undefined);mocks.share.mockResolvedValue(undefined);+ mocks.shareFromSource.mockResolvedValue(undefined);mocks.available.mockResolvedValue(true);let sequence = 0;mocks.uuid.mockImplementation(@@ -268,3 +283,118 @@ describe("downloadAndShareAttachment", () => {await first;});});++describe("attachment preview files", () => {+ it("does not start a native request after cancellation during setup", async () => {+ const controller = new AbortController();+ const loading = downloadAttachmentForPreview({ ...input, signal: controller.signal });+ controller.abort();+ await expect(loading).resolves.toBeNull();+ expect(mocks.download).not.toHaveBeenCalled();+ expect(mocks.share).not.toHaveBeenCalled();+ });++ it("downloads for playback without requiring a share sheet and removes the file on close", async () => {+ mocks.available.mockResolvedValue(false);+ const file = await downloadAttachmentForPreview({+ ...input,+ signal: new AbortController().signal,+ });+ expect(file?.uri.endsWith("/report.pdf")).toBe(true);+ expect(mocks.available).not.toHaveBeenCalled();+ expect(mocks.deleted).not.toHaveBeenCalled();+ file?.dispose();+ file?.dispose();+ expect(mocks.deleted).toHaveBeenCalledTimes(1);+ });++ it.each([undefined, "share-button"])(+ "keeps a shared preview after its owner closes (source: %s)",+ async (sourceIdentifier) => {+ const opened = Promise.withResolvers<void>();+ const sharing = Promise.withResolvers<void>();+ const nativeShare = sourceIdentifier ? mocks.shareFromSource : mocks.share;+ nativeShare.mockImplementationOnce(() => {+ opened.resolve();+ return sharing.promise;+ });+ const file = await downloadAttachmentForPreview({+ ...input,+ signal: new AbortController().signal,+ });+ const share = file!.share(new AbortController().signal, sourceIdentifier);+ await opened.promise;+ file!.dispose();+ expect(mocks.deleted).not.toHaveBeenCalled();+ expect(isForegroundHandoffActive()).toBe(true);+ sharing.resolve();+ await share;+ expect(isForegroundHandoffActive()).toBe(false);+ expect(mocks.deleted).not.toHaveBeenCalled();+ expect(mocks.download).toHaveBeenCalledTimes(1);+ expect(mocks.copy).not.toHaveBeenCalled();+ },+ );++ it.each([undefined, "share-button"])(+ "does not share a disposed preview after availability checking (source: %s)",+ async (sourceIdentifier) => {+ const checking = Promise.withResolvers<void>();+ const available = Promise.withResolvers<boolean>();+ mocks.available.mockImplementation(() => {+ checking.resolve();+ return available.promise;+ });+ const file = await downloadAttachmentForPreview({+ ...input,+ signal: new AbortController().signal,+ });+ const share = file!.share(new AbortController().signal, sourceIdentifier);+ await checking.promise;+ file!.dispose();+ available.resolve(true);+ await share;+ expect(mocks.share).not.toHaveBeenCalled();+ expect(mocks.shareFromSource).not.toHaveBeenCalled();+ expect(mocks.deleted).toHaveBeenCalledTimes(1);+ },+ );++ it("copies a local original before sharing without downloading or deleting the source", async () => {+ const uri = "file:///documents/draft/report.pdf";+ await shareLocalAttachment({+ uri,+ attachment: input.attachment,+ signal: new AbortController().signal,+ });+ expect(mocks.copy).toHaveBeenCalledWith(+ uri,+ expect.stringMatching(/^file:\/\/\/cache\/.+\/report\.pdf$/),+ );+ expect(mocks.share).toHaveBeenCalledWith(mocks.copy.mock.calls[0]![1], expect.any(Object));+ expect(mocks.download).not.toHaveBeenCalled();+ expect(mocks.deleted).not.toHaveBeenCalled();+ });++ it("waits for a local copy to finish before cleaning up a canceled share", async () => {+ const copying = Promise.withResolvers<void>();+ const copied = Promise.withResolvers<void>();+ mocks.copy.mockImplementation(() => {+ copying.resolve();+ return copied.promise;+ });+ const controller = new AbortController();+ const task = shareLocalAttachment({+ uri: "file:///documents/draft/report.pdf",+ attachment: input.attachment,+ signal: controller.signal,+ });+ await copying.promise;+ controller.abort();+ expect(mocks.deleted).not.toHaveBeenCalled();+ copied.resolve();+ await task;+ expect(mocks.share).not.toHaveBeenCalled();+ expect(mocks.deleted).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/mobile/src/lib/attachmentDownload.ts b/apps/mobile/src/lib/attachmentDownload.tsindex 8c9da9bc007..2ae0c729c19 100644--- a/apps/mobile/src/lib/attachmentDownload.ts+++ b/apps/mobile/src/lib/attachmentDownload.ts@@ -1,5 +1,6 @@import type { ChatFileAttachment } from "@t3tools/contracts";import type { Directory } from "expo-file-system";+import type { SharingOptions } from "expo-sharing";import { beginForegroundHandoff } from "./foreground-handoff";import { uuidv4 } from "./uuid";@@ -52,23 +53,27 @@ function removeDownloadDirectory(directory: Directory): void {}}-/** Downloads original bytes for the native save/share sheet, including inline video responses. */-export async function downloadAndShareAttachment(input: {- readonly url: string;- readonly attachment: Pick<ChatFileAttachment, "name" | "mimeType">;- readonly signal: AbortSignal;-}): Promise<void> {- const [{ Directory, File, Paths }, Sharing] = await Promise.all([- import("expo-file-system"),- import("expo-sharing"),- ]);- if (input.signal.aborted) return;+type AttachmentFileMetadata = Pick<ChatFileAttachment, "name" | "mimeType">;++export interface AttachmentPreviewFile {+ readonly uri: string;+ readonly share: (signal: AbortSignal, sourceIdentifier?: string) => Promise<void>;+ readonly dispose: () => void;+}++async function availableSharing(signal: AbortSignal) {+ if (signal.aborted) return null;+ const Sharing = await import("expo-sharing");const canShare = await Sharing.isAvailableAsync();- if (input.signal.aborted) return;+ if (signal.aborted) return null;if (!canShare) {throw new Error("Saving and sharing files is unavailable on this device.");}+ return Sharing;+}+async function createCachedAttachmentFile(attachment: AttachmentFileMetadata) {+ const { Directory, File, Paths } = await import("expo-file-system");const cache = new Directory(Paths.cache, ATTACHMENT_DOWNLOAD_DIRECTORY);cache.create({ idempotent: true, intermediates: true });const now = Date.now();@@ -89,40 +94,135 @@ export async function downloadAndShareAttachment(input: {}const directory = new Directory(cache, `${now}-${uuidv4()}`);+ directory.create();+ let file: InstanceType<typeof File>;+ try {+ file = new File(directory, downloadFileName(attachment.name));+ } catch (error) {+ removeDownloadDirectory(directory);+ throw error;+ }activeDirectories.add(directory.uri);+ let disposed = false;let shared = false;- let openingShareSheet = false;- try {- directory.create();- const destination = new File(directory, downloadFileName(input.attachment.name));- const file = await File.downloadFileAsync(input.url, destination, { signal: input.signal });- if (input.signal.aborted) return;+ let sharing = false;+ const release = () => {+ if (!disposed || sharing) return;+ activeDirectories.delete(directory.uri);+ // A receiver can still be reading after Android's chooser returns.+ if (!shared) removeDownloadDirectory(directory);+ };+ const preview: AttachmentPreviewFile = {+ uri: file.uri,+ dispose: () => {+ disposed = true;+ release();+ },+ share: async (signal, sourceIdentifier) => {+ if (disposed || sharing || signal.aborted) return;+ sharing = true;+ try {+ const Sharing = await availableSharing(signal);+ if (Sharing === null || disposed) return;+ const endHandoff = beginForegroundHandoff();+ try {+ const options: SharingOptions = {+ mimeType: attachment.mimeType.split(";", 1)[0]?.trim() || "application/octet-stream",+ dialogTitle: attachment.name,+ };+ if (sourceIdentifier) {+ const { shareFileFromSource } = await import("./shareFileFromSource");+ if (signal.aborted || disposed) return;+ await shareFileFromSource(file.uri, options, sourceIdentifier);+ } else {+ await Sharing.shareAsync(file.uri, options);+ }+ shared = true;+ } catch (cause) {+ if (!signal.aborted) {+ throw new Error("Could not open the share sheet. Try again.", { cause });+ }+ } finally {+ endHandoff();+ }+ } finally {+ sharing = false;+ release();+ }+ },+ };+ return { file, preview };+}- openingShareSheet = true;- const endHandoff = beginForegroundHandoff();- try {- await Sharing.shareAsync(file.uri, {- mimeType: input.attachment.mimeType.split(";", 1)[0]?.trim() || "application/octet-stream",- dialogTitle: input.attachment.name,- });- shared = true;- } finally {- endHandoff();+/** The caller owns this cached file until disposal, unless it has been shared with another app. */+export async function downloadAttachmentForPreview(input: {+ readonly url: string;+ readonly attachment: AttachmentFileMetadata;+ readonly signal: AbortSignal;+}): Promise<AttachmentPreviewFile | null> {+ if (input.signal.aborted) return null;+ const { File } = await import("expo-file-system");+ const cached = await createCachedAttachmentFile(input.attachment);+ try {+ if (input.signal.aborted) {+ cached.preview.dispose();+ return null;+ }+ await File.downloadFileAsync(input.url, cached.file, { signal: input.signal });+ if (input.signal.aborted) {+ cached.preview.dispose();+ return null;}+ return cached.preview;} catch (cause) {- if (input.signal.aborted) return;- throw new Error(- openingShareSheet- ? "Could not open the share sheet. Try again."- : "Could not download the attachment. Check the connection and try again.",- { cause },- );+ // Android may leave a partial file after a failed or interrupted request.+ cached.preview.dispose();+ if (input.signal.aborted) return null;+ throw new Error("Could not download the attachment. Check the connection and try again.", {+ cause,+ });+ }+}++/** Downloads original bytes for the native save/share sheet, including inline video responses. */+export async function downloadAndShareAttachment(input: {+ readonly url: string;+ readonly attachment: AttachmentFileMetadata;+ readonly signal: AbortSignal;+ readonly sourceIdentifier?: string;+}): Promise<void> {+ if ((await availableSharing(input.signal)) === null) return;+ const file = await downloadAttachmentForPreview(input);+ if (file === null) return;+ try {+ await file.share(input.signal, input.sourceIdentifier);} finally {- activeDirectories.delete(directory.uri);- // A receiver can still be reading after Android's chooser returns.- // Successful exports expire on a later open; partial downloads do not.- if (!shared) {- removeDownloadDirectory(directory);+ file.dispose();+ }+}++/** Shares a cache copy so another app never relies on the lifetime of a composer draft. */+export async function shareLocalAttachment(input: {+ readonly uri: string;+ readonly attachment: AttachmentFileMetadata;+ readonly signal: AbortSignal;+ readonly sourceIdentifier?: string;+}): Promise<void> {+ if ((await availableSharing(input.signal)) === null) return;+ const { File } = await import("expo-file-system");+ const cached = await createCachedAttachmentFile(input.attachment);+ try {+ if (input.signal.aborted) return;+ try {+ await new File(input.uri).copy(cached.file);+ } catch (cause) {+ if (input.signal.aborted) return;+ throw new Error("Could not prepare the attachment for sharing.", { cause });}+ if (!input.signal.aborted) {+ await cached.preview.share(input.signal, input.sourceIdentifier);+ }+ } finally {+ cached.preview.dispose();}}diff --git a/apps/mobile/src/lib/composerAttachmentFiles.ts b/apps/mobile/src/lib/composerAttachmentFiles.tsindex a50daa30b62..963566b6ad8 100644--- a/apps/mobile/src/lib/composerAttachmentFiles.ts+++ b/apps/mobile/src/lib/composerAttachmentFiles.ts@@ -6,6 +6,7 @@ const IOS_DOCUMENTS_PATH = new RegExp(`^(.*/Containers/Data/Application/)${UUID_PATTERN}/Documents$`,"i",);+const retainedFiles = new Map<string, number>();function fileUriPath(uri: string): string | null {try {@@ -52,6 +53,30 @@ export function composerAttachmentFileReferenceKey(uri: string): string {return `file://${documentPath}/${COMPOSER_ATTACHMENT_DIRECTORY}/${encodeURIComponent(location.name)}`;}+/** Holds a local copy until its last player or share-copy operation releases it. */+export function retainComposerAttachmentFile(uri: string, onLastRelease: () => void): () => void {+ const key = composerAttachmentFileReferenceKey(uri);+ retainedFiles.set(key, (retainedFiles.get(key) ?? 0) + 1);+ let released = false;+ return () => {+ if (released) {+ return;+ }+ released = true;+ const remaining = (retainedFiles.get(key) ?? 1) - 1;+ if (remaining > 0) {+ retainedFiles.set(key, remaining);+ return;+ }+ retainedFiles.delete(key);+ onLastRelease();+ };+}++export function isComposerAttachmentFileRetained(uri: string): boolean {+ return retainedFiles.has(composerAttachmentFileReferenceKey(uri));+}+/*** Resolves only our saved attachment copies. iOS preserves Documents on updates* but can change its container UUID. Picker and open-in-place source URIs mustdiff --git a/apps/mobile/src/lib/composerFiles.test.ts b/apps/mobile/src/lib/composerFiles.test.tsindex f52bd9276cf..561b2a800ae 100644--- a/apps/mobile/src/lib/composerFiles.test.ts+++ b/apps/mobile/src/lib/composerFiles.test.ts@@ -23,8 +23,6 @@ vi.mock("expo-file-system", () => {}class File {- static pickFileAsync = mocks.pickFile;-readonly uri: string;constructor(source: string | Directory, name?: string) {@@ -75,6 +73,7 @@ vi.mock("expo-file-system", () => {});vi.mock("expo-image-picker", () => ({ launchImageLibraryAsync: mocks.pickMedia }));+vi.mock("expo-document-picker", () => ({ getDocumentAsync: mocks.pickFile }));vi.mock("./uuid", () => ({ uuidv4: () => "attachment-id" }));import {@@ -85,6 +84,7 @@ import {removePersistedComposerAttachmentFile,} from "./composerImages";import { isForegroundHandoffActive } from "./foreground-handoff";+import { retainComposerAttachmentFile } from "./composerAttachmentFiles";describe("composer file attachments", () => {beforeEach(() => {@@ -274,11 +274,11 @@ describe("composer file attachments", () => {it("copies picked files into app-owned storage without loading their contents", async () => {mocks.pickFile.mockResolvedValue({canceled: false,- result: [+ assets: [{uri: "file:///downloads/report.pdf",name: "report.pdf",- type: "application/pdf",+ mimeType: "application/pdf",size: 42,},],@@ -303,14 +303,120 @@ describe("composer file attachments", () => {);});+ it("preserves Android picker metadata instead of using the content URI document id", async () => {+ const uri = "content://com.android.providers.media.documents/document/video%3A18";+ mocks.pickFile.mockResolvedValue({+ canceled: false,+ assets: [+ {+ uri,+ name: "preview-h264.mp4",+ mimeType: "video/mp4",+ size: 620_992,+ lastModified: 0,+ },+ ],+ });+ mocks.size.mockReturnValue(620_992);++ await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({+ files: [+ {+ id: "attachment-id",+ type: "file",+ name: "preview-h264.mp4",+ mimeType: "video/mp4",+ sizeBytes: 620_992,+ fileUri: "file:///documents/t3-composer-attachments/attachment-id-preview-h264.mp4",+ },+ ],+ error: null,+ });+ expect(mocks.pickFile).toHaveBeenCalledWith({ multiple: true, copyToCacheDirectory: true });+ expect(mocks.copy).toHaveBeenCalledWith(+ uri,+ "file:///documents/t3-composer-attachments/attachment-id-preview-h264.mp4",+ );+ expect(mocks.delete).not.toHaveBeenCalled();+ });++ it("persists provider selections that require a readable cache copy", async () => {+ const providerUri = "content://cloud-provider/documents/clip";+ const cachedUri = "file:///cache/DocumentPicker/clip.mp4";+ mocks.pickFile.mockImplementation(async (options) => ({+ canceled: false,+ assets: [+ {+ uri: options.copyToCacheDirectory ? cachedUri : providerUri,+ name: "Cloud recording.mp4",+ mimeType: "video/mp4",+ size: 42,+ lastModified: 0,+ },+ ],+ }));+ mocks.copy.mockImplementation((uri: string) => {+ if (uri === providerUri) throw new Error("The provider URI is not directly readable.");+ });++ const result = await pickComposerFiles({ existingCount: 0 });++ expect(result.error).toBeNull();+ expect(result.files).toEqual([+ expect.objectContaining({+ name: "Cloud recording.mp4",+ fileUri: "file:///documents/t3-composer-attachments/attachment-id-Cloud recording.mp4",+ }),+ ]);+ expect(mocks.copy).toHaveBeenCalledWith(cachedUri, result.files[0]!.fileUri);+ });++ it("ends the foreground handoff when the picker is canceled without copying files", async () => {+ mocks.pickFile.mockImplementation(async () => {+ expect(isForegroundHandoffActive()).toBe(true);+ return { canceled: true, assets: null };+ });++ await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({+ files: [],+ error: null,+ });++ expect(isForegroundHandoffActive()).toBe(false);+ expect(mocks.copy).not.toHaveBeenCalled();+ expect(mocks.open).not.toHaveBeenCalled();+ });++ it("reports picker failures and releases the foreground handoff", async () => {+ mocks.pickFile.mockRejectedValue(new Error("The document provider is unavailable."));++ await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({+ files: [],+ error: "The document provider is unavailable.",+ });++ expect(isForegroundHandoffActive()).toBe(false);+ expect(mocks.copy).not.toHaveBeenCalled();+ });++ it("does not open the picker when the draft has no remaining attachment slots", async () => {+ await expect(pickComposerFiles({ existingCount: 8 })).resolves.toEqual({+ files: [],+ error: "You can attach up to 8 files per message.",+ });++ expect(mocks.pickFile).not.toHaveBeenCalled();+ expect(isForegroundHandoffActive()).toBe(false);+ });+it("falls back to a usable name when the picker reports a blank one", async () => {mocks.pickFile.mockResolvedValue({canceled: false,- result: [+ assets: [{uri: "file:///downloads/unnamed",name: " ",- type: "application/pdf",+ mimeType: "application/pdf",size: 42,},],@@ -325,11 +431,11 @@ describe("composer file attachments", () => {it("rejects files that exceed the environment's advertised upload limit", async () => {mocks.pickFile.mockResolvedValue({canceled: false,- result: [+ assets: [{uri: "file:///downloads/archive.zip",name: "archive.zip",- type: "application/zip",+ mimeType: "application/zip",size: 2 * 1024 * 1024,},],@@ -345,11 +451,11 @@ describe("composer file attachments", () => {it("never accepts files above the 50 MB contract limit", async () => {mocks.pickFile.mockResolvedValue({canceled: false,- result: [+ assets: [{uri: "file:///downloads/archive.zip",name: "archive.zip",- type: "application/zip",+ mimeType: "application/zip",size: 51 * 1024 * 1024,},],@@ -366,11 +472,11 @@ describe("composer file attachments", () => {it("rejects a file that grew after the picker reported its size", async () => {mocks.pickFile.mockResolvedValue({canceled: false,- result: [+ assets: [{uri: "file:///downloads/archive.zip",name: "archive.zip",- type: "application/zip",+ mimeType: "application/zip",size: 42,},],@@ -434,11 +540,11 @@ describe("composer file attachments", () => {mocks.size.mockReturnValue(0);mocks.pickFile.mockResolvedValue({canceled: false,- result: [+ assets: [{uri: "file:///downloads/empty.txt",name: "empty.txt",- type: "text/plain",+ mimeType: "text/plain",size: 0,},],@@ -450,7 +556,7 @@ describe("composer file attachments", () => {});});- it("copies an Android SAF file when the picker reports an unknown zero size", async () => {+ it.each([0, undefined])("copies an Android SAF file when the picker size is %s", async (size) => {const reader = {readBytes: vi.fn()@@ -463,12 +569,12 @@ describe("composer file attachments", () => {mocks.open.mockImplementation((uri: string) => (uri.startsWith("content:") ? reader : writer));mocks.pickFile.mockResolvedValue({canceled: false,- result: [+ assets: [{uri: "content://shared/report",name: "report.pdf",- type: "application/pdf",- size: 0,+ mimeType: "application/pdf",+ size,},],});@@ -491,17 +597,17 @@ describe("composer file attachments", () => {it("uses the remaining slot for the first valid file after an oversized selection", async () => {mocks.pickFile.mockResolvedValue({canceled: false,- result: [+ assets: [{uri: "file:///downloads/huge.zip",name: "huge.zip",- type: "application/zip",+ mimeType: "application/zip",size: 2 * 1024 * 1024,},{uri: "file:///downloads/report.pdf",name: "report.pdf",- type: "application/pdf",+ mimeType: "application/pdf",size: 42,},],@@ -557,6 +663,26 @@ describe("composer file attachments", () => {]);});+ it("rechecks preview ownership after loading the native filesystem", async () => {+ const fileName = "33333333-3333-4333-8333-333333333333-recording.mp4";+ const oldUri = `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`;+ mocks.documentUri =+ "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";+ const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`;++ const deleting = removePersistedComposerAttachmentFile(oldUri);+ const release = retainComposerAttachmentFile(currentUri, () => {});+ try {+ await deleting;+ expect(mocks.delete).not.toHaveBeenCalled();+ } finally {+ release();+ }++ await removePersistedComposerAttachmentFile(oldUri);+ expect(mocks.delete.mock.calls).toEqual([[currentUri]]);+ });+it("copies an open-in-place source from its actual container without rebasing it", async () => {const sourceUri ="file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/33333333-3333-4333-8333-333333333333-report.pdf";diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.tsindex c1919315021..b4684e5bfc6 100644--- a/apps/mobile/src/lib/composerImages.ts+++ b/apps/mobile/src/lib/composerImages.ts@@ -10,10 +10,11 @@ import {type EnvironmentId,type UploadChatImageAttachment,} from "@t3tools/contracts";-import type { PickMultipleFilesResult } from "expo-file-system";+import type { DocumentPickerResult } from "expo-document-picker";import { estimateBase64ByteSize } from "./base64";import {COMPOSER_ATTACHMENT_DIRECTORY,+ isComposerAttachmentFileRetained,resolveOwnedComposerAttachmentFileUri,} from "./composerAttachmentFiles";import { beginForegroundHandoff } from "./foreground-handoff";@@ -145,7 +146,7 @@ export async function removePersistedComposerAttachmentFile(uri: string): Promistry {const { File, Paths } = await import("expo-file-system");const ownedUri = resolveOwnedComposerAttachmentFileUri(uri, Paths.document.uri);- if (ownedUri === null) {+ if (ownedUri === null || isComposerAttachmentFileRetained(ownedUri)) {return;}const file = new File(ownedUri);@@ -206,11 +207,18 @@ export async function pickComposerFiles(input: {};}- const { File } = await import("expo-file-system");+ const { getDocumentAsync } = await import("expo-document-picker");const endHandoff = beginForegroundHandoff();- let result: PickMultipleFilesResult;+ let result: DocumentPickerResult;try {- result = await File.pickFileAsync({ multipleFiles: true });+ // File providers may expose a URI that FileSystem cannot read directly.+ // Import a readable cache copy before persisting the draft's owned file.+ result = await getDocumentAsync({ multiple: true, copyToCacheDirectory: true });+ } catch (cause) {+ return {+ files: [],+ error: cause instanceof Error ? cause.message : "Could not open the file picker.",+ };} finally {endHandoff();}@@ -224,7 +232,7 @@ export async function pickComposerFiles(input: {const attachments: DraftComposerFileAttachment[] = [];let error: string | null = null;let exceededAttachmentLimit = false;- for (const file of result.result) {+ for (const file of result.assets) {if (attachments.length >= remainingSlots) {exceededAttachmentLimit = true;break;@@ -238,7 +246,7 @@ export async function pickComposerFiles(input: {await createComposerFileAttachment({uri: file.uri,name,- mimeType: file.type || "application/octet-stream",+ mimeType: file.mimeType || "application/octet-stream",sizeBytes: file.size ?? null,maxBytes,}),diff --git a/apps/mobile/src/lib/localVideoPreview.test.ts b/apps/mobile/src/lib/localVideoPreview.test.tsnew file mode 100644index 00000000000..706c6152168--- /dev/null+++ b/apps/mobile/src/lib/localVideoPreview.test.ts@@ -0,0 +1,114 @@+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";++const mocks = vi.hoisted(() => ({+ retain: vi.fn(),+ share: vi.fn(),+ exists: vi.fn(),+}));++vi.mock("../state/use-composer-drafts", () => ({+ retainComposerAttachmentFileForPreview: mocks.retain,+}));+vi.mock("./attachmentDownload", () => ({ shareLocalAttachment: mocks.share }));+vi.mock("expo-file-system", () => ({+ File: class {+ constructor(readonly uri: string) {}+ get exists(): boolean {+ return mocks.exists(this.uri);+ }+ },+ Paths: {+ document: {+ uri: "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents/",+ },+ },+}));++import { loadLocalVideoPreview } from "./localVideoPreview";++const attachment = {+ type: "file" as const,+ id: "draft-video",+ name: "clip.mov",+ mimeType: "video/quicktime",+ sizeBytes: 12,+ fileUri:+ "file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/33333333-3333-4333-8333-333333333333-clip.mov",+};++beforeEach(() => {+ mocks.retain.mockReset();+ mocks.share.mockReset();+ mocks.exists.mockReset();+ mocks.retain.mockImplementation(() => vi.fn());+ mocks.exists.mockReturnValue(true);+ mocks.share.mockResolvedValue(undefined);+});++describe("loadLocalVideoPreview", () => {+ it("resolves the current iOS container and releases its playback lease once", async () => {+ const preview = await loadLocalVideoPreview(attachment, new AbortController().signal);+ expect(preview?.uri).toContain("/22222222-2222-4222-8222-222222222222/Documents/");+ expect(mocks.retain).toHaveBeenCalledWith(attachment);+ const release = mocks.retain.mock.results[0]!.value;+ expect(release).not.toHaveBeenCalled();+ preview?.dispose();+ preview?.dispose();+ expect(release).toHaveBeenCalledTimes(1);+ });++ it.each([undefined, "share-button"])(+ "keeps a separate share lease after playback closes (source: %s)",+ async (sourceIdentifier) => {+ const shared = Promise.withResolvers<void>();+ mocks.share.mockReturnValue(shared.promise);+ const preview = await loadLocalVideoPreview(attachment, new AbortController().signal);+ const share = preview!.share(new AbortController().signal, sourceIdentifier);+ expect(mocks.retain).toHaveBeenCalledTimes(2);+ const releasePlayback = mocks.retain.mock.results[0]!.value;+ const releaseShare = mocks.retain.mock.results[1]!.value;+ preview!.dispose();+ expect(releasePlayback).toHaveBeenCalledTimes(1);+ expect(releaseShare).not.toHaveBeenCalled();+ shared.resolve();+ await share;+ expect(releaseShare).toHaveBeenCalledTimes(1);+ },+ );++ it("releases a failed share while keeping playback retained", async () => {+ mocks.share.mockRejectedValue(new Error("Sharing unavailable"));+ const preview = await loadLocalVideoPreview(attachment, new AbortController().signal);+ await expect(preview!.share(new AbortController().signal)).rejects.toThrow(+ "Sharing unavailable",+ );+ expect(mocks.retain.mock.results[1]!.value).toHaveBeenCalledTimes(1);+ expect(mocks.retain.mock.results[0]!.value).not.toHaveBeenCalled();+ preview!.dispose();+ });++ it("releases a load canceled during native module loading", async () => {+ const controller = new AbortController();+ const loading = loadLocalVideoPreview(attachment, controller.signal);+ controller.abort();+ await expect(loading).resolves.toBeNull();+ expect(mocks.retain.mock.results[0]!.value).toHaveBeenCalledTimes(1);+ expect(mocks.exists).not.toHaveBeenCalled();+ });++ it("reports missing files and releases their lease", async () => {+ mocks.exists.mockReturnValue(false);+ await expect(loadLocalVideoPreview(attachment, new AbortController().signal)).rejects.toThrow(+ "This video is no longer available. Attach the file again.",+ );+ expect(mocks.retain.mock.results[0]!.value).toHaveBeenCalledTimes(1);+ });++ it("does not start sharing a disposed preview", async () => {+ const preview = await loadLocalVideoPreview(attachment, new AbortController().signal);+ preview!.dispose();+ await preview!.share(new AbortController().signal);+ expect(mocks.share).not.toHaveBeenCalled();+ expect(mocks.retain).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/mobile/src/lib/localVideoPreview.ts b/apps/mobile/src/lib/localVideoPreview.tsnew file mode 100644index 00000000000..8398124b96c--- /dev/null+++ b/apps/mobile/src/lib/localVideoPreview.ts@@ -0,0 +1,59 @@+import { videoMimeType } from "@t3tools/shared/video";++import type { DraftComposerFileAttachment } from "./composerImages";+import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";+import { shareLocalAttachment, type AttachmentPreviewFile } from "./attachmentDownload";+import { retainComposerAttachmentFileForPreview } from "../state/use-composer-drafts";++/** Retains the draft original for playback and gives each outgoing share its own lease. */+export async function loadLocalVideoPreview(+ attachment: DraftComposerFileAttachment,+ signal: AbortSignal,+): Promise<AttachmentPreviewFile | null> {+ if (signal.aborted) return null;+ const release = retainComposerAttachmentFileForPreview(attachment);+ try {+ const { File, Paths } = await import("expo-file-system");+ if (signal.aborted) {+ release();+ return null;+ }+ const uri =+ resolveOwnedComposerAttachmentFileUri(attachment.fileUri, Paths.document.uri) ??+ attachment.fileUri;+ const file = new File(uri);+ if (!file.exists) {+ throw new Error("The local attachment file is missing.");+ }+ let disposed = false;+ return {+ uri: file.uri,+ dispose: () => {+ if (disposed) return;+ disposed = true;+ release();+ },+ share: async (shareSignal, sourceIdentifier) => {+ if (disposed || shareSignal.aborted) return;+ const releaseShare = retainComposerAttachmentFileForPreview(attachment);+ try {+ await shareLocalAttachment({+ uri: file.uri,+ attachment: {+ name: attachment.name,+ mimeType: videoMimeType(attachment) ?? attachment.mimeType,+ },+ signal: shareSignal,+ sourceIdentifier,+ });+ } finally {+ releaseShare();+ }+ },+ };+ } catch (cause) {+ release();+ if (signal.aborted) return null;+ throw new Error("This video is no longer available. Attach the file again.", { cause });+ }+}diff --git a/apps/mobile/src/lib/shareFileFromSource.ios.ts b/apps/mobile/src/lib/shareFileFromSource.ios.tsnew file mode 100644index 00000000000..5de0e0cbd42--- /dev/null+++ b/apps/mobile/src/lib/shareFileFromSource.ios.ts@@ -0,0 +1,14 @@+import { requireNativeModule } from "expo";+import type { SharingOptions } from "expo-sharing";++const NativeControls = requireNativeModule<{+ shareFileFromSource(uri: string, title: string, sourceIdentifier: string): Promise<void>;+}>("T3NativeControls");++export function shareFileFromSource(+ uri: string,+ options: SharingOptions,+ sourceIdentifier: string,+) {+ return NativeControls.shareFileFromSource(uri, options.dialogTitle ?? "", sourceIdentifier);+}diff --git a/apps/mobile/src/lib/shareFileFromSource.ts b/apps/mobile/src/lib/shareFileFromSource.tsnew file mode 100644index 00000000000..5e806612a04--- /dev/null+++ b/apps/mobile/src/lib/shareFileFromSource.ts@@ -0,0 +1,9 @@+import { shareAsync, type SharingOptions } from "expo-sharing";++export function shareFileFromSource(+ uri: string,+ options: SharingOptions,+ _sourceIdentifier: string,+) {+ return shareAsync(uri, options);+}diff --git a/apps/mobile/src/lib/videoThumbnails.test.ts b/apps/mobile/src/lib/videoThumbnails.test.tsnew file mode 100644index 00000000000..e577e448ea2--- /dev/null+++ b/apps/mobile/src/lib/videoThumbnails.test.ts@@ -0,0 +1,168 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++const mocks = vi.hoisted(() => ({ createPlayer: vi.fn() }));+vi.mock("expo-video", () => ({ createVideoPlayer: mocks.createPlayer }));++let thumbnails: typeof import("./videoThumbnails");+const frame = { width: 480, height: 270 };+const player = () => ({+ replaceAsync: vi.fn(async (): Promise<void> => {}),+ generateThumbnailsAsync: vi.fn(async () => [frame]),+ release: vi.fn(),+});+const source = () => ({ uri: "file:///clip.mp4", dispose: vi.fn() });++beforeEach(async () => {+ vi.resetModules();+ mocks.createPlayer.mockReset().mockImplementation(player);+ thumbnails = await import("./videoThumbnails");+});++afterEach(() => vi.useRealTimers());++describe("video thumbnails", () => {+ it("reuses a frame for duplicate requests and refreshed signed URLs", async () => {+ const file = source();+ const resolveSource = vi.fn(async () => file);+ const signal = new AbortController().signal;+ const results = await Promise.all([+ thumbnails.loadVideoThumbnail("env:clip", resolveSource, signal),+ thumbnails.loadVideoThumbnail("env:clip", resolveSource, signal),+ ]);+ expect(results).toEqual([frame, frame]);+ expect(resolveSource).toHaveBeenCalledTimes(1);+ expect(mocks.createPlayer).toHaveBeenCalledTimes(1);+ expect(file.dispose).toHaveBeenCalledTimes(1);+ const refreshed = vi.fn(async () => ({ ...source(), uri: "https://host/new-token/clip.mp4" }));+ expect(await thumbnails.loadVideoThumbnail("env:clip", refreshed, signal)).toBe(frame);+ expect(refreshed).not.toHaveBeenCalled();+ });++ it("serializes decoding and skips queued requests that scroll out of view", async () => {+ const started = Promise.withResolvers<void>();+ const generated = Promise.withResolvers<(typeof frame)[]>();+ const first = player();+ first.generateThumbnailsAsync.mockImplementation(() => {+ started.resolve();+ return generated.promise;+ });+ mocks.createPlayer.mockReturnValueOnce(first);+ const firstRequest = thumbnails.loadVideoThumbnail(+ "first",+ async () => source(),+ new AbortController().signal,+ );+ await started.promise;+ const removed = new AbortController();+ const skipped = vi.fn(async () => source());+ const queued = thumbnails.loadVideoThumbnail("removed", skipped, removed.signal);+ const next = vi.fn(async () => source());+ const nextRequest = thumbnails.loadVideoThumbnail("next", next, new AbortController().signal);+ expect(next).not.toHaveBeenCalled();+ removed.abort();+ generated.resolve([frame]);+ expect(await firstRequest).toBe(frame);+ expect(await queued).toBeNull();+ expect(await nextRequest).toBe(frame);+ expect(skipped).not.toHaveBeenCalled();+ expect(first.release).toHaveBeenCalledTimes(1);+ });++ it("releases an active canceled player and ignores late source loading", async () => {+ const started = Promise.withResolvers<void>();+ const replaced = Promise.withResolvers<void>();+ const first = player();+ first.replaceAsync.mockImplementation(() => {+ started.resolve();+ return replaced.promise;+ });+ mocks.createPlayer.mockReturnValueOnce(first);+ const file = source();+ const controller = new AbortController();+ const request = thumbnails.loadVideoThumbnail("canceled", async () => file, controller.signal);+ await started.promise;+ controller.abort();+ expect(await request).toBeNull();+ expect(first.release).toHaveBeenCalledTimes(1);+ expect(file.dispose).toHaveBeenCalledTimes(1);+ replaced.resolve();+ expect(+ await thumbnails.loadVideoThumbnail(+ "next",+ async () => source(),+ new AbortController().signal,+ ),+ ).toBe(frame);+ expect(first.generateThumbnailsAsync).not.toHaveBeenCalled();+ expect(thumbnails.cachedVideoThumbnail("canceled")).toBeNull();+ });++ it("releases failed extractions and permits a later retry", async () => {+ const broken = player();+ broken.generateThumbnailsAsync.mockRejectedValue(new Error("Invalid video"));+ mocks.createPlayer.mockReturnValueOnce(broken);+ const file = source();+ expect(+ await thumbnails.loadVideoThumbnail("retry", async () => file, new AbortController().signal),+ ).toBeNull();+ expect(broken.release).toHaveBeenCalledTimes(1);+ expect(file.dispose).toHaveBeenCalledTimes(1);+ expect(+ await thumbnails.loadVideoThumbnail(+ "retry",+ async () => source(),+ new AbortController().signal,+ ),+ ).toBe(frame);+ });++ it("does not let an unreachable source block the queue indefinitely", async () => {+ vi.useFakeTimers();+ const started = Promise.withResolvers<void>();+ const first = player();+ first.replaceAsync.mockImplementation(() => {+ started.resolve();+ return new Promise(() => {});+ });+ mocks.createPlayer.mockReturnValueOnce(first);+ const file = source();+ const request = thumbnails.loadVideoThumbnail(+ "unreachable",+ async () => file,+ new AbortController().signal,+ );+ await started.promise;+ await vi.advanceTimersByTimeAsync(15_000);+ expect(await request).toBeNull();+ expect(first.release).toHaveBeenCalledTimes(1);+ expect(file.dispose).toHaveBeenCalledTimes(1);+ expect(+ await thumbnails.loadVideoThumbnail(+ "reachable",+ async () => source(),+ new AbortController().signal,+ ),+ ).toBe(frame);+ });++ it("bounds the retained native images without invalidating frames still displayed", async () => {+ for (let i = 0; i < 33; i++) {+ await thumbnails.loadVideoThumbnail(+ `clip:${i}`,+ async () => source(),+ new AbortController().signal,+ );+ }+ expect(thumbnails.cachedVideoThumbnail("clip:0")).toBeNull();+ expect(thumbnails.cachedVideoThumbnail("clip:32")).toBe(frame);+ expect(mocks.createPlayer).toHaveBeenCalledTimes(33);+ expect(+ await thumbnails.loadVideoThumbnail(+ "clip:0",+ async () => source(),+ new AbortController().signal,+ ),+ ).toBe(frame);+ expect(mocks.createPlayer).toHaveBeenCalledTimes(34);+ });+});diff --git a/apps/mobile/src/lib/videoThumbnails.ts b/apps/mobile/src/lib/videoThumbnails.tsnew file mode 100644index 00000000000..927e1174a7f--- /dev/null+++ b/apps/mobile/src/lib/videoThumbnails.ts@@ -0,0 +1,81 @@+import type { VideoThumbnail } from "expo-video";++import type { AttachmentPreviewFile } from "./attachmentDownload";++const thumbnails = new Map<string, VideoThumbnail>();+const MAX_CACHED_THUMBNAILS = 32;+let pending: Promise<unknown> = Promise.resolve();++export function cachedVideoThumbnail(key: string): VideoThumbnail | null {+ return thumbnails.get(key) ?? null;+}++async function extractFrame(uri: string, signal: AbortSignal) {+ const { createVideoPlayer } = await import("expo-video");+ if (signal.aborted) return null;+ const player = createVideoPlayer(null);+ let disposed = false;+ let cancel = () => {};+ let timeout: ReturnType<typeof setTimeout> | undefined;+ try {+ // Never play or change audio settings: thumbnails must leave the shared audio session alone.+ player.bufferOptions = { preferredForwardBufferDuration: 1 };+ const canceled = new Promise<null>((resolve) => {+ cancel = () => resolve(null);+ });+ signal.addEventListener("abort", cancel, { once: true });+ // An unreachable environment must not hold up thumbnails for other environments.+ timeout = setTimeout(cancel, 15_000);+ const frame = (async () => {+ await player.replaceAsync({ uri, contentType: "progressive" });+ if (disposed || signal.aborted) return null;+ const [thumbnail] = await player.generateThumbnailsAsync([0], {+ maxWidth: 480,+ maxHeight: 480,+ });+ return thumbnail ?? null;+ })();+ return await Promise.race([frame, canceled]);+ } finally {+ disposed = true;+ clearTimeout(timeout);+ signal.removeEventListener("abort", cancel);+ player.release();+ }+}++/** Serializes frame extraction and releases each temporary player and local-file lease. */+export function loadVideoThumbnail(+ key: string,+ resolveSource: (+ signal: AbortSignal,+ ) => Promise<Pick<AttachmentPreviewFile, "uri" | "dispose"> | null>,+ signal: AbortSignal,+): Promise<VideoThumbnail | null> {+ if (signal.aborted) return Promise.resolve(null);+ const cached = cachedVideoThumbnail(key);+ if (cached) return Promise.resolve(cached);+ const load = pending+ .then(async () => {+ if (signal.aborted) return null;+ const cached = cachedVideoThumbnail(key);+ if (cached) return cached;++ const source = await resolveSource(signal);+ if (!source) return null;+ try {+ const thumbnail = await extractFrame(source.uri, signal);+ if (!thumbnail || signal.aborted) return null;+ thumbnails.set(key, thumbnail);+ if (thumbnails.size > MAX_CACHED_THUMBNAILS) {+ thumbnails.delete(thumbnails.keys().next().value!);+ }+ return thumbnail;+ } finally {+ source.dispose();+ }+ })+ .catch(() => null);+ pending = load;+ return load;+}diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.tsindex 3ab0baa3904..90b1ad26232 100644--- a/apps/mobile/src/state/use-composer-drafts.test.ts+++ b/apps/mobile/src/state/use-composer-drafts.test.ts@@ -134,6 +134,7 @@ import {releaseUnusedComposerAttachmentFiles,removeComposerDraftsForEnvironment,resetComposerDraftsLoadState,+ retainComposerAttachmentFileForPreview,restoreComposerDraftSnapshotState,setComposerDraftText,setStickyComposerModelSelection,@@ -319,6 +320,82 @@ describe("mobile composer drafts", () => {expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();});+ it("keeps a removed file until both playback and a share copy finish", async () => {+ const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);+ onTestFinished(() => outboxLoad.mockRestore());+ const fileName = "33333333-3333-4333-8333-333333333333-recording.mp4";+ const file = {+ id: "file-preview",+ type: "file" as const,+ name: "recording.mp4",+ mimeType: "video/mp4",+ sizeBytes: 42,+ fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,+ };+ const currentFile = {+ ...file,+ fileUri: `file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents/t3-composer-attachments/${fileName}`,+ };+ const releasePlayback = retainComposerAttachmentFileForPreview(file);+ const releaseShareCopy = retainComposerAttachmentFileForPreview(currentFile);+ onTestFinished(releasePlayback);+ onTestFinished(releaseShareCopy);++ await releaseUnusedComposerAttachmentFiles([currentFile]);+ expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();++ releasePlayback();+ releasePlayback();+ await releaseUnusedComposerAttachmentFiles([file]);+ expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();++ const deleted = Promise.withResolvers<void>();+ composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {+ deleted.resolve();+ return undefined;+ });+ releaseShareCopy();+ await deleted.promise;++ expect(composerAttachmentCleanupMocks.remove.mock.calls).toEqual([[currentFile.fileUri]]);+ });++ it("preserves a preview opened while cleanup is checking the incoming inbox", async () => {+ const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);+ onTestFinished(() => outboxLoad.mockRestore());+ const file = {+ id: "file-opening-preview",+ type: "file" as const,+ name: "recording.mp4",+ mimeType: "video/mp4",+ sizeBytes: 42,+ fileUri: "file:///documents/t3-composer-attachments/recording.mp4",+ };+ const ownershipReadStarted = Promise.withResolvers<void>();+ const ownershipRead = Promise.withResolvers<[]>();+ incomingShareStorageMocks.load.mockImplementationOnce(() => {+ ownershipReadStarted.resolve();+ return ownershipRead.promise;+ });++ const cleanup = releaseUnusedComposerAttachmentFiles([file]);+ await ownershipReadStarted.promise;+ const release = retainComposerAttachmentFileForPreview(file);+ onTestFinished(release);+ ownershipRead.resolve([]);+ await cleanup;+ expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();++ const deleted = Promise.withResolvers<void>();+ composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {+ deleted.resolve();+ return undefined;+ });+ release();+ await deleted.promise;+ expect(composerAttachmentCleanupMocks.remove.mock.calls).toEqual([[file.fileUri]]);+ });+it("removes an unreferenced local file and its pending upload", async () => {const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);onTestFinished(() => outboxLoad.mockRestore());diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.tsindex 7d243360f04..28f3b9f7f99 100644--- a/apps/mobile/src/state/use-composer-drafts.ts+++ b/apps/mobile/src/state/use-composer-drafts.ts@@ -15,8 +15,12 @@ import { Atom } from "effect/unstable/reactivity";import { writeFileAtomically } from "../lib/atomic-file";import { DraftComposerAttachmentSchema } from "../lib/composer-image-schema";-import { composerAttachmentFileReferenceKey } from "../lib/composerAttachmentFiles";-import type { DraftComposerAttachment } from "../lib/composerImages";+import {+ composerAttachmentFileReferenceKey,+ isComposerAttachmentFileRetained,+ retainComposerAttachmentFile,+} from "../lib/composerAttachmentFiles";+import type { DraftComposerAttachment, DraftComposerFileAttachment } from "../lib/composerImages";import { SerializedAsyncQueue } from "../lib/serialized-async-queue";import { appAtomRegistry } from "./atom-registry";import { flushThreadOutbox, threadOutboxManager } from "./thread-outbox";@@ -287,6 +291,9 @@ export async function flushComposerDrafts(): Promise<void> {}function isComposerAttachmentFileReferenced(fileUri: string): boolean {+ if (isComposerAttachmentFileRetained(fileUri)) {+ return true;+ }const referenceKey = composerAttachmentFileReferenceKey(fileUri);const drafts = Object.values(appAtomRegistry.get(composerDraftsAtom));const queuedMessages = Object.values(@@ -436,6 +443,15 @@ export function scheduleUnusedComposerAttachmentCleanup(});}+/** Keeps previews usable after send/removal, then retries the normal ownership cleanup. */+export function retainComposerAttachmentFileForPreview(+ attachment: DraftComposerFileAttachment,+): () => void {+ return retainComposerAttachmentFile(attachment.fileUri, () => {+ scheduleUnusedComposerAttachmentCleanup([attachment]);+ });+}+function schedulePersistComposerState(): void {if (persistTimer !== null) {clearTimeout(persistTimer);diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.tsindex 9ee36ffebdd..7ae036bdc99 100644--- a/apps/server/src/http.test.ts+++ b/apps/server/src/http.test.ts@@ -1,13 +1,102 @@import { expect, it } from "@effect/vitest";import { describe } from "vite-plus/test";+import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";+import * as NodeServices from "@effect/platform-node/NodeServices";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";+import * as Path from "effect/Path";+import { HttpServerResponse } from "effect/unstable/http";import {assetResponseHeaders,+ assetFileResponse,downloadContentDisposition,isLoopbackHostname,resolveDevRedirectUrl,} from "./http.ts";+const fileResponseLayer = Layer.mergeAll(NodeHttpPlatform.layer, NodeServices.layer);++describe("video asset byte ranges", () => {+ it.effect("streams exactly the requested bytes and leaves full downloads intact", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });+ const file = path.join(directory, "clip.mp4");+ yield* fs.writeFileString(file, "0123456789");+ const asset = { path: file, mimeType: "video/mp4" };+ for (const [header, expected, contentRange] of [+ ["bytes=0-1", "01", "bytes 0-1/10"],+ ["bytes=4-", "456789", "bytes 4-9/10"],+ ["bytes=-3", "789", "bytes 7-9/10"],+ ["bytes=-999999999999999999999999", "0123456789", "bytes 0-9/10"],+ ["bytes=8-999999999999999999999999", "89", "bytes 8-9/10"],+ ] as const) {+ const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));+ expect(response.status).toBe(206);+ expect(response.headers.get("accept-ranges")).toBe("bytes");+ expect(response.headers.get("content-range")).toBe(contentRange);+ expect(response.headers.get("content-length")).toBe(String(expected.length));+ expect(yield* Effect.promise(() => response.text())).toBe(expected);+ }+ for (const header of [+ undefined,+ "items=0-1",+ "bytes=0-1,4-5",+ "bytes=8-2",+ "bytes=-",+ "bytes=bad",+ ]) {+ const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));+ expect(response.status).toBe(200);+ expect(yield* Effect.promise(() => response.text())).toBe("0123456789");+ }+ const conditional = HttpServerResponse.toWeb(+ yield* assetFileResponse(asset, "bytes=0-1", '"old-etag"'),+ );+ expect(conditional.status).toBe(200);+ expect(yield* Effect.promise(() => conditional.text())).toBe("0123456789");+ const uppercase = HttpServerResponse.toWeb(+ yield* assetFileResponse({ ...asset, mimeType: "Video/MP4" }, "bytes=0-1"),+ );+ expect(uppercase.status).toBe(206);+ expect(yield* Effect.promise(() => uppercase.text())).toBe("01");+ const image = HttpServerResponse.toWeb(+ yield* assetFileResponse({ path: file, mimeType: "image/png" }, "bytes=0-1"),+ );+ expect(image.status).toBe(200);+ expect(image.headers.has("accept-ranges")).toBe(false);+ expect(yield* Effect.promise(() => image.text())).toBe("0123456789");+ }).pipe(Effect.provide(fileResponseLayer)),+ );++ it.effect("rejects ranges outside the file, including empty files", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });+ const file = path.join(directory, "clip.mp4");+ yield* fs.writeFileString(file, "0123456789");+ for (const header of ["bytes=10-", "bytes=-0", "bytes=999999999999999999999999-"]) {+ const response = HttpServerResponse.toWeb(+ yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, header),+ );+ expect(response.status).toBe(416);+ expect(response.headers.get("content-range")).toBe("bytes */10");+ expect(yield* Effect.promise(() => response.text())).toBe("");+ }+ yield* fs.writeFileString(file, "");+ const empty = HttpServerResponse.toWeb(+ yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, "bytes=0-1"),+ );+ expect(empty.status).toBe(416);+ expect(empty.headers.get("content-range")).toBe("bytes */0");+ }).pipe(Effect.provide(fileResponseLayer)),+ );+});+describe("http dev routing", () => {it("treats localhost and loopback addresses as local", () => {expect(isLoopbackHostname("127.0.0.1")).toBe(true);diff --git a/apps/server/src/http.ts b/apps/server/src/http.tsindex 5e3f46711b1..b83461775e9 100644--- a/apps/server/src/http.ts+++ b/apps/server/src/http.ts@@ -112,6 +112,63 @@ export function assetResponseHeaders(};}+/** A single byte range for native video readers; unsupported range syntax uses the full file. */+function assetByteRange(header: string, size: bigint) {+ const match = /^bytes=(\d*)-(\d*)$/i.exec(header.trim());+ if (!match || (!match[1] && !match[2])) return null;+ const first = match[1] ? BigInt(match[1]) : null;+ const last = match[2] ? BigInt(match[2]) : null;+ if (first !== null && last !== null && last < first) return null;+ if (size === 0n || (first !== null && first >= size) || (first === null && last === 0n)) {+ return { _tag: "Unsatisfiable" as const };+ }+ const start = first ?? (last! >= size ? 0n : size - last!);+ const end = first === null || last === null || last >= size ? size - 1n : last;+ return {+ _tag: "Range" as const,+ offset: start,+ bytesToRead: end - start + 1n,+ contentRange: `bytes ${start}-${end}/${size}`,+ };+}++export const assetFileResponse = Effect.fn("assetFileResponse")(function* (+ asset: {+ readonly path: string;+ readonly download?: boolean;+ readonly fileName?: string;+ readonly mimeType?: string;+ },+ rangeHeader?: string,+ ifRangeHeader?: string,+) {+ const headers = assetResponseHeaders(asset.path, asset);+ if (headers["Content-Type"]?.toLowerCase().startsWith("video/")) {+ headers["Accept-Ranges"] = "bytes";+ // If-Range requires a matching validator. A full response is safe when we cannot validate it.+ if (rangeHeader && !ifRangeHeader) {+ const fs = yield* FileSystem.FileSystem;+ const info = yield* fs.stat(asset.path);+ const range = assetByteRange(rangeHeader, info.size);+ if (range?._tag === "Unsatisfiable") {+ return HttpServerResponse.empty({+ status: 416,+ headers: { ...headers, "Content-Range": `bytes */${info.size}` },+ });+ }+ if (range?._tag === "Range") {+ return yield* HttpServerResponse.file(asset.path, {+ status: 206,+ offset: range.offset,+ bytesToRead: range.bytesToRead,+ headers: { ...headers, "Content-Range": range.contentRange },+ });+ }+ }+ }+ return yield* HttpServerResponse.file(asset.path, { status: 200, headers });+});+export const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {global: true,});@@ -277,19 +334,11 @@ export const assetRouteLayer = HttpRouter.add(if (!asset) {return HttpServerResponse.text("Not Found", { status: 404 });}- return yield* HttpServerResponse.file(asset.path, {- status: 200,- headers: assetResponseHeaders(- asset.path,- asset.download || asset.mimeType !== undefined- ? {- ...(asset.download ? { download: true } : {}),- ...(asset.fileName !== undefined ? { fileName: asset.fileName } : {}),- ...(asset.mimeType !== undefined ? { mimeType: asset.mimeType } : {}),- }- : undefined,- ),- }).pipe(+ return yield* assetFileResponse(+ asset,+ request.method === "GET" ? request.headers.range : undefined,+ request.headers["if-range"],+ ).pipe(Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),);}),diff --git a/apps/web/src/types.ts b/apps/web/src/types.tsindex f5727980a25..8638cade733 100644--- a/apps/web/src/types.ts+++ b/apps/web/src/types.ts@@ -17,6 +17,9 @@ import type {EnvironmentThread,EnvironmentThreadShell,} from "@t3tools/client-runtime/state/shell";+import { videoMimeType } from "@t3tools/shared/video";++export { videoMimeType } from "@t3tools/shared/video";export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";@@ -59,27 +62,6 @@ export function isFileAttachment(attachment: ChatAttachment): attachment is Chatreturn attachment.type === "file";}-const VIDEO_MIME_TYPE_BY_EXTENSION: Readonly<Record<string, string>> = {- avi: "video/x-msvideo",- m4v: "video/mp4",- mkv: "video/x-matroska",- mov: "video/quicktime",- mp4: "video/mp4",- ogv: "video/ogg",- webm: "video/webm",-};--export function videoMimeType(- attachment: Pick<ChatFileAttachment, "name" | "mimeType">,-): string | null {- const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? "";- if (mimeType.startsWith("video/")) return mimeType;- const dotIndex = attachment.name.lastIndexOf(".");- return dotIndex < 0- ? null- : (VIDEO_MIME_TYPE_BY_EXTENSION[attachment.name.slice(dotIndex + 1).toLowerCase()] ?? null);-}-export function isVideoAttachment(attachment: ChatFileAttachment): boolean {return videoMimeType(attachment) !== null;}diff --git a/docs/internals/mobile-navigation.md b/docs/internals/mobile-navigation.mdindex 86c61921ffc..ebc19d82d6d 100644--- a/docs/internals/mobile-navigation.md+++ b/docs/internals/mobile-navigation.md@@ -1,4 +1,4 @@-# Mobile navigation headers+# Mobile navigationThe iOS Home and thread routes share the root native stack in[`Stack.tsx`](../../apps/mobile/src/Stack.tsx). Keeping them in one navigation@@ -48,3 +48,59 @@ iOS `MenuView` action, including nested actions. The menu library's Fabric bridgrendering `MenuView` directly. Explicit colors are preserved, and destructiveactions default to the theme's danger foreground color. Native stack header menususe a separate implementation and do not need this workaround.++## Native media presentations++`PresentationSource` in `NativePresentation` registers a thumbnail for AVKit's+full-screen entry and UIKit's share sheet. Wrap the thumbnail as its single child+and pass the stable identifier to the presentation. The registry keeps weak+references to source views; recycled or compact composer thumbnails can register+the same identifier. Identifiers must distinguish simultaneously visible attachments.+This source registration does not own playback and can be reused by a future image+viewer. Android uses a regular view.++On iOS, video previews mount `AVPlayerViewController` temporarily inside the+registered source and enter full screen through AVKit. AVKit+owns that zoom, its playback controls, Close button, and interactive dismissal.+Do not replace AVKit's transition with `preferredTransition`: in the iOS 27+simulator, that leaves native Close unable to exit full screen. When the source is unavailable,+the player uses a standard modal presentation. Programmatic entry uses the same+guarded `enterFullScreenAnimated:completionHandler:` selector as Expo Video;+if that selector is unavailable, the player also falls back to a standard modal.+Images retain their existing viewer.++Received videos open directly from their signed asset URL. AVKit handles buffering;+the client does not download the entire file or show a separate opening overlay before+presentation. The URL is captured once per preview so credential refresh does not+restart playback. Saving or sharing still downloads the original file.++The native presentation promise completes after dismissal. Local draft previews+hold their file lease until that promise settles. The iOS preview component requests+native dismissal when its source screen unmounts. Playback pauses in the background.+AVPlayer activates audio as playback starts. The presenter pauses and releases+its own player on close, then restores the previous audio-session configuration+if no other component changed it during playback. It does not deactivate the+shared session, which may still serve another player or recorder. Android retains+its React Native modal and Expo Video player.++`shareFileFromSource` uses the same source registration to anchor UIKit's activity+controller. Its promise completes when the native share flow finishes, keeping+the existing attachment lease and foreground handoff active for that duration.+Android uses Expo Sharing. On iOS, received and draft video attachments expose+Save or share through `VideoAttachmentMenu`. The attachment supplies the source+identifier, and the native share presentation inherits its appearance. AVKit's+iOS playback controls do not expose a public custom-share-action API.++Video attachment thumbnails use Expo Video's native frame extraction and Expo Image.+Received attachments use their signed asset URL; drafts retain and resolve their local file+until extraction ends. Extraction is serial; temporary players never play or change audio settings. Leaving the screen cancels+pending work; a 15-second limit prevents an unreachable source from holding up the queue.+The client keeps at most 32 native images, each bounded to 480 pixels per side, keyed by+environment and attachment identity rather than expiring URLs. Images still displayed keep+their own references when evicted from that cache.++The asset HTTP route supports single byte ranges for videos so iOS can read metadata and+frames without first downloading the whole file. Normal downloads keep their full response;+unsupported ranges and conditional `If-Range` requests also fall back to the full file.+An older environment without range support may still show the play-card fallback. Thumbnail+failure never disables playback or sharing.diff --git a/docs/user/composer.md b/docs/user/composer.mdindex 6f14245ae27..62db0b073ff 100644--- a/docs/user/composer.md+++ b/docs/user/composer.md@@ -22,8 +22,15 @@ T3 Code from other apps through the system share sheet. Mobile uploads happen whsends, so queued messages keep their files until they deliver. Select a received file on mobileto save it or open it in another app through the system share sheet.-On web and desktop, select a video attachment before or after sending to play it with the browser's-built-in controls. Playback depends on the video formats and codecs that the browser supports.+Select a video attachment before or after sending to play it. Web and desktop use the browser's+built-in controls. On mobile, videos open in a full-screen player with native playback controls.+Supported videos show a thumbnail in the conversation and composer.+On iOS, received videos stream from their environment as they play. Supported formats and codecs+depend on the browser or device; you can save an unsupported video to open it in another app.++On iOS, the system player zooms from the attachment. Swipe down or tap Close to return to the+conversation or draft. Touch and hold the attachment, then choose **Save or share video** to open+the system share options. On Android, use **Save or share video** inside the preview.On web and desktop, if you reload before a file finishes uploading, the draft keeps the file's nameand shows **Attach again** next to it. Attach the file again or remove it, then send.diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex eeaa5f59e08..aeba7e602a8 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -199,6 +199,10 @@"types": "./src/filePreview.ts","import": "./src/filePreview.ts"},+ "./video": {+ "types": "./src/video.ts",+ "import": "./src/video.ts"+ },"./chatList": {"types": "./src/chatList.ts","import": "./src/chatList.ts"diff --git a/packages/shared/src/video.test.ts b/packages/shared/src/video.test.tsnew file mode 100644index 00000000000..b550033e298--- /dev/null+++ b/packages/shared/src/video.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from "vite-plus/test";++import { videoMimeType } from "./video.ts";++describe("videoMimeType", () => {+ it("recognizes a saved video with a generic picker MIME type", () => {+ expect(videoMimeType({ name: "Recording.MOV", mimeType: "application/octet-stream" })).toBe(+ "video/quicktime",+ );+ });++ it("keeps an explicit video MIME type authoritative and removes parameters", () => {+ expect(videoMimeType({ name: "recording.mp4", mimeType: " VIDEO/WebM; codecs=vp9 " })).toBe(+ "video/webm",+ );+ });++ it.each(["README", "report.pdf", "file.constructor", "file.__proto__"])(+ "does not mistake %s for a video",+ (name) => {+ expect(videoMimeType({ name, mimeType: "application/octet-stream" })).toBeNull();+ },+ );+});diff --git a/packages/shared/src/video.ts b/packages/shared/src/video.tsnew file mode 100644index 00000000000..634bc29ed6d--- /dev/null+++ b/packages/shared/src/video.ts@@ -0,0 +1,22 @@+const VIDEO_MIME_TYPE_BY_EXTENSION = new Map([+ ["avi", "video/x-msvideo"],+ ["m4v", "video/mp4"],+ ["mkv", "video/x-matroska"],+ ["mov", "video/quicktime"],+ ["mp4", "video/mp4"],+ ["ogv", "video/ogg"],+ ["webm", "video/webm"],+]);++/** Recognizes videos even when the file picker omitted their MIME type. */+export function videoMimeType(attachment: {+ readonly name: string;+ readonly mimeType: string;+}): string | null {+ const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? "";+ if (mimeType.startsWith("video/")) return mimeType;+ const dotIndex = attachment.name.lastIndexOf(".");+ return dotIndex < 0+ ? null+ : (VIDEO_MIME_TYPE_BY_EXTENSION.get(attachment.name.slice(dotIndex + 1).toLowerCase()) ?? null);+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 54e0b121859..4a1a2067a83 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -331,6 +331,9 @@ importers:expo-device:specifier: ~57.0.1version: 57.0.1([email protected])+ expo-document-picker:+ specifier: ~57.0.1+ version: 57.0.1([email protected])expo-file-system:specifier: ~57.0.6version: 57.0.6([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))@@ -382,6 +385,9 @@ importers:expo-updates:specifier: ~57.0.19version: 57.0.19([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ expo-video:+ specifier: ~57.0.3+ version: 57.0.3([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])expo-web-browser:specifier: ~57.0.2version: 57.0.2([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))@@ -6562,6 +6568,11 @@ packages:peerDependencies:expo: '*'+ resolution: {integrity: sha512-qBwM5oxDZ3I9kwFD3pUE1oK/WNv9artoEKO6UpqhQgNRr0XA1ALRVWYjkF4+ge9lUNDRehjTm/jenINkzqg84g==}+ peerDependencies:+ expo: '*'+resolution: {integrity: sha512-EfFiqUr0o9TvTOgMbqDiV1oIdG/d7kirhqtwa7roGmm9wF+CpXUz20d9YGzO6KzJWUYgdUgu4B6Ocv0jNJUdnQ==}@@ -6731,6 +6742,13 @@ packages:expo-dev-client:optional: true+ resolution: {integrity: sha512-Z+rLdBSzICwoHm/HUxND5fm5nfgqiB+QPWAOKxmA8ScYwvxG1UGjZ6OaayvPc3GkT4aucsbycmFO0uUv/qnIhg==}+ peerDependencies:+ expo: '*'+ react: '*'+ react-native: '*'+resolution: {integrity: sha512-3vl5kvd7PB48ub6PpNIJUuPxO8xVa6D8RnIgNba6SXRwqFprOfeEZgwTgtm41kz0AAtvMOztUVNEUkwrHKjqMQ==}peerDependencies:@@ -16434,6 +16452,10 @@ snapshots:expo: 57.0.18(f9c992a5d7c53d81398568d3950992dc)ua-parser-js: 0.7.41+ dependencies:+ expo: 57.0.18(f9c992a5d7c53d81398568d3950992dc)+[email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])):@@ -16674,6 +16696,12 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):+ dependencies:+ expo: 57.0.18(f9c992a5d7c53d81398568d3950992dc)+ react: 19.2.3+ react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])+[email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])):dependencies:expo: 57.0.18(f9c992a5d7c53d81398568d3950992dc)