Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(nodes): add managed file inputs (#9302)

Gohankaiju6b904e4c1614
diff --git a/docs/src/generated/invocation-context.json b/docs/src/generated/invocation-context.json
index 0c29c4b8d7..a9259a2e98 100644
--- a/docs/src/generated/invocation-context.json
+++ b/docs/src/generated/invocation-context.json
@@ -1,5 +1,5 @@
{
- "description": "Provides access to various services and data for the current invocation.\n\nAttributes:\n images (ImagesInterface): Methods to save, get and update images and their metadata.\n tensors (TensorsInterface): Methods to save and get tensors, including image, noise, masks, and masked images.\n conditioning (ConditioningInterface): Methods to save and get conditioning data.\n models (ModelsInterface): Methods to check if a model exists, get a model, and get a model's info.\n logger (LoggerInterface): The app logger.\n config (ConfigInterface): The app config.\n util (UtilInterface): Utility methods, including a method to check if an invocation was canceled and step callbacks.\n boards (BoardsInterface): Methods to interact with boards.\n wildcards (WildcardsInterface): Access to the queueing user's wildcards.",
+ "description": "Provides access to various services and data for the current invocation.\n\nAttributes:\n images (ImagesInterface): Methods to save, get and update images and their metadata.\n tensors (TensorsInterface): Methods to save and get tensors, including image, noise, masks, and masked images.\n conditioning (ConditioningInterface): Methods to save and get conditioning data.\n models (ModelsInterface): Methods to check if a model exists, get a model, and get a model's info.\n logger (LoggerInterface): The app logger.\n config (ConfigInterface): The app config.\n util (UtilInterface): Utility methods, including a method to check if an invocation was canceled and step callbacks.\n boards (BoardsInterface): Methods to interact with boards.\n files (FilesInterface): Methods to read managed files uploaded for node inputs.\n wildcards (WildcardsInterface): Access to the queueing user's wildcards.",
"interfaces": [
{
"description": "",
@@ -681,6 +681,63 @@
}
],
"name": "BoardsInterface"
+ },
+ {
+ "description": "",
+ "methods": [
+ {
+ "description": "Gets metadata for a managed file.",
+ "name": "get_dto",
+ "parameters": [
+ {
+ "default": "",
+ "description": "The managed file ID.",
+ "name": "file_id",
+ "type": "str"
+ }
+ ],
+ "return_type": "FileDTO",
+ "returns": "The file DTO.",
+ "signature": "(file_id: str) -> FileDTO"
+ },
+ {
+ "description": "Gets the server-side path to a managed file.",
+ "name": "get_path",
+ "parameters": [
+ {
+ "default": "",
+ "description": "The managed file ID.",
+ "name": "file_id",
+ "type": "str"
+ }
+ ],
+ "return_type": "Path",
+ "returns": "The path to the managed file on the InvokeAI server.",
+ "signature": "(file_id: str) -> Path"
+ },
+ {
+ "description": "Opens a managed file for reading.",
+ "name": "open",
+ "parameters": [
+ {
+ "default": "",
+ "description": "The managed file ID.",
+ "name": "file_id",
+ "type": "str"
+ },
+ {
+ "default": "'rb'",
+ "description": "The read mode to use. Supported values are \"rb\" and \"r\".",
+ "name": "mode",
+ "type": "str"
+ }
+ ],
+ "return_type": "IO[Any]",
+ "returns": "A readable file object.",
+ "signature": "(file_id: str, mode: str = 'rb') -> IO[Any]"
+ }
+ ],
+ "name": "FilesInterface"
}
],
"name": "InvocationContext"
diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.json
index b340d173c2..6ba1e1609e 100644
--- a/docs/src/generated/settings.json
+++ b/docs/src/generated/settings.json
@@ -293,6 +293,28 @@
"type": "<class 'int'>",
"validation": {}
},
+ {
+ "category": "PATHS",
+ "default": 52428800,
+ "description": "Maximum size in bytes of one managed file upload.",
+ "env_var": "INVOKEAI_MAX_FILE_UPLOAD_SIZE_BYTES",
+ "literal_values": [],
+ "name": "max_file_upload_size_bytes",
+ "required": false,
+ "type": "<class 'int'>",
+ "validation": {}
+ },
+ {
+ "category": "PATHS",
+ "default": 5368709120,
+ "description": "Maximum total size in bytes of all managed files.",
+ "env_var": "INVOKEAI_MAX_FILE_LIBRARY_BYTES",
+ "literal_values": [],
+ "name": "max_file_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.py
index ee776633b7..00e0188a92 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.files.files_disk import DiskFileService
from invokeai.app.services.fonts.fonts_default import FontService
from invokeai.app.services.gallery.gallery_default import GalleryService
from invokeai.app.services.gallery_maintenance.gallery_maintenance_default import GalleryMaintenanceService
@@ -135,6 +136,11 @@ class ApiDependencies:
raise ValueError("Output folder is not set")
image_files = DiskImageFileStorage(f"{output_folder}/images")
+ files = DiskFileService(
+ output_folder / "files",
+ max_file_size=config.max_file_upload_size_bytes,
+ max_storage_size=config.max_file_library_bytes,
+ )
video_files = DiskVideoFileStorage(f"{output_folder}/videos")
model_images_folder = config.models_path
@@ -247,6 +253,7 @@ class ApiDependencies:
configuration=configuration,
database=database,
events=events,
+ files=files,
image_files=image_files,
image_moves=image_moves,
progress_previews=MemoryProgressPreviews(),
diff --git a/invokeai/app/api/routers/files.py b/invokeai/app/api/routers/files.py
new file mode 100644
index 0000000000..255ed75427
--- /dev/null
+++ b/invokeai/app/api/routers/files.py
@@ -0,0 +1,108 @@
+from fastapi import HTTPException, Path, UploadFile
+from fastapi.concurrency import run_in_threadpool
+from fastapi.routing import APIRouter
+
+from invokeai.app.api.auth_dependencies import CurrentUserOrDefault
+from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.services.files.files_base import FileServiceBase
+from invokeai.app.services.files.files_common import (
+ FileAccessDeniedException,
+ FileDTO,
+ FileMetadataException,
+ FileNotFoundException,
+ FileQuotaExceededException,
+ FileTooLargeException,
+ UnsupportedFileTypeException,
+)
+
+files_router = APIRouter(prefix="/v1/files", tags=["files"])
+
+# The request-body limiter runs before Starlette parses multipart uploads. Keep the framing
+# allowance bounded so the configured managed-file limit remains the dominant part of the request cap.
+FILE_UPLOAD_MULTIPART_OVERHEAD = 1024 * 1024
+MAX_CONCURRENT_FILE_UPLOADS = 2
+MAX_CONCURRENT_FILE_UPLOADS_PER_USER = 1
+# Match the video-upload ingress: allow long transfers on slow links instead of dropping them after two minutes.
+FILE_UPLOAD_IDLE_TIMEOUT_SECONDS = 120.0
+FILE_UPLOAD_MAX_DURATION_SECONDS = 30 * 60
+
+
+def _get_file_service() -> FileServiceBase:
+ file_service = ApiDependencies.invoker.services.files
+ if file_service is None:
+ raise HTTPException(status_code=503, detail="Managed file service is not available")
+ return file_service
+
+
+@files_router.post(
+ "/upload",
+ operation_id="upload_file",
+ responses={
+ 201: {"description": "The file was uploaded successfully"},
+ 413: {"description": "The file is too large or managed file storage is full"},
+ 415: {"description": "The file type is not supported"},
+ },
+ status_code=201,
+ response_model=FileDTO,
+)
+async def upload_file(
+ current_user: CurrentUserOrDefault,
+ file: UploadFile,
+) -> FileDTO:
+ """Uploads a managed file for node inputs."""
+ try:
+ return await run_in_threadpool(
+ _get_file_service().save,
+ file_name=file.filename or "",
+ content_type=file.content_type,
+ file=file.file,
+ user_id=current_user.user_id,
+ )
+ except UnsupportedFileTypeException as e:
+ raise HTTPException(status_code=415, detail=str(e))
+ except (FileTooLargeException, FileQuotaExceededException) as e:
+ raise HTTPException(status_code=413, detail=str(e))
+ except FileMetadataException as e:
+ raise HTTPException(status_code=500, detail=str(e))
+ finally:
+ await file.close()
+
+
+@files_router.get(
+ "/i/{file_id}",
+ operation_id="get_file_dto",
+ response_model=FileDTO,
+)
+async def get_file_dto(
+ current_user: CurrentUserOrDefault,
+ file_id: str = Path(description="The managed file ID."),
+) -> FileDTO:
+ """Gets metadata for a managed file."""
+ try:
+ return await run_in_threadpool(_get_file_service().get_dto, file_id, user_id=current_user.user_id)
+ except FileAccessDeniedException:
+ raise HTTPException(status_code=403, detail="Not authorized to access this file")
+ except FileNotFoundException:
+ raise HTTPException(status_code=404, detail="File not found")
+ except FileMetadataException as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
+@files_router.delete(
+ "/i/{file_id}",
+ operation_id="delete_file",
+ status_code=204,
+)
+async def delete_file(
+ current_user: CurrentUserOrDefault,
+ file_id: str = Path(description="The managed file ID."),
+) -> None:
+ """Deletes a managed file."""
+ try:
+ await run_in_threadpool(_get_file_service().delete, file_id, user_id=current_user.user_id)
+ except FileAccessDeniedException:
+ raise HTTPException(status_code=403, detail="Not authorized to delete this file")
+ except FileNotFoundException:
+ raise HTTPException(status_code=404, detail="File not found")
+ except FileMetadataException as e:
+ raise HTTPException(status_code=500, detail=str(e))
diff --git a/invokeai/app/api_app.py b/invokeai/app/api_app.py
index 7b359a9e02..ba37bbe771 100644
--- a/invokeai/app/api_app.py
+++ b/invokeai/app/api_app.py
@@ -32,6 +32,7 @@ from invokeai.app.api.routers import (
boards,
client_state,
custom_nodes,
+ files,
fonts,
gallery,
gallery_maintenance,
@@ -646,6 +647,10 @@ def _is_font_upload(method: str, path: str) -> bool:
return method == "POST" and path in ("/api/v1/fonts", "/api/v1/fonts/validate")
+def _is_file_upload(method: str, path: str) -> bool:
+ return method == "POST" and path == "/api/v1/files/upload"
+
+
class ProjectWriteLimitASGIMiddleware(RequestBodyLimitASGIMiddleware):
"""Bound project writes before FastAPI parses their JSON documents."""
@@ -731,6 +736,22 @@ 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_file_upload,
+ too_large_detail=lambda _actual, limit: f"Managed file upload exceeds maximum request size ({limit} bytes)",
+ capacity_refusal_detail=lambda per_user: (
+ "Too many concurrent file uploads for this user; try again shortly"
+ if per_user
+ else "Too many concurrent file uploads; try again shortly"
+ ),
+ max_body_bytes=app_config.max_file_upload_size_bytes + files.FILE_UPLOAD_MULTIPART_OVERHEAD,
+ max_concurrent=files.MAX_CONCURRENT_FILE_UPLOADS,
+ max_concurrent_per_user=files.MAX_CONCURRENT_FILE_UPLOADS_PER_USER,
+ identify_user=_identify_video_upload_user_async,
+ idle_timeout_seconds=files.FILE_UPLOAD_IDLE_TIMEOUT_SECONDS,
+ max_upload_duration_seconds=files.FILE_UPLOAD_MAX_DURATION_SECONDS,
+)
app.add_middleware(
RequestBodyLimitASGIMiddleware,
matches_request=_is_font_upload,
@@ -788,6 +809,7 @@ 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(working_memory.working_memory_router, prefix="/api")
+app.include_router(files.files_router, prefix="/api")
app.include_router(image_moves.image_moves_router, prefix="/api")
app.include_router(images.images_router, prefix="/api")
app.include_router(image_map.image_map_router, prefix="/api")
diff --git a/invokeai/app/invocations/fields.py b/invokeai/app/invocations/fields.py
index a81527b124..a1acde9965 100644
--- a/invokeai/app/invocations/fields.py
+++ b/invokeai/app/invocations/fields.py
@@ -284,6 +284,12 @@ class ImageField(BaseModel):
image_name: str = Field(description="The name of the image")
+class FileField(BaseModel):
+ """A managed file primitive field"""
+
+ file_id: str = Field(description="The id of the managed file")
+
+
class VideoField(BaseModel):
"""A video primitive field"""
diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.py
index 849630e753..ef3fdfa333 100644
--- a/invokeai/app/services/config/config_default.py
+++ b/invokeai/app/services/config/config_default.py
@@ -19,6 +19,7 @@ from pydantic import BaseModel, Field, PrivateAttr, field_validator
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict
import invokeai.configs as model_configs
+from invokeai.app.services.files.files_common import DEFAULT_FILE_LIBRARY_MAX_BYTES, DEFAULT_FILE_UPLOAD_MAX_BYTES
from invokeai.backend.model_hash.model_hash import HASHING_ALGORITHMS
from invokeai.frontend.cli.arg_parser import InvokeAIArgs
@@ -219,6 +220,8 @@ class InvokeAIAppConfig(BaseSettings):
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.")
+ max_file_upload_size_bytes: int = Field(default=DEFAULT_FILE_UPLOAD_MAX_BYTES, gt=0, le=1024 * 1024 * 1024, description="Maximum size in bytes of one managed file upload.")
+ max_file_library_bytes: int = Field(default=DEFAULT_FILE_LIBRARY_MAX_BYTES, gt=0, le=16 * 1024 * 1024 * 1024, description="Maximum total size in bytes of all managed files.")
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.")
diff --git a/invokeai/app/services/files/__init__.py b/invokeai/app/services/files/__init__.py
new file mode 100644
index 0000000000..cf10eb939b
--- /dev/null
+++ b/invokeai/app/services/files/__init__.py
@@ -0,0 +1 @@
+"""Managed file services for node inputs."""
diff --git a/invokeai/app/services/files/files_base.py b/invokeai/app/services/files/files_base.py
new file mode 100644
index 0000000000..dd8f1e02f5
--- /dev/null
+++ b/invokeai/app/services/files/files_base.py
@@ -0,0 +1,33 @@
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import IO, Any, BinaryIO
+
+from invokeai.app.services.files.files_common import FileDTO
+
+
+class FileServiceBase(ABC):
+ @abstractmethod
+ def save(
+ self,
+ file_name: str,
+ content_type: str | None,
+ file: BinaryIO,
+ user_id: str | None,
+ ) -> FileDTO:
+ """Saves a managed file and returns its DTO."""
+
+ @abstractmethod
+ def get_dto(self, file_id: str, user_id: str | None = None) -> FileDTO:
+ """Gets a managed file DTO."""
+
+ @abstractmethod
+ def get_path(self, file_id: str, user_id: str | None = None) -> Path:
+ """Gets the path to a managed file."""
+
+ @abstractmethod
+ def open(self, file_id: str, mode: str = "rb", user_id: str | None = None) -> IO[Any]:
+ """Opens a managed file."""
+
+ @abstractmethod
+ def delete(self, file_id: str, user_id: str | None = None) -> None:
+ """Deletes a managed file."""
diff --git a/invokeai/app/services/files/files_common.py b/invokeai/app/services/files/files_common.py
new file mode 100644
index 0000000000..1df2f8b33b
--- /dev/null
+++ b/invokeai/app/services/files/files_common.py
@@ -0,0 +1,75 @@
+from datetime import datetime
+
+from pydantic import BaseModel, Field
+
+DEFAULT_FILE_UPLOAD_MAX_BYTES = 50 * 1024 * 1024
+DEFAULT_FILE_LIBRARY_MAX_BYTES = 5 * 1024 * 1024 * 1024
+
+SUPPORTED_FILE_EXTENSIONS = frozenset(
+ {
+ ".csv",
+ ".json",
+ ".md",
+ ".markdown",
+ ".pdf",
+ ".txt",
+ ".yaml",
+ ".yml",
+ }
+)
+
+SUPPORTED_FILE_MIME_TYPES = frozenset(
+ {
+ "application/csv",
+ "application/json",
+ "application/pdf",
+ "application/vnd.ms-excel",
+ "application/x-json",
+ "application/x-yaml",
+ "application/yaml",
+ "text/csv",
+ "text/json",
+ "text/markdown",
+ "text/plain",
+ "text/x-csv",
+ "text/x-markdown",
+ "text/x-yaml",
+ "text/yaml",
+ }
+)
+
+
+class FileDTO(BaseModel):
+ file_id: str = Field(description="The managed file ID.")
+ file_name: str = Field(description="The original file name.")
+ content_type: str = Field(description="The uploaded file content type.")
+ size_bytes: int = Field(description="The size of the file in bytes.", ge=0)
+ created_at: datetime = Field(description="When the file was uploaded.")
+
+
+class FileStorageException(Exception):
+ """Base exception for managed file storage errors."""
+
+
+class FileNotFoundException(FileStorageException):
+ """Raised when a managed file cannot be found."""
+
+
+class UnsupportedFileTypeException(FileStorageException):
+ """Raised when a managed file upload is not allowed."""
+
+
+class FileTooLargeException(FileStorageException):
+ """Raised when a managed file upload exceeds the size limit."""
+
+
+class FileQuotaExceededException(FileStorageException):
+ """Raised when a managed file upload would exceed the total storage limit."""
+
+
+class FileAccessDeniedException(FileStorageException):
+ """Raised when a user cannot access a managed file."""
+
+
+class FileMetadataException(FileStorageException):
+ """Raised when managed file metadata cannot be read or validated."""
diff --git a/invokeai/app/services/files/files_disk.py b/invokeai/app/services/files/files_disk.py
new file mode 100644
index 0000000000..98659d3106
--- /dev/null
+++ b/invokeai/app/services/files/files_disk.py
@@ -0,0 +1,232 @@
+import json
+import threading
+from datetime import datetime, timezone
+from json import JSONDecodeError
+from pathlib import Path
+from typing import IO, Any, BinaryIO
+
+from pydantic import Field, TypeAdapter, ValidationError
+
+from invokeai.app.services.files.files_base import FileServiceBase
+from invokeai.app.services.files.files_common import (
+ DEFAULT_FILE_LIBRARY_MAX_BYTES,
+ DEFAULT_FILE_UPLOAD_MAX_BYTES,
+ SUPPORTED_FILE_EXTENSIONS,
+ SUPPORTED_FILE_MIME_TYPES,
+ FileAccessDeniedException,
+ FileDTO,
+ FileMetadataException,
+ FileNotFoundException,
+ FileQuotaExceededException,
+ FileTooLargeException,
+ UnsupportedFileTypeException,
+)
+from invokeai.app.util.misc import uuid_string
+from invokeai.backend.util.logging import InvokeAILogger
+
+
+class FileRecord(FileDTO):
+ stored_file_name: str = Field(description="The file name used on disk.")
+ user_id: str | None = Field(default=None, description="The user who uploaded this file.")
+
+
+FileRecordAdapter = TypeAdapter(FileRecord)
+
+
+class DiskFileService(FileServiceBase):
+ def __init__(
+ self,
+ storage_path: Path,
+ max_file_size: int = DEFAULT_FILE_UPLOAD_MAX_BYTES,
+ max_storage_size: int = DEFAULT_FILE_LIBRARY_MAX_BYTES,
+ ) -> None:
+ self._storage_path = storage_path
+ self._max_file_size = max_file_size
+ self._max_storage_size = max_storage_size
+ self._logger = InvokeAILogger.get_logger(name=self.__class__.__name__)
+ self._validate_storage_folder()
+ self._storage_lock = threading.Lock()
+ # Recount on every construction so restarts (and files removed outside the service) are reflected.
+ self._used_bytes = self._calculate_used_bytes()
+
+ def save(
+ self,
+ file_name: str,
+ content_type: str | None,
+ file: BinaryIO,
+ user_id: str | None,
+ ) -> FileDTO:
+ safe_file_name = self._sanitize_file_name(file_name)
+ extension = self._get_supported_extension(safe_file_name)
+ normalized_content_type = self._normalize_content_type(content_type)
+ self._validate_content_type(normalized_content_type)
+
+ file_id = uuid_string()
+ stored_file_name = f"{file_id}{extension}"
+ file_path = self._get_file_path(stored_file_name)
+ metadata_path = self._get_metadata_path(file_id)
+ metadata_tmp_path = metadata_path.with_name(f"{metadata_path.name}.tmp")
+
+ size_bytes = 0
+ reserved_bytes = 0
+ try:
+ with open(file_path, "wb") as out_file:
+ while True:
+ chunk = file.read(1024 * 1024)
+ if not chunk:
+ break
+ size_bytes += len(chunk)
+ if size_bytes > self._max_file_size:
+ raise FileTooLargeException(f"File exceeds the maximum size of {self._max_file_size} bytes.")
+ self._reserve_storage(len(chunk))
+ reserved_bytes += len(chunk)
+ out_file.write(chunk)
+
+ record = FileRecord(
+ file_id=file_id,
+ file_name=safe_file_name,
+ stored_file_name=stored_file_name,
+ content_type=normalized_content_type,
+ size_bytes=size_bytes,
+ created_at=datetime.now(timezone.utc),
+ user_id=user_id,
+ )
+ # Write the metadata beside its final path and swap it in, so a crash mid-write cannot leave an
+ # unreadable record for a file that was saved completely.
+ metadata_tmp_path.write_text(record.model_dump_json(), encoding="utf-8")
+ metadata_tmp_path.replace(metadata_path)
+ return self._record_to_dto(record)
+ except Exception:
+ file_path.unlink(missing_ok=True)
+ metadata_path.unlink(missing_ok=True)
+ metadata_tmp_path.unlink(missing_ok=True)
+ self._release_storage(reserved_bytes)
+ raise
+
+ def get_dto(self, file_id: str, user_id: str | None = None) -> FileDTO:
+ record = self._get_record(file_id, user_id=user_id)
+ self._get_existing_file_path(record)
+ return self._record_to_dto(record)
+
+ def get_path(self, file_id: str, user_id: str | None = None) -> Path:
+ record = self._get_record(file_id, user_id=user_id)
+ return self._get_existing_file_path(record)
+
+ def open(self, file_id: str, mode: str = "rb", user_id: str | None = None) -> IO[Any]:
+ if mode not in {"rb", "r"}:
+ raise ValueError("Managed files may only be opened for reading.")
+ path = self.get_path(file_id, user_id=user_id)
+ if mode == "r":
+ return open(path, mode, encoding="utf-8")
+ return open(path, mode)
+
+ def delete(self, file_id: str, user_id: str | None = None) -> None:
+ record = self._get_record(file_id, user_id=user_id)
+ file_path = self._get_file_path(record.stored_file_name)
+ try:
+ size_bytes = file_path.stat().st_size
+ except FileNotFoundError:
+ size_bytes = 0
+ file_path.unlink(missing_ok=True)
+ self._get_metadata_path(file_id).unlink(missing_ok=True)
+ self._release_storage(size_bytes)
+
+ def _get_record(self, file_id: str, user_id: str | None = None) -> FileRecord:
+ metadata_path = self._get_metadata_path(file_id)
+ try:
+ data = json.loads(metadata_path.read_text(encoding="utf-8"))
+ record = FileRecordAdapter.validate_python(data)
+ except FileNotFoundError as e:
+ raise FileNotFoundException(f"File not found: {file_id}") from e
+ except (JSONDecodeError, ValidationError) as e:
+ self._logger.warning(f"Invalid managed file metadata for file: {file_id}")
+ raise FileMetadataException(f"Invalid file metadata: {file_id}") from e
+ except OSError as e:
+ self._logger.warning(f"Unable to read managed file metadata for file: {file_id}: {e}")
+ raise FileMetadataException(f"Unable to read file metadata: {file_id}") from e
+
+ if record.user_id != user_id:
+ raise FileAccessDeniedException(f"Not authorized to access file: {file_id}")
+ return record
+
+ def _get_existing_file_path(self, record: FileRecord) -> Path:
+ path = self._get_file_path(record.stored_file_name)
+ if not path.exists():
+ raise FileNotFoundException(f"File not found: {record.file_id}")
+ return path
+
+ def _get_file_path(self, stored_file_name: str) -> Path:
+ path = self._storage_path / stored_file_name
+ resolved_base = self._storage_path.resolve()
+ resolved_path = path.resolve()
+ if not resolved_path.is_relative_to(resolved_base):
+ raise ValueError("File path outside storage folder, potential directory traversal detected.")
+ return resolved_path
+
+ def _get_metadata_path(self, file_id: str) -> Path:
+ if Path(file_id).name != file_id:
+ raise ValueError("Invalid file ID, potential directory traversal detected.")
+ return self._get_file_path(f"{file_id}.meta.json")
+
+ def _validate_storage_folder(self) -> None:
+ self._storage_path.mkdir(parents=True, exist_ok=True)
+
+ def _calculate_used_bytes(self) -> int:
+ used_bytes = 0
+ for entry in self._storage_path.iterdir():
+ # Metadata is part of the record, not the stored document; counting only data files keeps the limit
+ # meaningful and matches what `save` reserves.
+ if entry.is_file() and not entry.name.endswith((".meta.json", ".tmp")):
+ try:
+ used_bytes += entry.stat().st_size
+ except FileNotFoundError:
+ continue
+ return used_bytes
+
+ def _reserve_storage(self, size_bytes: int) -> None:
+ with self._storage_lock:
+ if self._used_bytes + size_bytes > self._max_storage_size:
+ raise FileQuotaExceededException(
+ f"Managed file storage is full (limit {self._max_storage_size} bytes)."
+ )
+ self._used_bytes += size_bytes
+
+ def _release_storage(self, size_bytes: int) -> None:
+ if size_bytes == 0:
+ return
+ with self._storage_lock:
+ self._used_bytes = max(0, self._used_bytes - size_bytes)
+
+ @staticmethod
+ def _record_to_dto(record: FileRecord) -> FileDTO:
+ return FileDTO(**record.model_dump(exclude={"stored_file_name", "user_id"}))
+
+ @staticmethod
+ def _sanitize_file_name(file_name: str) -> str:
+ safe_file_name = Path(file_name.replace("\x00", "")).name.strip()
+ if not safe_file_name:
+ raise UnsupportedFileTypeException("Missing file name.")
+ return safe_file_name
+
+ @staticmethod
+ def _get_supported_extension(file_name: str) -> str:
+ extension = Path(file_name).suffix.lower()
+ if extension not in SUPPORTED_FILE_EXTENSIONS:
+ raise UnsupportedFileTypeException(f"Unsupported file extension: {extension}")
+ return extension
+
+ @staticmethod
+ def _normalize_content_type(content_type: str | None) -> str:
+ if not content_type:
+ return "application/octet-stream"
+ return content_type.split(";", 1)[0].strip().lower()
+
+ @staticmethod
+ def _validate_content_type(content_type: str) -> None:
+ # Some browsers or reverse proxies send application/octet-stream for document files, and some report
+ # vendor aliases such as application/vnd.ms-excel for CSV. The extension allowlist remains the primary
+ # check; the MIME allowlist only rejects clearly unrelated types.
+ if content_type in {"application/octet-stream", ""}:
+ return
+ if content_type not in SUPPORTED_FILE_MIME_TYPES:
+ raise UnsupportedFileTypeException(f"Unsupported content type: {content_type}")
diff --git a/invokeai/app/services/invocation_services.py b/invokeai/app/services/invocation_services.py
index 618de62722..45e5de21f7 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 DownloadQueueServiceBase
from invokeai.app.services.events.events_base import EventServiceBase
from invokeai.app.services.external_generation.external_generation_base import ExternalGenerationServiceBase
+ from invokeai.app.services.files.files_base import FileServiceBase
from invokeai.app.services.fonts.fonts_default import FontService
from invokeai.app.services.gallery.gallery_base import GalleryServiceABC
from invokeai.app.services.gallery_maintenance.gallery_maintenance_default import GalleryMaintenanceService
@@ -117,6 +118,7 @@ class InvocationServices:
image_index: "ImageIndexServiceBase",
intermediates: "IntermediatesServiceBase",
image_moves: "ImageMoveService | None" = None,
+ files: "FileServiceBase | None" = None,
progress_previews: "ProgressPreviewsBase | None" = None,
fonts: "FontService | None" = None,
gallery_maintenance: "GalleryMaintenanceService | None" = None,
@@ -164,6 +166,7 @@ class InvocationServices:
self.client_state_persistence = client_state_persistence
self.project_records = project_records
self.users = users
+ self.files = files
self.videos = videos
self.video_files = video_files
self.video_records = video_records
diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.py
index 7543ccaaf3..a941923930 100644
--- a/invokeai/app/services/shared/invocation_context.py
+++ b/invokeai/app/services/shared/invocation_context.py
@@ -2,7 +2,7 @@ from contextlib import ExitStack
from copy import deepcopy
from dataclasses import dataclass, field
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Callable, Optional, Union
+from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union
from dynamicprompts.wildcards import WildcardManager
from PIL.Image import Image
@@ -22,6 +22,7 @@ from invokeai.app.services.board_access.board_access_common import (
from invokeai.app.services.board_records.board_records_common import BoardRecordNotFoundException, BoardRecordOrderBy
from invokeai.app.services.boards.boards_common import BoardDTO
from invokeai.app.services.config.config_default import InvokeAIAppConfig
+from invokeai.app.services.files.files_common import FileDTO
from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
from invokeai.app.services.images.images_common import ImageDTO
from invokeai.app.services.invocation_services import InvocationServices
@@ -44,6 +45,7 @@ from invokeai.backend.util.devices import TorchDevice
if TYPE_CHECKING:
from invokeai.app.invocations.baseinvocation import BaseInvocation
from invokeai.app.invocations.model import ModelIdentifierField
+ from invokeai.app.services.files.files_base import FileServiceBase
from invokeai.app.services.session_queue.session_queue_common import SessionQueueItem
from invokeai.app.services.shared.execution_engine.child import ChildExecutionCapability
@@ -254,6 +256,47 @@ class LoggerInterface(InvocationContextInterface):
self._services.logger.error(message)
+class FilesInterface(InvocationContextInterface):
+ def get_dto(self, file_id: str) -> FileDTO:
+ """Gets metadata for a managed file.
+
+ Args:
+ file_id: The managed file ID.
+
+ Returns:
+ The file DTO.
+ """
+ return self._get_files_service().get_dto(file_id, user_id=self._data.queue_item.user_id)
+
+ def get_path(self, file_id: str) -> Path:
+ """Gets the server-side path to a managed file.
+
+ Args:
+ file_id: The managed file ID.
+
+ Returns:
+ The path to the managed file on the InvokeAI server.
+ """
+ return self._get_files_service().get_path(file_id, user_id=self._data.queue_item.user_id)
+
+ def open(self, file_id: str, mode: str = "rb") -> IO[Any]:
+ """Opens a managed file for reading.
+
+ Args:
+ file_id: The managed file ID.
+ mode: The read mode to use. Supported values are "rb" and "r".
+
+ Returns:
+ A readable file object.
+ """
+ return self._get_files_service().open(file_id, mode=mode, user_id=self._data.queue_item.user_id)
+
+ def _get_files_service(self) -> "FileServiceBase":
+ if self._services.files is None:
+ raise RuntimeError("The managed files service is not available.")
+ return self._services.files
+
+
class ImagesInterface(InvocationContextInterface):
def __init__(self, services: InvocationServices, data: InvocationContextData, util: "UtilInterface") -> None:
super().__init__(services, data)
@@ -1071,6 +1114,7 @@ class InvocationContext:
config (ConfigInterface): The app config.
util (UtilInterface): Utility methods, including a method to check if an invocation was canceled and step callbacks.
boards (BoardsInterface): Methods to interact with boards.
+ files (FilesInterface): Methods to read managed files uploaded for node inputs.
wildcards (WildcardsInterface): Access to the queueing user's wildcards.
"""
@@ -1085,6 +1129,7 @@ class InvocationContext:
config: ConfigInterface,
util: UtilInterface,
boards: BoardsInterface,
+ files: FilesInterface,
wildcards: WildcardsInterface,
data: InvocationContextData,
services: InvocationServices,
@@ -1108,6 +1153,8 @@ class InvocationContext:
"""Utility methods, including a method to check if an invocation was canceled and step callbacks."""
self.boards = boards
"""Methods to interact with boards."""
+ self.files = files
+ """Methods to read managed files uploaded for node inputs."""
self.wildcards = wildcards
"""Access to the queueing user's wildcards."""
self._data = data
@@ -1151,6 +1198,7 @@ def build_invocation_context(
images = ImagesInterface(services=services, data=data, util=util)
videos = VideosInterface(services=services, data=data, util=util)
boards = BoardsInterface(services=services, data=data)
+ files = FilesInterface(services=services, data=data)
wildcards = WildcardsInterface(services=services, data=data)
if execution_effects is None:
@@ -1168,6 +1216,7 @@ def build_invocation_context(
conditioning=conditioning,
services=services,
boards=boards,
+ files=files,
wildcards=wildcards,
execution_effects=execution_effects,
)
diff --git a/invokeai/app/util/custom_openapi.py b/invokeai/app/util/custom_openapi.py
index 2e365020ee..6dcf193a75 100644
--- a/invokeai/app/util/custom_openapi.py
+++ b/invokeai/app/util/custom_openapi.py
@@ -8,7 +8,7 @@ from invokeai.app.invocations.baseinvocation import (
InvocationRegistry,
UIConfigBase,
)
-from invokeai.app.invocations.fields import InputFieldJSONSchemaExtra, OutputFieldJSONSchemaExtra
+from invokeai.app.invocations.fields import FileField, InputFieldJSONSchemaExtra, OutputFieldJSONSchemaExtra
from invokeai.app.invocations.model import ModelIdentifierField
from invokeai.app.services.events.events_common import EventBase
from invokeai.app.services.session_processor.session_processor_common import ProgressImage
@@ -179,6 +179,7 @@ def get_openapi_func(
OutputFieldJSONSchemaExtra,
ModelIdentifierField,
ProgressImage,
+ FileField,
]
additional_schemas = models_json_schema(
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index 92cf3109a9..65b12ba19a 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -6725,6 +6725,144 @@
}
}
},
+ "/api/v1/files/upload": {
+ "post": {
+ "tags": ["files"],
+ "summary": "Upload File",
+ "description": "Uploads a managed file for node inputs.",
+ "operationId": "upload_file",
+ "requestBody": {
+ "content": {
+ "multipart/form-data": {
+ "schema": {
+ "$ref": "#/components/schemas/Body_upload_file"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "description": "The file was uploaded successfully",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/FileDTO"
+ }
+ }
+ }
+ },
+ "413": {
+ "description": "The file is too large or managed file storage is full"
+ },
+ "415": {
+ "description": "The file type is not supported"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
+ "/api/v1/files/i/{file_id}": {
+ "get": {
+ "tags": ["files"],
+ "summary": "Get File Dto",
+ "description": "Gets metadata for a managed file.",
+ "operationId": "get_file_dto",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "file_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "The managed file ID.",
+ "title": "File Id"
+ },
+ "description": "The managed file ID."
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/FileDTO"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["files"],
+ "summary": "Delete File",
+ "description": "Deletes a managed file.",
+ "operationId": "delete_file",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "file_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "The managed file ID.",
+ "title": "File Id"
+ },
+ "description": "The managed file ID."
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "Successful Response"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/v1/image_moves/start": {
"post": {
"tags": ["image_moves"],
@@ -24017,6 +24155,18 @@
"required": ["is_public"],
"title": "Body_update_workflow_is_public"
},
+ "Body_upload_file": {
+ "properties": {
+ "file": {
+ "type": "string",
+ "contentMediaType": "application/octet-stream",
+ "title": "File"
+ }
+ },
+ "type": "object",
+ "required": ["file"],
+ "title": "Body_upload_file"
+ },
"Body_upload_font": {
"properties": {
"file": {
@@ -38159,6 +38309,53 @@
"title": "FieldKind",
"type": "string"
},
+ "FileDTO": {
+ "properties": {
+ "file_id": {
+ "type": "string",
+ "title": "File Id",
+ "description": "The managed file ID."
+ },
+ "file_name": {
+ "type": "string",
+ "title": "File Name",
+ "description": "The original file name."
+ },
+ "content_type": {
+ "type": "string",
+ "title": "Content Type",
+ "description": "The uploaded file content type."
+ },
+ "size_bytes": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Size Bytes",
+ "description": "The size of the file in bytes."
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Created At",
+ "description": "When the file was uploaded."
+ }
+ },
+ "type": "object",
+ "required": ["file_id", "file_name", "content_type", "size_bytes", "created_at"],
+ "title": "FileDTO"
+ },
+ "FileField": {
+ "description": "A managed file primitive field",
+ "properties": {
+ "file_id": {
+ "description": "The id of the managed file",
+ "title": "File Id",
+ "type": "string"
+ }
+ },
+ "required": ["file_id"],
+ "title": "FileField",
+ "type": "object"
+ },
"FloatBatchInvocation": {
"category": "batch",
"class": "invocation",
@@ -65259,6 +65456,22 @@
"description": "Maximum total size of uploaded custom fonts in bytes per account or shared library.",
"default": 1073741824
},
+ "max_file_upload_size_bytes": {
+ "type": "integer",
+ "maximum": 1073741824.0,
+ "exclusiveMinimum": 0.0,
+ "title": "Max File Upload Size Bytes",
+ "description": "Maximum size in bytes of one managed file upload.",
+ "default": 52428800
+ },
+ "max_file_library_bytes": {
+ "type": "integer",
+ "maximum": 17179869184.0,
+ "exclusiveMinimum": 0.0,
+ "title": "Max File Library Bytes",
+ "description": "Maximum total size in bytes of all managed files.",
+ "default": 5368709120
+ },
"image_subfolder_strategy": {
"type": "string",
"enum": ["flat", "date", "type", "hash"],
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index 3885dcd26b..ef9c30f2b8 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -1380,6 +1380,50 @@ export type paths = {
patch?: never;
trace?: never;
};
+ "/api/v1/files/upload": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Upload File
+ * @description Uploads a managed file for node inputs.
+ */
+ post: operations["upload_file"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/files/i/{file_id}": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Get File Dto
+ * @description Gets metadata for a managed file.
+ */
+ get: operations["get_file_dto"];
+ put?: never;
+ post?: never;
+ /**
+ * Delete File
+ * @description Deletes a managed file.
+ */
+ delete: operations["delete_file"];
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v1/image_moves/start": {
parameters: {
query?: never;
@@ -7073,6 +7117,11 @@ export type components = {
*/
is_public: boolean;
};
+ /** Body_upload_file */
+ Body_upload_file: {
+ /** File */
+ file: Blob;
+ };
/** Body_upload_font */
Body_upload_font: {
/**
@@ -14446,6 +14495,46 @@ export type components = {
* @enum {string}
*/
FieldKind: "input" | "output" | "internal" | "node_attribute";
+ /** FileDTO */
+ FileDTO: {
+ /**
+ * File Id
+ * @description The managed file ID.
+ */
+ file_id: string;
+ /**
+ * File Name
+ * @description The original file name.
+ */
+ file_name: string;
+ /**
+ * Content Type
+ * @description The uploaded file content type.
+ */
+ content_type: string;
+ /**
+ * Size Bytes
+ * @description The size of the file in bytes.
+ */
+ size_bytes: number;
+ /**
+ * Created At
+ * Format: date-time
+ * @description When the file was uploaded.
+ */
+ created_at: string;
+ };
+ /**
+ * FileField
+ * @description A managed file primitive field
+ */
+ FileField: {
+ /**
+ * File Id
+ * @description The id of the managed file
+ */
+ file_id: string;
+ };
/**
* Float Batch
* @description Create a batched generation, where the workflow is executed once for each float in the batch.
@@ -25148,6 +25237,18 @@ export type components = {
* @default 1073741824
*/
max_font_library_bytes?: number;
+ /**
+ * Max File Upload Size Bytes
+ * @description Maximum size in bytes of one managed file upload.
+ * @default 52428800
+ */
+ max_file_upload_size_bytes?: number;
+ /**
+ * Max File Library Bytes
+ * @description Maximum total size in bytes of all managed files.
+ * @default 5368709120
+ */
+ max_file_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.
@@ -62283,6 +62384,115 @@ export interface operations {
};
};
};
+ upload_file: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "multipart/form-data": components["schemas"]["Body_upload_file"];
+ };
+ };
+ responses: {
+ /** @description The file was uploaded successfully */
+ 201: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["FileDTO"];
+ };
+ };
+ /** @description The file is too large or managed file storage is full */
+ 413: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description The file type is not supported */
+ 415: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
+ get_file_dto: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ /** @description The managed file ID. */
+ file_id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["FileDTO"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
+ delete_file: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ /** @description The managed file ID. */
+ file_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"];
+ };
+ };
+ };
+ };
start_image_move: {
parameters: {
query?: never;
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 3b996da554..f1484cae97 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1981,6 +1981,12 @@
"fieldInfo": "Field: {{name}} · Type: {{type}}",
"fieldName": "Field: {{name}}",
"fieldType": "Type: {{type}}",
+ "fileUnavailable": "This file is unavailable. It may have been deleted or access was revoked.",
+ "fileUpload": "Upload file",
+ "fileUploadDropHint": "Drop a file here, or choose one.",
+ "fileUploadFailed": "File upload failed",
+ "fileUploadRejected": "File type not supported",
+ "fileUploadRejectedDescription": "Choose a PDF, Markdown, text, CSV, JSON, or YAML file.",
"required": "Required",
"optional": "Optional",
"inputModes": {
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
index db8f90f146..af180e5b75 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
@@ -188,6 +188,19 @@ describe('workflow field validation', () => {
expect(isWorkflowFieldValueValid(input({ type: single('VideoField') }), {})).toBe(false);
});
+ it('treats a managed file as a direct input addressed by its file id', () => {
+ const file = input({ type: single('FileField') });
+
+ expect(isDirectInputField(file)).toBe(true);
+ expect(isWorkflowFieldValueValid(file, { file_id: 'file-1' })).toBe(true);
+ expect(isWorkflowFieldValueValid(file, {})).toBe(false);
+ expect(isWorkflowFieldValueValid(file, { file_id: '' })).toBe(false);
+ expect(getWorkflowFieldInvalidReason({ isConnected: false, template: file, value: undefined })).toBe(
+ 'Required value.'
+ );
+ expect(getWorkflowFieldInvalidReason({ isConnected: false, template: file, value: {} })).toBe('Invalid value.');
+ });
+
it('validates image collections as lists of image refs and keeps video collections on the non-null check', () => {
const videos = input({ type: { batch: false, cardinality: 'COLLECTION', name: 'VideoField' } });
const images = input({ type: { batch: false, cardinality: 'COLLECTION', name: 'ImageField' } });
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
index aefb9dcc67..d4ebd54c9a 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
@@ -22,6 +22,7 @@ const STATEFUL_FIELD_TYPE_NAMES = new Set([
'BooleanField',
'ColorField',
'EnumField',
+ 'FileField',
'FloatField',
'FloatGeneratorField',
'ImageField',
@@ -443,6 +444,8 @@ export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: u
value === 'none' ||
hasNonEmptyStringProp(value, 'board_id')
);
+ case 'FileField':
+ return hasNonEmptyStringProp(value, 'file_id');
case 'ImageField':
return hasNonEmptyStringProp(value, 'image_name');
case 'VideoField':
@@ -528,6 +531,7 @@ const FIELD_TYPE_COLORS: Record<string, string> = {
ControlField: '#5eead4',
DenoiseMaskField: '#93c5fd',
EnumField: '#60a5fa',
+ FileField: '#22d3ee',
FloatField: '#fb923c',
ImageField: '#c4b5fd',
IntegerField: '#f87171',
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/outputFields.ts b/invokeai/frontend/webv2/src/features/workflow/core/outputFields.ts
index 49572b39e3..2f53048ce8 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/outputFields.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/outputFields.ts
@@ -42,7 +42,16 @@ export const getOutputFieldRows = (fieldNames: OutputFieldNamesByScope): OutputF
};
const OUTPUT_VALUE_MAX_LENGTH = 40;
-const NAMED_OBJECT_KEYS = ['image_name', 'video_name', 'latents_name', 'tensor_name', 'name', 'key', 'board_id'];
+const NAMED_OBJECT_KEYS = [
+ 'image_name',
+ 'video_name',
+ 'file_id',
+ 'latents_name',
+ 'tensor_name',
+ 'name',
+ 'key',
+ 'board_id',
+];
/** Compact label for one output field's runtime value; `null` when the result carries no such field. */
export const formatOutputFieldValue = (result: unknown, fieldName: string): { full: string; short: string } | null => {
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/managedFiles.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/managedFiles.test.ts
new file mode 100644
index 0000000000..c654d3574e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/data/managedFiles.test.ts
@@ -0,0 +1,92 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ deleteManagedFile,
+ getManagedFile,
+ MANAGED_FILE_ACCEPT,
+ MANAGED_FILE_ACCEPTED_EXTENSIONS,
+ managedFileQueryOptions,
+ uploadManagedFile,
+} from './managedFiles';
+
+const httpMock = vi.hoisted(() => ({ apiFetch: vi.fn(), apiFetchJson: vi.fn() }));
+
+vi.mock('@platform/transport/http', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ apiFetch: httpMock.apiFetch,
+ apiFetchJson: httpMock.apiFetchJson,
+}));
+
+const FILE_DTO = {
+ content_type: 'text/markdown',
+ created_at: '2026-06-25T04:53:34.000Z',
+ file_id: 'file-1',
+ file_name: 'notes.md',
+ size_bytes: 2048,
+};
+
+const FILE = {
+ contentType: 'text/markdown',
+ createdAt: '2026-06-25T04:53:34.000Z',
+ id: 'file-1',
+ name: 'notes.md',
+ sizeBytes: 2048,
+};
+
+describe('managed files transport', () => {
+ beforeEach(() => {
+ httpMock.apiFetch.mockReset();
+ httpMock.apiFetchJson.mockReset();
+ });
+
+ it('maps the wire DTO into the domain shape and resolves the encoded file URL', async () => {
+ httpMock.apiFetchJson.mockResolvedValue(FILE_DTO);
+ const signal = new AbortController().signal;
+
+ await expect(getManagedFile('file/1', signal)).resolves.toEqual(FILE);
+ expect(httpMock.apiFetchJson).toHaveBeenCalledWith('/api/v1/files/i/file%2F1', { signal });
+ });
+
+ it('uploads through the multipart "file" field and maps the created file', async () => {
+ httpMock.apiFetchJson.mockResolvedValue(FILE_DTO);
+ const file = new File(['# Notes'], 'notes.md', { type: 'text/markdown' });
+ const signal = new AbortController().signal;
+
+ await expect(uploadManagedFile(file, signal)).resolves.toEqual(FILE);
+ const [path, init] = httpMock.apiFetchJson.mock.calls[0]!;
+
+ expect(path).toBe('/api/v1/files/upload');
+ expect(init).toEqual({ body: expect.any(FormData), method: 'POST', signal });
+ expect((init.body as FormData).get('file')).toBe(file);
+ });
+
+ it('deletes by id and accepts the 204 response', async () => {
+ httpMock.apiFetch.mockResolvedValue(new Response(null, { status: 204 }));
+ const signal = new AbortController().signal;
+
+ await expect(deleteManagedFile('file/1', signal)).resolves.toBeUndefined();
+ expect(httpMock.apiFetch).toHaveBeenCalledWith('/api/v1/files/i/file%2F1', { method: 'DELETE', signal });
+ });
+
+ it('offers the server-supported extensions and leaves an absent id unfetched', () => {
+ expect(MANAGED_FILE_ACCEPTED_EXTENSIONS).toEqual([
+ '.csv',
+ '.json',
+ '.md',
+ '.markdown',
+ '.pdf',
+ '.txt',
+ '.yaml',
+ '.yml',
+ ]);
+ expect(MANAGED_FILE_ACCEPT).toBe('.csv,.json,.md,.markdown,.pdf,.txt,.yaml,.yml');
+ expect(managedFileQueryOptions('').enabled).toBe(false);
+
+ const options = managedFileQueryOptions('file-1');
+
+ expect(options.enabled).toBe(true);
+ expect(options.queryKey).toEqual(['workflow', 'managed-file', 'file-1']);
+ expect(options.retry).toBe(false);
+ expect(options.staleTime).toBeGreaterThanOrEqual(60_000);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/managedFiles.ts b/invokeai/frontend/webv2/src/features/workflow/data/managedFiles.ts
new file mode 100644
index 0000000000..c652f68520
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/data/managedFiles.ts
@@ -0,0 +1,61 @@
+import type { components } from '@api/schema';
+
+import { apiFetch, apiFetchJson } from '@platform/transport/http';
+
+type FileDTO = components['schemas']['FileDTO'];
+
+/** A managed file as the workflow UI reads it; wire names stay in this module. */
+export interface ManagedFile {
+ id: string;
+ name: string;
+ contentType: string;
+ sizeBytes: number;
+ createdAt: string;
+}
+
+export const MANAGED_FILE_ACCEPTED_EXTENSIONS = ['.csv', '.json', '.md', '.markdown', '.pdf', '.txt', '.yaml', '.yml'];
+
+/** The hidden input's `accept` value; the server remains the authority on what it stores. */
+export const MANAGED_FILE_ACCEPT = MANAGED_FILE_ACCEPTED_EXTENSIONS.join(',');
+
+const mapManagedFile = (file: FileDTO): ManagedFile => ({
+ contentType: file.content_type,
+ createdAt: file.created_at,
+ id: file.file_id,
+ name: file.file_name,
+ sizeBytes: file.size_bytes,
+});
+
+export const managedFileQueryKey = (fileId: string) => ['workflow', 'managed-file', fileId] as const;
+
+export const getManagedFile = async (fileId: string, signal?: AbortSignal): Promise<ManagedFile> => {
+ const file = await apiFetchJson<FileDTO>(`/api/v1/files/i/${encodeURIComponent(fileId)}`, { signal });
+
+ return mapManagedFile(file);
+};
+
+const MANAGED_FILE_STALE_TIME_MS = 5 * 60 * 1000;
+
+/** Metadata for one uploaded file; an empty id leaves the query disabled. */
+export const managedFileQueryOptions = (fileId: string) => ({
+ enabled: fileId !== '',
+ queryFn: ({ signal }: { signal: AbortSignal }): Promise<ManagedFile> => getManagedFile(fileId, signal),
+ queryKey: managedFileQueryKey(fileId),
+ retry: false,
+ staleTime: MANAGED_FILE_STALE_TIME_MS,
+});
+
+export const uploadManagedFile = async (file: File, signal?: AbortSignal): Promise<ManagedFile> => {
+ const body = new FormData();
+
+ body.append('file', file);
+
+ const uploaded = await apiFetchJson<FileDTO>('/api/v1/files/upload', { body, method: 'POST', signal });
+
+ return mapManagedFile(uploaded);
+};
+
+/** Deleting a file is a server-side action; callers own when a reference no longer needs it. */
+export const deleteManagedFile = async (fileId: string, signal?: AbortSignal): Promise<void> => {
+ await apiFetch(`/api/v1/files/i/${encodeURIComponent(fileId)}`, { method: 'DELETE', signal });
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/FileFieldInput.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/FileFieldInput.browser.test.tsx
new file mode 100644
index 0000000000..f532e10db8
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/FileFieldInput.browser.test.tsx
@@ -0,0 +1,289 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type { FieldInputTemplate } from '@features/workflow/contracts';
+import type { WorkflowFieldInputProps } from '@features/workflow/ui/fields/WorkflowFieldInput';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { MANAGED_FILE_ACCEPT } from '@features/workflow/data/managedFiles';
+import { formatBytes } from '@platform/i18n/languages';
+import { ApiError } from '@platform/transport/http';
+import { toaster } from '@platform/ui/toaster';
+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 { WorkflowFieldInput } from './WorkflowFieldInput';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const httpMock = vi.hoisted(() => ({ apiFetch: vi.fn(), apiFetchJson: vi.fn() }));
+
+vi.mock('@platform/transport/http', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ apiFetch: httpMock.apiFetch,
+ apiFetchJson: httpMock.apiFetchJson,
+}));
+
+type DocumentState = { edges: unknown[]; id: string; nodes: { id: string }[] };
+
+const projectState = vi.hoisted(() => ({
+ projectGraph: { edges: [], id: 'graph-1', nodes: [{ id: 'node-1' }] } as DocumentState,
+ workflows: [] as { document: DocumentState }[],
+}));
+
+vi.mock('@features/workflow/ui/WorkflowUiContext', () => ({
+ useWorkflowProjectSelector: (selector: (project: typeof projectState) => unknown) => selector(projectState),
+ useWorkflowUi: () => ({ project: { getSnapshot: () => projectState } }),
+}));
+
+const FILE_TEMPLATE = {
+ input: 'direct',
+ name: 'file',
+ title: 'File',
+ type: { batch: false, cardinality: 'SINGLE', name: 'FileField' },
+} as unknown as FieldInputTemplate;
+
+const FILE_DTO = {
+ content_type: 'text/markdown',
+ created_at: '2026-06-25T04:53:34.000Z',
+ file_id: 'file-1',
+ file_name: 'notes.md',
+ size_bytes: 2048,
+};
+
+const REPLACEMENT_DTO = {
+ ...FILE_DTO,
+ file_id: 'file-2',
+ file_name: 'prompt.txt',
+ size_bytes: 512,
+};
+
+let host: HTMLDivElement;
+let root: Root;
+const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ httpMock.apiFetch.mockReset().mockResolvedValue(new Response(null, { status: 204 }));
+ httpMock.apiFetchJson.mockReset();
+ projectState.projectGraph = { edges: [], id: 'graph-1', nodes: [{ id: 'node-1' }] };
+ projectState.workflows = [];
+ queryClient.clear();
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await act(() => root.unmount());
+ host.remove();
+});
+
+const renderField = async (
+ value: unknown,
+ onChange: (value: unknown) => void,
+ props: Pick<WorkflowFieldInputProps, 'nodeId' | 'workflowId'> = { nodeId: 'node-1' }
+) => {
+ await act(() => {
+ root.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <WorkflowFieldInput template={FILE_TEMPLATE} value={value} onChange={onChange} {...props} />
+ </QueryClientProvider>
+ </ChakraProvider>
+ );
+ });
+
+ // The field widget is lazily imported, so wait for its fallback to be replaced.
+ await vi.waitFor(() => expect(host.querySelector('input[type="file"]')).not.toBeNull());
+};
+
+const findButton = (label: string): HTMLButtonElement => {
+ const button = Array.from(host.querySelectorAll('button')).find((el) => el.textContent?.includes(label));
+
+ if (!button) {
+ throw new Error(`Button "${label}" not found`);
+ }
+
+ return button;
+};
+
+const pickFile = async (file: File) => {
+ const fileInput = host.querySelector<HTMLInputElement>('input[type="file"]')!;
+ const transfer = new DataTransfer();
+
+ transfer.items.add(file);
+ fileInput.files = transfer.files;
+ await act(() => fileInput.dispatchEvent(new Event('change', { bubbles: true })));
+};
+
+const dropFile = async (file: File) => {
+ const dropZone = host.querySelector<HTMLElement>('[role="group"]')!;
+ const transfer = new DataTransfer();
+
+ transfer.items.add(file);
+ await act(() =>
+ dropZone.dispatchEvent(new DragEvent('dragenter', { bubbles: true, cancelable: true, dataTransfer: transfer }))
+ );
+ await act(() =>
+ dropZone.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: transfer }))
+ );
+ await act(() =>
+ dropZone.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: transfer }))
+ );
+};
+
+describe('WorkflowFieldInput managed file', () => {
+ it('uploads a picked file and writes only its id into the field', async () => {
+ httpMock.apiFetchJson.mockResolvedValue(FILE_DTO);
+ const onChange = vi.fn();
+
+ await renderField(undefined, onChange);
+ const fileInput = host.querySelector<HTMLInputElement>('input[type="file"]')!;
+
+ expect(fileInput.accept).toBe(MANAGED_FILE_ACCEPT);
+ await pickFile(new File(['# Notes'], 'notes.md', { type: 'text/markdown' }));
+
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalledWith({ file_id: 'file-1' }));
+ const [path, init] = httpMock.apiFetchJson.mock.calls[0]!;
+
+ expect(path).toBe('/api/v1/files/upload');
+ expect(init).toEqual(expect.objectContaining({ method: 'POST' }));
+ expect((init.body as FormData).get('file')).toBeInstanceOf(File);
+ });
+
+ it('uploads a file dropped onto the zone', async () => {
+ httpMock.apiFetchJson.mockResolvedValue(FILE_DTO);
+ const onChange = vi.fn();
+
+ await renderField(undefined, onChange);
+ await dropFile(new File(['# Notes'], 'notes.md', { type: 'text/markdown' }));
+
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalledWith({ file_id: 'file-1' }));
+ expect(httpMock.apiFetchJson.mock.calls[0]?.[0]).toBe('/api/v1/files/upload');
+ });
+
+ it('shows the stored file name and size, and clear removes only the reference', async () => {
+ httpMock.apiFetchJson.mockResolvedValue(FILE_DTO);
+ const onChange = vi.fn();
+
+ await renderField({ file_id: 'file-1' }, onChange);
+
+ await vi.waitFor(() => expect(host.textContent).toContain('notes.md'));
+ expect(host.textContent).toContain(formatBytes(FILE_DTO.size_bytes));
+ expect(httpMock.apiFetchJson).toHaveBeenCalledWith('/api/v1/files/i/file-1', {
+ signal: expect.any(AbortSignal),
+ });
+
+ await act(() => findButton('common.clear').click());
+
+ expect(onChange).toHaveBeenCalledWith(undefined);
+ expect(httpMock.apiFetch).not.toHaveBeenCalled();
+ });
+
+ it('replaces a referenced file without deleting the previous one', async () => {
+ httpMock.apiFetchJson.mockImplementation((path: string) =>
+ Promise.resolve(path === '/api/v1/files/upload' ? REPLACEMENT_DTO : FILE_DTO)
+ );
+ const onChange = vi.fn();
+
+ await renderField({ file_id: 'file-1' }, onChange);
+ await vi.waitFor(() => expect(host.textContent).toContain('notes.md'));
+
+ await pickFile(new File(['hello'], 'prompt.txt', { type: 'text/plain' }));
+
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalledWith({ file_id: 'file-2' }));
+ expect(httpMock.apiFetch).not.toHaveBeenCalled();
+ });
+
+ it('offers clear and retry when the stored file cannot be read, without mutating the field', async () => {
+ httpMock.apiFetchJson
+ .mockRejectedValueOnce(new ApiError(JSON.stringify({ detail: 'File not found' }), 404))
+ .mockResolvedValue(FILE_DTO);
+ const onChange = vi.fn();
+
+ await renderField({ file_id: 'file-1' }, onChange);
+
+ await vi.waitFor(() => expect(host.textContent).toContain('nodes.fileUnavailable'));
+ expect(onChange).not.toHaveBeenCalled();
+ expect(findButton('common.clear')).not.toBeNull();
+ expect(findButton('common.retry')).not.toBeNull();
+
+ await act(() => findButton('common.retry').click());
+ await vi.waitFor(() => expect(host.textContent).toContain('notes.md'));
+
+ await act(() => findButton('common.clear').click());
+ expect(onChange).toHaveBeenCalledWith(undefined);
+ });
+
+ it('rejects a file type the server does not accept before uploading it', async () => {
+ const createToast = vi.spyOn(toaster, 'create').mockImplementation(() => '');
+ const onChange = vi.fn();
+
+ await renderField(undefined, onChange);
+ await pickFile(new File(['binary'], 'archive.zip', { type: 'application/zip' }));
+
+ await vi.waitFor(() =>
+ expect(createToast).toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'nodes.fileUploadRejected', type: 'error' })
+ )
+ );
+ expect(httpMock.apiFetchJson).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
+ createToast.mockRestore();
+ });
+
+ it('shows the server’s own upload refusal message', async () => {
+ const createToast = vi.spyOn(toaster, 'create').mockImplementation(() => '');
+ httpMock.apiFetchJson.mockRejectedValue(
+ new ApiError(JSON.stringify({ detail: 'File type is not supported' }), 415)
+ );
+ const onChange = vi.fn();
+
+ await renderField(undefined, onChange);
+ await pickFile(new File(['# Notes'], 'notes.md', { type: 'text/markdown' }));
+
+ await vi.waitFor(() =>
+ expect(createToast).toHaveBeenCalledWith(
+ expect.objectContaining({ description: 'File type is not supported', title: 'nodes.fileUploadFailed' })
+ )
+ );
+ expect(onChange).not.toHaveBeenCalled();
+ createToast.mockRestore();
+ });
+
+ it('does not write a late upload into a document that was replaced, and removes the orphan', async () => {
+ let resolveUpload: ((dto: typeof FILE_DTO) => void) | null = null;
+
+ httpMock.apiFetchJson.mockImplementation(
+ (path: string) =>
+ new Promise((resolve) => {
+ if (path === '/api/v1/files/upload') {
+ resolveUpload = resolve;
+ return;
+ }
+
+ resolve(FILE_DTO);
+ })
+ );
+ const onChange = vi.fn();
+
+ await renderField(undefined, onChange);
+ await pickFile(new File(['# Notes'], 'notes.md', { type: 'text/markdown' }));
+ await vi.waitFor(() => expect(resolveUpload).not.toBeNull());
+
+ projectState.projectGraph = { edges: [], id: 'graph-2', nodes: [{ id: 'node-1' }] };
+ await act(() => {
+ resolveUpload?.(FILE_DTO);
+ });
+
+ await vi.waitFor(() =>
+ expect(httpMock.apiFetch).toHaveBeenCalledWith(
+ '/api/v1/files/i/file-1',
+ expect.objectContaining({ method: 'DELETE' })
+ )
+ );
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/FileFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/FileFieldInput.tsx
new file mode 100644
index 0000000000..c2979f2060
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/FileFieldInput.tsx
@@ -0,0 +1,272 @@
+import { HStack, Icon, Stack, Text } from '@chakra-ui/react';
+import {
+ deleteManagedFile,
+ MANAGED_FILE_ACCEPT,
+ MANAGED_FILE_ACCEPTED_EXTENSIONS,
+ managedFileQueryKey,
+ managedFileQueryOptions,
+ uploadManagedFile,
+} from '@features/workflow/data/managedFiles';
+import { useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';
+import { getFieldRecordId } from '@features/workflow/utility';
+import { formatBytes } from '@platform/i18n/languages';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { getApiErrorMessage } from '@platform/transport/http';
+import { Button } from '@platform/ui/Button';
+import { DropZone } from '@platform/ui/DropZone';
+import { toaster } from '@platform/ui/toaster';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { FileTextIcon, RotateCcwIcon, UploadIcon, XIcon } from 'lucide-react';
+import { useCallback, useRef, useState, type ChangeEvent, type DragEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { WorkflowFieldInputProps } from './WorkflowFieldInput';
+
+const HIDDEN_FILE_INPUT_STYLE = { display: 'none' } as const;
+
+const isAcceptedManagedFile = (file: File): boolean => {
+ const name = file.name.toLowerCase();
+
+ return MANAGED_FILE_ACCEPTED_EXTENSIONS.some((extension) => name.endsWith(extension));
+};
+
+/** A managed file reference: upload picks or drops one, while Clear removes only the field reference. */
+export const FileFieldInput = ({
+ id,
+ invalid,
+ nodeId,
+ onChange,
+ template,
+ value,
+ workflowId,
+}: WorkflowFieldInputProps) => {
+ const { t } = useTranslation();
+ const { project } = useWorkflowUi();
+ const queryClient = useQueryClient();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const uploadInFlightRef = useRef(false);
+ const [isUploading, setIsUploading] = useState(false);
+ const [isDragOver, setIsDragOver] = useState(false);
+ const fileId = getFieldRecordId(value, 'file_id');
+ const { data: file, isError, isFetching, refetch } = useQuery(managedFileQueryOptions(fileId ?? ''));
+ const metadataUnavailable = fileId !== null && isError;
+
+ const onPickClick = useCallback(() => fileInputRef.current?.click(), []);
+ const onClearClick = useCallback(() => onChange(undefined), [onChange]);
+ const onRetryClick = useCallback(() => void refetch(), [refetch]);
+
+ const startUpload = useCallback(
+ async (picked: File) => {
+ if (uploadInFlightRef.current) {
+ return;
+ }
+
+ if (!isAcceptedManagedFile(picked)) {
+ toaster.create({
+ description: t('nodes.fileUploadRejectedDescription'),
+ title: t('nodes.fileUploadRejected'),
+ type: 'error',
+ });
+
+ return;
+ }
+
+ const owner = captureAccountScope();
+ const documentId = workflowId ?? project.getSnapshot().projectGraph.id;
+
+ uploadInFlightRef.current = true;
+ setIsUploading(true);
+
+ try {
+ const uploaded = await uploadManagedFile(picked, owner.signal);
+ // The document that owned this widget may have closed or switched while the upload ran; a late success must
+ // not write into another document. The file was never adopted, so it is safe to remove as an orphan.
+ const snapshot = project.getSnapshot();
+ const document =
+ workflowId !== undefined
+ ? snapshot.workflows.find((entry) => entry.document.id === workflowId)?.document
+ : snapshot.projectGraph;
+ const nodeExists =
+ nodeId === undefined || document?.nodes.some((candidate) => candidate.id === nodeId) === true;
+ const isCurrent =
+ isAccountScopeCurrent(owner) &&
+ !owner.signal.aborted &&
+ document !== undefined &&
+ document.id === documentId &&
+ nodeExists;
+
+ if (!isCurrent) {
+ void deleteManagedFile(uploaded.id).catch(() => undefined);
+
+ return;
+ }
+
+ queryClient.setQueryData(managedFileQueryKey(uploaded.id), uploaded);
+ onChange({ file_id: uploaded.id });
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner) || owner.signal.aborted) {
+ return;
+ }
+
+ toaster.create({
+ description: getApiErrorMessage(error, t('nodes.fileUploadFailed')),
+ title: t('nodes.fileUploadFailed'),
+ type: 'error',
+ });
+ } finally {
+ uploadInFlightRef.current = false;
+ setIsUploading(false);
+ }
+ },
+ [nodeId, onChange, project, queryClient, t, workflowId]
+ );
+
+ const onFileChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const picked = event.currentTarget.files?.[0];
+
+ // Reset so picking the same file again re-fires the change event.
+ event.currentTarget.value = '';
+
+ if (picked) {
+ void startUpload(picked);
+ }
+ },
+ [startUpload]
+ );
+
+ const onDragEnter = useCallback(
+ (event: DragEvent<HTMLDivElement>) => {
+ if (isUploading) {
+ return;
+ }
+
+ event.preventDefault();
+ setIsDragOver(true);
+ },
+ [isUploading]
+ );
+
+ const onDragOver = useCallback(
+ (event: DragEvent<HTMLDivElement>) => {
+ if (isUploading) {
+ return;
+ }
+
+ event.preventDefault();
+
+ if (event.dataTransfer) {
+ event.dataTransfer.dropEffect = 'copy';
+ }
+ },
+ [isUploading]
+ );
+
+ const onDragLeave = useCallback((event: DragEvent<HTMLDivElement>) => {
+ const nextTarget = event.relatedTarget;
+
+ if (!(nextTarget instanceof Node) || !event.currentTarget.contains(nextTarget)) {
+ setIsDragOver(false);
+ }
+ }, []);
+
+ const onDrop = useCallback(
+ (event: DragEvent<HTMLDivElement>) => {
+ event.preventDefault();
+ setIsDragOver(false);
+
+ if (isUploading) {
+ return;
+ }
+
+ const dropped = event.dataTransfer?.files?.[0];
+
+ if (dropped) {
+ void startUpload(dropped);
+ }
+ },
+ [isUploading, startUpload]
+ );
+
+ return (
+ <Stack aria-invalid={invalid || undefined} gap="1" w="full">
+ <DropZone
+ aria-label={template.title}
+ className="nodrag"
+ isDisabled={isUploading}
+ isInvalid={invalid || metadataUnavailable}
+ isOver={isDragOver}
+ minH="14"
+ px="2"
+ py="2"
+ role="group"
+ w="full"
+ onDragEnter={onDragEnter}
+ onDragLeave={onDragLeave}
+ onDragOver={onDragOver}
+ onDrop={onDrop}
+ >
+ {metadataUnavailable ? (
+ <Text color="fg.error" fontSize="xs" textAlign="center">
+ {t('nodes.fileUnavailable')}
+ </Text>
+ ) : file ? (
+ <HStack align="center" gap="2" minW="0">
+ <Icon as={FileTextIcon} boxSize="5" color="fg.muted" flexShrink="0" />
+ <Stack flex="1" gap="0" minW="0">
+ <Tooltip content={file.name}>
+ <Text fontSize="sm" fontWeight="semibold" truncate>
+ {file.name}
+ </Text>
+ </Tooltip>
+ <Text color="fg.subtle" fontSize="xs">
+ {formatBytes(file.sizeBytes)}
+ </Text>
+ </Stack>
+ </HStack>
+ ) : fileId ? (
+ <Text color="fg.subtle" fontSize="xs">
+ {t('common.loading')}
+ </Text>
+ ) : (
+ <Stack align="center" gap="1">
+ <Text color="fg" fontSize="sm" fontWeight="600">
+ {t('nodes.fileUpload')}
+ </Text>
+ <Text color="fg.subtle" fontSize="xs" textAlign="center">
+ {t('nodes.fileUploadDropHint')}
+ </Text>
+ </Stack>
+ )}
+ </DropZone>
+ <HStack gap="1.5" w="full">
+ <Button id={id} className="nodrag" disabled={isUploading} size="sm" variant="outline" onClick={onPickClick}>
+ <Icon as={UploadIcon} boxSize="3" />
+ {isUploading ? t('common.loading') : t('nodes.fileUpload')}
+ </Button>
+ {metadataUnavailable ? (
+ <Button className="nodrag" disabled={isFetching} size="sm" variant="ghost" onClick={onRetryClick}>
+ <Icon as={RotateCcwIcon} boxSize="3" />
+ {t('common.retry')}
+ </Button>
+ ) : null}
+ {fileId !== null ? (
+ <Button className="nodrag" disabled={isUploading} size="sm" variant="ghost" onClick={onClearClick}>
+ <Icon as={XIcon} boxSize="3" />
+ {t('common.clear')}
+ </Button>
+ ) : null}
+ </HStack>
+ <input
+ ref={fileInputRef}
+ accept={MANAGED_FILE_ACCEPT}
+ aria-label={t('nodes.fileUpload')}
+ disabled={isUploading}
+ style={HIDDEN_FILE_INPUT_STYLE}
+ type="file"
+ onChange={onFileChange}
+ />
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
index 1cdbaebb5f..e91da8df82 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
@@ -151,6 +151,8 @@ const StylePresetInput = lazy(() =>
const SystemPromptInput = lazy(() =>
import('./RecordPickerInput').then((module) => ({ default: module.SystemPromptInput }))
);
+// Managed-file controls load with their node; uploads and file metadata stay out of the editor's boot graph.
+const FileFieldInput = lazy(() => import('./FileFieldInput').then((module) => ({ default: module.FileFieldInput })));
export const getWorkflowSelectedGalleryImage = getSelectedGalleryImageFromValues;
@@ -1920,6 +1922,12 @@ export const WorkflowFieldInput = (props: WorkflowFieldInputProps) => {
);
case 'BoardField':
return <BoardInput {...props} />;
+ case 'FileField':
+ return (
+ <Suspense fallback={RECORD_PICKER_FALLBACK}>
+ <FileFieldInput {...props} />
+ </Suspense>
+ );
case 'ImageField':
return <MediaInput {...props} kind="image" />;
case 'VideoField':
@@ -1952,6 +1960,7 @@ const formatSnapshotObject = (value: Record<string, unknown>): string | null =>
'name',
'image_name',
'video_name',
+ 'file_id',
'latents_name',
'tensor_name',
'key',
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index 59cc502861..2d72e65eee 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -63,6 +63,9 @@ const ROUTE_SHARED_MODULES = [
'/workbench/projects/editorSession.ts',
'/platform/ui/BrandIcon.tsx',
'/platform/ui/Button.tsx',
+ // The eager Generate and Gallery surfaces and the lazily loaded managed-file field share it; alone it costs both
+ // routes a startup request.
+ '/platform/ui/DropZone.tsx',
// Sign-in and deferred user management share session/form primitives. Keep the already-eager code together;
// splitting by the new importer sets would add a startup request on both routes.
'/features/identity/core/schemas.ts',
diff --git a/invokeai/invocation_api/__init__.py b/invokeai/invocation_api/__init__.py
index 172098e39b..77e84191ba 100644
--- a/invokeai/invocation_api/__init__.py
+++ b/invokeai/invocation_api/__init__.py
@@ -20,6 +20,7 @@ from invokeai.app.invocations.fields import (
DenoiseMaskField,
FieldDescriptions,
FieldKind,
+ FileField,
FluxConditioningField,
ImageField,
Input,
@@ -176,6 +177,7 @@ __all__ = [
"DenoiseMaskField",
"FieldDescriptions",
"FieldKind",
+ "FileField",
"FluxConditioningField",
"ImageField",
"Input",
diff --git a/scripts/generate_docs_json.py b/scripts/generate_docs_json.py
index 1a09cea5a8..542b7c18d2 100644
--- a/scripts/generate_docs_json.py
+++ b/scripts/generate_docs_json.py
@@ -23,6 +23,7 @@ INTERFACE_NAMES = (
"ConfigInterface",
"UtilInterface",
"BoardsInterface",
+ "FilesInterface",
)
diff --git a/tests/app/api/test_file_upload_limits.py b/tests/app/api/test_file_upload_limits.py
new file mode 100644
index 0000000000..1b503c8cee
--- /dev/null
+++ b/tests/app/api/test_file_upload_limits.py
@@ -0,0 +1,119 @@
+"""Ingress limits for managed-file multipart uploads."""
+
+import asyncio
+from typing import Any
+
+from invokeai.app import api_app
+from invokeai.app.api.routers import files
+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_file_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_file_upload
+ ]
+
+ assert len(limiters) == 1
+ kwargs = limiters[0].kwargs
+ assert (
+ kwargs["max_body_bytes"] == api_app.app_config.max_file_upload_size_bytes + files.FILE_UPLOAD_MULTIPART_OVERHEAD
+ )
+ assert kwargs["max_concurrent"] == files.MAX_CONCURRENT_FILE_UPLOADS
+ assert kwargs["max_concurrent_per_user"] == files.MAX_CONCURRENT_FILE_UPLOADS_PER_USER
+ assert api_app._is_file_upload("POST", "/api/v1/files/upload")
+ assert not api_app._is_file_upload("GET", "/api/v1/files/upload")
+ assert not api_app._is_file_upload("POST", "/api/v1/files/i/file-id")
+ assert not api_app._is_file_upload("POST", "/api/v1/files/upload/extra")
+
+
+def test_oversized_file_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 file request must not reach multipart parsing")
+
+ middleware = RequestBodyLimitASGIMiddleware(
+ downstream,
+ matches_request=api_app._is_file_upload,
+ too_large_detail=lambda _actual, limit: {"code": "file_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/files/upload", [(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_file_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_file_upload,
+ too_large_detail=lambda _actual, limit: {"code": "file_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/files/upload"), receive, send))
+
+ assert seen[-1]["type"] == "http.disconnect"
+ assert sum(len(message.get("body", b"")) for message in seen if message["type"] == "http.request") == 7
diff --git a/tests/app/routers/conftest.py b/tests/app/routers/conftest.py
index 994395507c..fb83ad182f 100644
--- a/tests/app/routers/conftest.py
+++ b/tests/app/routers/conftest.py
@@ -54,6 +54,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.files",
"invokeai.app.api.routers.fonts",
"invokeai.app.api.routers.wildcards",
"invokeai.app.api.routers.virtual_boards",
diff --git a/tests/app/routers/test_files.py b/tests/app/routers/test_files.py
new file mode 100644
index 0000000000..3982bb52c8
--- /dev/null
+++ b/tests/app/routers/test_files.py
@@ -0,0 +1,110 @@
+"""Router-level tests for /api/v1/files.
+
+Managed-file inputs upload through this router, so its registration is part of the feature:
+a missing include makes every upload answer 405 from the SPA catch-all instead of reaching
+the service. These tests go through the HTTP layer against a real `DiskFileService`.
+"""
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import status
+from fastapi.testclient import TestClient
+
+from invokeai.app.services.files.files_disk import DiskFileService
+from invokeai.app.services.invoker import Invoker
+
+UPLOAD_URL = "/api/v1/files/upload"
+MAX_FILE_SIZE_BYTES = 1024
+
+
+def _auth(token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {token}"}
+
+
+def file_service(enable_multiuser: Any, mock_invoker: Invoker, tmp_path: Path) -> DiskFileService:
+ service = DiskFileService(tmp_path / "files", max_file_size=MAX_FILE_SIZE_BYTES)
+ mock_invoker.services.files = service
+ return service
+
+
+def _upload(
+ client: TestClient,
+ token: str,
+ *,
+ file_name: str = "notes.txt",
+ content: bytes = b"hello",
+ content_type: str = "text/plain",
+):
+ return client.post(
+ UPLOAD_URL,
+ files={"file": (file_name, content, content_type)},
+ headers=_auth(token),
+ )
+
+
+def test_upload_get_delete_round_trip(client: TestClient, user1_token: str, file_service: DiskFileService) -> None:
+ del file_service
+
+ uploaded = _upload(client, user1_token)
+
+ assert uploaded.status_code == status.HTTP_201_CREATED
+ file = uploaded.json()
+ assert (file["file_name"], file["content_type"], file["size_bytes"]) == ("notes.txt", "text/plain", 5)
+
+ fetched = client.get(f"/api/v1/files/i/{file['file_id']}", headers=_auth(user1_token))
+ assert fetched.status_code == status.HTTP_200_OK
+ assert fetched.json() == file
+
+ deleted = client.delete(f"/api/v1/files/i/{file['file_id']}", headers=_auth(user1_token))
+ assert deleted.status_code == status.HTTP_204_NO_CONTENT
+
+ gone = client.get(f"/api/v1/files/i/{file['file_id']}", headers=_auth(user1_token))
+ assert gone.status_code == status.HTTP_404_NOT_FOUND
+
+
+def test_another_user_cannot_read_or_delete_a_file(
+ client: TestClient, user1_token: str, user2_token: str, file_service: DiskFileService
+) -> None:
+ del file_service
+ file_id = _upload(client, user1_token).json()["file_id"]
+
+ assert client.get(f"/api/v1/files/i/{file_id}", headers=_auth(user2_token)).status_code == status.HTTP_403_FORBIDDEN
+ assert (
+ client.delete(f"/api/v1/files/i/{file_id}", headers=_auth(user2_token)).status_code == status.HTTP_403_FORBIDDEN
+ )
+ # The refused delete must not have touched the owner's file.
+ assert client.get(f"/api/v1/files/i/{file_id}", headers=_auth(user1_token)).status_code == status.HTTP_200_OK
+
+
+def test_unsupported_extension_is_rejected(client: TestClient, user1_token: str, file_service: DiskFileService) -> None:
+ del file_service
+
+ response = _upload(client, user1_token, file_name="payload.exe", content_type="application/octet-stream")
+
+ assert response.status_code == status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
+
+
+def test_oversized_file_is_rejected(client: TestClient, user1_token: str, file_service: DiskFileService) -> None:
+ del file_service
+
+ response = _upload(client, user1_token, content=b"x" * (MAX_FILE_SIZE_BYTES + 1))
+
+ assert response.status_code == status.HTTP_413_CONTENT_TOO_LARGE
+
+
+def test_exhausted_storage_quota_is_rejected(
+ client: TestClient, user1_token: str, mock_invoker: Invoker, tmp_path: Path
+) -> None:
+ storage_path = tmp_path / "quota-files"
+ mock_invoker.services.files = DiskFileService(storage_path, max_storage_size=8)
+
+ assert _upload(client, user1_token, content=b"x" * 6).status_code == status.HTTP_201_CREATED
+
+ response = _upload(client, user1_token, content=b"x" * 6)
+
+ assert response.status_code == status.HTTP_413_CONTENT_TOO_LARGE
+ # The rejected upload's partial file and metadata are cleaned up.
+ assert len(list(storage_path.iterdir())) == 2
diff --git a/tests/app/services/files/__init__.py b/tests/app/services/files/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/app/services/files/test_files_disk.py b/tests/app/services/files/test_files_disk.py
new file mode 100644
index 0000000000..324e0abfcd
--- /dev/null
+++ b/tests/app/services/files/test_files_disk.py
@@ -0,0 +1,206 @@
+from io import BytesIO
+from pathlib import Path
+
+import pytest
+
+from invokeai.app.services.files.files_common import (
+ FileAccessDeniedException,
+ FileMetadataException,
+ FileNotFoundException,
+ FileQuotaExceededException,
+ FileTooLargeException,
+ UnsupportedFileTypeException,
+)
+from invokeai.app.services.files.files_disk import DiskFileService
+
+
+def test_save_open_get_path_and_delete_round_trip(tmp_path: Path) -> None:
+ service = DiskFileService(tmp_path)
+
+ dto = service.save(
+ file_name="report.pdf",
+ content_type="application/pdf",
+ file=BytesIO(b"%PDF-1.7 test"),
+ user_id="user-1",
+ )
+
+ assert dto.file_name == "report.pdf"
+ assert dto.content_type == "application/pdf"
+ assert dto.size_bytes == len(b"%PDF-1.7 test")
+
+ path = service.get_path(dto.file_id, user_id="user-1")
+ assert path.is_relative_to(tmp_path.resolve())
+ assert path.name == f"{dto.file_id}.pdf"
+ assert path.read_bytes() == b"%PDF-1.7 test"
+
+ with service.open(dto.file_id, user_id="user-1") as opened_file:
+ assert opened_file.read() == b"%PDF-1.7 test"
+
+ service.delete(dto.file_id, user_id="user-1")
+
+ with pytest.raises(FileNotFoundException):
+ service.get_dto(dto.file_id, user_id="user-1")
+
+
+def test_json_upload_does_not_collide_with_metadata(tmp_path: Path) -> None:
+ service = DiskFileService(tmp_path)
+ content = b'{"hello": "world"}'
+
+ dto = service.save(
+ file_name="data.json",
+ content_type="application/json",
+ file=BytesIO(content),
+ user_id="user-1",
+ )
+
+ file_path = service.get_path(dto.file_id, user_id="user-1")
+ metadata_path = tmp_path / f"{dto.file_id}.meta.json"
+
+ assert file_path.name == f"{dto.file_id}.json"
+ assert file_path.read_bytes() == content
+ assert metadata_path.exists()
+ assert metadata_path != file_path
+
+
+def test_open_text_mode_reads_utf8(tmp_path: Path) -> None:
+ service = DiskFileService(tmp_path)
+ content = "cafe 日本語"
+ dto = service.save(
+ file_name="notes.md",
+ content_type="text/markdown",
+ file=BytesIO(content.encode("utf-8")),
+ user_id=None,
+ )
+
+ with service.open(dto.file_id, mode="r", user_id=None) as opened_file:
+ assert opened_file.read() == content
+
+
+def test_get_dto_fails_when_file_is_missing(tmp_path: Path) -> None:
+ service = DiskFileService(tmp_path)
+ dto = service.save(file_name="notes.txt", content_type="text/plain", file=BytesIO(b"notes"), user_id=None)
+
+ service.get_path(dto.file_id).unlink()
+
+ with pytest.raises(FileNotFoundException):
+ service.get_dto(dto.file_id)
+
+
+def test_get_dto_fails_when_metadata_is_invalid(tmp_path: Path) -> None:
+ service = DiskFileService(tmp_path)
+ dto = service.save(file_name="notes.txt", content_type="text/plain", file=BytesIO(b"notes"), user_id=None)
+
+ (tmp_path / f"{dto.file_id}.meta.json").write_text("{", encoding="utf-8")
+
+ with pytest.raises(FileMetadataException):
+ service.get_dto(dto.file_id)
+
+
+def test_sanitizes_file_name_to_basename(tmp_path: Path) -> None:
+ service = DiskFileService(tmp_path)
+
+ dto = service.save(
+ file_name="../nested/data.csv",
+ content_type="text/csv",
+ file=BytesIO(b"a,b\n1,2\n"),
+ user_id=None,
+ )
+
+ assert dto.file_name == "data.csv"
+ assert service.get_path(dto.file_id).is_relative_to(tmp_path.resolve())
+
+
[email protected]("file_name", ["image.png", "archive.zip", "no-extension"])
+def test_rejects_unsupported_extension(tmp_path: Path, file_name: str) -> None:
+ service = DiskFileService(tmp_path)
+
+ with pytest.raises(UnsupportedFileTypeException):
+ service.save(file_name=file_name, content_type="application/octet-stream", file=BytesIO(b"data"), user_id=None)
+
+
[email protected]("content_type", ["image/png", "application/zip"])
+def test_rejects_unsupported_content_type(tmp_path: Path, content_type: str) -> None:
+ service = DiskFileService(tmp_path)
+
+ with pytest.raises(UnsupportedFileTypeException):
+ service.save(file_name="data.json", content_type=content_type, file=BytesIO(b"{}"), user_id=None)
+
+
[email protected]("content_type", [None, "", "application/octet-stream"])
+def test_allows_octet_stream_for_allowed_extensions(tmp_path: Path, content_type: str | None) -> None:
+ service = DiskFileService(tmp_path)
+
+ dto = service.save(file_name="notes.md", content_type=content_type, file=BytesIO(b"# Notes"), user_id=None)
+
+ assert dto.content_type == "application/octet-stream"
+
+
+ ("file_name", "content_type"),
+ [
+ ("data.csv", "application/vnd.ms-excel"),
+ ("data.csv", "text/x-csv"),
+ ("data.json", "text/json"),
+ ],
+)
+def test_allows_common_vendor_content_type_aliases(tmp_path: Path, file_name: str, content_type: str) -> None:
+ service = DiskFileService(tmp_path)
+
+ dto = service.save(file_name=file_name, content_type=content_type, file=BytesIO(b"data"), user_id=None)
+
+ assert dto.content_type == content_type
+
+
+def test_rejects_files_over_size_limit_and_cleans_up(tmp_path: Path) -> None:
+ service = DiskFileService(tmp_path, max_file_size=4)
+
+ with pytest.raises(FileTooLargeException):
+ service.save(file_name="large.txt", content_type="text/plain", file=BytesIO(b"12345"), user_id=None)
+
+ assert list(tmp_path.iterdir()) == []
+
+
+def test_rejects_files_over_storage_quota_and_cleans_up(tmp_path: Path) -> None:
+ service = DiskFileService(tmp_path, max_storage_size=4)
+
+ with pytest.raises(FileQuotaExceededException):
+ service.save(file_name="large.txt", content_type="text/plain", file=BytesIO(b"12345"), user_id=None)
+
+ assert list(tmp_path.iterdir()) == []
+
+
+def test_storage_quota_counts_existing_files_and_delete_frees_space(tmp_path: Path) -> None:
+ service = DiskFileService(tmp_path, max_storage_size=10)
+ first = service.save(file_name="first.txt", content_type="text/plain", file=BytesIO(b"123456"), user_id=None)
+
+ with pytest.raises(FileQuotaExceededException):
+ service.save(file_name="second.txt", content_type="text/plain", file=BytesIO(b"123456"), user_id=None)
+
+ # A fresh service recounts the directory instead of assuming an empty library.
+ restarted = DiskFileService(tmp_path, max_storage_size=10)
+ with pytest.raises(FileQuotaExceededException):
+ restarted.save(file_name="second.txt", content_type="text/plain", file=BytesIO(b"12345"), user_id=None)
+
+ restarted.delete(first.file_id)
+ restarted.save(file_name="second.txt", content_type="text/plain", file=BytesIO(b"1234567890"), user_id=None)
+
+
+def test_user_scoped_access(tmp_path: Path) -> None:
+ service = DiskFileService(tmp_path)
+ dto = service.save(file_name="private.txt", content_type="text/plain", file=BytesIO(b"secret"), user_id="user-1")
+
+ service.get_dto(dto.file_id, user_id="user-1")
+
+ with pytest.raises(FileAccessDeniedException):
+ service.get_dto(dto.file_id, user_id=None)
+
+ with pytest.raises(FileAccessDeniedException):
+ service.get_dto(dto.file_id, user_id="user-2")
+
+
+def test_rejects_write_modes(tmp_path: Path) -> None:
+ service = DiskFileService(tmp_path)
+ dto = service.save(file_name="notes.txt", content_type="text/plain", file=BytesIO(b"notes"), user_id=None)
+
+ with pytest.raises(ValueError, match="only be opened for reading"):
+ service.open(dto.file_id, mode="wb")
diff --git a/tests/app/services/shared/test_execution_effects.py b/tests/app/services/shared/test_execution_effects.py
index 511c50042f..e2565e3b47 100644
--- a/tests/app/services/shared/test_execution_effects.py
+++ b/tests/app/services/shared/test_execution_effects.py
@@ -159,6 +159,7 @@ def test_direct_and_builder_contexts_preserve_lifecycle_recorder_authority() ->
config=built.config,
util=built.util,
boards=built.boards,
+ files=built.files,
wildcards=built.wildcards,
data=data,
services=services,