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(webv2): report project file progress and partial success

joshistoast78271e1ec140
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index f044b05c83..b32e2ba1de 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -413,11 +413,18 @@
"duplicateFailed": "Duplicate failed",
"editedRelative": "Edited {{time}}",
"exportFailed": "Export failed",
+ "exported": "Exported \"{{name}}\"",
+ "exporting": "Exporting \"{{name}}\"…",
"failedToLoad": "Failed to load your projects.",
"file": {
+ "bundlingProgress": "Bundling {{completed}} of {{total}} assets…",
"damaged": "This project file is damaged and cannot be opened.",
"legacyCanvasProject": "This is a canvas project from an earlier version of Invoke, which cannot be opened here.",
+ "missingAssets_one": "1 asset could not be included.",
+ "missingAssets_other": "{{count}} assets could not be included.",
"notAProject": "This file is not an Invoke project.",
+ "packing": "Packing the archive…",
+ "restoringProgress": "Restoring {{completed}} of {{total}} assets…",
"tooLarge": "This project file is too large to open.",
"unsupportedVersion": "This project file was written by a newer version of Invoke."
},
@@ -431,7 +438,9 @@
"today": "Today",
"week": "Earlier this week"
},
+ "imported": "Imported \"{{name}}\"",
"importFailed": "Import failed",
+ "importing": "Importing project…",
"importWithEllipsis": "Import…",
"libraryDescription": "Every project saved to your account.",
"listView": "List view",
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/pages/HomePage.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/pages/HomePage.tsx
index 057095782e..89d89cd42d 100644
--- a/invokeai/frontend/webv2/src/workbench/launchpad/pages/HomePage.tsx
+++ b/invokeai/frontend/webv2/src/workbench/launchpad/pages/HomePage.tsx
@@ -1,14 +1,12 @@
/* eslint-disable react-perf/jsx-no-jsx-as-prop */
+import type { ProjectRecordDTO } from '@workbench/projects/api';
+
import { Skeleton, Stack, Text } from '@chakra-ui/react';
import { useAuthSession, useCapabilities } from '@features/identity';
import { LAUNCHPAD_READY_MARK, markSemanticReady } from '@platform/performance/semanticReady';
import { useMountEffect } from '@platform/react/useMountEffect';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
-import { Button, toaster } from '@platform/ui';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { Button } from '@platform/ui';
import { PageShell } from '@platform/ui/PageShell';
import { Link, useNavigate } from '@tanstack/react-router';
import { IntentTiles } from '@workbench/launchpad/home/IntentTiles';
@@ -19,8 +17,7 @@ import { KnownBrowserIssuesAlert } from '@workbench/launchpad/KnownBrowserIssues
import { prunePinnedProjects, toggleProjectPinPreference } from '@workbench/launchpad/projects/projectPins';
import { getProjectLibrary, refreshProjectLibrary, useProjectLibrarySelector } from '@workbench/projects/library';
import { refreshOpenProjects } from '@workbench/projects/openProjects';
-import { importProjectFile, pickProjectFile } from '@workbench/projects/projectFile';
-import { describeProjectFileError } from '@workbench/projects/projectFileErrors';
+import { useImportProjectFile } from '@workbench/projects/useProjectFileActions';
import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { FileUpIcon, PlusIcon } from 'lucide-react';
import { useCallback } from 'react';
@@ -66,33 +63,13 @@ export const HomePage = () => {
? t('launchpad.projectsGreetingWithName', { name: displayName })
: t('launchpad.projectsGreeting');
- const handleImport = useCallback(async () => {
- const owner = captureAccountScope();
- const file = await pickProjectFile(owner);
-
- if (!file || !isAccountScopeCurrent(owner)) {
- return;
- }
-
- try {
- const record = await importProjectFile(file, owner);
-
- assertAccountScopeCurrent(owner);
+ const openImportedProject = useCallback(
+ async (record: ProjectRecordDTO) => {
await navigate({ search: { project: record.project_id }, to: '/app' });
- assertAccountScopeCurrent(owner);
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- toaster.create({
- description: describeProjectFileError(error, t),
- title: t('projects.importFailed'),
- type: 'error',
- });
- }
- }, [navigate, t]);
- const handleImportClick = useCallback(() => void handleImport(), [handleImport]);
+ },
+ [navigate]
+ );
+ const handleImportClick = useImportProjectFile(openImportedProject);
const isFirstLoad = summaries.length === 0 && (status === 'idle' || status === 'loading');
const [mostRecent, ...rest] = summaries;
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx
index b525cabc63..4af7e0b3c3 100644
--- a/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx
+++ b/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx
@@ -1,15 +1,12 @@
/* eslint-disable react-perf/jsx-no-jsx-as-prop */
import type { ProjectSortId, ProjectsViewId } from '@workbench/launchpad/projects/projectLibraryView';
+import type { ProjectRecordDTO } from '@workbench/projects/api';
import { Stack } from '@chakra-ui/react';
import { LAUNCHPAD_READY_MARK, markSemanticReady } from '@platform/performance/semanticReady';
import { useMountEffect } from '@platform/react/useMountEffect';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
-import { Button, toaster } from '@platform/ui';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { Button } from '@platform/ui';
import { PageShell } from '@platform/ui/PageShell';
import { Link, useNavigate } from '@tanstack/react-router';
import { KnownBrowserIssuesAlert } from '@workbench/launchpad/KnownBrowserIssuesAlert';
@@ -18,8 +15,7 @@ import { ProjectsBrowser } from '@workbench/launchpad/projects/ProjectsBrowser';
import { ProjectsToolbar } from '@workbench/launchpad/projects/ProjectsToolbar';
import { getProjectLibrary, refreshProjectLibrary } from '@workbench/projects/library';
import { refreshOpenProjects } from '@workbench/projects/openProjects';
-import { importProjectFile, pickProjectFile } from '@workbench/projects/projectFile';
-import { describeProjectFileError } from '@workbench/projects/projectFileErrors';
+import { useImportProjectFile } from '@workbench/projects/useProjectFileActions';
import { patchWorkbenchPreferences, useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { FileUpIcon, PlusIcon } from 'lucide-react';
import { useCallback, useState } from 'react';
@@ -67,33 +63,13 @@ export const ProjectsPage = () => {
}, []);
const handleClearSearch = useCallback(() => setSearchTerm(''), []);
- const handleImport = useCallback(async () => {
- const owner = captureAccountScope();
- const file = await pickProjectFile(owner);
-
- if (!file || !isAccountScopeCurrent(owner)) {
- return;
- }
-
- try {
- const record = await importProjectFile(file, owner);
-
- assertAccountScopeCurrent(owner);
+ const openImportedProject = useCallback(
+ async (record: ProjectRecordDTO) => {
await navigate({ search: { project: record.project_id }, to: '/app' });
- assertAccountScopeCurrent(owner);
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- toaster.create({
- description: describeProjectFileError(error, t),
- title: t('projects.importFailed'),
- type: 'error',
- });
- }
- }, [navigate, t]);
- const handleImportClick = useCallback(() => void handleImport(), [handleImport]);
+ },
+ [navigate]
+ );
+ const handleImportClick = useImportProjectFile(openImportedProject);
return (
<PageShell
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts b/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts
index 65d1437f3c..994c6cb6d3 100644
--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts
@@ -5,8 +5,7 @@ import {
renameLibraryProject,
type ProjectSummary,
} from '@workbench/projects/library';
-import { exportLibraryProject } from '@workbench/projects/projectFile';
-import { describeProjectFileError } from '@workbench/projects/projectFileErrors';
+import { useExportLibraryProject } from '@workbench/projects/useProjectFileActions';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -20,12 +19,14 @@ import { dropProjectPin } from './projectPins';
export interface ProjectCardActions {
rename: (name: string) => Promise<void>;
duplicate: () => Promise<void>;
- export: () => Promise<void>;
+ /** Reports its own progress and result, so there is nothing to await here. */
+ export: () => void;
delete: () => Promise<void>;
}
export const useProjectCardActions = (summary: ProjectSummary): ProjectCardActions => {
const { t } = useTranslation();
+ const startExport = useExportLibraryProject();
const rename = useCallback(
async (name: string) => {
@@ -62,17 +63,9 @@ export const useProjectCardActions = (summary: ProjectSummary): ProjectCardActio
}
}, [summary.id, t]);
- const exportProject = useCallback(async () => {
- try {
- await exportLibraryProject(summary.id);
- } catch (error) {
- toaster.create({
- description: describeProjectFileError(error, t),
- title: t('projects.exportFailed'),
- type: 'error',
- });
- }
- }, [summary.id, t]);
+ const exportProject = useCallback(() => {
+ startExport(summary.id, summary.name);
+ }, [startExport, summary.id, summary.name]);
const deleteProject = useCallback(async () => {
try {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx
index 2beb6bb974..64b2ce3045 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx
@@ -1,3 +1,5 @@
+import type { ProjectRecordDTO } from '@workbench/projects/api';
+
import { Dialog, Icon, Portal, Spinner, Stack, Text } from '@chakra-ui/react';
import { flushGenerateDrafts } from '@features/generation/react';
import { useMountEffect } from '@platform/react/useMountEffect';
@@ -10,8 +12,7 @@ import { areArraysEqual } from '@platform/state/selectors';
import { Button, CloseButton, Row, Scrollable } from '@platform/ui';
import { formatRelativeTime } from '@workbench/launchpad/formatRelativeTime';
import { refreshProjectLibrary, useProjectLibrarySelector, type ProjectSummary } from '@workbench/projects/library';
-import { importProjectFile, pickProjectFile } from '@workbench/projects/projectFile';
-import { describeProjectFileError } from '@workbench/projects/projectFileErrors';
+import { useImportProjectFile } from '@workbench/projects/useProjectFileActions';
import { useNotify } from '@workbench/useNotify';
import {
useWorkbenchCommands,
@@ -90,18 +91,8 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClos
[notify, onClose, persistence, projects, t]
);
- const handleImport = useCallback(async () => {
- const owner = captureAccountScope();
- const file = await pickProjectFile(owner);
-
- if (!file || !isAccountScopeCurrent(owner)) {
- return;
- }
-
- try {
- const record = await importProjectFile(file, owner);
-
- assertAccountScopeCurrent(owner);
+ const openImportedProject = useCallback(
+ (record: ProjectRecordDTO) => {
const project = persistence.adoptProjectRecord(record);
if (project) {
@@ -109,14 +100,10 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClos
projects.open(project);
onClose();
}
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- notify.error(t('projects.importFailed'), describeProjectFileError(error, t));
- }
- }, [notify, onClose, persistence, projects, t]);
+ },
+ [onClose, persistence, projects]
+ );
+ const handleImport = useImportProjectFile(openImportedProject);
const handleOpenChange = useCallback(
(event: { open: boolean }) => {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
index 6edf216cf9..1373d0c1f0 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
@@ -23,9 +23,16 @@ const downloads = vi.hoisted(() => ({ downloadBlob: vi.fn(), downloadText: vi.fn
const transport = vi.hoisted(() => ({
coverExtensionForMime: () => 'webp',
- fetchImageBytes: vi.fn((imageName: string) => Promise.resolve(new TextEncoder().encode(`bytes:${imageName}`))),
+ // `Uint8Array | null` up front: a fetcher that returns `null` is how the
+ // "server would not serve it" path is exercised, and inferring the narrower
+ // type here would make that untypeable at the call site.
+ fetchImageBytes: vi.fn((imageName: string): Promise<Uint8Array | null> =>
+ Promise.resolve(new TextEncoder().encode(`bytes:${imageName}`))
+ ),
fetchImageThumbnail: vi.fn(() => Promise.resolve(null)),
- fetchVideoBytes: vi.fn((videoName: string) => Promise.resolve(new TextEncoder().encode(`bytes:${videoName}`))),
+ fetchVideoBytes: vi.fn((videoName: string): Promise<Uint8Array | null> =>
+ Promise.resolve(new TextEncoder().encode(`bytes:${videoName}`))
+ ),
findExistingImageNames: vi.fn((_names: readonly string[]) => Promise.resolve(new Set<string>())),
findExistingVideoNames: vi.fn((_names: readonly string[]) => Promise.resolve(new Set<string>())),
mimeForEntryName: () => 'image/png',
@@ -137,6 +144,87 @@ describe('exportLibraryProject', () => {
});
});
+/**
+ * Both directions can half-succeed, and both used to compute exactly what was
+ * lost and then discard it — so a project that shed forty layers looked like a
+ * clean round trip. These pin the reporting all the way out to the caller.
+ */
+describe('what a transfer reports', () => {
+ const projectWithImages = () => ({
+ ...createDraftProject([]),
+ canvas: {
+ document: {
+ layers: [
+ { id: 'l1', source: { image: { height: 1, imageName: 'a.png', width: 1 }, type: 'image' } },
+ { id: 'l2', source: { image: { height: 1, imageName: 'b.png', width: 1 }, type: 'image' } },
+ ],
+ },
+ },
+ name: 'Two layers',
+ });
+
+ it('counts every asset as it is bundled, then reports packing', async () => {
+ const document = { ...persistence.serializeProjectDocument(createDraftProject([])), ...projectWithImages() };
+ const onProgress = vi.fn();
+
+ api.getProject.mockResolvedValue({ data: document, name: 'Two layers', project_id: 'p1', revision: 1 });
+
+ await projectFile.exportLibraryProject('p1', { onProgress });
+
+ const phases = onProgress.mock.calls.map(([progress]) => progress.phase);
+
+ expect(phases.filter((phase: string) => phase === 'bundling')).toHaveLength(2);
+ expect(phases.at(-1)).toBe('packing');
+ });
+
+ it('names the assets the server would not serve', async () => {
+ const document = { ...persistence.serializeProjectDocument(createDraftProject([])), ...projectWithImages() };
+
+ api.getProject.mockResolvedValue({ data: document, name: 'Two layers', project_id: 'p1', revision: 1 });
+ transport.fetchImageBytes.mockImplementation((imageName: string) =>
+ Promise.resolve(imageName === 'b.png' ? null : new TextEncoder().encode('bytes'))
+ );
+
+ const outcome = await projectFile.exportLibraryProject('p1');
+
+ expect(outcome.missingAssetNames).toEqual(['b.png']);
+ expect(outcome.fileName).toBe('Two layers.invk');
+ });
+
+ it('reports nothing lost for a clean export', async () => {
+ const document = { ...persistence.serializeProjectDocument(createDraftProject([])), ...projectWithImages() };
+
+ api.getProject.mockResolvedValue({ data: document, name: 'Two layers', project_id: 'p1', revision: 1 });
+
+ const outcome = await projectFile.exportLibraryProject('p1');
+
+ expect(outcome.missingAssetNames).toEqual([]);
+ });
+
+ it('counts uploads on the way in, and names what stayed dangling', async () => {
+ const document = { ...persistence.serializeProjectDocument(createDraftProject([])), ...projectWithImages() };
+ const onProgress = vi.fn();
+
+ acceptCreate();
+ api.getProject.mockResolvedValue({ data: document, name: 'Two layers', project_id: 'p1', revision: 1 });
+ await projectFile.exportLibraryProject('p1');
+
+ const archive = capturedArchive();
+
+ // Neither image is on the receiving server, and one of them will not upload.
+ transport.uploadArchiveImage.mockImplementation((_bytes: Uint8Array, fileName: string) =>
+ fileName === 'b.png'
+ ? Promise.reject(new Error('rejected'))
+ : Promise.resolve({ height: 1, imageName: `server-${fileName}`, width: 1 })
+ );
+
+ const outcome = await projectFile.importProjectFile(archive, { onProgress });
+
+ expect(outcome.danglingAssetNames).toEqual(['b.png']);
+ expect(onProgress.mock.calls.map(([progress]) => progress.phase)).toContain('restoring');
+ });
+});
+
describe('importProjectFile', () => {
it('round-trips an exported project under a fresh id', async () => {
const project = { ...createDraftProject([]), name: 'Exported project' };
@@ -144,7 +232,7 @@ describe('importProjectFile', () => {
acceptCreate();
await projectFile.exportOpenProject(project);
- const record = await projectFile.importProjectFile(capturedArchive());
+ const { record } = await projectFile.importProjectFile(capturedArchive());
expect(record.project_id).not.toBe(project.id);
expect(record.name).toBe('Exported project');
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
index b40fa44ddf..5460236c52 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
@@ -42,7 +42,51 @@ import { remapAssetRefs } from './projectAssets';
* with `await import()`. The Launchpad offers Import and Export on a route that
* never mounts the editor, and it should not pay for either until someone
* actually picks a file.
+ *
+ * ### Both directions report as they go, and report what they lost
+ *
+ * A project file is the one operation here whose duration is set by how much
+ * someone has drawn: a few hundred full-resolution layers is a few hundred
+ * round trips and hundreds of megabytes. Silence for that long reads as a
+ * broken button, so {@link ProjectFileProgress} is reported throughout.
+ *
+ * Both directions can also half-succeed. Export skips an asset the server will
+ * not serve; import leaves a reference dangling when the archive did not carry
+ * it and this server does not have it. Both were computed and discarded before,
+ * which made a project that lost forty layers indistinguishable from a clean
+ * round trip. They are returned now, and every call site says so.
+ */
+
+/**
+ * How far along a project file is.
+ *
+ * `bundling` and `restoring` count assets; `packing` is the single ZIP write at
+ * the end, which has no unit worth counting and is reported so the caller can
+ * stop showing a number that has stopped moving.
*/
+export interface ProjectFileProgress {
+ completed: number;
+ phase: 'bundling' | 'packing' | 'restoring';
+ total: number;
+}
+
+export interface ProjectFileOptions {
+ onProgress?: (progress: ProjectFileProgress) => void;
+ owner?: AccountScope;
+}
+
+export interface ProjectExportOutcome {
+ /** Assets the server would not serve. Their references still ship. */
+ missingAssetNames: string[];
+ /** The name the archive was downloaded under. */
+ fileName: string;
+}
+
+export interface ProjectImportOutcome {
+ /** Referenced assets neither the archive nor this server has. */
+ danglingAssetNames: string[];
+ record: ProjectRecordDTO;
+}
const readProjectDocument = async (file: File) => {
const { readInvkArchive } = await import('./invk/importProject');
@@ -53,9 +97,10 @@ const readProjectDocument = async (file: File) => {
const exportProjectDocument = async (
name: string,
projectDocument: Record<string, unknown>,
- owner: AccountScope
-): Promise<void> => {
+ options: Required<Pick<ProjectFileOptions, 'owner'>> & ProjectFileOptions
+): Promise<ProjectExportOutcome> => {
const { executeInvkExport, planInvkExport } = await import('./invk/exportProject');
+ const { onProgress, owner } = options;
assertAccountScopeCurrent(owner);
@@ -66,30 +111,41 @@ const exportProjectDocument = async (
projectDocument,
});
- await executeInvkExport(plan, { download: downloadBlob, signal: owner.signal });
+ const result = await executeInvkExport(plan, {
+ download: downloadBlob,
+ signal: owner.signal,
+ ...(onProgress === undefined ? {} : { onProgress }),
+ });
+
assertAccountScopeCurrent(owner);
+
+ return { fileName: plan.fileName, missingAssetNames: result.missingAssetNames };
};
/** Export a closed project straight from its server record. */
export const exportLibraryProject = async (
projectId: string,
- owner: AccountScope = captureAccountScope()
-): Promise<void> => {
+ options: ProjectFileOptions = {}
+): Promise<ProjectExportOutcome> => {
+ const owner = options.owner ?? captureAccountScope();
const record = await apiGetProject(projectId, owner.signal);
assertAccountScopeCurrent(owner);
- await exportProjectDocument(record.name, record.data, owner);
+
+ return exportProjectDocument(record.name, record.data, { ...options, owner });
};
/** Export an open project from its live in-memory document. */
export const exportOpenProject = async (
project: Project,
- owner: AccountScope = captureAccountScope()
-): Promise<void> => {
+ options: ProjectFileOptions = {}
+): Promise<ProjectExportOutcome> => {
+ const owner = options.owner ?? captureAccountScope();
const { serializeProjectDocument } = await import('./projectDocument');
assertAccountScopeCurrent(owner);
- await exportProjectDocument(project.name, serializeProjectDocument(project), owner);
+
+ return exportProjectDocument(project.name, serializeProjectDocument(project), { ...options, owner });
};
/**
@@ -100,14 +156,22 @@ export const exportOpenProject = async (
*/
export const importProjectFile = async (
file: File,
- owner: AccountScope = captureAccountScope()
-): Promise<ProjectRecordDTO> => {
+ options: ProjectFileOptions = {}
+): Promise<ProjectImportOutcome> => {
+ const owner = options.owner ?? captureAccountScope();
const contents = await readProjectDocument(file);
assertAccountScopeCurrent(owner);
const { restoreArchiveAssets } = await import('./invk/importProject');
- const restored = await restoreArchiveAssets(contents, { signal: owner.signal });
+ const restored = await restoreArchiveAssets(contents, {
+ signal: owner.signal,
+ ...(options.onProgress === undefined
+ ? {}
+ : {
+ onProgress: ({ completed, total }) => options.onProgress?.({ completed, phase: 'restoring', total }),
+ }),
+ });
assertAccountScopeCurrent(owner);
@@ -137,7 +201,7 @@ export const importProjectFile = async (
recordProjectCover(record.project_id, restored.coverImageName, owner);
}
- return record;
+ return { danglingAssetNames: restored.danglingAssetNames, record };
};
/** Open the browser's file picker for a project file; null when dismissed. */
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts
new file mode 100644
index 0000000000..a4b0b04a2e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts
@@ -0,0 +1,145 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as toastsModule from './projectFileToasts';
+
+/**
+ * What a project file says while it runs and when it stops.
+ *
+ * The two properties worth pinning are that it is *one* toast for the whole
+ * operation — a slow export must not stack a line per asset — and that a run
+ * which lost assets does not finish looking like a clean one.
+ */
+
+interface ToastOptions {
+ description?: string;
+ duration?: number;
+ title?: string;
+ type?: string;
+}
+
+const toaster = vi.hoisted(() => ({
+ create: vi.fn((_options: ToastOptions): string => 'toast-1'),
+ dismiss: vi.fn((_id: string) => undefined),
+ update: vi.fn((_id: string, _options: ToastOptions) => undefined),
+}));
+
+vi.mock('@platform/ui', () => ({ toaster }));
+
+let toasts: typeof toastsModule;
+
+/** Stands in for i18next: echoes the key with its interpolations, so both are assertable. */
+const t = (key: string, options?: Record<string, unknown>): string =>
+ options === undefined ? key : `${key}(${JSON.stringify(options)})`;
+
+beforeEach(async () => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ toasts = await import('./projectFileToasts');
+});
+
+describe('startProjectFileReport', () => {
+ it('opens one toast that cannot expire while the transfer runs', () => {
+ toasts.startProjectFileReport(t, 'projects.exporting');
+
+ expect(toaster.create).toHaveBeenCalledTimes(1);
+ expect(toaster.create.mock.calls[0]![0]).toMatchObject({
+ duration: Number.POSITIVE_INFINITY,
+ title: 'projects.exporting',
+ type: 'loading',
+ });
+ });
+
+ it('updates that one toast rather than creating another per step', () => {
+ const report = toasts.startProjectFileReport(t, 'projects.exporting');
+
+ report.report({ completed: 1, phase: 'bundling', total: 3 });
+ report.report({ completed: 2, phase: 'bundling', total: 3 });
+ report.succeed('projects.exported', []);
+
+ expect(toaster.create).toHaveBeenCalledTimes(1);
+ expect(toaster.update).toHaveBeenCalledTimes(3);
+ expect(toaster.update.mock.calls.every(([id]) => id === 'toast-1')).toBe(true);
+ });
+
+ it('counts assets while bundling and stops counting while packing', () => {
+ const report = toasts.startProjectFileReport(t, 'projects.exporting');
+
+ report.report({ completed: 2, phase: 'bundling', total: 7 });
+ expect(toaster.update.mock.calls[0]![1].description).toBe(
+ 'projects.file.bundlingProgress({"completed":2,"total":7})'
+ );
+
+ report.report({ completed: 7, phase: 'packing', total: 7 });
+ expect(toaster.update.mock.calls[1]![1].description).toBe('projects.file.packing');
+ });
+
+ it('counts uploads on the way back in', () => {
+ const report = toasts.startProjectFileReport(t, 'projects.importing');
+
+ report.report({ completed: 1, phase: 'restoring', total: 4 });
+
+ expect(toaster.update.mock.calls[0]![1].description).toBe(
+ 'projects.file.restoringProgress({"completed":1,"total":4})'
+ );
+ });
+
+ it('finishes a clean run as a plain success with nothing to explain', () => {
+ const report = toasts.startProjectFileReport(t, 'projects.exporting');
+
+ report.succeed('projects.exported', []);
+
+ expect(toaster.update).toHaveBeenCalledWith('toast-1', {
+ duration: undefined,
+ title: 'projects.exported',
+ type: 'success',
+ });
+ });
+
+ /** A project that lost forty layers must not read the same as one that lost none. */
+ it('finishes a lossy run as a warning naming the count', () => {
+ const report = toasts.startProjectFileReport(t, 'projects.exporting');
+
+ report.succeed('projects.exported', ['a.png', 'b.png']);
+
+ expect(toaster.update).toHaveBeenCalledWith('toast-1', {
+ description: 'projects.file.missingAssets({"count":2})',
+ duration: undefined,
+ title: 'projects.exported',
+ type: 'warning',
+ });
+ });
+
+ it('translates a format error into its reason rather than its message', async () => {
+ const { InvkFormatError } = await import('./invk/format');
+ const report = toasts.startProjectFileReport(t, 'projects.importing');
+
+ report.fail('projects.importFailed', new InvkFormatError('legacy-canvas-project'));
+
+ expect(toaster.update).toHaveBeenCalledWith('toast-1', {
+ description: 'projects.file.legacyCanvasProject',
+ duration: undefined,
+ title: 'projects.importFailed',
+ type: 'error',
+ });
+ });
+
+ it('passes through the message of an error that is not ours', () => {
+ const report = toasts.startProjectFileReport(t, 'projects.importing');
+
+ report.fail('projects.importFailed', new Error('The server is on fire.'));
+
+ expect(toaster.update.mock.calls[0]![1]).toMatchObject({
+ description: 'The server is on fire.',
+ type: 'error',
+ });
+ });
+
+ it('takes the toast down without a verdict when there is no one left to tell', () => {
+ const report = toasts.startProjectFileReport(t, 'projects.exporting');
+
+ report.dismiss();
+
+ expect(toaster.dismiss).toHaveBeenCalledWith('toast-1');
+ expect(toaster.update).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts
new file mode 100644
index 0000000000..678908d04a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts
@@ -0,0 +1,108 @@
+import { toaster } from '@platform/ui';
+
+import type { ProjectFileProgress } from './projectFile';
+
+import { describeProjectFileError } from './projectFileErrors';
+
+/**
+ * How a project file reports itself while it runs, and what it says when it is
+ * done.
+ *
+ * Every entry point — Home, the Projects page, the in-editor Open dialog, the
+ * project switcher, each project card — used to start one of these and then say
+ * nothing until it either finished or threw. For an operation whose duration is
+ * set by how much someone has drawn, that is a long silence: a few hundred
+ * full-resolution layers is a few hundred round trips and hundreds of megabytes.
+ * A button that appears to do nothing for two minutes gets pressed again.
+ *
+ * The reporter is one live toast rather than a new one per phase, so a slow
+ * export occupies one line and updates in place instead of stacking. It is
+ * deliberately unglamorous: a count, then a result. There is no progress bar,
+ * because the honest unit here is assets and the expensive one is bytes, and a
+ * bar drawn from the first would sit at 99% through the whole of the second.
+ *
+ * ### Half-success is a result, not a success
+ *
+ * Export skips assets the server will not serve; import leaves references
+ * dangling when neither the archive nor this server has them. Both are correct
+ * — a project that exports every layer but one is far more use than one that
+ * refuses — but both are things the person holding the file needs to know
+ * before they hand it to someone else. So a lossy run finishes as a warning
+ * naming the count, and only a clean one finishes as a plain success.
+ */
+
+/** i18next's `t`, narrowed to what this module needs. */
+type Translate = (key: string, options?: Record<string, unknown>) => string;
+
+export interface ProjectFileReporter {
+ /**
+ * Take the toast down without a verdict, for the one case that has none: the
+ * account went away, so the operation belongs to a session that is over.
+ */
+ dismiss: () => void;
+ /** Update the live toast from a transfer's progress. */
+ report: (progress: ProjectFileProgress) => void;
+ /**
+ * Finish cleanly, or as a warning naming what was left behind. `lostAssetNames`
+ * is the export's `missingAssetNames` or the import's `danglingAssetNames`.
+ */
+ succeed: (title: string, lostAssetNames: readonly string[]) => void;
+ /** Finish as a failure, translating an `InvkFormatError` reason where there is one. */
+ fail: (title: string, error: unknown) => void;
+}
+
+const describeProgress = (t: Translate, progress: ProjectFileProgress): string => {
+ if (progress.phase === 'packing') {
+ return t('projects.file.packing');
+ }
+
+ const key = progress.phase === 'bundling' ? 'projects.file.bundlingProgress' : 'projects.file.restoringProgress';
+
+ return t(key, { completed: progress.completed, total: progress.total });
+};
+
+/**
+ * Open the live toast for a transfer that is starting. The returned reporter
+ * owns that toast for the rest of the operation; every path through a caller's
+ * `try`/`catch` has to end in `succeed` or `fail`, or the toast stays up.
+ */
+export const startProjectFileReport = (t: Translate, title: string): ProjectFileReporter => {
+ const id = toaster.create({
+ // No duration: a transfer ends when it ends, and a toast that expired
+ // mid-export would leave the operation invisible again.
+ duration: Number.POSITIVE_INFINITY,
+ title,
+ type: 'loading',
+ });
+
+ const settle = (options: { description?: string; title: string; type: 'error' | 'success' | 'warning' }): void => {
+ toaster.update(id, { ...options, duration: undefined });
+ };
+
+ return {
+ dismiss: () => {
+ toaster.dismiss(id);
+ },
+ fail: (failureTitle, error) => {
+ const description = describeProjectFileError(error, t);
+
+ settle({ ...(description === undefined ? {} : { description }), title: failureTitle, type: 'error' });
+ },
+ report: (progress) => {
+ toaster.update(id, { description: describeProgress(t, progress) });
+ },
+ succeed: (successTitle, lostAssetNames) => {
+ if (lostAssetNames.length === 0) {
+ settle({ title: successTitle, type: 'success' });
+
+ return;
+ }
+
+ settle({
+ description: t('projects.file.missingAssets', { count: lostAssetNames.length }),
+ title: successTitle,
+ type: 'warning',
+ });
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts
new file mode 100644
index 0000000000..2f982b13e4
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts
@@ -0,0 +1,123 @@
+import type { Project } from '@workbench/projectContracts';
+
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { ProjectRecordDTO } from './api';
+
+import { exportLibraryProject, exportOpenProject, importProjectFile, pickProjectFile } from './projectFile';
+import { startProjectFileReport } from './projectFileToasts';
+
+/**
+ * Picking, importing and exporting a project file, with the reporting attached.
+ *
+ * Five surfaces offer these — Home, the Projects page, the in-editor Open
+ * dialog, the project switcher, and every project card — and each had written
+ * out the same twenty lines of scope capture, picker, try/catch and toast. They
+ * had already drifted: the import sites checked the account scope before
+ * showing an error and the export sites did not, so cancelling an export by
+ * signing out produced a toast written for a developer.
+ *
+ * Keeping the sequence in one place is what makes progress and partial-success
+ * reporting land on all five at once rather than on whichever was edited last.
+ * What differs between call sites is only what happens with the imported record,
+ * which is the callback.
+ */
+
+/** Runs the sequence, keeping the toast and the account scope in step. */
+const runReported = async <T>(
+ t: (key: string, options?: Record<string, unknown>) => string,
+ titles: { failed: string; running: string },
+ run: (report: ReturnType<typeof startProjectFileReport>, owner: ReturnType<typeof captureAccountScope>) => Promise<T>
+): Promise<void> => {
+ const owner = captureAccountScope();
+ const report = startProjectFileReport(t, titles.running);
+
+ try {
+ await run(report, owner);
+ } catch (error) {
+ // An operation cancelled by the account going away failed on purpose, and
+ // its error is written for a developer. There is no verdict to show,
+ // because there is no longer anyone the verdict is about.
+ if (!isAccountScopeCurrent(owner)) {
+ report.dismiss();
+
+ return;
+ }
+
+ report.fail(titles.failed, error);
+ }
+};
+
+/**
+ * Import from the file picker. Resolves without doing anything if the picker is
+ * dismissed — no toast is opened for a decision not to import.
+ */
+export const useImportProjectFile = (onImported: (record: ProjectRecordDTO) => Promise<void> | void): (() => void) => {
+ const { t } = useTranslation();
+
+ const importFile = useCallback(async () => {
+ const owner = captureAccountScope();
+ const file = await pickProjectFile(owner);
+
+ if (!file || !isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ await runReported(t, { failed: t('projects.importFailed'), running: t('projects.importing') }, async (report) => {
+ const { danglingAssetNames, record } = await importProjectFile(file, { onProgress: report.report, owner });
+
+ assertAccountScopeCurrent(owner);
+ report.succeed(t('projects.imported', { name: record.name }), danglingAssetNames);
+ await onImported(record);
+ assertAccountScopeCurrent(owner);
+ });
+ }, [onImported, t]);
+
+ return useCallback(() => void importFile(), [importFile]);
+};
+
+/** Export a project that is only a library row — its document comes from the server. */
+export const useExportLibraryProject = (): ((projectId: string, name: string) => void) => {
+ const { t } = useTranslation();
+
+ return useCallback(
+ (projectId: string, name: string) => {
+ void runReported(
+ t,
+ { failed: t('projects.exportFailed'), running: t('projects.exporting', { name }) },
+ async (report, owner) => {
+ const { missingAssetNames } = await exportLibraryProject(projectId, { onProgress: report.report, owner });
+
+ report.succeed(t('projects.exported', { name }), missingAssetNames);
+ }
+ );
+ },
+ [t]
+ );
+};
+
+/** Export a project that is open in the editor, from its live document. */
+export const useExportOpenProject = (): ((project: Project) => void) => {
+ const { t } = useTranslation();
+
+ return useCallback(
+ (project: Project) => {
+ void runReported(
+ t,
+ { failed: t('projects.exportFailed'), running: t('projects.exporting', { name: project.name }) },
+ async (report, owner) => {
+ const { missingAssetNames } = await exportOpenProject(project, { onProgress: report.report, owner });
+
+ report.succeed(t('projects.exported', { name: project.name }), missingAssetNames);
+ }
+ );
+ },
+ [t]
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx
index 7262619524..ff63bd3116 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx
@@ -14,10 +14,8 @@ import { QueueCircularProgress } from '@workbench/components/QueueProgressIndica
import { formatRelativeTime } from '@workbench/launchpad/formatRelativeTime';
import { OpenProjectDialog } from '@workbench/projects/components';
import { refreshProjectLibrary, useProjectLibrarySelector } from '@workbench/projects/library';
-import { exportOpenProject } from '@workbench/projects/projectFile';
-import { describeProjectFileError } from '@workbench/projects/projectFileErrors';
import { useProjectActions } from '@workbench/projects/useProjectActions';
-import { useNotify } from '@workbench/useNotify';
+import { useExportOpenProject } from '@workbench/projects/useProjectFileActions';
import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
import {
useActiveProjectSelector,
@@ -57,7 +55,7 @@ export const ProjectSwitcher = () => {
const queries = useWorkbenchQueries();
const { projects } = useWorkbenchCommands();
const { closeProject, deleteProject, openProject } = useProjectActions();
- const notify = useNotify();
+ const startExport = useExportOpenProject();
const openWorkbenchWidget = useOpenWorkbenchWidget();
const [renameTarget, setRenameTarget] = useState<{ id: string; name: string } | null>(null);
const [deleteTarget, setDeleteTarget] = useState<{ id: string; name: string } | null>(null);
@@ -113,13 +111,11 @@ export const ProjectSwitcher = () => {
return;
}
- // Export bundles every image the project points at, so it can fail on a
- // dropped connection or a project past the archive ceiling. Silence would
- // read as "nothing happened" when the download never arrives.
- void exportOpenProject(project).catch((error: unknown) => {
- notify.error(t('projects.exportFailed'), describeProjectFileError(error, t));
- });
- }, [activeProjectId, getProject, notify, t]);
+ // Export bundles every image the project points at, so it runs for as long
+ // as the project is large and can fail on a dropped connection or a project
+ // past the archive ceiling. The reporter owns saying both.
+ startExport(project);
+ }, [activeProjectId, getProject, startExport]);
const closeActiveProject = useCallback(() => {
const project = getProject(activeProjectId);
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index 5d80b75e8e..994423cff0 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -40,9 +40,18 @@ const ROUTE_SHARED_MODULES = [
// The schema, the ZIP codec and the archive itself stay behind lazy imports.
'/workbench/projects/invk/format.ts',
'/workbench/projects/library.ts',
+ // Editor-eager through `syncedPersistence` (cover selection on every save)
+ // and Launchpad-eager through the import workflow. Pulling it out of the
+ // shared chunk to spare the Launchpad ~1.5 KB cost the editor a whole extra
+ // request, because nothing else would then group it — a round trip is the
+ // worse end of that trade.
'/workbench/projects/projectAssets.ts',
'/workbench/projects/projectFile.ts',
'/workbench/projects/projectFileErrors.ts',
+ // Both routes offer Import and Export, so both need the reporter and the
+ // hooks that drive it.
+ '/workbench/projects/projectFileToasts.ts',
+ '/workbench/projects/useProjectFileActions.ts',
'/workbench/settings/SettingsDialogHost.tsx',
] as const;