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): add configurable donation links (#9651)
Josh Corbett72d16f0a9a08
diff --git a/docs/src/content/docs/configuration/01.invokeai-yaml.mdx b/docs/src/content/docs/configuration/01.invokeai-yaml.mdxindex d4a68d54ae..8cef7ee714 100644--- a/docs/src/content/docs/configuration/01.invokeai-yaml.mdx+++ b/docs/src/content/docs/configuration/01.invokeai-yaml.mdx@@ -80,6 +80,16 @@ You can use any config file with the `--config` CLI arg. Pass in the path to theNote that environment variables will trump any settings in the config file.+#### Donation Links++The **Help & resources** and app menus show a heart icon labeled **Donate to InvokeAI**, which opens [GitHub Sponsors](https://github.com/sponsors/invoke-ai) in a new tab. Hosted deployments can hide both entries by adding this setting to `invokeai.yaml`:++```yaml+show_donation_link: false+```++The default is `true`. Restart InvokeAI and reload the browser after changing this setting. It can also be set with the `INVOKEAI_SHOW_DONATION_LINK` environment variable.+#### Model Marketplace API KeysSome model marketplaces require an API key to download models. You can provide a URL pattern and appropriate token in your `invokeai.yaml` file to provide that API key.diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.jsonindex 8782c7dd1e..2dcfa83781 100644--- a/docs/src/generated/settings.json+++ b/docs/src/generated/settings.json@@ -125,6 +125,17 @@"type": "<class 'int'>","validation": {}},+ {+ "category": "MISC FEATURES",+ "default": true,+ "description": "Show the Donate to InvokeAI link in the frontend menus.",+ "env_var": "INVOKEAI_SHOW_DONATION_LINK",+ "literal_values": [],+ "name": "show_donation_link",+ "required": false,+ "type": "<class 'bool'>",+ "validation": {}+ },{"category": "MISC FEATURES","default": false,diff --git a/invokeai/app/api/routers/app_info.py b/invokeai/app/api/routers/app_info.pyindex 25dc67fe3e..6e8ae9b165 100644--- a/invokeai/app/api/routers/app_info.py+++ b/invokeai/app/api/routers/app_info.py@@ -52,6 +52,17 @@ class AppVersion(BaseModel):version: str = Field(description="App version")+class FrontendConfig(BaseModel):+ """Presentation settings any signed-in user may read; never include private runtime configuration here."""++ show_donation_link: bool = Field(description="Whether to show the Donate to InvokeAI menu link")+++@app_router.get("/frontend_config", operation_id="get_frontend_config", response_model=FrontendConfig)+def get_frontend_config(current_user: CurrentUserOrDefault) -> FrontendConfig:+ return FrontendConfig(show_donation_link=get_config().show_donation_link)++@app_router.get("/version", operation_id="app_version", status_code=200, response_model=AppVersion)def get_version() -> AppVersion:return AppVersion(version=__version__)diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.pyindex e2a6610a02..29ce47a5b7 100644--- a/invokeai/app/services/config/config_default.py+++ b/invokeai/app/services/config/config_default.py@@ -84,6 +84,7 @@ class InvokeAIAppConfig(BaseSettings):allow_headers: Headers allowed for CORS.ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.+ show_donation_link: Show the Donate to InvokeAI link in the frontend menus.log_tokenization: Enable logging of parsed prompt tokens.patchmatch: Enable patchmatch inpaint code.models_dir: Path to the models directory.@@ -192,6 +193,7 @@ class InvokeAIAppConfig(BaseSettings):http_compression_level: int = Field(default=9, ge=0, le=9, description="Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses.")# MISC FEATURES+ show_donation_link: bool = Field(default=True, description="Show the Donate to InvokeAI link in the frontend menus.")log_tokenization: bool = Field(default=False, description="Enable logging of parsed prompt tokens.")patchmatch: bool = Field(default=True, description="Enable patchmatch inpaint code.")diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex d5e413a3a7..8c8b27d977 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -11355,6 +11355,30 @@]}},+ "/api/v1/app/frontend_config": {+ "get": {+ "tags": ["app"],+ "summary": "Get Frontend Config",+ "operationId": "get_frontend_config",+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/FrontendConfig"+ }+ }+ }+ }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]+ }+ },"/api/v1/app/version": {"get": {"tags": ["app"],@@ -40391,6 +40415,19 @@"$ref": "#/components/schemas/UNetOutput"}},+ "FrontendConfig": {+ "properties": {+ "show_donation_link": {+ "type": "boolean",+ "title": "Show Donation Link",+ "description": "Whether to show the Donate to InvokeAI menu link"+ }+ },+ "type": "object",+ "required": ["show_donation_link"],+ "title": "FrontendConfig",+ "description": "Presentation settings any signed-in user may read; never include private runtime configuration here."+ },"GalleryItem": {"properties": {"kind": {@@ -58626,6 +58663,12 @@"description": "Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses.","default": 9},+ "show_donation_link": {+ "type": "boolean",+ "title": "Show Donation Link",+ "description": "Show the Donate to InvokeAI link in the frontend menus.",+ "default": true+ },"log_tokenization": {"type": "boolean","title": "Log Tokenization",@@ -59348,7 +59391,7 @@"additionalProperties": false,"type": "object","title": "InvokeAIAppConfig",- "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.\n clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, Z-Image, Qwen-Image, Krea-2 and Wan decodes). Turn off to decode untiled unless tiling is requested; the FLUX.1 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\n 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.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n 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.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."+ "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n show_donation_link: Show the Donate to InvokeAI link in the frontend menus.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.\n clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, Z-Image, Qwen-Image, Krea-2 and Wan decodes). Turn off to decode untiled unless tiling is requested; the FLUX.1 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\n 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.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n 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.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."},"InvokeAIAppConfigWithSetFields": {"properties": {diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 99724dd334..1b039abca8 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -2671,6 +2671,23 @@ export type paths = {patch?: never;trace?: never;};+ "/api/v1/app/frontend_config": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /** Get Frontend Config */+ get: operations["get_frontend_config"];+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/v1/app/version": {parameters: {query?: never;@@ -16181,6 +16198,17 @@ export type components = {*/type: "freeu";};+ /**+ * FrontendConfig+ * @description Presentation settings any signed-in user may read; never include private runtime configuration here.+ */+ FrontendConfig: {+ /**+ * Show Donation Link+ * @description Whether to show the Donate to InvokeAI menu link+ */+ show_donation_link: boolean;+ };/*** GalleryItem* @description A gallery item — either an image or a video, with shared fields and a discriminator.@@ -22455,6 +22483,7 @@ export type components = {* allow_headers: Headers allowed for CORS.* ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.* ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.+ * show_donation_link: Show the Donate to InvokeAI link in the frontend menus.* log_tokenization: Enable logging of parsed prompt tokens.* patchmatch: Enable patchmatch inpaint code.* models_dir: Path to the models directory.@@ -22617,6 +22646,12 @@ export type components = {* @default 9*/http_compression_level?: number;+ /**+ * Show Donation Link+ * @description Show the Donate to InvokeAI link in the frontend menus.+ * @default true+ */+ show_donation_link?: boolean;/*** Log Tokenization* @description Enable logging of parsed prompt tokens.@@ -57132,6 +57167,26 @@ export interface operations {};};};+ get_frontend_config: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["FrontendConfig"];+ };+ };+ };+ };app_version: {parameters: {query?: never;diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 3d6c1cec0c..d8f81d4ea5 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -166,6 +166,7 @@}},"common": {+ "donateToInvokeAI": "Donate to InvokeAI","actions": "Actions","active": "Active","add": "Add",diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjsindex c95441e8ef..29ccb75355 100644--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -877,6 +877,10 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {return json(200, { version: MOCK_APP_VERSION });}+ if (method === 'GET' && path === '/api/v1/app/frontend_config') {+ return json(200, { show_donation_link: true });+ }+if (method === 'GET' && path === '/api/v1/app/generation_device_options') {return json(200, [{ device: 'cpu', name: 'CPU' }]);}diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjsindex 10cb7b155c..dfabe0ab8b 100644--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs@@ -537,15 +537,22 @@ const runTopbarMenuJourney = async (browser) => {const whatsNewItem = page.getByRole('menuitem', { exact: true, name: "What's New in Invoke" });const documentationItem = page.getByRole('menuitem', { exact: true, name: 'Documentation' });const discordItem = page.getByRole('menuitem', { exact: true, name: 'Discord' });+ const donationItem = appMenu.getByRole('menuitem', { exact: true, name: 'Donate to InvokeAI' });await commandPaletteItem.waitFor();await settingsItem.waitFor();await whatsNewItem.waitFor();await documentationItem.waitFor();await discordItem.waitFor();+ await donationItem.waitFor();+ assert.equal(await donationItem.getAttribute('href'), 'https://github.com/sponsors/invoke-ai');+ assert.equal(await donationItem.getAttribute('target'), '_blank');const footerMetrics = await appMenu.evaluate((menu) => {const menuBounds = menu.getBoundingClientRect();- const footerItems = [...menu.querySelectorAll('[role="menuitem"]')].slice(-5);+ const footerValues = ['command-palette', 'settings', 'whats-new', 'documentation', 'discord'];+ const footerItems = [...menu.querySelectorAll('[role="menuitem"]')].filter((item) =>+ footerValues.includes(item.getAttribute('data-value'))+ );return {itemsFit: footerItems.every((item) => {@@ -568,6 +575,8 @@ const runTopbarMenuJourney = async (browser) => {assert.equal(await page.getByRole('tooltip', { name: /^Command palette/ }).count(), 0);await appMenu.press('End');+ assert.equal(await appMenu.getAttribute('aria-activedescendant'), await donationItem.getAttribute('id'));+ await appMenu.press('ArrowUp');assert.equal(await appMenu.getAttribute('aria-activedescendant'), await discordItem.getAttribute('id'));for (const item of [documentationItem, whatsNewItem, settingsItem, commandPaletteItem]) {await appMenu.press('ArrowUp');diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/HelpMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/HelpMenu.browser.test.tsxnew file mode 100644index 0000000000..c3e24c48d4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/launchpad/HelpMenu.browser.test.tsx@@ -0,0 +1,103 @@+import { ChakraProvider } from '@chakra-ui/react';+import { apiFetchJson } from '@platform/transport/http';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import { HelpMenu } from './HelpMenu';++vi.mock('@platform/transport/http', () => ({ apiFetchJson: vi.fn() }));++const i18n = createInstance();+await i18n.use(initReactI18next).init({+ lng: 'en',+ resources: {+ en: {+ translation: {+ common: { donateToInvokeAI: 'Donate to InvokeAI' },+ launchpad: { help: { community: 'Community', github: 'GitHub', label: 'Help' } },+ },+ },+ },+});++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++describe('HelpMenu donation link', () => {+ let host: HTMLDivElement;+ let root: Root;+ let client: QueryClient;++ beforeEach(async () => {+ vi.mocked(apiFetchJson).mockReset();+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root.render(+ <QueryClientProvider client={client}>+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <HelpMenu />+ </I18nextProvider>+ </ChakraProvider>+ </QueryClientProvider>+ )+ );+ });++ afterEach(async () => {+ await act(() => root.unmount());+ client.clear();+ host.remove();+ });++ const trigger = () => page.getByRole('button', { name: 'Help' });++ it('resolves the setting on trigger hover so the link is already in the Community group when the menu opens', async () => {+ vi.mocked(apiFetchJson).mockResolvedValue({ show_donation_link: true });+ expect(apiFetchJson).not.toHaveBeenCalled();++ await userEvent.hover(trigger());+ await vi.waitFor(() => expect(client.getQueryState(['frontend-config'])?.status).toBe('success'));+ await trigger().click();++ const community = page.getByRole('group', { name: 'Community' });+ await expect.element(community.getByRole('menuitem', { name: 'Donate to InvokeAI' })).toBeVisible();+ const items = community.getByRole('menuitem').elements();+ expect(items.at(-1)?.textContent).toBe('Donate to InvokeAI');+ expect(apiFetchJson).toHaveBeenCalledTimes(1);+ });++ it('retries a failed request when the trigger regains focus', async () => {+ vi.mocked(apiFetchJson).mockRejectedValue(new Error('Server restarting'));++ await trigger().click();+ await vi.waitFor(() => expect(client.getQueryState(['frontend-config'])?.status).toBe('error'));+ await expect.element(page.getByRole('menuitem', { name: 'GitHub' })).toBeVisible();+ expect(page.getByRole('menuitem', { name: 'Donate to InvokeAI' }).query()).toBeNull();++ // The open menu keeps the item mounted, so recovery depends on the trigger asking again.+ vi.mocked(apiFetchJson).mockResolvedValue({ show_donation_link: true });+ await userEvent.keyboard('{Escape}');+ await expect.element(trigger()).toHaveFocus();+ await trigger().click();++ await expect.element(page.getByRole('menuitem', { name: 'Donate to InvokeAI' })).toBeVisible();+ });++ it('loads the link when assistive technology opens the menu without hovering or focusing the trigger', async () => {+ vi.mocked(apiFetchJson).mockResolvedValue({ show_donation_link: true });++ // HTMLElement.click() dispatches a bare click: no pointer events and no focus change.+ await act(() => (trigger().element() as HTMLElement).click());++ await expect.element(page.getByRole('menuitem', { name: 'Donate to InvokeAI' })).toBeVisible();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/HelpMenu.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/HelpMenu.tsxindex 01e226befa..fd50335a5c 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/HelpMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/HelpMenu.tsx@@ -1,16 +1,18 @@-import type { ElementType } from 'react';-import { chakra, HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';import { APP_VERSION, DOCS_URL } from '@platform/runtime/appMetadata';import { Button } from '@platform/ui/Button';import { MenuContent } from '@platform/ui/Menu';import { DiscordIcon, GithubIcon } from '@platform/ui/VendoredIcon';+import { useQueryClient } from '@tanstack/react-query';import { BookOpenTextIcon, ChevronRightIcon, ClapperboardIcon, CircleQuestionMarkIcon } from 'lucide-react';+import { useCallback, useState, type ComponentType, type ElementType } from 'react';import { useTranslation } from 'react-i18next';const MENU_POSITIONING = { placement: 'right-end' } as const;const GROUP_LABEL_PROPS = { color: 'fg.subtle', fontSize: 'xs', textTransform: 'uppercase' } as const;const TRIGGER_JUSTIFY = { justifyContent: 'space-between' } as const;+// Loaded on trigger hover or focus, so neither the chunk nor its request is part of route startup.+const loadDonationMenuItem = () => import('@workbench/shell/DonationMenuItem');interface HelpLink {href: string;@@ -65,11 +67,41 @@ const HelpMenuLink = ({ href, icon, labelKey, value }: HelpLink) => {export const HelpMenu = () => {const { t } = useTranslation();+ const queryClient = useQueryClient();+ // Rendered only once loaded: a lazy() boundary would suspend on open and React delays its reveal, shifting rows.+ // A chunk that fails to load (e.g. after an upgrade) leaves the optional link absent.+ const [DonationMenuItem, setDonationMenuItem] = useState<ComponentType | null>(null);+ const preloadDonationMenuItem = useCallback(() => {+ void loadDonationMenuItem().then(+ (module) => {+ setDonationMenuItem(() => module.DonationMenuItem);+ return module.prefetchDonationMenuItem(queryClient);+ },+ () => undefined+ );+ }, [queryClient]);+ // Assistive technology can activate the trigger with a bare click, without hovering or focusing it first.+ const handleOpenChange = useCallback(+ ({ open }: { open: boolean }) => {+ if (open) {+ preloadDonationMenuItem();+ }+ },+ [preloadDonationMenuItem]+ );return (- <Menu.Root positioning={MENU_POSITIONING}>+ <Menu.Root lazyMount positioning={MENU_POSITIONING} onOpenChange={handleOpenChange}><Menu.Trigger asChild>- <Button aria-label={t('launchpad.help.label')} color="fg.muted" css={TRIGGER_JUSTIFY} variant="ghost" w="full">+ <Button+ aria-label={t('launchpad.help.label')}+ color="fg.muted"+ css={TRIGGER_JUSTIFY}+ variant="ghost"+ w="full"+ onFocus={preloadDonationMenuItem}+ onPointerEnter={preloadDonationMenuItem}+ ><Icon as={CircleQuestionMarkIcon} boxSize="3.5" /><Text flex="1" textAlign="start" truncate>{t('launchpad.help.label')}@@ -92,6 +124,7 @@ export const HelpMenu = () => {{COMMUNITY.map((link) => (<HelpMenuLink key={link.value} {...link} />))}+ {DonationMenuItem ? <DonationMenuItem /> : null}</Menu.ItemGroup><Menu.Separator /><HStack justify="space-between" px="3" py="1.5">diff --git a/invokeai/frontend/webv2/src/workbench/settings/DatabaseMaintenance.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/DatabaseMaintenance.browser.test.tsxindex 702ef888bf..ad3dd40548 100644--- a/invokeai/frontend/webv2/src/workbench/settings/DatabaseMaintenance.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/DatabaseMaintenance.browser.test.tsx@@ -90,8 +90,10 @@ describe('database maintenance in Data & workspace settings', () => {await act(() =>root.render(<ChakraProvider value={system}>- <LaunchpadTopBar />- <AppMenu />+ <QueryClientProvider client={queryClient}>+ <LaunchpadTopBar />+ <AppMenu />+ </QueryClientProvider></ChakraProvider>));diff --git a/invokeai/frontend/webv2/src/workbench/shell/DonationMenuItem.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/DonationMenuItem.browser.test.tsxnew file mode 100644index 0000000000..14fe8dd215--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/DonationMenuItem.browser.test.tsx@@ -0,0 +1,101 @@+import { ChakraProvider, Menu } from '@chakra-ui/react';+import { apiFetchJson } from '@platform/transport/http';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import { DonationMenuItem } from './DonationMenuItem';++vi.mock('@platform/transport/http', () => ({ apiFetchJson: vi.fn() }));++const i18n = createInstance();+await i18n.use(initReactI18next).init({+ lng: 'en',+ resources: { en: { translation: { common: { donateToInvokeAI: 'Donate to InvokeAI' } } } },+});++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++describe('DonationMenuItem', () => {+ let host: HTMLDivElement;+ let root: Root;+ let client: QueryClient;++ beforeEach(() => {+ vi.mocked(apiFetchJson).mockReset();+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ client.clear();+ host.remove();+ });++ const render = () =>+ act(() =>+ root.render(+ <QueryClientProvider client={client}>+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <Menu.Root>+ <Menu.Trigger>Open menu</Menu.Trigger>+ <Menu.Positioner>+ <Menu.Content>+ <DonationMenuItem />+ <Menu.Item value="other">Other action</Menu.Item>+ </Menu.Content>+ </Menu.Positioner>+ </Menu.Root>+ </I18nextProvider>+ </ChakraProvider>+ </QueryClientProvider>+ )+ );++ it('offers a keyboard-selectable Sponsors link in a new tab when enabled', async () => {+ vi.mocked(apiFetchJson).mockResolvedValue({ show_donation_link: true });+ await render();+ await page.getByRole('button', { name: 'Open menu' }).click();+ const link = page.getByRole('menuitem', { name: 'Donate to InvokeAI' });+ await expect.element(link).toBeVisible();+ await expect.element(link).toHaveAttribute('href', 'https://github.com/sponsors/invoke-ai');+ await expect.element(link).toHaveAttribute('target', '_blank');+ await expect.element(link).toHaveAttribute('rel', 'noreferrer');+ await userEvent.keyboard('{Home}');+ await expect.element(page.getByRole('menu')).toHaveAttribute('aria-activedescendant', link.element().id);+ await expect.element(link).toHaveAttribute('data-highlighted');+ await userEvent.keyboard('{Escape}');+ await expect.element(page.getByRole('button', { name: 'Open menu' })).toHaveFocus();+ });++ it.each(['disabled', 'pending', 'failed'] as const)(+ 'keeps the link hidden when configuration is %s',+ async (state) => {+ if (state === 'disabled') {+ vi.mocked(apiFetchJson).mockResolvedValue({ show_donation_link: false });+ } else if (state === 'failed') {+ vi.mocked(apiFetchJson).mockRejectedValue(new Error('Unavailable'));+ } else {+ vi.mocked(apiFetchJson).mockImplementation(() => new Promise(() => {}));+ }+ await render();+ await page.getByRole('button', { name: 'Open menu' }).click();+ await expect.element(page.getByRole('menuitem', { name: 'Other action' })).toBeVisible();+ if (state !== 'pending') {+ await vi.waitFor(() =>+ expect(client.getQueryState(['frontend-config'])?.status).toBe(state === 'failed' ? 'error' : 'success')+ );+ }+ expect(document.querySelector('a[href="https://github.com/sponsors/invoke-ai"]')).toBeNull();+ }+ );+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/DonationMenuItem.tsx b/invokeai/frontend/webv2/src/workbench/shell/DonationMenuItem.tsxnew file mode 100644index 0000000000..93b86bcb22--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/DonationMenuItem.tsx@@ -0,0 +1,42 @@+import { chakra, Icon, Menu } from '@chakra-ui/react';+import { apiFetchJson } from '@platform/transport/http';+import { type QueryClient, queryOptions, useQuery } from '@tanstack/react-query';+import { HeartIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++interface FrontendConfig {+ show_donation_link: boolean;+}++const frontendConfigQueryOptions = queryOptions({+ queryKey: ['frontend-config'],+ queryFn: ({ signal }) => apiFetchJson<FrontendConfig>('/api/v1/app/frontend_config', { signal }),+ staleTime: Infinity,+});++/**+ * Menu triggers call this on hover and focus so the setting usually resolves before the menu opens, rather than+ * inserting a row under the pointer. It also retries a failed request, which the mounted menu item never does.+ */+export const prefetchDonationMenuItem = (queryClient: QueryClient) =>+ queryClient.prefetchQuery(frontendConfigQueryOptions);++/** Both menus share the server's visibility policy and the same external destination. */+export const DonationMenuItem = () => {+ const { t } = useTranslation();+ const { data } = useQuery(frontendConfigQueryOptions);++ // Keep the optional link hidden until the deployment's preference is known, including on request failure.+ if (!data?.show_donation_link) {+ return null;+ }++ return (+ <Menu.Item asChild value="donate">+ <chakra.a href="https://github.com/sponsors/invoke-ai" rel="noreferrer" target="_blank">+ <Icon as={HeartIcon} boxSize="3.5" />+ <Menu.ItemText>{t('common.donateToInvokeAI')}</Menu.ItemText>+ </chakra.a>+ </Menu.Item>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsxindex 339f3b13ef..4431237f6f 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsx@@ -7,6 +7,7 @@ import { InvokeMark } from '@platform/ui/InvokeMark';import { MenuContent } from '@platform/ui/Menu';import { Tooltip } from '@platform/ui/Tooltip';import { DiscordIcon, LightbulbFilamentIcon } from '@platform/ui/VendoredIcon';+import { useQueryClient } from '@tanstack/react-query';import { useNavigate } from '@tanstack/react-router';import { OPEN_COMMAND_PALETTE_HOTKEY } from '@workbench/hotkeys/catalog';import { openCommandPalette } from '@workbench/palette/paletteStore';@@ -26,13 +27,15 @@ import {SettingsIcon,TypeIcon,} from 'lucide-react';-import { useCallback, type ElementType } from 'react';+import { useCallback, useState, type ComponentType, type ElementType } from 'react';import { useTranslation } from 'react-i18next';import { useTopbarShortcut } from './useTopbarShortcut';const MENU_POSITIONING = { placement: 'bottom-start' } as const;const DISCORD_URL = 'https://discord.gg/ZmtBAhwWhy';+// Loaded on trigger hover or focus, so neither the chunk nor its request is part of route startup.+const loadDonationMenuItem = () => import('@workbench/shell/DonationMenuItem');export const AppMenu = () => {const { t } = useTranslation();@@ -60,10 +63,41 @@ export const AppMenu = () => {}, [navigate]);const openQueue = useCallback(() => openWorkbenchWidget('queue'), [openWorkbenchWidget]);const openSettings = useCallback(() => openWorkbenchSettings(), []);+ const queryClient = useQueryClient();+ // Rendered only once loaded: a lazy() boundary would suspend on open and React delays its reveal, shifting rows.+ // A chunk that fails to load (e.g. after an upgrade) leaves the optional link absent.+ const [DonationMenuItem, setDonationMenuItem] = useState<ComponentType | null>(null);+ const preloadDonationMenuItem = useCallback(() => {+ void loadDonationMenuItem().then(+ (module) => {+ setDonationMenuItem(() => module.DonationMenuItem);+ return module.prefetchDonationMenuItem(queryClient);+ },+ () => undefined+ );+ }, [queryClient]);+ // Assistive technology can activate the trigger with a bare click, without hovering or focusing it first.+ const handleOpenChange = useCallback(+ ({ open }: { open: boolean }) => {+ if (open) {+ preloadDonationMenuItem();+ }+ },+ [preloadDonationMenuItem]+ );+return (- <Menu.Root positioning={MENU_POSITIONING}>+ <Menu.Root lazyMount positioning={MENU_POSITIONING} onOpenChange={handleOpenChange}><Menu.Trigger asChild>- <IconButton aria-label={t('topbar.appMenu.open')} className="group" pe="1.5" size="lg" variant="ghost">+ <IconButton+ aria-label={t('topbar.appMenu.open')}+ className="group"+ pe="1.5"+ size="lg"+ variant="ghost"+ onFocus={preloadDonationMenuItem}+ onPointerEnter={preloadDonationMenuItem}+ ><AppMenuGlyph /></IconButton></Menu.Trigger>@@ -140,6 +174,7 @@ export const AppMenu = () => {/><AppMenuLink href={DISCORD_URL} icon={DiscordIcon} label="Discord" value="discord" /></HStack>+ {DonationMenuItem ? <DonationMenuItem /> : null}</MenuContent></Menu.Positioner></Portal>diff --git a/tests/app/routers/test_app_info.py b/tests/app/routers/test_app_info.pyindex 732bbad27f..3dc41d0651 100644--- a/tests/app/routers/test_app_info.py+++ b/tests/app/routers/test_app_info.py@@ -41,6 +41,41 @@ def _non_admin_user() -> Mock:return Mock(user_id="user-1", email="[email protected]", is_admin=False, is_active=True, token_epoch=0)+ ("setting", "visible"), [("", True), ("show_donation_link: true", True), ("show_donation_link: false", False)]+)+def test_frontend_config_exposes_only_presentation_settings_to_signed_in_users(+ setting: str,+ visible: bool,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ client: TestClient,+ mock_invoker: Invoker,+ enable_multiuser: Any,+) -> None:+ config_path = tmp_path / "invokeai.yaml"+ config_path.write_text(+ f"schema_version: 4.0.2\nmultiuser: true\nexternal_openai_api_key: private-test-key\n{setting}\n"+ )+ config = load_and_migrate_config(config_path)+ monkeypatch.setattr(app_info, "get_config", lambda: config)++ assert client.get("/api/v1/app/frontend_config").status_code == 401++ 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=_non_admin_user()))+ # Non-admin users read menu presentation without gaining access to the runtime config.+ headers = {"Authorization": "Bearer non-admin-token"}+ assert client.get("/api/v1/app/runtime_config", headers=headers).status_code == 403+ response = client.get("/api/v1/app/frontend_config", headers=headers)++ assert response.status_code == 200+ assert response.json() == {"show_donation_link": visible}++def _patch_database_cleaner(mock_invoker: Invoker, monkeypatch: Any) -> Mock:database = mock_invoker.services.databaseclean = Mock()