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): wire generate queue runtime to backend
joshistoaste25679412582
diff --git a/invokeai/frontend/webv2/src/App.tsx b/invokeai/frontend/webv2/src/App.tsxindex 2344acb33b..7d94366678 100644--- a/invokeai/frontend/webv2/src/App.tsx+++ b/invokeai/frontend/webv2/src/App.tsx@@ -1,12 +1,18 @@import { ChakraProvider } from '@chakra-ui/react';import { system } from './theme/system';+import { AppToaster } from './workbench/components/ui/toaster';+import { ThemeController } from './workbench/ThemeController';import { WorkbenchProvider } from './workbench/WorkbenchContext';+import { WorkbenchRuntime } from './workbench/WorkbenchRuntime';import { WorkbenchShell } from './workbench/WorkbenchShell';export const App = () => (<ChakraProvider value={system}>+ <AppToaster /><WorkbenchProvider>+ <ThemeController />+ <WorkbenchRuntime /><WorkbenchShell /></WorkbenchProvider></ChakraProvider>diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsxindex 600336bf00..75f0052035 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx@@ -19,6 +19,7 @@ const getPersistedStateKey = (state: WorkbenchState): string =>account: state.account,activeProjectId: state.activeProjectId,errorLog: state.errorLog,+ notifications: state.notifications,projects: state.projects,widgetFailures: state.widgetFailures,});diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsxnew file mode 100644index 0000000000..14ba4eb052--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx@@ -0,0 +1,145 @@+import { useEffect, useRef } from 'react';++import { cancelQueueItems, enqueueGenerateGraph, waitForQueueItemImages } from './generation/api';+import type { GenerateSettings } from './generation/types';+import { addImagesToGalleryBoard } from './gallery/api';+import type { QueueItem } from './types';+import { useWorkbench } from './WorkbenchContext';++const isGenerateSettings = (value: unknown): value is GenerateSettings => {+ if (!value || typeof value !== 'object') {+ return false;+ }++ const record = value as Record<string, unknown>;++ return (+ typeof record.modelKey === 'string' &&+ typeof record.positivePrompt === 'string' &&+ typeof record.negativePrompt === 'string' &&+ typeof record.seed === 'number' &&+ Number.isFinite(record.seed)+ );+};++const getPendingGenerateQueueItems = (items: QueueItem[]): QueueItem[] =>+ items.filter((item) => item.status === 'pending' && item.snapshot.sourceId === 'generate');++const getCancelledQueueItems = (items: QueueItem[]): QueueItem[] => items.filter((item) => item.status === 'cancelled');++const getCancelledBackendQueueItems = (items: QueueItem[]): QueueItem[] =>+ items.filter((item) => item.status === 'cancelled' && item.backendItemIds?.length);++const getSnapshotGalleryBoardId = (queueItem: QueueItem): string | null => {+ const selectedBoardId = queueItem.snapshot.widgetStates.gallery.values.selectedBoardId;++ return typeof selectedBoardId === 'string' ? selectedBoardId : null;+};++export const WorkbenchRuntime = () => {+ const { state, dispatch } = useWorkbench();+ const startedQueueItemIdsRef = useRef(new Set<string>());+ const cancelledQueueItemIdsRef = useRef(new Set<string>());+ const backendCancellationQueueItemIdsRef = useRef(new Set<string>());++ useEffect(() => {+ for (const project of state.projects) {+ for (const queueItem of getCancelledQueueItems(project.queue.items)) {+ cancelledQueueItemIdsRef.current.add(queueItem.id);+ }++ for (const queueItem of getPendingGenerateQueueItems(project.queue.items)) {+ if (startedQueueItemIdsRef.current.has(queueItem.id)) {+ continue;+ }++ startedQueueItemIdsRef.current.add(queueItem.id);++ const graph = queueItem.snapshot.graph.backendGraph;+ const generateValues = queueItem.snapshot.widgetStates.generate.values;++ if (!graph || !isGenerateSettings(generateValues)) {+ dispatch({+ error: 'Generate queue item is missing a compiled backend graph.',+ projectId: project.id,+ queueItemId: queueItem.id,+ status: 'failed',+ type: 'setQueueItemStatus',+ });+ continue;+ }++ const queuedAt = queueItem.snapshot.submittedAt;++ enqueueGenerateGraph({+ batchCount: generateValues.batchCount,+ destination: queueItem.snapshot.destination,+ graph,+ negativePrompt: generateValues.negativePrompt,+ negativePromptNodeId: 'negative_prompt',+ positivePrompt: generateValues.positivePrompt,+ positivePromptNodeId: 'positive_prompt',+ seed: generateValues.seed,+ seedNodeId: 'seed',+ sourceQueueItemId: queueItem.id,+ })+ .then(async ({ itemIds }) => {+ dispatch({+ backendItemIds: itemIds,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });++ if (cancelledQueueItemIdsRef.current.has(queueItem.id)) {+ return;+ }++ const images = (+ await Promise.all(itemIds.map((itemId) => waitForQueueItemImages(itemId, queueItem.id, queuedAt)))+ ).flat();++ if (cancelledQueueItemIdsRef.current.has(queueItem.id)) {+ return;+ }++ if (queueItem.snapshot.destination === 'gallery') {+ const selectedBoardId = getSnapshotGalleryBoardId(queueItem);++ if (selectedBoardId && selectedBoardId !== 'none') {+ await addImagesToGalleryBoard(+ selectedBoardId,+ images.map((image) => image.imageName)+ );+ }+ }++ dispatch({ images, projectId: project.id, queueItemId: queueItem.id, type: 'routeQueueItemResults' });+ })+ .catch((error: unknown) => {+ dispatch({+ error: error instanceof Error ? error.message : String(error),+ projectId: project.id,+ queueItemId: queueItem.id,+ status: 'failed',+ type: 'setQueueItemStatus',+ });+ });+ }++ for (const queueItem of getCancelledBackendQueueItems(project.queue.items)) {+ if (backendCancellationQueueItemIdsRef.current.has(queueItem.id) || !queueItem.backendItemIds?.length) {+ continue;+ }++ backendCancellationQueueItemIdsRef.current.add(queueItem.id);++ cancelQueueItems(queueItem.backendItemIds).catch((error: unknown) => {+ dispatch({ message: error instanceof Error ? error.message : String(error), type: 'recordError' });+ });+ }+ }+ }, [dispatch, state.projects]);++ return null;+};diff --git a/invokeai/frontend/webv2/src/workbench/gallery/api.ts b/invokeai/frontend/webv2/src/workbench/gallery/api.tsnew file mode 100644index 0000000000..a68a0d1e83--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/gallery/api.ts@@ -0,0 +1,201 @@+import type { GeneratedImageContract } from '../types';++const API_BASE_URL = import.meta.env.VITE_INVOKEAI_API_BASE_URL ?? '';++export type GalleryView = 'images' | 'assets';++export interface BackendBoardDTO {+ board_id: string;+ board_name: string;+ image_count: number;+ asset_count: number;+ archived: boolean;+ cover_image_name?: string | null;+}++export interface GalleryBoard {+ id: string;+ name: string;+ imageCount: number;+ assetCount: number;+ coverImageName?: string | null;+ coverThumbnailUrl?: string;+ isVirtual?: boolean;+}++export interface BackendImageDTO {+ image_name: string;+ image_url: string;+ thumbnail_url: string;+ width: number;+ height: number;+ created_at: string;+ image_category: 'general' | 'control' | 'mask' | 'user' | 'other';+ is_intermediate: boolean;+ board_id?: string | null;+}++export interface GalleryImage extends GeneratedImageContract {+ boardId: string;+ imageCategory: BackendImageDTO['image_category'];+}++interface ListImagesResponse {+ items: BackendImageDTO[];+ limit: number;+ offset: number;+ total: number;+}++const imageCategories = ['general'];+const assetCategories = ['control', 'mask', 'user', 'other'];++const buildUrl = (path: string): string => `${API_BASE_URL}${path}`;++const absolutizeImageUrl = (url: string): string => {+ if (!API_BASE_URL || url.startsWith('http://') || url.startsWith('https://')) {+ return url;+ }++ return new URL(url, API_BASE_URL).toString();+};++const getImageThumbnailUrl = (imageName: string): string =>+ absolutizeImageUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}/thumbnail`);++const assertOk = async (response: Response): Promise<Response> => {+ if (response.ok) {+ return response;+ }++ const text = await response.text();+ throw new Error(text || `${response.status} ${response.statusText}`);+};++const toSearchParams = (entries: Record<string, boolean | number | string | string[] | undefined>): string => {+ const params = new URLSearchParams();++ for (const [key, value] of Object.entries(entries)) {+ if (value === undefined || value === '') {+ continue;+ }++ if (Array.isArray(value)) {+ for (const item of value) {+ params.append(key, item);+ }+ continue;+ }++ params.set(key, String(value));+ }++ return params.toString();+};++const mapBoard = (board: BackendBoardDTO): GalleryBoard => ({+ assetCount: board.asset_count,+ coverImageName: board.cover_image_name,+ coverThumbnailUrl: board.cover_image_name ? getImageThumbnailUrl(board.cover_image_name) : undefined,+ id: board.board_id,+ imageCount: board.image_count,+ name: board.board_name,+});++const getGalleryTotal = async ({ boardId, categories }: { boardId: string; categories: string[] }): Promise<number> => {+ const query = toSearchParams({+ board_id: boardId,+ categories,+ is_intermediate: false,+ limit: 0,+ offset: 0,+ });+ const response = await assertOk(await fetch(buildUrl(`/api/v1/images/?${query}`)));+ const body = (await response.json()) as Pick<ListImagesResponse, 'total'>;++ return body.total;+};++const mapImage = (image: BackendImageDTO): GalleryImage => ({+ boardId: image.board_id ?? 'none',+ height: image.height,+ imageCategory: image.image_category,+ imageName: image.image_name,+ imageUrl: absolutizeImageUrl(image.image_url),+ queuedAt: image.created_at,+ sourceQueueItemId: 'backend-gallery',+ thumbnailUrl: absolutizeImageUrl(image.thumbnail_url),+ width: image.width,+});++export const listGalleryBoards = async (): Promise<GalleryBoard[]> => {+ const boardsResponsePromise = fetch(buildUrl('/api/v1/boards/?all=true&include_archived=false')).then(assertOk);++ const [response, uncategorizedImageCount, uncategorizedAssetCount] = await Promise.all([+ boardsResponsePromise,+ getGalleryTotal({ boardId: 'none', categories: imageCategories }),+ getGalleryTotal({ boardId: 'none', categories: assetCategories }),+ ]);+ const body = (await response.json()) as BackendBoardDTO[] | { items?: BackendBoardDTO[] };+ const boards = Array.isArray(body) ? body : (body.items ?? []);++ return [+ {+ assetCount: uncategorizedAssetCount,+ id: 'none',+ imageCount: uncategorizedImageCount,+ isVirtual: true,+ name: 'Uncategorized',+ },+ ...boards.filter((board) => !board.archived).map(mapBoard),+ ];+};++export const listGalleryImages = async ({+ boardId,+ galleryView,+ searchTerm,+}: {+ boardId: string;+ galleryView: GalleryView;+ searchTerm: string;+}): Promise<GalleryImage[]> => {+ const query = toSearchParams({+ board_id: boardId,+ categories: galleryView === 'assets' ? assetCategories : imageCategories,+ is_intermediate: false,+ limit: 100,+ offset: 0,+ order_dir: 'DESC',+ search_term: searchTerm.trim() || undefined,+ });+ const response = await assertOk(await fetch(buildUrl(`/api/v1/images/?${query}`)));+ const body = (await response.json()) as ListImagesResponse;++ return body.items.map(mapImage);+};++export const createGalleryBoard = async (boardName: string): Promise<GalleryBoard> => {+ const query = toSearchParams({ board_name: boardName });+ const response = await assertOk(+ await fetch(buildUrl(`/api/v1/boards/?${query}`), {+ method: 'POST',+ })+ );++ return mapBoard((await response.json()) as BackendBoardDTO);+};++export const addImagesToGalleryBoard = async (boardId: string, imageNames: string[]): Promise<void> => {+ if (boardId === 'none' || boardId === 'generated' || boardId === 'assets' || imageNames.length === 0) {+ return;+ }++ await assertOk(+ await fetch(buildUrl('/api/v1/board_images/batch'), {+ body: JSON.stringify({ board_id: boardId, image_names: imageNames }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ })+ );+};diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex 42762231ea..5e023b8ff9 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -28,5 +28,21 @@ export default defineConfig({server: {host: '0.0.0.0',port: 5174,+ proxy: {+ '/api/': {+ changeOrigin: true,+ rewrite: (path) => path.replace(/^\/api/, ''),+ target: 'http://127.0.0.1:9090/api/',+ },+ '/openapi.json': {+ changeOrigin: true,+ rewrite: (path) => path.replace(/^\/openapi.json/, ''),+ target: 'http://127.0.0.1:9090/openapi.json',+ },+ '/ws/socket.io': {+ target: 'ws://127.0.0.1:9090',+ ws: true,+ },+ },},});