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
feat(webv2): duplicate complete projects
Josh Corbetta2212599f470
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts b/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.tsindex 994c6cb6d3..278a0d06e3 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts@@ -47,12 +47,24 @@ export const useProjectCardActions = (summary: ProjectSummary): ProjectCardActioconst duplicate = useCallback(async () => {try {- const copy = await duplicateLibraryProject(summary.id);+ 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: t('projects.projectDuplicatedDescription', { name: copy.name }),+ description:+ lost.length === 0 ? t('projects.projectDuplicatedDescription', { name: copy.name }) : lost.join(' '),title: t('projects.projectDuplicated'),- type: 'success',+ type: lost.length === 0 ? 'success' : 'warning',});} catch (error) {toaster.create({diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.tsindex d0edf360cc..54f514fdf4 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts@@ -553,6 +553,77 @@ export const uploadBoardVideo = async (return { videoName: dto.video_name };};+/** One copy the server made, under the identity it assigned. */+export interface CopiedMedia {+ name: string;+ sourceName: string;+}++export interface CopyMediaResult {+ /** Source names the server would not copy. Reported per name, never fatal for the batch. */+ failed: string[];+ copied: CopiedMedia[];+}++/**+ * Copy media onto a board without the bytes leaving the server.+ *+ * Duplication needs new identities for the same reason import does — `board_images` keys on the+ * image name — but both projects live on this one server, so round-tripping the pixels through the+ * browser would cost twice the board's size in traffic, two requests per item, and would run into+ * the same cumulative budget that bounds an export. The endpoint carries category, origin and the+ * metadata embedded in the PNG; starring is not part of a copy, so callers star afterwards through+ * the same path an import uses.+ */+export const copyImagesToBoard = async (+ imageNames: readonly string[],+ boardId: string,+ signal?: AbortSignal+): Promise<CopyMediaResult> => {+ if (imageNames.length === 0) {+ return { copied: [], failed: [] };+ }++ const body = await apiFetchJson<{+ copied?: { image_name: string; source_image_name: string }[];+ failed?: string[];+ }>(`${IMAGES_BASE}/copy`, {+ body: JSON.stringify({ board_id: boardId, image_names: imageNames }),+ method: 'POST',+ signal,+ });++ return {+ copied: (body.copied ?? []).map((entry) => ({ name: entry.image_name, sourceName: entry.source_image_name })),+ failed: body.failed ?? [],+ };+};++/** The same, for videos. */+export const copyVideosToBoard = async (+ videoNames: readonly string[],+ boardId: string,+ signal?: AbortSignal+): Promise<CopyMediaResult> => {+ if (videoNames.length === 0) {+ return { copied: [], failed: [] };+ }++ const body = await apiFetchJson<{+ copied?: { source_video_name: string; video_name: string }[];+ failed?: string[];+ }>(`${VIDEOS_BASE}/copy`, {+ body: JSON.stringify({ board_id: boardId, video_names: videoNames }),+ method: 'POST',+ signal,+ });++ return {+ copied: (body.copied ?? []).map((entry) => ({ name: entry.video_name, sourceName: entry.source_video_name })),+ failed: body.failed ?? [],+ };+};+/** Names the server would not star, out of the names asked for. */export interface BulkStarResult {failed: string[];diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.tsnew file mode 100644index 0000000000..a5dd8b6b83--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts@@ -0,0 +1,298 @@+import type { AccountScope } from '@platform/state/accountLifecycle';+import type { ProjectBoardItemDTO, ProjectRecordDTO } from '@workbench/projects/api';++import { createDraftProject } from '@workbench/workbenchState';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as duplicateProjectModule from './duplicateProject';++/**+ * Duplication end to end, with the copy endpoints and the project API replaced.+ *+ * The rules it has to keep are import's rules, because it is import's engine: board media takes new+ * identities, the document follows them, a failed copy cannot leave a reference pointing at the+ * original's image, and a failure before the create undoes exactly what it made.+ */++const api = vi.hoisted(() => ({+ createProject: vi.fn(),+ getProject: vi.fn(),+ isProjectNotFoundError: (error: unknown) =>+ typeof error === 'object' && error !== null && 'status' in error && error.status === 404,+}));++const transport = vi.hoisted(() => ({+ copyImagesToBoard: vi.fn(),+ copyVideosToBoard: vi.fn(),+ createStagingBoard: vi.fn(() => Promise.resolve('staging-board')),+ deleteArchiveImages: vi.fn(() => Promise.resolve()),+ deleteArchiveVideos: vi.fn(() => Promise.resolve()),+ deleteStagingBoard: vi.fn(() => Promise.resolve()),+ findExistingImageNames: vi.fn((names: readonly string[]) => Promise.resolve(new Set(names))),+ findExistingVideoNames: vi.fn((names: readonly string[]) => Promise.resolve(new Set(names))),+ mimeForEntryName: () => 'image/png',+ starImages: vi.fn(() => Promise.resolve({ failed: [] as string[] })),+ starVideos: vi.fn(() => Promise.resolve({ failed: [] as string[] })),+ uploadArchiveImage: vi.fn(() => Promise.reject(new Error('duplication uploads nothing'))),+ uploadArchiveVideo: vi.fn(() => Promise.reject(new Error('duplication uploads nothing'))),+}));++vi.mock('@workbench/projects/api', () => api);+vi.mock('./assetTransport', () => transport);++let duplicateProject: typeof duplicateProjectModule;+let owner: AccountScope;++const rasterImageLayer = (id: string, imageName: string) => ({+ blendMode: 'normal' as const,+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 1,+ source: { image: { height: 1, imageName, width: 1 }, type: 'image' as const },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster' as const,+});++const sourceRecord = (document: Record<string, unknown> = {}): ProjectRecordDTO => {+ const project = createDraftProject([]);++ return {+ board_id: 'source-board',+ created_at: '2026-06-10 10:00:00.000',+ data: {+ ...project,+ canvas: {+ ...project.canvas,+ document: { ...project.canvas.document, layers: [rasterImageLayer('l1', 'shared.png')] },+ },+ id: 'source',+ name: 'Source',+ ...document,+ },+ name: 'Source',+ project_id: 'source',+ revision: 4,+ updated_at: '2026-06-10 10:00:00.000',+ };+};++const boardItem = (overrides: Partial<ProjectBoardItemDTO> = {}): ProjectBoardItemDTO => ({+ category: 'general',+ kind: 'image',+ name: 'shared.png',+ starred: false,+ ...overrides,+});++const copiesOf = (names: readonly string[]) => ({+ copied: names.map((name) => ({ name: `copy-${name}`, sourceName: name })),+ failed: [] as string[],+});++const createdData = (): Record<string, unknown> =>+ (api.createProject.mock.calls[0]![0] as { data: Record<string, unknown> }).data;++const restoredLayerName = (): string =>+ (+ createdData().canvas as {+ document: { layers: { source: { image: { imageName: string } } }[] };+ }+ ).document.layers[0]!.source.image.imageName;++beforeEach(async () => {+ vi.resetModules();+ vi.clearAllMocks();++ const account = await import('@platform/state/accountLifecycle');++ account.accountLifecycle.activate('duplicate-user');+ owner = account.captureAccountScope();++ transport.createStagingBoard.mockImplementation(() => Promise.resolve('staging-board'));+ transport.copyImagesToBoard.mockImplementation((names: readonly string[]) => Promise.resolve(copiesOf(names)));+ transport.copyVideosToBoard.mockImplementation((names: readonly string[]) => Promise.resolve(copiesOf(names)));+ transport.findExistingImageNames.mockImplementation((names: readonly string[]) => Promise.resolve(new Set(names)));+ transport.findExistingVideoNames.mockImplementation((names: readonly string[]) => Promise.resolve(new Set(names)));+ transport.starImages.mockImplementation(() => Promise.resolve({ failed: [] }));+ transport.starVideos.mockImplementation(() => Promise.resolve({ failed: [] }));+ api.createProject.mockImplementation(+ (request: { board_id?: string; data: Record<string, unknown>; name: string; project_id: string }) =>+ Promise.resolve({+ board_id: request.board_id ?? 'server-created-board',+ created_at: '2026-06-10 11:00:00.000',+ data: request.data,+ name: request.name,+ project_id: request.project_id,+ revision: 1,+ updated_at: '2026-06-10 11:00:00.000',+ })+ );++ duplicateProject = await import('./duplicateProject');+});++describe('duplicateProjectRecord', () => {+ it('copies every board item onto a staging board the create then claims', async () => {+ const result = await duplicateProject.duplicateProjectRecord({+ boardItems: [boardItem(), boardItem({ category: 'user', name: 'unreferenced.png' })],+ owner,+ record: sourceRecord(),+ });++ expect(transport.createStagingBoard).toHaveBeenCalledWith('Source copy', owner.signal);+ expect(transport.copyImagesToBoard).toHaveBeenCalledWith(+ ['shared.png', 'unreferenced.png'],+ 'staging-board',+ owner.signal+ );+ expect(api.createProject.mock.calls[0]![0]).toMatchObject({ board_id: 'staging-board', name: 'Source copy' });+ expect(result.record.project_id).not.toBe('source');+ expect(result.boardItemIssues).toEqual([]);+ });++ /** The whole reason duplication needs its own copies rather than a second reference. */+ it('points the copy at its own media, never the original name', async () => {+ await duplicateProject.duplicateProjectRecord({+ boardItems: [boardItem()],+ owner,+ record: sourceRecord(),+ });++ expect(restoredLayerName()).toBe('copy-shared.png');+ });++ it('stars the copies whose descriptor was starred', async () => {+ await duplicateProject.duplicateProjectRecord({+ boardItems: [boardItem({ name: 'plain.png' }), boardItem({ name: 'starred.png', starred: true })],+ owner,+ record: sourceRecord(),+ });++ expect(transport.starImages).toHaveBeenCalledWith(['copy-starred.png'], owner.signal);+ });++ it('copies videos through the video endpoint with their category', async () => {+ await duplicateProject.duplicateProjectRecord({+ boardItems: [boardItem({ category: 'user', kind: 'video', name: 'clip.mp4' })],+ owner,+ record: sourceRecord(),+ });++ expect(transport.copyVideosToBoard).toHaveBeenCalledWith(['clip.mp4'], 'staging-board', owner.signal);+ expect(transport.copyImagesToBoard).toHaveBeenCalledWith([], 'staging-board', owner.signal);+ });++ /**+ * A reference to media outside the project's own board is a pointer, and both projects live on+ * this one server, so the copy simply keeps pointing at it.+ */+ it('reuses a document reference the board does not own, copying nothing', async () => {+ const record = sourceRecord({ futureImageInput: { image_name: 'external.png' } });++ await duplicateProject.duplicateProjectRecord({ boardItems: [boardItem()], owner, record });++ expect(transport.copyImagesToBoard).toHaveBeenCalledWith(['shared.png'], 'staging-board', owner.signal);+ expect((createdData().futureImageInput as { image_name: string }).image_name).toBe('external.png');+ });++ /**+ * The failure that must not bind to a stranger: on this server the original's `shared.png` is+ * right there, and falling back to it would leave the copy quietly sharing the original's image.+ */+ it('forces a reference dangling when its board copy fails', async () => {+ transport.copyImagesToBoard.mockResolvedValue({ copied: [], failed: ['shared.png'] });++ const result = await duplicateProject.duplicateProjectRecord({+ boardItems: [boardItem()],+ owner,+ record: sourceRecord(),+ });++ expect(restoredLayerName()).not.toBe('shared.png');+ expect(restoredLayerName()).toContain('-missing-image-');+ expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'shared.png', reason: 'upload-failed' }]);+ expect(result.documentReferenceIssues).toEqual([{ kind: 'image', name: 'shared.png', reason: 'upload-failed' }]);+ });++ it('canonicalizes the copy under its own identity and drops installation state', async () => {+ const record = sourceRecord({+ widgetStates: { gallery: { values: { projectBoardId: 'source-board', selectedBoardId: 'source-board' } } },+ });++ const result = await duplicateProject.duplicateProjectRecord({ boardItems: [boardItem()], owner, record });+ const gallery = (createdData().widgetStates as { gallery: { values: Record<string, unknown> } }).gallery.values;++ // The document that goes to the server carries neither the original's board nor its selection.+ expect(gallery.projectBoardId).toBeUndefined();+ expect(gallery.selectedBoardId).toBeUndefined();+ expect(createdData().id).toBe(result.record.project_id);+ expect(createdData().name).toBe('Source copy');++ // The returned record is patched with the board the server says it claimed, and points at it.+ const claimed = (result.record.data.widgetStates as { gallery: { values: Record<string, unknown> } }).gallery+ .values;++ expect(claimed).toMatchObject({ projectBoardId: 'staging-board', selectedBoardId: 'staging-board' });+ });++ it('creates no staging board for a project whose board is empty', async () => {+ await duplicateProject.duplicateProjectRecord({ boardItems: [], owner, record: sourceRecord() });++ expect(transport.createStagingBoard).not.toHaveBeenCalled();+ expect(api.createProject.mock.calls[0]![0]).not.toHaveProperty('board_id');+ });++ it('deletes the copies it made and the staging board when the create fails', async () => {+ const { ApiError } = await import('@platform/transport/http');+ const failure = new Error('create rejected');++ api.createProject.mockRejectedValue(failure);+ api.getProject.mockRejectedValue(new ApiError('not found', 404));++ await expect(+ duplicateProject.duplicateProjectRecord({+ boardItems: [boardItem(), boardItem({ kind: 'video', name: 'clip.mp4' })],+ owner,+ record: sourceRecord(),+ })+ ).rejects.toBe(failure);++ expect(transport.deleteArchiveImages).toHaveBeenCalledWith(['copy-shared.png'], owner.signal);+ expect(transport.deleteArchiveVideos).toHaveBeenCalledWith(['copy-clip.mp4'], owner.signal);+ expect(transport.deleteStagingBoard).toHaveBeenCalledWith('staging-board', owner.signal);+ });++ it('leaves the copies alone when a rejected create may already have claimed the board', async () => {+ const failure = new Error('connection ended after create');++ api.createProject.mockRejectedValue(failure);+ api.getProject.mockResolvedValue(sourceRecord());++ await expect(+ duplicateProject.duplicateProjectRecord({ boardItems: [boardItem()], owner, record: sourceRecord() })+ ).rejects.toBe(failure);++ expect(transport.deleteArchiveImages).not.toHaveBeenCalled();+ expect(transport.deleteStagingBoard).not.toHaveBeenCalled();+ });++ it('does not issue destructive cleanup under a different account', async () => {+ const account = await import('@platform/state/accountLifecycle');++ api.createProject.mockImplementation(() => {+ account.accountLifecycle.activate('duplicate-user-b');++ return Promise.reject(new Error('create rejected'));+ });++ await expect(+ duplicateProject.duplicateProjectRecord({ boardItems: [boardItem()], owner, record: sourceRecord() })+ ).rejects.toThrow();++ expect(transport.deleteArchiveImages).not.toHaveBeenCalled();+ expect(transport.deleteStagingBoard).not.toHaveBeenCalled();+ account.accountLifecycle.invalidate();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.tsnew file mode 100644index 0000000000..e6828dc6c7--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts@@ -0,0 +1,217 @@+import type { ProjectBoardItemDTO, ProjectRecordDTO } from '@workbench/projects/api';++import { type AccountScope, assertAccountScopeCurrent, isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import {+ createProject as apiCreateProject,+ getProject as apiGetProject,+ isProjectNotFoundError,+} from '@workbench/projects/api';+import { createProjectId } from '@workbench/projects/ids';+import {+ collectLiveAssetRefs,+ remapAssetRefs,+ selectCoverImageName,+ stripInstallationState,+} from '@workbench/projects/projectAssets';++import type { InvkBoardItem } from './board';+import type { MediaMaterializer } from './restoreProjectMedia';+import type { ProjectTransferIssues } from './transfer';++import { copyImagesToBoard, copyVideosToBoard, createStagingBoard } from './assetTransport';+import { InvkFormatError } from './format';+import { createRestoredMediaLedger, restoreProjectMedia, rollbackRestoredMedia } from './restoreProjectMedia';+import { toMediaRefs } from './transfer';++/**+ * Duplicating a project: the same restore, with the bytes taking a shortcut.+ *+ * A copy has to own its media outright — `board_images` keys on the image name, so two projects+ * cannot share a board image — which makes duplication the same problem as import: materialize the+ * board under new identities, rewrite the document onto them, claim the staging board by creating+ * the project. Only the materialization differs, and it differs because both projects live on this+ * one server: the copy endpoints do it in place, so a 2 GiB board costs no traffic instead of 4 GiB+ * and 2N requests through a browser tab.+ *+ * Document-only references are the other half of that. They point at media that already exists here+ * and is not the project's own board content, so the copy reuses the identities rather than+ * duplicating them — the shared engine's existence check finds every one of them, and nothing is+ * uploaded.+ *+ * What the previous implementation did was `POST` the source's document with a new id and name. It+ * carried no media at all, so the copy's board was empty, and it did not canonicalize or strip+ * installation state either — the copy inherited the original's board id and gallery selection.+ */++export interface DuplicateProjectInput {+ /** The board's visible contents, enumerated for the source project. */+ boardItems: readonly ProjectBoardItemDTO[];+ owner: AccountScope;+ /** The acknowledged source record — for an open project, flushed first. */+ record: ProjectRecordDTO;+}++export interface DuplicateProjectDeps {+ copyImages?: typeof copyImagesToBoard;+ copyVideos?: typeof copyVideosToBoard;+ onProgress?: (progress: { completed: number; total: number }) => void;+}++export interface DuplicateProjectResult extends ProjectTransferIssues {+ /** The cover to record for the copy, or `null` when the source had none this server can serve. */+ coverImageName: string | null;+ record: ProjectRecordDTO;+}++/**+ * The duplication half of the materialization seam: one request per kind, and the pixels stay put.+ *+ * Progress moves per item once each batch answers rather than during it. The copy is a single+ * server-side request per kind, so there is no finer truth to report — and unlike an import, there+ * is no upload to sit and watch.+ */+export const createCopyMediaMaterializer = (+ deps: { copyImages?: typeof copyImagesToBoard; copyVideos?: typeof copyVideosToBoard; signal?: AbortSignal } = {}+): MediaMaterializer => {+ const copyImages = deps.copyImages ?? copyImagesToBoard;+ const copyVideos = deps.copyVideos ?? copyVideosToBoard;++ return async (items, boardId, onItemSettled) => {+ const imageNames = items.filter((item) => item.kind === 'image').map((item) => item.name);+ const videoNames = items.filter((item) => item.kind === 'video').map((item) => item.name);+ const [images, videos] = await Promise.all([+ copyImages(imageNames, boardId, deps.signal),+ copyVideos(videoNames, boardId, deps.signal),+ ]);++ for (let index = 0; index < items.length; index += 1) {+ onItemSettled();+ }++ return {+ failed: [+ ...images.failed.map((name) => ({ kind: 'image' as const, name, reason: 'upload-failed' as const })),+ ...videos.failed.map((name) => ({ kind: 'video' as const, name, reason: 'upload-failed' as const })),+ ],+ materialized: [+ ...images.copied.map((entry) => ({ kind: 'image' as const, name: entry.name, sourceName: entry.sourceName })),+ ...videos.copied.map((entry) => ({ kind: 'video' as const, name: entry.name, sourceName: entry.sourceName })),+ ],+ };+ };+};++/** A rejected create is safe to clean up only when its client-chosen id is confirmed absent. */+const isProjectConfirmedAbsent = async (projectId: string, owner: AccountScope): Promise<boolean> => {+ try {+ await apiGetProject(projectId, owner.signal);++ return false;+ } catch (error) {+ return isAccountScopeCurrent(owner) && isProjectNotFoundError(error);+ }+};++/**+ * Copy a project and everything its board holds, under identities the copy owns.+ *+ * The commit point is the same as an import's: the media is materialized onto an unclaimed staging+ * board, and creating the project claims it. A failure before that deletes exactly what this+ * duplication made and leaves the original untouched.+ */+export const duplicateProjectRecord = async (+ input: DuplicateProjectInput,+ deps: DuplicateProjectDeps = {}+): Promise<DuplicateProjectResult> => {+ const { owner } = input;+ const id = createProjectId();+ const name = `${input.record.name} copy`;++ assertAccountScopeCurrent(owner);++ // Canonicalized through the reducer with the new identity, exactly as an import is: the copy is a+ // new project, not a second pointer at the original's board and gallery selection.+ const { deserializeProjectDocument } = await import('@workbench/projects/syncedPersistence');++ assertAccountScopeCurrent(owner);++ const project = deserializeProjectDocument({ ...stripInstallationState(input.record.data), id, name });++ if (!project) {+ throw new InvkFormatError('damaged', 'The project document will not rehydrate.');+ }++ const { applyAuthoritativeProjectBoard, serializeProjectDocument } =+ await import('@workbench/projects/projectDocument');+ const canonicalDocument = serializeProjectDocument(project);+ const boardItems = input.boardItems as readonly InvkBoardItem[];+ const stagingBoardId = boardItems.length === 0 ? null : await createStagingBoard(name, owner.signal);+ const ledger = createRestoredMediaLedger(stagingBoardId);+ let didCreateProject = false;++ try {+ assertAccountScopeCurrent(owner);++ const restored = await restoreProjectMedia(+ {+ boardId: stagingBoardId,+ boardItems,+ // Nothing is bundled: every byte this project needs is already on this server, so a+ // reference the copy cannot resolve is one the original could not resolve either.+ coverBytes: null,+ coverSourceImageName: selectCoverImageName(canonicalDocument),+ documentRefs: toMediaRefs(collectLiveAssetRefs(canonicalDocument)),+ ledger,+ projectId: id,+ },+ {+ materializeBoardMedia: createCopyMediaMaterializer({+ ...(deps.copyImages === undefined ? {} : { copyImages: deps.copyImages }),+ ...(deps.copyVideos === undefined ? {} : { copyVideos: deps.copyVideos }),+ signal: owner.signal,+ }),+ ...(deps.onProgress === undefined ? {} : { onProgress: deps.onProgress }),+ signal: owner.signal,+ }+ );++ assertAccountScopeCurrent(owner);++ const record = await apiCreateProject(+ {+ data: remapAssetRefs(canonicalDocument, restored.mappings),+ name,+ project_id: id,+ ...(stagingBoardId === null ? {} : { board_id: stagingBoardId }),+ },+ owner.signal+ );++ didCreateProject = true;+ assertAccountScopeCurrent(owner);++ return {+ boardItemIssues: restored.boardItemIssues,+ coverImageName: restored.coverImageName,+ documentReferenceIssues: restored.documentReferenceIssues,+ record: {+ ...record,+ data: applyAuthoritativeProjectBoard(record.data, record.board_id, { selectBoard: true }),+ },+ };+ } catch (error) {+ const canRollback =+ !didCreateProject && isAccountScopeCurrent(owner) && (await isProjectConfirmedAbsent(id, owner));++ if (canRollback) {+ try {+ await rollbackRestoredMedia(ledger, { signal: owner.signal });+ } catch {+ // Best-effort: the create failure is the actionable result, and must never be replaced by+ // a failed delete request.+ }+ }++ throw error;+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.tsindex de9223581c..8fff1127ca 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts@@ -16,12 +16,17 @@ const api = vi.hoisted(() => ({deleteProject: vi.fn(),getClientStateValue: vi.fn(() => Promise.resolve<string | null>(null)),getProject: vi.fn(),+ getProjectBoardSnapshot: vi.fn(),listProjects: vi.fn(),setClientStateValue: vi.fn(() => Promise.resolve()),updateProject: vi.fn(),}));+/** The copying itself is `duplicateProject`'s own test; this file owns the library's part of it. */+const duplication = vi.hoisted(() => ({ duplicateProjectRecord: vi.fn() }));+vi.mock('./api', () => api);+vi.mock('./invk/duplicateProject', () => duplication);let library: typeof libraryModule;let syncStore: typeof syncStoreModule;@@ -46,6 +51,9 @@ beforeEach(async () => {api.getClientStateValue.mockResolvedValue(null);api.setClientStateValue.mockReset();api.setClientStateValue.mockResolvedValue(undefined);+ api.getProjectBoardSnapshot.mockReset();+ api.getProjectBoardSnapshot.mockResolvedValue({ items: [] });+ duplication.duplicateProjectRecord.mockReset();library = await import('./library');syncStore = await import('./syncStore');@@ -262,23 +270,43 @@ describe('library mutations', () => {expect(calls).toEqual(['flush', 'get']);});- it('duplicateLibraryProject copies under a fresh id', async () => {+ it('duplicates through the shared restore engine and adopts the copy', async () => {api.getProject.mockResolvedValue({...summaryDto('source', 'Source', '2026-06-10 10:00:00.000'),data: { id: 'source', layout: {}, name: 'Source' },});- api.createProject.mockImplementation((request: { project_id?: string; name: string }) =>- Promise.resolve({ ...summaryDto(request.project_id ?? '', request.name, '2026-06-10 11:00:00.000'), data: {} })- );+ api.getProjectBoardSnapshot.mockResolvedValue({+ items: [{ category: 'general', kind: 'image', name: 'on-board.png', starred: false }],+ });+ duplication.duplicateProjectRecord.mockResolvedValue({+ boardItemIssues: [{ kind: 'image', name: 'lost.png', reason: 'upload-failed' }],+ coverImageName: null,+ documentReferenceIssues: [],+ record: { ...summaryDto('copy-id', 'Source copy', '2026-06-10 11:00:00.000'), data: {} },+ });- const copy = await library.duplicateLibraryProject('source');+ const duplicated = await library.duplicateLibraryProject('source');- expect(copy.id).not.toBe('source');- expect(copy.name).toBe('Source copy');+ // The board is enumerated before anything is created: a copy whose board came back silently+ // empty would look like a faithful duplication of a project that had produced nothing.+ expect(api.getProjectBoardSnapshot).toHaveBeenCalledWith('source', expect.any(AbortSignal));+ expect(duplication.duplicateProjectRecord.mock.calls[0]?.[0]).toMatchObject({+ boardItems: [{ name: 'on-board.png' }],+ record: { project_id: 'source' },+ });+ expect(duplicated.summary.id).toBe('copy-id');+ expect(duplicated.boardItemIssues).toHaveLength(1);+ expect(library.getProjectLibrary().summaries[0]?.name).toBe('Source copy');+ });- const createRequest = api.createProject.mock.calls[0][0] as { data: Record<string, unknown>; project_id: string };+ it('does not create anything when the board cannot be enumerated', async () => {+ api.getProject.mockResolvedValue({+ ...summaryDto('source', 'Source', '2026-06-10 10:00:00.000'),+ data: { id: 'source', layout: {}, name: 'Source' },+ });+ api.getProjectBoardSnapshot.mockRejectedValue(new Error('snapshot unavailable'));- expect(createRequest.data.id).toBe(createRequest.project_id);- expect(createRequest.data.name).toBe('Source copy');+ await expect(library.duplicateLibraryProject('source')).rejects.toThrow('snapshot unavailable');+ expect(duplication.duplicateProjectRecord).not.toHaveBeenCalled();});});diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.tsindex eae14dd397..9507d94118 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts@@ -9,10 +9,12 @@ import { createExternalStore } from '@platform/state/externalStore';import { createSingleFlight } from '@platform/state/singleFlight';import { normalizeServerTimestamp } from '@platform/time/serverTimestamp';+import type { ProjectTransferIssues } from './invk/transfer';+import {- createProject as apiCreateProject,deleteProject as apiDeleteProject,getProject as apiGetProject,+ getProjectBoardSnapshot,listProjects,updateProject as apiUpdateProject,type ProjectRecordDTO,@@ -23,9 +25,9 @@ import {getProjectCoverImageName,getProjectCoverUrl,loadProjectCovers,+ recordProjectCover,subscribeProjectCovers,} from './covers';-import { createProjectId } from './ids';import { refreshOpenProjects } from './openProjects';import { pruneSessionProject } from './session';import { getOpenProject } from './syncStore';@@ -278,24 +280,41 @@ export const adoptCreatedProject = (record: ProjectRecordDTO, owner: AccountScopreturn summary;};-/** Copy a project under a fresh id; returns the new summary. */-export const duplicateLibraryProject = async (projectId: string): Promise<ProjectSummary> => {+export interface DuplicatedProject extends ProjectTransferIssues {+ summary: ProjectSummary;+}++/**+ * Copy a project, its board and everything on it, under a fresh id.+ *+ * The board is enumerated before anything is created, and a failure to enumerate it aborts: a copy+ * whose board came back silently empty would look like a successful duplication of a project that+ * had produced nothing. The copying itself lives behind the lazy `invk/` boundary with import's+ * 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();const record = await readProjectForDuplication(projectId, owner);assertAccountScopeCurrent(owner);- const newId = createProjectId();- const name = `${record.name} copy`;- const created = await apiCreateProject(- {- data: { ...record.data, id: newId, name },- name,- project_id: newId,- },- owner.signal- );++ const snapshot = await getProjectBoardSnapshot(projectId, owner.signal);++ assertAccountScopeCurrent(owner);++ const { duplicateProjectRecord } = await import('./invk/duplicateProject');+ const duplicated = await duplicateProjectRecord({ boardItems: snapshot.items, owner, record });assertAccountScopeCurrent(owner);- return adoptCreatedProject(created, owner);+ if (duplicated.coverImageName) {+ recordProjectCover(duplicated.record.project_id, duplicated.coverImageName, owner);+ }++ return {+ boardItemIssues: duplicated.boardItemIssues,+ documentReferenceIssues: duplicated.documentReferenceIssues,+ summary: adoptCreatedProject(duplicated.record, owner),+ };};