Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

refactor(app): make the composition root honest

joshistoast44ad757235e9
diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
index bbcd26719b..f91b669492 100644
--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
@@ -21,7 +21,10 @@ const GalleryImageContextMenu = lazy(() =>
import('./GalleryImageActionsBridge').then((module) => ({ default: module.GalleryImageContextMenu }))
);
-/** App-owned translation between Gallery UI intents and the Workbench aggregate. */
+/**
+ * Production binding of Gallery's UI port: translates Gallery UI intents into
+ * the Workbench aggregate. No second adapter is expected.
+ */
export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode }) => {
const projectId = useActiveProjectId();
const projectName = useActiveProjectName();
diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
index b58297d86f..2bba03f4a3 100644
--- a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
@@ -16,51 +16,74 @@ const GenerateCanvasCompositingSection = lazy(() =>
}))
);
+/**
+ * Production binding of Generation's UI port: builds each sub-port from
+ * Workbench, Models, and Gallery state. No second adapter is expected.
+ */
export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode }) => {
const project = useActiveProjectSelector((activeProject) => ({
activeProjectId: activeProject.id,
- canvasValues: getProjectWidgetValues(activeProject, 'canvas'),
generateValues: getProjectWidgetValues(activeProject, 'generate'),
invocationSourceId: activeProject.invocation.sourceId,
- promptHistory: activeProject.promptHistory,
- selectedGalleryImage: getSelectedGalleryImageFromValues(getProjectWidgetValues(activeProject, 'gallery')),
showPromptSyntaxHighlighting: activeProject.settings.showPromptSyntaxHighlighting,
}));
- const models = useModelsSelector((snapshot) => snapshot.models);
+ const promptHistoryItems = useActiveProjectSelector((activeProject) => activeProject.promptHistory);
+ const selectedGalleryImage = useActiveProjectSelector((activeProject) =>
+ getSelectedGalleryImageFromValues(getProjectWidgetValues(activeProject, 'gallery'))
+ );
+ const modelsCatalog = useModelsSelector((snapshot) => snapshot.models);
const modelsError = useModelsSelector((snapshot) => snapshot.error);
const modelsStatus = useModelsSelector((snapshot) => snapshot.status);
- const { gallery, generation, notifications, widgets } = useWorkbenchCommands();
+ const { gallery, generation, notifications } = useWorkbenchCommands();
const notify = useNotify();
- const adapter = useMemo<GenerationUiAdapter>(
+
+ const galleryGroup = useMemo<GenerationUiAdapter['gallery']>(
+ () => ({
+ selectedImage: selectedGalleryImage,
+ touchImages: () => gallery.touchImages(),
+ }),
+ [gallery, selectedGalleryImage]
+ );
+ const modelsGroup = useMemo<GenerationUiAdapter['models']>(
() => ({
- ...project,
- CanvasCompositingSection: GenerateCanvasCompositingSection,
ModelSelect,
- clearPromptHistory: () => generation.clearPromptHistory(),
- ensureModelsLoaded,
- getModelBaseColorPalette,
- getModelBaseLabel,
- models,
- modelsError,
- modelsStatus,
- notifications: { error: notify.error, info: notify.info, reportError: notifications.reportError },
- patchCanvasValues: (values) => widgets.patchValues('canvas', values),
- patchGenerateSettings: generation.patchSettings,
- removePromptFromHistory: generation.removePromptFromHistory,
- touchGalleryImages: () => gallery.touchImages(),
+ catalog: modelsCatalog,
+ ensureLoaded: ensureModelsLoaded,
+ error: modelsError,
+ getBaseColorPalette: getModelBaseColorPalette,
+ getBaseLabel: getModelBaseLabel,
+ status: modelsStatus,
+ }),
+ [modelsCatalog, modelsError, modelsStatus]
+ );
+ const notificationsGroup = useMemo<GenerationUiAdapter['notifications']>(
+ () => ({ error: notify.error, info: notify.info, reportError: notifications.reportError }),
+ [notifications.reportError, notify.error, notify.info]
+ );
+ const promptHistoryGroup = useMemo<GenerationUiAdapter['promptHistory']>(
+ () => ({
+ clear: () => generation.clearPromptHistory(),
+ items: promptHistoryItems,
+ remove: generation.removePromptFromHistory,
}),
- [
- gallery,
- generation,
- models,
- modelsError,
- modelsStatus,
- notifications.reportError,
- notify.error,
- notify.info,
+ [generation, promptHistoryItems]
+ );
+ const settingsGroup = useMemo<GenerationUiAdapter['settings']>(
+ () => ({ patchGenerateSettings: generation.patchSettings }),
+ [generation]
+ );
+
+ const adapter = useMemo<GenerationUiAdapter>(
+ () => ({
+ CanvasCompositingSection: GenerateCanvasCompositingSection,
+ gallery: galleryGroup,
+ models: modelsGroup,
+ notifications: notificationsGroup,
project,
- widgets,
- ]
+ promptHistory: promptHistoryGroup,
+ settings: settingsGroup,
+ }),
+ [galleryGroup, modelsGroup, notificationsGroup, project, promptHistoryGroup, settingsGroup]
);
return <GenerationUiProvider adapter={adapter}>{children}</GenerationUiProvider>;
diff --git a/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsx b/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsx
index ee1756b0f0..bed87aa109 100644
--- a/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsx
@@ -6,6 +6,10 @@ import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { useActiveProjectId } from '@workbench/WorkbenchContext';
import { useMemo } from 'react';
+/**
+ * Production binding of Models' UI port: supplies Workbench preferences and
+ * the active project. No second adapter is expected.
+ */
export const ModelsUiAdapterProvider = ({ children }: { children: ReactNode }) => {
const enableModelDescriptions = useWorkbenchPreferenceSelector((value) => value.enableModelDescriptions);
const managerProjectId = useActiveProjectId();
diff --git a/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx
index e5fc6eb0cf..8b4704c10a 100644
--- a/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx
@@ -10,7 +10,10 @@ const QueueItemActions = lazy(() =>
import('@workbench/queue-integration/QueueItemActions').then((module) => ({ default: module.QueueItemActions }))
);
-/** App-owned adapter for Queue UI concerns that belong to Workbench. */
+/**
+ * Production binding of Queue's UI port: adapts the Workbench-owned concerns
+ * Queue's UI depends on. No second adapter is expected.
+ */
export const QueueUiAdapterProvider = ({ children }: { children: ReactNode }) => {
const notify = useNotify();
const activeProjectId = useActiveProjectSelector((project) => project.id);
diff --git a/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx
index f802f358b4..7cfa236b3b 100644
--- a/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx
@@ -7,6 +7,10 @@ import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { useMemo } from 'react';
+/**
+ * Production binding of Upscale's UI port: maps the upscale widget instance
+ * and prompt drafts out of the Workbench aggregate. No second adapter is expected.
+ */
export const UpscaleUiAdapterProvider = ({ children }: { children: ReactNode }) => {
const project = useActiveProjectSelector(
(activeProject) => {
diff --git a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
index d3749890ca..04a08cda88 100644
--- a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
+++ b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
@@ -12,13 +12,8 @@ import { WorkbenchSessionController } from '@workbench/WorkbenchSessionControlle
import { WorkbenchWidgetRegistryProvider } from '@workbench/WorkbenchWidgetRegistryContext';
import { useMemo } from 'react';
-import { GalleryUiAdapterProvider } from './GalleryUiAdapter';
-import { GenerationUiAdapterProvider } from './GenerationUiAdapter';
-import { ModelsUiAdapterProvider } from './ModelsUiAdapter';
import { QueueRuntimeAdapter } from './QueueRuntimeAdapter';
-import { QueueUiAdapterProvider } from './QueueUiAdapter';
-import { UpscaleUiAdapterProvider } from './UpscaleUiAdapter';
-import { WorkflowUiAdapterProvider } from './WorkflowUiAdapter';
+import { WorkbenchUiPorts } from './workbenchPorts';
/**
* The authenticated editor: providers, editor-only runtimes, and the shell.
@@ -40,25 +35,15 @@ export const WorkbenchApp = () => {
return (
<WorkbenchProvider loadOptions={loadOptions}>
<WorkbenchWidgetRegistryProvider getWidgetById={getWidgetById} getWidgetsForRegion={getWidgetsForRegion}>
- <ModelsUiAdapterProvider>
- <QueueUiAdapterProvider>
- <GalleryUiAdapterProvider>
- <GenerationUiAdapterProvider>
- <UpscaleUiAdapterProvider>
- <WorkflowUiAdapterProvider>
- <SessionExpiryGuard />
- <WorkbenchHotkeyRuntime />
- <QueueRuntimeAdapter />
- <WorkbenchRuntime />
- <WorkbenchSessionController search={search} />
- <WidgetHosts />
- <WorkbenchShell />
- </WorkflowUiAdapterProvider>
- </UpscaleUiAdapterProvider>
- </GenerationUiAdapterProvider>
- </GalleryUiAdapterProvider>
- </QueueUiAdapterProvider>
- </ModelsUiAdapterProvider>
+ <WorkbenchUiPorts>
+ <SessionExpiryGuard />
+ <WorkbenchHotkeyRuntime />
+ <QueueRuntimeAdapter />
+ <WorkbenchRuntime />
+ <WorkbenchSessionController search={search} />
+ <WidgetHosts />
+ <WorkbenchShell />
+ </WorkbenchUiPorts>
</WorkbenchWidgetRegistryProvider>
</WorkbenchProvider>
);
diff --git a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx
index 977ff3b812..123fb0b114 100644
--- a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx
@@ -1,6 +1,4 @@
import type { WorkflowModelSelectProps, WorkflowUiAdapter } from '@features/workflow/react';
-import type { DiagnosticSource } from '@workbench/diagnostics/logger';
-import type { InvocationSourceId } from '@workbench/invocationContracts';
import type { ComponentType, ReactNode } from 'react';
import { flushGenerateDrafts } from '@features/generation/drafts';
@@ -31,9 +29,13 @@ import {
import { lazy, useMemo } from 'react';
const ModelSelect = lazy(() => import('@features/models/react').then((module) => ({ default: module.ModelSelect })));
-const WorkflowModelSelect = ModelSelect as ComponentType<WorkflowModelSelectProps>;
+const WorkflowModelSelect: ComponentType<WorkflowModelSelectProps> = ModelSelect;
const selectInvocationRouteInput = createInvocationRouteInputSelector();
+/**
+ * Production binding of Workflow's UI port: wires Workbench commands, routes,
+ * diagnostics, and Models/Nodes state. No second adapter is expected.
+ */
export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode }) => {
const project = useActiveProjectSelector((activeProject) => ({
activeProjectId: activeProject.id,
@@ -91,7 +93,7 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })
const route = resolveInvocationRouteInput(
routeInput,
'dialog',
- { ...routeInput.invocation, sourceId: sourceId as InvocationSourceId, sourceLocked: true },
+ { ...routeInput.invocation, sourceId, sourceLocked: true },
availabilityModels
);
@@ -109,24 +111,23 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })
models: availabilityModels,
prepareCanvasInvocation,
project: queries.getSnapshot().activeProject,
- sourceId: sourceId as InvocationSourceId | undefined,
+ sourceId,
});
},
},
notifications: { error: notify.error, info: notify.info, success: notify.success },
performance: {
- mark: (name, source) => markWorkbenchPerf(name, source as DiagnosticSource),
- measure: (name, start, source, end) => measureWorkbenchPerf(name, start, source as DiagnosticSource, end),
- time: (name, source, callback) => timeWorkbenchPerf(name, source as DiagnosticSource, callback),
+ mark: (name, source) => markWorkbenchPerf(name, source),
+ measure: (name, start, source, end) => measureWorkbenchPerf(name, start, source, end),
+ time: (name, source, callback) => timeWorkbenchPerf(name, source, callback),
},
preferences,
registerModalHotkeyLayer: registerHotkeyModalLayer,
nodeExecution: { get: nodeExecutionStore.get, subscribe: nodeExecutionStore.subscribe },
widgets: {
- open: (options) => commands.widgets.open(options as Parameters<typeof commands.widgets.open>[0]),
- patchValues: (widgetId, values) =>
- commands.widgets.patchValues(widgetId as Parameters<typeof commands.widgets.patchValues>[0], values),
- select: (options) => commands.widgets.select(options as Parameters<typeof commands.widgets.select>[0]),
+ open: (options) => commands.widgets.open(options),
+ patchValues: (widgetId, values) => commands.widgets.patchValues(widgetId, values),
+ select: (options) => commands.widgets.select(options),
},
}),
[
diff --git a/invokeai/frontend/webv2/src/app/configureDependencies.ts b/invokeai/frontend/webv2/src/app/configureDependencies.ts
deleted file mode 100644
index 6c7e781c5e..0000000000
--- a/invokeai/frontend/webv2/src/app/configureDependencies.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { identityTransportAuthAdapter } from '@features/identity';
-import { configureHttpAuth } from '@platform/transport/http';
-
-/** The App is the sole production adapter-selection and dependency-construction root. */
-export const configureDependencies = (): void => {
- configureHttpAuth(identityTransportAuthAdapter);
-};
diff --git a/invokeai/frontend/webv2/src/app/main.tsx b/invokeai/frontend/webv2/src/app/main.tsx
index 9236ee4611..731bcd2c6e 100644
--- a/invokeai/frontend/webv2/src/app/main.tsx
+++ b/invokeai/frontend/webv2/src/app/main.tsx
@@ -1,12 +1,15 @@
import '@fontsource/inter/index.css';
import '@platform/i18n/client';
+import { identityTransportAuthAdapter } from '@features/identity';
+import { configureHttpAuth } from '@platform/transport/http';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App';
-import { configureDependencies } from './configureDependencies';
-configureDependencies();
+// The only production binding that must exist before React mounts; all other
+// bindings are enumerated in `app/workbenchPorts.tsx`.
+configureHttpAuth(identityTransportAuthAdapter);
const rootElement = document.getElementById('root');
diff --git a/invokeai/frontend/webv2/src/app/workbenchPorts.tsx b/invokeai/frontend/webv2/src/app/workbenchPorts.tsx
new file mode 100644
index 0000000000..7cb7e91479
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/workbenchPorts.tsx
@@ -0,0 +1,36 @@
+import type { ProviderComponent } from '@platform/react/composeProviders';
+
+import { composeProviders } from '@platform/react/composeProviders';
+
+import { GalleryUiAdapterProvider } from './GalleryUiAdapter';
+import { GenerationUiAdapterProvider } from './GenerationUiAdapter';
+import { ModelsUiAdapterProvider } from './ModelsUiAdapter';
+import { QueueUiAdapterProvider } from './QueueUiAdapter';
+import { UpscaleUiAdapterProvider } from './UpscaleUiAdapter';
+import { WorkflowUiAdapterProvider } from './WorkflowUiAdapter';
+
+/**
+ * The enumerable index of production port bindings: this file answers "what
+ * does App bind in production?".
+ *
+ * Provider-shaped bindings are listed in `workbenchUiPortProviders` below.
+ * The remaining production bindings are not providers and mount elsewhere:
+ * - `QueueRuntimeAdapter` — mounted in `WorkbenchApp` (feeds Queue's runtime
+ * its Nodes execution store and Models load-activity sink).
+ * - `SocketHubRuntime` — mounted in `router.tsx`'s AuthenticatedLayout, above
+ * the editor route.
+ * - `GalleryImageActionsBridge` — lazy-loaded by `GalleryUiAdapter`.
+ * - `configureHttpAuth(identityTransportAuthAdapter)` — called in `main.tsx`
+ * before React mounts.
+ */
+export const workbenchUiPortProviders: ReadonlyArray<ProviderComponent> = [
+ ModelsUiAdapterProvider,
+ QueueUiAdapterProvider,
+ GalleryUiAdapterProvider,
+ GenerationUiAdapterProvider,
+ UpscaleUiAdapterProvider,
+ WorkflowUiAdapterProvider,
+];
+
+/** All six feature UI ports, composed once at module scope (identity must be render-stable). */
+export const WorkbenchUiPorts = composeProviders(workbenchUiPortProviders);
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
index 826b786bba..8f6fac412f 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
@@ -66,6 +66,10 @@ export interface GalleryWidgetProps {
runtime: GalleryWidgetRuntime;
}
+/**
+ * Gallery's UI port. The context is a dependency-direction port (the feature
+ * may not import workbench), not a test seam; no second adapter is expected.
+ */
export interface GalleryUiAdapter {
ImageActionsProvider: ComponentType<GalleryImageActionsOptions & { children: ReactNode }>;
ImageContextMenu: ComponentType<GalleryImageContextMenuProps>;
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateCanvasCompositingSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateCanvasCompositingSection.tsx
index 6d743773df..6c3e6c281f 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateCanvasCompositingSection.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateCanvasCompositingSection.tsx
@@ -1,6 +1,6 @@
import { useGenerationUi } from './GenerationUiContext';
export const GenerateCanvasCompositingSection = () => {
- const { CanvasCompositingSection, invocationSourceId } = useGenerationUi();
- return invocationSourceId === 'canvas' ? <CanvasCompositingSection /> : null;
+ const { CanvasCompositingSection, project } = useGenerationUi();
+ return project.invocationSourceId === 'canvas' ? <CanvasCompositingSection /> : null;
};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx
index 07829dffd7..bf76f2f8e1 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx
@@ -167,7 +167,7 @@ const LoraRow = ({
onWeightChange: (weight: number) => void;
}) => {
const { t } = useTranslation();
- const { getModelBaseColorPalette, getModelBaseLabel } = useGenerationUi();
+ const { getBaseColorPalette, getBaseLabel } = useGenerationUi().models;
const isActive = lora.isEnabled && isCompatible;
const defaultWeight = getDefaultLoraWeight(lora.model);
@@ -200,8 +200,8 @@ const LoraRow = ({
<Text color={isActive ? 'fg' : 'fg.muted'} fontSize="xs" fontWeight="medium" minW="0" truncate>
{lora.model.name}
</Text>
- <Badge colorPalette={getModelBaseColorPalette(lora.model.base)} flexShrink={0} size="xs" variant="surface">
- {getModelBaseLabel(lora.model.base)}
+ <Badge colorPalette={getBaseColorPalette(lora.model.base)} flexShrink={0} size="xs" variant="surface">
+ {getBaseLabel(lora.model.base)}
</Badge>
{!isCompatible ? (
<Badge colorPalette="orange" flexShrink={0} size="xs" variant="surface">
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
index 64aabbe495..970190507f 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
@@ -40,14 +40,14 @@ const getSettingsWithAutoComponentSource = (
export const GenerateWidgetView = () => {
const ui = useGenerationUi();
- const projectId = ui.activeProjectId;
- const storedValues = ui.generateValues;
- const error = ui.modelsError;
- const models = ui.models;
- const status = ui.modelsStatus;
+ const projectId = ui.project.activeProjectId;
+ const storedValues = ui.project.generateValues;
+ const error = ui.models.error;
+ const models = ui.models.catalog;
+ const status = ui.models.status;
useMountEffect(() => {
- ui.ensureModelsLoaded();
+ ui.models.ensureLoaded();
});
const supportedModels = useMemo<GenerateModelConfig[]>(() => models.filter(isSupportedGenerateModel), [models]);
@@ -86,7 +86,7 @@ export const GenerateWidgetView = () => {
return;
}
- ui.patchGenerateSettings(getGenerateFormCommitPatch({ ...nextSettings, model }), projectId);
+ ui.settings.patchGenerateSettings(getGenerateFormCommitPatch({ ...nextSettings, model }), projectId);
}, [models, projectId, selectedModel, settings, storedValues, supportedModels, ui]);
const commitSettings = useCallback(
@@ -97,7 +97,7 @@ export const GenerateWidgetView = () => {
return;
}
- ui.patchGenerateSettings(
+ ui.settings.patchGenerateSettings(
getGenerateFormCommitPatch({
...getSettingsWithAutoComponentSource(nextSettings, model, models),
model,
@@ -110,7 +110,7 @@ export const GenerateWidgetView = () => {
const patchSettings = useCallback(
(values: Partial<GenerateSettings>) => {
- ui.patchGenerateSettings(values, projectId);
+ ui.settings.patchGenerateSettings(values, projectId);
},
[projectId, ui]
);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
index a441e95a35..772c65b96d 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
@@ -26,32 +26,45 @@ export interface GenerationSelectedImage {
thumbnailUrl: string;
}
+/**
+ * Generation's UI port, grouped into sub-ports by backing concern. The context
+ * is a dependency-direction port (the feature may not import workbench), not a
+ * test seam; no second adapter is expected.
+ */
export interface GenerationUiAdapter {
CanvasCompositingSection: ComponentType;
- ModelSelect: ComponentType<GenerationModelSelectProps>;
- activeProjectId: string;
- canvasValues: Record<string, unknown>;
- ensureModelsLoaded(): void;
- generateValues: Record<string, unknown>;
- getModelBaseColorPalette(base: string): string;
- getModelBaseLabel(base: string): string;
- invocationSourceId: string;
- models: readonly GenerationModelCatalogItem[];
- modelsError: string | null;
- modelsStatus: 'error' | 'idle' | 'loaded' | 'loading';
+ gallery: {
+ selectedImage: GenerationSelectedImage | null;
+ touchImages(): void;
+ };
+ models: {
+ ModelSelect: ComponentType<GenerationModelSelectProps>;
+ catalog: readonly GenerationModelCatalogItem[];
+ ensureLoaded(): void;
+ error: string | null;
+ getBaseColorPalette(base: string): string;
+ getBaseLabel(base: string): string;
+ status: 'error' | 'idle' | 'loaded' | 'loading';
+ };
notifications: {
error(title: string, message?: string): void;
info(title: string, message?: string): void;
reportError(error: { area: string; message: string; namespace: 'generation'; projectId?: string }): void;
};
- patchCanvasValues(values: Record<string, unknown>): void;
- patchGenerateSettings(values: Partial<GenerateSettings>, projectId?: string): void;
- promptHistory: readonly PromptHistoryItem[];
- clearPromptHistory(): void;
- removePromptFromHistory(prompt: PromptHistoryItem): void;
- selectedGalleryImage: GenerationSelectedImage | null;
- showPromptSyntaxHighlighting: boolean;
- touchGalleryImages(): void;
+ project: {
+ activeProjectId: string;
+ generateValues: Record<string, unknown>;
+ invocationSourceId: string;
+ showPromptSyntaxHighlighting: boolean;
+ };
+ promptHistory: {
+ items: readonly PromptHistoryItem[];
+ clear(): void;
+ remove(prompt: PromptHistoryItem): void;
+ };
+ settings: {
+ patchGenerateSettings(values: Partial<GenerateSettings>, projectId?: string): void;
+ };
}
const GenerationUiContext = createContext<GenerationUiAdapter | null>(null);
@@ -71,6 +84,6 @@ export const useGenerationUi = (): GenerationUiAdapter => {
};
export const GenerationModelSelect = (props: GenerationModelSelectProps) => {
- const { ModelSelect } = useGenerationUi();
+ const { ModelSelect } = useGenerationUi().models;
return <ModelSelect {...props} />;
};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
index 3722e2ac4b..aa9f6b283f 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
@@ -40,7 +40,7 @@ export const GeneratePromptFields = ({
selectedModel,
settings,
}: GeneratePromptFieldsProps) => {
- const { generateValues, showPromptSyntaxHighlighting } = useGenerationUi();
+ const { generateValues, showPromptSyntaxHighlighting } = useGenerationUi().project;
const promptValues = getPromptValues(generateValues);
const promptPolicy = getPromptPolicy(selectedModel, settings);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
index 838560fffd..c5b4c2ff8f 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
@@ -187,7 +187,7 @@ export const PromptTriggerPopover = ({
onSelect: (trigger: string) => void;
}) => {
const { t } = useTranslation();
- const { ensureModelsLoaded, models } = useGenerationUi();
+ const { catalog: models, ensureLoaded: ensureModelsLoaded } = useGenerationUi().models;
const [searchTerm, setSearchTerm] = useState('');
const options = useMemo(
@@ -336,7 +336,11 @@ const ExpandPromptButton = ({
onPositivePromptChange: (prompt: string) => void;
}) => {
const { t } = useTranslation();
- const { activeProjectId, ensureModelsLoaded, models, notifications } = useGenerationUi();
+ const {
+ models: { catalog: models, ensureLoaded: ensureModelsLoaded },
+ notifications,
+ project: { activeProjectId },
+ } = useGenerationUi();
const activeProjectIdRef = useRef(activeProjectId);
const triggerId = useId();
const [isOpen, setIsOpen] = useState(false);
@@ -458,11 +462,10 @@ const ImageToPromptButton = ({
}) => {
const { t } = useTranslation();
const {
- activeProjectId,
- ensureModelsLoaded,
- models,
+ gallery: { selectedImage },
+ models: { catalog: models, ensureLoaded: ensureModelsLoaded },
notifications,
- selectedGalleryImage: selectedImage,
+ project: { activeProjectId },
} = useGenerationUi();
const activeProjectIdRef = useRef(activeProjectId);
const triggerId = useId();
@@ -592,7 +595,7 @@ const ImageToPromptButton = ({
const PositivePromptHistoryButton = ({ onUsePrompt }: Pick<PositivePromptActionsProps, 'onUsePrompt'>) => {
const { t } = useTranslation();
- const { clearPromptHistory, promptHistory } = useGenerationUi();
+ const { clear: clearPromptHistory, items: promptHistory } = useGenerationUi().promptHistory;
const historyTriggerId = useId();
const [isOpen, setIsOpen] = useState(false);
const [searchTerm, setSearchTerm] = useState('');
@@ -705,7 +708,7 @@ const PromptHistoryItemRow = ({
prompt: PromptHistoryItem;
}) => {
const { t } = useTranslation();
- const { removePromptFromHistory } = useGenerationUi();
+ const { remove: removePromptFromHistory } = useGenerationUi().promptHistory;
const handleUsePrompt = useCallback(() => onUsePrompt(prompt), [onUsePrompt, prompt]);
const handleDelete = useCallback(() => removePromptFromHistory(prompt), [prompt, removePromptFromHistory]);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx
index 6a4311bc38..9690d2e86a 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx
@@ -48,7 +48,7 @@ export const GenerateReferenceImagesSection = ({
settings,
}: GenerateReferenceImagesSectionProps) => {
const { t } = useTranslation();
- const { notifications, touchGalleryImages } = useGenerationUi();
+ const { gallery, notifications } = useGenerationUi();
const fileInputRef = useRef<HTMLInputElement | null>(null);
const referenceImages = settings.referenceImages;
const isSupported = isReferenceImageSupported(selectedModel);
@@ -144,7 +144,7 @@ export const GenerateReferenceImagesSection = ({
);
appendReferenceImages(uploaded.map(generatedImageToReferenceImage));
- touchGalleryImages();
+ gallery.touchImages();
} catch (error) {
notifications.reportError({
area: 'reference-images',
@@ -153,7 +153,7 @@ export const GenerateReferenceImagesSection = ({
});
}
},
- [appendReferenceImages, canAdd, maxReferenceImages, notifications, referenceImageCount, touchGalleryImages]
+ [appendReferenceImages, canAdd, gallery, maxReferenceImages, notifications, referenceImageCount]
);
const handleUploadZoneClick = useCallback(() => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx
index c052691c15..8d4ada1e1e 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx
@@ -159,7 +159,7 @@ export const ReferenceImageCropDialog = ({
onClose: () => void;
}) => {
const { t } = useTranslation();
- const { notifications, touchGalleryImages } = useGenerationUi();
+ const { gallery, notifications } = useGenerationUi();
const [cropBox, setCropBox] = useState<ReferenceImageCropBoxPct>(() => getReferenceImageCropBoxPct(image));
const [isApplying, setIsApplying] = useState(false);
const containerRef = useRef<HTMLDivElement | null>(null);
@@ -249,7 +249,7 @@ export const ReferenceImageCropDialog = ({
try {
setIsApplying(true);
const croppedImage = await applyReferenceImageCropSelection(image, cropBox);
- touchGalleryImages();
+ gallery.touchImages();
onApply(croppedImage);
onClose();
} catch (error) {
@@ -261,7 +261,7 @@ export const ReferenceImageCropDialog = ({
} finally {
setIsApplying(false);
}
- }, [close, cropBox, image, notifications, onApply, onClose, touchGalleryImages]);
+ }, [close, cropBox, gallery, image, notifications, onApply, onClose]);
return (
<Dialog.Root lazyMount open={isOpen} placement="center" size="lg" unmountOnExit onOpenChange={handleOpenChange}>
diff --git a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx
index 1fa202f6ad..94c3470185 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx
@@ -2,6 +2,10 @@ import type { ReactNode } from 'react';
import { createContext, use } from 'react';
+/**
+ * Models' UI port. The context is a dependency-direction port (the feature
+ * may not import workbench), not a test seam; no second adapter is expected.
+ */
export interface ModelsUiAdapter {
enableModelDescriptions: boolean;
managerProjectId: string | null;
diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx
index 570e9104a8..2f52bc387e 100644
--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx
@@ -8,6 +8,10 @@ export interface QueueUiNotificationPort {
success(title: string, description?: string): void;
}
+/**
+ * Queue's UI port. The context is a dependency-direction port (the feature
+ * may not import workbench), not a test seam; no second adapter is expected.
+ */
export interface QueueUiAdapter {
ItemActions: ComponentType<{ item: QueueItemReadModel }>;
activeProjectId: string | null;
diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx
index cdbabcedeb..c177e6328a 100644
--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx
@@ -4,6 +4,10 @@ import type { ReactNode } from 'react';
import { createContext, use } from 'react';
+/**
+ * Upscale's UI port. The context is a dependency-direction port (the feature
+ * may not import workbench), not a test seam; no second adapter is expected.
+ */
export interface UpscaleUiAdapter {
patchPromptDraft(values: ProjectPromptDraftPatch): void;
patchValues(values: Partial<UpscaleWidgetValues>): void;
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx
index eee0b6b48f..d0cfcc5fad 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx
@@ -6,6 +6,7 @@ import { createContext, use, useCallback, useSyncExternalStore } from 'react';
import type {
WorkflowCommands,
WorkflowGraphHistoryEntry,
+ WorkflowInvocationSourceId,
WorkflowModelSelectProps,
WorkflowNodeExecutionState,
WorkflowPerfSource,
@@ -21,6 +22,10 @@ export interface WorkflowPreferences {
workflowValidateConnections: boolean;
}
+/**
+ * Workflow's UI port. The context is a dependency-direction port (the feature
+ * may not import workbench), not a test seam; no second adapter is expected.
+ */
export interface WorkflowUiAdapter {
ModelSelect: ComponentType<WorkflowModelSelectProps>;
activeProjectId: string;
@@ -40,8 +45,10 @@ export interface WorkflowUiAdapter {
success(title: string, message?: string): void;
};
graphPreview: {
- getRoute(sourceId?: string): { canInvoke: boolean; label: string; validationMessage?: string } | null;
- invoke(sourceId?: string): Promise<boolean>;
+ getRoute(
+ sourceId?: WorkflowInvocationSourceId
+ ): { canInvoke: boolean; label: string; validationMessage?: string } | null;
+ invoke(sourceId?: WorkflowInvocationSourceId): Promise<boolean>;
};
performance: {
mark(name: string, source: WorkflowPerfSource): void;
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts
index 25d87bb40f..3a87fea18b 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts
@@ -3,6 +3,23 @@ import type { ProjectGraphState } from '@features/workflow/core/types';
export type WorkflowRegion = 'left' | 'right' | 'bottom' | 'center' | 'dialog' | 'popover';
+/**
+ * Panel regions workflow surfaces may open/select widgets in. Structural
+ * mirror of workbench's `WidgetRegion` (`workbench/layoutContracts.ts`) —
+ * the feature may not import workbench, so drift is caught as a tsc error at
+ * the check site: the `widgets` wiring in `app/WorkflowUiAdapter.tsx`.
+ */
+export type WorkflowWidgetPanelRegion = 'left' | 'right' | 'bottom' | 'center';
+
+/**
+ * Invocation sources the graph preview can route. Structural mirror of
+ * workbench's `InvocationSourceId` (`workbench/invocationContracts.ts`) —
+ * drift is caught as a tsc error at the check sites: the `graphPreview`
+ * wiring in `app/WorkflowUiAdapter.tsx` and the `GraphPreviewDialog` mount in
+ * `workbench/widget-frame/WidgetActionsMenu.tsx`.
+ */
+export type WorkflowInvocationSourceId = 'generate' | 'workflow' | 'upscale' | 'canvas';
+
export interface WorkflowRuntimeApi {
instanceId: string;
typeId: string;
@@ -44,9 +61,9 @@ export interface WorkflowCommands {
}
export interface WorkflowWidgetCommands {
- open(options: { region: WorkflowRegion; widgetId: string }): void;
+ open(options: { region: WorkflowWidgetPanelRegion; widgetId: string }): void;
patchValues(widgetId: string, values: Record<string, unknown>): void;
- select(options: { region: WorkflowRegion; widgetId: string }): void;
+ select(options: { region: WorkflowWidgetPanelRegion; widgetId: string }): void;
}
export interface WorkflowModel {
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx
index 9394368ed4..2512adb13a 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx
@@ -1,5 +1,5 @@
import type { XYPosition } from '@features/workflow/contracts';
-import type { WorkflowPreviewGraph } from '@features/workflow/ui/contracts';
+import type { WorkflowInvocationSourceId, WorkflowPreviewGraph } from '@features/workflow/ui/contracts';
import { Box, Dialog, Portal, SegmentGroup, Text } from '@chakra-ui/react';
import { useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';
@@ -15,7 +15,7 @@ interface GraphPreviewDialogProps {
isOpen: boolean;
/** Editor positions keyed by node id, when the graph mirrors an editable document. */
positionHints?: Record<string, XYPosition>;
- sourceId?: string;
+ sourceId?: WorkflowInvocationSourceId;
title: string;
onOpenChange: (isOpen: boolean) => void;
}
diff --git a/invokeai/frontend/webv2/src/platform/react/composeProviders.test.tsx b/invokeai/frontend/webv2/src/platform/react/composeProviders.test.tsx
new file mode 100644
index 0000000000..5c625199f5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/react/composeProviders.test.tsx
@@ -0,0 +1,66 @@
+import type { ReactNode } from 'react';
+
+import { createContext, use } from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { describe, expect, it } from 'vitest';
+
+import { composeProviders } from './composeProviders';
+
+// Three probe contexts. Each provider chains off the previous context's value,
+// so the probe output encodes the exact nesting order.
+const FirstContext = createContext('missing-first');
+const SecondContext = createContext('missing-second');
+const ThirdContext = createContext('missing-third');
+
+const FirstProvider = ({ children }: { children: ReactNode }) => (
+ <FirstContext.Provider value="first">{children}</FirstContext.Provider>
+);
+
+const SecondProvider = ({ children }: { children: ReactNode }) => (
+ <SecondContext.Provider value={`${use(FirstContext)}/second`}>{children}</SecondContext.Provider>
+);
+
+const ThirdProvider = ({ children }: { children: ReactNode }) => (
+ <ThirdContext.Provider value={`${use(SecondContext)}/third`}>{children}</ThirdContext.Provider>
+);
+
+const Probe = () => <output>{use(ThirdContext)}</output>;
+
+describe('composeProviders', () => {
+ it('nests providers in array order, outermost first', () => {
+ const Composed = composeProviders([FirstProvider, SecondProvider, ThirdProvider]);
+
+ const markup = renderToStaticMarkup(
+ <Composed>
+ <Probe />
+ </Composed>
+ );
+
+ expect(markup).toContain('first/second/third');
+ });
+
+ it('renders children unchanged for an empty provider list', () => {
+ const Composed = composeProviders([]);
+
+ const markup = renderToStaticMarkup(<Composed>plain children</Composed>);
+
+ expect(markup).toBe('plain children');
+ });
+
+ it('returns one stable component identity per call, so a module-scope composition is render-stable', () => {
+ const Composed = composeProviders([FirstProvider, SecondProvider, ThirdProvider]);
+
+ // The single composed reference renders identically every time it is used.
+ const renderOnce = () =>
+ renderToStaticMarkup(
+ <Composed>
+ <Probe />
+ </Composed>
+ );
+ expect(renderOnce()).toBe(renderOnce());
+
+ // A second call creates a distinct component: composing inside render would
+ // change element type each render and remount the subtree. Module scope only.
+ expect(composeProviders([FirstProvider, SecondProvider, ThirdProvider])).not.toBe(Composed);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/react/composeProviders.tsx b/invokeai/frontend/webv2/src/platform/react/composeProviders.tsx
new file mode 100644
index 0000000000..a350f40dc8
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/react/composeProviders.tsx
@@ -0,0 +1,18 @@
+import type { ComponentType, ReactNode } from 'react';
+
+export type ProviderComponent = ComponentType<{ children: ReactNode }>;
+
+/**
+ * Flattens a list of context providers into a single component. The array is
+ * nesting order, outermost first: `composeProviders([A, B])` renders
+ * `<A><B>{children}</B></A>`.
+ *
+ * MUST be called at module scope only. Each call creates a new component
+ * identity, so composing inside render would remount the entire subtree on
+ * every render.
+ */
+export const composeProviders = (providers: ReadonlyArray<ProviderComponent>): ProviderComponent => {
+ const Composed = ({ children }: { children: ReactNode }): ReactNode =>
+ providers.reduceRight<ReactNode>((wrapped, Provider) => <Provider>{wrapped}</Provider>, children);
+ return Composed;
+};