Application Services, Cloud, and Assets
Overview
This doc covers app/**, alembic_db/**, alembic.ini, blueprints/**, custom_nodes/**, models/**, input/**, and output/**. Route/index hints: changes to application service route registration, user settings, asset APIs, database migrations, custom-node/template discovery, model listing/previews, cloud deploy, governance, or runtime folders under those globs belong here.
server.PromptServer wires these services into the aiohttp server: it receives an AssetManager, constructs UserManager, ModelFileManager, CustomNodeManager, SubgraphManager, NodeReplaceManager, DeployToCloudRoutes, and PromptQueue, then registers asset routes before its own route table in server.py. main.py chooses default_asset_manager() from app/…/manager.py, publishes the assets feature flag, creates the server, loads custom nodes, applies governance disabled-node rules, initializes the database, and finally calls prompt_server.add_routes(). Execution-layer outputs are connected back to this module through comfy_execution/asset_enrichment.py, which calls the asset manager when prompt results or cached outputs are emitted.
User-specific state is file-backed. app/user_manager.py creates the user directory from folder_paths.get_user_directory(), stores multi-user names in users.json, resolves the comfy-user header when --multi-user is enabled, rejects system-user prefixes, and bounds all /userdata paths to the public user directory. It also exposes /users, /userdata, /v2/userdata, file upload/delete/move routes, and delegates /settings routes to app/app_settings.py, which reads and writes each user's comfy.settings.json.
The asset system is optional but, when enabled, is the main application database user. app/…/manager.py selects NoAssets under --disable-assets and AssetsEnabled otherwise. AssetsEnabled.startup() initializes hash-mode state, records hash-mode transition intent, cleans temp rows/files, and starts the background seeder via app/…/lifecycle.py; register_routes() mounts app/…/routes.py; register_upload(), register_executed_output(), and register_cached_output() delegate to app/…/ingest.py. NoAssets preserves route parity where possible: it can mount disabled asset routes when dependencies exist, disables the seeder, and returns None for all registration hooks.
Asset persistence is split between catalog rows and filesystem bytes. app/…/models.py declares AssetContent for bytes at a path with optional BLAKE3 hash, size, mtime, and is_missing; Asset for user-visible records with name, mime type, metadata, job id, loader path, preview link, timestamps, and content FK; Tag and AssetTag for labels; and AssetSystemState for mode state. AssetContent has a partial unique index on live paths, so replacing a file marks old content missing rather than creating two live rows for the same path. API responses in app/…/schemas_out.py expose record IDs, hashes, loader paths, previews, tags, metadata, job IDs, and cursor pagination fields.
The asset HTTP API in app/…/routes.py is feature-gated: routes return a JSON 503 envelope when assets are disabled. It handles /api/assets listing with tag filters and cursor pagination, detail/update/delete, /api/assets/{id}/content streaming with dangerous MIME-type hardening, /api/assets/from-hash, multipart uploads, tag add/remove/list/refine, seed status/cancel, and prune. Request boundary validation lives in app/…/schemas_in.py; lower-level operations live in services such as app/…/asset_management.py for metadata, tags, deletes, download resolution, preview reclamation, and export lookups, and app/…/ingest.py for uploads, in-place registration, executed outputs, cached outputs, preview linkage, and hash-based record creation.
The background scanner and seeder bridge runtime folders to database rows. app/…/scanner.py walks model folders, input, and output; marks missing files; builds seed specs with backend tags and loader paths; inserts content/records in batches; and enriches rows with metadata and hashes. app/…/seeder.py runs scans on daemon threads, tracks state/progress, supports pause/resume/cancel, drains pending hash-mode transitions, and exposes scan/prune control to the API. app/…/path_utils.py is the central path classifier: it maps tags to upload destinations, computes display_name and loader_path, classifies files as input, output, temp, or models, and emits trusted backend tags such as model_type:<folder_name>.
Database setup is centralized in app/…/db.py. It conditionally imports SQLAlchemy, Alembic, and BLAKE3; main.py stops startup when assets are enabled but these dependencies are unavailable. File-backed SQLite databases are placed at user/comfyui.db unless --database-url is provided, acquire a <db>.lock file for process exclusion, migrate with Alembic, enable foreign keys and WAL where possible, and use a separate write engine whose transactions start with BEGIN IMMEDIATE. In-memory SQLite skips Alembic and creates all Base.metadata tables directly. Migrations live in alembic_db/versions/**, with alembic_db/env.py targeting app.database.models.Base.metadata and using batch mode plus the shared naming convention from app/…/models.py; alembic.ini is rewritten at runtime with the actual script location and database URL.
Model and custom-node application services are mostly read/discovery layers. app/model_manager.py exposes experimental /experiment/models routes that list configured model folders from folder_paths.folder_names_and_paths, recursively cache model files by directory mtime, and serve companion previews or embedded safetensors cover images after validating folder indexes and path containment. app/custom_node_manager.py discovers workflow templates under custom-node example_workflows-style folders, mounts static routes for loaded modules, and merges custom-node locales/…/main.json, nodeDefs.json, commands.json, and settings.json into /i18n. app/subgraph_manager.py discovers global subgraphs from custom-node subgraphs/*.json and top-level blueprints/*.json, caches their metadata, and serves /global_subgraphs; the many JSON files in blueprints/** are the built-in workflow/subgraph catalog this manager indexes. custom_nodes/** and models/** are runtime extension/model locations rather than source in this checkout, but their directory contents are observed by these managers and by the asset scanner.
Node compatibility and governance sit between app services and custom-node loading. app/node_replace_manager.py stores replacement mappings registered by nodes, exposes /node_replacements, and can rewrite a prompt graph by replacing missing class_type values and remapping inputs/outputs before execution. app/governance.py verifies a signed governance policy when GOVERNANCE_REQUIRED is set, enforces custom-node allow/block lists by hashing measured pack files, refuses bytecode/symlink cases the digest cannot cover, disables legacy Manager under custom-node policy, and removes disabled node IDs from nodes.NODE_CLASS_MAPPINGS while wrapping nodes.load_custom_node so later loads also ignore them.
Cloud/deployment services are explicit application integrations. app/deploy_to_cloud.py records whether the server has been used headlessly, toggles the deploy_to_cloud feature flag, builds a Desktop-format installation snapshot by scanning custom nodes, pip packages, Python version, ComfyUI version, and model files, and exposes /api/deploy/summary plus /api/deploy/bundle. Bundle upload validates a bearer token or X-API-Key, accepts optional workflow/name JSON, posts to the builder API chosen by app/comfy_api_env.py, and returns a platform import URL on success. app/deploy_environment.py reads a .comfy_environment marker beside the ComfyUI install, defaulting to local-git; app/comfy_api_env.py exposes staging/testenv overrides and maps the selected API tier to platform and builder base URLs.
Export, frontend, logging, agent, and product-tip services round out the application layer. app/asset_export.py implements the shared local asset export contract: /api/assets/export resolves job and asset selections through asset services, writes an uncompressed zip in temp/exports on a background thread, emits asset_export websocket progress, and serves owned export URLs through /api/assets/exports/{exportName}. app/frontend_management.py finds the packaged frontend, workflow templates, and embedded docs, optionally downloads a requested GitHub release into web_custom_versions, and warns when required comfy packages are outdated. app/logger.py installs colored console/file logging plus a bounded in-memory log deque and startup warning buffer. app/agent_host.py loads the optional comfyui.agent entry point, lets it mount routes, starts/stops it around server lifecycle, and mirrors status into the agent feature flag. app/product_tips.py conditionally emits Comfy Org product hints at startup or after headless jobs.
Coupling
- If server.py changes route initialization order, verify app/…/manager.py and app/…/routes.py: asset routes are registered before the server route table,
USER_MANAGERis set only whenAssetsEnabled.register_routes()receives a user manager, and disabled routes rely on the same registration path to return 503 rather than disappearing. - If execution output payloads change, update both comfy_execution/asset_enrichment.py and app/…/ingest.py. The enrichment layer expects UI entries with
filename,type, optionalsubfolder, and optionalasset_preview, thenregister_executed_output()persists job IDs and preview links used by asset detail, export, and/viewhash resolution. - If
AssetContent,Asset, tags, or timestamps change in app/…/models.py, add matching Alembic revisions underalembic_db/versions/**and verify app/…/db.py destructive-upgrade handling.Base.metadatais shared through app/…/models.py, and in-memory databases create from metadata while file databases migrate through Alembic. - If upload destination rules or loader paths change in app/…/path_utils.py, verify app/…/ingest.py, app/…/scanner.py, app/…/routes.py, app/asset_export.py, and app/model_manager.py. Upload routing, backend tags, public
display_name, model-loaderloader_path, export eligibility, and model preview containment all depend on the same root/category interpretation. - If hash mode or hashing dependencies change, verify app/…/mode.py, app/…/lifecycle.py, app/…/seeder.py, app/…/ingest.py, app/…/asset_management.py, and app/…/db.py. Hash-addressed create/download paths must not silently behave as hashing-off, and startup currently requires BLAKE3 when assets are enabled.
- If custom-node loading or governance policy changes, verify app/custom_node_manager.py, app/subgraph_manager.py, app/node_replace_manager.py, and app/governance.py. The UI discovers templates, translations, subgraphs, and replacement maps separately from Python node loading, while governance can refuse packs and prune node IDs before prompts are validated.
- If
--comfy-api-base, staging hosts, or builder/platform URLs change, update both app/comfy_api_env.py and app/deploy_to_cloud.py. The deploy bundle route deliberately derives builder/platform targets from local CLI configuration, not request input, and the frontend reads environment overrides from server features. - If user identity or user-data path rules change in app/user_manager.py, verify app/app_settings.py, app/asset_export.py, and asset hash download behavior in server.py. Settings, export task ownership, and
/view?filename=blake3:...all depend onUserManager.get_request_user_id()and path containment semantics.
Risks
- app/…/db.py contains several startup-critical SQLite paths: file locks, legacy database relocation, pre-upgrade backup/restore, WAL configuration, and the destructive revision warning for
0007_record_content_split. If migration failure handling or lock acquisition regresses, startup can either refuse a valid database or corrupt/lose asset catalog state during upgrade. - app/…/ingest.py and app/…/scanner.py deliberately reconcile live path conflicts, stat/hash stability, and missing-row recovery before writes. If these ordering rules are simplified, a replaced file can inherit the old row's hash/mtime, duplicate records can point at stale content, or hash-addressed lookup can serve bytes different from the recorded hash.
- app/…/lifecycle.py hard-deletes temp DB rows and deletes the temp directory on startup/shutdown. Its temp-prefix predicate is intentionally case-sensitive; broadening it or reusing it for non-temp roots could delete persistent user assets or previews outside
temp. - app/…/routes.py, app/user_manager.py, and app/model_manager.py contain path traversal and stored-XSS defenses for
/api/assets/{id}/content,/userdata/{file},/view, and model preview serving. If content disposition, MIME-type downgrades,Sec-Fetch-Desthandling, orfolder_paths.is_within_directory()checks drift, uploaded SVG/HTML/XML or preview symlinks can execute or expose files outside allowed roots. - app/governance.py only measures selected source/frontend/native-library suffixes for custom-node pack digests and explicitly rejects bytecode/symlinks to keep that model sound. Adding executable file types without updating
_PACK_EXTENSIONSor relaxing bytecode checks would allow governed packs to execute unmeasured code. - app/deploy_to_cloud.py constructs an installation snapshot and forwards exactly one caller credential to the builder. If
_credential()or_strip_userinfo()is loosened, bundle upload could forward ambiguous credentials or leak tokens embedded in git/direct-url metadata.