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(generate): add preset and queue-insight ports
Josh Corbett543604f2e1aa
diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsxindex 44cc374321..ff32473011 100644--- a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx@@ -1,14 +1,22 @@import type { GenerationUiAdapter } from '@features/generation/react';+import type { QueueItemReadModel, QueueReadModel } from '@features/queue/contracts';import type { ReactNode } from 'react';import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';import { invalidateGallery } from '@features/gallery/queries';+import { galleryImageUrls } from '@features/gallery/utility';import { GenerationUiProvider } from '@features/generation/react';import { normalizeRebalancePresets } from '@features/generation/settings';import { useAuthSession, useCapabilities } from '@features/identity';import { ensureModelsLoaded, getModelBaseColorPalette, getModelBaseLabel, useModelsSelector } from '@features/models';+import {+ buildProjectQueueItemOriginPrefix,+ extractGenerationMeta,+ getResultImageName,+} from '@features/queue/contracts';+import { getQueueReadModelOptions } from '@features/queue/queries';import { useMountEffect } from '@platform/react/useMountEffect';-import { useQueryClient } from '@tanstack/react-query';+import { useQuery, useQueryClient } from '@tanstack/react-query';import {getWorkbenchPreferences,patchWorkbenchPreferences,@@ -28,6 +36,74 @@ const GenerateCanvasCompositingSection = lazy(() =>})));+const RECENT_RUN_WINDOW = 10;+const SEED_HISTORY_LIMIT = 6;++const selectQueueItems = (model: QueueReadModel): QueueItemReadModel[] => model.items;++/**+ * Seeds and durations of recent completed Generate runs, derived from the+ * project-scoped backend queue read model. Backend items map to a local queue+ * item to prove they came from the Generate source (canvas, workflow, and+ * upscale runs share the same backend queue); the executed seed comes from the+ * backend item's session meta, which is authoritative for randomized runs.+ */+const useGenerationQueueInsights = (projectId: string): GenerationUiAdapter['queueInsights'] => {+ const localQueueItems = useActiveProjectSelector((activeProject) => activeProject.queue.items);+ const scope = useMemo(() => ({ originPrefix: buildProjectQueueItemOriginPrefix(projectId) }), [projectId]);+ const backendItems = useQuery({ ...getQueueReadModelOptions(scope), select: selectQueueItems }).data;++ return useMemo(() => {+ if (!backendItems) {+ return { secondsPerRun: null, seedHistory: [] };+ }++ const generateBackendIds = new Set<number>();++ for (const item of localQueueItems) {+ if (item.snapshot.sourceId === 'generate') {+ for (const backendId of item.backendItemIds ?? []) {+ generateBackendIds.add(backendId);+ }+ }+ }++ const completed = backendItems+ .filter((item) => item.status === 'completed' && generateBackendIds.has(item.id))+ .sort((a, b) => (b.completedAt ?? b.updatedAt).localeCompare(a.completedAt ?? a.updatedAt));++ const seenSeeds = new Set<number>();+ const seedHistory: GenerationUiAdapter['queueInsights']['seedHistory'][number][] = [];++ for (const item of completed) {+ const seed = extractGenerationMeta(item).seed;++ if (seed === undefined || seenSeeds.has(seed)) {+ continue;+ }++ seenSeeds.add(seed);+ const imageName = getResultImageName(item);+ seedHistory.push({ seed, thumbnailUrl: imageName ? galleryImageUrls.thumbnail(imageName) : null });++ if (seedHistory.length >= SEED_HISTORY_LIMIT) {+ break;+ }+ }++ const durations = completed+ .slice(0, RECENT_RUN_WINDOW)+ .map((item) =>+ item.startedAt && item.completedAt ? (Date.parse(item.completedAt) - Date.parse(item.startedAt)) / 1000 : null+ )+ .filter((seconds): seconds is number => seconds !== null && Number.isFinite(seconds) && seconds > 0);+ const secondsPerRun =+ durations.length === 0 ? null : durations.reduce((total, seconds) => total + seconds, 0) / durations.length;++ return { secondsPerRun, seedHistory };+ }, [backendItems, localQueueItems]);+};+/*** Production binding of Generation's UI port: builds each sub-port from* Workbench, Models, and Gallery state. No second adapter is expected.@@ -152,6 +228,37 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode}),[krea2RebalancePresets]);+ const generatePresets = useWorkbenchPreferenceSelector((preferences) => preferences.generatePresets);+ const presetsGroup = useMemo<GenerationUiAdapter['presets']>(+ () => ({+ // Settings persists these shape-checked only; the feature re-normalizes the+ // snapshot against the current model catalog when a preset is applied.+ presets: generatePresets,+ remove: (presetId) => {+ void patchWorkbenchPreferences({+ generatePresets: getWorkbenchPreferences().generatePresets.filter((preset) => preset.id !== presetId),+ });+ },+ rename: (presetId, label) => {+ void patchWorkbenchPreferences({+ generatePresets: getWorkbenchPreferences().generatePresets.map((preset) =>+ preset.id === presetId ? { ...preset, label } : preset+ ),+ });+ },+ save: (label, values) => {+ const preset = { id: crypto.randomUUID(), label, values };++ void patchWorkbenchPreferences({+ generatePresets: [...getWorkbenchPreferences().generatePresets, preset],+ });++ return preset;+ },+ }),+ [generatePresets]+ );+ const queueInsightsGroup = useGenerationQueueInsights(project.activeProjectId);const generateSectionsOpen = useWorkbenchPreferenceSelector((preferences) => preferences.generateSectionsOpen);const sectionPreferencesGroup = useMemo<GenerationUiAdapter['sectionPreferences']>(() => ({@@ -173,8 +280,10 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNodegallery: galleryGroup,models: modelsGroup,notifications: notificationsGroup,+ presets: presetsGroup,project,promptHistory: promptHistoryGroup,+ queueInsights: queueInsightsGroup,rebalancePresets: rebalancePresetsGroup,sectionPreferences: sectionPreferencesGroup,settings: settingsGroup,@@ -185,8 +294,10 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNodegalleryGroup,modelsGroup,notificationsGroup,+ presetsGroup,project,promptHistoryGroup,+ queueInsightsGroup,rebalancePresetsGroup,sectionPreferencesGroup,settingsGroup,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsxindex 0db776c4f4..c2018da701 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx@@ -27,6 +27,19 @@ export interface GenerationSelectedImage {thumbnailUrl: string;}+/** One executed seed from a recent completed Generate run. */+export interface GenerationSeedHistoryItem {+ seed: number;+ thumbnailUrl: string | null;+}++/** A named Generate settings snapshot; `values` is normalized by the feature on apply. */+export interface GeneratePresetRecord {+ id: string;+ label: string;+ values: Record<string, unknown>;+}+/*** 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@@ -73,6 +86,20 @@ export interface GenerationUiAdapter {clear(): void;remove(prompt: PromptHistoryItem): void;};+ presets: {+ /** User-saved Generate settings snapshots ("recipes"), in save order. */+ presets: readonly GeneratePresetRecord[];+ /** Adds a snapshot under a new id and returns it. */+ save(label: string, values: Record<string, unknown>): GeneratePresetRecord;+ rename(presetId: string, label: string): void;+ remove(presetId: string): void;+ };+ queueInsights: {+ /** Executed seeds of recent completed Generate runs for this project, newest first. */+ seedHistory: readonly GenerationSeedHistoryItem[];+ /** Mean seconds per completed recent Generate run; null with no history to ground it. */+ secondsPerRun: number | null;+ };rebalancePresets: {/** User-saved conditioning rebalance curves; built-ins are not included. */presets: readonly RebalancePreset[];diff --git a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts b/invokeai/frontend/webv2/src/workbench/settings/contracts.tsindex da84d2a5b2..90cb49b7fe 100644--- a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts@@ -41,6 +41,17 @@ export interface StoredRebalancePreset {multiplier: number;}+/**+ * A named Generate settings snapshot ("recipe") as it is persisted. `values` is+ * opaque to Settings for the same bundle reason as {@link StoredRebalancePreset}:+ * the generation feature owns the shape and re-normalizes it on apply.+ */+export interface StoredGeneratePreset {+ id: string;+ label: string;+ values: Record<string, unknown>;+}+/** User-tunable appearance + behavior preferences surfaced in the Settings modal. */export interface WorkbenchPreferences {themeId: WorkbenchThemeId;@@ -83,4 +94,6 @@ export interface WorkbenchPreferences {launchpadPinnedProjectIds: string[];/** User-saved Krea-2 conditioning rebalance curves, in the order they were saved. */krea2RebalancePresets: StoredRebalancePreset[];+ /** User-saved Generate settings snapshots ("recipes"), in the order they were saved. */+ generatePresets: StoredGeneratePreset[];}diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex 6b5725b40e..9a6de04c00 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -3,6 +3,7 @@ import type {ProjectSettings,ProjectSortId,ProjectsViewId,+ StoredGeneratePreset,StoredRebalancePreset,WorkbenchPreferences,} from '@workbench/settings/contracts';@@ -62,6 +63,7 @@ export const DEFAULT_PREFERENCES: WorkbenchPreferences = {developerPerformanceTimingsEnabled: false,enableInformationalPopovers: true,enableModelDescriptions: true,+ generatePresets: [],generateSectionsOpen: {},krea2RebalancePresets: [],language: 'en',@@ -227,6 +229,42 @@ const normalizeRebalancePresets = (values: unknown): StoredRebalancePreset[] =>return presets;};+/** Shape-only, like {@link normalizeRebalancePresets}: the generation feature re-normalizes `values` on apply. */+const normalizeGeneratePresets = (values: unknown): StoredGeneratePreset[] => {+ if (!Array.isArray(values)) {+ return [];+ }++ const seen = new Set<string>();+ const presets: StoredGeneratePreset[] = [];++ for (const entry of values) {+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {+ continue;+ }++ const { id, label, values: snapshot } = entry as Partial<StoredGeneratePreset>;++ if (+ typeof id !== 'string' ||+ id.trim() === '' ||+ seen.has(id) ||+ typeof label !== 'string' ||+ label.trim() === '' ||+ !snapshot ||+ typeof snapshot !== 'object' ||+ Array.isArray(snapshot)+ ) {+ continue;+ }++ seen.add(id);+ presets.push({ id, label: label.trim(), values: snapshot });+ }++ return presets;+};+export const normalizeProjectSettings = (settings?: Partial<ProjectSettings>): ProjectSettings => ({antialiasProgressImages:typeof settings?.antialiasProgressImages === 'boolean'@@ -283,6 +321,7 @@ export const normalizeWorkbenchPreferences = (preferences?: WorkbenchPreferencestypeof preferences?.enableModelDescriptions === 'boolean'? preferences.enableModelDescriptions: DEFAULT_PREFERENCES.enableModelDescriptions,+ generatePresets: normalizeGeneratePresets(preferences?.generatePresets),generateSectionsOpen: normalizeGenerateSectionsOpen(preferences?.generateSectionsOpen),krea2RebalancePresets: normalizeRebalancePresets(preferences?.krea2RebalancePresets),language: normalizeWorkbenchLanguage(preferences?.language) ?? DEFAULT_PREFERENCES.language,