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
Feature: Add optional setting to prune queue on startup (#8861)
Valeri Che9d62bfdf8e45
diff --git a/invokeai/app/api/routers/app_info.py b/invokeai/app/api/routers/app_info.pyindex d8f3bb2f80..da777ebc73 100644--- a/invokeai/app/api/routers/app_info.py+++ b/invokeai/app/api/routers/app_info.py@@ -6,8 +6,14 @@ from fastapi import Bodyfrom fastapi.routing import APIRouterfrom pydantic import BaseModel, Field+from invokeai.app.api.auth_dependencies import AdminUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependencies-from invokeai.app.services.config.config_default import InvokeAIAppConfig, get_config+from invokeai.app.services.config.config_default import (+ DefaultInvokeAIAppConfig,+ InvokeAIAppConfig,+ get_config,+ load_and_migrate_config,+)from invokeai.app.services.invocation_cache.invocation_cache_common import InvocationCacheStatusfrom invokeai.backend.image_util.infill_methods.patchmatch import PatchMatchfrom invokeai.backend.util.logging import logging@@ -64,6 +70,16 @@ class InvokeAIAppConfigWithSetFields(BaseModel):config: InvokeAIAppConfig = Field(description="The InvokeAI App Config")+class UpdateAppGenerationSettingsRequest(BaseModel):+ """Writable generation-related app settings."""++ max_queue_history: int | None = Field(+ default=None,+ ge=0,+ description="Keep the last N completed, failed, and canceled queue items on startup. Set to 0 to prune all terminal items.",+ )++@app_router.get("/runtime_config", operation_id="get_runtime_config", status_code=200, response_model=InvokeAIAppConfigWithSetFields)@@ -72,6 +88,30 @@ async def get_runtime_config() -> InvokeAIAppConfigWithSetFields:return InvokeAIAppConfigWithSetFields(set_fields=config.model_fields_set, config=config)+@app_router.patch(+ "/runtime_config",+ operation_id="update_runtime_config",+ status_code=200,+ response_model=InvokeAIAppConfigWithSetFields,+)+async def update_runtime_config(+ _: AdminUserOrDefault,+ changes: UpdateAppGenerationSettingsRequest = Body(description="Writable runtime configuration changes"),+) -> InvokeAIAppConfigWithSetFields:+ config = get_config()+ update_dict = changes.model_dump(exclude_unset=True)+ config.update_config(update_dict)++ if config.config_file_path.exists():+ persisted_config = load_and_migrate_config(config.config_file_path)+ else:+ persisted_config = DefaultInvokeAIAppConfig()++ persisted_config.update_config(update_dict)+ persisted_config.write_file(config.config_file_path)+ return InvokeAIAppConfigWithSetFields(set_fields=config.model_fields_set, config=config)++@app_router.get("/logging",operation_id="get_log_level",diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.pyindex 5d1b1d0d8d..7e56db9f61 100644--- a/invokeai/app/services/config/config_default.py+++ b/invokeai/app/services/config/config_default.py@@ -101,7 +101,8 @@ class InvokeAIAppConfig(BaseSettings):force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.max_queue_size: Maximum number of items in the session queue.- clear_queue_on_startup: Empties session queue on startup.+ clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.+ max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.allow_nodes: List of nodes to allow. Omit to allow all.deny_nodes: List of nodes to deny. Omit to deny none.node_cache_size: How many cached nodes to keep in memory.@@ -191,7 +192,8 @@ class InvokeAIAppConfig(BaseSettings):force_tiled_decode: bool = Field(default=False, description="Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).")pil_compress_level: int = Field(default=1, description="The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.")max_queue_size: int = Field(default=10000, gt=0, description="Maximum number of items in the session queue.")- clear_queue_on_startup: bool = Field(default=False, description="Empties session queue on startup.")+ clear_queue_on_startup: bool = Field(default=False, description="Empties session queue on startup. If true, disables `max_queue_history`.")+ max_queue_history: Optional[int] = Field(default=None, ge=0, description="Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.")# NODESallow_nodes: Optional[list[str]] = Field(default=None, description="List of nodes to allow. Omit to allow all.")diff --git a/invokeai/app/services/session_queue/session_queue_sqlite.py b/invokeai/app/services/session_queue/session_queue_sqlite.pyindex 070a7cef29..172dc08d55 100644--- a/invokeai/app/services/session_queue/session_queue_sqlite.py+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py@@ -45,10 +45,19 @@ class SqliteSessionQueue(SessionQueueBase):def start(self, invoker: Invoker) -> None:self.__invoker = invokerself._set_in_progress_to_canceled()- if self.__invoker.services.configuration.clear_queue_on_startup:+ config = self.__invoker.services.configuration+ if config.clear_queue_on_startup:clear_result = self.clear(DEFAULT_QUEUE_ID)if clear_result.deleted > 0:self.__invoker.services.logger.info(f"Cleared all {clear_result.deleted} queue items")+ return++ if config.max_queue_history is not None:+ deleted = self._prune_terminal_to_limit(DEFAULT_QUEUE_ID, config.max_queue_history)+ if deleted > 0:+ self.__invoker.services.logger.info(+ f"Pruned {deleted} completed/failed/canceled queue items (kept up to {config.max_queue_history})"+ )def __init__(self, db: SqliteDatabase) -> None:super().__init__()@@ -68,6 +77,51 @@ class SqliteSessionQueue(SessionQueueBase):""")+ def _prune_terminal_to_limit(self, queue_id: str, keep: int) -> int:+ """Prune terminal items (completed/failed/canceled) to keep at most N most-recent items."""+ with self._db.transaction() as cursor:+ where = """--sql+ WHERE+ queue_id = ?+ AND (+ status = 'completed'+ OR status = 'failed'+ OR status = 'canceled'+ )+ """+ cursor.execute(+ f"""--sql+ SELECT COUNT(*)+ FROM session_queue+ {where}+ AND item_id NOT IN (+ SELECT item_id+ FROM session_queue+ {where}+ ORDER BY COALESCE(completed_at, updated_at, created_at) DESC, item_id DESC+ LIMIT ?+ );+ """,+ (queue_id, queue_id, keep),+ )+ count = cursor.fetchone()[0]+ cursor.execute(+ f"""--sql+ DELETE+ FROM session_queue+ {where}+ AND item_id NOT IN (+ SELECT item_id+ FROM session_queue+ {where}+ ORDER BY COALESCE(completed_at, updated_at, created_at) DESC, item_id DESC+ LIMIT ?+ );+ """,+ (queue_id, queue_id, keep),+ )+ return count+def _get_current_queue_size(self, queue_id: str) -> int:"""Gets the current number of pending queue items"""with self._db.transaction() as cursor:diff --git a/invokeai/frontend/web/public/locales/en.json b/invokeai/frontend/web/public/locales/en.jsonindex 7fad98531e..cd7287d46e 100644--- a/invokeai/frontend/web/public/locales/en.json+++ b/invokeai/frontend/web/public/locales/en.json@@ -1707,6 +1707,8 @@"enableNSFWChecker": "Enable NSFW Checker","general": "General","generation": "Generation",+ "maxQueueHistory": "Max Queue History",+ "maxQueueHistorySaveFailed": "Failed to save Max Queue History","models": "Models","preferAttentionStyleNumeric": "Prefer Numeric Attention Style","prompt": "Prompt",diff --git a/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsModal.tsx b/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsModal.tsxindex b95d2adb47..7bcc103402 100644--- a/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsModal.tsx+++ b/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsModal.tsx@@ -11,6 +11,8 @@ import {ModalFooter,ModalHeader,ModalOverlay,+ NumberInput,+ NumberInputField,Switch,Text,} from '@invoke-ai/ui-library';@@ -19,6 +21,7 @@ import { useAppDispatch, useAppSelector } from 'app/store/storeHooks';import { InformationalPopover } from 'common/components/InformationalPopover/InformationalPopover';import ScrollableContent from 'common/components/OverlayScrollbars/ScrollableContent';import { buildUseBoolean } from 'common/hooks/useBoolean';+import { selectCurrentUser } from 'features/auth/store/authSlice';import { selectShouldUseCPUNoise, shouldUseCpuNoiseChanged } from 'features/controlLayers/store/paramsSlice';import { useRefreshAfterResetModal } from 'features/system/components/SettingsModal/RefreshAfterResetModal';import { SettingsDeveloperLogIsEnabled } from 'features/system/components/SettingsModal/SettingsDeveloperLogIsEnabled';@@ -48,16 +51,25 @@ import {shouldUseNSFWCheckerChanged,shouldUseWatermarkerChanged,} from 'features/system/store/systemSlice';+import { toast } from 'features/toast/toast';import { selectShouldShowProgressInViewer } from 'features/ui/store/uiSelectors';import { setShouldShowProgressInViewer } from 'features/ui/store/uiSlice';-import type { ChangeEvent, ReactElement } from 'react';-import { cloneElement, memo, useCallback, useEffect } from 'react';+import type { ChangeEvent, KeyboardEvent, ReactElement } from 'react';+import { cloneElement, memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useGetRuntimeConfigQuery, useUpdateRuntimeConfigMutation } from 'services/api/endpoints/appInfo';import { SettingsLanguageSelect } from './SettingsLanguageSelect';const [useSettingsModal] = buildUseBoolean(false);+const formatOptionalInteger = (value: number | null | undefined) => {+ if (value === null || value === undefined) {+ return '';+ }+ return String(value);+};+const SettingsModal = (props: { children: ReactElement }) => {const dispatch = useAppDispatch();const { t } = useTranslation();@@ -72,6 +84,10 @@ const SettingsModal = (props: { children: ReactElement }) => {const settingsModal = useSettingsModal();const refreshModal = useRefreshAfterResetModal();+ const currentUser = useAppSelector(selectCurrentUser);+ const { data: runtimeConfig } = useGetRuntimeConfigQuery();+ const [updateRuntimeConfig, { isLoading: isUpdatingRuntimeConfig }] = useUpdateRuntimeConfigMutation();+ const pendingMaxQueueHistoryRef = useRef<number | null | undefined>(undefined);const prefersNumericAttentionWeights = useAppSelector(selectSystemPrefersNumericAttentionWeights);const shouldUseCpuNoise = useAppSelector(selectShouldUseCPUNoise);@@ -85,6 +101,10 @@ const SettingsModal = (props: { children: ReactElement }) => {const shouldHighlightFocusedRegions = useAppSelector(selectSystemShouldEnableHighlightFocusedRegions);const shouldConfirmOnNewSession = useAppSelector(selectSystemShouldConfirmOnNewSession);const shouldShowInvocationProgressDetail = useAppSelector(selectSystemShouldShowInvocationProgressDetail);+ const maxQueueHistory = runtimeConfig?.config.max_queue_history ?? null;+ const canEditRuntimeConfig = runtimeConfig ? !runtimeConfig.config.multiuser || currentUser?.is_admin : false;+ const [maxQueueHistoryInput, setMaxQueueHistoryInput] = useState(formatOptionalInteger(maxQueueHistory));+const onToggleConfirmOnNewSession = useCallback(() => {dispatch(shouldConfirmOnNewSessionToggled());}, [dispatch]);@@ -96,11 +116,60 @@ const SettingsModal = (props: { children: ReactElement }) => {}}, [refetchIntermediatesCount, settingsModal.isTrue]);+ useEffect(() => {+ setMaxQueueHistoryInput(formatOptionalInteger(maxQueueHistory));+ }, [maxQueueHistory]);++ const commitMaxQueueHistory = useCallback(async () => {+ if (!runtimeConfig || !canEditRuntimeConfig) {+ return;+ }++ const trimmedValue = maxQueueHistoryInput.trim();+ const parsedValue = trimmedValue === '' ? null : Number.parseInt(trimmedValue, 10);++ if (parsedValue !== null && Number.isNaN(parsedValue)) {+ setMaxQueueHistoryInput(formatOptionalInteger(maxQueueHistory));+ return;+ }++ const normalizedValue = parsedValue === null ? null : Math.max(0, parsedValue);+ const currentValue =+ pendingMaxQueueHistoryRef.current === undefined ? maxQueueHistory : pendingMaxQueueHistoryRef.current;++ if (normalizedValue === currentValue) {+ setMaxQueueHistoryInput(formatOptionalInteger(currentValue));+ return;+ }++ pendingMaxQueueHistoryRef.current = normalizedValue;+ setMaxQueueHistoryInput(formatOptionalInteger(normalizedValue));++ try {+ await updateRuntimeConfig({ max_queue_history: normalizedValue }).unwrap();+ } catch {+ setMaxQueueHistoryInput(formatOptionalInteger(maxQueueHistory));+ toast({+ id: 'SETTINGS_MAX_QUEUE_HISTORY_SAVE_FAILED',+ title: t('settings.maxQueueHistorySaveFailed'),+ status: 'error',+ });+ } finally {+ pendingMaxQueueHistoryRef.current = undefined;+ }+ }, [canEditRuntimeConfig, maxQueueHistory, maxQueueHistoryInput, runtimeConfig, t, updateRuntimeConfig]);++ const handleCloseSettingsModal = useCallback(() => {+ void commitMaxQueueHistory();+ settingsModal.setFalse();+ }, [commitMaxQueueHistory, settingsModal]);+const handleClickResetWebUI = useCallback(() => {+ void commitMaxQueueHistory();clearStorage();settingsModal.setFalse();refreshModal.setTrue();- }, [settingsModal, refreshModal]);+ }, [commitMaxQueueHistory, refreshModal, settingsModal]);const handleChangeShouldConfirmOnDelete = useCallback((e: ChangeEvent<HTMLInputElement>) => {@@ -172,12 +241,30 @@ const SettingsModal = (props: { children: ReactElement }) => {[dispatch]);+ const handleChangeMaxQueueHistory = useCallback((valueAsString: string) => {+ setMaxQueueHistoryInput(valueAsString);+ }, []);++ const handleBlurMaxQueueHistory = useCallback(() => {+ void commitMaxQueueHistory();+ }, [commitMaxQueueHistory]);++ const handleKeyDownMaxQueueHistory = useCallback(+ (e: KeyboardEvent<HTMLInputElement>) => {+ if (e.key === 'Enter') {+ void commitMaxQueueHistory();+ e.currentTarget.blur();+ }+ },+ [commitMaxQueueHistory]+ );+return (<>{cloneElement(props.children, {onClick: settingsModal.setTrue,})}- <Modal isOpen={settingsModal.isTrue} onClose={settingsModal.setFalse} size="2xl" isCentered useInert={false}>+ <Modal isOpen={settingsModal.isTrue} onClose={handleCloseSettingsModal} size="2xl" isCentered useInert={false}><ModalOverlay /><ModalContent maxH="80vh" h="68rem"><ModalHeader bg="none">{t('common.settingsLabel')}</ModalHeader>@@ -206,6 +293,21 @@ const SettingsModal = (props: { children: ReactElement }) => {<FormLabel>{t('settings.enableInvisibleWatermark')}</FormLabel><Switch isChecked={shouldUseWatermarker} onChange={handleChangeShouldUseWatermarker} /></FormControl>+ <FormControl>+ <FormLabel>{t('settings.maxQueueHistory')}</FormLabel>+ <NumberInput+ min={0}+ step={1}+ value={maxQueueHistoryInput}+ onChange={handleChangeMaxQueueHistory}+ onBlur={handleBlurMaxQueueHistory}+ clampValueOnBlur={false}+ isDisabled={!runtimeConfig || !canEditRuntimeConfig || isUpdatingRuntimeConfig}+ w="8rem"+ >+ <NumberInputField onKeyDown={handleKeyDownMaxQueueHistory} />+ </NumberInput>+ </FormControl></StickyScrollable><StickyScrollable title={t('settings.ui')}>diff --git a/invokeai/frontend/web/src/services/api/endpoints/appInfo.ts b/invokeai/frontend/web/src/services/api/endpoints/appInfo.tsindex 8fe85125e6..1c656d289b 100644--- a/invokeai/frontend/web/src/services/api/endpoints/appInfo.ts+++ b/invokeai/frontend/web/src/services/api/endpoints/appInfo.ts@@ -51,6 +51,26 @@ export const appInfoApi = api.injectEndpoints({url: buildAppInfoUrl('runtime_config'),method: 'GET',}),+ providesTags: ['AppConfig'],+ }),+ updateRuntimeConfig: build.mutation<+ paths['/api/v1/app/runtime_config']['patch']['responses']['200']['content']['application/json'],+ paths['/api/v1/app/runtime_config']['patch']['requestBody']['content']['application/json']+ >({+ query: (body) => ({+ url: buildAppInfoUrl('runtime_config'),+ method: 'PATCH',+ body,+ }),+ async onQueryStarted(_, { dispatch, queryFulfilled }) {+ try {+ const { data } = await queryFulfilled;+ dispatch(appInfoApi.util.upsertQueryData('getRuntimeConfig', undefined, data));+ } catch {+ // no-op+ }+ },+ invalidatesTags: ['AppConfig'],}),getInvocationCacheStatus: build.query<paths['/api/v1/app/invocation_cache/status']['get']['responses']['200']['content']['application/json'],@@ -95,6 +115,7 @@ export const {useGetAppDepsQuery,useGetPatchmatchStatusQuery,useGetRuntimeConfigQuery,+ useUpdateRuntimeConfigMutation,useClearInvocationCacheMutation,useDisableInvocationCacheMutation,useEnableInvocationCacheMutation,diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 4f10cf6c48..2e93e98ad5 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -1586,7 +1586,8 @@ export type paths = {delete?: never;options?: never;head?: never;- patch?: never;+ /** Update Runtime Config */+ patch: operations["update_runtime_config"];trace?: never;};"/api/v1/app/logging": {@@ -15199,7 +15200,8 @@ export type components = {* force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).* pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.* max_queue_size: Maximum number of items in the session queue.- * clear_queue_on_startup: Empties session queue on startup.+ * clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.+ * max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.* allow_nodes: List of nodes to allow. Omit to allow all.* deny_nodes: List of nodes to deny. Omit to deny none.* node_cache_size: How many cached nodes to keep in memory.@@ -15527,10 +15529,15 @@ export type components = {max_queue_size?: number;/*** Clear Queue On Startup- * @description Empties session queue on startup.+ * @description Empties session queue on startup. If true, disables `max_queue_history`.* @default false*/clear_queue_on_startup?: boolean;+ /**+ * Max Queue History+ * @description Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.+ */+ max_queue_history?: number | null;/*** Allow Nodes* @description List of nodes to allow. Omit to allow all.@@ -28585,6 +28592,17 @@ export type components = {*/unstarred_images: string[];};+ /**+ * UpdateAppGenerationSettingsRequest+ * @description Writable generation-related app settings.+ */+ UpdateAppGenerationSettingsRequest: {+ /**+ * Max Queue History+ * @description Keep the last N completed, failed, and canceled queue items on startup. Set to 0 to prune all terminal items.+ */+ max_queue_history?: number | null;+ };/*** UserDTO* @description User data transfer object.@@ -33751,6 +33769,39 @@ export interface operations {};};};+ update_runtime_config: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody: {+ content: {+ "application/json": components["schemas"]["UpdateAppGenerationSettingsRequest"];+ };+ };+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["InvokeAIAppConfigWithSetFields"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };get_log_level: {parameters: {query?: never;