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 { GalleryBoard } from '@features/gallery';
import type { Project } from '@workbench/projectContracts';
import type { ProjectCommandResult } from '@workbench/workbenchStore';
import { galleryBoardsOptions } from '@features/gallery/queries';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createDraftProject } from '@workbench/workbenchState';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
import type * as libraryModule from './library';
import { serializeProjectDocumentV3Json } from './projectDocument';
const harness = vi.hoisted(() => ({
close: vi.fn<() => ProjectCommandResult>(),
deleteLibraryProject: vi.fn(),
flushCanvasPixels: vi.fn<() => Promise<void>>(),
flush: vi.fn(),
navigate: vi.fn(),
notifyError: vi.fn(),
persistEmptySession: vi.fn(),
project: {} as Project,
reconcileDeletedBoardOutcome: vi.fn(),
releaseProjectSync: vi.fn(),
reopenSession: vi.fn(),
}));
vi.mock('./library', async (importOriginal) => {
const { describeProjectDeletionFailure, ProjectDeletionRefusedError } = await importOriginal<typeof libraryModule>();
return {
describeProjectDeletionFailure,
ProjectDeletionRefusedError,
deleteLibraryProject: harness.deleteLibraryProject,
refreshProjectLibrary: vi.fn(),
};
});
vi.mock('@tanstack/react-router', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useNavigate: () => harness.navigate,
}));
// Services the workbench hands out are stable for its lifetime; the doubles are too, so identity checks hold.
const services = vi.hoisted(() => ({
canvasEngines: { flushPendingPixels: () => harness.flushCanvasPixels() },
commands: {
gallery: { reconcileDeletedBoardOutcome: (...args: unknown[]) => harness.reconcileDeletedBoardOutcome(...args) },
projects: { close: (...args: unknown[]) => harness.close(...(args as [])) },
},
notify: { error: (...args: unknown[]) => harness.notifyError(...args) },
persistence: { getState: () => ({ projects: [harness.project] }) },
persistenceService: {
flushProjectToServer: (...args: unknown[]) => harness.flush(...args),
persistEmptySession: (...args: unknown[]) => harness.persistEmptySession(...args),
releaseProjectSync: (...args: unknown[]) => harness.releaseProjectSync(...args),
reopenSession: (...args: unknown[]) => harness.reopenSession(...args),
},
queries: {
getProject: () => harness.project,
getSnapshot: () => ({ projects: [harness.project, createDraftProject([harness.project])] }),
},
t: (key: string) => key,
}));
vi.mock('@workbench/useNotify', () => ({ useNotify: () => services.notify }));
vi.mock('@workbench/WorkbenchContext', () => ({
useWorkbenchLiveCanvasEngines: () => services.canvasEngines,
useWorkbenchCommands: () => services.commands,
useWorkbenchPersistenceAdapter: () => services.persistence,
useWorkbenchPersistenceService: () => services.persistenceService,
useWorkbenchQueries: () => services.queries,
}));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: services.t }) }));
import { useProjectActions } from './useProjectActions';
let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const seenOpenProjects: unknown[] = [];
const HarnessBody = (_props: { renderCount?: number }) => {
const { closeProject, deleteProject, openProject } = useProjectActions();
seenOpenProjects.push(openProject);
return (
<>
<button onClick={() => closeProject(harness.project)}>close</button>
<button onClick={() => void deleteProject(harness.project)}>delete</button>
<button onClick={() => void deleteProject(harness.project, 'delete')}>delete with boards</button>
</>
);
};
// Deleting invalidates the gallery's board lists, so the hook reads the query client.
const queryClient = new QueryClient();
const Harness = ({ renderCount }: { renderCount?: number }) => (
<QueryClientProvider client={queryClient}>
<HarnessBody renderCount={renderCount} />
</QueryClientProvider>
);
beforeEach(() => {
accountLifecycle.activate('use-project-actions-browser-test');
harness.project = createDraftProject([]);
harness.close.mockReset();
harness.close.mockReturnValue({ ok: true });
harness.deleteLibraryProject.mockReset();
harness.deleteLibraryProject.mockResolvedValue(undefined);
harness.flush.mockReset();
harness.flushCanvasPixels.mockReset();
harness.flushCanvasPixels.mockResolvedValue(undefined);
harness.navigate.mockReset();
harness.reconcileDeletedBoardOutcome.mockReset();
queryClient.clear();
harness.notifyError.mockReset();
harness.persistEmptySession.mockReset();
harness.persistEmptySession.mockResolvedValue(undefined);
harness.releaseProjectSync.mockReset();
harness.reopenSession.mockReset();
harness.reopenSession.mockResolvedValue(undefined);
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
});
afterEach(async () => {
accountLifecycle.invalidate();
await act(() => root?.unmount());
host?.remove();
host = null;
root = null;
});
describe('useProjectActions', () => {
it('blocks project deletion while a queue run is active and offers the queue', async () => {
harness.project.queue.items = [{ status: 'running' } as Project['queue']['items'][number]];
await act(() => root?.render(<Harness />));
await act(() => userEvent.click(document.querySelectorAll('button')[1]!));
expect(harness.notifyError).toHaveBeenCalledWith('projects.deleteFailed', 'projects.deleteRefused.active-runs', {
actions: [{ kind: 'open-widget', widgetId: 'queue' }],
});
expect(harness.deleteLibraryProject).not.toHaveBeenCalled();
});
it('clears other open projects of the boards that went with a deleted project, and only once it is gone', async () => {
const board = (id: string, projectId: string | null, isInbox = false, archived = false): GalleryBoard => ({
archived,
assetCount: 0,
assetVideoCount: 0,
id,
imageCount: 0,
isInbox,
kind: 'board',
name: id,
projectId,
videoCount: 0,
});
// The delete dialog's list holds archived boards, which go with the project too; the gallery's does not.
queryClient.setQueryData(galleryBoardsOptions({}).queryKey, [
board('inbox', harness.project.id, true),
board('member', harness.project.id),
board('elsewhere', 'other-project'),
board('library', null),
]);
queryClient.setQueryData(galleryBoardsOptions({ includeArchived: true }).queryKey, [
board('inbox', harness.project.id, true),
board('member', harness.project.id),
board('old-member', harness.project.id, false, true),
]);
const reconciledBoardIds = () =>
harness.reconcileDeletedBoardOutcome.mock.calls.map((call) => (call[0] as { boardId: string }).boardId);
await act(() => root?.render(<Harness />));
harness.deleteLibraryProject.mockRejectedValueOnce(new Error('offline'));
await act(() => userEvent.click(document.querySelectorAll('button')[2]!));
expect(harness.reconcileDeletedBoardOutcome).not.toHaveBeenCalled();
await act(() => userEvent.click(document.querySelectorAll('button')[1]!));
expect(reconciledBoardIds()).toEqual(['inbox']);
harness.reconcileDeletedBoardOutcome.mockReset();
await act(() => userEvent.click(document.querySelectorAll('button')[2]!));
expect(reconciledBoardIds()).toEqual(['inbox', 'member', 'old-member']);
expect(harness.reconcileDeletedBoardOutcome).toHaveBeenCalledWith(
expect.objectContaining({ deletedImageNames: [], deletedVideoNames: [], failedImageNames: [] })
);
});
it('persists canvas pixels before flushing the project document', async () => {
harness.flush.mockResolvedValue({
documentJson: serializeProjectDocumentV3Json(harness.project).documentJson,
kind: 'acknowledged',
});
await act(() => root?.render(<Harness />));
await act(() => userEvent.click(document.querySelector('button')!));
await vi.waitFor(() => expect(harness.close).toHaveBeenCalledOnce());
expect(harness.flushCanvasPixels.mock.invocationCallOrder[0]).toBeLessThan(
harness.flush.mock.invocationCallOrder[0]!
);
// Pixels painted while the document was being pushed are persisted before the tab closes.
expect(harness.flushCanvasPixels.mock.invocationCallOrder[1]).toBeGreaterThan(
harness.flush.mock.invocationCallOrder[0]!
);
});
it('reflushes an edit made while close is waiting for acknowledgement', async () => {
let releaseFirst!: () => void;
const firstReleased = new Promise<void>((resolve) => {
releaseFirst = resolve;
});
harness.flush.mockImplementationOnce(async (project: Project) => {
await firstReleased;
return { documentJson: serializeProjectDocumentV3Json(project).documentJson, kind: 'acknowledged' as const };
});
harness.flush.mockImplementationOnce((project: Project) =>
Promise.resolve({
documentJson: serializeProjectDocumentV3Json(project).documentJson,
kind: 'acknowledged' as const,
})
);
await act(() => root?.render(<Harness />));
await act(() => userEvent.click(document.querySelector('button')!));
await vi.waitFor(() => expect(harness.flush).toHaveBeenCalledOnce());
harness.project = { ...harness.project, name: 'edit during close' };
releaseFirst();
await vi.waitFor(() => expect(harness.flush).toHaveBeenCalledTimes(2));
await vi.waitFor(() => expect(harness.close).toHaveBeenCalledOnce());
expect(harness.flush.mock.calls[1]![0]).toMatchObject({ name: 'edit during close' });
expect(harness.releaseProjectSync).toHaveBeenCalledOnce();
});
it('keeps the tab open when queue work starts while the close flush is in flight', async () => {
harness.flush.mockImplementationOnce((project: Project) => {
harness.project = {
...harness.project,
queue: { items: [{ status: 'running' } as Project['queue']['items'][number]] },
};
return Promise.resolve({
documentJson: serializeProjectDocumentV3Json(project).documentJson,
kind: 'acknowledged' as const,
});
});
harness.close.mockReturnValue({ ok: false, reason: 'active-queue-runs' });
await act(() => root?.render(<Harness />));
await act(() => userEvent.click(document.querySelector('button')!));
await vi.waitFor(() => expect(harness.notifyError).toHaveBeenCalledOnce());
expect(harness.notifyError).toHaveBeenCalledWith('projects.closeBlocked', 'projects.activeRunsMustFinish');
expect(harness.close).toHaveBeenCalledOnce();
expect(harness.releaseProjectSync).not.toHaveBeenCalled();
expect(harness.navigate).not.toHaveBeenCalled();
});
it('reopens the emptied session when the last tab changed while it was being emptied', async () => {
harness.close
.mockReturnValueOnce({ ok: false, reason: 'last-project' })
.mockReturnValueOnce({ ok: false, reason: 'modified' })
.mockReturnValueOnce({ ok: false, reason: 'last-project' })
.mockReturnValueOnce({ ok: false, reason: 'last-project' });
harness.flush.mockImplementation((project: Project) =>
Promise.resolve({
documentJson: serializeProjectDocumentV3Json(project).documentJson,
kind: 'acknowledged' as const,
})
);
await act(() => root?.render(<Harness />));
await act(() => userEvent.click(document.querySelector('button')!));
await vi.waitFor(() => expect(harness.navigate).toHaveBeenCalledWith({ to: '/' }));
expect(harness.flush).toHaveBeenCalledTimes(2);
expect(harness.persistEmptySession).toHaveBeenCalledTimes(2);
expect(harness.reopenSession).toHaveBeenCalledOnce();
expect(harness.reopenSession.mock.invocationCallOrder[0]).toBeLessThan(
harness.persistEmptySession.mock.invocationCallOrder[1]!
);
});
});