Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(gallery): complete mixed media boards and uploads

joshistoast168957451f01
diff --git a/.superpowers/sdd/mixed-media-gallery-parity/task-10-report.md b/.superpowers/sdd/mixed-media-gallery-parity/task-10-report.md
new file mode 100644
index 0000000000..5833cff0a4
--- /dev/null
+++ b/.superpowers/sdd/mixed-media-gallery-parity/task-10-report.md
@@ -0,0 +1,217 @@
+# Task 10 Report: Boards, mixed upload, and i18n completion
+
+## Status
+
+Complete.
+
+Board rows now count images and videos together while preserving the separate
+asset count, expose a localized image/video breakdown, and mark static video
+covers with a decorative Play glyph. Board deletion confirmation and outcome
+messages include both media kinds, and the existing image-only archive wording
+uses the board's exact video count through localized plural forms.
+
+Gallery upload now classifies PNG, JPEG/JPG, WebP, and MP4 files by MIME first
+with the established extension fallback. Images retain concurrent upload
+behavior and the user category; videos upload one at a time as durable general
+media. Date boards reject before transport, synthetic board IDs never reach
+either upload route, partial failures do not stop later files, and one summary
+reports the complete settled outcome. The newest successful upload visible in
+the active board/view becomes the canonical selection.
+
+The compact gallery status and remaining mixed-media gallery/Preview labels
+are catalog-backed. Gallery/video `defaultValue` fallbacks were removed now
+that their English keys exist.
+
+## TDD evidence
+
+All frontend commands ran from `invokeai/frontend/webv2`.
+
+### Upload classifier and transports
+
+The first backend RED was:
+
+```sh
+pnpm test src/features/gallery/data/backend.test.ts
+```
+
+```text
+Test Files 1 failed (1)
+Tests 19 failed | 40 passed (59)
+```
+
+It proved the named classifier and video transport were absent and that the
+image upload still leaked the synthetic `all` board ID. After implementation,
+the focused file passed all 59 tests.
+
+### Board projection and presentation
+
+Adding `videoCount` to the board-count contract first failed one of 24 state
+projection tests. The focused file passed after `getBoardCounts()` returned
+all three counts.
+
+The new board browser contract initially failed both cases because the
+mixed-total/tooltip surface and exported existing cover seam were absent. It
+then passed 2/2 with:
+
+- video-only `5 | 2` rendering;
+- tabular numerals;
+- localized image/video tooltip content;
+- a decorative Play glyph over the static thumbnail;
+- no board-list `<video>`.
+
+The board-menu RED failed 2/2 against the image-only confirmation and
+hardcoded archive label. It passed 2/2 after image/video/asset confirmation
+counts, media-aware deletion wording, and localized omission text landed.
+
+### Settled mixed upload and delete outcomes
+
+The first consolidated action RED was:
+
+```text
+Test Files 1 failed (1)
+Tests 6 failed | 2 passed (8)
+```
+
+Those failures covered authoritative board-delete notifications, date-board
+pre-transport rejection, concurrent images plus sequential videos, continuation
+after per-file failure, one partial mixed summary, unsupported files, and
+newest visible selection. The file passed 8/8 after implementation.
+
+A follow-up account-lifetime regression then failed because the second video
+was scheduled after the first request aborted:
+
+```text
+Test Files 1 failed (1)
+Tests 1 failed | 8 passed (9)
+```
+
+The sequential worker now checks the captured account signal before every
+video and escalates account abort instead of treating it as a file-local
+failure. The file then passed 9/9.
+
+### Status and catalog
+
+The compact status browser test first failed because `GalleryStatusChip` did
+not exist; it passed after the component rendered
+`widgets.gallery.statusChip`.
+
+The English catalog test first failed on the missing status key. It now
+resolves and interpolates status, image/video/asset counts, board omissions
+and outcomes, mixed upload/split, playback/retry, frame copy, and video Details
+keys. It also exercises plural-safe composed media counts.
+
+## Implementation
+
+### Boards
+
+- `getBoardCounts()` returns image, video, and asset counts.
+- Board badges render `(imageCount + videoCount) | assetCount` with tabular
+ numerals.
+- The badge trigger and tooltip share the localized image/video breakdown.
+- A video cover remains a static poster and gains only a decorative Play
+ overlay.
+- Delete confirmation shows images, videos, and assets; completed deletion
+ messages use the backend's authoritative confirmed/failed arrays.
+
+### Upload
+
+- `classifyGalleryUpload()` recognizes only PNG, JPEG/JPG, WebP, and MP4.
+ Supported MIME wins; otherwise the established filename-extension fallback
+ handles empty, generic, or misreported MIME.
+- Both image and video transports omit `none`, `all`, and date-board IDs.
+- Image upload stays `image_category=user`, preserves current concurrency, and
+ remains strictly `GalleryImage`.
+- Video upload is `video_category=general`, `is_intermediate=false`, maps to
+ `GalleryVideoItem`, and runs sequentially.
+- Images and the sequential video lane run independently. Per-file failures
+ settle, unsupported files contribute to the failed total, and one localized
+ notification summarizes the batch.
+- Account expiry stops the video lane before another expensive request.
+- Selection is canonical and restricted to successful media visible in the
+ captured active board/view.
+
+### i18n
+
+- Replaced the hardcoded compact `Gallery: {total}` chip.
+- Added pluralized image/video/asset counts, board archive/deletion outcomes,
+ mixed upload results/split, and partial item-mutation/download messages.
+- Generalized upload/search/drop/window copy from images to gallery items or
+ media where appropriate.
+- Removed gallery/video `defaultValue` fallbacks from mixed item actions and
+ Preview video labels.
+
+## Full verification
+
+```sh
+pnpm lint
+```
+
+```text
+format: passed
+OXC: passed
+tsc --noEmit: passed
+architecture: 3 files, 34 tests passed
+```
+
+```sh
+pnpm exec vitest run --config vitest.config.mts --reporter=dot
+```
+
+```text
+Test Files 376 passed (376)
+Tests 5005 passed (5005)
+```
+
+```sh
+pnpm test:browser
+```
+
+The first full run hit the repository's known timing-sensitive
+`src/platform/ui/Tabs.browser.test.tsx` timeout. The focused Tabs file passed
+1/1, and the required complete rerun passed:
+
+```text
+Test Files 69 passed (69)
+Tests 345 passed (345)
+```
+
+The browser suite retained existing non-failing React `act(...)`,
+missing-i18n-instance, and intentional error-boundary diagnostics.
+
+```sh
+pnpm test:fixtures
+```
+
+```text
+Tests 4 passed (4)
+```
+
+## Source-policy checks
+
+- `GeneratedImageContract` and `core/types.ts` are unchanged.
+- `GalleryImage` and the image upload result remain strict image-only
+ contracts.
+- No production module or existing file rename was added.
+- No `useEffect`, migration exception, mock fixture, accessibility exception,
+ or performance baseline was added.
+- The only production `<video>` remains in `PreviewFrame.tsx`.
+- No new file imports the `@platform/ui` barrel; the existing board-select
+ importer only adds `Tooltip`.
+- Scoped gallery/Preview/image-action translation calls contain no
+ `defaultValue` fallback.
+- `git diff --check` passed.
+
+## Independent review
+
+The independent read-only review approved the uncommitted Task 10 diff with no
+Critical, Important, or Minor findings. It explicitly checked the board
+outcomes, classifier fallback rules, image/video concurrency, date/synthetic
+board handling, settled summary, visible-newest selection, i18n completion,
+tests, and global architecture invariants.
+
+## Task 11 dependencies
+
+Task 11 still owns additive mock-backend videos and media assets/routes,
+Range/HEAD fixture behavior, mixed mock ordering/filtering, and the dedicated
+video accessibility journey with its narrowly scoped caption-rule exception.
+No Task 11 or Task 12 baseline work was included here.
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 110e5dae74..7fb44a32b2 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2058,13 +2058,22 @@
"gallery": {
"alwaysShowDimensions": "Always show dimensions",
"archiveBoard": "Archive Board",
+ "assetCount_one": "{{count}} asset",
+ "assetCount_other": "{{count}} assets",
"boardActionsForBoard": "Board actions for {{name}}",
+ "boardArchivePreparing_one": "Preparing an image archive of \"{{name}}\". {{count}} video will be omitted.",
+ "boardArchivePreparing_other": "Preparing an image archive of \"{{name}}\". {{count}} videos will be omitted.",
+ "boardArchived": "Archived board \"{{name}}\"",
+ "boardCreated": "Created board \"{{name}}\"",
"boardGroups": {
"boards": "Boards",
"byDate": "By Date"
},
- "boardItemCounts": "{{images}} images | {{assets}} assets",
+ "boardItemCounts": "{{images}} · {{videos}} · {{assets}}",
+ "boardMediaCountBreakdown": "{{images}} · {{videos}}",
"boardName": "Board name",
+ "boardRenamed": "Renamed board to \"{{name}}\"",
+ "boardUnarchived": "Unarchived board \"{{name}}\"",
"commands": {
"clearSelection": "Clear gallery selection",
"deleteSelection": "Delete gallery selection",
@@ -2082,30 +2091,75 @@
"dateFilterRange": "{{from}} – {{to}}",
"dateFilterThrough": "Through {{date}}",
"deleteBoard": "Delete Board",
- "deleteBoardAndImages": "Delete Board and Images",
- "deleteBoardDescription": "Deleted boards cannot be restored. Choose whether the board's images move to Uncategorized or are permanently deleted with it.",
+ "deleteBoardAndMedia": "Delete Board and Media",
+ "deleteBoardDescription": "Deleted boards cannot be restored. Choose whether the board's media moves to Uncategorized or is permanently deleted with it.",
+ "deleteBoardMediaOutcome": "Deleted {{images}} and {{videos}}; {{failedImages}} and {{failedVideos}} could not be deleted.",
+ "deleteBoardMoveOutcome": "Moved {{images}} and {{videos}} to Uncategorized.",
"deleteBoardOnly": "Delete Board Only",
+ "deleteBoardPartialTitle": "Deleted board \"{{name}}\" with partial media cleanup",
"deleteBoardQuestion": "Delete board \"{{name}}\"?",
+ "deleteBoardSuccessTitle": "Deleted board \"{{name}}\"",
"downloadBoard": "Download Board",
- "dropImagesToUploadToBoard": "Drop images to upload to {{name}}",
+ "downloadBoardWithOmission_one": "Download Board ({{count}} video omitted)",
+ "downloadBoardWithOmission_other": "Download Board ({{count}} videos omitted)",
+ "downloadReady": "Download ready",
+ "dropMediaToUploadToBoard": "Drop images or videos to upload to {{name}}",
"generationProgress": "Generation progress",
"generationProgressPercent": "Generation {{percentage}}%",
"hideArchivedBoards": "Hide archived boards",
"hideDateBoards": "Hide date boards",
"imageDensity": "Image density",
+ "imageCount_one": "{{count}} image",
+ "imageCount_other": "{{count}} images",
"imageSort": "Image Sort",
"itemsAriaLabel": "Gallery items",
"infinite": "Infinite",
+ "itemActions": {
+ "delete": {
+ "failure_one": "Could not delete {{count}} item.",
+ "failure_other": "Could not delete {{count}} items.",
+ "partial": "{{succeeded}} of {{count}} items were deleted; {{failed}} failed.",
+ "success_one": "Deleted {{count}} item.",
+ "success_other": "Deleted {{count}} items."
+ },
+ "download": {
+ "partial": "{{succeeded}} of {{count}} items downloaded; {{failed}} failed or were skipped.",
+ "success": "Download ready"
+ },
+ "move": {
+ "failure_one": "Could not move {{count}} item to {{board}}.",
+ "failure_other": "Could not move {{count}} items to {{board}}.",
+ "partial": "{{succeeded}} of {{count}} items moved to {{board}}; {{failed}} failed.",
+ "success_one": "Moved {{count}} item to {{board}}.",
+ "success_other": "Moved {{count}} items to {{board}}."
+ },
+ "star": {
+ "failure_one": "Could not star {{count}} item.",
+ "failure_other": "Could not star {{count}} items.",
+ "partial": "{{succeeded}} of {{count}} items starred; {{failed}} failed.",
+ "success_one": "Starred {{count}} item.",
+ "success_other": "Starred {{count}} items."
+ },
+ "unstar": {
+ "failure_one": "Could not unstar {{count}} item.",
+ "failure_other": "Could not unstar {{count}} items.",
+ "partial": "{{succeeded}} of {{count}} items unstarred; {{failed}} failed.",
+ "success_one": "Unstarred {{count}} item.",
+ "success_other": "Unstarred {{count}} items."
+ }
+ },
"loadingBackendGallery": "Loading backend gallery...",
"loadingBoard": "Loading board...",
"newest": "Newest",
"noBoardsMatchSearch": "No boards match this search.",
- "noImagesMatch": "No images match this board, tab, or search.",
+ "noImagesMatch": "No items match this board, tab, or search.",
"oldest": "Oldest",
"pagination": "Pagination",
+ "preparingDownload": "Preparing download",
+ "projectBoardCreated": "Created project board \"{{name}}\"",
"renameBoard": "Rename board",
- "searchImagesAriaLabel": "Search gallery images",
- "searchImagesPlaceholder": "Search images",
+ "searchImagesAriaLabel": "Search gallery items",
+ "searchImagesPlaceholder": "Search items",
"searchOrCreateBoards": "Search or create boards",
"selectImageForPreview": "Select {{name}} for preview",
"selectVideoForPreview": "Select video {{name}}, duration {{duration}}, for preview",
@@ -2126,9 +2180,21 @@
"uncategorized": "Uncategorized",
"unknownBoard": "Unknown board",
"unstarImage": "Unstar {{name}}",
- "uploadImagesToBoard": "Upload images to {{name}}",
+ "uploadDateBoardUnavailable": "Uploads are unavailable for date boards.",
+ "uploadFailed": "No files uploaded. {{failed}} failed.",
+ "uploadMediaToBoard": "Upload images or videos to {{name}}",
+ "uploadPartialTitle": "Uploaded {{succeeded}} of {{total}} files",
+ "uploadSplit": "Images appear in Assets; videos appear in Images.",
+ "uploadSuccessTitle_one": "Uploaded {{count}} file",
+ "uploadSuccessTitle_other": "Uploaded {{count}} files",
+ "uploadSummary": "{{images}} and {{videos}} uploaded to {{board}}. {{failed}} failed.",
+ "uploadUnsupported": "No supported media files to upload (PNG, JPEG, WebP, or MP4).",
"uploadsUnavailableForDateBoards": "Uploads are unavailable for date boards",
- "windowLimit": "Showing the first {{count}} images. Narrow the search or switch to Pages to reach the rest."
+ "videoCount_one": "{{count}} video",
+ "videoCount_other": "{{count}} videos",
+ "windowLimit": "Showing the first {{count}} items. Narrow the search or switch to Pages to reach the rest.",
+ "statusChip_one": "Gallery: {{count}} item",
+ "statusChip_other": "Gallery: {{count}} items"
},
"serverStatus": {
"connected": "Connected to Server",
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
index 8a6aac006e..9a166654b4 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
@@ -18,6 +18,7 @@ vi.mock('@platform/transport/http', () => ({
import {
addImagesToGalleryBoard,
+ classifyGalleryUpload,
deleteGalleryBoard,
deleteGalleryImages,
downloadGalleryArchive,
@@ -34,6 +35,8 @@ import {
removeImagesFromGalleryBoard,
starGalleryImages,
unstarGalleryImages,
+ uploadGalleryImage,
+ uploadGalleryVideo,
} from './backend';
describe('deleteGalleryBoard outcomes', () => {
@@ -760,3 +763,127 @@ describe('deleteGalleryImages partial failures', () => {
expect(mocks.apiFetchJson).not.toHaveBeenCalled();
});
});
+
+describe('classifyGalleryUpload', () => {
+ it.each([
+ ['image/png', 'photo.bin', 'image'],
+ ['image/jpeg', 'photo.bin', 'image'],
+ ['image/jpg', 'photo.bin', 'image'],
+ ['image/webp', 'photo.bin', 'image'],
+ ['video/mp4', 'clip.bin', 'video'],
+ ['', 'photo.PNG', 'image'],
+ ['application/octet-stream', 'photo.jpeg', 'image'],
+ ['binary/octet-stream', 'clip.MP4', 'video'],
+ ['application/pdf', 'photo.png', 'image'],
+ ] as const)('classifies MIME %s and name %s as %s', (type, name, kind) => {
+ expect(classifyGalleryUpload(new File(['media'], name, { type }))).toEqual({ kind });
+ });
+
+ it.each([
+ ['application/pdf', 'document.pdf'],
+ ['', 'archive.zip'],
+ ['video/webm', 'clip.webm'],
+ ['image/gif', 'animation.gif'],
+ ] as const)('rejects unsupported MIME %s and name %s', (type, name) => {
+ expect(classifyGalleryUpload(new File(['media'], name, { type }))).toBeNull();
+ });
+
+ it('uses a supported MIME before a conflicting extension', () => {
+ expect(classifyGalleryUpload(new File(['media'], 'looks-like-video.mp4', { type: 'image/png' }))).toEqual({
+ kind: 'image',
+ });
+ });
+});
+
+describe('gallery uploads', () => {
+ beforeEach(() => {
+ accountLifecycle.activate('user-a');
+ mocks.apiFetchJson.mockReset();
+ });
+
+ it('uploads images as user assets and never sends a synthetic board id', async () => {
+ mocks.apiFetchJson.mockResolvedValue({
+ board_id: null,
+ created_at: '2026-07-30T12:00:00.000Z',
+ height: 64,
+ image_category: 'user',
+ image_name: 'photo.png',
+ image_url: '/images/photo.png',
+ is_intermediate: false,
+ starred: false,
+ thumbnail_url: '/thumbnails/photo.webp',
+ width: 64,
+ });
+
+ await uploadGalleryImage(new File(['image'], 'photo.png', { type: 'image/png' }), 'all');
+
+ const [url, init] = mocks.apiFetchJson.mock.calls[0] as [string, RequestInit];
+ const query = new URLSearchParams(url.split('?')[1]);
+ expect(url.split('?')[0]).toBe('/api/v1/images/upload');
+ expect(query.get('image_category')).toBe('user');
+ expect(query.get('is_intermediate')).toBe('false');
+ expect(query.has('board_id')).toBe(false);
+ expect(init.method).toBe('POST');
+ expect(init.body).toBeInstanceOf(FormData);
+ });
+
+ it('uploads videos as durable general media to a real board', async () => {
+ const controller = new AbortController();
+ mocks.apiFetchJson.mockResolvedValue({
+ board_id: 'board-1',
+ created_at: '2026-07-30T12:00:00.000Z',
+ duration: 4.2,
+ fps: 24,
+ height: 360,
+ is_intermediate: false,
+ starred: false,
+ thumbnail_url: '/videos/clip.webp',
+ video_category: 'general',
+ video_name: 'clip.mp4',
+ video_url: '/videos/clip.mp4',
+ width: 640,
+ });
+
+ await expect(
+ uploadGalleryVideo(new File(['video'], 'clip.mp4', { type: 'video/mp4' }), 'board-1', {
+ signal: controller.signal,
+ })
+ ).resolves.toMatchObject({
+ boardId: 'board-1',
+ category: 'general',
+ durationSeconds: 4.2,
+ kind: 'video',
+ name: 'clip.mp4',
+ });
+
+ const [url, init] = mocks.apiFetchJson.mock.calls[0] as [string, RequestInit];
+ const query = new URLSearchParams(url.split('?')[1]);
+ expect(url.split('?')[0]).toBe('/api/v1/videos/upload');
+ expect(query.get('video_category')).toBe('general');
+ expect(query.get('is_intermediate')).toBe('false');
+ expect(query.get('board_id')).toBe('board-1');
+ expect(init).toMatchObject({ method: 'POST', signal: controller.signal });
+ expect(init.body).toBeInstanceOf(FormData);
+ });
+
+ it.each(['none', 'all', 'by_date:2026-07-30'])('omits synthetic board %s from video uploads', async (boardId) => {
+ mocks.apiFetchJson.mockResolvedValue({
+ board_id: null,
+ created_at: '2026-07-30T12:00:00.000Z',
+ duration: 4,
+ height: 360,
+ is_intermediate: false,
+ starred: false,
+ thumbnail_url: '/videos/clip.webp',
+ video_category: 'general',
+ video_name: 'clip.mp4',
+ video_url: '/videos/clip.mp4',
+ width: 640,
+ });
+
+ await uploadGalleryVideo(new File(['video'], 'clip.mp4', { type: 'video/mp4' }), boardId);
+
+ const url = mocks.apiFetchJson.mock.calls[0]?.[0] as string;
+ expect(new URLSearchParams(url.split('?')[1]).has('board_id')).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index b157086e1f..72d0de1e65 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -64,6 +64,45 @@ export const isDateBoardId = (boardId: string): boolean => boardId.startsWith(DA
const getDateFromBoardId = (boardId: string): string => boardId.slice(DATE_BOARD_ID_PREFIX.length);
+const getUploadBoardId = (boardId: string): string | undefined =>
+ boardId === 'none' || boardId === ALL_READABLE_BOARDS_ID || isDateBoardId(boardId) ? undefined : boardId;
+
+export type GalleryUploadKind = 'image' | 'video';
+
+const GALLERY_UPLOAD_KIND_BY_MIME = new Map<string, GalleryUploadKind>([
+ ['image/jpeg', 'image'],
+ ['image/jpg', 'image'],
+ ['image/png', 'image'],
+ ['image/webp', 'image'],
+ ['video/mp4', 'video'],
+]);
+
+const GALLERY_UPLOAD_KIND_BY_EXTENSION = new Map<string, GalleryUploadKind>([
+ ['.jpeg', 'image'],
+ ['.jpg', 'image'],
+ ['.png', 'image'],
+ ['.webp', 'image'],
+ ['.mp4', 'video'],
+]);
+
+export const classifyGalleryUpload = (file: Pick<File, 'name' | 'type'>): { kind: GalleryUploadKind } | null => {
+ const mimeKind = GALLERY_UPLOAD_KIND_BY_MIME.get(file.type.toLowerCase());
+
+ if (mimeKind) {
+ return { kind: mimeKind };
+ }
+
+ const lowerName = file.name.toLowerCase();
+
+ for (const [extension, kind] of GALLERY_UPLOAD_KIND_BY_EXTENSION) {
+ if (lowerName.endsWith(extension)) {
+ return { kind };
+ }
+ }
+
+ return null;
+};
+
interface BackendImageDTO {
image_name: string;
image_url: string;
@@ -1320,7 +1359,7 @@ export const uploadGalleryImage = async (
options: { isIntermediate?: boolean; signal?: AbortSignal } = {}
): Promise<GalleryImage> => {
const query = toSearchParams({
- board_id: boardId === 'none' || isDateBoardId(boardId) ? undefined : boardId,
+ board_id: getUploadBoardId(boardId),
image_category: 'user',
is_intermediate: options.isIntermediate ?? false,
});
@@ -1335,3 +1374,25 @@ export const uploadGalleryImage = async (
return mapImage(uploadedImage);
};
+
+export const uploadGalleryVideo = async (
+ file: File,
+ boardId: string,
+ options: { signal?: AbortSignal } = {}
+): Promise<GalleryVideoItem> => {
+ const query = toSearchParams({
+ board_id: getUploadBoardId(boardId),
+ is_intermediate: false,
+ video_category: 'general',
+ });
+ const body = new FormData();
+ body.append('file', file);
+
+ const uploadedVideo = await apiFetchJson<BackendVideoDTO>(`/api/v1/videos/upload?${query}`, {
+ body,
+ method: 'POST',
+ signal: options.signal,
+ });
+
+ return mapVideo(uploadedVideo);
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
index 5056bc88bb..a83e9ff039 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
@@ -4,6 +4,7 @@ import { system } from '@theme/system';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
import type { GalleryWidgetContextValue } from './GalleryWidgetContext';
@@ -12,12 +13,25 @@ import { GalleryWidgetContext } from './GalleryWidgetContext';
vi.mock('react-i18next', () => ({
useTranslation: () => ({
- t: (key: string) =>
- (
- ({
- 'widgets.gallery.downloadBoard': 'Download Board',
- }) as Record<string, string>
- )[key] ?? key,
+ t: (key: string, values?: Record<string, unknown>) => {
+ const messages: Record<string, string> = {
+ 'widgets.gallery.assetCount': `${String(values?.count)} assets`,
+ 'common.cancel': 'Cancel',
+ 'widgets.gallery.boardItemCounts': `${String(values?.images)} · ${String(values?.videos)} · ${String(
+ values?.assets
+ )}`,
+ 'widgets.gallery.deleteBoard': 'Delete Board',
+ 'widgets.gallery.deleteBoardAndMedia': 'Delete Board and Media',
+ 'widgets.gallery.deleteBoardDescription': 'Choose whether the board media moves or is deleted.',
+ 'widgets.gallery.deleteBoardOnly': 'Delete Board Only',
+ 'widgets.gallery.deleteBoardQuestion': `Delete board "${String(values?.name)}"?`,
+ 'widgets.gallery.downloadBoardWithOmission': `Download Board (${String(values?.count)} video omitted)`,
+ 'widgets.gallery.imageCount': `${String(values?.count)} images`,
+ 'widgets.gallery.videoCount': `${String(values?.count)} videos`,
+ };
+
+ return messages[key] ?? key;
+ },
}),
}));
@@ -75,3 +89,17 @@ afterEach(async () => {
it('states the exact number of videos omitted from the image-only board archive', () => {
expect(document.body.textContent).toContain('Download Board (1 video omitted)');
});
+
+it('shows image, video, and asset counts before deleting a mixed-media board', async () => {
+ const deleteItem = Array.from(document.querySelectorAll('[role="menuitem"]')).find(
+ (element) => element.textContent === 'Delete Board'
+ );
+
+ expect(deleteItem).toBeDefined();
+ await act(() => userEvent.click(deleteItem as HTMLElement));
+
+ await vi.waitFor(() => {
+ expect(document.body.textContent).toContain('2 images · 1 videos · 0 assets');
+ });
+ expect(document.body.textContent).toContain('Delete Board and Media');
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
index 0680427da6..94ca5db917 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
@@ -207,8 +207,9 @@ export const GalleryBoardMenu = ({
</Text>
<Text color="fg.subtle" fontSize="2xs">
{t('widgets.gallery.boardItemCounts', {
- assets: deleteTarget?.assetCount ?? 0,
- images: deleteTarget?.imageCount ?? 0,
+ assets: t('widgets.gallery.assetCount', { count: deleteTarget?.assetCount ?? 0 }),
+ images: t('widgets.gallery.imageCount', { count: deleteTarget?.imageCount ?? 0 }),
+ videos: t('widgets.gallery.videoCount', { count: deleteTarget?.videoCount ?? 0 }),
})}
</Text>
</Stack>
@@ -221,7 +222,7 @@ export const GalleryBoardMenu = ({
{t('widgets.gallery.deleteBoardOnly')}
</Button>
<Button colorPalette="red" size="xs" onClick={handleDeleteBoardAndImages}>
- {t('widgets.gallery.deleteBoardAndImages')}
+ {t('widgets.gallery.deleteBoardAndMedia')}
</Button>
</Dialog.Footer>
</Dialog.Content>
@@ -236,12 +237,11 @@ const BoardDownloadMenuItem = ({ board }: { board: GalleryBoard }) => {
const { t } = useTranslation();
const { actions } = useGalleryWidget();
const handleClick = useCallback(() => void actions.downloadBoard(board.id), [actions, board.id]);
- const omittedVideos = `${board.videoCount} ${board.videoCount === 1 ? 'video' : 'videos'} omitted`;
return (
<BoardMenuItem
icon={DownloadIcon}
- label={`${t('widgets.gallery.downloadBoard')} (${omittedVideos})`}
+ label={t('widgets.gallery.downloadBoardWithOmission', { count: board.videoCount })}
value="download-board"
onClick={handleClick}
/>
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.browser.test.tsx
new file mode 100644
index 0000000000..06c6ed8db3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.browser.test.tsx
@@ -0,0 +1,96 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { BoardCover, BoardOptionContent } from './GalleryBoardSelect';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: Record<string, unknown>) => {
+ if (key === 'widgets.gallery.imageCount') {
+ return `${String(values?.count)} images`;
+ }
+ if (key === 'widgets.gallery.videoCount') {
+ return `${String(values?.count)} videos`;
+ }
+ if (key === 'widgets.gallery.boardMediaCountBreakdown') {
+ return `${String(values?.images)} · ${String(values?.videos)}`;
+ }
+
+ return key;
+ },
+ }),
+}));
+
+const board = {
+ archived: false,
+ assetCount: 2,
+ coverImageName: null,
+ coverThumbnailUrl: 'data:image/gif;base64,R0lGODlhAQABAAAAACw=',
+ coverVideoName: 'clip.mp4',
+ id: 'video-only',
+ imageCount: 0,
+ kind: 'board',
+ name: 'Video only',
+ videoCount: 5,
+} as const;
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('board mixed-media presentation', () => {
+ it('renders video-only boards with a mixed total, localized breakdown tooltip, and tabular numerals', async () => {
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <BoardOptionContent board={board} isSelected={false} />
+ </ChakraProvider>
+ )
+ );
+
+ await vi.waitFor(() => {
+ expect(document.body.textContent).toContain('5 | 2');
+ });
+
+ const countBadge = Array.from(document.querySelectorAll('[aria-label]')).find(
+ (element) => element.getAttribute('aria-label') === '0 images · 5 videos'
+ );
+
+ expect(countBadge).toBeDefined();
+ expect(countBadge ? getComputedStyle(countBadge).fontVariantNumeric : '').toContain('tabular-nums');
+ expect(countBadge?.getAttribute('data-scope')).toBe('tooltip');
+ expect(countBadge?.getAttribute('data-part')).toBe('trigger');
+ });
+
+ it('overlays a decorative play glyph on static video covers', async () => {
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <BoardCover board={board} />
+ </ChakraProvider>
+ )
+ );
+
+ await vi.waitFor(() => {
+ expect(document.querySelector('img')?.getAttribute('src')).toContain('data:image/gif');
+ });
+ expect(document.querySelector('svg[aria-hidden="true"]')).not.toBeNull();
+ expect(document.querySelector('video')).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx
index da654c65ea..b1beab526c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx
@@ -17,7 +17,7 @@ import {
} from '@chakra-ui/react';
import { useDndContext, useDndMonitor, useDroppable, type DragEndEvent, type DragStartEvent } from '@dnd-kit/core';
import { toGalleryItemKey } from '@features/gallery/core/items';
-import { Button, CloseButton, IconButton } from '@platform/ui';
+import { Button, CloseButton, IconButton, Tooltip } from '@platform/ui';
import {
ArchiveIcon,
ArrowDownAZIcon,
@@ -27,6 +27,7 @@ import {
ImageIcon,
MoreVerticalIcon,
PinIcon,
+ PlayIcon,
PlusIcon,
type LucideIcon,
SearchIcon,
@@ -566,7 +567,7 @@ const BoardRow = ({
);
};
-const BoardOptionContent = ({
+export const BoardOptionContent = ({
badge,
badgeColor = 'gray',
board,
@@ -580,7 +581,12 @@ const BoardOptionContent = ({
/** Render the owner line (admins on multi-user backends); off in the compact trigger. */
showOwner?: boolean;
}) => {
+ const { t } = useTranslation();
const counts = getBoardCounts(board);
+ const mediaCountBreakdown = t('widgets.gallery.boardMediaCountBreakdown', {
+ images: t('widgets.gallery.imageCount', { count: counts.imageCount }),
+ videos: t('widgets.gallery.videoCount', { count: counts.videoCount }),
+ });
return (
<HStack gap="2" minW="0" w="full">
@@ -601,9 +607,17 @@ const BoardOptionContent = ({
{badge}
</Badge>
)}
- <Badge flexShrink={0} size="xs" variant={isSelected ? 'solid' : 'subtle'}>
- {counts.imageCount} | {counts.assetCount}
- </Badge>
+ <Tooltip content={mediaCountBreakdown}>
+ <Badge
+ aria-label={mediaCountBreakdown}
+ flexShrink={0}
+ fontVariantNumeric="tabular-nums"
+ size="xs"
+ variant={isSelected ? 'solid' : 'subtle'}
+ >
+ {counts.imageCount + counts.videoCount} | {counts.assetCount}
+ </Badge>
+ </Tooltip>
</Flex>
</HStack>
);
@@ -625,20 +639,37 @@ const BoardCoverIcon = ({ icon }: { icon: LucideIcon }) => (
</Flex>
);
-const BoardCover = ({ board }: { board: GalleryBoard }) => {
+export const BoardCover = ({ board }: { board: GalleryBoard }) => {
if (board.coverThumbnailUrl) {
return (
- <Image
- alt=""
- bg="bg.emphasized"
- borderWidth="1px"
- borderColor="border.subtle"
- boxSize="7"
- flexShrink={0}
- objectFit="cover"
- rounded="md"
- src={board.coverThumbnailUrl}
- />
+ <Flex boxSize="7" flexShrink={0} position="relative">
+ <Image
+ alt=""
+ bg="bg.emphasized"
+ borderWidth="1px"
+ borderColor="border.subtle"
+ boxSize="7"
+ objectFit="cover"
+ rounded="md"
+ src={board.coverThumbnailUrl}
+ />
+ {board.coverVideoName ? (
+ <Flex
+ align="center"
+ aria-hidden="true"
+ bg="blackAlpha.700"
+ bottom="0.5"
+ boxSize="3"
+ color="white"
+ justify="center"
+ position="absolute"
+ right="0.5"
+ rounded="full"
+ >
+ <Icon as={PlayIcon} boxSize="2" fill="currentColor" />
+ </Flex>
+ ) : null}
+ </Flex>
);
}
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
index 69ce6e0cf0..241b34ed7f 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
@@ -630,7 +630,7 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
>
<UploadIcon size="20" />
<Text fontSize="xs" fontWeight="600">
- {t('widgets.gallery.dropImagesToUploadToBoard', { name: selectedBoardName })}
+ {t('widgets.gallery.dropMediaToUploadToBoard', { name: selectedBoardName })}
</Text>
</DropZone>
)}
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryToolbar.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryToolbar.tsx
index 29b7fcb3d7..1fd0e2fdd9 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryToolbar.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryToolbar.tsx
@@ -25,7 +25,7 @@ import { useTranslation } from 'react-i18next';
import { GalleryBoardSelect } from './GalleryBoardSelect';
import { useGalleryWidget } from './GalleryWidgetContext';
-const ACCEPTED_UPLOAD_EXTENSIONS = 'image/png,image/jpeg,image/webp';
+const ACCEPTED_UPLOAD_EXTENSIONS = 'image/png,image/jpeg,image/webp,video/mp4,.png,.jpg,.jpeg,.webp,.mp4';
const galleryViewTabs = [
{ labelKey: 'common.images', value: 'images' },
{ labelKey: 'common.assets', value: 'assets' },
@@ -233,7 +233,7 @@ const GalleryUploadButton = () => {
aria-label={
isVirtualTarget
? t('widgets.gallery.uploadsUnavailableForDateBoards')
- : t('widgets.gallery.uploadImagesToBoard', {
+ : t('widgets.gallery.uploadMediaToBoard', {
name: selectedBoard?.name ?? t('widgets.gallery.selectedBoardFallback'),
})
}
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsx
new file mode 100644
index 0000000000..93355fb0fd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsx
@@ -0,0 +1,44 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+import { GalleryStatusChip } from './GalleryWidgetView';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: Record<string, unknown>) =>
+ key === 'widgets.gallery.statusChip' ? `Gallery: ${String(values?.count)} items` : key,
+ }),
+}));
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+it('renders the compact gallery status through the localized status-chip key', async () => {
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <GalleryStatusChip count={12} />
+ </ChakraProvider>
+ )
+ );
+
+ expect(document.body.textContent).toContain('Gallery: 12 items');
+ expect(document.body.textContent).not.toContain('widgets.gallery.statusChip');
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.test.ts
index bce1cf1c02..85034f1a44 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.test.ts
@@ -1,7 +1,14 @@
+import i18n from 'i18next';
import { describe, expect, it } from 'vitest';
import { shouldPublishGalleryTotal } from './GalleryWidgetView';
+const englishCatalogModules = import.meta.glob('../../../../public/locales/en.json', {
+ eager: true,
+ import: 'default',
+});
+const englishCatalog = Object.values(englishCatalogModules)[0] as Record<string, unknown>;
+
describe('shouldPublishGalleryTotal', () => {
it('publishes finite totals that differ from known state and have not already been published', () => {
expect(shouldPublishGalleryTotal({ knownTotalImages: null, lastPublishedTotal: null, total: 12 })).toBe(true);
@@ -20,3 +27,53 @@ describe('shouldPublishGalleryTotal', () => {
);
});
});
+
+describe('mixed-media gallery translations', () => {
+ it('resolves the board, upload, status, and video labels with interpolation', async () => {
+ const instance = i18n.createInstance();
+ await instance.init({
+ initAsync: false,
+ lng: 'en',
+ resources: { en: { translation: englishCatalog } },
+ });
+
+ expect(instance.t('widgets.gallery.statusChip', { count: 12 })).toBe('Gallery: 12 items');
+ expect(
+ instance.t('widgets.gallery.boardMediaCountBreakdown', {
+ images: instance.t('widgets.gallery.imageCount', { count: 2 }),
+ videos: instance.t('widgets.gallery.videoCount', { count: 3 }),
+ })
+ ).toBe('2 images · 3 videos');
+ expect(
+ instance.t('widgets.gallery.boardItemCounts', {
+ assets: instance.t('widgets.gallery.assetCount', { count: 4 }),
+ images: instance.t('widgets.gallery.imageCount', { count: 2 }),
+ videos: instance.t('widgets.gallery.videoCount', { count: 3 }),
+ })
+ ).toBe('2 images · 3 videos · 4 assets');
+ expect(instance.t('widgets.gallery.downloadBoardWithOmission', { count: 2 })).toBe(
+ 'Download Board (2 videos omitted)'
+ );
+ expect(
+ instance.t('widgets.gallery.uploadSummary', {
+ board: 'Clips',
+ failed: 1,
+ images: instance.t('widgets.gallery.imageCount', { count: 2 }),
+ videos: instance.t('widgets.gallery.videoCount', { count: 3 }),
+ })
+ ).toBe('2 images and 3 videos uploaded to Clips. 1 failed.');
+ expect(instance.t('widgets.gallery.uploadSplit')).toBe('Images appear in Assets; videos appear in Images.');
+ expect(
+ instance.t('widgets.gallery.deleteBoardMediaOutcome', {
+ failedImages: instance.t('widgets.gallery.imageCount', { count: 1 }),
+ failedVideos: instance.t('widgets.gallery.videoCount', { count: 2 }),
+ images: instance.t('widgets.gallery.imageCount', { count: 3 }),
+ videos: instance.t('widgets.gallery.videoCount', { count: 4 }),
+ })
+ ).toBe('Deleted 3 images and 4 videos; 1 image and 2 videos could not be deleted.');
+ expect(instance.t('widgets.preview.videoLabel', { name: 'clip.mp4' })).toBe('Video clip.mp4');
+ expect(instance.t('widgets.preview.videoFailed')).toBe('Video could not be loaded');
+ expect(instance.t('widgets.preview.copyCurrentFrame')).toBe('Copy Current Frame');
+ expect(instance.t('widgets.preview.videoDetails')).toBe('Video Details');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx
index 4e010125c8..34fc969b43 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx
@@ -5,6 +5,7 @@ import { StatusWidgetChip } from '@platform/ui';
import { useQueryClient } from '@tanstack/react-query';
import { ImageIcon } from 'lucide-react';
import { useCallback, useEffect, useEffectEvent, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
import type { GalleryStateView } from './galleryStateView';
@@ -40,6 +41,18 @@ export const shouldPublishGalleryTotal = ({
}): boolean =>
typeof total === 'number' && Number.isFinite(total) && total !== knownTotalImages && total !== lastPublishedTotal;
+export const GalleryStatusChip = ({ count }: { count: number }) => {
+ const { t } = useTranslation();
+
+ return (
+ <StatusWidgetChip icon={ImageIcon}>
+ {t('widgets.gallery.statusChip', {
+ count,
+ })}
+ </StatusWidgetChip>
+ );
+};
+
export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgetProps) => {
const {
gallery: galleryCommands,
@@ -108,6 +121,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
const actions = useGalleryActions({
boards: data.boards,
+ galleryView,
loadMore,
projectBoardId: getGalleryProjectBoardId(galleryValues),
projectName,
@@ -157,7 +171,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
}, [galleryCommands, page, settings.paginationMode, total]);
if (region === 'bottom' && presentation !== 'expanded') {
- return <StatusWidgetChip icon={ImageIcon}>Gallery: {total ?? gallery.items.length}</StatusWidgetChip>;
+ return <GalleryStatusChip count={total ?? gallery.items.length} />;
}
return (
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
index bfc74d8055..6586683fa6 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
@@ -124,8 +124,12 @@ describe('gallery state view', () => {
expect(gallery.isLoading).toBe(true);
});
- it('exposes both image and asset counts for board labels', () => {
- expect(getBoardCounts(boards[1])).toEqual({ assetCount: 0, imageCount: 2 });
+ it('exposes image, video, and asset counts for board labels', () => {
+ expect(getBoardCounts({ ...boards[1], videoCount: 3 })).toEqual({
+ assetCount: 0,
+ imageCount: 2,
+ videoCount: 3,
+ });
});
it('parses persisted gallery settings with safe defaults', () => {
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
index edd0604086..792a33e4cd 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
@@ -433,7 +433,10 @@ export const getGalleryStateView = (
};
};
-export const getBoardCounts = (board: GalleryBoard): { assetCount: number; imageCount: number } => ({
+export const getBoardCounts = (
+ board: GalleryBoard
+): { assetCount: number; imageCount: number; videoCount: number } => ({
assetCount: board.assetCount,
imageCount: board.imageCount,
+ videoCount: board.videoCount,
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
index 5be6ace3f8..29c691584b 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
@@ -17,14 +17,66 @@ const mocks = vi.hoisted(() => ({
downloadGalleryArchive: vi.fn(),
invalidateGallery: vi.fn(),
notificationsAdd: vi.fn(),
+ notificationsReportError: vi.fn(),
+ uploadGalleryImage: vi.fn(),
+ uploadGalleryVideo: vi.fn(),
}));
vi.mock('@features/gallery/data/backend', () => ({
+ classifyGalleryUpload: (file: File) => {
+ const type = file.type.toLowerCase();
+ const name = file.name.toLowerCase();
+
+ if (['image/jpeg', 'image/jpg', 'image/png', 'image/webp'].includes(type) || /\.(jpe?g|png|webp)$/.test(name)) {
+ return { kind: 'image' as const };
+ }
+ if (type === 'video/mp4' || name.endsWith('.mp4')) {
+ return { kind: 'video' as const };
+ }
+ return null;
+ },
createGalleryBoard: vi.fn(),
deleteGalleryBoard: (...args: unknown[]) => mocks.deleteGalleryBoard(...args),
downloadGalleryArchive: (...args: unknown[]) => mocks.downloadGalleryArchive(...args),
+ isDateBoardId: (boardId: string) => boardId.startsWith('by_date:'),
updateGalleryBoard: vi.fn(),
- uploadGalleryImage: vi.fn(),
+ uploadGalleryImage: (...args: unknown[]) => mocks.uploadGalleryImage(...args),
+ uploadGalleryVideo: (...args: unknown[]) => mocks.uploadGalleryVideo(...args),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: Record<string, unknown>) => {
+ const messages: Record<string, string> = {
+ 'widgets.gallery.boardArchivePreparing': `Preparing an image archive of "${String(values?.name)}". ${String(
+ values?.count
+ )} video will be omitted.`,
+ 'widgets.gallery.deleteBoardMediaOutcome': `Deleted ${String(values?.images)} and ${String(
+ values?.videos
+ )}; ${String(values?.failedImages)} and ${String(values?.failedVideos)} failed.`,
+ 'widgets.gallery.deleteBoardMoveOutcome': `Moved ${String(values?.images)} and ${String(
+ values?.videos
+ )} to Uncategorized.`,
+ 'widgets.gallery.deleteBoardPartialTitle': `Deleted board "${String(values?.name)}" with partial media cleanup`,
+ 'widgets.gallery.deleteBoardSuccessTitle': `Deleted board "${String(values?.name)}"`,
+ 'widgets.gallery.downloadReady': 'Download ready',
+ 'widgets.gallery.imageCount': `${String(values?.count)} images`,
+ 'widgets.gallery.preparingDownload': 'Preparing download',
+ 'widgets.gallery.uploadDateBoardUnavailable': 'Uploads are unavailable for date boards.',
+ 'widgets.gallery.uploadFailed': `No files uploaded. ${String(values?.failed)} failed.`,
+ 'widgets.gallery.uploadPartialTitle': `Uploaded ${String(values?.succeeded)} of ${String(values?.total)} files`,
+ 'widgets.gallery.uploadSplit': 'Images appear in Assets; videos appear in Images.',
+ 'widgets.gallery.uploadSummary': `${String(values?.images)} and ${String(values?.videos)} uploaded to ${String(
+ values?.board
+ )}. ${String(values?.failed)} failed.`,
+ 'widgets.gallery.uploadSuccessTitle': `Uploaded ${String(values?.count)} files`,
+ 'widgets.gallery.uploadUnsupported': 'No supported media files to upload (PNG, JPEG, WebP, or MP4).',
+ 'widgets.gallery.videoCount': `${String(values?.count)} videos`,
+ };
+
+ return messages[key] ?? key;
+ },
+ }),
}));
vi.mock('@features/gallery/data/queryCache', () => ({
@@ -39,10 +91,19 @@ let host: HTMLDivElement | null = null;
let root: Root | null = null;
const actionsRef = createRef<GalleryActions>();
const reconcileDeletedBoardOutcome = vi.fn();
+const selectItem = vi.fn();
const setItemMultiSelection = vi.fn();
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-const Probe = ({ ref }: { ref: Ref<GalleryActions> }) => {
+const Probe = ({
+ galleryView,
+ ref,
+ selectedBoardId,
+}: {
+ galleryView: 'images' | 'assets';
+ ref: Ref<GalleryActions>;
+ selectedBoardId: string;
+}) => {
const actions = useGalleryActions({
boards: [
{
@@ -58,7 +119,8 @@ const Probe = ({ ref }: { ref: Ref<GalleryActions> }) => {
loadMore: vi.fn(),
projectBoardId: null,
projectName: 'Project',
- selectedBoardId: 'board-1',
+ selectedBoardId,
+ galleryView,
});
useImperativeHandle(ref, () => actions, [actions]);
@@ -78,7 +140,7 @@ const adapter: GalleryUiAdapter = {
reconcileDeletedBoardOutcome,
selectBoard: noop,
selectImage: noop,
- selectItem: noop,
+ selectItem,
setCompareImage: noop,
setCompareItem: noop,
setItemMultiSelection,
@@ -96,29 +158,40 @@ const adapter: GalleryUiAdapter = {
generateValues: {},
liveFollowEnabled: false,
liveProgressTarget: null,
- notifications: { add: (...args: unknown[]) => mocks.notificationsAdd(...args), reportError: noop },
+ notifications: {
+ add: (...args: unknown[]) => mocks.notificationsAdd(...args),
+ reportError: (...args: unknown[]) => mocks.notificationsReportError(...args),
+ },
projectId: 'project-1',
projectName: 'Project',
queueItems: [],
widgets: { patchGalleryValues: noop },
};
-beforeEach(async () => {
- vi.clearAllMocks();
- accountLifecycle.activate('user-a');
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
+let selectedBoardId = 'board-1';
+let galleryView: 'images' | 'assets' = 'images';
+const renderProbe = async () => {
await act(() => {
root?.render(
<QueryClientProvider client={new QueryClient()}>
<GalleryUiProvider adapter={adapter}>
- <Probe ref={actionsRef} />
+ <Probe galleryView={galleryView} ref={actionsRef} selectedBoardId={selectedBoardId} />
</GalleryUiProvider>
</QueryClientProvider>
);
});
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ accountLifecycle.activate('user-a');
+ selectedBoardId = 'board-1';
+ galleryView = 'images';
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await renderProbe();
});
afterEach(async () => {
@@ -147,6 +220,33 @@ describe('deleteBoard', () => {
expect(reconcileDeletedBoardOutcome).toHaveBeenCalledOnce();
expect(reconcileDeletedBoardOutcome).toHaveBeenCalledWith(outcome);
+ expect(mocks.notificationsAdd).toHaveBeenCalledWith({
+ kind: 'success',
+ message: 'Moved 1 images and 1 videos to Uncategorized.',
+ title: 'Deleted board "Board 1"',
+ });
+ });
+
+ it('reports authoritative deleted and failed image/video outcomes', async () => {
+ mocks.deleteGalleryBoard.mockResolvedValue({
+ boardId: 'board-1',
+ deletedBoardImageNames: [],
+ deletedBoardVideoNames: [],
+ deletedImageNames: ['one.png', 'two.png'],
+ deletedVideoNames: ['one.mp4'],
+ failedImageNames: ['locked.png'],
+ failedVideoNames: ['locked.mp4'],
+ });
+
+ await act(async () => {
+ await actionsRef.current?.deleteBoard('board-1', true);
+ });
+
+ expect(mocks.notificationsAdd).toHaveBeenCalledWith({
+ kind: 'success',
+ message: 'Deleted 2 images and 1 videos; 1 images and 1 videos failed.',
+ title: 'Deleted board "Board 1" with partial media cleanup',
+ });
});
});
@@ -201,3 +301,179 @@ describe('board image archive omission', () => {
});
});
});
+
+const imageUpload = (name: string, queuedAt: string) => ({
+ boardId: 'board-1',
+ height: 64,
+ imageCategory: 'user' as const,
+ imageName: name,
+ imageUrl: `/images/${name}`,
+ queuedAt,
+ sourceQueueItemId: 'upload',
+ starred: false,
+ thumbnailUrl: `/thumbnails/${name}`,
+ width: 64,
+});
+
+const videoUpload = (name: string, createdAt: string) => ({
+ boardId: 'board-1',
+ category: 'general' as const,
+ createdAt,
+ durationSeconds: 4,
+ fullUrl: `/videos/${name}`,
+ height: 64,
+ isIntermediate: false,
+ kind: 'video' as const,
+ name,
+ starred: false,
+ thumbnailUrl: `/video-thumbnails/${name}`,
+ width: 64,
+});
+
+describe('mixed gallery upload', () => {
+ it('rejects a date-board upload before starting any request', async () => {
+ selectedBoardId = 'by_date:2026-07-30';
+ await renderProbe();
+
+ await act(async () => {
+ await actionsRef.current?.uploadFiles([new File(['image'], 'photo.png', { type: 'image/png' })]);
+ });
+
+ expect(mocks.uploadGalleryImage).not.toHaveBeenCalled();
+ expect(mocks.uploadGalleryVideo).not.toHaveBeenCalled();
+ expect(mocks.notificationsReportError).toHaveBeenCalledOnce();
+ expect(mocks.notificationsReportError).toHaveBeenCalledWith({
+ area: 'gallery-upload',
+ message: 'Uploads are unavailable for date boards.',
+ namespace: 'gallery',
+ });
+ });
+
+ it('retains concurrent image uploads while running videos sequentially and continuing after failure', async () => {
+ let resolveFirstImage: ((value: ReturnType<typeof imageUpload>) => void) | undefined;
+ let resolveSecondImage: ((value: ReturnType<typeof imageUpload>) => void) | undefined;
+ let resolveFirstVideo: ((value: ReturnType<typeof videoUpload>) => void) | undefined;
+ const firstImage = new Promise<ReturnType<typeof imageUpload>>((resolve) => {
+ resolveFirstImage = resolve;
+ });
+ const secondImage = new Promise<ReturnType<typeof imageUpload>>((resolve) => {
+ resolveSecondImage = resolve;
+ });
+ const firstVideo = new Promise<ReturnType<typeof videoUpload>>((resolve) => {
+ resolveFirstVideo = resolve;
+ });
+ mocks.uploadGalleryImage.mockReturnValueOnce(firstImage).mockReturnValueOnce(secondImage);
+ mocks.uploadGalleryVideo
+ .mockReturnValueOnce(firstVideo)
+ .mockRejectedValueOnce(new Error('bad second video'))
+ .mockResolvedValueOnce(videoUpload('third.mp4', '2026-07-30T12:00:05.000Z'));
+
+ let upload: Promise<void> | undefined;
+ act(() => {
+ upload = actionsRef.current?.uploadFiles([
+ new File(['image'], 'one.png', { type: 'image/png' }),
+ new File(['image'], 'two.webp', { type: 'image/webp' }),
+ new File(['video'], 'one.mp4', { type: 'video/mp4' }),
+ new File(['video'], 'two.mp4', { type: 'video/mp4' }),
+ new File(['video'], 'three.mp4', { type: 'video/mp4' }),
+ ]);
+ });
+
+ await vi.waitFor(() => {
+ expect(mocks.uploadGalleryImage).toHaveBeenCalledTimes(2);
+ expect(mocks.uploadGalleryVideo).toHaveBeenCalledTimes(1);
+ });
+
+ resolveFirstImage?.(imageUpload('one.png', '2026-07-30T12:00:01.000Z'));
+ resolveSecondImage?.(imageUpload('two.webp', '2026-07-30T12:00:02.000Z'));
+ resolveFirstVideo?.(videoUpload('one.mp4', '2026-07-30T12:00:03.000Z'));
+
+ await act(async () => {
+ await upload;
+ });
+
+ expect(mocks.uploadGalleryVideo).toHaveBeenCalledTimes(3);
+ expect(mocks.uploadGalleryVideo.mock.invocationCallOrder[1]).toBeLessThan(
+ mocks.uploadGalleryVideo.mock.invocationCallOrder[2] ?? Number.POSITIVE_INFINITY
+ );
+ expect(mocks.invalidateGallery).toHaveBeenCalledOnce();
+ expect(mocks.notificationsAdd).toHaveBeenCalledOnce();
+ expect(mocks.notificationsAdd).toHaveBeenCalledWith({
+ kind: 'success',
+ message: '2 images and 2 videos uploaded to Board 1. 1 failed. Images appear in Assets; videos appear in Images.',
+ title: 'Uploaded 4 of 5 files',
+ });
+ });
+
+ it('selects the newest successful upload visible in the active view', async () => {
+ galleryView = 'assets';
+ await renderProbe();
+ mocks.uploadGalleryImage
+ .mockResolvedValueOnce(imageUpload('older.png', '2026-07-30T12:00:01.000Z'))
+ .mockResolvedValueOnce(imageUpload('newer.png', '2026-07-30T12:00:04.000Z'));
+ mocks.uploadGalleryVideo.mockResolvedValue(videoUpload('newest.mp4', '2026-07-30T12:00:05.000Z'));
+
+ await act(async () => {
+ await actionsRef.current?.uploadFiles([
+ new File(['image'], 'older.png', { type: 'image/png' }),
+ new File(['video'], 'newest.mp4', { type: 'video/mp4' }),
+ new File(['image'], 'newer.png', { type: 'image/png' }),
+ ]);
+ });
+
+ expect(selectItem).toHaveBeenCalledOnce();
+ expect(selectItem).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'image', name: 'newer.png', category: 'user' })
+ );
+ });
+
+ it('reports unsupported and rejected files once without aborting supported uploads', async () => {
+ mocks.uploadGalleryVideo.mockRejectedValue(new Error('corrupt video'));
+
+ await act(async () => {
+ await actionsRef.current?.uploadFiles([
+ new File(['text'], 'notes.txt', { type: 'text/plain' }),
+ new File(['video'], 'corrupt.mp4', { type: 'video/mp4' }),
+ ]);
+ });
+
+ expect(mocks.notificationsAdd).not.toHaveBeenCalled();
+ expect(mocks.notificationsReportError).toHaveBeenCalledOnce();
+ expect(mocks.notificationsReportError).toHaveBeenCalledWith({
+ area: 'gallery-upload',
+ message: 'No files uploaded. 2 failed.',
+ namespace: 'gallery',
+ });
+ });
+
+ it('does not schedule another expensive video after the account lifetime aborts', async () => {
+ let rejectFirstVideo: ((reason: unknown) => void) | undefined;
+ mocks.uploadGalleryVideo.mockReturnValueOnce(
+ new Promise((_, reject) => {
+ rejectFirstVideo = reject;
+ })
+ );
+
+ let upload: Promise<void> | undefined;
+ act(() => {
+ upload = actionsRef.current?.uploadFiles([
+ new File(['video'], 'one.mp4', { type: 'video/mp4' }),
+ new File(['video'], 'two.mp4', { type: 'video/mp4' }),
+ ]);
+ });
+
+ await vi.waitFor(() => {
+ expect(mocks.uploadGalleryVideo).toHaveBeenCalledOnce();
+ });
+ accountLifecycle.invalidate();
+ rejectFirstVideo?.(new DOMException('The operation was aborted.', 'AbortError'));
+
+ await act(async () => {
+ await upload;
+ });
+
+ expect(mocks.uploadGalleryVideo).toHaveBeenCalledOnce();
+ expect(mocks.notificationsAdd).not.toHaveBeenCalled();
+ expect(mocks.notificationsReportError).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
index 9b1f5d32b0..de6a4cceb7 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
@@ -1,12 +1,16 @@
-import type { GalleryBoard } from '@features/gallery/core/types';
+import type { GalleryItem } from '@features/gallery/core/items';
+import type { GalleryBoard, GalleryView } from '@features/gallery/core/types';
-import { toGalleryItemKey } from '@features/gallery/core/items';
+import { compareGalleryItems, legacyGeneratedImageToGalleryItem, toGalleryItemKey } from '@features/gallery/core/items';
import {
+ classifyGalleryUpload,
createGalleryBoard,
deleteGalleryBoard,
downloadGalleryArchive,
+ isDateBoardId,
updateGalleryBoard,
uploadGalleryImage,
+ uploadGalleryVideo,
} from '@features/gallery/data/backend';
import { invalidateGallery } from '@features/gallery/data/queryCache';
import { downloadBlob } from '@platform/browser/downloadBlob';
@@ -17,23 +21,24 @@ import {
} from '@platform/state/accountLifecycle';
import { useQueryClient } from '@tanstack/react-query';
import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
import type { GalleryActions } from './GalleryWidgetContext';
import { useGalleryUi } from './GalleryUiContext';
-const ACCEPTED_UPLOAD_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);
-
const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
export const useGalleryActions = ({
boards,
loadMore,
+ galleryView,
projectBoardId,
projectName,
selectedBoardId,
}: {
boards: GalleryBoard[];
+ galleryView: GalleryView;
loadMore: () => void;
projectBoardId: string | null;
projectName: string;
@@ -41,6 +46,7 @@ export const useGalleryActions = ({
}): GalleryActions => {
const { gallery, notifications } = useGalleryUi();
const queryClient = useQueryClient();
+ const { t } = useTranslation();
return useMemo<GalleryActions>(() => {
const recordError = (error: unknown) =>
@@ -48,7 +54,9 @@ export const useGalleryActions = ({
const recordSuccess = (title: string, message?: string) => notifications.add({ kind: 'success', message, title });
const refresh = () => void invalidateGallery(queryClient);
const getBoard = (boardId: string) => boards.find((board) => board.id === boardId);
- const getBoardName = (boardId: string) => getBoard(boardId)?.name ?? 'Uncategorized';
+ const getBoardName = (boardId: string) => getBoard(boardId)?.name ?? t('widgets.gallery.uncategorized');
+ const formatImageCount = (count: number) => t('widgets.gallery.imageCount', { count });
+ const formatVideoCount = (count: number) => t('widgets.gallery.videoCount', { count });
return {
archiveBoard: async (boardId, archived) => {
@@ -58,7 +66,11 @@ export const useGalleryActions = ({
await updateGalleryBoard(boardId, { archived }, owner.signal);
assertAccountScopeCurrent(owner);
- recordSuccess(`${archived ? 'Archived' : 'Unarchived'} board "${getBoardName(boardId)}"`);
+ recordSuccess(
+ t(archived ? 'widgets.gallery.boardArchived' : 'widgets.gallery.boardUnarchived', {
+ name: getBoardName(boardId),
+ })
+ );
if (archived && boardId === selectedBoardId) {
gallery.selectBoard('none');
@@ -81,7 +93,7 @@ export const useGalleryActions = ({
assertAccountScopeCurrent(owner);
gallery.selectBoard(board.id);
- recordSuccess(`Created board "${board.name}"`);
+ recordSuccess(t('widgets.gallery.boardCreated', { name: board.name }));
refresh();
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
@@ -100,10 +112,23 @@ export const useGalleryActions = ({
const outcome = await deleteGalleryBoard(boardId, includeImages, owner.signal);
assertAccountScopeCurrent(owner);
- recordSuccess(
- `Deleted board "${boardName}"`,
- includeImages ? 'Its images were permanently deleted.' : 'Its images were moved to Uncategorized.'
+ const failedCount = outcome.failedImageNames.length + outcome.failedVideoNames.length;
+ const title = t(
+ failedCount > 0 ? 'widgets.gallery.deleteBoardPartialTitle' : 'widgets.gallery.deleteBoardSuccessTitle',
+ { name: boardName }
);
+ const message = includeImages
+ ? t('widgets.gallery.deleteBoardMediaOutcome', {
+ failedImages: formatImageCount(outcome.failedImageNames.length),
+ failedVideos: formatVideoCount(outcome.failedVideoNames.length),
+ images: formatImageCount(outcome.deletedImageNames.length),
+ videos: formatVideoCount(outcome.deletedVideoNames.length),
+ })
+ : t('widgets.gallery.deleteBoardMoveOutcome', {
+ images: formatImageCount(outcome.deletedBoardImageNames.length),
+ videos: formatVideoCount(outcome.deletedBoardVideoNames.length),
+ });
+ recordSuccess(title, message);
gallery.reconcileDeletedBoardOutcome(outcome);
refresh();
@@ -124,17 +149,18 @@ export const useGalleryActions = ({
notifications.add({
kind: 'info',
- message: `Preparing an image archive of "${getBoardName(boardId)}". ${videoCount} ${
- videoCount === 1 ? 'video' : 'videos'
- } will be omitted.`,
- title: 'Preparing download',
+ message: t('widgets.gallery.boardArchivePreparing', {
+ count: videoCount,
+ name: getBoardName(boardId),
+ }),
+ title: t('widgets.gallery.preparingDownload'),
});
const { blob, fileName } = await downloadGalleryArchive({ boardId, signal: owner.signal });
assertAccountScopeCurrent(owner);
downloadBlob(blob, fileName);
- recordSuccess('Download ready');
+ recordSuccess(t('widgets.gallery.downloadReady'));
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
return;
@@ -152,7 +178,7 @@ export const useGalleryActions = ({
await updateGalleryBoard(boardId, { name: boardName }, owner.signal);
assertAccountScopeCurrent(owner);
- recordSuccess(`Renamed board to "${boardName}"`);
+ recordSuccess(t('widgets.gallery.boardRenamed', { name: boardName }));
refresh();
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
@@ -183,7 +209,7 @@ export const useGalleryActions = ({
assertAccountScopeCurrent(owner);
gallery.setProjectBoard(board.id);
gallery.selectBoard(board.id);
- recordSuccess(`Created project board "${board.name}"`);
+ recordSuccess(t('widgets.gallery.projectBoardCreated', { name: board.name }));
refresh();
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
@@ -200,28 +226,117 @@ export const useGalleryActions = ({
updateSettings: gallery.updateSettings,
uploadFiles: async (files) => {
const owner = captureAccountScope();
- const accepted = files.filter((file) => ACCEPTED_UPLOAD_TYPES.has(file.type));
+
+ if (isDateBoardId(selectedBoardId)) {
+ notifications.reportError({
+ area: 'gallery-upload',
+ message: t('widgets.gallery.uploadDateBoardUnavailable'),
+ namespace: 'gallery',
+ });
+ return;
+ }
+
+ const accepted = files.flatMap((file) => {
+ const classification = classifyGalleryUpload(file);
+
+ return classification ? [{ file, kind: classification.kind }] : [];
+ });
if (accepted.length === 0) {
notifications.reportError({
area: 'gallery-upload',
- message: 'No supported image files to upload (PNG, JPEG, or WebP).',
+ message: t('widgets.gallery.uploadUnsupported'),
namespace: 'gallery',
});
return;
}
try {
- await Promise.all(
- accepted.map((file) => uploadGalleryImage(file, selectedBoardId, { signal: owner.signal }))
+ const targetBoardId = getBoard(selectedBoardId)?.kind === 'board' ? selectedBoardId : 'none';
+ const imageUploads = accepted.filter((upload) => upload.kind === 'image');
+ const videoUploads = accepted.filter((upload) => upload.kind === 'video');
+ const imageResultsPromise = Promise.allSettled(
+ imageUploads.map(({ file }) => uploadGalleryImage(file, targetBoardId, { signal: owner.signal }))
);
+ const videoResultsPromise = (async () => {
+ const results: PromiseSettledResult<GalleryItem>[] = [];
+
+ for (const { file } of videoUploads) {
+ owner.signal.throwIfAborted();
+
+ try {
+ results.push({
+ status: 'fulfilled',
+ value: await uploadGalleryVideo(file, targetBoardId, { signal: owner.signal }),
+ });
+ } catch (reason: unknown) {
+ if (owner.signal.aborted) {
+ throw reason;
+ }
+
+ results.push({ reason, status: 'rejected' });
+ }
+ }
+
+ return results;
+ })();
+ const [imageResults, videoResults] = await Promise.all([imageResultsPromise, videoResultsPromise]);
assertAccountScopeCurrent(owner);
- recordSuccess(
- `Uploaded ${accepted.length} ${accepted.length === 1 ? 'image' : 'images'}`,
- `Added to ${getBoardName(selectedBoardId)} as assets.`
+ const uploadedImages = imageResults.flatMap((result) =>
+ result.status === 'fulfilled' ? [legacyGeneratedImageToGalleryItem(result.value)] : []
);
+ const uploadedVideos = videoResults.flatMap((result) =>
+ result.status === 'fulfilled' ? [result.value] : []
+ );
+ const uploadedItems = [...uploadedImages, ...uploadedVideos];
+ const failedCount = files.length - uploadedItems.length;
+
+ if (uploadedItems.length === 0) {
+ notifications.reportError({
+ area: 'gallery-upload',
+ message: t('widgets.gallery.uploadFailed', { failed: failedCount }),
+ namespace: 'gallery',
+ });
+ return;
+ }
+
+ const visibleUploads = uploadedItems.filter(
+ (item) =>
+ item.boardId === targetBoardId &&
+ (galleryView === 'images'
+ ? item.category === 'general'
+ : item.category === 'control' || item.category === 'mask' || item.category === 'user')
+ );
+ const newestVisibleUpload = visibleUploads.reduce<GalleryItem | undefined>(
+ (newest, item) =>
+ newest === undefined || compareGalleryItems(item, newest, { orderDir: 'DESC' }) < 0 ? item : newest,
+ undefined
+ );
+
+ if (newestVisibleUpload) {
+ gallery.selectItem(newestVisibleUpload);
+ }
+
refresh();
+
+ const summary = t('widgets.gallery.uploadSummary', {
+ board: getBoardName(selectedBoardId),
+ failed: failedCount,
+ images: formatImageCount(uploadedImages.length),
+ videos: formatVideoCount(uploadedVideos.length),
+ });
+ const split =
+ imageUploads.length > 0 && videoUploads.length > 0 ? ` ${t('widgets.gallery.uploadSplit')}` : '';
+ recordSuccess(
+ t(
+ failedCount > 0 ? 'widgets.gallery.uploadPartialTitle' : 'widgets.gallery.uploadSuccessTitle',
+ failedCount > 0
+ ? { succeeded: uploadedItems.length, total: files.length }
+ : { count: uploadedItems.length }
+ ),
+ `${summary}${split}`
+ );
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
return;
@@ -231,5 +346,16 @@ export const useGalleryActions = ({
}
},
};
- }, [boards, gallery, loadMore, notifications, projectBoardId, projectName, queryClient, selectedBoardId]);
+ }, [
+ boards,
+ gallery,
+ galleryView,
+ loadMore,
+ notifications,
+ projectBoardId,
+ projectName,
+ queryClient,
+ selectedBoardId,
+ t,
+ ]);
};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index 8be2be4acd..663e774e95 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -137,7 +137,8 @@ export const useImageActions = ({
projectId,
});
const recordSuccess = (title: string, message?: string) => notifications.add({ kind: 'success', message, title });
- const getBoardName = (boardId: string) => boards.find((board) => board.id === boardId)?.name ?? 'Uncategorized';
+ const getBoardName = (boardId: string) =>
+ boards.find((board) => board.id === boardId)?.name ?? t('widgets.gallery.uncategorized');
const getLatestGenerateValues = () => {
const snapshot = queries.getSnapshot();
const project = projectId
@@ -158,10 +159,6 @@ export const useImageActions = ({
t(`widgets.gallery.itemActions.${action}.${result.succeeded.length > 0 ? 'partial' : 'failure'}`, {
board: boardId ? getBoardName(boardId) : undefined,
count: requestedCount,
- defaultValue:
- result.succeeded.length > 0
- ? `${result.succeeded.length} of ${requestedCount} items succeeded; ${result.failed.length} failed.`
- : `Could not ${action} ${requestedCount === 1 ? 'item' : `${requestedCount} items`}.`,
failed: result.failed.length,
succeeded: result.succeeded.length,
})
@@ -174,14 +171,6 @@ export const useImageActions = ({
t(`widgets.gallery.itemActions.${action}.success`, {
board: boardId ? getBoardName(boardId) : undefined,
count: result.succeeded.length,
- defaultValue:
- action === 'move'
- ? `Moved ${result.succeeded.length === 1 ? 'item' : `${result.succeeded.length} items`} to ${getBoardName(
- boardId ?? 'none'
- )}.`
- : `${action === 'delete' ? 'Deleted' : action === 'star' ? 'Starred' : 'Unstarred'} ${
- result.succeeded.length === 1 ? 'item' : `${result.succeeded.length} items`
- }.`,
})
);
};
@@ -455,7 +444,6 @@ export const useImageActions = ({
new Error(
t('widgets.gallery.itemActions.download.partial', {
count: items.length,
- defaultValue: `${succeededCount} of ${items.length} items downloaded; ${failedCount} failed or skipped.`,
failed: failedCount,
succeeded: succeededCount,
})
@@ -465,7 +453,6 @@ export const useImageActions = ({
recordSuccess(
t('widgets.gallery.itemActions.download.success', {
count: succeededCount,
- defaultValue: 'Download ready',
})
);
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index d09435f463..1be73164bb 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -965,7 +965,7 @@ const SelectedVideoPreview = ({
() => ({
itemKey: toGalleryItemKey(item),
kind: 'video',
- label: t('widgets.preview.videoLabel', { defaultValue: `Video ${item.name}`, name: item.name }),
+ label: t('widgets.preview.videoLabel', { name: item.name }),
poster: item.thumbnailUrl,
src: item.fullUrl,
}),