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: add image subfolder strategy setting UI (#9133)
Jonathanaa865f6e0877
diff --git a/docs/src/content/docs/configuration/invokeai-yaml.mdx b/docs/src/content/docs/configuration/invokeai-yaml.mdxindex 43a68ee9f7..987c8eb98a 100644--- a/docs/src/content/docs/configuration/invokeai-yaml.mdx+++ b/docs/src/content/docs/configuration/invokeai-yaml.mdx@@ -114,6 +114,25 @@ Most common algorithms are supported, like `md5`, `sha256`, and `sha512`. TheseThese options set the paths of various directories and files used by InvokeAI. Any user-defined paths should be absolute paths.+#### Image Subfolder Strategy++By default, generated images are stored in a single flat directory under `outputs/images/`. The `image_subfolder_strategy` setting lets you organize newly-created images into subfolders automatically. You can edit this setting in `invokeai.yaml` or, as an admin user, in the Settings panel.++```yaml+image_subfolder_strategy: flat # default value+```++Available strategies:++| Strategy | Example Path | Description |+| -------- | -------------------------------------- | ------------------------------------------------------------------------------------------------- |+| `flat` | `outputs/images/abc123.png` | Store images directly in the images directory. |+| `date` | `outputs/images/2026/03/17/abc123.png` | Organize images by creation date. |+| `type` | `outputs/images/general/abc123.png` | Organize images by image category. |+| `hash` | `outputs/images/ab/abc123.png` | Use the first two characters of the image UUID for filesystem performance with large collections. |++Changing this setting only affects newly-created images. Existing images remain in their current locations.+#### LoggingSeveral different log handler destinations are available, and multiple destinations are supported by providing a list:diff --git a/invokeai/app/api/routers/app_info.py b/invokeai/app/api/routers/app_info.pyindex 68c0055e1c..f2cd65aa1c 100644--- a/invokeai/app/api/routers/app_info.py+++ b/invokeai/app/api/routers/app_info.py@@ -3,17 +3,19 @@ from enum import Enumfrom importlib.metadata import distributionsfrom pathlib import Path as FilePathfrom threading import Lock+from typing import Anyimport torchimport yamlfrom fastapi import Body, HTTPException, Pathfrom fastapi.routing import APIRouter-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, model_validatorfrom invokeai.app.api.auth_dependencies import AdminUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.services.config.config_default import (EXTERNAL_PROVIDER_CONFIG_FIELDS,+ IMAGE_SUBFOLDER_STRATEGY,DefaultInvokeAIAppConfig,InvokeAIAppConfig,get_config,@@ -105,15 +107,37 @@ EXTERNAL_PROVIDER_FIELDS: dict[str, tuple[str, str]] = {_EXTERNAL_PROVIDER_CONFIG_LOCK = Lock()+def _remove_nullable_default_from_schema(schema: dict[str, Any]) -> None:+ schema.pop("default", None)+ any_of = schema.pop("anyOf", None)+ if isinstance(any_of, list):+ non_null_schemas = [+ subschema for subschema in any_of if isinstance(subschema, dict) and subschema.get("type") != "null"+ ]+ if len(non_null_schemas) == 1:+ schema.update(non_null_schemas[0])++class UpdateAppGenerationSettingsRequest(BaseModel):"""Writable generation-related app settings."""+ image_subfolder_strategy: IMAGE_SUBFOLDER_STRATEGY | None = Field(+ default=None,+ description="Strategy for organizing images into subfolders.",+ json_schema_extra=_remove_nullable_default_from_schema,+ )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.",)+ @model_validator(mode="after")+ def validate_explicit_nulls(self) -> "UpdateAppGenerationSettingsRequest":+ if "image_subfolder_strategy" in self.model_fields_set and self.image_subfolder_strategy is None:+ raise ValueError("image_subfolder_strategy may not be null")+ return self+@app_router.get("/runtime_config", operation_id="get_runtime_config", status_code=200, response_model=InvokeAIAppConfigWithSetFields@@ -133,18 +157,19 @@ 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)+ with _EXTERNAL_PROVIDER_CONFIG_LOCK:+ 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()+ 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)+ 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(diff --git a/invokeai/frontend/web/public/locales/en.json b/invokeai/frontend/web/public/locales/en.jsonindex 05edf88689..e7631ff623 100644--- a/invokeai/frontend/web/public/locales/en.json+++ b/invokeai/frontend/web/public/locales/en.json@@ -1800,6 +1800,13 @@"enableNSFWChecker": "Enable NSFW Checker","general": "General","generation": "Generation",+ "imageSubfolderStrategy": "Image Subfolder Strategy",+ "imageSubfolderStrategyDate": "Date",+ "imageSubfolderStrategyFlat": "Flat",+ "imageSubfolderStrategyHash": "Hash",+ "imageSubfolderStrategySaveFailed": "Failed to save Image Subfolder Strategy",+ "imageSubfolderStrategyType": "Type",+ "imageSubfolderStrategyUnknown": "Unknown ({{strategy}})","maxQueueHistory": "Max Queue History","maxQueueHistorySaveFailed": "Failed to save Max Queue History","models": "Models",diff --git a/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsImageSubfolderStrategySelect.test.ts b/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsImageSubfolderStrategySelect.test.tsnew file mode 100644index 0000000000..ecfe12310e--- /dev/null+++ b/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsImageSubfolderStrategySelect.test.ts@@ -0,0 +1,43 @@+import type { S } from 'services/api/types';+import type { Equals } from 'tsafe';+import { assert } from 'tsafe';+import { describe, expect, it } from 'vitest';++import {+ getImageSubfolderStrategyOption,+ imageSubfolderStrategyOptions,+ isImageSubfolderStrategy,+} from './SettingsImageSubfolderStrategySelect';++describe('image subfolder strategy settings options', () => {+ it('covers all runtime config image subfolder strategies exposed by the API', () => {+ type ImageSubfolderStrategy = NonNullable<S['UpdateAppGenerationSettingsRequest']['image_subfolder_strategy']>;+ type OptionValue = (typeof imageSubfolderStrategyOptions)[number]['value'];++ assert<Equals<Exclude<ImageSubfolderStrategy, OptionValue>, never>>();+ assert<Equals<Exclude<OptionValue, ImageSubfolderStrategy>, never>>();+ });++ it('includes all runtime config image subfolder strategies', () => {+ expect(imageSubfolderStrategyOptions.map((option) => option.value)).toEqual(['flat', 'date', 'type', 'hash']);+ });++ it('validates image subfolder strategy values', () => {+ expect(isImageSubfolderStrategy('date')).toBe(true);+ expect(isImageSubfolderStrategy('unknown')).toBe(false);+ });++ it('gets the option for the active strategy', () => {+ expect(getImageSubfolderStrategyOption('hash')).toEqual({+ label: 'settings.imageSubfolderStrategyHash',+ value: 'hash',+ });+ });++ it('gets an explicit unknown option for an unrecognized active strategy', () => {+ expect(getImageSubfolderStrategyOption('unknown')).toEqual({+ label: 'settings.imageSubfolderStrategyUnknown',+ value: 'unknown',+ });+ });+});diff --git a/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsImageSubfolderStrategySelect.tsx b/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsImageSubfolderStrategySelect.tsxnew file mode 100644index 0000000000..b156a50de2--- /dev/null+++ b/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsImageSubfolderStrategySelect.tsx@@ -0,0 +1,100 @@+import type { ComboboxOnChange } from '@invoke-ai/ui-library';+import { Combobox, FormControl, FormLabel } from '@invoke-ai/ui-library';+import { useAppSelector } from 'app/store/storeHooks';+import { selectCurrentUser } from 'features/auth/store/authSlice';+import { toast } from 'features/toast/toast';+import { memo, useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';+import { useGetRuntimeConfigQuery, useUpdateRuntimeConfigMutation } from 'services/api/endpoints/appInfo';+import type { S } from 'services/api/types';++type ImageSubfolderStrategy = NonNullable<S['UpdateAppGenerationSettingsRequest']['image_subfolder_strategy']>;++type ImageSubfolderStrategyOption = {+ label: string;+ value: ImageSubfolderStrategy;+};++type ImageSubfolderStrategySelectOption = {+ label: string;+ value: string;+};++export const imageSubfolderStrategyOptions = [+ { label: 'settings.imageSubfolderStrategyFlat', value: 'flat' },+ { label: 'settings.imageSubfolderStrategyDate', value: 'date' },+ { label: 'settings.imageSubfolderStrategyType', value: 'type' },+ { label: 'settings.imageSubfolderStrategyHash', value: 'hash' },+] satisfies ImageSubfolderStrategyOption[];++export const isImageSubfolderStrategy = (value: unknown): value is ImageSubfolderStrategy =>+ imageSubfolderStrategyOptions.some((option) => option.value === value);++export const getImageSubfolderStrategyOption = (strategy: string): ImageSubfolderStrategySelectOption =>+ imageSubfolderStrategyOptions.find((option) => option.value === strategy) ?? {+ label: 'settings.imageSubfolderStrategyUnknown',+ value: strategy,+ };++export const SettingsImageSubfolderStrategySelect = memo(() => {+ const { t } = useTranslation();+ const currentUser = useAppSelector(selectCurrentUser);+ const { data: runtimeConfig } = useGetRuntimeConfigQuery();+ const [updateRuntimeConfig, { isLoading }] = useUpdateRuntimeConfigMutation();+ const imageSubfolderStrategy: string = runtimeConfig?.config.image_subfolder_strategy ?? 'flat';+ const canEditRuntimeConfig = runtimeConfig ? !runtimeConfig.config.multiuser || currentUser?.is_admin : false;++ const options = useMemo(() => {+ const localizedOptions: ImageSubfolderStrategySelectOption[] = imageSubfolderStrategyOptions.map((option) => ({+ ...option,+ label: t(option.label),+ }));++ if (!isImageSubfolderStrategy(imageSubfolderStrategy)) {+ localizedOptions.push({+ label: t('settings.imageSubfolderStrategyUnknown', { strategy: imageSubfolderStrategy }),+ value: imageSubfolderStrategy,+ });+ }++ return localizedOptions;+ }, [imageSubfolderStrategy, t]);++ const value = useMemo(+ () => options.find((option) => option.value === imageSubfolderStrategy),+ [imageSubfolderStrategy, options]+ );++ const onChange = useCallback<ComboboxOnChange>(+ async (selection) => {+ if (!isImageSubfolderStrategy(selection?.value) || selection.value === imageSubfolderStrategy) {+ return;+ }++ try {+ await updateRuntimeConfig({ image_subfolder_strategy: selection.value }).unwrap();+ } catch {+ toast({+ id: 'SETTINGS_IMAGE_SUBFOLDER_STRATEGY_SAVE_FAILED',+ title: t('settings.imageSubfolderStrategySaveFailed'),+ status: 'error',+ });+ }+ },+ [imageSubfolderStrategy, t, updateRuntimeConfig]+ );++ return (+ <FormControl>+ <FormLabel>{t('settings.imageSubfolderStrategy')}</FormLabel>+ <Combobox+ value={value}+ options={options}+ onChange={onChange}+ isDisabled={!runtimeConfig || !canEditRuntimeConfig || isLoading}+ />+ </FormControl>+ );+});++SettingsImageSubfolderStrategySelect.displayName = 'SettingsImageSubfolderStrategySelect';diff --git a/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsModal.tsx b/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsModal.tsxindex 1f28e786c1..64478953a3 100644--- a/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsModal.tsx+++ b/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsModal.tsx@@ -28,6 +28,7 @@ import { useRefreshAfterResetModal } from 'features/system/components/SettingsMoimport { SettingsDeveloperLogIsEnabled } from 'features/system/components/SettingsModal/SettingsDeveloperLogIsEnabled';import { SettingsDeveloperLogLevel } from 'features/system/components/SettingsModal/SettingsDeveloperLogLevel';import { SettingsDeveloperLogNamespaces } from 'features/system/components/SettingsModal/SettingsDeveloperLogNamespaces';+import { SettingsImageSubfolderStrategySelect } from 'features/system/components/SettingsModal/SettingsImageSubfolderStrategySelect';import { useClearIntermediates } from 'features/system/components/SettingsModal/useClearIntermediates';import { StickyScrollable } from 'features/system/components/StickyScrollable';import {@@ -319,6 +320,7 @@ const SettingsModal = (props: { children: ReactElement }) => {<NumberInputField onKeyDown={handleKeyDownMaxQueueHistory} /></NumberInput></FormControl>+ <SettingsImageSubfolderStrategySelect /></StickyScrollable><StickyScrollable title={t('settings.models')}>diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 62070fcbbb..63e365ce33 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -30603,6 +30603,12 @@ export type components = {* @description Writable generation-related app settings.*/UpdateAppGenerationSettingsRequest: {+ /**+ * Image Subfolder Strategy+ * @description Strategy for organizing images into subfolders.+ * @enum {string}+ */+ image_subfolder_strategy?: "flat" | "date" | "type" | "hash";/*** Max Queue History* @description Keep the last N completed, failed, and canceled queue items on startup. Set to 0 to prune all terminal items.diff --git a/tests/app/routers/test_app_info.py b/tests/app/routers/test_app_info.pyindex afc7115cfc..2f6d021704 100644--- a/tests/app/routers/test_app_info.py+++ b/tests/app/routers/test_app_info.py@@ -7,9 +7,12 @@ import pytestfrom fastapi.testclient import TestClientfrom invokeai.app.api.dependencies import ApiDependencies+from invokeai.app.api.routers import app_infofrom invokeai.app.api_app import app+from invokeai.app.services.auth.token_service import TokenDatafrom invokeai.app.services.config.config_default import get_config, load_and_migrate_config, load_external_api_keysfrom invokeai.app.services.external_generation.external_generation_common import ExternalProviderStatus+from invokeai.app.services.image_files.image_subfolder_strategy import DateStrategy, create_subfolder_strategyfrom invokeai.app.services.invoker import Invokerfrom invokeai.backend.model_manager.configs.external_api import ExternalApiModelConfig, ExternalModelCapabilitiesfrom invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType@@ -177,5 +180,111 @@ def test_set_external_provider_config_clears_provider_models_when_api_key_removemock_install.delete.assert_called_once_with("openai_model")+def test_update_runtime_config_persists_image_subfolder_strategy(+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient+) -> None:+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(mock_invoker))++ response = client.patch("/api/v1/app/runtime_config", json={"image_subfolder_strategy": "date"})++ assert response.status_code == 200+ assert response.json()["config"]["image_subfolder_strategy"] == "date"++ config_path = get_config().config_file_path+ file_config = load_and_migrate_config(config_path)+ assert file_config.image_subfolder_strategy == "date"+ assert "image_subfolder_strategy: date" in config_path.read_text()+ assert get_config().image_subfolder_strategy == "date"+ assert isinstance(create_subfolder_strategy(get_config().image_subfolder_strategy), DateStrategy)+++def test_update_runtime_config_rejects_null_image_subfolder_strategy(+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient+) -> None:+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(mock_invoker))++ response = client.patch("/api/v1/app/runtime_config", json={"image_subfolder_strategy": None})++ assert response.status_code == 422+++def test_update_runtime_config_image_subfolder_strategy_schema() -> None:+ app.openapi_schema = None+ property_schema = app.openapi()["components"]["schemas"]["UpdateAppGenerationSettingsRequest"]["properties"][+ "image_subfolder_strategy"+ ]++ assert property_schema == {+ "description": "Strategy for organizing images into subfolders.",+ "enum": ["flat", "date", "type", "hash"],+ "title": "Image Subfolder Strategy",+ "type": "string",+ }+++def test_update_runtime_config_reads_and_writes_yaml_under_config_lock(+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient+) -> None:+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(mock_invoker))++ class TrackingLock:+ is_locked = False+ load_seen = False+ write_seen = False++ def __enter__(self) -> None:+ self.is_locked = True++ def __exit__(self, *_: Any) -> None:+ self.is_locked = False++ tracking_lock = TrackingLock()+ original_load_and_migrate_config = app_info.load_and_migrate_config+ original_write_file = app_info.InvokeAIAppConfig.write_file++ def load_and_migrate_config_with_lock_assertion(config_path: Path) -> Any:+ assert tracking_lock.is_locked+ tracking_lock.load_seen = True+ return original_load_and_migrate_config(config_path)++ def write_file_with_lock_assertion(+ config: app_info.InvokeAIAppConfig, dest_path: Path, as_example: bool = False+ ) -> None:+ assert tracking_lock.is_locked+ tracking_lock.write_seen = True+ return original_write_file(config, dest_path, as_example)++ monkeypatch.setattr(app_info, "_EXTERNAL_PROVIDER_CONFIG_LOCK", tracking_lock)+ monkeypatch.setattr(app_info, "load_and_migrate_config", load_and_migrate_config_with_lock_assertion)+ monkeypatch.setattr(app_info.InvokeAIAppConfig, "write_file", write_file_with_lock_assertion)++ response = client.patch("/api/v1/app/runtime_config", json={"max_queue_history": 10})++ assert response.status_code == 200+ assert tracking_lock.load_seen+ assert tracking_lock.write_seen+++def test_update_runtime_config_rejects_non_admin_users(+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient+) -> None:+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(mock_invoker))+ monkeypatch.setattr(mock_invoker.services.configuration, "multiuser", True)+ monkeypatch.setattr(+ "invokeai.app.api.auth_dependencies.verify_token",+ lambda _: TokenData(user_id="user-1", email="[email protected]", is_admin=False),+ )+ monkeypatch.setattr(mock_invoker.services.users, "get", Mock(return_value=Mock(is_active=True)))++ response = client.patch(+ "/api/v1/app/runtime_config",+ json={"image_subfolder_strategy": "date"},+ headers={"Authorization": "Bearer non-admin-token"},+ )++ assert response.status_code == 403+ assert response.json()["detail"] == "Admin privileges required"++def _get_provider_config(payload: list[dict[str, Any]], provider_id: str) -> dict[str, Any]:return next(item for item in payload if item["provider_id"] == provider_id)