Skip to content

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.

Add command palette and all-readable gallery scope

joshistoastabb9866459f6
diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.py
index 679d2158e0..b396137640 100644
--- a/invokeai/app/api/routers/images.py
+++ b/invokeai/app/api/routers/images.py
@@ -447,7 +447,11 @@ async def list_image_dtos(
is_intermediate: Optional[bool] = Query(default=None, description="Whether to list intermediate images."),
board_id: Optional[str] = Query(
default=None,
- description="The board id to filter by. Use 'none' to find images without a board.",
+ description=(
+ "The board id to filter by. Use 'none' for the current user's uncategorized images or 'all' for "
+ "images on every readable, non-archived board plus authorized uncategorized images. If omitted, "
+ "non-admin results remain limited to images owned by the current user."
+ ),
),
offset: int = Query(default=0, description="The page offset"),
limit: int = Query(default=10, description="The number of images per page"),
@@ -464,8 +468,8 @@ async def list_image_dtos(
"""Gets a list of image DTOs for the current user"""
# Validate that the caller can read from this board before listing its images.
- # "none" is a sentinel for uncategorized images and is handled by the SQL layer.
- if board_id is not None and board_id != "none":
+ # "none" and "all" are sentinels handled by the SQL layer.
+ if board_id is not None and board_id not in {"none", "all"}:
_assert_board_read_access(board_id, current_user)
image_dtos = ApiDependencies.invoker.services.images.get_many(
@@ -737,7 +741,11 @@ async def get_image_names(
is_intermediate: Optional[bool] = Query(default=None, description="Whether to list intermediate images."),
board_id: Optional[str] = Query(
default=None,
- description="The board id to filter by. Use 'none' to find images without a board.",
+ description=(
+ "The board id to filter by. Use 'none' for the current user's uncategorized images or 'all' for "
+ "images on every readable, non-archived board plus authorized uncategorized images. If omitted, "
+ "non-admin results remain limited to images owned by the current user."
+ ),
),
order_dir: SQLiteDirection = Query(default=SQLiteDirection.Descending, description="The order of sort"),
starred_first: bool = Query(default=True, description="Whether to sort by starred images first"),
@@ -752,7 +760,7 @@ async def get_image_names(
"""Gets ordered list of image names with metadata for optimistic updates"""
# Validate that the caller can read from this board before listing its images.
- if board_id is not None and board_id != "none":
+ if board_id is not None and board_id not in {"none", "all"}:
_assert_board_read_access(board_id, current_user)
try:
diff --git a/invokeai/app/services/image_records/image_records_base.py b/invokeai/app/services/image_records/image_records_base.py
index 820d988751..6cf44cae61 100644
--- a/invokeai/app/services/image_records/image_records_base.py
+++ b/invokeai/app/services/image_records/image_records_base.py
@@ -61,7 +61,11 @@ class ImageRecordStorageBase(ABC):
user_id: Optional[str] = None,
is_admin: bool = False,
) -> OffsetPaginatedResults[ImageRecord]:
- """Gets a page of image records. When board_id is 'none', filters by user_id for per-user uncategorized images unless is_admin is True.
+ """Gets a page of image records.
+
+ When board_id is 'none', filters by user_id for per-user uncategorized images unless is_admin is True.
+ When board_id is 'all', returns uncategorized images and images on readable, non-archived boards.
+ Omitting board_id retains owner-only isolation for non-admin users.
created_from/created_to are inclusive YYYY-MM-DD bounds on created_at (UTC days).
"""
@@ -136,6 +140,8 @@ class ImageRecordStorageBase(ABC):
) -> ImageNamesResult:
"""Gets ordered list of image names with metadata for optimistic updates.
+ board_id supports the same 'none', 'all', concrete-ID, and omitted scopes as get_many().
+
created_from/created_to are inclusive YYYY-MM-DD bounds on created_at (UTC days).
"""
pass
diff --git a/invokeai/app/services/image_records/image_records_sqlite.py b/invokeai/app/services/image_records/image_records_sqlite.py
index 1c901b2a4a..949971bdda 100644
--- a/invokeai/app/services/image_records/image_records_sqlite.py
+++ b/invokeai/app/services/image_records/image_records_sqlite.py
@@ -1,4 +1,5 @@
import sqlite3
+from dataclasses import dataclass
from datetime import datetime
from typing import Optional, Union, cast
@@ -22,6 +23,116 @@ from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
from invokeai.app.services.virtual_boards.virtual_boards_common import VirtualSubBoardDTO
+@dataclass(frozen=True)
+class _ImageQueryFilters:
+ image_origin: Optional[ResourceOrigin] = None
+ categories: Optional[list[ImageCategory]] = None
+ is_intermediate: Optional[bool] = None
+ board_id: Optional[str] = None
+ search_term: Optional[str] = None
+ created_from: Optional[str] = None
+ created_to: Optional[str] = None
+ user_id: Optional[str] = None
+ is_admin: bool = False
+
+
+def _build_image_query_conditions(filters: _ImageQueryFilters) -> tuple[str, list[Union[int, str, bool]]]:
+ """Build the shared filters for image-list and image-name queries."""
+ conditions: list[str] = []
+ params: list[Union[int, str, bool]] = []
+
+ if filters.image_origin is not None:
+ conditions.append("images.image_origin = ?")
+ params.append(filters.image_origin.value)
+
+ if filters.categories is not None:
+ category_strings = [category.value for category in set(filters.categories)]
+ placeholders = ",".join("?" * len(category_strings))
+ conditions.append(f"images.image_category IN ( {placeholders} )")
+ params.extend(category_strings)
+
+ if filters.is_intermediate is not None:
+ conditions.append("images.is_intermediate = ?")
+ params.append(filters.is_intermediate)
+
+ if filters.board_id == "none":
+ conditions.append("board_images.board_id IS NULL")
+ if filters.user_id is not None and not filters.is_admin:
+ conditions.append("images.user_id = ?")
+ params.append(filters.user_id)
+ elif filters.board_id == "all":
+ if filters.is_admin:
+ conditions.append(
+ """(
+ board_images.board_id IS NULL
+ OR EXISTS (
+ SELECT 1
+ FROM boards
+ WHERE boards.board_id = board_images.board_id
+ AND boards.archived = 0
+ )
+ )"""
+ )
+ elif filters.user_id is not None:
+ conditions.append(
+ """(
+ (board_images.board_id IS NULL AND images.user_id = ?)
+ OR EXISTS (
+ SELECT 1
+ FROM boards
+ WHERE boards.board_id = board_images.board_id
+ AND boards.archived = 0
+ AND (
+ boards.user_id = ?
+ OR boards.board_visibility IN ('shared', 'public')
+ OR EXISTS (
+ SELECT 1
+ FROM shared_boards
+ WHERE shared_boards.board_id = boards.board_id
+ AND shared_boards.user_id = ?
+ )
+ )
+ )
+ )"""
+ )
+ params.extend([filters.user_id, filters.user_id, filters.user_id])
+ else:
+ # Single-user mode has no current user. It can read every active board
+ # and every uncategorized image, matching the administrative scope.
+ conditions.append(
+ """(
+ board_images.board_id IS NULL
+ OR EXISTS (
+ SELECT 1
+ FROM boards
+ WHERE boards.board_id = board_images.board_id
+ AND boards.archived = 0
+ )
+ )"""
+ )
+ elif filters.board_id is not None:
+ conditions.append("board_images.board_id = ?")
+ params.append(filters.board_id)
+ elif filters.user_id is not None and not filters.is_admin:
+ conditions.append("images.user_id = ?")
+ params.append(filters.user_id)
+
+ if filters.search_term:
+ conditions.append("(images.metadata LIKE ? OR images.created_at LIKE ?)")
+ search_pattern = f"%{filters.search_term.lower()}%"
+ params.extend([search_pattern, search_pattern])
+
+ if filters.created_from:
+ conditions.append("images.created_at >= ?")
+ params.append(filters.created_from)
+
+ if filters.created_to:
+ conditions.append("images.created_at < DATE(?, '+1 day')")
+ params.append(filters.created_to)
+
+ return "".join(f"\nAND {condition}" for condition in conditions), params
+
+
class SqliteImageRecordStorage(ImageRecordStorageBase):
def __init__(self, db: SqliteDatabase) -> None:
super().__init__()
@@ -182,86 +293,19 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
WHERE 1=1
"""
- query_conditions = ""
- query_params: list[Union[int, str, bool]] = []
-
- if image_origin is not None:
- query_conditions += """--sql
- AND images.image_origin = ?
- """
- query_params.append(image_origin.value)
-
- if categories is not None:
- # Convert the enum values to unique list of strings
- category_strings = [c.value for c in set(categories)]
- # Create the correct length of placeholders
- placeholders = ",".join("?" * len(category_strings))
-
- query_conditions += f"""--sql
- AND images.image_category IN ( {placeholders} )
- """
-
- # Unpack the included categories into the query params
- for c in category_strings:
- query_params.append(c)
-
- if is_intermediate is not None:
- query_conditions += """--sql
- AND images.is_intermediate = ?
- """
-
- query_params.append(is_intermediate)
-
- # board_id of "none" is reserved for images without a board
- if board_id == "none":
- query_conditions += """--sql
- AND board_images.board_id IS NULL
- """
- # For uncategorized images, filter by user_id to ensure per-user isolation
- # Admin users can see all uncategorized images from all users
- if user_id is not None and not is_admin:
- query_conditions += """--sql
- AND images.user_id = ?
- """
- query_params.append(user_id)
- elif board_id is not None:
- query_conditions += """--sql
- AND board_images.board_id = ?
- """
- query_params.append(board_id)
- elif user_id is not None and not is_admin:
- # No board_id supplied — still enforce per-user isolation so
- # non-admins cannot enumerate other users' images
- query_conditions += """--sql
- AND images.user_id = ?
- """
- query_params.append(user_id)
-
- # Search term condition
- if search_term:
- query_conditions += """--sql
- AND (
- images.metadata LIKE ?
- OR images.created_at LIKE ?
+ query_conditions, query_params = _build_image_query_conditions(
+ _ImageQueryFilters(
+ image_origin=image_origin,
+ categories=categories,
+ is_intermediate=is_intermediate,
+ board_id=board_id,
+ search_term=search_term,
+ created_from=created_from,
+ created_to=created_to,
+ user_id=user_id,
+ is_admin=is_admin,
)
- """
- query_params.append(f"%{search_term.lower()}%")
- query_params.append(f"%{search_term.lower()}%")
-
- # created_at is ISO text; date-only lexicographic bounds are safe for
- # both space- and T-separated stored values. created_to is inclusive,
- # hence the exclusive < next-day bound.
- if created_from:
- query_conditions += """--sql
- AND images.created_at >= ?
- """
- query_params.append(created_from)
-
- if created_to:
- query_conditions += """--sql
- AND images.created_at < DATE(?, '+1 day')
- """
- query_params.append(created_to)
+ )
if starred_first:
query_pagination = f"""--sql
@@ -462,79 +506,19 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
is_admin: bool = False,
) -> ImageNamesResult:
with self._db.transaction() as cursor:
- # Build query conditions (reused for both starred count and image names queries)
- query_conditions = ""
- query_params: list[Union[int, str, bool]] = []
-
- if image_origin is not None:
- query_conditions += """--sql
- AND images.image_origin = ?
- """
- query_params.append(image_origin.value)
-
- if categories is not None:
- category_strings = [c.value for c in set(categories)]
- placeholders = ",".join("?" * len(category_strings))
- query_conditions += f"""--sql
- AND images.image_category IN ( {placeholders} )
- """
- for c in category_strings:
- query_params.append(c)
-
- if is_intermediate is not None:
- query_conditions += """--sql
- AND images.is_intermediate = ?
- """
- query_params.append(is_intermediate)
-
- if board_id == "none":
- query_conditions += """--sql
- AND board_images.board_id IS NULL
- """
- # For uncategorized images, filter by user_id to ensure per-user isolation
- # Admin users can see all uncategorized images from all users
- if user_id is not None and not is_admin:
- query_conditions += """--sql
- AND images.user_id = ?
- """
- query_params.append(user_id)
- elif board_id is not None:
- query_conditions += """--sql
- AND board_images.board_id = ?
- """
- query_params.append(board_id)
- elif user_id is not None and not is_admin:
- # No board_id supplied — still enforce per-user isolation so
- # non-admins cannot enumerate other users' images
- query_conditions += """--sql
- AND images.user_id = ?
- """
- query_params.append(user_id)
-
- if search_term:
- query_conditions += """--sql
- AND (
- images.metadata LIKE ?
- OR images.created_at LIKE ?
+ query_conditions, query_params = _build_image_query_conditions(
+ _ImageQueryFilters(
+ image_origin=image_origin,
+ categories=categories,
+ is_intermediate=is_intermediate,
+ board_id=board_id,
+ search_term=search_term,
+ created_from=created_from,
+ created_to=created_to,
+ user_id=user_id,
+ is_admin=is_admin,
)
- """
- query_params.append(f"%{search_term.lower()}%")
- query_params.append(f"%{search_term.lower()}%")
-
- # created_at is ISO text; date-only lexicographic bounds are safe for
- # both space- and T-separated stored values. created_to is inclusive,
- # hence the exclusive < next-day bound.
- if created_from:
- query_conditions += """--sql
- AND images.created_at >= ?
- """
- query_params.append(created_from)
-
- if created_to:
- query_conditions += """--sql
- AND images.created_at < DATE(?, '+1 day')
- """
- query_params.append(created_to)
+ )
# Get starred count if starred_first is enabled
starred_count = 0
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 1bc4bdeb72..8a6cccbc4d 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -4554,10 +4554,10 @@
"type": "null"
}
],
- "description": "The board id to filter by. Use 'none' to find images without a board.",
+ "description": "The board id to filter by. Use 'none' for the current user's uncategorized images or 'all' for images on every readable, non-archived board plus authorized uncategorized images. If omitted, non-admin results remain limited to images owned by the current user.",
"title": "Board Id"
},
- "description": "The board id to filter by. Use 'none' to find images without a board."
+ "description": "The board id to filter by. Use 'none' for the current user's uncategorized images or 'all' for images on every readable, non-archived board plus authorized uncategorized images. If omitted, non-admin results remain limited to images owned by the current user."
},
{
"name": "offset",
@@ -5492,10 +5492,10 @@
"type": "null"
}
],
- "description": "The board id to filter by. Use 'none' to find images without a board.",
+ "description": "The board id to filter by. Use 'none' for the current user's uncategorized images or 'all' for images on every readable, non-archived board plus authorized uncategorized images. If omitted, non-admin results remain limited to images owned by the current user.",
"title": "Board Id"
},
- "description": "The board id to filter by. Use 'none' to find images without a board."
+ "description": "The board id to filter by. Use 'none' for the current user's uncategorized images or 'all' for images on every readable, non-archived board plus authorized uncategorized images. If omitted, non-admin results remain limited to images owned by the current user."
},
{
"name": "order_dir",
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index a8707177b1..41a80ee910 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -36443,7 +36443,7 @@ export interface operations {
categories?: components["schemas"]["ImageCategory"][] | null;
/** @description Whether to list intermediate images. */
is_intermediate?: boolean | null;
- /** @description The board id to filter by. Use 'none' to find images without a board. */
+ /** @description The board id to filter by. Use 'none' for the current user's uncategorized images or 'all' for images on every readable, non-archived board plus authorized uncategorized images. If omitted, non-admin results remain limited to images owned by the current user. */
board_id?: string | null;
/** @description The page offset */
offset?: number;
@@ -37072,7 +37072,7 @@ export interface operations {
categories?: components["schemas"]["ImageCategory"][] | null;
/** @description Whether to list intermediate images. */
is_intermediate?: boolean | null;
- /** @description The board id to filter by. Use 'none' to find images without a board. */
+ /** @description The board id to filter by. Use 'none' for the current user's uncategorized images or 'all' for images on every readable, non-archived board plus authorized uncategorized images. If omitted, non-admin results remain limited to images owned by the current user. */
board_id?: string | null;
/** @description The order of sort */
order_dir?: components["schemas"]["SQLiteDirection"];
diff --git a/invokeai/frontend/webv2/public/locales/en-GB.json b/invokeai/frontend/webv2/public/locales/en-GB.json
index 0967ef424b..2aaa0cdc42 100644
--- a/invokeai/frontend/webv2/public/locales/en-GB.json
+++ b/invokeai/frontend/webv2/public/locales/en-GB.json
@@ -1 +1,156 @@
-{}
+{
+ "commandPalette": {
+ "title": "Command palette",
+ "buttonLabel": "Command palette",
+ "buttonTooltip": "Command palette ({{hotkey}})",
+ "inputLabel": "Search commands and settings",
+ "placeholders": {
+ "root": "Search commands, settings, and more…",
+ "scope": "Search {{label}}…",
+ "stage": "Pick a value…"
+ },
+ "actions": {
+ "backToAll": "Back to all results",
+ "closeScope": "Close {{label}} — back to all results",
+ "openInSettings": "Open in Settings",
+ "openModelManager": "Open in Model Manager",
+ "revealInGallery": "Reveal in Gallery"
+ },
+ "footer": {
+ "back": "Back",
+ "close": "Close",
+ "navigate": "Navigate",
+ "pick": "Pick",
+ "run": "Run",
+ "scope": "Scope"
+ },
+ "states": {
+ "couldNotSearch": "Couldn't search {{label}}",
+ "invalidDate": "Invalid date: “{{value}}”",
+ "noItemsYet": "No {{label}} yet",
+ "noResults": "No results for “{{query}}”",
+ "partialFailure": "{{count}} results. {{failed}} searches failed.",
+ "resultCount": "{{count}} results.",
+ "retrySearch": "Retry {{label}} search",
+ "searching": "Searching…",
+ "searchingSection": "{{label}} — Searching…"
+ },
+ "date": {
+ "aWeekAgo": "A week ago",
+ "date": "Date",
+ "formatHint": "Or type a date — YYYY-MM-DD, 7d, 2w, 1m",
+ "from": "From {{date}}",
+ "pastWeek": "Past week",
+ "range": "{{from}} – {{to}}",
+ "through": "Through {{date}}",
+ "today": "Today",
+ "yesterday": "Yesterday"
+ },
+ "syntax": {
+ "commands": "Type > for commands",
+ "commandsAndDates": "Type > for commands · from:/date: to filter by date"
+ },
+ "search": {
+ "byDate": "Search {{label}} by date",
+ "forQuery": "Search {{label}} for “{{query}}”",
+ "in": "Search in",
+ "provider": "Search {{label}}…"
+ },
+ "groups": {
+ "app": "App",
+ "boards": "Boards",
+ "canvas": "Canvas",
+ "commands": "Commands",
+ "date": "Date",
+ "gallery": "Gallery",
+ "generation": "Generation",
+ "images": "Images",
+ "layout": "Layout",
+ "models": "Models",
+ "navigation": "Navigation",
+ "promptHistory": "Prompt history",
+ "queue": "Queue",
+ "queueItems": "Queue items",
+ "recent": "Recent",
+ "settings": "Settings",
+ "viewer": "Viewer",
+ "workflows": "Workflows"
+ },
+ "launchpad": {
+ "goToModels": "Go to Models",
+ "goToNodes": "Go to Nodes",
+ "goToProjects": "Go to Projects",
+ "goToUsers": "Go to Users",
+ "openEditor": "Open Editor",
+ "openSettings": "Open Settings"
+ },
+ "appEntries": {
+ "keyboardShortcuts": "Keyboard Shortcuts",
+ "openSettings": "Open Settings"
+ },
+ "providers": {
+ "boardSubtitle": "Board · {{count}} image",
+ "boardSubtitle_other": "Board · {{count}} images",
+ "defaultWorkflow": "Default workflow",
+ "images": "Images",
+ "models": "Models",
+ "noTitle": "Untitled generation",
+ "promptHistory": "Prompt history",
+ "queueItems": "Queue items",
+ "uncategorized": "Uncategorized",
+ "workflow": "Workflow",
+ "workflows": "Workflows"
+ },
+ "queueStatuses": {
+ "canceled": "Canceled",
+ "completed": "Completed",
+ "failed": "Failed",
+ "in_progress": "In progress",
+ "pending": "Pending",
+ "waiting": "Waiting"
+ },
+ "settings": {
+ "current": "Current",
+ "off": "Off",
+ "on": "On",
+ "sections": {
+ "appearance": "Appearance",
+ "behavior": "Behavior",
+ "developer": "Developer",
+ "hotkeys": "Hotkeys",
+ "project": "Project",
+ "queue": "Queue",
+ "workflow": "Workflow",
+ "workspace": "Workspace"
+ },
+ "settingsSection": "Settings: {{section}}",
+ "toggles": {
+ "confirmImageDeletion": "Confirm Image Deletion",
+ "developerLogEnabled": "Developer Logging",
+ "enableInformationalPopovers": "Informational Popovers",
+ "enableModelDescriptions": "Model Descriptions",
+ "reduceMotion": "Reduce Motion",
+ "showFocusRegionHighlight": "Show Focus Region Highlight",
+ "workflowShowMinimap": "Show Workflow Minimap",
+ "workflowSnapToGrid": "Snap Workflow Nodes to Grid",
+ "workflowValidateConnections": "Validate Workflow Connections"
+ },
+ "values": {
+ "activeProject": "Active Project",
+ "allProjects": "All Projects",
+ "curved": "Curved",
+ "language": "Language",
+ "queueJobsScope": "Queue Jobs Scope",
+ "square": "Square",
+ "theme": "Theme",
+ "workflowEdgeStyle": "Workflow Edge Style"
+ }
+ },
+ "workflowLoad": {
+ "couldNotLoad": "Could not load the workflow.",
+ "failed": "Failed to load workflow",
+ "loaded": "Loaded “{{name}}” from library",
+ "warning": "Workflow load warning"
+ }
+ }
+}
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 2f7fecdb45..a183f2f5b5 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1,4 +1,158 @@
{
+ "commandPalette": {
+ "title": "Command palette",
+ "buttonLabel": "Command palette",
+ "buttonTooltip": "Command palette ({{hotkey}})",
+ "inputLabel": "Search commands and settings",
+ "placeholders": {
+ "root": "Search commands, settings, and more…",
+ "scope": "Search {{label}}…",
+ "stage": "Pick a value…"
+ },
+ "actions": {
+ "backToAll": "Back to all results",
+ "closeScope": "Close {{label}} — back to all results",
+ "openInSettings": "Open in Settings",
+ "openModelManager": "Open in Model Manager",
+ "revealInGallery": "Reveal in Gallery"
+ },
+ "footer": {
+ "back": "Back",
+ "close": "Close",
+ "navigate": "Navigate",
+ "pick": "Pick",
+ "run": "Run",
+ "scope": "Scope"
+ },
+ "states": {
+ "couldNotSearch": "Couldn't search {{label}}",
+ "invalidDate": "Invalid date: “{{value}}”",
+ "noItemsYet": "No {{label}} yet",
+ "noResults": "No results for “{{query}}”",
+ "partialFailure": "{{count}} results. {{failed}} searches failed.",
+ "resultCount": "{{count}} results.",
+ "retrySearch": "Retry {{label}} search",
+ "searching": "Searching…",
+ "searchingSection": "{{label}} — Searching…"
+ },
+ "date": {
+ "aWeekAgo": "A week ago",
+ "date": "Date",
+ "formatHint": "Or type a date — YYYY-MM-DD, 7d, 2w, 1m",
+ "from": "From {{date}}",
+ "pastWeek": "Past week",
+ "range": "{{from}} – {{to}}",
+ "through": "Through {{date}}",
+ "today": "Today",
+ "yesterday": "Yesterday"
+ },
+ "syntax": {
+ "commands": "Type > for commands",
+ "commandsAndDates": "Type > for commands · from:/date: to filter by date"
+ },
+ "search": {
+ "byDate": "Search {{label}} by date",
+ "forQuery": "Search {{label}} for “{{query}}”",
+ "in": "Search in",
+ "provider": "Search {{label}}…"
+ },
+ "groups": {
+ "app": "App",
+ "boards": "Boards",
+ "canvas": "Canvas",
+ "commands": "Commands",
+ "date": "Date",
+ "gallery": "Gallery",
+ "generation": "Generation",
+ "images": "Images",
+ "layout": "Layout",
+ "models": "Models",
+ "navigation": "Navigation",
+ "promptHistory": "Prompt history",
+ "queue": "Queue",
+ "queueItems": "Queue items",
+ "recent": "Recent",
+ "settings": "Settings",
+ "viewer": "Viewer",
+ "workflows": "Workflows"
+ },
+ "launchpad": {
+ "goToModels": "Go to Models",
+ "goToNodes": "Go to Nodes",
+ "goToProjects": "Go to Projects",
+ "goToUsers": "Go to Users",
+ "openEditor": "Open Editor",
+ "openSettings": "Open Settings"
+ },
+ "appEntries": {
+ "keyboardShortcuts": "Keyboard Shortcuts",
+ "openSettings": "Open Settings"
+ },
+ "providers": {
+ "boardSubtitle": "Board · {{count}} image",
+ "boardSubtitle_other": "Board · {{count}} images",
+ "defaultWorkflow": "Default workflow",
+ "images": "Images",
+ "models": "Models",
+ "noTitle": "Untitled generation",
+ "promptHistory": "Prompt history",
+ "queueItems": "Queue items",
+ "uncategorized": "Uncategorized",
+ "workflow": "Workflow",
+ "workflows": "Workflows"
+ },
+ "queueStatuses": {
+ "canceled": "Canceled",
+ "completed": "Completed",
+ "failed": "Failed",
+ "in_progress": "In progress",
+ "pending": "Pending",
+ "waiting": "Waiting"
+ },
+ "settings": {
+ "current": "Current",
+ "off": "Off",
+ "on": "On",
+ "sections": {
+ "appearance": "Appearance",
+ "behavior": "Behavior",
+ "developer": "Developer",
+ "hotkeys": "Hotkeys",
+ "project": "Project",
+ "queue": "Queue",
+ "workflow": "Workflow",
+ "workspace": "Workspace"
+ },
+ "settingsSection": "Settings: {{section}}",
+ "toggles": {
+ "confirmImageDeletion": "Confirm Image Deletion",
+ "developerLogEnabled": "Developer Logging",
+ "enableInformationalPopovers": "Informational Popovers",
+ "enableModelDescriptions": "Model Descriptions",
+ "reduceMotion": "Reduce Motion",
+ "showFocusRegionHighlight": "Show Focus Region Highlight",
+ "workflowShowMinimap": "Show Workflow Minimap",
+ "workflowSnapToGrid": "Snap Workflow Nodes to Grid",
+ "workflowValidateConnections": "Validate Workflow Connections"
+ },
+ "values": {
+ "activeProject": "Active Project",
+ "allProjects": "All Projects",
+ "curved": "Curved",
+ "language": "Language",
+ "queueJobsScope": "Queue Jobs Scope",
+ "square": "Square",
+ "theme": "Theme",
+ "workflowEdgeStyle": "Workflow Edge Style"
+ }
+ },
+ "workflowLoad": {
+ "couldNotLoad": "Could not load the workflow.",
+ "failed": "Failed to load workflow",
+ "loaded": "Loaded “{{name}}” from library",
+ "warning": "Workflow load warning"
+ }
+ },
"common": {
"actions": "Actions",
"active": "Active",
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
index 845c80b09a..d3d8f5e643 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
@@ -163,6 +163,8 @@ describe('feature public-interface registry', () => {
]);
expect(checkDependency('workbench/shell/View.tsx', '@features/identity')).toEqual([]);
expect(checkDependency('workbench/palette/paletteProviders.ts', '@features/workflow/queries')).toEqual([]);
+ expect(checkDependency('workbench/palette/paletteProviders.ts', '@features/workflow/paletteSearch')).toEqual([]);
+ expect(checkDependency('workbench/palette/paletteProviders.ts', '@features/gallery/paletteSearch')).toEqual([]);
expect(checkDependency('workbench/palette/paletteProviders.ts', '@features/queue/queries')).toEqual([]);
expect(checkDependency('features/gallery/ui/View.tsx', '@features/queue/publicApi')).toMatchObject([
{ rule: 'feature-public-interface' },
diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
index 871d00f9b8..807dc8a449 100644
--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
@@ -5,12 +5,12 @@
* To publish a new entry module, add it here and cover it in dependencyPolicy.test.ts.
*/
export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string[]>> = {
- gallery: ['contracts', 'queries', 'react', 'utility', 'widget'],
+ gallery: ['contracts', 'paletteSearch', 'queries', 'react', 'utility', 'widget'],
generation: ['components', 'contracts', 'graph', 'react', 'settings', 'widget'],
identity: [],
models: ['react'],
nodes: [],
- queue: ['contracts', 'menu', 'queries', 'react', 'reveal', 'utility', 'widget'],
+ queue: ['contracts', 'menu', 'paletteSearch', 'queries', 'react', 'reveal', 'utility', 'widget'],
upscale: ['widget'],
- workflow: ['contracts', 'graph', 'preview', 'queries', 'react', 'utility', 'widget'],
+ workflow: ['contracts', 'graph', 'paletteSearch', 'preview', 'queries', 'react', 'utility', 'widget'],
};
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
index 96e78aa762..df511f939b 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
@@ -96,6 +96,22 @@ describe('listGalleryImages created-at range', () => {
expect(params.get('created_to')).toBe('2026-07-15');
});
+ it('sends the explicit all-readable scope and forwards cancellation', async () => {
+ const controller = new AbortController();
+
+ await listGalleryImages({
+ boardId: 'all',
+ galleryView: 'images',
+ searchTerm: 'sunset',
+ signal: controller.signal,
+ });
+
+ const [url, init] = mocks.apiFetchJson.mock.calls[0] as [string, RequestInit];
+ const params = new URLSearchParams(url.split('?')[1]);
+ expect(params.get('board_id')).toBe('all');
+ expect(init.signal).toBe(controller.signal);
+ });
+
it('omits the range params when no range is given', async () => {
await listGalleryImages({ boardId: 'board-1', galleryView: 'images', searchTerm: 'sunset' });
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index 2972ac1bad..788e7e3a23 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -31,6 +31,7 @@ interface BackendBoardDTO {
* grouping images by creation date (id 'by_date:YYYY-MM-DD').
*/
const DATE_BOARD_ID_PREFIX = 'by_date:';
+export const ALL_READABLE_BOARDS_ID = 'all';
export const isDateBoardId = (boardId: string): boolean => boardId.startsWith(DATE_BOARD_ID_PREFIX);
@@ -93,7 +94,15 @@ const mapBoard = (board: BackendBoardDTO): GalleryBoard => ({
ownerName: board.owner_username ?? null,
});
-const getGalleryTotal = async ({ boardId, categories }: { boardId: string; categories: string[] }): Promise<number> => {
+const getGalleryTotal = async ({
+ boardId,
+ categories,
+ signal,
+}: {
+ boardId: string;
+ categories: string[];
+ signal?: AbortSignal;
+}): Promise<number> => {
const query = toSearchParams({
board_id: boardId,
categories,
@@ -101,7 +110,7 @@ const getGalleryTotal = async ({ boardId, categories }: { boardId: string; categ
limit: 0,
offset: 0,
});
- const body = await apiFetchJson<Pick<ListImagesResponse, 'total'>>(`/api/v1/images/?${query}`);
+ const body = await apiFetchJson<Pick<ListImagesResponse, 'total'>>(`/api/v1/images/?${query}`, { signal });
return body.total;
};
@@ -126,10 +135,12 @@ export const listGalleryBoards = async ({
includeArchived = false,
orderBy = 'created_at',
orderDir = 'DESC',
+ signal,
}: {
includeArchived?: boolean;
orderBy?: GalleryBoardOrderBy;
orderDir?: GalleryOrderDir;
+ signal?: AbortSignal;
} = {}): Promise<GalleryBoard[]> => {
const boardsQuery = toSearchParams({
all: true,
@@ -138,13 +149,14 @@ export const listGalleryBoards = async ({
order_by: orderBy,
});
const boardsBodyPromise = apiFetchJson<BackendBoardDTO[] | { items?: BackendBoardDTO[] }>(
- `/api/v1/boards/?${boardsQuery}`
+ `/api/v1/boards/?${boardsQuery}`,
+ { signal }
);
const [body, uncategorizedImageCount, uncategorizedAssetCount] = await Promise.all([
boardsBodyPromise,
- getGalleryTotal({ boardId: 'none', categories: imageCategories }),
- getGalleryTotal({ boardId: 'none', categories: assetCategories }),
+ getGalleryTotal({ boardId: 'none', categories: imageCategories, signal }),
+ getGalleryTotal({ boardId: 'none', categories: assetCategories, signal }),
]);
const boards = Array.isArray(body) ? body : (body.items ?? []);
@@ -217,6 +229,7 @@ const listGalleryDateBoardImages = async ({
offset,
orderDir,
searchTerm,
+ signal,
starredFirst,
}: {
boardId: string;
@@ -227,6 +240,7 @@ const listGalleryDateBoardImages = async ({
offset: number;
orderDir: GalleryOrderDir;
searchTerm: string;
+ signal?: AbortSignal;
starredFirst: boolean;
}): Promise<GalleryImagesPage> => {
// The board already pins a single day; a date filter either contains that
@@ -245,7 +259,8 @@ const listGalleryDateBoardImages = async ({
starred_first: starredFirst,
});
const body = await apiFetchJson<{ image_names: string[]; total_count: number }>(
- `/api/v1/virtual_boards/by_date/${encodeURIComponent(getDateFromBoardId(boardId))}/image_names?${query}`
+ `/api/v1/virtual_boards/by_date/${encodeURIComponent(getDateFromBoardId(boardId))}/image_names?${query}`,
+ { signal }
);
const images = await getGalleryImagesByNames(body.image_names.slice(offset, offset + limit));
@@ -261,10 +276,10 @@ export const listGalleryImages = async ({
offset = 0,
orderDir = 'DESC',
searchTerm,
+ signal,
starredFirst = false,
}: {
- /** Omit to list across every board the user can see. */
- boardId?: string;
+ boardId: string;
createdFrom?: string;
createdTo?: string;
galleryView: GalleryView;
@@ -272,6 +287,7 @@ export const listGalleryImages = async ({
offset?: number;
orderDir?: GalleryOrderDir;
searchTerm: string;
+ signal?: AbortSignal;
starredFirst?: boolean;
}): Promise<GalleryImagesPage> => {
if (boardId !== undefined && isDateBoardId(boardId)) {
@@ -284,6 +300,7 @@ export const listGalleryImages = async ({
offset,
orderDir,
searchTerm,
+ signal,
starredFirst,
});
}
@@ -300,7 +317,7 @@ export const listGalleryImages = async ({
search_term: searchTerm.trim() || undefined,
starred_first: starredFirst,
});
- const body = await apiFetchJson<ListImagesResponse | BackendImageDTO[]>(`/api/v1/images/?${query}`);
+ const body = await apiFetchJson<ListImagesResponse | BackendImageDTO[]>(`/api/v1/images/?${query}`, { signal });
const items = Array.isArray(body) ? body : (body.items ?? []);
return {
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
index ba6052f8a3..53505be2f9 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
@@ -13,8 +13,7 @@ export interface GalleryBoardsQuery {
}
export interface GalleryImagesQuery {
- /** Omit to search across every board the user can see. */
- boardId?: string;
+ boardId: string;
/** Inclusive lower-bound calendar day (YYYY-MM-DD) on created_at. */
createdFrom?: string;
/** Inclusive upper-bound calendar day (YYYY-MM-DD) on created_at. */
@@ -36,9 +35,9 @@ export const galleryKeys = {
export const galleryBoardsOptions = (query: GalleryBoardsQuery = {}) =>
queryOptions({
- queryFn: async () => {
+ queryFn: async ({ signal }) => {
const [boards, dateBoards] = await Promise.all([
- listGalleryBoards(query),
+ listGalleryBoards({ ...query, signal }),
query.includeDateBoards ? listGalleryDateBoards() : Promise.resolve([]),
]);
@@ -50,7 +49,7 @@ export const galleryBoardsOptions = (query: GalleryBoardsQuery = {}) =>
export const galleryImagesOptions = (query: GalleryImagesQuery) =>
queryOptions({
- queryFn: () => listGalleryImages(query),
+ queryFn: ({ signal }) => listGalleryImages({ ...query, signal }),
queryKey: galleryKeys.images(query),
staleTime: 60_000,
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/paletteSearch.ts b/invokeai/frontend/webv2/src/features/gallery/paletteSearch.ts
new file mode 100644
index 0000000000..b1bace27fb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/paletteSearch.ts
@@ -0,0 +1,2 @@
+/** Cancellable gallery reads used by deferred cross-feature search surfaces. */
+export { ALL_READABLE_BOARDS_ID, listGalleryBoards, listGalleryImages } from './data/backend';
diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.ts
index 4f10c268a0..47277213a2 100644
--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts
@@ -1,2 +1,3 @@
export { galleryBoardsOptions, galleryImagesOptions, galleryKeys } from './data/queries';
export type { GalleryBoardsQuery, GalleryImagesQuery } from './data/queries';
+export { ALL_READABLE_BOARDS_ID, listGalleryBoards, listGalleryImages } from './data/backend';
diff --git a/invokeai/frontend/webv2/src/features/queue/paletteSearch.ts b/invokeai/frontend/webv2/src/features/queue/paletteSearch.ts
new file mode 100644
index 0000000000..c8b1573af0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/paletteSearch.ts
@@ -0,0 +1,16 @@
+import type { QueueQueryScope, QueueReadModel } from './core/types';
+
+import { queueBackend } from './data/httpRealtimeQueueBackend';
+
+/** Reads the bounded queue model used by deferred command-palette search. */
+export const loadPaletteQueueReadModel = async (scope: QueueQueryScope): Promise<QueueReadModel> => {
+ const [status, current, next, idsResult] = await Promise.all([
+ queueBackend.readStatus(scope),
+ queueBackend.readCurrent(scope),
+ queueBackend.readNext(scope),
+ queueBackend.readItemIds('desc', scope),
+ ]);
+ const items = await queueBackend.readItemsById(idsResult.itemIds.slice(0, 50));
+
+ return { current, items, next, scope, status };
+};
diff --git a/invokeai/frontend/webv2/src/features/queue/ui/NowNextSection.tsx b/invokeai/frontend/webv2/src/features/queue/ui/NowNextSection.tsx
index 61671dc4d7..72dee75bba 100644
--- a/invokeai/frontend/webv2/src/features/queue/ui/NowNextSection.tsx
+++ b/invokeai/frontend/webv2/src/features/queue/ui/NowNextSection.tsx
@@ -1,12 +1,14 @@
import { Stack } from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
+import type { QueueItemRevealRequest } from './queueUiStore';
+
import { useCurrentBatchItems } from './queueDataStore';
import { QueueItemRow } from './QueueItemRow';
import { SectionHeader } from './SectionHeader';
/** CURRENT BATCH — the running item plus every pending item in the same backend batch. */
-export const CurrentBatchSection = () => {
+export const CurrentBatchSection = ({ revealRequest = null }: { revealRequest?: QueueItemRevealRequest | null }) => {
const { t } = useTranslation();
const items = useCurrentBatchItems();
const count = items.length;
@@ -20,7 +22,11 @@ export const CurrentBatchSection = () => {
<SectionHeader count={count} title={t('widgets.queue.currentBatch')} />
<Stack gap="1">
{items.map((item) => (
- <QueueItemRow key={item.id} item={item} />
+ <QueueItemRow
+ key={item.id}
+ item={item}
+ revealRequest={item.id === revealRequest?.itemId ? revealRequest : null}
+ />
))}
</Stack>
</Stack>
diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx
index 4a73563ea9..ee10142df7 100644
--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx
@@ -62,7 +62,7 @@ const QueueContent = () => {
<Stack gap="3" p="3">
<QueueStats />
<QueueFilterTabs value={filter} onChange={setFilter} />
- <CurrentBatchSection />
+ <CurrentBatchSection revealRequest={revealRequest} />
<RecentSection filter={filter} revealRequest={revealRequest} />
</Stack>
);
diff --git a/invokeai/frontend/webv2/src/features/queue/ui/RecentSection.tsx b/invokeai/frontend/webv2/src/features/queue/ui/RecentSection.tsx
index e6b3eefda2..8398f28ce2 100644
--- a/invokeai/frontend/webv2/src/features/queue/ui/RecentSection.tsx
+++ b/invokeai/frontend/webv2/src/features/queue/ui/RecentSection.tsx
@@ -36,7 +36,8 @@ export const RecentSection = ({
const cannotReveal =
revealRequest !== null &&
loadState === 'loaded' &&
- (excluded.has(revealRequest.itemId) || !items.some((item) => item.id === revealRequest.itemId));
+ !excluded.has(revealRequest.itemId) &&
+ !items.some((item) => item.id === revealRequest.itemId);
return (
<Stack gap="2">
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/api.ts b/invokeai/frontend/webv2/src/features/workflow/data/api.ts
index 59b45b06f6..0752e0ce18 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/api.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/api.ts
@@ -32,6 +32,7 @@ export interface ListWorkflowsParams {
page: number;
perPage?: number;
query?: string;
+ signal?: AbortSignal;
}
export const listLibraryWorkflows = ({
@@ -39,6 +40,7 @@ export const listLibraryWorkflows = ({
page,
perPage = 20,
query,
+ signal,
}: ListWorkflowsParams): Promise<WorkflowLibraryPage> => {
const params = new URLSearchParams({
direction: 'DESC',
@@ -53,7 +55,7 @@ export const listLibraryWorkflows = ({
params.set('query', query.trim());
}
- return apiFetchJson<WorkflowLibraryPage>(`/api/v1/workflows/?${params.toString()}`);
+ return apiFetchJson<WorkflowLibraryPage>(`/api/v1/workflows/?${params.toString()}`, { signal });
};
interface WorkflowRecordDTO {
diff --git a/invokeai/frontend/webv2/src/features/workflow/paletteSearch.ts b/invokeai/frontend/webv2/src/features/workflow/paletteSearch.ts
new file mode 100644
index 0000000000..99d5f4d7fc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/paletteSearch.ts
@@ -0,0 +1,45 @@
+import { apiFetchJson } from '@platform/transport/http';
+
+interface WorkflowLibraryListItem {
+ workflow_id: string;
+ name: string;
+ description: string;
+ category: 'user' | 'default';
+ tags?: string | null;
+}
+
+interface WorkflowLibraryPage {
+ items: WorkflowLibraryListItem[];
+ page: number;
+ pages: number;
+ total: number;
+}
+
+/** Cancellable workflow-library read used by deferred cross-feature search surfaces. */
+export const listLibraryWorkflows = ({
+ category,
+ page,
+ perPage = 20,
+ query,
+ signal,
+}: {
+ category: 'user' | 'default';
+ page: number;
+ perPage?: number;
+ query?: string;
+ signal?: AbortSignal;
+}): Promise<WorkflowLibraryPage> => {
+ const params = new URLSearchParams({
+ direction: 'DESC',
+ order_by: 'updated_at',
+ page: String(page),
+ per_page: String(perPage),
+ });
+
+ params.append('categories', category);
+ if (query?.trim()) {
+ params.set('query', query.trim());
+ }
+
+ return apiFetchJson<WorkflowLibraryPage>(`/api/v1/workflows/?${params.toString()}`, { signal });
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
index c3095caf7d..d4774ea98b 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
@@ -4,6 +4,7 @@ import { useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContex
import { parseWorkflowJson } from '@features/workflow/utility';
import { useMountEffect } from '@platform/react/useMountEffect';
import { getApiErrorMessage } from '@platform/transport/http';
+import { useTranslation } from 'react-i18next';
import { startWorkflowUiPendingLoadRuntime } from './pendingLibraryWorkflowLoadRuntime';
@@ -14,6 +15,7 @@ import { startWorkflowUiPendingLoadRuntime } from './pendingLibraryWorkflowLoadR
* load path as WorkflowLibraryDialog, minus the dialog.
*/
export const PendingLibraryWorkflowLoader = () => {
+ const { t } = useTranslation();
const { replace } = useProjectGraphCommands();
const notify = useWorkflowNotifications();
useMountEffect(() =>
@@ -23,17 +25,20 @@ export const PendingLibraryWorkflowLoader = () => {
const { document, warnings } = parseWorkflowJson(raw);
const name = typeof raw.name === 'string' && raw.name.length > 0 ? raw.name : 'workflow';
- replace(document, `Loaded "${name}" from library`);
+ replace(document, t('commandPalette.workflowLoad.loaded', { name }));
for (const warning of warnings) {
- notify.info('Workflow load warning', warning);
+ notify.info(t('commandPalette.workflowLoad.warning'), warning);
}
void touchLibraryWorkflowOpenedAt(workflowId).catch(() => {
// Recency bookkeeping only; loading already succeeded.
});
} catch (error) {
- notify.error('Failed to load workflow', getApiErrorMessage(error, 'Could not load the workflow.'));
+ notify.error(
+ t('commandPalette.workflowLoad.failed'),
+ getApiErrorMessage(error, t('commandPalette.workflowLoad.couldNotLoad'))
+ );
}
})
);
diff --git a/invokeai/frontend/webv2/src/platform/search/dateTokens.test.ts b/invokeai/frontend/webv2/src/platform/search/dateTokens.test.ts
index 9c6934c3ee..b8733089b3 100644
--- a/invokeai/frontend/webv2/src/platform/search/dateTokens.test.ts
+++ b/invokeai/frontend/webv2/src/platform/search/dateTokens.test.ts
@@ -186,6 +186,7 @@ describe('formatIsoDate / formatDateRangeLabel', () => {
// A UTC-based Date('2026-07-21') would render Jul 20 in negative offsets;
// parts-based construction must always yield the written day.
expect(formatIsoDate('2026-07-21', 'en-US')).toBe('Jul 21');
+ expect(formatIsoDate('2026-07-21', 'de-DE')).toBe('21. Juli');
});
it('covers all four range shapes', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/extensions/extensionRegistry.ts b/invokeai/frontend/webv2/src/workbench/extensions/extensionRegistry.ts
index 24fda27f46..5dcc321291 100644
--- a/invokeai/frontend/webv2/src/workbench/extensions/extensionRegistry.ts
+++ b/invokeai/frontend/webv2/src/workbench/extensions/extensionRegistry.ts
@@ -96,7 +96,15 @@ export const createExtensionRegistry = (): ExtensionRegistry => {
},
search: {
registerProvider(provider) {
- return stores.search.register(provider, getWidgetContributionRegistrationKey(provider.id, provider.source));
+ // Each registration gets a fresh identity. Consumers can distinguish a
+ // replacement even when an extension reuses its id/source and omits a
+ // contextKey.
+ const registration = { ...provider };
+
+ return stores.search.register(
+ registration,
+ getWidgetContributionRegistrationKey(registration.id, registration.source)
+ );
},
},
stores,
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
index 3888dd3d3b..620c0e90d8 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
@@ -134,13 +134,16 @@ export const useRegisterFirstPartyCommands = () => {
}
});
+ useMountEffect(() =>
+ commandApi.register({
+ handler: toggleCommandPalette,
+ id: 'app.openCommandPalette',
+ title: 'Open Command Palette',
+ })
+ );
+
useEffect(() => {
const disposers = [
- commandApi.register({
- handler: toggleCommandPalette,
- id: 'app.openCommandPalette',
- title: 'Open Command Palette',
- }),
commandApi.register({ handler: submitInvocation, id: 'app.invoke', title: 'Invoke' }),
commandApi.register({ handler: submitInvocation, id: 'app.invokeFront', title: 'Invoke front' }),
commandApi.register({
diff --git a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx
index 3f8914b400..1ab6a45a3d 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx
@@ -1,18 +1,71 @@
import { ChakraProvider } from '@chakra-ui/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
+import i18n from 'i18next';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
import type { PaletteEntry, PaletteSearchProvider } from './entries';
import { CommandPaletteDialog } from './CommandPaletteDialog';
+import { closeCommandPalette, openCommandPalette, useIsCommandPaletteOpen } from './paletteStore';
let host: HTMLDivElement | null = null;
let root: Root | null = null;
+let diagnostics: string[] = [];
+let consoleErrorSpy: ReturnType<typeof vi.spyOn> | null = null;
+let consoleWarnSpy: ReturnType<typeof vi.spyOn> | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const i18nReady = fetch('/locales/en.json')
+ .then((response) => response.json())
+ .then((translation) =>
+ i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ interpolation: { escapeValue: false },
+ lng: 'en',
+ resources: { en: { translation } },
+ })
+ );
+
+const waitFor = async <Value,>(assertion: () => Value): Promise<Value> => {
+ let value: Value | undefined;
+
+ await act(async () => {
+ value = await vi.waitFor(assertion);
+ });
+
+ return value as Value;
+};
+
+const waitForDebounce = () =>
+ act(
+ () =>
+ new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 250);
+ })
+ );
+
+const formatDiagnostic = (value: unknown): string =>
+ value instanceof Error ? (value.stack ?? value.message) : String(value);
+const onPageError = (event: ErrorEvent) =>
+ diagnostics.push(`page error: ${formatDiagnostic(event.error ?? event.message)}`);
+const onUnhandledRejection = (event: PromiseRejectionEvent) =>
+ diagnostics.push(`unhandled rejection: ${formatDiagnostic(event.reason)}`);
+
+beforeEach(() => {
+ diagnostics = [];
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation((...args) => {
+ diagnostics.push(`console.error: ${args.map(formatDiagnostic).join(' ')}`);
+ });
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation((...args) => {
+ diagnostics.push(`console.warn: ${args.map(formatDiagnostic).join(' ')}`);
+ });
+ window.addEventListener('error', onPageError);
+ window.addEventListener('unhandledrejection', onUnhandledRejection);
+});
const entry = (id: string, title: string, run = vi.fn()): PaletteEntry => ({
group: 'Commands',
@@ -23,6 +76,23 @@ const entry = (id: string, title: string, run = vi.fn()): PaletteEntry => ({
title,
});
+const storeHostEntries = [entry('first', 'First command')];
+
+const StorePaletteHost = () => {
+ const isOpen = useIsCommandPaletteOpen();
+
+ return (
+ <>
+ <button type="button" onClick={openCommandPalette}>
+ Open palette
+ </button>
+ {isOpen ? (
+ <CommandPaletteDialog entries={storeHostEntries} isOpen modifierKeyLabel="ctrl" onClose={closeCommandPalette} />
+ ) : null}
+ </>
+ );
+};
+
const renderPalette = async ({
entries,
onClose = vi.fn(),
@@ -32,27 +102,33 @@ const renderPalette = async ({
onClose?: () => void;
providers?: PaletteSearchProvider[];
}) => {
+ await i18nReady;
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
- await act(() => {
+ await act(async () => {
root?.render(
- <ChakraProvider value={system}>
- <QueryClientProvider client={new QueryClient()}>
- <CommandPaletteDialog
- entries={entries}
- isOpen
- modifierKeyLabel="ctrl"
- providers={providers}
- onClose={onClose}
- />
- </QueryClientProvider>
- </ChakraProvider>
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={new QueryClient()}>
+ <CommandPaletteDialog
+ entries={entries}
+ isOpen
+ modifierKeyLabel="ctrl"
+ providers={providers}
+ onClose={onClose}
+ />
+ </QueryClientProvider>
+ </ChakraProvider>
+ </I18nextProvider>
);
+ await new Promise<void>((resolve) => {
+ requestAnimationFrame(() => resolve());
+ });
});
- const input = await vi.waitFor(() => {
+ const input = await waitFor(() => {
const node = document.querySelector<HTMLInputElement>('[name="command-palette-query"]');
expect(node).not.toBeNull();
return node!;
@@ -62,14 +138,63 @@ const renderPalette = async ({
};
afterEach(async () => {
- await act(() => root?.unmount());
+ await act(async () => {
+ await new Promise<void>((resolve) => {
+ requestAnimationFrame(() => resolve());
+ });
+ root?.unmount();
+ await Promise.resolve();
+ });
host?.remove();
host = null;
root = null;
window.localStorage.clear();
+ window.removeEventListener('error', onPageError);
+ window.removeEventListener('unhandledrejection', onUnhandledRejection);
+ consoleErrorSpy?.mockRestore();
+ consoleWarnSpy?.mockRestore();
+ consoleErrorSpy = null;
+ consoleWarnSpy = null;
+ closeCommandPalette();
+ expect(diagnostics, diagnostics.join('\n\n')).toEqual([]);
});
describe('CommandPaletteDialog interaction', () => {
+ it('restores focus through the store-driven host lifecycle and preserves the first return target', async () => {
+ await i18nReady;
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(async () => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={new QueryClient()}>
+ <StorePaletteHost />
+ </QueryClientProvider>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ await new Promise<void>((resolve) => {
+ requestAnimationFrame(() => resolve());
+ });
+ });
+ const button = document.querySelector<HTMLButtonElement>('button');
+ expect(button).not.toBeNull();
+
+ await act(() => userEvent.click(button!));
+ const input = await waitFor(() => {
+ const node = document.querySelector<HTMLInputElement>('[name="command-palette-query"]');
+ expect(node).not.toBeNull();
+ return node!;
+ });
+ expect(document.activeElement).toBe(input);
+
+ await act(() => openCommandPalette());
+ await act(() => userEvent.keyboard('{Escape}'));
+ await waitFor(() => expect(document.activeElement).toBe(button));
+ });
+
it('exposes an accessible focused search field and runs the stable highlighted command in bare > mode', async () => {
const firstRun = vi.fn();
const secondRun = vi.fn();
@@ -104,9 +229,7 @@ describe('CommandPaletteDialog interaction', () => {
expect(document.body.textContent).toContain('Second command');
expect(document.body.textContent).not.toContain('Hidden setting');
- await new Promise((resolve) => {
- globalThis.setTimeout(resolve, 250);
- });
+ await waitForDebounce();
expect(providerSearch).not.toHaveBeenCalled();
await act(() => userEvent.keyboard('{ArrowDown}{Enter}'));
@@ -126,7 +249,7 @@ describe('CommandPaletteDialog interaction', () => {
await act(() => userEvent.fill(input, 'zz'));
await act(() => userEvent.keyboard('{Tab}'));
- const retry = await vi.waitFor(() => {
+ const retry = await waitFor(() => {
const node = [...document.querySelectorAll('button')].find((button) => button.textContent === 'Retry');
expect(node).toBeDefined();
return node!;
@@ -136,7 +259,95 @@ describe('CommandPaletteDialog interaction', () => {
expect(document.activeElement).toBe(retry);
await act(() => userEvent.click(retry));
- await vi.waitFor(() => expect(document.activeElement).toBe(input));
+ await waitFor(() => expect(document.activeElement).toBe(input));
+ });
+
+ it('keeps successful root sections and retries only a failed provider', async () => {
+ const retryResult = entry('recovered', 'Recovered result');
+ const failedSearch = vi.fn().mockRejectedValueOnce(new Error('failed')).mockResolvedValueOnce([retryResult]);
+ const successfulSearch = vi.fn(() => [entry('success', 'Successful result')]);
+ const providers: PaletteSearchProvider[] = [
+ { contextKey: 'failed', label: 'Broken', providerKey: 'broken', search: failedSearch },
+ { contextKey: 'success', label: 'Working', providerKey: 'working', search: successfulSearch },
+ ];
+ const { input, onClose } = await renderPalette({ entries: [], providers });
+
+ await act(() => userEvent.fill(input, 'zz'));
+ await waitForDebounce();
+ const retryOption = await waitFor(() => {
+ expect(document.body.textContent).toContain('Successful result');
+ const node = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find((option) =>
+ option.textContent?.includes('Retry broken search')
+ );
+ expect(node).toBeDefined();
+ return node!;
+ });
+
+ await act(() => userEvent.click(retryOption));
+ await waitFor(() => expect(document.body.textContent).toContain('Recovered result'));
+ expect(failedSearch).toHaveBeenCalledTimes(2);
+ expect(successfulSearch).toHaveBeenCalledTimes(1);
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it('marks the listbox busy while a provider is pending and announces completion', async () => {
+ let resolveSearch: ((entries: PaletteEntry[]) => void) | undefined;
+ const search = vi.fn(
+ () =>
+ new Promise<PaletteEntry[]>((resolve) => {
+ resolveSearch = resolve;
+ })
+ );
+ const { input } = await renderPalette({
+ entries: [],
+ providers: [{ contextKey: 'pending', label: 'Entities', providerKey: 'entities', search }],
+ });
+
+ await act(() => userEvent.fill(input, 'zz'));
+ const listbox = await waitFor(() => {
+ const node = document.querySelector<HTMLElement>('[role="listbox"]');
+ expect(node?.getAttribute('aria-busy')).toBe('true');
+ expect(document.body.textContent).toContain('Searching…');
+ return node!;
+ });
+
+ await waitForDebounce();
+ await waitFor(() => expect(search).toHaveBeenCalledOnce());
+ await act(() => resolveSearch?.([entry('found', 'Found result')]));
+ await waitFor(() => expect(listbox.getAttribute('aria-busy')).toBe('false'));
+ expect(document.body.textContent).toContain('1 results.');
+ });
+
+ it('does not expose or activate provider entries from the pre-debounce query', async () => {
+ const oldRun = vi.fn();
+ const search = vi.fn((query: { text: string }) =>
+ query.text === 'old' ? [entry('old-result', 'Old result', oldRun)] : []
+ );
+ const { input } = await renderPalette({
+ entries: [],
+ providers: [{ contextKey: 'context', label: 'Entities', providerKey: 'entities', search }],
+ });
+
+ await act(() => userEvent.fill(input, 'old'));
+ await waitForDebounce();
+ await waitFor(() => expect(document.body.textContent).toContain('Old result'));
+
+ await act(() => userEvent.fill(input, 'new'));
+ expect(document.body.textContent).not.toContain('Old result');
+ await act(() => userEvent.keyboard('{Enter}'));
+ expect(oldRun).not.toHaveBeenCalled();
+ });
+
+ it('renders no interactive descendants inside listbox options', async () => {
+ const withSecondary: PaletteEntry = {
+ ...entry('first', 'First command'),
+ secondary: { label: 'Open Elsewhere', run: vi.fn() },
+ };
+ await renderPalette({ entries: [withSecondary] });
+
+ for (const option of document.querySelectorAll('[role="option"]')) {
+ expect(option.querySelector('button, a, input, select, textarea')).toBeNull();
+ }
});
it('shows key-specific date suggestions while typing a token, without flashing an error', async () => {
@@ -179,11 +390,14 @@ describe('CommandPaletteDialog interaction', () => {
expect(input.value).toBe('from:yesterday ');
expect(onClose).not.toHaveBeenCalled();
- await vi.waitFor(() => {
- expect(providerSearch).toHaveBeenCalledWith({
- range: { from: expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/), to: undefined },
- text: '',
- });
+ await waitFor(() => {
+ expect(providerSearch).toHaveBeenCalledWith(
+ {
+ range: { from: expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/), to: undefined },
+ text: '',
+ },
+ { signal: expect.any(AbortSignal) }
+ );
});
expect(document.body.textContent).toContain('Search images by date');
});
@@ -207,11 +421,9 @@ describe('CommandPaletteDialog interaction', () => {
const { input } = await renderPalette({ entries: [], providers: [capable, dateLess] });
await act(() => userEvent.fill(input, 'from:7d'));
- await new Promise((resolve) => {
- globalThis.setTimeout(resolve, 250);
- });
+ await waitForDebounce();
- await vi.waitFor(() => expect(capableSearch).toHaveBeenCalled());
+ await waitFor(() => expect(capableSearch).toHaveBeenCalled());
expect(dateLessSearch).not.toHaveBeenCalled();
});
@@ -249,14 +461,15 @@ describe('CommandPaletteDialog interaction', () => {
expect(document.body.textContent).not.toContain('Or type a date');
await act(() => userEvent.fill(input, 'from:7d'));
- await new Promise((resolve) => {
- globalThis.setTimeout(resolve, 250);
- });
+ await waitForDebounce();
// No acknowledgment chip, and the provider receives the literal text.
expect(document.getElementById('command-palette-date-hint')).toBeNull();
- await vi.waitFor(() => {
- expect(dateLessSearch).toHaveBeenCalledWith({ range: undefined, text: 'from:7d' });
+ await waitFor(() => {
+ expect(dateLessSearch).toHaveBeenCalledWith(
+ { range: undefined, text: 'from:7d' },
+ { signal: expect.any(AbortSignal) }
+ );
});
});
@@ -303,8 +516,8 @@ describe('CommandPaletteDialog interaction', () => {
expect(input.value).toBe('');
expect(onClose).not.toHaveBeenCalled();
- await vi.waitFor(() => {
- expect(providerSearch).toHaveBeenCalledWith({ range: undefined, text: '' });
+ await waitFor(() => {
+ expect(providerSearch).toHaveBeenCalledWith({ range: undefined, text: '' }, { signal: expect.any(AbortSignal) });
});
expect(document.body.textContent).toContain('Entity One');
@@ -313,7 +526,7 @@ describe('CommandPaletteDialog interaction', () => {
await act(() => userEvent.fill(input, '>search ent'));
await act(() => userEvent.keyboard('{Enter}'));
expect(input.value).toBe('');
- await vi.waitFor(() => expect(document.body.textContent).toContain('Entity One'));
+ await waitFor(() => expect(document.body.textContent).toContain('Entity One'));
});
it('keeps the query when entering a scope through a Tab scope row', async () => {
@@ -332,8 +545,11 @@ describe('CommandPaletteDialog interaction', () => {
await act(() => userEvent.keyboard('{Tab}'));
expect(input.value).toBe('zz');
- await vi.waitFor(() => {
- expect(providerSearch).toHaveBeenCalledWith({ range: undefined, text: 'zz' });
+ await waitFor(() => {
+ expect(providerSearch).toHaveBeenCalledWith(
+ { range: undefined, text: 'zz' },
+ { signal: expect.any(AbortSignal) }
+ );
});
});
@@ -348,20 +564,19 @@ describe('CommandPaletteDialog interaction', () => {
const { input } = await renderPalette({ entries: [], providers: [provider] });
await act(() => userEvent.fill(input, 'e'));
- await new Promise((resolve) => {
- globalThis.setTimeout(resolve, 250);
- });
+ await waitForDebounce();
expect(providerSearch).not.toHaveBeenCalled();
await act(() => userEvent.fill(input, ''));
await act(() => userEvent.keyboard('{Enter}'));
- await vi.waitFor(() => {
- expect(providerSearch).toHaveBeenCalledWith({ range: undefined, text: '' });
+ await waitFor(() => {
+ expect(providerSearch).toHaveBeenCalledWith({ range: undefined, text: '' }, { signal: expect.any(AbortSignal) });
});
await act(() => userEvent.fill(input, 'a'));
- await vi.waitFor(() => {
- expect(providerSearch).toHaveBeenCalledWith({ range: undefined, text: 'a' });
+ await waitForDebounce();
+ await waitFor(() => {
+ expect(providerSearch).toHaveBeenCalledWith({ range: undefined, text: 'a' }, { signal: expect.any(AbortSignal) });
});
});
@@ -375,10 +590,11 @@ describe('CommandPaletteDialog interaction', () => {
const { input } = await renderPalette({ entries: [], providers: [provider] });
await act(() => userEvent.keyboard('{Enter}'));
- await vi.waitFor(() => expect(document.body.textContent).toContain('No entities yet'));
+ await waitFor(() => expect(document.body.textContent).toContain('No entities yet'));
await act(() => userEvent.fill(input, 'x'));
- await vi.waitFor(() => expect(document.body.textContent).toContain('No results for “x”'));
+ await waitForDebounce();
+ await waitFor(() => expect(document.body.textContent).toContain('No results for “x”'));
});
it('keeps the error state and Retry for an empty scope', async () => {
@@ -391,7 +607,7 @@ describe('CommandPaletteDialog interaction', () => {
await renderPalette({ entries: [], providers: [provider] });
await act(() => userEvent.keyboard('{Enter}'));
- await vi.waitFor(() => expect(document.body.textContent).toContain("Couldn't search entities"));
+ await waitFor(() => expect(document.body.textContent).toContain("Couldn't search entities"));
expect([...document.querySelectorAll('button')].some((button) => button.textContent === 'Retry')).toBe(true);
});
@@ -448,7 +664,7 @@ describe('CommandPaletteDialog interaction', () => {
await act(() => userEvent.fill(input, 'search ent'));
await act(() => userEvent.keyboard('{Enter}'));
- const chip = await vi.waitFor(() => {
+ const chip = await waitFor(() => {
const node = [...document.querySelectorAll('button')].find((button) => button.textContent?.includes('Entities'));
expect(node).toBeDefined();
return node!;
@@ -458,10 +674,10 @@ describe('CommandPaletteDialog interaction', () => {
expect(onClose).not.toHaveBeenCalled();
expect(document.body.textContent).toContain('First command');
expect(input.value).toBe('');
- await vi.waitFor(() => expect(document.activeElement).toBe(input));
+ await waitFor(() => expect(document.activeElement).toBe(input));
});
- it('runs the highlighted row secondary action from its pointer affordance', async () => {
+ it('runs the highlighted row secondary action with Mod+Enter and exposes no nested button', async () => {
const secondaryRun = vi.fn();
const withSecondary: PaletteEntry = {
...entry('first', 'First command'),
@@ -469,13 +685,8 @@ describe('CommandPaletteDialog interaction', () => {
};
const { onClose } = await renderPalette({ entries: [withSecondary] });
- const secondaryButton = await vi.waitFor(() => {
- const node = document.querySelector<HTMLButtonElement>('button[aria-label="Open Elsewhere"]');
- expect(node).not.toBeNull();
- return node!;
- });
-
- await act(() => userEvent.click(secondaryButton));
+ expect(document.querySelector('button[aria-label="Open Elsewhere"]')).toBeNull();
+ await act(() => userEvent.keyboard('{Control>}{Enter}{/Control}'));
expect(secondaryRun).toHaveBeenCalledOnce();
expect(onClose).toHaveBeenCalledOnce();
});
@@ -506,8 +717,11 @@ describe('CommandPaletteDialog interaction', () => {
await act(() => userEvent.keyboard('{Tab}'));
expect(input.value).toBe('sunset');
- await vi.waitFor(() => {
- expect(dateLessSearch).toHaveBeenCalledWith({ range: undefined, text: 'sunset' });
+ await waitFor(() => {
+ expect(dateLessSearch).toHaveBeenCalledWith(
+ { range: undefined, text: 'sunset' },
+ { signal: expect.any(AbortSignal) }
+ );
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx
index 9b22e67f89..f4c081997c 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx
@@ -1,4 +1,3 @@
-/* eslint-disable react/react-compiler */
import type { ReactNode } from 'react';
import { Dialog, HStack, Icon, Kbd, Portal, Spacer, Text, chakra } from '@chakra-ui/react';
@@ -7,12 +6,14 @@ import { Button } from '@platform/ui/Button';
import { EmptyState } from '@platform/ui/EmptyState';
import { SearchIcon, XIcon } from 'lucide-react';
import { useCallback, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
import type { CommandPaletteRowsHandle } from './CommandPaletteRows';
import type { PaletteEntry, PaletteSearchProvider, PaletteStage } from './entries';
import { CommandPaletteRows, getCommandPaletteRowDomId } from './CommandPaletteRows';
-import { useCommandPaletteController } from './useCommandPaletteController';
+import { getCommandPaletteReturnFocusElement } from './paletteStore';
+import { COMMAND_PALETTE_INPUT_ID, useCommandPaletteController } from './useCommandPaletteController';
const INPUT_PLACEHOLDER_STYLE = { color: 'fg.subtle' };
const INPUT_FOCUS_WITHIN_STYLE = { outlineColor: 'accent.focusRing' };
@@ -65,8 +66,10 @@ export const CommandPaletteDialog = ({
return (
<Dialog.Root
closeOnEscape={false}
+ finalFocusEl={getCommandPaletteReturnFocusElement}
lazyMount
open={isOpen}
+ restoreFocus
scrollBehavior="inside"
unmountOnExit
onOpenChange={onDialogOpenChange}
@@ -96,13 +99,15 @@ const CommandPaletteContent = ({
onClose: () => void;
providers: PaletteSearchProvider[];
}) => {
+ const { t } = useTranslation();
const controller = useCommandPaletteController({ entries, onClose, providers });
const rowsRef = useRef<CommandPaletteRowsHandle>(null);
const modEnterHintKeys = useMemo(() => [modifierKeyLabel, '↵'], [modifierKeyLabel]);
+ const handleSearchKeyDown = controller.onSearchKeyDown;
const onSearchKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) =>
- controller.onSearchKeyDown(event, (index) => rowsRef.current?.scrollToIndex(index)),
- [controller]
+ handleSearchKeyDown(event, (index) => rowsRef.current?.scrollToIndex(index)),
+ [handleSearchKeyDown]
);
let emptyState: ReactNode = null;
@@ -110,18 +115,22 @@ const CommandPaletteContent = ({
if (controller.rows.length === 0) {
if (controller.scopeIsError && controller.scopeLabel) {
emptyState = (
- <EmptyState danger py="6" title={`Couldn't search ${controller.scopeLabel}`}>
+ <EmptyState danger py="6" title={t('commandPalette.states.couldNotSearch', { label: controller.scopeLabel })}>
<Button size="xs" variant="subtle" onClick={controller.onRetry}>
- Retry
+ {t('common.retry')}
</Button>
</EmptyState>
);
} else if (controller.scopeLabel && controller.scopeIsFetching) {
- emptyState = <EmptyState py="6" title="Searching…" />;
+ emptyState = <EmptyState py="6" title={t('commandPalette.states.searching')} />;
} else if (controller.scopeLabel && controller.trimmedQuery.length === 0) {
- emptyState = <EmptyState py="6" title={`No ${controller.scopeLabel} yet`} />;
+ emptyState = (
+ <EmptyState py="6" title={t('commandPalette.states.noItemsYet', { label: controller.scopeLabel })} />
+ );
} else {
- emptyState = <EmptyState py="6" title={`No results for “${controller.trimmedQuery}”`} />;
+ emptyState = (
+ <EmptyState py="6" title={t('commandPalette.states.noResults', { query: controller.trimmedQuery })} />
+ );
}
}
@@ -138,7 +147,7 @@ const CommandPaletteContent = ({
w="min(560px, calc(100vw - 32px))"
onKeyDown={controller.onContentKeyDown}
>
- <Dialog.Title srOnly>Command palette</Dialog.Title>
+ <Dialog.Title srOnly>{t('commandPalette.title')}</Dialog.Title>
<HStack
borderBottomWidth="1px"
borderColor="border.emphasized"
@@ -154,7 +163,7 @@ const CommandPaletteContent = ({
{controller.chipLabel ? (
<chakra.button
alignItems="center"
- aria-label={`Close ${controller.chipLabel} — back to all results`}
+ aria-label={t('commandPalette.actions.closeScope', { label: controller.chipLabel })}
bg="bg.emphasized"
borderRadius="sm"
color="fg"
@@ -166,7 +175,7 @@ const CommandPaletteContent = ({
gap="1"
px="1.5"
py="0.5"
- title="Back to all results"
+ title={t('commandPalette.actions.backToAll')}
type="button"
onClick={controller.onPopOverlay}
>
@@ -175,9 +184,9 @@ const CommandPaletteContent = ({
</chakra.button>
) : null}
<chakra.input
- ref={controller.setInputElement}
autoComplete="off"
autoFocus
+ id={COMMAND_PALETTE_INPUT_ID}
name="command-palette-query"
spellCheck={false}
type="search"
@@ -188,7 +197,7 @@ const CommandPaletteContent = ({
aria-describedby={controller.dateInvalidHint ? DATE_HINT_ID : undefined}
aria-expanded="true"
aria-invalid={controller.dateInvalidHint ? true : undefined}
- aria-label="Search commands and settings"
+ aria-label={t('commandPalette.inputLabel')}
bg="transparent"
color="fg"
flex="1"
@@ -222,16 +231,19 @@ const CommandPaletteContent = ({
</Text>
) : null}
</HStack>
+ <Text aria-live="polite" role="status" srOnly>
+ {controller.statusMessage}
+ </Text>
{controller.rows.length === 0 ? (
emptyState
) : (
<CommandPaletteRows
ref={rowsRef}
activeRowId={controller.activeRowId}
+ isBusy={controller.isBusy}
rows={controller.rows}
onActive={controller.onRowActive}
onRun={controller.onRowRun}
- onRunSecondary={controller.onRowRunSecondary}
/>
)}
<HStack
@@ -245,16 +257,20 @@ const CommandPaletteContent = ({
hideBelow="sm"
px="3"
>
- <FooterHint keys={NAV_HINT_KEYS}>Navigate</FooterHint>
- <FooterHint keys={ENTER_HINT_KEYS}>{controller.stage ? 'Pick' : 'Run'}</FooterHint>
+ <FooterHint keys={NAV_HINT_KEYS}>{t('commandPalette.footer.navigate')}</FooterHint>
+ <FooterHint keys={ENTER_HINT_KEYS}>
+ {controller.stage ? t('commandPalette.footer.pick') : t('commandPalette.footer.run')}
+ </FooterHint>
{controller.secondaryHint ? (
<FooterHint keys={modEnterHintKeys}>{controller.secondaryHint}</FooterHint>
) : null}
{controller.hasScopeRows || controller.activeRow?.kind === 'scope' ? (
- <FooterHint keys={TAB_HINT_KEYS}>Scope</FooterHint>
+ <FooterHint keys={TAB_HINT_KEYS}>{t('commandPalette.footer.scope')}</FooterHint>
) : null}
<Spacer />
- <FooterHint keys={ESC_HINT_KEYS}>{controller.isOverlayOpen ? 'Back' : 'Close'}</FooterHint>
+ <FooterHint keys={ESC_HINT_KEYS}>
+ {controller.isOverlayOpen ? t('commandPalette.footer.back') : t('commandPalette.footer.close')}
+ </FooterHint>
</HStack>
</Dialog.Content>
</Dialog.Positioner>
diff --git a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteRows.tsx b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteRows.tsx
index 489d31373b..21999d9e04 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteRows.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteRows.tsx
@@ -1,10 +1,10 @@
import type { ReactNode, Ref } from 'react';
import { Box, HStack, Icon, Kbd, ScrollArea, Spacer, Text, chakra } from '@chakra-ui/react';
+import { useVirtualizer } from '@tanstack/react-virtual';
import { dropdownGroupLabel } from '@theme/recipes';
-import { ArrowUpRightIcon, CheckIcon } from 'lucide-react';
+import { CheckIcon } from 'lucide-react';
import { useCallback, useImperativeHandle, useState } from 'react';
-import { useVirtualizer } from 'react-hook-tanstack-virtual';
import type { PaletteEntry, PaletteRow } from './entries';
@@ -17,8 +17,6 @@ export const getCommandPaletteRowDomId = (rowId: string): string => `${RESULT_LI
const preventFocusSteal = (event: { preventDefault: () => void }) => event.preventDefault();
-const SECONDARY_BUTTON_HOVER_STYLE = { color: 'fg' };
-
const renderTitle = (title: string, matchIndexes?: readonly number[]): ReactNode => {
if (!matchIndexes || matchIndexes.length === 0) {
return title;
@@ -48,8 +46,7 @@ const renderTitle = (title: string, matchIndexes?: readonly number[]): ReactNode
return segments;
};
-// Rows are divs, not buttons: they stay out of the tab order (combobox
-// aria-activedescendant pattern) and may nest a real secondary-action button.
+// Rows stay out of the tab order for the combobox aria-activedescendant pattern.
const rowButtonProps = {
cursor: 'pointer',
gap: '2.5',
@@ -67,7 +64,6 @@ const EntryRow = ({
matchIndexes,
onActive,
onRun,
- onRunSecondary,
}: {
domId: string;
entry: PaletteEntry;
@@ -75,16 +71,7 @@ const EntryRow = ({
matchIndexes?: readonly number[];
onActive: () => void;
onRun: () => void;
- onRunSecondary: () => void;
}) => {
- const onSecondaryClick = useCallback(
- (event: React.MouseEvent) => {
- event.stopPropagation();
- onRunSecondary();
- },
- [onRunSecondary]
- );
-
return (
<HStack
{...rowButtonProps}
@@ -110,25 +97,6 @@ const EntryRow = ({
</Text>
) : null}
<Spacer />
- {entry.secondary && isActive ? (
- <chakra.button
- aria-label={entry.secondary.label}
- color="fg.muted"
- cursor="pointer"
- display="inline-flex"
- flexShrink={0}
- p="1"
- rounded="sm"
- tabIndex={-1}
- title={entry.secondary.label}
- type="button"
- _hover={SECONDARY_BUTTON_HOVER_STYLE}
- onClick={onSecondaryClick}
- onMouseDown={preventFocusSteal}
- >
- <Icon as={ArrowUpRightIcon} boxSize="3.5" />
- </chakra.button>
- ) : null}
{entry.keys ? (
<HStack flexShrink={0} gap="0.5">
{entry.keys.map((part) => (
@@ -142,6 +110,36 @@ const EntryRow = ({
);
};
+const ProviderErrorRow = ({
+ domId,
+ isActive,
+ label,
+ onActive,
+ onRun,
+}: {
+ domId: string;
+ isActive: boolean;
+ label: string;
+ onActive: () => void;
+ onRun: () => void;
+}) => (
+ <HStack
+ {...rowButtonProps}
+ id={domId}
+ aria-selected={isActive}
+ bg={isActive ? 'bg.error' : undefined}
+ color="fg.error"
+ role="option"
+ onClick={onRun}
+ onMouseDown={preventFocusSteal}
+ onMouseMove={onActive}
+ >
+ <Text fontSize="sm" truncate>
+ {label}
+ </Text>
+ </HStack>
+);
+
const ScopeRow = ({
domId,
isActive,
@@ -183,7 +181,6 @@ const VirtualPaletteRow = ({
virtualStart,
onActive,
onRun,
- onRunSecondary,
}: {
activeRowId: string | null;
measureElement: (node: Element | null) => void;
@@ -192,11 +189,9 @@ const VirtualPaletteRow = ({
virtualStart: number;
onActive: (rowId: string) => void;
onRun: (row: PaletteRow) => void;
- onRunSecondary: (row: PaletteRow) => void;
}) => {
const handleActive = useCallback(() => onActive(row.id), [onActive, row.id]);
const handleRun = useCallback(() => onRun(row), [onRun, row]);
- const handleRunSecondary = useCallback(() => onRunSecondary(row), [onRunSecondary, row]);
const isActive = row.id === activeRowId;
return (
@@ -221,6 +216,14 @@ const VirtualPaletteRow = ({
onActive={handleActive}
onRun={handleRun}
/>
+ ) : row.kind === 'provider-error' ? (
+ <ProviderErrorRow
+ domId={getCommandPaletteRowDomId(row.id)}
+ isActive={isActive}
+ label={row.label}
+ onActive={handleActive}
+ onRun={handleRun}
+ />
) : (
<EntryRow
domId={getCommandPaletteRowDomId(row.id)}
@@ -229,7 +232,6 @@ const VirtualPaletteRow = ({
matchIndexes={row.matchIndexes}
onActive={handleActive}
onRun={handleRun}
- onRunSecondary={handleRunSecondary}
/>
)}
</Box>
@@ -240,20 +242,21 @@ export interface CommandPaletteRowsHandle {
scrollToIndex: (index: number) => void;
}
+// eslint-disable-next-line react/react-compiler -- TanStack Virtual exposes imperative functions that the compiler cannot memoize safely.
export const CommandPaletteRows = ({
activeRowId,
+ isBusy,
ref,
rows,
onActive,
onRun,
- onRunSecondary,
}: {
activeRowId: string | null;
+ isBusy: boolean;
ref?: Ref<CommandPaletteRowsHandle>;
rows: PaletteRow[];
onActive: (rowId: string) => void;
onRun: (row: PaletteRow) => void;
- onRunSecondary: (row: PaletteRow) => void;
}) => {
const [scrollElement, setScrollElement] = useState<HTMLDivElement | null>(null);
const estimateRowSize = useCallback(
@@ -278,9 +281,9 @@ export const CommandPaletteRows = ({
return (
<ScrollArea.Root maxH="min(400px, 55dvh)" size="xs" variant="hover" w="full">
<ScrollArea.Viewport ref={setScrollElement} aria-label="Command palette results" maxH="inherit" w="full">
- <ScrollArea.Content id={RESULT_LIST_ID} pb="1.5" role="listbox" w="full">
- <Box h={`${virtualizer.totalSize}px`} position="relative" w="full">
- {virtualizer.virtualItems.map((virtualRow) => {
+ <ScrollArea.Content id={RESULT_LIST_ID} aria-busy={isBusy} pb="1.5" role="listbox" w="full">
+ <Box h={`${virtualizer.getTotalSize()}px`} position="relative" w="full">
+ {virtualizer.getVirtualItems().map((virtualRow) => {
const row = rows[virtualRow.index];
return row ? (
@@ -293,7 +296,6 @@ export const CommandPaletteRows = ({
virtualStart={virtualRow.start}
onActive={onActive}
onRun={onRun}
- onRunSecondary={onRunSecondary}
/>
) : null;
})}
diff --git a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx
index 2c04ffcabf..30ee752bec 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx
@@ -8,14 +8,14 @@ import { tinykeys } from 'tinykeys';
import type { SettingsEntryDeps } from './entries';
-import { closeCommandPalette, commandPaletteStore, toggleCommandPalette } from './paletteStore';
+import { closeCommandPalette, toggleCommandPalette, useIsCommandPaletteOpen } from './paletteStore';
import { SETTINGS_ENTRY_DEPS } from './settingsEntryDeps';
const LazyLaunchpadCommandPaletteDialog = lazy(() => import('./LaunchpadCommandPaletteDialog'));
/** Lightweight Launchpad runtime and lazy dialog host. */
export const LaunchpadCommandPalette = () => {
- const isOpen = commandPaletteStore.useSelector((snapshot) => snapshot.isOpen);
+ const isOpen = useIsCommandPaletteOpen();
const preferences = useWorkbenchPreferences();
useMountEffect(() =>
@@ -30,8 +30,8 @@ export const LaunchpadCommandPalette = () => {
return isOpen ? (
<Suspense fallback={null}>
<LazyLaunchpadCommandPaletteDialog
+ modifierKeyLabel={formatHotkeyForPlatform('mod')[0]!}
preferences={preferences as WorkbenchPreferences}
- modifierKeyLabel={formatHotkeyForPlatform('mod')[0] ?? 'ctrl'}
settingsEntryDeps={SETTINGS_ENTRY_DEPS as SettingsEntryDeps}
onClose={closeCommandPalette}
/>
diff --git a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx
index f646d2c954..153170ac60 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx
@@ -1,9 +1,8 @@
-import type { WorkbenchPreferences } from '@workbench/settings/contracts';
-
import { useCapabilities } from '@features/identity';
import { useNavigate, useSearch } from '@tanstack/react-router';
import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';
import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
import type { PaletteEntry, SettingsEntryDeps } from './entries';
@@ -12,16 +11,17 @@ import { buildSettingsEntries } from './entries';
/** Launchpad-only palette adapter: navigation and settings, no editor providers. */
const LaunchpadCommandPaletteDialog = ({
- onClose,
modifierKeyLabel,
+ onClose,
preferences,
settingsEntryDeps,
}: {
- onClose: () => void;
modifierKeyLabel: string;
+ onClose: () => void;
preferences: WorkbenchPreferences;
settingsEntryDeps: SettingsEntryDeps;
}) => {
+ const { t } = useTranslation();
const navigate = useNavigate();
const search = useSearch({ strict: false }) as { project?: string };
const { canManageModels, canManageNodes, canManageUsers } = useCapabilities();
@@ -30,30 +30,33 @@ const LaunchpadCommandPaletteDialog = ({
const navigation: PaletteEntry[] = [
{
group: 'Navigation',
+ groupLabel: t('commandPalette.groups.navigation'),
id: 'launchpad.openEditor',
isPersistentRecent: true,
keywords: 'workbench app project',
run: () => void navigate({ search: search.project ? { project: search.project } : {}, to: '/app' }),
showInEmptyState: true,
- title: 'Open Editor',
+ title: t('commandPalette.launchpad.openEditor'),
},
{
group: 'Navigation',
+ groupLabel: t('commandPalette.groups.navigation'),
id: 'launchpad.goToProjects',
isPersistentRecent: true,
run: () => void navigate({ to: '/projects' }),
showInEmptyState: true,
- title: 'Go to Projects',
+ title: t('commandPalette.launchpad.goToProjects'),
},
...(canManageModels
? [
{
group: 'Navigation',
+ groupLabel: t('commandPalette.groups.navigation'),
id: 'launchpad.goToModels',
isPersistentRecent: true,
run: () => void navigate({ to: '/models' }),
showInEmptyState: true,
- title: 'Go to Models',
+ title: t('commandPalette.launchpad.goToModels'),
},
]
: []),
@@ -61,11 +64,12 @@ const LaunchpadCommandPaletteDialog = ({
? [
{
group: 'Navigation',
+ groupLabel: t('commandPalette.groups.navigation'),
id: 'launchpad.goToNodes',
isPersistentRecent: true,
run: () => void navigate({ to: '/nodes' }),
showInEmptyState: true,
- title: 'Go to Nodes',
+ title: t('commandPalette.launchpad.goToNodes'),
},
]
: []),
@@ -73,29 +77,32 @@ const LaunchpadCommandPaletteDialog = ({
? [
{
group: 'Navigation',
+ groupLabel: t('commandPalette.groups.navigation'),
id: 'launchpad.goToUsers',
isPersistentRecent: true,
run: () => void navigate({ to: '/users' }),
showInEmptyState: true,
- title: 'Go to Users',
+ title: t('commandPalette.launchpad.goToUsers'),
},
]
: []),
{
group: 'App',
+ groupLabel: t('commandPalette.groups.app'),
id: 'app.openSettings',
isPersistentRecent: true,
keywords: 'preferences options',
run: () => openWorkbenchSettings(),
showInEmptyState: true,
- title: 'Open Settings',
+ title: t('commandPalette.launchpad.openSettings'),
},
];
- return [...navigation, ...buildSettingsEntries(preferences, settingsEntryDeps)];
- }, [canManageModels, canManageNodes, canManageUsers, navigate, preferences, search.project, settingsEntryDeps]);
+ return [...navigation, ...buildSettingsEntries(preferences, settingsEntryDeps, t)];
+ }, [canManageModels, canManageNodes, canManageUsers, navigate, preferences, search.project, settingsEntryDeps, t]);
return <CommandPaletteDialog entries={entries} isOpen modifierKeyLabel={modifierKeyLabel} onClose={onClose} />;
};
export default LaunchpadCommandPaletteDialog;
+import type { WorkbenchPreferences } from '@workbench/settings/contracts';
diff --git a/invokeai/frontend/webv2/src/workbench/palette/PaletteButton.tsx b/invokeai/frontend/webv2/src/workbench/palette/PaletteButton.tsx
index 71460cd3f7..28b13bab79 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/PaletteButton.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/PaletteButton.tsx
@@ -1,16 +1,22 @@
import { Icon } from '@chakra-ui/react';
import { IconButton } from '@platform/ui/Button';
import { Tooltip } from '@platform/ui/Tooltip';
-import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
import { SearchIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
import { openCommandPalette } from './paletteStore';
+const hotkeyLabel = /mac/i.test(navigator.platform) ? 'cmd+k' : 'ctrl+k';
+
/** Pointer affordance for the palette; the kbd hint keeps mod+K discoverable. */
-export const PaletteButton = () => (
- <Tooltip content={`Command palette (${formatHotkeyForPlatform('mod+k').join('+')})`}>
- <IconButton aria-label="Command palette" size="sm" variant="ghost" onClick={openCommandPalette}>
- <Icon as={SearchIcon} />
- </IconButton>
- </Tooltip>
-);
+export const PaletteButton = () => {
+ const { t } = useTranslation();
+
+ return (
+ <Tooltip content={t('commandPalette.buttonTooltip', { hotkey: hotkeyLabel })}>
+ <IconButton aria-label={t('commandPalette.buttonLabel')} size="sm" variant="ghost" onClick={openCommandPalette}>
+ <Icon as={SearchIcon} />
+ </IconButton>
+ </Tooltip>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx
index 092769fb9a..300c526037 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx
@@ -1,6 +1,7 @@
import type { WorkbenchPreferences } from '@workbench/settings/contracts';
-import { getQueueQueryScope, getQueueReadModelOptions } from '@features/queue/queries';
+import { loadPaletteQueueReadModel } from '@features/queue/paletteSearch';
+import { requestQueueItemReveal } from '@features/queue/reveal';
import { useMountEffect } from '@platform/react/useMountEffect';
import { firstPartyHotkeyCatalog } from '@workbench/hotkeys/catalog';
import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
@@ -12,14 +13,14 @@ import { lazy, Suspense } from 'react';
import type { SettingsEntryDeps } from './entries';
-import { closeCommandPalette, commandPaletteStore } from './paletteStore';
+import { closeCommandPalette, useIsCommandPaletteOpen } from './paletteStore';
import { SETTINGS_ENTRY_DEPS } from './settingsEntryDeps';
const LazyWorkbenchCommandPaletteDialog = lazy(() => import('./WorkbenchCommandPaletteDialog'));
/** Lightweight route host; the palette implementation is loaded only while open. */
export const WorkbenchCommandPalette = () => {
- const isOpen = commandPaletteStore.useSelector((snapshot) => snapshot.isOpen);
+ const isOpen = useIsCommandPaletteOpen();
const preferences = useWorkbenchPreferences();
return isOpen ? <OpenWorkbenchCommandPalette preferences={preferences} /> : null;
@@ -33,12 +34,12 @@ const OpenWorkbenchCommandPalette = ({ preferences }: { preferences: WorkbenchPr
<LazyWorkbenchCommandPaletteDialog
catalog={firstPartyHotkeyCatalog}
formatHotkey={formatHotkeyForPlatform}
- modifierKeyLabel={formatHotkeyForPlatform('mod')[0] ?? 'ctrl'}
getWidgetsForRegion={getWidgetsForRegion}
- getQueueQueryScope={getQueueQueryScope}
- getQueueReadModelOptions={getQueueReadModelOptions}
+ modifierKeyLabel={formatHotkeyForPlatform('mod')[0]!}
openWidgetPlacement={openWidgetPlacement}
preferences={preferences}
+ loadQueueReadModel={loadPaletteQueueReadModel}
+ requestQueueItemReveal={requestQueueItemReveal}
settingsEntryDeps={SETTINGS_ENTRY_DEPS as SettingsEntryDeps}
onClose={closeCommandPalette}
/>
diff --git a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx
index ff94d80c47..19241ddffd 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx
@@ -1,26 +1,25 @@
-import type {
- getQueueQueryScope as GetQueueQueryScope,
- getQueueReadModelOptions as GetQueueReadModelOptions,
-} from '@features/queue/queries';
+import type { QueueQueryScope, QueueReadModel } from '@features/queue/contracts';
import type { HotkeyDefinition } from '@workbench/hotkeys/types';
import type { WorkbenchPreferences } from '@workbench/settings/contracts';
import type { openWidgetPlacement as OpenWidgetPlacement } from '@workbench/widgetPlacementCommands';
import type { getWidgetsForRegion as GetWidgetsForRegion } from '@workbench/widgetRegistry';
+import type { TFunction } from 'i18next';
import { getPromptHistoryRecallPatch } from '@features/generation/settings';
import { useModelsSnapshot } from '@features/models';
-import { requestQueueItemReveal } from '@features/queue/reveal';
import { queryClient } from '@platform/query/client';
import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchExtensions } from '@workbench/WorkbenchContext';
import { useCallback, useMemo, useSyncExternalStore } from 'react';
+import { useTranslation } from 'react-i18next';
import type { PaletteEntry, PaletteSearchProvider, SettingsEntryDeps } from './entries';
import { CommandPaletteDialog } from './CommandPaletteDialog';
import { buildCatalogCommandEntries, buildSettingsEntries } from './entries';
import { buildExtensionPaletteEntry, createExtensionSearchProvider } from './extensionPaletteAdapters';
+import { getObjectIdentity } from './objectIdentity';
import {
createBoardsProvider,
createImagesProvider,
@@ -30,23 +29,25 @@ import {
createWorkflowsProvider,
} from './paletteProviders';
-const STATIC_APP_ENTRIES: PaletteEntry[] = [
+const buildStaticAppEntries = (t: TFunction): PaletteEntry[] => [
{
group: 'App',
+ groupLabel: t('commandPalette.groups.app'),
id: 'app.openSettings',
isPersistentRecent: true,
keywords: 'preferences options',
run: () => openWorkbenchSettings(),
showInEmptyState: true,
- title: 'Open Settings',
+ title: t('commandPalette.appEntries.openSettings'),
},
{
group: 'App',
+ groupLabel: t('commandPalette.groups.app'),
id: 'app.openHotkeySettings',
isPersistentRecent: true,
keywords: 'hotkeys keybindings shortcuts',
run: () => openWorkbenchSettings('hotkeys'),
- title: 'Keyboard Shortcuts',
+ title: t('commandPalette.appEntries.keyboardShortcuts'),
},
];
@@ -54,26 +55,27 @@ const STATIC_APP_ENTRIES: PaletteEntry[] = [
const WorkbenchCommandPaletteDialog = ({
catalog,
formatHotkey,
- getQueueQueryScope,
- getQueueReadModelOptions,
getWidgetsForRegion,
+ loadQueueReadModel,
modifierKeyLabel,
onClose,
openWidgetPlacement,
preferences,
+ requestQueueItemReveal,
settingsEntryDeps,
}: {
catalog: readonly HotkeyDefinition[];
- formatHotkey: (key: string) => string[];
- getQueueQueryScope: typeof GetQueueQueryScope;
- getQueueReadModelOptions: typeof GetQueueReadModelOptions;
+ formatHotkey: (hotkey: string) => string[];
getWidgetsForRegion: typeof GetWidgetsForRegion;
+ loadQueueReadModel: (scope: QueueQueryScope) => Promise<QueueReadModel>;
modifierKeyLabel: string;
onClose: () => void;
openWidgetPlacement: typeof OpenWidgetPlacement;
preferences: WorkbenchPreferences;
+ requestQueueItemReveal: (itemId: number) => void;
settingsEntryDeps: SettingsEntryDeps;
}) => {
+ const { i18n, t } = useTranslation();
const extensions = useWorkbenchExtensions();
const modelsSnapshot = useModelsSnapshot();
const models = modelsSnapshot.status === 'loaded' ? modelsSnapshot.models : undefined;
@@ -105,12 +107,13 @@ const WorkbenchCommandPaletteDialog = ({
catalog,
formatHotkey,
presentWidgetTypeIds: new Set(presentWidgetTypeIds),
+ t,
}),
...paletteContributions.map((contribution) =>
buildExtensionPaletteEntry(contribution, extensions.commands.executeForSource)
),
- ...STATIC_APP_ENTRIES,
- ...buildSettingsEntries(preferences, settingsEntryDeps),
+ ...buildStaticAppEntries(t),
+ ...buildSettingsEntries(preferences, settingsEntryDeps, t),
],
[
catalog,
@@ -121,16 +124,18 @@ const WorkbenchCommandPaletteDialog = ({
preferences,
presentWidgetTypeIds,
settingsEntryDeps,
+ t,
]
);
const workbenchCommands = useWorkbenchCommands();
const searchStore = extensions.stores.search;
const extensionSearchProviders = useSyncExternalStore(searchStore.subscribe, searchStore.list, searchStore.list);
- const promptRecallContextKey = useMemo(() => JSON.stringify([generateValues, models]), [generateValues, models]);
+ const promptRecallContextKey = `${getObjectIdentity(generateValues, 'generation')}:${getObjectIdentity(models, 'models')}`;
const queueScope = useMemo(
- () => getQueueQueryScope({ projectId, queueJobsScope: preferences.queueJobsScope }),
- [getQueueQueryScope, preferences.queueJobsScope, projectId]
+ () =>
+ preferences.queueJobsScope === 'active-project' && projectId ? { originPrefix: `webv2:p:${projectId}:q:` } : {},
+ [preferences.queueJobsScope, projectId]
);
const providers = useMemo<PaletteSearchProvider[]>(() => {
const { gallery, widgets } = workbenchCommands;
@@ -150,27 +155,37 @@ const WorkbenchCommandPaletteDialog = ({
});
return [
- createWorkflowsProvider({ openWorkflowWidget: () => openWidget('workflow') }),
+ createWorkflowsProvider({ openWorkflowWidget: () => openWidget('workflow'), t }),
createBoardsProvider({
openGalleryWidget: () => openWidget('gallery'),
selectBoard: (boardId) => gallery.selectBoard(boardId),
+ t,
}),
createModelsProvider({
applyModel: (model) => widgets.patchValues('generate', { model, modelKey: model.key }, projectId),
openGenerateWidget: () => openWidget('generate'),
openModelManager: () => void executeCommand('app.selectModelsTab'),
+ t,
}),
createImagesProvider({
openGalleryWidget: () => openWidget('gallery'),
openPreviewWidget: () => openWidget('preview'),
selectBoard: (boardId) => gallery.selectBoard(boardId),
selectImage: (image) => gallery.selectImage(image),
+ locale: i18n.resolvedLanguage,
+ t,
}),
createQueueItemsProvider({
- contextKey: JSON.stringify(queueScope),
- loadQueue: () => queryClient.fetchQuery(getQueueReadModelOptions(queueScope)),
+ contextKey: queueScope.originPrefix ?? 'all-projects',
+ loadQueue: () =>
+ queryClient.fetchQuery({
+ queryFn: () => loadQueueReadModel(queueScope),
+ queryKey: ['queue', 'read-model', queueScope.originPrefix ?? 'all'],
+ staleTime: 5_000,
+ }),
openQueueWidget: () => openWidget('queue'),
revealItem: requestQueueItemReveal,
+ t,
}),
createPromptHistoryProvider({
openGenerateWidget: () => openWidget('generate'),
@@ -184,6 +199,7 @@ const WorkbenchCommandPaletteDialog = ({
widgets.patchValues('generate', patch, projectId);
}
},
+ t,
}),
...extensionSearchProviders.map((provider) =>
createExtensionSearchProvider(provider, extensions.commands.executeForSource)
@@ -194,14 +210,17 @@ const WorkbenchCommandPaletteDialog = ({
extensionSearchProviders,
extensions,
generateValues,
- getWidgetsForRegion,
- getQueueReadModelOptions,
+ i18n.resolvedLanguage,
models,
+ getWidgetsForRegion,
openWidgetPlacement,
projectId,
promptHistory,
promptRecallContextKey,
queueScope,
+ loadQueueReadModel,
+ requestQueueItemReveal,
+ t,
workbenchCommands,
]);
diff --git a/invokeai/frontend/webv2/src/workbench/palette/commandPaletteI18n.test.ts b/invokeai/frontend/webv2/src/workbench/palette/commandPaletteI18n.test.ts
new file mode 100644
index 0000000000..5113bfb6a2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/commandPaletteI18n.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+
+const enModules = import.meta.glob('../../../public/locales/en.json', { eager: true, import: 'default' });
+const enGbModules = import.meta.glob('../../../public/locales/en-GB.json', { eager: true, import: 'default' });
+const en = Object.values(enModules)[0] as { commandPalette: Record<string, unknown> };
+const enGb = Object.values(enGbModules)[0] as { commandPalette: Record<string, unknown> };
+
+const flattenKeys = (value: Record<string, unknown>, prefix = ''): string[] =>
+ Object.entries(value).flatMap(([key, child]) => {
+ const path = prefix ? `${prefix}.${key}` : key;
+
+ return child && typeof child === 'object' && !Array.isArray(child)
+ ? flattenKeys(child as Record<string, unknown>, path)
+ : [path];
+ });
+
+describe('command palette translations', () => {
+ it('keeps English and British-English command palette keys in parity', () => {
+ const enCommandPalette = en.commandPalette;
+ const enGbCommandPalette = enGb.commandPalette;
+
+ expect(flattenKeys(enGbCommandPalette).sort()).toEqual(flattenKeys(enCommandPalette).sort());
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/palette/contributionKey.ts b/invokeai/frontend/webv2/src/workbench/palette/contributionKey.ts
index bc448e7292..afe7748f36 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/contributionKey.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/contributionKey.ts
@@ -8,7 +8,7 @@ import type { WidgetContributionSource } from '@workbench/widgetContracts';
* pulling extension registry internals into either route's initial graph.
*/
export const getPaletteContributionKey = (
- kind: 'command' | 'provider' | 'provider-result' | 'provider-row' | 'scope' | 'scope-command',
+ kind: 'command' | 'provider' | 'provider-error' | 'provider-result' | 'provider-row' | 'scope' | 'scope-command',
id: string,
source?: WidgetContributionSource | null
): string =>
diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts
index 760c8d436e..573b123605 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts
@@ -1,3 +1,5 @@
+import type { TFunction } from 'i18next';
+
import { firstPartyHotkeyCatalog } from '@workbench/hotkeys/catalog';
import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
import { DEFAULT_PREFERENCES } from '@workbench/settings/store';
@@ -25,6 +27,35 @@ import {
*/
const noop = () => undefined;
+const translations: Record<string, string> = {
+ 'commandPalette.actions.openInSettings': 'Open in Settings',
+ 'commandPalette.groups.app': 'App',
+ 'commandPalette.groups.canvas': 'Canvas',
+ 'commandPalette.groups.generation': 'Generation',
+ 'commandPalette.groups.navigation': 'Navigation',
+ 'commandPalette.groups.settings': 'Settings',
+ 'commandPalette.settings.off': 'Off',
+ 'commandPalette.settings.on': 'On',
+ 'commandPalette.settings.settingsSection': 'Settings: {{section}}',
+ 'commandPalette.settings.values.activeProject': 'Active Project',
+ 'commandPalette.settings.values.allProjects': 'All Projects',
+ 'commandPalette.settings.values.curved': 'Curved',
+ 'commandPalette.settings.values.language': 'Language',
+ 'commandPalette.settings.values.queueJobsScope': 'Queue Jobs Scope',
+ 'commandPalette.settings.values.square': 'Square',
+ 'commandPalette.settings.values.theme': 'Theme',
+ 'commandPalette.settings.values.workflowEdgeStyle': 'Workflow Edge Style',
+};
+const t = ((key: string, options?: Record<string, unknown>) => {
+ let value =
+ translations[key] ?? (typeof options?.defaultValue === 'string' ? options.defaultValue : key.split('.').at(-1));
+
+ for (const [name, replacement] of Object.entries(options ?? {})) {
+ value = value?.replace(`{{${name}}}`, String(replacement));
+ }
+
+ return value;
+}) as TFunction;
const settingsEntryDeps = {
languageOptions: [{ label: 'English', value: 'en' as const }],
openSettingsSection: vi.fn(),
@@ -46,6 +77,7 @@ describe('buildCatalogCommandEntries', () => {
execute,
formatHotkey: formatHotkeyForPlatform,
presentWidgetTypeIds,
+ t,
});
it('surfaces implemented app commands with palette-facing titles and groups', () => {
@@ -83,6 +115,7 @@ describe('buildCatalogCommandEntries', () => {
execute,
formatHotkey: formatHotkeyForPlatform,
presentWidgetTypeIds: new Set(),
+ t,
});
const invoke = entries.find((entry) => entry.id === 'app.invoke');
const clearQueue = entries.find((entry) => entry.id === 'app.clearQueue');
@@ -100,7 +133,8 @@ describe('buildSettingsEntries', () => {
const patchPreferences = vi.fn();
const entries = buildSettingsEntries(
{ ...DEFAULT_PREFERENCES, reduceMotion: false },
- { ...settingsEntryDeps, openSettingsSection: vi.fn(), patchPreferences }
+ { ...settingsEntryDeps, openSettingsSection: vi.fn(), patchPreferences },
+ t
);
const reduceMotion = entries.find((entry) => entry.id === 'setting.reduceMotion');
@@ -112,11 +146,15 @@ describe('buildSettingsEntries', () => {
it('deep-links enum preferences and sections to the settings dialog', () => {
const openSettingsSection = vi.fn();
- const entries = buildSettingsEntries(DEFAULT_PREFERENCES, {
- ...settingsEntryDeps,
- openSettingsSection,
- patchPreferences: vi.fn(),
- });
+ const entries = buildSettingsEntries(
+ DEFAULT_PREFERENCES,
+ {
+ ...settingsEntryDeps,
+ openSettingsSection,
+ patchPreferences: vi.fn(),
+ },
+ t
+ );
const theme = entries.find((entry) => entry.id === 'setting.themeId');
const workflowSection = entries.find((entry) => entry.id === 'settings.section.workflow');
@@ -133,7 +171,8 @@ describe('buildSettingsEntries', () => {
const patchPreferences = vi.fn();
const entries = buildSettingsEntries(
{ ...DEFAULT_PREFERENCES, workflowEdgeStyle: 'curved' },
- { ...settingsEntryDeps, openSettingsSection: vi.fn(), patchPreferences }
+ { ...settingsEntryDeps, openSettingsSection: vi.fn(), patchPreferences },
+ t
);
const edgeStyle = entries.find((entry) => entry.id === 'setting.workflowEdgeStyle');
@@ -150,13 +189,17 @@ describe('buildSettingsEntries', () => {
it('wires theme stage preview hooks only when the host provides them', () => {
const previewTheme = vi.fn();
const clearThemePreview = vi.fn();
- const withPreview = buildSettingsEntries(DEFAULT_PREFERENCES, {
- ...settingsEntryDeps,
- clearThemePreview,
- openSettingsSection: vi.fn(),
- patchPreferences: vi.fn(),
- previewTheme,
- });
+ const withPreview = buildSettingsEntries(
+ DEFAULT_PREFERENCES,
+ {
+ ...settingsEntryDeps,
+ clearThemePreview,
+ openSettingsSection: vi.fn(),
+ patchPreferences: vi.fn(),
+ previewTheme,
+ },
+ t
+ );
const theme = withPreview.find((entry) => entry.id === 'setting.themeId');
theme?.stage?.preview?.('light');
@@ -164,11 +207,15 @@ describe('buildSettingsEntries', () => {
expect(previewTheme).toHaveBeenCalledWith('light');
expect(clearThemePreview).toHaveBeenCalled();
- const withoutPreview = buildSettingsEntries(DEFAULT_PREFERENCES, {
- ...settingsEntryDeps,
- openSettingsSection: vi.fn(),
- patchPreferences: vi.fn(),
- });
+ const withoutPreview = buildSettingsEntries(
+ DEFAULT_PREFERENCES,
+ {
+ ...settingsEntryDeps,
+ openSettingsSection: vi.fn(),
+ patchPreferences: vi.fn(),
+ },
+ t
+ );
const bareTheme = withoutPreview.find((entry) => entry.id === 'setting.themeId');
expect(bareTheme?.stage?.preview).toBeUndefined();
@@ -198,8 +245,11 @@ describe('provider row assembly', () => {
entries: Array.from({ length: count }, (_, index) =>
makeEntry({ group: id, id: `${id}:${index}`, title: `${id} ${index}` })
),
+ isError: false,
isFetching,
+ isWaitingForDebounce: false,
provider: { label: id, providerKey: id },
+ retry: vi.fn(),
});
it('caps sections in root mode and drops empty settled sections', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.ts
index d9c955a40d..edbf9fdd6f 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/entries.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.ts
@@ -2,6 +2,7 @@ import type { DateRange } from '@platform/search/dateTokens';
import type { CustomHotkeys, HotkeyDefinition } from '@workbench/hotkeys/types';
import type { WorkbenchPreferences } from '@workbench/settings/contracts';
import type { SettingsSectionId } from '@workbench/widgetContracts';
+import type { TFunction } from 'i18next';
import fuzzysort from 'fuzzysort';
@@ -37,6 +38,8 @@ export interface PaletteEntry {
title: string;
/** Section header the entry renders under; ordered via PALETTE_GROUP_ORDER. */
group: string;
+ /** Localized section header; group remains a stable internal ordering key. */
+ groupLabel?: string;
/** Trailing muted text: a setting's current value, an entity's metadata. */
subtitle?: string;
/** Leading 28×28 thumbnail (image results). */
@@ -65,6 +68,10 @@ export interface PaletteProviderQuery {
range?: DateRange;
}
+export interface PaletteSearchContext {
+ signal: AbortSignal;
+}
+
/** An async entity source the palette can query (workflows, boards, …). */
export interface PaletteSearchProvider {
/** Globally unique, stable identity (including extension source identity). */
@@ -78,12 +85,13 @@ export interface PaletteSearchProvider {
* could only return broad unfiltered results.
*/
supportsCreatedAtRange?: boolean;
- search: (query: PaletteProviderQuery) => Promise<PaletteEntry[]> | PaletteEntry[];
+ search: (query: PaletteProviderQuery, context: PaletteSearchContext) => Promise<PaletteEntry[]> | PaletteEntry[];
}
export type PaletteRow =
| { kind: 'label'; id: string; label: string }
| { kind: 'entry'; id: string; entry: PaletteEntry; matchIndexes?: readonly number[] }
+ | { kind: 'provider-error'; id: string; providerKey: string; label: string; retry: () => void }
| { kind: 'scope'; id: string; providerKey: string; label: string };
export interface ActivePaletteRow {
@@ -218,12 +226,14 @@ export const buildCatalogCommandEntries = ({
execute,
formatHotkey,
presentWidgetTypeIds,
+ t,
}: {
catalog: readonly HotkeyDefinition[];
customHotkeys: CustomHotkeys;
execute: (commandId: string) => unknown;
formatHotkey: (key: string) => string[];
presentWidgetTypeIds: ReadonlySet<string>;
+ t: TFunction;
}): PaletteEntry[] =>
catalog
.filter((definition) => definition.implemented !== false && !PALETTE_HIDDEN_COMMANDS.has(definition.commandId))
@@ -234,17 +244,25 @@ export const buildCatalogCommandEntries = ({
})
.map((definition) => {
const widgetGroup = WIDGET_CATEGORY_GROUPS[definition.category];
- const group = widgetGroup?.group ?? APP_COMMAND_GROUPS[definition.commandId] ?? 'App';
+ const rawGroup = widgetGroup?.group ?? APP_COMMAND_GROUPS[definition.commandId] ?? 'App';
+ const group = rawGroup;
+ const groupLabel = t(
+ `commandPalette.groups.${rawGroup.replaceAll(' ', '').replace(/^./, (char) => char.toLowerCase())}`,
+ { defaultValue: rawGroup }
+ );
return {
group,
+ groupLabel,
id: definition.commandId,
isPersistentRecent: true,
keys: getEntryKeys(definition, customHotkeys, formatHotkey),
keywords: widgetGroup?.group,
run: () => execute(definition.commandId),
showInEmptyState: group === 'Navigation',
- title: TITLE_OVERRIDES[definition.commandId] ?? definition.title,
+ title: t(`commandPalette.commands.${definition.commandId.replace('.', '_')}`, {
+ defaultValue: TITLE_OVERRIDES[definition.commandId] ?? definition.title,
+ }),
};
});
@@ -290,16 +308,21 @@ export interface SettingsEntryDeps {
themes: ReadonlyArray<{ id: WorkbenchPreferences['themeId']; label: string }>;
}
-export const buildSettingsEntries = (preferences: WorkbenchPreferences, deps: SettingsEntryDeps): PaletteEntry[] => {
+export const buildSettingsEntries = (
+ preferences: WorkbenchPreferences,
+ deps: SettingsEntryDeps,
+ t: TFunction
+): PaletteEntry[] => {
const toggles = SETTING_TOGGLES.map<PaletteEntry>(({ key, keywords, title }) => ({
group: 'Settings',
+ groupLabel: t('commandPalette.groups.settings'),
id: `setting.${key}`,
isPersistentRecent: true,
keepOpen: true,
keywords: keywords ? `${keywords} toggle` : 'toggle',
run: () => deps.patchPreferences({ [key]: !preferences[key] }),
- subtitle: preferences[key] ? 'On' : 'Off',
- title,
+ subtitle: preferences[key] ? t('commandPalette.settings.on') : t('commandPalette.settings.off'),
+ title: t(`commandPalette.settings.toggles.${key}`, { defaultValue: title }),
}));
// Multi-value preferences push an inline value-picker stage; mod+Enter (or
@@ -322,11 +345,12 @@ export const buildSettingsEntries = (preferences: WorkbenchPreferences, deps: Se
title: string;
}): PaletteEntry => ({
group: 'Settings',
+ groupLabel: t('commandPalette.groups.settings'),
id,
isPersistentRecent: true,
keywords,
run: () => deps.openSettingsSection(sectionId),
- secondary: { label: 'Open in Settings', run: () => deps.openSettingsSection(sectionId) },
+ secondary: { label: t('commandPalette.actions.openInSettings'), run: () => deps.openSettingsSection(sectionId) },
stage: { options, title, ...stagePreview },
subtitle,
title,
@@ -348,7 +372,7 @@ export const buildSettingsEntries = (preferences: WorkbenchPreferences, deps: Se
? { clearPreview: deps.clearThemePreview, preview: deps.previewTheme }
: undefined,
subtitle: deps.themes.find((theme) => theme.id === preferences.themeId)?.label ?? preferences.themeId,
- title: 'Theme',
+ title: t('commandPalette.settings.values.theme'),
}),
enumEntry({
id: 'setting.language',
@@ -362,7 +386,7 @@ export const buildSettingsEntries = (preferences: WorkbenchPreferences, deps: Se
sectionId: 'appearance',
subtitle:
deps.languageOptions.find((language) => language.value === preferences.language)?.label ?? preferences.language,
- title: 'Language',
+ title: t('commandPalette.settings.values.language'),
}),
enumEntry({
id: 'setting.workflowEdgeStyle',
@@ -371,11 +395,15 @@ export const buildSettingsEntries = (preferences: WorkbenchPreferences, deps: Se
apply: () => deps.patchPreferences({ workflowEdgeStyle: style }),
id: style,
isCurrent: style === preferences.workflowEdgeStyle,
- label: style === 'square' ? 'Square' : 'Curved',
+ label:
+ style === 'square' ? t('commandPalette.settings.values.square') : t('commandPalette.settings.values.curved'),
})),
sectionId: 'workflow',
- subtitle: preferences.workflowEdgeStyle === 'square' ? 'Square' : 'Curved',
- title: 'Workflow Edge Style',
+ subtitle:
+ preferences.workflowEdgeStyle === 'square'
+ ? t('commandPalette.settings.values.square')
+ : t('commandPalette.settings.values.curved'),
+ title: t('commandPalette.settings.values.workflowEdgeStyle'),
}),
enumEntry({
id: 'setting.queueJobsScope',
@@ -384,21 +412,30 @@ export const buildSettingsEntries = (preferences: WorkbenchPreferences, deps: Se
apply: () => deps.patchPreferences({ queueJobsScope: scope }),
id: scope,
isCurrent: scope === preferences.queueJobsScope,
- label: scope === 'all' ? 'All Projects' : 'Active Project',
+ label:
+ scope === 'all'
+ ? t('commandPalette.settings.values.allProjects')
+ : t('commandPalette.settings.values.activeProject'),
})),
sectionId: 'queue',
- subtitle: preferences.queueJobsScope === 'all' ? 'All Projects' : 'Active Project',
- title: 'Queue Jobs Scope',
+ subtitle:
+ preferences.queueJobsScope === 'all'
+ ? t('commandPalette.settings.values.allProjects')
+ : t('commandPalette.settings.values.activeProject'),
+ title: t('commandPalette.settings.values.queueJobsScope'),
}),
];
const sections = SETTINGS_SECTIONS.map<PaletteEntry>(({ id, title }) => ({
group: 'Settings',
+ groupLabel: t('commandPalette.groups.settings'),
id: `settings.section.${id}`,
isPersistentRecent: true,
keywords: 'settings preferences open',
run: () => deps.openSettingsSection(id),
- title: `Settings: ${title}`,
+ title: t('commandPalette.settings.settingsSection', {
+ section: t(`commandPalette.settings.sections.${id}`, { defaultValue: title }),
+ }),
}));
return [...toggles, ...enums, ...sections];
@@ -427,7 +464,7 @@ const toGroupedRows = (groups: Map<string, RankedEntry[]>): PaletteRow[] => {
continue;
}
- rows.push({ id: `label:${group}`, kind: 'label', label: group });
+ rows.push({ id: `label:${group}`, kind: 'label', label: ranked[0]?.entry.groupLabel ?? group });
for (const { entry, matchIndexes } of ranked) {
rows.push({ entry, id: entry.id, kind: 'entry', matchIndexes });
@@ -437,7 +474,11 @@ const toGroupedRows = (groups: Map<string, RankedEntry[]>): PaletteRow[] => {
return rows;
};
-const buildEmptyStateRows = (entries: readonly PaletteEntry[], recentIds: readonly string[]): PaletteRow[] => {
+const buildEmptyStateRows = (
+ entries: readonly PaletteEntry[],
+ recentIds: readonly string[],
+ recentLabel = RECENT_GROUP
+): PaletteRow[] => {
const byId = new Map(entries.map((entry) => [entry.id, entry]));
const recent = recentIds
.map((id) => byId.get(id))
@@ -446,7 +487,7 @@ const buildEmptyStateRows = (entries: readonly PaletteEntry[], recentIds: readon
const rows: PaletteRow[] = [];
if (recent.length > 0) {
- rows.push({ id: `label:${RECENT_GROUP}`, kind: 'label', label: RECENT_GROUP });
+ rows.push({ id: `label:${RECENT_GROUP}`, kind: 'label', label: recentLabel });
for (const entry of recent) {
rows.push({ entry, id: `recent:${entry.id}`, kind: 'entry' });
@@ -479,7 +520,11 @@ export const searchPaletteRows = (
entries: readonly PaletteEntry[],
query: string,
recentIds: readonly string[],
- { commandsOnly = false, showAllOnEmpty = false }: { commandsOnly?: boolean; showAllOnEmpty?: boolean } = {}
+ {
+ commandsOnly = false,
+ recentLabel = RECENT_GROUP,
+ showAllOnEmpty = false,
+ }: { commandsOnly?: boolean; recentLabel?: string; showAllOnEmpty?: boolean } = {}
): PaletteRow[] => {
const searchable = commandsOnly ? entries.filter((entry) => entry.group !== 'Settings') : entries;
const trimmed = query.trim();
@@ -497,7 +542,7 @@ export const searchPaletteRows = (
return toGroupedRows(all);
}
- return buildEmptyStateRows(searchable, recentIds);
+ return buildEmptyStateRows(searchable, recentIds, recentLabel);
}
const results = fuzzysort.go(trimmed, searchable, {
@@ -543,7 +588,7 @@ export const searchPaletteRows = (
export const STAGE_ENTRY_ID_PREFIX = 'stage:';
/** Turn a value-picker stage into filterable entry rows; picking applies and pops. */
-export const buildStageEntries = (stage: PaletteStage, onApplied: () => void): PaletteEntry[] =>
+export const buildStageEntries = (stage: PaletteStage, onApplied: () => void, t?: TFunction): PaletteEntry[] =>
stage.options.map((option) => ({
group: stage.title,
id: `${STAGE_ENTRY_ID_PREFIX}${option.id}`,
@@ -553,14 +598,17 @@ export const buildStageEntries = (stage: PaletteStage, onApplied: () => void): P
void option.apply();
onApplied();
},
- subtitle: option.isCurrent ? 'Current' : undefined,
+ subtitle: option.isCurrent ? (t?.('commandPalette.settings.current') ?? 'Current') : undefined,
title: option.label,
}));
export interface ProviderResultSection {
provider: Pick<PaletteSearchProvider, 'providerKey' | 'label'>;
entries: PaletteEntry[];
+ isError: boolean;
isFetching: boolean;
+ isWaitingForDebounce: boolean;
+ retry: () => void;
}
/**
@@ -570,24 +618,46 @@ export interface ProviderResultSection {
*/
export const buildProviderSectionRows = (
sections: readonly ProviderResultSection[],
- cap: number | null = PROVIDER_ROOT_RESULT_CAP
+ cap: number | null = PROVIDER_ROOT_RESULT_CAP,
+ t?: TFunction
): PaletteRow[] => {
const rows: PaletteRow[] = [];
for (const section of sections) {
+ if (cap === null && section.isError) {
+ // Scoped mode owns the full-width error and Retry presentation.
+ continue;
+ }
+
const visible = cap === null ? section.entries : section.entries.slice(0, cap);
- if (visible.length === 0 && !section.isFetching) {
+ if (visible.length === 0 && !section.isFetching && !section.isWaitingForDebounce && !section.isError) {
continue;
}
rows.push({
id: `label:provider:${section.provider.providerKey}`,
kind: 'label',
- label: section.isFetching ? `${section.provider.label} — Searching…` : section.provider.label,
+ label:
+ section.isFetching || section.isWaitingForDebounce
+ ? (t?.('commandPalette.states.searchingSection', { label: section.provider.label }) ??
+ `${section.provider.label} — Searching…`)
+ : section.provider.label,
});
- for (const entry of visible) {
+ if (section.isError && cap !== null) {
+ rows.push({
+ id: getPaletteContributionKey('provider-error', section.provider.providerKey),
+ kind: 'provider-error',
+ label:
+ t?.('commandPalette.states.retrySearch', { label: section.provider.label.toLowerCase() }) ??
+ `Retry ${section.provider.label.toLowerCase()} search`,
+ providerKey: section.provider.providerKey,
+ retry: section.retry,
+ });
+ }
+
+ for (const entry of section.isWaitingForDebounce ? [] : visible) {
rows.push({
entry,
id: getPaletteContributionKey('provider-row', `${section.provider.providerKey}:${entry.id}`),
@@ -606,7 +676,8 @@ export const buildProviderSectionRows = (
*/
export const buildScopeRows = (
providers: ReadonlyArray<Pick<PaletteSearchProvider, 'providerKey' | 'label'>>,
- query: string
+ query: string,
+ t?: TFunction
): PaletteRow[] => {
if (providers.length === 0) {
return [];
@@ -615,14 +686,16 @@ export const buildScopeRows = (
return [
// Distinct id: the scope-command *group* label ("label:Search in") can
// render in the same list when a query fuzzy-matches those commands.
- { id: 'label:scope-rows', kind: 'label', label: SEARCH_SCOPE_GROUP },
+ { id: 'label:scope-rows', kind: 'label', label: t?.('commandPalette.search.in') ?? SEARCH_SCOPE_GROUP },
...providers.map<PaletteRow>((provider) => ({
id: getPaletteContributionKey('scope', provider.providerKey),
kind: 'scope',
label:
query.length === 0
- ? `Search ${provider.label.toLowerCase()} by date`
- : `Search ${provider.label.toLowerCase()} for “${query}”`,
+ ? (t?.('commandPalette.search.byDate', { label: provider.label.toLowerCase() }) ??
+ `Search ${provider.label.toLowerCase()} by date`)
+ : (t?.('commandPalette.search.forQuery', { label: provider.label.toLowerCase(), query }) ??
+ `Search ${provider.label.toLowerCase()} for “${query}”`),
providerKey: provider.providerKey,
})),
];
diff --git a/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.test.ts b/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.test.ts
index f7e7951867..08d5704e62 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.test.ts
@@ -19,13 +19,15 @@ const extensionProvider = (instanceId: string): WidgetSearchProvider => ({
source: source(instanceId),
});
+const searchContext = () => ({ signal: new AbortController().signal });
+
describe('extension palette adapters', () => {
it('keeps providers, query keys, scopes, and results collision-free per widget source', async () => {
const execute = vi.fn();
const first = createExtensionSearchProvider(extensionProvider('one'), execute);
const second = createExtensionSearchProvider(extensionProvider('two'), execute);
- const [firstResult] = await first.search({ text: 'query' });
- const [secondResult] = await second.search({ text: 'query' });
+ const [firstResult] = await first.search({ text: 'query' }, searchContext());
+ const [secondResult] = await second.search({ text: 'query' }, searchContext());
expect(first.providerKey).not.toBe(second.providerKey);
expect(getPaletteProviderQueryKey(first, { text: 'query' })).not.toEqual(
@@ -38,9 +40,10 @@ describe('extension palette adapters', () => {
const search = vi.fn(() => [{ commandId: 'run', id: 'shared-result-id', title: 'Result' }]);
const provider = createExtensionSearchProvider({ ...extensionProvider('one'), search }, vi.fn());
- await provider.search({ range: { from: '2026-07-14', to: '2026-07-21' }, text: 'sunset' });
+ const context = searchContext();
+ await provider.search({ range: { from: '2026-07-14', to: '2026-07-21' }, text: 'sunset' }, context);
- expect(search).toHaveBeenCalledWith('sunset');
+ expect(search).toHaveBeenCalledWith('sunset', context);
expect(provider.supportsCreatedAtRange).toBeUndefined();
});
@@ -58,6 +61,41 @@ describe('extension palette adapters', () => {
}
});
+ it('keeps one registration stable and gives replacement registrations new identities', () => {
+ const registration = extensionProvider('one');
+ const firstAdaptation = createExtensionSearchProvider(registration, vi.fn());
+ const secondAdaptation = createExtensionSearchProvider(registration, vi.fn());
+ const replacement = createExtensionSearchProvider({ ...registration }, vi.fn());
+
+ expect(firstAdaptation.contextKey).toBe(secondAdaptation.contextKey);
+ expect(replacement.contextKey).not.toBe(firstAdaptation.contextKey);
+ });
+
+ it('includes the explicit extension context key in palette query identity', () => {
+ const registration = extensionProvider('one');
+ const first = createExtensionSearchProvider({ ...registration, contextKey: 'revision-1' }, vi.fn());
+ const second = createExtensionSearchProvider({ ...registration, contextKey: 'revision-2' }, vi.fn());
+
+ expect(first.contextKey).not.toBe(second.contextKey);
+ });
+
+ it('omits informational results without commands', async () => {
+ const provider = createExtensionSearchProvider(
+ {
+ ...extensionProvider('one'),
+ search: () => [
+ { id: 'info', title: 'Informational result' },
+ { commandId: 'run', id: 'action', title: 'Action result' },
+ ],
+ },
+ vi.fn()
+ );
+
+ const results = await provider.search({ text: '' }, searchContext());
+
+ expect(results.map((result) => result.title)).toEqual(['Action result']);
+ });
+
it('differentiates query keys by resolved date range', () => {
const provider = createExtensionSearchProvider(extensionProvider('one'), vi.fn());
diff --git a/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.ts b/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.ts
index 0df4b96be2..5f863e9f23 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.ts
@@ -7,6 +7,7 @@ import type {
import type { PaletteEntry, PaletteSearchProvider } from './entries';
import { getPaletteContributionKey } from './contributionKey';
+import { getObjectIdentity } from './objectIdentity';
type ExecuteExtensionCommand = (
commandId: string,
@@ -33,22 +34,24 @@ export const createExtensionSearchProvider = (
const providerKey = getPaletteContributionKey('provider', provider.id, provider.source);
return {
- contextKey: providerKey,
+ contextKey: `${providerKey}:${getObjectIdentity(provider, 'registration')}:${provider.contextKey ?? 'default'}`,
label: provider.label,
providerKey,
// Extensions keep their plain-string search contract; they receive the
// query text with date tokens stripped and never see the range.
- search: async (query) => {
- const results = await provider.search(query.text);
+ search: async (query, { signal }) => {
+ const results = await provider.search(query.text, { signal });
- return results.map<PaletteEntry>((result) => ({
- group: provider.label,
- id: getPaletteContributionKey('provider-result', `${providerKey}:${result.id}`, provider.source),
- isPersistentRecent: false,
- run: () => (result.commandId ? execute(result.commandId, provider.source ?? null, result.id) : undefined),
- subtitle: result.subtitle,
- title: result.title,
- }));
+ return results
+ .filter((result) => result.commandId !== undefined)
+ .map<PaletteEntry>((result) => ({
+ group: provider.label,
+ id: getPaletteContributionKey('provider-result', `${providerKey}:${result.id}`, provider.source),
+ isPersistentRecent: false,
+ run: () => execute(result.commandId!, provider.source ?? null, result.id),
+ subtitle: result.subtitle,
+ title: result.title,
+ }));
},
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/palette/objectIdentity.ts b/invokeai/frontend/webv2/src/workbench/palette/objectIdentity.ts
new file mode 100644
index 0000000000..4f14595317
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/objectIdentity.ts
@@ -0,0 +1,19 @@
+const identities = new WeakMap<object, number>();
+let nextIdentity = 1;
+
+/** A short, process-local identity for immutable snapshots used in query keys. */
+export const getObjectIdentity = (value: object | null | undefined, prefix = 'ref'): string => {
+ if (value === null || value === undefined) {
+ return `${prefix}:none`;
+ }
+
+ let identity = identities.get(value);
+
+ if (identity === undefined) {
+ identity = nextIdentity;
+ nextIdentity += 1;
+ identities.set(value, identity);
+ }
+
+ return `${prefix}:${identity}`;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteDebouncer.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteDebouncer.ts
new file mode 100644
index 0000000000..141da065b6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteDebouncer.ts
@@ -0,0 +1,30 @@
+export class PaletteDebouncer {
+ #timer: number | null = null;
+ readonly #commit: (value: string) => void;
+ readonly #delayMs: number;
+
+ constructor(delayMs: number, commit: (value: string) => void) {
+ this.#commit = commit;
+ this.#delayMs = delayMs;
+ }
+
+ cancel = (): void => {
+ if (this.#timer !== null) {
+ window.clearTimeout(this.#timer);
+ this.#timer = null;
+ }
+ };
+
+ commit = (value: string): void => {
+ this.cancel();
+ this.#commit(value);
+ };
+
+ schedule = (value: string): void => {
+ this.cancel();
+ this.#timer = window.setTimeout(() => {
+ this.#timer = null;
+ this.#commit(value);
+ }, this.#delayMs);
+ };
+}
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts
index 2b064f3591..38656d6b46 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts
@@ -1,21 +1,22 @@
import type { GalleryBoard, GalleryImage } from '@features/gallery/contracts';
import type { ModelConfig } from '@features/models';
-import type { QueueItemStatus, QueueReadModel } from '@features/queue/contracts';
+import type { QueueReadModel } from '@features/queue/contracts';
import type { PromptHistoryItem } from '@workbench/projectContracts';
+import type { TFunction } from 'i18next';
-import { galleryBoardsOptions, galleryImagesOptions } from '@features/gallery/queries';
+import { ALL_READABLE_BOARDS_ID, listGalleryBoards, listGalleryImages } from '@features/gallery/paletteSearch';
import { focusPositivePrompt } from '@features/generation/react';
import { ensureModelsLoaded, getModelBaseLabel, getModelsSnapshot } from '@features/models';
import { extractGenerationMeta, getResultImageName } from '@features/queue/contracts';
-import { listLibraryWorkflows } from '@features/workflow/queries';
+import { listLibraryWorkflows } from '@features/workflow/paletteSearch';
import { requestLibraryWorkflowLoad } from '@features/workflow/react';
-import { queryClient } from '@platform/query/client';
import { formatIsoDate, isTimestampInRange } from '@platform/search/dateTokens';
import { absolutizeApiUrl } from '@platform/transport/http';
import type { PaletteEntry, PaletteSearchProvider } from './entries';
import { getPaletteContributionKey } from './contributionKey';
+import { getObjectIdentity } from './objectIdentity';
/**
* First-party entity providers behind the palette's scoped search. Each is a
@@ -35,20 +36,23 @@ const matchesTerms = (haystack: string, query: string): boolean => {
export const createWorkflowsProvider = ({
openWorkflowWidget,
+ t,
}: {
openWorkflowWidget: () => void;
+ t: TFunction;
}): PaletteSearchProvider => ({
contextKey: 'global',
- label: 'Workflows',
+ label: t('commandPalette.providers.workflows'),
providerKey: getPaletteContributionKey('provider', 'workflows'),
- search: async (query) => {
+ search: async (query, { signal }) => {
const [user, defaults] = await Promise.all([
- listLibraryWorkflows({ category: 'user', page: 0, perPage: PROVIDER_PAGE_SIZE, query: query.text }),
- listLibraryWorkflows({ category: 'default', page: 0, perPage: PROVIDER_PAGE_SIZE, query: query.text }),
+ listLibraryWorkflows({ category: 'user', page: 0, perPage: PROVIDER_PAGE_SIZE, query: query.text, signal }),
+ listLibraryWorkflows({ category: 'default', page: 0, perPage: PROVIDER_PAGE_SIZE, query: query.text, signal }),
]);
return [...user.items, ...defaults.items].map<PaletteEntry>((item) => ({
group: 'Workflows',
+ groupLabel: t('commandPalette.groups.workflows'),
id: `workflow:${item.workflow_id}`,
isPersistentRecent: false,
keywords: item.tags ?? undefined,
@@ -56,7 +60,10 @@ export const createWorkflowsProvider = ({
openWorkflowWidget();
requestLibraryWorkflowLoad(item.workflow_id);
},
- subtitle: item.category === 'default' ? 'Default workflow' : 'Workflow',
+ subtitle:
+ item.category === 'default'
+ ? t('commandPalette.providers.defaultWorkflow')
+ : t('commandPalette.providers.workflow'),
title: item.name,
}));
},
@@ -65,16 +72,18 @@ export const createWorkflowsProvider = ({
export const createBoardsProvider = ({
openGalleryWidget,
selectBoard,
+ t,
}: {
openGalleryWidget: () => void;
selectBoard: (boardId: string) => void;
+ t: TFunction;
}): PaletteSearchProvider => ({
contextKey: 'global',
- label: 'Boards',
+ label: t('commandPalette.groups.boards'),
providerKey: getPaletteContributionKey('provider', 'boards'),
supportsCreatedAtRange: true,
- search: async (query) => {
- const boards = await queryClient.fetchQuery(galleryBoardsOptions({ includeArchived: false }));
+ search: async (query, { signal }) => {
+ const boards = await listGalleryBoards({ includeArchived: false, signal });
return boards
.filter(
@@ -86,13 +95,14 @@ export const createBoardsProvider = ({
)
.map<PaletteEntry>((board) => ({
group: 'Boards',
+ groupLabel: t('commandPalette.groups.boards'),
id: `board:${board.id}`,
isPersistentRecent: false,
run: () => {
openGalleryWidget();
selectBoard(board.id);
},
- subtitle: `Board · ${board.imageCount} image${board.imageCount === 1 ? '' : 's'}`,
+ subtitle: t('commandPalette.providers.boardSubtitle', { count: board.imageCount }),
title: board.name,
}));
},
@@ -104,17 +114,20 @@ export const createPromptHistoryProvider = ({
promptHistory,
recallContextKey,
recallPrompt,
+ t,
}: {
openGenerateWidget: () => void;
projectId: string;
promptHistory: readonly PromptHistoryItem[];
recallContextKey: string;
recallPrompt: (item: PromptHistoryItem) => void;
+ t: TFunction;
}): PaletteSearchProvider => ({
- contextKey: JSON.stringify([projectId, promptHistory, recallContextKey]),
- label: 'Prompt history',
+ contextKey: `${projectId}:${getObjectIdentity(promptHistory, 'history')}:${recallContextKey}`,
+ label: t('commandPalette.providers.promptHistory'),
providerKey: getPaletteContributionKey('provider', 'prompt-history'),
- search: (query) => {
+ search: (query, { signal }) => {
+ signal.throwIfAborted();
const seen = new Set<string>();
const entries: PaletteEntry[] = [];
@@ -130,6 +143,7 @@ export const createPromptHistoryProvider = ({
seen.add(dedupeKey);
entries.push({
group: 'Prompt history',
+ groupLabel: t('commandPalette.groups.promptHistory'),
id: `prompt:${index}`,
isPersistentRecent: false,
run: () => {
@@ -142,6 +156,7 @@ export const createPromptHistoryProvider = ({
});
}
+ signal.throwIfAborted();
return entries;
},
});
@@ -152,16 +167,20 @@ export const createModelsProvider = ({
applyModel,
openGenerateWidget,
openModelManager,
+ t,
}: {
applyModel: (model: ModelConfig) => void;
openGenerateWidget: () => void;
openModelManager: () => void;
+ t: TFunction;
}): PaletteSearchProvider => ({
contextKey: 'global',
- label: 'Models',
+ label: t('commandPalette.providers.models'),
providerKey: getPaletteContributionKey('provider', 'models'),
- search: async (query) => {
+ search: async (query, { signal }) => {
+ signal.throwIfAborted();
await ensureModelsLoaded();
+ signal.throwIfAborted();
const snapshot = getModelsSnapshot();
const models = snapshot.status === 'loaded' ? snapshot.models : [];
@@ -171,6 +190,7 @@ export const createModelsProvider = ({
)
.map<PaletteEntry>((model) => ({
group: 'Models',
+ groupLabel: t('commandPalette.groups.models'),
id: `model:${model.key}`,
isPersistentRecent: false,
keywords: model.base,
@@ -178,49 +198,44 @@ export const createModelsProvider = ({
openGenerateWidget();
applyModel(model);
},
- secondary: { label: 'Open in Model Manager', run: openModelManager },
+ secondary: { label: t('commandPalette.actions.openModelManager'), run: openModelManager },
subtitle: getModelBaseLabel(model.base),
title: model.name,
}));
},
});
-const QUEUE_STATUS_LABELS: Record<QueueItemStatus, string> = {
- canceled: 'Canceled',
- completed: 'Completed',
- failed: 'Failed',
- in_progress: 'In progress',
- pending: 'Pending',
- waiting: 'Waiting',
-};
-
export const createQueueItemsProvider = ({
contextKey,
loadQueue,
openQueueWidget,
revealItem,
+ t,
}: {
contextKey: string;
loadQueue: () => Promise<QueueReadModel>;
openQueueWidget: () => void;
revealItem: (itemId: number) => void;
+ t: TFunction;
}): PaletteSearchProvider => ({
contextKey,
- label: 'Queue items',
+ label: t('commandPalette.providers.queueItems'),
providerKey: getPaletteContributionKey('provider', 'queue-items'),
supportsCreatedAtRange: true,
- search: async (query) => {
+ search: async (query, { signal }) => {
// The queue read model is a recent window with no server-side text search;
// filter the fetched window client-side. Items without a timestamp fail
// closed while a date range is active.
+ signal.throwIfAborted();
const model = await loadQueue();
+ signal.throwIfAborted();
return model.items
.map((item) => ({ item, meta: extractGenerationMeta(item) }))
.filter(
({ item, meta }) =>
matchesTerms(
- `${meta.positivePrompt ?? ''} ${meta.negativePrompt ?? ''} ${QUEUE_STATUS_LABELS[item.status]} ${item.userDisplayName ?? ''}`,
+ `${meta.positivePrompt ?? ''} ${meta.negativePrompt ?? ''} ${t(`commandPalette.queueStatuses.${item.status}`)} ${item.userDisplayName ?? ''}`,
query.text
) &&
(query.range === undefined || isTimestampInRange(item.createdAt, query.range))
@@ -230,17 +245,18 @@ export const createQueueItemsProvider = ({
return {
group: 'Queue items',
+ groupLabel: t('commandPalette.groups.queueItems'),
id: `queue-item:${item.id}`,
isPersistentRecent: false,
run: () => {
openQueueWidget();
revealItem(item.id);
},
- subtitle: QUEUE_STATUS_LABELS[item.status],
+ subtitle: t(`commandPalette.queueStatuses.${item.status}`),
thumbnailUrl: resultImageName
? absolutizeApiUrl(`/api/v1/images/i/${encodeURIComponent(resultImageName)}/thumbnail`)
: undefined,
- title: meta.positivePrompt?.trim() || 'Untitled generation',
+ title: meta.positivePrompt?.trim() || t('commandPalette.providers.noTitle'),
};
});
},
@@ -251,35 +267,40 @@ export const createImagesProvider = ({
openPreviewWidget,
selectBoard,
selectImage,
+ locale,
+ t,
}: {
openGalleryWidget: () => void;
openPreviewWidget: () => void;
selectBoard: (boardId: string) => void;
selectImage: (image: GalleryImage) => void;
+ locale?: string;
+ t: TFunction;
}): PaletteSearchProvider => ({
contextKey: 'global',
- label: 'Images',
+ label: t('commandPalette.providers.images'),
providerKey: getPaletteContributionKey('provider', 'images'),
supportsCreatedAtRange: true,
- search: async (query) => {
- // Searches every board the user can see (no board_id filter); the cached
- // boards list labels each result. Text and date range filter server-side.
+ search: async (query, { signal }) => {
+ // Search the explicit all-readable scope. The endpoint excludes archived
+ // and inaccessible boards; the active board list supplies display labels.
const [page, boards] = await Promise.all([
- queryClient.fetchQuery(
- galleryImagesOptions({
- createdFrom: query.range?.from,
- createdTo: query.range?.to,
- galleryView: 'images',
- limit: 20,
- searchTerm: query.text,
- })
- ),
- queryClient.fetchQuery(galleryBoardsOptions({ includeArchived: false })),
+ listGalleryImages({
+ boardId: ALL_READABLE_BOARDS_ID,
+ createdFrom: query.range?.from,
+ createdTo: query.range?.to,
+ galleryView: 'images',
+ limit: 20,
+ searchTerm: query.text,
+ signal,
+ }),
+ listGalleryBoards({ includeArchived: false, signal }),
]);
const boardNames = new Map(boards.map((board: GalleryBoard) => [board.id, board.name]));
return page.images.map<PaletteEntry>((image) => ({
group: 'Images',
+ groupLabel: t('commandPalette.groups.images'),
id: `image:${image.imageName}`,
isPersistentRecent: false,
run: () => {
@@ -287,16 +308,16 @@ export const createImagesProvider = ({
selectImage(image);
},
secondary: {
- label: 'Reveal in Gallery',
+ label: t('commandPalette.actions.revealInGallery'),
run: () => {
openGalleryWidget();
selectBoard(image.boardId);
selectImage(image);
},
},
- subtitle: `${boardNames.get(image.boardId) ?? 'Uncategorized'} · ${image.width}×${image.height}`,
+ subtitle: `${boardNames.get(image.boardId) ?? t('commandPalette.providers.uncategorized')} · ${formatIsoDate(image.queuedAt.slice(0, 10), locale)} · ${image.width}×${image.height}`,
thumbnailUrl: image.thumbnailUrl,
- title: formatIsoDate(image.queuedAt.slice(0, 10)),
+ title: image.imageName,
}));
},
});
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteState.test.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteState.test.ts
new file mode 100644
index 0000000000..eb96db9437
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteState.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ changePaletteSelection,
+ commitPaletteQuery,
+ createInitialPaletteState,
+ enterPaletteScope,
+ enterPaletteStage,
+ replacePaletteQuery,
+ returnPaletteToRoot,
+} from './paletteState';
+
+describe('palette state transitions', () => {
+ it('replaces and commits a query without preserving a stale selection', () => {
+ const selected = changePaletteSelection(createInitialPaletteState(), 'row-1');
+ const typed = replacePaletteQuery(selected, 'sunset');
+
+ expect(typed).toEqual({ activeRowId: null, debouncedQuery: '', mode: { kind: 'root' }, query: 'sunset' });
+ expect(commitPaletteQuery(typed, 'sunset')).toEqual({ ...typed, debouncedQuery: 'sunset' });
+ });
+
+ it('enters scopes and stages with complete, non-contradictory state', () => {
+ expect(enterPaletteScope('images', 'cats')).toEqual({
+ activeRowId: null,
+ debouncedQuery: 'cats',
+ mode: { kind: 'scoped', providerKey: 'images' },
+ query: 'cats',
+ });
+
+ const stage = { options: [{ apply: vi.fn(), id: 'dark', isCurrent: true, label: 'Dark' }], title: 'Theme' };
+ expect(enterPaletteStage(stage, 'stage:dark')).toEqual({
+ activeRowId: 'stage:dark',
+ debouncedQuery: '',
+ mode: { kind: 'stage', stage },
+ query: '',
+ });
+ });
+
+ it('returns to a fresh root state', () => {
+ expect(returnPaletteToRoot()).toEqual(createInitialPaletteState());
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteState.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteState.ts
new file mode 100644
index 0000000000..51b02bc4b6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteState.ts
@@ -0,0 +1,52 @@
+import type { PaletteStage } from './entries';
+
+export type PaletteMode =
+ | { kind: 'root' }
+ | { kind: 'scoped'; providerKey: string }
+ | { kind: 'stage'; stage: PaletteStage };
+
+export interface PaletteState {
+ mode: PaletteMode;
+ query: string;
+ debouncedQuery: string;
+ activeRowId: string | null;
+}
+
+export const createInitialPaletteState = (): PaletteState => ({
+ activeRowId: null,
+ debouncedQuery: '',
+ mode: { kind: 'root' },
+ query: '',
+});
+
+export const replacePaletteQuery = (state: PaletteState, query: string): PaletteState => ({
+ ...state,
+ activeRowId: null,
+ query,
+});
+
+export const commitPaletteQuery = (state: PaletteState, debouncedQuery: string): PaletteState => ({
+ ...state,
+ debouncedQuery,
+});
+
+export const enterPaletteScope = (providerKey: string, query: string): PaletteState => ({
+ activeRowId: null,
+ debouncedQuery: query,
+ mode: { kind: 'scoped', providerKey },
+ query,
+});
+
+export const enterPaletteStage = (stage: PaletteStage, activeRowId: string | null): PaletteState => ({
+ activeRowId,
+ debouncedQuery: '',
+ mode: { kind: 'stage', stage },
+ query: '',
+});
+
+export const returnPaletteToRoot = (): PaletteState => createInitialPaletteState();
+
+export const changePaletteSelection = (state: PaletteState, activeRowId: string | null): PaletteState => ({
+ ...state,
+ activeRowId,
+});
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts
index c65ed3130b..8f2e60874a 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts
@@ -1,4 +1,5 @@
-import { createExternalStore } from '@platform/state/externalStore';
+import { createExternalStoreCore } from '@platform/state/externalStoreCore';
+import { useSyncExternalStore } from 'react';
/**
* Open/close state for the command palette, addressable from anywhere: the
@@ -8,9 +9,27 @@ import { createExternalStore } from '@platform/state/externalStore';
* launchpad) and subscribes to this store.
*/
-export const commandPaletteStore = createExternalStore<{ isOpen: boolean }>({ isOpen: false });
+export const commandPaletteStore = createExternalStoreCore<{ isOpen: boolean }>({ isOpen: false });
+
+export const useIsCommandPaletteOpen = (): boolean =>
+ useSyncExternalStore(commandPaletteStore.subscribe, commandPaletteStore.getSnapshot, commandPaletteStore.getSnapshot)
+ .isOpen;
+
+let returnFocusElement: HTMLElement | null = null;
+
+const captureReturnFocusElement = (): void => {
+ const activeElement = document.activeElement;
+
+ returnFocusElement = activeElement instanceof HTMLElement ? activeElement : null;
+};
+
+export const getCommandPaletteReturnFocusElement = (): HTMLElement | null =>
+ returnFocusElement?.isConnected ? returnFocusElement : null;
export const openCommandPalette = (): void => {
+ if (!commandPaletteStore.getSnapshot().isOpen) {
+ captureReturnFocusElement();
+ }
commandPaletteStore.setSnapshot({ isOpen: true });
};
@@ -19,5 +38,9 @@ export const closeCommandPalette = (): void => {
};
export const toggleCommandPalette = (): void => {
- commandPaletteStore.setSnapshot({ isOpen: !commandPaletteStore.getSnapshot().isOpen });
+ if (commandPaletteStore.getSnapshot().isOpen) {
+ closeCommandPalette();
+ } else {
+ openCommandPalette();
+ }
};
diff --git a/invokeai/frontend/webv2/src/workbench/palette/useCommandPaletteController.ts b/invokeai/frontend/webv2/src/workbench/palette/useCommandPaletteController.ts
index 43c07518cf..712e14e26d 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/useCommandPaletteController.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/useCommandPaletteController.ts
@@ -1,19 +1,18 @@
import type { DateTokenKey } from '@platform/search/dateTokens';
-/* eslint-disable react/react-compiler */
import type { ChangeEvent, KeyboardEvent } from 'react';
import { useMountEffect } from '@platform/react/useMountEffect';
import {
completeTrailingDateToken,
- formatDateRangeLabel,
+ formatIsoDate,
isPossibleDatePrefix,
matchTrailingDateToken,
parseDateTokens,
} from '@platform/search/dateTokens';
-import { useQueries } from '@tanstack/react-query';
-import { useCallback, useMemo, useRef, useState } from 'react';
+import { useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
-import type { PaletteEntry, PaletteRow, PaletteSearchProvider, PaletteStage, ProviderResultSection } from './entries';
+import type { PaletteEntry, PaletteProviderQuery, PaletteRow, PaletteSearchProvider, PaletteStage } from './entries';
import { getPaletteContributionKey } from './contributionKey';
import {
@@ -26,37 +25,46 @@ import {
searchPaletteRows,
STAGE_ENTRY_ID_PREFIX,
} from './entries';
-import { getPaletteProviderQueryKey } from './providerQueryKey';
+import { PaletteDebouncer } from './paletteDebouncer';
+import {
+ changePaletteSelection,
+ commitPaletteQuery,
+ createInitialPaletteState,
+ enterPaletteScope,
+ enterPaletteStage,
+ replacePaletteQuery,
+ returnPaletteToRoot,
+} from './paletteState';
import { getRecentEntryIds, recordRecentEntry } from './recents';
+import { usePaletteProviderSections } from './usePaletteProviderSections';
const PAGE_JUMP_ROWS = 8;
const PROVIDER_DEBOUNCE_MS = 200;
const NO_PROVIDERS: PaletteSearchProvider[] = [];
+export const COMMAND_PALETTE_INPUT_ID = 'command-palette-query';
/**
* Completions offered while a date token is being typed. `Nd` resolves to a
* single date N days ago, so the labels are key-specific: `from:7d` is a
* starting point ("Past week"), while `date:7d` is one day ("A week ago").
*/
-const DATE_TOKEN_SUGGESTIONS: Record<DateTokenKey, ReadonlyArray<{ label: string; value: string }>> = {
+const DATE_TOKEN_SUGGESTIONS: Record<DateTokenKey, ReadonlyArray<{ labelKey: string; value: string }>> = {
date: [
- { label: 'Today', value: 'today' },
- { label: 'Yesterday', value: 'yesterday' },
- { label: 'A week ago', value: '7d' },
+ { labelKey: 'commandPalette.date.today', value: 'today' },
+ { labelKey: 'commandPalette.date.yesterday', value: 'yesterday' },
+ { labelKey: 'commandPalette.date.aWeekAgo', value: '7d' },
],
from: [
- { label: 'Today', value: 'today' },
- { label: 'Yesterday', value: 'yesterday' },
- { label: 'Past week', value: '7d' },
+ { labelKey: 'commandPalette.date.today', value: 'today' },
+ { labelKey: 'commandPalette.date.yesterday', value: 'yesterday' },
+ { labelKey: 'commandPalette.date.pastWeek', value: '7d' },
],
to: [
- { label: 'Today', value: 'today' },
- { label: 'Yesterday', value: 'yesterday' },
+ { labelKey: 'commandPalette.date.today', value: 'today' },
+ { labelKey: 'commandPalette.date.yesterday', value: 'yesterday' },
],
};
-const DATE_FORMAT_HINT = 'Or type a date — YYYY-MM-DD, 7d, 2w, 1m';
-
type ScrollToIndex = (index: number) => void;
export interface CommandPaletteController {
@@ -75,8 +83,6 @@ export interface CommandPaletteController {
onRetry: () => void;
onRowActive: (rowId: string) => void;
onRowRun: (row: PaletteRow) => void;
- /** Run a row's mod+Enter secondary action (row-level pointer affordance). */
- onRowRunSecondary: (row: PaletteRow) => void;
onSearchChange: (event: ChangeEvent<HTMLInputElement>) => void;
onSearchKeyDown: (event: KeyboardEvent<HTMLInputElement>, scrollToIndex: ScrollToIndex) => void;
placeholder: string;
@@ -86,9 +92,10 @@ export interface CommandPaletteController {
scopeIsFetching: boolean;
scopeLabel: string | null;
secondaryHint: string | undefined;
- setInputElement: (node: HTMLInputElement | null) => void;
stage: PaletteStage | null;
trimmedQuery: string;
+ statusMessage: string;
+ isBusy: boolean;
}
export const useCommandPaletteController = ({
@@ -100,38 +107,32 @@ export const useCommandPaletteController = ({
onClose: () => void;
providers: PaletteSearchProvider[];
}): CommandPaletteController => {
- const [query, setQuery] = useState('');
- const [debouncedQuery, setDebouncedQuery] = useState('');
- const [activeRowId, setActiveRowId] = useState<string | null>(null);
- const [stage, setStage] = useState<PaletteStage | null>(null);
- const [scopeProviderKey, setScopeProviderKey] = useState<string | null>(null);
+ const { i18n, t } = useTranslation();
+ const [paletteState, setPaletteState] = useState(createInitialPaletteState);
const [recentIds] = useState(getRecentEntryIds);
- const inputRef = useRef<HTMLInputElement>(null);
- const debounceTimerRef = useRef<number | null>(null);
+ const [debouncer] = useState(
+ () =>
+ new PaletteDebouncer(PROVIDER_DEBOUNCE_MS, (value) => {
+ setPaletteState((current) => commitPaletteQuery(current, value));
+ })
+ );
- useMountEffect(() => () => {
- if (debounceTimerRef.current !== null) {
- window.clearTimeout(debounceTimerRef.current);
- }
- });
+ useMountEffect(() => debouncer.cancel);
- const setInputElement = useCallback((node: HTMLInputElement | null) => {
- inputRef.current = node;
- node?.focus();
- }, []);
const focusInput = useCallback(() => {
- window.requestAnimationFrame(() => inputRef.current?.focus());
- }, []);
- const clearDebounce = useCallback(() => {
- if (debounceTimerRef.current !== null) {
- window.clearTimeout(debounceTimerRef.current);
- debounceTimerRef.current = null;
- }
+ window.requestAnimationFrame(() => document.getElementById(COMMAND_PALETTE_INPUT_ID)?.focus());
}, []);
+ const clearDebounce = debouncer.cancel;
- const scopeProvider = scopeProviderKey
- ? (providers.find((provider) => provider.providerKey === scopeProviderKey) ?? null)
+ const requestedScopeProviderKey = paletteState.mode.kind === 'scoped' ? paletteState.mode.providerKey : null;
+ const scopeProvider = requestedScopeProviderKey
+ ? (providers.find((provider) => provider.providerKey === requestedScopeProviderKey) ?? null)
: null;
+ const resolvedMode =
+ paletteState.mode.kind === 'scoped' && scopeProvider === null ? { kind: 'root' as const } : paletteState.mode;
+ const stage = resolvedMode.kind === 'stage' ? resolvedMode.stage : null;
+ const scopeProviderKey = resolvedMode.kind === 'scoped' ? resolvedMode.providerKey : null;
+ const { activeRowId, debouncedQuery, query } = paletteState;
const isCommandsScope = !stage && !scopeProvider && query.startsWith('>');
const localQuery = isCommandsScope ? query.slice(1) : query;
const trimmedQuery = localQuery.trim();
@@ -151,23 +152,34 @@ export const useCommandPaletteController = ({
() => (datesEnabled ? parseDateTokens(debouncedQuery) : null),
[datesEnabled, debouncedQuery]
);
- const providerQuery = useMemo(
- () => ({ range: debouncedParse?.range, text: debouncedParse === null ? debouncedQuery : debouncedParse.text }),
+ const providerQuery = useMemo<PaletteProviderQuery>(
+ () => ({
+ range: debouncedParse?.range,
+ text: (debouncedParse === null ? debouncedQuery : debouncedParse.text).trim(),
+ }),
[debouncedParse, debouncedQuery]
);
+ const liveProviderQuery = useMemo<PaletteProviderQuery>(
+ () => ({ range: dateParse?.range, text: (dateParse === null ? localQuery : dateParse.text).trim() }),
+ [dateParse, localQuery]
+ );
+ const isWaitingForDebounce =
+ providerQuery.text !== liveProviderQuery.text ||
+ providerQuery.range?.from !== liveProviderQuery.range?.from ||
+ providerQuery.range?.to !== liveProviderQuery.range?.to;
// A valid date range is a complete query on its own — it bypasses the
// minimum text length so `from:7d` alone searches. An active scope is a
// committed search context: it searches at any length, including empty
// (initial recent results) and one character.
const shouldSearchProviders =
(scopeProvider !== null ||
- providerQuery.text.length >= PROVIDER_MIN_QUERY_LENGTH ||
- providerQuery.range !== undefined) &&
+ liveProviderQuery.text.length >= PROVIDER_MIN_QUERY_LENGTH ||
+ liveProviderQuery.range !== undefined) &&
!stage &&
!isCommandsScope;
// Pure date query (range, no text): only range-capable providers run —
// the rest would return broad, unfiltered results for empty text.
- const isPureDateQuery = providerQuery.range !== undefined && providerQuery.text.length === 0;
+ const isPureDateQuery = liveProviderQuery.range !== undefined && liveProviderQuery.text.length === 0;
const activeProviders = useMemo(() => {
if (stage || isCommandsScope) {
return NO_PROVIDERS;
@@ -178,40 +190,17 @@ export const useCommandPaletteController = ({
return isPureDateQuery ? base.filter((provider) => provider.supportsCreatedAtRange) : base;
}, [isCommandsScope, isPureDateQuery, providers, scopeProvider, stage]);
- const providerResults = useQueries({
- combine: (results) =>
- results.map((result) => ({
- data: result.data,
- isError: result.isError,
- isFetching: result.isFetching,
- refetch: result.refetch,
- })),
- queries: activeProviders.map((provider) => ({
- enabled: shouldSearchProviders,
- queryFn: () => Promise.resolve(provider.search(providerQuery)),
- queryKey: getPaletteProviderQueryKey(provider, providerQuery),
- retry: false,
- staleTime: 30_000,
- })),
+ const { results: providerResults, sections: providerSections } = usePaletteProviderSections({
+ enabled: shouldSearchProviders && !isWaitingForDebounce,
+ isWaitingForDebounce: shouldSearchProviders && isWaitingForDebounce,
+ providerQuery,
+ providers: activeProviders,
});
- const providerSections = useMemo<ProviderResultSection[]>(
- () =>
- activeProviders.map((provider, index) => ({
- entries: providerResults[index]?.data ?? [],
- isFetching: shouldSearchProviders && (providerResults[index]?.isFetching ?? false),
- provider,
- })),
- [activeProviders, providerResults, shouldSearchProviders]
- );
const scopedQueryResult = scopeProvider ? providerResults[0] : undefined;
const resetOverlayState = useCallback(() => {
clearDebounce();
- setStage(null);
- setScopeProviderKey(null);
- setQuery('');
- setDebouncedQuery('');
- setActiveRowId(null);
+ setPaletteState(returnPaletteToRoot());
}, [clearDebounce]);
const popOverlay = useCallback(() => {
resetOverlayState();
@@ -244,8 +233,7 @@ export const useCommandPaletteController = ({
const nextLocalQuery = !stage && !scopeProvider && nextQuery.startsWith('>') ? nextQuery.slice(1) : nextQuery;
const nextTrimmedQuery = nextLocalQuery.trim();
- setQuery(nextQuery);
- setActiveRowId(null);
+ setPaletteState((current) => replacePaletteQuery(current, nextQuery));
clearDebounce();
if (stage) {
@@ -256,16 +244,13 @@ export const useCommandPaletteController = ({
}
if (immediate) {
- setDebouncedQuery(nextTrimmedQuery);
+ debouncer.commit(nextTrimmedQuery);
return;
}
- debounceTimerRef.current = window.setTimeout(() => {
- debounceTimerRef.current = null;
- setDebouncedQuery(nextTrimmedQuery);
- }, PROVIDER_DEBOUNCE_MS);
+ debouncer.schedule(nextTrimmedQuery);
},
- [clearDebounce, onStageApplied, previewRow, scopeProvider, stage]
+ [clearDebounce, debouncer, onStageApplied, previewRow, scopeProvider, stage]
);
// Completion rows for an in-progress trailing token (`from:` → Today /
@@ -284,7 +269,7 @@ export const useCommandPaletteController = ({
const partial = trailing.partialValue.toLowerCase();
const options = DATE_TOKEN_SUGGESTIONS[trailing.key].filter((option) => option.value.startsWith(partial));
- const rows: PaletteRow[] = [{ id: 'label:date-suggestions', kind: 'label', label: 'Date' }];
+ const rows: PaletteRow[] = [{ id: 'label:date-suggestions', kind: 'label', label: t('commandPalette.date.date') }];
for (const option of options) {
const id = `date-suggestion:${trailing.key}:${option.value}`;
@@ -292,22 +277,23 @@ export const useCommandPaletteController = ({
rows.push({
entry: {
group: 'Date',
+ groupLabel: t('commandPalette.groups.date'),
id,
isPersistentRecent: false,
keepOpen: true,
run: () => replaceQuery(completeTrailingDateToken(query, option.value), { immediate: true }),
subtitle: `${trailing.key}:${option.value}`,
- title: option.label,
+ title: t(option.labelKey),
},
id,
kind: 'entry',
});
}
- rows.push({ id: 'label:date-format-hint', kind: 'label', label: DATE_FORMAT_HINT });
+ rows.push({ id: 'label:date-format-hint', kind: 'label', label: t('commandPalette.date.formatHint') });
return rows;
- }, [datesEnabled, query, replaceQuery]);
+ }, [datesEnabled, query, replaceQuery, t]);
const enterScope = useCallback(
(providerKey: string, { resetQuery = false }: { resetQuery?: boolean } = {}) => {
@@ -317,10 +303,7 @@ export const useCommandPaletteController = ({
const keptQuery = !target?.supportsCreatedAtRange && dateParse !== null ? dateParse.text.trim() : trimmedQuery;
clearDebounce();
- setScopeProviderKey(providerKey);
- setQuery(resetQuery ? '' : keptQuery);
- setDebouncedQuery(resetQuery ? '' : keptQuery);
- setActiveRowId(null);
+ setPaletteState(enterPaletteScope(providerKey, resetQuery ? '' : keptQuery));
focusInput();
},
[clearDebounce, dateParse, focusInput, providers, trimmedQuery]
@@ -335,25 +318,26 @@ export const useCommandPaletteController = ({
() =>
providers.map((provider) => ({
group: SEARCH_SCOPE_GROUP,
+ groupLabel: t('commandPalette.search.in'),
id: getPaletteContributionKey('scope-command', provider.providerKey),
isPersistentRecent: true,
keepOpen: true,
keywords: `search find browse ${provider.label.toLowerCase()}`,
run: () => enterScope(provider.providerKey, { resetQuery: true }),
showInEmptyState: true,
- title: `Search ${provider.label.toLowerCase()}…`,
+ title: t('commandPalette.search.provider', { label: provider.label.toLowerCase() }),
})),
- [enterScope, providers]
+ [enterScope, providers, t]
);
const allEntries = useMemo(() => [...entries, ...scopeCommandEntries], [entries, scopeCommandEntries]);
const rows = useMemo<PaletteRow[]>(() => {
if (stage) {
- return searchPaletteRows(buildStageEntries(stage, onStageApplied), query, [], { showAllOnEmpty: true });
+ return searchPaletteRows(buildStageEntries(stage, onStageApplied, t), query, [], { showAllOnEmpty: true });
}
if (scopeProvider) {
- return buildProviderSectionRows(providerSections, null);
+ return buildProviderSectionRows(providerSections, null, t);
}
const matchText = dateParse === null ? localQuery : dateParse.text;
@@ -365,6 +349,7 @@ export const useCommandPaletteController = ({
? []
: searchPaletteRows(allEntries, matchText, recentIds, {
commandsOnly: isCommandsScope,
+ recentLabel: t('commandPalette.groups.recent'),
showAllOnEmpty: isCommandsScope && trimmedQuery.length === 0,
});
@@ -376,8 +361,8 @@ export const useCommandPaletteController = ({
// Quiet trailing tip in the launcher — the only place the query syntax
// is advertised before it is typed.
const syntaxHint = providers.some((provider) => provider.supportsCreatedAtRange)
- ? 'Type > for commands · from:/date: to filter by date'
- : 'Type > for commands';
+ ? t('commandPalette.syntax.commandsAndDates')
+ : t('commandPalette.syntax.commands');
return [...localRows, { id: 'label:syntax-hint', kind: 'label', label: syntaxHint }];
}
@@ -388,9 +373,9 @@ export const useCommandPaletteController = ({
...dateSuggestionRows,
...localRows,
...(matchText.trim().length >= PROVIDER_MIN_QUERY_LENGTH || hasLiveRange
- ? buildProviderSectionRows(providerSections)
+ ? buildProviderSectionRows(providerSections, undefined, t)
: []),
- ...buildScopeRows(scopeProviders, isLivePureDate ? '' : matchText.trim()),
+ ...buildScopeRows(scopeProviders, isLivePureDate ? '' : matchText.trim(), t),
];
}, [
allEntries,
@@ -406,6 +391,7 @@ export const useCommandPaletteController = ({
scopeProvider,
stage,
trimmedQuery,
+ t,
]);
const navigableRows = useMemo(
() => rows.flatMap((row, index) => (row.kind === 'label' ? [] : [{ index, row }])),
@@ -426,6 +412,12 @@ export const useCommandPaletteController = ({
return;
}
+ if (row.kind === 'provider-error') {
+ row.retry();
+ focusInput();
+ return;
+ }
+
if (row.entry.isPersistentRecent) {
recordRecentEntry(row.entry);
}
@@ -435,10 +427,9 @@ export const useCommandPaletteController = ({
const currentOption = nextStage.options.find((option) => option.isCurrent);
clearDebounce();
- setStage(nextStage);
- setQuery('');
- setDebouncedQuery('');
- setActiveRowId(currentOption ? `${STAGE_ENTRY_ID_PREFIX}${currentOption.id}` : null);
+ setPaletteState(
+ enterPaletteStage(nextStage, currentOption ? `${STAGE_ENTRY_ID_PREFIX}${currentOption.id}` : null)
+ );
focusInput();
return;
}
@@ -470,15 +461,6 @@ export const useCommandPaletteController = ({
[onClose]
);
- const onRowRunSecondary = useCallback(
- (row: PaletteRow) => {
- if (row.kind === 'entry' && row.entry.secondary) {
- runSecondary(row.entry);
- }
- },
- [runSecondary]
- );
-
const moveActive = useCallback(
(offset: number, scrollToIndex: ScrollToIndex) => {
if (navigableRows.length === 0) {
@@ -498,7 +480,7 @@ export const useCommandPaletteController = ({
return;
}
- setActiveRowId(next.row.id);
+ setPaletteState((current) => changePaletteSelection(current, next.row.id));
previewRow(next.row);
scrollToIndex(next.index);
},
@@ -571,14 +553,14 @@ export const useCommandPaletteController = ({
const onRowActive = useCallback(
(rowId: string) => {
const row = rows.find((candidate) => candidate.id === rowId);
- setActiveRowId(rowId);
+ setPaletteState((current) => changePaletteSelection(current, rowId));
previewRow(row);
},
[previewRow, rows]
);
const onRetry = useCallback(() => {
- void scopedQueryResult?.refetch();
+ scopedQueryResult?.retry();
focusInput();
}, [focusInput, scopedQueryResult]);
@@ -602,9 +584,30 @@ export const useCommandPaletteController = ({
)
);
- return invalid ? `Invalid date: “${invalid.raw}”` : null;
- }, [dateParse, localQuery]);
- const dateSummary = dateParse?.range && dateInvalidHint === null ? formatDateRangeLabel(dateParse.range) : null;
+ return invalid ? t('commandPalette.states.invalidDate', { value: invalid.raw }) : null;
+ }, [dateParse, localQuery, t]);
+ const dateSummary =
+ dateParse?.range && dateInvalidHint === null
+ ? dateParse.range.from && dateParse.range.to
+ ? t('commandPalette.date.range', {
+ from: formatIsoDate(dateParse.range.from, i18n.resolvedLanguage),
+ to: formatIsoDate(dateParse.range.to, i18n.resolvedLanguage),
+ })
+ : dateParse.range.from
+ ? t('commandPalette.date.from', { date: formatIsoDate(dateParse.range.from, i18n.resolvedLanguage) })
+ : dateParse.range.to
+ ? t('commandPalette.date.through', { date: formatIsoDate(dateParse.range.to, i18n.resolvedLanguage) })
+ : null
+ : null;
+
+ const isBusy = providerSections.some((section) => section.isFetching || section.isWaitingForDebounce);
+ const failedProviderCount = providerSections.filter((section) => section.isError).length;
+ const providerResultCount = providerSections.reduce((count, section) => count + section.entries.length, 0);
+ const statusMessage = isBusy
+ ? t('commandPalette.states.searching')
+ : failedProviderCount > 0
+ ? t('commandPalette.states.partialFailure', { count: providerResultCount, failed: failedProviderCount })
+ : t('commandPalette.states.resultCount', { count: providerResultCount });
return {
dateInvalidHint,
@@ -613,28 +616,28 @@ export const useCommandPaletteController = ({
activeRowId: effectiveActiveRowId,
chipLabel: stage ? stage.title : (scopeProvider?.label ?? null),
hasScopeRows: rows.some((row) => row.kind === 'scope'),
- isOverlayOpen: Boolean(stage || scopeProviderKey),
+ isOverlayOpen: resolvedMode.kind !== 'root',
+ isBusy,
onContentKeyDown,
onPopOverlay: popOverlay,
onRetry,
onRowActive,
onRowRun: runRow,
- onRowRunSecondary,
onSearchChange,
onSearchKeyDown,
placeholder: stage
- ? 'Pick a value…'
+ ? t('commandPalette.placeholders.stage')
: scopeProvider
- ? `Search ${scopeProvider.label.toLowerCase()}…`
- : 'Search commands, settings, and more…',
+ ? t('commandPalette.placeholders.scope', { label: scopeProvider.label.toLowerCase() })
+ : t('commandPalette.placeholders.root'),
query,
rows,
scopeIsError: Boolean(scopeProvider && scopedQueryResult?.isError),
- scopeIsFetching: Boolean(scopeProvider && scopedQueryResult?.isFetching),
+ scopeIsFetching: Boolean(scopeProvider && (scopedQueryResult?.isFetching || isWaitingForDebounce)),
scopeLabel: scopeProvider?.label.toLowerCase() ?? null,
secondaryHint: activeRow?.kind === 'entry' ? activeRow.entry.secondary?.label : undefined,
- setInputElement,
stage,
+ statusMessage,
trimmedQuery,
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/palette/usePaletteProviderSections.ts b/invokeai/frontend/webv2/src/workbench/palette/usePaletteProviderSections.ts
new file mode 100644
index 0000000000..4abd027268
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/usePaletteProviderSections.ts
@@ -0,0 +1,66 @@
+import { useQueries } from '@tanstack/react-query';
+import { useMemo } from 'react';
+
+import type { PaletteProviderQuery, PaletteSearchProvider, ProviderResultSection } from './entries';
+
+import { getPaletteProviderQueryKey } from './providerQueryKey';
+
+export interface PaletteProviderQueryResult {
+ isError: boolean;
+ isFetching: boolean;
+ retry: () => void;
+}
+
+export const usePaletteProviderSections = ({
+ enabled,
+ isWaitingForDebounce,
+ providerQuery,
+ providers,
+}: {
+ enabled: boolean;
+ isWaitingForDebounce: boolean;
+ providerQuery: PaletteProviderQuery;
+ providers: PaletteSearchProvider[];
+}): { results: PaletteProviderQueryResult[]; sections: ProviderResultSection[] } => {
+ const queryResults = useQueries({
+ combine: (results) =>
+ results.map((result) => ({
+ data: result.data,
+ isError: result.isError,
+ isFetching: result.isFetching,
+ retry: () => void result.refetch(),
+ })),
+ queries: providers.map((provider) => ({
+ enabled,
+ gcTime: 60_000,
+ queryFn: ({ signal }: { signal: AbortSignal }) => Promise.resolve(provider.search(providerQuery, { signal })),
+ queryKey: getPaletteProviderQueryKey(provider, providerQuery),
+ retry: false,
+ staleTime: 0,
+ })),
+ });
+
+ const results = useMemo<PaletteProviderQueryResult[]>(
+ () =>
+ queryResults.map((result) => ({
+ isError: result.isError,
+ isFetching: result.isFetching,
+ retry: result.retry,
+ })),
+ [queryResults]
+ );
+ const sections = useMemo<ProviderResultSection[]>(
+ () =>
+ providers.map((provider, index) => ({
+ entries: queryResults[index]?.data ?? [],
+ isError: queryResults[index]?.isError ?? false,
+ isFetching: enabled && (queryResults[index]?.isFetching ?? false),
+ isWaitingForDebounce,
+ provider,
+ retry: queryResults[index]?.retry ?? (() => undefined),
+ })),
+ [enabled, isWaitingForDebounce, providers, queryResults]
+ );
+
+ return { results, sections };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
index 349879ac21..88312bb8f7 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
@@ -224,10 +224,16 @@ export interface WidgetSearchApi {
registerProvider: (provider: WidgetSearchProvider) => () => void;
}
+export interface WidgetSearchContext {
+ signal?: AbortSignal;
+}
+
export interface WidgetSearchProvider {
+ /** Identifies mutable inputs that affect results for the same query. */
+ contextKey?: string;
id: string;
label: string;
- search: (query: string) => Promise<WidgetSearchResult[]> | WidgetSearchResult[];
+ search: (query: string, context?: WidgetSearchContext) => Promise<WidgetSearchResult[]> | WidgetSearchResult[];
source?: WidgetContributionSource;
}
@@ -235,6 +241,7 @@ export interface WidgetSearchResult {
id: string;
title: string;
subtitle?: string;
+ /** Commandless results are informational and are omitted from the command palette. */
commandId?: string;
}
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index 2de1b27be2..4e38006f45 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -15,6 +15,15 @@ export default defineConfig({
rollupOptions: {
output: {
manualChunks(id) {
+ // The palette's tiny global state is an external-store selector;
+ // retain the established shared request instead of creating another.
+ if (id.endsWith('/platform/state/selectors.ts') || id.endsWith('/workbench/palette/paletteStore.ts')) {
+ return 'selectors';
+ }
+ if (id.endsWith('/platform/search/dateTokens.ts')) {
+ return 'vendor';
+ }
+
if (!id.includes('/node_modules/')) {
return undefined;
}
diff --git a/invokeai/frontend/webv2/vitest.browser.config.mts b/invokeai/frontend/webv2/vitest.browser.config.mts
index d1de280551..e069edf312 100644
--- a/invokeai/frontend/webv2/vitest.browser.config.mts
+++ b/invokeai/frontend/webv2/vitest.browser.config.mts
@@ -7,11 +7,21 @@ import viteConfig from './vite.config.mts';
export default mergeConfig(
viteConfig,
defineConfig({
- // Hook-bearing dependencies must be prebundled into the initial browser-test
- // graph. An optimization reload can otherwise leave the running suite with
- // two React instances and produce invalid-hook failures.
+ // Dependencies reached by browser tests must be prebundled into the initial
+ // graph. Late optimization reloads invalidate active Vitest suites, and
+ // React-bound dependencies can also leave two React instances in the graph
+ // and produce invalid-hook failures.
optimizeDeps: {
- include: ['@dnd-kit/core', '@tanstack/react-query', 'i18next-http-backend', 'react-hook-tanstack-virtual'],
+ include: [
+ '@chakra-ui/react',
+ '@chakra-ui/react/theme',
+ '@dnd-kit/core',
+ '@tanstack/react-query',
+ '@tanstack/react-virtual',
+ 'i18next-http-backend',
+ 'react-hook-tanstack-virtual',
+ 'tinykeys',
+ ],
},
test: {
browser: {
diff --git a/tests/app/routers/test_images.py b/tests/app/routers/test_images.py
index ab0712c01f..f8acada675 100644
--- a/tests/app/routers/test_images.py
+++ b/tests/app/routers/test_images.py
@@ -271,6 +271,54 @@ def test_get_image_names_forwards_created_range(monkeypatch: Any, mock_invoker:
assert kwargs["created_to"] == "2026-07-15"
[email protected]("path", ["/api/v1/images/", "/api/v1/images/names"])
[email protected]("board_id", ["all", "none"])
+def test_list_image_sentinel_scopes_skip_concrete_board_access_check(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient, path: str, board_id: str
+) -> None:
+ prepare_created_range_test(monkeypatch, mock_invoker)
+ access_check = MagicMock()
+ monkeypatch.setattr("invokeai.app.api.routers.images._assert_board_read_access", access_check)
+
+ response = client.get(path, params={"board_id": board_id})
+
+ assert response.status_code == 200
+ access_check.assert_not_called()
+
+
[email protected]("path", ["/api/v1/images/", "/api/v1/images/names"])
+def test_list_image_concrete_board_requires_read_access(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient, path: str
+) -> None:
+ prepare_created_range_test(monkeypatch, mock_invoker)
+ access_check = MagicMock()
+ monkeypatch.setattr("invokeai.app.api.routers.images._assert_board_read_access", access_check)
+
+ response = client.get(path, params={"board_id": "board-123"})
+
+ assert response.status_code == 200
+ access_check.assert_called_once()
+ assert access_check.call_args.args[0] == "board-123"
+
+
[email protected]("path", ["/api/v1/images/", "/api/v1/images/names"])
+def test_list_image_all_scope_combines_with_created_range(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient, path: str
+) -> None:
+ mock_get_many, mock_get_image_names = prepare_created_range_test(monkeypatch, mock_invoker)
+
+ response = client.get(
+ path,
+ params={"board_id": "all", "created_from": "2026-07-01", "created_to": "2026-07-15"},
+ )
+
+ assert response.status_code == 200
+ service_call = mock_get_image_names if path.endswith("/names") else mock_get_many
+ assert service_call.call_args.kwargs["board_id"] == "all"
+ assert service_call.call_args.kwargs["created_from"] == "2026-07-01"
+ assert service_call.call_args.kwargs["created_to"] == "2026-07-15"
+
+
def test_get_bulk_download_image_image_deleted_after_response(
monkeypatch: Any, mock_invoker: Invoker, tmp_path: Path, client: TestClient
) -> None:
diff --git a/tests/app/services/image_records/test_image_records_sqlite.py b/tests/app/services/image_records/test_image_records_sqlite.py
index 397e753104..4a67e6c6d5 100644
--- a/tests/app/services/image_records/test_image_records_sqlite.py
+++ b/tests/app/services/image_records/test_image_records_sqlite.py
@@ -8,6 +8,7 @@ and that get_many()/get_image_names() enforce per-user ownership isolation.
import pytest
from invokeai.app.services.board_image_records.board_image_records_sqlite import SqliteBoardImageRecordStorage
+from invokeai.app.services.board_records.board_records_common import BoardChanges, BoardVisibility
from invokeai.app.services.board_records.board_records_sqlite import SqliteBoardRecordStorage
from invokeai.app.services.config.config_default import InvokeAIAppConfig
from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
@@ -272,6 +273,159 @@ class TestOwnershipFilteringOmittedBoard:
assert result.image_names == ["u1-uncat.png"]
+class TestAllReadableBoardsFiltering:
+ def _seed_visibility_matrix(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> None:
+ image_store, board_store, board_image_store = stores
+
+ def add_boarded_image(
+ image_name: str,
+ *,
+ owner: str,
+ visibility: BoardVisibility = BoardVisibility.Private,
+ archived: bool = False,
+ ) -> str:
+ _save(image_store, image_name, user_id=owner)
+ board = board_store.save(board_name=image_name, user_id=owner)
+ board_store.update(
+ board.board_id,
+ BoardChanges(board_visibility=visibility, archived=archived),
+ )
+ board_image_store.add_image_to_board(board_id=board.board_id, image_name=image_name)
+ return board.board_id
+
+ add_boarded_image("own-private.png", owner="user1")
+ shared_private_id = add_boarded_image("explicit-share.png", owner="user2")
+ add_boarded_image("shared-visibility.png", owner="user2", visibility=BoardVisibility.Shared)
+ add_boarded_image("public-visibility.png", owner="user2", visibility=BoardVisibility.Public)
+ add_boarded_image("other-private.png", owner="user2")
+ add_boarded_image("own-archived.png", owner="user1", archived=True)
+ add_boarded_image(
+ "other-archived-public.png", owner="user2", visibility=BoardVisibility.Public, archived=True
+ )
+ _save(image_store, "own-uncategorized.png", user_id="user1")
+ _save(image_store, "other-uncategorized.png", user_id="user2")
+
+ with image_store._db.transaction() as cursor:
+ cursor.execute(
+ "INSERT OR IGNORE INTO users (user_id, email, password_hash) VALUES (?, ?, ?)",
+ ("user1", "[email protected]", "unused"),
+ )
+ cursor.execute(
+ "INSERT OR IGNORE INTO shared_boards (board_id, user_id) VALUES (?, ?)",
+ (shared_private_id, "user1"),
+ )
+
+ @pytest.mark.parametrize(
+ ("user_id", "is_admin", "expected"),
+ [
+ (
+ "user1",
+ False,
+ {
+ "own-private.png",
+ "explicit-share.png",
+ "shared-visibility.png",
+ "public-visibility.png",
+ "own-uncategorized.png",
+ },
+ ),
+ (
+ "admin",
+ True,
+ {
+ "own-private.png",
+ "explicit-share.png",
+ "shared-visibility.png",
+ "public-visibility.png",
+ "other-private.png",
+ "own-uncategorized.png",
+ "other-uncategorized.png",
+ },
+ ),
+ ],
+ )
+ def test_all_scope_authorization_and_counts_are_consistent(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ user_id: str,
+ is_admin: bool,
+ expected: set[str],
+ ) -> None:
+ self._seed_visibility_matrix(stores)
+ image_store = stores[0]
+ with image_store._db.transaction() as cursor:
+ cursor.executemany(
+ "UPDATE images SET starred = TRUE WHERE image_name = ?",
+ [("own-private.png",), ("other-private.png",)],
+ )
+
+ dtos = image_store.get_many(limit=100, board_id="all", user_id=user_id, is_admin=is_admin)
+ names = image_store.get_image_names(board_id="all", user_id=user_id, is_admin=is_admin)
+
+ assert {image.image_name for image in dtos.items} == expected
+ assert set(names.image_names) == expected
+ assert dtos.total == names.total_count == len(expected)
+ assert names.starred_count == len(expected & {"own-private.png", "other-private.png"})
+
+ def test_all_scope_combines_with_inclusive_date_filters(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> None:
+ self._seed_visibility_matrix(stores)
+ image_store = stores[0]
+ _set_created_at(image_store, "own-private.png", "2026-06-01 00:00:00.000")
+ _set_created_at(image_store, "explicit-share.png", "2026-06-01 23:59:59.999")
+ _set_created_at(image_store, "public-visibility.png", "2026-06-02 00:00:00.000")
+
+ dtos = image_store.get_many(
+ limit=100,
+ board_id="all",
+ user_id="user1",
+ created_from="2026-06-01",
+ created_to="2026-06-01",
+ )
+ names = image_store.get_image_names(
+ board_id="all",
+ user_id="user1",
+ created_from="2026-06-01",
+ created_to="2026-06-01",
+ )
+
+ assert {image.image_name for image in dtos.items} == {"own-private.png", "explicit-share.png"}
+ assert set(names.image_names) == {"own-private.png", "explicit-share.png"}
+ assert dtos.total == names.total_count == 2
+
+ @pytest.mark.parametrize(("user_id", "is_admin"), [("user1", False), ("admin", True)])
+ def test_all_scope_excludes_dangling_board_associations(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ user_id: str,
+ is_admin: bool,
+ ) -> None:
+ image_store = stores[0]
+ _save(image_store, "dangling.png", user_id="user1")
+ # Production foreign keys prevent this state, but imported/legacy DBs
+ # may contain it. Seed it deliberately to lock down fail-closed reads.
+ image_store._db._conn.execute("PRAGMA foreign_keys = OFF")
+ image_store._db._conn.execute(
+ "INSERT INTO board_images (board_id, image_name) VALUES (?, ?)",
+ ("deleted-board", "dangling.png"),
+ )
+ image_store._db._conn.commit()
+ image_store._db._conn.execute("PRAGMA foreign_keys = ON")
+
+ dtos = image_store.get_many(limit=100, board_id="all", user_id=user_id, is_admin=is_admin)
+ names = image_store.get_image_names(board_id="all", user_id=user_id, is_admin=is_admin)
+
+ assert dtos.items == []
+ assert dtos.total == 0
+ assert names.image_names == []
+ assert names.total_count == names.starred_count == 0
+
+
def _set_created_at(store: SqliteImageRecordStorage, name: str, created_at: str) -> None:
"""created_at is written by a SQL column default; tests override it directly."""
with store._db.transaction() as cursor: