Skip to content
TypeScript

fix(media): preview host files and stream videos across clients (#9023)

Julius Marmingebeae2147a948
diff --git a/apps/desktop/src/electron/ElectronProtocol.test.ts b/apps/desktop/src/electron/ElectronProtocol.test.ts
index 585dd7e7ea1..a5c03e0b933 100644
--- a/apps/desktop/src/electron/ElectronProtocol.test.ts
+++ b/apps/desktop/src/electron/ElectronProtocol.test.ts
@@ -225,7 +225,7 @@ describe("ElectronProtocol", () => {
"http:",
"https:",
]);
- assert.deepEqual(directives["media-src"], ["'self'", "t3code:", "blob:"]);
+ assert.deepEqual(directives["media-src"], ["'self'", "t3code:", "blob:", "http:", "https:"]);
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
});
});
diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.ts
index 845f03dba5d..fabd598d7ff 100644
--- a/apps/desktop/src/electron/ElectronProtocol.ts
+++ b/apps/desktop/src/electron/ElectronProtocol.ts
@@ -87,7 +87,7 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
`script-src ${scriptSources.join(" ")}`,
`connect-src ${connectSources.join(" ")}`,
`img-src 'self' ${input.scheme}: blob: data: http: https:`,
- `media-src 'self' ${input.scheme}: blob:`,
+ `media-src 'self' ${input.scheme}: blob: http: https:`,
"style-src 'self' 'unsafe-inline'",
`font-src 'self' ${input.scheme}: data:`,
"worker-src 'self' blob:",
@@ -118,6 +118,7 @@ export function registerDesktopSchemePrivilegesSync(): void {
secure: true,
supportFetchAPI: true,
corsEnabled: true,
+ stream: true,
},
},
{
@@ -127,6 +128,7 @@ export function registerDesktopSchemePrivilegesSync(): void {
secure: true,
supportFetchAPI: true,
corsEnabled: true,
+ stream: true,
},
},
]);
diff --git a/apps/mobile/modules/t3-markdown-text/assets/file-icons/pierre_video.png b/apps/mobile/modules/t3-markdown-text/assets/file-icons/pierre_video.png
new file mode 100644
index 00000000000..673c95d8b36
Binary files /dev/null and b/apps/mobile/modules/t3-markdown-text/assets/file-icons/pierre_video.png differ
diff --git a/apps/mobile/modules/t3-markdown-text/package.json b/apps/mobile/modules/t3-markdown-text/package.json
index d51b6c5d9ff..7ab3f1fbde8 100644
--- a/apps/mobile/modules/t3-markdown-text/package.json
+++ b/apps/mobile/modules/t3-markdown-text/package.json
@@ -26,6 +26,8 @@
"./types": "./src/SelectableMarkdownText.types.ts"
},
"peerDependencies": {
+ "@t3tools/client-runtime": "*",
+ "@t3tools/shared": "*",
"expo-asset": "*",
"expo-clipboard": "*",
"expo-haptics": "*",
diff --git a/apps/mobile/modules/t3-markdown-text/scripts/sync-pierre-file-icons.mjs b/apps/mobile/modules/t3-markdown-text/scripts/sync-pierre-file-icons.mjs
index 2c2cc43bc65..8510ce97ba6 100644
--- a/apps/mobile/modules/t3-markdown-text/scripts/sync-pierre-file-icons.mjs
+++ b/apps/mobile/modules/t3-markdown-text/scripts/sync-pierre-file-icons.mjs
@@ -66,6 +66,7 @@ const colors = {
terraform: "#693acf",
text: "#84848a",
typescript: "#1a85d4",
+ video: "#a631be",
vite: "#a631be",
vscode: "#1a85d4",
vue: "#199f43",
@@ -83,6 +84,7 @@ const customIcons = {
pnpm: "t3-file-icon-pnpm",
readme: "t3-file-icon-readme",
tsconfig: "t3-file-icon-tsconfig",
+ video: "t3-file-icon-video",
};
function symbolFromSprite(sprite, id) {
diff --git a/apps/mobile/modules/t3-markdown-text/src/markdownFileIcons.generated.ts b/apps/mobile/modules/t3-markdown-text/src/markdownFileIcons.generated.ts
index 608fa08c486..463e00207d9 100644
--- a/apps/mobile/modules/t3-markdown-text/src/markdownFileIcons.generated.ts
+++ b/apps/mobile/modules/t3-markdown-text/src/markdownFileIcons.generated.ts
@@ -51,6 +51,7 @@ export const MARKDOWN_FILE_ICON_SOURCES = {
text: require("../assets/file-icons/pierre_text.png"),
tsconfig: require("../assets/file-icons/pierre_tsconfig.png"),
typescript: require("../assets/file-icons/pierre_typescript.png"),
+ video: require("../assets/file-icons/pierre_video.png"),
vite: require("../assets/file-icons/pierre_vite.png"),
vscode: require("../assets/file-icons/pierre_vscode.png"),
vue: require("../assets/file-icons/pierre_vue.png"),
diff --git a/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts b/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts
index 20637c6ba0f..0caa24c3404 100644
--- a/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts
+++ b/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts
@@ -1,3 +1,9 @@
+import {
+ inlineCodeFilePathCandidate,
+ isConventionalFilePosition,
+} from "@t3tools/client-runtime/markdown-links";
+import { videoMimeType } from "@t3tools/shared/video";
+
import type { MARKDOWN_FILE_ICON_SOURCES } from "./markdownFileIcons.generated";
const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
@@ -253,15 +259,22 @@ function normalizeDestination(value: string): string {
return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
}
+/** Native link and media APIs have no document scheme to inherit from protocol-relative URLs. */
+export function normalizeNativeMarkdownUrl(value: string): string {
+ return value.startsWith("//") ? `https:${value}` : value;
+}
+
function fileUrlTarget(href: string): { readonly path: string; readonly hash: string } | null {
try {
const parsed = new URL(href);
if (parsed.protocol.toLowerCase() !== "file:") {
return null;
}
- const path = /^\/[A-Za-z]:[\\/]/.test(parsed.pathname)
- ? parsed.pathname.slice(1)
+ const uncHostname = parsed.hostname.toLowerCase() === "localhost" ? "" : parsed.hostname;
+ const rawPath = uncHostname
+ ? `\\\\${uncHostname}${parsed.pathname.replaceAll("/", "\\")}`
: parsed.pathname;
+ const path = /^\/[A-Za-z]:[\\/]/.test(rawPath) ? rawPath.slice(1) : rawPath;
return { path, hash: parsed.hash };
} catch {
return null;
@@ -327,6 +340,7 @@ function looksLikeFilePath(value: string): boolean {
if (FILE_ICON_BY_NAME[value.replace(POSITION_SUFFIX_PATTERN, "").toLowerCase()]) {
return true;
}
+ if (isConventionalFilePosition(value)) return true;
return RELATIVE_FILE_PATH_PATTERN.test(value) || RELATIVE_FILE_NAME_PATTERN.test(value);
}
@@ -338,6 +352,7 @@ function fileLabel(value: string): string {
export function resolveMarkdownFileIcon(value: string): MarkdownFileIcon {
const basename = fileLabel(value).replace(POSITION_SUFFIX_PATTERN, "").toLowerCase();
+ if (videoMimeType({ name: basename, mimeType: "" }) !== null) return "video";
const exactIcon = FILE_ICON_BY_NAME[basename];
if (exactIcon) return exactIcon;
if (basename.startsWith("tsconfig.") && basename.endsWith(".json")) {
@@ -354,7 +369,7 @@ export function resolveMarkdownFileIcon(value: string): MarkdownFileIcon {
export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPresentation {
const normalized = normalizeDestination(href);
try {
- const parsed = new URL(normalized);
+ const parsed = new URL(normalizeNativeMarkdownUrl(normalized));
if (parsed.protocol === "http:" || parsed.protocol === "https:") {
return {
kind: "external",
@@ -399,3 +414,13 @@ export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPrese
href: /^(?:mailto|tel):/i.test(normalized) ? normalized : null,
};
}
+
+/** Backticks become file references only when the shared path heuristic recognizes the whole span. */
+export function resolveMarkdownInlineCodePresentation(
+ content: string,
+): Extract<MarkdownLinkPresentation, { readonly kind: "file" }> | null {
+ const candidate = inlineCodeFilePathCandidate(content);
+ if (candidate === null) return null;
+ const presentation = resolveMarkdownLinkPresentation(candidate);
+ return presentation.kind === "file" ? presentation : null;
+}
diff --git a/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts b/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts
index 8db904b5a6c..2b39ac20159 100644
--- a/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts
+++ b/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts
@@ -1,7 +1,11 @@
import type { MarkdownNode } from "react-native-nitro-markdown/headless";
import type { SelectableMarkdownSkill } from "./SelectableMarkdownText.types";
-import { resolveMarkdownLinkPresentation, type MarkdownFileIcon } from "./markdownLinks";
+import {
+ resolveMarkdownInlineCodePresentation,
+ resolveMarkdownLinkPresentation,
+ type MarkdownFileIcon,
+} from "./markdownLinks";
export interface NativeMarkdownTextRun {
readonly text: string;
@@ -283,8 +287,17 @@ function appendNode(
return appendRun(runs, textNodeContent(nodeTextContent(node)), context);
case "html_inline":
return appendRun(runs, inlineHtmlText(nodeTextContent(node)), context);
- case "code_inline":
- return appendRun(runs, nodeTextContent(node), { ...context, code: true });
+ case "code_inline": {
+ const content = nodeTextContent(node);
+ const presentation = context.href ? null : resolveMarkdownInlineCodePresentation(content);
+ return presentation
+ ? appendRun(runs, presentation.label, {
+ ...context,
+ href: presentation.href,
+ fileIcon: presentation.icon,
+ })
+ : appendRun(runs, content, { ...context, code: true });
+ }
case "soft_break":
return appendRun(runs, " ", context);
case "line_break":
diff --git a/apps/mobile/src/components/FilePreview.ios.tsx b/apps/mobile/src/components/FilePreview.ios.tsx
index c7740104fe6..c2f5a6d72cc 100644
--- a/apps/mobile/src/components/FilePreview.ios.tsx
+++ b/apps/mobile/src/components/FilePreview.ios.tsx
@@ -3,6 +3,7 @@ import { useEffect, useEffectEvent, useId } from "react";
import { Alert } from "react-native";
import type { ResolvedFilePreviewSource } from "./FilePreviewModal";
+import { MediaImagePreview } from "./MediaImagePreview";
const NativeControls = requireNativeModule<{
presentFile(
@@ -14,7 +15,7 @@ const NativeControls = requireNativeModule<{
dismissFile(identifier: string): Promise<void>;
}>("T3NativeControls");
-export function FilePreview(props: {
+function NativeFilePreview(props: {
readonly source: ResolvedFilePreviewSource;
readonly onRequestClose: () => void;
}) {
@@ -41,3 +42,14 @@ export function FilePreview(props: {
return null;
}
+
+export function FilePreview(props: {
+ readonly source: ResolvedFilePreviewSource;
+ readonly onRequestClose: () => void;
+}) {
+ return props.source.kind === "image" && props.source.actionsSource ? (
+ <MediaImagePreview {...props} />
+ ) : (
+ <NativeFilePreview {...props} />
+ );
+}
diff --git a/apps/mobile/src/components/FilePreview.tsx b/apps/mobile/src/components/FilePreview.tsx
index f10bfb8b3e6..8240c4a6ad3 100644
--- a/apps/mobile/src/components/FilePreview.tsx
+++ b/apps/mobile/src/components/FilePreview.tsx
@@ -4,6 +4,7 @@ import ImageViewing from "react-native-image-viewing";
import { downloadAndShareAttachment, shareLocalAttachment } from "../lib/attachmentDownload";
import type { ResolvedFilePreviewSource } from "./FilePreviewModal";
+import { MediaImagePreview } from "./MediaImagePreview";
function PdfPreview(props: {
readonly source: ResolvedFilePreviewSource;
@@ -39,6 +40,7 @@ export function FilePreview(props: {
readonly onRequestClose: () => void;
}) {
if (props.source.kind === "pdf") return <PdfPreview {...props} />;
+ if (props.source.actionsSource) return <MediaImagePreview {...props} />;
return (
<ImageViewing
images={[{ uri: props.source.uri }]}
diff --git a/apps/mobile/src/components/FilePreviewModal.tsx b/apps/mobile/src/components/FilePreviewModal.tsx
index c9df7e892c2..c8a6d429194 100644
--- a/apps/mobile/src/components/FilePreviewModal.tsx
+++ b/apps/mobile/src/components/FilePreviewModal.tsx
@@ -5,6 +5,7 @@ import { Alert, Keyboard } from "react-native";
import type { DraftComposerFileAttachment } from "../lib/composerImages";
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
+import type { MediaActionsSource } from "../lib/mediaActions";
import { useAssetUrlState } from "../state/assets";
import { usePreparedConnection } from "../state/session";
import { FilePreview } from "./FilePreview";
@@ -14,6 +15,8 @@ export interface ResolvedFilePreviewSource {
readonly uri: string;
readonly name?: string;
readonly sourceIdentifier?: string;
+ readonly srcFragment?: string;
+ readonly actionsSource?: MediaActionsSource;
}
export type FilePreviewSource = Omit<ResolvedFilePreviewSource, "uri"> &
@@ -40,13 +43,18 @@ function ResolvedFilePreview(props: {
(connection._tag === "None" || asset._tag === "Failure");
useEffect(() => Keyboard.dismiss(), []);
useEffect(() => {
- if (uri === null && asset._tag === "Success") setUri(asset.url);
- }, [uri, asset]);
+ if (uri === null && asset._tag === "Success") setUri(asset.url + (source.srcFragment ?? ""));
+ }, [uri, asset, source.srcFragment]);
useEffect(() => {
if (!failed) return;
- Alert.alert("Could not open preview", "Reconnect to this environment and try again.");
+ Alert.alert(
+ "Could not open preview",
+ connection._tag === "None"
+ ? "Reconnect to this environment and try again."
+ : "The file could not be loaded. It may have been moved or deleted.",
+ );
onRequestClose();
- }, [failed]);
+ }, [failed, connection._tag]);
useEffect(() => {
if (!("attachment" in source)) return;
const controller = new AbortController();
diff --git a/apps/mobile/src/components/MediaActionsMenu.tsx b/apps/mobile/src/components/MediaActionsMenu.tsx
new file mode 100644
index 00000000000..a4b44e85258
--- /dev/null
+++ b/apps/mobile/src/components/MediaActionsMenu.tsx
@@ -0,0 +1,43 @@
+import { MenuView } from "@react-native-menu/menu";
+import type { ReactElement } from "react";
+import { Platform, View, type PressableProps } from "react-native";
+
+import type { useMediaActions } from "../lib/mediaActions";
+import { SymbolView } from "./AppSymbol";
+import { ControlPillMenu } from "./ControlPill";
+
+export function MediaActionsMenu(props: {
+ readonly media: ReturnType<typeof useMediaActions>;
+ readonly inModal?: boolean;
+ readonly children?: ReactElement<PressableProps>;
+}) {
+ if (props.media.actions.length === 0) return props.children ?? null;
+ // Android's normal anchored menu lives in the app-root portal, behind native modals.
+ const nativeAndroidMenu = props.inModal && Platform.OS === "android";
+ const Menu = nativeAndroidMenu ? MenuView : ControlPillMenu;
+ return (
+ <Menu
+ title={props.media.title}
+ shouldOpenOnLongPress={props.children !== undefined}
+ actions={props.media.actions.map(({ id, title, disabled }) => ({
+ id,
+ title,
+ attributes: { disabled: disabled ?? false },
+ }))}
+ onPressAction={({ nativeEvent }) => {
+ props.media.actions.find(({ id }) => id === nativeEvent.event)?.run();
+ }}
+ >
+ {props.children ?? (
+ <View
+ accessible
+ accessibilityRole="button"
+ accessibilityLabel="Media actions"
+ className="min-h-11 min-w-11 items-center justify-center rounded-md bg-black/60"
+ >
+ <SymbolView name="ellipsis" size={20} tintColor="#ffffff" type="monochrome" />
+ </View>
+ )}
+ </Menu>
+ );
+}
diff --git a/apps/mobile/src/components/MediaImagePreview.tsx b/apps/mobile/src/components/MediaImagePreview.tsx
new file mode 100644
index 00000000000..5bdc9140ddc
--- /dev/null
+++ b/apps/mobile/src/components/MediaImagePreview.tsx
@@ -0,0 +1,61 @@
+import { createContext, useContext } from "react";
+import { Pressable, View } from "react-native";
+import ImageViewing from "react-native-image-viewing";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+
+import { useMediaActions } from "../lib/mediaActions";
+import { AppText } from "./AppText";
+import { SymbolView } from "./AppSymbol";
+import type { ResolvedFilePreviewSource } from "./FilePreviewModal";
+import { MediaActionsMenu } from "./MediaActionsMenu";
+import { MediaSourceCaption } from "./MediaSourceCaption";
+
+type MediaImagePreviewProps = {
+ readonly source: ResolvedFilePreviewSource;
+ readonly onRequestClose: () => void;
+};
+
+const ImagePreviewContext = createContext<MediaImagePreviewProps | null>(null);
+
+function ImagePreviewHeader() {
+ const props = useContext(ImagePreviewContext)!;
+ const insets = useSafeAreaInsets();
+ const mediaActions = useMediaActions(props.source.actionsSource, props.onRequestClose);
+ return (
+ <View className="bg-black/70" style={{ paddingTop: insets.top }}>
+ <View className="flex-row items-center gap-2 px-3">
+ <AppText className="flex-1 text-base text-white" numberOfLines={2}>
+ {props.source.name ?? "Image"}
+ </AppText>
+ <MediaActionsMenu media={mediaActions} inModal />
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel="Close image"
+ onPress={props.onRequestClose}
+ className="min-h-11 min-w-11 items-center justify-center"
+ >
+ <SymbolView name="xmark" size={20} tintColor="#ffffff" type="monochrome" />
+ </Pressable>
+ </View>
+ <MediaSourceCaption source={mediaActions.title} />
+ </View>
+ );
+}
+
+/** Chat and workspace media retain source actions on both platforms; other files use native previews. */
+export function MediaImagePreview(props: MediaImagePreviewProps) {
+ return (
+ <ImagePreviewContext value={props}>
+ <ImageViewing
+ images={[{ uri: props.source.uri }]}
+ imageIndex={0}
+ visible
+ presentationStyle="fullScreen"
+ onRequestClose={props.onRequestClose}
+ swipeToCloseEnabled
+ doubleTapToZoomEnabled
+ HeaderComponent={ImagePreviewHeader}
+ />
+ </ImagePreviewContext>
+ );
+}
diff --git a/apps/mobile/src/components/MediaSourceCaption.tsx b/apps/mobile/src/components/MediaSourceCaption.tsx
new file mode 100644
index 00000000000..76c24290d34
--- /dev/null
+++ b/apps/mobile/src/components/MediaSourceCaption.tsx
@@ -0,0 +1,19 @@
+import { ScrollView } from "react-native";
+
+import { AppText } from "./AppText";
+
+/** Keep the original reference readable without letting long URLs displace the preview. */
+export function MediaSourceCaption(props: { readonly source: string | undefined }) {
+ if (!props.source) return null;
+ return (
+ <ScrollView
+ style={{ maxHeight: 88, flexGrow: 0 }}
+ contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 8 }}
+ nestedScrollEnabled
+ >
+ <AppText selectable className="text-xs text-white/70">
+ {props.source}
+ </AppText>
+ </ScrollView>
+ );
+}
diff --git a/apps/mobile/src/components/MediaVideoPlayer.tsx b/apps/mobile/src/components/MediaVideoPlayer.tsx
new file mode 100644
index 00000000000..a065f75e139
--- /dev/null
+++ b/apps/mobile/src/components/MediaVideoPlayer.tsx
@@ -0,0 +1,187 @@
+import { useIsFocused } from "@react-navigation/native";
+import { useEvent } from "expo";
+import { useVideoPlayer, VideoView } from "expo-video";
+import { useEffect, useEffectEvent, useRef, useState } from "react";
+import { ActivityIndicator, AppState, Pressable, View } from "react-native";
+
+import { AppText } from "./AppText";
+import { SymbolView } from "./AppSymbol";
+import { VideoThumbnailImage } from "./VideoThumbnailImage";
+import { useMediaActions, type MediaActionsSource } from "../lib/mediaActions";
+import { MediaActionsMenu } from "./MediaActionsMenu";
+
+/** Loads only after Play or opening the viewer. Source replacement never starts playback itself. */
+function LoadedMediaVideo(props: {
+ readonly uri: string;
+ readonly resolvePlaybackUri?: () => Promise<string | null>;
+ readonly playRequested: boolean;
+ readonly paused: boolean;
+}) {
+ const focused = useIsFocused();
+ const active = useRef(focused && AppState.currentState === "active");
+ const [attempt, setAttempt] = useState(0);
+ // Expo's Android player also reports completed playback as idle.
+ const [loadState, setLoadState] = useState<"pending" | "complete" | "error">("pending");
+ const player = useVideoPlayer(null, (player) => {
+ player.staysActiveInBackground = false;
+ player.bufferOptions = { preferredForwardBufferDuration: 5 };
+ });
+ const { status } = useEvent(player, "statusChange", { status: player.status });
+ const loadSource = useEffectEvent(async (signal: AbortSignal) => {
+ const uri = props.resolvePlaybackUri ? await props.resolvePlaybackUri() : props.uri;
+ if (signal.aborted) return;
+ if (uri === null) throw new Error("Video unavailable");
+ player.pause();
+ await player.replaceAsync({ uri, contentType: "progressive" });
+ if (!signal.aborted && props.playRequested && active.current) player.play();
+ });
+
+ useEffect(() => {
+ active.current = focused && !props.paused && AppState.currentState === "active";
+ if (!active.current) player.pause();
+ const subscription = AppState.addEventListener("change", (state) => {
+ active.current = focused && !props.paused && state === "active";
+ if (!active.current) player.pause();
+ });
+ return () => subscription.remove();
+ }, [focused, player, props.paused]);
+
+ useEffect(() => {
+ const controller = new AbortController();
+ setLoadState("pending");
+ // A renewed signature is used on Retry, not as a reason to reset the native player.
+ void loadSource(controller.signal).then(
+ () => {
+ if (!controller.signal.aborted) setLoadState("complete");
+ },
+ () => {
+ if (!controller.signal.aborted) setLoadState("error");
+ },
+ );
+ return () => controller.abort();
+ }, [player, props.playRequested, attempt]);
+
+ return (
+ <View collapsable={false} style={{ flex: 1 }}>
+ <VideoView
+ player={player}
+ style={{ width: "100%", height: "100%" }}
+ surfaceType="textureView"
+ nativeControls
+ contentFit="contain"
+ fullscreenOptions={{ enable: true }}
+ allowsPictureInPicture={false}
+ />
+ {loadState === "error" || (loadState === "complete" && status === "error") ? (
+ <View className="absolute inset-0 items-center justify-center gap-2 bg-black px-4">
+ <AppText className="text-center text-sm text-white/80">Video unavailable</AppText>
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel="Retry video"
+ onPress={() => setAttempt((value) => value + 1)}
+ className="min-h-11 justify-center px-4"
+ >
+ <AppText className="text-sm text-white">Retry</AppText>
+ </Pressable>
+ </View>
+ ) : loadState === "pending" || status === "loading" ? (
+ <View pointerEvents="none" className="absolute inset-0 items-center justify-center">
+ <ActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />
+ </View>
+ ) : null}
+ </View>
+ );
+}
+
+interface MediaVideoPlayerProps {
+ readonly uri: string | null;
+ readonly resolvePlaybackUri?: () => Promise<string | null>;
+ readonly name: string;
+ readonly thumbnailKey: string;
+ readonly thumbnailVisible?: boolean;
+ readonly unavailable?: boolean;
+ readonly expanded?: boolean;
+ readonly paused?: boolean;
+ readonly onExpand?: () => void;
+ readonly actionsSource?: MediaActionsSource;
+}
+
+function MediaVideoPlayerContent(props: MediaVideoPlayerProps) {
+ const mediaActions = useMediaActions(props.actionsSource);
+ const [playbackUri, setPlaybackUri] = useState<string | null>(props.expanded ? props.uri : null);
+ // Keep an opened player mounted while signing or reconnecting temporarily has no usable URL.
+ if (playbackUri === null && props.expanded && props.uri !== null) setPlaybackUri(props.uri);
+
+ return (
+ <View
+ collapsable={false}
+ className="overflow-hidden rounded-[10px] bg-black"
+ style={props.expanded ? { flex: 1 } : { width: "100%", maxWidth: 480, aspectRatio: 16 / 9 }}
+ >
+ {playbackUri ? (
+ <LoadedMediaVideo
+ uri={props.uri ?? playbackUri}
+ resolvePlaybackUri={props.resolvePlaybackUri}
+ playRequested={!props.expanded}
+ paused={(props.paused ?? false) || mediaActions.sharing}
+ />
+ ) : (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={`Play ${props.name}`}
+ accessibilityState={{ disabled: props.uri === null || props.unavailable === true }}
+ disabled={props.uri === null || props.unavailable === true}
+ onPress={() => setPlaybackUri(props.uri)}
+ className="flex-1 items-center justify-center gap-2 px-4"
+ >
+ {!props.unavailable ? (
+ <VideoThumbnailImage
+ cacheKey={props.thumbnailKey}
+ source={props.thumbnailVisible === false ? null : props.uri}
+ contentFit="contain"
+ />
+ ) : null}
+ {props.unavailable ? (
+ <AppText className="text-sm text-white/80">Video unavailable</AppText>
+ ) : props.uri === null ? (
+ <ActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />
+ ) : (
+ <>
+ <View className="size-12 items-center justify-center rounded-full bg-black/60">
+ <SymbolView name="play" size={28} tintColor="#ffffff" type="monochrome" />
+ </View>
+ <AppText
+ className="rounded bg-black/60 px-2 py-1 text-center text-xs text-white"
+ numberOfLines={2}
+ >
+ {props.name}
+ </AppText>
+ </>
+ )}
+ </Pressable>
+ )}
+ {props.onExpand ? (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={`Expand ${props.name}`}
+ onPress={() => {
+ setPlaybackUri(null);
+ props.onExpand?.();
+ }}
+ className="absolute right-1 top-1 min-h-11 min-w-11 items-center justify-center rounded-md bg-black/60 px-2"
+ >
+ <AppText className="text-xs text-white">Expand</AppText>
+ </Pressable>
+ ) : null}
+ {props.actionsSource ? (
+ <View className="absolute left-1 top-1">
+ <MediaActionsMenu media={mediaActions} inModal={props.expanded} />
+ </View>
+ ) : null}
+ </View>
+ );
+}
+
+export function MediaVideoPlayer(props: MediaVideoPlayerProps) {
+ return <MediaVideoPlayerContent key={props.thumbnailKey} {...props} />;
+}
diff --git a/apps/mobile/src/components/MediaVideoPreviewModal.tsx b/apps/mobile/src/components/MediaVideoPreviewModal.tsx
new file mode 100644
index 00000000000..6c231194701
--- /dev/null
+++ b/apps/mobile/src/components/MediaVideoPreviewModal.tsx
@@ -0,0 +1,96 @@
+import { useEffect } from "react";
+import { Keyboard, Modal, Pressable, View } from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+
+import { useMediaActions } from "../lib/mediaActions";
+import { MediaActionsMenu } from "./MediaActionsMenu";
+import {
+ mediaVideoPreviewUri,
+ mediaVideoThumbnailKey,
+ type MediaVideoPreviewSource,
+} from "../lib/videoPreviewSource";
+import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets";
+import { usePreparedConnection } from "../state/session";
+import { AppText } from "./AppText";
+import { SymbolView } from "./AppSymbol";
+import { MediaVideoPlayer } from "./MediaVideoPlayer";
+import { MediaSourceCaption } from "./MediaSourceCaption";
+
+/** Media files stream in place. A client-side copy is made only for an explicit share. */
+export function MediaVideoPreviewModal(props: {
+ readonly source: MediaVideoPreviewSource;
+ readonly onRequestClose: () => void;
+}) {
+ const { source } = props;
+ const insets = useSafeAreaInsets();
+ const environmentId = "environmentId" in source ? source.environmentId : null;
+ const connection = usePreparedConnection(environmentId);
+ const asset = useAssetUrlState(environmentId, "resource" in source ? source.resource : null);
+ const refreshAssetUrl = useRefreshAssetUrl(
+ environmentId,
+ "resource" in source ? source.resource : null,
+ );
+ const resolvePlaybackUri =
+ "resource" in source
+ ? async () => mediaVideoPreviewUri(source, await refreshAssetUrl())
+ : undefined;
+ const uri = mediaVideoPreviewUri(source, asset._tag === "Success" ? asset.url : null);
+ const mediaActions = useMediaActions(source.actionsSource, props.onRequestClose);
+ const unavailable =
+ uri === null &&
+ environmentId !== null &&
+ (connection._tag === "None" || asset._tag === "Failure");
+
+ useEffect(() => Keyboard.dismiss(), []);
+ 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}>
+ {source.name}
+ </AppText>
+ <MediaActionsMenu media={mediaActions} inModal />
+ <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>
+ <MediaSourceCaption source={mediaActions.title} />
+ <MediaVideoPlayer
+ uri={uri}
+ resolvePlaybackUri={resolvePlaybackUri}
+ name={source.name}
+ thumbnailKey={mediaVideoThumbnailKey(source)}
+ unavailable={unavailable}
+ paused={mediaActions.sharing}
+ expanded
+ />
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel="Save or share video"
+ disabled={uri === null || mediaActions.sharing}
+ onPress={mediaActions.share}
+ 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">
+ {mediaActions.sharing ? "Opening share sheet..." : "Save or share video"}
+ </AppText>
+ </Pressable>
+ </View>
+ </Modal>
+ );
+}
diff --git a/apps/mobile/src/components/VideoPreviewModal.ios.tsx b/apps/mobile/src/components/VideoPreviewModal.ios.tsx
index a947d8d2e51..88a1b5191dd 100644
--- a/apps/mobile/src/components/VideoPreviewModal.ios.tsx
+++ b/apps/mobile/src/components/VideoPreviewModal.ios.tsx
@@ -7,9 +7,10 @@ import { Alert, Keyboard } from "react-native";
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
import { useAssetUrlState } from "../state/assets";
import { usePreparedConnection } from "../state/session";
-import type { VideoPreviewSource } from "./VideoPreviewModal";
+import type { AttachmentVideoPreviewSource, VideoPreviewSource } from "../lib/videoPreviewSource";
+import { MediaVideoPreviewModal } from "./MediaVideoPreviewModal";
-export type { VideoPreviewSource } from "./VideoPreviewModal";
+export type { VideoPreviewSource } from "../lib/videoPreviewSource";
const NativeControls = requireNativeModule<{
presentVideo(
@@ -22,7 +23,7 @@ const NativeControls = requireNativeModule<{
}>("T3NativeControls");
function NativeVideoPreview(props: {
- readonly source: VideoPreviewSource;
+ readonly source: AttachmentVideoPreviewSource;
readonly onRequestClose: () => void;
}) {
const { source } = props;
@@ -117,5 +118,8 @@ export function VideoPreviewModal(props: {
}, [isFocused, hasSource]);
if (!props.source || !isFocused) return null;
+ if (props.source.type === "media") {
+ return <MediaVideoPreviewModal source={props.source} onRequestClose={props.onRequestClose} />;
+ }
return <NativeVideoPreview source={props.source} onRequestClose={props.onRequestClose} />;
}
diff --git a/apps/mobile/src/components/VideoPreviewModal.tsx b/apps/mobile/src/components/VideoPreviewModal.tsx
index eaa01c5d171..cc56b3952b7 100644
--- a/apps/mobile/src/components/VideoPreviewModal.tsx
+++ b/apps/mobile/src/components/VideoPreviewModal.tsx
@@ -1,5 +1,4 @@
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";
@@ -19,21 +18,15 @@ import {
downloadAttachmentForPreview,
type AttachmentPreviewFile,
} from "../lib/attachmentDownload";
-import type { DraftComposerFileAttachment } from "../lib/composerImages";
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
+import type { AttachmentVideoPreviewSource, VideoPreviewSource } from "../lib/videoPreviewSource";
import { useAssetUrlState } from "../state/assets";
import { usePreparedConnection } from "../state/session";
import { SymbolView } from "./AppSymbol";
import { AppText } from "./AppText";
+import { MediaVideoPreviewModal } from "./MediaVideoPreviewModal";
-export type VideoPreviewSource = (
- | { readonly type: "local"; readonly attachment: DraftComposerFileAttachment }
- | {
- readonly type: "remote";
- readonly environmentId: EnvironmentId;
- readonly attachment: ChatFileAttachment;
- }
-) & { readonly sourceIdentifier?: string };
+export type { VideoPreviewSource } from "../lib/videoPreviewSource";
function VideoPlayback(props: { readonly file: AttachmentPreviewFile }) {
const player = useVideoPlayer(props.file.uri, (player) => {
@@ -120,7 +113,7 @@ function VideoPlayback(props: { readonly file: AttachmentPreviewFile }) {
}
function OpenVideoPreviewModal(props: {
- readonly source: VideoPreviewSource;
+ readonly source: AttachmentVideoPreviewSource;
readonly onRequestClose: () => void;
}) {
const { source } = props;
@@ -250,6 +243,9 @@ export function VideoPreviewModal(props: {
}, [isFocused, hasSource, props.onRequestClose]);
const { source } = props;
if (source === null || !isFocused) return null;
+ if (source.type === "media") {
+ return <MediaVideoPreviewModal source={source} onRequestClose={props.onRequestClose} />;
+ }
const key =
source.type === "local"
? `local:${source.attachment.id}:${source.attachment.fileUri}`
diff --git a/apps/mobile/src/components/VideoThumbnailImage.tsx b/apps/mobile/src/components/VideoThumbnailImage.tsx
index 0be94c700ce..cfb8ceeb2ac 100644
--- a/apps/mobile/src/components/VideoThumbnailImage.tsx
+++ b/apps/mobile/src/components/VideoThumbnailImage.tsx
@@ -11,6 +11,7 @@ import { cachedVideoThumbnail, loadVideoThumbnail } from "../lib/videoThumbnails
export function VideoThumbnailImage(props: {
readonly cacheKey: string;
readonly source: string | DraftComposerFileAttachment | null;
+ readonly contentFit?: "cover" | "contain";
}) {
const { cacheKey, source } = props;
const isFocused = useIsFocused();
@@ -37,7 +38,7 @@ export function VideoThumbnailImage(props: {
<Image
source={thumbnail}
style={StyleSheet.absoluteFill}
- contentFit="cover"
+ contentFit={props.contentFit ?? "cover"}
recyclingKey={cacheKey}
accessible={false}
/>
diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
index 5dddac1dd82..052c89a7e62 100644
--- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
+++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
@@ -1,7 +1,7 @@
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import type { MenuAction } from "@react-native-menu/menu";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import { ActivityIndicator, Platform, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
@@ -11,6 +11,9 @@ import {
type ProjectReadFileResult,
ThreadId,
} from "@t3tools/contracts";
+import { videoMimeType } from "@t3tools/shared/video";
+import { mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";
+import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
import { AndroidHeaderIconButton, AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { SymbolView } from "../../components/AppSymbol";
@@ -24,6 +27,8 @@ import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { isPdfFile } from "../../lib/filePreview";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
+import type { MediaVideoPreviewSource } from "../../lib/videoPreviewSource";
+import { useMediaActions, type MediaActionsSource } from "../../lib/mediaActions";
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useEnvironmentQuery } from "../../state/query";
@@ -47,6 +52,7 @@ import { preloadWorkspaceFileContents } from "./preload-workspace-file";
import { SourceFileSurface } from "./SourceFileSurface";
import { ThreadFileNavigatorPane } from "./thread-file-navigator-pane";
import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
+import { WorkspaceFileVideoPreview } from "./WorkspaceFileVideoPreview";
import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
import {
basename,
@@ -54,8 +60,9 @@ import {
isImagePreviewFile,
isMarkdownPreviewFile,
isSvgImagePreviewFile,
+ isVideoPreviewFile,
} from "./filePath";
-import { useWorkspaceFileAssetUrl } from "./workspaceFileAssetUrl";
+import { useWorkspaceFileAssetUrlState } from "./workspaceFileAssetUrl";
type FileViewMode = "preview" | "source";
@@ -84,7 +91,8 @@ function normalizeRouteLine(value: string | null): number | null {
}
function defaultViewMode(path: string | null): FileViewMode {
- return path !== null && (isBrowserPreviewFile(path) || isImagePreviewFile(path))
+ return path !== null &&
+ (isBrowserPreviewFile(path) || isImagePreviewFile(path) || isVideoPreviewFile(path))
? "preview"
: "source";
}
@@ -92,6 +100,10 @@ function defaultViewMode(path: string | null): FileViewMode {
function FileContent(props: {
readonly activeMode: FileViewMode;
readonly previewUri: string | null;
+ readonly previewUnavailable: boolean;
+ readonly videoSource: MediaVideoPreviewSource | null;
+ readonly mediaSource?: MediaActionsSource;
+ readonly resolveVideoUri: () => Promise<string | null>;
readonly fileContents: string | null;
readonly fileError: string | null;
readonly relativePath: string;
@@ -99,10 +111,25 @@ function FileContent(props: {
readonly truncated: boolean;
readonly onRefresh?: () => Promise<void> | void;
}) {
+ // Reopening a mutable host file must not reuse a poster from an earlier visit.
+ const thumbnailInstanceId = useId();
const isMarkdown = isMarkdownPreviewFile(props.relativePath);
const isBrowserFile = isBrowserPreviewFile(props.relativePath);
const isImageFile = isImagePreviewFile(props.relativePath);
+ if (isVideoPreviewFile(props.relativePath)) {
+ return (
+ <WorkspaceFileVideoPreview
+ name={basename(props.relativePath)}
+ thumbnailKey={`workspace-video:${thumbnailInstanceId}`}
+ uri={props.previewUri}
+ source={props.videoSource}
+ resolvePlaybackUri={props.resolveVideoUri}
+ unavailable={props.previewUnavailable}
+ />
+ );
+ }
+
if (props.activeMode === "preview" && isImageFile) {
if (isSvgImagePreviewFile(props.relativePath)) {
return <WorkspaceFileWebPreview uri={props.previewUri} />;
@@ -111,6 +138,7 @@ function FileContent(props: {
<WorkspaceFileImagePreview
accessibilityLabel={basename(props.relativePath)}
uri={props.previewUri}
+ actionsSource={props.mediaSource}
/>
);
}
@@ -489,29 +517,73 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
readonly mode: FileViewMode;
} | null>(null);
const [previewRevision, setPreviewRevision] = useState(0);
+ const previewKey = JSON.stringify([environmentId, cwd, relativePath, previewRevision]);
const [fullScreenPreview, setFullScreenPreview] = useState<FilePreviewSource | null>(null);
- const isBrowserFile = relativePath !== null && isBrowserPreviewFile(relativePath);
- const isImageFile = relativePath !== null && isImagePreviewFile(relativePath);
+ const isVideoFile = relativePath !== null && isVideoPreviewFile(relativePath);
+ const isBrowserFile = relativePath !== null && !isVideoFile && isBrowserPreviewFile(relativePath);
+ const isImageFile = relativePath !== null && !isVideoFile && isImagePreviewFile(relativePath);
const canPreview =
- relativePath !== null && (isMarkdownPreviewFile(relativePath) || isBrowserFile || isImageFile);
+ relativePath !== null &&
+ (isMarkdownPreviewFile(relativePath) || isBrowserFile || isImageFile || isVideoFile);
const activeMode =
relativePath !== null && modeOverride?.path === relativePath
? modeOverride.mode
: defaultViewMode(relativePath);
- const resolvedActiveMode = canPreview ? activeMode : "source";
- const assetPreviewPath = isBrowserFile || isImageFile ? relativePath : null;
- const assetPreviewUri = useWorkspaceFileAssetUrl({
+ const resolvedActiveMode = isVideoFile ? "preview" : canPreview ? activeMode : "source";
+ const assetPreviewPath = isBrowserFile || isImageFile || isVideoFile ? relativePath : null;
+ const assetPreview = useWorkspaceFileAssetUrlState({
cwd,
environmentId,
relativePath: assetPreviewPath,
threadId,
});
+ const assetPreviewUri = assetPreview._tag === "Success" ? assetPreview.url : null;
+ const mediaSource = useMemo<MediaActionsSource | undefined>(
+ () =>
+ environmentId !== null &&
+ threadId !== null &&
+ relativePath !== null &&
+ assetPreview.resource !== null &&
+ "path" in assetPreview.resource &&
+ typeof assetPreview.resource.path === "string" &&
+ (isImageFile || isVideoFile)
+ ? {
+ reference: mediaFileReference(assetPreview.resource.path, cwd),
+ name: basename(relativePath),
+ mimeType:
+ mediaMimeTypeFromExtension(relativePath.slice(relativePath.lastIndexOf("."))) ??
+ "application/octet-stream",
+ environmentId,
+ threadId,
+ resource: assetPreview.resource,
+ }
+ : undefined,
+ [assetPreview.resource, cwd, environmentId, isImageFile, isVideoFile, relativePath, threadId],
+ );
+ const mediaActions = useMediaActions(mediaSource);
+ const videoSource = useMemo<MediaVideoPreviewSource | null>(
+ () =>
+ environmentId !== null &&
+ relativePath !== null &&
+ assetPreview.resource?._tag === "media-file"
+ ? {
+ type: "media",
+ environmentId,
+ resource: assetPreview.resource,
+ name: basename(relativePath),
+ mimeType: videoMimeType({ name: relativePath, mimeType: "" }) ?? "video/mp4",
+ actionsSource: mediaSource,
+ }
+ : null,
+ [assetPreview.resource, environmentId, relativePath, mediaSource],
+ );
const previewUri =
assetPreviewUri === null || previewRevision === 0
? assetPreviewUri
: `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
const needsFileContents =
relativePath !== null &&
+ !isVideoFile &&
(resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
const fileQuery = useEnvironmentQuery(
environmentId !== null && cwd !== null && relativePath !== null && needsFileContents
@@ -562,7 +634,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
const fileMenuActions = useMemo(() => {
if (relativePath === null) return [];
- const canToggleMode = canPreview && !isImageFile;
+ const canToggleMode = canPreview && !isImageFile && !isVideoFile;
return [
canToggleMode
? ({
@@ -582,13 +654,26 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
onPress: () => setModeOverride({ path: relativePath, mode: "source" }),
} as const)
: null,
- {
- id: "copy-path",
- title: "Copy path",
- icon: "doc.on.doc",
- inline: false,
- onPress: () => copyTextWithHaptic(relativePath),
- } as const,
+ ...(mediaSource
+ ? mediaActions.actions
+ .filter(({ id }) => id !== "open-file")
+ .map((action) => ({
+ id: action.id,
+ title: action.title,
+ icon:
+ action.id === "share" ? ("square.and.arrow.up" as const) : ("doc.on.doc" as const),
+ inline: false,
+ onPress: action.run,
+ }))
+ : [
+ {
+ id: "copy-path",
+ title: "Copy path",
+ icon: "doc.on.doc",
+ inline: false,
+ onPress: () => copyTextWithHaptic(relativePath),
+ } as const,
+ ]),
isPdfFile({ name: relativePath }) && previewUri !== null
? ({
id: "open-pdf",
@@ -612,24 +697,31 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
onPress: () => tryOpenExternalUrl(assetPreviewUri, "file-preview"),
} as const)
: null,
- resolvedActiveMode === "preview" && (isBrowserFile || isImageFile)
+ resolvedActiveMode === "preview" && (isBrowserFile || isImageFile || isVideoFile)
? ({
id: "refresh",
title: "Refresh",
icon: "arrow.clockwise",
inline: false,
- onPress: () => setPreviewRevision((current) => current + 1),
+ onPress: async () => {
+ if (isVideoFile) await assetPreview.refresh();
+ setPreviewRevision((current) => current + 1);
+ },
} as const)
: null,
].filter((action) => action !== null);
}, [
assetPreviewUri,
+ assetPreview.refresh,
previewUri,
canPreview,
isBrowserFile,
isImageFile,
+ isVideoFile,
relativePath,
resolvedActiveMode,
+ mediaSource,
+ mediaActions.actions,
]);
const androidFileMenuActions = useMemo<MenuAction[]>(
@@ -782,8 +874,13 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
</NativeHeaderToolbar.Menu>
</NativeHeaderToolbar>
<FileContent
+ key={previewKey}
activeMode={resolvedActiveMode}
previewUri={previewUri}
+ previewUnavailable={assetPreview._tag === "Failure"}
+ videoSource={videoSource}
+ mediaSource={mediaSource}
+ resolveVideoUri={assetPreview.refresh}
fileContents={fileData?.contents ?? null}
fileError={fileQuery.error}
initialLine={targetLine}
diff --git a/apps/mobile/src/features/files/WorkspaceFileImagePreview.tsx b/apps/mobile/src/features/files/WorkspaceFileImagePreview.tsx
index e725c4d133f..3e6afae6f84 100644
--- a/apps/mobile/src/features/files/WorkspaceFileImagePreview.tsx
+++ b/apps/mobile/src/features/files/WorkspaceFileImagePreview.tsx
@@ -8,14 +8,18 @@ import { EmptyState } from "../../components/EmptyState";
import { workspaceFileImageAtom } from "./workspace-file-image-cache";
import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
import { PresentationSource } from "../../components/NativePresentation";
+import { useMediaActions, type MediaActionsSource } from "../../lib/mediaActions";
+import { MediaActionsMenu } from "../../components/MediaActionsMenu";
function ResolvedWorkspaceFileImagePreview(props: {
readonly accessibilityLabel: string;
readonly uri: string;
+ readonly actionsSource?: MediaActionsSource;
}) {
const [loadError, setLoadError] = useState<string | null>(null);
const [preview, setPreview] = useState<FilePreviewSource | null>(null);
const sourceIdentifier = useId();
+ const mediaActions = useMediaActions(props.actionsSource);
const imageSource = useMemo(
() => ({ uri: props.uri, cache: "force-cache" as const }),
[props.uri],
@@ -34,6 +38,7 @@ function ResolvedWorkspaceFileImagePreview(props: {
uri: props.uri,
name: props.accessibilityLabel,
sourceIdentifier,
+ actionsSource: props.actionsSource,
})
}
>
@@ -50,13 +55,16 @@ function ResolvedWorkspaceFileImagePreview(props: {
/>
</PresentationSource>
</Pressable>
-
{loadError !== null ? (
<View className="absolute inset-0 items-center justify-center bg-card px-6">
<EmptyState title="Image unavailable" detail={loadError} />
</View>
) : null}
+ <View className="absolute right-2 top-2">
+ <MediaActionsMenu media={mediaActions} />
+ </View>
+
<FilePreviewModal source={preview} onRequestClose={() => setPreview(null)} />
</View>
);
@@ -65,6 +73,7 @@ function ResolvedWorkspaceFileImagePreview(props: {
function CachedWorkspaceFileImagePreview(props: {
readonly accessibilityLabel: string;
readonly uri: string;
+ readonly actionsSource?: MediaActionsSource;
}) {
const imageAtom = useMemo(() => workspaceFileImageAtom(props.uri), [props.uri]);
const imageResult = useAtomValue(imageAtom);
@@ -93,6 +102,7 @@ function CachedWorkspaceFileImagePreview(props: {
<ResolvedWorkspaceFileImagePreview
accessibilityLabel={props.accessibilityLabel}
uri={imageResult.value}
+ actionsSource={props.actionsSource}
/>
);
}
@@ -100,6 +110,7 @@ function CachedWorkspaceFileImagePreview(props: {
export function WorkspaceFileImagePreview(props: {
readonly accessibilityLabel: string;
readonly uri: string | null;
+ readonly actionsSource?: MediaActionsSource;
}) {
if (props.uri === null) {
return (
@@ -116,6 +127,7 @@ export function WorkspaceFileImagePreview(props: {
<CachedWorkspaceFileImagePreview
accessibilityLabel={props.accessibilityLabel}
uri={props.uri}
+ actionsSource={props.actionsSource}
/>
);
}
diff --git a/apps/mobile/src/features/files/WorkspaceFileVideoPreview.tsx b/apps/mobile/src/features/files/WorkspaceFileVideoPreview.tsx
new file mode 100644
index 00000000000..aaa13427fac
--- /dev/null
+++ b/apps/mobile/src/features/files/WorkspaceFileVideoPreview.tsx
@@ -0,0 +1,47 @@
+import { useState } from "react";
+import { View } from "react-native";
+
+import { EmptyState } from "../../components/EmptyState";
+import { MediaVideoPlayer } from "../../components/MediaVideoPlayer";
+import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
+import type { MediaVideoPreviewSource } from "../../lib/videoPreviewSource";
+
+/** Uses the signed progressive URL directly; choosing a file never preloads its video bytes as text. */
+export function WorkspaceFileVideoPreview(props: {
+ readonly name: string;
+ readonly thumbnailKey: string;
+ readonly uri: string | null;
+ readonly source: MediaVideoPreviewSource | null;
+ readonly resolvePlaybackUri: () => Promise<string | null>;
+ readonly unavailable: boolean;
+}) {
+ const [preview, setPreview] = useState<VideoPreviewSource | null>(null);
+ const uri = props.uri;
+
+ if (props.unavailable) {
+ return (
+ <View className="flex-1 items-center justify-center bg-sheet px-6">
+ <EmptyState
+ title="Video unavailable"
+ detail="This file may be missing, unsupported, or unavailable on this environment."
+ />
+ </View>
+ );
+ }
+
+ return (
+ <View className="flex-1 items-center justify-center bg-sheet p-4">
+ <MediaVideoPlayer
+ uri={uri}
+ resolvePlaybackUri={props.resolvePlaybackUri}
+ name={props.name}
+ thumbnailKey={props.thumbnailKey}
+ actionsSource={props.source?.actionsSource}
+ onExpand={
+ uri === null || props.source === null ? undefined : () => setPreview(props.source)
+ }
+ />
+ <VideoPreviewModal source={preview} onRequestClose={() => setPreview(null)} />
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/files/filePath.ts b/apps/mobile/src/features/files/filePath.ts
index 385d5c139ee..12217aab74f 100644
--- a/apps/mobile/src/features/files/filePath.ts
+++ b/apps/mobile/src/features/files/filePath.ts
@@ -1,6 +1,7 @@
import {
isWorkspaceBrowserPreviewPath,
isWorkspaceImagePreviewPath,
+ isWorkspaceVideoPreviewPath,
} from "@t3tools/shared/filePreview";
export interface FileBreadcrumb {
@@ -95,6 +96,10 @@ export function isImagePreviewFile(path: string): boolean {
return isWorkspaceImagePreviewPath(path);
}
+export function isVideoPreviewFile(path: string): boolean {
+ return isWorkspaceVideoPreviewPath(path);
+}
+
export function isSvgImagePreviewFile(path: string): boolean {
return /\.svg$/i.test(path.split(/[?#]/, 1)[0] ?? "");
}
diff --git a/apps/mobile/src/features/files/preload-workspace-file.ts b/apps/mobile/src/features/files/preload-workspace-file.ts
index b9e21cfd98f..7df750883f5 100644
--- a/apps/mobile/src/features/files/preload-workspace-file.ts
+++ b/apps/mobile/src/features/files/preload-workspace-file.ts
@@ -3,7 +3,7 @@ import type { EnvironmentId } from "@t3tools/contracts";
import { appAtomRegistry } from "../../state/atom-registry";
import { projectEnvironment } from "../../state/projects";
-import { isBrowserPreviewFile, isImagePreviewFile } from "./filePath";
+import { isBrowserPreviewFile, isImagePreviewFile, isVideoPreviewFile } from "./filePath";
import { prepareSourceFileDocument } from "./source-file-document";
import { sourceHighlightAtom } from "./sourceHighlightingState";
import type { ReviewDiffTheme } from "../review/shikiReviewHighlighter";
@@ -25,7 +25,11 @@ export function preloadWorkspaceFileContents(input: {
readonly relativePath: string;
readonly theme: ReviewDiffTheme;
}): void {
- if (isBrowserPreviewFile(input.relativePath) || isImagePreviewFile(input.relativePath)) {
+ if (
+ isBrowserPreviewFile(input.relativePath) ||
+ isImagePreviewFile(input.relativePath) ||
+ isVideoPreviewFile(input.relativePath)
+ ) {
return;
}
diff --git a/apps/mobile/src/features/files/workspaceFileAssetUrl.ts b/apps/mobile/src/features/files/workspaceFileAssetUrl.ts
index 70ea3e43582..eb2ba93b497 100644
--- a/apps/mobile/src/features/files/workspaceFileAssetUrl.ts
+++ b/apps/mobile/src/features/files/workspaceFileAssetUrl.ts
@@ -1,10 +1,10 @@
-import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import type { AssetResource, EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useMemo } from "react";
-import { useAssetUrl } from "../../state/assets";
-import { resolveWorkspaceFilePath } from "./filePath";
+import { useAssetUrlState, useRefreshAssetUrl } from "../../state/assets";
+import { isVideoPreviewFile, resolveWorkspaceFilePath } from "./filePath";
-export function useWorkspaceFileAssetUrl(props: {
+export function useWorkspaceFileAssetUrlState(props: {
readonly cwd: string | null;
readonly environmentId: EnvironmentId | null;
readonly relativePath: string | null;
@@ -18,14 +18,18 @@ export function useWorkspaceFileAssetUrl(props: {
[props.cwd, props.relativePath],
);
- return useAssetUrl(
- props.environmentId,
- absolutePath !== null && props.threadId !== null
- ? {
- _tag: "workspace-file",
- threadId: props.threadId,
- path: absolutePath,
- }
- : null,
+ const resource = useMemo<AssetResource | null>(
+ () =>
+ absolutePath !== null && props.threadId !== null
+ ? {
+ _tag: isVideoPreviewFile(absolutePath) ? "media-file" : "workspace-file",
+ threadId: props.threadId,
+ path: absolutePath,
+ }
+ : null,
+ [absolutePath, props.threadId],
);
+ const state = useAssetUrlState(props.environmentId, resource);
+ const refresh = useRefreshAssetUrl(props.environmentId, resource);
+ return { ...state, resource, refresh };
}
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index cb72aa1f653..3cbf02efa2b 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -1,6 +1,6 @@
import * as Haptics from "expo-haptics";
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
-import { type LegendListRef } from "@legendapp/list/react-native";
+import { useViewabilityAmount, type LegendListRef } from "@legendapp/list/react-native";
import type {
AssetResource,
ChatAttachment,
@@ -33,6 +33,7 @@ import { SymbolView, type AppSymbolName } from "../../components/AppSymbol";
import { HeaderHeightContext } from "@react-navigation/elements";
import { useFocusEffect, useNavigation } from "@react-navigation/native";
import {
+ createContext,
memo,
useCallback,
useContext,
@@ -97,6 +98,15 @@ import {
import { AppText as Text } from "../../components/AppText";
import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
import { VideoAttachmentTile } from "../../components/VideoAttachmentTile";
+import { MediaVideoPlayer } from "../../components/MediaVideoPlayer";
+import { resolveMarkdownMediaPreview } from "../../lib/markdownMedia";
+import { useMediaActions, type MediaActionsSource } from "../../lib/mediaActions";
+import { MediaActionsMenu } from "../../components/MediaActionsMenu";
+import {
+ mediaVideoPreviewUri,
+ mediaVideoThumbnailKey,
+ type MediaVideoPreviewSource,
+} from "../../lib/videoPreviewSource";
import { CopyTextButton } from "../../components/CopyTextButton";
import {
parseReviewCommentMessageSegments,
@@ -123,7 +133,11 @@ import {
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
-import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
+import {
+ normalizeNativeMarkdownUrl,
+ resolveMarkdownInlineCodePresentation,
+ resolveMarkdownLinkPresentation,
+} from "@t3tools/mobile-markdown-text/links";
import {
deriveThreadFeedPresentation,
type ThreadFeedEntry,
@@ -143,7 +157,12 @@ import {
WORK_GROUP_TOGGLE_HEIGHT,
} from "./thread-work-log";
import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
-import { assetEnvironment, useAssetUrl, useAssetUrlState } from "../../state/assets";
+import {
+ assetEnvironment,
+ useAssetUrl,
+ useAssetUrlState,
+ useRefreshAssetUrl,
+} from "../../state/assets";
import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
import { usePreparedConnection } from "../../state/session";
import * as Option from "effect/Option";
@@ -272,6 +291,7 @@ function MessageAttachmentFile(props: {
}) {
const sourceIdentifier = useId();
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
+ refresh: true,
reportFailure: false,
});
const preparedConnection = usePreparedConnection(props.environmentId);
@@ -453,9 +473,11 @@ function ThreadMarkdownImageView(props: {
readonly sourceKey: string;
readonly unavailable: boolean;
readonly alt: string | null;
+ readonly actionsSource?: MediaActionsSource;
readonly onPressPreview: (source: FilePreviewSource) => void;
}) {
const sourceIdentifier = useId();
+ const mediaActions = useMediaActions(props.actionsSource);
const [availableWidth, setAvailableWidth] = useState(0);
const [sourceSize, setSourceSize] = useState<{ width: number; height: number } | null>(null);
const [failedUri, setFailedUri] = useState<string | null>(null);
@@ -498,36 +520,51 @@ function ThreadMarkdownImageView(props: {
) : (
<ActivityIndicator />
)}
+ {props.actionsSource ? (
+ <View className="absolute right-1 top-1">
+ <MediaActionsMenu media={mediaActions} />
+ </View>
+ ) : null}
</View>
) : (
<PresentationSource identifier={sourceIdentifier} style={{ alignSelf: "flex-start" }}>
- <Pressable
- accessibilityRole="imagebutton"
- accessibilityLabel={props.alt ?? "Markdown image"}
- onPress={() =>
- props.onPressPreview({
- kind: "image",
- uri: props.uri!,
- name: props.alt ?? "Image",
- sourceIdentifier,
- })
- }
- style={{ alignSelf: "flex-start" }}
- >
- <View
- className="items-center justify-center overflow-hidden rounded-[10px] bg-md-code-bg"
- style={{
- ...frameStyle,
- }}
- >
- <ThreadMarkdownImageRequest
- key={props.uri}
- uri={props.uri}
- onLoad={setSourceSize}
- onError={() => setFailedUri(props.uri)}
- />
- </View>
- </Pressable>
+ <View>
+ <MediaActionsMenu media={mediaActions}>
+ <Pressable
+ accessibilityRole="imagebutton"
+ accessibilityLabel={props.alt ?? "Markdown image"}
+ onPress={() =>
+ props.onPressPreview({
+ kind: "image",
+ uri: props.uri!,
+ name: props.alt ?? "Image",
+ sourceIdentifier,
+ actionsSource: props.actionsSource,
+ })
+ }
+ style={{ alignSelf: "flex-start" }}
+ >
+ <View
+ className="items-center justify-center overflow-hidden rounded-[10px] bg-md-code-bg"
+ style={{
+ ...frameStyle,
+ }}
+ >
+ <ThreadMarkdownImageRequest
+ key={props.uri}
+ uri={props.uri}
+ onLoad={setSourceSize}
+ onError={() => setFailedUri(props.uri)}
+ />
+ </View>
+ </Pressable>
+ </MediaActionsMenu>
+ {props.actionsSource ? (
+ <View className="absolute right-1 top-1">
+ <MediaActionsMenu media={mediaActions} />
+ </View>
+ ) : null}
+ </View>
</PresentationSource>
)}
{props.alt ? (
@@ -574,9 +611,10 @@ function ThreadMarkdownImageRequest(props: {
/** Environment-hosted image that loads through a signed asset URL. */
function ThreadMarkdownImage(props: {
readonly environmentId: EnvironmentId;
- readonly resource: Extract<AssetResource, { readonly _tag: "attachment" | "workspace-file" }>;
+ readonly resource: Extract<AssetResource, { readonly _tag: "attachment" | "media-file" }>;
readonly alt: string | null;
readonly srcFragment?: string;
+ readonly actionsSource?: MediaActionsSource;
readonly onPressPreview: (source: FilePreviewSource) => void;
}) {
const assetUrl = useAssetUrlState(props.environmentId, props.resource);
@@ -591,11 +629,59 @@ function ThreadMarkdownImage(props: {
}
unavailable={assetUrl._tag === "Failure"}
alt={props.alt}
+ actionsSource={props.actionsSource}
onPressPreview={props.onPressPreview}
/>
);
}
+const ThreadMediaVisibleContext = createContext(false);
+// LegendList only computes hook visibility when the list has a viewability config.
+const THREAD_MEDIA_VIEWABILITY_CONFIG = { itemVisiblePercentThreshold: 0 };
+
+function ThreadMediaVisibility(props: { readonly children: ReactNode }) {
+ const [visible, setVisible] = useState(false);
+ useViewabilityAmount<ThreadFeedEntry>(
+ useCallback((token) => setVisible(token.sizeVisible > 0), []),
+ );
+ return <ThreadMediaVisibleContext value={visible}>{props.children}</ThreadMediaVisibleContext>;
+}
+
+function ThreadMarkdownVideo(props: {
+ readonly source: MediaVideoPreviewSource;
+ readonly onExpand: (source: MediaVideoPreviewSource) => void;
+}) {
+ const { source } = props;
+ const visible = useContext(ThreadMediaVisibleContext);
+ const thumbnailKey = mediaVideoThumbnailKey(source);
+ const asset = useAssetUrlState(
+ "environmentId" in source ? source.environmentId : null,
+ "resource" in source ? source.resource : null,
+ );
+ const refreshAssetUrl = useRefreshAssetUrl(
+ "environmentId" in source ? source.environmentId : null,
+ "resource" in source ? source.resource : null,
+ );
+ const uri = mediaVideoPreviewUri(source, asset._tag === "Success" ? asset.url : null);
+ return (
+ <MediaVideoPlayer
+ key={thumbnailKey}
+ uri={uri}
+ resolvePlaybackUri={
+ "resource" in source
+ ? async () => mediaVideoPreviewUri(source, await refreshAssetUrl())
+ : undefined
+ }
+ name={source.name}
+ thumbnailKey={thumbnailKey}
+ thumbnailVisible={visible}
+ unavailable={"resource" in source && asset._tag === "Failure"}
+ actionsSource={source.actionsSource}
+ onExpand={() => props.onExpand(source)}
+ />
+ );
+}
+
function ThreadMarkdownImageUnavailable(props: { readonly alt: string | null }) {
return (
<ThreadMarkdownImageView
@@ -636,6 +722,7 @@ interface ReviewCommentColors {
}
const failedMarkdownFaviconHosts = new Set<string>();
+const MarkdownLinkLabelContext = createContext(false);
const markdownLinkStyles = StyleSheet.create({
inlineIcon: {
width: 14,
@@ -653,15 +740,14 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
readonly color: string;
readonly host: string;
readonly href: string;
+ readonly onPress: (href: string) => void;
}) {
const [failed, setFailed] = useState(() => failedMarkdownFaviconHosts.has(props.host));
return (
<NativeText
className="font-sans"
- onPress={() => {
- void tryOpenExternalUrl(props.href, "markdown-link");
- }}
+ onPress={() => props.onPress(props.href)}
style={{
color: props.color,
textDecorationLine: "none",
@@ -686,6 +772,37 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
);
});
+function MarkdownInlineCode(props: {
+ readonly content: string;
+ readonly textColor: string;
+ readonly codeColor: string;
+ readonly fontSize: number;
+ readonly lineHeight: number;
+ readonly onLinkPress: (href: string) => void;
+}) {
+ const insideLink = useContext(MarkdownLinkLabelContext);
+ const presentation = insideLink ? null : resolveMarkdownInlineCodePresentation(props.content);
+ return (
+ <NativeText
+ className={presentation ? "font-t3-bold" : "font-mono"}
+ onPress={presentation ? () => props.onLinkPress(presentation.href) : undefined}
+ style={{
+ color: presentation ? props.textColor : props.codeColor,
+ fontSize: props.fontSize,
+ lineHeight: props.lineHeight,
+ }}
+ >
+ {presentation ? (
+ <Image
+ source={markdownFileIconSource(presentation.icon)}
+ style={markdownLinkStyles.inlineIcon}
+ />
+ ) : null}
+ {presentation?.label ?? props.content}
+ </NativeText>
+ );
+}
+
const ARTIFACT_TEMPLATE_SYMBOL_BY_KIND: Record<
CodexArtifactTemplate["artifactKind"],
AppSymbolName
@@ -1078,30 +1195,35 @@ function useMarkdownStyles(
}
if (presentation.kind === "external") {
return (
- <MarkdownExternalLink
- href={presentation.href}
- host={presentation.host}
- color={markdownLinkColor}
- >
- {children}
- </MarkdownExternalLink>
+ <MarkdownLinkLabelContext.Provider value>
+ <MarkdownExternalLink
+ href={presentation.href}
+ host={presentation.host}
+ color={markdownLinkColor}
+ onPress={onLinkPress}
+ >
+ {children}
+ </MarkdownExternalLink>
+ </MarkdownLinkLabelContext.Provider>
);
}
const linkHref = presentation.href;
return (
- <NativeText
- className="underline"
- onPress={
- linkHref
- ? () => {
- void tryOpenExternalUrl(linkHref, "markdown-link");
- }
- : undefined
- }
- style={{ color: markdownLinkColor }}
- >
- {children}
- </NativeText>
+ <MarkdownLinkLabelContext.Provider value>
+ <NativeText
+ className="underline"
+ onPress={
+ linkHref
+ ? () => {
+ void tryOpenExternalUrl(linkHref, "markdown-link");
+ }
+ : undefined
+ }
+ style={{ color: markdownLinkColor }}
+ >
+ {children}
+ </NativeText>
+ </MarkdownLinkLabelContext.Provider>
);
},
list: ({ node, Renderer, ordered = false, start = 1 }) => (
@@ -1144,21 +1266,16 @@ function useMarkdownStyles(
title: node.title ?? null,
}) ?? undefined)
: undefined,
- code_inline: ({ content }) => {
- const value = content ?? "";
- return (
- <NativeText
- className="font-mono"
- style={{
- color: inlineCodeTextColor,
- fontSize: markdownFontSizes.codeBlockFontSize,
- lineHeight: markdownFontSizes.bodyLineHeight,
- }}
- >
- {value}
- </NativeText>
- );
- },
+ code_inline: ({ content }) => (
+ <MarkdownInlineCode
+ content={content ?? ""}
+ textColor={inlineTextColor}
+ codeColor={inlineCodeTextColor}
+ fontSize={markdownFontSizes.codeBlockFontSize}
+ lineHeight={markdownFontSizes.bodyLineHeight}
+ onLinkPress={onLinkPress}
+ />
+ ),
...(preserveSoftBreaks
? {
soft_break: () => <NativeText>{"\n"}</NativeText>,
@@ -1954,11 +2071,26 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
path: relativePath.split("/").filter((segment) => segment.length > 0),
...(presentation.line ? { line: String(presentation.line) } : {}),
});
+ return;
+ }
+ }
+
+ const media = resolveMarkdownMediaPreview(href, {
+ environmentId: props.environmentId,
+ threadId: props.threadId,
+ workspaceRoot: props.workspaceRoot,
+ });
+ if (media) {
+ void Haptics.selectionAsync();
+ if (media.kind === "video") {
+ setExpandedVideo((current) => current ?? media.source);
+ } else {
+ setExpandedFile((current) => current ?? media.source);
}
return;
}
- if (presentation.href) {
+ if (presentation.kind !== "file" && presentation.href) {
if (/^https?:\/\//i.test(presentation.href) && isPdfFile({ name: presentation.href })) {
setExpandedFile(
(current) => current ?? { kind: "pdf", uri: presentation.href!, name: "Document.pdf" },
@@ -1972,14 +2104,30 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
);
const renderMarkdownImage = useCallback<MarkdownImageRenderer>(
(image) => {
+ const media = resolveMarkdownMediaPreview(image.href, {
+ environmentId: props.environmentId,
+ threadId: props.threadId,
+ workspaceRoot: props.workspaceRoot,
+ imageEmbed: true,
+ });
+ if (media?.kind === "video") {
+ return (
+ <ThreadMarkdownVideo
+ key={image.href}
+ source={{ ...media.source, name: image.alt ?? media.source.name }}
+ onExpand={(source) => setExpandedVideo((current) => current ?? source)}
+ />
+ );
+ }
const imageSource = classifyMarkdownImageSource(image.href, props.workspaceRoot ?? null);
if (imageSource._tag === "Direct") {
return (
<ThreadMarkdownImageView
- uri={imageSource.uri}
+ uri={normalizeNativeMarkdownUrl(imageSource.uri)}
sourceKey={imageSource.uri}
unavailable={false}
alt={image.alt}
+ actionsSource={media?.source.actionsSource}
onPressPreview={(source) => setExpandedFile((current) => current ?? source)}
/>
);
@@ -1991,12 +2139,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
<ThreadMarkdownImage
environmentId={props.environmentId}
resource={{
- _tag: "workspace-file",
+ _tag: "media-file",
threadId: props.threadId,
path: imageSource.path,
}}
alt={image.alt}
srcFragment={markdownImageSourceFragment(image.href)}
+ actionsSource={media?.source.actionsSource}
onPressPreview={(source) => setExpandedFile((current) => current ?? source)}
/>
);
@@ -2009,12 +2158,26 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
threadId: props.threadId,
workspaceRoot: props.workspaceRoot,
});
+ const media = viewedImage
+ ? resolveMarkdownMediaPreview(image.href, {
+ environmentId: props.environmentId,
+ threadId: props.threadId,
+ workspaceRoot: props.workspaceRoot,
+ imageEmbed: true,
+ })
+ : null;
+ const actionsSource = media?.source.actionsSource;
return viewedImage ? (
<ThreadMarkdownImage
environmentId={props.environmentId}
resource={viewedImage.resource}
alt={viewedImage.alt}
srcFragment={viewedImage.srcFragment}
+ actionsSource={
+ actionsSource && "resource" in actionsSource
+ ? { ...actionsSource, resource: viewedImage.resource }
+ : undefined
+ }
onPressPreview={(source) => setExpandedFile((current) => current ?? source)}
/>
) : null;
@@ -2438,30 +2601,32 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
key={info.item.id}
entering={disclosureToggleSettling ? THREAD_FEED_DISCLOSURE_ENTER_TRANSITION : undefined}
>
- {renderFeedEntry(info, {
- environmentId: props.environmentId,
- copiedRowId,
- expandedWorkRows,
- terminalAssistantMessageIds,
- unsettledTurnId,
- onCopyWorkRow,
- onToggleWorkGroup,
- onToggleWorkRow,
- onToggleTurnFold,
- onPressPreview,
- onPressVideo,
- onMarkdownLinkPress,
- renderMarkdownImage,
- renderViewedImage,
- iconSubtleColor,
- userBubbleColor,
- markdownStyles,
- reviewCommentColors,
- reviewCommentBubbleWidth,
- userBubbleMaxWidth,
- skills: props.skills,
- onUseArtifactTemplate: props.onUseArtifactTemplate,
- })}
+ <ThreadMediaVisibility>
+ {renderFeedEntry(info, {
+ environmentId: props.environmentId,
+ copiedRowId,
+ expandedWorkRows,
+ terminalAssistantMessageIds,
+ unsettledTurnId,
+ onCopyWorkRow,
+ onToggleWorkGroup,
+ onToggleWorkRow,
+ onToggleTurnFold,
+ onPressPreview,
+ onPressVideo,
+ onMarkdownLinkPress,
+ renderMarkdownImage,
+ renderViewedImage,
+ iconSubtleColor,
+ userBubbleColor,
+ markdownStyles,
+ reviewCommentColors,
+ reviewCommentBubbleWidth,
+ userBubbleMaxWidth,
+ skills: props.skills,
+ onUseArtifactTemplate: props.onUseArtifactTemplate,
+ })}
+ </ThreadMediaVisibility>
</Animated.View>
),
[
@@ -2586,6 +2751,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
data={presentedFeed}
extraData={listAppearanceData}
renderItem={renderItem}
+ viewabilityConfig={THREAD_MEDIA_VIEWABILITY_CONFIG}
keyExtractor={(entry) => entry.id}
getItemType={(entry) =>
entry.type === "message" ? `message:${entry.message.role}` : entry.type
diff --git a/apps/mobile/src/lib/markdownLinks.test.ts b/apps/mobile/src/lib/markdownLinks.test.ts
index 49a8b46648e..bf3d009b74a 100644
--- a/apps/mobile/src/lib/markdownLinks.test.ts
+++ b/apps/mobile/src/lib/markdownLinks.test.ts
@@ -3,6 +3,22 @@ import { describe, expect, it } from "vite-plus/test";
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
describe("resolveMarkdownLinkPresentation", () => {
+ it("treats protocol-relative media as an external URL, not a filesystem path", () => {
+ expect(resolveMarkdownLinkPresentation("//cdn.example.com/clip.mp4?sig=a%2fb#t=2")).toEqual({
+ kind: "external",
+ href: "https://cdn.example.com/clip.mp4?sig=a%2fb#t=2",
+ host: "cdn.example.com",
+ });
+ });
+
+ it("separates encoded filename characters from a video playback fragment", () => {
+ expect(resolveMarkdownLinkPresentation("/tmp/clip%23one.mp4#t=2")).toMatchObject({
+ path: "/tmp/clip#one.mp4",
+ label: "clip#one.mp4",
+ icon: "video",
+ });
+ });
+
it("extracts external link hosts", () => {
expect(resolveMarkdownLinkPresentation("https://example.com/docs?q=1")).toEqual({
kind: "external",
@@ -11,15 +27,16 @@ describe("resolveMarkdownLinkPresentation", () => {
});
});
- it("renders file URLs as basename pills with positions", () => {
- expect(
- resolveMarkdownLinkPresentation("file:///Users/julius/project/src/main.ts#L42C7"),
- ).toEqual({
+ it.each([
+ ["file:///Users/julius/project/src/main.ts#L42C7", "/Users/julius/project/src/main.ts"],
+ ["file://server/share/src/main.ts#L42C7", "\\\\server\\share\\src\\main.ts"],
+ ])("preserves the file URL path and position for %s", (href, path) => {
+ expect(resolveMarkdownLinkPresentation(href)).toEqual({
kind: "file",
- href: "file:///Users/julius/project/src/main.ts#L42C7",
+ href,
icon: "typescript",
label: "main.ts:42:7",
- path: "/Users/julius/project/src/main.ts",
+ path,
line: 42,
column: 7,
});
diff --git a/apps/mobile/src/lib/markdownMedia.test.ts b/apps/mobile/src/lib/markdownMedia.test.ts
new file mode 100644
index 00000000000..77834630dc2
--- /dev/null
+++ b/apps/mobile/src/lib/markdownMedia.test.ts
@@ -0,0 +1,77 @@
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import { resolveMarkdownMediaPreview } from "./markdownMedia";
+
+const input = {
+ environmentId: EnvironmentId.make("environment-1"),
+ threadId: ThreadId.make("thread-1"),
+ workspaceRoot: "/repo",
+};
+
+describe("resolveMarkdownMediaPreview", () => {
+ it("decodes remote filenames once without changing the authored URL", () => {
+ const href = "https://cdn.example.com/clip%20one%2520%2Emp4?signature=a%2fb#t=2";
+ expect(resolveMarkdownMediaPreview(href, input)).toMatchObject({
+ kind: "video",
+ source: {
+ uri: href,
+ actionsSource: {
+ name: "clip one%20.mp4",
+ mimeType: "video/mp4",
+ reference: { kind: "url", url: href },
+ },
+ },
+ });
+ });
+
+ it("provides extensionless image actions only for image embeds", () => {
+ const href = "https://cdn.example.com/render?id=42";
+ expect(resolveMarkdownMediaPreview(href, input)).toBeNull();
+ expect(resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true })).toMatchObject({
+ kind: "image",
+ source: { actionsSource: { reference: { kind: "url", url: href }, mimeType: "image/*" } },
+ });
+ });
+
+ it.each([
+ ["/tmp/frame%23one.png:12", "/tmp/frame#one.png"],
+ ["/tmp/frame%3Fone.png:12:3", "/tmp/frame?one.png"],
+ ["/tmp/frame%2523one.png:12", "/tmp/frame%23one.png"],
+ ["file://server/share/frame.png", "\\\\server\\share\\frame.png"],
+ ["\\\\server\\share\\frame.png", "\\\\server\\share\\frame.png"],
+ ])("keeps encoded filename and UNC semantics for %s", (href, path) => {
+ expect(resolveMarkdownMediaPreview(href, input)).toMatchObject({
+ kind: "image",
+ source: {
+ resource: { path },
+ actionsSource: { reference: { kind: "file", path } },
+ },
+ });
+ });
+
+ it("separates a video playback fragment from literal filename characters", () => {
+ expect(resolveMarkdownMediaPreview("/tmp/clip%23one.mp4#t=2", input)).toMatchObject({
+ kind: "video",
+ source: {
+ srcFragment: "#t=2",
+ resource: { path: "/tmp/clip#one.mp4" },
+ actionsSource: { reference: { kind: "file", path: "/tmp/clip#one.mp4" } },
+ },
+ });
+ });
+
+ it("resolves protocol-relative media for native APIs without rewriting its signed query", () => {
+ expect(
+ resolveMarkdownMediaPreview("//cdn.example.com/clip.mp4?signature=a%2fb#t=2", input),
+ ).toMatchObject({
+ kind: "video",
+ source: {
+ uri: "https://cdn.example.com/clip.mp4?signature=a%2fb#t=2",
+ actionsSource: {
+ reference: { kind: "url", url: "//cdn.example.com/clip.mp4?signature=a%2fb#t=2" },
+ },
+ },
+ });
+ });
+});
diff --git a/apps/mobile/src/lib/markdownMedia.ts b/apps/mobile/src/lib/markdownMedia.ts
new file mode 100644
index 00000000000..2196c2f22f2
--- /dev/null
+++ b/apps/mobile/src/lib/markdownMedia.ts
@@ -0,0 +1,89 @@
+import {
+ classifyMarkdownImageSource,
+ markdownImageSourceFragment,
+} from "@t3tools/client-runtime/markdown-images";
+import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { normalizeNativeMarkdownUrl } from "@t3tools/mobile-markdown-text/links";
+import { mediaMimeType, mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";
+import {
+ mediaFileReference,
+ mediaReferenceFileName,
+ mediaUrlReference,
+} from "@t3tools/client-runtime/media-reference";
+
+import type { FilePreviewSource } from "../components/FilePreviewModal";
+import type { MediaVideoPreviewSource } from "./videoPreviewSource";
+import type { MediaActionsSource } from "./mediaActions";
+
+/** Resolves only explicit media references. Ordinary links keep their existing navigation. */
+export function resolveMarkdownMediaPreview(
+ href: string,
+ input: {
+ readonly environmentId: EnvironmentId;
+ readonly threadId: ThreadId;
+ readonly workspaceRoot: string | null | undefined;
+ /** Image syntax can target an endpoint without a recognizable extension. */
+ readonly imageEmbed?: boolean;
+ },
+):
+ | { readonly kind: "image"; readonly source: FilePreviewSource }
+ | { readonly kind: "video"; readonly source: MediaVideoPreviewSource }
+ | null {
+ const classified = classifyMarkdownImageSource(href, input.workspaceRoot);
+ if (classified._tag === "Blocked") return null;
+ const path =
+ classified._tag === "WorkspaceFile"
+ ? classified.path.replace(/:\d+(?::\d+)?$/, "")
+ : classified.uri.split(/[?#]/, 1)[0]!;
+ const basename = path.split(/[\\/]/).at(-1) ?? "";
+ const extensionIndex = basename.lastIndexOf(".");
+ // Local paths have already been decoded. Do not interpret literal #, ?, or % characters again.
+ const detectedMimeType =
+ classified._tag === "Direct"
+ ? mediaMimeType(classified.uri)
+ : extensionIndex < 0
+ ? null
+ : mediaMimeTypeFromExtension(basename.slice(extensionIndex));
+ const mimeType = detectedMimeType ?? (input.imageEmbed ? "image/*" : null);
+ if (mimeType === null) return null;
+ const kind = mimeType.startsWith("video/") ? "video" : "image";
+ const reference =
+ classified._tag === "Direct"
+ ? mediaUrlReference(classified.uri)
+ : mediaFileReference(path, input.workspaceRoot);
+ const name =
+ (reference && mediaReferenceFileName(reference)) || (kind === "video" ? "Video" : "Image");
+ const srcFragment = markdownImageSourceFragment(href);
+ const target =
+ classified._tag === "Direct"
+ ? { uri: normalizeNativeMarkdownUrl(classified.uri) }
+ : {
+ environmentId: input.environmentId,
+ resource: {
+ _tag: "media-file" as const,
+ threadId: input.threadId,
+ path,
+ },
+ ...(srcFragment ? { srcFragment } : {}),
+ };
+ const actionsSource: MediaActionsSource =
+ classified._tag === "Direct"
+ ? { reference, uri: classified.uri, name, mimeType }
+ : {
+ reference,
+ environmentId: input.environmentId,
+ threadId: input.threadId,
+ resource: { _tag: "media-file", threadId: input.threadId, path },
+ name,
+ mimeType,
+ };
+ return kind === "video"
+ ? {
+ kind,
+ source: { type: "media", name, mimeType, ...target, actionsSource },
+ }
+ : {
+ kind,
+ source: { kind, name, ...target, actionsSource },
+ };
+}
diff --git a/apps/mobile/src/lib/mediaActions.ts b/apps/mobile/src/lib/mediaActions.ts
new file mode 100644
index 00000000000..14dc2de7bd2
--- /dev/null
+++ b/apps/mobile/src/lib/mediaActions.ts
@@ -0,0 +1,121 @@
+import { useNavigation } from "@react-navigation/native";
+import type { MediaReference } from "@t3tools/client-runtime/media-reference";
+import type { AssetResource, EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { normalizeNativeMarkdownUrl } from "@t3tools/mobile-markdown-text/links";
+import { useEffect, useRef, useState } from "react";
+import { Alert } from "react-native";
+
+import { useRefreshAssetUrl } from "../state/assets";
+import { downloadAndShareAttachment, shareLocalAttachment } from "./attachmentDownload";
+import { copyTextWithHaptic } from "./copyTextWithHaptic";
+
+/** Authored source metadata is kept separate from temporary preview/download URLs. */
+export type MediaActionsSource = {
+ readonly reference?: MediaReference;
+ readonly name: string;
+ readonly mimeType: string;
+} & (
+ | { readonly uri: string }
+ | {
+ readonly environmentId: EnvironmentId;
+ readonly threadId: ThreadId;
+ readonly resource: AssetResource;
+ }
+);
+
+export function useMediaActions(source: MediaActionsSource | undefined, onOpenFile?: () => void) {
+ const navigation = useNavigation();
+ const refresh = useRefreshAssetUrl(
+ source && "environmentId" in source ? source.environmentId : null,
+ source && "resource" in source ? source.resource : null,
+ );
+ const controller = useRef<AbortController | null>(null);
+ const [sharing, setSharing] = useState(false);
+ useEffect(() => () => controller.current?.abort(), []);
+
+ const share = () => {
+ if (!source || controller.current) return;
+ const request = new AbortController();
+ controller.current = request;
+ setSharing(true);
+ void (async () => {
+ const uri = "uri" in source ? normalizeNativeMarkdownUrl(source.uri) : await refresh();
+ if (request.signal.aborted) return;
+ if (uri === null) throw new Error("The file could not be loaded. Reconnect and try again.");
+ const input = {
+ attachment: { name: source.name, mimeType: source.mimeType },
+ signal: request.signal,
+ };
+ if (/^(file|content):/i.test(uri)) await shareLocalAttachment({ ...input, uri });
+ else await downloadAndShareAttachment({ ...input, url: uri });
+ })()
+ .catch((error: unknown) => {
+ if (!request.signal.aborted) {
+ Alert.alert(
+ "Could not share file",
+ error instanceof Error ? error.message : "Try again.",
+ );
+ }
+ })
+ .finally(() => {
+ if (controller.current === request) {
+ controller.current = null;
+ if (!request.signal.aborted) setSharing(false);
+ }
+ });
+ };
+
+ const reference = source?.reference;
+ const actions: { id: string; title: string; run: () => void; disabled?: boolean }[] = source
+ ? [
+ ...(reference?.kind === "file"
+ ? [
+ {
+ id: "copy-path",
+ title: "Copy full path",
+ run: () => copyTextWithHaptic(reference.path),
+ },
+ ...(reference.relativePath
+ ? [
+ {
+ id: "copy-relative-path",
+ title: "Copy relative path",
+ run: () => copyTextWithHaptic(reference.relativePath!),
+ },
+ ]
+ : []),
+ ...(reference.relativePath && source && "environmentId" in source
+ ? [
+ {
+ id: "open-file",
+ title: "Open in file viewer",
+ run: () => {
+ onOpenFile?.();
+ navigation.navigate("ThreadFile", {
+ environmentId: String(source.environmentId),
+ threadId: String(source.threadId),
+ path: reference.relativePath!.split("/"),
+ });
+ },
+ },
+ ]
+ : []),
+ ]
+ : reference
+ ? [{ id: "copy-url", title: "Copy URL", run: () => copyTextWithHaptic(reference.url) }]
+ : []),
+ {
+ id: "share",
+ title: sharing ? "Opening share sheet…" : "Save or share",
+ run: share,
+ disabled: sharing,
+ },
+ ]
+ : [];
+ return {
+ title: reference?.kind === "file" ? reference.path : reference?.url,
+ actions,
+ sharing,
+ share,
+ };
+}
diff --git a/apps/mobile/src/lib/nativeMarkdownText.test.ts b/apps/mobile/src/lib/nativeMarkdownText.test.ts
index 867d9e98301..1e7cb5f3164 100644
--- a/apps/mobile/src/lib/nativeMarkdownText.test.ts
+++ b/apps/mobile/src/lib/nativeMarkdownText.test.ts
@@ -11,6 +11,43 @@ import {
} from "@t3tools/mobile-markdown-text/markdown";
describe("nativeMarkdownTextRuns", () => {
+ it("links a path-shaped code span without changing the same path in prose", () => {
+ expect(
+ nativeMarkdownTextRuns({
+ type: "paragraph",
+ children: [
+ { type: "text", content: "/tmp/frame.png " },
+ { type: "code_inline", content: "/tmp/frame.png" },
+ ],
+ }),
+ ).toEqual([
+ { text: "/tmp/frame.png " },
+ { text: "frame.png", href: "/tmp/frame.png", fileIcon: "image" },
+ ]);
+ });
+
+ it("preserves the destination of a link with a code-formatted label", () => {
+ expect(
+ nativeMarkdownTextRuns({
+ type: "paragraph",
+ children: [
+ {
+ type: "link",
+ href: "https://example.com/docs",
+ children: [{ type: "code_inline", content: "src/main.ts" }],
+ },
+ ],
+ }),
+ ).toEqual([
+ {
+ text: "src/main.ts",
+ code: true,
+ href: "https://example.com/docs",
+ externalHost: "example.com",
+ },
+ ]);
+ });
+
it("preserves inline emphasis and code styles", () => {
const node: MarkdownNode = {
type: "paragraph",
diff --git a/apps/mobile/src/lib/videoPreviewSource.ts b/apps/mobile/src/lib/videoPreviewSource.ts
new file mode 100644
index 00000000000..af87a8d0f73
--- /dev/null
+++ b/apps/mobile/src/lib/videoPreviewSource.ts
@@ -0,0 +1,54 @@
+import type { AssetResource, ChatFileAttachment, EnvironmentId } from "@t3tools/contracts";
+
+import type { DraftComposerFileAttachment } from "./composerImages";
+import type { MediaActionsSource } from "./mediaActions";
+
+export type MediaVideoPreviewSource = {
+ readonly type: "media";
+ readonly name: string;
+ readonly mimeType: string;
+ readonly sourceIdentifier?: string;
+ readonly srcFragment?: string;
+ readonly actionsSource?: MediaActionsSource;
+} & (
+ | { readonly uri: string }
+ | {
+ readonly environmentId: EnvironmentId;
+ readonly resource: Extract<AssetResource, { readonly _tag: "media-file" }>;
+ }
+);
+
+/** Resolves the current capability without making it the identity of the video. */
+export function mediaVideoPreviewUri(
+ source: MediaVideoPreviewSource,
+ assetUrl: string | null,
+): string | null {
+ if ("uri" in source) return source.uri;
+ return assetUrl === null ? null : assetUrl + (source.srcFragment ?? "");
+}
+
+/** Keeps thumbnails independent of refreshed asset signatures and scoped to their environment. */
+export function mediaVideoThumbnailKey(source: MediaVideoPreviewSource): string {
+ return JSON.stringify(
+ "uri" in source
+ ? ["media-video", source.uri]
+ : [
+ "media-video",
+ source.environmentId,
+ source.resource.threadId,
+ source.resource.path,
+ source.srcFragment ?? "",
+ ],
+ );
+}
+
+export type AttachmentVideoPreviewSource = (
+ | { readonly type: "local"; readonly attachment: DraftComposerFileAttachment }
+ | {
+ readonly type: "remote";
+ readonly environmentId: EnvironmentId;
+ readonly attachment: ChatFileAttachment;
+ }
+) & { readonly sourceIdentifier?: string };
+
+export type VideoPreviewSource = AttachmentVideoPreviewSource | MediaVideoPreviewSource;
diff --git a/apps/mobile/src/state/assets.ts b/apps/mobile/src/state/assets.ts
index 611a1ed8b99..9e3e43c7cdc 100644
--- a/apps/mobile/src/state/assets.ts
+++ b/apps/mobile/src/state/assets.ts
@@ -2,9 +2,11 @@ import { useAtomValue } from "@effect/atom-react";
import { createAssetEnvironmentAtoms, resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
+import { useCallback } from "react";
import { connectionAtomRuntime } from "../connection/runtime";
import { usePreparedConnection } from "./session";
+import { useAtomQueryRunner } from "./use-atom-query-runner";
export const assetEnvironment = createAssetEnvironmentAtoms(connectionAtomRuntime);
@@ -44,3 +46,23 @@ export function useAssetUrl(
const state = useAssetUrlState(environmentId, resource);
return state._tag === "Success" ? state.url : null;
}
+
+/** Explicit playback and sharing must reauthorize files that may have been replaced on disk. */
+export function useRefreshAssetUrl(
+ environmentId: EnvironmentId | null,
+ resource: AssetResource | null,
+): () => Promise<string | null> {
+ const connection = usePreparedConnection(environmentId);
+ const httpBaseUrl = connection._tag === "Some" ? connection.value.httpBaseUrl : null;
+ const createUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
+ refresh: true,
+ reportFailure: false,
+ });
+ return useCallback(async () => {
+ if (environmentId === null || resource === null || httpBaseUrl === null) return null;
+ const result = await createUrl({ environmentId, input: { resource } });
+ return result._tag === "Success"
+ ? resolveAssetUrl(httpBaseUrl, result.value.relativeUrl)
+ : null;
+ }, [createUrl, environmentId, httpBaseUrl, resource]);
+}
diff --git a/apps/mobile/src/state/use-atom-query-runner.ts b/apps/mobile/src/state/use-atom-query-runner.ts
index 22f971e09a5..691b1f43cb8 100644
--- a/apps/mobile/src/state/use-atom-query-runner.ts
+++ b/apps/mobile/src/state/use-atom-query-runner.ts
@@ -1,7 +1,7 @@
import { RegistryContext } from "@effect/atom-react";
import {
executeAtomQuery,
- type AtomCommandOptions,
+ type AtomQueryOptions,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import { AsyncResult, type Atom } from "effect/unstable/reactivity";
@@ -9,12 +9,13 @@ import { useCallback, useContext } from "react";
export function useAtomQueryRunner<T, A, E>(
family: (target: T) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
- options?: string | AtomCommandOptions,
+ options?: string | AtomQueryOptions,
): (target: T) => Promise<AtomCommandResult<A, E>> {
const registry = useContext(RegistryContext);
const explicitLabel = typeof options === "string" ? options : options?.label;
const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true);
const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true);
+ const refresh = typeof options === "string" ? false : (options?.refresh ?? false);
return useCallback(
(target: T) => {
@@ -23,8 +24,9 @@ export function useAtomQueryRunner<T, A, E>(
label: explicitLabel ?? atom.label?.[0] ?? "atom query",
reportFailure,
reportDefect,
+ refresh,
});
},
- [explicitLabel, family, registry, reportDefect, reportFailure],
+ [explicitLabel, family, registry, refresh, reportDefect, reportFailure],
);
}
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts
index 8cf9c642384..4a47a17fabc 100644
--- a/apps/server/src/assets/AssetAccess.test.ts
+++ b/apps/server/src/assets/AssetAccess.test.ts
@@ -1,4 +1,7 @@
+// @effect-diagnostics nodeBuiltinImport:off - tests inject swaps at the native open boundary.
import * as NodeServices from "@effect/platform-node/NodeServices";
+import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
+import * as NodeFSP from "node:fs/promises";
import { AssetPreviewTypeValidationError, ThreadId } from "@t3tools/contracts";
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
import { describe, expect, it } from "@effect/vitest";
@@ -9,18 +12,28 @@ import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as TestClock from "effect/testing/TestClock";
+import { HttpServerResponse } from "effect/unstable/http";
+import { vi } from "vite-plus/test";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfig from "../config.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
+import { assetFileResponse } from "../http.ts";
import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
+import { openMediaFile } from "./MediaFile.ts";
+
+vi.mock("node:fs/promises", async (importOriginal) => {
+ const actual = await importOriginal<typeof NodeFSP>();
+ return { ...actual, open: vi.fn(actual.open), realpath: vi.fn(actual.realpath) };
+});
const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-asset-access-test-",
});
const testLayer = Layer.mergeAll(
+ NodeHttpPlatform.layer,
configLayer,
WorkspacePaths.layer,
ProjectFaviconResolver.layer.pipe(
@@ -31,6 +44,328 @@ const testLayer = Layer.mergeAll(
).pipe(Layer.provideMerge(NodeServices.layer));
describe("AssetAccess", () => {
+ it.effect("issues exact URLs for images and videos outside the workspace", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-root-" });
+ const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-outside-" });
+ for (const [name, mimeType] of [
+ ["screenshot.png", "image/png"],
+ ["recording.mp4", "video/mp4"],
+ ["recording.webm", "video/webm"],
+ ] as const) {
+ const filePath = path.join(outside, name);
+ yield* fs.writeFileString(filePath, "media");
+ const canonicalFile = yield* fs.realPath(filePath);
+ const result = yield* issueAssetUrl({
+ resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
+ workspaceRoot: root,
+ });
+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const separator = suffix.indexOf("/");
+ const token = suffix.slice(0, separator);
+ expect(yield* resolveAsset(token, suffix.slice(separator + 1))).toMatchObject({
+ kind: "file",
+ path: canonicalFile,
+ mimeType,
+ });
+ yield* fs.writeFileString(path.join(outside, "sibling.png"), "private sibling");
+ expect(yield* resolveAsset(token, "sibling.png")).toBeNull();
+ expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
+ expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
+ }
+ }).pipe(Effect.provide(testLayer)),
+ );
+
+ it.effect("resolves relative media paths from the thread workspace, including outside it", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-relative-" });
+ const root = path.join(directory, "workspace");
+ yield* fs.makeDirectory(root);
+ for (const relativePath of ["screenshot.png", "../recording.mp4"]) {
+ const filePath = path.resolve(root, relativePath);
+ yield* fs.writeFileString(filePath, "media");
+ const result = yield* issueAssetUrl({
+ resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: relativePath },
+ workspaceRoot: root,
+ });
+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const separator = suffix.indexOf("/");
+ expect(
+ yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
+ ).toMatchObject({
+ kind: "file",
+ path: yield* fs.realPath(filePath),
+ });
+ }
+ }).pipe(Effect.provide(testLayer)),
+ );
+
+ it.effect("rejects non-media files, disguised targets, and directories", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-validation-" });
+ for (const name of ["report.html", "secret.txt", "secret.%70ng", "secret.png#private.txt"]) {
+ const filePath = path.join(root, name);
+ yield* fs.writeFileString(filePath, "not media");
+ const error = yield* issueAssetUrl({
+ resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
+ }).pipe(Effect.flip);
+ expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
+ }
+ const disguisedPath = path.join(root, "disguised.png");
+ yield* fs.symlink(path.join(root, "report.html"), disguisedPath);
+ const disguisedError = yield* issueAssetUrl({
+ resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: disguisedPath },
+ }).pipe(Effect.flip);
+ expect(disguisedError).toBeInstanceOf(AssetPreviewTypeValidationError);
+ const directoryPath = path.join(root, "directory.png");
+ yield* fs.makeDirectory(directoryPath);
+ const directoryError = yield* issueAssetUrl({
+ resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: directoryPath },
+ }).pipe(Effect.flip);
+ expect(directoryError._tag).toBe("AssetWorkspaceAssetNotFoundError");
+ }).pipe(Effect.provide(testLayer)),
+ );
+
+ it.effect("binds media URLs to the canonical target and rejects symlink substitution", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-symlink-" });
+ const filePath = path.join(root, "actual.svg");
+ const aliasPath = path.join(root, "alias.png");
+ const replacementPath = path.join(root, "other.svg");
+ yield* fs.writeFileString(filePath, "<svg/>");
+ yield* fs.writeFileString(replacementPath, "<svg>private</svg>");
+ yield* fs.symlink(filePath, aliasPath);
+ const canonicalFile = yield* fs.realPath(filePath);
+ const result = yield* issueAssetUrl({
+ resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: aliasPath },
+ });
+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const separator = suffix.indexOf("/");
+ const token = suffix.slice(0, separator);
+ const name = suffix.slice(separator + 1);
+ const expected = { kind: "file", path: canonicalFile, mimeType: "image/svg+xml" };
+ expect(yield* resolveAsset(token, name)).toMatchObject(expected);
+ yield* fs.remove(aliasPath);
+ yield* fs.symlink(replacementPath, aliasPath);
+ expect(yield* resolveAsset(token, name)).toMatchObject(expected);
+ yield* fs.remove(filePath);
+ yield* fs.symlink(replacementPath, filePath);
+ expect(yield* resolveAsset(token, name)).toBeNull();
+ }).pipe(Effect.provide(testLayer)),
+ );
+
+ it.effect("keeps full and partial responses bound to the file opened during resolution", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-file-" });
+ const filePath = path.join(root, "recording.mp4");
+ const savedPath = path.join(root, "saved.mp4");
+ const secretPath = path.join(root, "secret.txt");
+ yield* fs.writeFileString(filePath, "0123456789");
+ yield* fs.writeFileString(secretPath, "private information");
+ const result = yield* issueAssetUrl({
+ resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
+ });
+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const separator = suffix.indexOf("/");
+ for (const [range, expected, status] of [
+ [undefined, "0123456789", 200],
+ ["bytes=2-5", "2345", 206],
+ ] as const) {
+ const asset = yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
+ if (!asset) throw new Error("Expected a resolved media file");
+
+ yield* fs.rename(filePath, savedPath);
+ yield* fs.symlink(secretPath, filePath);
+ const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, range));
+ expect(response.status).toBe(status);
+ expect(response.headers.get("content-length")).toBe(String(expected.length));
+ expect(yield* Effect.promise(() => response.text())).toBe(expected);
+ yield* fs.remove(filePath);
+ yield* fs.rename(savedPath, filePath);
+ }
+ }).pipe(Effect.provide(testLayer)),
+ );
+
+ it.effect("rejects a symlink swapped in after canonical validation but before open", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-race-" });
+ const filePath = path.join(root, "recording.mp4");
+ const secretPath = path.join(root, "secret.txt");
+ yield* fs.writeFileString(filePath, "video");
+ yield* fs.writeFileString(secretPath, "secret");
+ const canonicalPath = yield* fs.realPath(filePath);
+ const result = yield* issueAssetUrl({
+ resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
+ });
+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const separator = suffix.indexOf("/");
+ const swappingFileSystem = FileSystem.FileSystem.of({
+ ...fs,
+ stat: Effect.fn(function* (requestedPath) {
+ const info = yield* fs.stat(requestedPath);
+ if (requestedPath === canonicalPath) {
+ yield* fs.remove(filePath);
+ yield* fs.symlink(secretPath, filePath);
+ }
+ return info;
+ }),
+ });
+ expect(
+ yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
+ Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
+ ),
+ ).toBeNull();
+ }).pipe(Effect.provide(testLayer)),
+ );
+
+ it.effect("closes a descriptor rejected when its path changes during open", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-rejected-" });
+ const filePath = path.join(root, "recording.mp4");
+ const secretPath = path.join(root, "secret.txt");
+ yield* fs.writeFileString(filePath, "video");
+ yield* fs.writeFileString(secretPath, "secret");
+ const canonicalPath = yield* fs.realPath(filePath);
+ const originalOpen = (yield* Effect.promise(() =>
+ vi.importActual<typeof NodeFSP>("node:fs/promises"),
+ )).open;
+ let opened: NodeFSP.FileHandle | undefined;
+ const openSpy = vi.mocked(NodeFSP.open).mockImplementation(async (target, flags, mode) => {
+ const handle = await originalOpen(target, flags, mode);
+ if (target === canonicalPath) {
+ opened = handle;
+ await NodeFSP.unlink(filePath);
+ await NodeFSP.symlink(secretPath, filePath);
+ }
+ return handle;
+ });
+ yield* Effect.addFinalizer(() => Effect.sync(() => openSpy.mockImplementation(originalOpen)));
+ expect(yield* openMediaFile(canonicalPath)).toBeNull();
+ expect(opened).toBeDefined();
+ expect(opened?.fd).toBe(-1);
+ }).pipe(Effect.provide(testLayer)),
+ );
+
+ it.effect("rejects an ancestor symlink race even when canonical path rechecks would pass", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-parent-race-" });
+ const publicDirectory = path.join(root, "public");
+ const privateDirectory = path.join(root, "private");
+ yield* fs.makeDirectory(publicDirectory);
+ yield* fs.makeDirectory(privateDirectory);
+ const filePath = path.join(publicDirectory, "recording.mp4");
+ yield* fs.writeFileString(filePath, "public video");
+ yield* fs.writeFileString(path.join(privateDirectory, "recording.mp4"), "private video");
+ const canonicalPath = yield* fs.realPath(filePath);
+ const result = yield* issueAssetUrl({
+ resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
+ });
+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const separator = suffix.indexOf("/");
+ const native = yield* Effect.promise(() =>
+ vi.importActual<typeof NodeFSP>("node:fs/promises"),
+ );
+ const savedDirectory = path.join(root, "saved");
+ const realpathSpy = vi.mocked(NodeFSP.realpath).mockImplementationOnce(async () => {
+ // A pathname-only guard can see the original parents during realpath,
+ // but the private file during both lstat calls and open.
+ await native.unlink(publicDirectory);
+ await native.rename(savedDirectory, publicDirectory);
+ const canonical = await native.realpath(canonicalPath);
+ await native.rename(publicDirectory, savedDirectory);
+ await native.symlink(privateDirectory, publicDirectory, "junction");
+ return canonical;
+ });
+ yield* Effect.addFinalizer(() =>
+ Effect.sync(() => realpathSpy.mockReset().mockImplementation(native.realpath)),
+ );
+ const swappingFileSystem = FileSystem.FileSystem.of({
+ ...fs,
+ realPath: Effect.fn(function* (requestedPath) {
+ const canonical = yield* fs.realPath(requestedPath);
+ if (requestedPath === canonicalPath) {
+ yield* fs.rename(publicDirectory, savedDirectory);
+ yield* Effect.promise(() =>
+ NodeFSP.symlink(privateDirectory, publicDirectory, "junction"),
+ );
+ }
+ return canonical;
+ }),
+ });
+ expect(
+ yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
+ Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
+ ),
+ ).toBeNull();
+ }).pipe(Effect.provide(testLayer)),
+ );
+
+ it.effect("keeps in-place edits readable but requires a new URL after atomic replacement", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-replacement-" });
+ const filePath = path.join(root, "recording.mp4");
+ yield* fs.writeFileString(filePath, "original");
+ const input = {
+ resource: {
+ _tag: "media-file" as const,
+ threadId: ThreadId.make("thread-1"),
+ path: filePath,
+ },
+ };
+ const original = yield* issueAssetUrl(input);
+ const suffix = original.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const separator = suffix.indexOf("/");
+ const token = suffix.slice(0, separator);
+ const name = suffix.slice(separator + 1);
+ yield* fs.writeFileString(filePath, "in-place edit");
+ const edited = yield* resolveAsset(token, name);
+ if (!edited) throw new Error("Expected the edited media file");
+ const editedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(edited));
+ expect(yield* Effect.promise(() => editedResponse.text())).toBe("in-place edit");
+
+ const replacement = path.join(root, "replacement.mp4");
+ yield* fs.writeFileString(replacement, "replacement");
+ yield* fs.rename(replacement, filePath);
+ expect(yield* resolveAsset(token, name)).toBeNull();
+
+ const renewed = yield* issueAssetUrl(input);
+ const renewedSuffix = renewed.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const renewedSeparator = renewedSuffix.indexOf("/");
+ const renewedAsset = yield* resolveAsset(
+ renewedSuffix.slice(0, renewedSeparator),
+ renewedSuffix.slice(renewedSeparator + 1),
+ );
+ if (!renewedAsset) throw new Error("Expected the replacement media file");
+ const renewedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(renewedAsset));
+ expect(yield* Effect.promise(() => renewedResponse.text())).toBe("replacement");
+ yield* fs.remove(filePath);
+ expect(
+ yield* resolveAsset(
+ renewedSuffix.slice(0, renewedSeparator),
+ renewedSuffix.slice(renewedSeparator + 1),
+ ),
+ ).toBeNull();
+ }).pipe(Effect.provide(testLayer)),
+ );
+
it.effect("issues workspace URLs that resolve the entry file and sibling assets", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts
index d064ec07529..05801acca88 100644
--- a/apps/server/src/assets/AssetAccess.ts
+++ b/apps/server/src/assets/AssetAccess.ts
@@ -16,6 +16,7 @@ import {
import {
isWorkspaceImagePreviewPath,
isWorkspacePreviewEntryPath,
+ mediaMimeTypeFromExtension,
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
} from "@t3tools/shared/filePreview";
@@ -41,6 +42,7 @@ import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../atta
import * as ServerConfig from "../config.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
+import { openMediaFile, type OpenMediaFile } from "./MediaFile.ts";
export const ASSET_ROUTE_PREFIX = "/api/assets";
@@ -76,6 +78,14 @@ const AssetClaimsSchema = Schema.Union([
relativePath: Schema.String,
expiresAt: Schema.Number,
}),
+ Schema.Struct({
+ version: Schema.Literal(1),
+ kind: Schema.Literal("media-file-exact"),
+ filePath: Schema.String,
+ device: Schema.String,
+ inode: Schema.String,
+ expiresAt: Schema.Number,
+ }),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("attachment"),
@@ -115,6 +125,7 @@ export type ResolvedAsset = {
readonly download?: boolean;
readonly fileName?: string;
readonly mimeType?: string;
+ readonly file?: OpenMediaFile;
};
function decodeClaims(encodedPayload: string): AssetClaims | null {
@@ -211,6 +222,55 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
let sourcePath: string | undefined;
switch (input.resource._tag) {
+ case "media-file": {
+ let requestedPath = input.resource.path;
+ if (!path.isAbsolute(requestedPath)) {
+ if (!input.workspaceRoot) {
+ return yield* new AssetWorkspaceContextNotFoundError({ resource: input.resource });
+ }
+ const workspaceRoot = yield* workspacePaths
+ .normalizeWorkspaceRoot(input.workspaceRoot)
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new AssetWorkspaceRootNormalizationError({ resource: input.resource, cause }),
+ ),
+ );
+ requestedPath = path.resolve(workspaceRoot, requestedPath);
+ }
+ const canonicalFile = yield* resolveCanonicalFile(requestedPath).pipe(
+ Effect.mapError(
+ (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
+ ),
+ );
+ if (!canonicalFile) {
+ return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
+ }
+ if (mediaMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
+ return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
+ }
+ const identity = yield* openMediaFile(canonicalFile).pipe(
+ Effect.map((file) =>
+ file ? { device: file.info.dev.toString(), inode: file.info.ino.toString() } : null,
+ ),
+ Effect.scoped,
+ Effect.mapError(
+ (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
+ ),
+ );
+ if (!identity) {
+ return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
+ }
+ claims = {
+ version: 1,
+ kind: "media-file-exact",
+ filePath: canonicalFile,
+ ...identity,
+ expiresAt,
+ };
+ fileName = path.basename(canonicalFile);
+ break;
+ }
case "workspace-file": {
if (!input.workspaceRoot) {
return yield* new AssetWorkspaceContextNotFoundError({
@@ -526,6 +586,30 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
const decodedPath = decodeRelativePath(relativePath);
if (decodedPath === null) return null;
const path = yield* Path.Path;
+ if (claims.kind === "media-file-exact") {
+ if (decodedPath !== path.basename(claims.filePath)) return null;
+ const canonicalFile = yield* resolveCanonicalFile(claims.filePath).pipe(
+ Effect.tapError((cause) =>
+ Effect.logError("Failed to resolve canonical media path.", {
+ filePath: claims.filePath,
+ cause,
+ }),
+ ),
+ Effect.orElseSucceed(() => null),
+ );
+ if (canonicalFile !== claims.filePath) return null;
+ const mimeType = mediaMimeTypeFromExtension(path.extname(canonicalFile));
+ if (!mimeType) return null;
+ const file = yield* openMediaFile(canonicalFile, claims).pipe(
+ Effect.tapError((cause) =>
+ Effect.logError("Failed to open canonical media file.", { filePath: canonicalFile, cause }),
+ ),
+ Effect.orElseSucceed(() => null),
+ );
+ return file
+ ? ({ kind: "file", path: canonicalFile, mimeType, file } satisfies ResolvedAsset)
+ : null;
+ }
if (claims.kind === "workspace-file-exact") {
if (decodedPath !== path.basename(claims.relativePath)) return null;
const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
diff --git a/apps/server/src/assets/MediaFile.ts b/apps/server/src/assets/MediaFile.ts
new file mode 100644
index 00000000000..f1b63bb659e
--- /dev/null
+++ b/apps/server/src/assets/MediaFile.ts
@@ -0,0 +1,113 @@
+// @effect-diagnostics nodeBuiltinImport:off - FileSystem does not expose no-follow
+// or non-blocking open flags, and the response must keep the validated descriptor.
+import * as NodeFS from "node:fs";
+import * as NodeFSP from "node:fs/promises";
+
+import * as NodeStream from "@effect/platform-node/NodeStream";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+
+class MediaFileOpenError extends Schema.TaggedErrorClass<MediaFileOpenError>()(
+ "MediaFileOpenError",
+ {
+ path: Schema.String,
+ cause: Schema.Defect(),
+ },
+) {
+ override get message(): string {
+ return `Failed to open media file '${this.path}'.`;
+ }
+}
+
+class MediaFileStatError extends Schema.TaggedErrorClass<MediaFileStatError>()(
+ "MediaFileStatError",
+ {
+ path: Schema.String,
+ cause: Schema.Defect(),
+ },
+) {
+ override get message(): string {
+ return `Failed to read metadata for media file '${this.path}'.`;
+ }
+}
+
+/** Holds the file identity and descriptor for one HTTP request, never a copy of its bytes. */
+export interface OpenMediaFile {
+ readonly handle: NodeFSP.FileHandle;
+ readonly info: NodeFS.BigIntStats;
+}
+
+/** Opens a canonical media path once. Replacements cannot change the response's source. */
+export const openMediaFile = Effect.fn("openMediaFile")(function* (
+ filePath: string,
+ identity?: { readonly device: string; readonly inode: string },
+) {
+ return yield* Effect.acquireRelease(
+ Effect.tryPromise({
+ try: async () => {
+ const before = await NodeFSP.lstat(filePath, { bigint: true });
+ if (!before.isFile() || before.ino === 0n) return null;
+ if (
+ identity &&
+ (before.dev.toString() !== identity.device || before.ino.toString() !== identity.inode)
+ ) {
+ return null;
+ }
+
+ // Windows lacks these flags; the descriptor/path identity checks still apply.
+ const handle = await NodeFSP.open(
+ filePath,
+ NodeFS.constants.O_RDONLY |
+ (NodeFS.constants.O_NOFOLLOW ?? 0) |
+ (NodeFS.constants.O_NONBLOCK ?? 0),
+ );
+ let accepted = false;
+ try {
+ const info = await handle.stat({ bigint: true });
+ if (!info.isFile() || info.dev !== before.dev || info.ino !== before.ino) return null;
+ if (
+ identity &&
+ (info.dev.toString() !== identity.device || info.ino.toString() !== identity.inode)
+ ) {
+ return null;
+ }
+ if ((await NodeFSP.realpath(filePath)) !== filePath) return null;
+ const after = await NodeFSP.lstat(filePath, { bigint: true });
+ if (!after.isFile() || info.dev !== after.dev || info.ino !== after.ino) return null;
+ accepted = true;
+ return { handle, info } satisfies OpenMediaFile;
+ } finally {
+ if (!accepted) await handle.close();
+ }
+ },
+ catch: (cause) => new MediaFileOpenError({ path: filePath, cause }),
+ }),
+ (file) => (file ? Effect.promise(() => file.handle.close()) : Effect.void),
+ );
+});
+
+export const statMediaFile = Effect.fn("statMediaFile")(function* (
+ filePath: string,
+ file: OpenMediaFile,
+) {
+ return yield* Effect.tryPromise({
+ try: () => file.handle.stat({ bigint: true }),
+ catch: (cause) => new MediaFileStatError({ path: filePath, cause }),
+ });
+});
+
+export const streamMediaFile = (file: OpenMediaFile, offset: bigint, bytesToRead: bigint) => {
+ const start = Number(offset);
+ const end = Number(offset + bytesToRead - 1n);
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) {
+ return null;
+ }
+ return NodeStream.fromReadable<Uint8Array>({
+ evaluate: () =>
+ file.handle.createReadStream({
+ autoClose: false,
+ start,
+ end,
+ }),
+ });
+};
diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts
index 7ae036bdc99..9d54adef8ed 100644
--- a/apps/server/src/http.test.ts
+++ b/apps/server/src/http.test.ts
@@ -1,5 +1,5 @@
import { expect, it } from "@effect/vitest";
-import { describe } from "vite-plus/test";
+import { describe, vi } 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";
@@ -7,6 +7,7 @@ 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 { openMediaFile } from "./assets/MediaFile.ts";
import {
assetResponseHeaders,
@@ -19,6 +20,179 @@ import {
const fileResponseLayer = Layer.mergeAll(NodeHttpPlatform.layer, NodeServices.layer);
describe("video asset byte ranges", () => {
+ it.effect("uses current descriptor metadata after an in-place truncate or extension", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-current-stat-" });
+ const filePath = path.join(directory, "clip.mp4");
+ for (const [contents, range, method, expected, status, contentRange] of [
+ ["1234", undefined, "GET", "1234", 200, null],
+ ["0123456789abcdef", undefined, "GET", "0123456789abcdef", 200, null],
+ ["1234", "bytes=4-", "GET", "", 416, "bytes */4"],
+ ["1234", "bytes=1-20", "GET", "234", 206, "bytes 1-3/4"],
+ ["0123456789abcdef", "bytes=10-", "GET", "abcdef", 206, "bytes 10-15/16"],
+ ["0123456789abcdef", undefined, "HEAD", "", 200, null],
+ ["", undefined, "GET", "", 200, null],
+ ["", "bytes=0-1", "GET", "", 416, "bytes */0"],
+ ] as const) {
+ yield* fs.writeFileString(filePath, "0123456789");
+ const canonicalPath = yield* fs.realPath(filePath);
+ const file = yield* openMediaFile(canonicalPath);
+ if (!file) throw new Error("Expected an opened media file");
+ yield* fs.writeFileString(filePath, contents);
+ const response = HttpServerResponse.toWeb(
+ yield* assetFileResponse(
+ { path: canonicalPath, file, mimeType: "video/mp4" },
+ range,
+ undefined,
+ method,
+ ),
+ );
+ expect(response.status).toBe(status);
+ expect(response.headers.get("content-range")).toBe(contentRange);
+ if (status !== 416) {
+ expect(response.headers.get("content-length")).toBe(
+ String(method === "HEAD" ? contents.length : expected.length),
+ );
+ }
+ expect(yield* Effect.promise(() => response.text())).toBe(expected);
+ }
+ }).pipe(Effect.provide(fileResponseLayer)),
+ );
+
+ it.effect(
+ "rejects unaddressable ranges before streaming and preserves small ranges on large files",
+ () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-offset-limit-" });
+ const filePath = path.join(directory, "clip.mp4");
+ yield* fs.writeFileString(filePath, "0123456789");
+ const canonicalPath = yield* fs.realPath(filePath);
+ const unsafeOffset = BigInt(Number.MAX_SAFE_INTEGER) + 1n;
+ const size = unsafeOffset + 32n;
+ for (const [range, status] of [
+ [`bytes=${unsafeOffset}-${unsafeOffset}`, 416],
+ [`bytes=0-${unsafeOffset}`, 416],
+ ["bytes=-1", 416],
+ [undefined, 413],
+ ["bytes=0-1", 206],
+ ] as const) {
+ const file = yield* openMediaFile(canonicalPath);
+ if (!file) throw new Error("Expected an opened media file");
+ // Model a sparse file beyond the native stream's numeric addressing limit.
+ const info = yield* Effect.promise(() => file.handle.stat({ bigint: true }));
+ info.size = size;
+ const statSpy = vi.spyOn(file.handle, "stat").mockResolvedValue(info);
+ yield* Effect.addFinalizer(() => Effect.sync(() => statSpy.mockRestore()));
+ const response = HttpServerResponse.toWeb(
+ yield* assetFileResponse({ path: canonicalPath, file, mimeType: "video/mp4" }, range),
+ );
+ expect(response.status).toBe(status);
+ if (status === 416) {
+ expect(response.headers.get("content-range")).toBe(`bytes */${size}`);
+ expect(yield* Effect.promise(() => response.text())).toBe("");
+ } else if (status === 206) {
+ expect(response.headers.get("content-range")).toBe(`bytes 0-1/${size}`);
+ expect(yield* Effect.promise(() => response.text())).toBe("01");
+ } else {
+ expect(yield* Effect.promise(() => response.text())).toBe(
+ "File is too large to preview.",
+ );
+ }
+ }
+ }).pipe(Effect.provide(fileResponseLayer)),
+ );
+
+ it.effect("streams guarded file ranges, including suffixes and conditional requests", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-range-" });
+ const filePath = path.join(directory, "clip.mp4");
+ yield* fs.writeFileString(filePath, "0123456789");
+ const canonicalPath = yield* fs.realPath(filePath);
+ for (const [range, ifRange, expected, status, contentRange] of [
+ [undefined, undefined, "0123456789", 200, null],
+ ["bytes=0-1", undefined, "01", 206, "bytes 0-1/10"],
+ ["bytes=4-", undefined, "456789", 206, "bytes 4-9/10"],
+ ["bytes=-3", undefined, "789", 206, "bytes 7-9/10"],
+ ["bytes=-999999999999999999999999", undefined, "0123456789", 206, "bytes 0-9/10"],
+ ["bytes=10-", undefined, "", 416, "bytes */10"],
+ ["bytes=0-1", '"old-etag"', "0123456789", 200, null],
+ ["bytes=0-1", "", "0123456789", 200, null],
+ ] as const) {
+ const file = yield* openMediaFile(canonicalPath);
+ if (!file) throw new Error("Expected an opened media file");
+ const response = HttpServerResponse.toWeb(
+ yield* assetFileResponse(
+ { path: canonicalPath, file, mimeType: "video/mp4" },
+ range,
+ ifRange,
+ ),
+ );
+ expect(response.status).toBe(status);
+ expect(response.headers.get("accept-ranges")).toBe("bytes");
+ expect(response.headers.get("content-range")).toBe(contentRange);
+ expect(response.headers.get("cache-control")).toBe("private, no-store");
+ expect(response.headers.get("etag")).toBeNull();
+ expect(response.headers.get("last-modified")).toBeNull();
+ if (status !== 416)
+ expect(response.headers.get("content-length")).toBe(String(expected.length));
+ expect(yield* Effect.promise(() => response.text())).toBe(expected);
+ }
+ }).pipe(Effect.provide(fileResponseLayer)),
+ );
+
+ it.effect("closes guarded descriptors after full, HEAD, rejected, and cancelled responses", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-cleanup-" });
+ const filePath = path.join(directory, "clip.mp4");
+ const bytes = new Uint8Array(1024 * 1024).fill(42);
+ yield* fs.writeFile(filePath, bytes);
+ const canonicalPath = yield* fs.realPath(filePath);
+ for (const mode of ["full", "HEAD", "rejected", "cancelled"] as const) {
+ const file = yield* Effect.scoped(
+ Effect.gen(function* () {
+ const file = yield* openMediaFile(canonicalPath);
+ if (!file) throw new Error("Expected an opened media file");
+ const response = HttpServerResponse.toWeb(
+ yield* assetFileResponse(
+ { path: canonicalPath, file, mimeType: "video/mp4" },
+ mode === "rejected" ? `bytes=${bytes.length}-` : "bytes=0-",
+ undefined,
+ mode === "HEAD" ? "HEAD" : "GET",
+ ),
+ );
+ if (mode === "HEAD") {
+ expect(response.status).toBe(200);
+ expect(response.headers.get("content-length")).toBe(String(bytes.length));
+ expect(response.headers.get("content-range")).toBeNull();
+ expect(yield* Effect.promise(() => response.text())).toBe("");
+ } else if (mode === "rejected") {
+ expect(response.status).toBe(416);
+ expect(yield* Effect.promise(() => response.text())).toBe("");
+ } else if (mode === "cancelled") {
+ const reader = response.body!.getReader();
+ const first = yield* Effect.promise(() => reader.read());
+ expect(first.done).toBe(false);
+ expect(first.value!.byteLength).toBeLessThan(bytes.length);
+ yield* Effect.promise(() => reader.cancel());
+ } else {
+ expect(yield* Effect.promise(() => response.arrayBuffer())).toEqual(bytes.buffer);
+ }
+ return file;
+ }),
+ );
+ expect(file.handle.fd).toBe(-1);
+ }
+ }).pipe(Effect.provide(fileResponseLayer)),
+ );
+
it.effect("streams exactly the requested bytes and leaves full downloads intact", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts
index b83461775e9..8b7c2ad3a61 100644
--- a/apps/server/src/http.ts
+++ b/apps/server/src/http.ts
@@ -29,6 +29,7 @@ import { OtlpTracer } from "effect/unstable/observability";
import * as ServerConfig from "./config.ts";
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
+import { statMediaFile, streamMediaFile, type OpenMediaFile } from "./assets/MediaFile.ts";
import {
ATTACHMENT_UPLOAD_ROUTE_PREFIX,
storeAttachmentUpload,
@@ -124,6 +125,9 @@ function assetByteRange(header: string, size: bigint) {
}
const start = first ?? (last! >= size ? 0n : size - last!);
const end = first === null || last === null || last >= size ? size - 1n : last;
+ if (!Number.isSafeInteger(Number(start)) || !Number.isSafeInteger(Number(end))) {
+ return { _tag: "Unsatisfiable" as const };
+ }
return {
_tag: "Range" as const,
offset: start,
@@ -138,17 +142,30 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* (
readonly download?: boolean;
readonly fileName?: string;
readonly mimeType?: string;
+ readonly file?: OpenMediaFile;
},
rangeHeader?: string,
ifRangeHeader?: string,
+ method: "GET" | "HEAD" = "GET",
) {
const headers = assetResponseHeaders(asset.path, asset);
- if (headers["Content-Type"]?.toLowerCase().startsWith("video/")) {
+ const mediaFile = asset.file;
+ const mediaInfo = mediaFile ? yield* statMediaFile(asset.path, mediaFile) : undefined;
+ const isVideo = headers["Content-Type"]?.toLowerCase().startsWith("video/") === true;
+ if (mediaFile && isVideo) {
+ // Host videos can change in place. Do not invite conditional range requests
+ // with validators that cannot establish byte-for-byte identity.
+ headers["Cache-Control"] = "private, no-store";
+ }
+ let status = 200;
+ let offset = 0n;
+ let bytesToRead: bigint | undefined;
+ if (isVideo) {
headers["Accept-Ranges"] = "bytes";
// If-Range requires a matching validator. A full response is safe when we cannot validate it.
- if (rangeHeader && !ifRangeHeader) {
+ if (method === "GET" && rangeHeader && ifRangeHeader === undefined) {
const fs = yield* FileSystem.FileSystem;
- const info = yield* fs.stat(asset.path);
+ const info = mediaInfo ?? (yield* fs.stat(asset.path));
const range = assetByteRange(rangeHeader, info.size);
if (range?._tag === "Unsatisfiable") {
return HttpServerResponse.empty({
@@ -157,16 +174,34 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* (
});
}
if (range?._tag === "Range") {
- return yield* HttpServerResponse.file(asset.path, {
- status: 206,
- offset: range.offset,
- bytesToRead: range.bytesToRead,
- headers: { ...headers, "Content-Range": range.contentRange },
- });
+ status = 206;
+ offset = range.offset;
+ bytesToRead = range.bytesToRead;
+ headers["Content-Range"] = range.contentRange;
}
}
}
- return yield* HttpServerResponse.file(asset.path, { status: 200, headers });
+ if (mediaFile && mediaInfo) {
+ const size = bytesToRead ?? mediaInfo.size;
+ headers["Content-Type"] ??= Mime.getType(asset.path) ?? "application/octet-stream";
+ headers["Content-Length"] = String(size);
+ if (!isVideo) {
+ headers["Last-Modified"] = mediaInfo.mtime.toUTCString();
+ headers.ETag = `W/"${mediaInfo.size.toString(16)}-${mediaInfo.mtimeMs.toString(16)}"`;
+ }
+ if (method === "HEAD" || size === 0n) {
+ return HttpServerResponse.empty({ status, headers });
+ }
+ const body = streamMediaFile(mediaFile, offset, size);
+ if (!body) {
+ return HttpServerResponse.text("File is too large to preview.", { status: 413 });
+ }
+ return HttpServerResponse.stream(body, {
+ status,
+ headers,
+ });
+ }
+ return yield* HttpServerResponse.file(asset.path, { status, offset, bytesToRead, headers });
});
export const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {
@@ -338,6 +373,7 @@ export const assetRouteLayer = HttpRouter.add(
asset,
request.method === "GET" ? request.headers.range : undefined,
request.headers["if-range"],
+ request.method === "HEAD" ? "HEAD" : "GET",
).pipe(
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
);
diff --git a/apps/web/src/assets/assetUrls.ts b/apps/web/src/assets/assetUrls.ts
index f8c0b5ae75f..5c642471404 100644
--- a/apps/web/src/assets/assetUrls.ts
+++ b/apps/web/src/assets/assetUrls.ts
@@ -1,11 +1,13 @@
import { useAtomValue } from "@effect/atom-react";
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
import { AsyncResult } from "effect/unstable/reactivity";
-import { useMemo } from "react";
+import { useCallback, useMemo } from "react";
import { assetEnvironment } from "~/state/assets";
import { usePreparedConnection } from "~/state/session";
+import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
export { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
@@ -49,6 +51,21 @@ export function useAssetUrl(environmentId: EnvironmentId, resource: AssetResourc
return result.url;
}
+/** Re-mints an exact-file capability after a file change or an explicit retry. */
+export function useAssetUrlRefresh(
+ environmentId: EnvironmentId,
+ resource: AssetResource,
+): () => Promise<void> {
+ const refresh = useAtomQueryRunner(assetEnvironment.createUrl, {
+ reportFailure: false,
+ refresh: true,
+ });
+ return useCallback(async () => {
+ const result = await refresh({ environmentId, input: { resource } });
+ if (result._tag === "Failure") throw squashAtomCommandFailure(result);
+ }, [environmentId, resource, refresh]);
+}
+
export function useAssetUrls(
environmentId: EnvironmentId,
resources: ReadonlyArray<AssetResource>,
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index 470f0efcc26..6f7327b3ab3 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -42,6 +42,9 @@ import {
classifyMarkdownImageSource,
markdownImageSourceFragment,
} from "@t3tools/client-runtime/markdown-images";
+import { inlineCodeFilePathCandidate } from "@t3tools/client-runtime/markdown-links";
+import { mediaFileReference, mediaUrlReference } from "@t3tools/client-runtime/media-reference";
+import { mediaKindFromPath, mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import React, {
@@ -76,7 +79,14 @@ import {
renderCodexFileCitationsAsMarkdown,
} from "@t3tools/client-runtime/codex-markdown-directives";
import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
-import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";
+import {
+ resolveMarkdownMediaPreview,
+ type ExpandedImagePreview,
+} from "./chat/ExpandedImagePreview";
+import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";
+import { MediaVideoPlayer } from "./media/MediaVideoPlayer";
+import { MediaActions, type MediaActionSource } from "./media/MediaActions";
+import { resolveProtocolRelativeMediaUrl } from "./media/mediaContent";
import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
import {
@@ -126,7 +136,7 @@ import {
type MarkdownFileLinkMeta,
} from "../markdown-links";
import { readLocalApi } from "../localApi";
-import { useAssetUrlState } from "../assets/assetUrls";
+import { useAssetUrlRefresh, useAssetUrlState } from "../assets/assetUrls";
import { cn } from "../lib/utils";
import { useRemoteOpenResolution, type RemoteOpenMode } from "../remoteOpen";
import { useRightPanelStore } from "../rightPanelStore";
@@ -195,8 +205,14 @@ export function hasMarkdownFilePrimaryAction(input: {
canOpenInEditor: boolean;
canOpenInBrowser: boolean;
canOpenInPanel: boolean;
+ canOpenMedia?: boolean;
}): boolean {
- return input.canOpenInEditor || input.canOpenInBrowser || input.canOpenInPanel;
+ return (
+ input.canOpenInEditor ||
+ input.canOpenInBrowser ||
+ input.canOpenInPanel ||
+ input.canOpenMedia === true
+ );
}
export function shouldUseMarkdownFileBrowserPrimaryAction(input: {
@@ -1011,6 +1027,7 @@ interface MarkdownFileLinkProps {
onOpenInPanel: (workspaceRelativePath: string, line: number | undefined) => void;
openInEditorMenuLabel: string;
onOpenInBrowser?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
+ onOpenMedia?: (() => void) | undefined;
onReveal?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
/** Platform-specific menu label ("Reveal in Finder", ...); required for the
reveal item to show. */
@@ -1133,10 +1150,16 @@ const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host:
);
});
-const CHAT_MARKDOWN_IMAGE_BOUNDS_CLASS_NAME = "max-h-[30rem] max-w-[min(100%,30rem)]";
+const CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME = "max-w-[min(100%,30rem)]";
+const CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME = cn(
+ "max-h-[30rem]",
+ CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME,
+);
+const CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME = "inline-block!";
+const CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME = "rounded-lg border border-border/40";
const CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME = cn(
"h-auto w-auto object-contain",
- CHAT_MARKDOWN_IMAGE_BOUNDS_CLASS_NAME,
+ CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME,
);
function markdownImageCopy(alt: string, src: string, title: string | undefined): string {
@@ -1167,11 +1190,10 @@ function authoredImageSizeStyle(
return undefined;
}
-const CHAT_MARKDOWN_WORKSPACE_IMAGE_LAYOUT_CLASS_NAME = "inline-block!";
const CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME = cn(
CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME,
- CHAT_MARKDOWN_WORKSPACE_IMAGE_LAYOUT_CLASS_NAME,
- "rounded-lg border border-border/40",
+ CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
+ CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME,
);
const MarkdownLinkContext = React.createContext(false);
@@ -1179,6 +1201,8 @@ function expandableMarkdownImageProps(
onImageExpand: ((preview: ExpandedImagePreview) => void) | undefined,
src: string,
alt: string,
+ originalUrl?: string,
+ actionsSource?: MediaActionSource,
) {
if (!onImageExpand) return {};
const previewName = alt.trim() || "image";
@@ -1186,7 +1210,17 @@ function expandableMarkdownImageProps(
if (event.currentTarget.closest("a")) return;
event.preventDefault();
event.stopPropagation();
- onImageExpand({ images: [{ src, name: previewName }], index: 0 });
+ onImageExpand({
+ images: [
+ {
+ src,
+ name: previewName,
+ ...(originalUrl ? { originalUrl } : {}),
+ ...(actionsSource ? { actionsSource } : {}),
+ },
+ ],
+ index: 0,
+ });
};
return {
role: "button" as const,
@@ -1202,70 +1236,201 @@ function expandableMarkdownImageProps(
function ChatMarkdownImageFallback(props: {
readonly alt: string;
readonly copyMarkdown?: string | undefined;
+ readonly kind?: "image" | "video";
+ readonly actionsSource?: MediaActionSource;
}) {
- return (
+ const label = props.kind === "video" ? "Video unavailable" : "Image unavailable";
+ const content = (
<span
data-markdown-copy={props.copyMarkdown}
className={cn(
- CHAT_MARKDOWN_WORKSPACE_IMAGE_LAYOUT_CLASS_NAME,
+ CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
"rounded-md border border-border/40 bg-muted/40 px-2 py-1 text-xs text-muted-foreground",
)}
>
<span className="inline-flex items-center gap-1.5">
<TriangleAlertIcon aria-hidden className="size-3.5 shrink-0" />
- {props.alt.length > 0 ? `Image unavailable · ${props.alt}` : "Image unavailable"}
+ {props.alt.length > 0 ? `${label} · ${props.alt}` : label}
</span>
</span>
);
+ return props.actionsSource ? (
+ <MediaActions source={props.actionsSource}>{content}</MediaActions>
+ ) : (
+ content
+ );
+}
+
+function ChatMarkdownVideo(props: {
+ readonly src: string | null;
+ readonly alt: string;
+ readonly copyMarkdown: string | undefined;
+ readonly originalUrl?: string | undefined;
+ readonly sourceFailed?: boolean | undefined;
+ readonly style?: CSSProperties | undefined;
+ readonly mediaIdentity?: string | undefined;
+ readonly actionsSource?: MediaActionSource | undefined;
+ readonly onRetry?: (() => Promise<void>) | undefined;
+ readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
+}) {
+ return (
+ <MediaVideoPlayer
+ key={props.mediaIdentity ?? props.copyMarkdown ?? props.src}
+ src={props.src}
+ sourceFailed={props.sourceFailed}
+ label={props.alt}
+ originalUrl={props.originalUrl}
+ style={props.style}
+ copyMarkdown={props.copyMarkdown}
+ className={cn(
+ CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
+ CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME,
+ "w-full",
+ )}
+ videoClassName={cn(
+ CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME,
+ CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME,
+ )}
+ onRetry={props.onRetry}
+ actionsSource={props.actionsSource}
+ onExpand={
+ props.onImageExpand
+ ? (src) => {
+ props.onImageExpand?.({
+ images: [
+ {
+ src,
+ name: props.alt || "video",
+ type: "video",
+ autoPlay: false,
+ ...(props.originalUrl ? { originalUrl: props.originalUrl } : {}),
+ ...(props.actionsSource
+ ? { actionsSource: { ...props.actionsSource, src } }
+ : {}),
+ },
+ ],
+ index: 0,
+ });
+ }
+ : undefined
+ }
+ />
+ );
}
-/** Environment-hosted images load through a signed asset URL. */
+/** Environment-hosted media loads through an exact-file signed asset URL. */
export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props: {
readonly environmentId: EnvironmentId;
- readonly resource: Extract<AssetResource, { readonly _tag: "attachment" | "workspace-file" }>;
+ readonly resource: Extract<
+ AssetResource,
+ { readonly _tag: "attachment" | "workspace-file" | "media-file" }
+ >;
+ readonly kind?: "image" | "video";
readonly alt: string;
readonly copyMarkdown?: string;
readonly srcFragment?: string;
readonly style?: CSSProperties | undefined;
+ readonly workspaceRoot?: string | undefined;
readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
}) {
const assetUrl = useAssetUrlState(props.environmentId, props.resource);
+ const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, props.resource);
const [failedUrl, setFailedUrl] = useState<string | null>(null);
+ const resource = props.resource;
+ const path =
+ resource._tag === "media-file"
+ ? resource.path
+ : resource._tag === "workspace-file" && props.workspaceRoot
+ ? `${props.workspaceRoot.replace(/[\\/]+$/, "")}/${resource.path}`
+ : undefined;
+ const reference = path ? mediaFileReference(path, props.workspaceRoot) : undefined;
+ const relativePath = reference?.relativePath;
+ const src = assetUrl._tag === "Success" ? assetUrl.url + (props.srcFragment ?? "") : null;
+ const actionsSource: MediaActionSource = {
+ kind: props.kind ?? "image",
+ name: props.alt || (props.kind ?? "image"),
+ src,
+ asset: { environmentId: props.environmentId, resource },
+ ...(reference ? { reference } : {}),
+ ...(relativePath && resource._tag !== "attachment"
+ ? {
+ onOpenFile: () =>
+ useRightPanelStore
+ .getState()
+ .openFile(
+ { environmentId: props.environmentId, threadId: resource.threadId },
+ relativePath,
+ ),
+ }
+ : {}),
+ };
+
+ if (props.kind === "video") {
+ return (
+ <ChatMarkdownVideo
+ src={src}
+ sourceFailed={assetUrl._tag === "Failure"}
+ alt={props.alt}
+ copyMarkdown={props.copyMarkdown}
+ style={props.style}
+ mediaIdentity={JSON.stringify([props.environmentId, props.resource, props.srcFragment])}
+ onRetry={refreshAssetUrl}
+ onImageExpand={props.onImageExpand}
+ actionsSource={actionsSource}
+ />
+ );
+ }
if (assetUrl._tag === "Failure" || (assetUrl._tag === "Success" && failedUrl === assetUrl.url)) {
- return <ChatMarkdownImageFallback alt={props.alt} copyMarkdown={props.copyMarkdown} />;
+ return (
+ <ChatMarkdownImageFallback
+ alt={props.alt}
+ copyMarkdown={props.copyMarkdown}
+ kind={props.kind ?? "image"}
+ actionsSource={actionsSource}
+ />
+ );
}
if (assetUrl._tag !== "Success") {
return (
- <span
+ <MediaActions source={actionsSource}>
+ <span
+ data-markdown-copy={props.copyMarkdown}
+ role="status"
+ aria-label="Loading image"
+ className={cn(
+ CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
+ "aspect-video w-64 max-w-full rounded-lg bg-muted/60",
+ CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME,
+ )}
+ style={props.style}
+ />
+ </MediaActions>
+ );
+ }
+ return (
+ <MediaActions source={actionsSource}>
+ <img
+ src={src ?? undefined}
+ alt={props.alt}
data-markdown-copy={props.copyMarkdown}
- role="status"
- aria-label="Loading image"
+ loading="lazy"
+ draggable={false}
className={cn(
- CHAT_MARKDOWN_WORKSPACE_IMAGE_LAYOUT_CLASS_NAME,
- "aspect-video w-64 max-w-full rounded-lg bg-muted/60",
- CHAT_MARKDOWN_IMAGE_BOUNDS_CLASS_NAME,
+ CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME,
+ props.onImageExpand && "cursor-zoom-in",
)}
style={props.style}
+ {...expandableMarkdownImageProps(
+ props.onImageExpand,
+ src ?? assetUrl.url,
+ props.alt,
+ undefined,
+ actionsSource,
+ )}
+ onError={() => setFailedUrl(assetUrl.url)}
/>
- );
- }
- const src = assetUrl.url + (props.srcFragment ?? "");
- return (
- <img
- src={src}
- alt={props.alt}
- data-markdown-copy={props.copyMarkdown}
- loading="lazy"
- draggable={false}
- className={cn(
- CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME,
- props.onImageExpand && "cursor-zoom-in",
- )}
- style={props.style}
- {...expandableMarkdownImageProps(props.onImageExpand, src, props.alt)}
- onError={() => setFailedUrl(assetUrl.url)}
- />
+ </MediaActions>
);
});
@@ -1448,6 +1613,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
onOpenInPanel,
openInEditorMenuLabel,
onOpenInBrowser,
+ onOpenMedia,
onReveal,
revealLabel,
className,
@@ -1491,12 +1657,16 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
}, [onOpen, targetPath]);
const handleOpenInFilePreview = useCallback(() => {
- if (!threadRef || !workspaceRelativePath) {
- handleOpenInEditor();
+ if (threadRef && workspaceRelativePath) {
+ onOpenInPanel(workspaceRelativePath, line);
return;
}
- onOpenInPanel(workspaceRelativePath, line);
- }, [handleOpenInEditor, line, onOpenInPanel, threadRef, workspaceRelativePath]);
+ if (onOpenMedia) {
+ onOpenMedia();
+ return;
+ }
+ handleOpenInEditor();
+ }, [handleOpenInEditor, line, onOpenInPanel, onOpenMedia, threadRef, workspaceRelativePath]);
const handleOpenInBrowser = useCallback(() => {
if (!onOpenInBrowser) {
@@ -1621,6 +1791,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
try {
const clicked = await api.contextMenu.show(
[
+ ...(onOpenMedia ? ([{ id: "preview-media", label: "Preview media" }] as const) : []),
...(onOpen ? ([{ id: "open", label: openInEditorMenuLabel }] as const) : []),
...(onOpenInBrowser
? ([{ id: "open-in-browser", label: "Open in integrated browser" }] as const)
@@ -1632,6 +1803,10 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
position,
);
+ if (clicked === "preview-media") {
+ onOpenMedia?.();
+ return;
+ }
if (clicked === "open") {
handleOpenInEditor();
return;
@@ -1665,6 +1840,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
handleOpenInEditor,
handleRevealInFileManager,
onOpenInBrowser,
+ onOpenMedia,
onOpen,
onReveal,
openInEditorMenuLabel,
@@ -1696,6 +1872,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
canOpenInEditor,
canOpenInBrowser,
canOpenInPanel,
+ canOpenMedia: onOpenMedia !== undefined,
});
const useBrowserPrimaryAction = shouldUseMarkdownFileBrowserPrimaryAction({
iconPath,
@@ -1787,6 +1964,7 @@ function areMarkdownFileLinkPropsEqual(
previous.onOpenInPanel === next.onOpenInPanel &&
previous.openInEditorMenuLabel === next.openInEditorMenuLabel &&
previous.onOpenInBrowser === next.onOpenInBrowser &&
+ previous.onOpenMedia === next.onOpenMedia &&
previous.onReveal === next.onReveal &&
previous.revealLabel === next.revealLabel &&
previous.className === next.className
@@ -1810,8 +1988,18 @@ function ChatMarkdown({
extraRemarkPlugins = EMPTY_REMARK_PLUGINS,
}: ChatMarkdownProps) {
const { resolvedTheme } = useTheme();
+ const [localMediaPreview, setLocalMediaPreview] = useState<ExpandedImagePreview | null>(null);
+ const expandMedia = onImageExpand ?? setLocalMediaPreview;
+ const mediaRequestId = useRef(0);
+ useEffect(() => {
+ setLocalMediaPreview(null);
+ return () => {
+ mediaRequestId.current += 1;
+ };
+ }, [threadRef?.environmentId, threadRef?.threadId, explicitEnvironmentId, cwd, imageBaseDir]);
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false,
+ refresh: true,
});
const searchProjectEntries = useAtomQueryRunner(projectEnvironment.searchEntries, {
reportFailure: false,
@@ -1830,6 +2018,41 @@ function ChatMarkdown({
remoteOpen.isResolved,
);
const preparedConnection = usePreparedConnection(environmentId);
+ const openMarkdownMedia = useCallback(
+ (source: string, resolvedFilePath?: string) => {
+ const requestId = ++mediaRequestId.current;
+ void resolveMarkdownMediaPreview({
+ source,
+ resolvedFilePath,
+ cwd,
+ threadRef,
+ httpBaseUrl:
+ preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : undefined,
+ createAssetUrl,
+ onOpenFile: threadRef
+ ? (path) => useRightPanelStore.getState().openFile(threadRef, path)
+ : undefined,
+ }).then(
+ (preview) => {
+ if (preview && mediaRequestId.current === requestId) expandMedia(preview);
+ },
+ (error: unknown) => {
+ if (mediaRequestId.current !== requestId) return;
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Media unavailable",
+ description:
+ error instanceof Error
+ ? error.message
+ : "The file could not be loaded. It may have been moved or deleted.",
+ }),
+ );
+ },
+ );
+ },
+ [createAssetUrl, cwd, expandMedia, preparedConnection, threadRef],
+ );
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
const threadServerConfig = useAtomValue(
serverEnvironment.configValueAtom(threadRef?.environmentId ?? environmentId),
@@ -2068,6 +2291,7 @@ function ChatMarkdown({
fileLinkMeta: MarkdownFileLinkMeta,
copyMarkdown: string,
className?: string,
+ mediaSource?: string,
) => {
const parentSuffix = fileLinkParentSuffixByPath.get(
fileLinkMeta.filePath.replaceAll("\\", "/"),
@@ -2081,6 +2305,11 @@ function ChatMarkdown({
`L${fileLinkMeta.line}${fileLinkMeta.column ? `:C${fileLinkMeta.column}` : ""}`,
);
}
+ const mediaPath = mediaSource ?? fileLinkMeta.filePath;
+ const canPreviewMedia =
+ mediaMimeTypeFromExtension(
+ fileLinkMeta.basename.slice(fileLinkMeta.basename.lastIndexOf(".")),
+ ) !== null;
return (
<MarkdownFileLink
@@ -2096,6 +2325,11 @@ function ChatMarkdown({
threadRef={threadRef}
{...(canUseShellActions ? { onOpen: openInPreferredEditor } : {})}
onOpenInPanel={openFileInPanel}
+ onOpenMedia={
+ threadRef && canPreviewMedia
+ ? () => openMarkdownMedia(mediaPath, fileLinkMeta.filePath)
+ : undefined
+ }
openInEditorMenuLabel={preferredEditorMenuLabel}
onReveal={
canUseShellActions && revealInFileManagerLabel !== undefined
@@ -2232,6 +2466,21 @@ function ChatMarkdown({
handleMarkdownFragmentClick(event, href);
return;
}
+ if (
+ href &&
+ faviconHost !== null &&
+ mediaKindFromPath(href) !== null &&
+ !event.defaultPrevented &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.shiftKey &&
+ !event.altKey
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ openMarkdownMedia(href);
+ return;
+ }
// A link to a change request in a workspace project opens beside the
// conversation instead of in a browser: it is the thing being talked about, and
// the panel it opens offers the browser as one of its actions. Anything else is
@@ -2323,6 +2572,7 @@ function ChatMarkdown({
fileLinkMeta,
`[${fileLinkMeta.basename}](${normalizedHref})`,
props.className,
+ normalizedHref,
);
},
code({ node, children, className, ...props }) {
@@ -2332,7 +2582,12 @@ function ChatMarkdown({
inlineCodeFileLinkMetaByText.get(codeText.trim()) ??
resolveInlineCodeFileLinkMeta(codeText, cwd);
if (fileLinkMeta) {
- return fileLinkChip(fileLinkMeta, `\`${codeText}\``);
+ return fileLinkChip(
+ fileLinkMeta,
+ `\`${codeText}\``,
+ undefined,
+ inlineCodeFilePathCandidate(codeText) ?? codeText.trim(),
+ );
}
}
return (
@@ -2342,7 +2597,7 @@ function ChatMarkdown({
);
},
img: function MarkdownImage({ node, title, src, alt, ...props }) {
- const imageExpand = use(MarkdownLinkContext) ? undefined : onImageExpand;
+ const imageExpand = use(MarkdownLinkContext) ? undefined : expandMedia;
const localSrc = node?.properties?.dataLocalSrc;
const markdownTitle = node?.properties?.dataMarkdownTitle;
const authoredSrc = typeof localSrc === "string" ? localSrc : src;
@@ -2355,21 +2610,53 @@ function ChatMarkdown({
const copyMarkdown = markdownImageCopy(altText, srcString, authoredTitle);
const authoredSizeStyle = authoredImageSizeStyle(props.width, props.height);
const imageSource = classifyMarkdownImageSource(classifiedSrc, imageBaseDir ?? cwd);
+ const kind = mediaKindFromPath(classifiedSrc) ?? "image";
if (imageSource._tag === "Direct") {
+ const mediaSrc = resolveProtocolRelativeMediaUrl(imageSource.uri);
+ const originalUrl =
+ resolveExternalWebLinkHost(imageSource.uri) !== null ? imageSource.uri : undefined;
+ const reference = mediaUrlReference(imageSource.uri);
+ const actionsSource: MediaActionSource = {
+ kind,
+ name: altText || kind,
+ src: mediaSrc,
+ ...(reference ? { reference } : {}),
+ };
+ if (kind === "video") {
+ return (
+ <ChatMarkdownVideo
+ src={mediaSrc}
+ alt={altText}
+ copyMarkdown={copyMarkdown}
+ originalUrl={originalUrl}
+ style={authoredSizeStyle}
+ onImageExpand={imageExpand}
+ actionsSource={actionsSource}
+ />
+ );
+ }
return (
- <img
- {...props}
- src={imageSource.uri}
- alt={altText}
- loading="lazy"
- className={cn(
- props.className,
- CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME,
- imageExpand && "cursor-zoom-in",
- )}
- style={authoredSizeStyle}
- {...expandableMarkdownImageProps(imageExpand, imageSource.uri, altText)}
- />
+ <MediaActions source={actionsSource}>
+ <img
+ {...props}
+ src={mediaSrc}
+ alt={altText}
+ loading="lazy"
+ className={cn(
+ props.className,
+ CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME,
+ imageExpand && "cursor-zoom-in",
+ )}
+ style={authoredSizeStyle}
+ {...expandableMarkdownImageProps(
+ imageExpand,
+ mediaSrc,
+ altText,
+ originalUrl,
+ actionsSource,
+ )}
+ />
+ </MediaActions>
);
}
if (imageSource._tag === "WorkspaceFile" && threadRef) {
@@ -2377,19 +2664,21 @@ function ChatMarkdown({
<ChatMarkdownAssetImage
environmentId={threadRef.environmentId}
resource={{
- _tag: "workspace-file",
+ _tag: "media-file",
threadId: threadRef.threadId,
path: imageSource.path,
}}
alt={altText}
+ kind={kind}
copyMarkdown={copyMarkdown}
srcFragment={markdownImageSourceFragment(classifiedSrc)}
style={authoredSizeStyle}
+ workspaceRoot={cwd}
onImageExpand={imageExpand}
/>
);
}
- return <ChatMarkdownImageFallback alt={altText} copyMarkdown={copyMarkdown} />;
+ return <ChatMarkdownImageFallback alt={altText} copyMarkdown={copyMarkdown} kind={kind} />;
},
table({ node: _node, ...props }) {
return <MarkdownTable {...props} />;
@@ -2438,6 +2727,8 @@ function ChatMarkdown({
onTaskListChange,
onUseArtifactTemplate,
onImageExpand,
+ expandMedia,
+ openMarkdownMedia,
openFileInPanel,
openInPreferredEditor,
openChangeRequestLink,
@@ -2483,6 +2774,12 @@ function ChatMarkdown({
>
{text}
</ReactMarkdown>
+ {localMediaPreview ? (
+ <ExpandedImageDialog
+ preview={localMediaPreview}
+ onClose={() => setLocalMediaPreview(null)}
+ />
+ ) : null}
</div>
);
}
diff --git a/apps/web/src/components/ChatMarkdown.workspace-images.test.tsx b/apps/web/src/components/ChatMarkdown.workspace-images.test.tsx
index 39ea214d43c..172793bacb0 100644
--- a/apps/web/src/components/ChatMarkdown.workspace-images.test.tsx
+++ b/apps/web/src/components/ChatMarkdown.workspace-images.test.tsx
@@ -9,6 +9,7 @@ const testState = vi.hoisted(() => ({
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
vi.mock("../assets/assetUrls", () => ({
+ useAssetUrlRefresh: () => vi.fn(),
useAssetUrlState: (_environmentId: unknown, resource: unknown) => {
testState.resources.push(resource);
if (testState.assetState === "loading") return { _tag: "Loading" };
@@ -106,7 +107,7 @@ describe("ChatMarkdown workspace images", () => {
expect(testState.resources).toEqual([
{
- _tag: "workspace-file",
+ _tag: "media-file",
threadId: threadRef.threadId,
path: expectedPath,
},
@@ -126,14 +127,14 @@ describe("ChatMarkdown workspace images", () => {
expect(testState.resources).toEqual([
{
- _tag: "workspace-file",
+ _tag: "media-file",
threadId: threadRef.threadId,
path: "C:\\Users\\shawn\\project\\.t3\\workspace-image.svg",
},
- { _tag: "workspace-file", threadId: threadRef.threadId, path: imagePath },
- { _tag: "workspace-file", threadId: threadRef.threadId, path: imagePath },
+ { _tag: "media-file", threadId: threadRef.threadId, path: imagePath },
+ { _tag: "media-file", threadId: threadRef.threadId, path: imagePath },
{
- _tag: "workspace-file",
+ _tag: "media-file",
threadId: threadRef.threadId,
path: "\\\\server\\share\\workspace-image.svg",
},
@@ -149,7 +150,7 @@ describe("ChatMarkdown workspace images", () => {
expect(testState.resources).toEqual([
{
- _tag: "workspace-file",
+ _tag: "media-file",
threadId: threadRef.threadId,
path: "D:/screens/workspace-image.svg",
},
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts
index 6e391ab79e9..64ad1ce7d78 100644
--- a/apps/web/src/components/ChatView.logic.test.ts
+++ b/apps/web/src/components/ChatView.logic.test.ts
@@ -22,7 +22,6 @@ import {
dismissBranchMismatchForSession,
ENVIRONMENT_RECONNECT_WARNING_GRACE_MS,
getStartedThreadModelChangeBlockReason,
- loadVideoPreviewUrl,
isVideoPreviewRequestCurrent,
hasEnvironmentReconnectWarningGraceElapsed,
hasServerAcknowledgedLocalDispatch,
@@ -44,23 +43,6 @@ import {
shouldWriteThreadErrorToCurrentServerThread,
} from "./ChatView.logic";
-describe("loadVideoPreviewUrl", () => {
- it("loads video bytes into an object URL", async () => {
- const objectUrl = await loadVideoPreviewUrl("data:video/mp4;base64,AA==");
- expect(objectUrl).toMatch(/^blob:/);
- URL.revokeObjectURL(objectUrl);
- });
-
- it("stops loading when the preview request is cancelled", async () => {
- const controller = new AbortController();
- controller.abort();
-
- await expect(
- loadVideoPreviewUrl("data:video/mp4;base64,AA==", controller.signal),
- ).rejects.toMatchObject({ name: "AbortError" });
- });
-});
-
describe("isVideoPreviewRequestCurrent", () => {
it("rejects changed threads and replaced previews", () => {
expect(isVideoPreviewRequestCurrent("thread-1", "thread-2", 1, 1)).toBe(false);
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index a12bacad50d..de349e3dbee 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -1,4 +1,7 @@
import {
+ type AssetCreateUrlInput,
+ type AssetCreateUrlResult,
+ type ChatFileAttachment,
type EnvironmentId,
isProviderDriverKind,
ProjectId,
@@ -12,6 +15,12 @@ import {
type ThreadId,
type TurnId,
} from "@t3tools/contracts";
+import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
+import {
+ squashAtomCommandFailure,
+ type AtomCommandResult,
+} from "@t3tools/client-runtime/state/runtime";
+import { videoMimeType } from "@t3tools/shared/video";
import {
appendCodexArtifactTemplateUsePrompt,
codexArtifactTemplateUsePrompt,
@@ -299,10 +308,32 @@ export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
URL.revokeObjectURL(previewUrl);
}
-export async function loadVideoPreviewUrl(url: string, signal?: AbortSignal): Promise<string> {
- const response = await fetch(url, signal ? { signal } : {});
- if (!response.ok) throw new Error(`Could not load video (${response.status}).`);
- return URL.createObjectURL(await response.blob());
+/** Signs an attachment URL without reading its bytes, so video playback can request byte ranges. */
+export async function resolveFileAttachmentUrl(input: {
+ attachment: ChatFileAttachment;
+ environmentId: EnvironmentId;
+ httpBaseUrl: string;
+ createAssetUrl: (input: {
+ environmentId: EnvironmentId;
+ input: AssetCreateUrlInput;
+ }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
+}): Promise<string> {
+ const { attachment } = input;
+ const result = await input.createAssetUrl({
+ environmentId: input.environmentId,
+ input: {
+ resource: {
+ _tag: "attachment",
+ attachmentId: attachment.id,
+ fileName: attachment.name,
+ mimeType: videoMimeType(attachment) ?? attachment.mimeType,
+ },
+ },
+ });
+ if (result._tag === "Failure") throw squashAtomCommandFailure(result);
+ const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
+ if (url === null) throw new Error("The environment returned an invalid attachment URL.");
+ return url;
}
export function isVideoPreviewRequestCurrent(
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index a475230fe82..dc0d2ed122f 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -365,7 +365,7 @@ import {
cloneComposerImageForRetry,
deriveLockedProvider,
readFileAsDataUrl,
- loadVideoPreviewUrl,
+ resolveFileAttachmentUrl,
isVideoPreviewRequestCurrent,
reconcileMountedTerminalThreadIds,
resolveBackgroundDraftWorkspaceOptions,
@@ -424,7 +424,7 @@ import {
resolveServerSelfUpdateCapability,
serverUpdateGuidance,
} from "../versionSkew";
-import { resolveAssetUrl, useAssetUrls } from "../assets/assetUrls";
+import { useAssetUrls } from "../assets/assetUrls";
const ATTACHMENT_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more files without additional text. Respond using the conversation context and the attached files.]";
@@ -1331,6 +1331,7 @@ function ChatViewContent(props: ChatViewProps) {
const startThreadTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
const createAttachmentAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false,
+ refresh: true,
});
const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
reportFailure: false,
@@ -1459,11 +1460,8 @@ function ChatViewContent(props: ChatViewProps) {
const routeThreadKeyRef = useRef(routeThreadKey);
routeThreadKeyRef.current = routeThreadKey;
const videoPreviewRequestIdRef = useRef(0);
- const videoPreviewAbortControllerRef = useRef<AbortController | null>(null);
const cancelVideoPreviewRequest = useCallback(() => {
videoPreviewRequestIdRef.current += 1;
- videoPreviewAbortControllerRef.current?.abort();
- videoPreviewAbortControllerRef.current = null;
}, []);
const [openingVideoAttachmentId, setOpeningVideoAttachmentId] = useState<string | null>(null);
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
@@ -2542,14 +2540,8 @@ function ChatViewContent(props: ChatViewProps) {
toastManager.add({ type: "error", title: "The environment is not connected." });
return;
}
- const videoMime = videoMimeType(attachment);
- const isVideo = videoMime !== null;
+ const isVideo = videoMimeType(attachment) !== null;
const action = isVideo ? "play" : "download";
- const videoPreviewAbortController = isVideo ? new AbortController() : null;
- if (isVideo) {
- videoPreviewAbortControllerRef.current?.abort();
- videoPreviewAbortControllerRef.current = videoPreviewAbortController;
- }
const videoPreviewRequestId = isVideo ? ++videoPreviewRequestIdRef.current : 0;
const isCurrentRequest = () =>
!isVideo ||
@@ -2559,75 +2551,37 @@ function ChatViewContent(props: ChatViewProps) {
videoPreviewRequestId,
videoPreviewRequestIdRef.current,
);
- const finishVideoPreviewRequest = () => {
- if (videoPreviewRequestIdRef.current === videoPreviewRequestId) {
- setOpeningVideoAttachmentId(null);
- videoPreviewAbortControllerRef.current = null;
- }
- };
if (isVideo) setOpeningVideoAttachmentId(attachment.id);
- // fileName and mimeType ride in the signed claims so videos render
- // inline while other files keep their real download name and type.
- const result = await createAttachmentAssetUrl({
- environmentId,
- input: {
- resource: {
- _tag: "attachment",
- attachmentId: attachment.id,
- fileName: attachment.name,
- mimeType: videoMime ?? attachment.mimeType,
- },
- },
- });
- if (!isCurrentRequest()) {
- finishVideoPreviewRequest();
- return;
- }
- if (result._tag === "Failure") {
- finishVideoPreviewRequest();
- const error = squashAtomCommandFailure(result);
- toastManager.add({
- type: "error",
- title: "Could not " + action + " " + attachment.name,
- description: error instanceof Error ? error.message : "The attachment is unavailable.",
+ try {
+ const url = await resolveFileAttachmentUrl({
+ attachment,
+ environmentId,
+ httpBaseUrl: connection.httpBaseUrl,
+ createAssetUrl: createAttachmentAssetUrl,
});
- return;
- }
-
- const url = resolveAssetUrl(connection.httpBaseUrl, result.value.relativeUrl);
- if (!url) {
- finishVideoPreviewRequest();
- toastManager.add({ type: "error", title: "Could not " + action + " " + attachment.name });
- return;
- }
- if (isVideo) {
- try {
- const previewUrl = await loadVideoPreviewUrl(url, videoPreviewAbortController?.signal);
- if (!isCurrentRequest()) {
- revokeBlobPreviewUrl(previewUrl);
- return;
- }
+ if (!isCurrentRequest()) return;
+ if (isVideo) {
setExpandedImage({
- images: [{ src: previewUrl, name: attachment.name, type: "video" }],
+ images: [{ src: url, name: attachment.name, type: "video" }],
index: 0,
});
- } catch (error) {
- if (!isCurrentRequest()) return;
- toastManager.add({
- type: "error",
- title: "Could not play " + attachment.name,
- description: error instanceof Error ? error.message : "The attachment is unavailable.",
- });
- } finally {
- finishVideoPreviewRequest();
+ return;
}
- return;
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = attachment.name;
+ anchor.click();
+ } catch (error) {
+ if (!isCurrentRequest()) return;
+ toastManager.add({
+ type: "error",
+ title: "Could not " + action + " " + attachment.name,
+ description: error instanceof Error ? error.message : "The attachment is unavailable.",
+ });
+ } finally {
+ if (isVideo && isCurrentRequest()) setOpeningVideoAttachmentId(null);
}
- const anchor = document.createElement("a");
- anchor.href = url;
- anchor.download = attachment.name;
- anchor.click();
},
[createAttachmentAssetUrl, environmentId, routeThreadKey],
);
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index cd69eceb7ef..d74f1f0d8e7 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -172,6 +172,7 @@ import {
submitComposerDraft,
} from "./composerSubmission";
import { ComposerPromptLengthValidation } from "./ComposerPromptLengthValidation";
+import { prepareVideoFirstFrame } from "../../lib/videoFirstFrame";
function ComposerVideoThumbnail({ file }: { file: File }) {
const setVideo = useCallback(
@@ -189,9 +190,7 @@ function ComposerVideoThumbnail({ file }: { file: File }) {
playsInline
preload="metadata"
aria-hidden="true"
- onLoadedMetadata={(event) => {
- event.currentTarget.currentTime = Math.min(0.1, event.currentTarget.duration || 0);
- }}
+ onLoadedMetadata={(event) => prepareVideoFirstFrame(event.currentTarget)}
className="pointer-events-none absolute inset-0 size-full object-cover"
/>
);
diff --git a/apps/web/src/components/chat/ExpandedImageDialog.test.tsx b/apps/web/src/components/chat/ExpandedImageDialog.test.tsx
deleted file mode 100644
index c2a63f34ecd..00000000000
--- a/apps/web/src/components/chat/ExpandedImageDialog.test.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it } from "vite-plus/test";
-
-import { ExpandedImageDialog } from "./ExpandedImageDialog";
-import type { ExpandedImagePreview } from "./ExpandedImagePreview";
-
-describe("ExpandedImageDialog", () => {
- it("renders video previews with native controls", () => {
- const preview: ExpandedImagePreview = {
- images: [
- {
- src: "https://environment.test/api/assets/demo.mp4",
- name: "demo.mp4",
- type: "video",
- },
- ],
- index: 0,
- };
-
- const markup = renderToStaticMarkup(
- <ExpandedImageDialog preview={preview} onClose={() => {}} />,
- );
-
- expect(markup).toContain("<video");
- expect(markup).toContain('controls=""');
- expect(markup).toContain('aria-label="demo.mp4"');
- });
-});
diff --git a/apps/web/src/components/chat/ExpandedImageDialog.tsx b/apps/web/src/components/chat/ExpandedImageDialog.tsx
index f6f46d087f0..2ee40c0b8b6 100644
--- a/apps/web/src/components/chat/ExpandedImageDialog.tsx
+++ b/apps/web/src/components/chat/ExpandedImageDialog.tsx
@@ -1,41 +1,64 @@
-import { memo, useCallback, useEffect, useState } from "react";
-import { ChevronLeftIcon, ChevronRightIcon, DownloadIcon, XIcon } from "lucide-react";
+import { memo, useCallback, useEffect, useState, type ReactNode } from "react";
+import { createPortal } from "react-dom";
+import { ChevronLeftIcon, ChevronRightIcon, XIcon } from "lucide-react";
import { Button } from "../ui/button";
-import { downloadVideoPreview, type ExpandedImagePreview } from "./ExpandedImagePreview";
+import type { ExpandedImagePreview } from "./ExpandedImagePreview";
+import { prepareVideoFirstFrame } from "../../lib/videoFirstFrame";
+import { resolveExternalWebLinkHost } from "./externalLinkContextMenu";
+import { OpenMediaLink } from "../media/OpenMediaLink";
+import { MediaActions, type MediaActionSource } from "../media/MediaActions";
+import { isContextMenuOpen } from "../../contextMenuFallback";
interface ExpandedImageDialogProps {
preview: ExpandedImagePreview;
onClose: () => void;
}
+function ExpandedMediaFailure({ children }: { children: ReactNode }) {
+ return (
+ <div
+ role="alert"
+ className="flex h-48 w-[min(92vw,32rem)] flex-col items-center justify-center gap-3 rounded-lg border border-border/70 bg-black px-6 text-center text-sm text-white shadow-2xl"
+ >
+ {children}
+ </div>
+ );
+}
+
export const ExpandedImageDialog = memo(function ExpandedImageDialog({
preview,
onClose,
}: ExpandedImageDialogProps) {
const [imageOffset, setImageOffset] = useState(0);
const [failedVideoSrc, setFailedVideoSrc] = useState<string | null>(null);
- const [downloadingVideoSrc, setDownloadingVideoSrc] = useState<string | null>(null);
- const [downloadFailedVideoSrc, setDownloadFailedVideoSrc] = useState<string | null>(null);
+ const [failedImageSrc, setFailedImageSrc] = useState<string | null>(null);
const index = (preview.index + imageOffset + preview.images.length) % preview.images.length;
+ const item = preview.images[index];
+ const source: MediaActionSource = item?.actionsSource ?? {
+ kind: item?.type === "video" ? "video" : "image",
+ name: item?.name ?? "Media",
+ src: item?.src ?? null,
+ };
+ const openFile = source.onOpenFile;
+ const actionsSource: MediaActionSource = openFile
+ ? {
+ ...source,
+ onOpenFile: () => {
+ openFile();
+ onClose();
+ },
+ }
+ : source;
const navigateImage = useCallback((direction: -1 | 1) => {
setImageOffset((current) => current + direction);
}, []);
- const downloadVideo = async (src: string, name: string) => {
- setDownloadFailedVideoSrc(null);
- setDownloadingVideoSrc(src);
- try {
- await downloadVideoPreview(src, name);
- } catch {
- setDownloadFailedVideoSrc(src);
- } finally {
- setDownloadingVideoSrc((current) => (current === src ? null : current));
- }
- };
-
useEffect(() => {
const onKeyDown = (event: globalThis.KeyboardEvent) => {
+ if (event.defaultPrevented || isContextMenuOpen()) {
+ return;
+ }
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
@@ -58,13 +81,14 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
return () => window.removeEventListener("keydown", onKeyDown);
}, [navigateImage, onClose, preview.images.length]);
- const item = preview.images[index];
if (!item) return null;
const mediaLabel = item.type === "video" ? "video" : "image";
+ const openOriginalLink =
+ item.originalUrl && resolveExternalWebLinkHost(item.originalUrl) !== null ? (
+ <OpenMediaLink originalUrl={item.originalUrl} />
+ ) : null;
- const isDownloadingVideo = downloadingVideoSrc === item.src;
- const videoDownloadFailed = downloadFailedVideoSrc === item.src;
- return (
+ return createPortal(
<div
className="fixed inset-0 z-[60] flex items-center justify-center bg-black/75 px-4 py-6 [-webkit-app-region:no-drag]"
role="dialog"
@@ -89,61 +113,59 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
<ChevronLeftIcon className="size-5" />
</Button>
)}
- <div className="relative isolate z-10 max-h-[92vh] max-w-[92vw]">
- <Button
- type="button"
- size="icon-xs"
- variant="ghost"
- className="absolute right-2 top-2"
- onClick={onClose}
- aria-label={`Close ${mediaLabel} preview`}
- >
- <XIcon />
- </Button>
- {item.type === "video" && failedVideoSrc === item.src ? (
- <div className="flex h-48 w-[min(92vw,32rem)] flex-col items-center justify-center gap-3 rounded-lg border border-border/70 bg-black px-6 text-center text-white shadow-2xl">
- <p className="text-sm">
- {videoDownloadFailed
- ? "Could not download this video."
- : "This video format cannot be played here."}
- </p>
- <Button
- size="sm"
- variant="secondary"
- aria-busy={isDownloadingVideo || undefined}
- aria-disabled={isDownloadingVideo || undefined}
- onClick={() => {
- if (isDownloadingVideo) return;
- void downloadVideo(item.src, item.name);
- }}
- >
- <DownloadIcon />
- {isDownloadingVideo ? "Downloading…" : "Download video"}
- </Button>
- </div>
- ) : item.type === "video" ? (
- <video
- src={item.src}
- aria-label={item.name}
- autoPlay
- controls
- playsInline
- onError={() => setFailedVideoSrc(item.src)}
- className="max-h-[86vh] max-w-[92vw] rounded-lg border border-border/70 bg-black object-contain shadow-2xl"
- />
- ) : (
- <img
- src={item.src}
- alt={item.name}
- className="max-h-[86vh] max-w-[92vw] select-none rounded-lg border border-border/70 bg-background object-contain shadow-2xl"
- draggable={false}
- />
- )}
- <p className="mt-2 max-w-[92vw] truncate text-center text-xs text-muted-foreground/80">
- {item.name}
- {preview.images.length > 1 ? ` (${index + 1}/${preview.images.length})` : ""}
- </p>
- </div>
+ <MediaActions source={actionsSource}>
+ <div className="relative isolate z-10 max-h-[92vh] max-w-[92vw]">
+ <Button
+ type="button"
+ size="icon-xs"
+ variant="ghost"
+ className="absolute right-2 top-2 z-20"
+ onClick={onClose}
+ aria-label={`Close ${mediaLabel} preview`}
+ >
+ <XIcon />
+ </Button>
+ {item.type === "video" && failedVideoSrc === item.src ? (
+ <ExpandedMediaFailure>
+ <p>This video could not be loaded or played.</p>
+ <OpenMediaLink originalUrl={item.originalUrl} src={item.src} fileName={item.name} />
+ </ExpandedMediaFailure>
+ ) : item.type === "video" ? (
+ <video
+ src={item.src}
+ aria-label={item.name}
+ autoPlay={item.autoPlay ?? true}
+ preload="metadata"
+ controls
+ playsInline
+ onLoadedMetadata={(event) => prepareVideoFirstFrame(event.currentTarget)}
+ onError={() => setFailedVideoSrc(item.src)}
+ className="max-h-[86vh] max-w-[92vw] rounded-lg border border-border/70 bg-black object-contain shadow-2xl"
+ />
+ ) : failedImageSrc === item.src ? (
+ <ExpandedMediaFailure>
+ <p>
+ {openOriginalLink
+ ? "This image could not be loaded."
+ : "Image unavailable. The file may have been moved or deleted."}
+ </p>
+ {openOriginalLink}
+ </ExpandedMediaFailure>
+ ) : (
+ <img
+ src={item.src}
+ alt={item.name}
+ className="max-h-[86vh] max-w-[92vw] select-none rounded-lg border border-border/70 bg-background object-contain shadow-2xl"
+ draggable={false}
+ onError={() => setFailedImageSrc(item.src)}
+ />
+ )}
+ <p className="mt-2 max-w-[92vw] truncate text-center text-xs text-muted-foreground/80">
+ {item.name}
+ {preview.images.length > 1 ? ` (${index + 1}/${preview.images.length})` : ""}
+ </p>
+ </div>
+ </MediaActions>
{preview.images.length > 1 && (
<Button
type="button"
@@ -156,6 +178,7 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
<ChevronRightIcon className="size-5" />
</Button>
)}
- </div>
+ </div>,
+ document.body,
);
});
diff --git a/apps/web/src/components/chat/ExpandedImagePreview.test.ts b/apps/web/src/components/chat/ExpandedImagePreview.test.ts
index 71979a3cb01..f75ba86e4ec 100644
--- a/apps/web/src/components/chat/ExpandedImagePreview.test.ts
+++ b/apps/web/src/components/chat/ExpandedImagePreview.test.ts
@@ -1,12 +1,46 @@
-import { describe, expect, it, vi } from "vite-plus/test";
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import type { ComposerFileAttachment } from "../../composerDraftStore";
import {
attachVideoThumbnail,
buildExpandedImagePreview,
- downloadVideoPreview,
+ resolveMarkdownMediaPreview,
} from "./ExpandedImagePreview";
+describe("resolveMarkdownMediaPreview", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it.each([
+ ["t3code:", "https:"],
+ ["t3code-dev:", "https:"],
+ ["http:", "http:"],
+ ["https:", "https:"],
+ ])(
+ "resolves protocol-relative media on %s without changing its source",
+ async (pageProtocol, mediaProtocol) => {
+ vi.stubGlobal("window", { location: { protocol: pageProtocol } });
+ const source = "//cdn.example.com/recording.mp4?token=a%2FB&v=1#t=2";
+ const preview = await resolveMarkdownMediaPreview({
+ source,
+ createAssetUrl: async () => {
+ throw new Error("Remote media must not request a local asset URL.");
+ },
+ });
+
+ expect(preview?.images[0]).toMatchObject({
+ src: `${mediaProtocol}${source}`,
+ originalUrl: source,
+ actionsSource: {
+ src: `${mediaProtocol}${source}`,
+ reference: { kind: "url", url: source },
+ },
+ });
+ },
+ );
+});
+
describe("buildExpandedImagePreview", () => {
it("builds a video preview for a local video attachment", () => {
const file = new File([new Uint8Array([1, 2, 3])], "demo.mp4", { type: "video/mp4" });
@@ -40,29 +74,4 @@ describe("buildExpandedImagePreview", () => {
detach();
await expect(fetch(url)).rejects.toThrow();
});
-
- it("downloads a video through a local blob URL", async () => {
- vi.useFakeTimers();
- const source = URL.createObjectURL(new Blob([new Uint8Array([1, 2, 3])]));
- const click = vi.fn();
- const anchor = { href: "", download: "", click };
- vi.stubGlobal("document", { createElement: () => anchor });
-
- try {
- await downloadVideoPreview(source, "demo.mp4");
-
- expect(anchor.download).toBe("demo.mp4");
- expect(anchor.href).toMatch(/^blob:/);
- expect(anchor.href).not.toBe(source);
- expect(click).toHaveBeenCalledOnce();
- expect((await fetch(anchor.href)).ok).toBe(true);
-
- await vi.runAllTimersAsync();
- await expect(fetch(anchor.href)).rejects.toThrow();
- } finally {
- URL.revokeObjectURL(source);
- vi.useRealTimers();
- vi.unstubAllGlobals();
- }
- });
});
diff --git a/apps/web/src/components/chat/ExpandedImagePreview.tsx b/apps/web/src/components/chat/ExpandedImagePreview.tsx
index b57a292e0bf..cddfb95052b 100644
--- a/apps/web/src/components/chat/ExpandedImagePreview.tsx
+++ b/apps/web/src/components/chat/ExpandedImagePreview.tsx
@@ -1,10 +1,34 @@
import type { ComposerFileAttachment } from "../../composerDraftStore";
import { type ChatImageAttachment, isVideoAttachment } from "../../types";
+import type {
+ AssetCreateUrlResult,
+ AssetResource,
+ EnvironmentId,
+ ScopedThreadRef,
+} from "@t3tools/contracts";
+import {
+ classifyMarkdownImageSource,
+ markdownImageSourceFragment,
+} from "@t3tools/client-runtime/markdown-images";
+import { mediaFileReference, mediaUrlReference } from "@t3tools/client-runtime/media-reference";
+import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
+import {
+ squashAtomCommandFailure,
+ type AtomCommandResult,
+} from "@t3tools/client-runtime/state/runtime";
+import { mediaKindFromPath, mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";
+import { resolveExternalWebLinkHost } from "./externalLinkContextMenu";
+import type { MediaActionSource } from "../media/MediaActions";
+import { resolveProtocolRelativeMediaUrl } from "../media/mediaContent";
export interface ExpandedImageItem {
src: string;
name: string;
type?: "video";
+ autoPlay?: boolean;
+ /** Authored remote destination to open when embedding fails, never a generated asset URL. */
+ originalUrl?: string;
+ actionsSource?: MediaActionSource;
}
export interface ExpandedImagePreview {
@@ -12,23 +36,98 @@ export interface ExpandedImagePreview {
index: number;
}
+/** Resolves a chat media reference on its owning environment, without downloading its bytes. */
+export async function resolveMarkdownMediaPreview(input: {
+ source: string;
+ resolvedFilePath?: string | undefined;
+ cwd?: string | undefined;
+ threadRef?: ScopedThreadRef | undefined;
+ httpBaseUrl?: string | undefined;
+ onOpenFile?: ((relativePath: string) => void) | undefined;
+ createAssetUrl: (input: {
+ environmentId: EnvironmentId;
+ input: { resource: AssetResource };
+ }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
+}): Promise<ExpandedImagePreview | null> {
+ const source =
+ input.resolvedFilePath === undefined
+ ? classifyMarkdownImageSource(input.source, input.cwd)
+ : { _tag: "WorkspaceFile" as const, path: input.resolvedFilePath };
+ if (source._tag === "Blocked") return null;
+
+ const path =
+ source._tag === "Direct"
+ ? source.uri.split(/[?#]/, 1)[0]!
+ : source.path.replace(/:\d+(?::\d+)?$/, "");
+ const name = path.split(/[\\/]/).at(-1) ?? "";
+ const extensionIndex = name.lastIndexOf(".");
+ const fileMimeType =
+ extensionIndex < 0 ? null : mediaMimeTypeFromExtension(name.slice(extensionIndex));
+ const kind =
+ source._tag === "Direct"
+ ? mediaKindFromPath(source.uri)
+ : fileMimeType === null
+ ? null
+ : fileMimeType.startsWith("video/")
+ ? "video"
+ : "image";
+ if (kind === null) return null;
+
+ const reference =
+ source._tag === "Direct" ? mediaUrlReference(source.uri) : mediaFileReference(path, input.cwd);
+ const relativePath = reference?.kind === "file" ? reference.relativePath : undefined;
+ let src: string;
+ let asset: MediaActionSource["asset"];
+ if (source._tag === "Direct") {
+ src = resolveProtocolRelativeMediaUrl(source.uri);
+ } else {
+ if (!input.threadRef || !input.httpBaseUrl) {
+ throw new Error("Reconnect to this environment and open the media again.");
+ }
+ asset = {
+ environmentId: input.threadRef.environmentId,
+ resource: { _tag: "media-file", threadId: input.threadRef.threadId, path },
+ };
+ const result = await input.createAssetUrl({
+ environmentId: asset.environmentId,
+ input: { resource: asset.resource },
+ });
+ if (result._tag === "Failure") throw squashAtomCommandFailure(result);
+ const assetUrl = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
+ if (assetUrl === null) throw new Error("The environment returned an invalid media URL.");
+ src = assetUrl + markdownImageSourceFragment(input.source);
+ }
+ return {
+ images: [
+ {
+ src,
+ name: name || kind,
+ ...(kind === "video" ? { type: "video", autoPlay: false } : {}),
+ ...(source._tag === "Direct" && resolveExternalWebLinkHost(source.uri) !== null
+ ? { originalUrl: source.uri }
+ : {}),
+ actionsSource: {
+ kind,
+ name: name || kind,
+ src,
+ ...(reference ? { reference } : {}),
+ ...(asset ? { asset } : {}),
+ ...(relativePath && input.onOpenFile
+ ? { onOpenFile: () => input.onOpenFile?.(relativePath) }
+ : {}),
+ },
+ },
+ ],
+ index: 0,
+ };
+}
+
export function attachVideoThumbnail(video: HTMLVideoElement, file: File): () => void {
const url = URL.createObjectURL(file);
video.src = url;
return () => URL.revokeObjectURL(url);
}
-export async function downloadVideoPreview(src: string, name: string): Promise<void> {
- const response = await fetch(src);
- if (!response.ok) throw new Error(`Could not download video (${response.status}).`);
- const url = URL.createObjectURL(await response.blob());
- const anchor = document.createElement("a");
- anchor.href = url;
- anchor.download = name;
- anchor.click();
- setTimeout(() => URL.revokeObjectURL(url), 30_000);
-}
-
export function buildExpandedImagePreview(
images: ReadonlyArray<ChatImageAttachment | ComposerFileAttachment>,
selectedImageId: string,
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index df944a98485..2f9cd56c893 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -2556,6 +2556,7 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
resource={viewedImage.resource}
alt={viewedImage.alt}
srcFragment={viewedImage.srcFragment}
+ workspaceRoot={workspaceRoot}
style={{ maxHeight: "16rem" }}
onImageExpand={onImageExpand}
/>
diff --git a/apps/web/src/components/chat/externalLinkContextMenu.test.ts b/apps/web/src/components/chat/externalLinkContextMenu.test.ts
index 9eb924280f8..5761d4f9514 100644
--- a/apps/web/src/components/chat/externalLinkContextMenu.test.ts
+++ b/apps/web/src/components/chat/externalLinkContextMenu.test.ts
@@ -181,6 +181,8 @@ describe("external chat link context menu", () => {
it.each([
["https://example.com", "example.com"],
["http://localhost:3000/path", "localhost"],
+ ["//cdn.example.com/clip.mp4?signature=abc#t=2", "cdn.example.com"],
+ ["//", null],
["#details", null],
["mailto:[email protected]", null],
["file:///tmp/example.txt", null],
diff --git a/apps/web/src/components/chat/externalLinkContextMenu.ts b/apps/web/src/components/chat/externalLinkContextMenu.ts
index b31f27668ad..d0f37f97d80 100644
--- a/apps/web/src/components/chat/externalLinkContextMenu.ts
+++ b/apps/web/src/components/chat/externalLinkContextMenu.ts
@@ -76,7 +76,7 @@ interface ShowExternalLinkContextMenuOptions {
export function resolveExternalWebLinkHost(href: string | undefined): string | null {
if (!href) return null;
try {
- const url = new URL(href);
+ const url = new URL(href.startsWith("//") ? `https:${href}` : href);
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
return url.hostname || null;
} catch {
diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx
index f9ebb307628..1272fa7d497 100644
--- a/apps/web/src/components/files/FilePreviewPanel.tsx
+++ b/apps/web/src/components/files/FilePreviewPanel.tsx
@@ -4,7 +4,10 @@ import type {
ResolvedKeybindingsConfig,
ScopedThreadRef,
} from "@t3tools/contracts";
-import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
+import {
+ isWorkspaceImagePreviewPath,
+ isWorkspaceVideoPreviewPath,
+} from "@t3tools/shared/filePreview";
import { VirtualizedFile, type SelectedLineRange } from "@pierre/diffs";
import { Editor } from "@pierre/diffs/editor";
import { EditProvider, File, type FileOptions, Virtualizer } from "@pierre/diffs/react";
@@ -12,13 +15,16 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
+import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
import { ChevronRight, Code2, Eye, FolderTree, Globe2, LoaderCircle } from "lucide-react";
import * as Schema from "effect/Schema";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
-import { useAssetUrlState } from "~/assets/assetUrls";
+import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
import { OpenInPicker } from "~/components/chat/OpenInPicker";
+import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer";
+import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions";
import { useRemoteOpenState } from "~/remoteOpen";
import { useClientSettings } from "~/hooks/useSettings";
import { useTheme } from "~/hooks/useTheme";
@@ -135,37 +141,53 @@ function WorkspaceImagePreview(props: {
readonly environmentId: EnvironmentId;
readonly threadRef: ScopedThreadRef;
readonly absolutePath: string;
+ readonly workspaceRoot: string;
readonly alt: string;
readonly workspaceMutationId: string | null;
}) {
- const assetUrl = useAssetUrlState(props.environmentId, {
- _tag: "workspace-file",
- threadId: props.threadRef.threadId,
- path: props.absolutePath,
- });
+ const resource = useMemo(
+ () => ({
+ _tag: "workspace-file" as const,
+ threadId: props.threadRef.threadId,
+ path: props.absolutePath,
+ }),
+ [props.threadRef.threadId, props.absolutePath],
+ );
+ const assetUrl = useAssetUrlState(props.environmentId, resource);
const [failedUrl, setFailedUrl] = useState<string | null>(null);
const revisionSuffix =
props.workspaceMutationId === null
? ""
: `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
const imageUrl = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
+ const actionsSource: MediaActionSource = {
+ kind: "image",
+ name: props.alt,
+ src: imageUrl,
+ reference: mediaFileReference(props.absolutePath, props.workspaceRoot),
+ asset: { environmentId: props.environmentId, resource },
+ };
if (assetUrl._tag === "Failure" || (imageUrl !== null && failedUrl === imageUrl)) {
return (
- <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
- Unable to load workspace image.
- </div>
+ <MediaActions source={actionsSource}>
+ <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
+ Unable to load workspace image.
+ </div>
+ </MediaActions>
);
}
return assetUrl._tag === "Success" && imageUrl !== null ? (
<div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4">
- <img
- className="max-h-full max-w-full object-contain"
- src={imageUrl}
- alt={props.alt}
- onError={() => setFailedUrl(imageUrl)}
- />
+ <MediaActions source={actionsSource}>
+ <img
+ className="max-h-full max-w-full object-contain"
+ src={imageUrl}
+ alt={props.alt}
+ onError={() => setFailedUrl(imageUrl)}
+ />
+ </MediaActions>
</div>
) : (
<div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
@@ -174,6 +196,60 @@ function WorkspaceImagePreview(props: {
);
}
+function WorkspaceVideoPreview(props: {
+ readonly environmentId: EnvironmentId;
+ readonly threadRef: ScopedThreadRef;
+ readonly absolutePath: string;
+ readonly workspaceRoot: string;
+ readonly name: string;
+ readonly workspaceMutationId: string | null;
+}) {
+ const resource = useMemo(
+ () => ({
+ _tag: "media-file" as const,
+ threadId: props.threadRef.threadId,
+ path: props.absolutePath,
+ }),
+ [props.threadRef.threadId, props.absolutePath],
+ );
+ const assetUrl = useAssetUrlState(props.environmentId, resource);
+ const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
+ useWorkspaceMutationRefresh({
+ mutationId: props.workspaceMutationId,
+ resourceKey: JSON.stringify([props.environmentId, resource]),
+ refresh: () => {
+ // Failed refreshes flow through assetUrl and can be retried from the player.
+ void refreshAssetUrl().catch(() => undefined);
+ },
+ });
+ const revisionSuffix =
+ props.workspaceMutationId === null
+ ? ""
+ : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
+ const latestUrl = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
+
+ return (
+ <div className="flex min-h-0 flex-1 items-center justify-center overflow-hidden p-4">
+ <MediaVideoPlayer
+ src={latestUrl}
+ sourceFailed={assetUrl._tag === "Failure"}
+ label={props.name}
+ revision={props.workspaceMutationId}
+ preload="metadata"
+ className="flex h-full min-h-0 w-full max-w-5xl items-center justify-center"
+ onRetry={refreshAssetUrl}
+ actionsSource={{
+ kind: "video",
+ name: props.name,
+ src: latestUrl,
+ reference: mediaFileReference(props.absolutePath, props.workspaceRoot),
+ asset: { environmentId: props.environmentId, resource },
+ }}
+ />
+ </div>
+ );
+}
+
function clampFileLine(contents: string, requestedLine: number): number {
let lineCount = 1;
for (let index = 0; index < contents.length; index += 1) {
@@ -791,8 +867,10 @@ export default function FilePreviewPanel({
const openPreview = useAtomCommand(previewEnvironment.open, {
reportFailure: false,
});
- const isImage = relativePath !== null && isWorkspaceImagePreviewPath(relativePath);
- const file = useProjectFileQuery(environmentId, cwd, relativePath, !isImage);
+ const isVideo = relativePath !== null && isWorkspaceVideoPreviewPath(relativePath);
+ const isImage = relativePath !== null && !isVideo && isWorkspaceImagePreviewPath(relativePath);
+ const isMedia = isImage || isVideo;
+ const file = useProjectFileQuery(environmentId, cwd, relativePath, !isMedia);
const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
// Reading markdown rendered is a preference, not a property of one file. Keeping
// it on the panel meant a thread switch dropped it and forced source back.
@@ -816,7 +894,10 @@ export default function FilePreviewPanel({
(revealLine === null ||
(handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId));
const canOpenInBrowser =
- relativePath !== null && isPreviewSupportedInRuntime() && isBrowserPreviewFile(relativePath);
+ relativePath !== null &&
+ !isVideo &&
+ isPreviewSupportedInRuntime() &&
+ isBrowserPreviewFile(relativePath);
const absolutePath = relativePath ? resolvePathLinkTarget(relativePath, cwd) : null;
const breadcrumbs = useMemo(
() => (relativePath ? fileBreadcrumbs(projectName, relativePath) : []),
@@ -824,7 +905,7 @@ export default function FilePreviewPanel({
);
const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);
useWorkspaceMutationRefresh({
- enabled: relativePath !== null && !isImage && !selectedFilePending,
+ enabled: relativePath !== null && !isMedia && !selectedFilePending,
mutationId: workspaceMutationId,
refresh: file.refresh,
resourceKey: `file:${environmentId}:${cwd}:${relativePath ?? ""}`,
@@ -999,7 +1080,7 @@ export default function FilePreviewPanel({
</Tooltip>
</div>
) : null}
- {relativePath && file.data?.truncated ? (
+ {relativePath && !isMedia && file.data?.truncated ? (
<div className="shrink-0 border-b border-warning/20 bg-warning-surface px-3 py-1.5 text-[11px] text-warning-foreground">
Preview limited to the first 1 MB of a {file.data.byteLength.toLocaleString()} byte file.
</div>
@@ -1011,12 +1092,23 @@ export default function FilePreviewPanel({
relativePath ? "flex" : "hidden",
)}
>
- {relativePath && isImage && absolutePath ? (
+ {relativePath && isVideo && absolutePath ? (
+ <WorkspaceVideoPreview
+ key={`${environmentId}:${threadRef.threadId}:${absolutePath}`}
+ environmentId={environmentId}
+ threadRef={threadRef}
+ absolutePath={absolutePath}
+ workspaceRoot={cwd}
+ name={relativePath}
+ workspaceMutationId={workspaceMutationId}
+ />
+ ) : relativePath && isImage && absolutePath ? (
<WorkspaceImagePreview
key={absolutePath}
environmentId={environmentId}
threadRef={threadRef}
absolutePath={absolutePath}
+ workspaceRoot={cwd}
alt={relativePath}
workspaceMutationId={workspaceMutationId}
/>
@@ -1099,7 +1191,7 @@ export default function FilePreviewPanel({
selectedPathRevealId={revealRequestId}
onOpenFile={onOpenFile}
workspaceMutationId={workspaceMutationId}
- {...(relativePath && !isImage ? { onRefreshSelectedFile: file.refresh } : {})}
+ {...(relativePath && !isMedia ? { onRefreshSelectedFile: file.refresh } : {})}
/>
</aside>
) : null}
diff --git a/apps/web/src/components/files/projectFilesQueryState.ts b/apps/web/src/components/files/projectFilesQueryState.ts
index 08203ff6b87..d02ec99605b 100644
--- a/apps/web/src/components/files/projectFilesQueryState.ts
+++ b/apps/web/src/components/files/projectFilesQueryState.ts
@@ -4,6 +4,10 @@ import type {
ProjectListEntriesResult,
ProjectReadFileResult,
} from "@t3tools/contracts";
+import {
+ isWorkspaceImagePreviewPath,
+ isWorkspaceVideoPreviewPath,
+} from "@t3tools/shared/filePreview";
import * as Cause from "effect/Cause";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
@@ -178,9 +182,13 @@ export function useProjectFileQuery(
relativePath: string | null,
enabled = true,
): ProjectQueryState<ProjectReadFileResult> {
- const atom = enabled
- ? getProjectFileQueryAtom(environmentId, cwd, relativePath)
- : EMPTY_PROJECT_FILE_QUERY_ATOM;
+ const isMedia =
+ relativePath !== null &&
+ (isWorkspaceImagePreviewPath(relativePath) || isWorkspaceVideoPreviewPath(relativePath));
+ const atom =
+ enabled && !isMedia
+ ? getProjectFileQueryAtom(environmentId, cwd, relativePath)
+ : EMPTY_PROJECT_FILE_QUERY_ATOM;
const result = useAtomValue(atom);
const refreshAtom = useAtomRefresh(atom);
const refresh = useCallback(() => refreshAtom(), [refreshAtom]);
diff --git a/apps/web/src/components/media/MediaActions.tsx b/apps/web/src/components/media/MediaActions.tsx
new file mode 100644
index 00000000000..a67cadbca5a
--- /dev/null
+++ b/apps/web/src/components/media/MediaActions.tsx
@@ -0,0 +1,189 @@
+import {
+ mediaReferenceFileName,
+ type MediaReference,
+} from "@t3tools/client-runtime/media-reference";
+import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import type { AssetResource, ContextMenuItem, EnvironmentId } from "@t3tools/contracts";
+import { useCallback, useRef, useState, type ReactElement } from "react";
+
+import { writeTextToClipboard } from "../../hooks/useCopyToClipboard";
+import { readLocalApi } from "../../localApi";
+import { assetEnvironment } from "../../state/assets";
+import { readPreparedConnection } from "../../state/session";
+import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
+import { stackedThreadToast, toastManager } from "../ui/toast";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { downloadMedia, readMediaPng } from "./mediaContent";
+
+export interface MediaActionSource {
+ readonly kind: "image" | "video";
+ readonly name: string;
+ readonly src: string | null;
+ readonly reference?: MediaReference;
+ readonly asset?: { readonly environmentId: EnvironmentId; readonly resource: AssetResource };
+ readonly onOpenFile?: () => void;
+}
+
+function mediaFileName(source: MediaActionSource): string {
+ return (
+ (source.reference && mediaReferenceFileName(source.reference)) || source.name || source.kind
+ );
+}
+
+/** Explicit byte operations get fresh capabilities without replacing a player's active source. */
+export function useMediaActions(source: MediaActionSource) {
+ const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
+ reportFailure: false,
+ refresh: true,
+ });
+ const actionUrl = useCallback(async () => {
+ if (!source.asset) {
+ if (!source.src) throw new Error("This media is unavailable. Try reopening the preview.");
+ return source.src;
+ }
+ const { environmentId, resource } = source.asset;
+ const connection = readPreparedConnection(environmentId);
+ if (!connection) throw new Error("Reconnect to this environment and try again.");
+ const result = await createAssetUrl({ environmentId, input: { resource } });
+ if (result._tag === "Failure") throw squashAtomCommandFailure(result);
+ const url = resolveAssetUrl(connection.httpBaseUrl, result.value.relativeUrl);
+ if (!url) throw new Error("The environment returned an invalid media URL.");
+ return url;
+ }, [source, createAssetUrl]);
+ const save = useCallback(async () => {
+ await downloadMedia(await actionUrl(), mediaFileName(source));
+ }, [actionUrl, source]);
+ const copyImage = useCallback(async () => {
+ if (!navigator.clipboard?.write || typeof ClipboardItem === "undefined") {
+ throw new Error(
+ "Image copying is unavailable. Use a secure browser connection or save the image.",
+ );
+ }
+ // Start the clipboard write in the user gesture; fetching/decoding may finish later.
+ await navigator.clipboard.write([
+ new ClipboardItem({ "image/png": actionUrl().then(readMediaPng) }),
+ ]);
+ }, [actionUrl]);
+ return { save, copyImage };
+}
+
+type MediaAction = "copy-full" | "copy-relative" | "copy-url" | "save" | "copy-image" | "open-file";
+
+/** Adds source-aware actions and a tooltip to the existing media element without a layout wrapper. */
+export function MediaActions({
+ source,
+ children,
+}: {
+ source: MediaActionSource;
+ children: ReactElement;
+}) {
+ const { save, copyImage } = useMediaActions(source);
+ const [tooltipOpen, setTooltipOpen] = useState(false);
+ const menuOpen = useRef(false);
+ const reference = source.reference;
+ const hasActions =
+ source.kind === "image" || reference !== undefined || source.onOpenFile !== undefined;
+ const tooltip = reference?.kind === "file" ? reference.path : (reference?.url ?? source.name);
+
+ const showMenu = async (position: { x: number; y: number }) => {
+ const api = readLocalApi();
+ if (!api || menuOpen.current) return;
+ menuOpen.current = true;
+ setTooltipOpen(false);
+ let failureTitle = "Could not open media menu";
+ let progressToast: ReturnType<typeof toastManager.add> | undefined;
+ try {
+ const items: ContextMenuItem<MediaAction>[] = [];
+ if (reference?.kind === "file") {
+ items.push({ id: "copy-full", label: "Copy full path" });
+ if (reference.relativePath)
+ items.push({ id: "copy-relative", label: "Copy relative path" });
+ } else if (reference?.kind === "url") {
+ items.push({ id: "copy-url", label: "Copy URL" });
+ }
+ if (source.kind === "image") {
+ const unavailable = source.src === null && source.asset === undefined;
+ items.push({ id: "save", label: "Save image", disabled: unavailable });
+ items.push({ id: "copy-image", label: "Copy image", disabled: unavailable });
+ }
+ if (source.onOpenFile) items.push({ id: "open-file", label: "Open in file viewer" });
+
+ const action = await api.contextMenu.show(items, position);
+ if (!action) return;
+ failureTitle = `Could not ${items.find((item) => item.id === action)?.label.toLowerCase() ?? "complete media action"}`;
+ const text =
+ action === "copy-full" && reference?.kind === "file"
+ ? reference.path
+ : action === "copy-relative" && reference?.kind === "file"
+ ? reference.relativePath
+ : action === "copy-url" && reference?.kind === "url"
+ ? reference.url
+ : undefined;
+ if (text !== undefined) {
+ await writeTextToClipboard(text, reference?.kind === "file" ? "file path" : "URL");
+ toastManager.add({
+ type: "success",
+ title: action === "copy-url" ? "URL copied" : "Path copied",
+ });
+ } else if (action === "open-file") {
+ source.onOpenFile?.();
+ } else if (action === "save" || action === "copy-image") {
+ progressToast = toastManager.add({
+ type: "loading",
+ title: action === "save" ? "Preparing image download…" : "Copying image…",
+ });
+ await (action === "save" ? save() : copyImage());
+ toastManager.update(progressToast, {
+ type: "success",
+ title: action === "save" ? "Download started" : "Image copied",
+ });
+ }
+ } catch (error) {
+ const toast = stackedThreadToast({
+ type: "error",
+ title: failureTitle,
+ description: error instanceof Error ? error.message : "The media action failed.",
+ });
+ if (progressToast) toastManager.update(progressToast, toast);
+ else toastManager.add(toast);
+ } finally {
+ menuOpen.current = false;
+ }
+ };
+
+ return (
+ <Tooltip open={tooltipOpen} onOpenChange={setTooltipOpen}>
+ <TooltipTrigger
+ render={children}
+ tabIndex={0}
+ onContextMenu={(event) => {
+ if (!hasActions || event.defaultPrevented) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const bounds = event.currentTarget.getBoundingClientRect();
+ void showMenu(
+ event.clientX === 0 && event.clientY === 0
+ ? { x: bounds.left, y: bounds.bottom }
+ : { x: event.clientX, y: event.clientY },
+ );
+ }}
+ onKeyDown={(event) => {
+ if (
+ !hasActions ||
+ event.defaultPrevented ||
+ !(event.key === "ContextMenu" || (event.shiftKey && event.key === "F10"))
+ )
+ return;
+ event.preventDefault();
+ event.stopPropagation();
+ const bounds = event.currentTarget.getBoundingClientRect();
+ void showMenu({ x: bounds.left, y: bounds.bottom });
+ }}
+ />
+ <TooltipPopup className="max-w-[min(40rem,calc(100vw-2rem))] break-all font-mono text-[11px] leading-tight">
+ {tooltip}
+ </TooltipPopup>
+ </Tooltip>
+ );
+}
diff --git a/apps/web/src/components/media/MediaVideoPlayer.tsx b/apps/web/src/components/media/MediaVideoPlayer.tsx
new file mode 100644
index 00000000000..8f2d75680c1
--- /dev/null
+++ b/apps/web/src/components/media/MediaVideoPlayer.tsx
@@ -0,0 +1,197 @@
+import { Maximize2Icon, RotateCwIcon, TriangleAlertIcon } from "lucide-react";
+import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react";
+
+import { cn } from "../../lib/utils";
+import { prepareVideoFirstFrame } from "../../lib/videoFirstFrame";
+import { Button } from "../ui/button";
+import { OpenMediaLink } from "./OpenMediaLink";
+import { MediaActions, type MediaActionSource } from "./MediaActions";
+
+interface MediaVideoPlayerProps {
+ readonly src: string | null;
+ readonly label: string;
+ readonly sourceFailed?: boolean | undefined;
+ readonly originalUrl?: string | undefined;
+ readonly revision?: string | null | undefined;
+ readonly preload?: "visible" | "metadata" | undefined;
+ readonly className?: string | undefined;
+ readonly videoClassName?: string | undefined;
+ readonly style?: CSSProperties | undefined;
+ readonly copyMarkdown?: string | undefined;
+ readonly onExpand?: ((src: string) => void) | undefined;
+ readonly onRetry?: (() => Promise<void>) | undefined;
+ readonly actionsSource?: MediaActionSource | undefined;
+}
+
+/** Keeps native range streaming and playback state consistent across inline and file previews. */
+export function MediaVideoPlayer({
+ src: latestSrc,
+ label,
+ sourceFailed = false,
+ originalUrl,
+ revision = null,
+ preload = "visible",
+ className,
+ videoClassName,
+ style,
+ copyMarkdown,
+ onExpand,
+ onRetry,
+ actionsSource,
+}: MediaVideoPlayerProps) {
+ const videoRef = useRef<HTMLVideoElement>(null);
+ const [playbackSource, setPlaybackSource] = useState<{
+ src: string;
+ revision: string | null;
+ } | null>(null);
+ const [failedSrc, setFailedSrc] = useState<string | null>(null);
+ const [retrying, setRetrying] = useState(false);
+ const [loadAttempt, setLoadAttempt] = useState(0);
+ const [preloadedSrc, setPreloadedSrc] = useState<string | null>(null);
+ const src = playbackSource?.src ?? latestSrc;
+ const sourceRevision = playbackSource === null ? revision : playbackSource.revision;
+ const failed = src !== null ? failedSrc === src : sourceFailed;
+
+ // Re-signing must not reset the playhead. Changed files refresh once playback pauses.
+ const refreshPausedRevision = useCallback(() => {
+ const video = videoRef.current;
+ if (video === null || video.paused || video.ended) {
+ setPlaybackSource((current) =>
+ current !== null && current.revision !== revision ? null : current,
+ );
+ }
+ }, [revision]);
+ useEffect(refreshPausedRevision, [refreshPausedRevision]);
+
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!video || preload === "metadata" || preloadedSrc === src) return;
+ if (typeof IntersectionObserver === "undefined") {
+ setPreloadedSrc(src);
+ return;
+ }
+ let active = true;
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (!active || !entries.some((entry) => entry.isIntersecting)) return;
+ setPreloadedSrc(src);
+ observer.disconnect();
+ },
+ { rootMargin: "200px" },
+ );
+ observer.observe(video);
+ return () => {
+ active = false;
+ observer.disconnect();
+ };
+ }, [src, preload, preloadedSrc, failed, loadAttempt]);
+
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!video) return;
+ const pauseWhenHidden = () => {
+ if (document.hidden) video.pause();
+ };
+ document.addEventListener("visibilitychange", pauseWhenHidden);
+ return () => {
+ document.removeEventListener("visibilitychange", pauseWhenHidden);
+ video.pause();
+ };
+ }, [src, failed, loadAttempt]);
+
+ const retry = async () => {
+ if (retrying) return;
+ setRetrying(true);
+ try {
+ await onRetry?.();
+ setPlaybackSource(null);
+ setFailedSrc(null);
+ setLoadAttempt((current) => current + 1);
+ } catch {
+ setFailedSrc(src);
+ } finally {
+ setRetrying(false);
+ }
+ };
+
+ const expandButton =
+ onExpand && src !== null ? (
+ <Button
+ type="button"
+ variant="secondary"
+ size="icon-xs"
+ className={failed ? undefined : "absolute right-2 top-2"}
+ aria-label={`Expand ${label || "video"}`}
+ onClick={() => {
+ videoRef.current?.pause();
+ onExpand(latestSrc ?? src);
+ }}
+ >
+ <Maximize2Icon />
+ </Button>
+ ) : null;
+
+ const player = (
+ <span
+ className={cn("relative inline-block align-middle", className)}
+ style={style}
+ data-markdown-copy={copyMarkdown}
+ >
+ {failed ? (
+ <span
+ role="alert"
+ className="flex min-h-28 flex-col items-center justify-center gap-3 rounded-lg border border-border/40 bg-muted/40 p-4 text-center text-sm text-muted-foreground"
+ >
+ <span className="inline-flex items-center gap-1.5">
+ <TriangleAlertIcon aria-hidden className="size-3.5 shrink-0" />
+ Video unavailable{label ? ` · ${label}` : ""}
+ </span>
+ <span className="flex flex-wrap items-center justify-center gap-2">
+ {latestSrc !== null || onRetry ? (
+ <Button
+ size="sm"
+ variant="secondary"
+ disabled={retrying}
+ onClick={() => void retry()}
+ >
+ <RotateCwIcon />
+ {retrying ? "Retrying…" : "Retry video"}
+ </Button>
+ ) : null}
+ <OpenMediaLink originalUrl={originalUrl} src={latestSrc ?? src} fileName={label} />
+ {expandButton}
+ </span>
+ </span>
+ ) : src !== null ? (
+ <video
+ key={loadAttempt}
+ ref={videoRef}
+ src={src}
+ aria-label={label || "Video preview"}
+ controls
+ playsInline
+ preload={preload === "metadata" || preloadedSrc === src ? "metadata" : "none"}
+ className={cn("aspect-video max-h-full w-full bg-black object-contain", videoClassName)}
+ style={style}
+ onLoadedMetadata={(event) => prepareVideoFirstFrame(event.currentTarget)}
+ onPlay={() => setPlaybackSource({ src, revision: sourceRevision })}
+ onPause={refreshPausedRevision}
+ onEnded={refreshPausedRevision}
+ onError={() => {
+ if (latestSrc !== null && src !== latestSrc) setPlaybackSource(null);
+ else setFailedSrc(src);
+ }}
+ />
+ ) : (
+ <span
+ role="status"
+ aria-label="Loading video"
+ className="block aspect-video w-full rounded-lg bg-muted/60"
+ style={style}
+ />
+ )}
+ {!failed && expandButton}
+ </span>
+ );
+ return actionsSource ? <MediaActions source={actionsSource}>{player}</MediaActions> : player;
+}
diff --git a/apps/web/src/components/media/OpenMediaLink.tsx b/apps/web/src/components/media/OpenMediaLink.tsx
new file mode 100644
index 00000000000..dd3162ddc8b
--- /dev/null
+++ b/apps/web/src/components/media/OpenMediaLink.tsx
@@ -0,0 +1,45 @@
+import { DownloadIcon, ExternalLinkIcon } from "lucide-react";
+
+import { resolveExternalWebLinkHost } from "../chat/externalLinkContextMenu";
+import { Button } from "../ui/button";
+import { resolveProtocolRelativeMediaUrl } from "./mediaContent";
+
+/** Navigates directly so the browser handles video playback and downloads, without fetching bytes. */
+export function OpenMediaLink(props: {
+ readonly originalUrl?: string | undefined;
+ readonly src?: string | null | undefined;
+ readonly fileName?: string | undefined;
+ readonly className?: string | undefined;
+}) {
+ const originalUrl =
+ resolveExternalWebLinkHost(props.originalUrl) !== null ? props.originalUrl : undefined;
+ const source = originalUrl ?? props.src;
+ if (!source) return null;
+ const url = resolveProtocolRelativeMediaUrl(source);
+ let isBlob = false;
+ try {
+ const protocol = new URL(url).protocol;
+ if (protocol !== "http:" && protocol !== "https:" && protocol !== "blob:") return null;
+ isBlob = protocol === "blob:";
+ } catch {
+ return null;
+ }
+ return (
+ <Button
+ size="sm"
+ variant="secondary"
+ className={props.className}
+ render={
+ <a
+ href={url}
+ target={isBlob ? undefined : "_blank"}
+ download={isBlob ? props.fileName || true : undefined}
+ rel="noopener noreferrer"
+ />
+ }
+ >
+ {isBlob ? <DownloadIcon /> : <ExternalLinkIcon />}
+ {originalUrl ? "Open original" : isBlob ? "Download video" : "Open in browser"}
+ </Button>
+ );
+}
diff --git a/apps/web/src/components/media/mediaContent.ts b/apps/web/src/components/media/mediaContent.ts
new file mode 100644
index 00000000000..c20348ecd03
--- /dev/null
+++ b/apps/web/src/components/media/mediaContent.ts
@@ -0,0 +1,82 @@
+/** Resolves web references without inheriting the desktop renderer's custom app scheme. */
+export function resolveProtocolRelativeMediaUrl(src: string): string {
+ if (!src.startsWith("//")) return src;
+ const protocol =
+ typeof window !== "undefined" && window.location.protocol === "http:" ? "http:" : "https:";
+ return `${protocol}${src}`;
+}
+
+/** Reads media only for an explicit save/copy action; remote hosts must allow browser CORS. */
+async function readMediaBlob(src: string): Promise<Blob> {
+ let response: Response;
+ try {
+ response = await fetch(src);
+ } catch (cause) {
+ throw new Error(
+ "The file could not be fetched. The host may block browser access (CORS), or the connection may be unavailable.",
+ { cause },
+ );
+ }
+ if (!response.ok) throw new Error(`The file could not be fetched (HTTP ${response.status}).`);
+ const blob = await response.blob();
+ if (blob.type.split(";", 1)[0] === "text/html") {
+ throw new Error("This link returned a web page instead of media. Open the original URL.");
+ }
+ return blob;
+}
+
+/** Downloads the original bytes with their original filename, without changing playback URLs. */
+export async function downloadMedia(src: string, name: string): Promise<void> {
+ const url = URL.createObjectURL(await readMediaBlob(src));
+ try {
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = name;
+ anchor.click();
+ } finally {
+ setTimeout(() => URL.revokeObjectURL(url), 30_000);
+ }
+}
+
+/** Converts browser-decodable images, including SVG, into the clipboard's portable PNG format. */
+export async function readMediaPng(src: string): Promise<Blob> {
+ const blob = await readMediaBlob(src);
+ if (blob.type.split(";", 1)[0] === "image/png") return blob;
+
+ const url = URL.createObjectURL(blob);
+ const image = new Image();
+ image.src = url;
+ try {
+ try {
+ await image.decode();
+ } catch (cause) {
+ throw new Error(
+ "The browser could not decode this image for copying. Try saving it instead.",
+ {
+ cause,
+ },
+ );
+ }
+ const { naturalWidth: width, naturalHeight: height } = image;
+ if (width <= 0 || height <= 0 || width * height > 64_000_000) {
+ throw new Error(
+ "This image is too large or has no usable dimensions. Try saving it instead.",
+ );
+ }
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ const context = canvas.getContext("2d");
+ if (!context) throw new Error("Image copying is unavailable in this browser.");
+ context.drawImage(image, 0, 0);
+ return await new Promise<Blob>((resolve, reject) => {
+ canvas.toBlob(
+ (png) =>
+ png ? resolve(png) : reject(new Error("The image could not be converted to PNG.")),
+ "image/png",
+ );
+ });
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+}
diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
index ad06eb21e2a..020bafbd129 100644
--- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
@@ -14,10 +14,8 @@ export const PullRequestMarkdownContext = createContext<string | null>(null);
* A pull request body, rendered with the app's markdown renderer plus a card for each upload
* embedded in it, which that renderer drops on the floor.
*
- * The card links out instead of playing in place. GitHub serves the file as uploaded — Mac
- * recordings are `video/quicktime`, which no Chromium decodes — and the desktop window's
- * `media-src` allows only `'self'`, the app scheme and `blob:`, so a remote source is refused
- * before a byte is fetched. Opening the host works for every format.
+ * These upload URLs do not identify the media format. The card links to GitHub, where the
+ * original upload can be opened or downloaded even when its codec cannot play in the client.
*/
export function PullRequestMarkdown({
text,
diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts
index bfdb98c2d22..2c43641b2b5 100644
--- a/apps/web/src/contextMenuFallback.ts
+++ b/apps/web/src/contextMenuFallback.ts
@@ -196,6 +196,10 @@ function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly H
// dismiss it with the same result as an outside click or Escape.
let activeContextMenuDismiss: (() => void) | null = null;
+export function isContextMenuOpen(): boolean {
+ return activeContextMenuDismiss !== null;
+}
+
/**
* Closes the currently open fallback context menu, resolving its show() with
* null (the same result as dismissing by outside click or Escape). No-op when
diff --git a/apps/web/src/lib/videoFirstFrame.test.ts b/apps/web/src/lib/videoFirstFrame.test.ts
new file mode 100644
index 00000000000..f090a503c38
--- /dev/null
+++ b/apps/web/src/lib/videoFirstFrame.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { prepareVideoFirstFrame } from "./videoFirstFrame";
+
+type PreviewVideo = Parameters<typeof prepareVideoFirstFrame>[0];
+
+function previewVideo(overrides: Partial<PreviewVideo> = {}): PreviewVideo {
+ return {
+ autoplay: false,
+ paused: true,
+ seeking: false,
+ currentTime: 0,
+ duration: 5,
+ played: { length: 0, start: () => 0, end: () => 0 },
+ src: "https://environment.test/api/assets/signed/video.mp4?signature=example",
+ ...overrides,
+ };
+}
+
+describe("prepareVideoFirstFrame", () => {
+ it.each([
+ [5, 0.1],
+ [0.05, 0.025],
+ ])(
+ "seeks within a %s second video only once when metadata repeats",
+ (duration, expectedPosition) => {
+ const video = previewVideo({ duration });
+ const seeks: number[] = [];
+ Object.defineProperty(video, "currentTime", {
+ get: () => seeks.at(-1) ?? 0,
+ set: (value: number) => seeks.push(value),
+ });
+ prepareVideoFirstFrame(video);
+ prepareVideoFirstFrame(video);
+
+ expect(seeks).toEqual([expectedPosition]);
+ },
+ );
+
+ it.each<Partial<PreviewVideo>>([
+ { autoplay: true },
+ { paused: false },
+ { seeking: true },
+ { currentTime: 2 },
+ { played: { length: 1, start: () => 0, end: () => 2 } },
+ { duration: 0 },
+ { duration: Number.POSITIVE_INFINITY },
+ ])("does not seek over playback or unavailable metadata: %j", (state) => {
+ const video = previewVideo(state);
+ const position = video.currentTime;
+
+ prepareVideoFirstFrame(video);
+
+ expect(video.currentTime).toBe(position);
+ });
+
+ it.each([
+ ["video.mp4#t=0,4", 0],
+ ["video.mp4#xywh=0,0,100,100&%74=3", 0],
+ ["video%23t=3.mp4", 0.1],
+ ])(
+ "distinguishes temporal fragments from encoded filename hashes: %s",
+ (path, expectedPosition) => {
+ const video = previewVideo({ src: `https://environment.test/${path}` });
+
+ prepareVideoFirstFrame(video);
+
+ expect(video.currentTime).toBe(expectedPosition);
+ },
+ );
+
+ it("tolerates a browser rejecting the preview seek", () => {
+ const video = previewVideo();
+ Object.defineProperty(video, "currentTime", {
+ get: () => 0,
+ set: () => {
+ throw new Error("The stream is not seekable yet");
+ },
+ });
+
+ expect(() => prepareVideoFirstFrame(video)).not.toThrow();
+ });
+});
diff --git a/apps/web/src/lib/videoFirstFrame.ts b/apps/web/src/lib/videoFirstFrame.ts
new file mode 100644
index 00000000000..07acdbbc9eb
--- /dev/null
+++ b/apps/web/src/lib/videoFirstFrame.ts
@@ -0,0 +1,28 @@
+/** Requests an initial frame without playing or replacing the video's streaming source. */
+export function prepareVideoFirstFrame(
+ video: Pick<
+ HTMLVideoElement,
+ "autoplay" | "currentTime" | "duration" | "paused" | "played" | "seeking" | "src"
+ >,
+): void {
+ if (
+ video.autoplay ||
+ !video.paused ||
+ video.seeking ||
+ video.currentTime !== 0 ||
+ video.played.length > 0 ||
+ !Number.isFinite(video.duration) ||
+ video.duration <= 0
+ ) {
+ return;
+ }
+
+ const fragment = video.src.split("#", 2)[1];
+ if (fragment && new URLSearchParams(fragment).has("t")) return;
+
+ try {
+ video.currentTime = Math.min(0.1, video.duration / 2);
+ } catch {
+ // A rejected preview seek must leave the native Play control usable.
+ }
+}
diff --git a/apps/web/src/markdown-links.test.ts b/apps/web/src/markdown-links.test.ts
index 75c5d329f9f..fc77f48c2ca 100644
--- a/apps/web/src/markdown-links.test.ts
+++ b/apps/web/src/markdown-links.test.ts
@@ -163,6 +163,7 @@ describe("resolveMarkdownFileLinkTarget", () => {
it("ignores external urls", () => {
expect(resolveMarkdownFileLinkTarget("https://example.com/docs")).toBeNull();
+ expect(resolveMarkdownFileLinkTarget("//cdn.example.com/clip.mp4", "/workspace")).toBeNull();
});
it("does not double-decode file URLs", () => {
diff --git a/apps/web/src/markdown-links.ts b/apps/web/src/markdown-links.ts
index 1ce25765ee4..7ea965e71bb 100644
--- a/apps/web/src/markdown-links.ts
+++ b/apps/web/src/markdown-links.ts
@@ -1,3 +1,8 @@
+import {
+ inlineCodeFilePathCandidate,
+ isConventionalFilePosition,
+} from "@t3tools/client-runtime/markdown-links";
+
import { formatWorkspaceRelativePath } from "./filePathDisplay";
import {
isTerminalLinkActivation,
@@ -190,7 +195,7 @@ export function resolveMarkdownFileLinkTarget(
): string | null {
if (!href) return null;
const rawHref = normalizeMarkdownLinkDestination(href);
- if (rawHref.length === 0 || rawHref.startsWith("#")) return null;
+ if (rawHref.length === 0 || rawHref.startsWith("#") || rawHref.startsWith("//")) return null;
const fileUrlTarget = rawHref.toLowerCase().startsWith("file:")
? parseFileUrlHref(rawHref)
@@ -221,124 +226,6 @@ export function resolveMarkdownFileLinkTarget(
return resolvePathLinkTarget(pathWithPosition, cwd);
}
-const INLINE_CODE_DISQUALIFIER_PATTERN = /[\s`]/;
-const PATH_SEPARATOR_PATTERN = /[\\/]/;
-const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
-const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
-const BARE_EXTENSIONLESS_POSITION_PATTERN = /^[A-Za-z0-9_-]+(?::\d+){1,2}$/;
-// Any `Name:digits` shape also matches `error:1`, `port:3000`, `TODO:12`, so
-// extensionless linking is limited to conventional filenames.
-const EXTENSIONLESS_FILE_NAMES = new Set([
- "Makefile",
- "makefile",
- "GNUmakefile",
- "Dockerfile",
- "Containerfile",
- "Justfile",
- "justfile",
- "Rakefile",
- "Gemfile",
- "Procfile",
- "Brewfile",
- "Caddyfile",
- "Vagrantfile",
- "Jenkinsfile",
- "Podfile",
- "Fastfile",
- "BUILD",
- "WORKSPACE",
- "LICENSE",
- "LICENCE",
- "COPYING",
- "NOTICE",
- "AUTHORS",
- "CONTRIBUTORS",
- "CHANGELOG",
- "README",
- "CODEOWNERS",
-]);
-const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
-// Allowlists, not full public-suffix detection: treating every dotted first
-// segment as a host would swallow real paths like `conf.d/x.conf` or
-// `Makefile.in:12`. Extensions that double as filename suffixes (`sh`, `md`,
-// `ts`, `rs`, `in`, ...) are deliberately absent from both sets.
-const GENERIC_HOSTNAME_TLDS = new Set([
- "com",
- "net",
- "org",
- "io",
- "dev",
- "app",
- "ai",
- "co",
- "edu",
- "gov",
- "mil",
- "info",
- "biz",
- "xyz",
- "me",
- "tv",
- "cc",
- "gg",
- "chat",
- "cloud",
- "site",
- "online",
- "tech",
- "store",
- "link",
-]);
-// Country codes collide with file extensions (`.pl` Perl, `.pt` PyTorch,
-// `.es` ES modules), so they only count as host evidence when the candidate
-// lacks a :line suffix — an explicit line reference marks a file and wins.
-const COUNTRY_HOSTNAME_TLDS = new Set([
- "uk",
- "de",
- "fr",
- "nl",
- "se",
- "no",
- "fi",
- "dk",
- "pl",
- "ch",
- "at",
- "be",
- "es",
- "it",
- "pt",
- "eu",
- "us",
- "ca",
- "au",
- "nz",
- "jp",
- "kr",
- "cn",
- "br",
- "ru",
- "mx",
- "ie",
- "cz",
- "tr",
- "sg",
- "hk",
-]);
-
-/** `127.0.0.1`, `localhost`, `example.com`, `1.2.3` — hosts and versions, not files. */
-function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
- if (segment.startsWith(".")) return false;
- const lowered = segment.toLowerCase();
- if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
- if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
- const labels = lowered.split(".");
- const lastLabel = labels[labels.length - 1];
- if (labels.length < 2 || lastLabel === undefined) return false;
- if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
- return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
-}
-
/**
* Inline code spans mostly hold identifiers, commands, and refs (`node.meta`,
* `origin/main`) rather than deliberate link destinations, so auto-linking
@@ -349,33 +236,8 @@ export function resolveInlineCodeFileLinkMeta(
codeText: string,
cwd?: string,
): MarkdownFileLinkMeta | null {
- const trimmed = codeText.trim();
- if (trimmed.length === 0 || INLINE_CODE_DISQUALIFIER_PATTERN.test(trimmed)) return null;
-
- // Windows drive/UNC paths keep their backslashes; any other backslashes are
- // relative Windows-style paths, which neither the shape checks nor the
- // downstream resolver understand — normalize them to forward slashes.
- const candidate =
- WINDOWS_DRIVE_PATH_PATTERN.test(trimmed) || WINDOWS_UNC_PATH_PATTERN.test(trimmed)
- ? trimmed
- : trimmed.replaceAll("\\", "/");
-
- const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
- if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
-
- const hasExplicitPathShape =
- RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
- candidate.startsWith("/") ||
- WINDOWS_DRIVE_PATH_PATTERN.test(candidate) ||
- WINDOWS_UNC_PATH_PATTERN.test(candidate);
- if (!hasExplicitPathShape) {
- const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
- const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
- if (looksLikeHostname(firstSegment, hasPosition)) return null;
- if (!hasPosition && !FILE_EXTENSION_PATTERN.test(basenameOfPath(withoutPosition))) {
- return null;
- }
- }
+ const candidate = inlineCodeFilePathCandidate(codeText);
+ if (candidate === null) return null;
const resolved = resolveMarkdownFileLinkMeta(candidate, cwd);
if (resolved) return resolved;
@@ -383,11 +245,7 @@ export function resolveInlineCodeFileLinkMeta(
// `Makefile:12` — conventional extensionless names fail the generic
// markdown-link candidate patterns, but here the :line suffix already
// marked the span as a file reference.
- if (
- cwd &&
- BARE_EXTENSIONLESS_POSITION_PATTERN.test(candidate) &&
- EXTENSIONLESS_FILE_NAMES.has(candidate.replace(POSITION_SUFFIX_PATTERN, ""))
- ) {
+ if (cwd && isConventionalFilePosition(candidate)) {
return buildFileLinkMetaFromTarget(resolvePathLinkTarget(candidate, cwd), cwd);
}
return null;
diff --git a/apps/web/src/pierre-icons.ts b/apps/web/src/pierre-icons.ts
index b2511563df0..b4b83e4df97 100644
--- a/apps/web/src/pierre-icons.ts
+++ b/apps/web/src/pierre-icons.ts
@@ -3,6 +3,7 @@ import {
getBuiltInSpriteSheet,
type FileTreeIcons,
} from "@pierre/trees";
+import { VIDEO_FILE_EXTENSIONS } from "@t3tools/shared/video";
export interface PierreIconResolution {
name: string;
@@ -13,6 +14,13 @@ const PIERRE_ICON_SPRITE_ID = "t3code-pierre-file-icon-sprite";
const T3_FILE_ICON_SPRITE = `
<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" aria-hidden="true">
+ <!-- Lucide Film icon, ISC license. -->
+ <symbol id="t3-file-icon-video" viewBox="0 0 24 24">
+ <g fill="none" stroke="#a631be" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <rect width="18" height="18" x="3" y="3" rx="2" />
+ <path d="M7 3v18M3 7.5h4M3 12h18M3 16.5h4M17 3v18M17 7.5h4M17 16.5h4" />
+ </g>
+ </symbol>
<symbol id="t3-file-icon-package-json" viewBox="0 0 32 32">
<path d="M2 2H30V30H2" fill="#c12127" />
<path d="M7.25 7.25h17.5v17.5h-3.5v-14H16v14H7.25" fill="#fff" />
@@ -50,6 +58,9 @@ export const T3_PIERRE_ICONS = {
"pnpm-lock.yaml": "t3-file-icon-pnpm",
"pnpm-workspace.yaml": "t3-file-icon-pnpm",
},
+ byFileExtension: Object.fromEntries(
+ VIDEO_FILE_EXTENSIONS.map((extension) => [extension, "t3-file-icon-video"]),
+ ),
} satisfies FileTreeIcons;
const completeIconResolver = createFileTreeIconResolver(T3_PIERRE_ICONS);
diff --git a/apps/web/src/state/use-atom-query-runner.ts b/apps/web/src/state/use-atom-query-runner.ts
index 22f971e09a5..691b1f43cb8 100644
--- a/apps/web/src/state/use-atom-query-runner.ts
+++ b/apps/web/src/state/use-atom-query-runner.ts
@@ -1,7 +1,7 @@
import { RegistryContext } from "@effect/atom-react";
import {
executeAtomQuery,
- type AtomCommandOptions,
+ type AtomQueryOptions,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import { AsyncResult, type Atom } from "effect/unstable/reactivity";
@@ -9,12 +9,13 @@ import { useCallback, useContext } from "react";
export function useAtomQueryRunner<T, A, E>(
family: (target: T) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
- options?: string | AtomCommandOptions,
+ options?: string | AtomQueryOptions,
): (target: T) => Promise<AtomCommandResult<A, E>> {
const registry = useContext(RegistryContext);
const explicitLabel = typeof options === "string" ? options : options?.label;
const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true);
const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true);
+ const refresh = typeof options === "string" ? false : (options?.refresh ?? false);
return useCallback(
(target: T) => {
@@ -23,8 +24,9 @@ export function useAtomQueryRunner<T, A, E>(
label: explicitLabel ?? atom.label?.[0] ?? "atom query",
reportFailure,
reportDefect,
+ refresh,
});
},
- [explicitLabel, family, registry, reportDefect, reportFailure],
+ [explicitLabel, family, registry, refresh, reportDefect, reportFailure],
);
}
diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.md
index 5518d8e8c58..ac54e60dfcb 100644
--- a/docs/internals/environment-auth.md
+++ b/docs/internals/environment-auth.md
@@ -28,6 +28,40 @@ managed relay connectivity:
The desktop bootstrap credential and command-line administrative bootstrap
credentials additionally grant `access:read access:write relay:write`.
+## Media preview access
+
+Clients with `orchestration:read` can request a `media-file` URL through `assets.createUrl` for
+supported images and videos anywhere the environment's server account can read. A thread ID
+supplies the workspace for relative paths; absolute paths refer to the environment host, not the
+client. This follows the environment-wide authorization model rather than introducing per-project
+filesystem permissions.
+
+[`AssetAccess.ts`](../../apps/server/src/assets/AssetAccess.ts) resolves symlinks, requires a regular
+file, and validates the resolved file's literal extension. It opens the file and signs its canonical
+path and device/inode identity for one hour. The token grants access to that exact file, not adjacent
+files or its containing directory. Serving rechecks the canonical path, media type, and opened
+descriptor's identity, then streams full or partial responses from that descriptor. Replacing a
+file atomically requires a freshly signed URL; editing it in place does not. The existing workspace
+boundary still applies to HTML, PDF, and other workspace previews. Uploaded attachments keep their
+separate asset resource.
+
+Signed asset URLs are bearer credentials. Anyone who obtains a URL and can reach the environment
+can fetch that file until it expires. Clients should copy the authored reference, not the temporary
+URL. Responses use `nosniff`; SVG responses retain their restrictive sandbox policy. Video reads
+support byte ranges so playback does not require a complete download first.
+
+Host videos can change in place, so their responses use `private, no-store` and omit `ETag`
+and `Last-Modified`. File metadata cannot prove byte-for-byte identity for `If-Range`; advertising
+those validators would encourage native players to send conditional seeks that require a full
+response. Ordinary range requests receive partial responses. An explicitly supplied `If-Range`
+still falls back to a full response because no strong validator is available. Host image previews
+keep their private cache policy and weak metadata validators.
+
+The server serves media in place without importing it into attachment storage. Deletion makes
+future server reads fail, though an already loaded client or its cache can retain bytes. Native
+viewers may use temporary client-side files for display or explicit sharing; those are not durable
+environment copies.
+
## Authentication Flows
### Browser Session
diff --git a/docs/user/composer.md b/docs/user/composer.md
index 97f1f5cb14f..62974880f8e 100644
--- a/docs/user/composer.md
+++ b/docs/user/composer.md
@@ -34,7 +34,7 @@ viewer and PDFs open the system chooser.
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
+On web, desktop, and 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
@@ -52,6 +52,48 @@ On mobile, the model picker shows each OpenCode model's upstream provider, such
GitHub Copilot, or OpenCode Zen, beneath its name. Search by that provider name to narrow the list
when starting a thread or changing an existing thread's model.
+## Images and videos in messages
+
+On web, desktop, and mobile, select a link to an image or video to open it inside T3 Code.
+Workspace image and video links open the file viewer. Links to media outside the workspace
+open a media preview.
+Videos opened from the file explorer or a file-viewer tab also play inside T3 Code. They
+stream from the environment as needed, rather than downloading the entire video before playback.
+Paths in inline code, such as `/tmp/recording.mp4`, work the same way. Image embeds stay inline;
+video embeds show a player with controls and an option to expand. Visible video previews load
+an initial frame when supported, but stay paused until you press Play. Video file references use
+a filmstrip icon.
+
+On web and desktop, hover over a preview to see its full file path or original URL. Right-click
+to copy that reference, save an image, or copy an image to the clipboard. Use the video player's
+built-in controls to download videos. If the player cannot decode a video, its error message
+offers a link to open the source in the browser. Workspace media also offers **Copy relative
+path** and **Open in file viewer**. These actions are available in expanded previews too.
+
+On mobile, touch and hold an inline image or use a preview's **Media actions** menu to see its
+source, copy the path or URL, or choose **Save or share**. Workspace media can open in the file
+viewer from the same menu. Saving downloads a copy only when you request it; it does not change
+how the video buffers during playback.
+
+Use Markdown image syntax to embed either kind of media:
+
+```markdown
+![Screenshot](/tmp/screenshot.png)
+![Recording](/tmp/recording.mp4)
+[Open recording](/tmp/recording.mp4)
+```
+
+Relative paths resolve from the thread's workspace. Absolute paths and `file://` links refer to
+the environment's machine, even when you connect remotely or use your phone. Supported media
+can live outside the workspace, including in Downloads or `/tmp`.
+
+T3 Code serves the original file without adding it to attachment storage. If that file is moved
+or deleted, its preview can no longer load from the environment. A browser or device may still
+have a cached copy. Supported video formats and codecs depend on the browser or device.
+
+Bare paths in ordinary prose and paths inside code blocks stay text. Raw HTML `<video>` tags
+are not supported; use the Markdown embed syntax above.
+
## Changing projects
On web and desktop, changing the project from a new thread keeps the current environment when that
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index def75dafc5a..d4b4f717030 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -19,6 +19,14 @@
"types": "./src/markdownImages.ts",
"default": "./src/markdownImages.ts"
},
+ "./markdown-links": {
+ "types": "./src/markdownLinks.ts",
+ "default": "./src/markdownLinks.ts"
+ },
+ "./media-reference": {
+ "types": "./src/mediaReference.ts",
+ "default": "./src/mediaReference.ts"
+ },
"./codex-file-citations": {
"types": "./src/codexFileCitations.ts",
"default": "./src/codexFileCitations.ts"
diff --git a/packages/client-runtime/src/markdownImages.ts b/packages/client-runtime/src/markdownImages.ts
index 671a94d490d..6f6fa31dbff 100644
--- a/packages/client-runtime/src/markdownImages.ts
+++ b/packages/client-runtime/src/markdownImages.ts
@@ -67,7 +67,7 @@ function joinWorkspacePath(workspaceRoot: string, relativePath: string): string
}
/**
- * Classifies a markdown image source by where its bytes must be loaded from.
+ * Classifies a markdown image or video source by where its bytes must be loaded from.
* Filesystem paths belong to the environment host and must never reach a
* browser or native image component without first becoming a signed asset URL.
*/
diff --git a/packages/client-runtime/src/markdownLinks.test.ts b/packages/client-runtime/src/markdownLinks.test.ts
new file mode 100644
index 00000000000..5763fc5b6ff
--- /dev/null
+++ b/packages/client-runtime/src/markdownLinks.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { inlineCodeFilePathCandidate, isConventionalFilePosition } from "./markdownLinks.js";
+
+describe("inlineCodeFilePathCandidate", () => {
+ it.each([
+ ["src\\main.ts", "src/main.ts"],
+ ["C:\\Users\\demo\\image.png", "C:\\Users\\demo\\image.png"],
+ ["\\\\server\\share\\image.png", "\\\\server\\share\\image.png"],
+ ["conf.d/nginx.conf", "conf.d/nginx.conf"],
+ ["script.pl:10", "script.pl:10"],
+ ["node.meta", null],
+ ["Recorded evidence here: /tmp/image.png", null],
+ ["origin/main", null],
+ ["127.0.0.1:3000", null],
+ ["example.com/index.html", null],
+ ["example.pl/index.html", null],
+ ])("distinguishes file paths from code and hostnames in %s", (source, candidate) => {
+ expect(inlineCodeFilePathCandidate(source)).toBe(candidate);
+ });
+});
+
+describe("isConventionalFilePosition", () => {
+ it("distinguishes extensionless file locations from labels and ports", () => {
+ expect(isConventionalFilePosition("Dockerfile:8:2")).toBe(true);
+ expect(isConventionalFilePosition("Makefile")).toBe(false);
+ expect(isConventionalFilePosition("TODO:12")).toBe(false);
+ expect(isConventionalFilePosition("port:3000")).toBe(false);
+ });
+});
diff --git a/packages/client-runtime/src/markdownLinks.ts b/packages/client-runtime/src/markdownLinks.ts
new file mode 100644
index 00000000000..73048357e61
--- /dev/null
+++ b/packages/client-runtime/src/markdownLinks.ts
@@ -0,0 +1,158 @@
+const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
+const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
+const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
+const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
+const INLINE_CODE_DISQUALIFIER_PATTERN = /[\s`]/;
+const PATH_SEPARATOR_PATTERN = /[\\/]/;
+const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
+const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
+const BARE_EXTENSIONLESS_POSITION_PATTERN = /^[A-Za-z0-9_-]+(?::\d+){1,2}$/;
+// `Name:digits` also matches `error:1`, `port:3000`, and `TODO:12`.
+const EXTENSIONLESS_FILE_NAMES = new Set([
+ "Makefile",
+ "makefile",
+ "GNUmakefile",
+ "Dockerfile",
+ "Containerfile",
+ "Justfile",
+ "justfile",
+ "Rakefile",
+ "Gemfile",
+ "Procfile",
+ "Brewfile",
+ "Caddyfile",
+ "Vagrantfile",
+ "Jenkinsfile",
+ "Podfile",
+ "Fastfile",
+ "BUILD",
+ "WORKSPACE",
+ "LICENSE",
+ "LICENCE",
+ "COPYING",
+ "NOTICE",
+ "AUTHORS",
+ "CONTRIBUTORS",
+ "CHANGELOG",
+ "README",
+ "CODEOWNERS",
+]);
+const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
+// These allowlists avoid classifying dotted directories such as `conf.d/`
+// or filenames such as `Makefile.in:12` as hosts.
+const GENERIC_HOSTNAME_TLDS = new Set([
+ "com",
+ "net",
+ "org",
+ "io",
+ "dev",
+ "app",
+ "ai",
+ "co",
+ "edu",
+ "gov",
+ "mil",
+ "info",
+ "biz",
+ "xyz",
+ "me",
+ "tv",
+ "cc",
+ "gg",
+ "chat",
+ "cloud",
+ "site",
+ "online",
+ "tech",
+ "store",
+ "link",
+]);
+// Country codes also name file extensions. A :line suffix makes `.pl`
+// and `.pt` files more likely than hostnames.
+const COUNTRY_HOSTNAME_TLDS = new Set([
+ "uk",
+ "de",
+ "fr",
+ "nl",
+ "se",
+ "no",
+ "fi",
+ "dk",
+ "pl",
+ "ch",
+ "at",
+ "be",
+ "es",
+ "it",
+ "pt",
+ "eu",
+ "us",
+ "ca",
+ "au",
+ "nz",
+ "jp",
+ "kr",
+ "cn",
+ "br",
+ "ru",
+ "mx",
+ "ie",
+ "cz",
+ "tr",
+ "sg",
+ "hk",
+]);
+
+function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
+ if (segment.startsWith(".")) return false;
+ const lowered = segment.toLowerCase();
+ if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
+ if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
+ const labels = lowered.split(".");
+ const lastLabel = labels.at(-1);
+ if (labels.length < 2 || lastLabel === undefined) return false;
+ if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
+ return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
+}
+
+/** Recognizes conventional extensionless filenames with an explicit line position. */
+export function isConventionalFilePosition(path: string): boolean {
+ return (
+ BARE_EXTENSIONLESS_POSITION_PATTERN.test(path) &&
+ EXTENSIONLESS_FILE_NAMES.has(path.replace(POSITION_SUFFIX_PATTERN, ""))
+ );
+}
+
+/**
+ * Picks path-shaped inline code for the client's markdown file-link resolver.
+ * It does not resolve paths or turn plain prose and fenced code into links.
+ */
+export function inlineCodeFilePathCandidate(codeText: string): string | null {
+ const trimmed = codeText.trim();
+ if (trimmed.length === 0 || INLINE_CODE_DISQUALIFIER_PATTERN.test(trimmed)) return null;
+
+ const candidate =
+ WINDOWS_DRIVE_PATH_PATTERN.test(trimmed) || WINDOWS_UNC_PATH_PATTERN.test(trimmed)
+ ? trimmed
+ : trimmed.replaceAll("\\", "/");
+ const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
+ if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
+
+ const hasExplicitPathShape =
+ RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
+ candidate.startsWith("/") ||
+ WINDOWS_DRIVE_PATH_PATTERN.test(candidate) ||
+ WINDOWS_UNC_PATH_PATTERN.test(candidate);
+ if (!hasExplicitPathShape) {
+ const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
+ const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
+ if (looksLikeHostname(firstSegment, hasPosition)) return null;
+ const basename =
+ withoutPosition
+ .replace(/[/\\]+$/, "")
+ .split(/[\\/]/)
+ .at(-1) ?? "";
+ if (!hasPosition && !FILE_EXTENSION_PATTERN.test(basename)) return null;
+ }
+ return candidate;
+}
diff --git a/packages/client-runtime/src/mediaReference.test.ts b/packages/client-runtime/src/mediaReference.test.ts
new file mode 100644
index 00000000000..236953ad8b1
--- /dev/null
+++ b/packages/client-runtime/src/mediaReference.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { mediaFileReference, mediaReferenceFileName } from "./mediaReference.ts";
+
+describe("mediaFileReference", () => {
+ it.each([
+ ["/work/project/./media/../clip.mp4", "/work/project/", "clip.mp4"],
+ ["/work/project/../outside.mp4", "/work/project", undefined],
+ ["/work/project-other/clip.mp4", "/work/project", undefined],
+ ["/work/Project/clip.mp4", "/work/project", undefined],
+ ["/work/project/a\\b.mp4", "/work/project", "a\\b.mp4"],
+ ["/work/clip.mp4", "/work/other/..", "clip.mp4"],
+ ["/clip.mp4", "/", "clip.mp4"],
+ ["C:\\WORK\\project\\media\\..\\Clip.mp4", "c:/work/project/", "Clip.mp4"],
+ ["D:\\work\\clip.mp4", "C:\\work", undefined],
+ ["\\\\Server\\Share\\Project\\Clip.mp4", "//server/share/project", "Clip.mp4"],
+ ["\\\\server\\other\\clip.mp4", "\\\\server\\share", undefined],
+ ["../clip.mp4", "/work/project", undefined],
+ ])("preserves %s and only labels paths inside %s as relative", (path, root, relativePath) => {
+ expect(mediaFileReference(path, root)).toEqual({
+ kind: "file",
+ path,
+ ...(relativePath === undefined ? {} : { relativePath }),
+ });
+ });
+});
+
+describe("mediaReferenceFileName", () => {
+ it.each([
+ [{ kind: "file", path: "/tmp/take\\one%20.mp4" }, "take\\one%20.mp4"],
+ [{ kind: "file", path: "C:\\clips/take\\one.mp4" }, "one.mp4"],
+ [{ kind: "file", path: "\\\\server\\share\\one.mp4" }, "one.mp4"],
+ [{ kind: "url", url: "//cdn.example/clip%20one%2Emp4?sig=a+b#t=2" }, "clip one.mp4"],
+ [{ kind: "url", url: "https://cdn.example/clip%2520.mp4" }, "clip%20.mp4"],
+ [{ kind: "url", url: "https://cdn.example/clip%20%oops.mp4" }, "clip%20%oops.mp4"],
+ ] as const)("preserves filename semantics for %j", (reference, name) => {
+ expect(mediaReferenceFileName(reference)).toBe(name);
+ });
+});
diff --git a/packages/client-runtime/src/mediaReference.ts b/packages/client-runtime/src/mediaReference.ts
new file mode 100644
index 00000000000..dcb93e6bc57
--- /dev/null
+++ b/packages/client-runtime/src/mediaReference.ts
@@ -0,0 +1,95 @@
+import { isWindowsAbsolutePath } from "@t3tools/shared/path";
+
+/** The authored media location, never the temporary URL used to load its bytes. */
+export type MediaReference =
+ | {
+ readonly kind: "file";
+ readonly path: string;
+ readonly relativePath?: string;
+ }
+ | { readonly kind: "url"; readonly url: string };
+
+function absolutePathParts(path: string) {
+ const windows = isWindowsAbsolutePath(path) || path.startsWith("//");
+ const normalized = windows ? path.replaceAll("\\", "/") : path;
+ const prefix = windows
+ ? /^(?:[a-z]:\/|\/\/[^/]+\/[^/]+(?:\/|$))/i.exec(normalized)?.[0]
+ : normalized.startsWith("/")
+ ? "/"
+ : undefined;
+ if (!prefix) return undefined;
+
+ const segments: string[] = [];
+ for (const segment of normalized.slice(prefix.length).split("/")) {
+ if (!segment || segment === ".") continue;
+ if (segment === "..") segments.pop();
+ else segments.push(segment);
+ }
+ const root = prefix.replace(/\/$/, "");
+ return { root: windows ? root.toLowerCase() : root, segments, windows };
+}
+
+/** Compares paths lexically for the copy menu; it does not resolve filesystem symlinks. */
+export function mediaFileReference(
+ path: string,
+ workspaceRoot?: string | null,
+): Extract<MediaReference, { kind: "file" }> {
+ const target = absolutePathParts(path);
+ const workspace = workspaceRoot ? absolutePathParts(workspaceRoot) : undefined;
+ if (
+ !target ||
+ !workspace ||
+ target.windows !== workspace.windows ||
+ target.root !== workspace.root ||
+ target.segments.length <= workspace.segments.length ||
+ !workspace.segments.every((segment, index) =>
+ workspace.windows
+ ? segment.toLowerCase() === target.segments[index]?.toLowerCase()
+ : segment === target.segments[index],
+ )
+ ) {
+ return { kind: "file", path };
+ }
+ return {
+ kind: "file",
+ path,
+ relativePath: target.segments.slice(workspace.segments.length).join("/"),
+ };
+}
+
+/** Pass the authored source, not a generated URL used by the media player. */
+export function mediaUrlReference(
+ url: string,
+): Extract<MediaReference, { kind: "url" }> | undefined {
+ if (!/^(?:https?:\/\/|\/\/)/i.test(url)) return undefined;
+ try {
+ const parsed = new URL(url.startsWith("//") ? `https:${url}` : url);
+ return parsed.protocol === "http:" || parsed.protocol === "https:"
+ ? { kind: "url", url }
+ : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** Local paths are already decoded; URL filename escapes are decoded exactly once. */
+export function mediaReferenceFileName(reference: MediaReference): string | undefined {
+ if (reference.kind === "file") {
+ const windows = isWindowsAbsolutePath(reference.path) || reference.path.startsWith("//");
+ return reference.path.split(windows ? /[\\/]/ : "/").at(-1) || undefined;
+ }
+
+ let basename: string | undefined;
+ try {
+ const url = reference.url;
+ basename = new URL(url.startsWith("//") ? `https:${url}` : url).pathname.split("/").at(-1);
+ } catch {
+ return undefined;
+ }
+ if (!basename) return undefined;
+ try {
+ return decodeURIComponent(basename);
+ } catch {
+ return basename;
+ }
+}
diff --git a/packages/client-runtime/src/work-log/presentation.test.ts b/packages/client-runtime/src/work-log/presentation.test.ts
index 0289496c19b..b4abd4c4019 100644
--- a/packages/client-runtime/src/work-log/presentation.test.ts
+++ b/packages/client-runtime/src/work-log/presentation.test.ts
@@ -58,7 +58,7 @@ describe("resolveViewedImageAsset", () => {
}),
).toEqual({
resource: {
- _tag: "workspace-file",
+ _tag: "media-file",
threadId,
path: "/workspace/screens/logo.svg",
},
diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts
index 902745fdf95..2d5e6ebfc86 100644
--- a/packages/client-runtime/src/work-log/presentation.ts
+++ b/packages/client-runtime/src/work-log/presentation.ts
@@ -99,7 +99,7 @@ export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): strin
}
export interface ViewedImageAsset {
- readonly resource: Extract<AssetResource, { readonly _tag: "attachment" | "workspace-file" }>;
+ readonly resource: Extract<AssetResource, { readonly _tag: "attachment" | "media-file" }>;
readonly alt: string;
readonly srcFragment: string;
}
@@ -129,7 +129,7 @@ export function resolveViewedImageAsset(
return {
resource: attachmentId
? { _tag: "attachment", attachmentId }
- : { _tag: "workspace-file", threadId: input.threadId, path },
+ : { _tag: "media-file", threadId: input.threadId, path },
alt: path.split(/[\\/]/).at(-1) ?? "image",
srcFragment: markdownImageSourceFragment(source),
};
diff --git a/packages/contracts/src/assets.ts b/packages/contracts/src/assets.ts
index 1a2b50fc6e7..5a949fea38b 100644
--- a/packages/contracts/src/assets.ts
+++ b/packages/contracts/src/assets.ts
@@ -15,6 +15,10 @@ export const AssetResource = Schema.Union([
threadId: ThreadId,
path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
}),
+ Schema.TaggedStruct("media-file", {
+ threadId: ThreadId,
+ path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
+ }),
Schema.TaggedStruct("attachment", {
attachmentId: TrimmedNonEmptyString.check(Schema.isMaxLength(256)),
/** Display name and mime from the `ChatAttachment` the caller holds. The
@@ -152,7 +156,9 @@ export class AssetPreviewTypeValidationError extends Schema.TaggedErrorClass<Ass
},
) {
override get message(): string {
- return "Only browser documents and images can be previewed.";
+ return this.resource._tag === "media-file"
+ ? "Only images and videos can be previewed."
+ : "Only browser documents and images can be previewed.";
}
}
@@ -164,7 +170,9 @@ export class AssetWorkspaceAssetInspectionError extends Schema.TaggedErrorClass<
},
) {
override get message(): string {
- return "Failed to inspect the workspace asset.";
+ return this.resource._tag === "media-file"
+ ? "Failed to inspect the media file."
+ : "Failed to inspect the workspace asset.";
}
}
@@ -175,7 +183,9 @@ export class AssetWorkspaceAssetNotFoundError extends Schema.TaggedErrorClass<As
},
) {
override get message(): string {
- return "Workspace asset was not found.";
+ return this.resource._tag === "media-file"
+ ? "Media file was not found."
+ : "Workspace asset was not found.";
}
}
diff --git a/packages/shared/src/filePreview.test.ts b/packages/shared/src/filePreview.test.ts
index eb8b7d1e892..4aa466159af 100644
--- a/packages/shared/src/filePreview.test.ts
+++ b/packages/shared/src/filePreview.test.ts
@@ -4,6 +4,8 @@ import {
isWorkspaceBrowserPreviewPath,
isWorkspaceImagePreviewPath,
isWorkspacePreviewEntryPath,
+ isWorkspaceVideoPreviewPath,
+ mediaKindFromPath,
} from "./filePreview.ts";
describe("workspace file previews", () => {
@@ -34,3 +36,28 @@ describe("workspace file previews", () => {
},
);
});
+
+describe("media path parsing", () => {
+ it.each([
+ ["https://cdn.example/clip.webm?download=1#t=2", "video"],
+ ["https://example.com/download?name=recording.mp4", null],
+ ["https://example.png", null],
+ ["images%2Fresult%2Epng", "image"],
+ ["images/result%23v2.png", "image"],
+ ["images/result.png%23secret.txt", null],
+ ["images/result.png%3Fsecret.txt", null],
+ ["/tmp/100%.png", "image"],
+ ])("classifies the decoded pathname of %s", (source, kind) => {
+ expect(mediaKindFromPath(source)).toBe(kind);
+ });
+
+ it.each([
+ ["recording.mp4#t=2", "video", false],
+ ["recording%2Emp4", "video", false],
+ ["recording#take2.mp4", null, true],
+ ["recording?take2.mp4", null, true],
+ ])("distinguishes authored URLs from literal filenames in %s", (source, kind, literalVideo) => {
+ expect(mediaKindFromPath(source)).toBe(kind);
+ expect(isWorkspaceVideoPreviewPath(source)).toBe(literalVideo);
+ });
+});
diff --git a/packages/shared/src/filePreview.ts b/packages/shared/src/filePreview.ts
index c9d15e14c3b..1d1e41c2865 100644
--- a/packages/shared/src/filePreview.ts
+++ b/packages/shared/src/filePreview.ts
@@ -1,3 +1,5 @@
+import { videoMimeType } from "./video.ts";
+
export const WORKSPACE_BROWSER_PREVIEW_EXTENSIONS = [".htm", ".html", ".pdf"] as const;
export const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [
@@ -11,6 +13,57 @@ export const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [
".webp",
] as const;
+const IMAGE_MIME_TYPE_BY_EXTENSION = new Map([
+ [".avif", "image/avif"],
+ [".gif", "image/gif"],
+ [".ico", "image/x-icon"],
+ [".jpeg", "image/jpeg"],
+ [".jpg", "image/jpeg"],
+ [".png", "image/png"],
+ [".svg", "image/svg+xml"],
+ [".webp", "image/webp"],
+]);
+
+/** Classifies a literal filesystem extension, without URL decoding or suffix removal. */
+export function mediaMimeTypeFromExtension(extension: string): string | null {
+ if (!/^\.[a-z0-9]+$/i.test(extension)) return null;
+ return (
+ IMAGE_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??
+ videoMimeType({ name: `media${extension}`, mimeType: "" })
+ );
+}
+
+/** Classifies an authored media path or URL. Filesystem validation uses the literal extension. */
+export function mediaMimeType(path: string): string | null {
+ const trimmed = path.trim();
+ const source = trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
+ const dataMimeType = /^data:((?:image|video)\/[\w.+-]+)[;,]/i.exec(source)?.[1];
+ if (dataMimeType) return dataMimeType.toLowerCase();
+
+ let sourcePath = source.split(/[?#]/, 1)[0] ?? "";
+ if (/^(?:https?:|file:|\/\/)/i.test(source)) {
+ try {
+ sourcePath = new URL(source, "https://media.invalid").pathname;
+ } catch {
+ return null;
+ }
+ }
+ try {
+ sourcePath = decodeURIComponent(sourcePath);
+ } catch {
+ // A literal percent character is valid in a filename.
+ }
+ const basename = sourcePath.split(/[\\/]/).at(-1) ?? "";
+ const extensionIndex = basename.lastIndexOf(".");
+ return extensionIndex < 0 ? null : mediaMimeTypeFromExtension(basename.slice(extensionIndex));
+}
+
+export function mediaKindFromPath(path: string): "image" | "video" | null {
+ const mimeType = mediaMimeType(path);
+ if (mimeType === null) return null;
+ return mimeType.startsWith("video/") ? "video" : "image";
+}
+
function hasPreviewExtension(path: string, extensions: ReadonlyArray<string>): boolean {
const pathWithoutQuery = path.split(/[?#]/, 1)[0]?.toLowerCase() ?? "";
return extensions.some((extension) => pathWithoutQuery.endsWith(extension));
@@ -24,6 +77,11 @@ export function isWorkspaceImagePreviewPath(path: string): boolean {
return hasPreviewExtension(path, WORKSPACE_IMAGE_PREVIEW_EXTENSIONS);
}
+/** File viewers receive literal filesystem paths, not Markdown URLs. */
+export function isWorkspaceVideoPreviewPath(path: string): boolean {
+ return videoMimeType({ name: path, mimeType: "" }) !== null;
+}
+
export function isWorkspacePreviewEntryPath(path: string): boolean {
return isWorkspaceBrowserPreviewPath(path) || isWorkspaceImagePreviewPath(path);
}
diff --git a/packages/shared/src/video.ts b/packages/shared/src/video.ts
index 634bc29ed6d..291674c705c 100644
--- a/packages/shared/src/video.ts
+++ b/packages/shared/src/video.ts
@@ -8,6 +8,8 @@ const VIDEO_MIME_TYPE_BY_EXTENSION = new Map([
["webm", "video/webm"],
]);
+export const VIDEO_FILE_EXTENSIONS = Object.freeze([...VIDEO_MIME_TYPE_BY_EXTENSION.keys()]);
+
/** Recognizes videos even when the file picker omitted their MIME type. */
export function videoMimeType(attachment: {
readonly name: string;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 262203a1000..02fa8871059 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -273,7 +273,7 @@ importers:
version: link:../../packages/contracts
'@t3tools/mobile-markdown-text':
specifier: file:./modules/t3-markdown-text
- version: file:apps/mobile/modules/t3-markdown-text(8819e1ff552fc19b333a2dfaf02d39db)
+ version: file:apps/mobile/modules/t3-markdown-text(cd0d4cdec0d5bee3af406af520908919)
'@t3tools/mobile-review-diff-native':
specifier: file:./modules/t3-review-diff
version: file:apps/mobile/modules/t3-review-diff
@@ -4433,6 +4433,8 @@ packages:
'@t3tools/mobile-markdown-text@file:apps/mobile/modules/t3-markdown-text':
resolution: {directory: apps/mobile/modules/t3-markdown-text, type: directory}
peerDependencies:
+ '@t3tools/client-runtime': '*'
+ '@t3tools/shared': '*'
expo-asset: '*'
expo-clipboard: '*'
expo-haptics: '*'
@@ -14253,8 +14255,10 @@ snapshots:
dependencies:
defer-to-connect: 2.0.1
- '@t3tools/mobile-markdown-text@file:apps/mobile/modules/t3-markdown-text(8819e1ff552fc19b333a2dfaf02d39db)':
+ '@t3tools/mobile-markdown-text@file:apps/mobile/modules/t3-markdown-text(cd0d4cdec0d5bee3af406af520908919)':
dependencies:
+ '@t3tools/client-runtime': link:packages/client-runtime
+ '@t3tools/shared': link:packages/shared
expo-haptics: 57.0.2([email protected])