Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(webv2): guard workflow duplicate action and memoize per-entry requirement resolution
joshistoastdc2eb9e590bc
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 0e66e839d9..94babb2d02 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2984,6 +2984,7 @@"duplicate": "Duplicate","duplicateFailed": "Failed to duplicate workflow","duplicateName": "{{name}} copy",+ "duplicated": "Saved a copy under Yours","empty": "No workflows match these filters.","fetching": "Fetching workflow…","forkIntoProject": "Fork into new project",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 05aaf2f15e..a5a0fc54c8 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@@ -88,6 +88,7 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.duplicate': 'Duplicate','workflowLibrary.duplicateFailed': 'Failed to duplicate workflow','workflowLibrary.duplicateName': '{{name}} copy',+ 'workflowLibrary.duplicated': 'Saved a copy under Yours','workflowLibrary.forkIntoProject': 'Fork into new project','workflowLibrary.installModels_one': 'Install 1 model','workflowLibrary.installModels_other': 'Install {{count}} models',@@ -529,6 +530,49 @@ describe('WorkflowLibraryDetailPanel', () => {expect(RAW_WORKFLOW.meta).toStrictEqual({ category: 'default', version: '3.0.0' });expect(queries.invalidateWorkflowLibraryCache).toHaveBeenCalledTimes(1);expect(onDuplicated).toHaveBeenCalledWith('wf-copy');+ // From Browse, the copy lands in a category the user is not looking at, so+ // the notice is the only confirmation there is.+ expect(NOTIFICATIONS.success).toHaveBeenCalledWith('Saved a copy under Yours');+ });++ it('refuses a second duplicate while the first is still in flight', async () => {+ let release: (raw: Record<string, unknown>) => void = () => {};++ queries.getLibraryWorkflowCached.mockImplementation(+ () =>+ new Promise<Record<string, unknown>>((resolve) => {+ release = resolve;+ })+ );++ await renderPanel(DEFAULT_CATEGORY);++ await clickMenuItem('duplicate');++ // Nothing has changed on screen yet — the copy is two round trips away and+ // lands in a category this view is not showing — so the menu item holds+ // itself closed instead of letting an impatient second click mint a second+ // copy.+ await openMenu();+ expect(menuItem('duplicate')?.getAttribute('aria-disabled')).toBe('true');++ await act(async () => {+ menuItem('duplicate')?.click();+ await settleFrame();+ });++ await act(async () => {+ release(RAW_WORKFLOW);+ await settleFrame();+ });++ expect(queries.getLibraryWorkflowCached).toHaveBeenCalledTimes(1);+ expect(queries.createLibraryWorkflow).toHaveBeenCalledTimes(1);+ expect(NOTIFICATIONS.success).toHaveBeenCalledTimes(1);++ // And it is offered again once the copy exists.+ await openMenu();+ expect(menuItem('duplicate')?.getAttribute('aria-disabled')).toBeNull();});it('forks the cached workflow into a fresh project', 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 84b468f412..26a3279298 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx@@ -4,7 +4,6 @@ import type { WorkflowLibraryListItem } from '@features/workflow/queries';import { Badge, Box, Flex, HStack, Icon, Image, Menu, Portal, Stack, Text } from '@chakra-ui/react';import { getStarterModelInstallSources, useInstallActions } from '@features/models';-import { resolveWorkflowModelRequirements } from '@features/workflow/core/modelRequirements';import {createLibraryWorkflow,deleteLibraryWorkflow,@@ -31,11 +30,15 @@ import {Trash2Icon,WorkflowIcon,} from 'lucide-react';-import { useCallback, useMemo, useState } from 'react';+import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { formatRelativeTime } from './relativeTime';-import { useModelRequirementDeps, WorkflowRequirementsList } from './WorkflowRequirementsList';+import {+ resolveEntryRequirements,+ useModelRequirementDeps,+ WorkflowRequirementsList,+} from './WorkflowRequirementsList';/*** The library's right rail: everything about the selected workflow that@@ -51,6 +54,7 @@ import { useModelRequirementDeps, WorkflowRequirementsList } from './WorkflowReqconst DETAIL_RAIL_WIDTH = '18rem';const THUMBNAIL_ASPECT_RATIO = 3 / 2;+const DISABLED_ITEM = { opacity: 0.4 } as const;const INSTALL_HOVER = { opacity: 0.85 } as const;const MENU_ITEM_LAYOUT = { alignItems: 'center', gap: '2.5', py: '1' } as const;const MENU_ITEM_ICON_PROPS = { boxSize: '3.5', flexShrink: 0 } as const;@@ -85,13 +89,18 @@ export const WorkflowLibraryDetailPanel = ({// thumbnail without an effect resetting the flag.const [failedThumbnailUrl, setFailedThumbnailUrl] = useState<string | null>(null);const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);+ // A duplicate is two round trips with nothing on screen between them, and a+ // copy of a default lands in a category the user is not looking at — so the+ // menu item has to hold itself closed until the copy exists, or an impatient+ // second click mints a second copy.+ const [isDuplicatePending, setIsDuplicatePending] = useState(false);+ const isDuplicatePendingRef = useRef(false);const enrichment = entry?.enrichment ?? null;+ // Shares the grid's per-entry cache, so selecting a card the badges already+ // resolved costs nothing.const resolved = useMemo(- () =>- enrichment?.status === 'ready'- ? resolveWorkflowModelRequirements(enrichment.requirements.requirements, deps)- : null,+ () => (enrichment?.status === 'ready' ? resolveEntryRequirements(enrichment, deps) : null),[deps, enrichment]);const installableCount = resolved?.filter((requirement) => requirement.status === 'installable').length ?? 0;@@ -154,13 +163,16 @@ export const WorkflowLibraryDetailPanel = ({* loading it.*/const duplicate = useCallback(async () => {- if (!entry) {+ if (!entry || isDuplicatePendingRef.current) {return;}const owner = captureAccountScope();const { name } = entry.item;+ isDuplicatePendingRef.current = true;+ setIsDuplicatePending(true);+try {const raw = await getLibraryWorkflowCached(entry.item.workflow_id, owner.signal);@@ -180,11 +192,19 @@ export const WorkflowLibraryDetailPanel = ({assertAccountScopeCurrent(owner);invalidateWorkflowLibraryCache();+ // The copy is forced into the user category, so from the Browse tab it+ // lands out of sight — the notice is the only thing that says it worked.+ notify.success(t('workflowLibrary.duplicated'));onDuplicated(workflowId);} catch (error) {if (isAccountScopeCurrent(owner)) {notify.error(t('workflowLibrary.duplicateFailed'), getApiErrorMessage(error, t('common.unknownError')));}+ } finally {+ if (isAccountScopeCurrent(owner)) {+ isDuplicatePendingRef.current = false;+ setIsDuplicatePending(false);+ }}}, [entry, notify, onDuplicated, t]);const handleDuplicate = useCallback(() => void duplicate(), [duplicate]);@@ -378,7 +398,9 @@ export const WorkflowLibraryDetailPanel = ({</Menu.Item><Menu.Item{...MENU_ITEM_LAYOUT}+ _disabled={DISABLED_ITEM}data-menu-item="duplicate"+ disabled={isDuplicatePending}value="duplicate"onClick={handleDuplicate}>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.browser.test.tsxnew file mode 100644index 0000000000..80846a2b08--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.browser.test.tsx@@ -0,0 +1,157 @@+import type * as ModelRequirementsModule from '@features/workflow/core/modelRequirements';+import type { WorkflowModelRequirement } from '@features/workflow/core/modelRequirements';+import type { WorkflowLibraryEntry, WorkflowLibraryEntryEnrichment } from '@features/workflow/data/libraryBrowseStore';++import { createProjectGraph } from '@features/workflow/utility';+import { act, useEffect } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useWorkflowLibraryMissingCounts } from './WorkflowRequirementsList';++/**+ * The browse store publishes a fresh `entries` array every time a *single*+ * workflow finishes enriching, with four workers running — so loading a page+ * of 20 re-runs this hook 20 times. Resolution is therefore cached per+ * enrichment object, and this suite is the proof: the real resolver is wrapped+ * in a spy, and the assertion is how many entries each publish re-resolves.+ */+const resolveSpy = vi.hoisted(() => vi.fn());++vi.mock('@features/workflow/core/modelRequirements', async (importOriginal) => {+ const original = await importOriginal<typeof ModelRequirementsModule>();++ return {+ ...original,+ resolveWorkflowModelRequirements: (...args: Parameters<typeof original.resolveWorkflowModelRequirements>) => {+ resolveSpy(...args);++ return original.resolveWorkflowModelRequirements(...args);+ },+ };+});++const models = vi.hoisted(() => ({+ ensureModelsLoaded: vi.fn(() => Promise.resolve()),+ ensureStartersLoaded: vi.fn(),+ installedModels: { current: [] as unknown[] },+}));++vi.mock('@features/models', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ ensureModelsLoaded: models.ensureModelsLoaded,+ ensureStartersLoaded: models.ensureStartersLoaded,+ useActiveInstallSources: () => EMPTY_SOURCES,+ useModelsSelector: (selector: (snapshot: unknown) => unknown) => selector({ models: models.installedModels.current }),+ useStartersSelector: (selector: (snapshot: unknown) => unknown) =>+ selector({ response: { starter_models: STARTERS } }),+}));++const EMPTY_SOURCES: ReadonlySet<string> = new Set<string>();+const STARTERS = [+ {+ base: 'flux',+ description: 'FLUX.1 dev',+ is_installed: false,+ name: 'FLUX.1 dev',+ source: 'https://models.test/flux',+ type: 'main',+ },+];++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const FLUX_SLOT: WorkflowModelRequirement = { base: 'flux', kind: 'slot', label: 'FLUX checkpoint', modelType: 'main' };++const readyEnrichment = (): WorkflowLibraryEntryEnrichment => ({+ document: createProjectGraph('requirements-fixture'),+ nodeCount: 1,+ // A new object per call: this is the identity the cache keys on.+ requirements: { primaryBase: 'flux', requirements: [FLUX_SLOT] },+ status: 'ready',+});++const entry = (workflowId: string, enrichment: WorkflowLibraryEntryEnrichment): WorkflowLibraryEntry => ({+ enrichment,+ item: { category: 'user', description: '', name: workflowId, thumbnail_url: null, workflow_id: workflowId },+ tags: [],+});++describe('useWorkflowLibraryMissingCounts', () => {+ let host: HTMLDivElement;+ let root: Root;+ let counts: ReadonlyMap<string, number> | null;++ const Harness = ({ entries }: { entries: readonly WorkflowLibraryEntry[] }) => {+ const result = useWorkflowLibraryMissingCounts(entries);++ // Published after the commit, not during render, so the hook under test is+ // the only thing this component does while rendering.+ useEffect(() => {+ counts = result;+ });++ return null;+ };++ // No StrictMode here: this suite counts resolver invocations, and the+ // deliberate double-render would double every number it asserts.+ const render = async (entries: readonly WorkflowLibraryEntry[]) => {+ await act(() => {+ root.render(<Harness entries={entries} />);+ });+ };++ beforeEach(() => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ counts = null;+ models.installedModels.current = [];+ resolveSpy.mockClear();+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ it('re-resolves only the entry whose enrichment changed', async () => {+ const stable = entry('wf-a', readyEnrichment());+ const pending = entry('wf-b', { status: 'pending' });++ await render([stable, pending]);++ expect(resolveSpy).toHaveBeenCalledTimes(1);+ expect(counts?.get('wf-a')).toBe(1);+ expect(counts?.has('wf-b')).toBe(false);++ resolveSpy.mockClear();++ // What the store publishes when one more workflow finishes parsing: a new+ // array, a new entry object for the row that changed, and the untouched+ // entry (and its enrichment) carried over by identity.+ await render([stable, entry('wf-b', readyEnrichment())]);++ expect(resolveSpy).toHaveBeenCalledTimes(1);+ expect(counts?.get('wf-a')).toBe(1);+ expect(counts?.get('wf-b')).toBe(1);+ });++ it('re-resolves everything when the installed models change under it', async () => {+ const entries = [entry('wf-a', readyEnrichment()), entry('wf-b', readyEnrichment())];++ await render(entries);++ expect(resolveSpy).toHaveBeenCalledTimes(2);++ resolveSpy.mockClear();+ // The install landed: every row's answer can differ now.+ models.installedModels.current = [{ base: 'flux', hash: 'h', key: 'k', name: 'FLUX.1 dev', type: 'main' }];++ await render([...entries]);++ expect(resolveSpy).toHaveBeenCalledTimes(2);+ expect(counts?.size).toBe(0);+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsxindex 86856ee6ee..3506b017ad 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsx@@ -4,7 +4,7 @@ import type {ResolvedModelRequirement,WorkflowModelRequirement,} from '@features/workflow/core/modelRequirements';-import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';+import type { WorkflowLibraryEntry, WorkflowLibraryEntryEnrichment } from '@features/workflow/data/libraryBrowseStore';import type { ElementType } from 'react';import { DataList, Icon, Skeleton, Spinner, Stack, Text } from '@chakra-ui/react';@@ -85,6 +85,40 @@ export const useModelRequirementDeps = (): ModelRequirementDeps => {);};+type ReadyEnrichment = Extract<WorkflowLibraryEntryEnrichment, { status: 'ready' }>;++/**+ * Resolution is keyed by the enrichment object because that is exactly what+ * changes when one workflow finishes parsing: the browse store publishes a new+ * `entries` array per *individual* completion, with four workers running, so a+ * page of 20 lands 20 arrays. Without this, every one of those would re-resolve+ * every row — quadratic, synchronously, in render. The deps the entry was+ * resolved under are stored alongside, so a model install or a starter-catalog+ * load invalidates the entry as it should.+ */+const resolutionCache = new WeakMap<+ ReadyEnrichment,+ { deps: ModelRequirementDeps; resolved: ResolvedModelRequirement[] }+>();++/** Resolves one entry's requirements, reusing the previous result when nothing it depends on changed. */+export const resolveEntryRequirements = (+ enrichment: ReadyEnrichment,+ deps: ModelRequirementDeps+): ResolvedModelRequirement[] => {+ const cached = resolutionCache.get(enrichment);++ if (cached && cached.deps === deps) {+ return cached.resolved;+ }++ const resolved = resolveWorkflowModelRequirements(enrichment.requirements.requirements, deps);++ resolutionCache.set(enrichment, { deps, resolved });++ return resolved;+};+/*** How many models each card would have to *download* to run — the count the* grid badges and, on the selected card, exactly what the panel's Install@@ -105,7 +139,7 @@ export const useWorkflowLibraryMissingCounts = (continue;}- const installable = resolveWorkflowModelRequirements(entry.enrichment.requirements.requirements, deps).filter(+ const installable = resolveEntryRequirements(entry.enrichment, deps).filter((resolved) => resolved.status === 'installable').length;