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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
import type { GalleryUiAdapter } from '@features/gallery/react';
import { GalleryUiProvider } from '@features/gallery/react';
import { resolvedValues } from '@platform/core/resolvedValues.testing';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { ApiError } from '@platform/transport/http';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, createRef, type Ref, type ReactNode, useCallback, useImperativeHandle, useRef } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { GalleryActions } from './GalleryWidgetContext';
import { useGalleryUploadAction } from './useGalleryUploadAction';
const mocks = vi.hoisted(() => ({
// The ensured listing's answer per board; the panel's `boards` fixture names only board-1.
canAddToCachedGalleryBoard: vi.fn((boardId: string) => boardId === 'board-1' || boardId === 'board-9'),
ensureGalleryBoardDestinations: vi.fn((): Promise<void> | null => null),
invalidateGallery: vi.fn(),
notificationsAdd: vi.fn(),
notificationsReportError: vi.fn(),
uploadGalleryImage: vi.fn(),
uploadGalleryVideo: vi.fn(),
}));
vi.mock('@features/gallery/data/backend', () => ({
isDateBoardId: (boardId: string) => boardId.startsWith('by_date:'),
isInvalidGalleryBoardDestination: (boardId: string) => boardId.startsWith('by_date:'),
uploadGalleryImage: (...args: unknown[]) => mocks.uploadGalleryImage(...args),
uploadGalleryVideo: (...args: unknown[]) => mocks.uploadGalleryVideo(...args),
}));
vi.mock('@features/gallery/data/queryCache', () => ({
canAddToCachedGalleryBoard: (boardId: string) => mocks.canAddToCachedGalleryBoard(boardId),
ensureGalleryBoardDestinations: () => mocks.ensureGalleryBoardDestinations(),
getCachedGalleryBoard: () => undefined,
invalidateGallery: (...args: unknown[]) => mocks.invalidateGallery(...args),
invalidateGalleryBoardDestinations: vi.fn(),
}));
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) => {
const messages: Record<string, string> = {
'widgets.gallery.imageCount': `${String(values?.count)} ${values?.count === 1 ? 'image' : 'images'}`,
'widgets.gallery.mediaCountsTwo': `${String(values?.first)} and ${String(values?.second)}`,
'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.uploadFailedCount': `${String(values?.count)} failed.`,
'widgets.gallery.uploadSplit': 'Images and videos appear in Uploads.',
'widgets.gallery.uploadSummary': `${String(values?.media)} uploaded to ${String(values?.board)}.`,
'widgets.gallery.uploadSuccessTitle': `Uploaded ${String(values?.count)} files`,
'widgets.gallery.uploadUnsupported':
'No supported media files to upload (PNG, JPEG, or WebP images; video files; or audio files).',
'widgets.gallery.uncategorized': 'Uncategorized',
'widgets.gallery.videoCount': `${String(values?.count)} ${values?.count === 1 ? 'video' : 'videos'}`,
};
return messages[key] ?? key;
},
}),
}));
let host: HTMLDivElement | null = null;
let root: Root | null = null;
const uploadFilesRef = createRef<GalleryActions['uploadFiles']>();
const selectItem = vi.fn();
const setView = vi.fn();
const noop = vi.fn();
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const NoopProvider = ({ children }: { children: ReactNode }) => children;
const adapter: GalleryUiAdapter = {
ItemActionsProvider: NoopProvider,
ImageContextMenu: () => null,
antialiasProgressImages: false,
exportProject: vi.fn(),
getBoardMediaUsage: vi.fn(),
gallery: {
clearSelection: noop,
reconcileDeletedBoardOutcome: noop,
selectBoard: noop,
selectImage: noop,
selectItem,
setCompareImage: noop,
setCompareItem: noop,
setItemMultiSelection: noop,
setPage: noop,
setPageInfo: noop,
setSearchTerm: noop,
setStarredOnly: noop,
setSemanticSearchMode: noop,
setSemanticSearchText: noop,
commitSemanticSearch: noop,
clearSearch: noop,
setView,
toggleItemSelection: noop,
updateSettings: noop,
},
galleryValues: resolvedValues(),
generateValues: {},
getItemLabel: () => Promise.resolve(null),
liveFollowEnabled: false,
progressSessions: [],
pinnedProgressSessionId: null,
followedProgressSessionId: null,
followProgressSession: vi.fn(),
notifications: {
add: (...args: unknown[]) => mocks.notificationsAdd(...args),
reportError: (...args: unknown[]) => mocks.notificationsReportError(...args),
},
openItemContextMenu: noop,
projectId: 'project-1',
projectName: 'Project',
projects: [],
widgets: { openGallery: () => true, patchGalleryValues: noop },
};
const Probe = ({
galleryView,
ref,
revealInReceivingTab,
selectedBoardId,
}: {
galleryView: 'images' | 'assets';
ref: Ref<GalleryActions['uploadFiles']>;
revealInReceivingTab: boolean;
selectedBoardId: string;
}) => {
const currentGalleryLocationRef = useRef({ galleryView, selectedBoardId });
// eslint-disable-next-line react/refs
currentGalleryLocationRef.current = { galleryView, selectedBoardId };
const getCurrentGalleryLocation = useCallback(() => currentGalleryLocationRef.current, []);
const uploadFiles = useGalleryUploadAction({
boards: [
{
archived: false,
assetCount: 0,
assetVideoCount: 0,
id: 'board-1',
imageCount: 2,
kind: 'board',
name: 'Board 1',
isInbox: false,
projectId: null,
videoCount: 1,
},
{
archived: false,
assetCount: 0,
assetVideoCount: 0,
id: 'none',
imageCount: 0,
kind: 'uncategorized',
name: '',
isInbox: false,
projectId: null,
videoCount: 0,
},
],
getCurrentGalleryLocation,
revealInReceivingTab,
selectedBoardId,
});
useImperativeHandle(ref, () => uploadFiles, [uploadFiles]);
return null;
};
let selectedBoardId = 'board-1';
let galleryView: 'images' | 'assets' = 'images';
let revealInReceivingTab = true;
const renderProbe = async () => {
await act(() => {
root?.render(
<QueryClientProvider client={new QueryClient()}>
<GalleryUiProvider adapter={adapter}>
<Probe
galleryView={galleryView}
ref={uploadFilesRef}
revealInReceivingTab={revealInReceivingTab}
selectedBoardId={selectedBoardId}
/>
</GalleryUiProvider>
</QueryClientProvider>
);
});
};
beforeEach(async () => {
vi.clearAllMocks();
accountLifecycle.activate('user-a');
selectedBoardId = 'board-1';
galleryView = 'images';
revealInReceivingTab = true;
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
await renderProbe();
});
afterEach(async () => {
await act(() => root?.unmount());
host?.remove();
host = null;
root = null;
});
const imageUpload = (name: string, queuedAt: string, boardId = 'board-1') => ({
boardId,
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('focused gallery upload action', () => {
it('rejects a date-board upload before starting any request', async () => {
selectedBoardId = 'by_date:2026-07-30';
await renderProbe();
await act(async () => {
await expect(
uploadFilesRef.current?.([new File(['image'], 'photo.png', { type: 'image/png' })])
).resolves.toEqual([]);
});
expect(mocks.uploadGalleryImage).not.toHaveBeenCalled();
expect(mocks.uploadGalleryVideo).not.toHaveBeenCalled();
expect(mocks.notificationsReportError).toHaveBeenCalledWith({
area: 'gallery-upload',
message: 'Uploads are unavailable for date boards.',
namespace: 'gallery',
});
});
it('uploads images concurrently while running videos sequentially and continuing after a file 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<unknown> | undefined;
act(() => {
upload = uploadFilesRef.current?.([
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).toHaveBeenCalledWith({
kind: 'success',
message: '2 images and 2 videos uploaded to Board 1. 1 failed. Images and videos appear in Uploads.',
title: 'Uploaded 4 of 5 files',
});
expect(selectItem).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ kind: 'video', name: 'third.mp4' }));
// Some of a mixed upload landed on the tab showing, so the tab stays.
expect(setView).not.toHaveBeenCalled();
await expect(upload).resolves.toEqual([
expect.objectContaining({ kind: 'image', name: 'one.png' }),
expect.objectContaining({ kind: 'image', name: 'two.webp' }),
expect.objectContaining({ kind: 'video', name: 'one.mp4' }),
expect.objectContaining({ kind: 'video', name: 'third.mp4' }),
]);
});
it('does not select an upload from the launch board after the active board changes in flight', async () => {
let resolveUpload: ((value: ReturnType<typeof imageUpload>) => void) | undefined;
mocks.uploadGalleryImage.mockReturnValueOnce(
new Promise<ReturnType<typeof imageUpload>>((resolve) => {
resolveUpload = resolve;
})
);
let upload: Promise<unknown> | undefined;
act(() => {
upload = uploadFilesRef.current?.([new File(['image'], 'photo.png', { type: 'image/png' })]);
});
await vi.waitFor(() => expect(mocks.uploadGalleryImage).toHaveBeenCalledOnce());
selectedBoardId = 'none';
await renderProbe();
resolveUpload?.(imageUpload('photo.png', '2026-07-30T12:00:04.000Z'));
await act(async () => {
await upload;
});
expect(selectItem).not.toHaveBeenCalled();
expect(mocks.invalidateGallery).toHaveBeenCalledOnce();
await expect(upload).resolves.toEqual([expect.objectContaining({ kind: 'image', name: 'photo.png' })]);
});
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<unknown> | undefined;
act(() => {
upload = uploadFilesRef.current?.([
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();
await expect(upload).resolves.toEqual([]);
});
it('names only what was uploaded, under the localized Uncategorized label, with no failure clause', async () => {
selectedBoardId = 'none';
await renderProbe();
mocks.uploadGalleryImage.mockResolvedValue(imageUpload('photo.png', '2026-07-30T12:00:04.000Z', 'none'));
await act(async () => {
await uploadFilesRef.current?.([new File(['image'], 'photo.png', { type: 'image/png' })]);
});
expect(mocks.notificationsAdd).toHaveBeenCalledWith(
expect.objectContaining({ message: '1 image uploaded to Uncategorized.' })
);
});
it('switches to the tab that received the upload when none of it landed on the one showing', async () => {
galleryView = 'images';
await renderProbe();
mocks.uploadGalleryImage
.mockResolvedValueOnce(imageUpload('older.png', '2026-07-30T12:00:01.000Z'))
.mockResolvedValueOnce(imageUpload('newer.png', '2026-07-30T12:00:02.000Z'));
await act(async () => {
await uploadFilesRef.current?.([
new File(['image'], 'older.png', { type: 'image/png' }),
new File(['image'], 'newer.png', { type: 'image/png' }),
]);
});
// Uploaded images are listed under Uploads, not Media.
expect(setView).toHaveBeenCalledExactlyOnceWith('assets');
expect(selectItem).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ kind: 'image', name: 'newer.png' }));
expect(setView.mock.invocationCallOrder[0]).toBeLessThan(selectItem.mock.invocationCallOrder[0] ?? 0);
});
it('leaves the tab alone for an upload made outside the Gallery, such as a paste', async () => {
revealInReceivingTab = false;
await renderProbe();
mocks.uploadGalleryImage.mockResolvedValue(imageUpload('pasted.png', '2026-07-30T12:00:04.000Z'));
await act(async () => {
await uploadFilesRef.current?.([new File(['image'], 'pasted.png', { type: 'image/png' })]);
});
expect(setView).not.toHaveBeenCalled();
expect(selectItem).not.toHaveBeenCalled();
});
it('leaves the tab and selection alone for an upload that landed on a board the gallery left', async () => {
mocks.uploadGalleryImage.mockResolvedValue(imageUpload('photo.png', '2026-07-30T12:00:04.000Z', 'board-9'));
await act(async () => {
await uploadFilesRef.current?.([new File(['image'], 'photo.png', { type: 'image/png' })]);
});
expect(setView).not.toHaveBeenCalled();
expect(selectItem).not.toHaveBeenCalled();
});
it('surfaces the first actionable API detail when every upload fails', async () => {
mocks.uploadGalleryImage.mockRejectedValue(new ApiError('{"detail":"Image storage maintenance is active"}', 409));
await act(async () => {
await expect(
uploadFilesRef.current?.([new File(['image'], 'photo.png', { type: 'image/png' })])
).resolves.toEqual([]);
});
expect(mocks.notificationsReportError).toHaveBeenCalledWith({
area: 'gallery-upload',
message: 'Image storage maintenance is active',
namespace: 'gallery',
});
expect(mocks.notificationsAdd).not.toHaveBeenCalled();
// The board may be what refused it: the listing, boards included, is read again before the next upload.
expect(mocks.invalidateGallery).toHaveBeenCalledTimes(1);
});
it('sends an upload to a board the loaded list does not name once the ensured listing takes it', async () => {
mocks.uploadGalleryImage.mockResolvedValue(imageUpload('photo.png', '2026-07-30T12:00:04.000Z', 'board-9'));
selectedBoardId = 'board-9';
await renderProbe();
await act(async () => {
await uploadFilesRef.current?.([new File(['image'], 'photo.png', { type: 'image/png' })]);
});
expect(mocks.ensureGalleryBoardDestinations).toHaveBeenCalledOnce();
expect(mocks.canAddToCachedGalleryBoard).toHaveBeenCalledWith('board-9');
expect(mocks.uploadGalleryImage).toHaveBeenCalledExactlyOnceWith(expect.any(File), 'board-9', expect.anything());
});
it('rejects unsupported files without a request and resolves empty', async () => {
await act(async () => {
await expect(
uploadFilesRef.current?.([new File(['notes'], 'notes.txt', { type: 'text/plain' })])
).resolves.toEqual([]);
});
expect(mocks.uploadGalleryImage).not.toHaveBeenCalled();
expect(mocks.uploadGalleryVideo).not.toHaveBeenCalled();
expect(mocks.notificationsReportError).toHaveBeenCalledWith({
area: 'gallery-upload',
message: 'No supported media files to upload (PNG, JPEG, or WebP images; video files; or audio files).',
namespace: 'gallery',
});
});
});