Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(fonts): support custom fonts in webv2
Josh Corbett5cd0824f9cbe
diff --git a/.gitignore b/.gitignoreindex 45daa95ed4..d11f0c34f9 100644--- a/.gitignore+++ b/.gitignore@@ -144,6 +144,7 @@ invokeai.example.yaml/configs//nodes//outputs/+/fonts/# Spyder project settings.spyderprojectdiff --git a/docs/src/content/docs/development/Front End/project-files.mdx b/docs/src/content/docs/development/Front End/project-files.mdxindex 272a44d258..2dd60b9b2d 100644--- a/docs/src/content/docs/development/Front End/project-files.mdx+++ b/docs/src/content/docs/development/Front End/project-files.mdx@@ -59,6 +59,14 @@ client from opening a v3 project: it is treated as v2, not as unrestricted. Theforward-version gate and the project API adapter consume the same constant so advertised supportcannot drift from actual parsing support.+## Custom fonts++Webv2 exports font dependencies in the manifest's optional `fonts` array. Each dependency records a SHA-256 content hash, readable family and face labels, source reference IDs, and an optional `fonts/<hash>.<extension>` entry. The Canvas schema compatibility floor protects the newer editable text fields; the ZIP manifest remains version 2.++**Include font files** is unchecked by default. When selected, export authenticates and verifies every required font download, bundles each original file once, and fails if a requested font is missing or changed. Variable fonts travel as their original files, preserving editable axes. Export does not infer redistribution rights from metadata.++Import verifies dependency paths and hashes before any mutation, preflights font validity, then installs embedded files into the recipient's private library. Exact private duplicates are reused; font references are remapped by content hash, never by family name. A quota failure can be retried explicitly with references only. Cleanup tracks newly created font IDs and never deletes pre-existing duplicates or resources whose project creation outcome is unknown.+## File format`.invk` files are ZIP archives. The current manifest version is `2`.diff --git a/docs/src/content/docs/features/Canvas/text-tool.mdx b/docs/src/content/docs/features/Canvas/text-tool.mdxindex c826610139..cef6093226 100644--- a/docs/src/content/docs/features/Canvas/text-tool.mdx+++ b/docs/src/content/docs/features/Canvas/text-tool.mdx@@ -21,6 +21,16 @@ InvokeAI can also load custom fonts from the host-managed `fonts_dir` directory.In multiuser deployments, this directory is shared by the entire InvokeAI instance. Fonts added there are available to all authenticated users of that server.+### Webv2 font library++When using webv2 (`--webv2`), open **Fonts** in Launchpad. Select a font in the library column to preview it and inspect its variation axes and named instances. Use **Add Fonts** to upload files. Uploads default to **My fonts**, visible only to your account. Administrators can upload **Shared fonts** for everyone on the server. Fonts discovered in `fonts_dir` are marked as coming from the server directory; the app can rescan them but does not delete those files.++Choose an uploaded or shared face in the Canvas text picker. Variable fonts expose their named instances and variation axes, including custom axes. Changing an axis loads the selected instance before updating the rendered text.++If a project uses a missing font, its reference is retained. The missing-font dialog lets you retry, upload the font, or choose a replacement for affected layers. You can continue editing with a marked fallback preview, but operations that render affected text into output require the font to be resolved.++Project exports normally contain font references only. Select **Include font files** to bundle used fonts when you have permission to redistribute them. Importing an archive with fonts adds them to the recipient's private library. Deleting an uploaded font does not rewrite projects that use it; those projects will need the font installed again or explicitly replaced.+## Size and spacing- **Size** controls the font size in pixels.diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.jsonindex 657ebd346c..0fc31cbfb0 100644--- a/docs/src/generated/settings.json+++ b/docs/src/generated/settings.json@@ -224,6 +224,39 @@"type": "<class 'pathlib.Path'>","validation": {}},+ {+ "category": "PATHS",+ "default": "fonts-uploaded",+ "description": "Path to application-managed uploaded fonts.",+ "env_var": "INVOKEAI_FONTS_STORAGE_DIR",+ "literal_values": [],+ "name": "fonts_storage_dir",+ "required": false,+ "type": "<class 'pathlib.Path'>",+ "validation": {}+ },+ {+ "category": "PATHS",+ "default": 33554432,+ "description": "Maximum size of one uploaded custom font in bytes.",+ "env_var": "INVOKEAI_MAX_FONT_UPLOAD_BYTES",+ "literal_values": [],+ "name": "max_font_upload_bytes",+ "required": false,+ "type": "<class 'int'>",+ "validation": {}+ },+ {+ "category": "PATHS",+ "default": 1073741824,+ "description": "Maximum total size of uploaded custom fonts in bytes per account or shared library.",+ "env_var": "INVOKEAI_MAX_FONT_LIBRARY_BYTES",+ "literal_values": [],+ "name": "max_font_library_bytes",+ "required": false,+ "type": "<class 'int'>",+ "validation": {}+ },{"category": "PATHS","default": "flat",diff --git a/invokeai/app/api/dependencies.py b/invokeai/app/api/dependencies.pyindex f172c88b1b..da8b1fdb08 100644--- a/invokeai/app/api/dependencies.py+++ b/invokeai/app/api/dependencies.py@@ -25,6 +25,7 @@ from invokeai.app.services.external_generation.providers import (SeedreamProvider,)from invokeai.app.services.external_generation.startup import sync_configured_external_starter_models+from invokeai.app.services.fonts.fonts_default import FontServicefrom invokeai.app.services.gallery.gallery_default import SqliteGalleryServicefrom invokeai.app.services.image_files.image_files_disk import DiskImageFileStoragefrom invokeai.app.services.image_index.image_index_default import ImageIndexService, warm_up_attention@@ -221,6 +222,14 @@ class ApiDependencies:users = UserService(db=db)image_index_records = ImageIndexRecordsSqlite(db=db)image_index = ImageIndexService()+ fonts = FontService(+ db=db,+ fonts_dir=configuration.fonts_path,+ storage_dir=configuration.fonts_storage_path,+ logger=logger,+ max_upload_bytes=configuration.max_font_upload_bytes,+ max_library_bytes=configuration.max_font_library_bytes,+ )services = InvocationServices(board_image_records=board_image_records,@@ -266,6 +275,7 @@ class ApiDependencies:gallery=gallery,image_index_records=image_index_records,image_index=image_index,+ fonts=fonts,)# Constructing the Invoker starts every service, including the sessiondiff --git a/invokeai/app/api/routers/auth.py b/invokeai/app/api/routers/auth.pyindex ab32f99aeb..bdde3ab5fd 100644--- a/invokeai/app/api/routers/auth.py+++ b/invokeai/app/api/routers/auth.py@@ -686,6 +686,18 @@ def delete_user(detail=LAST_ADMIN_DETAIL,)+ fonts = getattr(ApiDependencies.invoker.services, "fonts", None)+ font_storage_paths: tuple[str, ...] = ()+ if fonts is not None:+ try:+ font_storage_paths = fonts.prepare_user_cleanup(user_id)+ except Exception:+ # The user deletion must still proceed; a later startup sweep can reclaim files+ # if the pre-delete snapshot could not be read.+ ApiDependencies.invoker.services.logger.warning(+ "Unable to snapshot fonts before deleting user %s", user_id, exc_info=True+ )+try:user_service.delete(user_id)except ValueError as e:@@ -694,6 +706,16 @@ def delete_user(# A deleted user must lose live access just like a deactivated one.ApiDependencies.invoker.services.events.emit_user_access_changed(user_id=user_id, is_admin=False, is_active=False)+ # Cleanup is best effort. The account is already gone, and a storage or filesystem+ # failure must not prevent the revocation event above from reaching live sessions.+ if fonts is not None:+ try:+ fonts.cleanup_user(user_id, font_storage_paths)+ except Exception:+ ApiDependencies.invoker.services.logger.warning(+ "Unable to clean up fonts after deleting user %s", user_id, exc_info=True+ )+@auth_router.patch("/me", response_model=UserDTO)def update_current_user(diff --git a/invokeai/app/api/routers/fonts.py b/invokeai/app/api/routers/fonts.pynew file mode 100644index 0000000000..0c4ed16d14--- /dev/null+++ b/invokeai/app/api/routers/fonts.py@@ -0,0 +1,357 @@+"""Authenticated custom-font catalog and file routes."""++from __future__ import annotations++import hashlib+import json+from pathlib import Path+from typing import Literal, cast+from urllib.parse import quote++from fastapi import APIRouter, File, Form, HTTPException, Query, Response, UploadFile, status+from fastapi import Path as PathParam+from pydantic import BaseModel, Field++from invokeai.app.api.auth_dependencies import AdminUserOrDefault, CurrentUserOrDefault+from invokeai.app.api.dependencies import ApiDependencies+from invokeai.app.services.fonts.fonts_common import FontAxis, FontInstance, FontRecord, FontScope+from invokeai.app.services.fonts.fonts_default import (+ FONT_MEDIA_TYPES,+ FontChangedError,+ FontDeleteForbiddenError,+ FontForbiddenError,+ FontInstanceError,+ FontNotFoundError,+ FontQuotaExceededError,+ FontService,+ FontStorageError,+ FontValidationError,+)+from invokeai.app.services.shared.pagination import MAX_PAGE_SIZE++fonts_router = APIRouter(prefix="/v1/fonts", tags=["fonts"])++# The request-body limiter runs before Starlette parses multipart uploads. Keep the framing+# allowance bounded so the configured font limit remains the dominant part of the request cap.+FONT_UPLOAD_MULTIPART_OVERHEAD = 1024 * 1024+MAX_CONCURRENT_FONT_UPLOADS = 2+MAX_CONCURRENT_FONT_UPLOADS_PER_USER = 1+FONT_UPLOAD_IDLE_TIMEOUT_SECONDS = 30.0+FONT_UPLOAD_MAX_DURATION_SECONDS = 120.0+++class FontAxisDTO(BaseModel):+ tag: str+ label: str+ minimum: float+ default: float+ maximum: float+ hidden: bool+++class FontInstanceDTO(BaseModel):+ name: str+ coordinates: dict[str, float]+++class FontDTO(BaseModel):+ id: str+ family: str+ label: str+ style: str+ weight: int+ content_hash: str+ scope: Literal["private", "shared"]+ source: Literal["uploaded", "directory"]+ filename: str+ byte_size: int+ url: str+ axes: list[FontAxisDTO]+ instances: list[FontInstanceDTO]+++class FontListResponse(BaseModel):+ offset: int+ limit: int+ total: int+ items: list[FontDTO]+++class FontUploadResponse(BaseModel):+ font: FontDTO+ created: bool+++class FontValidationResponse(BaseModel):+ filename: str+ family: str+ label: str+ style: str+ weight: int+ content_hash: str+ byte_size: int+ axes: list[FontAxisDTO]+ instances: list[FontInstanceDTO]+++class FontInstanceRequest(BaseModel):+ content_hash: str = Field(min_length=64, max_length=64, pattern=r"^[a-f0-9]{64}$")+ coordinates: dict[str, float] = Field(default_factory=dict)+++class FontRescanResponse(BaseModel):+ indexed: int+ revision: int+++def _get_font_service() -> FontService:+ service = getattr(ApiDependencies.invoker.services, "fonts", None)+ if service is None:+ raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Font service is unavailable")+ return cast(FontService, service)+++def _font_url(font_id: str) -> str:+ return f"/api/v1/fonts/{quote(font_id, safe='')}/file"+++def _axis_dto(axis: FontAxis) -> FontAxisDTO:+ return FontAxisDTO(+ tag=axis.tag,+ label=axis.label,+ minimum=axis.minimum,+ default=axis.default,+ maximum=axis.maximum,+ hidden=axis.hidden,+ )+++def _instance_dto(instance: FontInstance) -> FontInstanceDTO:+ return FontInstanceDTO(name=instance.name, coordinates=instance.coordinates)+++def _font_dto(font: FontRecord) -> FontDTO:+ return FontDTO(+ id=font.id,+ family=font.family,+ label=font.label,+ style=font.style,+ weight=font.weight,+ content_hash=font.content_hash,+ scope=font.scope.value,+ source=font.source.value,+ filename=font.filename,+ byte_size=font.byte_size,+ url=_font_url(font.id),+ axes=[_axis_dto(axis) for axis in font.axes],+ instances=[_instance_dto(instance) for instance in font.instances],+ )+++def _inline_content_disposition(filename: str) -> str:+ safe_filename = filename.replace("\r", "").replace("\n", "")+ return f"inline; filename*=UTF-8''{quote(safe_filename, safe='')}"+++def _get_font_cache_control(font: FontRecord | None = None) -> str:+ """Prevent cross-account browser reuse of font responses in multiuser mode."""+ if ApiDependencies.invoker.services.configuration.multiuser:+ return "private, no-store"+ if font is not None and font.source.value == "uploaded":+ return "private, max-age=31536000, immutable"+ return "private, no-cache"+++def _read_upload(file: UploadFile, max_bytes: int) -> bytes:+ chunks: list[bytes] = []+ size = 0+ while True:+ chunk = file.file.read(min(1024 * 1024, max_bytes - size + 1))+ if not chunk:+ break+ size += len(chunk)+ if size > max_bytes:+ raise FontQuotaExceededError("Font file exceeds the upload size limit")+ chunks.append(chunk)+ return b"".join(chunks)+++def _raise_font_http_error(error: Exception) -> None:+ if isinstance(error, FontNotFoundError):+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Font not found") from error+ if isinstance(error, FontChangedError):+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(error)) from error+ if isinstance(error, FontDeleteForbiddenError | FontForbiddenError):+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(error)) from error+ if isinstance(error, FontQuotaExceededError):+ raise HTTPException(status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, detail=str(error)) from error+ if isinstance(error, FontValidationError | FontInstanceError):+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(error)) from error+ if isinstance(error, FontStorageError):+ raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Font storage failed") from error+ raise error+++@fonts_router.get("", response_model=FontListResponse, operation_id="list_fonts")+def list_fonts(+ current_user: CurrentUserOrDefault,+ response: Response,+ offset: int = Query(default=0, ge=0),+ limit: int = Query(default=100, ge=0, le=MAX_PAGE_SIZE),+ search: str | None = Query(default=None, max_length=200),+ scope: FontScope = Query(default=FontScope.ALL),+ content_hash: str | None = Query(default=None, min_length=64, max_length=64, pattern=r"^[a-f0-9]{64}$"),+) -> FontListResponse:+ service = _get_font_service()+ try:+ fonts, total = service.list(+ user_id=current_user.user_id,+ offset=offset,+ limit=limit,+ search=search,+ scope=scope,+ content_hash=content_hash,+ )+ except Exception as e:+ _raise_font_http_error(e)+ response.headers["Cache-Control"] = _get_font_cache_control()+ response.headers["X-Font-Catalog-Revision"] = str(service.revision)+ return FontListResponse(offset=offset, limit=limit, total=total, items=[_font_dto(font) for font in fonts])+++@fonts_router.post("/validate", response_model=FontValidationResponse, operation_id="validate_font")+def validate_font(+ current_user: CurrentUserOrDefault, file: UploadFile = File(description="The font file to validate")+) -> FontValidationResponse:+ del current_user+ service = _get_font_service()+ try:+ validation = service.validate(file.filename or "", _read_upload(file, service.max_upload_bytes))+ except Exception as e:+ _raise_font_http_error(e)+ return FontValidationResponse(+ filename=validation.filename,+ family=validation.family,+ label=validation.label,+ style=validation.style,+ weight=validation.weight,+ content_hash=validation.content_hash,+ byte_size=validation.byte_size,+ axes=[_axis_dto(axis) for axis in validation.axes],+ instances=[_instance_dto(instance) for instance in validation.instances],+ )+++@fonts_router.post("", response_model=FontUploadResponse, operation_id="upload_font")+def upload_font(+ current_user: CurrentUserOrDefault,+ response: Response,+ file: UploadFile = File(description="The font file to upload"),+ scope: str = Form(default=FontScope.PRIVATE.value),+) -> FontUploadResponse:+ service = _get_font_service()+ try:+ requested_scope = FontScope(scope)+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Invalid font scope") from e+ if requested_scope == FontScope.ALL:+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Invalid font scope")+ if requested_scope == FontScope.SHARED and not current_user.is_admin:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin privileges required for shared fonts")+ try:+ result = service.upload(+ user_id=current_user.user_id,+ filename=file.filename or "",+ data=_read_upload(file, service.max_upload_bytes),+ scope=requested_scope,+ )+ except Exception as e:+ _raise_font_http_error(e)+ response.headers["X-Font-Catalog-Revision"] = str(service.revision)+ return FontUploadResponse(font=_font_dto(result.font), created=result.created)+++@fonts_router.post("/rescan", response_model=FontRescanResponse, operation_id="rescan_fonts")+def rescan_fonts(_admin_user: AdminUserOrDefault) -> FontRescanResponse:+ service = _get_font_service()+ return FontRescanResponse(indexed=service.rescan_directory(), revision=service.revision)+++@fonts_router.get("/{font_id}/file", operation_id="get_font_file")+def get_font_file(+ current_user: CurrentUserOrDefault,+ font_id: str = PathParam(min_length=1),+ expected_hash: str | None = Query(default=None, min_length=64, max_length=64, pattern=r"^[a-f0-9]{64}$"),+) -> Response:+ service = _get_font_service()+ try:+ font, data = service.read_file(user_id=current_user.user_id, font_id=font_id, expected_hash=expected_hash)+ except Exception as e:+ _raise_font_http_error(e)+ extension = Path(font.filename).suffix.lower()+ return Response(+ content=data,+ media_type=FONT_MEDIA_TYPES.get(extension, "application/octet-stream"),+ headers={+ "Cache-Control": _get_font_cache_control(font),+ "ETag": f'"{font.content_hash}"',+ "Content-Disposition": _inline_content_disposition(font.filename),+ },+ )+++@fonts_router.get("/{font_id}", response_model=FontDTO, operation_id="get_font")+def get_font(current_user: CurrentUserOrDefault, response: Response, font_id: str = PathParam(min_length=1)) -> FontDTO:+ service = _get_font_service()+ try:+ font = service.get_accessible(user_id=current_user.user_id, font_id=font_id)+ except Exception as e:+ _raise_font_http_error(e)+ response.headers["Cache-Control"] = _get_font_cache_control()+ return _font_dto(font)+++@fonts_router.post("/{font_id}/instance", operation_id="create_font_instance")+def create_font_instance(+ current_user: CurrentUserOrDefault,+ request: FontInstanceRequest,+ font_id: str = PathParam(min_length=1),+) -> Response:+ service = _get_font_service()+ try:+ font, data = service.instance(+ user_id=current_user.user_id,+ font_id=font_id,+ content_hash=request.content_hash,+ coordinates=request.coordinates,+ )+ except Exception as e:+ _raise_font_http_error(e)+ extension = Path(font.filename).suffix.lower()+ return Response(+ content=data,+ media_type=FONT_MEDIA_TYPES.get(extension, "application/octet-stream"),+ headers={+ "Cache-Control": _get_font_cache_control(font),+ "ETag": f'"{font.content_hash}-{hashlib.sha256(json.dumps(request.coordinates, sort_keys=True).encode()).hexdigest()[:16]}"',+ "Content-Disposition": _inline_content_disposition(f"{Path(font.filename).stem}-instance{extension}"),+ },+ )+++@fonts_router.delete("/{font_id}", status_code=status.HTTP_204_NO_CONTENT, operation_id="delete_font")+def delete_font(current_user: CurrentUserOrDefault, font_id: str = PathParam(min_length=1)) -> Response:+ service = _get_font_service()+ try:+ service.delete(user_id=current_user.user_id, font_id=font_id, is_admin=current_user.is_admin)+ except Exception as e:+ _raise_font_http_error(e)+ return Response(status_code=status.HTTP_204_NO_CONTENT, headers={"X-Font-Catalog-Revision": str(service.revision)})+++__all__ = [+ "FontDTO",+ "FontListResponse",+ "FontUploadResponse",+ "fonts_router",+]diff --git a/invokeai/app/api/routers/utilities.py b/invokeai/app/api/routers/utilities.pyindex a5b7401cb9..2e6af7b63a 100644--- a/invokeai/app/api/routers/utilities.py+++ b/invokeai/app/api/routers/utilities.py@@ -40,7 +40,9 @@ FONT_MEDIA_TYPES = {".woff": "font/woff",".woff2": "font/woff2",}-FONT_CACHE_CONTROL = "private, max-age=31536000, immutable"+# Directory-backed files can be replaced in place. They must not be pinned by the browser's+# immutable cache, otherwise a rescan can expose stale bytes to a project.+FONT_CACHE_CONTROL = "private, no-cache"# The underlying model loader is not thread-safe, so we serialize load_model calls._model_load_lock = threading.Lock()diff --git a/invokeai/app/api_app.py b/invokeai/app/api_app.pyindex b37644c24c..6c49be86a9 100644--- a/invokeai/app/api_app.py+++ b/invokeai/app/api_app.py@@ -28,6 +28,7 @@ from invokeai.app.api.routers import (boards,client_state,custom_nodes,+ fonts,gallery,image_map,image_moves,@@ -571,6 +572,10 @@ def _is_project_write(method: str, path: str) -> bool:return bool(project_id) and "/" not in project_id+def _is_font_upload(method: str, path: str) -> bool:+ return method == "POST" and path in ("/api/v1/fonts", "/api/v1/fonts/validate")++class ProjectWriteLimitASGIMiddleware(RequestBodyLimitASGIMiddleware):"""Bound project writes before FastAPI parses their JSON documents."""@@ -656,6 +661,23 @@ app.add_middleware(max_concurrent_per_user=videos.MAX_CONCURRENT_VIDEO_UPLOADS_PER_USER,identify_user=_identify_video_upload_user_async,)+app.add_middleware(+ RequestBodyLimitASGIMiddleware,+ matches_request=_is_font_upload,+ too_large_detail=lambda _actual, limit: f"Font upload exceeds maximum request size ({limit} bytes)",+ capacity_refusal_detail=lambda per_user: (+ "Too many concurrent font uploads for this user; try again shortly"+ if per_user+ else "Too many concurrent font uploads; try again shortly"+ ),+ max_body_bytes=app_config.max_font_upload_bytes + fonts.FONT_UPLOAD_MULTIPART_OVERHEAD,+ max_concurrent=fonts.MAX_CONCURRENT_FONT_UPLOADS,+ max_concurrent_per_user=fonts.MAX_CONCURRENT_FONT_UPLOADS_PER_USER,+ identify_user=_identify_video_upload_user_async,+ idle_timeout_seconds=fonts.FONT_UPLOAD_IDLE_TIMEOUT_SECONDS,+ max_upload_duration_seconds=fonts.FONT_UPLOAD_MAX_DURATION_SECONDS,+ retry_after_seconds=1,+)app.add_middleware(ProjectWriteLimitASGIMiddleware,max_body_bytes=projects.PROJECT_WRITE_REQUEST_MAX_BYTES,@@ -693,6 +715,7 @@ configure_gzip(app, app_config.http_compression_level)# Authentication router should be first so it's registered before protected routesapp.include_router(auth.auth_router, prefix="/api")app.include_router(utilities.utilities_router, prefix="/api")+app.include_router(fonts.fonts_router, prefix="/api")app.include_router(model_manager.model_manager_router, prefix="/api")app.include_router(image_moves.image_moves_router, prefix="/api")app.include_router(images.images_router, prefix="/api")diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.pyindex 5a7b2c0c4d..dc43d70027 100644--- a/invokeai/app/services/config/config_default.py+++ b/invokeai/app/services/config/config_default.py@@ -190,6 +190,9 @@ class InvokeAIAppConfig(BaseSettings):db_dir: Path = Field(default=Path("databases"), description="Path to InvokeAI databases directory.")outputs_dir: Path = Field(default=Path("outputs"), description="Path to directory for outputs.")fonts_dir: Path = Field(default=Path("fonts"), description="Path to directory for custom fonts.")+ fonts_storage_dir: Path = Field(default=Path("fonts-uploaded"), description="Path to application-managed uploaded fonts.")+ max_font_upload_bytes: int = Field(default=32 * 1024 * 1024, gt=0, le=128 * 1024 * 1024, description="Maximum size of one uploaded custom font in bytes.")+ max_font_library_bytes: int = Field(default=1024 * 1024 * 1024, gt=0, le=16 * 1024 * 1024 * 1024, description="Maximum total size of uploaded custom fonts in bytes per account or shared library.")image_subfolder_strategy: IMAGE_SUBFOLDER_STRATEGY = Field(default="flat", description="Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.")custom_nodes_dir: Path = Field(default=Path("nodes"), description="Path to directory for custom nodes.")style_presets_dir: Path = Field(default=Path("style_presets"), description="Path to directory for style presets.")@@ -431,6 +434,11 @@ class InvokeAIAppConfig(BaseSettings):"""Path to the custom fonts directory, resolved to an absolute path."""return self._resolve(self.fonts_dir)+ @property+ def fonts_storage_path(self) -> Path:+ """Path to application-managed uploaded fonts, resolved to an absolute path."""+ return self._resolve(self.fonts_storage_dir)+@propertydef db_path(self) -> Path:"""Path to the invokeai.db file, resolved to an absolute path.."""diff --git a/invokeai/app/services/fonts/__init__.py b/invokeai/app/services/fonts/__init__.pynew file mode 100644index 0000000000..cd0dc1e564--- /dev/null+++ b/invokeai/app/services/fonts/__init__.py@@ -0,0 +1,43 @@+"""Font library services."""++from invokeai.app.services.fonts.fonts_common import (+ FontAxis,+ FontInstance,+ FontRecord,+ FontScope,+ FontSource,+ FontUploadResult,+ FontValidationResult,+)+from invokeai.app.services.fonts.fonts_default import (+ FontChangedError,+ FontDeleteForbiddenError,+ FontForbiddenError,+ FontInstanceError,+ FontNotFoundError,+ FontQuotaExceededError,+ FontService,+ FontServiceError,+ FontStorageError,+ FontValidationError,+)++__all__ = [+ "FontAxis",+ "FontChangedError",+ "FontDeleteForbiddenError",+ "FontForbiddenError",+ "FontInstance",+ "FontInstanceError",+ "FontNotFoundError",+ "FontQuotaExceededError",+ "FontRecord",+ "FontScope",+ "FontService",+ "FontServiceError",+ "FontSource",+ "FontStorageError",+ "FontUploadResult",+ "FontValidationError",+ "FontValidationResult",+]diff --git a/invokeai/app/services/fonts/fonts_common.py b/invokeai/app/services/fonts/fonts_common.pynew file mode 100644index 0000000000..dc6daeecfe--- /dev/null+++ b/invokeai/app/services/fonts/fonts_common.py@@ -0,0 +1,86 @@+"""Domain types for the managed and configured font libraries."""++from __future__ import annotations++from dataclasses import dataclass+from enum import StrEnum+++class FontScope(StrEnum):+ """The account scope of an uploaded font."""++ PRIVATE = "private"+ SHARED = "shared"+ ALL = "all"+++class FontSource(StrEnum):+ """How the font file is supplied to InvokeAI."""++ UPLOADED = "uploaded"+ DIRECTORY = "directory"+++@dataclass(frozen=True)+class FontAxis:+ """One OpenType variation axis."""++ tag: str+ label: str+ minimum: float+ default: float+ maximum: float+ hidden: bool+++@dataclass(frozen=True)+class FontInstance:+ """A named OpenType variation instance."""++ name: str+ coordinates: dict[str, float]+++@dataclass(frozen=True)+class FontRecord:+ """A single font file face indexed by the service."""++ id: str+ family: str+ label: str+ style: str+ weight: int+ content_hash: str+ scope: FontScope+ source: FontSource+ filename: str+ byte_size: int+ axes: tuple[FontAxis, ...]+ instances: tuple[FontInstance, ...]+ # Internal ownership key. API serializers intentionally omit this field.+ owner_id: str | None = None+ storage_path: str | None = None+ source_path: str | None = None+++@dataclass(frozen=True)+class FontValidationResult:+ """Validated metadata for a file that has not been persisted yet."""++ filename: str+ family: str+ label: str+ style: str+ weight: int+ content_hash: str+ byte_size: int+ axes: tuple[FontAxis, ...]+ instances: tuple[FontInstance, ...]+++@dataclass(frozen=True)+class FontUploadResult:+ """The result of an upload, including whether a hash dedupe was used."""++ font: FontRecord+ created: booldiff --git a/invokeai/app/services/fonts/fonts_default.py b/invokeai/app/services/fonts/fonts_default.pynew file mode 100644index 0000000000..a6b53fe678--- /dev/null+++ b/invokeai/app/services/fonts/fonts_default.py@@ -0,0 +1,1005 @@+"""SQLite-backed custom font library.++The service keeps the configured ``fonts_dir`` as a read-only, shared source and stores+uploads in an application-owned directory. Font files are addressed by opaque IDs and+content hashes, so a changed directory file cannot silently satisfy an old project+reference.+"""++from __future__ import annotations++import hashlib+import io+import json+import logging+import math+import os+import pickle+import re+import subprocess+import sys+import threading+from collections import OrderedDict+from pathlib import Path+from typing import Any+from uuid import uuid4++from fontTools.ttLib import TTFont+from fontTools.varLib.instancer import instantiateVariableFont++from invokeai.app.services.fonts.fonts_common import (+ FontAxis,+ FontInstance,+ FontRecord,+ FontScope,+ FontSource,+ FontUploadResult,+ FontValidationResult,+)+from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase++SUPPORTED_FONT_EXTENSIONS = frozenset({".ttf", ".otf", ".woff", ".woff2"})+FONT_MEDIA_TYPES = {+ ".ttf": "font/ttf",+ ".otf": "font/otf",+ ".woff": "font/woff",+ ".woff2": "font/woff2",+}++MAX_FONT_UPLOAD_BYTES = 32 * 1024 * 1024+MAX_FONT_LIBRARY_BYTES = 1024 * 1024 * 1024+MAX_INDEXED_FONT_BYTES = 128 * 1024 * 1024+MAX_INSTANCE_JOBS = 2+MAX_INSTANCE_QUEUE = 4+MAX_INSTANCE_CACHE_BYTES = 64 * 1024 * 1024+INSTANCE_JOB_TIMEOUT_SECONDS = 30.0++_FONT_COLUMNS = """+ id, owner_id, family, label, style, weight, content_hash, scope, source, filename,+ byte_size, axes_json, instances_json, storage_path, source_path+"""+++class FontServiceError(RuntimeError):+ """Base class for errors raised by the font service."""+++class FontNotFoundError(FontServiceError):+ """The font does not exist or is not visible to the requesting account."""+++class FontForbiddenError(FontServiceError):+ """The caller is not permitted to perform the requested operation."""+++class FontDeleteForbiddenError(FontForbiddenError):+ """A read-only or otherwise protected font cannot be deleted."""+++class FontValidationError(FontServiceError):+ """The file is too large, unsupported, malformed, or missing font metadata."""+++class FontQuotaExceededError(FontServiceError):+ """An upload would exceed the configured library quota."""+++class FontChangedError(FontServiceError):+ """A font ID no longer points at the requested content hash."""+++class FontInstanceError(FontServiceError):+ """A variable font instance could not be produced."""+++class FontStorageError(FontServiceError):+ """A managed font file could not be read or safely stored."""+++def _normalize_variant_text(value: str) -> str:+ value = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", value)+ value = value.replace("_", " ").replace("-", " ")+ value = re.sub(r"\s+", " ", value)+ return value.strip().lower()+++def _infer_font_weight(style_name: str, filename: str, weight_class: int | None) -> int:+ if isinstance(weight_class, int) and 1 <= weight_class <= 1000:+ return weight_class++ combined = _normalize_variant_text(f"{style_name} {filename}")+ weight_keywords = [+ (("thin", "hairline"), 100),+ (("extra light", "ultra light", "extralight", "ultralight"), 200),+ (("light",), 300),+ (("normal", "regular", "roman", "book"), 400),+ (("medium",), 500),+ (("semi bold", "semibold", "demi bold", "demibold"), 600),+ (("extra bold", "ultra bold", "extrabold", "ultrabold"), 800),+ (("black", "heavy"), 900),+ (("bold",), 700),+ ]+ for keywords, weight in weight_keywords:+ if any(keyword in combined for keyword in keywords):+ return weight+ return 400+++def _infer_font_style(style_name: str, filename: str, italic_flag: bool) -> str:+ if italic_flag:+ return "italic"+ combined = _normalize_variant_text(f"{style_name} {filename}")+ return "italic" if "italic" in combined or "oblique" in combined else "normal"+++def _get_name_table_value(font: TTFont, name_ids: tuple[int, ...]) -> str | None:+ """Read a localized OpenType name, preferring English Windows records."""+ if "name" not in font:+ return None++ def sort_key(record: Any) -> tuple[int, int]:+ platform_id = getattr(record, "platformID", -1)+ language_id = getattr(record, "langID", -1)+ if platform_id == 3 and language_id in (0x0409, 0):+ return (0, 0)+ if platform_id == 3:+ return (1, 0)+ if platform_id == 0:+ return (2, 0)+ return (3, language_id)++ records = font["name"].names+ for name_id in name_ids:+ for record in sorted((record for record in records if record.nameID == name_id), key=sort_key):+ try:+ value = record.toUnicode().strip()+ except Exception:+ continue+ if value:+ return value+ return None+++def _parse_font_bytes(filename: str, data: bytes, *, max_bytes: int) -> FontValidationResult:+ """Validate and extract metadata without persisting the supplied bytes."""+ if (+ not filename+ or Path(filename).name != filename+ or any(separator in filename for separator in ("/", "\\"))+ or any(ord(character) < 32 for character in filename)+ or filename in {".", ".."}+ ):+ raise FontValidationError("Font filename is invalid")+ extension = Path(filename).suffix.lower()+ if extension not in SUPPORTED_FONT_EXTENSIONS:+ raise FontValidationError("Unsupported font format; use TTF, OTF, WOFF, or WOFF2")+ if len(data) == 0:+ raise FontValidationError("Font file is empty")+ if len(data) > max_bytes:+ raise FontValidationError(f"Font file exceeds the {max_bytes // (1024 * 1024)} MiB limit")++ try:+ with TTFont(file=io.BytesIO(data), lazy=False) as font:+ family = (_get_name_table_value(font, (16, 1, 4)) or "").strip()+ style_name = (_get_name_table_value(font, (17, 2)) or "").strip()+ label = (_get_name_table_value(font, (4,)) or family).strip()+ if not family:+ raise FontValidationError("Font is missing a family name")++ os2_table = font["OS/2"] if "OS/2" in font else None+ head_table = font["head"] if "head" in font else None+ post_table = font["post"] if "post" in font else None+ weight_class = getattr(os2_table, "usWeightClass", None)+ italic_flag = bool(getattr(os2_table, "fsSelection", 0) & 0x01) or bool(+ getattr(head_table, "macStyle", 0) & 0x02+ )+ if post_table is not None:+ italic_flag = italic_flag or bool(getattr(post_table, "italicAngle", 0))+ weight = _infer_font_weight(style_name, filename, weight_class)+ style = _infer_font_style(style_name, filename, italic_flag)++ axes: list[FontAxis] = []+ instances: list[FontInstance] = []+ if "fvar" in font:+ for axis in font["fvar"].axes:+ axis_tag = str(axis.axisTag)+ axis_label = _get_name_table_value(font, (int(axis.axisNameID),)) or axis_tag+ axes.append(+ FontAxis(+ tag=axis_tag,+ label=axis_label,+ minimum=float(axis.minValue),+ default=float(axis.defaultValue),+ maximum=float(axis.maxValue),+ hidden=bool(getattr(axis, "flags", 0) & 0x0001),+ )+ )+ for index, instance in enumerate(font["fvar"].instances):+ instance_name = _get_name_table_value(font, (int(instance.subfamilyNameID),)) or (+ f"Instance {index + 1}"+ )+ coordinates = {+ axis.axisTag: float(instance.coordinates.get(axis.axisTag, axis.defaultValue))+ for axis in font["fvar"].axes+ }+ instances.append(FontInstance(name=instance_name, coordinates=coordinates))+ except FontValidationError:+ raise+ except Exception as e:+ raise FontValidationError("The uploaded file is not a valid font") from e++ return FontValidationResult(+ filename=filename,+ family=family,+ label=label,+ style=style,+ weight=weight,+ content_hash=hashlib.sha256(data).hexdigest(),+ byte_size=len(data),+ axes=tuple(axes),+ instances=tuple(instances),+ )+++def _parse_font_worker(filename: str, data: bytes, max_bytes: int) -> FontValidationResult:+ """Pickle-friendly worker entry point for isolated metadata parsing."""+ return _parse_font_bytes(filename, data, max_bytes=max_bytes)+++def _json_axes(axes: tuple[FontAxis, ...]) -> str:+ return json.dumps([axis.__dict__ for axis in axes], separators=(",", ":"), sort_keys=True)+++def _json_instances(instances: tuple[FontInstance, ...]) -> str:+ return json.dumps([instance.__dict__ for instance in instances], separators=(",", ":"), sort_keys=True)+++def _record_from_row(row: Any) -> FontRecord:+ axes = tuple(FontAxis(**axis) for axis in json.loads(row[11]))+ instances = tuple(FontInstance(**instance) for instance in json.loads(row[12]))+ return FontRecord(+ id=row[0],+ family=row[2],+ label=row[3],+ style=row[4],+ weight=int(row[5]),+ content_hash=row[6],+ scope=FontScope(row[7]),+ source=FontSource(row[8]),+ filename=row[9],+ byte_size=int(row[10]),+ axes=axes,+ instances=instances,+ owner_id=row[1],+ storage_path=row[13],+ source_path=row[14],+ )+++def _validation_from_record(record: FontRecord, filename: str) -> FontValidationResult:+ """Reuse indexed metadata when a directory file's content hash is unchanged."""+ return FontValidationResult(+ filename=filename,+ family=record.family,+ label=record.label,+ style=record.style,+ weight=record.weight,+ content_hash=record.content_hash,+ byte_size=record.byte_size,+ axes=record.axes,+ instances=record.instances,+ )+++def _read_bounded_file(path: Path, max_bytes: int) -> bytes:+ """Read at most ``max_bytes`` and reject a file that grows during the read."""+ if path.stat().st_size > max_bytes:+ raise FontValidationError(f"Font file exceeds the {max_bytes // (1024 * 1024)} MiB limit")+ chunks: list[bytes] = []+ size = 0+ with path.open("rb") as file:+ while size <= max_bytes:+ chunk = file.read(min(1024 * 1024, max_bytes + 1 - size))+ if not chunk:+ break+ chunks.append(chunk)+ size += len(chunk)+ if size > max_bytes:+ raise FontValidationError(f"Font file exceeds the {max_bytes // (1024 * 1024)} MiB limit")+ return b"".join(chunks)+++def _safe_relative_path(path: Path, root: Path) -> Path:+ """Resolve a path under ``root`` while rejecting symlink components."""+ root_absolute = root.absolute()+ candidate = (root_absolute / path).absolute()+ try:+ candidate.relative_to(root_absolute)+ except ValueError as e:+ raise FontStorageError("Font path escapes its storage directory") from e++ current = candidate+ while True:+ if current.is_symlink():+ raise FontStorageError("Symlinked font paths are not supported")+ if current == root_absolute:+ break+ current = current.parent++ try:+ candidate.resolve(strict=False).relative_to(root.resolve())+ except ValueError as e:+ raise FontStorageError("Font path escapes its storage directory") from e+ return candidate+++class FontService:+ """Owns font metadata, managed files, access checks, and variable instances."""++ def __init__(+ self,+ db: SqliteDatabase,+ fonts_dir: Path,+ storage_dir: Path,+ logger: logging.Logger | None = None,+ *,+ max_upload_bytes: int = MAX_FONT_UPLOAD_BYTES,+ max_library_bytes: int = MAX_FONT_LIBRARY_BYTES,+ max_instance_cache_bytes: int = MAX_INSTANCE_CACHE_BYTES,+ instance_job_timeout_seconds: float = INSTANCE_JOB_TIMEOUT_SECONDS,+ ) -> None:+ fonts_absolute = fonts_dir.resolve()+ storage_absolute = storage_dir.resolve()+ if (+ fonts_absolute == storage_absolute+ or fonts_absolute.is_relative_to(storage_absolute)+ or storage_absolute.is_relative_to(fonts_absolute)+ ):+ raise ValueError("Font source and managed storage directories must not overlap")+ self._db = db+ self._fonts_dir = fonts_dir+ self._storage_dir = storage_dir+ self._logger = logger or logging.getLogger(__name__)+ self._max_upload_bytes = max_upload_bytes+ self._max_library_bytes = max_library_bytes+ self._max_instance_cache_bytes = max_instance_cache_bytes+ self._instance_job_timeout_seconds = instance_job_timeout_seconds+ # FontTools parses binary tables and performs variation instancing in native/Python+ # code that cannot be interrupted safely from a thread. Each operation runs in a+ # short-lived, lightweight worker subprocess so a timeout can terminate the work+ # without inheriting the server's CUDA or thread state.+ self._worker_admission = threading.BoundedSemaphore(MAX_INSTANCE_JOBS + MAX_INSTANCE_QUEUE)+ self._worker_slots = threading.BoundedSemaphore(MAX_INSTANCE_JOBS)+ self._active_workers: set[subprocess.Popen[bytes]] = set()+ self._active_workers_lock = threading.RLock()+ # Coordinate catalog snapshots with the managed-file write/commit sequence. A+ # cleanup sweep must not observe an upload between writing its file and committing+ # its row, or it could remove a live upload.+ self._managed_storage_lock = threading.RLock()+ self._instance_cache: OrderedDict[tuple[str, tuple[tuple[str, float], ...]], bytes] = OrderedDict()+ self._instance_cache_bytes = 0+ self._cache_lock = threading.RLock()+ self._revision = 0+ self._revision_lock = threading.Lock()++ @property+ def revision(self) -> int:+ """Monotonic process-local revision for client catalog invalidation."""+ with self._revision_lock:+ return self._revision++ @property+ def max_upload_bytes(self) -> int:+ """Maximum accepted size for a single uploaded font."""+ return self._max_upload_bytes++ def _bump_revision(self) -> None:+ with self._revision_lock:+ self._revision += 1++ def start(self, _invoker: object | None = None) -> None:+ """Index configured directory fonts once the service is attached to the invoker."""+ self.cleanup_orphaned_files()+ self.rescan_directory()++ def stop(self, _invoker: object | None = None) -> None:+ """Terminate active font workers and release cached instances."""+ with self._active_workers_lock:+ workers = list(self._active_workers)+ for worker in workers:+ if worker.poll() is None:+ worker.kill()+ self._invalidate_instance_cache()++ def validate(self, filename: str, data: bytes) -> FontValidationResult:+ """Validate a font upload and return metadata without changing the database."""+ if len(data) > self._max_upload_bytes:+ raise FontValidationError(f"Font file exceeds the {self._max_upload_bytes // (1024 * 1024)} MiB limit")+ return self._run_worker(+ "parse",+ (filename, data, self._max_upload_bytes),+ error_type=FontValidationError,+ )++ def upload(+ self, *, user_id: str, filename: str, data: bytes, scope: FontScope = FontScope.PRIVATE+ ) -> FontUploadResult:+ """Validate and atomically publish an uploaded font, deduplicating by content hash."""+ if scope not in (FontScope.PRIVATE, FontScope.SHARED):+ raise FontValidationError("Uploaded fonts must be private or shared")+ validation = self.validate(filename, data)+ owner_id = user_id if scope == FontScope.PRIVATE else None+ duplicate: FontRecord | None = None+ storage_path: str | None = None+ font_id = f"font_{uuid4().hex}"+ with self._managed_storage_lock:+ try:+ with self._db.transaction() as cursor:+ cursor.execute("BEGIN IMMEDIATE;")+ if scope == FontScope.PRIVATE:+ cursor.execute(+ f"SELECT {_FONT_COLUMNS} FROM fonts WHERE source = 'uploaded' AND scope = ? "+ "AND owner_id = ? AND content_hash = ? LIMIT 1;",+ (scope.value, owner_id, validation.content_hash),+ )+ else:+ cursor.execute(+ f"SELECT {_FONT_COLUMNS} FROM fonts WHERE source = 'uploaded' AND scope = ? "+ "AND owner_id IS NULL AND content_hash = ? LIMIT 1;",+ (scope.value, validation.content_hash),+ )+ row = cursor.fetchone()+ if row is not None:+ duplicate = _record_from_row(row)+ else:+ cursor.execute(+ "SELECT COALESCE(SUM(byte_size), 0) FROM fonts WHERE source = 'uploaded' "+ "AND scope = ? AND (owner_id IS ? OR (? = 'shared' AND owner_id IS NULL));",+ (scope.value, owner_id, scope.value),+ )+ current_bytes = int(cursor.fetchone()[0])+ if current_bytes + validation.byte_size > self._max_library_bytes:+ raise FontQuotaExceededError("Font library storage quota exceeded")++ extension = Path(filename).suffix.lower()+ storage_path = f"{font_id}{extension}"+ target = _safe_relative_path(Path(storage_path), self._storage_dir)+ self._write_atomic(target, data)+ cursor.execute(+ """--sql+ INSERT INTO fonts (+ id, owner_id, scope, source, filename, storage_path, source_path,+ family, label, style, weight, content_hash, byte_size, axes_json, instances_json+ ) VALUES (?, ?, ?, 'uploaded', ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?);+ """,+ (+ font_id,+ owner_id,+ scope.value,+ validation.filename,+ storage_path,+ validation.family,+ validation.label,+ validation.style,+ validation.weight,+ validation.content_hash,+ validation.byte_size,+ _json_axes(validation.axes),+ _json_instances(validation.instances),+ ),+ )+ except Exception:+ if storage_path is not None:+ self._unlink_managed_file(storage_path)+ raise++ if duplicate is not None:+ return FontUploadResult(font=duplicate, created=False)++ self._bump_revision()+ record = self.get(font_id)+ if record is None:+ raise FontStorageError("Uploaded font was not indexed")+ return FontUploadResult(font=record, created=True)++ def rescan_directory(self) -> int:+ """Index valid files in the configured directory and remove stale directory rows."""+ root = self._fonts_dir+ if not root.exists() or not root.is_dir() or root.is_symlink():+ if root.is_symlink():+ self._logger.warning("Skipping custom fonts directory %s: symlinks are not supported", root)+ with self._db.transaction() as cursor:+ cursor.execute("DELETE FROM fonts WHERE source = 'directory';")+ removed = cursor.rowcount+ if removed:+ self._bump_revision()+ return 0++ with self._db.transaction() as cursor:+ cursor.execute(f"SELECT {_FONT_COLUMNS} FROM fonts WHERE source = 'directory';")+ existing_records = {+ record.source_path: record+ for record in (_record_from_row(row) for row in cursor.fetchall())+ if record.source_path is not None+ }++ discovered: list[tuple[str, FontValidationResult, str]] = []+ for path in sorted(root.rglob("*")):+ if self._path_has_symlink_component(path, root):+ self._logger.warning("Skipping font path %s: symlinks are not supported", path)+ continue+ if not path.is_file() or path.suffix.lower() not in SUPPORTED_FONT_EXTENSIONS:+ continue+ try:+ data = _read_bounded_file(path, MAX_INDEXED_FONT_BYTES)+ relative = path.relative_to(root).as_posix()+ content_hash = hashlib.sha256(data).hexdigest()+ existing = existing_records.get(relative)+ if existing is not None and existing.byte_size == len(data) and existing.content_hash == content_hash:+ metadata = _validation_from_record(existing, path.name)+ else:+ metadata = self._run_worker(+ "parse",+ (path.name, data, MAX_INDEXED_FONT_BYTES),+ error_type=FontValidationError,+ )+ except (OSError, FontValidationError) as e:+ self._logger.warning("Skipping font file %s: %s", path, e)+ continue+ # The path-derived ID lets a project distinguish two same-named files and remains+ # stable when a directory file is replaced. Its content hash detects that replacement.+ font_id = f"directory_{hashlib.sha256(relative.encode('utf-8')).hexdigest()[:32]}"+ discovered.append((font_id, metadata, relative))++ discovered_ids = {font_id for font_id, _metadata, _relative in discovered}+ existing_by_id = {record.id: record for record in existing_records.values()}+ changed = set(existing_by_id) != discovered_ids+ if not changed:+ for font_id, metadata, relative in discovered:+ existing = existing_by_id[font_id]+ if (+ existing.filename != metadata.filename+ or existing.source_path != relative+ or existing.family != metadata.family+ or existing.label != metadata.label+ or existing.style != metadata.style+ or existing.weight != metadata.weight+ or existing.content_hash != metadata.content_hash+ or existing.byte_size != metadata.byte_size+ or existing.axes != metadata.axes+ or existing.instances != metadata.instances+ ):+ changed = True+ break+ with self._db.transaction() as cursor:+ for font_id, metadata, relative in discovered:+ cursor.execute(+ """--sql+ INSERT INTO fonts (+ id, owner_id, scope, source, filename, storage_path, source_path,+ family, label, style, weight, content_hash, byte_size, axes_json, instances_json+ ) VALUES (?, NULL, 'shared', 'directory', ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(id) DO UPDATE SET+ filename = excluded.filename,+ source_path = excluded.source_path,+ family = excluded.family,+ label = excluded.label,+ style = excluded.style,+ weight = excluded.weight,+ content_hash = excluded.content_hash,+ byte_size = excluded.byte_size,+ axes_json = excluded.axes_json,+ instances_json = excluded.instances_json;+ """,+ (+ font_id,+ metadata.filename,+ relative,+ metadata.family,+ metadata.label,+ metadata.style,+ metadata.weight,+ metadata.content_hash,+ metadata.byte_size,+ _json_axes(metadata.axes),+ _json_instances(metadata.instances),+ ),+ )++ if discovered_ids:+ placeholders = ",".join("?" for _ in discovered_ids)+ cursor.execute(+ f"DELETE FROM fonts WHERE source = 'directory' AND id NOT IN ({placeholders});",+ tuple(discovered_ids),+ )+ else:+ cursor.execute("DELETE FROM fonts WHERE source = 'directory';")++ if changed:+ self._invalidate_instance_cache()+ self._bump_revision()+ return len(discovered)++ def list(+ self,+ *,+ user_id: str,+ offset: int = 0,+ limit: int = 100,+ search: str | None = None,+ scope: FontScope = FontScope.ALL,+ content_hash: str | None = None,+ ) -> tuple[list[FontRecord], int]:+ """List fonts visible to an account with bounded offset pagination."""+ if offset < 0 or limit < 0:+ raise ValueError("offset and limit must be non-negative")+ if scope not in (FontScope.ALL, FontScope.PRIVATE, FontScope.SHARED):+ raise ValueError("Invalid font scope")++ conditions = [+ "(source = 'directory' OR scope = 'shared' OR (scope = 'private' AND owner_id = ?))",+ ]+ params: list[object] = [user_id]+ if scope == FontScope.PRIVATE:+ conditions.append("source = 'uploaded' AND scope = 'private' AND owner_id = ?")+ params.append(user_id)+ elif scope == FontScope.SHARED:+ conditions.append("(source = 'directory' OR (source = 'uploaded' AND scope = 'shared'))")+ if content_hash is not None:+ if re.fullmatch(r"[a-f0-9]{64}", content_hash) is None:+ raise ValueError("content_hash must be a lowercase SHA-256 hash")+ conditions.append("content_hash = ?")+ params.append(content_hash)+ if search:+ conditions.append(+ "(family LIKE ? COLLATE NOCASE OR label LIKE ? COLLATE NOCASE OR filename LIKE ? COLLATE NOCASE)"+ )+ term = f"%{search}%"+ params.extend((term, term, term))+ where = " AND ".join(conditions)+ with self._db.transaction() as cursor:+ cursor.execute(f"SELECT COUNT(*) FROM fonts WHERE {where};", tuple(params))+ total = int(cursor.fetchone()[0])+ cursor.execute(+ f"SELECT {_FONT_COLUMNS} FROM fonts WHERE {where} ORDER BY family COLLATE NOCASE, label COLLATE NOCASE, id LIMIT ? OFFSET ?;",+ (*params, limit, offset),+ )+ rows = cursor.fetchall()+ return [_record_from_row(row) for row in rows], total++ def get(self, font_id: str) -> FontRecord | None:+ """Get an indexed font without applying account visibility."""+ with self._db.transaction() as cursor:+ cursor.execute(f"SELECT {_FONT_COLUMNS} FROM fonts WHERE id = ?;", (font_id,))+ row = cursor.fetchone()+ return _record_from_row(row) if row is not None else None++ def get_accessible(self, *, user_id: str, font_id: str) -> FontRecord:+ """Get a font visible to the account, hiding private-resource existence."""+ record = self.get(font_id)+ if record is None:+ raise FontNotFoundError("Font not found")+ if record.source == FontSource.DIRECTORY or record.scope == FontScope.SHARED or record.owner_id == user_id:+ return record+ raise FontNotFoundError("Font not found")++ def read_file(self, *, user_id: str, font_id: str, expected_hash: str | None = None) -> tuple[FontRecord, bytes]:+ """Read an accessible font and verify its immutable content hash."""+ record = self.get_accessible(user_id=user_id, font_id=font_id)+ if expected_hash is not None and expected_hash != record.content_hash:+ raise FontChangedError("Font content has changed")+ if record.source == FontSource.UPLOADED:+ if record.storage_path is None:+ raise FontStorageError("Managed font has no storage path")+ path = _safe_relative_path(Path(record.storage_path), self._storage_dir)+ else:+ if record.source_path is None:+ raise FontStorageError("Directory font has no source path")+ path = _safe_relative_path(Path(record.source_path), self._fonts_dir)+ try:+ data = _read_bounded_file(path, max(self._max_upload_bytes, MAX_INDEXED_FONT_BYTES))+ except OSError as e:+ raise FontNotFoundError("Font file not found") from e+ except FontValidationError as e:+ raise FontChangedError("Font content has changed; refresh the font library") from e+ actual_hash = hashlib.sha256(data).hexdigest()+ if actual_hash != record.content_hash:+ raise FontChangedError("Font content has changed; refresh the font library")+ return record, data++ def delete(self, *, user_id: str, font_id: str, is_admin: bool = False) -> None:+ """Delete an owned upload and best-effort clean its managed file."""+ record = self.get_accessible(user_id=user_id, font_id=font_id)+ if record.source != FontSource.UPLOADED:+ raise FontDeleteForbiddenError("Configured directory fonts cannot be deleted")+ if record.scope == FontScope.PRIVATE and record.owner_id != user_id:+ raise FontForbiddenError("Only the font owner may delete a private font")+ if record.scope == FontScope.SHARED and not is_admin:+ raise FontForbiddenError("Only administrators may delete a shared font")++ with self._db.transaction() as cursor:+ cursor.execute("DELETE FROM fonts WHERE id = ? AND source = 'uploaded';", (font_id,))+ if cursor.rowcount != 1:+ raise FontNotFoundError("Font not found")+ # A variable-font instance is derived from the source bytes. Drop every derived+ # value before unlinking the source so a later request cannot serve a deleted font+ # from memory while the filesystem cleanup is in progress.+ self._invalidate_instance_cache()+ if record.storage_path is not None:+ self._unlink_managed_file(record.storage_path)+ self._bump_revision()++ def cleanup_orphaned_files(self) -> None:+ """Remove interrupted-upload files that are no longer referenced by the catalog."""+ with self._managed_storage_lock:+ # Account deletion cascades font rows in SQLite, but it cannot remove files.+ # Clearing derived instances here also covers that deletion path and ensures+ # an in-flight worker cannot repopulate the cache without re-checking access.+ self._invalidate_instance_cache()+ if not self._storage_dir.exists() or not self._storage_dir.is_dir() or self._storage_dir.is_symlink():+ return+ with self._db.transaction() as cursor:+ cursor.execute("SELECT storage_path FROM fonts WHERE source = 'uploaded' AND storage_path IS NOT NULL;")+ referenced = {row[0] for row in cursor.fetchall()}+ for path in self._storage_dir.iterdir():+ if not path.is_file() or path.is_symlink():+ continue+ # Managed uploads are flat files whose names begin with the opaque `font_` ID;+ # leave unrelated operator files alone in case a shared storage directory is used.+ if (+ re.fullmatch(r"font_[0-9a-f]{32}\.(?:ttf|otf|woff2?)", path.name) is None+ and re.fullmatch(r"\.font_[0-9a-f]{32}\.(?:ttf|otf|woff2?)\.[0-9a-f]{32}\.tmp", path.name) is None+ ):+ continue+ if path.name in referenced:+ continue+ try:+ path.unlink()+ except OSError:+ self._logger.warning("Unable to clean up orphaned font file %s", path, exc_info=True)++ def prepare_user_cleanup(self, user_id: str) -> tuple[str, ...]:+ """Capture a user's private managed paths before its account row is deleted."""+ with self._managed_storage_lock:+ with self._db.transaction() as cursor:+ cursor.execute(+ "SELECT storage_path FROM fonts "+ "WHERE source = 'uploaded' AND scope = 'private' AND owner_id = ? AND storage_path IS NOT NULL;",+ (user_id,),+ )+ storage_paths = tuple(row[0] for row in cursor.fetchall())+ # A caller may delete the account through a separate service, which cascades+ # rows without notifying this process. Purge derived values before that race.+ self._invalidate_instance_cache()+ return storage_paths++ def cleanup_user(self, user_id: str, storage_paths: tuple[str, ...]) -> None:+ """Remove only private files captured before an account deletion.++ Shared uploads have no account owner and are deliberately absent from ``storage_paths``.+ The startup orphan sweep remains responsible for files from interrupted uploads.+ """+ self._logger.debug("Cleaning up fonts after deleting user %s", user_id)+ self._invalidate_instance_cache()+ for storage_path in storage_paths:+ self._unlink_managed_file(storage_path)++ def instance(+ self,+ *,+ user_id: str,+ font_id: str,+ content_hash: str,+ coordinates: dict[str, float],+ ) -> tuple[FontRecord, bytes]:+ """Create a pinned static instance of an accessible variable font."""+ record, data = self.read_file(user_id=user_id, font_id=font_id, expected_hash=content_hash)+ normalized = self._normalize_coordinates(record, coordinates)+ if not record.axes:+ if normalized:+ raise FontInstanceError("Font does not contain variation axes")+ return record, data++ key = (record.content_hash, tuple(sorted(normalized.items())))+ with self._cache_lock:+ self._assert_accessible_instance_source(user_id=user_id, font_id=font_id, content_hash=record.content_hash)+ cached = self._instance_cache.get(key)+ if cached is not None:+ self._instance_cache.move_to_end(key)+ return record, cached++ instance_data = self._run_worker(+ "instance",+ (data, record.filename, normalized),+ error_type=FontInstanceError,+ )++ with self._cache_lock:+ # The source can be deleted while FontTools is running in the child process.+ # Hold the cache lock across this check and insertion so deletion cannot commit,+ # invalidate, and then race us into retaining a result for an inaccessible font.+ self._assert_accessible_instance_source(user_id=user_id, font_id=font_id, content_hash=record.content_hash)+ if len(instance_data) <= self._max_instance_cache_bytes:+ previous = self._instance_cache.pop(key, None)+ if previous is not None:+ self._instance_cache_bytes -= len(previous)+ self._instance_cache[key] = instance_data+ self._instance_cache_bytes += len(instance_data)+ while self._instance_cache_bytes > self._max_instance_cache_bytes and self._instance_cache:+ _old_key, old_data = self._instance_cache.popitem(last=False)+ self._instance_cache_bytes -= len(old_data)+ return record, instance_data++ def _assert_accessible_instance_source(self, *, user_id: str, font_id: str, content_hash: str) -> None:+ """Reject a worker result when its source was deleted, replaced, or hidden."""+ current = self.get_accessible(user_id=user_id, font_id=font_id)+ if current.content_hash != content_hash:+ raise FontChangedError("Font content has changed; refresh the font library")++ def _invalidate_instance_cache(self) -> None:+ """Drop all derived instances after a source catalog mutation."""+ with self._cache_lock:+ self._instance_cache.clear()+ self._instance_cache_bytes = 0++ def _normalize_coordinates(self, record: FontRecord, coordinates: dict[str, float]) -> dict[str, float]:+ known_axes = {axis.tag: axis for axis in record.axes}+ unknown = set(coordinates) - set(known_axes)+ if unknown:+ raise FontInstanceError(f"Unknown variation axis: {sorted(unknown)[0]}")+ normalized: dict[str, float] = {}+ for axis in record.axes:+ raw = coordinates.get(axis.tag, axis.default)+ try:+ value = float(raw)+ except (TypeError, ValueError) as e:+ raise FontInstanceError(f"Invalid value for variation axis {axis.tag}") from e+ if not math.isfinite(value) or value < axis.minimum or value > axis.maximum:+ raise FontInstanceError(+ f"Variation axis {axis.tag} must be between {axis.minimum:g} and {axis.maximum:g}"+ )+ normalized[axis.tag] = value+ return normalized++ def _run_worker(self, operation: str, args: tuple[Any, ...], *, error_type: type[FontServiceError]) -> Any:+ """Run a fontTools operation in a killable, bounded child process."""+ if not self._worker_admission.acquire(blocking=False):+ raise error_type("Too many font processing jobs are queued")+ if not self._worker_slots.acquire(timeout=self._instance_job_timeout_seconds):+ self._worker_admission.release()+ raise error_type("Too many font processing jobs are queued")+ if operation == "parse":+ filename, data, max_bytes = args+ command = [+ sys.executable,+ "-m",+ "invokeai.app.services.fonts.fonts_worker",+ "parse",+ str(filename),+ str(max_bytes),+ ]+ input_data = data+ elif operation == "instance":+ data, filename, coordinates = args+ command = [+ sys.executable,+ "-m",+ "invokeai.app.services.fonts.fonts_worker",+ "instance",+ str(filename),+ json.dumps(coordinates, separators=(",", ":"), sort_keys=True),+ ]+ input_data = data+ else:+ self._worker_slots.release()+ self._worker_admission.release()+ raise error_type("Unknown font processing operation")++ process: subprocess.Popen[bytes] | None = None+ try:+ with self._active_workers_lock:+ process = subprocess.Popen(+ command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL+ )+ self._active_workers.add(process)+ try:+ stdout, _ = process.communicate(input=input_data, timeout=self._instance_job_timeout_seconds)+ except subprocess.TimeoutExpired as e:+ process.kill()+ process.communicate()+ raise error_type("Font processing timed out") from e+ if process.returncode != 0 or not stdout:+ raise error_type("Font processing failed")+ try:+ result = pickle.loads(stdout)+ if not isinstance(result, tuple) or len(result) != 2:+ raise ValueError("invalid worker response")+ result_kind, payload = result+ except (EOFError, ValueError, pickle.PickleError, TypeError, AttributeError, ImportError) as e:+ raise error_type("Font processing returned invalid data") from e+ if result_kind == "error":+ raise error_type(str(payload))+ if result_kind != "ok":+ raise error_type("Font processing returned an unknown result")+ return payload+ finally:+ if process is not None:+ with self._active_workers_lock:+ self._active_workers.discard(process)+ if process.poll() is None:+ process.kill()+ process.communicate()+ self._worker_slots.release()+ self._worker_admission.release()++ @staticmethod+ def _write_atomic(target: Path, data: bytes) -> None:+ target.parent.mkdir(parents=True, exist_ok=True)+ temporary = target.parent / f".{target.name}.{uuid4().hex}.tmp"+ try:+ with temporary.open("xb") as file:+ file.write(data)+ file.flush()+ os.fsync(file.fileno())+ os.replace(temporary, target)+ except Exception:+ try:+ temporary.unlink()+ except OSError:+ pass+ raise++ def _unlink_managed_file(self, storage_path: str) -> None:+ try:+ path = _safe_relative_path(Path(storage_path), self._storage_dir)+ path.unlink(missing_ok=True)+ except (OSError, FontStorageError):+ self._logger.warning("Unable to clean up managed font file %s", storage_path, exc_info=True)++ @staticmethod+ def _path_has_symlink_component(path: Path, boundary: Path) -> bool:+ current = path+ boundary = boundary.absolute()+ try:+ current.absolute().relative_to(boundary)+ except ValueError:+ return True+ while True:+ if current.is_symlink():+ return True+ if current == boundary:+ return False+ current = current.parent+++def _instantiate_font_bytes(data: bytes, filename: str, coordinates: dict[str, float]) -> bytes:+ """Worker function for variable-font instancing."""+ source = io.BytesIO(data)+ with TTFont(file=source, lazy=False) as font:+ if "fvar" not in font:+ return data+ flavor = font.flavor+ # fontTools calls the coordinate mapping ``axisLimits``: values outside the+ # declared ranges are rejected by the service before this worker is submitted.+ instantiated = instantiateVariableFont(font, axisLimits=coordinates, inplace=False)+ instantiated.flavor = flavor+ output = io.BytesIO()+ try:+ instantiated.save(output)+ return output.getvalue()+ finally:+ instantiated.close()+++__all__ = [+ "FontChangedError",+ "FontDeleteForbiddenError",+ "FontForbiddenError",+ "FontInstanceError",+ "FontNotFoundError",+ "FontQuotaExceededError",+ "FontService",+ "FontStorageError",+ "FontValidationError",+ "SUPPORTED_FONT_EXTENSIONS",+]diff --git a/invokeai/app/services/fonts/fonts_worker.py b/invokeai/app/services/fonts/fonts_worker.pynew file mode 100644index 0000000000..7d653ae0a2--- /dev/null+++ b/invokeai/app/services/fonts/fonts_worker.py@@ -0,0 +1,39 @@+"""Small subprocess entry point for bounded fontTools work.++The API process sends one font as stdin and receives a pickled result on stdout. Keeping+this module separate from the web application avoids importing the inference stack in a+worker and lets the service terminate a job that exceeds its deadline.+"""++from __future__ import annotations++import json+import pickle+import sys++from invokeai.app.services.fonts.fonts_default import _instantiate_font_bytes, _parse_font_bytes+++def main() -> None:+ if len(sys.argv) < 3:+ raise SystemExit("usage: fonts_worker.py parse <filename> <max_bytes> | instance <filename> <coordinates>")++ operation = sys.argv[1]+ filename = sys.argv[2]+ data = sys.stdin.buffer.read()+ try:+ if operation == "parse" and len(sys.argv) == 4:+ result = _parse_font_bytes(filename, data, max_bytes=int(sys.argv[3]))+ elif operation == "instance" and len(sys.argv) == 4:+ result = _instantiate_font_bytes(data, filename, json.loads(sys.argv[3]))+ else:+ raise ValueError("invalid font worker operation")+ except BaseException as error:+ payload = ("error", f"{type(error).__name__}: {error}")+ else:+ payload = ("ok", result)+ sys.stdout.buffer.write(pickle.dumps(payload, protocol=pickle.HIGHEST_PROTOCOL))+++if __name__ == "__main__":+ main()diff --git a/invokeai/app/services/invocation_services.py b/invokeai/app/services/invocation_services.pyindex 0e3d64898e..589a747f6c 100644--- a/invokeai/app/services/invocation_services.py+++ b/invokeai/app/services/invocation_services.py@@ -25,6 +25,7 @@ if TYPE_CHECKING:from invokeai.app.services.download import DownloadQueueServiceBasefrom invokeai.app.services.events.events_base import EventServiceBasefrom invokeai.app.services.external_generation.external_generation_base import ExternalGenerationServiceBase+ from invokeai.app.services.fonts.fonts_default import FontServicefrom invokeai.app.services.gallery.gallery_base import GalleryServiceABCfrom invokeai.app.services.image_files.image_files_base import ImageFileStorageBasefrom invokeai.app.services.image_index.image_index_base import ImageIndexServiceBase@@ -109,6 +110,7 @@ class InvocationServices:image_index: "ImageIndexServiceBase",image_moves: "ImageMoveService | None" = None,progress_previews: "ProgressPreviewsBase | None" = None,+ fonts: "FontService | None" = None,):self.board_images = board_imagesself.board_image_records = board_image_records@@ -157,3 +159,4 @@ class InvocationServices:self.gallery = galleryself.image_index_records = image_index_recordsself.image_index = image_index+ self.fonts = fontsdiff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_07_add_fonts.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_07_add_fonts.pynew file mode 100644index 0000000000..d935a5fb5c--- /dev/null+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_07_add_fonts.py@@ -0,0 +1,67 @@+"""Add the account-scoped custom font catalog."""++import sqlite3++from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+++class AddFontsCallback:+ """Create the font catalog and its ownership/source indexes."""++ def __call__(self, cursor: sqlite3.Cursor) -> None:+ cursor.execute(+ """--sql+ CREATE TABLE IF NOT EXISTS fonts (+ id TEXT NOT NULL PRIMARY KEY,+ owner_id TEXT,+ scope TEXT NOT NULL CHECK (scope IN ('private', 'shared')),+ source TEXT NOT NULL CHECK (source IN ('uploaded', 'directory')),+ filename TEXT NOT NULL,+ storage_path TEXT,+ source_path TEXT,+ family TEXT NOT NULL,+ label TEXT NOT NULL,+ style TEXT NOT NULL,+ weight INTEGER NOT NULL CHECK (weight >= 1 AND weight <= 1000),+ content_hash TEXT NOT NULL CHECK (length(content_hash) = 64),+ byte_size INTEGER NOT NULL CHECK (byte_size > 0),+ axes_json TEXT NOT NULL DEFAULT '[]',+ instances_json TEXT NOT NULL DEFAULT '[]',+ created_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ updated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ FOREIGN KEY (owner_id) REFERENCES users(user_id) ON DELETE CASCADE,+ CHECK (+ (source = 'directory' AND owner_id IS NULL AND scope = 'shared' AND storage_path IS NULL AND source_path IS NOT NULL)+ OR+ (source = 'uploaded' AND storage_path IS NOT NULL AND source_path IS NULL AND+ ((scope = 'private' AND owner_id IS NOT NULL) OR (scope = 'shared' AND owner_id IS NULL)))+ )+ );+ """+ )+ cursor.execute(+ """--sql+ CREATE INDEX IF NOT EXISTS idx_fonts_visible_private+ ON fonts(source, scope, owner_id, family COLLATE NOCASE);+ """+ )+ cursor.execute(+ """--sql+ CREATE UNIQUE INDEX IF NOT EXISTS idx_fonts_directory_source_path+ ON fonts(source_path) WHERE source = 'directory';+ """+ )+ cursor.execute(+ """--sql+ CREATE INDEX IF NOT EXISTS idx_fonts_uploaded_hash+ ON fonts(source, scope, owner_id, content_hash);+ """+ )+++def build_migration() -> Migration:+ return Migration(+ id="2026_09_07_add_fonts",+ depends_on="migration_27",+ callback=AddFontsCallback(),+ )diff --git a/invokeai/app/util/user_management.py b/invokeai/app/util/user_management.pyindex d0f682482a..9c9c738f86 100644--- a/invokeai/app/util/user_management.py+++ b/invokeai/app/util/user_management.py@@ -14,6 +14,7 @@ import getpassimport jsonimport osimport sys+from typing import Any_root_help = ("Path to the InvokeAI root directory. If omitted, the root is resolved in this order: "@@ -33,6 +34,36 @@ _LIVE_SERVER_NOTE = (" connections are re-checked within about a minute.")++def _prepare_deleted_user_fonts(config: Any, db: Any, user_id: str, logger: Any) -> tuple[Any | None, tuple[str, ...]]:+ """Snapshot private managed paths before the user-row foreign-key cascade."""+ try:+ from invokeai.app.services.fonts.fonts_default import FontService++ fonts = FontService(+ db=db,+ fonts_dir=config.fonts_path,+ storage_dir=config.fonts_storage_path,+ logger=logger,+ max_upload_bytes=config.max_font_upload_bytes,+ max_library_bytes=config.max_font_library_bytes,+ )+ return fonts, fonts.prepare_user_cleanup(user_id)+ except Exception:+ logger.warning("Unable to snapshot fonts before deleting user %s", user_id, exc_info=True)+ return None, ()+++def _cleanup_deleted_user_fonts(fonts: Any | None, user_id: str, storage_paths: tuple[str, ...], logger: Any) -> None:+ """Best-effort cleanup of only the paths captured for a deleted user."""+ if fonts is None:+ return+ try:+ fonts.cleanup_user(user_id, storage_paths)+ except Exception:+ logger.warning("Unable to clean up fonts after deleting user %s", user_id, exc_info=True)++# ---------------------------------------------------------------------------# useradd# ---------------------------------------------------------------------------@@ -192,7 +223,8 @@ def _delete_user_interactive() -> bool:try:config = get_config()- db = SqliteDatabase(config.db_path, InvokeAILogger.get_logger())+ logger = InvokeAILogger.get_logger(config=config)+ db = SqliteDatabase(config.db_path, logger)user_service = UserService(db)user = user_service.get_by_email(email)@@ -212,7 +244,9 @@ def _delete_user_interactive() -> bool:print("Deletion cancelled.")return False+ fonts, font_storage_paths = _prepare_deleted_user_fonts(config, db, user.user_id, logger)user_service.delete(user.user_id)+ _cleanup_deleted_user_fonts(fonts, user.user_id, font_storage_paths, logger)print("\n✅ User deleted successfully!")print(_LIVE_SERVER_NOTE)return True@@ -237,7 +271,8 @@ def _delete_user_cli(email: str, force: bool = False) -> bool:try:config = get_config()- db = SqliteDatabase(config.db_path, InvokeAILogger.get_logger())+ logger = InvokeAILogger.get_logger(config=config)+ db = SqliteDatabase(config.db_path, logger)user_service = UserService(db)user = user_service.get_by_email(email)@@ -258,7 +293,9 @@ def _delete_user_cli(email: str, force: bool = False) -> bool:print("Deletion cancelled.")return False+ fonts, font_storage_paths = _prepare_deleted_user_fonts(config, db, user.user_id, logger)user_service.delete(user.user_id)+ _cleanup_deleted_user_fonts(fonts, user.user_id, font_storage_paths, logger)print("✅ User deleted successfully!")print(_LIVE_SERVER_NOTE)return Truediff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 32cabd401e..6e31935c11 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -671,6 +671,420 @@]}},+ "/api/v1/fonts": {+ "get": {+ "tags": ["fonts"],+ "summary": "List Fonts",+ "operationId": "list_fonts",+ "security": [+ {+ "HTTPBearer": []+ }+ ],+ "parameters": [+ {+ "name": "offset",+ "in": "query",+ "required": false,+ "schema": {+ "type": "integer",+ "minimum": 0,+ "default": 0,+ "title": "Offset"+ }+ },+ {+ "name": "limit",+ "in": "query",+ "required": false,+ "schema": {+ "type": "integer",+ "maximum": 1000,+ "minimum": 0,+ "default": 100,+ "title": "Limit"+ }+ },+ {+ "name": "search",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string",+ "maxLength": 200+ },+ {+ "type": "null"+ }+ ],+ "title": "Search"+ }+ },+ {+ "name": "scope",+ "in": "query",+ "required": false,+ "schema": {+ "$ref": "#/components/schemas/FontScope",+ "default": "all"+ }+ },+ {+ "name": "content_hash",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string",+ "minLength": 64,+ "maxLength": 64,+ "pattern": "^[a-f0-9]{64}$"+ },+ {+ "type": "null"+ }+ ],+ "title": "Content Hash"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/FontListResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ },+ "post": {+ "tags": ["fonts"],+ "summary": "Upload Font",+ "operationId": "upload_font",+ "security": [+ {+ "HTTPBearer": []+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "multipart/form-data": {+ "schema": {+ "$ref": "#/components/schemas/Body_upload_font"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/FontUploadResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/fonts/validate": {+ "post": {+ "tags": ["fonts"],+ "summary": "Validate Font",+ "operationId": "validate_font",+ "requestBody": {+ "content": {+ "multipart/form-data": {+ "schema": {+ "$ref": "#/components/schemas/Body_validate_font"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/FontValidationResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]+ }+ },+ "/api/v1/fonts/rescan": {+ "post": {+ "tags": ["fonts"],+ "summary": "Rescan Fonts",+ "operationId": "rescan_fonts",+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/FontRescanResponse"+ }+ }+ }+ }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]+ }+ },+ "/api/v1/fonts/{font_id}/file": {+ "get": {+ "tags": ["fonts"],+ "summary": "Get Font File",+ "operationId": "get_font_file",+ "security": [+ {+ "HTTPBearer": []+ }+ ],+ "parameters": [+ {+ "name": "font_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "minLength": 1,+ "title": "Font Id"+ }+ },+ {+ "name": "expected_hash",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string",+ "minLength": 64,+ "maxLength": 64,+ "pattern": "^[a-f0-9]{64}$"+ },+ {+ "type": "null"+ }+ ],+ "title": "Expected Hash"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {}+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/fonts/{font_id}": {+ "get": {+ "tags": ["fonts"],+ "summary": "Get Font",+ "operationId": "get_font",+ "security": [+ {+ "HTTPBearer": []+ }+ ],+ "parameters": [+ {+ "name": "font_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "minLength": 1,+ "title": "Font Id"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/FontDTO"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ },+ "delete": {+ "tags": ["fonts"],+ "summary": "Delete Font",+ "operationId": "delete_font",+ "security": [+ {+ "HTTPBearer": []+ }+ ],+ "parameters": [+ {+ "name": "font_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "minLength": 1,+ "title": "Font Id"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "Successful Response"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/fonts/{font_id}/instance": {+ "post": {+ "tags": ["fonts"],+ "summary": "Create Font Instance",+ "operationId": "create_font_instance",+ "security": [+ {+ "HTTPBearer": []+ }+ ],+ "parameters": [+ {+ "name": "font_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "minLength": 1,+ "title": "Font Id"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/FontInstanceRequest"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {}+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },"/api/v2/models/": {"get": {"tags": ["model_manager"],@@ -18606,6 +19020,24 @@"required": ["is_public"],"title": "Body_update_workflow_is_public"},+ "Body_upload_font": {+ "properties": {+ "file": {+ "type": "string",+ "contentMediaType": "application/octet-stream",+ "title": "File",+ "description": "The font file to upload"+ },+ "scope": {+ "type": "string",+ "title": "Scope",+ "default": "private"+ }+ },+ "type": "object",+ "required": ["file"],+ "title": "Body_upload_font"+ },"Body_upload_image": {"properties": {"file": {@@ -18643,6 +19075,19 @@"required": ["file"],"title": "Body_upload_image"},+ "Body_validate_font": {+ "properties": {+ "file": {+ "type": "string",+ "contentMediaType": "application/octet-stream",+ "title": "File",+ "description": "The font file to validate"+ }+ },+ "type": "object",+ "required": ["file"],+ "title": "Body_validate_font"+ },"BooleanCollectionInvocation": {"category": "primitives","class": "invocation",@@ -36405,6 +36850,277 @@"title": "FluxVariantType","description": "FLUX.1 model variants."},+ "FontAxisDTO": {+ "properties": {+ "tag": {+ "type": "string",+ "title": "Tag"+ },+ "label": {+ "type": "string",+ "title": "Label"+ },+ "minimum": {+ "type": "number",+ "title": "Minimum"+ },+ "default": {+ "type": "number",+ "title": "Default"+ },+ "maximum": {+ "type": "number",+ "title": "Maximum"+ },+ "hidden": {+ "type": "boolean",+ "title": "Hidden"+ }+ },+ "type": "object",+ "required": ["tag", "label", "minimum", "default", "maximum", "hidden"],+ "title": "FontAxisDTO"+ },+ "FontDTO": {+ "properties": {+ "id": {+ "type": "string",+ "title": "Id"+ },+ "family": {+ "type": "string",+ "title": "Family"+ },+ "label": {+ "type": "string",+ "title": "Label"+ },+ "style": {+ "type": "string",+ "title": "Style"+ },+ "weight": {+ "type": "integer",+ "title": "Weight"+ },+ "content_hash": {+ "type": "string",+ "title": "Content Hash"+ },+ "scope": {+ "type": "string",+ "enum": ["private", "shared"],+ "title": "Scope"+ },+ "source": {+ "type": "string",+ "enum": ["uploaded", "directory"],+ "title": "Source"+ },+ "filename": {+ "type": "string",+ "title": "Filename"+ },+ "byte_size": {+ "type": "integer",+ "title": "Byte Size"+ },+ "url": {+ "type": "string",+ "title": "Url"+ },+ "axes": {+ "items": {+ "$ref": "#/components/schemas/FontAxisDTO"+ },+ "type": "array",+ "title": "Axes"+ },+ "instances": {+ "items": {+ "$ref": "#/components/schemas/FontInstanceDTO"+ },+ "type": "array",+ "title": "Instances"+ }+ },+ "type": "object",+ "required": [+ "id",+ "family",+ "label",+ "style",+ "weight",+ "content_hash",+ "scope",+ "source",+ "filename",+ "byte_size",+ "url",+ "axes",+ "instances"+ ],+ "title": "FontDTO"+ },+ "FontInstanceDTO": {+ "properties": {+ "name": {+ "type": "string",+ "title": "Name"+ },+ "coordinates": {+ "additionalProperties": {+ "type": "number"+ },+ "type": "object",+ "title": "Coordinates"+ }+ },+ "type": "object",+ "required": ["name", "coordinates"],+ "title": "FontInstanceDTO"+ },+ "FontInstanceRequest": {+ "properties": {+ "content_hash": {+ "type": "string",+ "maxLength": 64,+ "minLength": 64,+ "pattern": "^[a-f0-9]{64}$",+ "title": "Content Hash"+ },+ "coordinates": {+ "additionalProperties": {+ "type": "number"+ },+ "type": "object",+ "title": "Coordinates"+ }+ },+ "type": "object",+ "required": ["content_hash"],+ "title": "FontInstanceRequest"+ },+ "FontListResponse": {+ "properties": {+ "offset": {+ "type": "integer",+ "title": "Offset"+ },+ "limit": {+ "type": "integer",+ "title": "Limit"+ },+ "total": {+ "type": "integer",+ "title": "Total"+ },+ "items": {+ "items": {+ "$ref": "#/components/schemas/FontDTO"+ },+ "type": "array",+ "title": "Items"+ }+ },+ "type": "object",+ "required": ["offset", "limit", "total", "items"],+ "title": "FontListResponse"+ },+ "FontRescanResponse": {+ "properties": {+ "indexed": {+ "type": "integer",+ "title": "Indexed"+ },+ "revision": {+ "type": "integer",+ "title": "Revision"+ }+ },+ "type": "object",+ "required": ["indexed", "revision"],+ "title": "FontRescanResponse"+ },+ "FontScope": {+ "type": "string",+ "enum": ["private", "shared", "all"],+ "title": "FontScope",+ "description": "The account scope of an uploaded font."+ },+ "FontUploadResponse": {+ "properties": {+ "font": {+ "$ref": "#/components/schemas/FontDTO"+ },+ "created": {+ "type": "boolean",+ "title": "Created"+ }+ },+ "type": "object",+ "required": ["font", "created"],+ "title": "FontUploadResponse"+ },+ "FontValidationResponse": {+ "properties": {+ "filename": {+ "type": "string",+ "title": "Filename"+ },+ "family": {+ "type": "string",+ "title": "Family"+ },+ "label": {+ "type": "string",+ "title": "Label"+ },+ "style": {+ "type": "string",+ "title": "Style"+ },+ "weight": {+ "type": "integer",+ "title": "Weight"+ },+ "content_hash": {+ "type": "string",+ "title": "Content Hash"+ },+ "byte_size": {+ "type": "integer",+ "title": "Byte Size"+ },+ "axes": {+ "items": {+ "$ref": "#/components/schemas/FontAxisDTO"+ },+ "type": "array",+ "title": "Axes"+ },+ "instances": {+ "items": {+ "$ref": "#/components/schemas/FontInstanceDTO"+ },+ "type": "array",+ "title": "Instances"+ }+ },+ "type": "object",+ "required": [+ "filename",+ "family",+ "label",+ "style",+ "weight",+ "content_hash",+ "byte_size",+ "axes",+ "instances"+ ],+ "title": "FontValidationResponse"+ },"ForInvocation": {"class": "invocation","classification": "stable",@@ -53265,6 +53981,29 @@"description": "Path to directory for custom fonts.","default": "fonts"},+ "fonts_storage_dir": {+ "type": "string",+ "format": "path",+ "title": "Fonts Storage Dir",+ "description": "Path to application-managed uploaded fonts.",+ "default": "fonts-uploaded"+ },+ "max_font_upload_bytes": {+ "type": "integer",+ "maximum": 134217728.0,+ "exclusiveMinimum": 0.0,+ "title": "Max Font Upload Bytes",+ "description": "Maximum size of one uploaded custom font in bytes.",+ "default": 33554432+ },+ "max_font_library_bytes": {+ "type": "integer",+ "maximum": 17179869184.0,+ "exclusiveMinimum": 0.0,+ "title": "Max Font Library Bytes",+ "description": "Maximum total size of uploaded custom fonts in bytes per account or shared library.",+ "default": 1073741824+ },"image_subfolder_strategy": {"type": "string","enum": ["flat", "date", "type", "hash"],diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex d2040c677c..74cbd59c8b 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -430,6 +430,110 @@ export type paths = {patch?: never;trace?: never;};+ "/api/v1/fonts": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /** List Fonts */+ get: operations["list_fonts"];+ put?: never;+ /** Upload Font */+ post: operations["upload_font"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/api/v1/fonts/validate": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /** Validate Font */+ post: operations["validate_font"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/api/v1/fonts/rescan": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /** Rescan Fonts */+ post: operations["rescan_fonts"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/api/v1/fonts/{font_id}/file": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /** Get Font File */+ get: operations["get_font_file"];+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/api/v1/fonts/{font_id}": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /** Get Font */+ get: operations["get_font"];+ put?: never;+ post?: never;+ /** Delete Font */+ delete: operations["delete_font"];+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/api/v1/fonts/{font_id}/instance": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /** Create Font Instance */+ post: operations["create_font_instance"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/v2/models/": {parameters: {query?: never;@@ -5761,6 +5865,19 @@ export type components = {*/is_public: boolean;};+ /** Body_upload_font */+ Body_upload_font: {+ /**+ * File+ * @description The font file to upload+ */+ file: Blob;+ /**+ * Scope+ * @default private+ */+ scope?: string;+ };/** Body_upload_image */Body_upload_image: {/** File */@@ -5777,6 +5894,14 @@ export type components = {*/metadata?: string | null;};+ /** Body_validate_font */+ Body_validate_font: {+ /**+ * File+ * @description The font file to validate+ */+ file: Blob;+ };/*** Boolean Collection Primitive* @description A collection of boolean primitive values@@ -14883,6 +15008,125 @@ export type components = {* @enum {string}*/FluxVariantType: "schnell" | "dev" | "dev_fill";+ /** FontAxisDTO */+ FontAxisDTO: {+ /** Tag */+ tag: string;+ /** Label */+ label: string;+ /** Minimum */+ minimum: number;+ /** Default */+ default: number;+ /** Maximum */+ maximum: number;+ /** Hidden */+ hidden: boolean;+ };+ /** FontDTO */+ FontDTO: {+ /** Id */+ id: string;+ /** Family */+ family: string;+ /** Label */+ label: string;+ /** Style */+ style: string;+ /** Weight */+ weight: number;+ /** Content Hash */+ content_hash: string;+ /**+ * Scope+ * @enum {string}+ */+ scope: "private" | "shared";+ /**+ * Source+ * @enum {string}+ */+ source: "uploaded" | "directory";+ /** Filename */+ filename: string;+ /** Byte Size */+ byte_size: number;+ /** Url */+ url: string;+ /** Axes */+ axes: components["schemas"]["FontAxisDTO"][];+ /** Instances */+ instances: components["schemas"]["FontInstanceDTO"][];+ };+ /** FontInstanceDTO */+ FontInstanceDTO: {+ /** Name */+ name: string;+ /** Coordinates */+ coordinates: {+ [key: string]: number;+ };+ };+ /** FontInstanceRequest */+ FontInstanceRequest: {+ /** Content Hash */+ content_hash: string;+ /** Coordinates */+ coordinates?: {+ [key: string]: number;+ };+ };+ /** FontListResponse */+ FontListResponse: {+ /** Offset */+ offset: number;+ /** Limit */+ limit: number;+ /** Total */+ total: number;+ /** Items */+ items: components["schemas"]["FontDTO"][];+ };+ /** FontRescanResponse */+ FontRescanResponse: {+ /** Indexed */+ indexed: number;+ /** Revision */+ revision: number;+ };+ /**+ * FontScope+ * @description The account scope of an uploaded font.+ * @enum {string}+ */+ FontScope: "private" | "shared" | "all";+ /** FontUploadResponse */+ FontUploadResponse: {+ font: components["schemas"]["FontDTO"];+ /** Created */+ created: boolean;+ };+ /** FontValidationResponse */+ FontValidationResponse: {+ /** Filename */+ filename: string;+ /** Family */+ family: string;+ /** Label */+ label: string;+ /** Style */+ style: string;+ /** Weight */+ weight: number;+ /** Content Hash */+ content_hash: string;+ /** Byte Size */+ byte_size: number;+ /** Axes */+ axes: components["schemas"]["FontAxisDTO"][];+ /** Instances */+ instances: components["schemas"]["FontInstanceDTO"][];+ };/** ForInvocation */ForInvocation: {/**@@ -20736,6 +20980,25 @@ export type components = {* @default fonts*/fonts_dir?: string;+ /**+ * Fonts Storage Dir+ * Format: path+ * @description Path to application-managed uploaded fonts.+ * @default fonts-uploaded+ */+ fonts_storage_dir?: string;+ /**+ * Max Font Upload Bytes+ * @description Maximum size of one uploaded custom font in bytes.+ * @default 33554432+ */+ max_font_upload_bytes?: number;+ /**+ * Max Font Library Bytes+ * @description Maximum total size of uploaded custom fonts in bytes per account or shared library.+ * @default 1073741824+ */+ max_font_library_bytes?: number;/*** Image Subfolder Strategy* @description Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.@@ -46819,6 +47082,255 @@ export interface operations {};};};+ list_fonts: {+ parameters: {+ query?: {+ offset?: number;+ limit?: number;+ search?: string | null;+ scope?: components["schemas"]["FontScope"];+ content_hash?: string | null;+ };+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["FontListResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ upload_font: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody: {+ content: {+ "multipart/form-data": components["schemas"]["Body_upload_font"];+ };+ };+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["FontUploadResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ validate_font: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody: {+ content: {+ "multipart/form-data": components["schemas"]["Body_validate_font"];+ };+ };+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["FontValidationResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ rescan_fonts: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["FontRescanResponse"];+ };+ };+ };+ };+ get_font_file: {+ parameters: {+ query?: {+ expected_hash?: string | null;+ };+ header?: never;+ path: {+ font_id: string;+ };+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": unknown;+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ get_font: {+ parameters: {+ query?: never;+ header?: never;+ path: {+ font_id: string;+ };+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["FontDTO"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ delete_font: {+ parameters: {+ query?: never;+ header?: never;+ path: {+ font_id: string;+ };+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 204: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ create_font_instance: {+ parameters: {+ query?: never;+ header?: never;+ path: {+ font_id: string;+ };+ cookie?: never;+ };+ requestBody: {+ content: {+ "application/json": components["schemas"]["FontInstanceRequest"];+ };+ };+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": unknown;+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };list_model_records: {parameters: {query?: {diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex c78c47c585..45cfd238d1 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -35,6 +35,10 @@ Platform State also owns reusable projections of broad external stores into refeThe queue pilot is the first migrated feature. Its private `QueueBackendPort` is the adapter seam; public callers use domain reads, commands, and production runtime factories from `@features/queue`. Private snake_case HTTP DTOs map explicitly to camelCase Queue read models before crossing that interface. TanStack Query owns the global backend queue read model, and non-React runtimes own reconciliation and realtime orchestration. Persisted per-project queue history remains in the Workbench aggregate.+Fonts owns its authenticated catalog, managed-library UI, and browser font-registration lifetime behind `@features/fonts`. App composes the session runtime; Canvas receives a font-resolution port and owns text geometry, rendering, and output readiness. Persisted text references and project-file remapping remain in Workbench. Launchpad font previews and Canvas share the same account lifetime; font binaries and browser registration names are not project state. The browser registry admits at most 64 faces and 128 MiB of font input data, including faces currently being parsed. Active references are protected from eviction; if they exhaust the budget, further loads fail until references are released. This bounds retained input, not browser-specific decoded font memory. Canvas reconciles active references only when the document forests or text draft source change.++Font runtime composition and project-file option state travel in the existing shared route chunk. Catalog transport, the Fonts page, and project-file option dialogs load on demand. Missing-font recovery loads only for documents containing custom references. The locale asset plugin serves font-library strings as a separate namespace in development and production, loaded when the library or recovery UI opens; source translations remain in the canonical locale files. Text tool controls load when selected; their shared Canvas/Layer form and interaction dependencies remain grouped to avoid extra widget-activation requests. Catalog query keys have a lightweight public entry so invalidating an imported font does not pull the transport into startup.+Workbench persistence follows the same lifetime rule. `createWorkbenchPersistenceRuntime` owns hydration ordering, debounced autosave, revision/generation checks, conflict application, reconnect replay, status publication, and disposal without importing React. `createSyncedWorkbenchPersistence` constructs the local/remote project synchronization state for one mounted Workbench; no process-wide maps, sets, flags, or caches hold that state. `WorkbenchProvider` only constructs these lifetimes, starts/disposes the runtime through the mount lifecycle adapter, and selects aggregate hydration state.## Contract ownershipdiff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex 66cd509803..2d74dd9d6c 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -129,6 +129,10 @@"source:src/app/main.tsx","source:src/app/router.tsx","source:src/assets/SplashImage.webp",+ "source:src/features/fonts/data/keys.ts",+ "source:src/features/fonts/launchpad.tsx",+ "source:src/features/fonts/react.tsx",+ "source:src/features/fonts/runtime.ts","source:src/features/identity/capabilities.ts","source:src/features/identity/core/schemas.ts","source:src/features/identity/core/sessionPolicy.ts",@@ -285,6 +289,7 @@"source:src/workbench/palette/paletteStore.ts","source:src/workbench/palette/settingsEntryDeps.ts","source:src/workbench/projects/api.ts",+ "source:src/workbench/projects/components/ProjectFileOptionsProvider.tsx","source:src/workbench/projects/covers.ts","source:src/workbench/projects/ids.ts","source:src/workbench/projects/invk/format.ts",@@ -469,6 +474,10 @@"source:src/app/router.tsx","source:src/app/workbenchPorts.tsx","source:src/assets/SplashImage.webp",+ "source:src/features/fonts/data/keys.ts",+ "source:src/features/fonts/launchpad.tsx",+ "source:src/features/fonts/react.tsx",+ "source:src/features/fonts/runtime.ts","source:src/features/gallery/contracts.ts","source:src/features/gallery/core/boardLabels.ts","source:src/features/gallery/core/image.ts",@@ -866,6 +875,7 @@"source:src/workbench/projects/accountOwnedWorkbenchDatabase.ts","source:src/workbench/projects/api.ts","source:src/workbench/projects/components/OpenProjectDialog.tsx",+ "source:src/workbench/projects/components/ProjectFileOptionsProvider.tsx","source:src/workbench/projects/components/index.ts","source:src/workbench/projects/covers.ts","source:src/workbench/projects/draftStore.ts",diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 6a295d1134..0b4c49c3a5 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -726,6 +726,10 @@"source:src/app/main.tsx","source:src/app/router.tsx","source:src/assets/SplashImage.webp",+ "source:src/features/fonts/data/keys.ts",+ "source:src/features/fonts/launchpad.tsx",+ "source:src/features/fonts/react.tsx",+ "source:src/features/fonts/runtime.ts","source:src/features/gallery/core/imagePaths.ts","source:src/features/gallery/core/items.ts","source:src/features/gallery/core/recentImages.ts",@@ -917,6 +921,7 @@"source:src/workbench/palette/paletteStore.ts","source:src/workbench/palette/settingsEntryDeps.ts","source:src/workbench/projects/api.ts",+ "source:src/workbench/projects/components/ProjectFileOptionsProvider.tsx","source:src/workbench/projects/covers.ts","source:src/workbench/projects/ids.ts","source:src/workbench/projects/invk/format.ts",@@ -1071,6 +1076,10 @@"source:src/app/router.tsx","source:src/app/workbenchPorts.tsx","source:src/assets/SplashImage.webp",+ "source:src/features/fonts/data/keys.ts",+ "source:src/features/fonts/launchpad.tsx",+ "source:src/features/fonts/react.tsx",+ "source:src/features/fonts/runtime.ts","source:src/features/gallery/contracts.ts","source:src/features/gallery/core/boardLabels.ts","source:src/features/gallery/core/image.ts",@@ -1558,6 +1567,7 @@"source:src/workbench/canvas-engine/export/psdExport.ts","source:src/workbench/canvas-engine/exportRasterComposite.ts","source:src/workbench/canvas-engine/filterError.ts",+ "source:src/workbench/canvas-engine/fontReferences.ts","source:src/workbench/canvas-engine/freehand.ts","source:src/workbench/canvas-engine/history/documentPatch.ts","source:src/workbench/canvas-engine/history/history.ts",@@ -1765,6 +1775,7 @@"source:src/workbench/projects/accountOwnedWorkbenchDatabase.ts","source:src/workbench/projects/api.ts","source:src/workbench/projects/components/OpenProjectDialog.tsx",+ "source:src/workbench/projects/components/ProjectFileOptionsProvider.tsx","source:src/workbench/projects/components/index.ts","source:src/workbench/projects/covers.ts","source:src/workbench/projects/draftStore.ts",@@ -2080,6 +2091,10 @@"source:src/app/router.tsx","source:src/app/workbenchPorts.tsx","source:src/assets/SplashImage.webp",+ "source:src/features/fonts/data/keys.ts",+ "source:src/features/fonts/launchpad.tsx",+ "source:src/features/fonts/react.tsx",+ "source:src/features/fonts/runtime.ts","source:src/features/gallery/contracts.ts","source:src/features/gallery/core/boardLabels.ts","source:src/features/gallery/core/image.ts",@@ -2580,6 +2595,7 @@"source:src/workbench/canvas-engine/export/psdExport.ts","source:src/workbench/canvas-engine/exportRasterComposite.ts","source:src/workbench/canvas-engine/filterError.ts",+ "source:src/workbench/canvas-engine/fontReferences.ts","source:src/workbench/canvas-engine/freehand.ts","source:src/workbench/canvas-engine/history/documentPatch.ts","source:src/workbench/canvas-engine/history/history.ts",@@ -2791,6 +2807,7 @@"source:src/workbench/projects/accountOwnedWorkbenchDatabase.ts","source:src/workbench/projects/api.ts","source:src/workbench/projects/components/OpenProjectDialog.tsx",+ "source:src/workbench/projects/components/ProjectFileOptionsProvider.tsx","source:src/workbench/projects/components/index.ts","source:src/workbench/projects/covers.ts","source:src/workbench/projects/draftStore.ts",@@ -2970,12 +2987,12 @@"source:src/workbench/widgets/canvas/tool-options/SamOptions.tsx","source:src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx","source:src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx",- "source:src/workbench/widgets/canvas/tool-options/TextOptions.tsx","source:src/workbench/widgets/canvas/tool-options/geometryForm.tsx","source:src/workbench/widgets/canvas/tool-options/gradientStops.ts","source:src/workbench/widgets/canvas/tool-options/hintForms.tsx","source:src/workbench/widgets/canvas/tool-options/paintForm.tsx","source:src/workbench/widgets/canvas/tool-options/selectionForm.tsx",+ "source:src/workbench/widgets/canvas/tool-options/textForm.tsx","source:src/workbench/widgets/canvas/tool-options/useBboxEditor.ts","source:src/workbench/widgets/canvas/tool-presentation/FormControls.tsx","source:src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx",@@ -3258,6 +3275,10 @@"source:src/app/router.tsx","source:src/app/workbenchPorts.tsx","source:src/assets/SplashImage.webp",+ "source:src/features/fonts/data/keys.ts",+ "source:src/features/fonts/launchpad.tsx",+ "source:src/features/fonts/react.tsx",+ "source:src/features/fonts/runtime.ts","source:src/features/gallery/contracts.ts","source:src/features/gallery/core/boardLabels.ts","source:src/features/gallery/core/image.ts",@@ -3812,6 +3833,7 @@"source:src/workbench/canvas-engine/export/psdExport.ts","source:src/workbench/canvas-engine/exportRasterComposite.ts","source:src/workbench/canvas-engine/filterError.ts",+ "source:src/workbench/canvas-engine/fontReferences.ts","source:src/workbench/canvas-engine/freehand.ts","source:src/workbench/canvas-engine/history/documentPatch.ts","source:src/workbench/canvas-engine/history/history.ts",@@ -4019,6 +4041,7 @@"source:src/workbench/projects/accountOwnedWorkbenchDatabase.ts","source:src/workbench/projects/api.ts","source:src/workbench/projects/components/OpenProjectDialog.tsx",+ "source:src/workbench/projects/components/ProjectFileOptionsProvider.tsx","source:src/workbench/projects/components/index.ts","source:src/workbench/projects/covers.ts","source:src/workbench/projects/draftStore.ts",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex c38cc4baad..a051df0849 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -80,6 +80,7 @@"workflows": "Workflows"},"launchpad": {+ "goToFonts": "Go to Fonts","goToModels": "Go to Models","goToNodes": "Go to Nodes","goToProjects": "Go to Projects",@@ -506,7 +507,18 @@"name": "Name"},"unpin": "Unpin",- "viewLabel": "Project layout"+ "viewLabel": "Project layout",+ "fonts": {+ "exportTitle": "Export {{name}}",+ "includeFiles": "Include font files",+ "exportDescription": "Without font files, recipients may need to install or replace fonts used in this project.",+ "rightsReminder": "Only include fonts you have permission to redistribute. Recipients import them into their private libraries.",+ "exportAction": "Export project",+ "importTitle": "Font storage limit reached",+ "quotaDescription": "This server has insufficient font storage. Import with font references, then install or replace missing fonts before generating or exporting images.",+ "importReferences": "Import without font files",+ "installing": "Installing fonts {{completed}} / {{total}}"+ }},"users": {"accountCount_one": "{{count}} account in this workspace.",@@ -560,6 +572,82 @@"user": "User","you": "You"},+ "fonts": {+ "title": "Fonts",+ "description": "Browse fonts available to this Invoke workspace and add your own files.",+ "filterLabel": "Font library scope",+ "filterMenu": "Filter fonts",+ "library": "Font library",+ "filters": {+ "all": "All",+ "my": "My fonts",+ "shared": "Shared"+ },+ "searchLabel": "Search fonts",+ "searchPlaceholder": "Search fonts…",+ "upload": "Upload fonts",+ "uploadShared": "Upload shared",+ "loadMore": "Load more fonts",+ "loadingMore": "Loading more fonts…",+ "uploadScopeLabel": "Upload destination",+ "rescan": "Rescan directory",+ "scope": {+ "private": "My font",+ "shared": "Shared"+ },+ "source": {+ "directory": "Server directory",+ "uploaded": "Uploaded"+ },+ "previewText": "The quick brown fox jumps over the lazy dog.",+ "loadingPreview": "Loading preview…",+ "retryPreview": "Retry preview",+ "axisCount_one": "{{count}} axis",+ "axisCount_other": "{{count}} axes",+ "namedInstances_one": "{{count}} named instance",+ "namedInstances_other": "{{count}} named instances",+ "fileSize": "{{bytes}}",+ "emptyTitle": "No fonts available",+ "emptyDescription": "Upload a TTF, OTF, WOFF, or WOFF2 file, or add one to the server fonts directory.",+ "noSearchMatches": "No fonts match this search",+ "noSearchMatchesDescription": "Try a different name or clear the search.",+ "couldNotLoad": "Could not load fonts",+ "rescanFailed": "Could not rescan the fonts directory",+ "uploading": "Uploading…",+ "uploaded": "Uploaded",+ "duplicate": "Already available",+ "uploadFailed": "Upload failed",+ "deleteNamed": "Delete {{name}}",+ "deleteTitle": "Delete font?",+ "deleteBody": "Delete {{name}}? Existing projects keep their reference and may need a replacement.",+ "deleteConfirm": "Delete font",+ "deleteFailed": "Could not delete the font",+ "missing": {+ "warning_one": "Missing font — review",+ "warning_other": "Missing fonts — review",+ "title": "Missing fonts",+ "description": "Some text fonts are unavailable. Previews use a fallback. Export, baking, and generation that use this text remain blocked until its fonts are restored or replaced.",+ "continue": "Continue with previews",+ "layers_one": "Used by {{count}} text layer",+ "layers_other": "Used by {{count}} text layers",+ "search": "Search replacement fonts",+ "replacement": "Replacement font",+ "select": "Select a replacement",+ "upload": "Upload font",+ "replaceAll": "Replace all uses",+ "axesNotice": "Replacement preserves supported variation axes within their limits and resets unsupported axes. You can undo this change.",+ "catalogError": "Unable to load the font library. Retry to reconnect.",+ "failed": "The font could not be replaced. Finish the current Canvas operation and retry."+ },+ "addFonts": "Add Fonts",+ "details": "Details",+ "selectFont": "Select a font",+ "selectFontDescription": "Choose a font from your library to preview it and view its details.",+ "uploadDescription": "Upload TTF, OTF, WOFF or WOFF2 files. My fonts are private to your account; shared fonts are available to everyone on this server.",+ "axesTitle": "Variation axes",+ "axisDefault": "Default {{value}}",+ "instancesTitle": "Named instances"+ },"graphPreview": {"back": "Back","cfgScale": "CFG scale",@@ -1460,7 +1548,8 @@"models": "Models","nodes": "Nodes","projects": "Projects",- "users": "Users"+ "users": "Users",+ "fonts": "Fonts"},"sectionsLabel": "Launchpad sections"},@@ -2767,7 +2856,19 @@"textColor": "Text color","textEdit": "Edit text","textFont": "Font",+ "textFontAxes": "Axes",+ "textFontBuiltinGroup": "Built-in",+ "textFontCustomGroup": "Custom",+ "textFontDefaultPreset": "Default",+ "textFontHideAdvancedAxes": "Hide hidden axes","textLineHeight": "Line height",+ "textFontPreset": "Preset",+ "textFontResetAxes": "Reset axes",+ "textFontShowAdvancedAxes": "Show hidden axes",+ "textFontStyle": "Style",+ "textFontStyleItalic": "Italic",+ "textFontStyleNormal": "Regular",+ "textFontStyleOblique": "Oblique","textSize": "Font size","textWeight": "Weight","gradientPairPreset": "Foreground to background preset"diff --git a/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs b/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjsindex c79c7e2f99..07f27c5a00 100644--- a/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs+++ b/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs@@ -1,10 +1,35 @@import { readFile, readdir } from 'node:fs/promises';import { resolve } from 'node:path';-/** Keep source locales readable while serving compact JSON at their existing URLs. */+const splitLocale = (translations) => {+ const { fonts, ...translation } = translations;+ return { translation, fonts: fonts ? { fonts } : {} };+};++/** Keep source locales readable; load font-library copy only when that UI opens. */export const localeAssetsPlugin = ({ projectRoot }) => ({- apply: 'build',name: 'invokeai-locale-assets',+ configureServer(server) {+ server.middlewares.use(async (request, response, next) => {+ const match = request.url?.match(/\/locales\/([a-zA-Z0-9_-]+)(\.fonts)?\.json(?:\?.*)?$/);+ if (!match) {+ next();+ return;+ }+ try {+ const source = await readFile(resolve(projectRoot, `public/locales/${match[1]}.json`), 'utf8');+ const parts = splitLocale(JSON.parse(source));+ response.setHeader('Content-Type', 'application/json');+ response.end(JSON.stringify(match[2] ? parts.fonts : parts.translation));+ } catch (error) {+ if (error.code === 'ENOENT') {+ next();+ } else {+ next(error);+ }+ }+ });+ },async generateBundle() {const directory = resolve(projectRoot, 'public/locales');const entries = await readdir(directory, { withFileTypes: true });@@ -19,8 +44,14 @@ export const localeAssetsPlugin = ({ projectRoot }) => ({} catch (error) {throw new Error(`Invalid locale JSON: ${entry.name}`, { cause: error });}- // Vite copies public files before generateBundle; this replaces only the emitted locale copy.- this.emitFile({ type: 'asset', fileName: `locales/${entry.name}`, source: JSON.stringify(parsed) });+ const parts = splitLocale(parsed);+ // Vite copies public files before generateBundle; replace only the emitted copy.+ this.emitFile({ type: 'asset', fileName: `locales/${entry.name}`, source: JSON.stringify(parts.translation) });+ this.emitFile({+ type: 'asset',+ fileName: `locales/${entry.name.replace('.json', '.fonts.json')}`,+ source: JSON.stringify(parts.fonts),+ });}},});diff --git a/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs b/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjsindex 3d667a8beb..d0a5835f26 100644--- a/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs+++ b/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs@@ -3,7 +3,7 @@ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { resolve } from 'node:path';import test from 'node:test';-import { build } from 'vite';+import { build, createServer } from 'vite';import { localeAssetsPlugin } from './locale-assets-plugin.mjs';@@ -59,3 +59,36 @@ test('invalid locale JSON fails the production build with the failing filename',await assert.rejects(buildFixture(projectRoot), /Invalid locale JSON: broken\.json/);});++test('font namespace loads separately in production and development, preserving fallback locales', async (context) => {+ const projectRoot = await createFixture(context);+ const translations = { common: { retry: 'Retry' }, fonts: { title: 'Fonts 🎨' } };+ await writeFile(resolve(projectRoot, 'public/locales/en.json'), JSON.stringify(translations));+ await writeFile(resolve(projectRoot, 'public/locales/fr.json'), JSON.stringify({ common: { retry: 'Réessayer' } }));+ await buildFixture(projectRoot);+ assert.deepEqual(JSON.parse(await readFile(resolve(projectRoot, 'dist/locales/en.json'), 'utf8')), {+ common: translations.common,+ });+ assert.deepEqual(JSON.parse(await readFile(resolve(projectRoot, 'dist/locales/en.fonts.json'), 'utf8')), {+ fonts: translations.fonts,+ });+ assert.deepEqual(JSON.parse(await readFile(resolve(projectRoot, 'dist/locales/fr.fonts.json'), 'utf8')), {});+ const server = await createServer({+ root: projectRoot,+ configFile: false,+ logLevel: 'silent',+ plugins: [localeAssetsPlugin({ projectRoot })],+ server: { port: 0, host: '127.0.0.1' },+ });+ context.after(() => server.close());+ await server.listen();+ const origin = server.resolvedUrls.local[0];+ for (const filename of ['en.json', 'en.fonts.json', 'fr.fonts.json']) {+ const response = await fetch(new URL(`locales/${filename}`, origin));+ assert.equal(response.status, 200);+ assert.deepEqual(+ await response.json(),+ JSON.parse(await readFile(resolve(projectRoot, `dist/locales/${filename}`), 'utf8'))+ );+ }+});diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjsindex 8af09fb0f2..97f7df94ca 100644--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -968,6 +968,15 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {return json(200, []);}+ if (method === 'GET' && path === '/api/v1/fonts') {+ return json(200, {+ items: [],+ total: 0,+ offset: Math.max(0, Number(url.searchParams.get('offset') ?? 0)),+ limit: Number(url.searchParams.get('limit') ?? 100),+ });+ }+// Dynamic prompt expansion. Enough of the `{a|b}` grammar for journeys to// exercise the preview and the batch dimension; the real generator lives// in the backend.diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjsindex b83074aa47..74733cdb7b 100644--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs@@ -155,6 +155,14 @@ const surfaces = [path: '/#/projects',ready: waitForProjects,},+ {+ id: 'launchpad-fonts-empty',+ path: '/#/fonts',+ ready: async (page) => {+ await page.getByRole('textbox', { exact: true, name: 'Search fonts' }).waitFor();+ await page.getByText('No fonts available', { exact: true }).waitFor();+ },+ },{id: 'launchpad-models-representative',path: '/#/models',@@ -270,13 +278,18 @@ const runKeyboardJourney = async (browser) => {await waitForHome(page);const projectsTab = page.getByRole('tab', { exact: true, name: 'Projects' });+ const fontsTab = page.getByRole('tab', { exact: true, name: 'Fonts' });const modelsTab = page.getByRole('tab', { exact: true, name: 'Models' });// The rail is grouped, but it is still one tablist: arrowing off the last// Workspace tab has to land on the first Manage tab, skipping the headings.await projectsTab.focus();await projectsTab.press('ArrowDown');- await expectFocused(modelsTab, 'ArrowDown should move focus from Projects to Models.');+ await expectFocused(fontsTab, 'ArrowDown should move focus from Projects to Fonts.');+ assert.match(page.url(), /#\/fonts$/);+ assert.equal(await fontsTab.getAttribute('aria-selected'), 'true');+ await fontsTab.press('ArrowDown');+ await expectFocused(modelsTab, 'ArrowDown should move focus from Fonts to Models.');await waitForModels(page);assert.match(page.url(), /#\/models$/);assert.equal(await modelsTab.getAttribute('aria-selected'), 'true');diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjsindex e8a7465f1f..df0cb86003 100644--- a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs@@ -269,6 +269,9 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectory.getByRole('button', { exact: true, name: `Switch project. Current project: ${sourceProjectName}` }).click();await exportPage.getByRole('menuitem', { exact: true, name: 'Export' }).click();+ await exportPage.getByRole('dialog', { name: `Export ${sourceProjectName}`, exact: true }).waitFor();+ assert.equal(await exportPage.getByRole('checkbox', { name: 'Include font files', exact: true }).isChecked(), false);+ await exportPage.getByRole('button', { name: 'Export project', exact: true }).click();const download = await downloadPromise;const archivePath = join(tempDirectory, 'fixture-project-002.invk');diff --git a/invokeai/frontend/webv2/src/app/router.tsx b/invokeai/frontend/webv2/src/app/router.tsxindex 4bc136255c..81c2f3811e 100644--- a/invokeai/frontend/webv2/src/app/router.tsx+++ b/invokeai/frontend/webv2/src/app/router.tsx@@ -1,3 +1,4 @@+import { FontsRuntimeProvider } from '@features/fonts/react';import {AuthSessionUnavailableError,AuthUnavailableScreen,@@ -25,6 +26,7 @@ import {import { WorkbenchSplashScreen } from '@workbench/components/WorkbenchSplashScreen';import { isLaunchpadIntentId, isLaunchpadLayoutId } from '@workbench/launchpad/intents';import { Launchpad } from '@workbench/launchpad/Launchpad';+import { ProjectFileOptionsProvider } from '@workbench/projects/components/ProjectFileOptionsProvider';import { peekOpenProjectIds, type WorkbenchSearch } from '@workbench/projects/session';import { loadWorkbenchSettings } from '@workbench/settings/store';import { Fragment } from 'react';@@ -72,6 +74,8 @@ const rootRoute = createRootRoute({ component: Outlet, errorComponent: RouterErr* editor/model-manager view code.*/const AuthenticatedLayout = () => {+ 'use no memo';+ // Account transitions are infrequent; provider composition does not need a memo cache.const session = useAuthSession();if (session.phase !== 'ready') {@@ -86,7 +90,11 @@ const AuthenticatedLayout = () => {<Fragment key={session.accountEpoch}><SocketHubRuntime /><ModelInstallRuntime />- <Outlet />+ <FontsRuntimeProvider>+ <ProjectFileOptionsProvider>+ <Outlet />+ </ProjectFileOptionsProvider>+ </FontsRuntimeProvider></Fragment>);};@@ -122,22 +130,24 @@ const requireLaunchpadCapability = async (capability: keyof Capabilities): Promi// `/` plus a deep-link alias per Launchpad section. All render the same shell;// it reads the path to pick the active page.-const homeRoute = createRoute({+const launchpadRouteOptions = {component: Launchpad,getParentRoute: () => authenticatedRoute,+};++const homeRoute = createRoute({+ ...launchpadRouteOptions,path: '/',});const projectsHomeRoute = createRoute({- component: Launchpad,- getParentRoute: () => authenticatedRoute,+ ...launchpadRouteOptions,path: 'projects',});const modelsHomeRoute = createRoute({beforeLoad: () => requireLaunchpadCapability('canManageModels'),- component: Launchpad,- getParentRoute: () => authenticatedRoute,+ ...launchpadRouteOptions,path: 'models',validateSearch: (search: Record<string, unknown>): { project?: string } => ({project: typeof search.project === 'string' && search.project.length > 0 ? search.project : undefined,@@ -146,18 +156,21 @@ const modelsHomeRoute = createRoute({const nodesHomeRoute = createRoute({beforeLoad: () => requireLaunchpadCapability('canManageNodes'),- component: Launchpad,- getParentRoute: () => authenticatedRoute,+ ...launchpadRouteOptions,path: 'nodes',});const usersHomeRoute = createRoute({beforeLoad: () => requireLaunchpadCapability('canManageUsers'),- component: Launchpad,- getParentRoute: () => authenticatedRoute,+ ...launchpadRouteOptions,path: 'users',});+const fontsHomeRoute = createRoute({+ ...launchpadRouteOptions,+ path: 'fonts',+});+const workbenchRoute = createRoute({beforeLoad: async ({ cause, search }) => {// Warm the editor bundle while the guard's session peek is in flight. The@@ -240,6 +253,7 @@ export const router = createRouter({modelsHomeRoute,nodesHomeRoute,usersHomeRoute,+ fontsHomeRoute,workbenchRoute,]),loginRoute,diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.tsindex da6b8578e5..c7617b018a 100644--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts@@ -17,6 +17,7 @@ export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string['utility','widget',],+ fonts: ['contracts', 'launchpad', 'react', 'runtime'],generation: ['canvasGraph','canvasProcessingSize',diff --git a/invokeai/frontend/webv2/src/features/fonts/contracts.ts b/invokeai/frontend/webv2/src/features/fonts/contracts.tsnew file mode 100644index 0000000000..def85808d3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/contracts.ts@@ -0,0 +1,13 @@+export { fontKeys } from './data/keys';++export type {+ FontAxis,+ FontCatalogPage,+ FontDownloadReference,+ FontInstance,+ FontLoadState,+ FontRecord,+ FontReference,+ FontScope,+ FontSource,+} from './core/types';diff --git a/invokeai/frontend/webv2/src/features/fonts/core/types.ts b/invokeai/frontend/webv2/src/features/fonts/core/types.tsnew file mode 100644index 0000000000..fe3af307b4--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/core/types.ts@@ -0,0 +1,63 @@+/** A variation axis exposed by a font file. */+export interface FontAxis {+ tag: string;+ label: string;+ minimum: number;+ default: number;+ maximum: number;+ hidden: boolean;+}++/** A named variation instance supplied by the font's metadata. */+export interface FontInstance {+ name: string;+ coordinates: Readonly<Record<string, number>>;+}++export type FontScope = 'private' | 'shared';+export type FontSource = 'uploaded' | 'directory';++/**+ * The frontend read model for one indexed font file/face. `id` and+ * `contentHash` are stable identity fields; the readable family and filename+ * are presentation metadata only.+ */+export interface FontRecord {+ id: string;+ family: string;+ label: string;+ style: string;+ weight: number;+ contentHash: string;+ scope: FontScope;+ source: FontSource;+ filename: string;+ byteSize: number;+ url: string;+ axes: readonly FontAxis[];+ instances: readonly FontInstance[];+}++export interface FontCatalogPage {+ items: readonly FontRecord[];+ total: number;+ offset: number;+ limit: number;+}++/** Persistable input for resolving an indexed font in the browser runtime. */+export interface FontReference {+ id: string;+ contentHash?: string | null;+ family?: string;+ style?: string;+ weight?: number;+ axes?: Readonly<Record<string, number>>;+}++export interface FontDownloadReference extends FontReference {+ /** A non-empty axis map requests a pinned static instance from the backend. */+ axes?: Readonly<Record<string, number>>;+}++export type FontLoadState = 'idle' | 'loading' | 'ready' | 'error';diff --git a/invokeai/frontend/webv2/src/features/fonts/data/api.test.ts b/invokeai/frontend/webv2/src/features/fonts/data/api.test.tsnew file mode 100644index 0000000000..7705dd6317--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/data/api.test.ts@@ -0,0 +1,108 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const transport = vi.hoisted(() => ({+ apiFetch: vi.fn(),+ apiFetchJson: vi.fn(),+}));++vi.mock('@platform/transport/http', () => transport);++const dto = {+ axes: [{ default: 400, hidden: false, label: 'Weight', maximum: 900, minimum: 100, tag: 'wght' }],+ byte_size: 128,+ content_hash: 'a'.repeat(64),+ family: 'Example Sans',+ filename: 'ExampleSans.ttf',+ id: 'font/example',+ instances: [{ coordinates: { wght: 400 }, name: 'Regular' }],+ label: 'Example Sans Regular',+ scope: 'private',+ source: 'uploaded',+ style: 'normal',+ url: '/api/v1/fonts/font%2Fexample/file',+ weight: 400,+};++describe('font transport', () => {+ beforeEach(() => {+ transport.apiFetch.mockReset();+ transport.apiFetchJson.mockReset();+ });++ it('maps the paginated catalog and sends the server query contract', async () => {+ transport.apiFetchJson.mockResolvedValue({ items: [dto], limit: 25, offset: 50, total: 75 });+ const { listFonts } = await import('./api');++ await expect(+ listFonts({ contentHash: 'a'.repeat(64), limit: 25, offset: 50, scope: 'private', search: ' Sans ' })+ ).resolves.toEqual({+ items: [+ expect.objectContaining({+ axes: [{ default: 400, hidden: false, label: 'Weight', maximum: 900, minimum: 100, tag: 'wght' }],+ byteSize: 128,+ contentHash: 'a'.repeat(64),+ instances: [{ coordinates: { wght: 400 }, name: 'Regular' }],+ }),+ ],+ limit: 25,+ offset: 50,+ total: 75,+ });+ expect(transport.apiFetchJson).toHaveBeenCalledWith(+ '/api/v1/fonts?limit=25&offset=50&content_hash=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&search=Sans&scope=private',+ {+ signal: undefined,+ }+ );+ });++ it('pins variation coordinates and sends the JSON content hash', async () => {+ transport.apiFetch.mockResolvedValue(new Response(new Uint8Array([1, 2, 3])));+ const { downloadFont } = await import('./api');+ const signal = new AbortController().signal;++ await expect(+ downloadFont(+ {+ axes: { wdth: 90, wght: 650 },+ contentHash: 'b'.repeat(64),+ id: 'font/example',+ },+ signal+ )+ ).resolves.toEqual(new Uint8Array([1, 2, 3]));+ expect(transport.apiFetch).toHaveBeenCalledWith('/api/v1/fonts/font%2Fexample/instance', {+ body: JSON.stringify({ content_hash: 'b'.repeat(64), coordinates: { wdth: 90, wght: 650 } }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ signal,+ });+ });++ it('validates multipart files, uploads private scope, and deletes by opaque id', async () => {+ transport.apiFetchJson+ .mockResolvedValueOnce({ ...dto, filename: 'checked.otf' })+ .mockResolvedValueOnce({ created: true, font: dto });+ transport.apiFetch.mockResolvedValue(new Response(null, { status: 204 }));+ const { deleteFont, uploadFont, validateFont } = await import('./api');+ const file = new File(['font bytes'], 'checked.otf', { type: 'font/otf' });++ await expect(validateFont(file)).resolves.toMatchObject({+ contentHash: 'a'.repeat(64),+ filename: 'checked.otf',+ });+ await expect(uploadFont(file, 'private')).resolves.toMatchObject({ created: true, font: { id: dto.id } });+ await deleteFont('font/example');++ const validationInit = transport.apiFetchJson.mock.calls[0]?.[1] as RequestInit;+ expect(validationInit.method).toBe('POST');+ expect(validationInit.body).toBeInstanceOf(FormData);+ expect((validationInit.body as FormData).get('file')).toBe(file);+ const uploadInit = transport.apiFetchJson.mock.calls[1]?.[1] as RequestInit;+ expect((uploadInit.body as FormData).get('scope')).toBe('private');+ expect(transport.apiFetch).toHaveBeenCalledWith('/api/v1/fonts/font%2Fexample', {+ method: 'DELETE',+ signal: undefined,+ });+ });+});diff --git a/invokeai/frontend/webv2/src/features/fonts/data/api.ts b/invokeai/frontend/webv2/src/features/fonts/data/api.tsnew file mode 100644index 0000000000..480dfc4f68--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/data/api.ts@@ -0,0 +1,235 @@+import type {+ FontAxis,+ FontCatalogPage,+ FontDownloadReference,+ FontInstance,+ FontRecord,+ FontScope,+} from '@features/fonts/core/types';++import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';+import { apiFetch, apiFetchJson } from '@platform/transport/http';++import type { FontListParams } from './keys';++export type { FontListParams } from './keys';++const FONTS_BASE = '/api/v1/fonts';++interface FontAxisDTO {+ tag: string;+ label?: string;+ minimum: number;+ default: number;+ maximum: number;+ hidden?: boolean;+}++interface FontInstanceDTO {+ name: string;+ coordinates: Record<string, number>;+}++interface FontRecordDTO {+ id: string;+ family: string;+ label: string;+ style: string;+ weight: number;+ content_hash: string;+ scope: FontScope;+ source: 'uploaded' | 'directory';+ filename: string;+ byte_size: number;+ url: string;+ axes?: FontAxisDTO[];+ instances?: FontInstanceDTO[];+}++interface FontCatalogPageDTO {+ items: FontRecordDTO[];+ total: number;+ offset: number;+ limit: number;+}++interface FontValidationDTO {+ filename: string;+ family: string;+ label: string;+ style: string;+ weight: number;+ content_hash: string;+ byte_size: number;+ axes?: FontAxisDTO[];+ instances?: FontInstanceDTO[];+}++export interface FontRescanResult {+ indexed: number;+ revision: number;+}++export interface FontValidationResult {+ filename: string;+ family: string;+ label: string;+ style: string;+ weight: number;+ contentHash: string;+ byteSize: number;+ axes: readonly FontAxis[];+ instances: readonly FontInstance[];+}++export interface UploadFontResult {+ font: FontRecord;+ created: boolean;+}++const mapAxis = (axis: FontAxisDTO): FontAxis => ({+ default: axis.default,+ hidden: axis.hidden === true,+ label: axis.label?.trim() || axis.tag,+ maximum: axis.maximum,+ minimum: axis.minimum,+ tag: axis.tag,+});++const mapInstance = (instance: FontInstanceDTO): FontInstance => ({+ coordinates: { ...instance.coordinates },+ name: instance.name,+});++export const mapFontRecord = (dto: FontRecordDTO): FontRecord => ({+ axes: (dto.axes ?? []).map(mapAxis),+ byteSize: dto.byte_size,+ contentHash: dto.content_hash,+ family: dto.family,+ filename: dto.filename,+ id: dto.id,+ instances: (dto.instances ?? []).map(mapInstance),+ label: dto.label,+ scope: dto.scope,+ source: dto.source,+ style: dto.style,+ url: dto.url,+ weight: dto.weight,+});++const mapValidationResult = (dto: FontValidationDTO): FontValidationResult => ({+ axes: (dto.axes ?? []).map(mapAxis),+ byteSize: dto.byte_size,+ contentHash: dto.content_hash,+ family: dto.family,+ filename: dto.filename,+ instances: (dto.instances ?? []).map(mapInstance),+ label: dto.label,+ style: dto.style,+ weight: dto.weight,+});++const buildListUrl = ({+ contentHash,+ limit = 100,+ offset = 0,+ scope = 'all',+ search = '',+}: FontListParams = {}): string => {+ const params = new URLSearchParams({ limit: String(limit), offset: String(offset) });++ if (contentHash) {+ params.set('content_hash', contentHash);+ }+ if (search.trim()) {+ params.set('search', search.trim());+ }+ if (scope !== 'all') {+ params.set('scope', scope);+ }++ return `${FONTS_BASE}?${params.toString()}`;+};++export const listFonts = async (params: FontListParams = {}, signal?: AbortSignal): Promise<FontCatalogPage> => {+ const dto = await apiFetchJson<FontCatalogPageDTO>(buildListUrl(params), { signal });+ const items = dto.items.map(mapFontRecord);++ return {+ items,+ limit: dto.limit,+ offset: dto.offset,+ total: dto.total,+ };+};++export const getFont = async (id: string, signal?: AbortSignal): Promise<FontRecord> => {+ const dto = await apiFetchJson<FontRecordDTO>(`${FONTS_BASE}/${encodeURIComponent(id)}`, { signal });++ return mapFontRecord(dto);+};++const getFontFileUrl = (reference: FontDownloadReference): string => {+ const params = new URLSearchParams();++ if (reference.contentHash) {+ params.set('expected_hash', reference.contentHash);+ }++ const query = params.toString();+ return `${FONTS_BASE}/${encodeURIComponent(reference.id)}/file${query ? `?${query}` : ''}`;+};++/** Downloads an original face or a pinned static variation instance. */+export const downloadFont = async (reference: FontDownloadReference, signal?: AbortSignal): Promise<Uint8Array> => {+ const owner = captureAccountScope();+ const hasAxes = reference.axes !== undefined && Object.keys(reference.axes).length > 0;+ const response = hasAxes+ ? await apiFetch(`${FONTS_BASE}/${encodeURIComponent(reference.id)}/instance`, {+ body: JSON.stringify({+ content_hash: reference.contentHash ?? undefined,+ coordinates: reference.axes,+ }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ signal,+ })+ : await apiFetch(getFontFileUrl(reference), { signal });++ const bytes = new Uint8Array(await response.arrayBuffer());+ assertAccountScopeCurrent(owner);+ return bytes;+};++/** Validates and extracts metadata without publishing the upload. */+export const validateFont = async (file: Blob, signal?: AbortSignal): Promise<FontValidationResult> => {+ const body = new FormData();+ body.append('file', file);+ const dto = await apiFetchJson<FontValidationDTO>(`${FONTS_BASE}/validate`, { body, method: 'POST', signal });++ return mapValidationResult(dto);+};++export const uploadFont = async (+ file: Blob,+ scope: FontScope = 'private',+ signal?: AbortSignal+): Promise<UploadFontResult> => {+ const body = new FormData();+ body.append('file', file);+ body.append('scope', scope);+ const dto = await apiFetchJson<{ font: FontRecordDTO; created: boolean }>(FONTS_BASE, {+ body,+ method: 'POST',+ signal,+ });++ return { created: dto.created, font: mapFontRecord(dto.font) };+};++export const deleteFont = async (id: string, signal?: AbortSignal): Promise<void> => {+ await apiFetch(`${FONTS_BASE}/${encodeURIComponent(id)}`, { method: 'DELETE', signal });+};++export const rescanFonts = (signal?: AbortSignal): Promise<FontRescanResult> =>+ apiFetchJson<FontRescanResult>(`${FONTS_BASE}/rescan`, { method: 'POST', signal });diff --git a/invokeai/frontend/webv2/src/features/fonts/data/keys.ts b/invokeai/frontend/webv2/src/features/fonts/data/keys.tsnew file mode 100644index 0000000000..bbdfeae4f2--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/data/keys.ts@@ -0,0 +1,16 @@+export interface FontListParams {+ contentHash?: string;+ offset?: number;+ limit?: number;+ search?: string;+ scope?: 'private' | 'shared' | 'all';+}++/** Query keys are kept independent from the transport so account-owned callers+ * can invalidate the catalog without importing the font byte/API module. */+export const fontKeys = {+ all: ['fonts'] as const,+ catalog: (params: FontListParams = {}) => ['fonts', 'catalog', params] as const,+ infiniteCatalog: (params: FontListParams = {}) => ['fonts', 'infinite-catalog', params] as const,+ detail: (id: string) => ['fonts', 'detail', id] as const,+};diff --git a/invokeai/frontend/webv2/src/features/fonts/data/queries.test.ts b/invokeai/frontend/webv2/src/features/fonts/data/queries.test.tsnew file mode 100644index 0000000000..d18e9d4e61--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/data/queries.test.ts@@ -0,0 +1,99 @@+import type { FontCatalogPage, FontListParams, FontRecord } from '@features/fonts';++import { InfiniteQueryObserver, QueryClient } from '@tanstack/react-query';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const transport = vi.hoisted(() => ({+ listFonts: vi.fn(),+}));++vi.mock('./api', () => transport);++import { fontsInfiniteQueryOptions, fontsQueryOptions } from './queries';++const createFont = (id: string): FontRecord => ({+ axes: [],+ byteSize: 1024,+ contentHash: id,+ family: `Example ${id}`,+ filename: `${id}.ttf`,+ id,+ instances: [],+ label: `Example ${id} Regular`,+ scope: 'private',+ source: 'uploaded',+ style: 'normal',+ url: `/api/v1/fonts/${id}/file`,+ weight: 400,+});++describe('font catalog queries', () => {+ beforeEach(() => {+ transport.listFonts.mockReset();+ });++ it('fetches offset pages until the catalog total is covered', async () => {+ const firstPage: FontCatalogPage = {+ items: [createFont('first')],+ limit: 100,+ offset: 0,+ total: 101,+ };+ const secondPage: FontCatalogPage = {+ items: [createFont('second')],+ limit: 100,+ offset: 100,+ total: 101,+ };+ transport.listFonts.mockImplementation(({ offset }: FontListParams) =>+ Promise.resolve(offset === 0 ? firstPage : secondPage)+ );++ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const options = fontsInfiniteQueryOptions({ limit: 100, scope: 'all' });+ const observer = new InfiniteQueryObserver(queryClient, options);++ try {+ await observer.refetch();+ expect(observer.getCurrentResult().hasNextPage).toBe(true);+ await observer.fetchNextPage();++ const result = observer.getCurrentResult();+ expect(result.data?.pageParams).toEqual([0, 100]);+ expect(result.data?.pages.flatMap((page) => page.items.map((font) => font.id))).toEqual(['first', 'second']);+ expect(result.hasNextPage).toBe(false);+ expect(transport.listFonts.mock.calls.map(([params]) => params.offset)).toEqual([0, 100]);+ } finally {+ observer.destroy();+ }+ });++ it('keeps an offset-started catalog window on its own cache key', () => {+ const base = fontsInfiniteQueryOptions({ limit: 100, scope: 'all' });+ const offset = fontsInfiniteQueryOptions({ limit: 100, offset: 100, scope: 'all' });++ expect(offset.queryKey).not.toEqual(base.queryKey);+ });++ it('keeps normal and infinite catalog data isolated for matching filters', async () => {+ const page: FontCatalogPage = {+ items: [createFont('shared')],+ limit: 100,+ offset: 0,+ total: 1,+ };+ transport.listFonts.mockResolvedValue(page);++ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const params = { limit: 100, scope: 'all' } as const;+ const normal = fontsQueryOptions(params);+ const infinite = fontsInfiniteQueryOptions(params);++ await queryClient.fetchQuery(normal);+ await queryClient.fetchInfiniteQuery(infinite);++ expect(normal.queryKey).not.toEqual(infinite.queryKey);+ expect(queryClient.getQueryData(normal.queryKey)).toEqual(page);+ expect(queryClient.getQueryData(infinite.queryKey)).toEqual({ pages: [page], pageParams: [0] });+ });+});diff --git a/invokeai/frontend/webv2/src/features/fonts/data/queries.ts b/invokeai/frontend/webv2/src/features/fonts/data/queries.tsnew file mode 100644index 0000000000..5cd4e4b95e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/data/queries.ts@@ -0,0 +1,53 @@+import type { FontCatalogPage } from '@features/fonts/core/types';++import { infiniteQueryOptions, queryOptions, type InfiniteData } from '@tanstack/react-query';++import type { FontListParams } from './keys';++import { listFonts } from './api';+import { fontKeys } from './keys';++export const FONT_PAGE_SIZE = 100;++export { fontKeys } from './keys';++export const fontsQueryOptions = (params: FontListParams = {}) =>+ queryOptions({+ queryFn: ({ signal }) => listFonts(params, signal),+ queryKey: fontKeys.catalog(params),+ staleTime: 30_000,+ });++/**+ * A bounded transport page assembled as an infinite query for controls that+ * need to append catalog results. Every request remains offset based, so the+ * server never sends an unbounded response and callers can stop at the real+ * catalog total.+ */+export const fontsInfiniteQueryOptions = (params: FontListParams = {}) => {+ const { offset: initialOffset = 0, ...filters } = params;+ const limit = params.limit ?? FONT_PAGE_SIZE;+ const queryParams = { ...filters, limit, ...(initialOffset > 0 ? { offset: initialOffset } : {}) };++ return infiniteQueryOptions<+ FontCatalogPage,+ Error,+ InfiniteData<FontCatalogPage, number>,+ ReturnType<typeof fontKeys.infiniteCatalog>,+ number+ >({+ getNextPageParam: (lastPage, _allPages, lastPageParam) => {+ if (lastPage.items.length === 0) {+ return undefined;+ }++ const pageSize = lastPage.limit > 0 ? lastPage.limit : limit;+ const nextOffset = lastPageParam + pageSize;+ return nextOffset < lastPage.total ? nextOffset : undefined;+ },+ initialPageParam: initialOffset,+ queryFn: ({ pageParam, signal }) => listFonts({ ...filters, limit, offset: pageParam }, signal),+ queryKey: fontKeys.infiniteCatalog(queryParams),+ staleTime: 30_000,+ });+};diff --git a/invokeai/frontend/webv2/src/features/fonts/index.ts b/invokeai/frontend/webv2/src/features/fonts/index.tsnew file mode 100644index 0000000000..723532e7ef--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/index.ts@@ -0,0 +1,33 @@+export type {+ FontAxis,+ FontCatalogPage,+ FontDownloadReference,+ FontInstance,+ FontLoadState,+ FontRecord,+ FontReference,+ FontScope,+ FontSource,+} from './contracts';+export {+ deleteFont,+ downloadFont,+ getFont,+ listFonts,+ rescanFonts,+ uploadFont,+ validateFont,+ type FontListParams,+ type FontRescanResult,+ type FontValidationResult,+ type UploadFontResult,+} from './data/api';+export { fontKeys } from './data/keys';+export { FONT_PAGE_SIZE, fontsInfiniteQueryOptions, fontsQueryOptions } from './data/queries';+export {+ createFontRuntime,+ getFontRuntimeKey,+ type CreateFontRuntimeOptions,+ type FontRuntime,+ type FontRuntimeSnapshot,+} from './runtime';diff --git a/invokeai/frontend/webv2/src/features/fonts/launchpad.tsx b/invokeai/frontend/webv2/src/features/fonts/launchpad.tsxnew file mode 100644index 0000000000..0e53765bea--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/launchpad.tsx@@ -0,0 +1,17 @@+import { Center, Spinner } from '@chakra-ui/react';+import { lazy, Suspense } from 'react';++/** Launchpad entry kept separate so the editor's initial chunk does not load the library view. */+const LazyFontsPage = lazy(() => import('./ui/FontsPage').then((module) => ({ default: module.FontsPage })));++const FALLBACK = (+ <Center h="full">+ <Spinner color="fg.muted" size="sm" />+ </Center>+);++export const FontsPage = () => (+ <Suspense fallback={FALLBACK}>+ <LazyFontsPage />+ </Suspense>+);diff --git a/invokeai/frontend/webv2/src/features/fonts/react.tsx b/invokeai/frontend/webv2/src/features/fonts/react.tsxnew file mode 100644index 0000000000..d683204a84--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/react.tsx@@ -0,0 +1,287 @@+import type { ReactNode } from 'react';++import { useMountEffect } from '@platform/react/useMountEffect';+import { createContext, use, useState, useSyncExternalStore } from 'react';++import type { FontDownloadReference, FontReference } from './contracts';+import type { FontRuntime, FontRuntimeSnapshot } from './runtime';++const DISPOSED_MESSAGE = 'The font runtime has been disposed.';++interface PendingRetain {+ reference: FontReference;+ release?: () => void;+ released: boolean;+}++interface DeferredFontRuntime extends FontRuntime {+ attach(runtime: FontRuntime): void;+ fail(error: unknown): void;+}++const createAbortError = (): Error => {+ if (typeof DOMException !== 'undefined') {+ return new DOMException('The font load was aborted.', 'AbortError');+ }+ const error = new Error('The font load was aborted.');+ error.name = 'AbortError';+ return error;+};++/**+ * Keeps the provider/context seam small enough for the authenticated shell.+ * The browser registry and authenticated transport are loaded only after the+ * route mounts, while callers can still retain faces and queue ensures during+ * that short handoff.+ */+const createDeferredFontRuntime = (): DeferredFontRuntime => {+ const listeners = new Set<() => void>();+ const pendingRetains = new Set<PendingRetain>();+ let delegate: FontRuntime | undefined;+ let delegateUnsubscribe: (() => void) | undefined;+ let delegatePromise: Promise<FontRuntime> | undefined;+ let resolveDelegate: ((runtime: FontRuntime) => void) | undefined;+ let rejectDelegate: ((error: unknown) => void) | undefined;+ let snapshot: FontRuntimeSnapshot = Object.freeze({ generation: 0, states: new Map() });+ let startupError: unknown;+ let disposed = false;+ let started = false;++ const notify = (): void => {+ if (disposed) {+ return;+ }+ for (const listener of listeners) {+ listener();+ }+ };++ const createDelegatePromise = (): Promise<FontRuntime> => {+ if (delegatePromise) {+ return delegatePromise;+ }++ delegatePromise = new Promise<FontRuntime>((resolve, reject) => {+ resolveDelegate = resolve;+ rejectDelegate = reject;+ });+ // The provider creates this promise before any consumer necessarily asks+ // for a face. Mark a disposal/import failure as handled while preserving+ // the rejection for callers that are waiting on it.+ void delegatePromise.catch(() => undefined);+ return delegatePromise;+ };++ const waitForDelegate = (signal?: AbortSignal): Promise<FontRuntime> => {+ const pending = createDelegatePromise();+ if (!signal) {+ return pending;+ }+ if (signal.aborted) {+ return Promise.reject(signal.reason ?? createAbortError());+ }++ return new Promise<FontRuntime>((resolve, reject) => {+ const onAbort = (): void => {+ signal.removeEventListener('abort', onAbort);+ reject(signal.reason ?? createAbortError());+ };+ signal.addEventListener('abort', onAbort, { once: true });+ pending.then(+ (runtime) => {+ signal.removeEventListener('abort', onAbort);+ resolve(runtime);+ },+ (error: unknown) => {+ signal.removeEventListener('abort', onAbort);+ reject(error);+ }+ );+ });+ };++ const start = (): void => {+ if (started && !disposed) {+ return;+ }+ disposed = false;+ started = true;+ startupError = undefined;+ createDelegatePromise();+ };++ const runtime: DeferredFontRuntime = {+ attach: (next) => {+ if (disposed || !started) {+ next.dispose();+ return;+ }+ delegateUnsubscribe?.();+ delegate?.dispose();+ delegate = next;+ startupError = undefined;+ next.start();+ snapshot = next.getSnapshot();+ delegateUnsubscribe = next.subscribe(() => {+ snapshot = next.getSnapshot();+ notify();+ });+ for (const pending of pendingRetains) {+ if (!pending.released) {+ pending.release = next.retain(pending.reference);+ }+ }+ resolveDelegate?.(next);+ resolveDelegate = undefined;+ rejectDelegate = undefined;+ notify();+ },+ dispose: () => {+ if (disposed) {+ return;+ }+ disposed = true;+ started = false;+ delegateUnsubscribe?.();+ delegateUnsubscribe = undefined;+ delegate?.dispose();+ delegate = undefined;+ rejectDelegate?.(new Error(DISPOSED_MESSAGE));+ resolveDelegate = undefined;+ rejectDelegate = undefined;+ delegatePromise = undefined;+ startupError = undefined;+ for (const pending of pendingRetains) {+ pending.release?.();+ }+ pendingRetains.clear();+ snapshot = Object.freeze({ generation: snapshot.generation + 1, states: new Map() });+ for (const listener of listeners) {+ listener();+ }+ },+ ensure: (reference: FontDownloadReference, signal?: AbortSignal) => {+ if (disposed) {+ return Promise.reject(new Error(DISPOSED_MESSAGE));+ }+ start();+ if (startupError !== undefined) {+ return Promise.reject(startupError);+ }+ const wait = delegate ? Promise.resolve(delegate) : waitForDelegate(signal);+ return wait.then((next) => {+ if (disposed) {+ throw new Error(DISPOSED_MESSAGE);+ }+ return next.ensure(reference, signal);+ });+ },+ ensureForOutput: (reference: FontDownloadReference, signal?: AbortSignal) => {+ if (disposed) {+ return Promise.reject(new Error(DISPOSED_MESSAGE));+ }+ start();+ if (startupError !== undefined) {+ return Promise.reject(startupError);+ }+ const wait = delegate ? Promise.resolve(delegate) : waitForDelegate(signal);+ return wait.then((next) => {+ if (disposed) {+ throw new Error(DISPOSED_MESSAGE);+ }+ return next.ensureForOutput(reference, signal);+ });+ },+ fail: (error) => {+ if (disposed) {+ return;+ }+ startupError = error;+ rejectDelegate?.(error);+ resolveDelegate = undefined;+ rejectDelegate = undefined;+ delegatePromise = undefined;+ notify();+ },+ getSnapshot: () => snapshot,+ resolveFamily: (reference) => delegate?.resolveFamily(reference) ?? reference.family ?? 'sans-serif',+ retain: (reference) => {+ const pending: PendingRetain = { reference, released: false };+ pendingRetains.add(pending);+ if (delegate) {+ pending.release = delegate.retain(reference);+ }+ return () => {+ if (pending.released) {+ return;+ }+ pending.released = true;+ pending.release?.();+ pendingRetains.delete(pending);+ };+ },+ start,+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };++ return runtime;+};++const FontRuntimeContext = createContext<FontRuntime | null>(null);++export const FontsRuntimeProvider = ({ children, runtime }: { children: ReactNode; runtime?: FontRuntime }) => {+ const [providedRuntime] = useState(() => runtime);+ const [ownedRuntime] = useState<FontRuntime>(() => runtime ?? createDeferredFontRuntime());+ if (providedRuntime !== runtime) {+ throw new Error('FontsRuntimeProvider runtime must remain stable for its mounted lifetime.');+ }++ useMountEffect(() => {+ ownedRuntime.start();+ if (runtime) {+ return;+ }++ const deferredRuntime = ownedRuntime as DeferredFontRuntime;+ let cancelled = false;+ void import('./runtime')+ .then(({ createFontRuntime }) => {+ const implementation = createFontRuntime();+ if (cancelled) {+ implementation.dispose();+ return;+ }+ deferredRuntime.attach(implementation);+ })+ .catch((error: unknown) => {+ if (!cancelled) {+ deferredRuntime.fail(error);+ }+ });++ return () => {+ cancelled = true;+ deferredRuntime.dispose();+ };+ });++ return <FontRuntimeContext value={ownedRuntime}>{children}</FontRuntimeContext>;+};++export const useFontRuntime = (): FontRuntime => {+ const runtime = use(FontRuntimeContext);++ if (!runtime) {+ throw new Error('Font runtime requires an App-composed FontsRuntimeProvider.');+ }++ return runtime;+};++export const useFontRuntimeSnapshot = () => {+ const runtime = useFontRuntime();+ return useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot);+};diff --git a/invokeai/frontend/webv2/src/features/fonts/runtime.test.ts b/invokeai/frontend/webv2/src/features/fonts/runtime.test.tsnew file mode 100644index 0000000000..9c714c020f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/runtime.test.ts@@ -0,0 +1,644 @@+import { AccountScopeExpiredError, createAccountLifecycle } from '@platform/state/accountLifecycle';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { FontRecord } from './contracts';++import { createFontRuntime, getFontRuntimeKey, type FontRuntimeEnvironment } from './runtime';++const createRuntime = (options: Parameters<typeof createFontRuntime>[0]) =>+ createFontRuntime({+ getFont: (id) =>+ Promise.resolve({+ id,+ contentHash: id.padEnd(64, '0').slice(0, 64),+ style: 'normal',+ weight: 400,+ axes: [],+ instances: [],+ byteSize: 1,+ family: 'Example Sans',+ filename: 'example.ttf',+ label: 'Example Sans',+ scope: 'private',+ source: 'uploaded',+ url: '',+ }),+ ...options,+ });++class FakeFontFace {+ readonly family: string;+ readonly source: ArrayBuffer;+ readonly descriptors: { style?: string; weight?: string } | undefined;++ constructor(family: string, source: ArrayBuffer, descriptors?: { style?: string; weight?: string }) {+ this.family = family;+ this.source = source;+ this.descriptors = descriptors;+ }++ load(): Promise<FakeFontFace> {+ return Promise.resolve(this);+ }+}++const createEnvironment = () => {+ const added: FakeFontFace[] = [];+ const deleted: FakeFontFace[] = [];+ const environment: FontRuntimeEnvironment = {+ FontFace: FakeFontFace,+ fonts: {+ add: (font) => added.push(font as FakeFontFace),+ delete: (font) => {+ deleted.push(font as FakeFontFace);+ return true;+ },+ },+ };+ return { added, deleted, environment };+};++const reference = (id: string, axes?: Readonly<Record<string, number>>) => ({+ axes,+ contentHash: id.padEnd(64, '0').slice(0, 64),+ family: 'Example Sans',+ id,+ style: 'normal',+ weight: 400,+});++describe('font runtime', () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ });++ it('deduplicates equivalent requests and publishes readiness by stable identity', async () => {+ const { added, environment } = createEnvironment();+ const download = vi.fn(() => Promise.resolve(new Uint8Array([1, 2, 3])));+ const runtime = createRuntime({ download, environment, lifecycle: createAccountLifecycle() });+ const first = reference('font-a', { wght: 400, wdth: 90 });+ const second = reference('font-a', { wdth: 90, wght: 400 });++ const [firstFamily, secondFamily] = await Promise.all([runtime.ensure(first), runtime.ensure(second)]);++ expect(firstFamily).toBe(secondFamily);+ expect(download).toHaveBeenCalledTimes(1);+ expect(added).toHaveLength(1);+ expect(runtime.getSnapshot().states.get(getFontRuntimeKey(first))).toBe('ready');+ expect(runtime.resolveFamily(second)).toBe(firstFamily);+ runtime.dispose();+ });++ it('keeps long variation identities distinct inside one session', async () => {+ const { environment } = createEnvironment();+ const runtime = createRuntime({+ download: vi.fn(() => Promise.resolve(new Uint8Array([1]))),+ environment,+ lifecycle: createAccountLifecycle(),+ });+ const axes = Object.fromEntries(Array.from({ length: 14 }, (_, index) => [`axis${index}`, index]));+ const first = reference('font-a', axes);+ const second = reference('font-a', { ...axes, axis13: 999 });++ const [firstFamily, secondFamily] = await Promise.all([runtime.ensure(first), runtime.ensure(second)]);++ expect(firstFamily).not.toBe(secondFamily);+ runtime.dispose();+ });++ it('keeps browser family aliases unique across runtime instances', async () => {+ const first = createEnvironment();+ const second = createEnvironment();+ const firstRuntime = createRuntime({+ download: vi.fn(() => Promise.resolve(new Uint8Array([1]))),+ environment: first.environment,+ lifecycle: createAccountLifecycle(),+ });+ const secondRuntime = createRuntime({+ download: vi.fn(() => Promise.resolve(new Uint8Array([1]))),+ environment: second.environment,+ lifecycle: createAccountLifecycle(),+ });++ const firstFamily = await firstRuntime.ensure(reference('font-a'));+ const secondFamily = await secondRuntime.ensure(reference('font-a'));++ expect(firstFamily).not.toBe(secondFamily);+ firstRuntime.dispose();+ secondRuntime.dispose();+ });++ it('limits simultaneous byte downloads', async () => {+ const { environment } = createEnvironment();+ let active = 0;+ let maximumActive = 0;+ const pending = new Map<string, (bytes: Uint8Array) => void>();+ const download = vi.fn(+ (font: { id: string }) =>+ new Promise<Uint8Array>((resolve) => {+ active += 1;+ maximumActive = Math.max(maximumActive, active);+ pending.set(font.id, (bytes) => {+ active -= 1;+ resolve(bytes);+ });+ })+ );+ const runtime = createRuntime({ download, environment, lifecycle: createAccountLifecycle() });+ const requests = Array.from({ length: 6 }, (_, index) => runtime.ensure(reference(`font-${index}`)));++ await vi.waitFor(() => expect(download).toHaveBeenCalledTimes(4));+ expect(maximumActive).toBe(4);+ for (let index = 0; index < 6; index += 1) {+ await vi.waitFor(() => expect(pending.has(`font-${index}`)).toBe(true));+ pending.get(`font-${index}`)!(new Uint8Array([index]));+ }+ await expect(Promise.all(requests)).resolves.toHaveLength(6);+ runtime.dispose();+ });++ it('removes canceled queued axis previews so the next distinct request starts promptly', async () => {+ const { environment } = createEnvironment();+ const resolvers = new Map<number, (bytes: Uint8Array) => void>();+ const download = vi.fn(+ (font: { axes?: Readonly<Record<string, number>> }, _signal?: AbortSignal) =>+ new Promise<Uint8Array>((resolve) => {+ const axis = font.axes?.wght ?? 0;+ resolvers.set(axis, resolve);+ })+ );+ const runtime = createRuntime({ download, environment, lifecycle: createAccountLifecycle() });+ const requests = Array.from({ length: 4 }, (_, index) =>+ runtime.ensure(reference(`axis-${index}`, { wght: index }))+ );+ await vi.waitFor(() => expect(download).toHaveBeenCalledTimes(4));++ const canceledController = new AbortController();+ const canceled = runtime.ensure(reference('axis-canceled', { wght: 4 }), canceledController.signal);+ const next = runtime.ensure(reference('axis-next', { wght: 5 }));+ canceledController.abort();+ await expect(canceled).rejects.toMatchObject({ name: 'AbortError' });+ expect(download).toHaveBeenCalledTimes(4);++ for (let index = 0; index < 4; index += 1) {+ resolvers.get(index)?.(new Uint8Array([index]));+ }+ await vi.waitFor(() => expect(download).toHaveBeenCalledTimes(5));+ expect(download.mock.calls.some(([font]) => font.axes?.wght === 4)).toBe(false);+ resolvers.get(5)?.(new Uint8Array([5]));+ await expect(Promise.all(requests.concat(next))).resolves.toHaveLength(5);+ runtime.dispose();+ });++ it('isolates caller cancellation from another consumer of the same face', async () => {+ const { environment } = createEnvironment();+ let resolveDownload!: (bytes: Uint8Array) => void;+ let downloadSignal!: AbortSignal;+ const download = vi.fn((_font: { axes?: Readonly<Record<string, number>> }, signal?: AbortSignal) => {+ downloadSignal = signal!;+ return new Promise<Uint8Array>((resolve) => {+ resolveDownload = resolve;+ });+ });+ const runtime = createRuntime({ download, environment, lifecycle: createAccountLifecycle() });+ const font = reference('shared-axis', { wght: 500 });+ const firstController = new AbortController();+ const first = runtime.ensure(font, firstController.signal);+ const second = runtime.ensure(font);+ await vi.waitFor(() => expect(download).toHaveBeenCalledOnce());++ firstController.abort(new Error('obsolete preview'));+ await expect(first).rejects.toMatchObject({ name: 'AbortError' });+ expect(downloadSignal.aborted).toBe(false);+ resolveDownload(new Uint8Array([1]));+ await expect(second).resolves.toMatch(/^__invoke_font_/);+ expect(environment.fonts).toBeTruthy();+ runtime.dispose();+ });++ it('aborts a queued and active preview when the runtime is disposed', async () => {+ const { added, environment } = createEnvironment();+ let resolveDownload!: (bytes: Uint8Array) => void;+ let downloadSignal!: AbortSignal;+ const runtime = createRuntime({+ download: vi.fn((_font: { axes?: Readonly<Record<string, number>> }, signal?: AbortSignal) => {+ downloadSignal = signal!;+ return new Promise<Uint8Array>((resolve) => {+ resolveDownload = resolve;+ });+ }),+ environment,+ lifecycle: createAccountLifecycle(),+ });+ const loading = runtime.ensure(reference('dispose-preview'));+ await vi.waitFor(() => expect(downloadSignal).toBeDefined());++ runtime.dispose();+ expect(downloadSignal.aborted).toBe(true);+ resolveDownload(new Uint8Array([1]));+ await expect(loading).rejects.toBeInstanceOf(AccountScopeExpiredError);+ expect(added).toHaveLength(0);+ expect(runtime.getSnapshot().states.size).toBe(0);+ });++ it('describes pinned variable coordinates while preserving static-face synthesis metadata', async () => {+ const { added, environment } = createEnvironment();+ const download = vi.fn(() => Promise.resolve(new Uint8Array([1])));+ const getFont = (id: string): Promise<FontRecord> =>+ Promise.resolve({+ axes: [+ { default: 400, hidden: false, label: 'Weight', maximum: 900, minimum: 100, tag: 'wght' },+ { default: 0, hidden: false, label: 'Italic', maximum: 1, minimum: 0, tag: 'ital' },+ ],+ byteSize: 1,+ contentHash: id.padEnd(64, '0').slice(0, 64),+ family: 'Example Sans',+ filename: 'example.ttf',+ id,+ instances: [],+ label: 'Example Sans',+ scope: 'private',+ source: 'uploaded',+ style: 'normal',+ url: '',+ weight: 400,+ });+ const runtime = createRuntime({+ download,+ environment,+ getFont,+ lifecycle: createAccountLifecycle(),+ });++ await runtime.ensure(reference('variable-descriptor', { ital: 1, wght: 800 }));+ expect(added[0]?.descriptors).toEqual({ style: 'italic', weight: '800' });++ const staticFont = reference('static-descriptor');+ const staticFamily = await runtime.ensure({ ...staticFont, weight: 700 });+ expect(added[1]?.descriptors).toEqual({ style: 'normal', weight: '400' });+ await expect(runtime.ensure({ ...staticFont, style: 'italic', weight: 900 })).resolves.toBe(staticFamily);+ expect(download).toHaveBeenCalledTimes(2);+ expect(added).toHaveLength(2);+ runtime.dispose();+ });++ it('does not evict a face retained by a live Canvas consumer', async () => {+ const { added, deleted, environment } = createEnvironment();+ const runtime = createRuntime({+ download: vi.fn(() => Promise.resolve(new Uint8Array([1]))),+ environment,+ lifecycle: createAccountLifecycle(),+ });+ const pinned = reference('pinned');+ const pinnedFamily = await runtime.ensure(pinned);+ const release = runtime.retain(pinned);++ for (let index = 0; index < 65; index += 1) {+ await runtime.ensure(reference(`cache-${index}`));+ }++ expect(added.some((face) => face.family === pinnedFamily)).toBe(true);+ expect(deleted.some((face) => face.family === pinnedFamily)).toBe(false);+ release();+ await runtime.ensure(reference('cache-after-release'));+ expect(deleted.some((face) => face.family === pinnedFamily)).toBe(true);+ runtime.dispose();+ });++ it('fails closed when browser font registration is unavailable', async () => {+ const runtime = createRuntime({+ download: vi.fn(() => Promise.resolve(new Uint8Array([1]))),+ environment: { FontFace: null, fonts: null },+ lifecycle: createAccountLifecycle(),+ });++ await expect(runtime.ensure(reference('font-a'))).rejects.toThrow('FontFace API');+ expect(runtime.getSnapshot().states.get(getFontRuntimeKey(reference('font-a')))).toBe('error');+ runtime.dispose();+ });++ it('bounds failed face state while preserving retry behavior', async () => {+ const { environment } = createEnvironment();+ const runtime = createRuntime({+ download: vi.fn(() => {+ throw new Error('font bytes unavailable');+ }),+ environment,+ lifecycle: createAccountLifecycle(),+ });++ for (let index = 0; index < 70; index += 1) {+ await expect(runtime.ensure(reference(`failed-${index}`))).rejects.toThrow('unavailable');+ }++ expect(runtime.getSnapshot().states.size).toBeLessThanOrEqual(64);+ await expect(runtime.ensure(reference('failed-0'))).rejects.toThrow('unavailable');+ runtime.dispose();+ });++ it('refuses new faces at the active-font limit and recovers when a consumer releases', async () => {+ const { added, deleted, environment } = createEnvironment();+ const runtime = createRuntime({+ download: () => Promise.resolve(new Uint8Array([1])),+ environment,+ lifecycle: createAccountLifecycle(),+ });+ const releases = [];+ for (let index = 0; index < 64; index += 1) {+ const font = reference(`active-${index}`);+ releases.push(runtime.retain(font));+ await runtime.ensure(font);+ }+ const extra = reference('extra');+ await expect(runtime.ensure(extra)).rejects.toThrow('budget is full');+ expect(added).toHaveLength(64);+ expect(deleted).toHaveLength(0);+ releases[0]!();+ await expect(runtime.ensure(extra)).resolves.toMatch(/^__invoke_font_/);+ expect(deleted).toHaveLength(1);+ releases.forEach((release) => release());+ runtime.dispose();+ });++ it('reserves bytes during concurrent FontFace loading and releases a failed reservation', async () => {+ const bytes = new Uint8Array(64 * 1024 * 1024);+ const loads: Array<{ resolve: () => void; reject: (error: Error) => void }> = [];+ class DeferredFontFace extends FakeFontFace {+ override load(): Promise<FakeFontFace> {+ return new Promise((resolve, reject) => {+ loads.push({ resolve: () => resolve(this), reject });+ });+ }+ }+ const { added, environment } = createEnvironment();+ environment.FontFace = DeferredFontFace;+ const runtime = createRuntime({+ download: () => Promise.resolve(bytes),+ environment,+ lifecycle: createAccountLifecycle(),+ });+ const first = runtime.ensure(reference('large-a'));+ const second = runtime.ensure(reference('large-b'));+ const failed = expect(second).rejects.toThrow('parse failed');+ await vi.waitFor(() => expect(loads).toHaveLength(2));+ await expect(runtime.ensure(reference('large-c'))).rejects.toThrow('budget is full');+ loads[0]!.resolve();+ loads[1]!.reject(new Error('parse failed'));+ await first;+ await failed;+ const retry = runtime.ensure(reference('large-c'));+ await vi.waitFor(() => expect(loads).toHaveLength(3));+ loads[2]!.resolve();+ await retry;+ expect(added).toHaveLength(2);+ expect(added[0]!.source).toBe(bytes.buffer);+ runtime.dispose();+ });++ it('trims failed state after its retained consumer releases', async () => {+ const { environment } = createEnvironment();+ const runtime = createRuntime({+ download: vi.fn(() => {+ throw new Error('font bytes unavailable');+ }),+ environment,+ lifecycle: createAccountLifecycle(),+ });+ const retained = reference('failed-retained');+ const release = runtime.retain(retained);++ for (let index = 0; index < 64; index += 1) {+ await expect(runtime.ensure(reference(`failed-retained-${index}`))).rejects.toThrow('unavailable');+ }+ await expect(runtime.ensure(retained)).rejects.toThrow('unavailable');+ expect(runtime.getSnapshot().states.size).toBe(65);++ release();+ expect(runtime.getSnapshot().states.size).toBeLessThanOrEqual(64);+ runtime.dispose();+ });++ it('honors an aborted caller before returning a loaded face', async () => {+ const { environment } = createEnvironment();+ const runtime = createRuntime({+ download: vi.fn(() => Promise.resolve(new Uint8Array([1]))),+ environment,+ lifecycle: createAccountLifecycle(),+ });+ const font = reference('font-a');+ await runtime.ensure(font);+ const controller = new AbortController();+ const reason = new Error('cancelled');+ controller.abort(reason);++ await expect(runtime.ensure(font, controller.signal)).rejects.toBe(reason);+ runtime.dispose();+ });++ it('clears an aborted in-flight state instead of retaining an error entry', async () => {+ const { environment } = createEnvironment();+ let resolveDownload: (bytes: Uint8Array) => void = () => undefined;+ const download = vi.fn(+ () =>+ new Promise<Uint8Array>((resolve) => {+ resolveDownload = resolve;+ })+ );+ const runtime = createRuntime({ download, environment, lifecycle: createAccountLifecycle() });+ const font = reference('font-aborted');+ const controller = new AbortController();+ const loading = runtime.ensure(font, controller.signal);++ await vi.waitFor(() => expect(download).toHaveBeenCalledTimes(1));+ controller.abort(new Error('caller cancelled'));+ resolveDownload(new Uint8Array([1]));++ await expect(loading).rejects.toThrow('aborted');+ expect(runtime.getSnapshot().states.has(getFontRuntimeKey(font))).toBe(false);+ runtime.dispose();+ });++ it('revalidates a cached face before output and removes it when the catalog entry changes', async () => {+ const { added, deleted, environment } = createEnvironment();+ const font = reference('font-output');+ let currentHash = font.contentHash;+ const getFont = vi.fn(() =>+ Promise.resolve({+ axes: [],+ byteSize: 1,+ contentHash: currentHash,+ family: 'Example Sans',+ filename: 'example.ttf',+ id: font.id,+ instances: [],+ label: 'Example Sans',+ scope: 'private' as const,+ source: 'uploaded' as const,+ style: 'normal',+ url: '/fonts/example/file',+ weight: 400,+ })+ );+ const runtime = createRuntime({+ download: vi.fn(() => Promise.resolve(new Uint8Array([1]))),+ environment,+ getFont,+ lifecycle: createAccountLifecycle(),+ });+ const loadedFamily = await runtime.ensure(font);+ currentHash = 'f'.repeat(64);+ await expect(runtime.ensureForOutput(font)).rejects.toThrow('changed');++ expect(getFont).toHaveBeenCalledTimes(2);+ expect(added).toHaveLength(1);+ expect(deleted).toHaveLength(1);+ expect(runtime.resolveFamily(font)).toBe('Example Sans');+ expect(loadedFamily).not.toBe(runtime.resolveFamily(font));+ runtime.dispose();+ });++ it('deduplicates concurrent output metadata checks by id and hash', async () => {+ const { environment } = createEnvironment();+ const font = reference('font-output-shared');+ let resolveMetadata: (record: FontRecord) => void = () => undefined;+ const getFont = vi.fn(+ () =>+ new Promise<FontRecord>((resolve) => {+ resolveMetadata = resolve;+ })+ );+ const runtime = createRuntime({+ download: vi.fn(() => Promise.resolve(new Uint8Array([1]))),+ environment,+ getFont,+ lifecycle: createAccountLifecycle(),+ });+ const first = runtime.ensureForOutput(font);+ const second = runtime.ensureForOutput({ ...font, axes: { wght: 600 } });++ await vi.waitFor(() => expect(getFont).toHaveBeenCalledTimes(1));+ resolveMetadata({+ axes: [],+ byteSize: 1,+ contentHash: font.contentHash!,+ family: 'Example Sans',+ filename: 'example.ttf',+ id: font.id,+ instances: [],+ label: 'Example Sans',+ scope: 'private',+ source: 'uploaded',+ style: 'normal',+ url: '/fonts/example/file',+ weight: 400,+ });++ await expect(Promise.all([first, second])).resolves.toHaveLength(2);+ runtime.dispose();+ });++ it('cancels and fences output metadata across dispose and restart', async () => {+ const { environment } = createEnvironment();+ const font = reference('font-output-restart');+ const metadataResolvers: Array<(record: FontRecord) => void> = [];+ const metadataSignals: AbortSignal[] = [];+ const getFont = vi.fn(+ (_id: string, signal?: AbortSignal) =>+ new Promise<FontRecord>((resolve) => {+ metadataSignals.push(signal!);+ metadataResolvers.push(resolve);+ })+ );+ const runtime = createRuntime({+ download: vi.fn(() => Promise.resolve(new Uint8Array([1]))),+ environment,+ getFont,+ lifecycle: createAccountLifecycle(),+ });+ const first = runtime.ensureForOutput(font);++ await vi.waitFor(() => expect(getFont).toHaveBeenCalledTimes(1));+ runtime.dispose();+ expect(metadataSignals[0]?.aborted).toBe(true);+ runtime.start();+ metadataResolvers[0]!({+ axes: [],+ byteSize: 1,+ contentHash: font.contentHash!,+ family: 'Example Sans',+ filename: 'example.ttf',+ id: font.id,+ instances: [],+ label: 'Example Sans',+ scope: 'private',+ source: 'uploaded',+ style: 'normal',+ url: '/fonts/example/file',+ weight: 400,+ });+ await expect(first).rejects.toBeInstanceOf(AccountScopeExpiredError);++ const second = runtime.ensureForOutput(font);+ await vi.waitFor(() => expect(getFont).toHaveBeenCalledTimes(2));+ metadataResolvers[1]!({+ axes: [],+ byteSize: 1,+ contentHash: font.contentHash!,+ family: 'Example Sans',+ filename: 'example.ttf',+ id: font.id,+ instances: [],+ label: 'Example Sans',+ scope: 'private',+ source: 'uploaded',+ style: 'normal',+ url: '/fonts/example/file',+ weight: 400,+ });+ await expect(second).resolves.toMatch(/^__invoke_font_/);+ runtime.dispose();+ });++ it('fences an in-flight load when the account changes before bytes arrive', async () => {+ const { added, environment } = createEnvironment();+ let resolveDownload: (bytes: Uint8Array) => void = () => undefined;+ const download = vi.fn(+ () =>+ new Promise<Uint8Array>((resolve) => {+ resolveDownload = resolve;+ })+ );+ const lifecycle = createAccountLifecycle();+ lifecycle.activate('account-a');+ const runtime = createRuntime({ download, environment, lifecycle });+ const loading = runtime.ensure(reference('font-a'));++ await vi.waitFor(() => expect(download).toHaveBeenCalledTimes(1));+ lifecycle.activate('account-b');+ resolveDownload(new Uint8Array([1, 2, 3]));++ await expect(loading).rejects.toBeInstanceOf(AccountScopeExpiredError);+ expect(added).toHaveLength(0);+ expect(runtime.getSnapshot().states.size).toBe(0);+ runtime.dispose();+ });++ it('clears browser faces when disposed and can be restarted by a StrictMode effect', async () => {+ const { added, deleted, environment } = createEnvironment();+ const runtime = createRuntime({+ download: vi.fn(() => Promise.resolve(new Uint8Array([1]))),+ environment,+ lifecycle: createAccountLifecycle(),+ });+ const firstFamily = await runtime.ensure(reference('font-a'));++ runtime.dispose();+ expect(added).toHaveLength(1);+ expect(deleted).toHaveLength(1);+ expect(runtime.getSnapshot().states.size).toBe(0);++ runtime.start();+ await expect(runtime.ensure(reference('font-a'))).resolves.not.toBe(firstFamily);+ runtime.dispose();+ });+});diff --git a/invokeai/frontend/webv2/src/features/fonts/runtime.ts b/invokeai/frontend/webv2/src/features/fonts/runtime.tsnew file mode 100644index 0000000000..42282dad1c--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/runtime.ts@@ -0,0 +1,700 @@+import { AccountScopeExpiredError, accountLifecycle, type AccountLifecycle } from '@platform/state/accountLifecycle';++import type { FontDownloadReference, FontLoadState, FontRecord, FontReference } from './contracts';++const MAX_CONCURRENT_DOWNLOADS = 4;+const MAX_REGISTERED_FONTS = 64;+const MAX_REGISTERED_FONT_BYTES = 128 * 1024 * 1024;+const MAX_FAILED_FONTS = 64;+let nextRuntimeId = 1;++interface FontFaceLike {+ load(): Promise<FontFaceLike>;+}++interface FontFaceSetLike {+ add(font: FontFaceLike): void;+ delete(font: FontFaceLike): boolean;+}++interface FontFaceConstructorLike {+ new (family: string, source: ArrayBuffer, descriptors?: { style?: string; weight?: string }): FontFaceLike;+}++export interface FontRuntimeEnvironment {+ FontFace: FontFaceConstructorLike | null;+ fonts: FontFaceSetLike | null;+}++export interface FontRuntimeSnapshot {+ generation: number;+ states: ReadonlyMap<string, FontLoadState>;+}++export interface FontRuntime {+ /** Starts account cleanup registration. Safe to call more than once. */+ start(): void;+ /** Ensures the requested face/instance is registered and returns its CSS family name. */+ ensure(reference: FontDownloadReference, signal?: AbortSignal): Promise<string>;+ /** Revalidates the persisted face before an operation whose pixels leave the editor. */+ ensureForOutput(reference: FontDownloadReference, signal?: AbortSignal): Promise<string>;+ /** Keeps a loaded face registered while a long-lived Canvas consumer uses it. */+ retain(reference: FontReference): () => void;+ /** Returns the registered family if ready, otherwise the readable fallback family. */+ resolveFamily(reference: FontReference): string;+ getSnapshot(): FontRuntimeSnapshot;+ subscribe(listener: () => void): () => void;+ dispose(): void;+}++export interface CreateFontRuntimeOptions {+ download?: (reference: FontDownloadReference, signal?: AbortSignal) => Promise<Uint8Array>;+ getFont?: (id: string, signal?: AbortSignal) => Promise<FontRecord>;+ environment?: FontRuntimeEnvironment;+ lifecycle?: AccountLifecycle;+}++const downloadDefaultFont = async (reference: FontDownloadReference, signal?: AbortSignal): Promise<Uint8Array> => {+ // Keep the authenticated route shell and editor boot free of catalog/query+ // code. The transport is only needed after a custom face is requested.+ const { downloadFont } = await import('./data/api');+ return downloadFont(reference, signal);+};++const getDefaultFont = async (id: string, signal?: AbortSignal): Promise<FontRecord> => {+ // Metadata validation is an output boundary too, but catalog code should+ // stay out of the authenticated shell until a face is actually used.+ const { getFont } = await import('./data/api');+ return getFont(id, signal);+};++const getBrowserEnvironment = (): FontRuntimeEnvironment => {+ if (typeof document === 'undefined' || typeof globalThis.FontFace === 'undefined' || !document.fonts) {+ return { FontFace: null, fonts: null };+ }++ return {+ FontFace: globalThis.FontFace as unknown as FontFaceConstructorLike,+ fonts: document.fonts as unknown as FontFaceSetLike,+ };+};++const normalizeAxes = (axes: FontReference['axes']): string =>+ Object.entries(axes ?? {})+ .filter(([, value]) => Number.isFinite(value))+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([tag, value]) => `${tag}:${value}`)+ .join(',');++export const getFontRuntimeKey = (reference: FontReference): string =>+ JSON.stringify([reference.id, reference.contentHash ?? null, normalizeAxes(reference.axes)]);++const createAbortError = (): Error => {+ if (typeof DOMException !== 'undefined') {+ return new DOMException('The font load was aborted.', 'AbortError');+ }+ const error = new Error('The font load was aborted.');+ error.name = 'AbortError';+ return error;+};++const withAbortSignal = <T>(promise: Promise<T>, signal?: AbortSignal, abortReason?: unknown): Promise<T> => {+ if (!signal) {+ return promise;+ }+ const getReason = (): unknown => abortReason ?? signal.reason ?? createAbortError();+ if (signal.aborted) {+ return Promise.reject(getReason());+ }++ return new Promise<T>((resolve, reject) => {+ const onAbort = (): void => {+ signal.removeEventListener('abort', onAbort);+ reject(getReason());+ };+ signal.addEventListener('abort', onAbort, { once: true });+ promise.then(+ (value) => {+ signal.removeEventListener('abort', onAbort);+ resolve(value);+ },+ (error: unknown) => {+ signal.removeEventListener('abort', onAbort);+ reject(error);+ }+ );+ });+};++const isAbortError = (error: unknown): boolean =>+ typeof DOMException !== 'undefined' && error instanceof DOMException+ ? error.name === 'AbortError'+ : error instanceof Error && (error.name === 'AbortError' || error.message.includes('aborted'));++const combineSignals = (+ first: AbortSignal | undefined,+ second: AbortSignal+): { signal: AbortSignal; dispose: () => void } => {+ const controller = new AbortController();+ const abort = (): void => controller.abort();++ if (first?.aborted || second.aborted) {+ controller.abort();+ }+ first?.addEventListener('abort', abort, { once: true });+ second.addEventListener('abort', abort, { once: true });++ return {+ dispose: () => {+ first?.removeEventListener('abort', abort);+ second.removeEventListener('abort', abort);+ },+ signal: controller.signal,+ };+};++interface QueueTask<T> {+ run: () => Promise<T>;+ reject: (error: unknown) => void;+ resolve: (value: T) => void;+ signal?: AbortSignal;+ started: boolean;+ settled: boolean;+ cleanup?: () => void;+}++const createLimiter = (limit: number) => {+ let active = 0;+ const queue: QueueTask<unknown>[] = [];++ const pump = (): void => {+ while (active < limit && queue.length > 0) {+ const task = queue.shift()!;+ if (task.settled) {+ continue;+ }+ if (task.signal?.aborted) {+ task.settled = true;+ task.reject(task.signal.reason ?? createAbortError());+ task.cleanup?.();+ continue;+ }+ task.started = true;+ active += 1;+ void Promise.resolve()+ .then(task.run)+ .then(task.resolve, task.reject)+ .finally(() => {+ active -= 1;+ task.settled = true;+ task.cleanup?.();+ pump();+ });+ }+ };++ return <T>(run: () => Promise<T>, signal?: AbortSignal): Promise<T> =>+ new Promise<T>((resolve, reject) => {+ const task: QueueTask<unknown> = {+ reject,+ resolve: (value) => resolve(value as T),+ run: run as () => Promise<unknown>,+ signal,+ settled: false,+ started: false,+ };+ const onAbort = (): void => {+ if (task.started || task.settled) {+ return;+ }+ const index = queue.indexOf(task);+ if (index >= 0) {+ queue.splice(index, 1);+ }+ task.settled = true;+ signal?.removeEventListener('abort', onAbort);+ reject(signal?.reason ?? createAbortError());+ pump();+ };+ task.cleanup = () => signal?.removeEventListener('abort', onAbort);+ signal?.addEventListener('abort', onAbort, { once: true });+ queue.push(task);+ pump();+ });+};++interface InflightRequest {+ readonly key: string;+ readonly family: string;+ readonly requestController: AbortController;+ readonly combined: { signal: AbortSignal; dispose: () => void };+ readonly consumers: Set<symbol>;+ readonly promise: Promise<string>;+}++const fontFaceDescriptors = (face: FontRecord, reference: FontDownloadReference): { style: string; weight: string } => {+ let style = face.style ?? 'normal';+ let weight = face.weight ?? 400;+ const axes = new Set(face.axes.map((axis) => axis.tag));+ const requestedAxes = reference.axes ?? {};++ // The download endpoint returns a pinned static instance when coordinates are+ // present. Its CSS descriptor must describe that instance, otherwise a+ // requested wght=900 face is registered as the metadata's default 400 face+ // and the browser may synthesize another bold pass over the already-bold+ // outline. Static files (and requests without the corresponding axis) keep+ // their catalog descriptor so CSS bold synthesis remains available.+ if (axes.has('wght') && Number.isFinite(requestedAxes.wght)) {+ weight = requestedAxes.wght!;+ }+ const requestedItalic = axes.has('ital') && Number.isFinite(requestedAxes.ital);+ const requestedSlant = axes.has('slnt') && Number.isFinite(requestedAxes.slnt);+ if (requestedItalic && requestedAxes.ital! >= 0.5) {+ style = 'italic';+ } else if (requestedSlant && requestedAxes.slnt !== 0) {+ style = 'oblique';+ } else if (requestedItalic || requestedSlant) {+ style = 'normal';+ }++ return { style, weight: String(weight) };+};++const createSnapshot = (generation: number, states: ReadonlyMap<string, FontLoadState>): FontRuntimeSnapshot =>+ Object.freeze({ generation, states });++/**+ * Creates a session-owned browser font registry. Every request is keyed by the+ * persisted resource identity and normalized variation coordinates, so two+ * consumers cannot race to register the same bytes under different names.+ * Requested CSS style and weight stay outside the key: they describe how a+ * consumer uses a static face, while the face's catalog metadata owns the+ * registration descriptor and the browser performs any requested synthesis.+ */+export const createFontRuntime = (options: CreateFontRuntimeOptions = {}): FontRuntime => {+ const runtimeId = nextRuntimeId++;+ const environment = options.environment ?? getBrowserEnvironment();+ const lifecycle = options.lifecycle ?? accountLifecycle;+ const fetchFont = options.download ?? downloadDefaultFont;+ const fetchFontRecord = options.getFont ?? getDefaultFont;+ const limit = createLimiter(MAX_CONCURRENT_DOWNLOADS);+ const listeners = new Set<() => void>();+ const inflight = new Map<string, InflightRequest>();+ const outputInflight = new Map<string, Promise<FontRecord>>();+ const registered = new Map<+ string,+ { face: FontFaceLike; family: string; retained: number; touched: number; byteSize: number }+ >();+ const reservations = new Map<string, number>();+ const retainCounts = new Map<string, number>();+ const familyNames = new Map<string, string>();+ const abortControllers = new Set<AbortController>();+ const stateTouches = new Map<string, number>();+ let states = new Map<string, FontLoadState>();+ let snapshot = createSnapshot(0, states);+ let generation = 0;+ let touch = 0;+ let nextFamilyId = 1;+ let disposed = false;+ let unregister: (() => void) | undefined;+ let started = false;++ const publish = (key: string, state: FontLoadState): void => {+ if (disposed) {+ return;+ }+ stateTouches.set(key, ++touch);+ if (states.get(key) === state) {+ return;+ }+ states = new Map(states).set(key, state);+ snapshot = createSnapshot(generation, states);+ for (const listener of listeners) {+ listener();+ }+ };++ const removeState = (key: string): void => {+ if (disposed) {+ return;+ }+ stateTouches.delete(key);+ if (!states.has(key)) {+ if (!registered.has(key) && !inflight.has(key)) {+ familyNames.delete(key);+ }+ return;+ }+ states = new Map(states);+ states.delete(key);+ if (!registered.has(key) && !inflight.has(key)) {+ familyNames.delete(key);+ }+ snapshot = createSnapshot(generation, states);+ for (const listener of listeners) {+ listener();+ }+ };++ const trimFailed = (): void => {+ const failed = [...states.entries()]+ .filter(+ ([key, state]) => state === 'error' && !registered.has(key) && !inflight.has(key) && !retainCounts.has(key)+ )+ .sort(([left], [right]) => (stateTouches.get(left) ?? 0) - (stateTouches.get(right) ?? 0));++ while (failed.length > MAX_FAILED_FONTS) {+ const oldest = failed.shift();+ if (oldest) {+ removeState(oldest[0]);+ }+ }+ };++ const reserveFont = (key: string, byteSize: number): void => {+ let usedBytes =+ [...registered.values()].reduce((sum, entry) => sum + entry.byteSize, 0) ++ [...reservations.values()].reduce((sum, size) => sum + size, 0);+ const evictable = [...registered.entries()]+ .filter(([, entry]) => entry.retained === 0)+ .sort(([, left], [, right]) => left.touched - right.touched);+ while (+ registered.size + reservations.size >= MAX_REGISTERED_FONTS ||+ usedBytes + byteSize > MAX_REGISTERED_FONT_BYTES+ ) {+ const oldest = evictable.shift();+ if (!oldest) {+ throw new Error(+ 'The custom font budget is full (64 faces / 128 MiB). Replace unused fonts or close other documents, then retry.'+ );+ }+ environment.fonts?.delete(oldest[1].face);+ registered.delete(oldest[0]);+ usedBytes -= oldest[1].byteSize;+ removeState(oldest[0]);+ }+ reservations.set(key, byteSize);+ trimFailed();+ };++ const clear = (): void => {+ generation += 1;+ for (const controller of abortControllers) {+ controller.abort();+ }+ abortControllers.clear();+ for (const entry of registered.values()) {+ environment.fonts?.delete(entry.face);+ }+ registered.clear();+ reservations.clear();+ retainCounts.clear();+ familyNames.clear();+ inflight.clear();+ outputInflight.clear();+ stateTouches.clear();+ states = new Map();+ snapshot = createSnapshot(generation, states);+ for (const listener of listeners) {+ listener();+ }+ };++ const start = (): void => {+ if (started && !disposed) {+ return;+ }+ disposed = false;+ started = true;+ unregister = lifecycle.register({ clear, name: `fonts-runtime-${runtimeId}` });+ };++ const attachConsumer = (request: InflightRequest, signal?: AbortSignal): Promise<string> => {+ if (signal?.aborted) {+ return Promise.reject(signal.reason ?? createAbortError());+ }+ const token = Symbol('font-consumer');+ request.consumers.add(token);+ let released = false;+ const release = (): void => {+ if (released) {+ return;+ }+ released = true;+ request.consumers.delete(token);+ // The shared request belongs to the loader/runtime, while each caller+ // owns only its consumer. Abort the transport only after every caller+ // has gone away; this keeps one canceled raster job from canceling a+ // still-live text editor or another layer using the same instance.+ if (request.consumers.size === 0 && inflight.get(request.key) === request) {+ request.requestController.abort(createAbortError());+ }+ };+ return withAbortSignal(request.promise, signal, createAbortError()).finally(release);+ };++ const ensure = (reference: FontDownloadReference, signal?: AbortSignal, knownFace?: FontRecord): Promise<string> => {+ if (disposed) {+ return Promise.reject(new Error('The font runtime has been disposed.'));+ }+ start();+ const owner = lifecycle.capture();+ if (signal?.aborted) {+ return Promise.reject(signal.reason ?? createAbortError());+ }+ if (!lifecycle.isCurrent(owner)) {+ return Promise.reject(new AccountScopeExpiredError());+ }+ const key = getFontRuntimeKey(reference);+ const loaded = registered.get(key);+ if (loaded) {+ loaded.touched = ++touch;+ return withAbortSignal(Promise.resolve(loaded.family), signal);+ }+ const pending = inflight.get(key);+ if (pending) {+ return attachConsumer(pending, signal);+ }++ const requestController = new AbortController();+ abortControllers.add(requestController);+ const combined = combineSignals(owner.signal, requestController.signal);+ const requestGeneration = generation;+ const family = familyNames.get(key) ?? `__invoke_font_${runtimeId}_${nextFamilyId++}`;+ familyNames.set(key, family);++ const task = limit(async () => {+ if (disposed || generation !== requestGeneration || !lifecycle.isCurrent(owner) || combined.signal.aborted) {+ throw new AccountScopeExpiredError();+ }+ if (!environment.FontFace || !environment.fonts) {+ throw new Error('The browser FontFace API is unavailable for custom font output.');+ }+ const [bytes, face] = await Promise.all([+ fetchFont(reference, combined.signal),+ knownFace ?? fetchFontRecord(reference.id, combined.signal),+ ]);+ if (disposed || generation !== requestGeneration || !lifecycle.isCurrent(owner) || combined.signal.aborted) {+ throw new AccountScopeExpiredError();+ }+ if (face.id !== reference.id || (reference.contentHash && face.contentHash !== reference.contentHash)) {+ throw new Error('The font face does not match the requested reference.');+ }+ reserveFont(key, bytes.byteLength);+ try {+ const descriptors = fontFaceDescriptors(face, reference);+ const source =+ bytes.buffer instanceof ArrayBuffer && bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength+ ? bytes.buffer+ : (bytes.slice().buffer as ArrayBuffer);+ const fontFace = new environment.FontFace(family, source, {+ style: descriptors.style,+ weight: descriptors.weight,+ });+ const loadedFace = await fontFace.load();+ if (disposed || generation !== requestGeneration || !lifecycle.isCurrent(owner) || combined.signal.aborted) {+ throw new AccountScopeExpiredError();+ }+ environment.fonts.add(loadedFace);+ registered.set(key, {+ face: loadedFace,+ family,+ retained: retainCounts.get(key) ?? 0,+ touched: ++touch,+ byteSize: bytes.byteLength,+ });+ return family;+ } finally {+ if (generation === requestGeneration) {+ reservations.delete(key);+ }+ }+ }, combined.signal);++ let request!: InflightRequest;++ const result = task+ .then((resolvedFamily) => {+ if (lifecycle.isCurrent(owner) && !disposed && generation === requestGeneration) {+ publish(key, 'ready');+ }+ return resolvedFamily;+ })+ .catch((error: unknown) => {+ if (lifecycle.isCurrent(owner) && !disposed && generation === requestGeneration) {+ if (combined.signal.aborted || isAbortError(error) || error instanceof AccountScopeExpiredError) {+ removeState(key);+ } else {+ publish(key, 'error');+ trimFailed();+ }+ }+ throw error;+ })+ .finally(() => {+ combined.dispose();+ abortControllers.delete(requestController);+ if (inflight.get(key) === request) {+ inflight.delete(key);+ }+ if (!registered.has(key) && !states.has(key)) {+ familyNames.delete(key);+ }+ trimFailed();+ });++ request = {+ combined,+ consumers: new Set(),+ family,+ key,+ promise: result,+ requestController,+ };+ inflight.set(key, request);+ publish(key, 'loading');+ return attachConsumer(request, signal);+ };++ const clearLoaded = (reference: FontReference): void => {+ const key = getFontRuntimeKey(reference);+ const loaded = registered.get(key);+ if (loaded) {+ environment.fonts?.delete(loaded.face);+ registered.delete(key);+ }+ removeState(key);+ };++ const ensureForOutput = (reference: FontDownloadReference, signal?: AbortSignal): Promise<string> => {+ if (disposed) {+ return Promise.reject(new Error('The font runtime has been disposed.'));+ }+ start();+ const owner = lifecycle.capture();+ if (signal?.aborted) {+ return Promise.reject(signal.reason ?? createAbortError());+ }+ if (!lifecycle.isCurrent(owner)) {+ return Promise.reject(new AccountScopeExpiredError());+ }++ const metadataKey = JSON.stringify([reference.id, reference.contentHash ?? null]);+ let metadata = outputInflight.get(metadataKey);+ if (!metadata) {+ const metadataGeneration = generation;+ const metadataRequestController = new AbortController();+ abortControllers.add(metadataRequestController);+ const ownerAndRuntime = combineSignals(owner.signal, metadataRequestController.signal);+ const metadataRequest = fetchFontRecord(reference.id, ownerAndRuntime.signal).then((record) => {+ if (+ disposed ||+ generation !== metadataGeneration ||+ ownerAndRuntime.signal.aborted ||+ !lifecycle.isCurrent(owner)+ ) {+ throw new AccountScopeExpiredError();+ }+ if (record.id !== reference.id) {+ throw new Error(`Font metadata did not match requested font "${reference.id}".`);+ }+ if (!record.contentHash) {+ throw new Error(`Font "${reference.id}" has no content hash.`);+ }+ if (reference.contentHash && record.contentHash !== reference.contentHash) {+ throw new Error(`Font "${reference.id}" changed since this document was created.`);+ }+ return record;+ });+ metadata = metadataRequest+ .catch((error: unknown) => {+ if (lifecycle.isCurrent(owner) && !(error instanceof AccountScopeExpiredError)) {+ clearLoaded(reference);+ }+ throw error;+ })+ .finally(() => {+ if (outputInflight.get(metadataKey) === metadata) {+ outputInflight.delete(metadataKey);+ }+ ownerAndRuntime.dispose();+ abortControllers.delete(metadataRequestController);+ });+ outputInflight.set(metadataKey, metadata);+ }++ return withAbortSignal(metadata, signal).then((record) => {+ if (!lifecycle.isCurrent(owner)) {+ throw new AccountScopeExpiredError();+ }+ const ownerAndCaller = combineSignals(signal, owner.signal);+ return ensure(+ {+ ...reference,+ contentHash: record.contentHash,+ },+ ownerAndCaller.signal,+ record+ ).finally(ownerAndCaller.dispose);+ });+ };++ const runtime: FontRuntime = {+ dispose: () => {+ if (disposed) {+ return;+ }+ unregister?.();+ unregister = undefined;+ disposed = true;+ started = false;+ clear();+ listeners.clear();+ },+ ensure,+ ensureForOutput,+ retain: (reference) => {+ const key = getFontRuntimeKey(reference);+ retainCounts.set(key, (retainCounts.get(key) ?? 0) + 1);+ const entry = registered.get(key);+ if (entry) {+ entry.retained += 1;+ }+ let released = false;+ return () => {+ if (released) {+ return;+ }+ released = true;+ const count = retainCounts.get(key) ?? 0;+ if (count <= 1) {+ retainCounts.delete(key);+ } else {+ retainCounts.set(key, count - 1);+ }+ const current = registered.get(key);+ if (current) {+ current.retained = Math.max(0, current.retained - 1);+ }+ trimFailed();+ };+ },+ getSnapshot: () => snapshot,+ resolveFamily: (reference) => {+ const key = getFontRuntimeKey(reference);+ const loaded = registered.get(key);+ if (loaded) {+ loaded.touched = ++touch;+ return loaded.family;+ }+ return reference.family ?? 'sans-serif';+ },+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ start,+ };++ return runtime;+};diff --git a/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.browser.test.tsx b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.browser.test.tsxnew file mode 100644index 0000000000..2576df353a--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.browser.test.tsx@@ -0,0 +1,356 @@+import { ChakraProvider } from '@chakra-ui/react';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page } from 'vitest/browser';++const dependencies = vi.hoisted(() => ({+ canManageSharedFonts: false,+ deleteFont: vi.fn(),+ ensure: vi.fn(),+ fontsQueryOptions: vi.fn(),+ rescanFonts: vi.fn(),+ retain: vi.fn(() => () => undefined),+ uploadFont: vi.fn(),+}));++vi.mock('@features/fonts', () => ({+ deleteFont: dependencies.deleteFont,+ fontKeys: { all: ['fonts'] },+ fontsQueryOptions: dependencies.fontsQueryOptions,+ getFontRuntimeKey: (reference: { id: string }) => reference.id,+ rescanFonts: dependencies.rescanFonts,+ uploadFont: dependencies.uploadFont,+}));+vi.mock('@features/fonts/react', () => ({+ useFontRuntime: () => ({+ ensure: dependencies.ensure,+ retain: dependencies.retain,+ resolveFamily: () => 'Example Sans',+ subscribe: () => vi.fn(),+ getSnapshot: () => ({ generation: 0, states: new Map() }),+ }),+ useFontRuntimeSnapshot: () => ({ generation: 0, states: new Map() }),+}));+vi.mock('@features/identity', () => ({+ useCapabilities: () => ({ canManageSharedFonts: dependencies.canManageSharedFonts }),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++const font = {+ axes: [],+ byteSize: 1024,+ contentHash: 'a'.repeat(64),+ family: 'Example Sans',+ filename: 'ExampleSans.ttf',+ id: 'font-a',+ instances: [],+ label: 'Example Sans Regular',+ scope: 'private',+ source: 'uploaded',+ style: 'normal',+ url: '/api/v1/fonts/font-a/file',+ weight: 400,+};++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement;+let root: Root;+let queryClient: QueryClient;++const renderPage = async (): Promise<void> => {+ host = document.createElement('div');+ host.style.height = '720px';+ host.style.width = '960px';+ document.body.append(host);+ root = createRoot(host);+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const { FontsPage } = await import('./FontsPage');++ await act(() => {+ root.render(+ <ChakraProvider value={system}>+ <QueryClientProvider client={queryClient}>+ <FontsPage />+ </QueryClientProvider>+ </ChakraProvider>+ );+ });+};++describe('FontsPage', () => {+ beforeEach(() => {+ dependencies.canManageSharedFonts = false;+ dependencies.deleteFont.mockReset();+ dependencies.ensure.mockReset().mockResolvedValue('Example Sans');+ dependencies.retain.mockClear();+ dependencies.fontsQueryOptions.mockReset().mockImplementation((params: unknown) => ({+ queryFn: () => Promise.resolve({ items: [font], limit: 100, offset: 0, total: 1 }),+ queryKey: ['fonts', params],+ }));+ dependencies.rescanFonts.mockReset().mockResolvedValue({ indexed: 1, revision: 1 });+ dependencies.uploadFont.mockReset();+ });++ afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ });++ it('shows an available font and keeps shared administration hidden for a regular account', async () => {+ await renderPage();++ await vi.waitFor(() => expect(host.textContent).toContain('Example Sans Regular'));+ expect(host.textContent).toContain('fonts.scope.private');+ expect(host.textContent).not.toContain('fonts.rescan');+ expect(host.textContent).not.toContain('fonts.uploadShared');+ expect(dependencies.fontsQueryOptions).toHaveBeenCalledWith({ limit: 100, scope: 'all', search: '' });+ });++ it('opens font details from the keyboard while showing family samples in the list', async () => {+ await renderPage();+ await vi.waitFor(() => expect(host.textContent).toContain('Example Sans Regular'));+ await vi.waitFor(() => expect(dependencies.ensure).toHaveBeenCalledOnce());+ const row = host.querySelector<HTMLElement>('[role="button"][aria-pressed="false"]');+ expect(row).not.toBeNull();+ expect(row!.textContent).toContain('Aa');+ expect(dependencies.retain).not.toHaveBeenCalled();+ await act(() => {+ row!.focus();+ row!.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' }));+ });+ await vi.waitFor(() => expect(dependencies.ensure).toHaveBeenCalledTimes(2));+ expect(row!.getAttribute('aria-pressed')).toBe('true');+ expect(dependencies.retain).toHaveBeenCalledOnce();+ expect(host.querySelector('h3')?.textContent).toBe('Example Sans Regular');+ expect(host.textContent).toContain('fonts.previewText');+ expect(host.querySelector('button[aria-label="fonts.deleteNamed"]')).not.toBeNull();+ });++ it('exposes shared upload and directory rescan only for an administrator', async () => {+ dependencies.canManageSharedFonts = true;+ await renderPage();++ await vi.waitFor(() => expect(host.textContent).toContain('Example Sans Regular'));+ expect(host.textContent).toContain('fonts.rescan');+ const addTab = host.querySelector<HTMLButtonElement>('[role="tab"][data-value="add"]');+ expect(addTab).not.toBeNull();+ await act(() => addTab!.click());+ const sharedScopeInput = host.querySelector<HTMLInputElement>(+ '[aria-label="fonts.uploadScopeLabel"] input[value="shared"]'+ );+ expect(sharedScopeInput).not.toBeNull();+ await act(() => sharedScopeInput!.click());+ expect(host.textContent).toContain('fonts.uploadShared');++ const rescanButton = [...host.querySelectorAll('button')].find((button) =>+ button.textContent?.includes('fonts.rescan')+ );+ expect(rescanButton).toBeDefined();+ await act(async () => {+ rescanButton!.click();+ await vi.waitFor(() => expect(dependencies.rescanFonts).toHaveBeenCalledOnce());+ });+ });++ it('lets the managed catalog browse past the first page', async () => {+ const secondPageFont = { ...font, id: 'font-b', label: 'Second Page Font' };+ const requestedOffsets: number[] = [];+ dependencies.fontsQueryOptions.mockReset().mockImplementation((params: { offset?: number }) => ({+ queryFn: () => {+ const offset = params.offset ?? 0;+ requestedOffsets.push(offset);+ return Promise.resolve({+ items: [offset === 0 ? font : secondPageFont],+ limit: 100,+ offset,+ total: 101,+ });+ },+ queryKey: ['fonts', params],+ }));++ await renderPage();+ await vi.waitFor(() => expect(host.textContent).toContain('Example Sans Regular'));+ expect(requestedOffsets).toEqual([0]);++ const nextPageButton = host.querySelector<HTMLButtonElement>('button[aria-label="common.nextPage"]');+ expect(nextPageButton).not.toBeNull();+ await act(() => nextPageButton!.click());+ await vi.waitFor(() => expect(host.textContent).toContain('Second Page Font'));+ expect(requestedOffsets).toEqual([0, 100]);+ });++ it('keeps navigation available when a later page becomes empty', async () => {+ const requestedOffsets: number[] = [];+ dependencies.fontsQueryOptions.mockReset().mockImplementation((params: { offset?: number }) => ({+ queryFn: () => {+ const offset = params.offset ?? 0;+ requestedOffsets.push(offset);+ return Promise.resolve({+ items: offset === 0 ? [font] : [],+ limit: 100,+ offset,+ total: offset === 0 ? 101 : 100,+ });+ },+ queryKey: ['fonts', params],+ }));++ await renderPage();+ await vi.waitFor(() => expect(host.textContent).toContain('Example Sans Regular'));+ const nextPageButton = host.querySelector<HTMLButtonElement>('button[aria-label="common.nextPage"]');+ expect(nextPageButton).not.toBeNull();++ await act(() => nextPageButton!.click());+ await vi.waitFor(() => expect(host.textContent).toContain('fonts.emptyTitle'));++ const previousPageButton = host.querySelector<HTMLButtonElement>('button[aria-label="common.previousPage"]');+ expect(previousPageButton).not.toBeNull();+ expect(previousPageButton).toBeEnabled();+ expect(requestedOffsets).toEqual([0, 100]);+ });++ it('resets a scrolled library when switching to cached filter results', async () => {+ const data = {+ items: Array.from({ length: 100 }, (_, index) => ({ ...font, id: `font-${index}`, label: `Font ${index}` })),+ limit: 100,+ offset: 0,+ total: 100,+ };+ dependencies.fontsQueryOptions.mockImplementation((params: unknown) => ({+ queryFn: () => Promise.resolve(data),+ queryKey: ['fonts', params],+ }));+ await renderPage();+ await vi.waitFor(() => expect(host.querySelector('[data-index="0"]')).not.toBeNull());+ queryClient.setQueryData(['fonts', { limit: 100, scope: 'private', search: '' }], data);+ const viewport = host.querySelector<HTMLElement>('[aria-label="fonts.library"]')!;+ await act(() => {+ viewport.scrollTop = 800;+ viewport.dispatchEvent(new Event('scroll'));+ });+ await vi.waitFor(() => expect(viewport.scrollTop).toBe(800));+ await page.getByRole('button', { name: 'fonts.filterMenu', exact: true }).click();+ await page.getByRole('menuitemradio', { name: 'fonts.filters.my', exact: true }).click();+ await vi.waitFor(() => expect(viewport.scrollTop).toBe(0));+ expect(host.querySelector('[data-index="0"]')).not.toBeNull();+ });++ it('keeps the library rows directly below search after the page is hidden and shown', async () => {+ dependencies.fontsQueryOptions.mockImplementation((params: unknown) => ({+ queryFn: () =>+ Promise.resolve({+ items: Array.from({ length: 6 }, (_, index) => ({ ...font, id: `font-${index}`, label: `Font ${index}` })),+ limit: 100,+ offset: 0,+ total: 6,+ }),+ queryKey: ['fonts', params],+ }));+ await renderPage();+ const firstRow = () => host.querySelector<HTMLElement>('[data-index="0"] [role="button"]');+ await vi.waitFor(() => expect(firstRow()).not.toBeNull());+ const search = host.querySelector<HTMLInputElement>('input[aria-label="fonts.searchLabel"]')!;+ for (let index = 0; index < 3; index += 1) {+ await act(async () => {+ host.style.display = 'none';+ await new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+ });+ await act(async () => {+ host.style.display = 'block';+ await new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+ });+ await vi.waitFor(() => {+ expect(firstRow()).not.toBeNull();+ const gap = firstRow()!.getBoundingClientRect().top - search.getBoundingClientRect().bottom;+ expect(gap).toBeGreaterThanOrEqual(0);+ expect(gap).toBeLessThan(24);+ });+ }+ });++ it('serializes uploads across separately selected batches', async () => {+ let activeUploads = 0;+ let peakUploads = 0;+ const releaseUpload: Array<() => void> = [];+ dependencies.uploadFont.mockImplementation(+ () =>+ new Promise((resolve) => {+ activeUploads += 1;+ peakUploads = Math.max(peakUploads, activeUploads);+ releaseUpload.push(() => {+ activeUploads -= 1;+ resolve({ created: true });+ });+ })+ );++ await renderPage();+ await vi.waitFor(() => expect(host.textContent).toContain('Example Sans Regular'));+ const input = host.querySelector<HTMLInputElement>('input[type="file"]');+ expect(input).not.toBeNull();+ const selectFiles = (file: File): void => {+ Object.defineProperty(input!, 'files', { configurable: true, value: [file] });+ input!.dispatchEvent(new Event('change', { bubbles: true }));+ };++ await act(() => {+ selectFiles(new File(['font-a'], 'font-a.ttf', { type: 'font/ttf' }));+ selectFiles(new File(['font-b'], 'font-b.ttf', { type: 'font/ttf' }));+ });+ await vi.waitFor(() => expect(dependencies.uploadFont).toHaveBeenCalledTimes(1));+ expect(peakUploads).toBe(1);++ await act(() => releaseUpload.shift()!());+ await vi.waitFor(() => expect(dependencies.uploadFont).toHaveBeenCalledTimes(2));+ expect(peakUploads).toBe(1);++ await act(() => releaseUpload.shift()!());+ await vi.waitFor(() => expect(activeUploads).toBe(0));+ });++ it('marks queued uploads stale when the account changes before they start', async () => {+ accountLifecycle.activate('font-upload-owner-a');+ let releaseUpload: (() => void) | undefined;+ dependencies.uploadFont.mockImplementation(+ () =>+ new Promise((resolve) => {+ releaseUpload = () => resolve({ created: true });+ })+ );++ try {+ await renderPage();+ await vi.waitFor(() => expect(host.textContent).toContain('Example Sans Regular'));+ const input = host.querySelector<HTMLInputElement>('input[type="file"]');+ expect(input).not.toBeNull();+ const selectFiles = (file: File): void => {+ Object.defineProperty(input!, 'files', { configurable: true, value: [file] });+ input!.dispatchEvent(new Event('change', { bubbles: true }));+ };++ await act(() => {+ selectFiles(new File(['font-a'], 'font-a.ttf', { type: 'font/ttf' }));+ selectFiles(new File(['font-b'], 'font-b.ttf', { type: 'font/ttf' }));+ });+ await vi.waitFor(() => expect(dependencies.uploadFont).toHaveBeenCalledOnce());++ expect(releaseUpload).toBeDefined();+ accountLifecycle.activate('font-upload-owner-b');+ await act(() => releaseUpload!());+ await vi.waitFor(() => expect(host.textContent).toContain('fonts.uploadFailed'));+ expect(dependencies.uploadFont).toHaveBeenCalledOnce();+ } finally {+ accountLifecycle.invalidate();+ }+ });+});diff --git a/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsx b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsxnew file mode 100644index 0000000000..03446696aa--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsx@@ -0,0 +1,815 @@+/* eslint-disable react-perf/jsx-no-new-function-as-prop */+import type { ChangeEvent } from 'react';++import {+ Badge,+ Box,+ Center,+ Flex,+ HStack,+ Icon,+ Input,+ InputGroup,+ Menu,+ Portal,+ Spinner,+ Stack,+ Text,+} from '@chakra-ui/react';+import {+ deleteFont,+ fontKeys,+ fontsQueryOptions,+ getFontRuntimeKey,+ rescanFonts,+ uploadFont,+ type FontDownloadReference,+ type FontRecord,+ type FontScope,+ type FontListParams,+} from '@features/fonts';+import { useFontRuntime, useFontRuntimeSnapshot } from '@features/fonts/react';+import { useCapabilities } from '@features/identity';+import { useMountEffect } from '@platform/react/useMountEffect';+import {+ assertAccountScopeCurrent,+ captureAccountScope,+ isAccountScopeCurrent,+} from '@platform/state/accountLifecycle';+import { getApiErrorMessage } from '@platform/transport/http';+import { Button, ConfirmDialog, IconButton, Row, Scrollable, SegmentedControl, Tabs } from '@platform/ui';+import { EmptyState } from '@platform/ui/EmptyState';+import { MenuContent } from '@platform/ui/Menu';+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { useVirtualizer } from '@tanstack/react-virtual';+import {+ ArrowRightIcon,+ CircleAlertIcon,+ FileTypeIcon,+ PackageOpenIcon,+ PlusIcon,+ RefreshCwIcon,+ SearchIcon,+ SlidersHorizontalIcon,+ Trash2Icon,+ UploadIcon,+} from 'lucide-react';+import { useCallback, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++const FONT_ACCEPT = '.ttf,.otf,.woff,.woff2,font/ttf,font/otf,font/woff,font/woff2';+const FONT_PAGE_SIZE = 100;+const FONT_ROW_HEIGHT = 56;+// Match the Models and Nodes manager columns without coupling feature owners.+const LIBRARY_WIDTH = 'clamp(22rem, 32vw, 28rem)';+const HEADER_MIN_HEIGHT = '2.75rem';+const FILTER_POSITION = { placement: 'bottom-end' } as const;+const PREVIEW_TEXT_SX = { textWrap: 'pretty' } as const;+const ERROR_ICON = <CircleAlertIcon />;+const EMPTY_ICON = <Icon as={PackageOpenIcon} />;+const EMPTY_SEARCH_ICON = <Icon as={SearchIcon} />;+const SEARCH_ICON = <Icon as={SearchIcon} boxSize="3.5" color="fg.subtle" />;+let nextUploadId = 1;++type FontFilter = 'all' | 'private' | 'shared';+type UploadStatus = 'queued' | 'uploading' | 'created' | 'duplicate' | 'error';++interface UploadItem {+ id: string;+ name: string;+ status: UploadStatus;+ message?: string;+}++const getScopeLabelKey = (scope: FontScope): string =>+ scope === 'private' ? 'fonts.scope.private' : 'fonts.scope.shared';++const FontPreview = ({ font, compact = false }: { font: FontRecord; compact?: boolean }) => {+ const { t } = useTranslation('fonts');+ const runtime = useFontRuntime();+ const snapshot = useFontRuntimeSnapshot();+ const reference = useMemo<FontDownloadReference>(+ () => ({+ contentHash: font.contentHash,+ family: font.family,+ id: font.id,+ style: font.style,+ weight: font.weight,+ }),+ [font.contentHash, font.family, font.id, font.style, font.weight]+ );+ const key = getFontRuntimeKey(reference);+ const loadState = snapshot.states.get(key) ?? 'idle';+ const family = runtime.resolveFamily(reference);++ const load = useCallback(() => {+ void runtime.ensure(reference).catch(() => undefined);+ }, [reference, runtime]);++ useMountEffect(() => {+ const controller = new AbortController();+ // Small list samples may be evicted to make room for the selected face or Canvas.+ const release = compact ? undefined : runtime.retain(reference);+ void runtime.ensure(reference, controller.signal).catch(() => undefined);+ return () => {+ controller.abort();+ release?.();+ };+ });++ if (compact) {+ return (+ <Box+ aria-hidden="true"+ alignItems="center"+ display="flex"+ flexShrink={0}+ h="8"+ justifyContent="center"+ overflow="hidden"+ w="9"+ >+ <Text fontFamily={family} fontSize="xl" fontStyle={font.style} fontWeight={font.weight} lineHeight="1">+ Aa+ </Text>+ </Box>+ );+ }++ return (+ <Box bg="bg.inset" borderColor="border.subtle" borderWidth="1px" minH="16" p="3" rounded="md">+ <Text+ css={PREVIEW_TEXT_SX}+ fontFamily={family}+ fontSize="3xl"+ fontStyle={font.style === 'italic' || font.style === 'oblique' ? font.style : 'normal'}+ fontWeight={font.weight}+ lineHeight="1.25"+ overflowWrap="anywhere"+ >+ {t('fonts.previewText')}+ </Text>+ {loadState === 'loading' ? (+ <HStack color="fg.muted" gap="1.5" mt="2">+ <Spinner size="xs" />+ <Text fontSize="2xs">{t('fonts.loadingPreview')}</Text>+ </HStack>+ ) : loadState === 'error' ? (+ <Button size="2xs" variant="ghost" onClick={load}>+ {t('fonts.retryPreview')}+ </Button>+ ) : null}+ </Box>+ );+};++const FontDetail = ({+ canDelete,+ font,+ onDelete,+}: {+ canDelete: boolean;+ font: FontRecord;+ onDelete: (font: FontRecord) => void;+}) => {+ const { t } = useTranslation('fonts');+ const scopeLabel = t(getScopeLabelKey(font.scope));+ const sourceLabel = font.source === 'directory' ? t('fonts.source.directory') : t('fonts.source.uploaded');+ const variantLabel = `${font.style} · ${font.weight}`;++ return (+ <Stack gap="4" p="3">+ <Flex align="flex-start" gap="2" justify="space-between" minW="0">+ <Stack gap="0.5" minW="0">+ <Text as="h3" fontSize="lg" fontWeight="600" overflowWrap="anywhere">+ {font.label || font.family}+ </Text>+ <Text color="fg.muted" fontSize="2xs" overflowWrap="anywhere">+ {font.filename} · {variantLabel}+ </Text>+ </Stack>+ {canDelete ? (+ <Button+ aria-label={t('fonts.deleteNamed', { name: font.label || font.family })}+ color="fg.muted"+ size="2xs"+ variant="ghost"+ onClick={() => onDelete(font)}+ >+ <Trash2Icon />+ </Button>+ ) : null}+ </Flex>+ <HStack gap="1.5" wrap="wrap">+ <Badge colorPalette={font.scope === 'shared' ? 'purple' : 'gray'} fontSize="2xs" variant="surface">+ {scopeLabel}+ </Badge>+ <Badge fontSize="2xs" variant="surface">+ {sourceLabel}+ </Badge>+ {font.axes.length > 0 ? (+ <Badge fontSize="2xs" variant="surface">+ {t('fonts.axisCount', { count: font.axes.length })}+ </Badge>+ ) : null}+ </HStack>+ <FontPreview key={`${font.id}:${font.contentHash}:${font.family}:${font.style}:${font.weight}`} font={font} />+ <HStack align="center" color="fg.muted" gap="2" minW="0" wrap="wrap">+ <Text fontSize="2xs" overflowWrap="anywhere">+ {font.instances.length > 0+ ? t('fonts.namedInstances', { count: font.instances.length })+ : t('fonts.fileSize', { bytes: formatBytes(font.byteSize) })}+ </Text>+ {font.axes.length > 0 ? (+ <Text fontSize="2xs" overflowWrap="anywhere">+ {font.axes.map((axis) => axis.tag).join(', ')}+ </Text>+ ) : null}+ </HStack>+ {font.axes.length > 0 ? (+ <Stack gap="2">+ <Text fontSize="xs" fontWeight="600">+ {t('fonts.axesTitle')}+ </Text>+ {font.axes.map((axis) => (+ <HStack key={axis.tag} borderBottomWidth="1px" gap="3" justify="space-between" py="2" wrap="wrap">+ <Text fontSize="xs">+ {axis.label}{' '}+ <Text as="span" color="fg.muted">+ {axis.tag}+ </Text>+ </Text>+ <Text color="fg.muted" fontSize="xs" fontVariantNumeric="tabular-nums">+ {axis.minimum} – {axis.maximum} · {t('fonts.axisDefault', { value: axis.default })}+ </Text>+ </HStack>+ ))}+ </Stack>+ ) : null}+ {font.instances.length > 0 ? (+ <Stack gap="2">+ <Text fontSize="xs" fontWeight="600">+ {t('fonts.instancesTitle')}+ </Text>+ <HStack gap="1.5" wrap="wrap">+ {font.instances.map((instance, index) => (+ <Badge key={index} variant="surface">+ {instance.name}+ </Badge>+ ))}+ </HStack>+ </Stack>+ ) : null}+ </Stack>+ );+};++const formatBytes = (bytes: number): string => {+ if (!Number.isFinite(bytes) || bytes < 1) {+ return '0 B';+ }+ if (bytes < 1024) {+ return `${Math.round(bytes)} B`;+ }+ if (bytes < 1024 * 1024) {+ return `${(bytes / 1024).toFixed(1)} KB`;+ }+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+};++const UploadStatusList = ({ items }: { items: readonly UploadItem[] }) => {+ const { t } = useTranslation('fonts');++ if (items.length === 0) {+ return null;+ }++ return (+ <Stack aria-live="polite" gap="1.5">+ {items.map((item) => (+ <HStack key={item.id} color={item.status === 'error' ? 'fg.error' : 'fg.muted'} gap="2">+ {item.status === 'uploading' ? (+ <Spinner size="xs" />+ ) : (+ <Icon as={item.status === 'error' ? CircleAlertIcon : FileTypeIcon} />+ )}+ <Text fontSize="2xs" overflowWrap="anywhere">+ {item.name}+ </Text>+ <Text fontSize="2xs">+ {item.status === 'queued' || item.status === 'uploading'+ ? t('fonts.uploading')+ : item.status === 'created'+ ? t('fonts.uploaded')+ : item.status === 'duplicate'+ ? t('fonts.duplicate')+ : (item.message ?? t('fonts.uploadFailed'))}+ </Text>+ </HStack>+ ))}+ </Stack>+ );+};++const FontLibrary = () => {+ const { t } = useTranslation('fonts');+ const { canManageSharedFonts } = useCapabilities();+ const queryClient = useQueryClient();+ const [filter, setFilter] = useState<FontFilter>('all');+ const [activeTab, setActiveTab] = useState('details');+ const [selectedFont, setSelectedFont] = useState<FontRecord | null>(null);+ const [search, setSearch] = useState('');+ const [uploadScope, setUploadScope] = useState<FontScope>('private');+ const [uploads, setUploads] = useState<UploadItem[]>([]);+ const [deleteTarget, setDeleteTarget] = useState<FontRecord | null>(null);+ const [isRescanning, setIsRescanning] = useState(false);+ const inputRef = useRef<HTMLInputElement | null>(null);+ const scrollRef = useRef<HTMLDivElement | null>(null);+ const uploadChainRef = useRef<Promise<void>>(Promise.resolve());+ const [offset, setOffset] = useState(0);+ const params = useMemo<FontListParams>(+ () => ({+ limit: FONT_PAGE_SIZE,+ scope: filter === 'all' ? 'all' : filter,+ search,+ ...(offset > 0 ? { offset } : {}),+ }),+ [filter, offset, search]+ );+ const query = useQuery(fontsQueryOptions(params));+ const fonts = query.data?.items ?? [];+ const virtualizer = useVirtualizer({+ count: fonts.length,+ estimateSize: () => FONT_ROW_HEIGHT,+ getItemKey: (index) => fonts[index]?.id ?? index,+ getScrollElement: () => scrollRef.current,+ overscan: 4,+ });++ const invalidateFonts = useCallback(() => queryClient.invalidateQueries({ queryKey: fontKeys.all }), [queryClient]);+ const handleFiles = useCallback(+ (files: FileList | File[]) => {+ const selected = [...files];+ if (selected.length === 0) {+ return Promise.resolve();+ }+ const scope = canManageSharedFonts ? uploadScope : 'private';+ const owner = captureAccountScope();+ const next = selected.map<UploadItem>((file) => ({+ id: `upload-${nextUploadId++}`,+ name: file.name,+ status: 'queued',+ }));+ setUploads((current) => [...next, ...current].slice(0, 12));++ const runBatch = async (): Promise<void> => {+ for (const [index, file] of selected.entries()) {+ const item = next[index]!;+ try {+ assertAccountScopeCurrent(owner);+ setUploads((current) =>+ current.map((entry) => (entry.id === item.id ? { ...entry, status: 'uploading' } : entry))+ );+ const result = await uploadFont(file, scope, owner.signal);+ assertAccountScopeCurrent(owner);+ setUploads((current) =>+ current.map((item) =>+ item.id === next[index]!.id ? { ...item, status: result.created ? 'created' : 'duplicate' } : item+ )+ );+ } catch (error) {+ const ownerIsCurrent = isAccountScopeCurrent(owner);+ setUploads((current) =>+ current.map((item) =>+ item.id === next[index]!.id+ ? {+ ...item,+ message: ownerIsCurrent+ ? getApiErrorMessage(error, t('fonts.uploadFailed'))+ : t('fonts.uploadFailed'),+ status: 'error',+ }+ : item+ )+ );+ if (!ownerIsCurrent) {+ const pendingIds = new Set(next.slice(index + 1).map(({ id }) => id));+ setUploads((current) =>+ current.map((item) =>+ pendingIds.has(item.id)+ ? { ...item, message: t('fonts.uploadFailed'), status: 'error' as const }+ : item+ )+ );+ break;+ }+ }+ }+ if (isAccountScopeCurrent(owner)) {+ await invalidateFonts();+ }+ };++ const queuedBatch = uploadChainRef.current.then(runBatch, runBatch);+ const settledBatch = queuedBatch.catch(() => undefined);+ uploadChainRef.current = settledBatch;+ return settledBatch;+ },+ [canManageSharedFonts, invalidateFonts, t, uploadScope]+ );+ const handleInputChange = useCallback(+ (event: ChangeEvent<HTMLInputElement>) => {+ if (event.currentTarget.files) {+ void handleFiles(event.currentTarget.files);+ }+ event.currentTarget.value = '';+ },+ [handleFiles]+ );+ const handleDelete = useCallback(async () => {+ if (!deleteTarget) {+ return;+ }+ try {+ await deleteFont(deleteTarget.id);+ setSelectedFont((current) => (current?.id === deleteTarget.id ? null : current));+ setDeleteTarget(null);+ await invalidateFonts();+ } catch (error) {+ setUploads((current) =>+ [+ {+ id: `delete:${deleteTarget.id}`,+ message: getApiErrorMessage(error, t('fonts.deleteFailed')),+ name: deleteTarget.label,+ status: 'error' as const,+ },+ ...current,+ ].slice(0, 12)+ );+ }+ }, [deleteTarget, invalidateFonts, t]);+ const handleRescan = useCallback(async () => {+ setIsRescanning(true);+ try {+ await rescanFonts();+ await queryClient.invalidateQueries({ queryKey: fontKeys.all });+ } catch (error) {+ setUploads((current) =>+ [+ {+ id: `rescan-${Date.now()}`,+ message: getApiErrorMessage(error, t('fonts.rescanFailed')),+ name: t('fonts.rescan'),+ status: 'error' as const,+ },+ ...current,+ ].slice(0, 12)+ );+ } finally {+ setIsRescanning(false);+ }+ }, [queryClient, t]);+ const uploadScopeOptions = useMemo(+ () => [+ { label: t('fonts.scope.private'), value: 'private' },+ ...(canManageSharedFonts ? [{ label: t('fonts.scope.shared'), value: 'shared' }] : []),+ ],+ [canManageSharedFonts, t]+ );+ const filterOptions = useMemo(+ () => [+ { label: t('fonts.filters.all'), value: 'all' },+ { label: t('fonts.filters.my'), value: 'private' },+ { label: t('fonts.filters.shared'), value: 'shared' },+ ],+ [t]+ );+ const handleRetry = useCallback(() => void query.refetch(), [query]);+ const hasPreviousPage = offset > 0;+ const hasNextPage = query.data !== undefined && offset + fonts.length < query.data.total;+ const handlePreviousPage = useCallback(() => {+ virtualizer.scrollToOffset(0);+ setOffset((current) => Math.max(0, current - FONT_PAGE_SIZE));+ }, [virtualizer]);+ const handleNextPage = useCallback(() => {+ if (hasNextPage) {+ virtualizer.scrollToOffset(0);+ setOffset((current) => current + FONT_PAGE_SIZE);+ }+ }, [hasNextPage, virtualizer]);+ const showPagination = offset > 0 || (query.data?.total ?? 0) > FONT_PAGE_SIZE;+ const canDelete = useCallback(+ (font: FontRecord) => font.source === 'uploaded' && (font.scope === 'private' || canManageSharedFonts),+ [canManageSharedFonts]+ );+ const deleteBody = useMemo(+ () => t('fonts.deleteBody', { name: deleteTarget?.label ?? '' }),+ [deleteTarget?.label, t]+ );+ const effectiveUploadScope = canManageSharedFonts ? uploadScope : 'private';++ const activeFont = fonts.find((font) => font.id === selectedFont?.id) ?? selectedFont;++ return (+ <Flex aria-label={t('fonts.title')} role="region" h="full" minH="0" w="full">+ <input ref={inputRef} accept={FONT_ACCEPT} hidden multiple type="file" onChange={handleInputChange} />+ <Flex borderEndWidth="1px" direction="column" flexShrink={0} h="full" minH="0" w={LIBRARY_WIDTH}>+ <HStack borderBottomWidth="1px" flexShrink={0} gap="2" minH={HEADER_MIN_HEIGHT} px="3">+ <Text as="h2" fontSize="sm" fontWeight="700">+ {t('fonts.title')}+ </Text>+ <Text color="fg.muted" fontSize="xs" fontVariantNumeric="tabular-nums">+ {query.data?.total ?? '–'}+ </Text>+ {canManageSharedFonts ? (+ <Button+ aria-label={t('fonts.rescan')}+ disabled={isRescanning}+ ms="auto"+ size="2xs"+ variant="ghost"+ onClick={handleRescan}+ >+ <RefreshCwIcon />+ {t('fonts.rescan')}+ </Button>+ ) : null}+ </HStack>+ <HStack gap="1.5" p="3">+ <InputGroup startElement={SEARCH_ICON}>+ <Input+ aria-label={t('fonts.searchLabel')}+ placeholder={t('fonts.searchPlaceholder')}+ size="xs"+ value={search}+ onChange={(event) => {+ virtualizer.scrollToOffset(0);+ setSearch(event.currentTarget.value);+ setOffset(0);+ }}+ />+ </InputGroup>+ <Menu.Root closeOnSelect={false} positioning={FILTER_POSITION}>+ <Menu.Trigger asChild>+ <IconButton+ aria-label={t('fonts.filterMenu')}+ color={filter !== 'all' ? 'accent.solid' : 'fg.muted'}+ size="xs"+ variant="outline"+ >+ <Icon as={SlidersHorizontalIcon} boxSize="4" />+ </IconButton>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="13rem">+ <Menu.RadioItemGroup+ value={filter}+ onValueChange={(event) => {+ virtualizer.scrollToOffset(0);+ setFilter(event.value as FontFilter);+ setOffset(0);+ }}+ >+ <Menu.ItemGroupLabel color="fg" fontSize="2xs" textTransform="uppercase">+ {t('fonts.filterLabel')}+ </Menu.ItemGroupLabel>+ {filterOptions.map((option) => (+ <Menu.RadioItem key={option.value} value={option.value}>+ <Menu.ItemIndicator />+ <Menu.ItemText fontSize="xs">{option.label}</Menu.ItemText>+ </Menu.RadioItem>+ ))}+ </Menu.RadioItemGroup>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </HStack>+ {query.isPending ? (+ <Center flex="1" minH="32">+ <Spinner color="fg.muted" size="sm" />+ </Center>+ ) : query.isError ? (+ <EmptyState+ danger+ description={getApiErrorMessage(query.error, t('fonts.couldNotLoad'))}+ icon={ERROR_ICON}+ title={t('fonts.couldNotLoad')}+ >+ <Button size="xs" variant="outline" onClick={handleRetry}>+ {t('common.retry')}+ </Button>+ </EmptyState>+ ) : fonts.length === 0 ? (+ <EmptyState+ description={search.trim() ? t('fonts.noSearchMatchesDescription') : t('fonts.emptyDescription')}+ icon={search.trim() ? EMPTY_SEARCH_ICON : EMPTY_ICON}+ title={search.trim() ? t('fonts.noSearchMatches') : t('fonts.emptyTitle')}+ >+ {search.trim() ? (+ <Button+ size="xs"+ variant="outline"+ onClick={() => {+ virtualizer.scrollToOffset(0);+ setSearch('');+ setOffset(0);+ }}+ >+ {t('common.clearSearch')}+ </Button>+ ) : (+ <Button size="sm" onClick={() => setActiveTab('add')}>+ {t('fonts.addFonts')}+ <Icon as={ArrowRightIcon} />+ </Button>+ )}+ </EmptyState>+ ) : (+ <Scrollable flex="1" h="full" label={t('fonts.library')} minH="0" viewportRef={scrollRef}>+ <Box h={`${virtualizer.getTotalSize()}px`} position="relative" w="full">+ {virtualizer.getVirtualItems().map((item) => {+ const font = fonts[item.index];+ if (!font) {+ return null;+ }+ return (+ <Box+ data-index={item.index}+ key={item.key}+ left="0"+ position="absolute"+ h={`${FONT_ROW_HEIGHT}px`}+ top="0"+ transform={`translateY(${item.start}px)`}+ w="full"+ >+ <Box h="full" px="3" py="0.5">+ <Row+ active={selectedFont?.id === font.id ? 'accent' : 'none'}+ aria-pressed={selectedFont?.id === font.id}+ gap="2"+ h="full"+ minW="0"+ overflow="hidden"+ px="2"+ py="2"+ role="button"+ rounded="md"+ tabIndex={0}+ onClick={() => {+ setSelectedFont(font);+ setActiveTab('details');+ }}+ onKeyDown={(event) => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault();+ setSelectedFont(font);+ setActiveTab('details');+ }+ }}+ >+ <FontPreview+ compact+ key={`${font.id}:${font.contentHash}:${font.style}:${font.weight}`}+ font={font}+ />+ <Stack gap="0.5" minW="0" flex="1">+ <Text fontSize="xs" fontWeight="600" truncate>+ {font.label || font.family}+ </Text>+ <Text fontSize="2xs" opacity="0.75" truncate>+ {font.filename}+ </Text>+ </Stack>+ <Badge flexShrink={0} fontSize="2xs" variant="surface">+ {t(getScopeLabelKey(font.scope))}+ </Badge>+ </Row>+ </Box>+ </Box>+ );+ })}+ </Box>+ </Scrollable>+ )}+ {showPagination ? (+ <HStack justify="center" minH="8">+ <Button+ aria-label={t('common.previousPage')}+ disabled={!hasPreviousPage || query.isFetching}+ size="2xs"+ variant="ghost"+ onClick={handlePreviousPage}+ >+ {t('common.previousPage')}+ </Button>+ <Text aria-live="polite" color="fg.muted" fontSize="2xs">+ {t('common.pageNumber', { page: Math.floor(offset / FONT_PAGE_SIZE) + 1 })}+ </Text>+ <Button+ aria-label={t('common.nextPage')}+ disabled={!hasNextPage || query.isFetching}+ size="2xs"+ variant="ghost"+ onClick={handleNextPage}+ >+ {t('common.nextPage')}+ </Button>+ </HStack>+ ) : null}+ </Flex>+ <Tabs.Root+ asChild+ lazyMount+ size="sm"+ unmountOnExit+ value={activeTab}+ onValueChange={(event) => setActiveTab(event.value)}+ >+ <Flex direction="column" flex="1" minH="0" minW="0">+ <Flex align="flex-end" borderBottomWidth="1px" flexShrink={0} minH={HEADER_MIN_HEIGHT} px="2">+ <Tabs.List mb="-1px">+ <Tabs.Trigger value="details">+ <Icon as={FileTypeIcon} boxSize="3" />+ <Text maxW="14rem" truncate>+ {activeFont?.label || t('fonts.details')}+ </Text>+ </Tabs.Trigger>+ <Tabs.Trigger value="add">+ <Icon as={PlusIcon} boxSize="3" />+ {t('fonts.addFonts')}+ </Tabs.Trigger>+ </Tabs.List>+ </Flex>+ <Box flex="1" minH="0">+ <Tabs.Content h="full" p="0" value="details">+ {activeFont ? (+ <Scrollable h="full" label={t('fonts.details')} minH="0">+ <FontDetail canDelete={canDelete(activeFont)} font={activeFont} onDelete={setDeleteTarget} />+ </Scrollable>+ ) : (+ <Flex align="center" direction="column" gap="2" h="full" justify="center" p="6">+ <Icon as={FileTypeIcon} boxSize="8" color="fg.subtle" />+ <Text color="fg.muted" fontSize="sm" fontWeight="600">+ {t('fonts.selectFont')}+ </Text>+ <Text color="fg.muted" fontSize="xs" maxW="22rem" textAlign="center">+ {t('fonts.selectFontDescription')}+ </Text>+ </Flex>+ )}+ </Tabs.Content>+ <Tabs.Content h="full" p="0" value="add">+ <Scrollable h="full" label={t('fonts.addFonts')} minH="0" p="3">+ <Stack align="start" gap="4" maxW="xl">+ <Stack gap="1">+ <Text as="h3" fontSize="sm" fontWeight="600">+ {t('fonts.upload')}+ </Text>+ <Text color="fg.muted" fontSize="xs">+ {t('fonts.description')}+ </Text>+ <Text color="fg.muted" fontSize="xs">+ {t('fonts.uploadDescription')}+ </Text>+ </Stack>+ {canManageSharedFonts ? (+ <SegmentedControl+ ariaLabel={t('fonts.uploadScopeLabel')}+ isFullWidth={false}+ options={uploadScopeOptions}+ value={effectiveUploadScope}+ onChange={(value) => setUploadScope(value as FontScope)}+ />+ ) : null}+ <Button size="xs" onClick={() => inputRef.current?.click()}>+ <UploadIcon />+ {effectiveUploadScope === 'shared' ? t('fonts.uploadShared') : t('fonts.upload')}+ </Button>+ </Stack>+ </Scrollable>+ </Tabs.Content>+ </Box>+ {uploads.length > 0 ? (+ <Box borderTopWidth="1px" maxH="32" overflowY="auto" p="3">+ <UploadStatusList items={uploads} />+ </Box>+ ) : null}+ </Flex>+ </Tabs.Root>+ <ConfirmDialog+ body={deleteBody}+ confirmLabel={t('fonts.deleteConfirm')}+ isOpen={deleteTarget !== null}+ title={t('fonts.deleteTitle')}+ onClose={() => setDeleteTarget(null)}+ onConfirm={handleDelete}+ />+ </Flex>+ );+};++export const FontsPage = () => <FontLibrary />;diff --git a/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.visual.browser.test.tsx b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.visual.browser.test.tsxnew file mode 100644index 0000000000..583b47bc58--- /dev/null+++ b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.visual.browser.test.tsx@@ -0,0 +1,155 @@+import { ChakraProvider } from '@chakra-ui/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import axe from 'axe-core';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++const dependencies = vi.hoisted(() => ({+ deleteFont: vi.fn(),+ ensure: vi.fn(),+ fontsQueryOptions: vi.fn(),+ rescanFonts: vi.fn(),+ uploadFont: vi.fn(),+}));++vi.mock('@features/fonts', () => ({+ deleteFont: dependencies.deleteFont,+ fontKeys: { all: ['fonts'] },+ fontsQueryOptions: dependencies.fontsQueryOptions,+ getFontRuntimeKey: (reference: { id: string }) => reference.id,+ rescanFonts: dependencies.rescanFonts,+ uploadFont: dependencies.uploadFont,+}));+vi.mock('@features/fonts/react', () => ({+ useFontRuntime: () => ({+ ensure: dependencies.ensure,+ retain: () => () => undefined,+ resolveFamily: () => 'Example Sans',+ subscribe: () => vi.fn(),+ getSnapshot: () => ({ generation: 0, states: new Map() }),+ }),+ useFontRuntimeSnapshot: () => ({ generation: 0, states: new Map() }),+}));+vi.mock('@features/identity', () => ({ useCapabilities: () => ({ canManageSharedFonts: false }) }));++const i18n = createInstance();+await i18n.use(initReactI18next).init({+ fallbackLng: 'en',+ interpolation: { escapeValue: false },+ lng: 'en',+ fallbackNS: 'translation',+ resources: {+ en: {+ translation: await fetch('/locales/en.json').then((response) => response.json()),+ fonts: await fetch('/locales/en.fonts.json').then((response) => response.json()),+ },+ },+});++const font = {+ axes: [{ default: 400, hidden: false, label: 'Weight', maximum: 700, minimum: 100, tag: 'wght' }],+ byteSize: 1024 * 32,+ contentHash: 'a'.repeat(64),+ family: 'Example Sans',+ filename: 'ExampleSans-Variable.ttf',+ id: 'font-a',+ instances: [{ coordinates: { wght: 400 }, name: 'Regular' }],+ label: 'Example Sans Variable',+ scope: 'private',+ source: 'uploaded',+ style: 'normal',+ url: '/api/v1/fonts/font-a/file',+ weight: 400,+};++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement | undefined;+let root: Root | undefined;+let queryClient: QueryClient | undefined;++const renderPage = async (): Promise<void> => {+ await page.viewport(1280, 900);+ host = document.createElement('div');+ host.style.height = '720px';+ host.style.width = '960px';+ document.body.append(host);+ root = createRoot(host);+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const { FontsPage } = await import('./FontsPage');++ await act(() => {+ root!.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <QueryClientProvider client={queryClient!}>+ <FontsPage />+ </QueryClientProvider>+ </I18nextProvider>+ </ChakraProvider>+ );+ });+};++afterEach(async () => {+ await act(() => root?.unmount());+ queryClient?.clear();+ host?.remove();+ root = undefined;+ queryClient = undefined;+ host = undefined;+});++it('renders the font library with the real English locale', async () => {+ dependencies.ensure.mockReset().mockResolvedValue('Example Sans');+ dependencies.fontsQueryOptions.mockReset().mockImplementation((params: unknown) => ({+ queryFn: () => Promise.resolve({ items: [font], limit: 100, offset: 0, total: 1 }),+ queryKey: ['fonts', params],+ }));++ await renderPage();++ await expect.element(page.getByRole('heading', { name: 'Fonts' })).toBeVisible();+ await expect.element(page.getByText('Example Sans Variable')).toBeVisible();+ await page.getByRole('button', { name: /Example Sans Variable/ }).click();+ await expect.element(page.getByRole('heading', { name: 'Example Sans Variable' })).toBeVisible();+ await expect.element(page.getByText('Variation axes', { exact: true })).toBeVisible();+ await page.screenshot({ path: '../../../../artifacts/fonts/fonts-page-real-en.png' });+ await page.getByRole('button', { name: 'Filter fonts' }).click();+ await expect+ .element(page.getByRole('menuitemradio', { name: 'All', exact: true }))+ .toHaveAttribute('aria-checked', 'true');+ expect((await axe.run(host!)).violations).toEqual([]);+ expect((await axe.run(document.querySelector('[role="menu"]')!)).violations).toEqual([]);+ await page.screenshot({ path: '../../../../artifacts/fonts/fonts-filter-real-en.png' });+ await page.getByRole('menuitemradio', { name: 'My fonts', exact: true }).click();+ await vi.waitFor(() =>+ expect(dependencies.fontsQueryOptions).toHaveBeenCalledWith({ limit: 100, scope: 'private', search: '' })+ );+ await expect+ .element(page.getByRole('menuitemradio', { name: 'My fonts', exact: true }))+ .toHaveAttribute('aria-checked', 'true');+ await userEvent.keyboard('{Escape}');+ await expect.element(page.getByRole('button', { name: 'Filter fonts' })).toHaveFocus();+ await page.getByRole('tab', { name: 'Add Fonts' }).click();+ await expect.element(page.getByRole('button', { name: 'Upload fonts' })).toBeVisible();+ await page.screenshot({ path: '../../../../artifacts/fonts/fonts-add-real-en.png' });+});++it('uses the manager empty state and opens Add Fonts from its action', async () => {+ dependencies.fontsQueryOptions.mockReset().mockImplementation((params: unknown) => ({+ queryFn: () => Promise.resolve({ items: [], limit: 100, offset: 0, total: 0 }),+ queryKey: ['fonts', params],+ }));+ await renderPage();+ await expect.element(page.getByText('No fonts available', { exact: true })).toBeVisible();+ expect((await axe.run(host!)).violations).toEqual([]);+ await page.screenshot({ path: '../../../../artifacts/fonts/fonts-empty-real-en.png' });+ await page.getByRole('button', { name: 'Add Fonts', exact: true }).click();+ await expect.element(page.getByRole('button', { name: 'Upload fonts', exact: true })).toBeVisible();+});diff --git a/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts b/invokeai/frontend/webv2/src/features/identity/capabilities.test.tsindex 8c5a3c07b7..048569e9c5 100644--- a/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts+++ b/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts@@ -22,6 +22,7 @@ describe('Identity route capabilities', () => {canManageImageMapVocabulary: false,canManageModels: false,canManageNodes: false,+ canManageSharedFonts: false,canManagePromptTemplates: false,canManageUsers: false,});@@ -33,6 +34,7 @@ describe('Identity route capabilities', () => {canManageImageMapVocabulary: true,canManageModels: true,canManageNodes: true,+ canManageSharedFonts: true,canManagePromptTemplates: true,canManageUsers: false,});@@ -54,6 +56,7 @@ describe('Identity route capabilities', () => {canManageImageMapVocabulary: false,canManageModels: false,canManageNodes: false,+ canManageSharedFonts: false,canManagePromptTemplates: false,canManageUsers: false,});@@ -62,6 +65,7 @@ describe('Identity route capabilities', () => {canManageImageMapVocabulary: true,canManageModels: true,canManageNodes: true,+ canManageSharedFonts: true,canManagePromptTemplates: true,canManageUsers: true,});diff --git a/invokeai/frontend/webv2/src/features/identity/capabilities.ts b/invokeai/frontend/webv2/src/features/identity/capabilities.tsindex dd48493e72..8cab47012a 100644--- a/invokeai/frontend/webv2/src/features/identity/capabilities.ts+++ b/invokeai/frontend/webv2/src/features/identity/capabilities.ts@@ -7,6 +7,8 @@ export interface Capabilities {canManageImageMapVocabulary: boolean;canManageModels: boolean;canManageNodes: boolean;+ /** Upload, delete, and rescan shared fonts; all authenticated users can read fonts. */+ canManageSharedFonts: boolean;/** Bulk import/export of prompt templates; the routes are admin-only. */canManagePromptTemplates: boolean;canManageUsers: boolean;@@ -19,6 +21,7 @@ export const getCapabilities = (session: AuthSession): Capabilities => {canManageImageMapVocabulary: false,canManageModels: false,canManageNodes: false,+ canManageSharedFonts: false,canManagePromptTemplates: false,canManageUsers: false,};@@ -32,6 +35,7 @@ export const getCapabilities = (session: AuthSession): Capabilities => {canManageImageMapVocabulary: isAdmin,canManageModels: isAdmin,canManageNodes: isAdmin,+ canManageSharedFonts: isAdmin,// Matches the routers' `AdminUserOrDefault`: everyone qualifies in// single-user mode, only admins once multiuser is on.canManagePromptTemplates: isAdmin,diff --git a/invokeai/frontend/webv2/src/platform/i18n/client.ts b/invokeai/frontend/webv2/src/platform/i18n/client.tsindex b920586aa1..d06557d2e9 100644--- a/invokeai/frontend/webv2/src/platform/i18n/client.ts+++ b/invokeai/frontend/webv2/src/platform/i18n/client.ts@@ -8,10 +8,14 @@ void i18n.use(initReactI18next).init({backend: {- loadPath: `${getDeploymentBaseUrl()}/locales/{{lng}}.json`,+ loadPath: (_languages: readonly string[], namespaces: readonly string[]) =>+ `${getDeploymentBaseUrl()}/locales/{{lng}}${namespaces[0] === 'fonts' ? '.fonts' : ''}.json`,},debug: false,fallbackLng: 'en',+ fallbackNS: 'translation',+ ns: ['translation'],+ defaultNS: 'translation',interpolation: {escapeValue: false,},diff --git a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.tsindex 5ad868815e..64410eed5f 100644--- a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts+++ b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts@@ -121,6 +121,7 @@ const CANVAS_EDIT_CONFIDENCE = {mergeCanvasLayersDown: 'high',removeCanvasLayers: 'high',reorderCanvasSiblings: 'high',+ replaceCanvasFontReferences: 'high',replaceCanvasDocument: 'none',replaceCanvasLayer: 'high',resizeCanvasDocument: 'high',diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex b18ae007d3..a890240673 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -2,8 +2,10 @@ import type {CanvasDocumentContractV3,CanvasImageRef,CanvasLayerContract,+ CanvasLayerSourceContract,CanvasStagingCandidateContract,CanvasStateContractV3,+ CanvasTextFontRef,} from '@workbench/canvas-engine/contracts';import type { CanvasMutationOrigin } from '@workbench/canvas-engine/mutationContracts';import type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';@@ -34,6 +36,11 @@ import type {TransformSession,} from './engineStores';import type { RasterCompositeExportRequest, RasterCompositeExportResult } from './exportRasterComposite';+import type {+ CanvasFontReferenceGroup,+ CanvasFontReplacementSummary,+ CanvasFontReplacementTarget,+} from './fontReferences';import type { CanvasProjectMutation } from './mutationContracts';import type { Rect, ToolId, Vec2 } from './types';import type { Viewport } from './viewport';@@ -135,6 +142,23 @@ export interface CanvasInteractionStateCapability {subscribeLayerThumbnailVersion(layerId: string, listener: () => void): () => void;}+/**+ * Font resolution shared by Canvas rasterization and the editing portal.+ * Implementations may return a browser-only family alias, but that alias must+ * never be written into a persisted text source.+ */+export interface CanvasFontCapability {+ resolveFamily(source: Extract<CanvasLayerSourceContract, { type: 'text' }>): string;+ /** Starts/joins a live editor preview and isolates caller cancellation. */+ ensurePreview(source: Extract<CanvasLayerSourceContract, { type: 'text' }>, signal?: AbortSignal): Promise<string>;+ waitForReady(source: Extract<CanvasLayerSourceContract, { type: 'text' }>, signal?: AbortSignal): Promise<string>;+ subscribe(listener: () => void): () => void;+ /** Groups exact persisted custom references for missing-font recovery UI. */+ collectReferences(document: CanvasDocumentContractV3): readonly CanvasFontReferenceGroup[];+ /** Replaces every matching text source in one undoable structural edit. */+ replaceAllReferences(from: CanvasTextFontRef, target: CanvasFontReplacementTarget): CanvasFontReplacementResult;+}+export interface CanvasCoreStoreCapability {readonly interaction: CanvasInteractionStateCapability;}@@ -321,6 +345,10 @@ export type StructuralCommitResult =| { status: SubsetOf<CanvasTransactionOutcome, 'stale'>; expectedRevision: number; actualRevision: number }| { status: 'postcondition-failed'; recovered: 'reverted' | 'reverted-unmirrored' | 'unreverted' };+export type CanvasFontReplacementResult =+ | (CanvasFontReplacementSummary & { status: 'committed' | 'unchanged' })+ | Exclude<StructuralCommitResult, { status: 'committed' }>;+export interface StructuralCommitOptions {/** The edit revision the edit was prepared against; a mismatch refuses as `stale`. */expectedRevision?: number;@@ -570,6 +598,7 @@ export interface CanvasEngine {readonly exports: CanvasEngineExportCapability;readonly diagnostics: CanvasDiagnosticsCapability;readonly interaction: CanvasInteractionStateCapability;+ readonly fonts: CanvasFontCapability;}// Public Canvas-owned value contracts. These remain serializable and containdiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.tsindex faf87d4d53..9f1e43be9c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts@@ -92,6 +92,27 @@ export type CanvasBlendMode =| 'color'| 'luminosity';+/**+ * Stable identity for an indexed custom font face.+ *+ * The family and label are deliberately copied into the document alongside+ * the opaque id and hash. They keep an unresolved document understandable and+ * let the missing-font recovery UI offer a useful replacement without ever+ * persisting the browser-only family alias used by the font runtime.+ */+export interface CanvasTextFontRef {+ id: string;+ contentHash: string;+ family: string;+ label: string;+}++/** CSS font style accepted by both CanvasRenderingContext2D and FontFace. */+export type CanvasTextFontStyle = 'normal' | 'italic' | 'oblique';++/** Explicit OpenType variation coordinates, keyed by four-character axis tag. */+export type CanvasTextFontVariations = Readonly<Record<string, number>>;+/** A reference to a persisted image asset by name, not by resolved URL. */export interface CanvasImageRef {imageName: string;@@ -124,6 +145,12 @@ export type CanvasLayerSourceContract =fontFamily: string;fontSize: number;fontWeight: number;+ /** Optional stable custom-font identity; omitted for built-in/legacy text. */+ fontRef?: CanvasTextFontRef;+ /** Defaults to `normal` for documents written before v4. */+ fontStyle?: CanvasTextFontStyle;+ /** Defaults to an empty coordinate set for documents written before v4. */+ fontVariations?: CanvasTextFontVariations;lineHeight: number;align: 'left' | 'center' | 'right';color: string;@@ -407,7 +434,8 @@ export const CANVAS_MAX_NODE_DEPTH = 10;export const CANVAS_MAX_NODE_COUNT = 10_000;export interface CanvasDocumentContractV3 {- version: 3;+ /** v3 is read for compatibility; v4 is the current writable schema. */+ version: 3 | 4;width: number;height: number;background: 'transparent' | { color: string };@@ -417,6 +445,9 @@ export interface CanvasDocumentContractV3 {selectedLayerId: string | null;}+/** Current writable document contract. v3 remains accepted at the load boundary. */+export type CanvasDocumentContractV4 = Omit<CanvasDocumentContractV3, 'version'> & { version: 4 };+export interface CanvasSnapshotContract {id: string;name: string;@@ -429,7 +460,8 @@ export interface CanvasStagingAreaContractV2 extends CanvasStagingAreaContract {}export interface CanvasStateContractV3 {- version: 3;+ /** v3 is read for compatibility; v4 is the current writable schema. */+ version: 3 | 4;document: CanvasDocumentContractV3;/*** Monotonic counter bumped whenever the document is swapped wholesale@@ -443,3 +475,6 @@ export interface CanvasStateContractV3 {snapshots: CanvasSnapshotContract[];stagingArea: CanvasStagingAreaContractV2;}++/** Current writable state contract. v3 remains accepted at the load boundary. */+export type CanvasStateContractV4 = Omit<CanvasStateContractV3, 'version'> & { version: 4 };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.tsindex acdb32fd8e..d4f8d394ce 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.ts@@ -164,4 +164,155 @@ describe('RasterExportController budget', () => {}expect(release).toHaveBeenCalledOnce();});++ it('waits for custom font readiness before returning cached text pixels', async () => {+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);+ const entry = layers.getOrCreate('text-layer', 80, 32);+ entry.hasPublishedPixels = true;+ entry.renderedFontFamily = '__invoke_font_1';+ entry.stale = false;+ const source = {+ align: 'left' as const,+ color: '#fff',+ content: 'custom',+ fontFamily: 'Catalog Family',+ fontRef: { contentHash: 'hash-1', family: 'Catalog Family', id: 'font-1', label: 'Catalog Regular' },+ fontSize: 24,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text' as const,+ };+ const layer = {+ blendMode: 'normal' as const,+ id: 'text-layer',+ isEnabled: true,+ isLocked: false,+ name: 'Text',+ opacity: 1,+ source,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster' as const,+ };+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: { height: 32, width: 80, x: 0, y: 0 },+ height: 32,+ stacks: stacksFrom([layer]),+ selectedLayerId: null,+ version: 3,+ width: 80,+ };+ let resolveFont!: (family: string) => void;+ const waitForFont = vi.fn(+ () =>+ new Promise<string>((resolve) => {+ resolveFont = resolve;+ })+ );+ const getOrStartRasterization = vi.fn(() => Promise.resolve<'published'>('published'));+ const controller = new RasterExportController({+ backend,+ captureGuard: () => ({ cacheVersion: 1, documentGeneration: 1, layer, layerId: 'text-layer', projectId: 'p' }),+ getDocument: () => document,+ getOrStartRasterization,+ isGuardCurrent: () => true,+ isRasterizing: () => false,+ isSupportedSource: () => true,+ layers,+ waitForFont,+ });++ const pending = controller.rasterize('text-layer');+ expect(waitForFont).toHaveBeenCalledWith(source, undefined);+ expect(getOrStartRasterization).not.toHaveBeenCalled();+ resolveFont('__invoke_font_1');+ await expect(pending).resolves.toMatchObject({ status: 'ok' });+ });++ it('re-rasterizes fallback text once when a missing font recovers before export', async () => {+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);+ const entry = layers.getOrCreate('text-layer', 80, 32);+ entry.hasPublishedPixels = true;+ entry.renderedFontFamily = 'Catalog Family';+ entry.stale = false;+ const source = {+ align: 'left' as const,+ color: '#fff',+ content: 'custom',+ fontFamily: 'Catalog Family',+ fontRef: { contentHash: 'hash-1', family: 'Catalog Family', id: 'font-1', label: 'Catalog Regular' },+ fontSize: 24,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text' as const,+ };+ const layer = {+ blendMode: 'normal' as const,+ id: 'text-layer',+ isEnabled: true,+ isLocked: false,+ name: 'Text',+ opacity: 1,+ source,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster' as const,+ };+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: { height: 32, width: 80, x: 0, y: 0 },+ height: 32,+ stacks: stacksFrom([layer]),+ selectedLayerId: null,+ version: 3,+ width: 80,+ };+ const waitForFont = vi+ .fn()+ .mockRejectedValueOnce(new Error('font unavailable'))+ .mockResolvedValue('__invoke_font_1');+ const invalidateLayerCache = vi.fn((layerId: string) => layers.invalidate(layerId));+ const rasterizedCustomPixels = vi.fn(() => {+ entry.renderedFontFamily = '__invoke_font_1';+ entry.stale = false;+ entry.hasPublishedPixels = true;+ entry.surface.ctx.fillText('custom pixels', 0, 0);+ });+ const getOrStartRasterization = vi.fn(() => {+ rasterizedCustomPixels();+ return Promise.resolve('published' as const);+ });+ const controller = new RasterExportController({+ backend,+ captureGuard: () => ({+ cacheVersion: entry.version,+ documentGeneration: 1,+ layer,+ layerId: 'text-layer',+ projectId: 'p',+ }),+ getDocument: () => document,+ getOrStartRasterization,+ invalidateLayerCache,+ isGuardCurrent: () => true,+ isRasterizing: () => false,+ isSupportedSource: () => true,+ layers,+ waitForFont,+ });++ await expect(controller.rasterize('text-layer')).resolves.toEqual({ status: 'not-ready' });+ expect(getOrStartRasterization).not.toHaveBeenCalled();++ await expect(controller.rasterize('text-layer')).resolves.toMatchObject({ status: 'ok' });+ expect(invalidateLayerCache).toHaveBeenCalledOnce();+ expect(getOrStartRasterization).toHaveBeenCalledOnce();+ expect(rasterizedCustomPixels).toHaveBeenCalledOnce();+ expect(entry.renderedFontFamily).toBe('__invoke_font_1');++ await expect(controller.rasterize('text-layer')).resolves.toMatchObject({ status: 'ok' });+ expect(invalidateLayerCache).toHaveBeenCalledOnce();+ expect(getOrStartRasterization).toHaveBeenCalledOnce();+ });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.tsindex 3b18efdeeb..ba20490423 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts@@ -9,6 +9,7 @@ import type {CanvasLayerContract,CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';+import type { CanvasTextSource } from '@workbench/canvas-engine/render/fontLoader';import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';@@ -48,6 +49,10 @@ export interface RasterExportControllerOptions {| { status: 'ok'; lease: { release(): void } }| { status: 'over-budget'; requestedBytes: number; availableBytes: number };readonly pin?: (layerId: string) => { release(): void };+ /** Resolves custom font bytes before an operation whose pixels leave the editor. */+ readonly waitForFont?: (source: CanvasTextSource, signal?: AbortSignal) => Promise<string>;+ /** Invalidates cached pixels rendered with a fallback family after output readiness recovers. */+ readonly invalidateLayerCache?: (layerId: string) => void;}interface ReservedExportLayerPixels {@@ -123,6 +128,24 @@ export class RasterExportController {if (!this.options.isSupportedSource(source)) {return { status: 'unsupported' };}+ if (source.type === 'text' && this.options.waitForFont) {+ let readyFontFamily: string;+ try {+ readyFontFamily = await this.options.waitForFont(source, options.signal);+ } catch {+ return { status: options.signal?.aborted ? 'aborted' : 'not-ready' };+ }+ const cachedText = this.options.layers.peek(layerId);+ if (+ source.fontRef &&+ cachedText &&+ !cachedText.stale &&+ !isEmpty(cachedText.rect) &&+ cachedText.renderedFontFamily !== readyFontFamily+ ) {+ (this.options.invalidateLayerCache ?? this.options.layers.invalidate)(layerId);+ }+ }const liveEntry = this.options.layers.get(layerId);if (liveEntry && !liveEntry.stale && !this.options.isRasterizing(layer) && !isEmpty(liveEntry.rect)) {return this.applyAdjustments(diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.tsindex 3b01845553..aef868e519 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts@@ -1,6 +1,6 @@import type { StructuralCommitResult } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';-import type { TextEditSession } from '@workbench/canvas-engine/engineStores';+import type { TextEditSession, TextToolOptions } from '@workbench/canvas-engine/engineStores';import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { EMPTY_STACKS } from '@workbench/canvas-engine/document/documentTree';@@ -10,7 +10,7 @@ import { describe, expect, it, vi } from 'vitest';import { TextEditingController } from './textEditingController';-const createHarness = (document: CanvasDocumentContractV3) => {+const createHarness = (document: CanvasDocumentContractV3, textOptions: TextToolOptions = DEFAULT_TEXT_OPTIONS) => {let session: TextEditSession | null = null;const commitStructural = vi.fn<(label: string, forward: unknown, inverse: unknown) => StructuralCommitResult>(() => ({status: 'committed',@@ -25,7 +25,7 @@ const createHarness = (document: CanvasDocumentContractV3) => {getDocument: () => document,invalidate,isGestureActive: () => false,- options: { get: () => DEFAULT_TEXT_OPTIONS },+ options: { get: () => textOptions },session: {get: () => session,set: (value) => (session = value),@@ -69,6 +69,38 @@ describe('TextEditingController', () => {expect(h.commitStructural).not.toHaveBeenCalled();expect(h.invalidate).toHaveBeenCalledWith({ overlay: true });});++ it('carries custom font identity, style, and exact variation coordinates into the structural source', () => {+ const options: TextToolOptions = {+ ...DEFAULT_TEXT_OPTIONS,+ fontFamily: 'Catalog Family',+ fontRef: { contentHash: 'hash-1', family: 'Catalog Family', id: 'font-1', label: 'Catalog Regular' },+ fontStyle: 'italic',+ fontVariations: { opsz: 14, wght: 650 },+ fontWeight: 650,+ };+ const h = createHarness(+ {+ bbox: { height: 1, width: 1, x: 0, y: 0 },+ height: 1,+ stacks: stacksFrom([]),+ width: 1,+ } as never,+ options+ );++ h.controller.openCreate({ x: 0, y: 0 });+ h.controller.commit('hello');++ const forward = h.commitStructural.mock.calls[0]?.[1] as {+ layer?: { source?: { fontRef?: unknown; fontStyle?: string; fontVariations?: unknown } };+ };+ expect(forward.layer?.source).toMatchObject({+ fontRef: options.fontRef,+ fontStyle: 'italic',+ fontVariations: { opsz: 14, wght: 650 },+ });+ });});describe('TextEditingController refusals', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.tsindex 32ecf803e4..873ca8e988 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts@@ -37,15 +37,53 @@ export interface TextEditingControllerOptions {readonly invalidate: (payload: { layers?: string[]; overlay?: true }) => void;}+const fontRefEqual = (left: TextSource['fontRef'], right: TextSource['fontRef']): boolean =>+ left === right ||+ (left !== undefined &&+ right !== undefined &&+ left.id === right.id &&+ left.contentHash === right.contentHash &&+ left.family === right.family &&+ left.label === right.label);++const fontVariationsEqual = (left: TextSource['fontVariations'], right: TextSource['fontVariations']): boolean => {+ const leftEntries = Object.entries(left ?? {});+ const rightEntries = Object.entries(right ?? {});+ return (+ leftEntries.length === rightEntries.length &&+ leftEntries.every(([tag, value]) => (right?.[tag] ?? undefined) === value)+ );+};+const sourcesEqual = (left: TextSource, right: TextSource): boolean =>left.content === right.content &&left.fontFamily === right.fontFamily &&left.fontSize === right.fontSize &&left.fontWeight === right.fontWeight &&+ fontRefEqual(left.fontRef, right.fontRef) &&+ (left.fontStyle ?? 'normal') === (right.fontStyle ?? 'normal') &&+ fontVariationsEqual(left.fontVariations, right.fontVariations) &&left.lineHeight === right.lineHeight &&left.align === right.align &&left.color === right.color;+/** Keeps default typography out of new documents while accepting older explicit defaults. */+const canonicalizeSource = (source: TextSource): TextSource => {+ const next: TextSource = { ...source };+ if (next.fontRef) {+ next.fontRef = { ...next.fontRef };+ }+ if (next.fontStyle === 'normal') {+ delete next.fontStyle;+ }+ if (!next.fontVariations || Object.keys(next.fontVariations).length === 0) {+ delete next.fontVariations;+ } else {+ next.fontVariations = { ...next.fontVariations };+ }+ return next;+};+/** Owns create/edit text session state and its structural commits. */export class TextEditingController {private sessionId = 0;@@ -56,7 +94,7 @@ export class TextEditingController {private sourceFromOptions(content: string): TextSource {const options = this.deps.options.get();- return {+ const source: TextSource = {align: options.align,color: this.deps.colors.get().foreground,content,@@ -66,6 +104,16 @@ export class TextEditingController {lineHeight: options.lineHeight,type: 'text',};+ if (options.fontRef) {+ source.fontRef = { ...options.fontRef };+ }+ if (options.fontStyle && options.fontStyle !== 'normal') {+ source.fontStyle = options.fontStyle;+ }+ if (options.fontVariations && Object.keys(options.fontVariations).length > 0) {+ source.fontVariations = { ...options.fontVariations };+ }+ return canonicalizeSource(source);}setContentReader(reader: (() => string) | null): void {@@ -101,8 +149,8 @@ export class TextEditingController {id: ++this.sessionId,layerId,mode: 'edit',- source: { ...layer.source },- startSource: { ...layer.source },+ source: canonicalizeSource(layer.source),+ startSource: canonicalizeSource(layer.source),transform: { ...layer.transform },});this.deps.invalidate({ layers: [layerId] });@@ -113,7 +161,11 @@ export class TextEditingController {if (this.disposed || !session) {return;}- this.deps.session.set({ ...session, source: { ...session.source, ...patch } });+ const source = canonicalizeSource({ ...session.source, ...patch });+ if ('fontRef' in patch) {+ source.fontRef = patch.fontRef ? { ...patch.fontRef } : undefined;+ }+ this.deps.session.set({ ...session, source });}cancel(): void {@@ -139,7 +191,7 @@ export class TextEditingController {if (!session) {return null;}- const finalSource: TextSource = { ...session.source, ...styleChanges, content };+ const finalSource = canonicalizeSource({ ...session.source, ...styleChanges, content });if (session.mode === 'create') {if (content.trim() === '') {this.cancel();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex cd82eb848d..ca7ea271e2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -3,6 +3,8 @@ import type {CanvasDiagnosticsCapability,CanvasEngine,CanvasEngineExportCapability,+ CanvasFontCapability,+ CanvasFontReplacementResult,CanvasEngineLayerCapability,CanvasEnginePreviewCapability,CanvasEngineToolCapability,@@ -72,7 +74,7 @@ import type {CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';import type { CreatePath2D } from '@workbench/canvas-engine/freehand';-import type { FontLoadApi } from '@workbench/canvas-engine/render/fontLoader';+import type { CanvasFontRuntime, CanvasTextSource, FontLoadApi } from '@workbench/canvas-engine/render/fontLoader';import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { OverlayCursor } from '@workbench/canvas-engine/render/overlayRenderer';import type { RenderScheduler } from '@workbench/canvas-engine/render/scheduler';@@ -171,6 +173,7 @@ import { createBitmapStore, type BitmapStore } from './document/bitmapStore';import { createDocumentMirror, type DocumentMirror } from './document/documentMirror';import { decideLayerChange } from './document/layerChangeDecision';import { getSourceBounds, getSourceContentRect, isRenderableLayer, renderableSourceOf } from './document/sources';+import { collectCanvasFontReferences, replaceCanvasFontReferences } from './fontReferences';import { createLayerExportGuards, isSupportedExportSource } from './layerExportGuards';import { createLayerRasterizer } from './layerRasterizer';import { createPreviewPublisher } from './previewPublisher';@@ -277,7 +280,7 @@ export interface CanvasEngineOptions {* pending font loads. Defaults to the browser's `document.fonts` (or a no-op* in node). Tests inject a fake to drive the load without a real FontFaceSet.*/- fonts?: FontLoadApi | null;+ fonts?: FontLoadApi | CanvasFontRuntime | null;/** Enables deterministic raster/render counters. Disabled by default. */enableDiagnostics?: boolean;}@@ -419,7 +422,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// resolves (a no-op in node / when `document.fonts` is absent). `undefined`// opts.fonts falls back to the DOM api; an explicit `null` forces the no-op.const fontLoader = createFontLoader(opts.fonts === undefined ? domFontLoadApi() : opts.fonts);-+ let syncActiveFontSources: () => void = () => undefined;const tools = new Map<ToolId, Tool>([['view', createViewTool()],['brush', createBrushTool()],@@ -1203,6 +1206,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCbitmapPool: rasterController.bitmaps,documentSize: { height: doc.height, width: doc.width },resolver: imageResolver,+ resolveFontFamily: fontLoader.resolveFamily,signal,store: layerCache,});@@ -1260,6 +1264,35 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCinverse: CanvasProjectMutation,options?: StructuralCommitOptions): StructuralCommitResult => structuralController.commit(label, forward, inverse, options);+ const replaceAllFontReferences = (+ from: Parameters<CanvasFontCapability['replaceAllReferences']>[0],+ target: Parameters<CanvasFontCapability['replaceAllReferences']>[1]+ ): CanvasFontReplacementResult => {+ const before = mirror.getDocument();+ if (!before) {+ return { status: 'not-ready' };+ }+ const expectedRevision = mutationContext.getEditRevision();+ const summary = replaceCanvasFontReferences(before, from, target);+ if (summary.replacedCount === 0) {+ return { ...summary, status: 'unchanged' };+ }+ const result = commitStructural(+ 'Replace missing font',+ { document: summary.document, type: 'replaceCanvasFontReferences' },+ { document: before, type: 'replaceCanvasFontReferences' },+ { expectedRevision }+ );+ return result.status === 'committed' ? { ...summary, status: 'committed' } : result;+ };+ const fonts: CanvasFontCapability = {+ collectReferences: collectCanvasFontReferences,+ ensurePreview: fontLoader.ensurePreview,+ replaceAllReferences: replaceAllFontReferences,+ resolveFamily: fontLoader.resolveFamily,+ subscribe: fontLoader.subscribe,+ waitForReady: fontLoader.waitForReady,+ };const nudgeSelectedLayer = (dx: number, dy: number): StructuralCommitResult => structuralController.nudge(dx, dy);// Tools commit at pointer-up with nowhere to show a refusal; contention is expected, anything else is logged.const commitToolStructural = (@@ -1284,11 +1317,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCisRasterizing: isCurrentRasterizationJob,isSupportedSource: isSupportedExportSource,layers: layerCache,+ invalidateLayerCache,pin: (layerId) => rasterController.memory.pin(layerId, lifecycleGeneration),reserve: (bytes) => {syncMemoryBaselines();return rasterController.memory.reserve(bytes, { generation: lifecycleGeneration, purpose: 'raster-export' });},+ waitForFont: fontLoader.waitForReady,});const rasterizeLayerPixels = rasterExportController.rasterize.bind(rasterExportController);const prepareLayerRasterCache = async (layerId: string) => {@@ -1742,6 +1777,30 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreConStagingChanged: () => scheduler.invalidate({ overlay: true }),});+ let fontSourceStacks: CanvasDocumentContractV3['stacks'] | null = null;+ let documentFontSources: CanvasTextSource[] = [];+ let draftFontSource: CanvasTextSource | undefined;+ syncActiveFontSources = () => {+ const document = mutationPort.getCanvasState()?.document;+ const stacks = document?.stacks ?? null;+ const draft = document ? stores.textEditSession.get()?.source : undefined;+ if (stacks === fontSourceStacks && draft === draftFontSource) {+ return;+ }+ if (stacks !== fontSourceStacks) {+ fontSourceStacks = stacks;+ documentFontSources = document+ ? getDocumentLeaves(document).flatMap((layer) =>+ (layer.type === 'raster' || layer.type === 'control') && layer.source.type === 'text' ? [layer.source] : []+ )+ : [];+ }+ draftFontSource = draft;+ fontLoader.setActiveSources(draft ? [...documentFontSources, draft] : documentFontSources);+ };+ syncActiveFontSources();+ const unsubscribeTextFontSources = stores.textEditSession.subscribe(syncActiveFontSources);+for (const layer of getDocumentLeaves(mirror.getDocument())) {rasterController.setThumbnailKey(layer.id, getLayerThumbnailDisplayKey(layer));const imageName = layerImageName(layer);@@ -1755,6 +1814,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// this project cannot resurrect it.let projectWasPresent = mutationPort.getCanvasState() !== null;const unsubscribeProjectPreviewLifecycle = mutationPort.subscribe(() => {+ syncActiveFontSources();const projectIsPresent = mutationPort.getCanvasState() !== null;if (projectWasPresent && !projectIsPresent) {const cleanup = createCleanupAccumulator();@@ -2631,6 +2691,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(unsubscribeBboxOverlay);cleanup.run(unsubscribeRuleOfThirds);cleanup.run(unsubscribeProjectPreviewLifecycle);+ cleanup.run(unsubscribeTextFontSources);cleanup.run(() => mutationContext.dispose());cleanup.run(unsubscribeHistoryEpoch);cleanup.run(() => historyController.dispose());@@ -2639,6 +2700,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(() => previewPublisher.dispose());cleanup.run(() => renderController.dispose());cleanup.run(() => rasterController.dispose());+ cleanup.run(() => fontLoader.dispose());cleanup.run(() => stores.thumbnailStatus.clear());cleanup.run(() => strokeListeners.clear());cleanup.run(() => toolChangeListeners.clear());@@ -3189,6 +3251,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCdocument: documentCapability,edits: editingController.edits,exports: exportCapability,+ fonts,history: historyCapability,interaction,lifecycle,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.tsindex e53bedd7a5..608654b406 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts@@ -11,7 +11,13 @@* Zero React, zero import-time side effects.*/-import type { CanvasLayerSourceContract, ParametricShapeKind } from '@workbench/canvas-engine/contracts';+import type {+ CanvasLayerSourceContract,+ CanvasTextFontRef,+ CanvasTextFontStyle,+ CanvasTextFontVariations,+ ParametricShapeKind,+} from '@workbench/canvas-engine/contracts';import type { SamInteractionState } from '@workbench/canvas-engine/samInteraction';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { Rect, SelectionOp, ToolId, Vec2 } from '@workbench/canvas-engine/types';@@ -179,6 +185,12 @@ export interface TextToolOptions {fontSize: number;/** CSS numeric weight (400/500/600/700). */fontWeight: number;+ /** Stable custom-font identity, omitted for built-in font stacks. */+ fontRef?: CanvasTextFontRef;+ /** CSS style used by both the editing portal and Canvas rasterizer. Defaults to `normal`. */+ fontStyle?: CanvasTextFontStyle;+ /** Explicit OpenType variation coordinates for custom or variable faces. Defaults to `{}`. */+ fontVariations?: CanvasTextFontVariations;/** Unitless line-height multiplier over `fontSize`. */lineHeight: number;align: 'left' | 'center' | 'right';@@ -212,6 +224,8 @@ export const DEFAULT_TEXT_OPTIONS: TextToolOptions = {fontFamily: TEXT_FONT_FAMILIES[0]!.value,fontSize: 48,fontWeight: 400,+ fontStyle: 'normal',+ fontVariations: {},lineHeight: 1.2,};@@ -706,10 +720,31 @@ const transformSessionEqual = (a: TransformSession | null, b: TransformSession |);};+const textFontRefEqual = (a: CanvasTextFontRef | undefined, b: CanvasTextFontRef | undefined): boolean =>+ a === b ||+ (a !== undefined &&+ b !== undefined &&+ a.id === b.id &&+ a.contentHash === b.contentHash &&+ a.family === b.family &&+ a.label === b.label);++const textVariationsEqual = (+ a: CanvasTextFontVariations | undefined,+ b: CanvasTextFontVariations | undefined+): boolean => {+ const aKeys = Object.keys(a ?? {});+ const bKeys = Object.keys(b ?? {});+ return aKeys.length === bKeys.length && aKeys.every((key) => (a ?? {})[key] === (b ?? {})[key]);+};+const textOptionsEqual = (a: TextToolOptions, b: TextToolOptions): boolean =>a.fontFamily === b.fontFamily &&a.fontSize === b.fontSize &&a.fontWeight === b.fontWeight &&+ textFontRefEqual(a.fontRef, b.fontRef) &&+ a.fontStyle === b.fontStyle &&+ textVariationsEqual(a.fontVariations, b.fontVariations) &&a.lineHeight === b.lineHeight &&a.align === b.align;@@ -718,6 +753,9 @@ const textSourceEqual = (a: TextSource, b: TextSource): boolean =>a.fontFamily === b.fontFamily &&a.fontSize === b.fontSize &&a.fontWeight === b.fontWeight &&+ textFontRefEqual(a.fontRef, b.fontRef) &&+ (a.fontStyle ?? 'normal') === (b.fontStyle ?? 'normal') &&+ textVariationsEqual(a.fontVariations ?? {}, b.fontVariations ?? {}) &&a.lineHeight === b.lineHeight &&a.align === b.align &&a.color === b.color;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/fontReferences.engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/fontReferences.engine.test.tsnew file mode 100644index 0000000000..038af8b35f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/fontReferences.engine.test.ts@@ -0,0 +1,152 @@+import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';+import type { Project } from '@workbench/projectContracts';++import { createEmptyCanvasState } from '@workbench/canvasMigration';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createInitialWorkbenchState } from '@workbench/workbenchState.testing';+import { describe, expect, it, vi } from 'vitest';++import type { CanvasDocumentContractV3, CanvasLayerContract, CanvasTextFontRef } from './contracts';+import type { BitmapStore } from './document/bitmapStore';++import { documentFrom, groupContract, layerContract } from './document-model/documentFixtures.testStub';+import { createCanvasEngine } from './engine';+import { createTestStubRasterBackend } from './render/raster.testStub';++const from: CanvasTextFontRef = {+ contentHash: 'a'.repeat(64),+ family: 'Catalog Sans',+ id: 'font-a',+ label: 'Catalog Sans Regular',+};+const to: CanvasTextFontRef = {+ contentHash: 'b'.repeat(64),+ family: 'Replacement Sans',+ id: 'font-b',+ label: 'Replacement Sans Variable',+};++const textLayer = (id: string, fontRef: CanvasTextFontRef): CanvasLayerContract =>+ layerContract(id, 'raster', {+ source: {+ align: 'left',+ color: '#ffffff',+ content: id,+ fontFamily: fontRef.family,+ fontRef,+ fontSize: 24,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ });++const createBitmapStoreStub = (): BitmapStore => ({+ discardLayer: () => undefined,+ dispose: () => undefined,+ flushPendingUploads: () => Promise.resolve(),+ hasPendingClear: () => false,+ hasPendingWork: () => false,+ isSelfEcho: () => false,+ markLayerDirty: () => undefined,+ reset: () => undefined,+ suspendLayer: () => () => undefined,+});++const createHarness = (document: CanvasDocumentContractV3) => {+ const initial = createInitialWorkbenchState().projects[0]!;+ let project: Project = { ...initial, canvas: { ...createEmptyCanvasState(), document } };+ const listeners = new Set<() => void>();+ const mutationPort: CanvasProjectMutationPort = {+ commitEdit: () => undefined,+ dispatch: (mutation) => {+ const next = applyCanvasProjectMutation(project, mutation);+ if (next.canvas === project.canvas) {+ return false;+ }+ project = next;+ for (const listener of listeners) {+ listener();+ }+ return true;+ },+ getCanvasState: () => project.canvas,+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+ const composition = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createBitmapStoreStub(),+ fonts: null,+ imageResolver: () => Promise.resolve(new Blob()),+ mutationPort,+ projectId: project.id,+ reportError: () => undefined,+ uploadImage: () => Promise.resolve({ height: 1, imageName: 'image', width: 1 }),+ uploadIntermediateImage: () => Promise.resolve({ height: 1, imageName: 'intermediate', width: 1 }),+ });+ return {+ composition,+ getDocument: () => project.canvas.document,+ notifyUnchanged: () => listeners.forEach((listener) => listener()),+ };+};++describe('Canvas font replacement capability', () => {+ it('does not rescan text sources for unrelated workbench notifications', () => {+ const layer = textLayer('one', from);+ const source = layer.type === 'raster' ? layer.source : undefined;+ const readSource = vi.fn(() => source);+ Object.defineProperty(layer, 'source', { get: readSource });+ const harness = createHarness(documentFrom([layer]));+ readSource.mockClear();+ for (let index = 0; index < 100; index += 1) {+ harness.notifyUnchanged();+ }+ expect(readSource).not.toHaveBeenCalled();+ harness.composition.engine.lifecycle.dispose();+ });++ it('commits one replace-all history step and restores it with undo/redo', () => {+ const document = documentFrom([groupContract('group', [textLayer('one', from), textLayer('two', from)])]);+ const harness = createHarness(document);+ const { engine } = harness.composition;++ expect(engine.fonts.collectReferences(document)).toEqual([{ count: 2, fontRef: from, layerIds: ['one', 'two'] }]);+ expect(+ engine.fonts.replaceAllReferences(from, {+ fontRef: to,+ style: 'normal',+ weight: 400,+ axes: [{ default: 400, maximum: 700, minimum: 300, tag: 'wght' }],+ })+ ).toEqual(expect.objectContaining({ replacedCount: 2, status: 'committed' }));+ expect(harness.getDocument().version).toBe(4);+ const replaced = harness.getDocument().stacks.raster[0];+ expect(replaced?.type === 'group' ? replaced.children[0] : null).toMatchObject({+ source: { fontFamily: to.family, fontRef: to },+ });+ expect(engine.stores.canUndo.get()).toBe(true);++ engine.history.undo();+ expect(harness.getDocument().stacks.raster[0]).toEqual(document.stacks.raster[0]);+ engine.history.redo();+ expect(harness.getDocument().version).toBe(4);+ expect(engine.stores.canUndo.get()).toBe(true);+ engine.lifecycle.dispose();+ });++ it('returns unchanged without adding history when no layer uses the reference', () => {+ const document = documentFrom([textLayer('other', { ...from, label: 'Other' })]);+ const harness = createHarness(document);+ const { engine } = harness.composition;++ expect(engine.fonts.replaceAllReferences(from, { fontRef: to, style: 'italic', weight: 700, axes: [] })).toEqual(+ expect.objectContaining({ replacedCount: 0, status: 'unchanged' })+ );+ expect(engine.stores.canUndo.get()).toBe(false);+ engine.lifecycle.dispose();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/fontReferences.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/fontReferences.test.tsnew file mode 100644index 0000000000..788df6c41f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/fontReferences.test.ts@@ -0,0 +1,141 @@+import { describe, expect, it } from 'vitest';++import type { CanvasLayerContract, CanvasTextFontRef } from './contracts';++import { documentFrom, groupContract, layerContract } from './document-model/documentFixtures.testStub';+import { collectCanvasFontReferences, replaceCanvasFontReferences, sameCanvasTextFontRef } from './fontReferences';++const from: CanvasTextFontRef = {+ contentHash: 'a'.repeat(64),+ family: 'Catalog Sans',+ id: 'font-a',+ label: 'Catalog Sans Regular',+};+const to: CanvasTextFontRef = {+ contentHash: 'b'.repeat(64),+ family: 'Replacement Sans',+ id: 'font-b',+ label: 'Replacement Sans Variable',+};++const textLayer = (+ id: string,+ fontRef: CanvasTextFontRef,+ fontVariations?: Readonly<Record<string, number>>+): CanvasLayerContract =>+ layerContract(id, 'raster', {+ source: {+ align: 'left',+ color: '#ffffff',+ content: id,+ fontFamily: fontRef.family,+ fontRef,+ fontSize: 24,+ fontVariations,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ });++describe('canvas font references', () => {+ it('groups exact custom references across stacks and nested groups', () => {+ const other: CanvasTextFontRef = { ...from, label: 'Catalog Sans Italic' };+ const document = documentFrom([+ groupContract('group', [textLayer('nested-a', from), textLayer('nested-b', from)]),+ textLayer('root-other', other),+ ]);+ document.stacks.control.push(textLayer('control-a', from));++ expect(collectCanvasFontReferences(document)).toEqual([+ { count: 3, fontRef: from, layerIds: ['nested-a', 'nested-b', 'control-a'] },+ { count: 1, fontRef: other, layerIds: ['root-other'] },+ ]);+ });++ it('replaces every exact match, clamps supported axes, and reports resets', () => {+ const document = documentFrom([+ groupContract('group', [+ textLayer('clamped', from, { opsz: 14, wght: 900 }),+ textLayer('reset', from, { ital: 1, wght: 250 }),+ ]),+ textLayer('untouched', { ...from, label: 'Other face' }, { wght: 900 }),+ ]);++ const result = replaceCanvasFontReferences(document, from, {+ fontRef: to,+ style: 'normal',+ weight: 400,+ axes: [{ default: 400, maximum: 700, minimum: 300, tag: 'wght' }],+ });++ expect(result.replacedLayerIds).toEqual(['clamped', 'reset']);+ expect(result.replacedCount).toBe(2);+ expect(result.clampedAxisTags).toEqual(['wght']);+ expect(result.resetAxisTags).toEqual(['ital', 'opsz']);+ expect(result.document.version).toBe(4);+ const group = result.document.stacks.raster[0];+ expect(group?.type).toBe('group');+ if (group?.type === 'group') {+ expect(group.children[0]).toMatchObject({+ source: {+ fontFamily: to.family,+ fontRef: to,+ fontVariations: { wght: 700 },+ fontWeight: 700,+ fontStyle: 'normal',+ },+ });+ expect(group.children[1]).toMatchObject({+ source: {+ fontFamily: to.family,+ fontRef: to,+ fontVariations: { wght: 300 },+ fontWeight: 300,+ fontStyle: 'normal',+ },+ });+ }+ expect(result.document.stacks.raster[1]).toEqual(document.stacks.raster[1]);+ });++ it('resets all coordinates for a static replacement and treats same-ref replacement as a no-op', () => {+ const document = documentFrom([textLayer('text', from, { opsz: 14, wght: 500 })]);+ const staticResult = replaceCanvasFontReferences(document, from, {+ fontRef: to,+ style: 'italic',+ weight: 700,+ axes: [],+ });+ const source = staticResult.document.stacks.raster[0];+ expect(source?.type === 'raster' ? source.source : null).toMatchObject({+ fontRef: to,+ fontFamily: to.family,+ fontWeight: 700,+ fontStyle: 'italic',+ });+ expect(+ source?.type === 'raster' && source.source.type === 'text' ? source.source.fontVariations : null+ ).toBeUndefined();+ expect(staticResult.resetAxisTags).toEqual(['opsz', 'wght']);++ const noOp = replaceCanvasFontReferences(document, from, { fontRef: from, style: 'normal', weight: 400, axes: [] });+ expect(noOp).toMatchObject({ replacedCount: 0, document });+ expect(sameCanvasTextFontRef(from, { ...from })).toBe(true);+ });+ it('uses target axis defaults when replacing a static face and synchronizes CSS typography', () => {+ const document = documentFrom([textLayer('text', from)]);+ const result = replaceCanvasFontReferences(document, from, {+ fontRef: to,+ style: 'normal',+ weight: 400,+ axes: [+ { tag: 'wght', minimum: 100, maximum: 900, default: 650 },+ { tag: 'ital', minimum: 0, maximum: 1, default: 1 },+ ],+ });+ expect(result.document.stacks.raster[0]).toMatchObject({+ source: { fontWeight: 650, fontStyle: 'italic', fontVariations: { wght: 650, ital: 1 }, fontRef: to },+ });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/fontReferences.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/fontReferences.tsnew file mode 100644index 0000000000..1dac3fbd35--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/fontReferences.ts@@ -0,0 +1,244 @@+import type {+ CanvasDocumentContractV3,+ CanvasLayerContract,+ CanvasNodeContract,+ CanvasStackForests,+ CanvasTextFontRef,+ CanvasTextFontStyle,+ CanvasTextFontVariations,+} from './contracts';++type CanvasSourceLayerContract = Extract<CanvasLayerContract, { type: 'raster' | 'control' }>;++/** The range of one OpenType variation axis exposed by a replacement face. */+export interface CanvasFontAxisRange {+ tag: string;+ minimum: number;+ maximum: number;+ default: number;+}++/** File metadata and axis ranges used to reset typography when replacing a face. */+export interface CanvasFontReplacementTarget {+ fontRef: CanvasTextFontRef;+ axes: readonly CanvasFontAxisRange[];+ style: CanvasTextFontStyle;+ weight: number;+}++/** One exact persisted reference and the text layers that use it. */+export interface CanvasFontReferenceGroup {+ readonly fontRef: CanvasTextFontRef;+ readonly count: number;+ readonly layerIds: readonly string[];+}++/** Details returned by a replace-all operation before it is added to history. */+export interface CanvasFontReplacementSummary {+ readonly document: CanvasDocumentContractV3;+ readonly from: CanvasTextFontRef;+ readonly to: CanvasTextFontRef;+ readonly replacedLayerIds: readonly string[];+ readonly replacedCount: number;+ /** Coordinates retained on the target face after clamping to its ranges. */+ readonly clampedAxisTags: readonly string[];+ /** Coordinates present on the source face but absent from the target face. */+ readonly resetAxisTags: readonly string[];+}++export const sameCanvasTextFontRef = (left: CanvasTextFontRef, right: CanvasTextFontRef): boolean =>+ left.id === right.id &&+ left.contentHash === right.contentHash &&+ left.family === right.family &&+ left.label === right.label;++const referenceKey = (reference: CanvasTextFontRef): string =>+ JSON.stringify([reference.id, reference.contentHash, reference.family, reference.label]);++const visit = (nodes: readonly CanvasNodeContract[], callback: (layer: CanvasLayerContract) => void): void => {+ for (const node of nodes) {+ if (node.type === 'group') {+ visit(node.children, callback);+ } else {+ callback(node);+ }+ }+};++const visitStacks = (stacks: CanvasStackForests, callback: (layer: CanvasLayerContract) => void): void => {+ visit(stacks.raster, callback);+ visit(stacks.control, callback);+ visit(stacks.regional_guidance, callback);+ visit(stacks.inpaint_mask, callback);+};++const hasSource = (layer: CanvasLayerContract): layer is CanvasSourceLayerContract =>+ layer.type === 'raster' || layer.type === 'control';++/** Collects custom text references in deterministic stack/tree order. */+export const collectCanvasFontReferences = (+ document: CanvasDocumentContractV3+): readonly CanvasFontReferenceGroup[] => {+ const groups = new Map<string, { fontRef: CanvasTextFontRef; layerIds: string[] }>();+ visitStacks(document.stacks, (layer) => {+ if (!hasSource(layer) || layer.source.type !== 'text' || !layer.source.fontRef) {+ return;+ }+ const key = referenceKey(layer.source.fontRef);+ const group = groups.get(key);+ if (group) {+ group.layerIds.push(layer.id);+ return;+ }+ groups.set(key, { fontRef: { ...layer.source.fontRef }, layerIds: [layer.id] });+ });+ return [...groups.values()].map(({ fontRef, layerIds }) => ({+ count: layerIds.length,+ fontRef,+ layerIds,+ }));+};++const clamp = (value: number, range: CanvasFontAxisRange): number =>+ Math.min(range.maximum, Math.max(range.minimum, value));++const replaceVariations = (+ variations: CanvasTextFontVariations | undefined,+ targetAxes: ReadonlyMap<string, CanvasFontAxisRange>,+ clampedAxisTags: Set<string>,+ resetAxisTags: Set<string>+): CanvasTextFontVariations | undefined => {+ const entries = Object.entries(variations ?? {});+ const next: Record<string, number> = Object.fromEntries([...targetAxes].map(([tag, range]) => [tag, range.default]));+ for (const [tag, value] of entries) {+ const range = targetAxes.get(tag);+ if (!range || !Number.isFinite(value)) {+ resetAxisTags.add(tag);+ continue;+ }+ const bounded = clamp(value, range);+ if (bounded !== value) {+ clampedAxisTags.add(tag);+ }+ next[tag] = bounded;+ }+ return Object.keys(next).length > 0 ? next : undefined;+};++const replaceNodes = (+ nodes: readonly CanvasNodeContract[],+ from: CanvasTextFontRef,+ target: CanvasFontReplacementTarget,+ targetAxes: ReadonlyMap<string, CanvasFontAxisRange>,+ replacedLayerIds: string[],+ clampedAxisTags: Set<string>,+ resetAxisTags: Set<string>+): readonly CanvasNodeContract[] => {+ let changed = false;+ const next = nodes.map((node) => {+ if (node.type === 'group') {+ const children = replaceNodes(+ node.children,+ from,+ target,+ targetAxes,+ replacedLayerIds,+ clampedAxisTags,+ resetAxisTags+ );+ if (children === node.children) {+ return node;+ }+ changed = true;+ return { ...node, children: [...children] };+ }+ if (+ !hasSource(node) ||+ node.source.type !== 'text' ||+ !node.source.fontRef ||+ !sameCanvasTextFontRef(node.source.fontRef, from)+ ) {+ return node;+ }+ const variations = replaceVariations(node.source.fontVariations, targetAxes, clampedAxisTags, resetAxisTags);+ const style =+ variations?.ital !== undefined+ ? variations.ital >= 0.5+ ? 'italic'+ : 'normal'+ : variations?.slnt !== undefined+ ? variations.slnt !== 0+ ? 'oblique'+ : 'normal'+ : target.style;+ replacedLayerIds.push(node.id);+ changed = true;+ return {+ ...node,+ source: {+ ...node.source,+ fontFamily: target.fontRef.family,+ fontRef: { ...target.fontRef },+ fontStyle: style,+ fontWeight: variations?.wght ?? target.weight,+ fontVariations: variations,+ },+ };+ });+ return changed ? next : nodes;+};++/**+ * Replaces every exact reference in a document while sharing untouched trees.+ * `targetAxes` is empty for a static face, so all source variation coordinates+ * are intentionally reset and included in the summary.+ */+export const replaceCanvasFontReferences = (+ document: CanvasDocumentContractV3,+ from: CanvasTextFontRef,+ target: CanvasFontReplacementTarget+): CanvasFontReplacementSummary => {+ const { fontRef: to, axes: targetAxes } = target;+ if (sameCanvasTextFontRef(from, to)) {+ return {+ clampedAxisTags: [],+ document,+ from: { ...from },+ replacedCount: 0,+ replacedLayerIds: [],+ resetAxisTags: [],+ to: { ...to },+ };+ }+ const axes = new Map(targetAxes.map((axis) => [axis.tag, axis]));+ const replacedLayerIds: string[] = [];+ const clampedAxisTags = new Set<string>();+ const resetAxisTags = new Set<string>();+ let changed = false;+ const stacks = { ...document.stacks };+ for (const stack of ['raster', 'control', 'regional_guidance', 'inpaint_mask'] as const) {+ const nodes = replaceNodes(+ document.stacks[stack],+ from,+ target,+ axes,+ replacedLayerIds,+ clampedAxisTags,+ resetAxisTags+ );+ if (nodes !== document.stacks[stack]) {+ stacks[stack] = [...nodes];+ changed = true;+ }+ }+ const nextDocument = changed ? { ...document, stacks, version: 4 as const } : document;+ return {+ clampedAxisTags: [...clampedAxisTags].sort(),+ document: nextDocument,+ from: { ...from },+ replacedCount: replacedLayerIds.length,+ replacedLayerIds,+ resetAxisTags: [...resetAxisTags].sort(),+ to: { ...to },+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.tsindex 377fceb8c9..547e275700 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts@@ -106,6 +106,7 @@ const makeHarness = (overrides: Partial<CreateLayerRasterizerDeps> = {}): Harnesensure: (_font, onReady) => {result.fontReady = onReady;},+ resolveFamily: (source) => source.fontFamily,},getDocument: () => document.value,hasCanvasState: () => state.hasCanvas,@@ -372,6 +373,7 @@ describe('text sources', () => {it('re-invalidates once the real font arrives', async () => {harness.document.value = documentOf([textLayer()]);await start(textLayer());+ expect(harness.entry.renderedFontFamily).toBe('Inter');expect(harness.fontReady).toBeTypeOf('function');harness.fontReady?.();expect(harness.spies.invalidateLayerCache).toHaveBeenCalledWith('layer-1');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.tsindex a09fd5aa7e..d6ccab2597 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts@@ -4,6 +4,7 @@ import type {CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';import type { RasterizationJob } from '@workbench/canvas-engine/controllers/rasterController';+import type { FontLoader } from '@workbench/canvas-engine/render/fontLoader';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { RasterizeResult } from '@workbench/canvas-engine/render/rasterizers';@@ -13,7 +14,6 @@ import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndeimport { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';import { isSupportedExportSource } from '@workbench/canvas-engine/layerExportGuards';import { isEmpty } from '@workbench/canvas-engine/math/rect';-import { textFontString } from '@workbench/canvas-engine/render/rasterizers/textRasterizer';/** How a rasterization ended: pixels landed, the world moved, it threw, or it was cancelled. */export type LayerRasterizationOutcome = 'published' | 'stale' | 'error' | 'aborted';@@ -45,7 +45,7 @@ export interface CreateLayerRasterizerDeps {setVersion(layerId: string, version: number): void;setStatus(layerId: string, status: 'ready' | 'error'): void;};- readonly fontLoader: { ensure(font: string, onReady: () => void): void };+ readonly fontLoader: Pick<FontLoader, 'ensure' | 'resolveFamily'>;readonly createSurface: (width: number, height: number) => RasterSurface;readonly rasterize: (source: CanvasLayerSourceContract,@@ -143,26 +143,31 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRas}jobs.cancel(layer.id);+ const controller = new AbortController();+ const renderedFontFamily = source.type === 'text' ? deps.fontLoader.resolveFamily(source) : undefined;if (source.type === 'text') {- deps.fontLoader.ensure(textFontString(source), () => {- const currentLayer = getDocumentLayer(deps.getDocument(), layer.id);- if (- deps.isDisposed() ||- !deps.hasCanvasState() ||- !currentLayer ||- jobs.getDocumentGeneration() !== documentGeneration ||- layerCache.version(layer.id) !== version ||- !areJsonValuesStructurallyEqual(renderableSourceOf(currentLayer), source)- ) {- return;- }- deps.invalidateLayerCache(layer.id);- deps.invalidateLayerRender(layer.id);- });+ deps.fontLoader.ensure(+ source,+ () => {+ const currentLayer = getDocumentLayer(deps.getDocument(), layer.id);+ if (+ deps.isDisposed() ||+ !deps.hasCanvasState() ||+ !currentLayer ||+ jobs.getDocumentGeneration() !== documentGeneration ||+ layerCache.version(layer.id) !== version ||+ !areJsonValuesStructurallyEqual(renderableSourceOf(currentLayer), source)+ ) {+ return;+ }+ deps.invalidateLayerCache(layer.id);+ deps.invalidateLayerRender(layer.id);+ },+ controller.signal+ );}const scratch = deps.createSurface(contentRect.width, contentRect.height);- const controller = new AbortController();let settleJob!: (result: LayerRasterizationOutcome) => void;const promise = new Promise<LayerRasterizationOutcome>((resolve) => {settleJob = resolve;@@ -202,6 +207,7 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRasif (!isEmpty(result.rect)) {ctx.drawImage(result.surface.canvas, 0, 0);}+ currentEntry.renderedFontFamily = renderedFontFamily;currentEntry.rect = { ...result.rect };const publishedEntry = layerCache.publishPixels(layer.id);if (!publishedEntry) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.tsindex 921379d3f5..50b2634b9b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts@@ -156,6 +156,8 @@ export type CanvasProjectMutation =| { type: 'setCanvasBbox'; bbox: CanvasDocumentContractV3['bbox'] }| { type: 'setCanvasSelectedLayer'; id: string | null }| { type: 'resizeCanvasDocument'; width: number; height: number; offsetX?: number; offsetY?: number }+ /** Replaces text sources while preserving the document revision for one undoable font recovery edit. */+ | { type: 'replaceCanvasFontReferences'; document: CanvasDocumentContractV3 }| { type: 'replaceCanvasDocument'; document: CanvasDocumentContractV3 }| { type: 'saveCanvasSnapshot'; id: string; name: string; createdAt: string }| { type: 'restoreCanvasSnapshot'; snapshotId: string }diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fixtures/README.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fixtures/README.mdnew file mode 100644index 0000000000..c4eafebab8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fixtures/README.md@@ -0,0 +1,7 @@+# Canvas font fixtures++These tiny TrueType files are self-authored browser-test fixtures generated with+fontTools. They contain a single rectangle glyph for `A`; `custom-axis.ttf` is+variable with `wght` and `TEST` axes, while `custom-axis-wide.ttf` is a static+wide instance used to verify pinned output metrics. They contain no third-party+font data or licensing restrictions.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fixtures/custom-axis-wide.ttf b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fixtures/custom-axis-wide.ttfnew file mode 100644index 0000000000..3e44afcdb9Binary files /dev/null and b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fixtures/custom-axis-wide.ttf differdiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fixtures/custom-axis.ttf b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fixtures/custom-axis.ttfnew file mode 100644index 0000000000..5479d248baBinary files /dev/null and b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fixtures/custom-axis.ttf differdiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.browser.test.tsnew file mode 100644index 0000000000..66c23dcca5--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.browser.test.ts@@ -0,0 +1,176 @@+import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';++import { createFontRuntime, type FontRecord } from '@features/fonts';+import { afterEach, describe, expect, it } from 'vitest';++import customAxisWideFontUrl from './fixtures/custom-axis-wide.ttf?url&inline';+import customAxisFontUrl from './fixtures/custom-axis.ttf?url&inline';+import { createFontLoader } from './fontLoader';+import { createLayerCacheStore } from './layerCache';+import { createDomRasterBackend } from './raster';+import { rasterizeTextSource } from './rasterizers/textRasterizer';++type TextSource = Extract<CanvasLayerSourceContract, { type: 'text' }>;++const loaders: Array<{ dispose: () => void }> = [];++const sourceFor = (overrides: Partial<TextSource> = {}): TextSource => ({+ align: 'left',+ color: '#fff',+ content: 'A',+ fontFamily: 'Invoke Font Fixture',+ fontRef: {+ contentHash: 'a'.repeat(64),+ family: 'Invoke Font Fixture',+ id: 'browser-variable',+ label: 'Invoke Font Fixture Regular',+ },+ fontSize: 64,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ ...overrides,+});++const glyphPixels = (source: Awaited<ReturnType<typeof rasterizeTextSource>>): number => {+ const pixels = source.surface.ctx.getImageData(0, 0, source.surface.width, source.surface.height).data;+ let count = 0;+ for (let index = 3; index < pixels.length; index += 4) {+ if (pixels[index] > 0) {+ count += 1;+ }+ }+ return count;+};++afterEach(() => {+ for (const loader of loaders.splice(0)) {+ loader.dispose();+ }+});++describe('Canvas custom-font loading in Chromium', () => {+ it('applies requested bold styling to a static regular face', async () => {+ const runtime = createFontRuntime({+ download: async () => new Uint8Array(await (await fetch(customAxisWideFontUrl)).arrayBuffer()),+ getFont: (id): Promise<FontRecord> =>+ Promise.resolve({+ id,+ contentHash: 'a'.repeat(64),+ family: 'Invoke Font Fixture',+ label: 'Regular',+ filename: 'regular.ttf',+ axes: [],+ instances: [],+ byteSize: 1,+ scope: 'private',+ source: 'uploaded',+ style: 'normal',+ weight: 400,+ url: '',+ }),+ });+ const loader = createFontLoader(runtime);+ loaders.push({+ dispose: () => {+ loader.dispose();+ runtime.dispose();+ },+ });+ const normal = sourceFor();+ const bold = sourceFor({ fontWeight: 700 });+ loader.setActiveSources([normal, bold]);+ await Promise.all([loader.waitForReady(normal), loader.waitForReady(bold)]);+ const backend = createDomRasterBackend();+ const rasterize = (source: TextSource) =>+ rasterizeTextSource(source, {+ backend,+ documentSize: { height: 128, width: 128 },+ resolver: () => Promise.resolve(new Blob()),+ resolveFontFamily: loader.resolveFamily,+ store: createLayerCacheStore(backend),+ });+ const normalRaster = await rasterize(normal);+ const boldRaster = await rasterize(bold);+ expect(glyphPixels(boldRaster)).toBeGreaterThan(glyphPixels(normalRaster));+ });++ it('registers real variable and pinned static faces, then rasterizes their distinct glyph metrics', async () => {+ const variable = sourceFor({ fontVariations: { TEST: 0, wght: 400 } });+ const pinnedStatic = sourceFor({+ fontRef: {+ contentHash: 'b'.repeat(64),+ family: 'Invoke Font Fixture',+ id: 'browser-static-wide',+ label: 'Invoke Font Fixture Wide',+ },+ fontVariations: { TEST: 100, wght: 400 },+ });+ const runtime = createFontRuntime({+ download: async (reference) => {+ const url = reference.axes?.TEST === 100 ? customAxisWideFontUrl : customAxisFontUrl;+ return new Uint8Array(await (await fetch(url)).arrayBuffer());+ },+ getFont: (id): Promise<FontRecord> =>+ Promise.resolve({+ axes:+ id === 'browser-variable'+ ? [+ { default: 400, hidden: false, label: 'Weight', maximum: 900, minimum: 100, tag: 'wght' },+ { default: 0, hidden: false, label: 'Test', maximum: 100, minimum: 0, tag: 'TEST' },+ ]+ : [],+ byteSize: 1,+ contentHash: id === 'browser-static-wide' ? 'b'.repeat(64) : 'a'.repeat(64),+ family: 'Invoke Font Fixture',+ filename: `${id}.ttf`,+ id,+ instances: [],+ label: id === 'browser-static-wide' ? 'Invoke Font Fixture Wide' : 'Invoke Font Fixture Regular',+ scope: 'private',+ source: 'uploaded',+ style: 'normal',+ url: '',+ weight: 400,+ }),+ });+ const loader = createFontLoader(runtime);+ loaders.push({+ dispose: () => {+ loader.dispose();+ runtime.dispose();+ },+ });+ loader.setActiveSources([variable, pinnedStatic]);++ const [variableFamily, staticFamily] = await Promise.all([+ loader.waitForReady(variable),+ loader.waitForReady(pinnedStatic),+ ]);+ expect(variableFamily).toMatch(/^__invoke_font_/);+ expect(staticFamily).toMatch(/^__invoke_font_/);+ expect(staticFamily).not.toBe(variableFamily);+ expect(document.fonts.check(`400 64px ${variableFamily}`)).toBe(true);+ expect(document.fonts.check(`400 64px ${staticFamily}`)).toBe(true);++ const backend = createDomRasterBackend();+ const variableRaster = await rasterizeTextSource(variable, {+ backend,+ documentSize: { height: 128, width: 128 },+ resolver: () => Promise.resolve(new Blob()),+ resolveFontFamily: loader.resolveFamily,+ store: createLayerCacheStore(backend),+ });+ const staticRaster = await rasterizeTextSource(pinnedStatic, {+ backend,+ documentSize: { height: 128, width: 128 },+ resolver: () => Promise.resolve(new Blob()),+ resolveFontFamily: loader.resolveFamily,+ store: createLayerCacheStore(backend),+ });++ expect(glyphPixels(variableRaster)).toBeGreaterThan(0);+ expect(glyphPixels(staticRaster)).toBeGreaterThan(0);+ expect(staticRaster.rect.width).toBeGreaterThan(variableRaster.rect.width);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.test.tsindex d5cae5e72b..c24d9495e0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest';-import type { FontLoadApi } from './fontLoader';+import type { CanvasFontRuntime, FontLoadApi } from './fontLoader';import { createFontLoader } from './fontLoader';@@ -29,6 +29,20 @@ const flush = (): Promise<void> =>setTimeout(resolve, 0);});+const customText = {+ align: 'left' as const,+ color: '#fff',+ content: 'hello',+ fontFamily: 'Catalog Family',+ fontRef: { contentHash: 'hash-1', family: 'Catalog Family', id: 'font-1', label: 'Catalog Regular' },+ fontSize: 32,+ fontStyle: 'oblique' as const,+ fontVariations: { opsz: 14, wght: 612 },+ fontWeight: 612,+ lineHeight: 1.2,+ type: 'text' as const,+};+describe('createFontLoader', () => {it('is a silent no-op with no api (node-safe)', () => {const loader = createFontLoader(null);@@ -58,6 +72,21 @@ describe('createFontLoader', () => {expect(onReady).toHaveBeenCalledTimes(1);});+ it('does not call onReady again after a completed load', async () => {+ const { api, load, settle } = createFakeFonts(false);+ const loader = createFontLoader(api);+ const first = vi.fn();+ const second = vi.fn();+ loader.ensure('400 20px Inter', first);+ settle();+ await flush();+ loader.ensure('400 20px Inter', second);+ await flush();+ expect(load).toHaveBeenCalledTimes(1);+ expect(first).toHaveBeenCalledTimes(1);+ expect(second).not.toHaveBeenCalled();+ });+it('dedupes concurrent loads of the same font (one load, both onReady fire)', async () => {const { api, load, settle } = createFakeFonts(false);const loader = createFontLoader(api);@@ -83,4 +112,322 @@ describe('createFontLoader', () => {expect(() => loader.ensure('garbage', vi.fn())).not.toThrow();expect(api.load).toHaveBeenCalledTimes(1);});++ it('passes the stable reference and exact typography coordinates to the custom runtime', async () => {+ let resolveEnsure!: (family: string) => void;+ const runtime: CanvasFontRuntime = {+ ensure: vi.fn(+ () =>+ new Promise<string>((resolve) => {+ resolveEnsure = resolve;+ })+ ),+ ensureForOutput: vi.fn(() => Promise.resolve('internal-font-family')),+ resolveFamily: vi.fn(() => 'internal-font-family'),+ };+ const loader = createFontLoader(runtime);+ const onReady = vi.fn();++ loader.ensure(customText, onReady);++ expect(loader.resolveFamily(customText)).toBe('internal-font-family');+ expect(runtime.ensure).toHaveBeenCalledWith(+ {+ axes: { opsz: 14, wght: 612 },+ contentHash: 'hash-1',+ family: 'Catalog Family',+ id: 'font-1',+ style: 'oblique',+ weight: 612,+ },+ expect.any(AbortSignal)+ );+ resolveEnsure('internal-font-family');+ await flush();+ expect(onReady).toHaveBeenCalledOnce();+ });++ it('keeps a shared preview alive after one caller cancels until its source is superseded', async () => {+ let resolveEnsure!: (family: string) => void;+ let runtimeSignal!: AbortSignal;+ const runtime: CanvasFontRuntime = {+ ensure: vi.fn((_reference, signal?: AbortSignal) => {+ runtimeSignal = signal!;+ return new Promise<string>((resolve) => {+ resolveEnsure = resolve;+ });+ }),+ ensureForOutput: vi.fn(() => Promise.resolve('validated-family')),+ resolveFamily: () => 'fallback',+ };+ const loader = createFontLoader(runtime);+ loader.setActiveSources([customText]);+ const caller = new AbortController();+ const preview = loader.ensurePreview(customText, caller.signal);++ caller.abort();+ await expect(preview).rejects.toMatchObject({ name: 'AbortError' });+ expect(runtimeSignal.aborted).toBe(false);++ loader.setActiveSources([]);+ expect(runtimeSignal.aborted).toBe(true);+ resolveEnsure('obsolete-family');+ loader.dispose();+ });++ it('cancels an obsolete preview without allowing its late completion to notify', async () => {+ let resolveEnsure!: (family: string) => void;+ let runtimeSignal!: AbortSignal;+ const runtime: CanvasFontRuntime = {+ ensure: vi.fn((_reference, signal?: AbortSignal) => {+ runtimeSignal = signal!;+ return new Promise<string>((resolve) => {+ resolveEnsure = resolve;+ });+ }),+ ensureForOutput: vi.fn(() => Promise.resolve('validated-family')),+ resolveFamily: () => 'fallback',+ };+ const loader = createFontLoader(runtime);+ const onReady = vi.fn();+ loader.setActiveSources([customText]);+ loader.ensure(customText, onReady);+ loader.setActiveSources([]);+ expect(runtimeSignal.aborted).toBe(true);+ resolveEnsure('late-family');+ await flush();+ expect(onReady).not.toHaveBeenCalled();+ loader.dispose();+ });++ it('does not fence a ready result when the runtime announces ordinary loading state', async () => {+ let notifyRuntime!: () => void;+ let resolvedFamily = 'fallback';+ const runtime: CanvasFontRuntime = {+ ensure: vi.fn(() => {+ notifyRuntime();+ resolvedFamily = 'internal-font-family';+ return Promise.resolve('internal-font-family');+ }),+ ensureForOutput: vi.fn(() => Promise.resolve('internal-font-family')),+ getSnapshot: () => ({ generation: 0 }),+ resolveFamily: () => resolvedFamily,+ subscribe: (listener) => {+ notifyRuntime = listener;+ return () => undefined;+ },+ };+ const loader = createFontLoader(runtime);+ const onReady = vi.fn();+ loader.ensure(customText, onReady);+ await flush();+ expect(onReady).toHaveBeenCalledOnce();+ loader.ensure(customText, onReady);+ await flush();+ expect(onReady).toHaveBeenCalledOnce();+ });++ it('reloads a custom preview after the runtime evicts its cached family', async () => {+ let resolvedFamily = 'fallback';+ const runtime: CanvasFontRuntime = {+ ensure: vi.fn(() => {+ resolvedFamily = 'loaded-family';+ return Promise.resolve(resolvedFamily);+ }),+ ensureForOutput: vi.fn(() => Promise.resolve('validated-family')),+ getSnapshot: () => ({ generation: 0 }),+ resolveFamily: () => resolvedFamily,+ };+ const loader = createFontLoader(runtime);+ loader.setActiveSources([customText]);++ await expect(loader.ensurePreview(customText)).resolves.toBe('loaded-family');+ expect(runtime.ensure).toHaveBeenCalledOnce();++ // Runtime LRU eviction removes its browser alias without changing the+ // account generation. A later preview must consult that authoritative+ // resolver instead of trusting the loader's stale ready entry.+ resolvedFamily = 'fallback';+ await expect(loader.ensurePreview(customText)).resolves.toBe('loaded-family');+ expect(runtime.ensure).toHaveBeenCalledTimes(2);+ loader.dispose();+ });++ it('shares custom-face readiness with output gating and subscriptions', async () => {+ let resolveOutput!: (family: string) => void;+ const runtime: CanvasFontRuntime = {+ ensure: vi.fn(() => Promise.resolve('preview-family')),+ ensureForOutput: vi.fn(+ () =>+ new Promise<string>((resolve) => {+ resolveOutput = resolve;+ })+ ),+ resolveFamily: () => 'fallback',+ };+ const loader = createFontLoader(runtime);+ const notified = vi.fn();+ loader.subscribe(notified);++ const ready = loader.waitForReady(customText);+ expect(runtime.ensureForOutput).toHaveBeenCalledOnce();+ resolveOutput('internal-font-family');+ await expect(ready).resolves.toBe('internal-font-family');+ expect(notified).toHaveBeenCalled();+ });++ it('keeps document-active custom faces registered and releases obsolete variations', async () => {+ const release = vi.fn();+ const runtime: CanvasFontRuntime = {+ ensure: vi.fn(() => Promise.resolve('internal-font-family')),+ ensureForOutput: vi.fn(() => Promise.resolve('internal-font-family')),+ retain: vi.fn(() => release),+ resolveFamily: vi.fn(() => 'internal-font-family'),+ };+ const loader = createFontLoader(runtime);+ loader.setActiveSources([customText]);++ await expect(loader.waitForReady(customText)).resolves.toBe('internal-font-family');+ expect(runtime.retain).toHaveBeenCalledWith({+ axes: { opsz: 14, wght: 612 },+ contentHash: 'hash-1',+ family: 'Catalog Family',+ id: 'font-1',+ style: 'oblique',+ weight: 612,+ });+ const nextText = { ...customText, fontVariations: { opsz: 16, wght: 612 } };+ loader.setActiveSources([nextText]);+ expect(release).toHaveBeenCalledOnce();+ loader.dispose();+ expect(release).toHaveBeenCalledOnce();+ });++ it('revalidates a cached custom face for each output readiness check', async () => {+ const runtime: CanvasFontRuntime = {+ ensure: vi+ .fn()+ .mockResolvedValueOnce('internal-font-family')+ .mockRejectedValueOnce(new Error('font was deleted')),+ ensureForOutput: vi+ .fn()+ .mockResolvedValueOnce('internal-font-family')+ .mockRejectedValueOnce(new Error('font was deleted')),+ resolveFamily: () => 'internal-font-family',+ };+ const loader = createFontLoader(runtime);+ loader.setActiveSources([customText]);++ await expect(loader.waitForReady(customText)).resolves.toBe('internal-font-family');+ await expect(loader.waitForReady(customText)).rejects.toThrow('font was deleted');+ expect(runtime.ensureForOutput).toHaveBeenCalledTimes(2);+ });++ it('uses the runtime output check instead of the preview cache', async () => {+ const runtime: CanvasFontRuntime = {+ ensure: vi.fn().mockResolvedValue('cached-family'),+ ensureForOutput: vi.fn().mockRejectedValue(new Error('font metadata changed')),+ resolveFamily: () => 'cached-family',+ };+ const loader = createFontLoader(runtime);++ await expect(loader.waitForReady(customText)).rejects.toThrow('font metadata changed');+ expect(runtime.ensure).not.toHaveBeenCalled();+ expect(runtime.ensureForOutput).toHaveBeenCalledOnce();+ });++ it('does not reuse an in-flight preview request for output readiness', async () => {+ let resolvePreview!: (family: string) => void;+ const runtime: CanvasFontRuntime = {+ ensure: vi.fn(+ () =>+ new Promise<string>((resolve) => {+ resolvePreview = resolve;+ })+ ),+ ensureForOutput: vi.fn().mockResolvedValue('validated-family'),+ resolveFamily: () => 'fallback',+ };+ const loader = createFontLoader(runtime);++ loader.ensure(customText, vi.fn());+ await expect(loader.waitForReady(customText)).resolves.toBe('validated-family');+ expect(runtime.ensureForOutput).toHaveBeenCalledOnce();+ expect(runtime.ensure).toHaveBeenCalledOnce();+ resolvePreview('preview-family');+ });++ it('notifies subscribers when a runtime without its own event stream reports an error', async () => {+ const runtime: CanvasFontRuntime = {+ ensure: vi.fn().mockRejectedValue(new Error('font unavailable')),+ ensureForOutput: vi.fn().mockRejectedValue(new Error('font unavailable')),+ resolveFamily: () => 'fallback',+ };+ const loader = createFontLoader(runtime);+ const notified = vi.fn();+ loader.subscribe(notified);++ await expect(loader.waitForReady(customText)).rejects.toThrow('font unavailable');+ expect(notified).toHaveBeenCalledOnce();+ });++ it('fails closed for a legacy custom runtime without output revalidation', async () => {+ const runtime = {+ ensure: vi.fn().mockResolvedValue('legacy-family'),+ resolveFamily: () => 'legacy-family',+ } as unknown as CanvasFontRuntime;+ const loader = createFontLoader(runtime);++ await expect(loader.waitForReady(customText)).rejects.toThrow('output validation');+ expect(runtime.ensure).not.toHaveBeenCalled();+ });++ it('fails closed for a custom reference when no runtime is available', async () => {+ const loader = createFontLoader(null);+ await expect(loader.waitForReady(customText)).rejects.toThrow('custom Canvas font runtime');+ const onReady = vi.fn();+ loader.ensure(customText, onReady);+ await flush();+ expect(onReady).not.toHaveBeenCalled();+ });++ it('fences a stale custom load after the runtime invalidates its account scope', async () => {+ let invalidate!: () => void;+ const resolves: Array<(family: string) => void> = [];+ const release = vi.fn();+ const runtime: CanvasFontRuntime = {+ ensure: vi.fn(+ () =>+ new Promise<string>((resolve) => {+ resolves.push(resolve);+ })+ ),+ ensureForOutput: vi.fn(+ () =>+ new Promise<string>((resolve) => {+ resolves.push(resolve);+ })+ ),+ retain: vi.fn(() => release),+ resolveFamily: vi.fn(() => 'internal-font-family'),+ subscribe: vi.fn((listener) => {+ invalidate = listener;+ return () => undefined;+ }),+ };+ const loader = createFontLoader(runtime);+ loader.setActiveSources([customText]);+ const first = loader.waitForReady(customText);++ invalidate();+ const second = loader.waitForReady(customText);+ resolves[0]!('stale-family');+ await expect(first).resolves.toBe('stale-family');+ expect(runtime.retain).not.toHaveBeenCalled();++ resolves[1]!('current-family');+ await expect(second).resolves.toBe('current-family');+ expect(runtime.retain).toHaveBeenCalledOnce();+ loader.dispose();+ });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.tsindex 5d5759aaf9..3e75e321b7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.ts@@ -1,28 +1,18 @@/**- * Web-font readiness for text layers.+ * The Canvas-owned font boundary.*- * A text layer's rasterized metrics depend on the font actually being available:- * if a web font isn't loaded yet, the platform substitutes a fallback and- * `measureText` reports the WRONG advances, so the cached text pixels (and the- * layer's extent) would be wrong until something else happened to re-rasterize.- *- * This loader is the seam the engine uses to fix that without importing the DOM- * into the rasterizer: given a `FontLoadApi` (the browser's `document.fonts`, or- * a fake in tests), it kicks a load for a not-yet-available font exactly once- * (concurrent requests for the same font string share one in-flight promise) and- * invokes `onReady` when it resolves — the engine's callback re-rasterizes the- * affected layer. A `null` api (node, or a browser without `document.fonts`) is- * a silent no-op, so importing this module and the engine stays node-safe.- *- * The loader holds NO permanent "loaded" set — it trusts `api.check()` (the- * browser flips it to `true` post-load) as the source of truth and only tracks- * in-flight promises (cleared on settle). Combined with the per-engine instance,- * that keeps it free of cross-test global state.+ * Built-in CSS families continue to use the small `FontFaceSet` slice below.+ * The application can inject its account-scoped custom-font runtime without+ * making the Canvas engine import feature code. Custom sources are translated+ * into the runtime's stable reference plus their exact style, weight, and axis+ * coordinates; the runtime owns the browser-only family alias.** Zero React, zero import-time side effects.*/-/** The minimal slice of `FontFaceSet` the loader needs (so tests can inject a fake). */+import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';++/** A CSS `font` shorthand readiness API, normally backed by `document.fonts`. */export interface FontLoadApi {/** Whether every face for the CSS `font` shorthand is loaded and usable. */check(font: string): boolean;@@ -30,15 +20,59 @@ export interface FontLoadApi {load(font: string): Promise<unknown>;}-/** A per-engine font loader bound to one `FontLoadApi` (or `null` in node). */-export interface FontLoader {+/** The optional fields accepted by the feature font runtime. */+export interface CanvasFontReference {+ id: string;+ contentHash?: string | null;+ family?: string;+ style?: string;+ weight?: number;+ axes?: Readonly<Record<string, number>>;+}++/**+ * Application-owned custom-font runtime. It is intentionally structural so+ * Canvas stays below feature composition and remains usable in node tests.+ */+export interface CanvasFontRuntime {+ /** Ensures the exact static face/instance is loaded and returns its browser family alias. */+ ensure(reference: CanvasFontReference, signal?: AbortSignal): Promise<string>;/**- * Ensures `font` is available, invoking `onReady` once when a pending load- * resolves. A no-op (never calls `onReady`) when there is no api or the font- * is already available — the caller's synchronous rasterize already used the- * correct metrics in that case.+ * Revalidates the exact face against the current account/catalog state before+ * an exported or generated output is allowed to use it. Preview ensures may+ * serve the browser registry cache; output checks must be able to reject a+ * deleted or changed resource even when that cache still has an alias.*/- ensure(font: string, onReady: () => void): void;+ ensureForOutput(reference: CanvasFontReference, signal?: AbortSignal): Promise<string>;+ /** Keeps the loaded face registered while this engine has a live text consumer. */+ retain?(reference: CanvasFontReference): () => void;+ /** Optional generation that changes when account scope cleanup removes registered faces. */+ getSnapshot?(): { generation: number };+ /** Returns the already-registered browser family alias, or the readable fallback family. */+ resolveFamily(reference: CanvasFontReference): string;+ /** Optional readiness/account-lifecycle notifications for editor overlays. */+ subscribe?(listener: () => void): () => void;+}++/** A text source, kept local to avoid importing the rasterizer into this seam. */+export type CanvasTextSource = Extract<CanvasLayerSourceContract, { type: 'text' }>;++/** The per-engine adapter used by layer rasterization and editor overlays. */+export interface FontLoader {+ /** Ensures a legacy CSS shorthand or source-aware custom face is ready. */+ ensure(font: string, onReady: () => void, signal?: AbortSignal): void;+ ensure(source: CanvasTextSource, onReady: () => void, signal?: AbortSignal): void;+ /** Ensures an active editor/raster preview while keeping the shared request alive. */+ ensurePreview(source: CanvasTextSource, signal?: AbortSignal): Promise<string>;+ /** Resolves the family passed to both CanvasRenderingContext2D and CSS. */+ resolveFamily(source: CanvasTextSource): string;+ /** Updates the long-lived document/session sources that must keep custom faces registered. */+ setActiveSources(sources: readonly CanvasTextSource[]): void;+ /** Waits for a source before operations whose output must use final font metrics. */+ waitForReady(source: CanvasTextSource, signal?: AbortSignal): Promise<string>;+ subscribe(listener: () => void): () => void;+ /** Stops callbacks owned by this engine; the application runtime remains app-owned. */+ dispose(): void;}/** `check` can throw on an unparseable font string; treat a throw as "not available". */@@ -50,32 +84,421 @@ const safeCheck = (api: FontLoadApi, font: string): boolean => {}};-/** Creates a font loader bound to `api` (pass `null` for a node-safe no-op loader). */-export const createFontLoader = (api: FontLoadApi | null): FontLoader => {- const pending = new Map<string, Promise<void>>();+const createAbortError = (): Error => {+ if (typeof DOMException !== 'undefined') {+ return new DOMException('The Canvas font preview was aborted.', 'AbortError');+ }+ const error = new Error('The Canvas font preview was aborted.');+ error.name = 'AbortError';+ return error;+};++/** Gives one caller cancellation without aborting the shared request. */+const withAbortSignal = <T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> => {+ if (!signal) {+ return promise;+ }+ const getReason = (): unknown => signal.reason ?? createAbortError();+ if (signal.aborted) {+ return Promise.reject(getReason());+ }+ return new Promise<T>((resolve, reject) => {+ const onAbort = (): void => {+ signal.removeEventListener('abort', onAbort);+ reject(getReason());+ };+ signal.addEventListener('abort', onAbort, { once: true });+ promise.then(+ (value) => {+ signal.removeEventListener('abort', onAbort);+ resolve(value);+ },+ (error: unknown) => {+ signal.removeEventListener('abort', onAbort);+ reject(error);+ }+ );+ });+};++const isCanvasFontRuntime = (value: FontLoadApi | CanvasFontRuntime): value is CanvasFontRuntime =>+ typeof (value as CanvasFontRuntime).ensure === 'function' &&+ typeof (value as CanvasFontRuntime).resolveFamily === 'function' &&+ typeof (value as FontLoadApi).check !== 'function';+const sourceReference = (source: CanvasTextSource): CanvasFontReference | null => {+ if (!source.fontRef) {+ return null;+ }return {- ensure: (font, onReady) => {- if (!api || safeCheck(api, font)) {- return;+ axes: source.fontVariations,+ contentHash: source.fontRef.contentHash,+ family: source.fontRef.family || source.fontFamily,+ id: source.fontRef.id,+ style: source.fontStyle ?? 'normal',+ weight: source.fontWeight,+ };+};++const variationKey = (axes: CanvasTextSource['fontVariations']): string =>+ Object.entries(axes ?? {})+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([tag, value]) => `${tag}:${value}`)+ .join(',');++const sourceKey = (source: CanvasTextSource): string => {+ const ref = sourceReference(source);+ if (!ref) {+ return `css:${source.fontStyle ?? 'normal'} ${source.fontWeight} ${source.fontSize}px ${source.fontFamily}`;+ }+ return [+ ref.id,+ ref.contentHash ?? '',+ ref.family ?? '',+ ref.style ?? '',+ ref.weight ?? '',+ variationKey(ref.axes),+ ].join('|');+};++/** Creates a font loader bound to a legacy API or an application custom-font runtime. */+export const createFontLoader = (api: FontLoadApi | CanvasFontRuntime | null): FontLoader => {+ const cssApi = api && isCanvasFontRuntime(api) ? domFontLoadApi() : api;+ const pending = new Map<string, Promise<string>>();+ const previewControllers = new Map<string, AbortController>();+ const ready = new Map<string, string>();+ const leases = new Map<string, () => void>();+ const activeReferences = new Map<string, CanvasFontReference>();+ const listeners = new Set<() => void>();+ let disposed = false;+ let generation = 0;+ let runtimeSnapshotGeneration = api && isCanvasFontRuntime(api) ? api.getSnapshot?.().generation : undefined;++ const notify = (): void => {+ if (disposed) {+ return;+ }+ for (const listener of listeners) {+ listener();+ }+ };+ const cancelPendingPreviews = (): void => {+ for (const controller of previewControllers.values()) {+ controller.abort(createAbortError());+ }+ previewControllers.clear();+ };++ const releaseLease = (key: string): void => {+ const release = leases.get(key);+ if (!release) {+ return;+ }+ release();+ leases.delete(key);+ };++ const invalidateEvictedReady = (): void => {+ if (!api || !isCanvasFontRuntime(api)) {+ return;+ }+ for (const [key, reference] of activeReferences) {+ const cached = ready.get(key);+ if (cached !== undefined && api.resolveFamily(reference) !== cached) {+ ready.delete(key);+ releaseLease(key);}- const existing = pending.get(font);+ }+ };+ const runtimeUnsubscribe =+ api && isCanvasFontRuntime(api)+ ? api.subscribe?.(() => {+ const nextGeneration = api.getSnapshot?.().generation;+ const generationChanged = nextGeneration === undefined || nextGeneration !== runtimeSnapshotGeneration;+ runtimeSnapshotGeneration = nextGeneration ?? runtimeSnapshotGeneration;+ // The runtime owns account lifecycle and may remove every registered+ // face at once. A runtime without a generation API is treated as a+ // coarse lifecycle boundary for compatibility; runtimes with a+ // generation leave ordinary loading/ready notifications alone.+ if (generationChanged) {+ generation += 1;+ cancelPendingPreviews();+ for (const release of leases.values()) {+ release();+ }+ leases.clear();+ ready.clear();+ } else {+ invalidateEvictedReady();+ }+ notify();+ })+ : undefined;++ const retainActive = (key: string, reference: CanvasFontReference): void => {+ if (!activeReferences.has(key) || leases.has(key) || !api || !isCanvasFontRuntime(api) || !api.retain) {+ return;+ }+ leases.set(key, api.retain(reference));+ };++ const setActiveSources = (sources: readonly CanvasTextSource[]): void => {+ const next = new Map<string, CanvasFontReference>();+ for (const source of sources) {+ const reference = sourceReference(source);+ if (reference) {+ next.set(`runtime:${sourceKey(source)}`, reference);+ }+ }+ for (const [key, controller] of previewControllers) {+ if (!next.has(key)) {+ controller.abort(createAbortError());+ previewControllers.delete(key);+ pending.delete(key);+ }+ }+ for (const key of leases.keys()) {+ if (!next.has(key)) {+ releaseLease(key);+ }+ }+ for (const key of ready.keys()) {+ if (key.startsWith('runtime:') && !next.has(key)) {+ ready.delete(key);+ }+ }+ activeReferences.clear();+ for (const [key, reference] of next) {+ activeReferences.set(key, reference);+ if (ready.has(key)) {+ retainActive(key, reference);+ }+ }+ };++ const track = (+ key: string,+ load: () => Promise<string>,+ notifyOnResolve = true,+ reference?: CanvasFontReference,+ bypassReady = false,+ controller?: AbortController+ ): { pending: boolean; promise: Promise<string> } => {+ const resolved = ready.get(key);+ if (resolved !== undefined && !bypassReady) {+ return { pending: false, promise: Promise.resolve(resolved) };+ }+ // An output check must not inherit a preview request that started before+ // the operation. That request may have used a cached alias without the+ // fresh metadata/authentication validation required at the output boundary.+ const existing = bypassReady ? undefined : pending.get(key);+ if (existing) {+ return { pending: true, promise: existing };+ }+ let loaded: Promise<string>;+ try {+ loaded = load();+ } catch (error) {+ loaded = Promise.reject(error);+ }+ // A runtime may publish its ordinary `loading` state synchronously from+ // inside ensure(). Capture the fence after that call; a later lifecycle+ // notification still invalidates this request before it can be retained.+ const requestGeneration = generation;+ let promise!: Promise<string>;+ promise = loaded+ .then((value) => {+ if (disposed || requestGeneration !== generation || (!bypassReady && pending.get(key) !== promise)) {+ return value;+ }+ ready.set(key, value);+ if (reference) {+ retainActive(key, reference);+ }+ if (notifyOnResolve) {+ notify();+ }+ return value;+ })+ .catch((error: unknown) => {+ if (+ !disposed &&+ requestGeneration === generation &&+ notifyOnResolve &&+ (bypassReady || pending.get(key) === promise)+ ) {+ if (reference) {+ ready.delete(key);+ releaseLease(key);+ }+ notify();+ }+ throw error;+ })+ .finally(() => {+ if (pending.get(key) === promise) {+ pending.delete(key);+ }+ if (controller && previewControllers.get(key) === controller) {+ previewControllers.delete(key);+ }+ });+ if (!bypassReady) {+ pending.set(key, promise);+ }+ return { pending: true, promise };+ };++ const ensureCss = (font: string): { pending: boolean; promise: Promise<string> } => {+ const key = `css:${font}`;+ if (!cssApi || safeCheck(cssApi, font)) {+ ready.set(key, font);+ return { pending: false, promise: Promise.resolve(font) };+ }+ return track(key, async () => {+ await cssApi.load(font);+ return font;+ });+ };++ const ensureSource = (+ source: CanvasTextSource,+ signal?: AbortSignal,+ preview = true+ ): { pending: boolean; promise: Promise<string> } => {+ const reference = sourceReference(source);+ if (reference && api && isCanvasFontRuntime(api)) {+ const key = `runtime:${sourceKey(source)}`;+ if (preview) {+ const cached = ready.get(key);+ if (cached !== undefined && api.resolveFamily(reference) !== cached) {+ ready.delete(key);+ releaseLease(key);+ }+ }+ const existing = !preview ? undefined : pending.get(key);if (existing) {- existing.then(onReady, () => {});+ const controller = previewControllers.get(key);+ const shared = controller ? withAbortSignal(existing, controller.signal) : existing;+ return { pending: true, promise: withAbortSignal(shared, signal) };+ }+ const controller = preview ? new AbortController() : undefined;+ const result = track(+ key,+ () => (preview ? api.ensure(reference, controller!.signal) : api.ensure(reference, signal)),+ !api.subscribe,+ reference,+ !preview,+ controller+ );+ if (preview && result.pending && controller) {+ previewControllers.set(key, controller);+ }+ if (!preview || !controller) {+ return result;+ }+ const shared = withAbortSignal(result.promise, controller.signal);+ return { ...result, promise: withAbortSignal(shared, signal) };+ }+ if (reference) {+ // A custom reference cannot be made trustworthy by loading the readable+ // family name through document.fonts. Failing closed keeps export and+ // generation output from silently baking fallback glyphs.+ return {+ pending: true,+ promise: Promise.reject(new Error('A custom Canvas font runtime is required for this text source.')),+ };+ }+ const result = ensureCss(textFontShorthand(source));+ return { ...result, promise: withAbortSignal(result.promise, signal) };+ };++ const ensurePreview = (source: CanvasTextSource, signal?: AbortSignal): Promise<string> =>+ ensureSource(source, signal, true).promise;++ return {+ dispose: () => {+ disposed = true;+ generation += 1;+ runtimeUnsubscribe?.();+ cancelPendingPreviews();+ for (const release of leases.values()) {+ release();+ }+ leases.clear();+ activeReferences.clear();+ listeners.clear();+ ready.clear();+ pending.clear();+ },+ ensure: (value: string | CanvasTextSource, onReady: () => void, signal?: AbortSignal) => {+ if (disposed) {+ return;+ }+ const result =+ typeof value === 'string'+ ? (() => {+ const css = ensureCss(value);+ return { ...css, promise: withAbortSignal(css.promise, signal) };+ })()+ : ensureSource(value, signal, true);+ if (!result.pending) {return;}- const promise = Promise.resolve(api.load(font)).then(- () => {},- () => {}+ result.promise.then(+ () => {+ if (!disposed && !signal?.aborted) {+ onReady();+ }+ },+ () => {+ // A failed load leaves fallback pixels in place. An asynchronous+ // raster job must not become an unhandled rejection solely because a+ // face is missing; the UI can retry explicitly.+ });- const tracked = promise.finally(() => pending.delete(font));- pending.set(font, tracked);- tracked.then(onReady, () => {});+ },+ ensurePreview,+ resolveFamily: (source) => {+ const reference = sourceReference(source);+ return reference && api && isCanvasFontRuntime(api) ? api.resolveFamily(reference) : source.fontFamily;+ },+ setActiveSources,+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ waitForReady: (source, signal) => {+ if (disposed) {+ return Promise.reject(new Error('The Canvas font loader has been disposed.'));+ }+ const reference = sourceReference(source);+ if (!reference || !api || !isCanvasFontRuntime(api)) {+ return ensureSource(source, signal).promise;+ }+ if (!api.ensureForOutput) {+ return Promise.reject(new Error('A custom Canvas font runtime needs output validation before export.'));+ }+ const key = `runtime:${sourceKey(source)}`;+ const result = track(key, () => api.ensureForOutput(reference, signal), !api.subscribe, reference, true);+ return result.promise.catch((error: unknown) => {+ // A readiness operation is allowed to discover that an account-scoped+ // face disappeared after rasterization cached its previous alias.+ ready.delete(key);+ releaseLease(key);+ throw error;+ });},};};-/** Resolves the browser's `document.fonts` api, or `null` where it is unavailable (node, older browsers). */+/** The CSS shorthand used for legacy sources and for the FontFaceSet fallback path. */+export const textFontShorthand = (source: CanvasTextSource): string => {+ const style = source.fontStyle && source.fontStyle !== 'normal' ? `${source.fontStyle} ` : '';+ return `${style}${source.fontWeight} ${source.fontSize}px ${source.fontFamily}`;+};++/** Resolves the browser's `document.fonts` api, or `null` where it is unavailable. */export const domFontLoadApi = (): FontLoadApi | null => {if (typeof document === 'undefined') {return null;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.tsindex 0243b4e450..3e5ce11ab1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts@@ -62,6 +62,13 @@ export interface LayerCacheEntry {stale: boolean;/** Monotonic access tick, used to order LRU eviction. */lastUsed: number;+ /**+ * Browser family alias used for the most recent text rasterization. The alias+ * identifies the exact account-scoped face/variation in the Canvas font+ * runtime, so output can reject pixels rendered with a fallback family after+ * the real face becomes available.+ */+ renderedFontFamily?: string;}/**diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.tsindex 0afc11bc9f..e86ce2fdb4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts@@ -11,6 +11,7 @@ import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Mat2d, Rect } from '@workbench/canvas-engine/types';import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';+import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';import { roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import { adjustmentsKey, applyAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';@@ -72,9 +73,20 @@ const isBaseRasterLeaf = (leaf: SemanticLeaf): leaf is SemanticLeaf & { layer: Cif (layer.source.type === 'image') {return true;}- return layer.source.type === 'paint' && layer.source.bitmap !== null;+ if (layer.source.type === 'paint') {+ return layer.source.bitmap !== null;+ }+ return layer.source.type === 'text' && layer.source.content.length > 0;};+/** JSON with recursively sorted object keys, so text edits produce deterministic identities. */+const stableSourceKey = (value: unknown): string =>+ JSON.stringify(value, (_key, entry: unknown) =>+ entry && typeof entry === 'object' && !Array.isArray(entry)+ ? Object.fromEntries(Object.entries(entry).sort(([a], [b]) => (a < b ? -1 : 1)))+ : entry+ );+/** A stable string identifying a source's pixels (its asset name, or an empty sentinel). */const sourceRefOf = (source: CanvasLayerSourceContract): string => {switch (source.type) {@@ -82,6 +94,8 @@ const sourceRefOf = (source: CanvasLayerSourceContract): string => {return `image:${source.image.imageName}`;case 'paint':return source.bitmap ? `paint:${source.bitmap.imageName}` : 'paint:empty';+ case 'text':+ return `text:${stableSourceKey(source)}`;default:return `${source.type}:unsupported`;}@@ -97,6 +111,9 @@ const contentRectOf = (layer: CanvasRasterLayerContractV2, doc: CanvasDocumentCoconst offset = source.offset ?? { x: 0, y: 0 };return { height: source.bitmap.height, width: source.bitmap.width, x: offset.x, y: offset.y };}+ if (source.type === 'text') {+ return getSourceContentRect(layer, doc);+ }return { height: doc.height, width: doc.width, x: 0, y: 0 };};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.tsindex 0f0334b945..8821b108f3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts@@ -27,7 +27,7 @@ export { rasterizeGradientSource } from './gradientRasterizer';export { rasterizeImageSource } from './imageRasterizer';export { rasterizePaintSource } from './paintRasterizer';export { rasterizeShapeSource } from './shapeRasterizer';-export { rasterizeTextSource } from './textRasterizer';+export { rasterizeTextSource, textFontString, textFontVariationSettings } from './textRasterizer';/*** Rasterizes any supported layer source into a surface. Throws only for thediff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.test.tsindex d0556ace40..6f08ecc617 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.test.ts@@ -7,7 +7,13 @@ import { describe, expect, it } from 'vitest';import type { TextSource } from './textRasterizer';import type { RasterizeDeps } from './types';-import { estimateTextExtent, rasterizeTextSource, TEXT_CHAR_WIDTH_FACTOR, textFontString } from './textRasterizer';+import {+ estimateTextExtent,+ rasterizeTextSource,+ TEXT_CHAR_WIDTH_FACTOR,+ textFontString,+ textFontVariationSettings,+} from './textRasterizer';const makeDeps = (): RasterizeDeps => {const backend = createTestStubRasterBackend();@@ -47,6 +53,29 @@ describe('rasterizeTextSource — measurement + extent', () => {expect(surface.height).toBe(Math.ceil(1 * 20 * 1.5)); // one line → 30});+ it('uses the injected runtime family and preserves style and variation coordinates', async () => {+ const deps = { ...makeDeps(), resolveFontFamily: () => '__invoke_font_1' };+ const source = text({+ fontStyle: 'italic',+ fontVariations: { wght: 650, opsz: 14 },+ });+ const surface = (await rasterizeTextSource(source, deps)).surface as StubRasterSurface;++ expect(textFontString(source, '__invoke_font_1')).toBe('italic 400 20px __invoke_font_1');+ expect(textFontVariationSettings(source)).toBe('"opsz" 14, "wght" 650');+ expect(+ surface.callLog.some(+ (entry) => entry.op === 'set' && entry.args[0] === 'font' && entry.args[1] === 'italic 400 20px __invoke_font_1'+ )+ ).toBe(true);+ expect(+ surface.callLog.some(+ (entry) =>+ entry.op === 'set' && entry.args[0] === 'fontVariationSettings' && entry.args[1] === '"opsz" 14, "wght" 650'+ )+ ).toBe(true);+ });+it('agrees with the pure estimateTextExtent (cache-size stability)', async () => {const deps = makeDeps();const source = text({ content: 'abc\ndefgh', fontSize: 16, lineHeight: 1.2 });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.tsindex 7b61f3a805..7b92ddd754 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.ts@@ -1,7 +1,8 @@/*** Rasterizes a `text` layer source. Text layers are PARAMETRIC and* EDITABLE-FOREVER: their pixels are derived from the source params (`content`,- * `fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `align`, `color`) rather+ * `fontFamily`, `fontSize`, `fontWeight`, `fontStyle`, `fontVariations`,+ * `lineHeight`, `align`, `color`) rather* than a persisted bitmap, so a style/content edit re-renders for free — the* headline upgrade over legacy's rasterized (frozen) text.*@@ -45,9 +46,18 @@ type Ctx = RasterSurface['ctx'];*/export const TEXT_CHAR_WIDTH_FACTOR = 0.6;-/** The CSS `font` shorthand for a text source (`"<weight> <size>px <family>"`). */-export const textFontString = (source: TextSource): string =>- `${source.fontWeight} ${source.fontSize}px ${source.fontFamily}`;+/** The CSS `font` shorthand for a text source (`"<style> <weight> <size>px <family>"`). */+export const textFontString = (source: TextSource, family = source.fontFamily): string => {+ const style = source.fontStyle && source.fontStyle !== 'normal' ? `${source.fontStyle} ` : '';+ return `${style}${source.fontWeight} ${source.fontSize}px ${family}`;+};++/** A stable CSS/OpenType representation of the exact coordinates carried by a text source. */+export const textFontVariationSettings = (source: TextSource): string =>+ Object.entries(source.fontVariations ?? {})+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([tag, value]) => `"${tag}" ${value}`)+ .join(', ');/** Splits a text source's content into lines on `\n`; always at least one (possibly empty) line. */export const textLines = (content: string): string[] => content.split('\n');@@ -95,11 +105,15 @@ export const rasterizeTextSource = (target?: RasterSurface): Promise<RasterizeResult> => {const lines = textLines(source.content);- const font = textFontString(source);+ const font = textFontString(source, deps.resolveFontFamily?.(source));+ const context = (ctx: Ctx): Ctx & { fontVariationSettings?: string } =>+ ctx as Ctx & { fontVariationSettings?: string };+ const variationSettings = textFontVariationSettings(source);// Measure on the target's own ctx (or a fresh surface) with the font applied.const surface = target ?? deps.backend.createSurface(1, 1);surface.ctx.font = font;+ context(surface.ctx).fontVariationSettings = variationSettings || 'normal';const { height, width } = measureBlock(surface.ctx, source, lines);if (surface.width !== width || surface.height !== height) {@@ -111,6 +125,7 @@ export const rasterizeTextSource = (ctx.setTransform(1, 0, 0, 1, 0, 0);ctx.clearRect(0, 0, width, height);ctx.font = font;+ context(ctx).fontVariationSettings = variationSettings || 'normal';ctx.textBaseline = 'top';ctx.fillStyle = source.color;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/types.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/types.tsindex 1e71ad666e..0173b6b0c1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/types.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/types.ts@@ -6,6 +6,7 @@* cycle. Zero React, zero side effects.*/+import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { DecodedBitmapPool } from '@workbench/canvas-engine/render/decodedBitmapPool';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';@@ -19,6 +20,9 @@ import type { Rect } from '@workbench/canvas-engine/types';*/export type ImageResolver = (imageName: string, signal?: AbortSignal) => Promise<Blob>;+/** A text source whose family may be replaced by an injected custom-font alias. */+export type RasterizeTextSource = Extract<CanvasLayerSourceContract, { type: 'text' }>;+/*** The result of rasterizing a source: the surface holding its pixels plus the* content `rect` those pixels occupy in the layer's LOCAL coordinate space. For@@ -42,6 +46,8 @@ export interface RasterizeDeps {store: LayerCacheStore;/** Coalesces concurrent decodes and owns decoded pixels only for the duration of a rasterization. */bitmapPool?: DecodedBitmapPool;+ /** Resolves a stable persisted face to the runtime family used for this render. */+ resolveFontFamily?: (source: RasterizeTextSource) => string;/*** Document pixel size. Layers are content-sized, so this only backs the* legacy default for gradients that predate the explicit extent field (theydiff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.tsindex c3ecea8510..1d18f47a02 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts@@ -194,11 +194,33 @@ const setTransform = (ctx: Ctx, m: Mat2d): void => {* Union of a plan's base-raster content bounds in document space, or `null`* when the plan has no enabled raster content. Pure geometry (no pixels, no* upload), so the invoke orchestrator can run it as a bounds-only pre-pass to- * decide txt2img (no bbox overlap) *before* paying for a composite/encode/upload.+ * decide txt2img (no bbox overlap) before paying for a composite/encode/upload.+ * When `actualLayerRects` is supplied, those detached cache rects replace the+ * planner's estimates for sources whose browser metrics can differ from their+ * DOM-free extent.*/-export const computeCompositeContentBounds = (plan: CompositePlan): Rect | null => {+export const computeCompositeContentBounds = (+ plan: CompositePlan,+ actualLayerRects?: ReadonlyMap<string, Rect>+): Rect | null => {const entry = plan.entries.find((e) => e.kind === 'base-raster');- return entry ? getCompositeLayerBounds(entry.layers) : null;+ if (!entry) {+ return null;+ }+ if (!actualLayerRects || actualLayerRects.size === 0) {+ return getCompositeLayerBounds(entry.layers);+ }+ const layers = entry.layers.map((layer) => {+ const rect = actualLayerRects.get(layer.id);+ return rect+ ? {+ ...layer,+ contentOffset: { x: rect.x, y: rect.y },+ contentSize: { height: rect.height, width: rect.width },+ }+ : layer;+ });+ return getCompositeLayerBounds(layers);};/** True when every pixel of `imageData` is fully opaque (alpha === 255). Empty → false. */diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.tsindex 1126305052..fdbb43753d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts@@ -31,6 +31,36 @@ const rasterLayer = (id: string, size = 64): CanvasRasterLayerContractV2 => ({type: 'raster',});+const textLayer = (id: string, overrides: Partial<CanvasRasterLayerContractV2> = {}): CanvasRasterLayerContractV2 => ({+ ...rasterLayer(id),+ source: {+ align: 'left',+ color: '#ffffff',+ content: 'hello',+ fontFamily: 'Inter',+ fontSize: 32,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ ...overrides,+});++const customTextLayer = (id: string): CanvasRasterLayerContractV2 =>+ textLayer(id, {+ source: {+ align: 'left',+ color: '#ffffff',+ content: 'hello',+ fontFamily: 'Custom Sans',+ fontRef: { contentHash: 'hash-v1', family: 'Custom Sans', id: 'font-1', label: 'Custom Sans' },+ fontSize: 32,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ });+const controlLayer = (id: string): CanvasControlLayerContract => ({adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 0.75 },blendMode: 'normal',@@ -120,6 +150,7 @@ interface HostHarness {interface HostOptions {alpha?: number;+ layerRects?: Readonly<Record<string, Rect>>;uploadImage?: (blob: Blob) => Promise<CanvasImageUploadResult>;}@@ -157,12 +188,13 @@ const makeHost = (document: CanvasDocumentContractV3, options: HostOptions = {})const detached = new Map<string, { rect: Rect; surface: RasterSurface }>();for (const layerId of layerIds) {surfaceIds.push(layerId);+ const rect = options.layerRects?.[layerId] ?? { height: 64, width: 64, x: 0, y: 0 };let surface = layerSurfaces.get(layerId);if (!surface) {- surface = stub.createSurface(64, 64);+ surface = stub.createSurface(rect.width, rect.height);layerSurfaces.set(layerId, surface);}- detached.set(layerId, { rect: { height: 64, width: 64, x: 0, y: 0 }, surface });+ detached.set(layerId, { rect, surface });}return Promise.resolve({snapshot: {@@ -322,6 +354,61 @@ describe('composeForGeneration', () => {expect(result.composites.bbox).toEqual({ height: 64, width: 64, x: 0, y: 0 });});+ it('uses captured custom-text bounds when browser metrics exceed the pure estimate', async () => {+ const text = customTextLayer('text');+ const document = {+ ...makeDoc([text]),+ // The estimate is 60px wide, so this bbox only edge-touches it. The+ // captured surface below is 100px wide, representing a wider loaded face.+ bbox: { height: 32, width: 4, x: 60, y: 0 },+ };+ const harness = makeHost(document, { layerRects: { text: { height: 32, width: 100, x: 0, y: 0 } } });+ const detectMode = vi.fn(() => 'img2img' as const);++ const result = await compose(harness.host, { detectMode });++ expect(result.status).toBe('ok');+ expect(detectMode).toHaveBeenCalledWith(+ expect.objectContaining({+ bbox: { height: 32, width: 4, x: 60, y: 0 },+ contentBounds: { height: 32, width: 100, x: 0, y: 0 },+ })+ );+ expect(harness.uploadImage).toHaveBeenCalledOnce();+ });++ it('requests custom text from raster capture and composites the authorized pixels', async () => {+ const text = customTextLayer('text');+ const harness = makeHost(makeDoc([text]));+ const captureRasterSnapshot = vi.fn(harness.host.captureRasterSnapshot);+ harness.host.captureRasterSnapshot = captureRasterSnapshot;++ const result = await compose(harness.host);+ expect(result.status).toBe('ok');+ expect(captureRasterSnapshot).toHaveBeenCalledWith(+ expect.any(Object),+ ['text'],+ expect.objectContaining({ signal: expect.any(AbortSignal) })+ );+ expect(harness.surfaceIds).toContain('text');+ expect(harness.uploadImage).toHaveBeenCalledOnce();+ if (result.status === 'ok') {+ expect(result.composites.mode).toBe('img2img');+ expect(result.composites.baseImageName).toBe('composite-1.png');+ }+ });++ it('fails closed when raster capture cannot authorize a custom text font', async () => {+ const text = customTextLayer('text');+ const harness = makeHost(makeDoc([text]));+ harness.host.captureRasterSnapshot = vi.fn(() => Promise.resolve({ status: 'not-ready' as const }));++ const result = await compose(harness.host);++ expect(result).toEqual({ status: 'not-ready' });+ expect(harness.uploadImage).not.toHaveBeenCalled();+ });+it('executes the inpaint mask before consulting detectMode and reports its coverage', async () => {const harness = makeHost(makeDoc([rasterLayer('base'), inpaintMaskLayer('mask')]));const detectMode = vi.fn((facts: GenerationModeFacts) => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.tsindex d068aed634..da571ff4b2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts@@ -167,6 +167,9 @@ export const composeForGeneration = async (if (!documentSnapshot) {return { status: 'no-document' };}+ if (options.signal.aborted) {+ return { status: 'aborted' };+ }const document = documentSnapshot.canvas.document;const bbox = document.bbox;@@ -196,6 +199,14 @@ export const composeForGeneration = async (}const rasterSnapshot = capture.snapshot;+ // A test/fallback host may resolve capture despite an already-aborted signal;+ // preserve the no-pixel-output guarantee and release that caller-owned+ // snapshot before returning.+ if (options.signal.aborted) {+ rasterSnapshot.release();+ return { status: 'aborted' };+ }+// Operation-scoped dedupe: composites read/write a copy. Publication remains// provisional until the caller successfully compiles and dispatches.const operationDedupe: CompositeDedupeCache = {@@ -228,7 +239,14 @@ export const composeForGeneration = async (// overlap the bbox is txt2img no matter the coverage. Also naturally skips a// zero-area bbox (`intersect` is null for empty rects). `intersect`'s strict// overlap matches generation's `rectsIntersect` (flush edges don't count).- const contentBounds = computeCompositeContentBounds(plan);+ // The planner uses a DOM-free text extent estimate. Once capture has run,+ // the detached surfaces provide actual measured rects, so a wide loaded+ // font cannot be omitted from generation because its estimate was narrow.+ const actualLayerRects = new Map<string, Rect>();+ for (const [layerId, detached] of rasterSnapshot.layerSurfaces) {+ actualLayerRects.set(layerId, detached.rect);+ }+ const contentBounds = computeCompositeContentBounds(plan, actualLayerRects);let mode: GenerationCompositeMode = 'txt2img';let baseImageName: string | null = null;@@ -249,7 +267,7 @@ export const composeForGeneration = async (mode = options.detectMode({bbox,bboxFullyCovered: result.bboxFullyCovered,- contentBounds: result.contentBounds,+ contentBounds,hasActiveInpaintMask: maskResult?.hasContent ?? false,});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.tsindex 7687f228c1..0892f75ced 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.ts@@ -37,6 +37,21 @@ const rasterLayer = (...overrides,});+const textLayer = (id: string, overrides: Partial<CanvasRasterLayerContractV2> = {}): CanvasRasterLayerContractV2 =>+ rasterLayer(id, {+ source: {+ align: 'left',+ color: '#ffffff',+ content: 'hello',+ fontFamily: 'Inter',+ fontSize: 20,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ ...overrides,+ });+const maskLayer = (id: string): CanvasLayerContract => ({autoNegative: false,blendMode: 'normal',@@ -125,6 +140,72 @@ describe('planComposites — plan shape', () => {expect(paint!.contentOffset).toEqual({ x: 40, y: 25 });});+ it('includes committed text with its estimated content rect and complete source identity', () => {+ const doc = makeDoc([textLayer('text')]);+ const entry = planComposites(doc, BBOX).entries[0]!;+ expect(entry.layers.map((layer) => layer.id)).toEqual(['text']);+ expect(entry.layers[0]!.sourceRef).toContain('text:');+ expect(entry.layers[0]!.contentSize).toEqual({ height: 24, width: 60 });++ const edited = makeDoc([+ textLayer('text', {+ source: {+ align: 'left',+ color: '#ffffff',+ content: 'edited text',+ fontFamily: 'Inter',+ fontSize: 20,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ }),+ ]);+ expect(planComposites(edited, BBOX).entries[0]!.key).not.toBe(entry.key);+ });++ it('keeps custom text in z-order over image content and keys the exact font reference', () => {+ const fontRef = { contentHash: 'font-hash-v1', family: 'Studio Sans', id: 'font-studio', label: 'Studio Sans' };+ const doc = makeDoc([+ textLayer('text', {+ source: {+ align: 'left',+ color: '#fff',+ content: 'hello',+ fontFamily: 'Studio Sans',+ fontRef,+ fontSize: 20,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ }),+ rasterLayer('image'),+ ]);+ const entry = planComposites(doc, BBOX).entries[0]!;+ expect(entry.layers.map((layer) => layer.id)).toEqual(['text', 'image']);+ expect(entry.layers[0]!.contentSize).toEqual({ height: 24, width: 60 });+ expect(entry.layers[0]!.sourceRef).toContain(JSON.stringify(fontRef.id));++ const changedReference = makeDoc([+ textLayer('text', {+ source: {+ align: 'left',+ color: '#fff',+ content: 'hello',+ fontFamily: 'Studio Sans',+ fontRef: { ...fontRef, contentHash: 'font-hash-v2' },+ fontSize: 20,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ }),+ rasterLayer('image'),+ ]);+ expect(planComposites(changedReference, BBOX).entries[0]!.key).not.toBe(entry.key);+ });+it('excludes an empty (bitmap: null) paint layer so it cannot force outpaint', () => {// An auto-created paint layer left blank (e.g. its stroke was undone) carries// no pixels; including it would inject a doc-sized transparent rect that readsdiff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.tsindex 47e9fbc882..368e09cede 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts@@ -1,5 +1,6 @@import type { CanvasEngine, ImageResolver } from '@workbench/canvas-engine/api';+import { useFontRuntime } from '@features/fonts/react';import { galleryImageUrls } from '@features/gallery/utility';import { getModelsSnapshot } from '@features/models';import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';@@ -59,6 +60,7 @@ export const createCanvasEngineResource = (projectId: string, deps: EngineDeps):/** Returns the active project's shared engine through a balanced registry lease. */export const useCanvasEngine = (): CanvasEngineHandle | null => {+ const fonts = useFontRuntime();const store = useWorkbenchInternalStore();const { notifications } = useWorkbenchCommands();const projectId = useActiveProjectId();@@ -77,10 +79,11 @@ export const useCanvasEngine = (): CanvasEngineHandle | null => {setSelectedLayerIds: (primaryId, selectedIds) =>publishLayerPanelSelection({ primaryId, projectId, selectedIds }),imageResolver: createImageResolver(),+ fonts,mutationPort: createCanvasProjectMutationPort(store, projectId),reportError: notifications.reportError,}),- [notifications.reportError, projectId, store]+ [fonts, notifications.reportError, projectId, store]);return useSyncExternalStore(resource.subscribe, resource.getSnapshot, resource.getSnapshot);diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.tsindex ac1478af34..e967c578cd 100644--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts@@ -485,7 +485,7 @@ describe('loadCanvasState', () => {});it.each([- ['a future outer version', { ...createEmptyCanvasState(), version: 4 }, 'state', 4],+ ['a future outer version', { ...createEmptyCanvasState(), version: 5 }, 'state', 5],['an older outer version', { ...createEmptyCanvasState(), version: 2 }, 'state', 2],['a legacy version', { ...createEmptyCanvasState(), version: 1 }, 'state', 1],[@@ -498,10 +498,10 @@ describe('loadCanvasState', () => {'a snapshot of another version',{...createEmptyCanvasState(),- snapshots: [{ createdAt: 'now', document: { ...createEmptyCanvasDocument(), version: 4 }, id: 'f', name: 'F' }],+ snapshots: [{ createdAt: 'now', document: { ...createEmptyCanvasDocument(), version: 5 }, id: 'f', name: 'F' }],},'snapshot',- 4,+ 5,],])('refuses %s before parsing anything', (_label, raw, scope, version) => {expect(refusal(raw)).toEqual({ raw, scope, status: 'unsupported-version', version });@@ -541,6 +541,80 @@ describe('loadCanvasState', () => {});});+ it('reads a v3 canvas and keeps the compatibility floor when no v4 typography is present', () => {+ const current = createEmptyCanvasState();+ const legacy = {+ ...current,+ document: { ...current.document, version: 3 as const },+ version: 3 as const,+ };++ expect(load(legacy)).toEqual(legacy);+ });++ it('adopts v4 when a v3 canvas contains custom-font typography', () => {+ const current = createEmptyCanvasState();+ const textLayer = {+ ...createEmptyPaintLayer('Text', 'text'),+ source: {+ align: 'left',+ color: '#fff',+ content: 'hello',+ fontFamily: 'Example',+ fontRef: { contentHash: 'a'.repeat(64), family: 'Example', id: 'font-1', label: 'Example Regular' },+ fontSize: 24,+ fontStyle: 'italic' as const,+ fontVariations: { wght: 650 },+ fontWeight: 650,+ lineHeight: 1.2,+ type: 'text' as const,+ },+ };+ const legacy = {+ ...current,+ document: {+ ...current.document,+ stacks: { ...current.document.stacks, raster: [textLayer] },+ version: 3 as const,+ },+ version: 3 as const,+ };++ const loaded = load(legacy);+ expect(loaded.version).toBe(4);+ expect(loaded.document.version).toBe(4);+ expect(loaded.document.stacks.raster[0]).toMatchObject({ source: textLayer.source });+ });++ it('refuses a custom-font reference whose content hash is not a lowercase SHA-256', () => {+ const current = createEmptyCanvasState();+ const textLayer = {+ ...createEmptyPaintLayer('Text', 'text'),+ source: {+ align: 'left',+ color: '#fff',+ content: 'hello',+ fontFamily: 'Example',+ fontRef: { contentHash: 'hash-a', family: 'Example', id: 'font-1', label: 'Example Regular' },+ fontSize: 24,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text' as const,+ },+ };+ const legacy = {+ ...current,+ document: {+ ...current.document,+ stacks: { ...current.document.stacks, raster: [textLayer] },+ version: 3 as const,+ },+ version: 3 as const,+ };++ expect(refusal(legacy)).toMatchObject({ scope: 'document', status: 'invalid' });+ });+it('passes a valid state through normalized, keeping every persisted field', () => {const canvas = {...withNodes([diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.tsindex 99f2b374f0..eda20d9360 100644--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts@@ -18,7 +18,7 @@ import { z } from 'zod';import type { CanvasLoadDiagnostic, CanvasLoadResult, CanvasVersionScope } from './canvasLoadContracts';-import { MAX_SUPPORTED_CANVAS_SCHEMA_VERSION } from './canvasSchemaVersion';+import { MAX_SUPPORTED_CANVAS_SCHEMA_VERSION, MIN_SUPPORTED_CANVAS_SCHEMA_VERSION } from './canvasSchemaVersion';import { normalizeControlAdapter } from './controlAdapters';export const DEFAULT_CANVAS_DOCUMENT_WIDTH = 1024;@@ -43,6 +43,12 @@ const zPaintSource = z.object({offset: zCoordinate.optional(),type: z.literal('paint'),});+const zTextFontRef = z.object({+ contentHash: z.string().regex(/^[a-f0-9]{64}$/u),+ family: z.string(),+ id: z.string().min(1),+ label: z.string(),+});const zLayerSource = z.discriminatedUnion('type', [zPaintSource,z.object({ image: zImageRef, type: z.literal('image') }),@@ -53,6 +59,9 @@ const zLayerSource = z.discriminatedUnion('type', [fontFamily: z.string(),fontSize: zFiniteNumber,fontWeight: zFiniteNumber,+ fontRef: zTextFontRef.optional(),+ fontStyle: z.enum(['normal', 'italic', 'oblique']).optional(),+ fontVariations: z.record(z.string().min(1), zFiniteNumber).optional(),lineHeight: zFiniteNumber,type: z.literal('text'),}),@@ -347,6 +356,23 @@ const createDefaultStagingArea = (): CanvasStagingAreaContractV2 => ({selectedImageIndex: 0,});+/** v4 is adopted only when a document actually carries custom-font typography. */+const textSourceRequiresV4 = (source: unknown): boolean =>+ isRecord(source) &&+ source.type === 'text' &&+ ('fontRef' in source || 'fontStyle' in source || 'fontVariations' in source);++const nodeRequiresV4 = (node: unknown): boolean =>+ isRecord(node) &&+ (textSourceRequiresV4(node.source) || (Array.isArray(node.children) && node.children.some(nodeRequiresV4)));++/** Returns whether a document uses any v4-only custom-font source fields. */+export const canvasDocumentRequiresFontSchemaV4 = (document: Pick<CanvasDocumentContractV3, 'stacks'>): boolean =>+ Object.values(document.stacks).some((roots) => roots.some(nodeRequiresV4));++const writableDocumentVersion = (declaredVersion: unknown, stacks: CanvasStackForests): 3 | 4 =>+ declaredVersion === 4 || canvasDocumentRequiresFontSchemaV4({ stacks }) ? 4 : 3;+/*** Converts a `{x,y,width,height}` placement rect, plus the native size of the image it places,* into a layer `transform`. Used by the "accept staged image into a raster layer" reducer path.@@ -408,6 +434,14 @@ const classifyVersion = (value: unknown): DeclaredVersion => {if (value === MAX_SUPPORTED_CANVAS_SCHEMA_VERSION) {return { kind: 'current' };}+ if (+ typeof value === 'number' &&+ Number.isInteger(value) &&+ value >= MIN_SUPPORTED_CANVAS_SCHEMA_VERSION &&+ value < MAX_SUPPORTED_CANVAS_SCHEMA_VERSION+ ) {+ return { kind: 'current' };+ }if (typeof value === 'number' && Number.isInteger(value) && value >= 1) {return { kind: 'other', version: value };}@@ -428,7 +462,7 @@ const unsupported = (scope: CanvasVersionScope, version: number): Refusal => ({version,});-/** Refuses any declared version other than the current one before anything is defaulted or parsed. */+/** Refuses unsupported declared versions before anything is defaulted or parsed. */const checkVersion = (value: Record<string, unknown>, scope: CanvasVersionScope, path: string): Refusal | null => {const version = classifyVersion(value.version);switch (version.kind) {@@ -598,6 +632,7 @@ export const normalizeCanvasDocumentContract = (...document,...normalizeCanvasDocumentGeometry(document.width, document.height, document.bbox),stacks: parsed.stacks,+ version: writableDocumentVersion(document.version, parsed.stacks),}: null;};@@ -639,7 +674,7 @@ const loadCanvasDocument = (...normalizeCanvasDocumentGeometry(value.width, value.height, value.bbox),selectedLayerId,stacks: stacks.stacks,- version: 3,+ version: writableDocumentVersion(value.version, stacks.stacks),},};};@@ -702,7 +737,12 @@ const loadCanvasStateStep = (canvas: unknown): LoadStep<CanvasStateContractV3> =documentRevision: asNumber(canvas.documentRevision, 0),snapshots,stagingArea: normalizeStagingArea(canvas),- version: 3,+ version:+ canvas.version === MAX_SUPPORTED_CANVAS_SCHEMA_VERSION ||+ document.value.version === MAX_SUPPORTED_CANVAS_SCHEMA_VERSION ||+ snapshots.some((snapshot) => snapshot.document.version === MAX_SUPPORTED_CANVAS_SCHEMA_VERSION)+ ? MAX_SUPPORTED_CANVAS_SCHEMA_VERSION+ : 3,},};};diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.tsindex 0609f700e4..5a8686ff1c 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts@@ -46,7 +46,7 @@ import { isOverlayStack, layerStackOf, reorderSiblings } from '@workbench/canvasimport { repairSelectedLayerId } from '@workbench/canvas-engine/document/selectionRepair';import { prependProjectEvent } from '@workbench/projectEvents';-import { normalizeCanvasDocumentContract } from './canvasMigration';+import { canvasDocumentRequiresFontSchemaV4, normalizeCanvasDocumentContract } from './canvasMigration';import {getCanvasStagingCandidateFingerprint,getCanvasStagingSlotCount,@@ -69,6 +69,7 @@ const CANVAS_PROJECT_MUTATION_TYPES: ReadonlySet<string> = new Set<CanvasProject'mergeCanvasLayersDown','removeCanvasLayers','reorderCanvasSiblings',+ 'replaceCanvasFontReferences','replaceCanvasDocument','replaceCanvasLayer','resizeCanvasDocument',@@ -117,16 +118,26 @@ const withRepairedSelection = (document: CanvasDocumentContractV3): CanvasDocumereturn selectedLayerId === document.selectedLayerId ? document : { ...document, selectedLayerId };};-const setCanvasDocument = (project: Project, document: CanvasDocumentContractV3): Project =>- document === project.canvas.document ? project : { ...project, canvas: { ...project.canvas, document } };+const setCanvasDocument = (project: Project, document: CanvasDocumentContractV3): Project => {+ const schemaVersion: 3 | 4 =+ project.canvas.version === 4 || document.version === 4 || canvasDocumentRequiresFontSchemaV4(document) ? 4 : 3;+ const nextDocument = document.version === schemaVersion ? document : { ...document, version: schemaVersion };+ return nextDocument === project.canvas.document && schemaVersion === project.canvas.version+ ? project+ : { ...project, canvas: { ...project.canvas, document: nextDocument, version: schemaVersion } };+};const updateCanvasDocument = (project: Project,update: (document: CanvasDocumentContractV3) => CanvasDocumentContractV3): Project => setCanvasDocument(project, update(project.canvas.document));-const setCanvasState = (project: Project, canvas: CanvasStateContractV3): Project =>- canvas === project.canvas ? project : { ...project, canvas };+const setCanvasState = (project: Project, canvas: CanvasStateContractV3): Project => {+ const hasV4Snapshot = canvas.snapshots.some((snapshot) => snapshot.document.version === 4);+ const schemaVersion: 3 | 4 = canvas.version === 4 || canvas.document.version === 4 || hasV4Snapshot ? 4 : 3;+ const nextCanvas = canvas.version === schemaVersion ? canvas : { ...canvas, version: schemaVersion };+ return nextCanvas === project.canvas ? project : { ...project, canvas: nextCanvas };+};const withStacks = (document: CanvasDocumentContractV3, stacks: CanvasStackForests): CanvasDocumentContractV3 =>stacks === document.stacks ? document : { ...document, stacks };@@ -958,6 +969,15 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasPro}): project;}+ case 'replaceCanvasFontReferences': {+ const document = normalizeCanvasDocumentContract(structuredClone(mutation.document));+ return document+ ? setCanvasState(project, {+ ...project.canvas,+ document: withRepairedSelection(document),+ })+ : project;+ }case 'saveCanvasSnapshot': {const document = normalizeCanvasDocumentContract(structuredClone(project.canvas.document));return documentdiff --git a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.tsindex ac5aa17b1e..d42b2a22f1 100644--- a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts@@ -2,7 +2,7 @@export const MIN_SUPPORTED_CANVAS_SCHEMA_VERSION = 3;/** Newest canvas document schema this build can safely read, edit, and write. */-export const MAX_SUPPORTED_CANVAS_SCHEMA_VERSION = 3;+export const MAX_SUPPORTED_CANVAS_SCHEMA_VERSION = 4;/** Whether a project whose documents need at least `minimumCanvasSchemaVersion` can be opened here. */export const isCanvasSchemaVersionSupported = (minimumCanvasSchemaVersion: number): boolean =>diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsxindex 2cbc9be42d..de3ea6ca92 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx@@ -1,11 +1,12 @@import { Box, Flex, VisuallyHidden, type SystemStyleObject } from '@chakra-ui/react';+import { FontsPage } from '@features/fonts/launchpad';import { useCapabilities, UsersPage } from '@features/identity';import { ModelsPage } from '@features/models';import { NodesPage } from '@features/nodes';import { Tabs } from '@platform/ui';import { useLocation, useNavigate } from '@tanstack/react-router';import { LaunchpadCommandPalette } from '@workbench/palette/LaunchpadCommandPalette';-import { BoxIcon, BlocksIcon, FolderIcon, HouseIcon, UsersIcon, type LucideIcon } from 'lucide-react';+import { BlocksIcon, BoxIcon, FolderIcon, HouseIcon, TypeIcon, UsersIcon, type LucideIcon } from 'lucide-react';import { useCallback, useMemo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';@@ -28,7 +29,7 @@ import { ProjectActionsMenuProvider } from './projects/ProjectActionsMenuHost';* not peers: a flat list gave "Users" the same standing as "Projects".*/-type LaunchpadSectionId = 'home' | 'projects' | 'models' | 'nodes' | 'users';+type LaunchpadSectionId = 'home' | 'projects' | 'models' | 'nodes' | 'users' | 'fonts';interface LaunchpadSection {id: LaunchpadSectionId;@@ -40,7 +41,7 @@ interface LaunchpadSection {}const DEFAULT_SECTION_ID: LaunchpadSectionId = 'home';-const SECTION_IDS: readonly string[] = ['home', 'projects', 'models', 'nodes', 'users'];+const SECTION_IDS: readonly string[] = ['home', 'projects', 'models', 'nodes', 'users', 'fonts'];const isSectionId = (value: string): value is LaunchpadSectionId => SECTION_IDS.includes(value);@@ -55,7 +56,8 @@ const normalizeSectionId = (value: string): LaunchpadSectionId | null => {return isSectionId(id) ? id : null;};-const SECTION_PATHS: Record<LaunchpadSectionId, '/' | '/projects' | '/models' | '/nodes' | '/users'> = {+const SECTION_PATHS: Record<LaunchpadSectionId, '/' | '/projects' | '/models' | '/nodes' | '/users' | '/fonts'> = {+ fonts: '/fonts',home: '/',models: '/models',nodes: '/nodes',@@ -102,6 +104,13 @@ export const Launchpad = () => {label: t('launchpad.sections.projects'),render: () => <ProjectsPage />,},+ {+ group: 'manage',+ icon: TypeIcon,+ id: 'fonts',+ label: t('launchpad.sections.fonts'),+ render: () => <FontsPage />,+ },{condition: canManageModels,group: 'manage',diff --git a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsxindex 6ffc2d866c..962fda1aa7 100644--- a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx@@ -46,6 +46,7 @@ const LaunchpadCommandPaletteDialog = ({run: () => void navigate({ search: search.project ? { project: search.project } : {}, to: '/app' }),}),navEntry({ id: 'goToProjects', run: () => void navigate({ to: '/projects' }) }),+ navEntry({ id: 'goToFonts', keywords: 'font typeface typography', run: () => void navigate({ to: '/fonts' }) }),...(canManageModels ? [navEntry({ id: 'goToModels', run: () => void navigate({ to: '/models' }) })] : []),...(canManageNodes ? [navEntry({ id: 'goToNodes', run: () => void navigate({ to: '/nodes' }) })] : []),...(canManageUsers ? [navEntry({ id: 'goToUsers', run: () => void navigate({ to: '/users' }) })] : []),diff --git a/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts b/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.tsindex 1232a999ad..1804adca07 100644--- a/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts@@ -13,14 +13,14 @@ describe('gateProjectCanvases', () => {});it('refuses a project whose live canvas is unsupported or invalid, keeping the raw document', () => {- const future = { canvas: { ...canvas, version: 4 }, id: 'p', name: 'P' };+ const future = { canvas: { ...canvas, version: 5 }, id: 'p', name: 'P' };const broken = { canvas: { ...canvas, version: '2' }, id: 'p', name: 'P' };expect(gateProjectCanvases(future)).toMatchObject({projectId: 'p',projectName: 'P',raw: future,- refusal: { scope: 'state', status: 'unsupported-version', version: 4 },+ refusal: { scope: 'state', status: 'unsupported-version', version: 5 },source: 'canvas',});expect(gateProjectCanvases(broken)).toMatchObject({diff --git a/invokeai/frontend/webv2/src/workbench/projects/README.md b/invokeai/frontend/webv2/src/workbench/projects/README.mdindex 44dd30a151..2f8dab29d8 100644--- a/invokeai/frontend/webv2/src/workbench/projects/README.md+++ b/invokeai/frontend/webv2/src/workbench/projects/README.md@@ -19,6 +19,14 @@ The old workbench mirror, sync map, and refused-project localStorage keys are deCold-start offline editing is not supported. When the backend cannot load, the unavailable screen provides retry and local draft/run exports. Conflicted or schema-refused drafts are retained until explicitly resolved or deleted; they are never silently evicted.+## Font dependencies++Custom text retains an immutable font reference and explicit variation coordinates. Browser registration names are runtime state and never enter the project document. New typography requires Canvas schema 4; documents without it retain their existing compatibility floor.++Project archives record font dependencies by content hash. Export defaults to references only; **Include font files** embeds the original referenced files, once per hash, after authenticated download and checksum verification. A failed required font download fails the embedded export rather than producing a silently incomplete archive.++Import verifies declared entries and checksums, then validates all embedded fonts before creating server resources. Fonts are uploaded privately and the canonical document's references are remapped to the destination IDs. Duplicate uploads reuse existing private records. Rollback removes only newly created fonts and only when project creation has not been attempted or has confirmed absence; an ambiguous create response retains the resources. Font quota failures offer an explicit references-only retry. Changing accounts cancels the operation and prevents cleanup under another user's credentials.+## VerificationRun `pnpm lint`, `pnpm test`, `pnpm test:browser`, and `pnpm run test:performance:build` from webv2. Queue receipt tests also cover backend admission, account isolation, project deletion, partial acceptance, and idempotent retries. Browser tests exercise actual IndexedDB transactions and Web Locks.diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts b/invokeai/frontend/webv2/src/workbench/projects/api.test.tsindex 2cf695fe89..4332013f88 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts@@ -40,7 +40,7 @@ beforeEach(() => {describe('createProjectSettled', () => {const request = { data: {}, name: 'Imported', project_id: 'project-1' };const post = () => ({- body: JSON.stringify({ ...request, max_canvas_schema_version: 3, minimum_canvas_schema_version: 3 }),+ body: JSON.stringify({ ...request, max_canvas_schema_version: 4, minimum_canvas_schema_version: 3 }),method: 'POST',signal: expect.anything(),});@@ -78,7 +78,7 @@ describe('createProjectSettled', () => {expect(transport.apiFetchJson).toHaveBeenNthCalledWith(2, '/api/v1/projects/', post());expect(transport.apiFetchJson).toHaveBeenNthCalledWith(3,- '/api/v1/projects/project-1?max_canvas_schema_version=3',+ '/api/v1/projects/project-1?max_canvas_schema_version=4',expect.anything());});@@ -212,7 +212,7 @@ describe('canvas schema compatibility declarations', () => {await getProject('project/one');- expect(transport.apiFetchJson).toHaveBeenCalledWith('/api/v1/projects/project%2Fone?max_canvas_schema_version=3', {+ expect(transport.apiFetchJson).toHaveBeenCalledWith('/api/v1/projects/project%2Fone?max_canvas_schema_version=4', {signal: undefined,});});@@ -226,7 +226,7 @@ describe('canvas schema compatibility declarations', () => {body: JSON.stringify({data: {},name: 'Project',- max_canvas_schema_version: 3,+ max_canvas_schema_version: 4,minimum_canvas_schema_version: 3,}),method: 'POST',@@ -250,7 +250,7 @@ describe('canvas schema compatibility declarations', () => {expected_revision: 4,minimum_canvas_schema_version: 3,name: 'Project',- max_canvas_schema_version: 3,+ max_canvas_schema_version: 4,}),method: 'PUT',signal: undefined,diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsDialog.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsDialog.tsxnew file mode 100644index 0000000000..d36193b440--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsDialog.tsx@@ -0,0 +1,82 @@+import { Checkbox, Dialog, Portal, Stack, Text } from '@chakra-ui/react';+import { useMountEffect } from '@platform/react/useMountEffect';+import { Button, CloseButton } from '@platform/ui';+import { registerHotkeyModalLayer } from '@workbench/hotkeys/modalLayer';+import { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { ProjectFileOptionsRequest } from './ProjectFileOptionsProvider';++export const ProjectFileOptionsDialog = ({ request }: { request: ProjectFileOptionsRequest }) => {+ const { t } = useTranslation();+ const [includeFonts, setIncludeFonts] = useState(false);+ useMountEffect(() => registerHotkeyModalLayer('project-file-options'));+ const close = useCallback(() => request.settle(null), [request]);+ const isExport = request.kind === 'export';+ const returnFocus = useCallback(+ () => (request.returnFocus?.isConnected ? request.returnFocus : null),+ [request.returnFocus]+ );+ const handleOpenChange = useCallback(+ ({ open }: { open: boolean }) => {+ if (!open) {+ close();+ }+ },+ [close]+ );+ const handleCheckedChange = useCallback(+ ({ checked }: { checked: boolean | 'indeterminate' }) => setIncludeFonts(checked === true),+ []+ );+ const confirm = useCallback(() => request.settle({ includeFonts }), [includeFonts, request]);++ return (+ <Dialog.Root open placement="center" size="sm" finalFocusEl={returnFocus} onOpenChange={handleOpenChange}>+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content>+ <Dialog.Header>+ <Dialog.Title>+ {t(isExport ? 'projects.fonts.exportTitle' : 'projects.fonts.importTitle', { name: request.name })}+ </Dialog.Title>+ </Dialog.Header>+ <Dialog.Body>+ <Stack gap="3">+ {isExport ? (+ <>+ <Checkbox.Root checked={includeFonts} onCheckedChange={handleCheckedChange}>+ <Checkbox.HiddenInput />+ <Checkbox.Control>+ <Checkbox.Indicator />+ </Checkbox.Control>+ <Checkbox.Label>{t('projects.fonts.includeFiles')}</Checkbox.Label>+ </Checkbox.Root>+ <Text color="fg.muted" fontSize="sm">+ {t('projects.fonts.exportDescription')}+ </Text>+ {includeFonts ? <Text fontSize="sm">{t('projects.fonts.rightsReminder')}</Text> : null}+ </>+ ) : (+ <Text fontSize="sm">{t('projects.fonts.quotaDescription')}</Text>+ )}+ </Stack>+ </Dialog.Body>+ <Dialog.Footer>+ <Button color="fg" variant="ghost" onClick={close}>+ {t('common.cancel')}+ </Button>+ <Button colorPalette="accent" onClick={confirm}>+ {t(isExport ? 'projects.fonts.exportAction' : 'projects.fonts.importReferences')}+ </Button>+ </Dialog.Footer>+ <Dialog.CloseTrigger asChild>+ <CloseButton aria-label={t('common.close')} />+ </Dialog.CloseTrigger>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.browser.test.tsxnew file mode 100644index 0000000000..0c3a6ab3b0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.browser.test.tsx@@ -0,0 +1,91 @@+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */+import { ChakraProvider } from '@chakra-ui/react';+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';+import { system } from '@theme/system';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, expect, it } from 'vitest';+import { page } from 'vitest/browser';++import { ProjectFileOptionsProvider, useProjectFileOptions } from './ProjectFileOptionsProvider';++const i18n = createInstance();+await i18n.use(initReactI18next).init({+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },+});++let root: Root | undefined;+let host: HTMLDivElement | undefined;+let results: ({ includeFonts: boolean } | null)[] = [];+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const Harness = () => {+ const { requestExportOptions } = useProjectFileOptions();+ return (+ <button+ type="button"+ onClick={() => {+ void requestExportOptions('Typography', captureAccountScope()).then((result) => results.push(result));+ }}+ >+ Export+ </button>+ );+};++const render = async () => {+ await page.viewport(1280, 900);+ results = [];+ accountLifecycle.activate('fonts-test');+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root!.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <ProjectFileOptionsProvider>+ <Harness />+ </ProjectFileOptionsProvider>+ </I18nextProvider>+ </ChakraProvider>+ )+ );+};++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ accountLifecycle.invalidate();+});++it('defaults to references, includes files only when selected, and restores focus', async () => {+ await render();+ const trigger = page.getByRole('button', { name: 'Export', exact: true });+ await act(() => trigger.click());+ const checkbox = page.getByRole('checkbox', { name: 'Include font files' });+ await expect.element(checkbox).not.toBeChecked();+ await act(() => page.getByRole('button', { name: 'Export project', exact: true }).click());+ expect(results).toEqual([{ includeFonts: false }]);+ await expect.element(trigger).toHaveFocus();++ await act(() => trigger.click());+ await act(() => page.getByText('Include font files', { exact: true }).click());+ await expect.element(page.getByText(/permission to redistribute/)).toBeVisible();+ await page.screenshot({ path: '../../../../artifacts/fonts/export-dialog.png' });+ await act(() => page.getByRole('button', { name: 'Export project', exact: true }).click());+ expect(results).toEqual([{ includeFonts: false }, { includeFonts: true }]);+});++it('cancels a pending choice when its account goes away', async () => {+ await render();+ await act(() => page.getByRole('button', { name: 'Export', exact: true }).click());+ await expect.element(page.getByRole('dialog')).toBeVisible();+ await act(() => accountLifecycle.activate('another-account'));+ expect(results).toEqual([null]);+ await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.tsxnew file mode 100644index 0000000000..98ecf1ae83--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.tsx@@ -0,0 +1,96 @@+import { useMountEffect } from '@platform/react/useMountEffect';+import { type AccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import {+ lazy,+ Suspense,+ createContext,+ useCallback,+ useContext,+ useMemo,+ useRef,+ useState,+ type ReactNode,+} from 'react';++interface ExportOptions {+ includeFonts: boolean;+}++interface ProjectFileOptionsControl {+ requestExportOptions: (name: string, owner: AccountScope) => Promise<ExportOptions | null>;+ requestReferencesOnlyImport: (owner: AccountScope) => Promise<boolean>;+}++export interface ProjectFileOptionsRequest {+ ticket: number;+ kind: 'export' | 'import';+ name: string;+ returnFocus: HTMLElement | null;+ settle: (result: ExportOptions | null) => void;+}++const ProjectFileOptionsDialog = lazy(() =>+ import('./ProjectFileOptionsDialog').then((module) => ({ default: module.ProjectFileOptionsDialog }))+);++const ProjectFileOptionsContext = createContext<ProjectFileOptionsControl | null>(null);++export const useProjectFileOptions = (): ProjectFileOptionsControl => {+ const control = useContext(ProjectFileOptionsContext);+ if (!control) {+ throw new Error('Project file actions require ProjectFileOptionsProvider.');+ }+ return control;+};++export const ProjectFileOptionsProvider = ({ children }: { children: ReactNode }) => {+ const [request, setRequest] = useState<ProjectFileOptionsRequest | null>(null);+ const current = useRef<ProjectFileOptionsRequest | null>(null);+ const ticket = useRef(0);+ const requestOptions = useCallback((kind: ProjectFileOptionsRequest['kind'], name: string, owner: AccountScope) => {+ current.current?.settle(null);+ if (!isAccountScopeCurrent(owner)) {+ return Promise.resolve(null);+ }+ return new Promise<ExportOptions | null>((resolve) => {+ const requestTicket = ++ticket.current;+ const abort = () => current.current?.settle(null);+ const next: ProjectFileOptionsRequest = {+ ticket: requestTicket,+ kind,+ name,+ returnFocus: document.activeElement instanceof HTMLElement ? document.activeElement : null,+ settle: (result) => {+ owner.signal.removeEventListener('abort', abort);+ if (current.current?.ticket === requestTicket) {+ current.current = null;+ setRequest(null);+ }+ resolve(isAccountScopeCurrent(owner) ? result : null);+ },+ };+ current.current = next;+ owner.signal.addEventListener('abort', abort, { once: true });+ setRequest(next);+ });+ }, []);+ useMountEffect(() => () => current.current?.settle(null));+ const control = useMemo<ProjectFileOptionsControl>(+ () => ({+ requestExportOptions: (name, owner) => requestOptions('export', name, owner),+ requestReferencesOnlyImport: async (owner) => (await requestOptions('import', '', owner)) !== null,+ }),+ [requestOptions]+ );++ return (+ <ProjectFileOptionsContext.Provider value={control}>+ {children}+ {request ? (+ <Suspense fallback={null}>+ <ProjectFileOptionsDialog key={request.ticket} request={request} />+ </Suspense>+ ) : null}+ </ProjectFileOptionsContext.Provider>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.tsindex a62d4da068..048122e6d3 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts@@ -1,3 +1,4 @@+import { sha256Hex } from '@platform/browser/sha256';import { mapWithConcurrency } from '@platform/core/concurrency';import { collectLiveAssetRefs, selectCoverImageName, stripInstallationState } from '@workbench/projects/projectAssets';@@ -14,6 +15,12 @@ import {isRequestCancellation,} from './assetTransport';import { buildInvkBoardSnapshot } from './board';+import {+ collectFontDependencies,+ INVK_MAX_FONT_BYTES,+ type FontArchiveTransport,+ type InvkFontDependency,+} from './fonts';import {INVK_BOARD_ENTRY,INVK_DOCUMENT_ENTRY,@@ -45,6 +52,8 @@ export interface InvkExportPlan {documentJson: string;/** Download file name, including the extension. */fileName: string;+ fonts: InvkFontDependency[];+ includeFonts: boolean;manifestInput: {appVersion: string;createdAt: string;@@ -69,6 +78,7 @@ export const planInvkExport = (input: {minimumCanvasSchemaVersion: number;name: string;projectDocument: Record<string, unknown>;+ includeFonts?: boolean;}): InvkExportPlan => {const sourceProjectId = typeof input.projectDocument.id === 'string' ? input.projectDocument.id : undefined;@@ -78,10 +88,11 @@ export const planInvkExport = (input: {const projectDocument = stripInstallationState(input.projectDocument);const boardSnapshot = buildInvkBoardSnapshot(input.boardItems);const transferItems = planMediaTransfer(boardSnapshot.items, toMediaRefs(collectLiveAssetRefs(projectDocument)));+ const fonts = collectFontDependencies(projectDocument);// Refused before a single byte is fetched. An archive that cannot be packed is not worth the// hundreds of round trips it would take to discover that at the end.- const worstCaseEntries = FIXED_ENTRY_COUNT + transferItems.length + 1;+ const worstCaseEntries = FIXED_ENTRY_COUNT + transferItems.length + (input.includeFonts ? fonts.length : 0) + 1;if (worstCaseEntries > INVK_MAX_ENTRIES) {throw new InvkFormatError('too-large', `Project needs ${worstCaseEntries} archive entries`);@@ -94,6 +105,8 @@ export const planInvkExport = (input: {// bytes per line would be the largest entry in the archive before deflate.documentJson: JSON.stringify(projectDocument),fileName: toInvkFileName(input.name),+ fonts,+ includeFonts: input.includeFonts ?? false,manifestInput: {appVersion: input.appVersion,createdAt: input.createdAt,@@ -118,6 +131,7 @@ export interface InvkExportDeps {fetchVideoBytes?: (videoName: string, signal?: AbortSignal) => Promise<Uint8Array | null>;onProgress?: (progress: InvkExportProgress) => void;signal?: AbortSignal;+ fontTransport?: FontArchiveTransport;}export interface InvkExportResult extends ProjectTransferIssues {@@ -137,6 +151,29 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDelet bundledImageCount = 0;let bundledVideoCount = 0;let completed = 0;+ const fonts = plan.fonts.map((font) => ({ ...font }));+ const total = plan.transferItems.length + (plan.includeFonts ? fonts.length : 0);++ if (plan.includeFonts && fonts.length > 0) {+ const fontTransport = deps.fontTransport ?? (await import('./fontTransport')).createFontArchiveTransport();+ for (const font of fonts) {+ deps.signal?.throwIfAborted();+ const { bytes, filename } = await fontTransport.download(font, deps.signal);+ const extension = filename.split('.').at(-1)?.toLowerCase();+ if (+ !extension ||+ !['ttf', 'otf', 'woff', 'woff2'].includes(extension) ||+ bytes.byteLength > INVK_MAX_FONT_BYTES ||+ (await sha256Hex(bytes)) !== font.contentHash+ ) {+ throw new InvkFormatError('damaged', `The font file for ${font.label} is unavailable or changed.`);+ }+ font.entry = `fonts/${font.contentHash}.${extension}`;+ entries.set(font.entry, binaryEntry(bytes));+ completed += 1;+ deps.onProgress?.({ completed, phase: 'bundling', total });+ }+ }/** Unservable is `null`; cancelled rethrows. */const skipUnservable = async <T>(read: () => Promise<T | null>): Promise<T | null> => {@@ -167,7 +204,7 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDe);completed += 1;- deps.onProgress?.({ completed, phase: 'bundling', total: assets.length });+ deps.onProgress?.({ completed, phase: 'bundling', total });if (bytes === null) {// Reported against every role it filled: the same failure costs a board result and a canvas@@ -199,10 +236,11 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDe// step that precedes handing a file to the browser.deps.signal?.throwIfAborted();- deps.onProgress?.({ completed: assets.length, phase: 'packing', total: assets.length });+ deps.onProgress?.({ completed, phase: 'packing', total });const manifest = buildInvkManifest({...plan.manifestInput,+ fonts,...(coverEntryName === undefined ? {} : { cover: coverEntryName }),});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/fontTransport.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/fontTransport.test.tsnew file mode 100644index 0000000000..15c0329442--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/fontTransport.test.ts@@ -0,0 +1,73 @@+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { ApiError } from '@platform/transport/http';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createFontArchiveTransport } from './fontTransport';+import { FontImportQuotaError } from './format';++const fonts = vi.hoisted(() => ({+ deleteFont: vi.fn(),+ downloadFont: vi.fn(),+ getFont: vi.fn(),+ listFonts: vi.fn(),+ uploadFont: vi.fn(),+ validateFont: vi.fn(),+}));+vi.mock('@features/fonts', () => fonts);++const dependency = {+ contentHash: 'a'.repeat(64),+ family: 'Example',+ label: 'Example Regular',+ references: ['old-server-id'],+};++describe('archive font transport', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ accountLifecycle.activate('font-import-owner');+ });++ it('resolves a cross-server id collision by exact content instead of downloading the wrong face', async () => {+ fonts.getFont.mockResolvedValue({ contentHash: 'b'.repeat(64), id: 'old-server-id' });+ fonts.listFonts.mockResolvedValue({+ items: [{ contentHash: dependency.contentHash, filename: 'original.ttf', id: 'local-id' }],+ });+ fonts.downloadFont.mockResolvedValue(new Uint8Array([1, 2]));++ await expect(createFontArchiveTransport().download(dependency)).resolves.toEqual({+ bytes: new Uint8Array([1, 2]),+ filename: 'original.ttf',+ });+ expect(fonts.listFonts).toHaveBeenCalledWith(+ { contentHash: dependency.contentHash, limit: 1 },+ expect.any(AbortSignal)+ );+ expect(fonts.downloadFont).toHaveBeenCalledWith(+ { contentHash: dependency.contentHash, id: 'local-id' },+ expect.any(AbortSignal)+ );+ });++ it.each(['validate', 'upload'] as const)(+ 'offers references-only recovery for a server limit during %s',+ async (method) => {+ fonts.validateFont.mockRejectedValue(new ApiError('File exceeds configured limit', 413));+ fonts.uploadFont.mockRejectedValue(new ApiError('Library is full', 413));++ await expect(createFontArchiveTransport()[method](new File(['font'], 'font.ttf'))).rejects.toBeInstanceOf(+ FontImportQuotaError+ );+ }+ );++ it('rejects work owned by the previous account before making requests', async () => {+ const transport = createFontArchiveTransport();+ accountLifecycle.activate('another-owner');++ await expect(transport.download(dependency)).rejects.toThrow();+ await expect(transport.upload(new File(['font'], 'font.ttf'))).rejects.toThrow();+ expect(fonts.getFont).not.toHaveBeenCalled();+ expect(fonts.uploadFont).not.toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/fontTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/fontTransport.tsnew file mode 100644index 0000000000..7e14226dac--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/fontTransport.ts@@ -0,0 +1,88 @@+import {+ deleteFont,+ downloadFont,+ getFont,+ listFonts,+ uploadFont,+ validateFont,+ type FontRecord,+} from '@features/fonts';+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';+import { ApiError } from '@platform/transport/http';++import type { FontArchiveTransport, InvkFontDependency } from './fonts';++import { FontImportQuotaError } from './format';++/** Resolves identity collisions across servers by exact bytes, never by a family name. */+const resolveFont = async (dependency: InvkFontDependency, signal?: AbortSignal): Promise<FontRecord> => {+ for (const id of dependency.references) {+ try {+ const font = await getFont(id, signal);+ if (font.contentHash === dependency.contentHash) {+ return font;+ }+ } catch (error) {+ if (!(error instanceof ApiError) || error.status !== 404) {+ throw error;+ }+ }+ }+ const page = await listFonts({ contentHash: dependency.contentHash, limit: 1 }, signal);+ const font = page.items.find((item) => item.contentHash === dependency.contentHash);+ if (font) {+ return font;+ }+ throw new Error(`The font “${dependency.label}” is unavailable. Install it or export without font files.`);+};++export const createFontArchiveTransport = (): FontArchiveTransport => {+ const owner = captureAccountScope();+ return {+ download: async (dependency, signal = owner.signal) => {+ assertAccountScopeCurrent(owner);+ const font = await resolveFont(dependency, signal);+ const bytes = await downloadFont({ contentHash: dependency.contentHash, id: font.id }, signal);+ assertAccountScopeCurrent(owner);+ return { bytes, filename: font.filename };+ },+ remove: async (id, signal = owner.signal) => {+ assertAccountScopeCurrent(owner);+ await deleteFont(id, signal);+ assertAccountScopeCurrent(owner);+ },+ upload: async (file, signal = owner.signal) => {+ assertAccountScopeCurrent(owner);+ try {+ const result = await uploadFont(file, 'private', signal);+ assertAccountScopeCurrent(owner);+ return {+ created: result.created,+ font: {+ contentHash: result.font.contentHash,+ family: result.font.family,+ id: result.font.id,+ label: result.font.label,+ },+ };+ } catch (error) {+ if (error instanceof ApiError && error.status === 413) {+ throw new FontImportQuotaError();+ }+ throw error;+ }+ },+ validate: async (file, signal = owner.signal) => {+ assertAccountScopeCurrent(owner);+ try {+ await validateFont(file, signal);+ assertAccountScopeCurrent(owner);+ } catch (error) {+ if (error instanceof ApiError && error.status === 413) {+ throw new FontImportQuotaError();+ }+ throw error;+ }+ },+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/fonts.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/fonts.test.tsnew file mode 100644index 0000000000..e554d17a1d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/fonts.test.ts@@ -0,0 +1,197 @@+import { sha256Hex } from '@platform/browser/sha256';+import { describe, expect, it, vi } from 'vitest';++import { binaryEntry, readArchive, readEntryText, textEntry, writeArchive } from './archive';+import { executeInvkExport, planInvkExport } from './exportProject';+import {+ collectFontDependencies,+ createRestoredFontLedger,+ preflightEmbeddedFonts,+ readEmbeddedFonts,+ remapFontReferences,+ restoreEmbeddedFonts,+ rollbackRestoredFonts,+ type FontArchiveTransport,+} from './fonts';+import { readInvkArchive } from './importProject';++const bytes = new Uint8Array([0, 1, 0, 0, 1, 2, 3]);+const fontRefFor = async (fontBytes: Uint8Array, id = 'original') => ({+ contentHash: await sha256Hex(fontBytes),+ family: 'Example',+ id,+ label: 'Example Regular',+});+const fontRef = (id = 'original') => fontRefFor(bytes, id);+const documentWith = (+ font: Awaited<ReturnType<typeof fontRef>>,+ secondFont: Awaited<ReturnType<typeof fontRef>> = font+) => ({+ canvas: {+ document: {+ stacks: {+ raster: [+ { id: 'one', source: { content: 'First', fontFamily: 'Example', fontRef: font, type: 'text' } },+ { id: 'two', source: { content: 'Second', fontFamily: 'Example', fontRef: secondFont, type: 'text' } },+ ],+ },+ },+ },+});+const planFor = async (includeFonts: boolean) =>+ planInvkExport({+ appVersion: '7',+ boardItems: [],+ createdAt: '2026-09-07',+ includeFonts,+ minimumCanvasSchemaVersion: 4,+ name: 'Fonts',+ projectDocument: documentWith(await fontRef()),+ });+const transportFor = (): FontArchiveTransport => ({+ download: vi.fn(() => Promise.resolve({ bytes, filename: 'Example.ttf' })),+ remove: vi.fn(async () => {}),+ upload: vi.fn(async () => ({ created: true, font: await fontRef('imported') })),+ validate: vi.fn(async () => {}),+});++describe('project font archives', () => {+ it('writes references by default without downloading private font bytes', async () => {+ const transport = await transportFor();+ let archive: Blob | undefined;+ await executeInvkExport(await planFor(false), {+ download: (blob) => {+ archive = blob;+ },+ fontTransport: transport,+ });+ const entries = await readArchive(new Uint8Array(await archive!.arrayBuffer()));+ expect(transport.download).not.toHaveBeenCalled();+ expect([...entries.keys()].some((key) => key.startsWith('fonts/'))).toBe(false);+ expect(JSON.parse(readEntryText(entries.get('manifest.json')!)).fonts).toEqual([+ {+ contentHash: await sha256Hex(bytes),+ family: 'Example',+ label: 'Example Regular',+ references: ['original'],+ },+ ]);+ const contents = await readInvkArchive(new File([archive!], 'fonts.invk'));+ expect(contents.fonts).toEqual([]);+ });++ it('embeds one file for multiple text layers, verifies it, and remaps without changing typography', async () => {+ const transport = await transportFor();+ let archive: Blob | undefined;+ await executeInvkExport(await planFor(true), {+ download: (blob) => {+ archive = blob;+ },+ fontTransport: transport,+ });+ expect(transport.download).toHaveBeenCalledTimes(1);+ const contents = await readInvkArchive(new File([archive!], 'fonts.invk'));+ expect(contents.fonts).toHaveLength(1);+ const ledger = createRestoredFontLedger();+ await preflightEmbeddedFonts(contents.fonts!, transport);+ await restoreEmbeddedFonts(contents.fonts!, ledger, transport);+ const imported = remapFontReferences(contents.projectDocument, ledger.mappings);+ expect(collectFontDependencies(imported)[0]?.references).toEqual(['imported']);+ expect(collectFontDependencies(contents.projectDocument)[0]?.references).toEqual(['original']);+ expect(JSON.stringify(imported)).toContain('First');+ expect(JSON.stringify(imported)).toContain('Second');+ });++ it('does not produce an archive when an embedded font is unavailable or changed', async () => {+ const transport = await transportFor();+ transport.download = () => Promise.resolve({ bytes: new Uint8Array([9]), filename: 'Example.ttf' });+ const download = vi.fn();+ await expect(executeInvkExport(await planFor(true), { download, fontTransport: transport })).rejects.toThrow();+ expect(download).not.toHaveBeenCalled();+ });++ it('rejects missing manifest dependencies, including an absent manifest, before accepting references-only archives', async () => {+ const first = await fontRef();+ const second = await fontRefFor(new Uint8Array([9, 8, 7]), 'second');+ const document = documentWith(first, second);+ const dependencies = collectFontDependencies(document);++ expect(dependencies).toHaveLength(2);+ await expect(readEmbeddedFonts([dependencies[0]!], document, new Map())).rejects.toThrow(+ 'Font dependencies do not match the project.'+ );+ await expect(readEmbeddedFonts([], document, new Map())).rejects.toThrow(+ 'Font dependencies do not match the project.'+ );+ await expect(readEmbeddedFonts(dependencies, document, new Map())).resolves.toEqual([]);+ });++ it('rejects corrupt and undeclared embedded bytes before any import mutations', async () => {+ const ref = await fontRef();+ const makeArchive = (fonts: unknown[], path: string) =>+ writeArchive(+ new Map([+ [+ 'manifest.json',+ textEntry(+ JSON.stringify({+ appVersion: '7',+ contents: 'workbench-project',+ createdAt: 'now',+ fonts,+ name: 'Fonts',+ version: 2,+ })+ ),+ ],+ ['project.json', textEntry(JSON.stringify(documentWith(ref)))],+ [path, binaryEntry(new Uint8Array([9]))],+ ])+ );+ const entry = `fonts/${ref.contentHash}.ttf`;+ const dependencies = collectFontDependencies(documentWith(ref)).map((item) => ({ ...item, entry }));+ await expect(readInvkArchive(new File([await makeArchive(dependencies, entry)], 'fonts.invk'))).rejects.toThrow(+ 'Invalid embedded font'+ );+ const validFontArchive = await writeArchive(+ new Map([+ [+ 'manifest.json',+ textEntry(+ JSON.stringify({+ appVersion: '7',+ contents: 'workbench-project',+ createdAt: 'now',+ fonts: dependencies,+ name: 'Fonts',+ version: 2,+ })+ ),+ ],+ ['project.json', textEntry(JSON.stringify(documentWith(ref)))],+ [entry, binaryEntry(bytes)],+ ['fonts/../../private.ttf', binaryEntry(new Uint8Array([9]))],+ ])+ );+ await expect(readInvkArchive(new File([validFontArchive], 'fonts.invk'))).rejects.toThrow('not declared');+ });++ it('preflights every font before uploading and cleans up only newly created resources', async () => {+ const transport = await transportFor();+ const dependencies = collectFontDependencies(documentWith(await fontRef()));+ const embedded = [{ bytes, dependency: dependencies[0]!, filename: 'Example.ttf' }];+ transport.validate = () => Promise.reject(new Error('invalid font'));+ await expect(preflightEmbeddedFonts(embedded, transport)).rejects.toThrow('invalid font');+ expect(transport.upload).not.toHaveBeenCalled();++ const ledger = createRestoredFontLedger();+ transport.upload = async () => ({ created: false, font: await fontRef('existing') });+ await restoreEmbeddedFonts(embedded, ledger, transport);+ await rollbackRestoredFonts(ledger, transport);+ expect(transport.remove).not.toHaveBeenCalled();+ transport.upload = async () => ({ created: true, font: await fontRef('new') });+ await restoreEmbeddedFonts(embedded, ledger, transport);+ await rollbackRestoredFonts(ledger, transport);+ expect(transport.remove).toHaveBeenCalledWith('new', undefined);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/fonts.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/fonts.tsnew file mode 100644index 0000000000..973bbf6c91--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/fonts.ts@@ -0,0 +1,219 @@+import { sha256Hex } from '@platform/browser/sha256';+import { z } from 'zod';++import { InvkFormatError } from './format';++const zFontReference = z.object({+ contentHash: z.string().regex(/^[a-f0-9]{64}$/u),+ family: z.string(),+ id: z.string().min(1),+ label: z.string(),+});++export const zInvkFontDependency = z.object({+ contentHash: z.string().regex(/^[a-f0-9]{64}$/u),+ entry: z+ .string()+ .regex(/^fonts\/[a-f0-9]{64}\.(ttf|otf|woff|woff2)$/u)+ .optional(),+ family: z.string(),+ label: z.string(),+ references: z.array(z.string().min(1)).min(1),+});++export type InvkFontReference = z.infer<typeof zFontReference>;+export type InvkFontDependency = z.infer<typeof zInvkFontDependency>;+/** Matches the backend's hard ceiling; the receiving server can configure a lower upload limit. */+export const INVK_MAX_FONT_BYTES = 128 * 1024 * 1024;++const isRecord = (value: unknown): value is Record<string, unknown> =>+ value !== null && typeof value === 'object' && !Array.isArray(value);++/** Only text sources own font references; arbitrary workflow fields are not font dependencies. */+const walkTextSources = (value: unknown, visit: (source: Record<string, unknown>) => void): void => {+ if (Array.isArray(value)) {+ for (const item of value) {+ walkTextSources(item, visit);+ }+ } else if (isRecord(value)) {+ if (value.type === 'text' && 'fontRef' in value) {+ visit(value);+ return;+ }+ for (const child of Object.values(value)) {+ walkTextSources(child, visit);+ }+ }+};++export const collectFontDependencies = (document: Record<string, unknown>): InvkFontDependency[] => {+ const byHash = new Map<string, InvkFontDependency>();+ walkTextSources(document.canvas, (source) => {+ const parsed = zFontReference.safeParse(source.fontRef);+ if (!parsed.success) {+ throw new InvkFormatError('damaged', 'A text layer has an invalid font reference.');+ }+ const ref = parsed.data;+ const dependency = byHash.get(ref.contentHash);+ if (dependency) {+ if (!dependency.references.includes(ref.id)) {+ dependency.references.push(ref.id);+ }+ } else {+ byHash.set(ref.contentHash, {+ contentHash: ref.contentHash,+ family: ref.family,+ label: ref.label,+ references: [ref.id],+ });+ }+ });+ return [...byHash.values()].sort((a, b) => a.contentHash.localeCompare(b.contentHash));+};++export const remapFontReferences = (+ document: Record<string, unknown>,+ byHash: ReadonlyMap<string, InvkFontReference>+): Record<string, unknown> => {+ if (byHash.size === 0) {+ return document;+ }+ const copy = structuredClone(document);+ walkTextSources(copy.canvas, (source) => {+ const ref = zFontReference.parse(source.fontRef);+ const replacement = byHash.get(ref.contentHash);+ if (replacement) {+ source.fontRef = replacement;+ }+ });+ return copy;+};++export interface EmbeddedFont {+ bytes: Uint8Array;+ dependency: InvkFontDependency;+ filename: string;+}++const hasExactReferences = (expected: readonly string[], actual: readonly string[]): boolean => {+ if (expected.length !== actual.length) {+ return false;+ }++ const actualSet = new Set(actual);++ return actualSet.size === actual.length && expected.every((reference) => actualSet.has(reference));+};++/** Checks the dependency manifest against the document and authenticates every embedded payload. */+export const readEmbeddedFonts = async (+ dependencies: readonly InvkFontDependency[],+ document: Record<string, unknown>,+ entries: ReadonlyMap<string, Uint8Array>+): Promise<EmbeddedFont[]> => {+ const required = new Map(collectFontDependencies(document).map((dependency) => [dependency.contentHash, dependency]));+ const byHash = new Map(dependencies.map((dependency) => [dependency.contentHash, dependency]));+ const declaredEntries = new Set(dependencies.flatMap((dependency) => (dependency.entry ? [dependency.entry] : [])));+ if (byHash.size !== dependencies.length) {+ throw new InvkFormatError('damaged', 'Duplicate font dependencies.');+ }+ if (required.size !== byHash.size || [...required.keys()].some((contentHash) => !byHash.has(contentHash))) {+ throw new InvkFormatError('damaged', 'Font dependencies do not match the project.');+ }+ const embedded: EmbeddedFont[] = [];+ for (const dependency of dependencies) {+ const expected = required.get(dependency.contentHash);+ if (!expected || !hasExactReferences(expected.references, dependency.references)) {+ throw new InvkFormatError('damaged', 'Font dependencies do not match the project.');+ }+ if (!dependency.entry) {+ continue;+ }+ const bytes = entries.get(dependency.entry);+ if (+ !dependency.entry.startsWith(`fonts/${dependency.contentHash}.`) ||+ !bytes ||+ bytes.byteLength > INVK_MAX_FONT_BYTES ||+ (await sha256Hex(bytes)) !== dependency.contentHash+ ) {+ throw new InvkFormatError('damaged', `Invalid embedded font: ${dependency.label}`);+ }+ embedded.push({ bytes, dependency, filename: dependency.entry.slice('fonts/'.length) });+ }+ for (const path of entries.keys()) {+ if (path.startsWith('fonts/') && !declaredEntries.has(path)) {+ throw new InvkFormatError('damaged', 'An embedded font is not declared in the manifest.');+ }+ }+ return embedded;+};++export interface FontArchiveTransport {+ download: (dependency: InvkFontDependency, signal?: AbortSignal) => Promise<{ bytes: Uint8Array; filename: string }>;+ validate: (file: File, signal?: AbortSignal) => Promise<void>;+ upload: (file: File, signal?: AbortSignal) => Promise<{ created: boolean; font: InvkFontReference }>;+ remove: (id: string, signal?: AbortSignal) => Promise<void>;+}++export interface RestoredFontLedger {+ createdIds: string[];+ mappings: Map<string, InvkFontReference>;+}++export const createRestoredFontLedger = (): RestoredFontLedger => ({ createdIds: [], mappings: new Map() });++const embeddedFile = (font: EmbeddedFont): File =>+ new File([font.bytes as BlobPart], font.filename, { type: 'application/octet-stream' });++export const preflightEmbeddedFonts = async (+ fonts: readonly EmbeddedFont[],+ transport: FontArchiveTransport,+ signal?: AbortSignal+): Promise<void> => {+ // Validate all files before the first upload, including files later deduplicated by the server.+ for (const font of fonts) {+ signal?.throwIfAborted();+ await transport.validate(embeddedFile(font), signal);+ }+};++export const restoreEmbeddedFonts = async (+ fonts: readonly EmbeddedFont[],+ ledger: RestoredFontLedger,+ transport: FontArchiveTransport,+ signal?: AbortSignal,+ onProgress?: (completed: number, total: number) => void+): Promise<void> => {+ let completed = 0;+ onProgress?.(completed, fonts.length);+ for (const font of fonts) {+ signal?.throwIfAborted();+ const result = await transport.upload(embeddedFile(font), signal);+ if (result.created) {+ ledger.createdIds.push(result.font.id);+ }+ if (result.font.contentHash !== font.dependency.contentHash) {+ throw new InvkFormatError('damaged', 'The uploaded font does not match its archive checksum.');+ }+ ledger.mappings.set(font.dependency.contentHash, result.font);+ completed += 1;+ onProgress?.(completed, fonts.length);+ }+};++export const rollbackRestoredFonts = async (+ ledger: RestoredFontLedger,+ transport: FontArchiveTransport,+ signal?: AbortSignal+): Promise<void> => {+ for (const id of ledger.createdIds) {+ signal?.throwIfAborted();+ try {+ await transport.remove(id, signal);+ } catch {+ // Best effort: cleanup must not mask the import failure or delete pre-existing resources.+ }+ }+ ledger.createdIds = [];+ ledger.mappings.clear();+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/format.tsindex 61909ec7c7..709d1f0e0e 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts@@ -36,6 +36,13 @@ export const INVK_BOARD_ENTRY = 'board.json';export const INVK_IMAGES_PREFIX = 'images/';export const INVK_VIDEOS_PREFIX = 'videos/';+export class FontImportQuotaError extends Error {+ constructor() {+ super('The font library has insufficient space for the embedded fonts.');+ this.name = 'FontImportQuotaError';+ }+}+export type InvkFormatReason =/** A ZIP, but the manifest is a canvas project written by the previous frontend. */| 'legacy-canvas-project'diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.tsindex 573be1b121..f3a038100b 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts@@ -19,6 +19,7 @@ import {uploadBoardVideo,} from './assetTransport';import { parseInvkBoardSnapshot } from './board';+import { type EmbeddedFont, readEmbeddedFonts } from './fonts';import {INVK_BOARD_ENTRY,INVK_DOCUMENT_ENTRY,@@ -50,6 +51,7 @@ export interface InvkArchiveContents {cover: { bytes: Uint8Array; entryName: string } | null;/** Bundled image bytes, keyed by the image name the exporting server used. */images: Map<string, Uint8Array>;+ fonts?: EmbeddedFont[];manifest: InvkManifest;projectDocument: Record<string, unknown>;/** Bundled video bytes, keyed by the video name the exporting server used. */@@ -157,13 +159,16 @@ export const readInvkArchive = async (file: File): Promise<InvkArchiveContents>}const coverBytes = manifest.cover === undefined ? undefined : entries.get(manifest.cover);+ const projectDocument = parseDocumentEntry(documentEntry);+ const fonts = await readEmbeddedFonts(manifest.fonts ?? [], projectDocument, entries);return {boardSnapshot,cover: coverBytes === undefined ? null : { bytes: coverBytes, entryName: manifest.cover! },images,+ fonts,manifest,- projectDocument: parseDocumentEntry(documentEntry),+ projectDocument,videos,};};diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.tsindex 53587d3538..5d058ac5bd 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts@@ -1,5 +1,6 @@import { z } from 'zod';+import { zInvkFontDependency } from './fonts';import { INVK_EXTENSION, INVK_VERSION, InvkFormatError } from './format';/**@@ -39,6 +40,7 @@ const zManifestV2 = z.object({/** Entry path of the preview image, when the archive carries one. */cover: z.string().optional(),createdAt: z.string(),+ fonts: z.array(zInvkFontDependency).optional(),/** Highest canvas schema version required by the source project and its retained history. */minimumCanvasSchemaVersion: z.number().int().min(1).optional(),name: z.string(),@@ -86,6 +88,7 @@ export const buildInvkManifest = (input: {appVersion: string;cover?: string;createdAt: string;+ fonts?: InvkManifest['fonts'];minimumCanvasSchemaVersion?: number;name: string;sourceProjectId?: string;@@ -95,6 +98,7 @@ export const buildInvkManifest = (input: {createdAt: input.createdAt,name: input.name,version: INVK_VERSION,+ ...(input.fonts === undefined || input.fonts.length === 0 ? {} : { fonts: input.fonts }),...(input.cover === undefined ? {} : { cover: input.cover }),...(input.minimumCanvasSchemaVersion === undefined? {}diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.tsindex d47005ad78..2dcd53a70f 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts@@ -141,7 +141,7 @@ describe('refreshProjectLibrary', () => {it('identifies summaries that require a newer canvas reader without fetching the document', async () => {api.listProjects.mockResolvedValue([- { ...summaryDto('future', 'Future', '2026-06-10 10:00:00.000'), minimum_canvas_schema_version: 4 },+ { ...summaryDto('future', 'Future', '2026-06-10 10:00:00.000'), minimum_canvas_schema_version: 5 },]);await library.refreshProjectLibrary();diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.tsindex f0f040fa00..10a7684aad 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts@@ -34,6 +34,13 @@ const api = vi.hoisted(() => ({const downloads = vi.hoisted(() => ({ downloadBlob: vi.fn(), downloadText: vi.fn() }));const covers = vi.hoisted(() => ({ recordProjectCover: vi.fn() }));+const fontTransport = vi.hoisted(() => ({+ download: vi.fn(),+ remove: vi.fn(async () => {}),+ upload: vi.fn(),+ validate: vi.fn(async () => {}),+}));+vi.mock('./invk/fontTransport', () => ({ createFontArchiveTransport: () => fontTransport }));const transport = vi.hoisted(() => ({coverExtensionForMime: () => 'webp',@@ -595,7 +602,7 @@ describe('importing a project board', () => {const rewrittenEntries = new Map([...entries].map(([path, bytes]) => [path, binaryEntry(bytes)]));- rewrittenEntries.set('manifest.json', textEntry(JSON.stringify({ ...manifest, minimumCanvasSchemaVersion: 4 })));+ rewrittenEntries.set('manifest.json', textEntry(JSON.stringify({ ...manifest, minimumCanvasSchemaVersion: 5 })));const archive = new File([await writeArchive(rewrittenEntries)], original.name);await expect(projectFile.importProjectFile(archive)).rejects.toMatchObject({ reason: 'unsupported-version' });@@ -985,3 +992,78 @@ describe('importProjectFile', () => {account.accountLifecycle.invalidate();});});++describe('embedded font project imports', () => {+ const fontProject = async () => {+ const { sha256Hex } = await import('@platform/browser/sha256');+ const bytes = new Uint8Array([0, 1, 0, 0, 4, 5, 6]);+ const font = {+ contentHash: await sha256Hex(bytes),+ family: 'Example',+ id: 'source-font',+ label: 'Example Regular',+ };+ const project = createDraftProject([]);+ const layer = {+ ...rasterImageLayer('text', 'unused.png'),+ source: {+ align: 'left' as const,+ color: '#ffffff',+ content: 'Portable typography',+ fontFamily: 'Example',+ fontRef: font,+ fontSize: 40,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text' as const,+ },+ };+ project.canvas.document.stacks = stacksFrom([layer]);+ fontTransport.download.mockResolvedValue({ bytes, filename: 'Example.ttf' });+ fontTransport.upload.mockResolvedValue({ created: true, font: { ...font, id: 'imported-font' } });+ await projectFile.exportOpenProject(project, { includeFonts: true });+ return capturedArchive();+ };++ it('validates included fonts, installs them privately, and persists remapped references', async () => {+ const archive = await fontProject();+ acceptCreate();+ const result = await projectFile.importProjectFile(archive);+ const { collectFontDependencies } = await import('./invk/fonts');+ expect(collectFontDependencies(result.record.data)[0]?.references).toEqual(['imported-font']);+ expect(fontTransport.validate).toHaveBeenCalledTimes(1);+ expect(fontTransport.upload).toHaveBeenCalledTimes(1);+ expect(fontTransport.remove).not.toHaveBeenCalled();+ });++ it('rejects invalid font payloads before creating any server resources', async () => {+ const archive = await fontProject();+ fontTransport.validate.mockRejectedValue(new Error('Invalid font tables'));+ await expect(projectFile.importProjectFile(archive)).rejects.toThrow('Invalid font tables');+ expect(fontTransport.upload).not.toHaveBeenCalled();+ expect(transport.createStagingBoard).not.toHaveBeenCalled();+ expect(api.createProjectSettled).not.toHaveBeenCalled();+ });++ it('cleans up newly installed fonts only when failed project creation proves absence', async () => {+ const archive = await fontProject();+ const { ProjectCreateAbsentError: AbsentError } = await import('./api');+ api.createProjectSettled.mockRejectedValue(new AbsentError(new Error('rejected')));+ await expect(projectFile.importProjectFile(archive)).rejects.toBeInstanceOf(AbsentError);+ expect(fontTransport.remove).toHaveBeenCalledWith('imported-font', expect.any(AbortSignal));+ fontTransport.remove.mockClear();+ api.createProjectSettled.mockRejectedValue(new Error('Unknown create outcome'));+ await expect(projectFile.importProjectFile(archive)).rejects.toThrow('Unknown create outcome');+ expect(fontTransport.remove).not.toHaveBeenCalled();+ });++ it('allows an explicit references-only retry without installing or deleting fonts', async () => {+ const archive = await fontProject();+ acceptCreate();+ const result = await projectFile.importProjectFile(archive, { skipEmbeddedFonts: true });+ const { collectFontDependencies } = await import('./invk/fonts');+ expect(collectFontDependencies(result.record.data)[0]?.references).toEqual(['source-font']);+ expect(fontTransport.upload).not.toHaveBeenCalled();+ expect(fontTransport.remove).not.toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.tsindex 2bf118b62d..3ee592bb39 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts@@ -76,13 +76,15 @@ export const parseProjectFile = (text: string): Record<string, unknown> | null =*/export interface ProjectFileProgress {completed: number;- phase: 'bundling' | 'packing' | 'restoring';+ phase: 'bundling' | 'packing' | 'restoring' | 'restoring-fonts';total: number;}export interface ProjectFileOptions {onProgress?: (progress: ProjectFileProgress) => void;owner?: AccountScope;+ includeFonts?: boolean;+ skipEmbeddedFonts?: boolean;}export interface ProjectExportOutcome extends ProjectTransferIssues {@@ -141,6 +143,7 @@ const exportProjectDocument = async (minimumCanvasSchemaVersion,name,projectDocument,+ includeFonts: options.includeFonts ?? false,});const result = await executeInvkExport(plan, {@@ -265,6 +268,13 @@ export const importProjectFile = async (const archive = source.format === 'invk' ? source.contents : null;// Loaded only for an archive: a legacy JSON document restores nothing, so it has nothing to undo.const restoreMedia = archive === null ? null : await import('./invk/restoreProjectMedia');+ const fontTransfer = archive?.fonts?.length && !options.skipEmbeddedFonts ? await import('./invk/fonts') : null;+ const fontTransport = fontTransfer ? (await import('./invk/fontTransport')).createFontArchiveTransport() : null;+ const fontLedger = fontTransfer?.createRestoredFontLedger() ?? null;++ if (fontTransfer && fontTransport && archive?.fonts) {+ await fontTransfer.preflightEmbeddedFonts(archive.fonts, fontTransport, owner.signal);+ }assertAccountScopeCurrent(owner);@@ -280,10 +290,22 @@ export const importProjectFile = async (: null;const ledger = restoreMedia?.createRestoredMediaLedger(stagingBoardId) ?? null;let didCreateProject = false;+ let didAttemptProjectCreate = false;try {assertAccountScopeCurrent(owner);+ if (fontTransfer && fontTransport && fontLedger && archive?.fonts) {+ await fontTransfer.restoreEmbeddedFonts(+ archive.fonts,+ fontLedger,+ fontTransport,+ owner.signal,+ (completed, total) => options.onProgress?.({ completed, phase: 'restoring-fonts', total })+ );+ assertAccountScopeCurrent(owner);+ }+const restored =archive === null || ledger === null? null@@ -307,11 +329,14 @@ export const importProjectFile = async (assertAccountScopeCurrent(owner);- const document = restored === null ? canonicalDocument : remapAssetRefs(canonicalDocument, restored.mappings);+ const mediaDocument = restored === null ? canonicalDocument : remapAssetRefs(canonicalDocument, restored.mappings);+ const document =+ fontTransfer && fontLedger ? fontTransfer.remapFontReferences(mediaDocument, fontLedger.mappings) : mediaDocument;const minimumCanvasSchemaVersion = Math.max(getProjectCanvasSchemaRequirement(document),archive?.manifest.minimumCanvasSchemaVersion ?? 1);+ didAttemptProjectCreate = true;const record = await createProjectSettled({data: document,@@ -350,12 +375,23 @@ export const importProjectFile = async (},};} catch (error) {+ if (fontTransfer && fontTransport && fontLedger && isAccountScopeCurrent(owner)) {+ const rollback = () => fontTransfer.rollbackRestoredFonts(fontLedger, fontTransport, owner.signal);+ if (!didAttemptProjectCreate) {+ await rollback();+ } else if (restoreMedia) {+ await restoreMedia.rollbackUnlessProjectExists(error, didCreateProject, owner, rollback);+ }+ }// Reached through the lazily-loaded module, so a legacy JSON import still never pulls the// restore engine into the graph — it has no media to undo.if (ledger !== null && restoreMedia !== null) {- await restoreMedia.rollbackUnlessProjectExists(error, didCreateProject, owner, () =>- restoreMedia.rollbackRestoredMedia(ledger, { signal: owner.signal })- );+ const rollback = () => restoreMedia.rollbackRestoredMedia(ledger, { signal: owner.signal });+ if (!didAttemptProjectCreate && isAccountScopeCurrent(owner)) {+ await rollback();+ } else {+ await restoreMedia.rollbackUnlessProjectExists(error, didCreateProject, owner, rollback);+ }}throw error;diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.tsindex d5c6b27ccc..b067792d0a 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts@@ -49,6 +49,9 @@ const describeProgress = (t: Translate, progress: ProjectFileProgress): string =if (progress.phase === 'packing') {return t('projects.file.packing');}+ if (progress.phase === 'restoring-fonts') {+ return t('projects.fonts.installing', { completed: progress.completed, total: progress.total });+ }const key = progress.phase === 'bundling' ? 'projects.file.bundlingProgress' : 'projects.file.restoringProgress';diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.tsindex 64c8cff66e..03feefba30 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts@@ -123,7 +123,7 @@ describe('project document serialization', () => {it('refuses a document whose canvas was written by a newer client, keeping the raw document', () => {const project = getProject();const document = serializeProjectDocument(project);- const future = { ...document, canvas: { ...(document.canvas as object), version: 4 } };+ const future = { ...document, canvas: { ...(document.canvas as object), version: 5 } };const result = deserializeProjectDocument(future);@@ -131,7 +131,7 @@ describe('project document serialization', () => {refused: {projectId: project.id,raw: future,- refusal: { scope: 'state', status: 'unsupported-version', version: 4 },+ refusal: { scope: 'state', status: 'unsupported-version', version: 5 },source: 'canvas',},status: 'refused',diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.tsindex 82941369df..27701e7811 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts@@ -1,10 +1,12 @@import type { Project } from '@workbench/projectContracts';+import { fontKeys } from '@features/fonts/contracts';import {assertAccountScopeCurrent,captureAccountScope,isAccountScopeCurrent,} from '@platform/state/accountLifecycle';+import { useQueryClient } from '@tanstack/react-query';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -12,6 +14,8 @@ import type { ProjectRecordDTO } from './api';import type { DuplicatedProject } from './library';import type { ProjectFileDirection } from './projectFileErrors';+import { useProjectFileOptions } from './components/ProjectFileOptionsProvider';+import { FontImportQuotaError } from './invk/format';import { duplicateLibraryProject } from './library';import { exportLibraryProject, exportOpenProject, importProjectFile, pickProjectFile } from './projectFile';import { startProjectFileReport } from './projectFileToasts';@@ -56,6 +60,8 @@ const runReported = async <T>(*/export const useImportProjectFile = (onImported: (record: ProjectRecordDTO) => Promise<void> | void): (() => void) => {const { t } = useTranslation();+ const { requestReferencesOnlyImport } = useProjectFileOptions();+ const queryClient = useQueryClient();const importFile = useCallback(async () => {const owner = captureAccountScope();@@ -66,14 +72,30 @@ export const useImportProjectFile = (onImported: (record: ProjectRecordDTO) => P}await runReported(t, { failed: t('projects.importFailed'), running: t('projects.importing') }, async (report) => {- const { record, ...issues } = await importProjectFile(file, { onProgress: report.report, owner });+ let outcome;+ try {+ outcome = await importProjectFile(file, { onProgress: report.report, owner });+ } catch (error) {+ if (!(error instanceof FontImportQuotaError) || !isAccountScopeCurrent(owner)) {+ throw error;+ }+ if (!(await requestReferencesOnlyImport(owner))) {+ report.dismiss();+ return;+ }+ outcome = await importProjectFile(file, { onProgress: report.report, owner, skipEmbeddedFonts: true });+ }+ const { record, ...issues } = outcome;assertAccountScopeCurrent(owner);report.succeed(t('projects.imported', { name: record.name }), issues);await onImported(record);assertAccountScopeCurrent(owner);});- }, [onImported, t]);+ if (isAccountScopeCurrent(owner)) {+ void queryClient.invalidateQueries({ queryKey: fontKeys.all });+ }+ }, [onImported, queryClient, requestReferencesOnlyImport, t]);return useCallback(() => void importFile(), [importFile]);};@@ -81,20 +103,27 @@ export const useImportProjectFile = (onImported: (record: ProjectRecordDTO) => P/** Export a project that is only a library row — its document comes from the server. */export const useExportLibraryProject = (): ((projectId: string, name: string) => void) => {const { t } = useTranslation();+ const { requestExportOptions } = useProjectFileOptions();return useCallback((projectId: string, name: string) => {- void runReported(- t,- { direction: 'write', failed: t('projects.exportFailed'), running: t('projects.exporting', { name }) },- async (report, owner) => {- const issues = await exportLibraryProject(projectId, { onProgress: report.report, owner });-- report.succeed(t('projects.exported', { name }), issues);+ const owner = captureAccountScope();+ void requestExportOptions(name, owner).then(async (options) => {+ if (!options || !isAccountScopeCurrent(owner)) {+ return;}- );+ await runReported(+ t,+ { direction: 'write', failed: t('projects.exportFailed'), running: t('projects.exporting', { name }) },+ async (report) => {+ const issues = await exportLibraryProject(projectId, { ...options, onProgress: report.report, owner });++ report.succeed(t('projects.exported', { name }), issues);+ }+ );+ });},- [t]+ [requestExportOptions, t]);};@@ -137,23 +166,30 @@ export const useDuplicateProject = (/** Export a project that is open in the editor, from its live document. */export const useExportOpenProject = (): ((project: Project) => void) => {const { t } = useTranslation();+ const { requestExportOptions } = useProjectFileOptions();return useCallback((project: Project) => {- void runReported(- t,- {- direction: 'write',- failed: t('projects.exportFailed'),- running: t('projects.exporting', { name: project.name }),- },- async (report, owner) => {- const issues = await exportOpenProject(project, { onProgress: report.report, owner });-- report.succeed(t('projects.exported', { name: project.name }), issues);+ const owner = captureAccountScope();+ void requestExportOptions(project.name, owner).then(async (options) => {+ if (!options || !isAccountScopeCurrent(owner)) {+ return;}- );+ await runReported(+ t,+ {+ direction: 'write',+ failed: t('projects.exportFailed'),+ running: t('projects.exporting', { name: project.name }),+ },+ async (report) => {+ const issues = await exportOpenProject(project, { ...options, onProgress: report.report, owner });++ report.succeed(t('projects.exported', { name: project.name }), issues);+ }+ );+ });},- [t]+ [requestExportOptions, t]);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsxindex a2eb6dc1cb..8196787652 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx@@ -46,6 +46,7 @@ vi.mock('./CanvasGlobalContextMenu', () => ({ CanvasGlobalContextMenu: () => nulvi.mock('./CanvasImageDropOverlay', () => ({ CanvasImageDropOverlay: () => null }));vi.mock('./CanvasSaveToGallerySubmenu', () => ({ CanvasSaveToGallerySubmenu: () => null }));vi.mock('./CanvasSurface', () => ({ CanvasSurface: () => null }));+vi.mock('./MissingFontsDialog', () => ({ MissingFontsDialog: () => null }));vi.mock('./ToolStrip', () => ({ ToolStrip: () => null }));vi.mock('@workbench/widgets/layers/LayerContextMenu', () => ({ CanvasLayerContextMenu: () => null }));@@ -99,7 +100,10 @@ describe('CanvasWidgetView staged acceptance eligibility', () => {harness.engine = null;expect(getAcceptButtonTag(renderView())).toContain('disabled=""');- harness.engine = { layers: { commitStagedImage: vi.fn() } } as unknown as CanvasEngine;+ harness.engine = {+ fonts: { collectReferences: () => [] },+ layers: { commitStagedImage: vi.fn() },+ } as unknown as CanvasEngine;expect(getAcceptButtonTag(renderView())).not.toContain('disabled=""');});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex 9fb8643058..f4dae466dc 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -22,7 +22,7 @@ import {useWorkbenchCommands,useWorkbenchQueries,} from '@workbench/WorkbenchContext';-import { useCallback, useEffect, useEffectEvent, useLayoutEffect, useMemo, useState } from 'react';+import { lazy, Suspense, useCallback, useEffect, useEffectEvent, useLayoutEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { gridSizeForModelBase } from './bboxGrid';@@ -62,6 +62,10 @@ import { useCanvasGallerySave } from './useCanvasGallerySave';import { useCreateFromBbox } from './useCreateFromBbox';import { reportPreparedCommit, reportStructuralCommit } from './useStructuralCommit';+const MissingFontsDialog = lazy(() =>+ import('./MissingFontsDialog').then((module) => ({ default: module.MissingFontsDialog }))+);+/*** The canvas widget shell. The engine owns pixels and interaction and renders* into {@link CanvasSurface}; this component only wires the reducer-backed@@ -82,6 +86,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {const queueItems = useActiveProjectSelector((project) => project.queue.items);const antialiasProgressImages = useActiveProjectSelector((project) => project.settings.antialiasProgressImages);const { document, stagingArea } = canvas;+ const fontReferences = useMemo(() => engine?.fonts.collectReferences(document) ?? [], [document, engine]);const operation = useCanvasOperation(engine);const operationKind = operation?.status === 'active' ? operation.identity.kind : null;// An operation's panel supersedes any pending layer-properties request.@@ -510,6 +515,11 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {w="full"><CanvasColorFeed engine={engine} />+ {engine && fontReferences.length > 0 ? (+ <Suspense fallback={null}>+ <MissingFontsDialog key={projectId} engine={engine} groups={fontReferences} />+ </Suspense>+ ) : null}<CanvasSurfaceContextLayout surface={canvasSurface} onContextMenu={handleSurfaceContextMenu}><CanvasImageDropOverlayisDocumentEditingLocked={interactionCapabilities.isDocumentEditingLocked}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.browser.test.tsxnew file mode 100644index 0000000000..5922588d56--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.browser.test.tsx@@ -0,0 +1,137 @@+import type * as FontsFeature from '@features/fonts';+import type { CanvasEngine } from '@workbench/canvas-engine/api';++import { ChakraProvider } from '@chakra-ui/react';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { ApiError } from '@platform/transport/http';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { createEmptyCanvasState } from '@workbench/canvasMigration';+import axe from 'axe-core';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, expect, it, vi } from 'vitest';+import { page } from 'vitest/browser';++import { MissingFontsDialog } from './MissingFontsDialog';++const api = vi.hoisted(() => ({ getFont: vi.fn(), listFonts: vi.fn() }));+vi.mock('@features/fonts', async (original) => ({ ...(await original<typeof FontsFeature>()), ...api }));+const i18n = createInstance();+await i18n.use(initReactI18next).init({+ interpolation: { escapeValue: false },+ lng: 'en',+ fallbackNS: 'translation',+ resources: {+ en: {+ translation: await fetch('/locales/en.json').then((response) => response.json()),+ fonts: await fetch('/locales/en.fonts.json').then((response) => response.json()),+ },+ },+});+let root: Root | undefined;+let host: HTMLDivElement | undefined;+let client: QueryClient | undefined;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+const missing = { id: 'missing', contentHash: 'a'.repeat(64), family: 'Lost Sans', label: 'Lost Sans Regular' };+const replacement = {+ id: 'replacement',+ contentHash: 'b'.repeat(64),+ family: 'Available Sans',+ label: 'Available Sans Variable',+ style: 'italic',+ weight: 700,+ axes: [{ tag: 'wdth', minimum: 50, maximum: 150, default: 100 }],+};+const replaceAllReferences = vi.fn(() => ({ status: 'committed' }));+const engine = {+ fonts: {+ collectReferences: () => [{ fontRef: missing, count: 3, layerIds: ['a', 'b', 'c'] }],+ replaceAllReferences,+ },+} as unknown as CanvasEngine;++const render = async (total = 1) => {+ await page.viewport(1280, 900);+ accountLifecycle.activate('font-recovery');+ replaceAllReferences.mockClear();+ api.getFont.mockRejectedValue(new ApiError('Missing font', 404));+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ client.setQueryData(['fonts', 'catalog', { limit: 50, search: '' }], { items: [replacement], total });+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root!.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <QueryClientProvider client={client!}>+ <MissingFontsDialog+ engine={engine}+ groups={engine.fonts.collectReferences(createEmptyCanvasState().document)}+ />+ </QueryClientProvider>+ </I18nextProvider>+ </ChakraProvider>+ )+ );+};+afterEach(async () => {+ await act(() => root?.unmount());+ client?.clear();+ host?.remove();+ accountLifecycle.invalidate();+});++it('groups affected layers, keeps a warning after dismissal, and reopens recovery', async () => {+ await render();+ await expect.element(page.getByRole('dialog', { name: 'Missing fonts' })).toBeVisible();+ await expect.element(page.getByText('Used by 3 text layers')).toBeVisible();+ await expect.element(page.getByRole('button', { name: 'Replace all uses' })).toBeDisabled();+ expect((await axe.run(document.querySelector('[role="dialog"]')!)).violations).toEqual([]);+ await page.screenshot({ path: '../../../../artifacts/fonts/missing-fonts-dialog.png' });+ await act(() => page.getByRole('button', { name: 'Continue with previews' }).click());+ await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();+ await act(() => page.getByRole('button', { name: 'Missing font — review' }).click());+ await expect.element(page.getByRole('dialog')).toBeVisible();+});++it('replaces every use through the undoable Canvas capability with target axis limits', async () => {+ await render();+ await act(() => page.getByRole('combobox', { name: 'Replacement font' }).selectOptions('replacement'));+ await act(() => page.getByRole('button', { name: 'Replace all uses' }).click());+ expect(replaceAllReferences).toHaveBeenCalledWith(missing, {+ fontRef: {+ id: replacement.id,+ contentHash: replacement.contentHash,+ family: replacement.family,+ label: replacement.label,+ },+ axes: replacement.axes,+ style: replacement.style,+ weight: replacement.weight,+ });+});++it('browses replacements beyond the first catalog page and preserves selection across pages', async () => {+ const later = { ...replacement, id: 'later', label: 'Later page font' };+ await render(101);+ client!.setQueryData(['fonts', 'catalog', { limit: 50, search: '', offset: 50 }], {+ items: [later],+ total: 101,+ offset: 50,+ limit: 50,+ });+ await act(() => page.getByRole('button', { name: 'Next page' }).click());+ await expect.element(page.getByRole('option', { name: later.label })).toBeInTheDocument();+ await act(() => page.getByRole('combobox', { name: 'Replacement font' }).selectOptions('later'));+ await act(() => page.getByRole('button', { name: 'Previous page' }).click());+ await expect.element(page.getByRole('combobox', { name: 'Replacement font' })).toHaveValue('later');+ await act(() => page.getByRole('button', { name: 'Replace all uses' }).click());+ expect(replaceAllReferences).toHaveBeenCalledWith(+ missing,+ expect.objectContaining({ fontRef: expect.objectContaining({ id: 'later' }) })+ );+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.tsxnew file mode 100644index 0000000000..bfeb1c7cb7--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.tsx@@ -0,0 +1,264 @@+import type { CanvasEngine, CanvasFontCapability } from '@workbench/canvas-engine/api';++import { Box, Dialog, Flex, Input, NativeSelect, Portal, Stack, Text } from '@chakra-ui/react';+import { fontKeys, fontsQueryOptions, getFont, uploadFont, type FontRecord } from '@features/fonts';+import { useMountEffect } from '@platform/react/useMountEffect';+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { Button, CloseButton } from '@platform/ui';+import { useQueries, useQuery, useQueryClient } from '@tanstack/react-query';+import { registerHotkeyModalLayer } from '@workbench/hotkeys/modalLayer';+import { useCallback, useDeferredValue, useMemo, useRef, useState, type ChangeEvent } from 'react';+import { useTranslation } from 'react-i18next';++type FontGroup = ReturnType<CanvasFontCapability['collectReferences']>[number];++export const MissingFontsDialog = ({ engine, groups }: { engine: CanvasEngine; groups: readonly FontGroup[] }) => {+ const { t } = useTranslation('fonts');+ const queries = useQueries({+ queries: groups.map(({ fontRef }) => ({+ queryKey: fontKeys.detail(fontRef.id),+ queryFn: ({ signal }: { signal: AbortSignal }) => getFont(fontRef.id, signal),+ retry: false,+ staleTime: 30_000,+ })),+ });+ const unavailable = useMemo(+ () =>+ groups.filter((group, index) => {+ const query = queries[index];+ return query && !query.isPending && (query.isError || query.data?.contentHash !== group.fontRef.contentHash);+ }),+ [groups, queries]+ );+ const signature = JSON.stringify(unavailable.map(({ fontRef }) => [fontRef.id, fontRef.contentHash]));+ const [dismissed, setDismissed] = useState<string | null>(null);+ const close = useCallback(() => setDismissed(signature), [signature]);+ const reopen = useCallback(() => setDismissed(null), []);+ if (!unavailable.length) {+ return null;+ }+ return (+ <>+ <Box position="absolute" top="2" left="50%" transform="translateX(-50%)" zIndex="2">+ <Button colorPalette="orange" size="xs" onClick={reopen}>+ {t('fonts.missing.warning', { count: unavailable.length })}+ </Button>+ </Box>+ {dismissed !== signature ? <RecoveryDialog groups={unavailable} engine={engine} onClose={close} /> : null}+ </>+ );+};++const RecoveryDialog = ({+ groups,+ engine,+ onClose,+}: {+ groups: FontGroup[];+ engine: CanvasEngine;+ onClose: () => void;+}) => {+ const { t } = useTranslation('fonts');+ const queryClient = useQueryClient();+ useMountEffect(() => registerHotkeyModalLayer('missing-fonts'));+ const onOpenChange = useCallback(+ ({ open }: { open: boolean }) => {+ if (!open) {+ onClose();+ }+ },+ [onClose]+ );+ const retry = useCallback(() => {+ void queryClient.invalidateQueries({ queryKey: fontKeys.all });+ }, [queryClient]);+ return (+ <Dialog.Root open placement="center" size="lg" scrollBehavior="inside" onOpenChange={onOpenChange}>+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content>+ <Dialog.Header>+ <Dialog.Title>{t('fonts.missing.title')}</Dialog.Title>+ </Dialog.Header>+ <Dialog.Body>+ <Stack gap="4">+ <Text color="fg.muted" fontSize="sm">+ {t('fonts.missing.description')}+ </Text>+ {groups.map((group) => (+ <RecoveryRow key={`${group.fontRef.id}:${group.fontRef.contentHash}`} group={group} engine={engine} />+ ))}+ </Stack>+ </Dialog.Body>+ <Dialog.Footer>+ <Button color="fg" variant="outline" onClick={retry}>+ {t('common.retry')}+ </Button>+ <Button colorPalette="accent" onClick={onClose}>+ {t('fonts.missing.continue')}+ </Button>+ </Dialog.Footer>+ <Dialog.CloseTrigger asChild>+ <CloseButton aria-label={t('common.close')} />+ </Dialog.CloseTrigger>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ );+};++const RecoveryRow = ({ group, engine }: { group: FontGroup; engine: CanvasEngine }) => {+ const { t } = useTranslation('fonts');+ const queryClient = useQueryClient();+ const [search, setSearch] = useState('');+ const deferredSearch = useDeferredValue(search);+ const [offset, setOffset] = useState(0);+ const catalog = useQuery(fontsQueryOptions({ limit: 50, search: deferredSearch, ...(offset ? { offset } : {}) }));+ const [selected, setSelected] = useState<FontRecord | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const inputRef = useRef<HTMLInputElement>(null);+ const [owner] = useState(captureAccountScope);+ const searchChanged = useCallback((event: ChangeEvent<HTMLInputElement>) => {+ setSearch(event.target.value);+ setOffset(0);+ }, []);+ const previousPage = useCallback(() => setOffset((current) => Math.max(0, current - 50)), []);+ const nextPage = useCallback(() => setOffset((current) => current + 50), []);+ const selectionChanged = useCallback(+ (event: ChangeEvent<HTMLSelectElement>) => {+ setSelected(catalog.data?.items.find((font) => font.id === event.target.value) ?? null);+ },+ [catalog.data]+ );+ const retryCatalog = useCallback(() => void catalog.refetch(), [catalog]);+ const chooseFile = useCallback(() => inputRef.current?.click(), []);+ const uploaded = useCallback(+ async (event: ChangeEvent<HTMLInputElement>) => {+ const file = event.target.files?.[0];+ event.target.value = '';+ if (!file || !isAccountScopeCurrent(owner)) {+ return;+ }+ setBusy(true);+ setError(null);+ try {+ const result = await uploadFont(file, 'private', owner.signal);+ if (!isAccountScopeCurrent(owner)) {+ return;+ }+ setSelected(result.font);+ await queryClient.invalidateQueries({ queryKey: fontKeys.all });+ } catch (failure) {+ if (isAccountScopeCurrent(owner)) {+ setError(failure instanceof Error ? failure.message : t('fonts.missing.failed'));+ }+ } finally {+ if (isAccountScopeCurrent(owner)) {+ setBusy(false);+ }+ }+ },+ [owner, queryClient, t]+ );+ const replace = useCallback(() => {+ if (!selected || !isAccountScopeCurrent(owner)) {+ return;+ }+ const result = engine.fonts.replaceAllReferences(group.fontRef, {+ fontRef: { id: selected.id, contentHash: selected.contentHash, family: selected.family, label: selected.label },+ axes: selected.axes,+ style: selected.style === 'italic' || selected.style === 'oblique' ? selected.style : 'normal',+ weight: selected.weight,+ });+ if (result.status !== 'committed' && result.status !== 'unchanged') {+ setError(t('fonts.missing.failed'));+ }+ }, [engine, group.fontRef, owner, selected, t]);+ const choices =+ selected && !catalog.data?.items.some((font) => font.id === selected.id)+ ? [selected, ...(catalog.data?.items ?? [])]+ : (catalog.data?.items ?? []);+ return (+ <Stack borderWidth="1px" borderRadius="md" p="3" gap="2">+ <Text fontWeight="medium">{group.fontRef.label}</Text>+ <Text color="fg.muted" fontSize="xs">+ {t('fonts.missing.layers', { count: group.count })}+ </Text>+ <Input+ aria-label={t('fonts.missing.search')}+ placeholder={t('fonts.missing.search')}+ size="sm"+ value={search}+ onChange={searchChanged}+ />+ <NativeSelect.Root size="sm">+ <NativeSelect.Field+ aria-label={t('fonts.missing.replacement')}+ value={selected?.id ?? ''}+ onChange={selectionChanged}+ >+ <option value="">{t('fonts.missing.select')}</option>+ {choices.map((font) => (+ <option key={font.id} value={font.id}>+ {font.label}+ </option>+ ))}+ </NativeSelect.Field>+ <NativeSelect.Indicator />+ </NativeSelect.Root>+ {offset > 0 || (catalog.data?.total ?? 0) > 50 ? (+ <Flex gap="2" justify="flex-end">+ <Button+ size="xs"+ variant="outline"+ color="fg"+ disabled={offset === 0 || catalog.isFetching}+ onClick={previousPage}+ >+ {t('common.previousPage')}+ </Button>+ <Button+ size="xs"+ variant="outline"+ color="fg"+ disabled={catalog.isFetching || offset + 50 >= (catalog.data?.total ?? 0)}+ onClick={nextPage}+ >+ {t('common.nextPage')}+ </Button>+ </Flex>+ ) : null}+ {catalog.isPending ? <Text fontSize="xs">{t('common.loading')}</Text> : null}+ {catalog.isError ? (+ <Text role="alert" color="fg.error" fontSize="xs">+ {t('fonts.missing.catalogError')}+ <Button size="xs" color="fg" variant="outline" ml="2" onClick={retryCatalog}>+ {t('common.retry')}+ </Button>+ </Text>+ ) : null}+ {selected ? (+ <Text fontSize="xs" color="fg.muted">+ {t('fonts.missing.axesNotice')}+ </Text>+ ) : null}+ {error ? (+ <Text role="alert" color="fg.error" fontSize="xs">+ {error}+ </Text>+ ) : null}+ <Flex gap="2" justify="flex-end">+ <input ref={inputRef} type="file" accept=".ttf,.otf,.woff,.woff2" hidden onChange={uploaded} />+ <Button color="fg" variant="outline" size="sm" loading={busy} onClick={chooseFile}>+ {t('fonts.missing.upload')}+ </Button>+ <Button colorPalette="accent" size="sm" disabled={!selected || busy} onClick={replace}>+ {t('fonts.missing.replaceAll')}+ </Button>+ </Flex>+ </Stack>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.browser.test.tsxindex d0bb7c94eb..72293570e7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.browser.test.tsx@@ -8,6 +8,7 @@ import { system } from '@theme/system';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';+import { page } from 'vitest/browser';import { StagingItemContextMenu } from './StagingItemContextMenu';@@ -100,8 +101,12 @@ const menuItem = (label: string): HTMLElement => {return item;};-/** Selects a menu item the way a mouse does: highlight it (zag selects the highlighted item), then click. */+/** Real pointer events let the menu finish highlighting before selection; disabled rows remain inert under synthetic clicks too. */const activate = async (label: string): Promise<void> => {+ if (menuItem(label).getAttribute('aria-disabled') !== 'true') {+ await act(() => page.getByRole('menuitem', { name: label, exact: true }).click());+ return;+ }await interact(() =>menuItem(label).dispatchEvent(new PointerEvent('pointermove', { bubbles: true, pointerType: 'mouse' })));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.browser.test.tsxindex faf632a657..b62b7ee8af 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.browser.test.tsx@@ -43,7 +43,15 @@ const session = (overrides: Partial<TextEditSession> = {}): TextEditSession =>* A minimal engine double: the portal only needs the interaction store to read* the session, the layers commands it drives, and a viewport for positioning.*/-const createEngine = (initialSession: TextEditSession | null) => {+const createEngine = (+ initialSession: TextEditSession | null,+ fonts?: {+ ensurePreview: (source: TextEditSession['source'], signal?: AbortSignal) => Promise<string>;+ resolveFamily: (source: TextEditSession['source']) => string;+ subscribe: (listener: () => void) => () => void;+ },+ closeOnCommand = false+) => {let current = initialSession;const listeners = new Set<() => void>();const layers = {@@ -67,16 +75,25 @@ const createEngine = (initialSession: TextEditSession | null) => {},layers,viewport: { getViewport: () => viewport },+ ...(fonts ? { fonts } : {}),};const setSession = (next: TextEditSession | null) => {current = next;listeners.forEach((listener) => listener());};+ if (closeOnCommand) {+ layers.cancelTextEdit.mockImplementation(() => setSession(null));+ layers.commitTextEdit.mockImplementation(() => {+ setSession(null);+ return null;+ });+ }return { engine: engine as unknown as Parameters<typeof TextEditPortal>[0]['engine'], layers, setSession };};const mount = (engine: Parameters<typeof TextEditPortal>[0]['engine']) => {const host = window.document.createElement('div');+ host.tabIndex = -1;window.document.body.append(host);const root = createRoot(host);act(() => root.render(<TextEditPortal engine={engine} />));@@ -106,6 +123,8 @@ describe('TextEditPortal', () => {expect(el.textContent).toBe('hello');expect(window.document.activeElement).toBe(el);expect(el.dataset.seeded).toBe('true');+ expect(el.getAttribute('aria-label')).toBe('widgets.canvas.toolOptions.textEdit');+ expect(el.getAttribute('aria-multiline')).toBe('true');});it('places the caret at the end of the seeded content', () => {@@ -144,6 +163,61 @@ describe('TextEditPortal', () => {expect(layers.commitTextEdit).toHaveBeenCalledWith('edited');});+ it.each(['busy', 'gesture-active', 'not-ready'] as const)(+ 'keeps focus in the editable when a keyboard commit is refused as %s',+ (status) => {+ const { engine, layers } = createEngine(session());+ layers.commitTextEdit.mockReturnValue({ status });+ const { host } = mount(engine);+ const el = editableIn(host);+ el.textContent = 'retry this text';+ act(() => {+ el.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter', metaKey: true }));+ });+ expect(layers.commitTextEdit).toHaveBeenCalledExactlyOnceWith('retry this text');+ expect(host.querySelector('[role="textbox"]')).toBe(el);+ expect(document.activeElement).toBe(el);+ }+ );++ it.each(['commit', 'cancel'] as const)(+ 'restores CanvasSurface focus when keyboard %s unmounts the editable',+ (action) => {+ const { engine, layers } = createEngine(session(), undefined, true);+ const { host } = mount(engine);+ const el = editableIn(host);++ act(() => {+ el.dispatchEvent(+ new KeyboardEvent('keydown', {+ bubbles: true,+ key: action === 'commit' ? 'Enter' : 'Escape',+ ...(action === 'commit' ? { ctrlKey: true } : {}),+ })+ );+ });++ expect(action === 'commit' ? layers.commitTextEdit : layers.cancelTextEdit).toHaveBeenCalledTimes(1);+ expect(layers.commitTextEdit).toHaveBeenCalledTimes(action === 'commit' ? 1 : 0);+ expect(host.querySelector('[role="textbox"]')).toBeNull();+ expect(document.activeElement).toBe(host);+ }+ );++ it('keeps the pointer blur destination focused while committing the edited text', () => {+ const { engine, layers } = createEngine(session());+ const { host } = mount(engine);+ const el = editableIn(host);+ const destination = document.createElement('button');+ destination.textContent = 'Elsewhere';+ host.append(destination);+ el.textContent = 'pointer edit';++ act(() => destination.focus());+ expect(layers.commitTextEdit).toHaveBeenCalledWith('pointer edit');+ expect(document.activeElement).toBe(destination);+ });+it('commits on mod+enter and cancels on escape', () => {const { engine, layers } = createEngine(session());const { host } = mount(engine);@@ -206,4 +280,50 @@ describe('TextEditPortal', () => {expect(el.style.whiteSpace).toBe('pre');expect(el.style.color).toBe('rgb(255, 0, 0)');});++ it('loads the active custom source and updates overlay metrics when its family becomes ready', async () => {+ let resolvePreview!: (family: string) => void;+ let resolvedFamily = 'fallback-family';+ const listeners = new Set<() => void>();+ const ensurePreview = vi.fn(+ (_source: TextEditSession['source'], _signal?: AbortSignal) =>+ new Promise<string>((resolve) => {+ resolvePreview = resolve;+ })+ );+ const fonts = {+ ensurePreview,+ resolveFamily: vi.fn(() => resolvedFamily),+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+ const source = {+ ...session().source,+ fontFamily: 'Catalog Family',+ fontRef: { contentHash: 'hash', family: 'Catalog Family', id: 'font-1', label: 'Catalog Regular' },+ };+ const { engine } = createEngine(session({ source }), fonts);+ const { host, root } = mount(engine);+ expect(ensurePreview).toHaveBeenCalledWith(source, expect.any(AbortSignal));+ expect(editableIn(host).style.fontFamily).toBe('fallback-family');+ expect(listeners.size).toBeGreaterThan(0);++ await act(async () => {+ resolvedFamily = 'loaded-family';+ resolvePreview('loaded-family');+ listeners.forEach((listener) => listener());+ await Promise.resolve();+ });+ expect(fonts.resolveFamily).toHaveBeenCalledWith(source);+ expect(fonts.resolveFamily.mock.results.at(-1)?.value).toBe('loaded-family');+ await vi.waitFor(() => expect(editableIn(host).style.fontFamily).toBe('loaded-family'));++ const previewSignal = ensurePreview.mock.calls[0]?.[1] as AbortSignal;+ act(() => root.unmount());+ mounted.pop();+ host.remove();+ expect(previewSignal.aborted).toBe(true);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsxindex 9afdf1295d..533711eda8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx@@ -3,13 +3,21 @@ import type { TextEditSession } from '@workbench/canvas-engine/api';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { CSSProperties, KeyboardEvent as ReactKeyboardEvent } from 'react';+import { useMountEffect } from '@platform/react/useMountEffect';import { useNotify } from '@workbench/useNotify';import { useTextEditSession } from '@workbench/widgets/canvas/engineStoreHooks';import { reportStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';-import { useCallback, useSyncExternalStore } from 'react';+import { useCallback, useRef, useSyncExternalStore } from 'react';import { useTranslation } from 'react-i18next';-type TextEditEngine = Pick<CanvasEngineHandle, 'interaction' | 'layers' | 'viewport'>;+type TextEditEngine = Pick<CanvasEngineHandle, 'interaction' | 'layers' | 'viewport'> &+ Partial<Pick<CanvasEngineHandle, 'fonts'>>;++const textFontVariationSettings = (source: TextEditSession['source']): string =>+ Object.entries(source.fontVariations ?? {})+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([tag, value]) => `"${tag}" ${value}`)+ .join(', ');/*** The text-editing portal: a positioned `contenteditable` div, rendered over the@@ -47,6 +55,45 @@ const useViewportTick = (engine: TextEditEngine): string => {return '';};+/** Re-renders when the account-scoped runtime registers or evicts a custom face. */+const useResolvedFontFamily = (engine: TextEditEngine, source: TextEditSession['source']): string => {+ const fonts = engine.fonts;+ const subscribe = useCallback((onChange: () => void) => fonts?.subscribe(onChange) ?? (() => {}), [fonts]);+ const getSnapshot = useCallback(() => fonts?.resolveFamily(source) ?? source.fontFamily, [fonts, source]);+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);+};++const textFontKey = (source: TextEditSession['source']): string =>+ JSON.stringify([+ source.fontRef?.id ?? null,+ source.fontRef?.contentHash ?? null,+ source.fontFamily,+ source.fontStyle ?? 'normal',+ source.fontWeight,+ Object.entries(source.fontVariations ?? {})+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([tag, value]) => [tag, value]),+ ]);++/** Keeps the active edit source loading until it is replaced or the portal unmounts. */+const TextFontReadiness = ({+ fonts,+ source,+}: {+ fonts: TextEditEngine['fonts'];+ source: TextEditSession['source'];+}) => {+ useMountEffect(() => {+ if (!fonts || typeof fonts.ensurePreview !== 'function') {+ return;+ }+ const controller = new AbortController();+ void fonts.ensurePreview(source, controller.signal).catch(() => undefined);+ return () => controller.abort();+ });+ return null;+};+/** Reads the editable's text with manual line breaks preserved (`\n` per visual line). */const readEditableText = (el: HTMLElement): string => el.innerText;@@ -63,6 +110,25 @@ const placeCaretAtEnd = (el: HTMLElement): void => {selection.addRange(range);};+/** Returns keyboard focus to the focusable CanvasSurface container after closing the editor. */+const restoreCanvasFocus = (+ surface: HTMLElement | null,+ editable: HTMLElement,+ ignoreNextBlur: { current: boolean }+): void => {+ if (!(surface instanceof HTMLElement) || surface.tabIndex !== -1) {+ return;+ }++ if (document.activeElement === editable) {+ ignoreNextBlur.current = true;+ }+ surface.focus({ preventScroll: true });+ if (document.activeElement !== surface && ignoreNextBlur.current) {+ ignoreNextBlur.current = false;+ }+};+interface TextEditableProps {engine: TextEditEngine;session: TextEditSession;@@ -78,6 +144,8 @@ const TextEditable = ({ engine, session }: TextEditableProps) => {useViewportTick(engine);const viewport = engine.viewport.getViewport();const { source, transform } = session;+ const resolvedFontFamily = useResolvedFontFamily(engine, source);+ const ignoreNextBlur = useRef(false);// Seeds content + focus once when the element mounts, and registers a live-// content reader with the engine so it can commit on a canvas pointerdown@@ -115,7 +183,16 @@ const TextEditable = ({ engine, session }: TextEditableProps) => {},[engine, notify, t]);- const onBlur = useCallback((event: { currentTarget: HTMLElement }) => commit(event.currentTarget), [commit]);+ const onBlur = useCallback(+ (event: { currentTarget: HTMLElement }) => {+ if (ignoreNextBlur.current) {+ ignoreNextBlur.current = false;+ return;+ }+ commit(event.currentTarget);+ },+ [commit]+ );const onKeyDown = useCallback((event: ReactKeyboardEvent<HTMLDivElement>) => {@@ -123,12 +200,20 @@ const TextEditable = ({ engine, session }: TextEditableProps) => {event.stopPropagation();if (event.key === 'Escape') {event.preventDefault();+ const surface = event.currentTarget.parentElement;engine.layers.cancelTextEdit();+ if (engine.interaction.get('textEditSession') === null) {+ restoreCanvasFocus(surface, event.currentTarget, ignoreNextBlur);+ }return;}if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {event.preventDefault();+ const surface = event.currentTarget.parentElement;commit(event.currentTarget);+ if (engine.interaction.get('textEditSession') === null) {+ restoreCanvasFocus(surface, event.currentTarget, ignoreNextBlur);+ }}},[commit, engine]@@ -142,8 +227,10 @@ const TextEditable = ({ engine, session }: TextEditableProps) => {border: 'none',color: source.color,cursor: 'text',- fontFamily: source.fontFamily,+ fontFamily: resolvedFontFamily,fontSize: `${source.fontSize}px`,+ fontStyle: source.fontStyle ?? 'normal',+ fontVariationSettings: textFontVariationSettings(source) || 'normal',fontWeight: source.fontWeight,left: 0,lineHeight: source.lineHeight,@@ -163,7 +250,8 @@ const TextEditable = ({ engine, session }: TextEditableProps) => {return (<div- aria-label="Text editor"+ aria-label={t('widgets.canvas.toolOptions.textEdit')}+ aria-multilinecontentEditabledir="auto"ref={setRef}@@ -183,5 +271,10 @@ export const TextEditPortal = ({ engine }: { engine: TextEditEngine }) => {if (!session) {return null;}- return <TextEditable key={session.id} engine={engine} session={session} />;+ return (+ <>+ <TextFontReadiness key={textFontKey(session.source)} fonts={engine.fonts} source={session.source} />+ <TextEditable key={session.id} engine={engine} session={session} />+ </>+ );};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.tsindex fb94dba24b..b1b4bff654 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts@@ -604,7 +604,6 @@ describe('runCanvasInvocation', () => {const captureRasterSnapshot = vi.fn(() => Promise.resolve({ status: 'aborted' as const }));harness.host.captureRasterSnapshot = captureRasterSnapshot;harness.deps.signal = controller.signal;- controller.abort(new DOMException('invoke cancelled', 'AbortError'));await runCanvasInvocation(harness.deps);@@ -616,6 +615,22 @@ describe('runCanvasInvocation', () => {expect(harness.submittedGraphs()).toHaveLength(0);});+ it('does not start raster capture when the orchestration signal is already aborted', async () => {+ const harness = makeHarness();+ const controller = new AbortController();+ const captureRasterSnapshot = vi.fn(harness.host.captureRasterSnapshot);+ harness.host.captureRasterSnapshot = captureRasterSnapshot;+ harness.deps.signal = controller.signal;+ controller.abort(new DOMException('invoke cancelled', 'AbortError'));++ await runCanvasInvocation(harness.deps);++ expect(captureRasterSnapshot).not.toHaveBeenCalled();+ expect(harness.uploadImage).not.toHaveBeenCalled();+ expect(harness.submittedGraphs()).toHaveLength(0);+ expect(harness.notices()).toHaveLength(0);+ });+it('quietly stops when its account signal expires during composition', async () => {const harness = makeHarness();const controller = new AbortController();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.browser.test.tsxnew file mode 100644index 0000000000..df6446da8f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.browser.test.tsx@@ -0,0 +1,351 @@+import type { FontRecord } from '@features/fonts';+import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';+import type { ToolFormProps } from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';++import { ChakraProvider } from '@chakra-ui/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page } from 'vitest/browser';++const mocks = vi.hoisted(() => {+ const font: FontRecord = {+ axes: [+ { default: 400, hidden: false, label: 'Weight', maximum: 900, minimum: 100, tag: 'wght' },+ { default: 0, hidden: false, label: 'Italic', maximum: 1, minimum: 0, tag: 'ital' },+ { default: 100, hidden: true, label: 'Width', maximum: 125, minimum: 75, tag: 'wdth' },+ ],+ byteSize: 1024,+ contentHash: 'a'.repeat(64),+ family: 'Variable Sans',+ filename: 'variable-sans.ttf',+ id: 'variable-sans',+ instances: [{ coordinates: { wdth: 75, wght: 400 }, name: 'Condensed' }],+ label: 'Variable Sans Regular',+ scope: 'private',+ source: 'uploaded',+ style: 'normal',+ url: '/fonts/variable-sans.ttf',+ weight: 400,+ };+ return {+ font,+ fontsInfiniteQueryOptions: vi.fn(),+ useActiveColorPair: vi.fn(() => ({ background: '#000000', foreground: '#ffffff' })),+ useActiveColorCommands: vi.fn(() => ({ setPairColor: vi.fn() })),+ useActiveProjectSelector: vi.fn(() => null),+ useColorSampler: vi.fn(() => undefined),+ usePreparedCommit: vi.fn(() => vi.fn()),+ useTextEditSession: vi.fn(() => null),+ useTextOptions: vi.fn(() => ({+ align: 'left' as const,+ color: '#ffffff',+ fontFamily: 'Variable Sans',+ fontRef: {+ contentHash: 'a'.repeat(64),+ family: 'Variable Sans',+ id: 'variable-sans',+ label: 'Variable Sans Regular',+ },+ fontSize: 32,+ fontStyle: 'normal' as const,+ fontVariations: { ital: 0, wdth: 100, wght: 650 },+ fontWeight: 650,+ lineHeight: 1.2,+ })),+ };+});++vi.mock('@features/fonts', () => ({+ fontsInfiniteQueryOptions: mocks.fontsInfiniteQueryOptions,+}));+vi.mock('@workbench/WorkbenchContext', () => ({ useActiveProjectSelector: mocks.useActiveProjectSelector }));+vi.mock('@workbench/widgets/canvas/color-system/useActiveColors', () => ({+ useActiveColorCommands: mocks.useActiveColorCommands,+ useActiveColorPair: mocks.useActiveColorPair,+}));+vi.mock('@workbench/widgets/canvas/engineStoreHooks', () => ({+ useTextEditSession: mocks.useTextEditSession,+ useTextOptions: mocks.useTextOptions,+}));+vi.mock('@workbench/widgets/canvas/useColorSampler', () => ({ useColorSampler: mocks.useColorSampler }));+vi.mock('@workbench/widgets/canvas/useStructuralCommit', () => ({ usePreparedCommit: mocks.usePreparedCommit }));++import { textForm } from './textForm';+import { canonicalizeSelectedTextSource } from './TextOptions';++const i18n = createInstance();+const queryClient = new QueryClient();+await i18n.use(initReactI18next).init({+ lng: 'en',+ resources: {+ en: {+ translation: {+ 'widgets.canvas.toolOptions.textFont': 'Font',+ 'widgets.canvas.toolOptions.textFontAxes': 'Axes',+ 'widgets.canvas.toolOptions.textFontCustomGroup': 'Custom fonts',+ 'widgets.canvas.toolOptions.textFontDefaultPreset': 'Default',+ 'widgets.canvas.toolOptions.textFontHideAdvancedAxes': 'Hide hidden axes',+ 'widgets.canvas.toolOptions.textFontPreset': 'Preset',+ 'widgets.canvas.toolOptions.textFontResetAxes': 'Reset axes',+ 'widgets.canvas.toolOptions.textFontShowAdvancedAxes': 'Show hidden axes',+ 'widgets.canvas.toolOptions.textFontStyle': 'Style',+ 'widgets.canvas.toolOptions.textFontStyleNormal': 'Normal',+ 'widgets.canvas.toolOptions.textFontWeight': 'Weight',+ 'widgets.properties.groups.font': 'Font',+ 'widgets.properties.rows.size': 'Size',+ 'widgets.properties.rows.weight': 'Weight',+ 'widgets.properties.target.defaults': 'Defaults',+ 'common.loading': 'Loading…',+ 'common.retry': 'Retry',+ },+ fonts: {+ fonts: {+ couldNotLoad: 'Could not load fonts',+ loadMore: 'Load more fonts',+ loadingMore: 'Loading more fonts…',+ },+ },+ },+ },+});++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++describe('custom font controls', () => {+ let container: HTMLDivElement | null = null;+ let root: Root | null = null;+ const engine = null as unknown as ToolFormProps['engine'];++ beforeEach(() => {+ mocks.fontsInfiniteQueryOptions.mockReset().mockImplementation(() => ({+ getNextPageParam: () => undefined,+ initialPageParam: 0,+ queryFn: () => Promise.resolve({ items: [mocks.font], limit: 100, offset: 0, total: 1 }),+ queryKey: ['font-catalog-test'],+ }));+ });++ it('canonicalizes built-in restyles without upgrading a v3 source', () => {+ const source: Extract<CanvasLayerSourceContract, { type: 'text' }> = {+ align: 'left',+ color: '#ffffff',+ content: 'hello',+ fontFamily: 'Inter',+ fontRef: undefined,+ fontSize: 32,+ fontStyle: 'normal',+ fontVariations: {},+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ };+ const canonical = canonicalizeSelectedTextSource(source);+ expect(canonical).not.toHaveProperty('fontRef');+ expect(canonical).not.toHaveProperty('fontStyle');+ expect(canonical).not.toHaveProperty('fontVariations');++ const custom = canonicalizeSelectedTextSource({+ ...source,+ fontRef: { contentHash: 'hash', family: 'Catalog Family', id: 'font-1', label: 'Catalog Regular' },+ fontStyle: 'italic',+ fontVariations: { wght: 650 },+ });+ expect(custom.fontRef?.id).toBe('font-1');+ expect(custom.fontStyle).toBe('italic');+ expect(custom.fontVariations).toEqual({ wght: 650 });+ });++ afterEach(async () => {+ await act(() => root?.unmount());+ queryClient.clear();+ container?.remove();+ container = null;+ root = null;+ });++ it('makes variation axes authoritative and reveals hidden axes on demand', async () => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const FontGroup = textForm.groups[0]!.body;+ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <QueryClientProvider client={queryClient}>+ <FontGroup engine={engine} isSurfaceInteractionLocked={false} />+ </QueryClientProvider>+ </I18nextProvider>+ </ChakraProvider>+ );+ });++ await expect.element(page.getByRole('combobox', { name: 'Style' })).toBeDisabled();+ await expect.element(page.getByRole('combobox', { name: 'Weight' })).toBeDisabled();+ await expect.element(page.getByRole('slider', { name: 'Weight (wght)' })).toBeVisible();+ await expect.element(page.getByText('Width (wdth)')).not.toBeInTheDocument();+ await expect.element(page.getByRole('button', { name: 'Show hidden axes' })).toBeVisible();++ await act(() => page.getByRole('button', { name: 'Show hidden axes' }).click());+ await expect.element(page.getByRole('slider', { name: 'Width (wdth)' })).toBeVisible();+ await expect.element(page.getByRole('combobox', { name: 'Preset' })).toBeVisible();+ });++ it('reveals catalog fonts beyond the first page with an explicit load-more action', async () => {+ const secondPageFont: FontRecord = {+ ...mocks.font,+ family: 'Second Page Sans',+ id: 'second-page-sans',+ label: 'Second Page Sans Regular',+ };+ const pageParams: number[] = [];+ mocks.fontsInfiniteQueryOptions.mockReset().mockImplementation(() => ({+ getNextPageParam: (_lastPage: unknown, _allPages: unknown[], lastPageParam: number) =>+ lastPageParam === 0 ? 100 : undefined,+ initialPageParam: 0,+ queryFn: ({ pageParam }: { pageParam: number }) => {+ pageParams.push(pageParam);+ return Promise.resolve({+ items: [pageParam === 0 ? mocks.font : secondPageFont],+ limit: 100,+ offset: pageParam,+ total: 101,+ });+ },+ queryKey: ['font-catalog-test', 'paged'],+ }));++ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const FontGroup = textForm.groups[0]!.body;+ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <QueryClientProvider client={queryClient}>+ <FontGroup engine={engine} isSurfaceInteractionLocked={false} />+ </QueryClientProvider>+ </I18nextProvider>+ </ChakraProvider>+ );+ });++ await expect.element(page.getByRole('button', { name: 'Load more fonts' })).toBeVisible();+ await act(() => page.getByRole('button', { name: 'Load more fonts' }).click());+ await vi.waitFor(() => expect(pageParams).toContain(100));++ await act(() => page.getByRole('combobox', { name: 'Font' }).click());+ await expect.element(page.getByRole('option', { name: 'Second Page Sans Regular', exact: true })).toBeVisible();+ });++ it('surfaces an initial catalog failure and retries it without losing built-ins', async () => {+ let attempts = 0;+ let rejectInitial: ((reason?: unknown) => void) | undefined;+ const initialCatalog = new Promise<never>((_resolve, reject) => {+ rejectInitial = reject;+ });+ mocks.fontsInfiniteQueryOptions.mockReset().mockImplementation(() => ({+ getNextPageParam: () => undefined,+ initialPageParam: 0,+ queryFn: () => {+ attempts += 1;+ return attempts === 1+ ? initialCatalog+ : Promise.resolve({ items: [mocks.font], limit: 100, offset: 0, total: 1 });+ },+ queryKey: ['font-catalog-test', 'retry'],+ retry: false,+ }));++ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const FontGroup = textForm.groups[0]!.body;+ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <QueryClientProvider client={queryClient}>+ <FontGroup engine={engine} isSurfaceInteractionLocked={false} />+ </QueryClientProvider>+ </I18nextProvider>+ </ChakraProvider>+ );+ });++ await expect.element(page.getByText('Loading…', { exact: true })).toBeVisible();+ await act(() => rejectInitial?.(new Error('catalog unavailable')));+ await expect.element(page.getByText('Could not load fonts', { exact: true })).toBeVisible();+ await expect.element(page.getByRole('combobox', { name: 'Font' })).toBeVisible();+ await expect.element(page.getByRole('button', { name: 'Retry' })).toBeVisible();++ await act(() => page.getByRole('button', { name: 'Retry' }).click());+ await expect.element(page.getByRole('button', { name: 'Retry' })).not.toBeInTheDocument();+ await act(() => page.getByRole('combobox', { name: 'Font' }).click());+ await expect.element(page.getByRole('option', { name: 'Variable Sans Regular', exact: true })).toBeVisible();+ });++ it('preserves loaded choices when loading the next catalog page fails', async () => {+ const secondPageFont: FontRecord = {+ ...mocks.font,+ family: 'Second Page Sans',+ id: 'second-page-sans-retry',+ label: 'Second Page Sans Retry',+ };+ let failedNextPage = false;+ const pageParams: number[] = [];+ mocks.fontsInfiniteQueryOptions.mockReset().mockImplementation(() => ({+ getNextPageParam: (_lastPage: unknown, _allPages: unknown[], lastPageParam: number) =>+ lastPageParam === 0 ? 100 : undefined,+ initialPageParam: 0,+ queryFn: ({ pageParam }: { pageParam: number }) => {+ pageParams.push(pageParam);+ if (pageParam === 100 && !failedNextPage) {+ failedNextPage = true;+ return Promise.reject(new Error('next page unavailable'));+ }+ return Promise.resolve({+ items: [pageParam === 0 ? mocks.font : secondPageFont],+ limit: 100,+ offset: pageParam,+ total: 101,+ });+ },+ queryKey: ['font-catalog-test', 'next-page-retry'],+ retry: false,+ }));++ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const FontGroup = textForm.groups[0]!.body;+ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <QueryClientProvider client={queryClient}>+ <FontGroup engine={engine} isSurfaceInteractionLocked={false} />+ </QueryClientProvider>+ </I18nextProvider>+ </ChakraProvider>+ );+ });++ await expect.element(page.getByRole('button', { name: 'Load more fonts' })).toBeVisible();+ await act(() => page.getByRole('button', { name: 'Load more fonts' }).click());+ await vi.waitFor(() => expect(pageParams).toContain(100));+ await expect.element(page.getByText('Could not load fonts', { exact: true })).toBeVisible();++ await act(() => page.getByRole('combobox', { name: 'Font' }).click());+ await expect.element(page.getByRole('option', { name: 'Variable Sans Regular', exact: true })).toBeVisible();++ await act(() => page.getByRole('button', { name: 'Retry' }).click());+ await expect.element(page.getByRole('option', { name: 'Second Page Sans Retry', exact: true })).toBeVisible();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsxindex 576355e99f..1e73f63e54 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx@@ -1,11 +1,13 @@import type { SelectValueChangeDetails } from '@chakra-ui/react';-import type { CanvasLayerSourceContract, TextToolOptions } from '@workbench/canvas-engine/api';-import type { ToolFormProps, ToolPropertyForm } from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';+import type { CanvasLayerSourceContract, CanvasTextFontRef, TextToolOptions } from '@workbench/canvas-engine/api';+import type { ToolFormProps } from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';-import { createListCollection, HStack } from '@chakra-ui/react';-import { IconButton } from '@platform/ui/Button';+import { Box, createListCollection, HStack, Spinner, Text } from '@chakra-ui/react';+import { fontsInfiniteQueryOptions, type FontAxis, type FontRecord } from '@features/fonts';+import { Button, IconButton, ToggleIconButton } from '@platform/ui/Button';import { ColorPicker } from '@platform/ui/ColorPicker';import { Select } from '@platform/ui/Select';+import { useInfiniteQuery } from '@tanstack/react-query';import {MAX_TEXT_FONT_SIZE,MIN_TEXT_FONT_SIZE,@@ -25,8 +27,8 @@ import { EditTargetChip, PropertyControlRow } from '@workbench/widgets/canvas/toimport { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';-import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon } from 'lucide-react';-import { useCallback, useMemo } from 'react';+import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon, RotateCcwIcon, SlidersHorizontalIcon } from 'lucide-react';+import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';type TextSource = Extract<CanvasLayerSourceContract, { type: 'text' }>;@@ -54,6 +56,81 @@ const ALIGN_LABEL_KEYS: Record<TextAlign, string> = {};const ALIGN_VALUES: readonly TextAlign[] = ['left', 'center', 'right'];+const EMPTY_FONT_VARIATIONS: Readonly<Record<string, number>> = {};+const EMPTY_FONT_RECORDS: readonly FontRecord[] = [];++type FontChoiceGroup = 'builtin' | 'custom';++interface FontChoice {+ family: string;+ font?: FontRecord;+ group: FontChoiceGroup;+ label: string;+ ref?: CanvasTextFontRef;+ value: string;+}++const sameFontRef = (left: CanvasTextFontRef | undefined, right: CanvasTextFontRef | undefined): boolean =>+ left === right ||+ (left !== undefined &&+ right !== undefined &&+ left.id === right.id &&+ left.contentHash === right.contentHash &&+ left.family === right.family &&+ left.label === right.label);++const fontReferenceFromRecord = (font: FontRecord): CanvasTextFontRef => ({+ contentHash: font.contentHash,+ family: font.family,+ id: font.id,+ label: font.label,+});++const fontChoiceValue = (font: FontRecord | CanvasTextFontRef): string =>+ `custom:${font.id}:${font.contentHash}:${font.label}`;++const normalizeFontStyle = (style: string): NonNullable<TextSource['fontStyle']> =>+ style === 'italic' || style === 'oblique' ? style : 'normal';++/** Keeps v3 built-in sources free of optional defaults that force a v4 rewrite. */+export const canonicalizeSelectedTextSource = (source: TextSource): TextSource => {+ const next = { ...source };+ if (next.fontRef === undefined) {+ delete next.fontRef;+ }+ if (next.fontStyle === undefined || next.fontStyle === 'normal') {+ delete next.fontStyle;+ }+ if (!next.fontVariations || Object.keys(next.fontVariations).length === 0) {+ delete next.fontVariations;+ } else {+ next.fontVariations = { ...next.fontVariations };+ }+ return next;+};++const clampFontAxisValue = (value: number, axis: FontAxis): number =>+ Math.min(axis.maximum, Math.max(axis.minimum, Number.isFinite(value) ? value : axis.default));++/** Keeps variation maps aligned with the catalog's declared axes and exact coordinates. */+const fontVariationCoordinates = (+ font: FontRecord,+ coordinates: Readonly<Record<string, number>> = {}+): Record<string, number> =>+ Object.fromEntries(+ font.axes.map((axis) => [axis.tag, clampFontAxisValue(coordinates[axis.tag] ?? axis.default, axis)])+ );++const axisStep = (axis: FontAxis): number => {+ const span = axis.maximum - axis.minimum;+ if (span <= 2) {+ return 0.01;+ }+ if (span <= 200) {+ return 0.1;+ }+ return 1;+};const AlignButton = ({active,@@ -110,17 +187,32 @@ const useTextEditor = (engine: ToolFormProps['engine']) => {const fontFamily = styleSource?.fontFamily ?? options.fontFamily;const fontSize = styleSource?.fontSize ?? options.fontSize;const fontWeight = styleSource?.fontWeight ?? options.fontWeight;+ const fontRef = styleSource ? styleSource.fontRef : options.fontRef;+ const fontStyle = styleSource ? (styleSource.fontStyle ?? 'normal') : (options.fontStyle ?? 'normal');+ const fontVariations = styleSource+ ? (styleSource.fontVariations ?? EMPTY_FONT_VARIATIONS)+ : (options.fontVariations ?? EMPTY_FONT_VARIATIONS);const lineHeight = styleSource?.lineHeight ?? options.lineHeight;const color = styleSource?.color ?? pair.foreground;const active = useMemo(- () => ({ align, color, fontFamily, fontSize, fontWeight, lineHeight }),- [align, color, fontFamily, fontSize, fontWeight, lineHeight]+ () => ({ align, color, fontFamily, fontRef, fontSize, fontStyle, fontVariations, fontWeight, lineHeight }),+ [align, color, fontFamily, fontRef, fontSize, fontStyle, fontVariations, fontWeight, lineHeight]);const applyEdit = useCallback((patch: Partial<TextSource>, commit: boolean) => {const { color: colorPatch, ...stylePatch } = patch;if (Object.keys(stylePatch).length > 0) {- engine.interaction.set('textOptions', { align, fontFamily, fontSize, fontWeight, lineHeight, ...stylePatch });+ engine.interaction.set('textOptions', {+ align,+ fontFamily,+ fontRef,+ fontSize,+ fontStyle,+ fontVariations,+ fontWeight,+ lineHeight,+ ...stylePatch,+ });}if (session) {engine.layers.updateTextEditStyle(patch);@@ -128,7 +220,7 @@ const useTextEditor = (engine: ToolFormProps['engine']) => {}if (selected) {if (commit) {- const after: TextSource = { ...selected.source, ...patch };+ const after = canonicalizeSelectedTextSource({ ...selected.source, ...patch });commitPrepared(t('widgets.canvas.toolOptions.textEdit'), (model) =>model.prepare({ id: selected.id, source: after, type: 'patch-source' }));@@ -139,7 +231,22 @@ const useTextEditor = (engine: ToolFormProps['engine']) => {colorCommands.setPairColor('foreground', colorPatch);}},- [align, colorCommands, commitPrepared, engine, fontFamily, fontSize, fontWeight, lineHeight, selected, session, t]+ [+ align,+ colorCommands,+ commitPrepared,+ engine,+ fontFamily,+ fontRef,+ fontSize,+ fontStyle,+ fontVariations,+ fontWeight,+ lineHeight,+ selected,+ session,+ t,+ ]);// The chip names what applyEdit actually writes: the SESSION when one is// open (its layer's name, or the new-text placeholder in create mode), else@@ -154,39 +261,318 @@ const useTextEditor = (engine: ToolFormProps['engine']) => {return { active, applyEdit, targetName };};-const TextFontSettings = ({ engine }: ToolFormProps) => {+const AxisControl = ({+ activeVariations,+ applyEdit,+ axis,+}: {+ activeVariations: Readonly<Record<string, number>>;+ applyEdit: (patch: Partial<TextSource>, commit: boolean) => void;+ axis: FontAxis;+}) => {+ const committed = clampFontAxisValue(activeVariations[axis.tag] ?? axis.default, axis);+ const step = axisStep(axis);+ const precision = step < 0.1 ? 2 : step < 1 ? 1 : 0;+ const setValue = useCallback(+ (value: number, commit: boolean) => {+ const next = clampFontAxisValue(value, axis);+ applyEdit({ fontVariations: { ...activeVariations, [axis.tag]: next } }, commit);+ },+ [activeVariations, applyEdit, axis]+ );+ const previewValue = useCallback((value: number) => setValue(value, false), [setValue]);+ const commitValue = useCallback((value: number) => setValue(value, true), [setValue]);+ const gesture = useSliderGesture(committed, commitValue, previewValue);+ const onNumber = useNumberCommit(commitValue);+ const displayedValue = gesture.value.toFixed(precision);+ const ariaLabel = `${axis.label} (${axis.tag})`;++ return (+ <PropertyControlRow label={ariaLabel}>+ <FormSlider+ aria-label={ariaLabel}+ max={axis.maximum}+ min={axis.minimum}+ step={step}+ value={gesture.value}+ onValueChange={gesture.onChange}+ onValueChangeEnd={gesture.onChangeEnd}+ />+ <FormNumberField+ aria-label={ariaLabel}+ max={axis.maximum}+ min={axis.minimum}+ step={step}+ value={displayedValue}+ onValueCommit={onNumber}+ />+ </PropertyControlRow>+ );+};++const variationMapsEqual = (+ left: Readonly<Record<string, number>>,+ right: Readonly<Record<string, number>>,+ axes: readonly FontAxis[]+): boolean => axes.every((axis) => left[axis.tag] === right[axis.tag]);++const FontAxisSettings = ({+ activeVariations,+ applyEdit,+ font,+}: {+ activeVariations: Readonly<Record<string, number>>;+ applyEdit: (patch: Partial<TextSource>, commit: boolean) => void;+ font?: FontRecord;+}) => {const { t } = useTranslation();+ const [showAdvanced, setShowAdvanced] = useState(false);+ const axes = useMemo(() => font?.axes.filter((axis) => axis.maximum > axis.minimum) ?? [], [font?.axes]);+ const visibleAxes = useMemo(() => axes.filter((axis) => showAdvanced || !axis.hidden), [axes, showAdvanced]);+ const hasHiddenAxes = axes.some((axis) => axis.hidden);+ const presetCollection = useMemo(+ () =>+ createListCollection<{ label: string; value: string }>({+ items: [+ { label: t('widgets.canvas.toolOptions.textFontDefaultPreset'), value: 'default' },+ ...(font?.instances ?? []).map((instance, index) => ({ label: instance.name, value: `instance:${index}` })),+ ],+ }),+ [font?.instances, t]+ );+ const presetValue = useMemo(() => {+ if (!font) {+ return ['default'];+ }+ const defaultCoordinates = fontVariationCoordinates(font);+ if (variationMapsEqual(activeVariations, defaultCoordinates, axes)) {+ return ['default'];+ }+ const instanceIndex = font.instances.findIndex((instance) =>+ variationMapsEqual(activeVariations, fontVariationCoordinates(font, instance.coordinates), axes)+ );+ return [instanceIndex >= 0 ? `instance:${instanceIndex}` : 'default'];+ }, [activeVariations, axes, font]);+ const onPreset = useCallback(+ ({ value }: SelectValueChangeDetails<{ label: string; value: string }>) => {+ if (!font) {+ return;+ }+ const selection = value[0];+ if (selection === 'default') {+ applyEdit({ fontVariations: fontVariationCoordinates(font) }, true);+ return;+ }+ const index = selection?.startsWith('instance:') ? Number(selection.slice('instance:'.length)) : -1;+ const instance = Number.isInteger(index) && index >= 0 ? font.instances[index] : undefined;+ if (instance) {+ applyEdit({ fontVariations: fontVariationCoordinates(font, instance.coordinates) }, true);+ }+ },+ [applyEdit, font]+ );+ const resetAxes = useCallback(() => {+ if (font) {+ applyEdit({ fontVariations: fontVariationCoordinates(font) }, true);+ }+ }, [applyEdit, font]);++ if (!font || axes.length === 0) {+ return null;+ }++ const advancedLabel = t(+ showAdvanced+ ? 'widgets.canvas.toolOptions.textFontHideAdvancedAxes'+ : 'widgets.canvas.toolOptions.textFontShowAdvancedAxes'+ );++ return (+ <Box borderColor="border.subtle" borderTopWidth="1px" mt="1" pt="1">+ <HStack justifyContent="space-between" minH="7">+ <Text color="fg.muted" fontSize="xs">+ {t('widgets.canvas.toolOptions.textFontAxes')}+ </Text>+ <HStack gap="1">+ <Button+ aria-label={t('widgets.canvas.toolOptions.textFontResetAxes')}+ size="2xs"+ variant="ghost"+ onClick={resetAxes}+ >+ <RotateCcwIcon />+ </Button>+ {hasHiddenAxes ? (+ <ToggleIconButton+ checked={showAdvanced}+ icon={SlidersHorizontalIcon}+ label={advancedLabel}+ onCheckedChange={setShowAdvanced}+ />+ ) : null}+ </HStack>+ </HStack>+ <PropertyControlRow label={t('widgets.canvas.toolOptions.textFontPreset')}>+ <Select+ aria-label={t('widgets.canvas.toolOptions.textFontPreset')}+ collection={presetCollection}+ gridColumn="2 / -1"+ positioning={SELECT_POSITIONING}+ size="xs"+ value={presetValue}+ valueText={presetCollection.items.find((item) => item.value === presetValue[0])?.label}+ w="full"+ onValueChange={onPreset}+ />+ </PropertyControlRow>+ {visibleAxes.map((axis) => (+ <AxisControl key={axis.tag} activeVariations={activeVariations} applyEdit={applyEdit} axis={axis} />+ ))}+ </Box>+ );+};++export const TextFontSettings = ({ engine }: ToolFormProps) => {+ const { t } = useTranslation();+ const { t: tFonts } = useTranslation('fonts');const { active, applyEdit, targetName } = useTextEditor(engine);- const familyCollection = useMemo(- () => createListCollection<{ label: string; value: string }>({ items: [...TEXT_FONT_FAMILIES] }),- []+ const { data, fetchNextPage, hasNextPage, isError, isFetchNextPageError, isFetchingNextPage, isPending, refetch } =+ useInfiniteQuery(fontsInfiniteQueryOptions({ limit: 100, scope: 'all' }));+ const loadMoreFonts = useCallback(() => void fetchNextPage(), [fetchNextPage]);+ const retryFontCatalog = useCallback(() => {+ if (isFetchNextPageError) {+ void fetchNextPage();+ return;+ }+ void refetch();+ }, [fetchNextPage, isFetchNextPageError, refetch]);+ const fonts = useMemo(() => data?.pages.flatMap((page) => page.items) ?? EMPTY_FONT_RECORDS, [data?.pages]);+ const familyChoices = useMemo(() => {+ const builtins: FontChoice[] = TEXT_FONT_FAMILIES.map((font) => ({+ family: font.value,+ group: 'builtin',+ label: font.label,+ value: `builtin:${font.value}`,+ }));+ const custom = [...fonts]+ .sort((left, right) => left.family.localeCompare(right.family) || left.label.localeCompare(right.label))+ .map((font): FontChoice => ({+ family: font.family,+ font,+ group: 'custom',+ label: font.label,+ ref: fontReferenceFromRecord(font),+ value: fontChoiceValue(font),+ }));+ if (active.fontRef && !custom.some((choice) => sameFontRef(choice.ref, active.fontRef))) {+ custom.push({+ family: active.fontRef.family,+ group: 'custom',+ label: active.fontRef.label,+ ref: { ...active.fontRef },+ value: fontChoiceValue(active.fontRef),+ });+ }+ return [...builtins, ...custom];+ }, [active.fontRef, fonts]);+ const familyCollection = useMemo(() => createListCollection<FontChoice>({ items: familyChoices }), [familyChoices]);+ const groupBy = useCallback((item: FontChoice) => item.group, []);+ const renderGroupLabel = useCallback(+ (group: string) =>+ group === 'custom'+ ? t('widgets.canvas.toolOptions.textFontCustomGroup')+ : t('widgets.canvas.toolOptions.textFontBuiltinGroup'),+ [t]+ );+ const activeChoice = useMemo(+ () =>+ familyChoices.find((choice) =>+ choice.group === 'custom'+ ? sameFontRef(choice.ref, active.fontRef)+ : active.fontRef === undefined && choice.family === active.fontFamily+ ),+ [active.fontFamily, active.fontRef, familyChoices]);- const familyValue = useMemo(() => [active.fontFamily], [active.fontFamily]);- const familyLabel = useMemo(- () => TEXT_FONT_FAMILIES.find((entry) => entry.value === active.fontFamily)?.label ?? active.fontFamily,- [active.fontFamily]+ const familyValue = useMemo(+ () => [activeChoice?.value ?? active.fontFamily],+ [active.fontFamily, activeChoice?.value]);+ const familyLabel = activeChoice?.label ?? active.fontRef?.label ?? active.fontFamily;+ const activeFont = activeChoice?.font;+ const hasWeightAxis = activeFont?.axes.some((axis) => axis.tag === 'wght') ?? false;+ const hasStyleAxis = activeFont?.axes.some((axis) => axis.tag === 'ital' || axis.tag === 'slnt') ?? false;const onFamily = useCallback(- ({ value }: SelectValueChangeDetails<{ label: string; value: string }>) => {+ ({ value }: SelectValueChangeDetails<FontChoice>) => {+ const choice = familyChoices.find((entry) => entry.value === value[0]);+ if (!choice) {+ return;+ }+ if (choice.group === 'builtin') {+ if (active.fontFamily !== choice.family || active.fontRef !== undefined) {+ applyEdit({ fontFamily: choice.family, fontRef: undefined, fontStyle: 'normal', fontVariations: {} }, true);+ }+ return;+ }+ if (!choice.font || !choice.ref) {+ return;+ }+ if (active.fontFamily === choice.family && sameFontRef(active.fontRef, choice.ref)) {+ return;+ }+ applyEdit(+ {+ fontFamily: choice.family,+ fontRef: choice.ref,+ fontStyle: normalizeFontStyle(choice.font.style),+ fontVariations: fontVariationCoordinates(choice.font),+ fontWeight:+ Number.isFinite(choice.font.weight) && choice.font.weight > 0 ? choice.font.weight : active.fontWeight,+ },+ true+ );+ },+ [active.fontFamily, active.fontRef, active.fontWeight, applyEdit, familyChoices]+ );+ const styleCollection = useMemo(+ () =>+ createListCollection<{ label: string; value: NonNullable<TextSource['fontStyle']> }>({+ items: [+ { label: t('widgets.canvas.toolOptions.textFontStyleNormal'), value: 'normal' },+ { label: t('widgets.canvas.toolOptions.textFontStyleItalic'), value: 'italic' },+ { label: t('widgets.canvas.toolOptions.textFontStyleOblique'), value: 'oblique' },+ ],+ }),+ [t]+ );+ const onStyle = useCallback(+ ({ value }: SelectValueChangeDetails<{ label: string; value: NonNullable<TextSource['fontStyle']> }>) => {const next = value[0];- if (next && next !== active.fontFamily) {- applyEdit({ fontFamily: next }, true);+ if ((next === 'normal' || next === 'italic' || next === 'oblique') && next !== active.fontStyle) {+ applyEdit({ fontStyle: next }, true);}},- [active.fontFamily, applyEdit]+ [active.fontStyle, applyEdit]+ );+ const weightValues = useMemo(+ () =>+ [...new Set([...TEXT_FONT_WEIGHTS, active.fontWeight].filter((weight) => Number.isFinite(weight)))].sort(+ (a, b) => a - b+ ),+ [active.fontWeight]);const weightCollection = useMemo(() =>createListCollection<{ label: string; value: string }>({- items: TEXT_FONT_WEIGHTS.map((weight) => ({ label: String(weight), value: String(weight) })),+ items: weightValues.map((weight) => ({ label: String(weight), value: String(weight) })),}),- []+ [weightValues]);const weightValue = useMemo(() => [String(active.fontWeight)], [active.fontWeight]);+ const styleValue = useMemo(() => [active.fontStyle], [active.fontStyle]);const onWeight = useCallback(({ value }: SelectValueChangeDetails<{ label: string; value: string }>) => {const next = value[0] ? Number(value[0]) : undefined;- if (next && next !== active.fontWeight) {+ if (next !== undefined && Number.isFinite(next) && next !== active.fontWeight) {applyEdit({ fontWeight: next }, true);}},@@ -219,16 +605,69 @@ const TextFontSettings = ({ engine }: ToolFormProps) => {<><EditTargetChip layerName={targetName} /><PropertyControlRow label={t('widgets.properties.rows.family')}>+ <HStack gap="1" gridColumn="2 / -1" minW="0" w="full">+ <Select+ aria-label={t('widgets.canvas.toolOptions.textFont')}+ collection={familyCollection}+ flex="1"+ groupBy={groupBy}+ itemsMaxH="20rem"+ minW="0"+ positioning={SELECT_POSITIONING}+ renderGroupLabel={renderGroupLabel}+ size="xs"+ value={familyValue}+ valueText={familyLabel}+ onValueChange={onFamily}+ />+ {isPending ? (+ <HStack aria-live="polite" color="fg.muted" flexShrink="0" gap="1" role="status">+ <Spinner size="xs" />+ <Text fontSize="2xs">{t('common.loading')}</Text>+ </HStack>+ ) : isError ? (+ <HStack aria-live="polite" color="fg.error" flexShrink="0" gap="1" role="alert">+ <Text fontSize="2xs">{tFonts('fonts.couldNotLoad')}</Text>+ <Button+ aria-label={t('common.retry')}+ disabled={isFetchingNextPage}+ size="2xs"+ variant="ghost"+ onClick={retryFontCatalog}+ >+ {t('common.retry')}+ </Button>+ </HStack>+ ) : null}+ </HStack>+ </PropertyControlRow>+ {hasNextPage ? (+ <HStack justify="flex-end" minH="7">+ <Button+ aria-label={tFonts('fonts.loadMore', { defaultValue: 'Load more fonts' })}+ disabled={isFetchingNextPage}+ size="2xs"+ variant="ghost"+ onClick={loadMoreFonts}+ >+ {isFetchingNextPage+ ? tFonts('fonts.loadingMore', { defaultValue: 'Loading more fonts…' })+ : tFonts('fonts.loadMore', { defaultValue: 'Load more fonts' })}+ </Button>+ </HStack>+ ) : null}+ <PropertyControlRow label={t('widgets.canvas.toolOptions.textFontStyle')}><Select- aria-label={t('widgets.canvas.toolOptions.textFont')}- collection={familyCollection}+ aria-label={t('widgets.canvas.toolOptions.textFontStyle')}+ collection={styleCollection}+ disabled={hasStyleAxis}gridColumn="2 / -1"positioning={SELECT_POSITIONING}size="xs"- value={familyValue}- valueText={familyLabel}+ value={styleValue}+ valueText={styleCollection.items.find((item) => item.value === active.fontStyle)?.label}w="full"- onValueChange={onFamily}+ onValueChange={onStyle}/></PropertyControlRow><PropertyControlRow label={t('widgets.properties.rows.size')}>@@ -253,6 +692,7 @@ const TextFontSettings = ({ engine }: ToolFormProps) => {<Selectaria-label={t('widgets.canvas.toolOptions.textWeight')}collection={weightCollection}+ disabled={hasWeightAxis}flexShrink={0}positioning={SELECT_POSITIONING}size="xs"@@ -282,11 +722,12 @@ const TextFontSettings = ({ engine }: ToolFormProps) => {onValueCommit={onLineHeight}/></PropertyControlRow>+ <FontAxisSettings activeVariations={active.fontVariations} applyEdit={applyEdit} font={activeChoice?.font} /></>);};-const TextParagraphSettings = ({ engine }: ToolFormProps) => {+export const TextParagraphSettings = ({ engine }: ToolFormProps) => {const { t } = useTranslation();const { active, applyEdit } = useTextEditor(engine);const onAlign = useCallback((next: TextAlign) => applyEdit({ align: next }, true), [applyEdit]);@@ -301,7 +742,7 @@ const TextParagraphSettings = ({ engine }: ToolFormProps) => {);};-const TextColorSettings = ({ engine }: ToolFormProps) => {+export const TextColorSettings = ({ engine }: ToolFormProps) => {const { t } = useTranslation();const { active, applyEdit } = useTextEditor(engine);const sampleColor = useColorSampler(engine);@@ -319,13 +760,3 @@ const TextColorSettings = ({ engine }: ToolFormProps) => {</PropertyControlRow>);};--export const textForm: ToolPropertyForm = {- groups: [- { body: TextFontSettings, id: 'text-font', labelKey: 'widgets.properties.groups.font' },- { body: TextParagraphSettings, id: 'text-paragraph', labelKey: 'widgets.properties.groups.paragraph' },- { body: TextColorSettings, id: 'text-color', labelKey: 'widgets.properties.rows.color' },- ],- id: 'text',- paintsLeaf: true,-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/textForm.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/textForm.tsxnew file mode 100644index 0000000000..2cb023da05--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/textForm.tsx@@ -0,0 +1,41 @@+import type {+ ToolFormComponent,+ ToolPropertyForm,+} from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';++import { Skeleton } from '@chakra-ui/react';+import { lazy, Suspense } from 'react';++const loading = <Skeleton height="8" />;++// Catalog queries and variable-font controls are needed only while text is selected.+const lazyGroup = (load: () => Promise<{ default: ToolFormComponent }>): ToolFormComponent => {+ const Body = lazy(load);+ return (props) => (+ <Suspense fallback={loading}>+ <Body {...props} />+ </Suspense>+ );+};++export const textForm: ToolPropertyForm = {+ groups: [+ {+ body: lazyGroup(() => import('./TextOptions').then((module) => ({ default: module.TextFontSettings }))),+ id: 'text-font',+ labelKey: 'widgets.properties.groups.font',+ },+ {+ body: lazyGroup(() => import('./TextOptions').then((module) => ({ default: module.TextParagraphSettings }))),+ id: 'text-paragraph',+ labelKey: 'widgets.properties.groups.paragraph',+ },+ {+ body: lazyGroup(() => import('./TextOptions').then((module) => ({ default: module.TextColorSettings }))),+ id: 'text-color',+ labelKey: 'widgets.properties.rows.color',+ },+ ],+ id: 'text',+ paintsLeaf: true,+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.tsindex 486ce951a7..66aabfa522 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.ts@@ -8,7 +8,7 @@ import { brushForm, eraserForm } from '@workbench/widgets/canvas/tool-options/paimport { selectObjectOperationForm } from '@workbench/widgets/canvas/tool-options/SamOptions';import { lassoForm, marqueeForm } from '@workbench/widgets/canvas/tool-options/selectionForm';import { shapeForm } from '@workbench/widgets/canvas/tool-options/ShapeOptions';-import { textForm } from '@workbench/widgets/canvas/tool-options/TextOptions';+import { textForm } from '@workbench/widgets/canvas/tool-options/textForm';import type { CanvasOperationKind, OperationPropertyForm, ToolPropertyForm } from './toolFormContracts';diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex c314d28df9..2ff136c9b2 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -989,7 +989,7 @@ const cloneCanvas = (canvas: CanvasStateContractV3): CanvasStateContractV3 => {const document = structuredClone(canvas.document);return {- version: 3,+ version: canvas.version,document,documentRevision: canvas.documentRevision,snapshots: canvas.snapshots.map((snapshot) => ({ ...snapshot, document: structuredClone(snapshot.document) })),diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex e2c030939f..9fbc487d25 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -20,6 +20,10 @@ const PROJECT_ROOT = fileURLToPath(new URL('.', import.meta.url));// Modules both routes fetch eagerly. Grouping keeps a module with two// consumers from being split into its own request on each route.const ROUTE_SHARED_MODULES = [+ '/features/fonts/data/keys.ts',+ '/features/fonts/launchpad.tsx',+ '/features/fonts/react.tsx',+ '/features/fonts/runtime.ts','/features/models/data/modelLoadStore.ts','/features/models/index.ts','/features/models/ui/ModelsPage.tsx',@@ -49,6 +53,7 @@ const ROUTE_SHARED_MODULES = ['/workbench/launchpad/intents.ts','/workbench/palette/settingsEntryDeps.ts','/workbench/projects/covers.ts',+ '/workbench/projects/components/ProjectFileOptionsProvider.tsx','/workbench/projects/ids.ts','/workbench/projects/invk/format.ts','/workbench/projects/library.ts',@@ -128,6 +133,38 @@ const WIDGET_HOST_MODULES = ['/workbench/widgets/image-map/ImageMapDataRuntime.tsx',] as const;+// Canvas and Layers already load these interaction/form modules together.+// Keep their shared text-tool consumers from creating extra activation requests.+const CANVAS_LAYER_SHARED_MODULES = [+ '/features/workflow/core/layerWorkflow.ts',+ '/workbench/canvas-operations/react.ts',+ '/workbench/canvas-operations/useCanvasEngine.ts',+ '/workbench/canvasProjectMutationPort.ts',+ '/workbench/useCanvasProjectMutationDispatch.ts',+ '/workbench/widgets/canvas/canvasInteractionLock.ts',+ '/workbench/widgets/canvas/color-system/colorPair.ts',+ '/workbench/widgets/canvas/color-system/useActiveColors.ts',+ '/workbench/widgets/canvas/engineStoreHooks.ts',+ '/workbench/widgets/canvas/tool-presentation/FormControls.tsx',+ '/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx',+ '/workbench/widgets/canvas/tool-presentation/propertyGroupStore.ts',+ '/workbench/widgets/canvas/useCanvasEngine.ts',+ '/workbench/widgets/canvas/useColorSampler.ts',+ '/workbench/widgets/canvas/useStructuralCommit.ts',+ '/workbench/widgets/layers/LayerContextMenu.tsx',+ '/workbench/widgets/layers/RunLayerWorkflowDialog.tsx',+ '/workbench/widgets/layers/colorLabels.ts',+ '/workbench/widgets/layers/layerActionSession.ts',+ '/workbench/widgets/layers/layerContextActions.ts',+ '/workbench/widgets/layers/layerContextMenuLayout.ts',+ '/workbench/widgets/layers/layerExportActions.ts',+ '/workbench/widgets/layers/layerGroupCommands.ts',+ '/workbench/widgets/layers/layerMenuState.ts',+ '/workbench/widgets/layers/layerPropertiesRequestStore.ts',+ '/workbench/widgets/layers/runLayerWorkflow.ts',+ '/workbench/widgets/layers/useSelectedModelBase.ts',+];+const matchesAnySuffix = (id: string, suffixes: readonly string[]) => suffixes.some((suffix) => id.endsWith(suffix));const getLegacyChunkName = (id: string): string | null => {@@ -200,6 +237,12 @@ export default defineConfig({output: {codeSplitting: {groups: [+ {+ includeDependenciesRecursively: false,+ name: 'canvas-layer-shared',+ priority: 30,+ test: (id) => matchesAnySuffix(id, CANVAS_LAYER_SHARED_MODULES),+ },{includeDependenciesRecursively: false,name: 'gallery-state',diff --git a/tests/app/api/test_font_upload_limits.py b/tests/app/api/test_font_upload_limits.pynew file mode 100644index 0000000000..e525f14cb9--- /dev/null+++ b/tests/app/api/test_font_upload_limits.py@@ -0,0 +1,117 @@+"""Ingress limits for custom-font multipart uploads."""++import asyncio+from typing import Any++from invokeai.app import api_app+from invokeai.app.api.routers import fonts+from invokeai.app.api_app import RequestBodyLimitASGIMiddleware+++def _scope(path: str, headers: list[tuple[bytes, bytes]] | None = None) -> dict[str, Any]:+ return {+ "type": "http",+ "asgi": {"version": "3.0"},+ "http_version": "1.1",+ "method": "POST",+ "scheme": "http",+ "path": path,+ "raw_path": path.encode(),+ "query_string": b"",+ "headers": headers or [],+ "client": ("testclient", 50000),+ "server": ("testserver", 80),+ "root_path": "",+ }+++def test_font_upload_limiter_is_installed_with_configured_request_cap() -> None:+ limiters = [+ middleware+ for middleware in api_app.app.user_middleware+ if middleware.cls is RequestBodyLimitASGIMiddleware+ and middleware.kwargs["matches_request"] is api_app._is_font_upload+ ]++ assert len(limiters) == 1+ kwargs = limiters[0].kwargs+ assert kwargs["max_body_bytes"] == api_app.app_config.max_font_upload_bytes + fonts.FONT_UPLOAD_MULTIPART_OVERHEAD+ assert kwargs["max_concurrent"] == fonts.MAX_CONCURRENT_FONT_UPLOADS+ assert kwargs["max_concurrent_per_user"] == fonts.MAX_CONCURRENT_FONT_UPLOADS_PER_USER+ assert api_app._is_font_upload("POST", "/api/v1/fonts")+ assert api_app._is_font_upload("POST", "/api/v1/fonts/validate")+ assert not api_app._is_font_upload("GET", "/api/v1/fonts")+ assert not api_app._is_font_upload("GET", "/api/v1/fonts/font-id/file")+++def test_oversized_font_request_is_rejected_before_downstream_body_read() -> None:+ calls: list[str] = []++ async def downstream(_scope: Any, _receive: Any, _send: Any) -> None:+ calls.append("route")+ raise AssertionError("an oversized font request must not reach multipart parsing")++ middleware = RequestBodyLimitASGIMiddleware(+ downstream,+ matches_request=api_app._is_font_upload,+ too_large_detail=lambda _actual, limit: {"code": "font_request_too_large", "max_bytes": limit},+ capacity_refusal_detail=lambda _per_user: "busy",+ max_body_bytes=10,+ max_concurrent=1,+ identify_user=lambda _scope: (True, None),+ )+ messages: list[dict[str, Any]] = []++ async def receive() -> dict[str, Any]:+ raise AssertionError("the middleware can reject from Content-Length without reading the body")++ async def send(message: dict[str, Any]) -> None:+ messages.append(message)++ asyncio.run(+ middleware(+ _scope("/api/v1/fonts", [(b"content-length", b"11")]),+ receive,+ send,+ )+ )++ assert next(message["status"] for message in messages if message["type"] == "http.response.start") == 413+ assert calls == []+++def test_chunked_font_request_is_cut_off_at_ingress_cap() -> None:+ seen: list[dict[str, Any]] = []++ async def downstream(_scope: Any, receive: Any, send: Any) -> None:+ while True:+ message = await receive()+ seen.append(message)+ if message["type"] != "http.request" or not message.get("more_body"):+ break+ await send({"type": "http.response.start", "status": 200, "headers": []})+ await send({"type": "http.response.body", "body": b""})++ middleware = RequestBodyLimitASGIMiddleware(+ downstream,+ matches_request=api_app._is_font_upload,+ too_large_detail=lambda _actual, limit: {"code": "font_request_too_large", "max_bytes": limit},+ capacity_refusal_detail=lambda _per_user: "busy",+ max_body_bytes=10,+ max_concurrent=1,+ identify_user=lambda _scope: (True, None),+ )+ chunks = [b"x" * 7, b"x" * 7]++ async def receive() -> dict[str, Any]:+ if chunks:+ return {"type": "http.request", "body": chunks.pop(0), "more_body": bool(chunks)}+ return {"type": "http.disconnect"}++ async def send(_message: dict[str, Any]) -> None:+ pass++ asyncio.run(middleware(_scope("/api/v1/fonts/validate"), receive, send))++ assert seen[-1]["type"] == "http.disconnect"+ assert sum(len(message.get("body", b"")) for message in seen if message["type"] == "http.request") == 7diff --git a/tests/app/routers/conftest.py b/tests/app/routers/conftest.pyindex 4d5d1a9858..9261f3d8fd 100644--- a/tests/app/routers/conftest.py+++ b/tests/app/routers/conftest.py@@ -53,6 +53,7 @@ _PATCHED_API_DEPENDENCIES_MODULES = ("invokeai.app.api.routers.style_presets","invokeai.app.api.routers.model_relationships","invokeai.app.api.routers.utilities",+ "invokeai.app.api.routers.fonts","invokeai.app.api.routers.wildcards","invokeai.app.api.routers.virtual_boards","invokeai.app.api.routers.gallery",diff --git a/tests/app/routers/test_auth.py b/tests/app/routers/test_auth.pyindex 328c42b7c3..7c1c809af6 100644--- a/tests/app/routers/test_auth.py+++ b/tests/app/routers/test_auth.py@@ -3,6 +3,7 @@import osfrom pathlib import Pathfrom typing import Any+from unittest.mock import MagicMockimport pytestfrom fastapi.testclient import TestClient@@ -281,6 +282,39 @@ def test_setup_admin_first_time(monkeypatch: Any, mock_invoker: Invoker, client:assert json_response["user"]["is_admin"] is True+def test_delete_user_emits_revocation_when_font_cleanup_fails(+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient+) -> None:+ """A cleanup failure cannot leave the deleted user's live sessions authorized."""+ dependencies = MockApiDependencies(mock_invoker)+ monkeypatch.setattr("invokeai.app.api.routers.auth.ApiDependencies", dependencies)+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", dependencies)++ setup_test_admin(mock_invoker, "[email protected]", "AdminPass123")+ deleted_user_id = setup_test_user(mock_invoker, "[email protected]", "TestPass123")+ admin_token = client.post(+ "/api/v1/auth/login",+ json={"email": "[email protected]", "password": "AdminPass123", "remember_me": False},+ ).json()["token"]++ fonts = MagicMock()+ fonts.prepare_user_cleanup.return_value = ()+ fonts.cleanup_user.side_effect = OSError("storage unavailable")+ mock_invoker.services.fonts = fonts+ events = mock_invoker.services.events+ events.emit_user_access_changed = MagicMock()++ response = client.delete(+ f"/api/v1/auth/users/{deleted_user_id}", headers={"Authorization": f"Bearer {admin_token}"}+ )++ assert response.status_code == 204+ assert mock_invoker.services.users.get(deleted_user_id) is None+ events.emit_user_access_changed.assert_called_once_with(user_id=deleted_user_id, is_admin=False, is_active=False)+ fonts.prepare_user_cleanup.assert_called_once_with(deleted_user_id)+ fonts.cleanup_user.assert_called_once_with(deleted_user_id, ())++def test_setup_admin_already_exists(monkeypatch: Any, mock_invoker: Invoker, client: TestClient) -> None:"""Test setup fails when admin already exists."""monkeypatch.setattr("invokeai.app.api.routers.auth.ApiDependencies", MockApiDependencies(mock_invoker))diff --git a/tests/app/routers/test_fonts.py b/tests/app/routers/test_fonts.pynew file mode 100644index 0000000000..e3fb2d179e--- /dev/null+++ b/tests/app/routers/test_fonts.py@@ -0,0 +1,170 @@+"""HTTP coverage for the authenticated custom-font catalog."""++from pathlib import Path+from typing import Any++import pytest+from fastapi import status+from fastapi.testclient import TestClient++from invokeai.app.services.fonts.fonts_default import FontService+from invokeai.app.services.invoker import Invoker+++def font_service(mock_invoker: Invoker, tmp_path: Path) -> FontService:+ service = FontService(+ db=mock_invoker.services.image_records._db,+ fonts_dir=tmp_path / "fonts",+ storage_dir=tmp_path / "uploaded-fonts",+ )+ mock_invoker.services.fonts = service+ yield service+ service.stop()+++def font_bytes() -> bytes:+ return (Path(__file__).parents[3] / "invokeai" / "assets" / "fonts" / "inter" / "Inter-Regular.ttf").read_bytes()+++def _auth(token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {token}"}+++def _upload(client: TestClient, token: str, data: bytes, filename: str = "Inter-Regular.ttf", **form: str):+ return client.post(+ "/api/v1/fonts",+ headers=_auth(token),+ files={"file": (filename, data, "font/ttf")},+ data=form,+ )+++ ("method", "path"),+ [("get", "/api/v1/fonts"), ("post", "/api/v1/fonts/validate")],+)+def test_font_routes_require_auth(+ method: str, path: str, enable_multiuser: Any, client: TestClient, font_bytes: bytes+) -> None:+ request = getattr(client, method)+ kwargs = {"files": {"file": ("font.ttf", font_bytes, "font/ttf")}} if method == "post" else {}+ response = request(path, **kwargs)+ assert response.status_code == status.HTTP_401_UNAUTHORIZED+++def test_upload_download_validate_and_hash_filter(+ client: TestClient, user1_token: str, font_service: FontService, font_bytes: bytes+) -> None:+ validation = client.post(+ "/api/v1/fonts/validate",+ headers=_auth(user1_token),+ files={"file": ("preview.ttf", font_bytes, "font/ttf")},+ )+ assert validation.status_code == status.HTTP_200_OK+ assert validation.json()["content_hash"]+ assert font_service.list(user_id="system")[1] == 0++ response = _upload(client, user1_token, font_bytes, filename="Résumé.ttf")+ assert response.status_code == status.HTTP_200_OK, response.text+ body = response.json()+ assert body["created"] is True+ font = body["font"]+ assert font["source"] == "uploaded"+ assert font["scope"] == "private"+ assert font["url"].endswith("/file")++ duplicate = _upload(client, user1_token, font_bytes, filename="renamed.ttf")+ assert duplicate.status_code == status.HTTP_200_OK+ assert duplicate.json()["created"] is False+ assert duplicate.json()["font"]["id"] == font["id"]++ filtered = client.get(+ "/api/v1/fonts",+ params={"content_hash": font["content_hash"]},+ headers=_auth(user1_token),+ )+ assert filtered.status_code == status.HTTP_200_OK+ assert filtered.json()["total"] == 1+ assert filtered.headers["cache-control"] == "private, no-store"++ metadata = client.get(f"/api/v1/fonts/{font['id']}", headers=_auth(user1_token))+ assert metadata.status_code == status.HTTP_200_OK+ assert metadata.headers["cache-control"] == "private, no-store"++ downloaded = client.get(font["url"], headers=_auth(user1_token))+ assert downloaded.status_code == status.HTTP_200_OK+ assert downloaded.content == font_bytes+ assert downloaded.headers["content-type"] == "font/ttf"+ assert downloaded.headers["cache-control"] == "private, no-store"+ assert downloaded.headers["content-disposition"] == "inline; filename*=UTF-8''R%C3%A9sum%C3%A9.ttf"++ changed = client.get(font["url"], params={"expected_hash": "0" * 64}, headers=_auth(user1_token))+ assert changed.status_code == status.HTTP_409_CONFLICT+++def test_private_font_is_hidden_from_other_users_and_owner_can_delete(+ client: TestClient, user1_token: str, user2_token: str, font_service: FontService, font_bytes: bytes+) -> None:+ uploaded = _upload(client, user1_token, font_bytes).json()["font"]++ listed = client.get("/api/v1/fonts", headers=_auth(user2_token))+ assert listed.status_code == status.HTTP_200_OK+ assert all(item["id"] != uploaded["id"] for item in listed.json()["items"])++ hidden = client.get(uploaded["url"], headers=_auth(user2_token))+ assert hidden.status_code == status.HTTP_404_NOT_FOUND++ deleted = client.delete(f"/api/v1/fonts/{uploaded['id']}", headers=_auth(user1_token))+ assert deleted.status_code == status.HTTP_204_NO_CONTENT+ assert font_service.get(uploaded["id"]) is None+ assert not list(font_service._storage_dir.glob("*"))+++def test_shared_upload_and_admin_rescan_authorization(+ client: TestClient,+ admin_token: str,+ user1_token: str,+ user2_token: str,+ font_service: FontService,+ font_bytes: bytes,+) -> None:+ regular_shared = _upload(client, user1_token, font_bytes, scope="shared")+ assert regular_shared.status_code == status.HTTP_403_FORBIDDEN++ shared = _upload(client, admin_token, font_bytes, filename="Shared.ttf", scope="shared")+ assert shared.status_code == status.HTTP_200_OK+ shared_font = shared.json()["font"]+ listed = client.get("/api/v1/fonts", headers=_auth(user2_token))+ assert any(item["id"] == shared_font["id"] for item in listed.json()["items"])++ forbidden_delete = client.delete(f"/api/v1/fonts/{shared_font['id']}", headers=_auth(user2_token))+ assert forbidden_delete.status_code == status.HTTP_403_FORBIDDEN++ directory_file = font_service._fonts_dir / "Directory.ttf"+ directory_file.parent.mkdir(parents=True)+ directory_file.write_bytes(font_bytes)+ rescan = client.post("/api/v1/fonts/rescan", headers=_auth(user1_token))+ assert rescan.status_code == status.HTTP_403_FORBIDDEN+ rescan = client.post("/api/v1/fonts/rescan", headers=_auth(admin_token))+ assert rescan.status_code == status.HTTP_200_OK+ assert rescan.json()["indexed"] == 1++ deleted = client.delete(f"/api/v1/fonts/{shared_font['id']}", headers=_auth(admin_token))+ assert deleted.status_code == status.HTTP_204_NO_CONTENT+++def test_static_instance_route_returns_original_binary(+ client: TestClient, user1_token: str, font_service: FontService, font_bytes: bytes+) -> None:+ uploaded = _upload(client, user1_token, font_bytes).json()["font"]+ response = client.post(+ f"/api/v1/fonts/{uploaded['id']}/instance",+ headers=_auth(user1_token),+ json={"content_hash": uploaded["content_hash"], "coordinates": {}},+ )+ assert response.status_code == status.HTTP_200_OK+ assert response.content == font_bytes+ assert response.headers["content-type"] == "font/ttf"+ assert response.headers["cache-control"] == "private, no-store"diff --git a/tests/app/routers/test_utilities.py b/tests/app/routers/test_utilities.pyindex 1a2f2c2935..de5fd17b8c 100644--- a/tests/app/routers/test_utilities.py+++ b/tests/app/routers/test_utilities.py@@ -232,7 +232,7 @@ def test_user_fonts_support_real_font_files_and_configured_directory(assert font_response.status_code == status.HTTP_200_OKassert font_response.headers["content-type"] == "font/ttf"- assert font_response.headers["cache-control"] == "private, max-age=31536000, immutable"+ assert font_response.headers["cache-control"] == "private, no-cache"assert font_response.headers["content-disposition"].startswith('inline; filename="Inter-Regular.ttf"')assert font_response.content == source_font.read_bytes()diff --git a/tests/app/services/fonts/test_fonts_service.py b/tests/app/services/fonts/test_fonts_service.pynew file mode 100644index 0000000000..b1ab4bcd9a--- /dev/null+++ b/tests/app/services/fonts/test_fonts_service.py@@ -0,0 +1,422 @@+"""Service-level coverage for the account-scoped font library."""++import io+import logging+import subprocess+import threading+from pathlib import Path+from unittest.mock import Mock++import pytest+from fontTools.fontBuilder import FontBuilder+from fontTools.pens.ttGlyphPen import TTGlyphPen+from fontTools.ttLib.tables.TupleVariation import TupleVariation++from invokeai.app.services.config.config_default import InvokeAIAppConfig+from invokeai.app.services.fonts.fonts_common import FontScope, FontSource, FontUploadResult+from invokeai.app.services.fonts.fonts_default import (+ MAX_INDEXED_FONT_BYTES,+ FontChangedError,+ FontDeleteForbiddenError,+ FontNotFoundError,+ FontQuotaExceededError,+ FontService,+ FontValidationError,+)+from invokeai.app.services.image_files.image_files_base import ImageFileStorageBase+from invokeai.app.services.shared.sqlite.sqlite_util import init_db+from invokeai.app.services.users.users_common import UserCreateRequest+from invokeai.app.services.users.users_default import UserService+++def font_service(tmp_path: Path) -> FontService:+ config = InvokeAIAppConfig(use_memory_db=True)+ db = init_db(config, logging.getLogger("font-tests"), Mock(spec=ImageFileStorageBase))+ service = FontService(+ db=db,+ fonts_dir=tmp_path / "fonts",+ storage_dir=tmp_path / "uploaded-fonts",+ logger=logging.getLogger("font-tests"),+ )+ yield service+ service.stop()+++def font_bytes() -> bytes:+ return (Path(__file__).parents[4] / "invokeai" / "assets" / "fonts" / "inter" / "Inter-Regular.ttf").read_bytes()+++def _create_user(service: FontService, email: str) -> str:+ users = UserService(service._db)+ return users.create(UserCreateRequest(email=email, password="TestPass123", display_name=email)).user_id+++def _variable_font_bytes() -> bytes:+ """Build a tiny variable TTF so the worker test has no external fixture dependency."""+ glyph_order = [".notdef", "space", "A"]+ glyphs = {}+ for glyph_name in glyph_order:+ pen = TTGlyphPen(None)+ pen.moveTo((100, 100))+ pen.lineTo((100, 800))+ pen.lineTo((500, 800))+ pen.lineTo((500, 100))+ pen.closePath()+ glyphs[glyph_name] = pen.glyph()++ builder = FontBuilder(1000, isTTF=True)+ builder.setupGlyphOrder(glyph_order)+ builder.setupCharacterMap({32: "space", 65: "A"})+ builder.setupGlyf(glyphs)+ builder.setupHorizontalMetrics({".notdef": (600, 0), "space": (500, 0), "A": (500, 100)})+ builder.setupHorizontalHeader(ascent=800, descent=-200)+ builder.setupNameTable(+ {+ "familyName": "Fixture Variable",+ "styleName": "Regular",+ "uniqueFontIdentifier": "Fixture Variable Regular",+ "fullName": "Fixture Variable Regular",+ "psName": "FixtureVariable-Regular",+ "version": "Version 1.0",+ }+ )+ builder.setupOS2(sTypoAscender=800, usWinAscent=800, usWinDescent=200, usWeightClass=400)+ builder.setupPost()+ builder.setupFvar(+ [("wght", 100, 400, 900, "Weight")],+ [{"location": {"wght": 700}, "stylename": "Bold"}],+ )+ # Four outline points plus four phantom points for A. The right edge widens as wght rises.+ builder.setupGvar(+ {+ "A": [+ TupleVariation(+ {"wght": (0.0, 1.0, 1.0)},+ [(0, 0), (0, 0), (100, 0), (100, 0), (0, 0), (0, 0), (0, 0), (0, 0)],+ )+ ]+ }+ )+ output = io.BytesIO()+ builder.save(output)+ return output.getvalue()+++def test_private_uploads_are_deduplicated_and_isolated(font_service: FontService, font_bytes: bytes) -> None:+ alice = _create_user(font_service, "[email protected]")+ bob = _create_user(font_service, "[email protected]")++ first = font_service.upload(user_id=alice, filename="Inter-Regular.ttf", data=font_bytes)+ duplicate = font_service.upload(user_id=alice, filename="renamed.ttf", data=font_bytes)++ assert first.created is True+ assert duplicate.created is False+ assert duplicate.font.id == first.font.id+ assert font_service.list(user_id=alice)[1] == 1+ assert font_service.list(user_id=bob)[1] == 0+ with pytest.raises(FontNotFoundError):+ font_service.get_accessible(user_id=bob, font_id=first.font.id)+++def test_user_cleanup_removes_private_files_but_preserves_shared_files(+ font_service: FontService, font_bytes: bytes+) -> None:+ users = UserService(font_service._db)+ user_id = _create_user(font_service, "[email protected]")++ private = font_service.upload(user_id=user_id, filename="Private.ttf", data=font_bytes).font+ shared = font_service.upload(user_id="system", filename="Shared.ttf", data=font_bytes, scope=FontScope.SHARED).font+ assert private.storage_path is not None+ assert shared.storage_path is not None+ private_path = font_service._storage_dir / private.storage_path+ shared_path = font_service._storage_dir / shared.storage_path+ assert private_path.is_file()+ assert shared_path.is_file()++ font_storage_paths = font_service.prepare_user_cleanup(user_id)+ users.delete(user_id)+ font_service.cleanup_user(user_id, font_storage_paths)++ assert not private_path.exists()+ assert shared_path.is_file()+ assert font_service.get(private.id) is None+ assert font_service.get(shared.id) is not None+++def test_shared_uploads_are_visible_and_directory_fonts_are_read_only(+ font_service: FontService, font_bytes: bytes, tmp_path: Path+) -> None:+ shared = font_service.upload(user_id="system", filename="Inter.ttf", data=font_bytes, scope=FontScope.SHARED)+ assert shared.font.scope == FontScope.SHARED+ assert font_service.list(user_id="another-user", scope=FontScope.SHARED)[1] == 1++ directory_file = tmp_path / "fonts" / "nested" / "Inter.ttf"+ directory_file.parent.mkdir(parents=True)+ directory_file.write_bytes(font_bytes)+ assert font_service.rescan_directory() == 1+ directory = font_service.list(user_id="another-user", scope=FontScope.SHARED)[0]+ assert directory[0].source == FontSource.DIRECTORY++ with pytest.raises(FontDeleteForbiddenError):+ font_service.delete(user_id="system", font_id=directory[0].id, is_admin=True)+++def test_validation_and_quota_do_not_leave_files(font_service: FontService, font_bytes: bytes) -> None:+ validated = font_service.validate("Inter-Regular.ttf", font_bytes)+ assert validated.content_hash+ assert font_service.list(user_id="system")[1] == 0++ tiny_quota = FontService(+ db=font_service._db,+ fonts_dir=font_service._fonts_dir,+ storage_dir=font_service._storage_dir / "quota",+ max_library_bytes=len(font_bytes) - 1,+ )+ try:+ with pytest.raises(FontQuotaExceededError):+ tiny_quota.upload(user_id="system", filename="Inter.ttf", data=font_bytes)+ assert not list((font_service._storage_dir / "quota").glob("*"))+ finally:+ tiny_quota.stop()+++def test_rescan_removes_missing_directory_rows_and_detects_replacement(+ font_service: FontService, font_bytes: bytes, tmp_path: Path+) -> None:+ directory_file = tmp_path / "fonts" / "Inter.ttf"+ directory_file.parent.mkdir(parents=True)+ directory_file.write_bytes(font_bytes)+ assert font_service.rescan_directory() == 1+ record = font_service.list(user_id="system")[0][0]++ directory_file.write_bytes(b"changed")+ with pytest.raises(FontChangedError):+ font_service.read_file(user_id="system", font_id=record.id, expected_hash=record.content_hash)++ directory_file.unlink()+ assert font_service.rescan_directory() == 0+ assert font_service.list(user_id="system")[1] == 0+++def test_rescan_clears_index_when_directory_is_removed(+ font_service: FontService, font_bytes: bytes, tmp_path: Path+) -> None:+ directory_file = tmp_path / "fonts" / "Inter.ttf"+ directory_file.parent.mkdir(parents=True)+ directory_file.write_bytes(font_bytes)+ assert font_service.rescan_directory() == 1+ assert font_service.list(user_id="system")[1] == 1++ directory_file.unlink()+ directory_file.parent.rmdir()+ assert font_service.rescan_directory() == 0+ assert font_service.list(user_id="system")[1] == 0+++def test_rescan_rejects_oversized_directory_files_before_open(+ font_service: FontService, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ oversized = tmp_path / "fonts" / "oversized.ttf"+ oversized.parent.mkdir(parents=True)+ with oversized.open("wb") as file:+ file.truncate(MAX_INDEXED_FONT_BYTES + 1)++ original_open = Path.open+ opened = False++ def guarded_open(path: Path, *args: object, **kwargs: object):+ nonlocal opened+ if path == oversized:+ opened = True+ raise AssertionError("oversized directory file must be rejected before opening")+ return original_open(path, *args, **kwargs)++ monkeypatch.setattr(Path, "open", guarded_open)+ assert font_service.rescan_directory() == 0+ assert opened is False+ assert font_service.list(user_id="system")[1] == 0+++def test_cleanup_cannot_delete_upload_that_starts_during_sweep(+ font_service: FontService, font_bytes: bytes, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The cleanup snapshot and upload publish sequence share one mutation lock."""+ validation = font_service.validate("Inter.ttf", font_bytes)+ font_service._storage_dir.mkdir(parents=True)+ validation_started = threading.Event()+ write_finished = threading.Event()+ sweep_started = threading.Event()+ allow_sweep = threading.Event()+ cleanup_errors: list[BaseException] = []+ upload_result: list[FontUploadResult | BaseException] = []++ def validate(_filename: str, _data: bytes):+ validation_started.set()+ return validation++ original_write = font_service._write_atomic++ def write_atomic(target: Path, data: bytes) -> None:+ original_write(target, data)+ write_finished.set()++ original_iterdir = Path.iterdir++ def blocked_iterdir(path: Path):+ if path == font_service._storage_dir and not sweep_started.is_set():+ sweep_started.set()+ assert allow_sweep.wait(timeout=5)+ return original_iterdir(path)++ monkeypatch.setattr(font_service, "validate", validate)+ monkeypatch.setattr(font_service, "_write_atomic", write_atomic)+ monkeypatch.setattr(Path, "iterdir", blocked_iterdir)++ def cleanup() -> None:+ try:+ font_service.cleanup_orphaned_files()+ except BaseException as error: # pragma: no cover - surfaced below+ cleanup_errors.append(error)++ def upload() -> None:+ try:+ upload_result.append(font_service.upload(user_id="system", filename="Inter.ttf", data=font_bytes))+ except BaseException as error: # pragma: no cover - surfaced below+ upload_result.append(error)++ cleanup_thread = threading.Thread(target=cleanup)+ upload_thread = threading.Thread(target=upload)+ cleanup_thread.start()+ assert sweep_started.wait(timeout=5)+ upload_thread.start()+ try:+ assert validation_started.wait(timeout=5)+ assert not write_finished.wait(timeout=0.25)+ finally:+ allow_sweep.set()+ cleanup_thread.join(timeout=5)+ upload_thread.join(timeout=5)++ assert cleanup_errors == []+ assert upload_result and not isinstance(upload_result[0], BaseException)+ assert write_finished.is_set()+ uploaded = upload_result[0]+ assert isinstance(uploaded, FontUploadResult)+ assert uploaded.font.storage_path is not None+ assert (font_service._storage_dir / uploaded.font.storage_path).is_file()+++def test_variable_instances_are_pinned_and_cached(font_service: FontService, tmp_path: Path) -> None:+ data = _variable_font_bytes()+ destination = tmp_path / "fonts" / "FixtureVariable.ttf"+ destination.parent.mkdir(parents=True)+ destination.write_bytes(data)+ assert font_service.rescan_directory() == 1+ record = font_service.list(user_id="system")[0][0]++ _, default_data = font_service.instance(+ user_id="system", font_id=record.id, content_hash=record.content_hash, coordinates={"wght": 400}+ )+ _, bold_data = font_service.instance(+ user_id="system", font_id=record.id, content_hash=record.content_hash, coordinates={"wght": 850}+ )+ _, cached_bold_data = font_service.instance(+ user_id="system", font_id=record.id, content_hash=record.content_hash, coordinates={"wght": 850}+ )++ assert default_data != data+ assert bold_data != default_data+ assert cached_bold_data == bold_data+++def test_deleted_font_cannot_repopulate_instance_cache_after_worker_finishes(+ font_service: FontService, font_bytes: bytes, monkeypatch: pytest.MonkeyPatch+) -> None:+ user_id = _create_user(font_service, "[email protected]")+ uploaded = font_service.upload(user_id=user_id, filename="Variable.ttf", data=_variable_font_bytes()).font+ font_service.instance(+ user_id=user_id,+ font_id=uploaded.id,+ content_hash=uploaded.content_hash,+ coordinates={"wght": 400},+ )+ assert font_service._instance_cache+ worker_started = threading.Event()+ allow_worker = threading.Event()+ worker_errors: list[BaseException] = []++ def blocked_worker(operation: str, args: tuple[object, ...], *, error_type: type[FontValidationError]):+ del args, error_type+ assert operation == "instance"+ worker_started.set()+ assert allow_worker.wait(timeout=5)+ return b"derived-instance"++ monkeypatch.setattr(font_service, "_run_worker", blocked_worker)++ def run_instance() -> None:+ try:+ font_service.instance(+ user_id=user_id,+ font_id=uploaded.id,+ content_hash=uploaded.content_hash,+ coordinates={"wght": 700},+ )+ except BaseException as error: # pragma: no cover - surfaced below+ worker_errors.append(error)++ instance_thread = threading.Thread(target=run_instance)+ instance_thread.start()+ assert worker_started.wait(timeout=5)+ font_service.delete(user_id=user_id, font_id=uploaded.id)+ allow_worker.set()+ instance_thread.join(timeout=5)++ assert not instance_thread.is_alive()+ assert worker_errors and isinstance(worker_errors[0], FontNotFoundError)+ assert not font_service._instance_cache+++def test_failed_worker_is_cleaned_up_before_next_job(font_service: FontService, font_bytes: bytes) -> None:+ with pytest.raises(FontValidationError):+ font_service.validate("broken.ttf", b"not-a-font")+ assert not font_service._active_workers++ uploaded = font_service.upload(user_id="system", filename="Inter.ttf", data=font_bytes)+ assert uploaded.created is True+++def test_timed_out_worker_is_killed_and_slots_are_released(+ font_service: FontService, font_bytes: bytes, monkeypatch: pytest.MonkeyPatch+) -> None:+ class HangingProcess:+ returncode = None++ def __init__(self) -> None:+ self.killed = False++ def communicate(self, input: bytes | None = None, timeout: float | None = None):+ del input+ if timeout is not None:+ raise subprocess.TimeoutExpired(cmd="font-worker", timeout=timeout)+ return b"", b""++ def poll(self) -> int | None:+ return -9 if self.killed else None++ def kill(self) -> None:+ self.killed = True++ hanging = HangingProcess()+ with monkeypatch.context() as patch:+ patch.setattr("invokeai.app.services.fonts.fonts_default.subprocess.Popen", lambda *args, **kwargs: hanging)+ with pytest.raises(FontValidationError, match="timed out"):+ font_service.validate("Inter.ttf", font_bytes)+ assert hanging.killed+ assert not font_service._active_workers++ # This call proves the worker admission and active-slot semaphores were both released.+ uploaded = font_service.upload(user_id="system", filename="Inter.ttf", data=font_bytes)+ assert uploaded.created is Truediff --git a/tests/app/util/test_user_management.py b/tests/app/util/test_user_management.pynew file mode 100644index 0000000000..8d8c121535--- /dev/null+++ b/tests/app/util/test_user_management.py@@ -0,0 +1,81 @@+"""Coverage for account deletion through the user-management commands."""++import logging+from pathlib import Path+from unittest.mock import Mock++import pytest++from invokeai.app.services.config.config_default import InvokeAIAppConfig+from invokeai.app.services.fonts.fonts_common import FontScope+from invokeai.app.services.fonts.fonts_default import FontService+from invokeai.app.services.image_files.image_files_base import ImageFileStorageBase+from invokeai.app.services.shared.sqlite.sqlite_util import init_db+from invokeai.app.services.users.users_common import UserCreateRequest+from invokeai.app.services.users.users_default import UserService+from invokeai.app.util import user_management+++def deletion_fixture(tmp_path: Path):+ config = InvokeAIAppConfig(+ use_memory_db=False,+ db_dir=tmp_path / "databases",+ fonts_dir=tmp_path / "fonts",+ fonts_storage_dir=tmp_path / "uploaded-fonts",+ )+ config._root = tmp_path+ logger = logging.getLogger("user-management-font-tests")+ db = init_db(config, logger, Mock(spec=ImageFileStorageBase))+ fonts = FontService(+ db=db,+ fonts_dir=config.fonts_path,+ storage_dir=config.fonts_storage_path,+ logger=logger,+ )+ users = UserService(db)+ users.create(UserCreateRequest(email="[email protected]", password="AdminPass123", is_admin=True))+ owner = users.create(UserCreateRequest(email="[email protected]", password="OwnerPass123"))+ font_bytes = (+ Path(__file__).parents[3] / "invokeai" / "assets" / "fonts" / "inter" / "Inter-Regular.ttf"+ ).read_bytes()+ private = fonts.upload(user_id=owner.user_id, filename="Private.ttf", data=font_bytes).font+ shared = fonts.upload(user_id="system", filename="Shared.ttf", data=font_bytes, scope=FontScope.SHARED).font+ assert private.storage_path is not None+ assert shared.storage_path is not None+ pending = fonts._storage_dir / ("font_" + "a" * 32 + ".ttf")+ pending.write_bytes(font_bytes)+ yield (+ config,+ fonts,+ owner.email,+ shared.id,+ fonts._storage_dir / private.storage_path,+ fonts._storage_dir / shared.storage_path,+ pending,+ )+ fonts.stop()++[email protected]("interactive", [False, True])+def test_user_delete_commands_clean_private_fonts_and_keep_shared_fonts(+ monkeypatch: pytest.MonkeyPatch, deletion_fixture, interactive: bool+) -> None:+ config, fonts, email, shared_id, private_path, shared_path, pending_path = deletion_fixture+ assert private_path.is_file()+ assert shared_path.is_file()+ assert pending_path.is_file()++ monkeypatch.setattr("invokeai.app.services.config.get_config", lambda: config)+ if interactive:+ answers = iter([email, "yes"])+ monkeypatch.setattr("builtins.input", lambda _prompt: next(answers))+ deleted = user_management._delete_user_interactive()+ else:+ deleted = user_management._delete_user_cli(email, force=True)++ assert deleted is True+ assert not private_path.exists()+ assert shared_path.is_file()+ assert pending_path.is_file()+ assert fonts.get_accessible(user_id="system", font_id=shared_id).id == shared_id