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 { beforeEach, describe, expect, it, vi } from 'vitest';
const transportMocks = vi.hoisted(() => ({ apiFetchRaw: vi.fn() }));
vi.mock('@platform/transport/http', async (importOriginal) => ({
...(await importOriginal<object>()),
apiFetchRaw: transportMocks.apiFetchRaw,
}));
import { INVK_MAX_ARCHIVE_BYTES, readArchive, readEntryText } from './archive';
import { executeInvkExport, planInvkExport } from './exportProject';
import { INVK_DOCUMENT_ENTRY, INVK_MANIFEST_ENTRY } from './format';
const imageRef = (imageName: string) => ({ height: 64, imageName, width: 64 });
const projectDocument = (): Record<string, unknown> => ({
canvas: {
document: {
stacks: {
raster: [
{ id: 'l1', source: { image: imageRef('live-a.png'), type: 'image' } },
{ id: 'l2', source: { bitmap: imageRef('live-b.png'), type: 'paint' } },
],
},
},
snapshots: [
{ document: { stacks: { raster: [{ id: 'old', source: { image: imageRef('history.png'), type: 'image' } }] } } },
],
},
id: 'project-1',
layout: {},
name: 'My project',
queue: {
items: [{ snapshot: { canvas: { document: { stacks: { raster: [{ source: { image: imageRef('q.png') } }] } } } } }],
},
});
const planInput = {
appVersion: '7.0',
boards: [{ archived: false, isInbox: true, items: [], name: 'My project' }],
createdAt: '2026-08-04T00:00:00.000Z',
minimumCanvasSchemaVersion: 3,
content: projectDocument(),
documentSchemaVersion: 4,
name: 'My project',
workspace: null,
};
/** The names a plan will fetch, in the union's stable order. */
const plannedNames = (plan: ReturnType<typeof planInvkExport>): string[] => plan.transferItems.map((item) => item.name);
describe('planInvkExport', () => {
it('bundles the live document and nothing from history', () => {
expect(plannedNames(planInvkExport(planInput))).toEqual(['live-a.png', 'live-b.png']);
});
/** Strip selection references as well as excluding their bytes. */
it('writes a document carrying no gallery selection', () => {
const plan = planInvkExport({
...planInput,
content: {
...projectDocument(),
widgetInstances: {
'gallery-1': {
state: { values: { selectedImageName: 'image:selected.png', selectedImageNames: ['image:selected.png'] } },
typeId: 'gallery',
},
'preview-1': { state: { values: { compareImage: imageRef('compare.png') } }, typeId: 'preview' },
},
},
});
expect(plan.documentJson).not.toContain('selected.png');
expect(plan.documentJson).not.toContain('compare.png');
expect(plannedNames(plan)).toEqual(['live-a.png', 'live-b.png']);
});
it('carries the workspace, and the media only it names, only when it is included', () => {
const workspace = {
canvas: { selectedLayerId: null, stagingArea: { images: [imageRef('staged.png')] } },
layout: {},
widgetInstances: {
'gallery-1': { state: { values: { recentImages: [imageRef('recent.png')] } }, typeId: 'gallery' },
},
};
const included = planInvkExport({ ...planInput, workspace });
const left = planInvkExport(planInput);
expect(plannedNames(included)).toEqual(['live-a.png', 'live-b.png', 'staged.png']);
expect(JSON.parse(included.workspaceJson!)).toMatchObject({ canvas: workspace.canvas });
// The newest result is the workspace's to show; without it the cover is the canvas's.
expect(included.coverImageName).toBe('recent.png');
expect(plannedNames(left)).toEqual(['live-a.png', 'live-b.png']);
expect(left.workspaceJson).toBeNull();
expect(left.coverImageName).toBe('live-a.png');
});
});
describe('executeInvkExport', () => {
const bytesFor = (imageName: string) => new Uint8Array([...imageName].map((character) => character.codePointAt(0)!));
beforeEach(() => {
transportMocks.apiFetchRaw.mockReset();
});
it('writes a readable archive holding the manifest, document, images and cover', async () => {
const download = vi.fn();
const result = await executeInvkExport(planInvkExport(planInput), {
download,
fetchImageBytes: (imageName) => Promise.resolve(bytesFor(imageName)),
fetchImageThumbnail: () =>
Promise.resolve({ bytes: new Uint8Array([1, 2, 3]), contentType: 'image/webp;charset=binary' }),
});
expect(result).toEqual({
boardIssues: [],
boardItemIssues: [],
bundledImageCount: 2,
bundledVideoCount: 0,
documentReferenceIssues: [],
});
expect(download).toHaveBeenCalledTimes(1);
const [blob, fileName] = download.mock.calls[0]! as [Blob, string];
expect(fileName).toBe('My project.invk');
const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));
expect([...entries.keys()].sort()).toEqual([
'board.json',
'cover.webp',
'images/live-a.png',
'images/live-b.png',
'manifest.json',
'project.json',
]);
expect(JSON.parse(readEntryText(entries.get(INVK_MANIFEST_ENTRY)!))).toMatchObject({
contents: 'workbench-project',
cover: 'cover.webp',
name: 'My project',
documentSchemaVersion: 4,
minimumCanvasSchemaVersion: 3,
sourceProjectId: 'project-1',
version: 3,
});
expect(JSON.parse(readEntryText(entries.get(INVK_DOCUMENT_ENTRY)!))).toEqual(projectDocument());
});
it('skips an image the server will not serve rather than failing the export', async () => {
const download = vi.fn();
const result = await executeInvkExport(planInvkExport(planInput), {
download,
fetchImageBytes: (imageName) => Promise.resolve(imageName === 'live-b.png' ? null : bytesFor(imageName)),
fetchImageThumbnail: () => Promise.resolve(null),
});
expect(result).toEqual({
boardIssues: [],
boardItemIssues: [],
bundledImageCount: 1,
bundledVideoCount: 0,
documentReferenceIssues: [{ kind: 'image', name: 'live-b.png', reason: 'fetch-failed' }],
});
expect(download).toHaveBeenCalledTimes(1);
});
it('writes videos under their own prefix, beside the images', async () => {
const download = vi.fn();
const plan = planInvkExport({
...planInput,
content: {
...projectDocument(),
projectGraph: { nodes: [{ data: { inputs: { video: { video_name: 'clip.mp4' } } }, id: 'n' }] },
},
});
expect(plan.transferItems.filter((item) => item.kind === 'video').map((item) => item.name)).toEqual(['clip.mp4']);
const result = await executeInvkExport(plan, {
download,
fetchImageBytes: (imageName) => Promise.resolve(bytesFor(imageName)),
fetchImageThumbnail: () => Promise.resolve(null),
fetchVideoBytes: (videoName) => Promise.resolve(bytesFor(videoName)),
});
expect(result).toEqual({
boardIssues: [],
boardItemIssues: [],
bundledImageCount: 2,
bundledVideoCount: 1,
documentReferenceIssues: [],
});
const [blob] = download.mock.calls[0]! as [Blob];
const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));
expect([...entries.keys()].sort()).toEqual([
'board.json',
'images/live-a.png',
'images/live-b.png',
'manifest.json',
'project.json',
'videos/clip.mp4',
]);
});
/** Aborted fetches must fail export rather than produce an empty successful archive. */
it.each([
[
'the fetches themselves abort',
() => {
const abort = () => Promise.reject(new DOMException('The operation was aborted.', 'AbortError'));
return { fetchImageBytes: abort, fetchImageThumbnail: abort };
},
],
[
'the signal aborts after the last fetch but before packing',
() => {
const controller = new AbortController();
return {
fetchImageBytes: (imageName: string) => {
controller.abort();
return Promise.resolve(bytesFor(imageName));
},
signal: controller.signal,
};
},
],
[
'cancellation lands during packing',
() => {
const controller = new AbortController();
return {
onProgress: ({ phase }: { phase: string }) => {
if (phase === 'packing') {
controller.abort();
}
},
signal: controller.signal,
};
},
],
])('rejects rather than downloading when %s', async (_label, build) => {
const download = vi.fn();
await expect(
executeInvkExport(planInvkExport(planInput), {
download,
fetchImageBytes: (imageName) => Promise.resolve(bytesFor(imageName)),
fetchImageThumbnail: () => Promise.resolve(null),
...build(),
})
).rejects.toMatchObject({ name: 'AbortError' });
expect(download).not.toHaveBeenCalled();
});
it('rejects a cumulative response refusal and cancels an active sibling fetch', async () => {
let settleFirstRead: (result: ReadableStreamReadResult<Uint8Array>) => void = () => undefined;
const firstRead = new Promise<ReadableStreamReadResult<Uint8Array>>((resolve) => {
settleFirstRead = resolve;
});
const firstReader = {
cancel: vi.fn(() => {
settleFirstRead({ done: true, value: undefined });
return Promise.resolve();
}),
read: vi.fn(() => firstRead),
releaseLock: vi.fn(),
};
const secondReader = {
cancel: vi.fn(() => Promise.resolve()),
read: vi
.fn()
.mockResolvedValueOnce({ done: false, value: new Uint8Array([1]) })
.mockResolvedValueOnce({ done: true, value: undefined }),
releaseLock: vi.fn(),
};
const secondBodyCancel = vi.fn(() => Promise.resolve());
const secondGetReader = vi.fn(() => {
// Complete the first response so a per-request budget bug fails instead of hanging.
settleFirstRead({ done: true, value: undefined });
return secondReader;
});
const responses = [
{
body: { cancel: vi.fn(() => Promise.resolve()), getReader: vi.fn(() => firstReader) },
headers: new Headers({ 'content-length': String(INVK_MAX_ARCHIVE_BYTES) }),
ok: true,
},
{
body: { cancel: secondBodyCancel, getReader: secondGetReader },
headers: new Headers({ 'content-length': '1' }),
ok: true,
},
] as unknown as Response[];
transportMocks.apiFetchRaw.mockImplementation(() => responses.shift());
const download = vi.fn();
await expect(
executeInvkExport(planInvkExport(planInput), {
download,
fetchImageThumbnail: () => Promise.resolve(null),
})
).rejects.toMatchObject({ reason: 'too-large' });
expect(download).not.toHaveBeenCalled();
expect(secondGetReader).not.toHaveBeenCalled();
expect(secondBodyCancel).toHaveBeenCalledTimes(1);
expect(firstReader.cancel).toHaveBeenCalledTimes(1);
});
});
/** board.json carries generated media absent from document references in the v2 archive. */
describe('board membership', () => {
const bytesFor = (name: string) => new Uint8Array([...name].map((character) => character.codePointAt(0)!));
const boardItem = (name: string, overrides: Record<string, unknown> = {}) => ({
category: 'general' as const,
kind: 'image' as const,
name,
starred: false,
...overrides,
});
const readBoard = async (blob: Blob) => {
const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));
return JSON.parse(readEntryText(entries.get('board.json')!));
};
const withInbox = (items: ReturnType<typeof boardItem>[]) => ({
...planInput,
boards: [{ archived: false, isInbox: true, items, name: 'My project' }],
});
it('carries board media the document never references', async () => {
const download = vi.fn();
const plan = planInvkExport(withInbox([boardItem('unreferenced.png', { category: 'user', starred: true })]));
expect(plan.transferItems.map((item) => item.name)).toEqual(['live-a.png', 'live-b.png', 'unreferenced.png']);
const result = await executeInvkExport(plan, {
download,
fetchImageBytes: (imageName) => Promise.resolve(bytesFor(imageName)),
fetchImageThumbnail: () => Promise.resolve(null),
});
expect(result.bundledImageCount).toBe(3);
const [blob] = download.mock.calls[0]! as [Blob];
const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));
expect(entries.has('images/unreferenced.png')).toBe(true);
// Category and starring travel: they are what the item was, not merely that it existed.
expect(await readBoard(blob)).toEqual({
boards: [
{
archived: false,
isInbox: true,
items: [{ category: 'user', kind: 'image', name: 'unreferenced.png', starred: true }],
name: 'My project',
},
],
version: 2,
});
});
it('carries every board of the project, each with its own media', async () => {
const download = vi.fn();
const plan = planInvkExport({
...planInput,
boards: [
{ archived: true, isInbox: false, items: [boardItem('old.png')], name: 'Old façades' },
{ archived: false, isInbox: true, items: [boardItem('inbox.png')], name: 'My project' },
],
});
// Items of every board are fetched once each; the inbox leads in the plan as in the file.
expect(plan.transferItems.map((item) => item.name)).toEqual(['inbox.png', 'live-a.png', 'live-b.png', 'old.png']);
await executeInvkExport(plan, {
download,
fetchImageBytes: (imageName) => Promise.resolve(bytesFor(imageName)),
fetchImageThumbnail: () => Promise.resolve(null),
});
const [blob] = download.mock.calls[0]! as [Blob];
expect(
(await readBoard(blob)).boards.map((board: { name: string; items: { name: string }[] }) => [
board.name,
board.items.map((item) => item.name),
])
).toEqual([
['My project', ['inbox.png']],
['Old façades', ['old.png']],
]);
});
/** Refused before a single round trip: discovering it after hundreds would be the wrong order. */
it('refuses a project that could never be packed, before fetching anything', () => {
const boardItems = Array.from({ length: 20_001 }, (_unused, index) => boardItem(`image-${index}.png`));
expect(() => planInvkExport(withInbox(boardItems))).toThrowError(/archive entries/u);
});
});