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): ask before opening a library workflow the project already holds
Josh Corbett81316ae71338
diff --git a/docs/src/content/docs/features/Workflows/editor-interface.mdx b/docs/src/content/docs/features/Workflows/editor-interface.mdxindex 8d23fb07bb..9b1048938c 100644--- a/docs/src/content/docs/features/Workflows/editor-interface.mdx+++ b/docs/src/content/docs/features/Workflows/editor-interface.mdx@@ -33,7 +33,7 @@ Earlier releases wrote every edit of a workflow opened from the library straight- **Browse** lists curated bundled templates, filterable by a fixed set of category tags.- **Yours** lists templates you have saved; each can be renamed, duplicated, downloaded or deleted from its card menu, opened from the **⋯** button beside the title or with a right-click. The tag filter here is **dynamic** — it shows every unique tag found across your own templates, with a count per tag.- Opening a template adds an independent copy to your project; the template itself is untouched. If the project already has a copy, **Open project copy** switches to it, and **Add another copy** makes a second one.+ Opening a template adds an independent copy to your project; the template itself is untouched. If the project already has a copy, opening the template asks what to do: **Open copy** switches to it, **Add new copy** makes another, and **Replace copy** swaps the copy's graph for the library version while keeping its name. A replace is a single undo step.Editing or running a project workflow never changes the library. To publish, use **Save to library…** in the editor header: it creates a new template with the name you enter, using the workflow's current graph, form and input values as the template's defaults. A copy opened from one of your own templates can also **Update library template** explicitly; that replaces the template's content while the template and the project workflow each keep their own name. Because a template may have changed since you opened it, an update is checked against the revision you last saw; if the template moved on, you can save as new instead, or review the current template and replace it deliberately. Replacing a template affects workflows that call it through **Call Saved Workflow**.diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex a7238516dc..4e3b54d0a3 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -1208,6 +1208,7 @@"source:src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx","source:src/features/workflow/ui/editor/flowInstanceStore.ts","source:src/features/workflow/ui/editor/workflowViewportStore.ts",+ "source:src/features/workflow/ui/library/LibraryCopyChoiceDialog.tsx","source:src/features/workflow/ui/library/ProjectWorkflowsView.tsx","source:src/features/workflow/ui/library/WorkflowLibraryCard.tsx","source:src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx",@@ -2276,6 +2277,7 @@"source:src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx","source:src/features/workflow/ui/editor/flowInstanceStore.ts","source:src/features/workflow/ui/editor/workflowViewportStore.ts",+ "source:src/features/workflow/ui/library/LibraryCopyChoiceDialog.tsx","source:src/features/workflow/ui/library/ProjectWorkflowsView.tsx","source:src/features/workflow/ui/library/WorkflowLibraryCard.tsx","source:src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx",@@ -3553,6 +3555,7 @@"source:src/features/workflow/ui/graph-preview/index.ts","source:src/features/workflow/ui/graph-preview/nodeSummaries.ts","source:src/features/workflow/ui/implementation.ts",+ "source:src/features/workflow/ui/library/LibraryCopyChoiceDialog.tsx","source:src/features/workflow/ui/library/ProjectWorkflowsView.tsx","source:src/features/workflow/ui/library/WorkflowLibraryCard.tsx","source:src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex ca61a11b35..0ea27752f7 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -4271,12 +4271,9 @@},"workflowLibrary": {"activeWorkflow": "Active",- "addAnotherCopy": "Add another copy",- "addAnotherCopyHint": "A second, independent copy in this project","allTag": "All","applying": "Applying workflow…","browse": "Browse",- "chooseProjectCopy": "Open which copy?","conflictStaleBody": "The library template behind \"{{name}}\" has changed since this copy was loaded or last saved.","conflictTitle": "Template has changed","conflictUnknownBody": "It is not known whether the library template behind \"{{name}}\" still matches this copy.",@@ -4306,6 +4303,7 @@"loadFailedBody": "Could not load \"{{name}}\".","loadWarning": "Workflow load warning","loadedLabel": "Loaded \"{{name}}\" from library",+ "replacedLabel": "Replaced with \"{{name}}\" from library","loading": "Loading workflows…","loadingMore": "Loading more…","moreActions": "More actions",@@ -4315,11 +4313,22 @@"nodeCount_one": "{{count}} node","nodeCount_other": "{{count}} nodes","notRunYet": "Not run yet",+ "copyChoice": {+ "addCopy": "Add new copy",+ "body_one": "This project already has a copy of this workflow. Open it, add another copy, or replace the copy with the library version.",+ "body_other": "This project already has {{count}} copies of this workflow. Open one, add another copy, or replace one with the library version.",+ "copy": "Copy",+ "open": "Open copy",+ "openCopyLabel": "{{name}} (open now)",+ "replace": "Replace copy",+ "replaceHint": "Replacing keeps the copy's name and swaps in the library's graph; undo restores the previous one.",+ "title": "“{{name}}” is already in this project"+ },"open": "Open",+ "openExistingCopiesHint": "This project already has a copy; choose to open it, add another, or replace it","openHint": "Adds a copy to this project",+ "openWithEllipsis": "Open…","openProjectChanged": "The project changed while \"{{name}}\" was loading; nothing was added.",- "openProjectCopy": "Open project copy",- "openProjectCopyHint": "Switches to the copy this project already has","openProjectWorkflowHint": "Makes it the active workflow","previewGraph": "Preview graph","projectWorkflowCount_one": "{{count}} workflow in this project",diff --git a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsxindex bfce0bd691..9e7a2ef798 100644--- a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx@@ -261,6 +261,7 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })renameWorkflow: (workflowId, name) => {commands.workflows.rename(workflowId, name);},+ replaceWorkflow: (target, document, options) => commands.workflows.replaceDocument(target, document, options),selectWorkflow: (workflowId) => commands.workflows.select(workflowId),setWorkflowSource: (target, source) =>commands.workflows.setSource(target.projectId, target.workflowId, source),diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.browser.test.tsxnew file mode 100644index 0000000000..56319464a8--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.browser.test.tsx@@ -0,0 +1,100 @@+/* eslint-disable react-perf/jsx-no-new-object-as-prop -- the test wires a fake adapter directly */+import type { ProjectWorkflowEntry } from '@features/workflow/core/types';+import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';++import { WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';+import { requestLibraryWorkflowLoad, workflowUiStore } from '@features/workflow/ui/workflowUiStore';+import { createProjectGraph } from '@features/workflow/utility';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { PendingWorkflowLoader } from './PendingLibraryWorkflowLoader';++const api = vi.hoisted(() => ({ getLibraryWorkflowRecord: vi.fn() }));++vi.mock('@features/workflow/data/api', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ getLibraryWorkflowRecord: api.getLibraryWorkflowRecord,+ touchLibraryWorkflowOpenedAt: () => Promise.resolve(),+}));++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const copyOf = (libraryWorkflowId: string): ProjectWorkflowEntry => ({+ document: { ...createProjectGraph('copy-1'), name: 'My tweaks' },+ source: { libraryWorkflowId, revision: 1 },+});++describe('PendingWorkflowLoader', () => {+ let host: HTMLDivElement;+ let root: Root;+ let addWorkflow: ReturnType<typeof vi.fn>;++ const render = (workflows: ProjectWorkflowEntry[]) =>+ act(() =>+ root.render(+ <WorkflowUiProvider+ adapter={+ {+ commands: { addWorkflow },+ notifications: { error: vi.fn(), info: vi.fn() },+ project: { getSnapshot: () => ({ id: 'project-1', workflows }), subscribe: () => () => {} },+ } as unknown as WorkflowUiAdapter+ }+ >+ <PendingWorkflowLoader />+ </WorkflowUiProvider>+ )+ );++ beforeEach(() => {+ addWorkflow = vi.fn();+ api.getLibraryWorkflowRecord.mockReset().mockResolvedValue({+ name: 'Portrait',+ revision: 2,+ workflow: { edges: [], name: 'Portrait', nodes: [] },+ workflow_id: 'lib-portrait',+ });+ workflowUiStore.patchSnapshot({ libraryCopyChoice: null, pendingWorkflowLoad: null });+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ // The palette once resumed the first copy silently; it now asks, as the library does.+ it('asks about a template the project already holds, under the template’s name', async () => {+ await render([copyOf('lib-portrait')]);++ await act(() => requestLibraryWorkflowLoad('lib-portrait', 'Portrait'));++ await vi.waitFor(() =>+ expect(workflowUiStore.getSnapshot().libraryCopyChoice).toMatchObject({+ item: { name: 'Portrait', workflow_id: 'lib-portrait' },+ projectId: 'project-1',+ })+ );+ expect(api.getLibraryWorkflowRecord).not.toHaveBeenCalled();+ expect(addWorkflow).not.toHaveBeenCalled();+ });++ it('adds the first copy of a template the project does not hold', async () => {+ await render([copyOf('lib-other')]);++ await act(() => requestLibraryWorkflowLoad('lib-portrait', 'Portrait'));++ await vi.waitFor(() => expect(addWorkflow).toHaveBeenCalledTimes(1));+ expect(addWorkflow.mock.calls[0]?.[1]).toMatchObject({+ reusePlaceholder: true,+ source: { libraryWorkflowId: 'lib-portrait', revision: 2 },+ });+ expect(workflowUiStore.getSnapshot().libraryCopyChoice).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsxindex 1456d302d4..2035bfe1d3 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx@@ -2,6 +2,7 @@ import { getLibraryWorkflowRecord, touchLibraryWorkflowOpenedAt } from '@featureimport { updateLoadedWorkflowNodes } from '@features/workflow/data/templates';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import { useWorkflowNotifications, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';+import { requestLibraryCopyChoice } from '@features/workflow/ui/workflowUiStore';import { parseWorkflowJson } from '@features/workflow/utility';import { useMountEffect } from '@platform/react/useMountEffect';import {@@ -17,12 +18,12 @@ import { startWorkflowUiPendingLoadRuntime } from './pendingLibraryWorkflowLoadR/*** Apply external library or embedded-workflow requests through the same collection commands as the library- * dialog: a template resumes its existing copy or becomes a new one, an embedded document becomes a new workflow.- * Without a chooser to hand to the user, a template with several copies resumes the first.+ * dialog: a template becomes the project's first copy, or the copy-choice host asks what to do once it has one;+ * an embedded document becomes a new workflow.*/export const PendingWorkflowLoader = () => {const { t } = useTranslation();- const { addWorkflow, selectWorkflow } = useProjectGraphCommands();+ const { addWorkflow } = useProjectGraphCommands();const { project } = useWorkflowUi();const notify = useWorkflowNotifications();useMountEffect(() => {@@ -38,8 +39,12 @@ export const PendingWorkflowLoader = () => {if (source.kind === 'library') {const plan = planLibraryWorkflowOpen(project.getSnapshot().workflows, source.workflowId);- if (plan.kind !== 'add') {- selectWorkflow(plan.kind === 'resume' ? plan.workflowId : plan.copies[0]!.document.id);+ if (plan.kind === 'choose') {+ requestLibraryCopyChoice(projectId, {+ // Without the template's name, the copy's own stands in for it.+ name: source.name ?? plan.copies[0]!.document.name,+ workflow_id: source.workflowId,+ });return;}}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxindex 16e3528816..19d30154e7 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -42,6 +42,7 @@ import { AddNodeDialog } from './editor/AddNodeDialog';import { CallSavedWorkflowSyncRuntime } from './editor/CallSavedWorkflowSyncRuntime';import { getWorkflowFlowInstance } from './editor/flowInstanceStore';import { releaseWorkflowViewportsExcept } from './editor/workflowViewportStore';+import { LibraryCopyChoiceHost } from './library/LibraryCopyChoiceDialog';import { isUpdatableSource } from './library/projectWorkflowEntries';import { WorkflowLibraryDialog } from './library/WorkflowLibraryDialog';import { WorkflowPublicationHost } from './library/WorkflowPublicationHost';@@ -571,6 +572,7 @@ export const WorkflowDialogHost = () => {onOpenChange={setAddNodeOpen}/><WorkflowLibraryDialog isOpen={isLibraryOpen} onOpenChange={setWorkflowLibraryOpen} />+ <LibraryCopyChoiceHost /><RenameDialogkey={renameRequest?.requestId ?? 0}initialName={renameTargetName}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.tsindex 17807005ae..ae12a91d76 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts@@ -58,6 +58,12 @@ export interface WorkflowCommands {redo(target?: WorkflowTarget): void;removeWorkflow(workflowId: string): void;renameWorkflow(workflowId: string, name: string): void;+ /** Replaces a copy's document (keeping its id and name) as one undo step, and activates it. */+ replaceWorkflow(+ target: WorkflowTarget,+ document: ProjectGraphState,+ options: { label: string; source: ProjectWorkflowSource }+ ): void;selectWorkflow(workflowId: string): void;/** Records a publication target; ignored once that project or workflow no longer exists. */setWorkflowSource(target: WorkflowTarget, source: ProjectWorkflowSource | undefined): void;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/LibraryCopyChoiceDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/LibraryCopyChoiceDialog.browser.test.tsxnew file mode 100644index 0000000000..22fe797834--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/LibraryCopyChoiceDialog.browser.test.tsx@@ -0,0 +1,156 @@+import type { ProjectWorkflowEntry } from '@features/workflow/core/types';++import { ChakraProvider } from '@chakra-ui/react';+import {+ requestLibraryCopyChoice,+ setWorkflowLibraryOpen,+ workflowUiStore,+} from '@features/workflow/ui/workflowUiStore';+import { createProjectGraph } from '@features/workflow/utility';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++import { LibraryCopyChoiceHost } from './LibraryCopyChoiceDialog';++const loader = vi.hoisted(() => ({+ open: vi.fn((_item: unknown, _mode: string) => Promise.resolve()),+ replace: vi.fn((_item: unknown, _workflowId: string) => Promise.resolve()),+ resume: vi.fn((_workflowId: string) => {}),+}));++vi.mock('./useOpenLibraryWorkflow', () => ({+ useOpenLibraryWorkflow: (onOpened: () => void) => ({+ loadPhase: 'idle',+ open: loader.open,+ replace: loader.replace,+ resume: (workflowId: string) => {+ loader.resume(workflowId);+ onOpened();+ },+ }),+}));++const project = vi.hoisted(() => ({+ activeWorkflowId: 'copy-1',+ id: 'project-1',+ listeners: new Set<() => void>(),+ workflows: [] as ProjectWorkflowEntry[],+}));++vi.mock('@features/workflow/ui/WorkflowUiContext', () => ({+ useWorkflowProjectSelector: (selector: (snapshot: typeof project) => unknown) => selector(project),+ useWorkflowUi: () => ({+ project: {+ getSnapshot: () => project,+ subscribe: (listener: () => void) => {+ project.listeners.add(listener);+ return () => project.listeners.delete(listener);+ },+ },+ }),+}));++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const ITEM = { name: 'Portrait', workflow_id: 'lib-portrait' };+const copy = (id: string, name: string, libraryWorkflowId = ITEM.workflow_id): ProjectWorkflowEntry => ({+ document: { ...createProjectGraph(id), name },+ source: { libraryWorkflowId, revision: 1 },+});++const dialog = () => document.querySelector<HTMLElement>('[data-library-copy-choice]');+const button = (label: string) =>+ [...(dialog()?.querySelectorAll<HTMLButtonElement>('button') ?? [])].find(+ (candidate) => candidate.textContent === label+ );++describe('LibraryCopyChoiceHost', () => {+ let host: HTMLDivElement;+ let root: Root;++ const render = () =>+ act(() =>+ root.render(+ <ChakraProvider value={system}>+ <LibraryCopyChoiceHost />+ </ChakraProvider>+ )+ );++ beforeEach(() => {+ loader.open.mockClear();+ loader.replace.mockClear();+ loader.resume.mockClear();+ project.id = 'project-1';+ project.activeWorkflowId = 'copy-1';+ project.workflows = [copy('copy-1', 'Portrait'), copy('other', 'Other', 'lib-other')];+ workflowUiStore.patchSnapshot({ libraryCopyChoice: null });+ setWorkflowLibraryOpen(true);+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ it('asks about the one copy; opening it switches there and closes the library', async () => {+ await render();+ expect(dialog()).toBeNull();++ await act(() => requestLibraryCopyChoice('project-1', ITEM));++ await vi.waitFor(() => expect(dialog()).not.toBeNull());+ expect(dialog()?.querySelector('[role="combobox"]')).toBeNull();+ // Enter on arrival opens the copy; it must never replace it.+ await vi.waitFor(() => expect(document.activeElement).toBe(button('workflowLibrary.copyChoice.open')));++ await act(() => button('workflowLibrary.copyChoice.open')!.click());++ expect(loader.resume).toHaveBeenCalledExactlyOnceWith('copy-1');+ expect(workflowUiStore.getSnapshot().libraryCopyChoice).toBeNull();+ expect(workflowUiStore.getSnapshot().isLibraryOpen).toBe(false);+ });++ it('adds another copy, or replaces the copy picked from several', async () => {+ project.workflows = [copy('copy-1', 'Portrait'), copy('copy-2', 'Portrait, tuned')];+ await render();+ await act(() => requestLibraryCopyChoice('project-1', ITEM));+ await vi.waitFor(() => expect(dialog()).not.toBeNull());++ await act(() => button('workflowLibrary.copyChoice.addCopy')!.click());+ expect(loader.open).toHaveBeenCalledExactlyOnceWith(ITEM, 'add-copy');++ await act(() => userEvent.click(dialog()!.querySelector<HTMLElement>('[role="combobox"]')!));+ await act(() => userEvent.click(dialog()!.querySelector<HTMLElement>('[role="option"][data-value="copy-2"]')!));+ await act(() => button('workflowLibrary.copyChoice.replace')!.click());++ expect(loader.replace).toHaveBeenCalledExactlyOnceWith(ITEM, 'copy-2');+ expect(loader.resume).not.toHaveBeenCalled();+ });++ it('leaves a choice made in another project unasked', async () => {+ await render();+ await act(() => requestLibraryCopyChoice('project-2', ITEM));++ expect(dialog()).toBeNull();+ });++ it('drops the question when its project stops being active', async () => {+ await render();+ await act(() => requestLibraryCopyChoice('project-1', ITEM));+ await vi.waitFor(() => expect(dialog()).not.toBeNull());++ project.id = 'project-2';+ await act(() => project.listeners.forEach((listener) => listener()));++ expect(workflowUiStore.getSnapshot().libraryCopyChoice).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/LibraryCopyChoiceDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/LibraryCopyChoiceDialog.tsxnew file mode 100644index 0000000000..12700040b3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/LibraryCopyChoiceDialog.tsx@@ -0,0 +1,207 @@+import type { LibraryCopyChoiceRequest } from '@features/workflow/ui/workflowUiStore';++import { createListCollection, Dialog, Portal, Stack } from '@chakra-ui/react';+import { useWorkflowProjectSelector, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';+import { clearLibraryCopyChoice, setWorkflowLibraryOpen, workflowUiStore } from '@features/workflow/ui/workflowUiStore';+import { useMountEffect } from '@platform/react/useMountEffect';+import { Button, CloseButton } from '@platform/ui/Button';+import { Field } from '@platform/ui/Field';+import { Select } from '@platform/ui/Select';+import { useCallback, useMemo, useRef, useState, type RefObject } from 'react';+import { useTranslation } from 'react-i18next';++import { findProjectCopiesOf } from './projectWorkflowEntries';+import { useOpenLibraryWorkflow, type OpenLibraryWorkflow } from './useOpenLibraryWorkflow';++/**+ * Asks what opening a template the project already holds should do; one host serves the library and the palette.+ * The root stays mounted and only its `open` changes: a dialog that mounts open while the menu that asked for it is+ * still closing gets dismissed with that menu's layer.+ */+export const LibraryCopyChoiceHost = () => {+ const { project } = useWorkflowUi();+ const request = workflowUiStore.useSelector((snapshot) => snapshot.libraryCopyChoice);+ const projectId = useWorkflowProjectSelector((snapshot) => snapshot.id);+ // A count, not the copies: the host stays mounted and must not re-render on every edit to the project's graphs.+ const copyCount = useWorkflowProjectSelector((snapshot) =>+ request ? findProjectCopiesOf(snapshot.workflows, request.item.workflow_id).length : 0+ );+ const openButtonRef = useRef<HTMLButtonElement | null>(null);+ const requestId = request?.requestId ?? null;+ const close = useCallback(() => {+ if (requestId !== null) {+ clearLibraryCopyChoice(requestId);+ }+ }, [requestId]);+ const finish = useCallback(() => {+ close();+ setWorkflowLibraryOpen(false);+ }, [close]);+ const loader = useOpenLibraryWorkflow(finish);+ const isBusy = loader.loadPhase !== 'idle';+ // About copies that are all gone, there is nothing left to ask.+ const isOpen = request !== null && request.projectId === projectId && copyCount > 0;+ const handleOpenChange = useCallback(+ (event: { open: boolean }) => {+ if (!event.open && !isBusy) {+ close();+ }+ },+ [close, isBusy]+ );+ // Opening is the safe default: Enter on arrival must never replace a copy.+ const getInitialFocus = useCallback(() => openButtonRef.current, []);++ /* eslint-disable react-hooks/rules-of-hooks -- useMountEffect is the repository's explicit useEffect wrapper */+ // A question about another project's copies ends when that project stops being active.+ useMountEffect(() =>+ project.subscribe(() => {+ const pending = workflowUiStore.getSnapshot().libraryCopyChoice;++ if (pending && pending.projectId !== project.getSnapshot().id) {+ clearLibraryCopyChoice(pending.requestId);+ }+ })+ );+ /* eslint-enable react-hooks/rules-of-hooks */++ return (+ <Dialog.Root+ closeOnEscape={!isBusy}+ closeOnInteractOutside={!isBusy}+ initialFocusEl={getInitialFocus}+ lazyMount+ open={isOpen}+ size="sm"+ unmountOnExit+ onOpenChange={handleOpenChange}+ >+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content data-library-copy-choice="">+ {isOpen ? (+ <LibraryCopyChoiceContent+ key={request.requestId}+ loader={loader}+ openButtonRef={openButtonRef}+ request={request}+ />+ ) : null}+ <Dialog.CloseTrigger asChild>+ <CloseButton disabled={isBusy} />+ </Dialog.CloseTrigger>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ );+};++type PendingChoice = 'add' | 'replace' | null;++const LibraryCopyChoiceContent = ({+ loader: { loadPhase, open, replace, resume },+ openButtonRef,+ request,+}: {+ loader: OpenLibraryWorkflow;+ openButtonRef: RefObject<HTMLButtonElement | null>;+ request: LibraryCopyChoiceRequest;+}) => {+ const { t } = useTranslation();+ const workflows = useWorkflowProjectSelector((snapshot) => snapshot.workflows);+ const activeWorkflowId = useWorkflowProjectSelector((snapshot) => snapshot.activeWorkflowId);+ const copies = useMemo(+ () => findProjectCopiesOf(workflows, request.item.workflow_id),+ [request.item.workflow_id, workflows]+ );+ // The copy being edited is the likeliest one meant; otherwise the oldest.+ const [selectedCopyId, setSelectedCopyId] = useState(+ copies.some((copy) => copy.document.id === activeWorkflowId) ? activeWorkflowId : copies[0]!.document.id+ );+ const [pending, setPending] = useState<PendingChoice>(null);+ const copyId = copies.some((copy) => copy.document.id === selectedCopyId) ? selectedCopyId : copies[0]!.document.id;+ const selectValue = useMemo(() => [copyId], [copyId]);+ const isBusy = loadPhase !== 'idle';+ const name = request.item.name || t('workflowLibrary.untitled');+ const copyCollection = useMemo(+ () =>+ createListCollection({+ // Copies often share the template's name; the open one is told apart.+ items: copies.map((copy) => {+ const copyName = copy.document.name || t('workflowLibrary.untitled');++ return {+ label:+ copy.document.id === activeWorkflowId+ ? t('workflowLibrary.copyChoice.openCopyLabel', { name: copyName })+ : copyName,+ value: copy.document.id,+ };+ }),+ }),+ [activeWorkflowId, copies, t]+ );++ const handleCopyChange = useCallback(({ value }: { value: string[] }) => {+ if (value[0]) {+ setSelectedCopyId(value[0]);+ }+ }, []);+ const handleResume = useCallback(() => resume(copyId), [copyId, resume]);+ const handleAdd = useCallback(() => {+ setPending('add');+ void open(request.item, 'add-copy').finally(() => setPending(null));+ }, [open, request.item]);+ const handleReplace = useCallback(() => {+ setPending('replace');+ void replace(request.item, copyId).finally(() => setPending(null));+ }, [copyId, replace, request.item]);++ return (+ <>+ <Dialog.Header>+ <Dialog.Title>{t('workflowLibrary.copyChoice.title', { name })}</Dialog.Title>+ </Dialog.Header>+ <Dialog.Body>+ <Stack gap="3">+ <Dialog.Description fontSize="xs">+ {t('workflowLibrary.copyChoice.body', { count: copies.length })}{' '}+ {t('workflowLibrary.copyChoice.replaceHint')}+ </Dialog.Description>+ {copies.length > 1 ? (+ <Field label={t('workflowLibrary.copyChoice.copy')}>+ <Select+ collection={copyCollection}+ portalled={false}+ size="xs"+ value={selectValue}+ onValueChange={handleCopyChange}+ />+ </Field>+ ) : null}+ </Stack>+ </Dialog.Body>+ <Dialog.Footer>+ <Button+ colorPalette="red"+ disabled={isBusy}+ loading={pending === 'replace'}+ me="auto"+ size="xs"+ variant="outline"+ onClick={handleReplace}+ >+ {t('workflowLibrary.copyChoice.replace')}+ </Button>+ <Button disabled={isBusy} loading={pending === 'add'} size="xs" variant="outline" onClick={handleAdd}>+ {t('workflowLibrary.copyChoice.addCopy')}+ </Button>+ <Button ref={openButtonRef} disabled={isBusy} size="xs" variant="solid" onClick={handleResume}>+ {t('workflowLibrary.copyChoice.open')}+ </Button>+ </Dialog.Footer>+ </>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsxindex 74a477b25c..f8384c6e46 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx@@ -132,9 +132,6 @@ vi.mock('@platform/browser/downloadBlob', () => ({ downloadText }));const TRANSLATIONS: Record<string, string> = {'common.unknownError': 'Something went wrong',- 'workflowLibrary.addAnotherCopy': 'Add another copy',- 'workflowLibrary.addAnotherCopyHint': 'A second, independent copy in this project',- 'workflowLibrary.chooseProjectCopy': 'Open which copy?','workflowLibrary.delete': 'Delete','workflowLibrary.deleteConfirmBody': 'Delete "{{name}}" from the workflow library? This cannot be undone.','workflowLibrary.deleteConfirmTitle': 'Delete workflow',@@ -175,8 +172,7 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.notRunYet': 'Not run yet','workflowLibrary.open': 'Open','workflowLibrary.openHint': 'Adds a copy to this project',- 'workflowLibrary.openProjectCopy': 'Open project copy',- 'workflowLibrary.openProjectCopyHint': 'Switches to the copy this project already has',+ 'workflowLibrary.openWithEllipsis': 'Open…','workflowLibrary.previewGraph': 'Preview graph','workflowLibrary.requirementInstallable': 'Not installed','workflowLibrary.requirementInstalled': 'Installed',@@ -329,13 +325,12 @@ const RAW_RECORD = {workflow: RAW_WORKFLOW,};-/** Project copies of TEXT_TO_IMAGE: what Open resumes instead of adding another. */+/** Project copies of TEXT_TO_IMAGE: once one exists, Open asks instead of adding another. */const projectCopy = (id: string, name: string, libraryWorkflowId = 'wf-text-to-image'): ProjectWorkflowEntry => ({document: { ...createProjectGraph(id), name },source: { libraryWorkflowId, revision: 1 },});const FIRST_COPY = projectCopy('copy-1', 'Text to image');-const SECOND_COPY = projectCopy('copy-2', 'Text to image, tuned');const OTHER_TEMPLATE_COPY = projectCopy('copy-other', 'Something else', 'wf-image-to-video');const NO_COPIES: readonly ProjectWorkflowEntry[] = [];@@ -358,9 +353,8 @@ describe('WorkflowLibraryDetailPanel', () => {let onClose: () => void;let onDeleted: () => void;let onDuplicated: (workflowId: string) => void;- let onOpen: (item: WorkflowLibraryEntry['item'], mode: 'resume-or-add' | 'add-copy') => void;+ let onOpen: (item: WorkflowLibraryEntry['item']) => void;let onPreview: (selected: WorkflowLibraryEntry) => void;- let onResume: (workflowId: string) => void;/** See `WorkflowLibraryDialog.browser.test.tsx`: keeps Chakra's observer-driven commits inside the act scope. */const settleFrame = () =>@@ -390,7 +384,6 @@ describe('WorkflowLibraryDetailPanel', () => {onDuplicated={onDuplicated}onOpen={onOpen}onPreview={onPreview}- onResume={onResume}/></WorkflowGraphPreviewProvider></GalleryHostProvider>@@ -456,7 +449,6 @@ describe('WorkflowLibraryDetailPanel', () => {onDuplicated = vi.fn((_workflowId: string) => {});onOpen = vi.fn();onPreview = vi.fn();- onResume = vi.fn();models.activeInstallSources.current = new Set();models.installedModels.current = [INSTALLED_SDXL_MAIN, INSTALLED_WAN_VAE];@@ -513,64 +505,25 @@ describe('WorkflowLibraryDetailPanel', () => {await clickButton('Open');- // No project copy exists yet, so opening adds the first one.- expect(onOpen).toHaveBeenCalledWith(TEXT_TO_IMAGE.item, 'resume-or-add');- expect(onResume).not.toHaveBeenCalled();+ expect(onOpen).toHaveBeenCalledExactlyOnceWith(TEXT_TO_IMAGE.item);});- it('resumes the one project copy of the template instead of adding another', async () => {- await renderPanel(TEXT_TO_IMAGE, [OTHER_TEMPLATE_COPY, FIRST_COPY]);-- expect(buttonWithText('Open')).toBeUndefined();- expect(buttonWithText('Open project copy')).not.toBeUndefined();-- await clickButton('Open project copy');-- expect(onResume).toHaveBeenCalledWith('copy-1');- expect(onOpen).not.toHaveBeenCalled();- });+ // The shell asks what to do; the rail only says that opening will ask.+ it('labels Open as a choice once the project holds a copy of the template', async () => {+ await renderPanel(TEXT_TO_IMAGE, [OTHER_TEMPLATE_COPY]);- it('lets the user choose which of several project copies to resume', async () => {- await renderPanel(TEXT_TO_IMAGE, [FIRST_COPY, OTHER_TEMPLATE_COPY, SECOND_COPY]);-- await clickButton('Open project copy');-- const chooser = () => document.querySelector<HTMLElement>('[data-workflow-copy-chooser]');- await vi.waitFor(() => expect(chooser()).not.toBeNull());-- // Only this template's copies, by name, in collection order.- const choices = [...(chooser()?.querySelectorAll<HTMLElement>('[data-menu-item]') ?? [])];- expect(choices.map((choice) => choice.dataset.menuItem)).toEqual(['resume:copy-1', 'resume:copy-2']);- expect(chooser()?.textContent).toContain('Text to image, tuned');- expect(chooser()?.textContent).not.toContain('Something else');- expect(onResume).not.toHaveBeenCalled();+ expect(buttonWithText('Open')).not.toBeUndefined();- await act(async () => {- choices[1]?.click();- await settleFrame();- });+ await renderPanel(TEXT_TO_IMAGE, [OTHER_TEMPLATE_COPY, FIRST_COPY]);- expect(onResume).toHaveBeenCalledWith('copy-2');- expect(onOpen).not.toHaveBeenCalled();- });+ expect(buttonWithText('Open')).toBeUndefined();+ await clickButton('Open…');+ expect(onOpen).toHaveBeenCalledExactlyOnceWith(TEXT_TO_IMAGE.item);- it('offers another independent copy only once the project already has one', async () => {- await renderPanel(TEXT_TO_IMAGE);await openMenu();+ expect(menuItem('open')?.textContent).toContain('Open…');expect(menuItem('add-copy')).toBeNull();- expect(menuItem('open')?.textContent).toContain('Open');-- await renderPanel(TEXT_TO_IMAGE, [FIRST_COPY]);- await openMenu();-- expect(menuItem('open')?.textContent).toContain('Open project copy');- expect(menuItem('add-copy')?.textContent).toContain('Add another copy');-- await clickMenuItem('add-copy');-- expect(onOpen).toHaveBeenCalledWith(TEXT_TO_IMAGE.item, 'add-copy');- expect(onResume).not.toHaveBeenCalled();});it('opens the workflow from the keyboard, the path the double-click-only cards do not offer', async () => {@@ -589,7 +542,7 @@ describe('WorkflowLibraryDetailPanel', () => {await settleFrame();});- expect(onOpen).toHaveBeenCalledWith(TEXT_TO_IMAGE.item, 'resume-or-add');+ expect(onOpen).toHaveBeenCalledWith(TEXT_TO_IMAGE.item);});it('swaps the primary action for an install when starter models can fill the gaps', async () => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsxindex e00869390c..b6a499c2e3 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx@@ -38,21 +38,10 @@ import {Tooltip,useTooltipTriggerIds,} from '@platform/ui';-import {- CopyIcon,- CopyPlusIcon,- DownloadIcon,- EllipsisIcon,- GitForkIcon,- PencilIcon,- Trash2Icon,- WorkflowIcon,-} from 'lucide-react';+import { CopyIcon, DownloadIcon, EllipsisIcon, GitForkIcon, PencilIcon, Trash2Icon, WorkflowIcon } from 'lucide-react';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import type { OpenLibraryWorkflowMode } from './useOpenLibraryWorkflow';-import { planLibraryWorkflowOpen } from './useOpenLibraryWorkflow';import {getWorkflowLibraryCardId,@@ -84,38 +73,15 @@ export interface WorkflowLibraryDetailPanelProps {onDeleted: () => void;/** Carries the copy's id so the shell can select it once the list refreshes. */onDuplicated: (workflowId: string) => void;- onOpen: (item: WorkflowLibraryListItem, mode: OpenLibraryWorkflowMode) => void;+ /** Adds the first copy, or asks what to do when the project already holds one. */+ onOpen: (item: WorkflowLibraryListItem) => void;onPreview: (entry: WorkflowLibraryEntry) => void;- /** Activates a project copy the project already made from this template. */- onResume: (workflowId: string) => void;- /** The project's workflows, so the rail can offer the existing copies of this template. */+ /** The project's workflows, so the rail can say when opening will ask about existing copies. */projectWorkflows: readonly ProjectWorkflowEntry[];}const toFileSlug = (name: string): string => name.trim().replaceAll(/\s+/g, '-').toLowerCase() || 'workflow';-const CHOOSER_POSITIONING = { placement: 'top-start' } as const;--const ProjectCopyItem = ({- copy,- onResume,-}: {- copy: ProjectWorkflowEntry;- onResume: (workflowId: string) => void;-}) => {- const { t } = useTranslation();- const handleSelect = useCallback(() => onResume(copy.document.id), [copy.document.id, onResume]);-- return (- <MenuActionItem- icon={WorkflowIcon}- label={copy.document.name || t('workflowLibrary.untitled')}- value={`resume:${copy.document.id}`}- onSelect={handleSelect}- />- );-};-export const WorkflowLibraryDetailPanel = ({contextMenuPoint,contextMenuTriggerId,@@ -126,7 +92,6 @@ export const WorkflowLibraryDetailPanel = ({onDuplicated,onOpen,onPreview,- onResume,projectWorkflows,}: WorkflowLibraryDetailPanelProps) => {const { t } = useTranslation();@@ -149,36 +114,15 @@ export const WorkflowLibraryDetailPanel = ({);const installableCount = resolved?.filter((requirement) => requirement.status === 'installable').length ?? 0;- const openPlan = useMemo(- () => (entry ? planLibraryWorkflowOpen(projectWorkflows, entry.item.workflow_id) : null),+ const hasCopies = useMemo(+ () => (entry ? planLibraryWorkflowOpen(projectWorkflows, entry.item.workflow_id).kind === 'choose' : false),[entry, projectWorkflows]);- const [isCopyChooserOpen, setIsCopyChooserOpen] = useState(false);-- /** Open lands in the project: the first copy is added, an existing one resumed, several offered as a choice. */const handleOpen = useCallback(() => {- if (!entry || !openPlan) {- return;- }-- if (openPlan.kind === 'choose') {- setIsCopyChooserOpen(true);- return;- }-- if (openPlan.kind === 'resume') {- onResume(openPlan.workflowId);- return;- }-- onOpen(entry.item, 'resume-or-add');- }, [entry, onOpen, onResume, openPlan]);- const handleAddCopy = useCallback(() => {if (entry) {- onOpen(entry.item, 'add-copy');+ onOpen(entry.item);}}, [entry, onOpen]);- const handleCopyChooserOpenChange = useCallback((event: { open: boolean }) => setIsCopyChooserOpen(event.open), []);const handlePreview = useCallback(() => {if (entry && entry.enrichment.status === 'ready') {@@ -400,9 +344,6 @@ export const WorkflowLibraryDetailPanel = ({: undefined,[contextMenuTriggerId, entry]);- // The chooser is anchored to the button that opened it, so closing returns focus there.- const openButtonId = entry ? `${getWorkflowLibraryCardId(entry.item.workflow_id)}-open` : undefined;- const chooserIds = useMemo(() => (openButtonId ? { trigger: openButtonId } : undefined), [openButtonId]);const moreActionsIds = useTooltipTriggerIds();const confirmDelete = useCallback(async () => {@@ -433,28 +374,18 @@ export const WorkflowLibraryDetailPanel = ({const { item, tags } = entry;const name = item.name || t('workflowLibrary.untitled');- const hasCopies = openPlan !== null && openPlan.kind !== 'add';- const openLabel = hasCopies ? t('workflowLibrary.openProjectCopy') : t('workflowLibrary.open');+ const openLabel = hasCopies ? t('workflowLibrary.openWithEllipsis') : t('workflowLibrary.open');// One item set behind both the rail's overflow button and a card's right-click.const actionItems = (<><MenuActionItem- hint={hasCopies ? t('workflowLibrary.openProjectCopyHint') : t('workflowLibrary.openHint')}+ hint={hasCopies ? t('workflowLibrary.openExistingCopiesHint') : t('workflowLibrary.openHint')}icon={WorkflowIcon}label={openLabel}value="open"onSelect={handleOpen}/>- {hasCopies ? (- <MenuActionItem- hint={t('workflowLibrary.addAnotherCopyHint')}- icon={CopyPlusIcon}- label={t('workflowLibrary.addAnotherCopy')}- value="add-copy"- onSelect={handleAddCopy}- />- ) : null}<MenuActionItemhint={t('workflowLibrary.duplicateHint')}icon={CopyIcon}@@ -566,7 +497,7 @@ export const WorkflowLibraryDetailPanel = ({{t('workflowLibrary.installModels', { count: installableCount })}</Button>) : (- <Button flex="1" id={openButtonId} minW="0" size="sm" onClick={handleOpen}>+ <Button flex="1" minW="0" size="sm" onClick={handleOpen}>{openLabel}</Button>)}@@ -611,31 +542,6 @@ export const WorkflowLibraryDetailPanel = ({</Portal></Menu.Root>- {/* Several copies exist: the chooser lists them by name; another copy is a separate action. */}- <Menu.Root- ids={chooserIds}- open={isCopyChooserOpen && openPlan?.kind === 'choose'}- positioning={CHOOSER_POSITIONING}- onOpenChange={handleCopyChooserOpenChange}- >- <Portal>- <Menu.Positioner>- <MenuContent data-workflow-copy-chooser minW="16rem">- <Menu.ItemGroup>- <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">- {t('workflowLibrary.chooseProjectCopy')}- </Menu.ItemGroupLabel>- {openPlan?.kind === 'choose'- ? openPlan.copies.map((copy) => (- <ProjectCopyItem key={copy.document.id} copy={copy} onResume={onResume} />- ))- : null}- </Menu.ItemGroup>- </MenuContent>- </Menu.Positioner>- </Portal>- </Menu.Root>-<RenameDialoginitialName={name}isOpen={isRenameOpen}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsxindex 3f87d0fd02..88f6d76d3f 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx@@ -35,6 +35,7 @@ import { userEvent } from 'vitest/browser';// Warm the mocked lazy module to avoid first-compile timing variability in preview wiring tests.import '@features/workflow/ui/graph-preview/GraphPreviewDialog';+import { LibraryCopyChoiceHost } from './LibraryCopyChoiceDialog';import { WorkflowLibraryDialog } from './WorkflowLibraryDialog';/** In the app the workbench derives this from its Gallery adapter; the library's thumbnail slot reads it. */@@ -145,7 +146,7 @@ vi.mock('@features/workflow/data/libraryBrowseStore', async () => {// Test opener invocation and busy-state wiring here; load sequencing has separate coverage.const loader = vi.hoisted(() => ({- open: vi.fn((_item: unknown, _mode: 'resume-or-add' | 'add-copy') => Promise.resolve()),+ open: vi.fn((_item: unknown, _mode: 'first-copy' | 'add-copy') => Promise.resolve()),phase: { current: 'idle' as 'applying' | 'fetching' | 'idle' },resume: vi.fn((_workflowId: string) => {}),}));@@ -204,8 +205,7 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.notRunYet': 'Not run yet','workflowLibrary.open': 'Open','workflowLibrary.openHint': 'Adds a copy to this project',- 'workflowLibrary.openProjectCopy': 'Open project copy',- 'workflowLibrary.openProjectCopyHint': 'Switches to the copy this project already has',+ 'workflowLibrary.openWithEllipsis': 'Open…','workflowLibrary.previewGraph': 'Preview graph','workflowLibrary.projectWorkflowCount_one': '{{count}} workflow in this project','workflowLibrary.projectWorkflowCount_other': '{{count}} workflows in this project',@@ -430,6 +430,7 @@ describe('WorkflowLibraryDialog', () => {<GalleryHostProvider host={GALLERY_HOST}><WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}><WorkflowLibraryDialog isOpen={isOpen} onOpenChange={onOpenChange} />+ <LibraryCopyChoiceHost /></WorkflowGraphPreviewProvider></GalleryHostProvider></WorkflowUiProvider>@@ -701,7 +702,7 @@ describe('WorkflowLibraryDialog', () => {});expect(loader.open).toHaveBeenCalledTimes(1);- expect(loader.open).toHaveBeenCalledWith(LANDSCAPE.item, 'resume-or-add');+ expect(loader.open).toHaveBeenCalledWith(LANDSCAPE.item, 'first-copy');});it('dedupes entries that share a workflow id', async () => {@@ -851,7 +852,31 @@ describe('WorkflowLibraryDialog', () => {await vi.waitFor(() => expect(open()).not.toBeNull());await act(() => open()?.click());- expect(loader.open).toHaveBeenCalledWith(LANDSCAPE.item, 'resume-or-add');+ expect(loader.open).toHaveBeenCalledWith(LANDSCAPE.item, 'first-copy');+ });++ // The question mounts while the menu that asked it is still closing; the menu's teardown must not dismiss it.+ it('keeps the copy question a card menu raised for a template the project already holds', async () => {+ await openWith(LOADED_SNAPSHOT);++ await act(() =>+ card('wf-portrait')?.dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 80 })+ )+ );++ const open = () => document.querySelector<HTMLElement>('[data-workflow-context-menu] [data-menu-item="open"]');++ await vi.waitFor(() => expect(open()).not.toBeNull());+ await act(async () => {+ open()?.click();+ await settleFrame();+ await settleFrame();+ });++ await vi.waitFor(() => expect(document.querySelector('[data-workflow-context-menu]')).toBeNull());+ expect(document.querySelector('[data-library-copy-choice]')).not.toBeNull();+ expect(loader.open).not.toHaveBeenCalled();});it('closes the card context menu on Escape and hands focus back to the card', async () => {@@ -882,17 +907,17 @@ describe('WorkflowLibraryDialog', () => {it('opens the selected workflow from the rail, the keyboard-reachable path', async () => {await openWith(LOADED_SNAPSHOT);- // Portrait needs nothing installed, but the project already holds a copy of it: Open resumes that copy.- await clickText('Open project copy');+ // Portrait needs nothing installed, but the project already holds a copy of it: Open asks what to do.+ await clickText('Open…');- expect(loader.resume).toHaveBeenCalledWith('wf-user');+ expect(workflowUiStore.getSnapshot().libraryCopyChoice?.item.workflow_id).toBe(PORTRAIT.item.workflow_id);expect(loader.open).not.toHaveBeenCalled();// Upscale has no copy yet (and nothing to install first), so Open adds one.await act(() => card('wf-upscale')?.click());await clickText('Open');- expect(loader.open).toHaveBeenCalledWith(UPSCALE.item, 'resume-or-add');+ expect(loader.open).toHaveBeenCalledWith(UPSCALE.item, 'first-copy');});it('badges the cards with the models their workflows still need', async () => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsxindex 00d45be6db..35fd889d83 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx@@ -13,6 +13,7 @@ import {import { useInvocationTemplatesSnapshot } from '@features/workflow/react';import { useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';import {+ requestLibraryCopyChoice,setWorkflowLibrarySelection,setWorkflowLibraryTab,workflowUiStore,@@ -31,11 +32,7 @@ import {preloadGraphPreview,} from './libraryPreviewSource';import { ProjectWorkflowsView } from './ProjectWorkflowsView';-import {- type OpenLibraryWorkflowMode,- planLibraryWorkflowOpen,- useOpenLibraryWorkflow,-} from './useOpenLibraryWorkflow';+import { planLibraryWorkflowOpen, useOpenLibraryWorkflow } from './useOpenLibraryWorkflow';import { WorkflowLibraryDetailPanel } from './WorkflowLibraryDetailPanel';import { WorkflowLibraryGrid } from './WorkflowLibraryGrid';import { WorkflowLibraryTagChips } from './WorkflowLibraryTagChips';@@ -121,7 +118,7 @@ export const WorkflowLibraryDialog = ({setContextMenuPoint(null);onOpenChange(false);}, [onOpenChange]);- const { loadPhase, open, resume } = useOpenLibraryWorkflow(closeDialog);+ const { loadPhase, open } = useOpenLibraryWorkflow(closeDialog);const isLoadPending = loadPhase !== 'idle';const missingCounts = useWorkflowLibraryMissingCounts(entries);@@ -229,33 +226,29 @@ export const WorkflowLibraryDialog = ({const handleTagSelect = useCallback((nextTag: string | null) => setWorkflowLibraryBrowseFilter({ tag: nextTag }), []);+ // The first copy is added directly; with one already in the project, the host asks what opening should do.+ const handleOpenItem = useCallback(+ (item: WorkflowLibraryListItem) => {+ if (planLibraryWorkflowOpen(projectWorkflows, item.workflow_id).kind === 'choose') {+ requestLibraryCopyChoice(projectId, item);+ return;+ }++ void open(item, 'first-copy');+ },+ [open, projectId, projectWorkflows]+ );const handleOpenWorkflow = useCallback((workflowId: string) => {const entry = getWorkflowLibraryBrowseSnapshot().entries.find((candidate) => candidate.item.workflow_id === workflowId);- if (!entry) {- return;+ if (entry) {+ handleOpenItem(entry.item);}-- const plan = planLibraryWorkflowOpen(projectWorkflows, workflowId);-- if (plan.kind === 'choose') {- // Several copies: the project view shows them all, with the first one selected.- setWorkflowLibrarySelection({ projectId, workflowId: plan.copies[0]!.document.id });- setWorkflowLibraryTab('project');- return;- }-- void open(entry.item, 'resume-or-add');},- [open, projectId, projectWorkflows]- );-- const handleOpenItem = useCallback(- (item: WorkflowLibraryListItem, mode: OpenLibraryWorkflowMode) => void open(item, mode),- [open]+ [handleOpenItem]);const handleDeleted = useCallback(() => {@@ -425,7 +418,6 @@ export const WorkflowLibraryDialog = ({onDuplicated={setSelectedWorkflowId}onOpen={handleOpenItem}onPreview={handlePreviewRequest}- onResume={resume}/></>)}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.browser.test.tsxnew file mode 100644index 0000000000..32db7dd13e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.browser.test.tsx@@ -0,0 +1,157 @@+/* eslint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop -- the probe wires fakes directly */+import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';++import { workflowFitViewRequestStore } from '@features/workflow/ui/editor/flowInstanceStore';+import { WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useOpenLibraryWorkflow } from './useOpenLibraryWorkflow';++const library = vi.hoisted(() => ({+ beforeAnswer: () => {},+ getLibraryWorkflowRecordCached: vi.fn(),+}));++vi.mock('@features/workflow/queries', () => ({+ getLibraryWorkflowRecordCached: (workflowId: string) => {+ library.beforeAnswer();+ return library.getLibraryWorkflowRecordCached(workflowId);+ },+ touchLibraryWorkflowOpenedAt: () => Promise.resolve(),+}));++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const ITEM = { name: 'Portrait', workflow_id: 'lib-portrait' };+const RECORD = {+ name: 'Portrait',+ revision: 4,+ workflow: {+ author: '',+ contact: '',+ description: '',+ edges: [],+ exposedFields: [],+ form: { elements: {}, rootElementId: '' },+ meta: { category: 'user', version: '3.0.0' },+ name: 'Portrait',+ nodes: [+ {+ data: {+ id: 'value',+ inputs: { value: { label: '', name: 'value', value: 1 } },+ isIntermediate: false,+ isOpen: true,+ label: '',+ nodePack: 'invokeai',+ notes: '',+ type: 'integer',+ useCache: true,+ version: '1.0.1',+ },+ id: 'value',+ position: { x: 400, y: 300 },+ type: 'invocation',+ },+ ],+ notes: '',+ tags: '',+ version: '3.0.0',+ },+ workflow_id: ITEM.workflow_id,+};++describe('useOpenLibraryWorkflow replace', () => {+ let host: HTMLDivElement;+ let root: Root;+ let projectId: string;+ let commands: { addWorkflow: ReturnType<typeof vi.fn>; replaceWorkflow: ReturnType<typeof vi.fn> };+ let notifications: { error: ReturnType<typeof vi.fn>; info: ReturnType<typeof vi.fn> };+ const onOpened = vi.fn();++ const Probe = () => {+ const { replace } = useOpenLibraryWorkflow(onOpened);++ return (+ <button type="button" onClick={() => void replace(ITEM, 'copy-1')}>+ replace+ </button>+ );+ };++ const runReplace = async () => {+ await act(() =>+ root.render(+ <WorkflowUiProvider+ adapter={+ {+ commands,+ notifications,+ project: { getSnapshot: () => ({ id: projectId, workflows: [] }), subscribe: () => () => {} },+ } as unknown as WorkflowUiAdapter+ }+ >+ <Probe />+ </WorkflowUiProvider>+ )+ );+ await act(async () => {+ host.querySelector('button')!.click();+ await vi.waitFor(() => expect(library.getLibraryWorkflowRecordCached).toHaveBeenCalled());+ // The load waits two frames for the busy overlay to paint before applying.+ await new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));+ });+ });+ };++ beforeEach(() => {+ projectId = 'project-1';+ commands = { addWorkflow: vi.fn(), replaceWorkflow: vi.fn() };+ notifications = { error: vi.fn(), info: vi.fn() };+ onOpened.mockClear();+ library.beforeAnswer = () => {};+ library.getLibraryWorkflowRecordCached.mockReset().mockResolvedValue(RECORD);+ workflowFitViewRequestStore.setSnapshot({ request: null });+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ it('puts the library version in the chosen copy at its revision and fits the copy’s kept editor', async () => {+ await runReplace();++ expect(commands.replaceWorkflow).toHaveBeenCalledExactlyOnceWith(+ { projectId: 'project-1', workflowId: 'copy-1' },+ expect.objectContaining({ nodes: [expect.objectContaining({ id: 'value' })] }),+ { label: 'workflowLibrary.replacedLabel', source: { libraryWorkflowId: ITEM.workflow_id, revision: 4 } }+ );+ expect(commands.addWorkflow).not.toHaveBeenCalled();+ expect(workflowFitViewRequestStore.getSnapshot().request).toMatchObject({+ nodes: [{ id: 'value', position: { x: 400, y: 300 } }],+ scope: { projectId: 'project-1', workflowId: 'copy-1' },+ });+ expect(onOpened).toHaveBeenCalledTimes(1);+ });++ it('replaces nothing when another project became active while the template loaded', async () => {+ library.beforeAnswer = () => {+ projectId = 'project-2';+ };++ await runReplace();++ expect(commands.replaceWorkflow).not.toHaveBeenCalled();+ expect(notifications.info).toHaveBeenCalledWith('workflowLibrary.openProjectChanged');+ expect(onOpened).not.toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.test.tsindex a56af1c84e..a147c85b82 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.test.ts@@ -9,12 +9,12 @@ const entry = (id: string, libraryWorkflowId?: string) => ({});describe('planLibraryWorkflowOpen', () => {- it('adds a copy when the project has none, resumes a single copy, and asks when there are several', () => {+ it('adds the first copy and asks once the project holds any', () => {expect(planLibraryWorkflowOpen([entry('a'), entry('b', 'other')], 'lib')).toEqual({ kind: 'add' });- expect(planLibraryWorkflowOpen([entry('a', 'lib'), entry('b')], 'lib')).toEqual({- kind: 'resume',- workflowId: 'a',- });++ const single = [entry('a', 'lib')];++ expect(planLibraryWorkflowOpen([...single, entry('b')], 'lib')).toEqual({ copies: single, kind: 'choose' });const copies = [entry('a', 'lib'), entry('b', 'lib')];diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.tsindex c975c2e3af..1201a71e55 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.ts@@ -1,8 +1,9 @@import type { ProjectWorkflowEntry } from '@features/workflow/core/types';-import type { WorkflowLibraryListItem } from '@features/workflow/queries';+import type { LibraryOpenItem } from '@features/workflow/ui/workflowUiStore';import { updateLoadedWorkflowNodes } from '@features/workflow/data/templates';import { getLibraryWorkflowRecordCached, touchLibraryWorkflowOpenedAt } from '@features/workflow/queries';+import { requestWorkflowFitView } from '@features/workflow/ui/editor/flowInstanceStore';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import { useWorkflowNotifications, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';import { parseWorkflowJson } from '@features/workflow/utility';@@ -18,23 +19,21 @@ import { useTranslation } from 'react-i18next';import { findProjectCopiesOf } from './projectWorkflowEntries';/**- * Opening a template always lands in the project's own collection: as a new copy, or by resuming the copy the- * project already made from it. Overlapping opens are dropped; a queued second load would add a second copy.+ * Opening a template always lands in the project's own collection. The first copy is added directly; once the+ * project holds one, the caller asks whether to open a copy, add another, or replace one with the library version.+ * Overlapping loads are dropped; a queued second load would add a second copy.*/export type WorkflowLoadPhase = 'applying' | 'fetching' | 'idle';export type OpenLibraryWorkflowMode =- /** Resume the one existing copy, or add the first; several copies need a choice the caller makes. */- | 'resume-or-add'- /** Always add a fresh, independent copy beside any existing ones. */+ /** The project's first copy; it may take over the untouched blank a fresh project starts with. */+ | 'first-copy'+ /** Another, independent copy beside the existing ones. */| 'add-copy';-/** What opening a template would do given the project's current copies. */-export type LibraryWorkflowOpenPlan =- | { kind: 'add' }- | { kind: 'resume'; workflowId: string }- | { kind: 'choose'; copies: readonly ProjectWorkflowEntry[] };+/** What opening a template involves given the project's current copies. */+export type LibraryWorkflowOpenPlan = { kind: 'add' } | { kind: 'choose'; copies: readonly ProjectWorkflowEntry[] };export const planLibraryWorkflowOpen = (workflows: readonly ProjectWorkflowEntry[],@@ -42,29 +41,25 @@ export const planLibraryWorkflowOpen = (): LibraryWorkflowOpenPlan => {const copies = findProjectCopiesOf(workflows, libraryWorkflowId);- if (copies.length === 0) {- return { kind: 'add' };- }-- if (copies.length === 1) {- return { kind: 'resume', workflowId: copies[0]!.document.id };- }-- return { copies, kind: 'choose' };+ return copies.length === 0 ? { kind: 'add' } : { copies, kind: 'choose' };};export interface OpenLibraryWorkflow {- /** Fetches the template and adds a copy, or resumes the existing one; resolves once the project has it. */- open: (item: Pick<WorkflowLibraryListItem, 'name' | 'workflow_id'>, mode: OpenLibraryWorkflowMode) => Promise<void>;+ /** Fetches the template and adds a copy; resolves once the project has it. */+ open: (item: LibraryOpenItem, mode: OpenLibraryWorkflowMode) => Promise<void>;+ /** Fetches the template and puts it in place of an existing copy, as one undo step. */+ replace: (item: LibraryOpenItem, workflowId: string) => Promise<void>;/** Activates a copy the project already owns. */resume: (workflowId: string) => void;/** Drives the caller's busy overlay; `applying` is the expensive half. */loadPhase: WorkflowLoadPhase;}+type LibraryLoadTarget = { kind: 'add'; mode: OpenLibraryWorkflowMode } | { kind: 'replace'; workflowId: string };+export const useOpenLibraryWorkflow = (onOpened: () => void): OpenLibraryWorkflow => {const { t } = useTranslation();- const { addWorkflow, selectWorkflow } = useProjectGraphCommands();+ const { addWorkflow, replaceWorkflow, selectWorkflow } = useProjectGraphCommands();const { project } = useWorkflowUi();const notify = useWorkflowNotifications();const [loadPhase, setLoadPhase] = useState<WorkflowLoadPhase>('idle');@@ -78,28 +73,14 @@ export const useOpenLibraryWorkflow = (onOpened: () => void): OpenLibraryWorkflo[onOpened, selectWorkflow]);- const open = useCallback(- async (item: Pick<WorkflowLibraryListItem, 'name' | 'workflow_id'>, mode: OpenLibraryWorkflowMode) => {+ const load = useCallback(+ async (item: LibraryOpenItem, target: LibraryLoadTarget) => {const owner = captureAccountScope();if (isInFlightRef.current) {return;}- if (mode === 'resume-or-add') {- const plan = planLibraryWorkflowOpen(project.getSnapshot().workflows, item.workflow_id);-- if (plan.kind === 'resume') {- resume(plan.workflowId);- return;- }-- if (plan.kind === 'choose') {- // Several copies exist; the surface offering the open owns the choice.- return;- }- }-isInFlightRef.current = true;// The project the open started from is the project it lands in, whatever becomes active meanwhile.@@ -132,12 +113,22 @@ export const useOpenLibraryWorkflow = (onOpened: () => void): OpenLibraryWorkfloreturn;}- addWorkflow(document, {- label: t('workflowLibrary.loadedLabel', { name: item.name }),- // The first copy may take over the blank a fresh project starts with; another copy never does.- reusePlaceholder: mode === 'resume-or-add',- source: { libraryWorkflowId: record.workflow_id, revision: record.revision },- });+ const source = { libraryWorkflowId: record.workflow_id, revision: record.revision };++ if (target.kind === 'replace') {+ replaceWorkflow({ projectId, workflowId: target.workflowId }, document, {+ label: t('workflowLibrary.replacedLabel', { name: item.name }),+ source,+ });+ // The copy keeps its id, so its editor stays mounted and fits the new graph on request.+ requestWorkflowFitView({ projectId, workflowId: target.workflowId }, document.nodes);+ } else {+ addWorkflow(document, {+ label: t('workflowLibrary.loadedLabel', { name: item.name }),+ reusePlaceholder: target.mode === 'first-copy',+ source,+ });+ }for (const warning of warnings) {notify.info(t('workflowLibrary.loadWarning'), warning);@@ -163,8 +154,16 @@ export const useOpenLibraryWorkflow = (onOpened: () => void): OpenLibraryWorkflo}}},- [addWorkflow, notify, onOpened, project, resume, t]+ [addWorkflow, notify, onOpened, project, replaceWorkflow, t]+ );+ const open = useCallback(+ (item: LibraryOpenItem, mode: OpenLibraryWorkflowMode) => load(item, { kind: 'add', mode }),+ [load]+ );+ const replace = useCallback(+ (item: LibraryOpenItem, workflowId: string) => load(item, { kind: 'replace', workflowId }),+ [load]);- return { loadPhase, open, resume };+ return { loadPhase, open, replace, resume };};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.tsindex a0c1b5e187..46ae343b37 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts@@ -44,10 +44,28 @@ export interface WorkflowUiSnapshot {pendingWorkflowLoad: WorkflowLoadRequest | null;/** A publication the always-mounted host should start a dialog for. */publicationIntent: WorkflowPublicationIntent | null;+ /** A template the project already holds copies of; the host asks whether to open, add, or replace a copy. */+ libraryCopyChoice: LibraryCopyChoiceRequest | null;}+/** The library template being opened; the name labels the dialog and the undo step. */+export interface LibraryOpenItem {+ name: string;+ workflow_id: string;+}++export interface LibraryCopyChoiceRequest {+ item: LibraryOpenItem;+ /** The project whose copies the choice is about; another active project never sees it. */+ projectId: string;+ requestId: number;+}++let nextLibraryCopyChoiceRequestId = 0;+export type WorkflowLoadSource =- | { kind: 'library'; workflowId: string }+ /** `name` titles the copy question when the project already holds the template. */+ | { kind: 'library'; name?: string; workflowId: string }/** An already-fetched workflow document (an image's embedded workflow); `label` names the undo step. */| { kind: 'document'; label: string; raw: unknown };@@ -69,6 +87,7 @@ const INITIAL_WORKFLOW_UI_SNAPSHOT: WorkflowUiSnapshot = {libraryTab: 'project',pendingWorkflowLoad: null,publicationIntent: null,+ libraryCopyChoice: null,};export const workflowUiStore = createExternalStore<WorkflowUiSnapshot>(INITIAL_WORKFLOW_UI_SNAPSHOT);@@ -103,6 +122,23 @@ export const openWorkflowLibraryAtProjectWorkflow = (projectId: string, workflow});};+export const requestLibraryCopyChoice = (projectId: string, item: LibraryOpenItem): void => {+ nextLibraryCopyChoiceRequestId += 1;+ workflowUiStore.patchSnapshot({+ libraryCopyChoice: {+ item: { name: item.name, workflow_id: item.workflow_id },+ projectId,+ requestId: nextLibraryCopyChoiceRequestId,+ },+ });+};++export const clearLibraryCopyChoice = (requestId: number): void => {+ if (workflowUiStore.getSnapshot().libraryCopyChoice?.requestId === requestId) {+ workflowUiStore.patchSnapshot({ libraryCopyChoice: null });+ }+};+export const requestWorkflowPublication = (intent: WorkflowPublicationIntent): void => {workflowUiStore.patchSnapshot({ publicationIntent: intent });};@@ -130,8 +166,8 @@ const requestWorkflowLoad = (source: WorkflowLoadSource): void => {workflowUiStore.patchSnapshot({ pendingWorkflowLoad: { requestId: nextWorkflowLoadRequestId, source } });};-export const requestLibraryWorkflowLoad = (workflowId: string): void =>- requestWorkflowLoad({ kind: 'library', workflowId });+export const requestLibraryWorkflowLoad = (workflowId: string, name?: string): void =>+ requestWorkflowLoad({ kind: 'library', workflowId, ...(name ? { name } : {}) });export const requestWorkflowDocumentLoad = (raw: unknown, label: string): void =>requestWorkflowLoad({ kind: 'document', label, raw });diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.tsindex 84ed3cd8da..dddfbeb8c7 100644--- a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts@@ -69,7 +69,7 @@ export const createWorkflowsProvider = ({keywords: item.tags,run: () => {openWorkflowWidget();- requestLibraryWorkflowLoad(item.workflowId);+ requestLibraryWorkflowLoad(item.workflowId, item.name);},subtitle:item.category === 'default'diff --git a/invokeai/frontend/webv2/src/workbench/projectWorkflows.test.ts b/invokeai/frontend/webv2/src/workbench/projectWorkflows.test.tsindex 847236e91a..aa0464d093 100644--- a/invokeai/frontend/webv2/src/workbench/projectWorkflows.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projectWorkflows.test.ts@@ -15,6 +15,7 @@ import {recordProjectWorkflowRun,redoProjectWorkflow,removeProjectWorkflow,+ replaceProjectWorkflowDocument,selectProjectWorkflow,setProjectWorkflowSource,stripProjectWorkflowSources,@@ -271,6 +272,61 @@ describe('per-workflow edit history', () => {});});+describe('replacing a copy with its library version', () => {+ it('keeps the copy’s id and name, moves its source, and undoes to the previous graph in one step', () => {+ const copy = { ...createProjectGraph('copy'), name: 'My tweaks' };+ let project: ProjectWorkflowSession = {+ workflowHistories: {},+ workflows: {+ activeWorkflowId: 'copy',+ entries: [{ document: copy, source: { libraryWorkflowId: 'lib', revision: 1 } }],+ },+ };++ project = addNode(project, 'copy', 'mine');++ const authored = getActiveProjectGraph(project);+ const library = { ...createProjectGraph('parsed-elsewhere'), name: 'Library name' };+ const libraryWithNode = applyProjectWorkflowAction(session(library), library.id, {+ node: { ...buildInvocationNode(template, { x: 10, y: 10 }), id: 'theirs' },+ type: 'addNode',+ }).project;++ project = replaceProjectWorkflowDocument(project, 'copy', getActiveProjectGraph(libraryWithNode), {+ label: 'Replace',+ source: { libraryWorkflowId: 'lib', revision: 4 },+ });++ const replaced = project.workflows.entries[0]!;++ expect(replaced.document).toMatchObject({ id: 'copy', name: 'My tweaks' });+ expect(replaced.document.nodes.map((node) => node.id)).toEqual(['theirs']);+ expect(replaced.source).toEqual({ libraryWorkflowId: 'lib', revision: 4 });++ project = undoProjectWorkflow(project, 'copy');++ // The graph and the revision it is based on travel together, so a later update still meets the conflict check.+ expect(getActiveProjectGraph(project)).toBe(authored);+ expect(project.workflows.entries[0]!.source).toEqual({ libraryWorkflowId: 'lib', revision: 1 });++ project = redoProjectWorkflow(project, 'copy');++ expect(getActiveProjectGraph(project).nodes.map((node) => node.id)).toEqual(['theirs']);+ expect(project.workflows.entries[0]!.source).toEqual({ libraryWorkflowId: 'lib', revision: 4 });+ });++ it('leaves the project alone when the copy is gone', () => {+ const project = session(createProjectGraph('a'));++ expect(+ replaceProjectWorkflowDocument(project, 'missing', createProjectGraph('b'), {+ label: 'Replace',+ source: { libraryWorkflowId: 'lib', revision: 1 },+ })+ ).toBe(project);+ });+});+describe('persisted collections', () => {it('migrates a single graph into the first, active workflow and turns a binding into an unknown-revision source', () => {const graph = { ...createProjectGraph('legacy'), libraryWorkflowId: 'lib-9' };diff --git a/invokeai/frontend/webv2/src/workbench/projectWorkflows.ts b/invokeai/frontend/webv2/src/workbench/projectWorkflows.tsindex 9d4ecf12b0..9610d3b931 100644--- a/invokeai/frontend/webv2/src/workbench/projectWorkflows.ts+++ b/invokeai/frontend/webv2/src/workbench/projectWorkflows.ts@@ -38,6 +38,11 @@ export interface WorkflowHistoryEntry {mergedAt?: string;/** Global order across the project's histories; the aggregate cap evicts the lowest first. */sequence: number;+ /**+ * The library source the copy had before the step, for steps that move it (a library replace); null means none.+ * Undo restores it with the document, so the copy never claims a revision its graph is not based on.+ */+ source?: ProjectWorkflowSource | null;}export interface WorkflowEditHistory {@@ -390,6 +395,40 @@ export const setProjectWorkflowSource = <Session extends ProjectWorkflowSession>return source ? { ...rest, source } : rest;});+/**+ * Puts a freshly loaded document in a copy's place as one undoable step. The copy keeps its id and name, and its+ * source moves to the revision it now holds.+ */+export const replaceProjectWorkflowDocument = <Session extends ProjectWorkflowSession>(+ project: Session,+ workflowId: string,+ document: ProjectGraphState,+ { label, source }: { label: string; source: ProjectWorkflowSource },+ timestamp = new Date().toISOString()+): Session => {+ const entry = findProjectWorkflow(project, workflowId);++ if (!entry) {+ return project;+ }++ const withHistory = pushHistory(+ project,+ workflowId,+ entry.document,+ label,+ undefined,+ timestamp,+ entry.source ?? null+ );++ return replaceEntry(withHistory, workflowId, (current) => ({+ ...current,+ document: { ...document, id: workflowId, name: current.document.name },+ source,+ }));+};+/** Records a successful run's output. An older submission that finishes later never replaces a newer one. */export const recordProjectWorkflowRun = <Session extends ProjectWorkflowSession>(project: Session,@@ -467,7 +506,8 @@ const pushHistory = <Session extends ProjectWorkflowSession>(previous: ProjectGraphState,label: string,mergeKey: string | undefined,- timestamp: string+ timestamp: string,+ previousSource?: ProjectWorkflowSource | null): Session => {const history = getProjectWorkflowHistory(project, workflowId);const last = history.past.at(-1);@@ -498,6 +538,7 @@ const pushHistory = <Session extends ProjectWorkflowSession>(label,...(mergeKey ? { mergeKey } : {}),sequence: nextHistorySequence,+ ...(previousSource !== undefined ? { source: previousSource } : {}),};return {@@ -545,6 +586,17 @@ export const applyProjectWorkflowAction = <Session extends ProjectWorkflowSessio};};+/** Puts a history entry's document back, and its source when the step moved it. */+const restoreHistoryEntry = (current: ProjectWorkflowEntry, step: WorkflowHistoryEntry): ProjectWorkflowEntry => {+ if (step.source === undefined) {+ return { ...current, document: step.document };+ }++ const { source: _moved, ...rest } = current;++ return step.source ? { ...rest, document: step.document, source: step.source } : { ...rest, document: step.document };+};+export const undoProjectWorkflow = <Session extends ProjectWorkflowSession>(project: Session,workflowId: string,@@ -566,8 +618,9 @@ export const undoProjectWorkflow = <Session extends ProjectWorkflowSession>(id: `redo-${nextHistorySequence.toString(36)}`,label: undone.label,sequence: nextHistorySequence,+ ...(undone.source !== undefined ? { source: entry.source ?? null } : {}),};- const restored = replaceEntry(project, workflowId, (current) => ({ ...current, document: undone.document }));+ const restored = replaceEntry(project, workflowId, (current) => restoreHistoryEntry(current, undone));return {...restored,@@ -602,8 +655,9 @@ export const redoProjectWorkflow = <Session extends ProjectWorkflowSession>(id: `undo-${nextHistorySequence.toString(36)}`,label: redone.label,sequence: nextHistorySequence,+ ...(redone.source !== undefined ? { source: entry.source ?? null } : {}),};- const restored = replaceEntry(project, workflowId, (current) => ({ ...current, document: redone.document }));+ const restored = replaceEntry(project, workflowId, (current) => restoreHistoryEntry(current, redone));return {...restored,diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex b63d944385..de7ab0772c 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -112,6 +112,7 @@ import {recordProjectWorkflowRun,redoProjectWorkflow,removeProjectWorkflow,+ replaceProjectWorkflowDocument,selectProjectWorkflow,setProjectWorkflowDocument,setProjectWorkflowSource,@@ -341,6 +342,14 @@ type WorkbenchReducerAction =| { type: 'duplicateProjectWorkflow'; workflowId: string; copyId: string; copyName: string; projectId?: string }| { type: 'removeProjectWorkflow'; workflowId: string; projectId?: string }| { type: 'setProjectWorkflowSource'; projectId: string; workflowId: string; source?: ProjectWorkflowSource }+ | {+ type: 'replaceProjectWorkflowDocument';+ projectId: string;+ workflowId: string;+ document: ProjectGraphState;+ label: string;+ source: ProjectWorkflowSource;+ }| { type: 'undoWorkflowChange'; projectId?: string; workflowId?: string }| { type: 'redoWorkflowChange'; projectId?: string; workflowId?: string }| { type: 'submitInvocationSnapshot'; backendSupportsCancellation: boolean; models?: readonly ModelConfig[] }@@ -4322,6 +4331,20 @@ export const __workbenchReducerInternal = (removeProjectWorkflow(project, action.workflowId));}+ case 'replaceProjectWorkflowDocument': {+ return updateProjectById(state, action.projectId, (project) =>+ selectProjectWorkflow(+ replaceProjectWorkflowDocument(+ project,+ action.workflowId,+ action.document,+ { label: action.label, source: action.source },+ now()+ ),+ action.workflowId+ )+ );+ }case 'setProjectWorkflowSource': {return updateProjectById(state, action.projectId, (project) =>setProjectWorkflowSource(project, action.workflowId, action.source)diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex 772a9559bd..02d31f4a7c 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -535,6 +535,15 @@ const createCommands = (});return { ok: true };},+ /** Replaces a copy's document with a fresh load and activates it; one undo step restores the old one. */+ replaceDocument: command(+ 'replaceProjectWorkflowDocument',+ (+ target: { projectId: string; workflowId: string },+ document: ProjectGraphState,+ options: { label: string; source: ProjectWorkflowSource }+ ) => ({ ...target, ...options, document })+ ),select: command('selectProjectWorkflow', (workflowId: string, projectId?: string) => ({ projectId, workflowId })),/** Records where a workflow was explicitly published; a no-op once the project or workflow is gone. */setSource: command(