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: Images and Video strips stop re-rendering every card per thumbnail and page (#16311)

Daniel Hana9f51af029f1
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.yml
index 42dc4097e3e..5ca0c04f61b 100644
--- a/.github/workflows/studio-frontend-ci.yml
+++ b/.github/workflows/studio-frontend-ci.yml
@@ -42,6 +42,7 @@ on:
- 'tests/studio/playwright_progressive_rows.py'
- 'tests/studio/playwright_model_picker_renders.py'
- 'tests/studio/playwright_recipe_drag_renders.py'
+ - 'tests/studio/playwright_gallery_strip_renders.py'
- 'tests/studio/_code_block_flicker_analysis.py'
- 'tests/studio/test_code_block_flicker_contract.py'
- 'tests/studio/_playwright_robust.py'
@@ -89,6 +90,7 @@ on:
- 'tests/studio/playwright_progressive_rows.py'
- 'tests/studio/playwright_model_picker_renders.py'
- 'tests/studio/playwright_recipe_drag_renders.py'
+ - 'tests/studio/playwright_gallery_strip_renders.py'
- 'tests/studio/_code_block_flicker_analysis.py'
- 'tests/studio/test_code_block_flicker_contract.py'
- 'tests/studio/_playwright_robust.py'
@@ -540,6 +542,13 @@ jobs:
timeout-minutes: 5
run: python3 tests/studio/playwright_recipe_drag_renders.py
+ # Render counts, not timings: a thumbnail arriving or a page appending to the Images or Video
+ # strip must not re-render every card's menu, and a card's own menu must delete that card.
+ - name: Browser check for gallery strip re-renders
+ working-directory: ${{ github.workspace }}
+ timeout-minutes: 8
+ run: python3 tests/studio/playwright_gallery_strip_renders.py
+
# Two small sizes and one repetition on Chromium: enough to prove the fixture still
# renders every kind of content it claims to and that the curve still rises, which is all
# a PR gate can afford. The measurement this harness exists for is the three-engine,
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 177b81178a6..15494155f51 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -11,10 +11,13 @@ import type { CompareRun } from "./compare/compare-run";
import ComparePanel from "./compare/compare-panel";
import {
type DragEvent,
+ type KeyboardEvent as ReactKeyboardEvent,
+ memo,
type ReactNode,
type SetStateAction,
useCallback,
useEffect,
+ useLayoutEffect,
useMemo,
useRef,
useState,
@@ -121,7 +124,7 @@ import { GalleryItemMenu, GalleryPinBadge } from "@/components/gallery-item-menu
import { MediaRailResizeHandle } from "@/components/media-rail-resize-handle";
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 { type StripDropCue, useStripReorder } from "@/hooks/use-strip-reorder";
import { MediaApiButton } from "@/components/media-api-button";
import { LibraryPageLink, SiblingMediaPageLink } from "@/components/media-page-link";
import { translate, useT } from "@/i18n";
@@ -1593,6 +1596,131 @@ function openImageLabel(t: ReturnType<typeof useT>, prompt: string): string {
return text ? t("library.viewer.openImageNamed", { prompt: text }) : t("library.viewer.openImage");
}
+/** Page callbacks a tile reads at event time, so new page closures never re-render it. */
+interface StripTileActions {
+ tileProps: ReturnType<typeof useStripReorder>["tileProps"];
+ select: (id: string) => void;
+ setMenuId: (id: string | null) => void;
+ togglePin: (id: string, pinned: boolean) => void;
+ archive: (id: string) => void;
+ remove: (id: string) => void;
+ download: (image: GalleryImage) => void;
+ addToProject: (id: string, projectId: string) => Promise<{ already: boolean }>;
+ toggleFavorite: (key: string) => void;
+ editImage: (image: GalleryImage) => void;
+}
+
+class StripTileActionsBox {
+ private actions: StripTileActions | null = null;
+ set(actions: StripTileActions) {
+ this.actions = actions;
+ }
+ get(): StripTileActions {
+ return this.actions as StripTileActions;
+ }
+}
+
+function EditImageMenuItem({ onClick }: { onClick: () => void }) {
+ return (
+ <DropdownMenuItem onClick={onClick}>
+ <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />
+ Edit image
+ </DropdownMenuItem>
+ );
+}
+
+const GalleryStripTile = memo(function GalleryStripTile({
+ image,
+ src,
+ selected,
+ menuOpen,
+ active,
+ favorite,
+ dragging,
+ cueEdge,
+ actions,
+}: {
+ image: GalleryImage;
+ src: string | undefined;
+ selected: boolean;
+ menuOpen: boolean;
+ active: boolean;
+ favorite: boolean;
+ dragging: boolean;
+ cueEdge: StripDropCue["edge"] | null;
+ actions: StripTileActionsBox;
+}) {
+ const id = image.id;
+ return (
+ <div
+ data-image-id={id}
+ data-reorder-id={id}
+ draggable={true}
+ onDragStart={(event: DragEvent<HTMLElement>) => actions.get().tileProps(id).onDragStart(event)}
+ onDragEnd={() => actions.get().tileProps(id).onDragEnd()}
+ onKeyDown={(event: ReactKeyboardEvent<HTMLElement>) => actions.get().tileProps(id).onKeyDown(event)}
+ // Desktop only: a browser's own image menu works on these thumbnails, so keep it there.
+ // Portalled children (the New project dialog) bubble here too: leave their menu alone.
+ onContextMenu={(event) => {
+ if (!isTauri || !event.currentTarget.contains(event.target as Node)) return;
+ event.preventDefault();
+ actions.get().setMenuId(id);
+ }}
+ className={cn("group relative size-16 shrink-0", dragging && "opacity-40")}
+ >
+ {cueEdge && <StripDropLine edge={cueEdge} />}
+ <button
+ type="button"
+ onClick={() => actions.get().select(id)}
+ className="relative size-full overflow-hidden rounded-lg bg-muted/40 outline-none ring-1 ring-transparent transition-shadow hover:ring-border focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {src ? (
+ <img
+ src={src}
+ alt={image.prompt}
+ draggable={false}
+ className="size-full object-cover"
+ />
+ ) : (
+ <span className="flex size-full items-center justify-center">
+ <Spinner className="size-4 text-muted-foreground" />
+ </span>
+ )}
+ {/* Selection marker on a non-focusable overlay, so the button's focus state cannot mask it. */}
+ {selected && (
+ <span className="pointer-events-none absolute inset-0 rounded-lg border border-border bg-white/35 dark:border-[rgb(255_255_255_/_calc(0.25*var(--contrast-edge-gain,1)))] dark:bg-white/20" />
+ )}
+ </button>
+ {image.pinned && (
+ <GalleryPinBadge
+ noun="image"
+ className="bottom-0.5 left-0.5"
+ onUnpin={() => actions.get().togglePin(id, false)}
+ />
+ )}
+ <div className="absolute right-0.5 top-0.5">
+ <GalleryItemMenu
+ variant="overlay"
+ noun="image"
+ active={active}
+ open={menuOpen}
+ onOpenChange={(open) => actions.get().setMenuId(open ? id : null)}
+ pinned={Boolean(image.pinned)}
+ archived={Boolean(image.archived)}
+ favorite={favorite}
+ onToggleFavorite={() => actions.get().toggleFavorite(`image:${id}`)}
+ onTogglePin={() => actions.get().togglePin(id, !image.pinned)}
+ onToggleArchive={() => actions.get().archive(id)}
+ onDelete={() => actions.get().remove(id)}
+ onDownload={() => actions.get().download(image)}
+ onAddToProject={(projectId) => actions.get().addToProject(id, projectId)}
+ leadingItems={<EditImageMenuItem onClick={() => actions.get().editImage(image)} />}
+ />
+ </div>
+ </div>
+ );
+});
+
export function ImagesPage({
active = true,
onInitialReady,
@@ -3899,11 +4027,24 @@ export function ImagesPage({
applyEditSource(dataUrl);
}, [pendingLibraryEdit, capabilitiesKnown, applyEditSource]);
const editImageItem = (image: GalleryImage) => (
- <DropdownMenuItem onClick={() => void editGalleryImage(image)}>
- <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />
- Edit image
- </DropdownMenuItem>
+ <EditImageMenuItem onClick={() => void editGalleryImage(image)} />
);
+ // Refreshed after every commit, read only from tile event handlers, so new page closures never re-render a tile.
+ const [stripTileActions] = useState(() => new StripTileActionsBox());
+ useLayoutEffect(() => {
+ stripTileActions.set({
+ tileProps: stripReorder.tileProps,
+ select: setSelectedId,
+ setMenuId: setTileMenuId,
+ togglePin: (id, pinned) => void handleTogglePin(id, pinned),
+ archive: (id) => void handleArchive(id),
+ remove: (id) => void handleDelete(id),
+ download: (image) => void handleQuickDownload(image),
+ addToProject: addGalleryImageToProject,
+ toggleFavorite,
+ editImage: (image) => void editGalleryImage(image),
+ });
+ });
const { openCrop: openInpaintCrop, cropDialog: inpaintCropDialog } = useImageCrop(
initImage,
handleInitChange,
@@ -7241,74 +7382,18 @@ export function ImagesPage({
</div>
)}
{images.map((image) => (
- <div
+ <GalleryStripTile
key={image.id}
- data-image-id={image.id}
- {...stripReorder.tileProps(image.id)}
- // Desktop only: a browser's own image menu works on these thumbnails, so keep it there.
- // Portalled children (the New project dialog) bubble here too: leave their menu alone.
- onContextMenu={(event) => {
- if (!isTauri || !event.currentTarget.contains(event.target as Node)) return;
- event.preventDefault();
- setTileMenuId(image.id);
- }}
- className={cn(
- "group relative size-16 shrink-0",
- stripReorder.draggingId === image.id && "opacity-40",
- )}
- >
- {stripReorder.cue?.id === image.id && (
- <StripDropLine edge={stripReorder.cue.edge} />
- )}
- <button
- type="button"
- onClick={() => setSelectedId(image.id)}
- className="relative size-full overflow-hidden rounded-lg bg-muted/40 outline-none ring-1 ring-transparent transition-shadow hover:ring-border focus-visible:ring-2 focus-visible:ring-ring"
- >
- {(thumbById[image.id] ?? srcById[image.id]) ? (
- <img
- src={thumbById[image.id] ?? srcById[image.id]}
- alt={image.prompt}
- draggable={false}
- className="size-full object-cover"
- />
- ) : (
- <span className="flex size-full items-center justify-center">
- <Spinner className="size-4 text-muted-foreground" />
- </span>
- )}
- {/* Selection marker on a non-focusable overlay, so the button's focus state cannot mask it. */}
- {image.id === selected?.id && (
- <span className="pointer-events-none absolute inset-0 rounded-lg border border-border bg-white/35 dark:border-[rgb(255_255_255_/_calc(0.25*var(--contrast-edge-gain,1)))] dark:bg-white/20" />
- )}
- </button>
- {image.pinned && (
- <GalleryPinBadge
- noun="image"
- className="bottom-0.5 left-0.5"
- onUnpin={() => void handleTogglePin(image.id, false)}
- />
- )}
- <div className="absolute right-0.5 top-0.5">
- <GalleryItemMenu
- variant="overlay"
- noun="image"
- active={active}
- open={tileMenuId === image.id}
- onOpenChange={(open) => setTileMenuId(open ? image.id : null)}
- pinned={Boolean(image.pinned)}
- archived={Boolean(image.archived)}
- favorite={isFavorite(`image:${image.id}`)}
- onToggleFavorite={() => toggleFavorite(`image:${image.id}`)}
- onTogglePin={() => void handleTogglePin(image.id, !image.pinned)}
- onToggleArchive={() => void handleArchive(image.id)}
- onDelete={() => void handleDelete(image.id)}
- onDownload={() => void handleQuickDownload(image)}
- onAddToProject={(projectId) => addGalleryImageToProject(image.id, projectId)}
- leadingItems={editImageItem(image)}
- />
- </div>
- </div>
+ image={image}
+ src={thumbById[image.id] ?? srcById[image.id]}
+ selected={image.id === selected?.id}
+ menuOpen={tileMenuId === image.id}
+ active={active}
+ favorite={isFavorite(`image:${image.id}`)}
+ dragging={stripReorder.draggingId === image.id}
+ cueEdge={stripReorder.cue?.id === image.id ? stripReorder.cue.edge : null}
+ actions={stripTileActions}
+ />
))}
{hasMore && (
<div className="flex size-16 shrink-0 items-center justify-center">
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 5242539c9f6..edecbabace8 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -2,7 +2,18 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { generationFailureLogsAction } from "@/features/settings/lib/view-logs-action";
-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import {
+ type DragEvent,
+ type KeyboardEvent as ReactKeyboardEvent,
+ memo,
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import {
Alert02Icon,
ArrowLeftRightIcon,
@@ -26,7 +37,7 @@ import { MediaViewer } from "@/components/media-viewer";
import { MessageCircleIcon, TestTubeOutlineIcon } 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 { type StripDropCue, useStripReorder } from "@/hooks/use-strip-reorder";
import { ImageDropzone } from "@/components/image-dropzone";
import { MediaApiButton } from "@/components/media-api-button";
import { LibraryPageLink, SiblingMediaPageLink } from "@/components/media-page-link";
@@ -781,6 +792,136 @@ function ReferenceVideoTrimStatus({
);
}
+/** Page callbacks a card reads at event time, so new page closures never re-render it. */
+interface VideoStripTileActions {
+ tileProps: ReturnType<typeof useStripReorder>["tileProps"];
+ select: (id: string) => void;
+ posterError: (id: string) => void;
+ togglePin: (id: string, pinned: boolean) => void;
+ archive: (id: string) => void;
+ remove: (id: string) => void;
+ download: (video: GalleryVideo) => void;
+ addToProject: (id: string, projectId: string) => Promise<{ already: boolean }>;
+ toggleFavorite: (key: string) => void;
+}
+
+class VideoStripTileActionsBox {
+ private actions: VideoStripTileActions | null = null;
+ set(actions: VideoStripTileActions) {
+ this.actions = actions;
+ }
+ get(): VideoStripTileActions {
+ return this.actions as VideoStripTileActions;
+ }
+}
+
+const VideoStripTile = memo(function VideoStripTile({
+ video,
+ thumbnail,
+ thumbnailFailed,
+ selected,
+ active,
+ favorite,
+ dragging,
+ cueEdge,
+ actions,
+}: {
+ video: GalleryVideo;
+ thumbnail: string | undefined;
+ thumbnailFailed: boolean;
+ selected: boolean;
+ active: boolean;
+ favorite: boolean;
+ dragging: boolean;
+ cueEdge: StripDropCue["edge"] | null;
+ actions: VideoStripTileActionsBox;
+}) {
+ const id = video.id;
+ return (
+ <div
+ data-clip-id={id}
+ data-reorder-id={id}
+ draggable={true}
+ onDragStart={(event: DragEvent<HTMLElement>) => actions.get().tileProps(id).onDragStart(event)}
+ onDragEnd={() => actions.get().tileProps(id).onDragEnd()}
+ onKeyDown={(event: ReactKeyboardEvent<HTMLElement>) => actions.get().tileProps(id).onKeyDown(event)}
+ className={cn("group relative h-16 w-24 shrink-0", dragging && "opacity-40")}
+ >
+ {cueEdge && <StripDropLine edge={cueEdge} />}
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ onClick={() => actions.get().select(id)}
+ className="relative flex size-full flex-col justify-end overflow-hidden rounded-lg bg-muted/40 outline-none ring-1 ring-transparent transition-shadow hover:ring-border focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {thumbnail ? (
+ <img
+ src={thumbnail}
+ alt=""
+ draggable={false}
+ onError={() => actions.get().posterError(id)}
+ className="absolute inset-0 size-full object-cover"
+ />
+ ) : thumbnailFailed ? (
+ <span className="absolute inset-0 flex items-center justify-center">
+ <HugeiconsIcon
+ icon={FlimSlateIcon}
+ className="size-4 text-muted-foreground"
+ />
+ </span>
+ ) : (
+ <span className="absolute inset-0 flex items-center justify-center">
+ <Spinner className="size-4 text-muted-foreground" />
+ </span>
+ )}
+ {/* A terse caption strip so cards read at a glance. Left/bottom padding clears the rounded
+ corner and the selection border. */}
+ <span className="relative z-10 truncate bg-gradient-to-t from-black/70 to-transparent px-2 pb-1 pt-2 text-left text-ui-9 font-medium leading-none text-white">
+ {clipMeta(video)}
+ </span>
+ {selected && (
+ <span className="pointer-events-none absolute inset-0 z-20 rounded-lg border border-border bg-white/35 dark:border-[rgb(255_255_255_/_calc(0.25*var(--contrast-edge-gain,1)))] dark:bg-white/20" />
+ )}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">
+ {video.prompt}
+ <span className="mt-0.5 block opacity-70">
+ seed {video.seed} - {clipMeta(video)}
+ {CONDITIONING_LABELS[video.conditioning ?? ""]
+ ? ` - ${CONDITIONING_LABELS[video.conditioning ?? ""]}`
+ : ""}
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ {video.pinned && (
+ <GalleryPinBadge
+ noun="video"
+ className="left-0.5 top-0.5 z-30"
+ onUnpin={() => actions.get().togglePin(id, false)}
+ />
+ )}
+ <div className="absolute right-0.5 top-0.5 z-30">
+ <GalleryItemMenu
+ variant="overlay"
+ noun="video"
+ active={active}
+ pinned={Boolean(video.pinned)}
+ archived={Boolean(video.archived)}
+ favorite={favorite}
+ onToggleFavorite={() => actions.get().toggleFavorite(`video:${id}`)}
+ onTogglePin={() => actions.get().togglePin(id, !video.pinned)}
+ onToggleArchive={() => actions.get().archive(id)}
+ onDelete={() => actions.get().remove(id)}
+ onDownload={() => actions.get().download(video)}
+ onAddToProject={(projectId) => actions.get().addToProject(id, projectId)}
+ />
+ </div>
+ </div>
+ );
+});
+
function RecipePopover({
video,
onRestore,
@@ -2167,6 +2308,22 @@ function VideoGenerator({
[dropFromStrip],
);
+ // Refreshed after every commit, read only from card event handlers, so new page closures never re-render a card.
+ const [stripTileActions] = useState(() => new VideoStripTileActionsBox());
+ useLayoutEffect(() => {
+ stripTileActions.set({
+ tileProps: stripReorder.tileProps,
+ select: setSelectedId,
+ posterError: handlePosterError,
+ togglePin: (id, pinned) => void handleTogglePin(id, pinned),
+ archive: (id) => void handleArchive(id),
+ remove: (id) => void handleDelete(id),
+ download: (video) => void handleQuickDownload(video),
+ addToProject: addGalleryVideoToProject,
+ toggleFavorite,
+ });
+ });
+
const handleClearAll = useCallback(async () => {
setClearingGallery(true);
try {
@@ -4743,89 +4900,18 @@ function VideoGenerator({
since a button inside a button is invalid. data-clip-id rides the wrapper so the observer
still sees it. */}
{videos.map((video) => (
- <div
+ <VideoStripTile
key={video.id}
- data-clip-id={video.id}
- {...stripReorder.tileProps(video.id)}
- className={cn(
- "group relative h-16 w-24 shrink-0",
- stripReorder.draggingId === video.id && "opacity-40",
- )}
- >
- {stripReorder.cue?.id === video.id && (
- <StripDropLine edge={stripReorder.cue.edge} />
- )}
- <Tooltip>
- <TooltipTrigger asChild={true}>
- <button
- type="button"
- onClick={() => setSelectedId(video.id)}
- className="relative flex size-full flex-col justify-end overflow-hidden rounded-lg bg-muted/40 outline-none ring-1 ring-transparent transition-shadow hover:ring-border focus-visible:ring-2 focus-visible:ring-ring"
- >
- {thumbnailById[video.id] ? (
- <img
- src={thumbnailById[video.id]}
- alt=""
- draggable={false}
- onError={() => handlePosterError(video.id)}
- className="absolute inset-0 size-full object-cover"
- />
- ) : thumbnailFailedIds.has(video.id) ? (
- <span className="absolute inset-0 flex items-center justify-center">
- <HugeiconsIcon
- icon={FlimSlateIcon}
- className="size-4 text-muted-foreground"
- />
- </span>
- ) : (
- <span className="absolute inset-0 flex items-center justify-center">
- <Spinner className="size-4 text-muted-foreground" />
- </span>
- )}
- {/* A terse caption strip so cards read at a glance. Left/bottom padding clears the rounded
- corner and the selection border. */}
- <span className="relative z-10 truncate bg-gradient-to-t from-black/70 to-transparent px-2 pb-1 pt-2 text-left text-ui-9 font-medium leading-none text-white">
- {clipMeta(video)}
- </span>
- {video.id === selected?.id && (
- <span className="pointer-events-none absolute inset-0 z-20 rounded-lg border border-border bg-white/35 dark:border-[rgb(255_255_255_/_calc(0.25*var(--contrast-edge-gain,1)))] dark:bg-white/20" />
- )}
- </button>
- </TooltipTrigger>
- <TooltipContent className="max-w-xs">
- {video.prompt}
- <span className="mt-0.5 block opacity-70">
- seed {video.seed} - {clipMeta(video)}
- {CONDITIONING_LABELS[video.conditioning ?? ""]
- ? ` - ${CONDITIONING_LABELS[video.conditioning ?? ""]}`
- : ""}
- </span>
- </TooltipContent>
- </Tooltip>
- {video.pinned && (
- <GalleryPinBadge
- noun="video"
- className="left-0.5 top-0.5 z-30"
- onUnpin={() => void handleTogglePin(video.id, false)}
- />
- )}
- <div className="absolute right-0.5 top-0.5 z-30">
- <GalleryItemMenu
- variant="overlay"
- noun="video"
- active={active}
- pinned={Boolean(video.pinned)}
- archived={Boolean(video.archived)}
- favorite={isFavorite(`video:${video.id}`)}
- onToggleFavorite={() => toggleFavorite(`video:${video.id}`)}
- onTogglePin={() => void handleTogglePin(video.id, !video.pinned)}
- onToggleArchive={() => void handleArchive(video.id)}
- onDelete={() => void handleDelete(video.id)}
- onDownload={() => void handleQuickDownload(video)}
- onAddToProject={(projectId) => addGalleryVideoToProject(video.id, projectId)}
- />
- </div>
- </div>
+ video={video}
+ thumbnail={thumbnailById[video.id]}
+ thumbnailFailed={thumbnailFailedIds.has(video.id)}
+ selected={video.id === selected?.id}
+ active={active}
+ favorite={isFavorite(`video:${video.id}`)}
+ dragging={stripReorder.draggingId === video.id}
+ cueEdge={stripReorder.cue?.id === video.id ? stripReorder.cue.edge : null}
+ actions={stripTileActions}
+ />
))}
{/* Tail spinner while older pages stream in on scroll. */}
{hasMore && (
diff --git a/studio/frontend/tests/images-gallery-thumbnails.test.ts b/studio/frontend/tests/images-gallery-thumbnails.test.ts
index 26f9b3b586b..2604deec81b 100644
--- a/studio/frontend/tests/images-gallery-thumbnails.test.ts
+++ b/studio/frontend/tests/images-gallery-thumbnails.test.ts
@@ -27,12 +27,12 @@ function between(text: string, start: string, end: string): string {
const page = source("../src/features/images/images-page.tsx");
test("strip tiles fetch and show thumbnails, falling back to a cached original", () => {
- const strip = between(
- page,
- "{(thumbById[image.id] ?? srcById[image.id]) ? (",
- "{/* Selection marker",
- );
+ // The strip hands each tile its thumbnail (or the cached original); the tile draws it or a spinner.
+ const strip = between(page, "{images.map((image) => (", "{hasMore && (");
assert.ok(strip.includes("src={thumbById[image.id] ?? srcById[image.id]}"));
+ const tile = between(page, "const GalleryStripTile = memo(", "{/* Selection marker");
+ assert.ok(tile.includes("{src ? ("));
+ assert.ok(tile.includes("src={src}"));
const observer = between(page, "const io = new IntersectionObserver(", "return () => io.disconnect();");
assert.ok(observer.includes("void ensureThumb(image);"));
diff --git a/studio/frontend/tests/images-strip-context-menu.test.ts b/studio/frontend/tests/images-strip-context-menu.test.ts
index 1af9c030fdd..a0c656a3535 100644
--- a/studio/frontend/tests/images-strip-context-menu.test.ts
+++ b/studio/frontend/tests/images-strip-context-menu.test.ts
@@ -8,7 +8,7 @@ import { readSrc } from "./helpers/kit.ts";
test("a right-click on an Images strip tile opens the tile's actions menu", () => {
const page = readSrc("features/images/images-page.tsx");
- const tile = page.slice(page.indexOf("data-image-id={image.id}"));
+ const tile = page.slice(page.indexOf("const GalleryStripTile = memo("));
const handler = /onContextMenu=\{\(event\) => \{([^}]*)\}\}/.exec(tile)?.[1] ?? "";
// The desktop webview's own image menu cannot open or copy a blob: thumbnail, so it must not show there.
// A browser's menu works on them, so browsers keep it.
@@ -17,9 +17,12 @@ test("a right-click on an Images strip tile opens the tile's actions menu", () =
handler,
/^\s*if \(!isTauri \|\| !event\.currentTarget\.contains\(event\.target as Node\)\) return;\s*event\.preventDefault\(\)/,
);
- assert.match(handler, /setTileMenuId\(image\.id\)/);
- assert.match(tile, /open=\{tileMenuId === image\.id\}/);
- assert.match(tile, /onOpenChange=\{\(open\) => setTileMenuId\(open \? image\.id : null\)\}/);
+ assert.match(handler, /actions\.get\(\)\.setMenuId\(id\)/);
+ assert.match(tile, /open=\{menuOpen\}/);
+ assert.match(tile, /onOpenChange=\{\(open\) => actions\.get\(\)\.setMenuId\(open \? id : null\)\}/);
+ // The page owns which tile's menu is open.
+ assert.ok(page.includes("menuOpen={tileMenuId === image.id}"));
+ assert.ok(page.includes("setMenuId: setTileMenuId,"));
// A tab switch or a deleted tile drops the request, so it cannot reopen later.
assert.match(page, /if \(tileMenuId && \(!active \|\| !images\.some\(/);
});
diff --git a/studio/frontend/tests/video-gallery-thumbnail-load.test.ts b/studio/frontend/tests/video-gallery-thumbnail-load.test.ts
index a3629cae4ca..96f24b09e97 100644
--- a/studio/frontend/tests/video-gallery-thumbnail-load.test.ts
+++ b/studio/frontend/tests/video-gallery-thumbnail-load.test.ts
@@ -37,11 +37,12 @@ test("video gallery tiles use still posters instead of media pipelines", () => {
"{/* Tail spinner while older pages stream in on scroll.",
);
- assert.ok(strip.includes("thumbnailById[video.id]"));
- assert.ok(strip.includes("<img"));
- assert.ok(strip.includes("src={thumbnailById[video.id]}"));
- assert.ok(!strip.includes("<video"));
+ assert.ok(strip.includes("thumbnail={thumbnailById[video.id]}"));
assert.ok(!strip.includes("srcById[video.id]"));
+ const tile = between(page, "const VideoStripTile = memo(", "function RecipePopover(");
+ assert.ok(tile.includes("<img"));
+ assert.ok(tile.includes("src={thumbnail}"));
+ assert.ok(!tile.includes("<video"));
});
test("selected playback does not depend on poster decoding", () => {
@@ -196,7 +197,10 @@ test("a poster the renderer cannot decode falls back to the slate", () => {
"{/* In-progress generation: a placeholder tile",
"{/* Tail spinner while older pages stream in on scroll.",
);
- assert.ok(strip.includes("onError={() => handlePosterError(video.id)}"));
+ const tile = between(page, "const VideoStripTile = memo(", "function RecipePopover(");
+ assert.ok(tile.includes("onError={() => actions.get().posterError(id)}"));
+ assert.ok(strip.includes("thumbnailFailed={thumbnailFailedIds.has(video.id)}"));
+ assert.ok(page.includes("posterError: handlePosterError,"));
const handler = between(page, "const handlePosterError", "}, []);");
assert.ok(handler.includes("galleryCache.thumbnailById.delete(id)"));
assert.ok(handler.includes("galleryCache.thumbnailFailed.add(id)"));
diff --git a/tests/studio/playwright_gallery_strip_renders.py b/tests/studio/playwright_gallery_strip_renders.py
new file mode 100644
index 00000000000..8e943dbc096
--- /dev/null
+++ b/tests/studio/playwright_gallery_strip_renders.py
@@ -0,0 +1,321 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Render counts while the Images and Video strips page in and their thumbnails arrive.
+
+A thumbnail arriving or a page being appended must re-render only the cards it changes, not the
+actions menu of every card already in the strip. Then a card from a later page is deleted through
+its own menu, which must remove that card and only that card. Counts come from a React DevTools
+hook installed before the page loads, using DevTools' rule for which fibers rendered.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import struct
+import sys
+import zlib
+from pathlib import Path
+from urllib.parse import parse_qs, urlparse
+
+from playwright.sync_api import sync_playwright
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _playwright_robust import ( # noqa: E402
+ chromium_launch_args,
+ start_vite,
+ stop_process,
+ wait_for_smoke_page,
+)
+
+PORT = int(os.environ.get("SMOKE_PORT", "5219"))
+_EXTERNAL = os.environ.get("SMOKE_BASE_URL", "").strip().rstrip("/")
+BASE = _EXTERNAL or f"http://127.0.0.1:{PORT}"
+# Six pages of 50, so the strip appends five times while thumbnails stream in.
+ITEMS = 300
+
+RENDER_COUNTER = r"""
+(() => {
+ window.__renders = null;
+ const nameOf = (fiber) => {
+ const type = fiber.type;
+ if (!type) return null;
+ if (fiber.tag === 0 || fiber.tag === 1 || fiber.tag === 15) return type.displayName || type.name || null;
+ if (fiber.tag === 11) return type.displayName || type.render?.displayName || type.render?.name || null;
+ if (fiber.tag === 14) return type.displayName || type.type?.displayName || type.type?.name || null;
+ return null;
+ };
+ const walk = (fiber, counts) => {
+ // Children that were not cloned this commit were not visited by React.
+ if (fiber.alternate && fiber.alternate.child === fiber.child) return;
+ for (let child = fiber.child; child; child = child.sibling) {
+ const name = nameOf(child);
+ // PerformedWork (1) is set only on fibers whose component function ran this commit.
+ if (name && child.alternate && (child.flags & 1)) counts[name] = (counts[name] || 0) + 1;
+ walk(child, counts);
+ }
+ };
+ window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
+ supportsFiber: true,
+ isDisabled: false,
+ renderers: new Map(),
+ inject(renderer) { const id = this.renderers.size + 1; this.renderers.set(id, renderer); return id; },
+ checkDCE() {},
+ onScheduleFiberRoot() {},
+ onCommitFiberUnmount() {},
+ onPostCommitFiberRoot() {},
+ onCommitFiberRoot(_id, root) {
+ if (window.__renders) walk(root.current, window.__renders);
+ },
+ };
+})();
+"""
+
+
+def info(message: str) -> None:
+ print(f"[gallery-strip-renders] {message}", flush = True)
+
+
+def _png() -> bytes:
+ rows = b"".join(b"\x00" + bytes((x * 16) % 256 for x in range(8 * 3)) for _ in range(8))
+
+ def chunk(tag: bytes, data: bytes) -> bytes:
+ body = tag + data
+ return (
+ struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF)
+ )
+
+ return (
+ b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(rows))
+ + chunk(b"IEND", b"")
+ )
+
+
+PNG = _png()
+
+
+def _image(i: int) -> dict:
+ return {
+ "id": f"img{i:05d}",
+ "url": f"/api/inference/images/gallery/file/img{i:05d}.png",
+ "prompt": f"prompt number {i}",
+ "negative_prompt": None,
+ "width": 1024,
+ "height": 1024,
+ "steps": 4,
+ "guidance": 0.0,
+ "seed": i,
+ "batch_index": 0,
+ "batch_size": 1,
+ "model": "stabilityai/sdxl-turbo",
+ "created_at": 1760000000 - i,
+ }
+
+
+def _video(i: int) -> dict:
+ return {
+ "id": f"vid{i:05d}",
+ "url": f"/api/inference/video/gallery/file/vid{i:05d}.mp4",
+ "prompt": f"clip {i}",
+ "negative_prompt": None,
+ "width": 832,
+ "height": 480,
+ "num_frames": 33,
+ "fps": 16,
+ "duration_s": 2.0,
+ "steps": 4,
+ "guidance": 1.0,
+ "seed": i,
+ "has_audio": False,
+ "model": "Wan-AI/Wan2.1-T2V-1.3B",
+ "created_at": 1760000000 - i,
+ }
+
+
+class MockApi:
+ """Paged galleries that honour deletes, so a refill after a delete sees the shorter shelf."""
+
+ def __init__(self) -> None:
+ self.images = [_image(i) for i in range(ITEMS)]
+ self.videos = [_video(i) for i in range(ITEMS)]
+ self.deleted: list[str] = []
+
+ def handle(self, route) -> None:
+ request = route.request
+ parsed = urlparse(request.url)
+ path, query = parsed.path, parse_qs(parsed.query)
+
+ def page(items: list[dict], key: str) -> None:
+ if query.get("archived", ["false"])[0] == "true":
+ return self._json(route, {key: [], "has_more": False})
+ offset = int(query.get("offset", ["0"])[0])
+ limit = int(query.get("limit", ["50"])[0])
+ chunk = items[offset : offset + limit]
+ self._json(route, {key: chunk, "has_more": offset + limit < len(items)})
+
+ if path == "/api/auth/status":
+ return self._json(
+ route,
+ {
+ "initialized": True,
+ "requires_password_change": False,
+ "login_mode": "single",
+ "full_access": True,
+ },
+ )
+ if path == "/api/system/hardware":
+ return self._json(
+ route, {"video_supported": True, "gpu": {"gpu_name": "Mock", "vram_total_gb": 24}}
+ )
+ if path.startswith("/api/inference/images/gallery/file/") or path.startswith("/v1/videos/"):
+ return route.fulfill(status = 200, content_type = "image/png", body = PNG)
+ for prefix, items, key in (
+ ("/api/inference/images/gallery", self.images, "images"),
+ ("/api/inference/video/gallery", self.videos, "videos"),
+ ):
+ if path == prefix and request.method == "GET":
+ return page(items, key)
+ if path.startswith(prefix + "/") and request.method == "DELETE":
+ item_id = path.rsplit("/", 1)[1]
+ self.deleted.append(item_id)
+ items[:] = [item for item in items if item["id"] != item_id]
+ return self._json(route, {})
+ route.fulfill(status = 404, content_type = "application/json", body = "{}")
+
+ @staticmethod
+ def _json(route, payload: dict) -> None:
+ route.fulfill(status = 200, content_type = "application/json", body = json.dumps(payload))
+
+
+# A card's menu renders about twice as it pages in (once settling after mount, once when its
+# thumbnail lands). Re-rendering every card per page append or per thumbnail is many times this.
+MENU_RENDER_BOUND = 4 * ITEMS
+
+
+def open_strip(page, route: str, tiles: str) -> None:
+ page.goto(f"{BASE}{route}", timeout = 120_000)
+ page.wait_for_function(
+ f"() => document.querySelectorAll('{tiles}').length >= 50", timeout = 120_000
+ )
+ page.wait_for_function(
+ f"() => document.querySelectorAll('{tiles} img').length >= 10", timeout = 60_000
+ )
+
+
+def check_strip(page, api: MockApi, *, route: str, tile_attr: str, noun: str, victim: str) -> int:
+ tiles = f"[{tile_attr}]"
+ open_strip(page, route, tiles)
+ page.wait_for_timeout(1000)
+ page.evaluate("() => { window.__renders = {}; }")
+ for _ in range(600):
+ count, left = page.evaluate(
+ f"""() => {{
+ const strip = document.querySelector('{tiles}')?.parentElement;
+ if (!strip) return [0, 1];
+ strip.scrollLeft += 600;
+ return [document.querySelectorAll('{tiles}').length,
+ strip.scrollWidth - strip.scrollLeft - strip.clientWidth];
+ }}"""
+ )
+ page.wait_for_timeout(30)
+ if count >= ITEMS and left < 2:
+ break
+ page.wait_for_timeout(1000)
+ counts = page.evaluate(
+ "() => { const c = window.__renders; window.__renders = null; return c; }"
+ )
+ # A reload mid-measure (vite re-optimizing dependencies) resets the counter to null.
+ assert counts is not None, f"{route}: the page reloaded while it was being measured"
+ total = page.evaluate(f"() => document.querySelectorAll('{tiles}').length")
+ loaded = page.evaluate(f"() => document.querySelectorAll('{tiles} img').length")
+ menus = counts.get("GalleryItemMenu", 0)
+ info(
+ json.dumps({"route": route, "tiles": total, "thumbnails": loaded, "GalleryItemMenu": menus})
+ )
+ # Fails the run, not the bound, when the strip never paged or nothing loaded.
+ assert total == ITEMS, f"{route}: the strip shows {total} of {ITEMS} items after scrolling"
+ assert loaded >= 50, f"{route}: only {loaded} thumbnails loaded, so little was measured"
+ # A card from the last page, after five appends: its own menu must delete it and only it.
+ card = page.locator(f"[{tile_attr}='{victim}']")
+ card.scroll_into_view_if_needed()
+ card.get_by_role("button", name = f"More actions for this {noun}").click()
+ page.get_by_role("menuitem", name = "Delete").click()
+ page.wait_for_function(
+ f"() => !document.querySelector(\"[{tile_attr}='{victim}']\")", timeout = 30_000
+ )
+ page.wait_for_timeout(500)
+ assert api.deleted[-1:] == [
+ victim
+ ], f"{route}: the menu deleted {api.deleted[-1:]}, not {victim}"
+ left = page.evaluate(f"() => document.querySelectorAll('{tiles}').length")
+ assert left == ITEMS - 1, f"{route}: {left} cards left after deleting one of {ITEMS}"
+ return menus
+
+
+def main() -> int:
+ proc = None
+ try:
+ if not _EXTERNAL:
+ proc = start_vite(PORT)
+ wait_for_smoke_page(f"{BASE}/images", "/src/main.tsx", proc = proc, info = info)
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch(headless = True, args = chromium_launch_args())
+ try:
+ api = MockApi()
+ context = browser.new_context(viewport = {"width": 1280, "height": 900})
+ context.add_init_script(
+ "localStorage.setItem('unsloth_auth_token','x.eyJleHAiOjk5OTk5OTk5OTl9.y');"
+ "localStorage.setItem('unsloth_auth_refresh_token','r');"
+ )
+ context.add_init_script(RENDER_COUNTER)
+ context.route(
+ lambda url: urlparse(url).path.startswith(("/api/", "/v1/")), api.handle
+ )
+ page = context.new_page()
+ errors: list[str] = []
+ page.on("pageerror", lambda error: errors.append(str(error)))
+ # A first visit to each page lets the dev server finish optimizing dependencies, whose
+ # reload would otherwise land in the middle of a measurement.
+ open_strip(page, "/images", "[data-image-id]")
+ open_strip(page, "/video", "[data-clip-id]")
+ page.wait_for_timeout(2000)
+ menus = {
+ "/images": check_strip(
+ page,
+ api,
+ route = "/images",
+ tile_attr = "data-image-id",
+ noun = "image",
+ victim = "img00287",
+ ),
+ "/video": check_strip(
+ page,
+ api,
+ route = "/video",
+ tile_attr = "data-clip-id",
+ noun = "video",
+ victim = "vid00287",
+ ),
+ }
+ finally:
+ browser.close()
+ # Endpoints this check does not mock answer 404, which the app reports and moves past.
+ unexpected = [error for error in errors if not error.startswith("Request failed (404)")]
+ assert not unexpected, unexpected
+ over = {route: count for route, count in menus.items() if count > MENU_RENDER_BOUND}
+ assert not over, (
+ f"card menus rendered {over} times while {ITEMS} cards paged in (bound "
+ f"{MENU_RENDER_BOUND}): a thumbnail or page append is re-rendering every card"
+ )
+ info("ok")
+ return 0
+ finally:
+ if proc is not None:
+ stop_process(proc)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index f057cc5cf54..1239ef4a6e6 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -1999,7 +1999,10 @@ def test_video_gallery_fetches_clips_as_their_cards_come_into_view():
"""Cards show stills; only the selected clip mints a playback link, avoiding a pipeline per clip."""
src = _read("features/video/video-page.tsx")
assert "new IntersectionObserver(" in src
- assert "ref={stripRef}" in src and "data-clip-id={video.id}" in src
+ assert "ref={stripRef}" in src
+ # The card is the memoized VideoStripTile, which tags itself with its own video's id.
+ tile = src[src.index("const VideoStripTile = memo(") :]
+ assert "const id = video.id;" in tile and "data-clip-id={id}" in tile
assert 'root.querySelectorAll("[data-clip-id]")' in src
# rootMargin applies to the root box only, so the clipping strip must BE the root.
assert '{ root, rootMargin: "0px 600px" }' in src