Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: open Images and Video previews in the Library viewer (#11776)

Michael Hanc089e04e1e43
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index 8dfc2fb19dc..aeb9288b717 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -528,11 +528,14 @@ export async function clearGallery(): Promise<void> {
if (!res.ok) throw new Error(await readFastApiError(res));
}
-/** Fetch an auth-protected gallery image as its original blob. */
-export async function fetchGalleryBlob(url: string): Promise<Blob> {
+export async function fetchGalleryResponse(url: string): Promise<Response> {
const res = await authFetch(url);
if (!res.ok) throw new Error(await readFastApiError(res));
- return res.blob();
+ return res;
+}
+
+export async function fetchGalleryBlob(url: string): Promise<Blob> {
+ return (await fetchGalleryResponse(url)).blob();
}
/** Fetch a gallery PNG (auth-protected, so it cannot be a plain <img src>) and wrap it in an object
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 6d414a6d44b..ea8532889ec 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -12,6 +12,7 @@ import {
useState,
} from "react";
import {
+ ArrowExpand01Icon,
ArrowLeftRightIcon,
ArrowUpDownIcon,
ArrowReloadHorizontalIcon,
@@ -23,7 +24,9 @@ import {
SparklesIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";
-import { TestTubeOutlineIcon } from "@/lib/hugeicons-derived";
+import { MessageCircleIcon, TestTubeOutlineIcon } from "@/lib/hugeicons-derived";
+import { MediaViewer } from "@/components/media-viewer";
+import { shortPrompt } from "@/lib/prompt-text";
import { ImageDropzone } from "@/components/image-dropzone";
import { GuidedTour, useGuidedTourController } from "@/features/tour";
@@ -87,8 +90,13 @@ import { MEDIA_RAIL_ROOT_ATTR, useMediaRailWidth } from "@/hooks/use-media-rail-
import { StripDropLine } from "@/components/gallery-strip-reorder";
import { useStripReorder } from "@/hooks/use-strip-reorder";
import { LibraryPageLink } from "@/components/media-page-link";
-import { translate } from "@/i18n";
-import { useLibraryFavorites } from "@/features/library";
+import { translate, useT } from "@/i18n";
+import {
+ chatAboutMedia,
+ revealInFolder,
+ useLibraryFavorites,
+ useRevealLabel,
+} from "@/features/library";
import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";
import {
type NewRecordProbeBaseline,
@@ -202,6 +210,7 @@ import {
cancelDiffusionGeneration,
deleteGalleryImage,
fetchGalleryBlob,
+ fetchGalleryResponse,
fetchGalleryObjectUrl,
generateDiffusionImage,
getDiffusionLoadProgress,
@@ -1247,6 +1256,11 @@ type LoadAdvanced = Pick<
| "gpu_ids"
>;
+function openImageLabel(t: ReturnType<typeof useT>, prompt: string): string {
+ const text = shortPrompt(prompt);
+ return text ? t("library.viewer.openImageNamed", { prompt: text }) : t("library.viewer.openImage");
+}
+
export function ImagesPage({
active = true,
onInitialReady,
@@ -1254,6 +1268,7 @@ export function ImagesPage({
active?: boolean;
onInitialReady?: () => void;
}) {
+ const t = useT();
const initialReadySent = useRef(false);
const [rememberedModel, setRememberedModel] = useState(readImageModel);
const pendingRecalledGeneration = useRef<{ model: RememberedImageModel; load: number; workflow: WorkflowId; allowOversized?: boolean } | null>(null);
@@ -1773,6 +1788,18 @@ export function ImagesPage({
[images, selectedId],
);
const selectedSrc = selected ? srcById[selected.id] : undefined;
+ const [viewerId, setViewerId] = useState<string | null>(null);
+ const viewerImage = viewerId ? (images.find((image) => image.id === viewerId) ?? null) : null;
+ const viewerSrc = viewerImage ? srcById[viewerImage.id] : undefined;
+ if (viewerId && (!active || !viewerImage)) setViewerId(null);
+ // Pruning below must not revoke the image on screen.
+ const viewerIdRef = useRef<string | null>(null);
+ useEffect(() => {
+ viewerIdRef.current = viewerId;
+ }, [viewerId]);
+ const openViewer = () => selected && selectedSrc && setViewerId(selected.id);
+ const navigateToChat = useNavigate();
+ const revealLabel = useRevealLabel();
// Fetch (once) the object URL for a record's PNG; cached across remounts.
const ensureSrc = useCallback(async (image: GalleryImage) => {
@@ -1787,7 +1814,12 @@ export function ImagesPage({
galleryCache.srcById.set(image.id, url, bytes);
// Evict the coldest off-screen images this one pushed over budget; on-screen and open tiles are protected.
const evicted = galleryCache.srcById.prune(
- new Set([image.id, ...visibleIds.current, galleryCache.selectedId ?? ""]),
+ new Set([
+ image.id,
+ ...visibleIds.current,
+ galleryCache.selectedId ?? "",
+ viewerIdRef.current ?? "",
+ ]),
);
setSrcById((prev) => {
const next = { ...prev, [image.id]: url };
@@ -5315,6 +5347,43 @@ export function ImagesPage({
data-tour="images-preview"
className="relative flex min-h-[60dvh] min-w-0 flex-1 flex-col overflow-hidden @[50rem]:min-h-0"
>
+ {viewerImage && viewerSrc && (
+ <MediaViewer
+ open={true}
+ onOpenChange={(open) => !open && setViewerId(null)}
+ title={viewerImage.prompt || t("library.viewer.untitledImage")}
+ meta={`Generated · ${viewerImage.width} × ${viewerImage.height}`}
+ media={true}
+ noun="image"
+ actions={{
+ primary: {
+ label: t("library.menu.chatAboutThis"),
+ icon: MessageCircleIcon,
+ onClick: () =>
+ void chatAboutMedia(
+ navigateToChat,
+ // The authenticated original: WebKit shows the object URL but cannot refetch it.
+ () => fetchGalleryResponse(viewerImage.url),
+ viewerImage.prompt,
+ "image",
+ ),
+ },
+ onDownload: () => void handleQuickDownload(viewerImage),
+ reveal: revealLabel
+ ? { label: revealLabel, onClick: () => revealInFolder(`image:${viewerImage.id}`) }
+ : undefined,
+ favorite: isFavorite(`image:${viewerImage.id}`),
+ onToggleFavorite: () => toggleFavorite(`image:${viewerImage.id}`),
+ onAddToProject: (projectId) => addGalleryImageToProject(viewerImage.id, projectId),
+ onDelete: () => {
+ setViewerId(null);
+ void handleDelete(viewerImage.id);
+ },
+ }}
+ >
+ <img src={viewerSrc} alt={viewerImage.prompt} className="size-full object-contain" />
+ </MediaViewer>
+ )}
<div className="hover-scrollbar relative flex flex-1 items-center justify-center overflow-auto p-6 px-10 @[50rem]:pt-[calc(60px*var(--ui-space-scale,1))]">
{selected && selectedSrc ? (
<>
@@ -5322,12 +5391,35 @@ export function ImagesPage({
src={selectedSrc}
alt={selected.prompt}
style={TRANSPARENCY_CHECKER}
- className="max-h-full max-w-full object-contain shadow-sm"
+ role="button"
+ tabIndex={0}
+ aria-label={openImageLabel(t, selected.prompt)}
+ onClick={openViewer}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ openViewer();
+ }
+ }}
+ className="max-h-full max-w-full cursor-zoom-in object-contain shadow-sm"
/>
{/* Actions grouped in one glass toolbar so they stay legible over any image. Size and seed
live in the Recipe popover. */}
{/* No button borders: focus returning from a menu would draw one. Keyboard focus tints instead. */}
<div className="absolute bottom-4 right-4 flex items-center gap-0.5 rounded-xl bg-background/80 p-1 shadow-lg ring-1 ring-border backdrop-blur [&_[data-slot=button]]:border-0 [&_[data-slot=button]:focus-visible]:bg-muted">
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ aria-label={t("library.viewer.openImage")}
+ title={t("library.viewer.openImage")}
+ onClick={(event) => {
+ // Safari does not focus a clicked button, and the viewer returns focus to what had it.
+ event.currentTarget.focus();
+ openViewer();
+ }}
+ >
+ <HugeiconsIcon icon={ArrowExpand01Icon} className="size-4" />
+ </Button>
<RecipePopover image={selected} onRestore={restoreSettings} active={active} />
<DropdownMenu>
<DropdownMenuTrigger asChild={true}>
diff --git a/studio/frontend/src/features/library/actions.ts b/studio/frontend/src/features/library/actions.ts
index 64750621083..dfb56eea571 100644
--- a/studio/frontend/src/features/library/actions.ts
+++ b/studio/frontend/src/features/library/actions.ts
@@ -4,7 +4,7 @@
import type { useNavigate } from "@tanstack/react-router";
import { zipSync } from "fflate";
import { getAuthSessionEpoch } from "@/features/auth";
-import { clearNewChatDraft, listLoras, useChatRuntimeStore } from "@/features/chat";
+import { listLoras } from "@/features/chat";
import {
clearModelConfigHandoff,
createModelConfigHandoffRequestId,
@@ -25,16 +25,12 @@ import {
} from "./api";
import { fileKind } from "./file-kind";
import { hasOwnFile, libraryFileName, uniqueFileNames } from "./file-name";
-import {
- type LibraryChatHandoff,
- useLibraryChatHandoffStore,
-} from "./chat-handoff-store";
+import { MAX_IMAGE_OR_TEXT_BYTES, resetToNewChat, startLibraryChat } from "./start-chat";
type Navigate = ReturnType<typeof useNavigate>;
export const MAX_CHAT_FILES = 10;
-const MAX_IMAGE_OR_TEXT_BYTES = 20 * 1024 * 1024;
const MAX_DOCUMENT_BYTES = 50 * 1024 * 1024;
function chatSizeLimit(item: LibraryItem): number {
@@ -128,24 +124,6 @@ export async function downloadLibraryItems(items: LibraryItem[]): Promise<void>
}
}
-function resetToNewChat(): void {
- clearNewChatDraft();
- const runtime = useChatRuntimeStore.getState();
- runtime.setActiveThreadId(null);
- runtime.setActiveProjectId(null);
- runtime.setIncognito(false);
-}
-
-function startLibraryChat(
- navigate: Navigate,
- handoff: LibraryChatHandoff,
-): void {
- const nonce = createModelConfigHandoffRequestId();
- resetToNewChat();
- useLibraryChatHandoffStore.getState().offer(`single:${nonce}`, handoff);
- void navigate({ to: "/chat", search: { new: nonce } });
-}
-
export async function chatAboutItems(
navigate: Navigate,
items: LibraryItem[],
diff --git a/studio/frontend/src/features/library/index.ts b/studio/frontend/src/features/library/index.ts
index 2b6c871b4ed..e12d63d6fd9 100644
--- a/studio/frontend/src/features/library/index.ts
+++ b/studio/frontend/src/features/library/index.ts
@@ -3,6 +3,8 @@
export { useLibraryChatHandoffStore } from "./chat-handoff-store";
export { useLibraryFavorites } from "./favorites-store";
+export { chatAboutMedia } from "./start-chat";
+export { revealInFolder, useRevealLabel } from "./reveal";
export { LIBRARY_TABS, validateLibrarySearch, type LibrarySearch, type LibraryTab } from "./search";
export {
LIBRARY_SETTINGS_STORAGE_KEY,
@@ -25,4 +27,3 @@ export {
moveLibraryLocation,
revealLibraryLocation,
} from "./api";
-export { useRevealLabel } from "./reveal";
diff --git a/studio/frontend/src/features/library/start-chat.ts b/studio/frontend/src/features/library/start-chat.ts
new file mode 100644
index 00000000000..8414e58b214
--- /dev/null
+++ b/studio/frontend/src/features/library/start-chat.ts
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { useNavigate } from "@tanstack/react-router";
+import { getAuthSessionEpoch } from "@/features/auth";
+// eslint-disable-next-line no-restricted-imports -- the chat barrel imports the Library back
+import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
+// eslint-disable-next-line no-restricted-imports -- the chat barrel imports the Library back
+import { clearNewChatDraft } from "@/features/chat/utils/composer-draft";
+import { createModelConfigHandoffRequestId } from "@/features/model-picker";
+import { translate } from "@/i18n";
+import { toast } from "@/lib/toast";
+import { MAX_VIDEO_SIZE } from "@/lib/video-utils";
+import {
+ type LibraryChatHandoff,
+ useLibraryChatHandoffStore,
+} from "./chat-handoff-store";
+import { mediaFileName } from "@/lib/prompt-text";
+
+type Navigate = ReturnType<typeof useNavigate>;
+
+export function resetToNewChat(): void {
+ clearNewChatDraft();
+ const runtime = useChatRuntimeStore.getState();
+ runtime.setActiveThreadId(null);
+ runtime.setActiveProjectId(null);
+ runtime.setIncognito(false);
+}
+
+export function startLibraryChat(
+ navigate: Navigate,
+ handoff: LibraryChatHandoff,
+): void {
+ const nonce = createModelConfigHandoffRequestId();
+ resetToNewChat();
+ useLibraryChatHandoffStore.getState().offer(`single:${nonce}`, handoff);
+ void navigate({ to: "/chat", search: { new: nonce } });
+}
+
+export const MAX_IMAGE_OR_TEXT_BYTES = 20 * 1024 * 1024;
+
+const MEDIA = {
+ image: {
+ bytes: MAX_IMAGE_OR_TEXT_BYTES,
+ extension: "png",
+ type: "image/png",
+ tooLarge: "library.toast.imageTooLarge",
+ attaching: "library.toast.attachingImage",
+ readFailed: "library.toast.readImageFailed",
+ },
+ video: {
+ bytes: MAX_VIDEO_SIZE,
+ extension: "mp4",
+ type: "video/mp4",
+ tooLarge: "library.toast.videoTooLarge",
+ attaching: "library.toast.attachingVideo",
+ readFailed: "library.toast.readVideoFailed",
+ },
+} as const;
+
+const LOADING_TOAST_DELAY_MS = 400;
+
+// One hand-off at a time: a second click while a large clip downloads would open a second chat.
+let handoffInFlight = false;
+
+export async function chatAboutMedia(
+ navigate: Navigate,
+ load: () => Promise<Response>,
+ prompt: string,
+ kind: keyof typeof MEDIA,
+): Promise<void> {
+ if (handoffInFlight) return;
+ handoffInFlight = true;
+ const media = MEDIA[kind];
+ const tooLarge = () =>
+ toast.error(translate(media.tooLarge), {
+ description: translate("library.toast.attachmentLimit", {
+ size: Math.round(media.bytes / (1024 * 1024)),
+ }),
+ });
+ let loadingToast: string | number | null = null;
+ const loadingTimer = setTimeout(() => {
+ loadingToast = toast.loading(translate(media.attaching));
+ }, LOADING_TOAST_DELAY_MS);
+ // A sign-out while the file downloads would hand it to the next account's chat.
+ const epoch = getAuthSessionEpoch();
+ // The media pages stay mounted off-route: a user who moved on must not be pulled into a new chat.
+ const startedAt = typeof window === "undefined" ? "" : window.location.pathname;
+ try {
+ const response = await load();
+ if (!response.ok) throw new Error(translate(media.readFailed, { status: response.status }));
+ // Before reading the body, so an oversized file is never buffered.
+ if (Number(response.headers.get("content-length")) > media.bytes) {
+ void response.body?.cancel();
+ tooLarge();
+ return;
+ }
+ const blob = await response.blob();
+ if (getAuthSessionEpoch() !== epoch) return;
+ if (typeof window !== "undefined" && window.location.pathname !== startedAt) return;
+ if (blob.size > media.bytes) {
+ tooLarge();
+ return;
+ }
+ const type = blob.type.startsWith(`${kind}/`) ? blob.type : media.type;
+ startLibraryChat(navigate, {
+ files: [new File([blob], mediaFileName(prompt, media.extension), { type })],
+ });
+ } catch (error) {
+ toast.error(translate("library.toast.openFileFailed"), {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ clearTimeout(loadingTimer);
+ if (loadingToast !== null) toast.dismiss(loadingToast);
+ handoffInFlight = false;
+ }
+}
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index a7ca4e49337..b2e5b34cb2a 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -3,6 +3,7 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
+ ArrowExpand01Icon,
Cancel01Icon,
Delete02Icon,
Download01Icon,
@@ -16,13 +17,20 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { AdvancedDisclosure } from "@/components/advanced-disclosure";
import { GalleryItemMenu, GalleryPinBadge } from "@/components/gallery-item-menu";
import { MediaRailResizeHandle } from "@/components/media-rail-resize-handle";
+import { MediaViewer } from "@/components/media-viewer";
+import { MessageCircleIcon } from "@/lib/hugeicons-derived";
import { MEDIA_RAIL_ROOT_ATTR, useMediaRailWidth } from "@/hooks/use-media-rail-width";
import { StripDropLine } from "@/components/gallery-strip-reorder";
import { useStripReorder } from "@/hooks/use-strip-reorder";
import { ImageDropzone } from "@/components/image-dropzone";
import { LibraryPageLink } from "@/components/media-page-link";
-import { translate } from "@/i18n";
-import { useLibraryFavorites } from "@/features/library";
+import { translate, useT } from "@/i18n";
+import {
+ chatAboutMedia,
+ revealInFolder,
+ useLibraryFavorites,
+ useRevealLabel,
+} from "@/features/library";
import { GuidedTour, useGuidedTourController } from "@/features/tour";
import { videoTourSteps } from "./tour";
import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";
@@ -199,6 +207,7 @@ import {
loadVideoModel,
unloadVideoModel,
} from "./api";
+import { type Playback, fetchWithFreshLink, playWithMutedFallback, readPlayback } from "./viewer";
import { videoThumbnailQueue, withThumbnailRetries } from "./thumbnail-request-queue";
/** Placeholder hint until the prompt box is first focused. */
@@ -299,6 +308,8 @@ const VIDEO_LINK_REFRESH_MS = 6 * 60 * 60 * 1000;
// Videos loaded per infinite-scroll page.
const PAGE_SIZE = 50;
+const INLINE_PLAYBACK: Playback = { time: 0, playing: false, muted: true, volume: 1 };
+
// Passes a window resync may make before giving up: each extra pass only happens when
// pagination moved while it was fetching.
const RESYNC_MAX_ATTEMPTS = 3;
@@ -913,6 +924,7 @@ function VideoGenerator({
active?: boolean;
onInitialReady?: () => void;
}) {
+ const t = useT();
const initialReadySent = useRef(false);
// Clear the floating sidebar toggle on mobile.
const isMobileShell = useIsMobileShell();
@@ -1160,6 +1172,48 @@ function VideoGenerator({
[videos, selectedId],
);
const selectedSrc = selected ? srcById[selected.id] : undefined;
+ const [viewer, setViewer] = useState<{ id: string; from: Playback } | null>(null);
+ const viewerVideoRef = useRef<HTMLVideoElement | null>(null);
+ const viewerPositioned = useRef(false);
+ const handback = useRef<{ id: string; playback: Playback } | null>(null);
+ const navigateToChat = useNavigate();
+ const revealLabel = useRevealLabel();
+ const viewerVideo = viewer ? (videos.find((video) => video.id === viewer.id) ?? null) : null;
+ const viewerSrc = viewerVideo ? srcById[viewerVideo.id] : undefined;
+ if (viewer && (!active || !viewerVideo)) setViewer(null);
+ const openViewer = () => {
+ if (!selected || !selectedSrc) return;
+ const inline = previewRef.current;
+ viewerPositioned.current = false;
+ handback.current = null;
+ setViewer({ id: selected.id, from: readPlayback(inline, INLINE_PLAYBACK) });
+ inline?.pause();
+ };
+ const recordViewer = (video: HTMLVideoElement) => {
+ if (!viewer || video !== viewerVideoRef.current) return;
+ handback.current = {
+ id: viewer.id,
+ playback: readPlayback(video, viewer.from, viewerPositioned.current),
+ };
+ };
+ const closeViewer = () => {
+ if (viewerVideoRef.current) recordViewer(viewerVideoRef.current);
+ setViewer(null);
+ };
+ const shownId = selected?.id;
+ useEffect(() => {
+ const last = handback.current;
+ if (viewer || !last || last.id !== shownId) return;
+ const inline = previewRef.current;
+ if (!selectedSrc || !inline) return;
+ handback.current = null;
+ const { playback } = last;
+ inline.currentTime = playback.time;
+ inline.muted = playback.muted;
+ inline.volume = playback.volume;
+ if (playback.playing && activeRef.current) void playWithMutedFallback(inline);
+ else inline.pause();
+ }, [viewer, shownId, selectedSrc]);
// The resolution presets + temporal lattice for the loaded family, or the fallbacks before anything is loaded.
const resolutionPresets = useMemo<Array<[number, number]>>(() => {
@@ -4245,6 +4299,66 @@ function VideoGenerator({
data-tour="video-preview"
className="relative flex min-h-[60dvh] min-w-0 flex-1 flex-col overflow-hidden pl-2 lg:min-h-0"
>
+ {viewer && viewerVideo && viewerSrc && (
+ <MediaViewer
+ open={true}
+ onOpenChange={(open) => !open && closeViewer()}
+ title={viewerVideo.prompt || t("library.viewer.untitledVideo")}
+ meta={`Generated · ${viewerVideo.width} × ${viewerVideo.height} · ${Math.round(viewerVideo.duration_s)}s`}
+ media={true}
+ noun="video"
+ actions={{
+ primary: {
+ label: t("library.menu.chatAboutThis"),
+ icon: MessageCircleIcon,
+ onClick: () =>
+ void chatAboutMedia(
+ navigateToChat,
+ () => fetchWithFreshLink(viewerSrc, () => fetchGalleryVideoSignedUrl(viewerVideo.id)),
+ viewerVideo.prompt,
+ "video",
+ ),
+ },
+ onDownload: () => void handleQuickDownload(viewerVideo),
+ reveal: revealLabel
+ ? { label: revealLabel, onClick: () => revealInFolder(`video:${viewerVideo.id}`) }
+ : undefined,
+ favorite: isFavorite(`video:${viewerVideo.id}`),
+ onToggleFavorite: () => toggleFavorite(`video:${viewerVideo.id}`),
+ onAddToProject: (projectId) => addGalleryVideoToProject(viewerVideo.id, projectId),
+ onDelete: () => {
+ viewerVideoRef.current?.pause();
+ handback.current = null;
+ setViewer(null);
+ void handleDelete(viewerVideo.id);
+ },
+ }}
+ >
+ <video
+ ref={viewerVideoRef}
+ src={viewerSrc}
+ controls
+ playsInline
+ muted={viewer.from.muted}
+ onLoadedMetadata={(event) => {
+ const video = event.currentTarget;
+ if (viewer.from.time) video.currentTime = viewer.from.time;
+ video.volume = viewer.from.volume;
+ viewerPositioned.current = true;
+ if (viewer.from.playing) void playWithMutedFallback(video);
+ }}
+ onTimeUpdate={(event) => recordViewer(event.currentTarget)}
+ onVolumeChange={(event) => recordViewer(event.currentTarget)}
+ onError={(event) => {
+ const from = readPlayback(event.currentTarget, viewer.from, viewerPositioned.current);
+ viewerPositioned.current = false;
+ setViewer((current) => current && { ...current, from });
+ remintSrc(viewerVideo);
+ }}
+ className="size-full object-contain"
+ />
+ </MediaViewer>
+ )}
<div className="hover-scrollbar relative flex flex-1 items-center justify-center overflow-auto p-6">
{selected && selectedSrc ? (
<>
@@ -4255,7 +4369,8 @@ function VideoGenerator({
ref={previewRef}
src={selectedSrc}
controls
- autoPlay
+ // A clip finishing behind the open viewer is selected, but must not play under it.
+ autoPlay={viewer === null}
muted
playsInline
onPlay={() => {
@@ -4280,6 +4395,21 @@ function VideoGenerator({
{/* Actions grouped in one glass toolbar so they stay legible over any clip. */}
{/* No button borders: focus returning from a menu would draw one. Keyboard focus tints instead. */}
<div className="absolute bottom-4 right-4 flex items-center gap-0.5 rounded-xl bg-background/80 p-1 shadow-lg ring-1 ring-border backdrop-blur [&_[data-slot=button]]:border-0 [&_[data-slot=button]:focus-visible]:bg-muted">
+ {/* Not a click on the clip itself: Chrome's ⋮ menu, WebKit's centred play button and the
+ first click of a double-click to fullscreen all land on the frame, above the controls. */}
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ aria-label={t("library.viewer.openVideo")}
+ title={t("library.viewer.openVideo")}
+ onClick={(event) => {
+ // Safari does not focus a clicked button, and the viewer returns focus to what had it.
+ event.currentTarget.focus();
+ openViewer();
+ }}
+ >
+ <HugeiconsIcon icon={ArrowExpand01Icon} className="size-4" />
+ </Button>
<RecipePopover video={selected} onRestore={restoreSettings} active={active} />
<DropdownMenu>
<DropdownMenuTrigger asChild={true}>
diff --git a/studio/frontend/src/features/video/viewer.ts b/studio/frontend/src/features/video/viewer.ts
new file mode 100644
index 00000000000..9f70b0a9abc
--- /dev/null
+++ b/studio/frontend/src/features/video/viewer.ts
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+
+export type Playback = { time: number; playing: boolean; muted: boolean; volume: number };
+
+type PlayerState = Pick<
+ HTMLMediaElement,
+ "currentTime" | "paused" | "ended" | "muted" | "volume" | "readyState"
+>;
+
+// HTMLMediaElement.HAVE_METADATA, spelled out so this also runs where there is no DOM.
+const HAVE_METADATA = 1;
+
+export function readPlayback(
+ video: PlayerState | null,
+ fallback: Playback,
+ positioned = video !== null && video.readyState >= HAVE_METADATA,
+): Playback {
+ if (!video) return fallback;
+ if (!positioned) return { ...fallback, muted: video.muted };
+ return {
+ time: video.currentTime,
+ playing: !video.paused && !video.ended,
+ muted: video.muted,
+ volume: video.volume,
+ };
+}
+
+export function playWithMutedFallback(video: Pick<HTMLMediaElement, "play" | "muted">): Promise<void> {
+ return video.play().catch((error: unknown) => {
+ // An AbortError is a newer load or pause taking over, not a refusal.
+ if (video.muted || (error as { name?: unknown } | null)?.name !== "NotAllowedError") return;
+ video.muted = true;
+ return video.play().catch(() => undefined);
+ });
+}
+
+export async function fetchWithFreshLink(url: string, mint: () => Promise<string>): Promise<Response> {
+ const response = await fetch(url);
+ if (response.status !== 401 && response.status !== 403) return response;
+ void response.body?.cancel();
+ return fetch(await mint());
+}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 7736979853c..424b8aed6b5 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -3107,6 +3107,11 @@ export const ar = {
moreActionsVideo: "إجراءات أخرى لهذا الفيديو",
moreActionsClip: "إجراءات أخرى لهذا المقطع",
moreActionsFile: "إجراءات أخرى لهذا الملف",
+ openImage: "فتح الصورة",
+ openImageNamed: "فتح الصورة: {prompt}",
+ openVideo: "فتح الفيديو",
+ untitledImage: "صورة بلا عنوان",
+ untitledVideo: "فيديو بلا عنوان",
},
project: {
label: "المشروع",
@@ -3172,6 +3177,14 @@ export const ar = {
imageNotFound: "تعذّر العثور على هذه الصورة",
clipNotFound: "تعذّر العثور على هذا المقطع",
notFoundDescription: "ربما تمت أرشفته أو حذفه.",
+ imageTooLarge: "هذه الصورة أكبر من أن تُرفق",
+ videoTooLarge: "هذا الفيديو أكبر من أن يُرفق",
+ attachmentLimit: "الحد الأقصى لمرفقات المحادثة {size} ميغابايت.",
+ attachingImage: "جارٍ إرفاق الصورة…",
+ attachingVideo: "جارٍ إرفاق الفيديو…",
+ readImageFailed: "تعذّرت قراءة الصورة ({status}).",
+ readVideoFailed: "تعذّرت قراءة الفيديو ({status}).",
+ openFileFailed: "تعذّر فتح الملف",
},
},
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index f88f15d86b2..a9afaf3e92c 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -3176,6 +3176,11 @@ export const de = {
moreActionsVideo: "Weitere Aktionen für dieses Video",
moreActionsClip: "Weitere Aktionen für diesen Clip",
moreActionsFile: "Weitere Aktionen für diese Datei",
+ openImage: "Bild öffnen",
+ openImageNamed: "Bild öffnen: {prompt}",
+ openVideo: "Video öffnen",
+ untitledImage: "Unbenanntes Bild",
+ untitledVideo: "Unbenanntes Video",
},
project: {
label: "Projekt",
@@ -3241,6 +3246,14 @@ export const de = {
imageNotFound: "Dieses Bild wurde nicht gefunden",
clipNotFound: "Dieser Clip wurde nicht gefunden",
notFoundDescription: "Möglicherweise archiviert oder gelöscht.",
+ imageTooLarge: "Dieses Bild ist zu groß zum Anhängen",
+ videoTooLarge: "Dieses Video ist zu groß zum Anhängen",
+ attachmentLimit: "Chat-Anhänge dürfen höchstens {size} MB groß sein.",
+ attachingImage: "Bild wird angehängt…",
+ attachingVideo: "Video wird angehängt…",
+ readImageFailed: "Das Bild konnte nicht gelesen werden ({status}).",
+ readVideoFailed: "Das Video konnte nicht gelesen werden ({status}).",
+ openFileFailed: "Die Datei konnte nicht geöffnet werden",
},
},
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index c5f8c05d871..6159a5b209d 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -3105,6 +3105,11 @@ export const en = {
moreActionsVideo: "More actions for this video",
moreActionsClip: "More actions for this clip",
moreActionsFile: "More actions for this file",
+ openImage: "Open image",
+ openImageNamed: "Open image: {prompt}",
+ openVideo: "Open video",
+ untitledImage: "Untitled image",
+ untitledVideo: "Untitled video",
},
// The Project submenu that copies a file into a project.
project: {
@@ -3174,6 +3179,14 @@ export const en = {
imageNotFound: "Could not find this image",
clipNotFound: "Could not find this clip",
notFoundDescription: "It may be archived or deleted.",
+ imageTooLarge: "This image is too large to attach",
+ videoTooLarge: "This video is too large to attach",
+ attachmentLimit: "Chat attachments are limited to {size} MB.",
+ attachingImage: "Attaching the image…",
+ attachingVideo: "Attaching the video…",
+ readImageFailed: "Could not read the image ({status}).",
+ readVideoFailed: "Could not read the video ({status}).",
+ openFileFailed: "Could not open the file",
},
},
} as const;
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index ec07c867d03..4a384ecf853 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -3173,6 +3173,11 @@ export const es = {
moreActionsVideo: "Más acciones para este vídeo",
moreActionsClip: "Más acciones para este clip",
moreActionsFile: "Más acciones para este archivo",
+ openImage: "Abrir imagen",
+ openImageNamed: "Abrir imagen: {prompt}",
+ openVideo: "Abrir vídeo",
+ untitledImage: "Imagen sin título",
+ untitledVideo: "Vídeo sin título",
},
project: {
label: "Proyecto",
@@ -3238,6 +3243,14 @@ export const es = {
imageNotFound: "No se encontró esta imagen",
clipNotFound: "No se encontró este clip",
notFoundDescription: "Puede que se haya archivado o eliminado.",
+ imageTooLarge: "Esta imagen es demasiado grande para adjuntarla",
+ videoTooLarge: "Este vídeo es demasiado grande para adjuntarlo",
+ attachmentLimit: "Los adjuntos del chat tienen un límite de {size} MB.",
+ attachingImage: "Adjuntando la imagen…",
+ attachingVideo: "Adjuntando el vídeo…",
+ readImageFailed: "No se pudo leer la imagen ({status}).",
+ readVideoFailed: "No se pudo leer el vídeo ({status}).",
+ openFileFailed: "No se pudo abrir el archivo",
},
},
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 4fd12dbcd22..95aaf3fad6b 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -3187,6 +3187,11 @@ export const fr = {
moreActionsVideo: "Plus d'actions pour cette vidéo",
moreActionsClip: "Plus d'actions pour cet extrait",
moreActionsFile: "Plus d'actions pour ce fichier",
+ openImage: "Ouvrir l'image",
+ openImageNamed: "Ouvrir l'image : {prompt}",
+ openVideo: "Ouvrir la vidéo",
+ untitledImage: "Image sans titre",
+ untitledVideo: "Vidéo sans titre",
},
project: {
label: "Projet",
@@ -3252,6 +3257,14 @@ export const fr = {
imageNotFound: "Impossible de trouver cette image",
clipNotFound: "Impossible de trouver cet extrait",
notFoundDescription: "Cet élément a peut-être été archivé ou supprimé.",
+ imageTooLarge: "Cette image est trop volumineuse pour être jointe",
+ videoTooLarge: "Cette vidéo est trop volumineuse pour être jointe",
+ attachmentLimit: "Les pièces jointes du chat sont limitées à {size} Mo.",
+ attachingImage: "Ajout de l'image…",
+ attachingVideo: "Ajout de la vidéo…",
+ readImageFailed: "Impossible de lire l'image ({status}).",
+ readVideoFailed: "Impossible de lire la vidéo ({status}).",
+ openFileFailed: "Impossible d'ouvrir le fichier",
},
},
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 89ccb655a78..d5632a9bd11 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -3114,6 +3114,11 @@ export const hi = {
moreActionsVideo: "इस वीडियो के लिए और कार्रवाइयाँ",
moreActionsClip: "इस क्लिप के लिए और कार्रवाइयाँ",
moreActionsFile: "इस फ़ाइल के लिए और कार्रवाइयाँ",
+ openImage: "इमेज खोलें",
+ openImageNamed: "इमेज खोलें: {prompt}",
+ openVideo: "वीडियो खोलें",
+ untitledImage: "बिना शीर्षक की इमेज",
+ untitledVideo: "बिना शीर्षक का वीडियो",
},
project: {
label: "प्रोजेक्ट",
@@ -3179,6 +3184,14 @@ export const hi = {
imageNotFound: "यह इमेज नहीं मिली",
clipNotFound: "यह क्लिप नहीं मिली",
notFoundDescription: "हो सकता है इसे संग्रहीत या हटा दिया गया हो।",
+ imageTooLarge: "यह इमेज अटैच करने के लिए बहुत बड़ी है",
+ videoTooLarge: "यह वीडियो अटैच करने के लिए बहुत बड़ा है",
+ attachmentLimit: "चैट अटैचमेंट की सीमा {size} MB है।",
+ attachingImage: "इमेज अटैच की जा रही है…",
+ attachingVideo: "वीडियो अटैच किया जा रहा है…",
+ readImageFailed: "इमेज पढ़ी नहीं जा सकी ({status})।",
+ readVideoFailed: "वीडियो पढ़ा नहीं जा सका ({status})।",
+ openFileFailed: "फ़ाइल खोली नहीं जा सकी",
},
},
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 48a7cae70a0..0437b83be4b 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -3174,6 +3174,11 @@ export const it = {
moreActionsVideo: "Altre azioni per questo video",
moreActionsClip: "Altre azioni per questa clip",
moreActionsFile: "Altre azioni per questo file",
+ openImage: "Apri immagine",
+ openImageNamed: "Apri immagine: {prompt}",
+ openVideo: "Apri video",
+ untitledImage: "Immagine senza titolo",
+ untitledVideo: "Video senza titolo",
},
project: {
label: "Progetto",
@@ -3239,6 +3244,14 @@ export const it = {
imageNotFound: "Impossibile trovare questa immagine",
clipNotFound: "Impossibile trovare questa clip",
notFoundDescription: "L'elemento potrebbe essere stato archiviato o eliminato.",
+ imageTooLarge: "Questa immagine è troppo grande da allegare",
+ videoTooLarge: "Questo video è troppo grande da allegare",
+ attachmentLimit: "Gli allegati della chat sono limitati a {size} MB.",
+ attachingImage: "Allegando l'immagine…",
+ attachingVideo: "Allegando il video…",
+ readImageFailed: "Impossibile leggere l'immagine ({status}).",
+ readVideoFailed: "Impossibile leggere il video ({status}).",
+ openFileFailed: "Impossibile aprire il file",
},
},
} as const;
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index c171dfdbc99..0d236adb99b 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -3055,6 +3055,11 @@ export const ja = {
moreActionsVideo: "この動画のその他の操作",
moreActionsClip: "このクリップのその他の操作",
moreActionsFile: "このファイルのその他の操作",
+ openImage: "画像を開く",
+ openImageNamed: "画像を開く: {prompt}",
+ openVideo: "動画を開く",
+ untitledImage: "無題の画像",
+ untitledVideo: "無題の動画",
},
project: {
label: "プロジェクト",
@@ -3120,6 +3125,14 @@ export const ja = {
imageNotFound: "この画像が見つかりませんでした",
clipNotFound: "このクリップが見つかりませんでした",
notFoundDescription: "アーカイブまたは削除された可能性があります。",
+ imageTooLarge: "この画像は大きすぎて添付できません",
+ videoTooLarge: "この動画は大きすぎて添付できません",
+ attachmentLimit: "チャットの添付ファイルは {size} MB までです。",
+ attachingImage: "画像を添付しています…",
+ attachingVideo: "動画を添付しています…",
+ readImageFailed: "画像を読み込めませんでした ({status})。",
+ readVideoFailed: "動画を読み込めませんでした ({status})。",
+ openFileFailed: "ファイルを開けませんでした",
},
},
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index e594724d9a9..114222ef49b 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -3101,6 +3101,11 @@ export const ko = {
moreActionsVideo: "이 동영상에 대한 추가 작업",
moreActionsClip: "이 클립에 대한 추가 작업",
moreActionsFile: "이 파일에 대한 추가 작업",
+ openImage: "이미지 열기",
+ openImageNamed: "이미지 열기: {prompt}",
+ openVideo: "동영상 열기",
+ untitledImage: "제목 없는 이미지",
+ untitledVideo: "제목 없는 동영상",
},
project: {
label: "프로젝트",
@@ -3166,6 +3171,14 @@ export const ko = {
imageNotFound: "이 이미지를 찾을 수 없습니다",
clipNotFound: "이 클립을 찾을 수 없습니다",
notFoundDescription: "보관되었거나 삭제되었을 수 있습니다.",
+ imageTooLarge: "이 이미지는 너무 커서 첨부할 수 없습니다",
+ videoTooLarge: "이 동영상은 너무 커서 첨부할 수 없습니다",
+ attachmentLimit: "채팅 첨부 파일은 {size}MB까지 가능합니다.",
+ attachingImage: "이미지를 첨부하는 중…",
+ attachingVideo: "동영상을 첨부하는 중…",
+ readImageFailed: "이미지를 읽을 수 없습니다 ({status}).",
+ readVideoFailed: "동영상을 읽을 수 없습니다 ({status}).",
+ openFileFailed: "파일을 열 수 없습니다",
},
},
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 7991b8bba26..75b36fc903e 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -3135,6 +3135,11 @@ export const ptBR = {
moreActionsVideo: "Mais ações para este vídeo",
moreActionsClip: "Mais ações para este clipe",
moreActionsFile: "Mais ações para este arquivo",
+ openImage: "Abrir imagem",
+ openImageNamed: "Abrir imagem: {prompt}",
+ openVideo: "Abrir vídeo",
+ untitledImage: "Imagem sem título",
+ untitledVideo: "Vídeo sem título",
},
project: {
label: "Projeto",
@@ -3200,6 +3205,14 @@ export const ptBR = {
imageNotFound: "Não foi possível encontrar esta imagem",
clipNotFound: "Não foi possível encontrar este clipe",
notFoundDescription: "O item pode ter sido arquivado ou excluído.",
+ imageTooLarge: "Esta imagem é grande demais para anexar",
+ videoTooLarge: "Este vídeo é grande demais para anexar",
+ attachmentLimit: "Os anexos do chat são limitados a {size} MB.",
+ attachingImage: "Anexando a imagem…",
+ attachingVideo: "Anexando o vídeo…",
+ readImageFailed: "Não foi possível ler a imagem ({status}).",
+ readVideoFailed: "Não foi possível ler o vídeo ({status}).",
+ openFileFailed: "Não foi possível abrir o arquivo",
},
},
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index ce446d2433f..39db36eef7d 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -3134,6 +3134,11 @@ export const ru = {
moreActionsVideo: "Другие действия с видео",
moreActionsClip: "Другие действия с клипом",
moreActionsFile: "Другие действия с файлом",
+ openImage: "Открыть изображение",
+ openImageNamed: "Открыть изображение: {prompt}",
+ openVideo: "Открыть видео",
+ untitledImage: "Изображение без названия",
+ untitledVideo: "Видео без названия",
},
project: {
label: "Проект",
@@ -3199,6 +3204,14 @@ export const ru = {
imageNotFound: "Не удалось найти это изображение",
clipNotFound: "Не удалось найти этот клип",
notFoundDescription: "Возможно, элемент архивирован или удалён.",
+ imageTooLarge: "Это изображение слишком большое для вложения",
+ videoTooLarge: "Это видео слишком большое для вложения",
+ attachmentLimit: "Размер вложений в чате — не более {size} МБ.",
+ attachingImage: "Прикрепляем изображение…",
+ attachingVideo: "Прикрепляем видео…",
+ readImageFailed: "Не удалось прочитать изображение ({status}).",
+ readVideoFailed: "Не удалось прочитать видео ({status}).",
+ openFileFailed: "Не удалось открыть файл",
},
},
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index b34d778460a..e8deb54c426 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -3014,6 +3014,11 @@ export const zhCN = {
moreActionsVideo: "此视频的更多操作",
moreActionsClip: "此片段的更多操作",
moreActionsFile: "此文件的更多操作",
+ openImage: "打开图片",
+ openImageNamed: "打开图片:{prompt}",
+ openVideo: "打开视频",
+ untitledImage: "未命名图片",
+ untitledVideo: "未命名视频",
},
project: {
label: "项目",
@@ -3079,6 +3084,14 @@ export const zhCN = {
imageNotFound: "找不到此图像",
clipNotFound: "找不到此片段",
notFoundDescription: "它可能已被归档或删除。",
+ imageTooLarge: "此图片太大,无法附加",
+ videoTooLarge: "此视频太大,无法附加",
+ attachmentLimit: "聊天附件的大小上限为 {size} MB。",
+ attachingImage: "正在附加图片…",
+ attachingVideo: "正在附加视频…",
+ readImageFailed: "无法读取图片({status})。",
+ readVideoFailed: "无法读取视频({status})。",
+ openFileFailed: "无法打开文件",
},
},
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/lib/prompt-text.ts b/studio/frontend/src/lib/prompt-text.ts
new file mode 100644
index 00000000000..6294058f098
--- /dev/null
+++ b/studio/frontend/src/lib/prompt-text.ts
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Cut by code point so an emoji is never split into a lone surrogate.
+
+const UNSAFE_IN_FILE_NAME = /[\p{Cc}\\/:*?"<>|\s]+/gu;
+
+export function mediaFileName(prompt: string, extension: string, maxChars = 60): string {
+ const cleaned = prompt.replace(UNSAFE_IN_FILE_NAME, " ").trim();
+ const base = Array.from(cleaned)
+ .slice(0, maxChars)
+ .join("")
+ .replace(/^[.\s]+|[.\s]+$/g, "");
+ return `${base || "Untitled"}.${extension}`;
+}
+
+export function shortPrompt(prompt: string, maxChars = 80): string {
+ const text = prompt.replace(/\s+/g, " ").trim();
+ const chars = Array.from(text);
+ if (chars.length <= maxChars) return text;
+ const cut = chars.slice(0, maxChars).join("");
+ const space = chars[maxChars] === " " ? cut.length : cut.lastIndexOf(" ");
+ const shown = space > cut.length / 2 ? cut.slice(0, space) : cut;
+ return `${shown.replace(/[\s.,;:]+$/, "")}…`;
+}
diff --git a/studio/frontend/tests/library-state.test.ts b/studio/frontend/tests/library-state.test.ts
index edf8e01a0a3..0de1d10070b 100644
--- a/studio/frontend/tests/library-state.test.ts
+++ b/studio/frontend/tests/library-state.test.ts
@@ -398,6 +398,7 @@ function loadDownloads(
"./file-kind": {},
"./file-name": { hasOwnFile: () => true, ...fileNames },
"./chat-handoff-store": {},
+ "./start-chat": {},
}).downloadLibraryItems;
}
diff --git a/studio/frontend/tests/media-page-viewer.test.ts b/studio/frontend/tests/media-page-viewer.test.ts
new file mode 100644
index 00000000000..ed94ec80244
--- /dev/null
+++ b/studio/frontend/tests/media-page-viewer.test.ts
@@ -0,0 +1,164 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { readSrc } from "./helpers/kit.ts";
+import { mediaFileName, shortPrompt } from "../src/lib/prompt-text.ts";
+import {
+ fetchWithFreshLink,
+ playWithMutedFallback,
+ readPlayback,
+} from "../src/features/video/viewer.ts";
+
+const a59 = "a".repeat(59);
+
+test("a prompt becomes a safe file name, cut by code point", () => {
+ for (const [prompt, extension, expected] of [
+ ['a cat: "sitting" on a/b\\c?', "png", "a cat sitting on a b c.png"],
+ ["tabs\tand\nnewlines\r\n here", "mp4", "tabs and newlines here.mp4"],
+ ["bell\u0007 and del\u007f and c1\u0085", "png", "bell and del and c1.png"],
+ ["", "png", "Untitled.png"],
+ [" *** ??? ", "png", "Untitled.png"],
+ ["...", "mp4", "Untitled.mp4"],
+ ["a sunset...", "png", "a sunset.png"],
+ [".hidden prompt", "png", "hidden prompt.png"],
+ [`${a59} tail`, "png", `${a59}.png`],
+ [`${a59}.tail`, "png", `${a59}.png`],
+ [`a${"🐱".repeat(80)}`, "png", `a${"🐱".repeat(59)}.png`],
+ ]) {
+ assert.equal(mediaFileName(prompt, extension), expected, prompt);
+ }
+ assert.equal(mediaFileName("abcdef", "png", 3), "abc.png");
+});
+
+test("the preview's name keeps a short prompt, cut at a word", () => {
+ const long = "a very detailed painting of a lighthouse on a cliff at dusk, waves crashing below, gulls";
+ for (const [prompt, max, expected] of [
+ ["a red fox in snow", 80, "a red fox in snow"],
+ [" a red\n fox ", 80, "a red fox"],
+ ["", 80, ""],
+ [" \n ", 80, ""],
+ [long, 40, "a very detailed painting of a lighthouse…"],
+ [long, 38, "a very detailed painting of a…"],
+ ["x".repeat(50), 10, `${"x".repeat(10)}…`],
+ [`a${"🐱".repeat(20)}`, 10, `a${"🐱".repeat(9)}…`],
+ ] as const) {
+ assert.equal(shortPrompt(prompt, max), expected, prompt);
+ }
+});
+
+test("a signed link refused with 401 or 403 is minted afresh once; other statuses are returned", async () => {
+ const realFetch = globalThis.fetch;
+ try {
+ for (const [statuses, asked, final] of [
+ [{ "/old": 200 }, ["/old"], 200],
+ [{ "/old": 401, "/new": 200 }, ["/old", "/new"], 200],
+ [{ "/old": 403, "/new": 200 }, ["/old", "/new"], 200],
+ [{ "/old": 404 }, ["/old"], 404],
+ [{ "/old": 401, "/new": 401 }, ["/old", "/new"], 401],
+ ] as const) {
+ const seen: string[] = [];
+ globalThis.fetch = (async (url: string) => {
+ seen.push(url);
+ const status = (statuses as Record<string, number>)[url]!;
+ return new Response(status === 200 ? "clip" : null, { status });
+ }) as typeof fetch;
+ const response = await fetchWithFreshLink("/old", async () => "/new");
+ assert.equal(response.status, final);
+ assert.deepEqual(seen, asked);
+ }
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+});
+
+const START = { time: 12.5, playing: true, muted: false, volume: 0.4 };
+const player = (overrides: object = {}) =>
+ ({ currentTime: 3, paused: false, ended: false, muted: true, volume: 0.8, readyState: 4, ...overrides }) as unknown as HTMLVideoElement;
+
+test("playback is the player's own once positioned, else the start with the player's mute", () => {
+ const loaded = { time: 3, playing: true, muted: true, volume: 0.8 };
+ const notSeeked = player({ currentTime: 0, paused: true, readyState: 1 });
+ for (const [video, positioned, expected] of [
+ [player(), undefined, loaded],
+ [player({ paused: true }), undefined, { ...loaded, playing: false }],
+ [player({ ended: true }), undefined, { ...loaded, playing: false }],
+ [player({ currentTime: 0, paused: true, readyState: 0, volume: 1 }), undefined, { ...START, muted: true }],
+ [notSeeked, false, { ...START, muted: true }],
+ [notSeeked, true, { time: 0, playing: false, muted: true, volume: 0.8 }],
+ [null, undefined, START],
+ ] as const) {
+ assert.deepEqual(readPlayback(video, START, positioned), expected);
+ }
+});
+
+test("a refusal of sound retries muted; an abort or a muted refusal is not retried, and nothing rejects", async () => {
+ for (const [refusals, muted, plays] of [
+ [[], false, [false]],
+ [["NotAllowedError"], false, [false, true]],
+ [["NotAllowedError", "NotAllowedError"], false, [false, true]],
+ [["AbortError"], false, [false]],
+ [["NotAllowedError"], true, [true]],
+ ] as const) {
+ const queue: string[] = [...refusals];
+ const seen: boolean[] = [];
+ const video = {
+ muted,
+ play() {
+ seen.push(video.muted);
+ const name = queue.shift();
+ return name ? Promise.reject(Object.assign(new Error(name), { name })) : Promise.resolve();
+ },
+ };
+ await playWithMutedFallback(video);
+ assert.deepEqual(seen, plays, refusals.join());
+ assert.equal(video.muted, plays.at(-1));
+ }
+});
+
+function slice(page: string, from: string, to: string): string {
+ const start = page.indexOf(from);
+ assert.ok(start >= 0, from);
+ return page.slice(start, page.indexOf(to, start));
+}
+
+test("the Images preview is a button named for its prompt", () => {
+ const preview = slice(readSrc("features/images/images-page.tsx"), "alt={selected.prompt}", "/>");
+ for (const attribute of ['role="button"', "tabIndex={0}", "aria-label={openImageLabel(t, selected.prompt)}"]) {
+ assert.ok(preview.includes(attribute), attribute);
+ }
+});
+
+test("the Video viewer plays only if the inline clip was, and hands its place back", () => {
+ const page = readSrc("features/video/video-page.tsx");
+ const viewer = slice(page, "<video\n ref={viewerVideoRef}", "</MediaViewer>");
+ assert.ok(!/^\s*autoPlay(=|\s*$)/m.test(viewer), "no autoPlay");
+ for (const line of [
+ "if (viewer.from.playing) void playWithMutedFallback(video);",
+ "viewerPositioned.current = true;",
+ "readPlayback(event.currentTarget, viewer.from, viewerPositioned.current)",
+ ]) {
+ assert.ok(viewer.includes(line), line);
+ }
+ const inline = slice(page, "ref={previewRef}", "/>");
+ assert.ok(!inline.includes("onClick") && !inline.includes("openViewer"));
+ const effect = slice(page, "const last = handback.current;", "}, [viewer, shownId, selectedSrc]);");
+ for (const line of [
+ "if (viewer || !last || last.id !== shownId) return;",
+ "if (!selectedSrc || !inline) return;",
+ "playback.playing && activeRef.current",
+ "else inline.pause();",
+ ]) {
+ assert.ok(effect.includes(line), line);
+ }
+ assert.equal(page.split("handback.current = null;").length - 1, 3);
+ const remove = slice(page, "onDelete: () => {", "void handleDelete(viewerVideo.id);");
+ const cleared = remove.indexOf("handback.current = null;");
+ assert.ok(
+ cleared >= 0 && cleared < remove.indexOf("setViewer(null);"),
+ "a deleted clip is not handed back to play on",
+ );
+});