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
fix(webv2): hold every project-file surface to the rules it already documents
Josh Corbettbc89db1d970a
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 509356eb0d..269516d2e9 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -411,6 +411,7 @@"deleteProjectTabBody": "Delete \"{{name}}\"? The project and its saved copy on the server are removed permanently. To keep it in your library, close the tab instead.","deleteProjectWithEllipsis": "Delete project…","duplicateFailed": "Duplicate failed",+ "duplicating": "Duplicating project…","editedRelative": "Edited {{time}}","exportFailed": "Export failed","exported": "Exported \"{{name}}\"",diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsxindex 64644e39c1..3ed47bec3f 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx@@ -81,7 +81,13 @@ export const WorkbenchProvider = ({// mutates an open project through the sync engine rather than beside it.const openProjectBroker = createOpenProjectBroker({closeProject: (projectId) => {- store.commands.projects.close(projectId);+ // The last tab is not this handle's business. `close` refuses it *and* raises "at least one+ // project must remain open" — correct for someone closing a tab, wrong for a deletion,+ // which is not asking to keep working here. Leaving the editor is the caller's job+ // (`leaveEditorIfLast`), and it is already doing it.+ if (store.getSnapshot().projects.length > 1) {+ store.commands.projects.close(projectId);+ }},flushProject: async (projectId) => {const project = store.getSnapshot().projects.find((candidate) => candidate.id === projectId);@@ -98,6 +104,9 @@ export const WorkbenchProvider = ({store.commands.projects.rename(projectId, name);},subscribe: store.subscribe,+ unmarkProjectDeleted: (projectId) => {+ persistence.unmarkProjectDeleted(projectId);+ },});persistenceRuntime.start();diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts b/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.tsindex 278a0d06e3..a66863c65f 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts@@ -1,11 +1,6 @@import { toaster } from '@platform/ui';-import {- deleteLibraryProject,- duplicateLibraryProject,- renameLibraryProject,- type ProjectSummary,-} from '@workbench/projects/library';-import { useExportLibraryProject } from '@workbench/projects/useProjectFileActions';+import { deleteLibraryProject, renameLibraryProject, type ProjectSummary } from '@workbench/projects/library';+import { useDuplicateProject, useExportLibraryProject } from '@workbench/projects/useProjectFileActions';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -18,7 +13,8 @@ import { dropProjectPin } from './projectPins';*/export interface ProjectCardActions {rename: (name: string) => Promise<void>;- duplicate: () => Promise<void>;+ /** Reports its own progress and result, so there is nothing to await here. */+ duplicate: () => void;/** Reports its own progress and result, so there is nothing to await here. */export: () => void;delete: () => Promise<void>;@@ -27,6 +23,7 @@ export interface ProjectCardActions {export const useProjectCardActions = (summary: ProjectSummary): ProjectCardActions => {const { t } = useTranslation();const startExport = useExportLibraryProject();+ const startDuplicate = useDuplicateProject();const rename = useCallback(async (name: string) => {@@ -45,35 +42,12 @@ export const useProjectCardActions = (summary: ProjectSummary): ProjectCardActio[summary.id, t]);- const duplicate = useCallback(async () => {- try {- const { boardItemIssues, documentReferenceIssues, summary: copy } = await duplicateLibraryProject(summary.id);- // A copy that lost part of its board is not a failure — the project exists and opens — but it- // is not a plain success either, and the two counts mean different things: a missing board- // item is a result still findable elsewhere, a missing reference is a hole in the canvas.- const lost = [- ...(boardItemIssues.length === 0- ? []- : [t('projects.file.missingBoardItems', { count: boardItemIssues.length })]),- ...(documentReferenceIssues.length === 0- ? []- : [t('projects.file.missingReferences', { count: documentReferenceIssues.length })]),- ];-- toaster.create({- description:- lost.length === 0 ? t('projects.projectDuplicatedDescription', { name: copy.name }) : lost.join(' '),- title: t('projects.projectDuplicated'),- type: lost.length === 0 ? 'success' : 'warning',- });- } catch (error) {- toaster.create({- description: error instanceof Error ? error.message : undefined,- title: t('projects.duplicateFailed'),- type: 'error',- });- }- }, [summary.id, t]);+ // Progress, partial success and error translation all come from the shared reporter — the same+ // one import and export use. Duplication runs the same restore engine over the same board, so a+ // hand-rolled toast here only meant it reported that work differently from its twins.+ const duplicate = useCallback(() => {+ startDuplicate(summary.id);+ }, [startDuplicate, summary.id]);const exportProject = useCallback(() => {startExport(summary.id, summary.name);diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.tsindex 8fff1127ca..79506d51de 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts@@ -79,6 +79,9 @@ const openProject = (projectId: string, calls: string[] = []) => {return Promise.resolve();}),+ unmarkDeleted: vi.fn(() => {+ calls.push('unmarkDeleted');+ }),};syncStore.registerOpenProject(projectId, handle);@@ -223,6 +226,21 @@ describe('library mutations', () => {expect(api.deleteProject).toHaveBeenCalledWith('open', expect.any(AbortSignal));});+ /**+ * A project left marked deleted never autosaves again for the rest of the session, and nothing+ * says so. Unmarking belongs here, beside the mark, rather than in each caller's catch — one of+ * the two that had to remember it did not.+ */+ it('lets an open project save again when its deletion fails', async () => {+ api.deleteProject.mockRejectedValue(new Error('offline'));++ const { calls } = openProject('open');++ await expect(library.deleteLibraryProject('open')).rejects.toThrow('offline');++ expect(calls).toEqual(['markDeleted', 'unmarkDeleted']);+ });+it('takes a deleted project out of the saved session', async () => {api.deleteProject.mockResolvedValue(undefined);api.getClientStateValue.mockResolvedValue(diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.tsindex 9507d94118..49704b4a39 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts@@ -211,7 +211,17 @@ export const deleteLibraryProject = async (projectId: string): Promise<void> =>// Marked before the request so an autosave in flight cannot recreate the project — and with it a// board — between the DELETE and the tab closing.openProject?.markDeleted();- await apiDeleteProject(projectId, owner.signal);++ try {+ await apiDeleteProject(projectId, owner.signal);+ } catch (error) {+ // Unmarked here rather than by the caller, because a project left marked stops autosaving for+ // the rest of the session — silently, and with no way to notice. Two of the three call sites+ // had to remember this and one of them did not.+ openProject?.unmarkDeleted();+ throw error;+ }+assertAccountScopeCurrent(owner);openProject?.close();forgetProjectCover(projectId, owner);@@ -293,8 +303,11 @@ export interface DuplicatedProject extends ProjectTransferIssues {* restore engine, which it shares — this is where the two directions meet, not a second* implementation of them.*/-export const duplicateLibraryProject = async (projectId: string): Promise<DuplicatedProject> => {- const owner = captureAccountScope();+export const duplicateLibraryProject = async (+ projectId: string,+ options: { onProgress?: (progress: { completed: number; total: number }) => void; owner?: AccountScope } = {}+): Promise<DuplicatedProject> => {+ const owner = options.owner ?? captureAccountScope();const record = await readProjectForDuplication(projectId, owner);assertAccountScopeCurrent(owner);@@ -304,7 +317,10 @@ export const duplicateLibraryProject = async (projectId: string): Promise<DuplicassertAccountScopeCurrent(owner);const { duplicateProjectRecord } = await import('./invk/duplicateProject');- const duplicated = await duplicateProjectRecord({ boardItems: snapshot.items, owner, record });+ const duplicated = await duplicateProjectRecord(+ { boardItems: snapshot.items, owner, record },+ options.onProgress ? { onProgress: options.onProgress } : {}+ );assertAccountScopeCurrent(owner);diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.tsindex 4171aecad0..cf068d7dd6 100644--- a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts@@ -17,6 +17,7 @@ const createHarness = () => {getOpenProjectIds: vi.fn(() => openIds),markProjectDeleted: vi.fn(),renameProject: vi.fn(),+ unmarkProjectDeleted: vi.fn(),subscribe: (listener: () => void) => {listeners.add(listener);diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.tsindex 7ebe4e4228..dc7ff0884b 100644--- a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts@@ -21,6 +21,8 @@ export interface OpenProjectBrokerDeps {getOpenProjectIds: () => string[];/** Stop the autosave recreating a project that is being deleted. */markProjectDeleted: (projectId: string) => void;+ /** Let it save again after a deletion that failed. */+ unmarkProjectDeleted: (projectId: string) => void;renameProject: (projectId: string, name: string) => void;subscribe: (listener: () => void) => () => void;}@@ -43,6 +45,7 @@ export const createOpenProjectBroker = (deps: OpenProjectBrokerDeps): OpenProjecdeps.renameProject(projectId, name);await deps.flushProject(projectId);},+ unmarkDeleted: () => deps.unmarkProjectDeleted(projectId),});const sync = (): void => {diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.tsindex 323942f43c..24e3c09cec 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type { ProjectBoardItemDTO } from './api';import type * as coversModule from './covers';+import type * as assetTransportModule from './invk/assetTransport';import type * as projectFileModule from './projectFile';import type * as persistenceModule from './syncedPersistence';@@ -75,7 +76,13 @@ vi.mock('./covers', async (importOriginal) => ({recordProjectCover: covers.recordProjectCover,}));vi.mock('@platform/browser/downloadBlob', () => downloads);-vi.mock('./invk/assetTransport', () => transport);+// Partial, so the module's pure predicates stay real. `isRequestCancellation` decides whether a+// failure is this asset's or the whole operation's — a stub of it would let the tests agree with a+// restore that mistook a cancelled import for three hundred dangling references.+vi.mock('./invk/assetTransport', async (importOriginal) => ({+ ...(await importOriginal<typeof assetTransportModule>()),+ ...transport,+}));let projectFile: typeof projectFileModule;let persistence: typeof persistenceModule;@@ -221,6 +228,59 @@ describe('exportLibraryProject', () => {expect(api.getProject).toHaveBeenCalledWith('p1', expect.anything());expect(downloads.downloadBlob.mock.calls[0]![1]).toBe('Closed.invk');});++ /**+ * This is reachable from a project card and from the gallery board menu, both of which can be on+ * screen while the editor holds that project — and the board most likely to be right-clicked is+ * the open project's own. Reading the server record without flushing first hands someone a file+ * missing everything since the last autosave.+ */+ it('flushes an open project before reading its record', async () => {+ const { registerOpenProject, unregisterOpenProject } = await import('./syncStore');+ const order: string[] = [];+ const flush = vi.fn(() => {+ order.push('flush');+ return Promise.resolve();+ });++ api.getProject.mockImplementation(() => {+ order.push('get');++ return Promise.resolve({+ data: persistence.serializeProjectDocument({ ...createDraftProject([]), name: 'Open' }),+ name: 'Open',+ project_id: 'p1',+ revision: 3,+ });+ });+ registerOpenProject('p1', {+ close: vi.fn(),+ flush,+ markDeleted: vi.fn(),+ rename: vi.fn(),+ unmarkDeleted: vi.fn(),+ });++ try {+ await projectFile.exportLibraryProject('p1');+ } finally {+ unregisterOpenProject('p1');+ }++ expect(flush).toHaveBeenCalledTimes(1);+ expect(order).toEqual(['flush', 'get']);+ });++ it('does not flush a project nothing holds', async () => {+ api.getProject.mockResolvedValue({+ data: persistence.serializeProjectDocument({ ...createDraftProject([]), name: 'Closed' }),+ name: 'Closed',+ project_id: 'p1',+ revision: 3,+ });++ await expect(projectFile.exportLibraryProject('p1')).resolves.toBeDefined();+ });});/**@@ -536,6 +596,45 @@ describe('importProjectFile', () => {expect(createRequest.data.id).toBe(createRequest.project_id);});+ /**+ * Export strips installation state, so its own archives never carry it — but import must not+ * rely on that. A legacy `.invokeproject.json`, a dev-build archive or a hand-edited one can all+ * arrive with a stranger's gallery selection, and the collector skips those keys, so a restore+ * can neither fetch what they point at nor report it as dangling.+ */+ it('strips a stranger’s gallery selection from a document it did not write', async () => {+ acceptCreate();+ const envelope = {+ document: {+ ...createDraftProject([]),+ name: 'Handed over',+ widgetInstances: {+ 'gallery-1': {+ state: {+ values: {+ compareImage: { imageName: 'theirs-compare.png', imageUrl: '' },+ selectedImage: { imageName: 'theirs-selected.png', kind: 'image' },+ selectedImageNames: ['image:theirs-selected.png'],+ },+ },+ typeId: 'gallery',+ },+ },+ },+ kind: 'invokeai-project',+ version: 1,+ };+ const file = new File([JSON.stringify(envelope)], 'handed-over.invokeproject.json');++ await projectFile.importProjectFile(file);++ const { data } = api.createProject.mock.calls[0]![0] as { data: Record<string, unknown> };+ const serialized = JSON.stringify(data);++ expect(serialized).not.toContain('theirs-compare.png');+ expect(serialized).not.toContain('theirs-selected.png');+ });+it('uploads only the images the server is missing', async () => {const project = createDraftProject([]);diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.tsindex 1782e56555..3cae079b64 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts@@ -22,7 +22,8 @@ import { recordProjectCover } from './covers';import { createProjectId } from './ids';import { INVK_EXTENSION, InvkFormatError } from './invk/format';import { upsertProjectSummary } from './library';-import { remapAssetRefs } from './projectAssets';+import { remapAssetRefs, stripInstallationState } from './projectAssets';+import { getOpenProject } from './syncStore';export const PROJECT_FILE_KIND = 'invokeai-project';export const PROJECT_FILE_VERSION = 1;@@ -206,12 +207,23 @@ const exportProjectDocument = async (};};-/** Export a closed project straight from its server record. */+/**+ * Export a project from its server record.+ *+ * Flushed first when the editor holds it, for the reason duplication is: the surfaces that call+ * this — a project card, a gallery board's menu — are reachable while that project is open, and the+ * board most likely to be right-clicked is the open project's own. Exporting what the server last+ * acknowledged would hand someone a file that silently omits the last ten minutes of their work.+ */export const exportLibraryProject = async (projectId: string,options: ProjectFileOptions = {}): Promise<ProjectExportOutcome> => {const owner = options.owner ?? captureAccountScope();++ await getOpenProject(projectId)?.flush();+ assertAccountScopeCurrent(owner);+const record = await apiGetProject(projectId, owner.signal);assertAccountScopeCurrent(owner);@@ -270,7 +282,11 @@ export const importProjectFile = async (typeof projectDocument.name === 'string' && projectDocument.name.trim()? projectDocument.name.trim(): 'Imported project';- const candidate = { ...projectDocument, id, name };+ // Stripped on the way in as well as on the way out, so the rule holds for documents this app did+ // not write: a legacy `.invokeproject.json`, an archive from a dev build, a hand-edited one. A+ // stranger's `selectedImage`/`compareImage` would otherwise arrive intact and unfixable — the+ // collector skips those keys, so the restore can neither fetch them nor report them as dangling.+ const candidate = { ...stripInstallationState(projectDocument), id, name };// Full validation rehydrates the document through the Workbench reducer, so// it is loaded here rather than imported: the Launchpad should not carry the// editor's aggregate state just to offer an Import button.diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts b/invokeai/frontend/webv2/src/workbench/projects/syncStore.tsindex 18102b4dcd..96cc718db9 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts@@ -63,6 +63,13 @@ export interface OpenProjectHandle {flush: () => Promise<void>;/** Stop the autosave from recreating this project while it is being deleted. */markDeleted: () => void;+ /**+ * Undo {@link markDeleted} after a deletion that did not happen.+ *+ * Paired with it here rather than left to call sites, because a project left marked never+ * autosaves again for the rest of the session — a silent, unrecoverable failure to notice.+ */+ unmarkDeleted: () => void;/** Rename through the reducer, then flush — so the project and its board rename together. */rename: (name: string) => Promise<void>;}diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.tsindex ffaa4979fe..86621e5815 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts@@ -9,7 +9,9 @@ import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import type { ProjectRecordDTO } from './api';+import type { DuplicatedProject } from './library';+import { duplicateLibraryProject } from './library';import { exportLibraryProject, exportOpenProject, importProjectFile, pickProjectFile } from './projectFile';import { startProjectFileReport } from './projectFileToasts';@@ -102,6 +104,42 @@ export const useExportLibraryProject = (): ((projectId: string, name: string) =>);};+/**+ * Duplicate a project, reported like the transfers it shares its engine with.+ *+ * Duplication is a project file operation in everything but the file: same restore, same partial+ * success, same durations. It reported none of that — no progress for the whole server-side copy,+ * and `InvkFormatError`'s developer message straight into a toast on failure.+ */+export const useDuplicateProject = (+ onDuplicated?: (duplicated: DuplicatedProject) => Promise<void> | void+): ((projectId: string) => void) => {+ const { t } = useTranslation();++ return useCallback(+ (projectId: string) => {+ void runReported(+ t,+ { failed: t('projects.duplicateFailed'), running: t('projects.duplicating') },+ async (report, owner) => {+ const duplicated = await duplicateLibraryProject(projectId, {+ // Everything a duplication moves is restored onto the copy's board, so the phase is+ // fixed. Naming it here keeps the reporting vocabulary in the reporting layer.+ onProgress: ({ completed, total }) => report.report({ completed, phase: 'restoring', total }),+ owner,+ });++ assertAccountScopeCurrent(owner);+ report.succeed(t('projects.projectDuplicated'), duplicated);+ await onDuplicated?.(duplicated);+ assertAccountScopeCurrent(owner);+ }+ );+ },+ [onDuplicated, t]+ );+};+/** Export a project that is open in the editor, from its live document. */export const useExportOpenProject = (): ((project: Project) => void) => {const { t } = useTranslation();