Compare commits
14 Commits
d8f94ca371
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 6d433ba371 | |||
| 7ca7d95ef3 | |||
| 2692bb1752 | |||
| e043ec865c | |||
| 4ffaddef7c | |||
| 19b96de322 | |||
| 406a4bf9ff | |||
| 0707a76768 | |||
| a67b628140 | |||
| 73185ad638 | |||
| cc1369a38b | |||
| acaa9f0168 | |||
| 77c159a918 | |||
| 5860b232d4 |
@@ -15,9 +15,10 @@ A ComfyUI custom node package that silently tracks which nodes, packages, and mo
|
|||||||
- **Smart aging** — items gradually move from "recently unused" to "safe to remove" over time
|
- **Smart aging** — items gradually move from "recently unused" to "safe to remove" over time
|
||||||
- **Uninstall detection** — removed packages/models are flagged separately, historical data preserved
|
- **Uninstall detection** — removed packages/models are flagged separately, historical data preserved
|
||||||
- **Expandable detail** — click any package to see individual node-level stats
|
- **Expandable detail** — click any package to see individual node-level stats
|
||||||
- **One-click disable** — disable unused packages straight from the dialog via ComfyUI Manager (per-package or in bulk), reversible at any time
|
- **One-click disable** — disable unused packages straight from the dialog (per-package or in bulk), reversible at any time. Uses ComfyUI Manager when it manages the pack, and **falls back to a native disable** (moving the pack into `custom_nodes/.disabled/`) for hand-cloned packs, loose single-file nodes, or when Manager isn't installed. Natively-disabled packs get an **Enable** button in the *Uninstalled* tier to move them back — no Manager needed (restart to apply)
|
||||||
- **Workflow tab** — on loading a workflow, splits unresolved nodes into *Missing* (install via Manager) and *Disabled*, with a temporary **Enable 7d** trial that auto-disables packages left unused
|
- **Whitelist** — click the ☆ star on any package to protect it: whitelisted packs move into their own pinned group, never show a Disable button, and are skipped by the 7-day trial auto-disable
|
||||||
- **Mirror search** — a standalone palette (⌕ button / `Ctrl/Cmd+Shift+D`) that searches nodes belonging to currently-disabled packages and re-enables them on the spot
|
- **Workflow tab** — on loading a workflow, splits unresolved nodes into *Missing* (install permanently or on a trial) and *Disabled* (enable permanently or on a trial), with a rolling **7-day trial** that auto-disables packages left unused
|
||||||
|
- **Mirror search** — a standalone palette (⌕ button / `Ctrl/Cmd+Shift+D`) that searches nodes belonging to currently-disabled packages, draws an imitation node box (real inputs/widgets/outputs, parsed from source), and re-enables the pack on the spot
|
||||||
- **Non-blocking** — DB writes happen in a background thread, no impact on workflow execution
|
- **Non-blocking** — DB writes happen in a background thread, no impact on workflow execution
|
||||||
|
|
||||||
## Package Classification
|
## Package Classification
|
||||||
@@ -81,21 +82,35 @@ package, plus a **Disable all** button per section. Disabling:
|
|||||||
|
|
||||||
If ComfyUI Manager is not installed, the disable buttons are hidden and stats work as before.
|
If ComfyUI Manager is not installed, the disable buttons are hidden and stats work as before.
|
||||||
|
|
||||||
|
> **Manager compatibility:** works with both the standalone
|
||||||
|
> [ComfyUI-Manager](https://github.com/ltdrdata/ComfyUI-Manager) custom node and
|
||||||
|
> ComfyUI core's built-in manager. For the built-in manager, launch ComfyUI with
|
||||||
|
> `--enable-manager-legacy-ui` (the extension detects the active manager and its
|
||||||
|
> API automatically). Without a reachable manager, all enable/disable/install
|
||||||
|
> actions are simply omitted.
|
||||||
|
|
||||||
### Workflow tab & temporary enable
|
### Workflow tab & temporary enable
|
||||||
|
|
||||||
Whenever you load a workflow, the extension scans for node types the running
|
Whenever you load a workflow, the extension scans for node types the running
|
||||||
ComfyUI can't resolve and, if any are found, opens the dialog on the **Workflow**
|
ComfyUI can't resolve and, if any are found, opens the dialog on the **Workflow**
|
||||||
tab. Unresolved nodes are split into two groups:
|
tab. Unresolved nodes are split into two groups:
|
||||||
|
|
||||||
- **Missing** — the owning package isn't installed. Install is handled by
|
- **Missing** — the owning package isn't installed. Each row offers:
|
||||||
[ComfyUI Manager](https://github.com/ltdrdata/ComfyUI-Manager) like always: the
|
- **Install 7d** — really install the package (via
|
||||||
**Install** button opens Manager's Custom Nodes Manager (use its *Missing*
|
[ComfyUI Manager](https://github.com/ltdrdata/ComfyUI-Manager)) and start a
|
||||||
filter).
|
*temporary trial*, so trying out someone else's workflow stays
|
||||||
|
non-committal — anything you don't actually use auto-disables.
|
||||||
|
- **Install** — install permanently (no trial).
|
||||||
|
|
||||||
|
Both take effect after a ComfyUI restart. If the install can't be resolved or
|
||||||
|
Manager refuses it (e.g. a blocked git URL), the buttons fall back to opening
|
||||||
|
Manager's Custom Nodes Manager (use its *Missing* filter).
|
||||||
- **Disabled** — the package is installed but currently disabled. Each row offers:
|
- **Disabled** — the package is installed but currently disabled. Each row offers:
|
||||||
- **Enable 7d** — re-enable the package and start a *temporary trial*.
|
- **Enable 7d** — re-enable the package and start a *temporary trial*.
|
||||||
- **Enable** — re-enable permanently (no trial).
|
- **Enable** — re-enable permanently (no trial).
|
||||||
|
|
||||||
**The temporary trial** is a rolling budget of **7 distinct boot-days**. A
|
**The temporary trial** (started by either *Install 7d* or *Enable 7d*) is a
|
||||||
|
rolling budget of **7 distinct boot-days**. A
|
||||||
"boot-day" is counted at most once per calendar day, the first time ComfyUI
|
"boot-day" is counted at most once per calendar day, the first time ComfyUI
|
||||||
starts that day — so the clock measures days you actually run ComfyUI, not wall
|
starts that day — so the clock measures days you actually run ComfyUI, not wall
|
||||||
time. **Any execution that uses the package resets the counter to zero.** If a
|
time. **Any execution that uses the package resets the counter to zero.** If a
|
||||||
@@ -119,15 +134,25 @@ package* and lets you re-enable the owning package right from the results.
|
|||||||
**`Ctrl/Cmd+Shift+D`** (ignored while typing in an input).
|
**`Ctrl/Cmd+Shift+D`** (ignored while typing in an input).
|
||||||
- Type to filter — results are ranked (node-name prefix first, then word-start,
|
- Type to filter — results are ranked (node-name prefix first, then word-start,
|
||||||
substring, finally pack-name matches) and show the `class_type` and its pack.
|
substring, finally pack-name matches) and show the `class_type` and its pack.
|
||||||
|
- Hover a result (or use ↑/↓) to open a **preview panel** on the right with the
|
||||||
|
owning package's title, author, description, repo link, and the full list of
|
||||||
|
sibling nodes in that pack — the active node highlighted.
|
||||||
|
- **Click a node's name** (or *Draw this node*) to render an **imitation node
|
||||||
|
box** — the real input sockets, widget defaults, and output sockets, drawn from
|
||||||
|
a static parse of the disabled pack's source. Since the pack isn't loaded,
|
||||||
|
there's no live definition to render; the backend AST-parses the pack on disk
|
||||||
|
(read-only, never executed) to recover the schema. Works for most packs (~90%);
|
||||||
|
packs that build their node list dynamically fall back to a placeholder box.
|
||||||
- Each result offers **Enable 7d** (re-enable under a 7-day trial) and **Enable**
|
- Each result offers **Enable 7d** (re-enable under a 7-day trial) and **Enable**
|
||||||
(re-enable permanently) — the same enable path as the Workflow tab.
|
(re-enable permanently) — in the row and in the preview panel — the same enable
|
||||||
|
path as the Workflow tab.
|
||||||
- Enabling takes effect after a ComfyUI restart; enabled rows mark
|
- Enabling takes effect after a ComfyUI restart; enabled rows mark
|
||||||
*"✓ enabled · restart"*.
|
*"✓ enabled · restart"*.
|
||||||
|
|
||||||
The catalog is built once per session by joining ComfyUI Manager's node→pack
|
The catalog is built once per session by joining ComfyUI Manager's node→pack
|
||||||
mappings with the list of disabled packs, and cached; use the **↻** button to
|
mappings with the disabled packs (matched across dir name, registry id, and repo
|
||||||
rebuild it. The palette is inert (with a clear message) when ComfyUI Manager is
|
URL), and cached; use the **↻** button to rebuild it. The palette is inert (with
|
||||||
absent or there are no disabled packages.
|
a clear message) when ComfyUI Manager is absent or there are no disabled packages.
|
||||||
|
|
||||||
**Models tab**
|
**Models tab**
|
||||||
- Summary bar with counts for each tier across all model types
|
- Summary bar with counts for each tier across all model types
|
||||||
@@ -141,6 +166,7 @@ absent or there are no disabled packages.
|
|||||||
| `/nodes-stats/packages` | GET | Per-package aggregated stats with classification |
|
| `/nodes-stats/packages` | GET | Per-package aggregated stats with classification |
|
||||||
| `/nodes-stats/usage` | GET | Raw per-node usage data |
|
| `/nodes-stats/usage` | GET | Raw per-node usage data |
|
||||||
| `/nodes-stats/models` | GET | Per-type model stats with classification |
|
| `/nodes-stats/models` | GET | Per-type model stats with classification |
|
||||||
|
| `/nodes-stats/node-schema` | GET | Parsed input/output schema for one disabled-pack node — query `class_type`, `pack` (read-only AST parse) |
|
||||||
| `/nodes-stats/reset` | POST | Clear all tracked data |
|
| `/nodes-stats/reset` | POST | Clear all tracked data |
|
||||||
| `/nodes-stats/trials` | GET | Active temporary-enable trials with `days_remaining`/`expired` |
|
| `/nodes-stats/trials` | GET | Active temporary-enable trials with `days_remaining`/`expired` |
|
||||||
| `/nodes-stats/trials/start` | POST | Begin/restart a trial — body `{"package": "<dir-name>"}` |
|
| `/nodes-stats/trials/start` | POST | Begin/restart a trial — body `{"package": "<dir-name>"}` |
|
||||||
@@ -262,7 +288,8 @@ timeout so the kernel keeps the listing warm across restarts, e.g.
|
|||||||
__init__.py Entry point: prompt handler, API routes
|
__init__.py Entry point: prompt handler, API routes
|
||||||
mapper.py class_type → package mapping; model filename → type mapping
|
mapper.py class_type → package mapping; model filename → type mapping
|
||||||
tracker.py SQLite persistence and stats aggregation
|
tracker.py SQLite persistence and stats aggregation
|
||||||
js/nodes_stats.js Frontend: menu button + stats dialog (Nodes/Models/Workflow tabs)
|
node_introspect.py Read-only AST parse of disabled packs → node input/output schema
|
||||||
|
js/nodes_stats.js Frontend: menu button + stats dialog (Nodes/Models/Workflow tabs) + mirror search
|
||||||
tools/diagnose_model_scan.py Standalone: diagnose slow model-folder scans at boot
|
tools/diagnose_model_scan.py Standalone: diagnose slow model-folder scans at boot
|
||||||
pyproject.toml Package metadata
|
pyproject.toml Package metadata
|
||||||
tests/ Unit tests for tracker and mapper
|
tests/ Unit tests for tracker and mapper
|
||||||
|
|||||||
+124
@@ -1,3 +1,4 @@
|
|||||||
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
import threading
|
import threading
|
||||||
|
|
||||||
@@ -5,6 +6,8 @@ from aiohttp import web
|
|||||||
from server import PromptServer
|
from server import PromptServer
|
||||||
|
|
||||||
from .mapper import NodePackageMapper, ModelMapper
|
from .mapper import NodePackageMapper, ModelMapper
|
||||||
|
from .node_introspect import find_disabled_pack_path, get_node_schema
|
||||||
|
from .pack_fs import disable_pack_native, enable_pack_native, list_disabled_packs
|
||||||
from .tracker import UsageTracker
|
from .tracker import UsageTracker
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -115,6 +118,127 @@ async def reset_stats(request):
|
|||||||
return web.json_response({"error": "internal error"}, status=500)
|
return web.json_response({"error": "internal error"}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
@routes.get("/nodes-stats/node-schema")
|
||||||
|
async def get_node_schema_route(request):
|
||||||
|
"""Parse a disabled pack's source and return one node's input/output schema.
|
||||||
|
|
||||||
|
Read-only and never imports/executes the pack. Used by the mirror-search
|
||||||
|
palette to draw a faithful node box for a node that isn't loaded.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
class_type = request.query.get("class_type")
|
||||||
|
pack = request.query.get("pack")
|
||||||
|
if not class_type or not pack:
|
||||||
|
return web.json_response({"error": "class_type and pack required"}, status=400)
|
||||||
|
|
||||||
|
def _resolve():
|
||||||
|
path = find_disabled_pack_path(pack)
|
||||||
|
if not path:
|
||||||
|
return {"parseable": False, "reason": "source_not_found"}
|
||||||
|
return get_node_schema(class_type, path)
|
||||||
|
|
||||||
|
# AST-parsing a whole pack can take tens of ms; keep it off the event loop.
|
||||||
|
schema = await asyncio.get_event_loop().run_in_executor(None, _resolve)
|
||||||
|
return web.json_response(schema)
|
||||||
|
except Exception:
|
||||||
|
logger.error("nodes-stats: error parsing node schema", exc_info=True)
|
||||||
|
return web.json_response({"error": "internal error"}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
@routes.post("/nodes-stats/native-disable")
|
||||||
|
async def native_disable(request):
|
||||||
|
"""Disable a pack by moving it into custom_nodes/.disabled/ (no Manager).
|
||||||
|
|
||||||
|
Fallback for packs ComfyUI Manager doesn't manage. A restart is required for
|
||||||
|
ComfyUI to unload the pack.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
data = await request.json()
|
||||||
|
package = data.get("package")
|
||||||
|
if not package:
|
||||||
|
return web.json_response({"error": "package required"}, status=400)
|
||||||
|
|
||||||
|
ok, message = await asyncio.get_event_loop().run_in_executor(
|
||||||
|
None, disable_pack_native, package
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
return web.json_response({"status": "error", "message": message}, status=409)
|
||||||
|
mapper.invalidate()
|
||||||
|
return web.json_response({"status": "ok", "message": message})
|
||||||
|
except Exception:
|
||||||
|
logger.error("nodes-stats: error in native disable", exc_info=True)
|
||||||
|
return web.json_response({"error": "internal error"}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
@routes.post("/nodes-stats/native-enable")
|
||||||
|
async def native_enable(request):
|
||||||
|
"""Re-enable a pack by moving it out of custom_nodes/.disabled/ (no Manager)."""
|
||||||
|
try:
|
||||||
|
data = await request.json()
|
||||||
|
package = data.get("package")
|
||||||
|
if not package:
|
||||||
|
return web.json_response({"error": "package required"}, status=400)
|
||||||
|
|
||||||
|
ok, message = await asyncio.get_event_loop().run_in_executor(
|
||||||
|
None, enable_pack_native, package
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
return web.json_response({"status": "error", "message": message}, status=409)
|
||||||
|
mapper.invalidate()
|
||||||
|
return web.json_response({"status": "ok", "message": message})
|
||||||
|
except Exception:
|
||||||
|
logger.error("nodes-stats: error in native enable", exc_info=True)
|
||||||
|
return web.json_response({"error": "internal error"}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
@routes.get("/nodes-stats/disabled-packs")
|
||||||
|
async def get_disabled_packs(request):
|
||||||
|
"""List packs present in custom_nodes/.disabled/ (re-enable candidates)."""
|
||||||
|
try:
|
||||||
|
names = await asyncio.get_event_loop().run_in_executor(None, list_disabled_packs)
|
||||||
|
return web.json_response(sorted(names))
|
||||||
|
except Exception:
|
||||||
|
logger.error("nodes-stats: error listing disabled packs", exc_info=True)
|
||||||
|
return web.json_response({"error": "internal error"}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
@routes.get("/nodes-stats/whitelist")
|
||||||
|
async def get_whitelist(request):
|
||||||
|
try:
|
||||||
|
return web.json_response(sorted(tracker.get_whitelist()))
|
||||||
|
except Exception:
|
||||||
|
logger.error("nodes-stats: error getting whitelist", exc_info=True)
|
||||||
|
return web.json_response({"error": "internal error"}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
@routes.post("/nodes-stats/whitelist/add")
|
||||||
|
async def whitelist_add(request):
|
||||||
|
try:
|
||||||
|
data = await request.json()
|
||||||
|
package = data.get("package")
|
||||||
|
if not package:
|
||||||
|
return web.json_response({"error": "package required"}, status=400)
|
||||||
|
tracker.add_to_whitelist(package)
|
||||||
|
return web.json_response({"status": "ok"})
|
||||||
|
except Exception:
|
||||||
|
logger.error("nodes-stats: error adding to whitelist", exc_info=True)
|
||||||
|
return web.json_response({"error": "internal error"}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
@routes.post("/nodes-stats/whitelist/remove")
|
||||||
|
async def whitelist_remove(request):
|
||||||
|
try:
|
||||||
|
data = await request.json()
|
||||||
|
package = data.get("package")
|
||||||
|
if not package:
|
||||||
|
return web.json_response({"error": "package required"}, status=400)
|
||||||
|
tracker.remove_from_whitelist(package)
|
||||||
|
return web.json_response({"status": "ok"})
|
||||||
|
except Exception:
|
||||||
|
logger.error("nodes-stats: error removing from whitelist", exc_info=True)
|
||||||
|
return web.json_response({"error": "internal error"}, status=500)
|
||||||
|
|
||||||
|
|
||||||
@routes.get("/nodes-stats/trials")
|
@routes.get("/nodes-stats/trials")
|
||||||
async def get_trials(request):
|
async def get_trials(request):
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# Design: Trial-install (7-day) for missing nodes on workflow load
|
||||||
|
|
||||||
|
Date: 2026-06-22
|
||||||
|
Status: Approved
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
Extend the existing 7-day rolling trial from *disabled* packages to *missing*
|
||||||
|
(not-installed) ones. When a loaded workflow references node types whose owning
|
||||||
|
pack isn't installed, the Workflow tab's **Missing** section gains:
|
||||||
|
|
||||||
|
- **Install 7d** — really install the pack via ComfyUI Manager, then register a
|
||||||
|
7-day trial. If it isn't used (executed) within 7 distinct boot-days, it
|
||||||
|
auto-disables (moves to `.disabled`, reversible) via the existing expiry path.
|
||||||
|
- **Install** — really install the pack permanently (no trial).
|
||||||
|
|
||||||
|
This makes trying out someone else's workflow non-committal: pull in what it
|
||||||
|
needs, and anything you don't actually use gets parked in `.disabled` instead of
|
||||||
|
permanently bloating the install (which slows boot — the whole point of this
|
||||||
|
extension).
|
||||||
|
|
||||||
|
## Decisions (from clarification)
|
||||||
|
|
||||||
|
- **Expiry action:** auto-**disable** (not uninstall). This is free: the trial
|
||||||
|
table is keyed by package and `processExpiredTrials()` already disables any
|
||||||
|
expired trial pack and clears its row. No new expiry code.
|
||||||
|
- **Missing-row actions:** both **Install 7d** and **Install** (permanent),
|
||||||
|
symmetric with the Disabled section's Enable 7d / Enable. Both perform real
|
||||||
|
installs from our UI; the current "open ComfyUI Manager" behavior becomes the
|
||||||
|
failure fallback.
|
||||||
|
|
||||||
|
## Current state it builds on (v1.6.0, verified)
|
||||||
|
|
||||||
|
- `tracker.py`: `trial_packages` table + `start_trial` / `tick_boot_days` /
|
||||||
|
`reset_trials_for` / `stop_trial` / `get_trials`. Boot tick + usage reset +
|
||||||
|
routes (`/nodes-stats/trials[/start|/stop]`) wired in `__init__.py`.
|
||||||
|
- `js/nodes_stats.js`:
|
||||||
|
- `classifyUnresolved()` (≈624) → `{ disabled[], missing[] }`; missing entries
|
||||||
|
are `{ type, pkg: <getmappings packKey> }` where packKey is a dir name,
|
||||||
|
registry id, or repo/gist URL.
|
||||||
|
- `handleInstall(pkg, dialog)` (≈1155) currently only opens Manager's Custom
|
||||||
|
Nodes Manager.
|
||||||
|
- `runManagerEnable(payload)` (≈701) = reset → POST `/manager/queue/install`
|
||||||
|
→ start → `waitForQueue` (install and enable share this endpoint; only the
|
||||||
|
payload differs).
|
||||||
|
- `processExpiredTrials()` (≈1192) disables expired trial packs via Manager,
|
||||||
|
then `stopTrial`.
|
||||||
|
- `fetchManagerInfo()` (≈483) returns installed/disabled packs only — it
|
||||||
|
**skips** `state==="not-installed"`, so registry data for missing packs is
|
||||||
|
not in hand and must be fetched separately.
|
||||||
|
|
||||||
|
## Install resolution (the only real new logic)
|
||||||
|
|
||||||
|
Not-installed `getlist` entries expose enough to install (verified live):
|
||||||
|
|
||||||
|
- CNR pack: `id` = cnr_id, `version` = semver, `files` = `[git url]`.
|
||||||
|
- Git-only pack: no `id`, `version` = `"unknown"`, `files` = `[git url]`.
|
||||||
|
|
||||||
|
Plan:
|
||||||
|
|
||||||
|
1. **`resolveInstallTarget(packKey)`** — fetch
|
||||||
|
`/customnode/getlist?mode=local&skip_update=true`, index `not-installed`
|
||||||
|
entries by every identifier (key, `id`, `files`, `repository`) with the same
|
||||||
|
normalize used in `classifyUnresolved` (lowercase, strip trailing `/`,
|
||||||
|
`.git`), and return the matching entry (or null).
|
||||||
|
2. **`installPayload(entry)`** — mirror Manager's installNodes:
|
||||||
|
`{ id: entry.id || <key>, version: entry.version, files: entry.files,
|
||||||
|
channel:"default", mode:"cache", selected_version: entry.version==="unknown"
|
||||||
|
? "unknown" : "latest", skip_post_install:false, ui_id:<key> }`.
|
||||||
|
3. Install via the existing `runManagerEnable(payload)` (same queue endpoint).
|
||||||
|
4. **`findInstalledDir(entry)`** — re-fetch getlist; find the now-installed entry
|
||||||
|
matching `entry` by id/files/repo; its **key is the directory name** (needed
|
||||||
|
to key the trial). Fallback: repo basename of `files[0]` (strip `.git`).
|
||||||
|
5. For Install 7d: `POST /nodes-stats/trials/start { package: <dir name> }`.
|
||||||
|
6. Show the restart banner: "Installed X — restart to load it" (+ " for a 7-day
|
||||||
|
trial").
|
||||||
|
|
||||||
|
## Components (all in `js/nodes_stats.js`)
|
||||||
|
|
||||||
|
- `resolveInstallTarget(packKey)`, `installPayload(entry)`, `findInstalledDir(entry)`
|
||||||
|
— small, mostly-pure helpers.
|
||||||
|
- `handleTrialInstall(pkg, dialog, temporary)` — orchestrates resolve → install →
|
||||||
|
dir discovery → (trial start if temporary) → restart banner; on any failure
|
||||||
|
falls back to the existing open-Manager behavior of `handleInstall`.
|
||||||
|
- Missing rows render `[Install 7d]` + `[Install]`; wire them in
|
||||||
|
`wireWorkflowButtons`. Reuse `setWorkflowButtonsBusy`, `notify`,
|
||||||
|
`showRestartBanner`, `managerIsBusy`.
|
||||||
|
|
||||||
|
## Data flow
|
||||||
|
|
||||||
|
```
|
||||||
|
Workflow tab (missing row)
|
||||||
|
Install 7d -> resolveInstallTarget(packKey) -> installPayload
|
||||||
|
-> runManagerEnable (POST install, start, wait)
|
||||||
|
-> findInstalledDir -> trials/start{dir}
|
||||||
|
-> restart banner "installed for 7-day trial"
|
||||||
|
Install -> same, minus trials/start
|
||||||
|
later boots -> tracker.tick_boot_days (distinct days)
|
||||||
|
use in prompt-> tracker.reset_trials_for (counter -> 0)
|
||||||
|
expiry -> processExpiredTrials (UI load) -> Manager disable + stopTrial
|
||||||
|
```
|
||||||
|
|
||||||
|
## Error handling
|
||||||
|
|
||||||
|
- ComfyUI Manager absent → Missing actions inert (as today).
|
||||||
|
- `resolveInstallTarget` miss, install HTTP error, or git-url install blocked by
|
||||||
|
Manager security level → toast + fall back to `handleInstall`'s open-Manager
|
||||||
|
guidance. No crash.
|
||||||
|
- `findInstalledDir` returns nothing (install didn't land) → don't register a
|
||||||
|
trial; toast "installed; couldn't register trial — enable/disable manually".
|
||||||
|
- `managerIsBusy()` → ask the user to retry (same guard as enable/disable).
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
- Backend unchanged → no new pytest; existing `tests/` stays green.
|
||||||
|
- Pure helpers (`resolveInstallTarget` matching, `installPayload`,
|
||||||
|
`findInstalledDir` matching) written standalone; `node --check` for syntax.
|
||||||
|
- Manual: load a workflow needing a not-installed CNR pack → Install 7d installs
|
||||||
|
it, `/nodes-stats/trials` shows the resulting dir, restart banner appears;
|
||||||
|
Install (permanent) installs without a trial row; a git-url-only/blocked pack
|
||||||
|
falls back to opening Manager; Manager-absent path inert.
|
||||||
|
|
||||||
|
## Files touched
|
||||||
|
|
||||||
|
- `js/nodes_stats.js` — resolution helpers, `handleTrialInstall`, Missing-row
|
||||||
|
buttons + wiring.
|
||||||
|
- `README.md`, `pyproject.toml` — docs + version bump (1.6.0 → 1.7.0).
|
||||||
|
|
||||||
|
## Out of scope (YAGNI)
|
||||||
|
|
||||||
|
- Auto-uninstall on expiry (chose disable; reversible + free).
|
||||||
|
- Bulk "install all missing 7d" (start per-row; revisit if wanted).
|
||||||
|
- Replicating Manager's full dependency/security UX (fall back to Manager).
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
# 7-Day Trial-Install for Missing Nodes — Implementation Plan
|
||||||
|
|
||||||
|
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||||
|
|
||||||
|
**Goal:** Let the Workflow tab really install a workflow's missing (not-installed) packs — either permanently or on the existing 7-day rolling trial that auto-disables unused packs.
|
||||||
|
|
||||||
|
**Architecture:** Frontend-only (`js/nodes_stats.js`). Resolve a missing pack's install spec from its not-installed `getlist` entry, install via ComfyUI Manager's queue (reusing `runManagerEnable`, which posts to `/manager/queue/install`), discover the resulting directory name by re-reading `getlist`, and register a trial via the existing `/nodes-stats/trials/start`. Expiry (auto-disable) is already handled by `processExpiredTrials()` — no new expiry code. On any failure, fall back to the current open-Manager behavior.
|
||||||
|
|
||||||
|
**Tech Stack:** Vanilla JS ComfyUI extension; ComfyUI Manager HTTP endpoints; the trial machinery already shipped in v1.6.0.
|
||||||
|
|
||||||
|
**Design doc:** `docs/plans/2026-06-22-trial-install-design.md`
|
||||||
|
|
||||||
|
**Testing note:** No JS test harness. After every edit run:
|
||||||
|
`cp js/nodes_stats.js /tmp/c.mjs && node --check /tmp/c.mjs && echo OK && rm /tmp/c.mjs`
|
||||||
|
Behavior is verified manually in ComfyUI (hard-refresh after each change).
|
||||||
|
|
||||||
|
**Confirmed reuse points (v1.6.0, real line numbers):** `classifyUnresolved` (≈624, builds `missing[]`), `buildWorkflowTabContent` Missing section (≈410-422), `wireWorkflowButtons` (≈698), `handleInstall` (≈1155, open-Manager fallback), `runManagerEnable` (≈701, install-queue helper), `processExpiredTrials` (≈1192), `setWorkflowButtonsBusy` (≈1172), `managerIsBusy`, `showRestartBanner`, `notify`, `escapeHtml`, `escapeAttr`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 1: Shared `normKey` + install-resolution helpers
|
||||||
|
|
||||||
|
**Files:** Modify `js/nodes_stats.js` (add helpers near `classifyUnresolved`, ~line 620).
|
||||||
|
|
||||||
|
**Step 1: Add a module-level `normKey`** (and point `classifyUnresolved`'s local `norm` at it for DRY):
|
||||||
|
|
||||||
|
```js
|
||||||
|
// Normalize an identifier (dir name, registry id, or repo URL) for matching.
|
||||||
|
function normKey(s) {
|
||||||
|
return String(s).trim().replace(/\/+$/, "").replace(/\.git$/i, "").toLowerCase();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
In `classifyUnresolved`, replace the local
|
||||||
|
`const norm = (s) => String(s).trim().replace(/\/+$/, "").replace(/\.git$/i, "").toLowerCase();`
|
||||||
|
with `const norm = normKey;`.
|
||||||
|
|
||||||
|
**Step 2: Add the resolver, payload builder, and dir finder:**
|
||||||
|
|
||||||
|
```js
|
||||||
|
// Find the not-installed getlist entry for a missing pack key (from getmappings).
|
||||||
|
// Returns { key, id?, version, files, repository, ... } or null.
|
||||||
|
async function resolveInstallTarget(packKey) {
|
||||||
|
let packs;
|
||||||
|
try {
|
||||||
|
const r = await fetch("/customnode/getlist?mode=local&skip_update=true");
|
||||||
|
if (!r.ok) return null;
|
||||||
|
packs = (await r.json()).node_packs;
|
||||||
|
} catch { return null; }
|
||||||
|
if (!packs) return null;
|
||||||
|
const want = normKey(packKey);
|
||||||
|
for (const [key, v] of Object.entries(packs)) {
|
||||||
|
if (!v || v.state !== "not-installed") continue;
|
||||||
|
const ids = [key, v.id, v.repository, ...(v.files || [])].filter(Boolean).map(normKey);
|
||||||
|
if (ids.includes(want)) return { key, ...v };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build the /manager/queue/install payload, mirroring Manager's installNodes.
|
||||||
|
function installPayload(entry, packKey) {
|
||||||
|
const unknown = !entry.version || entry.version === "unknown";
|
||||||
|
const id = entry.id || packKey;
|
||||||
|
return {
|
||||||
|
id, version: entry.version || "unknown", files: entry.files,
|
||||||
|
channel: "default", mode: "cache",
|
||||||
|
selected_version: unknown ? "unknown" : "latest",
|
||||||
|
skip_post_install: false, ui_id: id,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// After install, find the now-installed directory name (the trial key) by
|
||||||
|
// re-reading getlist and matching the entry; fall back to the repo basename.
|
||||||
|
async function findInstalledDir(entry) {
|
||||||
|
let packs = null;
|
||||||
|
try {
|
||||||
|
const r = await fetch("/customnode/getlist?mode=local&skip_update=true");
|
||||||
|
if (r.ok) packs = (await r.json()).node_packs;
|
||||||
|
} catch { /* fall through to basename */ }
|
||||||
|
if (packs) {
|
||||||
|
const want = [entry.id, entry.repository, ...(entry.files || [])].filter(Boolean).map(normKey);
|
||||||
|
for (const [key, v] of Object.entries(packs)) {
|
||||||
|
if (!v || v.state === "not-installed") continue;
|
||||||
|
const cand = [key, v.id, v.repository, ...(v.files || [])].filter(Boolean).map(normKey);
|
||||||
|
if (cand.some((c) => want.includes(c))) return key; // key = directory name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const url = (entry.files && entry.files[0]) || entry.repository || "";
|
||||||
|
return url.replace(/\/+$/, "").replace(/\.git$/i, "").split("/").pop() || null;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 3: Verify syntax** — run the `node --check` line. Expected `OK`.
|
||||||
|
|
||||||
|
**Step 4: Verify resolver (browser console, after hard-refresh)** — pick a known not-installed pack key from `await (await fetch('/customnode/getlist?mode=local&skip_update=true')).json()` and confirm `resolveInstallTarget(key)` returns it. Expected: the entry with `files`/`version`.
|
||||||
|
|
||||||
|
**Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add js/nodes_stats.js
|
||||||
|
git commit -m "feat(install): install-target resolution helpers for missing packs"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 2: `handleTrialInstall` orchestrator
|
||||||
|
|
||||||
|
**Files:** Modify `js/nodes_stats.js` (add next to `handleInstall`, ~line 1155).
|
||||||
|
|
||||||
|
**Step 1: Add the orchestrator** (keep `handleInstall` as the fallback):
|
||||||
|
|
||||||
|
```js
|
||||||
|
// Real install of a missing pack, optionally on a 7-day trial. Resolves the
|
||||||
|
// install spec, installs via Manager, discovers the resulting directory, and
|
||||||
|
// (for a trial) registers it. Falls back to opening Manager on any failure.
|
||||||
|
async function handleTrialInstall(pkg, dialog, temporary) {
|
||||||
|
if (await managerIsBusy()) {
|
||||||
|
notify("ComfyUI Manager is busy. Please try again in a moment.", "warn");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const target = await resolveInstallTarget(pkg);
|
||||||
|
if (!target) { await handleInstall(pkg, dialog); return; }
|
||||||
|
|
||||||
|
setWorkflowButtonsBusy(dialog, true);
|
||||||
|
try {
|
||||||
|
await runManagerEnable(installPayload(target, pkg)); // shared /manager/queue/install flow
|
||||||
|
const dir = temporary ? await findInstalledDir(target) : null;
|
||||||
|
if (temporary && dir) {
|
||||||
|
await fetch("/nodes-stats/trials/start", {
|
||||||
|
method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ package: dir }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
showRestartBanner(dialog);
|
||||||
|
if (temporary && !dir) {
|
||||||
|
notify(`Installed ${pkg}, but couldn't register the trial — manage it manually. Restart to load.`, "warn");
|
||||||
|
} else {
|
||||||
|
notify(`Installed ${pkg}${temporary ? " for a 7-day trial" : ""}. Restart ComfyUI to load it.`, "success");
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
notify("Install failed: " + e.message + " — opening ComfyUI Manager.", "warn");
|
||||||
|
await handleInstall(pkg, dialog);
|
||||||
|
} finally {
|
||||||
|
setWorkflowButtonsBusy(dialog, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 2: Verify syntax** — `node --check`. Expected `OK`.
|
||||||
|
|
||||||
|
**Step 3: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add js/nodes_stats.js
|
||||||
|
git commit -m "feat(install): handleTrialInstall orchestrator with Manager fallback"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 3: Missing rows — `Install 7d` + `Install` buttons
|
||||||
|
|
||||||
|
**Files:** Modify `js/nodes_stats.js` — `buildWorkflowTabContent` Missing section (~410-422).
|
||||||
|
|
||||||
|
**Step 1: Update the subtitle and the action cell.** Replace the section header subtitle "Not installed — install via ComfyUI Manager" with "Not installed — install, optionally on a 7-day trial", and replace the single-button cell:
|
||||||
|
|
||||||
|
```js
|
||||||
|
<td style="padding:6px 8px;text-align:right;white-space:nowrap;">
|
||||||
|
${m.pkg
|
||||||
|
? `<button class="ns-btn ns-install-temp-btn" data-pkg="${escapeAttr(m.pkg)}">Install 7d</button>
|
||||||
|
<button class="ns-btn ns-install-perm-btn" data-pkg="${escapeAttr(m.pkg)}" style="margin-left:6px;">Install</button>`
|
||||||
|
: "—"}
|
||||||
|
</td>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 2: Verify syntax** — `node --check`. Expected `OK`.
|
||||||
|
|
||||||
|
**Step 3: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add js/nodes_stats.js
|
||||||
|
git commit -m "feat(install): Missing rows offer Install 7d + Install"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 4: Wire the new buttons + busy state
|
||||||
|
|
||||||
|
**Files:** Modify `js/nodes_stats.js` — `wireWorkflowButtons` (~698) and `setWorkflowButtonsBusy` (~1172).
|
||||||
|
|
||||||
|
**Step 1:** In `wireWorkflowButtons`, replace the `.ns-install-btn` wiring with:
|
||||||
|
|
||||||
|
```js
|
||||||
|
dialog.querySelectorAll(".ns-install-temp-btn").forEach((b) =>
|
||||||
|
b.addEventListener("click", (e) => { e.stopPropagation(); handleTrialInstall(b.dataset.pkg, dialog, true); }));
|
||||||
|
dialog.querySelectorAll(".ns-install-perm-btn").forEach((b) =>
|
||||||
|
b.addEventListener("click", (e) => { e.stopPropagation(); handleTrialInstall(b.dataset.pkg, dialog, false); }));
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 2:** In `setWorkflowButtonsBusy`, update the selector to the new classes:
|
||||||
|
|
||||||
|
```js
|
||||||
|
dialog.querySelectorAll(".ns-enable-temp-btn, .ns-enable-perm-btn, .ns-install-temp-btn, .ns-install-perm-btn").forEach((b) => {
|
||||||
|
b.disabled = busy;
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 3: Verify syntax** — `node --check`. Expected `OK`.
|
||||||
|
|
||||||
|
**Step 4: Verify (manual)** — hard-refresh; load a workflow that needs a not-installed **CNR** pack (small one, e.g. a simple utility pack). Click **Install 7d** → it installs, restart banner appears, and `await (await fetch('/nodes-stats/trials')).json()` lists the installed dir. Click **Install** on another → installs, no trial row. Try a pack that fails / git-url-blocked → falls back to opening Manager with a toast.
|
||||||
|
|
||||||
|
**Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add js/nodes_stats.js
|
||||||
|
git commit -m "feat(install): wire Install 7d / Install buttons"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 5: Docs + version bump
|
||||||
|
|
||||||
|
**Files:** Modify `README.md`, `pyproject.toml`.
|
||||||
|
|
||||||
|
**Step 1:** In the README's Workflow-tab section, document that Missing nodes can now be installed permanently or on a 7-day trial (auto-disables if unused, takes effect after restart, falls back to ComfyUI Manager on failure). Update any feature bullet.
|
||||||
|
|
||||||
|
**Step 2:** Bump `version` in `pyproject.toml` from `1.6.0` to `1.7.0`.
|
||||||
|
|
||||||
|
**Step 3: Verify** — `python -m pytest -q` (unchanged, green) and the `node --check` line (`OK`).
|
||||||
|
|
||||||
|
**Step 4: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add README.md pyproject.toml
|
||||||
|
git commit -m "docs: document 7-day trial-install for missing nodes; bump to 1.7.0"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Done criteria
|
||||||
|
|
||||||
|
- Workflow tab Missing rows show **Install 7d** and **Install**.
|
||||||
|
- Install 7d really installs the pack (CNR via registry; git-url where Manager allows) and registers a trial keyed by the installed directory; Install does the same without a trial.
|
||||||
|
- Unused trial-installed packs auto-disable on a later UI load via the existing `processExpiredTrials` (no new expiry code); using one resets its 7-day counter.
|
||||||
|
- Failures (unresolvable spec, HTTP error, git-url blocked, Manager absent) fall back to opening ComfyUI Manager — no crash.
|
||||||
|
- `python -m pytest -q` green; `node --check` clean.
|
||||||
|
```
|
||||||
+707
-95
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,287 @@
|
|||||||
|
"""Static (no-execution) introspection of disabled custom-node packages.
|
||||||
|
|
||||||
|
The mirror-search palette previews nodes that belong to *disabled* packs. Those
|
||||||
|
packs aren't imported by ComfyUI, so their INPUT_TYPES / RETURN_TYPES are not in
|
||||||
|
/object_info. To draw a faithful node box we parse the pack's Python source with
|
||||||
|
``ast`` — we never import or execute it (importing a disabled pack could have
|
||||||
|
side effects, pull heavy deps, or fail). This yields real inputs/outputs for the
|
||||||
|
~75% of packs that declare a literal ``NODE_CLASS_MAPPINGS``; packs that build
|
||||||
|
their mappings dynamically simply report ``parseable: False`` and the frontend
|
||||||
|
falls back to a placeholder box.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import ast
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import warnings
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Input "types" that ComfyUI renders as in-node widgets rather than sockets.
|
||||||
|
_WIDGET_TYPES = {"INT", "FLOAT", "STRING", "BOOLEAN", "BOOL"}
|
||||||
|
|
||||||
|
# Cache parsed pack indexes for the session, keyed by source path. Disabled
|
||||||
|
# packs don't change while ComfyUI runs, so we never invalidate.
|
||||||
|
_INDEX_CACHE = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _const_str(node):
|
||||||
|
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
||||||
|
return node.value
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_file(path):
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8", errors="ignore") as fh:
|
||||||
|
src = fh.read()
|
||||||
|
# Third-party sources often contain unescaped regex strings; ast.parse
|
||||||
|
# emits SyntaxWarning for those. Suppress to keep server logs clean.
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.simplefilter("ignore")
|
||||||
|
return ast.parse(src)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _iter_py_files(root, limit=500):
|
||||||
|
"""Yield up to ``limit`` .py files under a pack dir (or the file itself)."""
|
||||||
|
if os.path.isfile(root):
|
||||||
|
if root.endswith(".py"):
|
||||||
|
yield root
|
||||||
|
return
|
||||||
|
count = 0
|
||||||
|
for dirpath, dirnames, filenames in os.walk(root):
|
||||||
|
dirnames[:] = [
|
||||||
|
d for d in dirnames
|
||||||
|
if not d.startswith(".") and d not in ("__pycache__", "node_modules", "js", "web", "dist")
|
||||||
|
]
|
||||||
|
for fn in filenames:
|
||||||
|
if fn.endswith(".py"):
|
||||||
|
yield os.path.join(dirpath, fn)
|
||||||
|
count += 1
|
||||||
|
if count >= limit:
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
def _string_tuple(node):
|
||||||
|
"""A RETURN_TYPES / RETURN_NAMES value -> list of strings ("*" for non-literal)."""
|
||||||
|
if isinstance(node, (ast.Tuple, ast.List)):
|
||||||
|
out = []
|
||||||
|
for e in node.elts:
|
||||||
|
s = _const_str(e)
|
||||||
|
out.append(s if s is not None else "*")
|
||||||
|
return out
|
||||||
|
s = _const_str(node)
|
||||||
|
return [s] if s is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_input_def(name, val):
|
||||||
|
"""One INPUT_TYPES entry -> {name, type, widget, default, options}."""
|
||||||
|
d = {"name": name, "type": "*", "widget": False, "default": None, "options": None}
|
||||||
|
type_node, opts_node = None, None
|
||||||
|
if isinstance(val, (ast.Tuple, ast.List)) and val.elts:
|
||||||
|
type_node = val.elts[0]
|
||||||
|
if len(val.elts) > 1:
|
||||||
|
opts_node = val.elts[1]
|
||||||
|
else:
|
||||||
|
type_node = val
|
||||||
|
|
||||||
|
s = _const_str(type_node)
|
||||||
|
if s is not None:
|
||||||
|
d["type"] = s
|
||||||
|
if s.upper() in _WIDGET_TYPES:
|
||||||
|
d["widget"] = True
|
||||||
|
elif isinstance(type_node, (ast.List, ast.Tuple)):
|
||||||
|
# Inline combo box: ["a", "b", ...]
|
||||||
|
opts = [_const_str(e) for e in type_node.elts]
|
||||||
|
opts = [o for o in opts if o is not None]
|
||||||
|
d["type"] = "COMBO"
|
||||||
|
d["widget"] = True
|
||||||
|
d["options"] = opts or None
|
||||||
|
elif isinstance(type_node, ast.Call):
|
||||||
|
# Dynamic list, e.g. folder_paths.get_filename_list(...) -> dropdown widget.
|
||||||
|
d["type"] = "COMBO"
|
||||||
|
d["widget"] = True
|
||||||
|
# else: a Name/Attribute (custom or wildcard socket type) -> keep "*", socket.
|
||||||
|
|
||||||
|
if isinstance(opts_node, ast.Dict):
|
||||||
|
for ok, ov in zip(opts_node.keys, opts_node.values):
|
||||||
|
if _const_str(ok) == "default":
|
||||||
|
try:
|
||||||
|
d["default"] = ast.literal_eval(ov)
|
||||||
|
except Exception:
|
||||||
|
d["default"] = _const_str(ov)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_input_types(fn):
|
||||||
|
"""The INPUT_TYPES classmethod -> {"required": [...], "optional": [...]} or None."""
|
||||||
|
ret = None
|
||||||
|
for n in ast.walk(fn):
|
||||||
|
if isinstance(n, ast.Return) and isinstance(n.value, ast.Dict):
|
||||||
|
ret = n.value
|
||||||
|
break
|
||||||
|
if ret is None:
|
||||||
|
return None
|
||||||
|
result = {"required": [], "optional": []}
|
||||||
|
for cat_key, cat_val in zip(ret.keys, ret.values):
|
||||||
|
cat = _const_str(cat_key)
|
||||||
|
if cat not in ("required", "optional") or not isinstance(cat_val, ast.Dict):
|
||||||
|
continue
|
||||||
|
for nk, nv in zip(cat_val.keys, cat_val.values):
|
||||||
|
name = _const_str(nk)
|
||||||
|
if name is not None:
|
||||||
|
result[cat].append(_extract_input_def(name, nv))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_class(cls):
|
||||||
|
info = {"input_types": None, "return_types": None, "return_names": None,
|
||||||
|
"category": None, "output_node": False}
|
||||||
|
for b in cls.body:
|
||||||
|
if isinstance(b, (ast.FunctionDef, ast.AsyncFunctionDef)) and b.name == "INPUT_TYPES":
|
||||||
|
info["input_types"] = _extract_input_types(b)
|
||||||
|
elif isinstance(b, ast.Assign):
|
||||||
|
for t in b.targets:
|
||||||
|
tn = getattr(t, "id", None)
|
||||||
|
if tn == "RETURN_TYPES":
|
||||||
|
info["return_types"] = _string_tuple(b.value)
|
||||||
|
elif tn == "RETURN_NAMES":
|
||||||
|
info["return_names"] = _string_tuple(b.value)
|
||||||
|
elif tn == "CATEGORY":
|
||||||
|
info["category"] = _const_str(b.value)
|
||||||
|
elif tn == "OUTPUT_NODE" and isinstance(b.value, ast.Constant):
|
||||||
|
info["output_node"] = bool(b.value.value)
|
||||||
|
return info
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_mapping(out, dictnode):
|
||||||
|
if not isinstance(dictnode, ast.Dict):
|
||||||
|
return
|
||||||
|
for k, v in zip(dictnode.keys, dictnode.values):
|
||||||
|
key = _const_str(k)
|
||||||
|
if key is None:
|
||||||
|
continue
|
||||||
|
if isinstance(v, ast.Name):
|
||||||
|
out[key] = v.id
|
||||||
|
elif isinstance(v, ast.Call) and isinstance(v.func, ast.Name):
|
||||||
|
out[key] = v.func.id
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_display(out, dictnode):
|
||||||
|
if not isinstance(dictnode, ast.Dict):
|
||||||
|
return
|
||||||
|
for k, v in zip(dictnode.keys, dictnode.values):
|
||||||
|
key, val = _const_str(k), _const_str(v)
|
||||||
|
if key is not None and val is not None:
|
||||||
|
out[key] = val
|
||||||
|
|
||||||
|
|
||||||
|
def build_pack_index(pack_path):
|
||||||
|
"""Parse a pack -> (classes, mappings, display).
|
||||||
|
|
||||||
|
classes: { ClassName: {input_types, return_types, return_names, category, output_node} }
|
||||||
|
mappings: { node_key: ClassName } (from literal NODE_CLASS_MAPPINGS / .update)
|
||||||
|
display: { node_key: "Pretty Name" }
|
||||||
|
"""
|
||||||
|
cached = _INDEX_CACHE.get(pack_path)
|
||||||
|
if cached is not None:
|
||||||
|
return cached
|
||||||
|
|
||||||
|
classes, mappings, display = {}, {}, {}
|
||||||
|
for f in _iter_py_files(pack_path):
|
||||||
|
tree = _parse_file(f)
|
||||||
|
if tree is None:
|
||||||
|
continue
|
||||||
|
for node in ast.walk(tree):
|
||||||
|
if isinstance(node, ast.ClassDef):
|
||||||
|
classes.setdefault(node.name, _extract_class(node))
|
||||||
|
elif isinstance(node, ast.Assign):
|
||||||
|
for t in node.targets:
|
||||||
|
name = getattr(t, "id", None)
|
||||||
|
if name == "NODE_CLASS_MAPPINGS":
|
||||||
|
_merge_mapping(mappings, node.value)
|
||||||
|
elif name == "NODE_DISPLAY_NAME_MAPPINGS":
|
||||||
|
_merge_display(display, node.value)
|
||||||
|
elif isinstance(node, ast.Call):
|
||||||
|
fn = node.func
|
||||||
|
if (isinstance(fn, ast.Attribute) and fn.attr == "update"
|
||||||
|
and isinstance(fn.value, ast.Name) and node.args
|
||||||
|
and isinstance(node.args[0], ast.Dict)):
|
||||||
|
if fn.value.id == "NODE_CLASS_MAPPINGS":
|
||||||
|
_merge_mapping(mappings, node.args[0])
|
||||||
|
elif fn.value.id == "NODE_DISPLAY_NAME_MAPPINGS":
|
||||||
|
_merge_display(display, node.args[0])
|
||||||
|
|
||||||
|
result = (classes, mappings, display)
|
||||||
|
_INDEX_CACHE[pack_path] = result
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def get_node_schema(class_type, pack_path):
|
||||||
|
"""Return a render-ready schema for one node, or {parseable: False, reason}."""
|
||||||
|
classes, mappings, display = build_pack_index(pack_path)
|
||||||
|
|
||||||
|
cls_name = mappings.get(class_type)
|
||||||
|
if cls_name is None and class_type in classes:
|
||||||
|
cls_name = class_type # fall back: class_type IS the class name
|
||||||
|
if cls_name is None or cls_name not in classes:
|
||||||
|
return {"parseable": False, "reason": "dynamic_mapping" if mappings else "no_mapping"}
|
||||||
|
|
||||||
|
info = classes[cls_name]
|
||||||
|
inputs = []
|
||||||
|
it = info["input_types"]
|
||||||
|
if it:
|
||||||
|
for cat in ("required", "optional"):
|
||||||
|
for d in it[cat]:
|
||||||
|
inputs.append({**d, "required": cat == "required"})
|
||||||
|
|
||||||
|
rt = info["return_types"] or []
|
||||||
|
rn = info["return_names"] or []
|
||||||
|
outputs = []
|
||||||
|
for i, t in enumerate(rt):
|
||||||
|
nm = rn[i] if i < len(rn) and rn[i] else t
|
||||||
|
outputs.append({"name": nm or t, "type": t})
|
||||||
|
|
||||||
|
return {
|
||||||
|
"parseable": True,
|
||||||
|
"class_type": class_type,
|
||||||
|
"display_name": display.get(class_type) or class_type,
|
||||||
|
"category": info["category"],
|
||||||
|
"output_node": info["output_node"],
|
||||||
|
"inputs": inputs,
|
||||||
|
"outputs": outputs,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def find_disabled_pack_path(pack_name):
|
||||||
|
"""Locate a disabled pack's source under any custom_nodes/.disabled/ dir.
|
||||||
|
|
||||||
|
Matches case-insensitively and ignores any ``@version`` suffix that ComfyUI
|
||||||
|
Manager appends on disk (e.g. ``ComfyMath@nightly`` for pack ``comfymath``).
|
||||||
|
Returns an absolute path (dir or .py file) or None. Rejects path-y input.
|
||||||
|
"""
|
||||||
|
if not pack_name or any(c in pack_name for c in ("/", "\\")) or ".." in pack_name:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
import folder_paths
|
||||||
|
roots = folder_paths.get_folder_paths("custom_nodes")
|
||||||
|
except Exception:
|
||||||
|
roots = []
|
||||||
|
|
||||||
|
target = pack_name.lower()
|
||||||
|
for root in roots:
|
||||||
|
ddir = os.path.join(root, ".disabled")
|
||||||
|
if not os.path.isdir(ddir):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
entries = os.listdir(ddir)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
for e in entries:
|
||||||
|
base = e.split("@", 1)[0]
|
||||||
|
stem = base[:-3] if base.endswith(".py") else base
|
||||||
|
if target in (stem.lower(), base.lower()):
|
||||||
|
return os.path.join(ddir, e)
|
||||||
|
return None
|
||||||
+138
@@ -0,0 +1,138 @@
|
|||||||
|
"""Native enable/disable of custom-node packages, independent of ComfyUI Manager.
|
||||||
|
|
||||||
|
Disabling a pack is just a filesystem convention that ComfyUI core honors: a
|
||||||
|
directory (or ``*.py`` file) moved into ``custom_nodes/.disabled/`` is skipped at
|
||||||
|
boot, because core ignores any entry named ``.disabled`` / starting with a dot.
|
||||||
|
Manager uses the same convention. We only *move* files here — never import,
|
||||||
|
delete, or re-clone — so the operation is reversible and safe.
|
||||||
|
|
||||||
|
This is the fallback the extension uses when ComfyUI Manager is absent or does
|
||||||
|
not recognize a pack (a hand-cloned repo, an oddly-installed pack, or a loose
|
||||||
|
single-file node). A restart is required for ComfyUI to pick up the change,
|
||||||
|
exactly as with a Manager disable.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# find_disabled_pack_path already knows how to locate a pack under .disabled/,
|
||||||
|
# including Manager's @version suffix. Import it in a way that works both as a
|
||||||
|
# package (runtime) and as a top-level module (tests add the root to sys.path).
|
||||||
|
try:
|
||||||
|
from .node_introspect import find_disabled_pack_path
|
||||||
|
except ImportError: # pragma: no cover - exercised via top-level import in tests
|
||||||
|
from node_introspect import find_disabled_pack_path
|
||||||
|
|
||||||
|
|
||||||
|
def _custom_node_roots():
|
||||||
|
import folder_paths
|
||||||
|
|
||||||
|
return [os.path.normpath(r) for r in folder_paths.get_folder_paths("custom_nodes")]
|
||||||
|
|
||||||
|
|
||||||
|
def _valid_name(pack_name):
|
||||||
|
"""Reject path-y input; pack names are plain directory/file names."""
|
||||||
|
return bool(pack_name) and not any(c in pack_name for c in ("/", "\\")) and ".." not in pack_name
|
||||||
|
|
||||||
|
|
||||||
|
def list_disabled_packs():
|
||||||
|
"""Return clean names of packs sitting in any custom_nodes/.disabled/ dir.
|
||||||
|
|
||||||
|
Strips a Manager ``@version`` suffix and a ``.py`` extension so the names
|
||||||
|
match package names as reported in the stats (and accepted by
|
||||||
|
``enable_pack_native``).
|
||||||
|
"""
|
||||||
|
names = set()
|
||||||
|
for root in _custom_node_roots():
|
||||||
|
ddir = os.path.join(root, ".disabled")
|
||||||
|
try:
|
||||||
|
entries = os.listdir(ddir)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
for e in entries:
|
||||||
|
if e.startswith("."):
|
||||||
|
continue
|
||||||
|
base = e.split("@", 1)[0]
|
||||||
|
stem = base[:-3] if base.endswith(".py") else base
|
||||||
|
if stem:
|
||||||
|
names.add(stem)
|
||||||
|
return names
|
||||||
|
|
||||||
|
|
||||||
|
def find_active_pack_path(pack_name):
|
||||||
|
"""Locate an installed (active) pack directly under a custom_nodes root.
|
||||||
|
|
||||||
|
Returns an absolute path to the pack directory or single ``.py`` file, or
|
||||||
|
None. Matches case-insensitively and tolerates a Manager ``@version`` suffix.
|
||||||
|
Only real packs (a directory, or a ``.py`` file) qualify.
|
||||||
|
"""
|
||||||
|
if not _valid_name(pack_name):
|
||||||
|
return None
|
||||||
|
target = pack_name.lower()
|
||||||
|
for root in _custom_node_roots():
|
||||||
|
try:
|
||||||
|
entries = os.listdir(root)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
for e in entries:
|
||||||
|
if e.startswith("."):
|
||||||
|
continue
|
||||||
|
base = e.split("@", 1)[0]
|
||||||
|
stem = base[:-3] if base.endswith(".py") else base
|
||||||
|
if target not in (stem.lower(), base.lower(), e.lower()):
|
||||||
|
continue
|
||||||
|
full = os.path.join(root, e)
|
||||||
|
if os.path.isdir(full) or (os.path.isfile(full) and full.endswith(".py")):
|
||||||
|
return os.path.normpath(full)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def disable_pack_native(pack_name):
|
||||||
|
"""Move an active pack into ``custom_nodes/.disabled/``.
|
||||||
|
|
||||||
|
Returns ``(ok, message)``. Never raises for expected conditions (pack not
|
||||||
|
found, collision, permission error); those come back as ``(False, reason)``.
|
||||||
|
"""
|
||||||
|
src = find_active_pack_path(pack_name)
|
||||||
|
if not src:
|
||||||
|
return False, "pack not found on disk"
|
||||||
|
root = os.path.dirname(src)
|
||||||
|
ddir = os.path.join(root, ".disabled")
|
||||||
|
dest = os.path.join(ddir, os.path.basename(src))
|
||||||
|
if os.path.exists(dest):
|
||||||
|
return False, "a disabled copy already exists at " + dest
|
||||||
|
try:
|
||||||
|
os.makedirs(ddir, exist_ok=True)
|
||||||
|
shutil.move(src, dest)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("nodes-stats: native disable failed for %s", pack_name, exc_info=True)
|
||||||
|
return False, str(e)
|
||||||
|
return True, "disabled"
|
||||||
|
|
||||||
|
|
||||||
|
def enable_pack_native(pack_name):
|
||||||
|
"""Move a pack from ``custom_nodes/.disabled/`` back to its root.
|
||||||
|
|
||||||
|
Returns ``(ok, message)``. Drops any Manager ``@version`` suffix from the
|
||||||
|
destination so the pack lands as a clean, importable directory name — the
|
||||||
|
same shape Manager itself restores on enable (``ComfyMath@nightly`` ->
|
||||||
|
``ComfyMath``). A single ``.py`` file keeps its extension.
|
||||||
|
"""
|
||||||
|
src = find_disabled_pack_path(pack_name)
|
||||||
|
if not src:
|
||||||
|
return False, "disabled pack not found"
|
||||||
|
ddir = os.path.dirname(src) # .../custom_nodes/.disabled
|
||||||
|
root = os.path.dirname(ddir) # .../custom_nodes
|
||||||
|
dest_name = os.path.basename(src).split("@", 1)[0]
|
||||||
|
dest = os.path.join(root, dest_name)
|
||||||
|
if os.path.exists(dest):
|
||||||
|
return False, "an active copy already exists at " + dest
|
||||||
|
try:
|
||||||
|
shutil.move(src, dest)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("nodes-stats: native enable failed for %s", pack_name, exc_info=True)
|
||||||
|
return False, str(e)
|
||||||
|
return True, "enabled"
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "comfyui-nodes-stats"
|
name = "comfyui-nodes-stats"
|
||||||
description = "Track usage statistics for all ComfyUI nodes and packages"
|
description = "Track usage statistics for all ComfyUI nodes and packages"
|
||||||
version = "1.4.0"
|
version = "1.8.0"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|
||||||
[project.urls]
|
[project.urls]
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import node_introspect as ni
|
||||||
|
|
||||||
|
|
||||||
|
_SAMPLE = '''
|
||||||
|
import folder_paths
|
||||||
|
|
||||||
|
|
||||||
|
class MyCoolNode:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(cls):
|
||||||
|
return {
|
||||||
|
"required": {
|
||||||
|
"image": ("IMAGE",),
|
||||||
|
"model": ("MODEL",),
|
||||||
|
"strength": ("FLOAT", {"default": 1.5, "min": 0.0}),
|
||||||
|
"mode": (["fast", "slow"], {"default": "slow"}),
|
||||||
|
"ckpt": (folder_paths.get_filename_list("checkpoints"),),
|
||||||
|
},
|
||||||
|
"optional": {
|
||||||
|
"mask": ("MASK",),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
RETURN_TYPES = ("IMAGE", "LATENT")
|
||||||
|
RETURN_NAMES = ("out_image", "out_latent")
|
||||||
|
CATEGORY = "testing/cool"
|
||||||
|
FUNCTION = "run"
|
||||||
|
|
||||||
|
def run(self, image, model, strength, mode, ckpt, mask=None):
|
||||||
|
return (image, None)
|
||||||
|
|
||||||
|
|
||||||
|
class DynamicNode:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(cls):
|
||||||
|
d = {"required": {}}
|
||||||
|
return d
|
||||||
|
RETURN_TYPES = ("STRING",)
|
||||||
|
|
||||||
|
|
||||||
|
NODE_CLASS_MAPPINGS = {"My Cool Node": MyCoolNode}
|
||||||
|
NODE_CLASS_MAPPINGS.update({"Dynamic": DynamicNode})
|
||||||
|
NODE_DISPLAY_NAME_MAPPINGS = {"My Cool Node": "My Cool Node ✨"}
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def _write_pack(tmp_path, body=_SAMPLE, name="nodes.py"):
|
||||||
|
ni._INDEX_CACHE.clear()
|
||||||
|
f = tmp_path / name
|
||||||
|
f.write_text(body)
|
||||||
|
return str(tmp_path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_inputs_sockets_widgets_and_defaults(tmp_path):
|
||||||
|
pack = _write_pack(tmp_path)
|
||||||
|
s = ni.get_node_schema("My Cool Node", pack)
|
||||||
|
assert s["parseable"] is True
|
||||||
|
assert s["display_name"] == "My Cool Node ✨"
|
||||||
|
assert s["category"] == "testing/cool"
|
||||||
|
by = {i["name"]: i for i in s["inputs"]}
|
||||||
|
|
||||||
|
# custom types are sockets
|
||||||
|
assert by["image"]["type"] == "IMAGE" and by["image"]["widget"] is False
|
||||||
|
assert by["model"]["type"] == "MODEL" and by["model"]["widget"] is False
|
||||||
|
# primitives + combos are widgets, with defaults
|
||||||
|
assert by["strength"]["widget"] is True and by["strength"]["default"] == 1.5
|
||||||
|
assert by["mode"]["type"] == "COMBO" and by["mode"]["options"] == ["fast", "slow"]
|
||||||
|
assert by["mode"]["default"] == "slow"
|
||||||
|
# folder_paths.get_filename_list(...) -> dynamic combo widget, options unknown
|
||||||
|
assert by["ckpt"]["type"] == "COMBO" and by["ckpt"]["widget"] is True
|
||||||
|
assert by["ckpt"]["options"] is None
|
||||||
|
# optional inputs are flagged
|
||||||
|
assert by["mask"]["required"] is False and by["image"]["required"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_outputs_use_return_names(tmp_path):
|
||||||
|
pack = _write_pack(tmp_path)
|
||||||
|
s = ni.get_node_schema("My Cool Node", pack)
|
||||||
|
assert [(o["name"], o["type"]) for o in s["outputs"]] == [
|
||||||
|
("out_image", "IMAGE"),
|
||||||
|
("out_latent", "LATENT"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_mapping_update_call_is_merged(tmp_path):
|
||||||
|
pack = _write_pack(tmp_path)
|
||||||
|
s = ni.get_node_schema("Dynamic", pack)
|
||||||
|
assert s["parseable"] is True
|
||||||
|
assert s["outputs"] == [{"name": "STRING", "type": "STRING"}]
|
||||||
|
assert s["inputs"] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_class_type_not_parseable(tmp_path):
|
||||||
|
pack = _write_pack(tmp_path)
|
||||||
|
s = ni.get_node_schema("Nope", pack)
|
||||||
|
assert s["parseable"] is False
|
||||||
|
assert s["reason"] == "dynamic_mapping"
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_mapping_reason(tmp_path):
|
||||||
|
pack = _write_pack(tmp_path, body="class A:\n RETURN_TYPES = ('X',)\n")
|
||||||
|
s = ni.get_node_schema("A", pack)
|
||||||
|
# class_type falls back to the class name even without NODE_CLASS_MAPPINGS
|
||||||
|
assert s["parseable"] is True
|
||||||
|
s2 = ni.get_node_schema("Missing", pack)
|
||||||
|
assert s2["parseable"] is False and s2["reason"] == "no_mapping"
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_disabled_pack_path_strips_version_and_case(tmp_path, monkeypatch):
|
||||||
|
cn = tmp_path / "custom_nodes"
|
||||||
|
disabled = cn / ".disabled"
|
||||||
|
disabled.mkdir(parents=True)
|
||||||
|
(disabled / "ComfyMath@nightly").mkdir()
|
||||||
|
|
||||||
|
fp = MagicMock()
|
||||||
|
fp.get_folder_paths.return_value = [str(cn)]
|
||||||
|
monkeypatch.setitem(sys.modules, "folder_paths", fp)
|
||||||
|
|
||||||
|
found = ni.find_disabled_pack_path("comfymath")
|
||||||
|
assert found == os.path.join(str(disabled), "ComfyMath@nightly")
|
||||||
|
assert ni.find_disabled_pack_path("not-there") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_disabled_pack_path_rejects_traversal(tmp_path):
|
||||||
|
assert ni.find_disabled_pack_path("../evil") is None
|
||||||
|
assert ni.find_disabled_pack_path("a/b") is None
|
||||||
|
assert ni.find_disabled_pack_path("") is None
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import pack_fs
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def custom_nodes(tmp_path):
|
||||||
|
"""A custom_nodes root wired into the mocked folder_paths."""
|
||||||
|
import folder_paths
|
||||||
|
|
||||||
|
root = tmp_path / "custom_nodes"
|
||||||
|
root.mkdir()
|
||||||
|
folder_paths.get_folder_paths.return_value = [str(root)]
|
||||||
|
return root
|
||||||
|
|
||||||
|
|
||||||
|
def _make_pack(root, name):
|
||||||
|
pack = root / name
|
||||||
|
pack.mkdir()
|
||||||
|
(pack / "__init__.py").write_text("NODE_CLASS_MAPPINGS = {}\n")
|
||||||
|
return pack
|
||||||
|
|
||||||
|
|
||||||
|
# --- find_active_pack_path ------------------------------------------------
|
||||||
|
|
||||||
|
def test_find_active_dir(custom_nodes):
|
||||||
|
_make_pack(custom_nodes, "MyPack")
|
||||||
|
found = pack_fs.find_active_pack_path("MyPack")
|
||||||
|
assert found == os.path.normpath(str(custom_nodes / "MyPack"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_active_case_insensitive(custom_nodes):
|
||||||
|
_make_pack(custom_nodes, "MyPack")
|
||||||
|
assert pack_fs.find_active_pack_path("mypack") is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_active_single_py_file(custom_nodes):
|
||||||
|
(custom_nodes / "loose_node.py").write_text("NODE_CLASS_MAPPINGS = {}\n")
|
||||||
|
found = pack_fs.find_active_pack_path("loose_node")
|
||||||
|
assert found == os.path.normpath(str(custom_nodes / "loose_node.py"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_active_ignores_disabled_dir(custom_nodes):
|
||||||
|
(custom_nodes / ".disabled").mkdir()
|
||||||
|
_make_pack(custom_nodes / ".disabled", "MyPack")
|
||||||
|
assert pack_fs.find_active_pack_path("MyPack") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_active_rejects_path_traversal(custom_nodes):
|
||||||
|
assert pack_fs.find_active_pack_path("../evil") is None
|
||||||
|
assert pack_fs.find_active_pack_path("a/b") is None
|
||||||
|
assert pack_fs.find_active_pack_path("") is None
|
||||||
|
|
||||||
|
|
||||||
|
# --- disable_pack_native --------------------------------------------------
|
||||||
|
|
||||||
|
def test_disable_moves_dir_into_disabled(custom_nodes):
|
||||||
|
_make_pack(custom_nodes, "MyPack")
|
||||||
|
ok, msg = pack_fs.disable_pack_native("MyPack")
|
||||||
|
assert ok, msg
|
||||||
|
assert not (custom_nodes / "MyPack").exists()
|
||||||
|
assert (custom_nodes / ".disabled" / "MyPack" / "__init__.py").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_disable_moves_single_py_file(custom_nodes):
|
||||||
|
(custom_nodes / "loose_node.py").write_text("x = 1\n")
|
||||||
|
ok, msg = pack_fs.disable_pack_native("loose_node")
|
||||||
|
assert ok, msg
|
||||||
|
assert not (custom_nodes / "loose_node.py").exists()
|
||||||
|
assert (custom_nodes / ".disabled" / "loose_node.py").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_disable_missing_pack_fails(custom_nodes):
|
||||||
|
ok, msg = pack_fs.disable_pack_native("Ghost")
|
||||||
|
assert not ok
|
||||||
|
assert "not found" in msg
|
||||||
|
|
||||||
|
|
||||||
|
def test_disable_collision_fails(custom_nodes):
|
||||||
|
_make_pack(custom_nodes, "MyPack")
|
||||||
|
(custom_nodes / ".disabled").mkdir()
|
||||||
|
(custom_nodes / ".disabled" / "MyPack").mkdir() # pre-existing disabled copy
|
||||||
|
ok, msg = pack_fs.disable_pack_native("MyPack")
|
||||||
|
assert not ok
|
||||||
|
assert "already exists" in msg
|
||||||
|
# original left untouched
|
||||||
|
assert (custom_nodes / "MyPack").exists()
|
||||||
|
|
||||||
|
|
||||||
|
# --- enable_pack_native ---------------------------------------------------
|
||||||
|
|
||||||
|
def test_enable_moves_back(custom_nodes):
|
||||||
|
_make_pack(custom_nodes, "MyPack")
|
||||||
|
assert pack_fs.disable_pack_native("MyPack")[0]
|
||||||
|
ok, msg = pack_fs.enable_pack_native("MyPack")
|
||||||
|
assert ok, msg
|
||||||
|
assert (custom_nodes / "MyPack" / "__init__.py").exists()
|
||||||
|
assert not (custom_nodes / ".disabled" / "MyPack").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_enable_missing_fails(custom_nodes):
|
||||||
|
ok, msg = pack_fs.enable_pack_native("Ghost")
|
||||||
|
assert not ok
|
||||||
|
assert "not found" in msg
|
||||||
|
|
||||||
|
|
||||||
|
def test_enable_strips_version_suffix(custom_nodes):
|
||||||
|
# A Manager-disabled pack on disk carries an @version suffix; enabling should
|
||||||
|
# restore it as a clean, importable directory name.
|
||||||
|
ddir = custom_nodes / ".disabled"
|
||||||
|
ddir.mkdir()
|
||||||
|
pack = ddir / "ComfyMath@nightly"
|
||||||
|
pack.mkdir()
|
||||||
|
(pack / "__init__.py").write_text("NODE_CLASS_MAPPINGS = {}\n")
|
||||||
|
|
||||||
|
ok, msg = pack_fs.enable_pack_native("ComfyMath")
|
||||||
|
assert ok, msg
|
||||||
|
assert (custom_nodes / "ComfyMath" / "__init__.py").exists()
|
||||||
|
assert not (custom_nodes / "ComfyMath@nightly").exists()
|
||||||
|
assert not (ddir / "ComfyMath@nightly").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_disable_then_enable_roundtrip_py_file(custom_nodes):
|
||||||
|
(custom_nodes / "loose_node.py").write_text("x = 1\n")
|
||||||
|
assert pack_fs.disable_pack_native("loose_node")[0]
|
||||||
|
assert pack_fs.enable_pack_native("loose_node")[0]
|
||||||
|
assert (custom_nodes / "loose_node.py").exists()
|
||||||
|
|
||||||
|
|
||||||
|
# --- list_disabled_packs --------------------------------------------------
|
||||||
|
|
||||||
|
def test_list_disabled_empty(custom_nodes):
|
||||||
|
assert pack_fs.list_disabled_packs() == set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_disabled_strips_version_and_ext(custom_nodes):
|
||||||
|
ddir = custom_nodes / ".disabled"
|
||||||
|
ddir.mkdir()
|
||||||
|
(ddir / "ComfyMath@nightly").mkdir() # Manager-style @version suffix
|
||||||
|
(ddir / "PlainPack").mkdir()
|
||||||
|
(ddir / "loose_node.py").write_text("x = 1\n") # single-file pack
|
||||||
|
assert pack_fs.list_disabled_packs() == {"ComfyMath", "PlainPack", "loose_node"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_disabled_reflects_a_native_disable(custom_nodes):
|
||||||
|
_make_pack(custom_nodes, "MyPack")
|
||||||
|
assert pack_fs.disable_pack_native("MyPack")[0]
|
||||||
|
assert "MyPack" in pack_fs.list_disabled_packs()
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from tracker import UsageTracker
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def tracker(tmp_path):
|
||||||
|
return UsageTracker(db_path=str(tmp_path / "test.db"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_whitelist_starts_empty(tracker):
|
||||||
|
assert tracker.get_whitelist() == set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_and_get(tracker):
|
||||||
|
tracker.add_to_whitelist("My-Pack")
|
||||||
|
assert tracker.get_whitelist() == {"My-Pack"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_is_idempotent(tracker):
|
||||||
|
tracker.add_to_whitelist("My-Pack")
|
||||||
|
tracker.add_to_whitelist("My-Pack")
|
||||||
|
assert tracker.get_whitelist() == {"My-Pack"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_remove(tracker):
|
||||||
|
tracker.add_to_whitelist("My-Pack")
|
||||||
|
tracker.remove_from_whitelist("My-Pack")
|
||||||
|
assert tracker.get_whitelist() == set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_remove_absent_is_noop(tracker):
|
||||||
|
tracker.remove_from_whitelist("Nope") # must not raise
|
||||||
|
assert tracker.get_whitelist() == set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_reset_clears_whitelist(tracker):
|
||||||
|
tracker.add_to_whitelist("My-Pack")
|
||||||
|
tracker.reset()
|
||||||
|
assert tracker.get_whitelist() == set()
|
||||||
|
|
||||||
|
|
||||||
|
class _Mapper:
|
||||||
|
"""Minimal stand-in for NodePackageMapper with a fixed mapping."""
|
||||||
|
|
||||||
|
def __init__(self, mapping):
|
||||||
|
self.mapping = mapping
|
||||||
|
|
||||||
|
def get_package(self, ct):
|
||||||
|
return self.mapping.get(ct, "__unknown__")
|
||||||
|
|
||||||
|
def get_all_packages(self):
|
||||||
|
return set(self.mapping.values()) - {"__builtin__"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_stats_flags_whitelisted(tracker):
|
||||||
|
mapper = _Mapper({"NodeA": "Pack-A", "NodeB": "Pack-B"})
|
||||||
|
tracker.record_usage(["NodeA", "NodeB"], mapper)
|
||||||
|
tracker.add_to_whitelist("Pack-A")
|
||||||
|
|
||||||
|
stats = {p["package"]: p for p in tracker.get_package_stats(mapper)}
|
||||||
|
assert stats["Pack-A"]["whitelisted"] is True
|
||||||
|
assert stats["Pack-B"]["whitelisted"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_stats_whitelist_is_case_insensitive(tracker):
|
||||||
|
mapper = _Mapper({"NodeA": "Pack-A"})
|
||||||
|
tracker.record_usage(["NodeA"], mapper)
|
||||||
|
tracker.add_to_whitelist("pack-a") # different case than the package name
|
||||||
|
|
||||||
|
stats = {p["package"]: p for p in tracker.get_package_stats(mapper)}
|
||||||
|
assert stats["Pack-A"]["whitelisted"] is True
|
||||||
+51
@@ -57,6 +57,11 @@ CREATE TABLE IF NOT EXISTS trial_packages (
|
|||||||
budget INTEGER NOT NULL DEFAULT 7
|
budget INTEGER NOT NULL DEFAULT 7
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS whitelist_packages (
|
||||||
|
package TEXT PRIMARY KEY,
|
||||||
|
added_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_node_usage_package ON node_usage(package);
|
CREATE INDEX IF NOT EXISTS idx_node_usage_package ON node_usage(package);
|
||||||
CREATE INDEX IF NOT EXISTS idx_prompt_log_timestamp ON prompt_log(timestamp);
|
CREATE INDEX IF NOT EXISTS idx_prompt_log_timestamp ON prompt_log(timestamp);
|
||||||
CREATE INDEX IF NOT EXISTS idx_model_usage_type ON model_usage(model_type);
|
CREATE INDEX IF NOT EXISTS idx_model_usage_type ON model_usage(model_type);
|
||||||
@@ -286,6 +291,13 @@ class UsageTracker:
|
|||||||
tracking_start, one_month_ago, two_months_ago, "unused_new"
|
tracking_start, one_month_ago, two_months_ago, "unused_new"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Flag whitelisted packages so the UI can pull them into their own group
|
||||||
|
# and suppress disable actions. Whitelist entries are kept verbatim; match
|
||||||
|
# case-insensitively since directory names vary by how users clone/symlink.
|
||||||
|
whitelist = {w.lower() for w in self.get_whitelist()}
|
||||||
|
for entry in packages.values():
|
||||||
|
entry["whitelisted"] = entry["package"].lower() in whitelist
|
||||||
|
|
||||||
result = [p for p in packages.values() if p["package"].lower() not in EXCLUDED_PACKAGES]
|
result = [p for p in packages.values() if p["package"].lower() not in EXCLUDED_PACKAGES]
|
||||||
result.sort(key=lambda p: p["total_executions"])
|
result.sort(key=lambda p: p["total_executions"])
|
||||||
return result
|
return result
|
||||||
@@ -480,6 +492,44 @@ class UsageTracker:
|
|||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
def add_to_whitelist(self, package):
|
||||||
|
"""Protect a package: keep it out of disable actions and its own group."""
|
||||||
|
now = datetime.now(timezone.utc).isoformat()
|
||||||
|
with self._lock:
|
||||||
|
self._ensure_db()
|
||||||
|
conn = self._connect()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"""INSERT INTO whitelist_packages (package, added_at) VALUES (?, ?)
|
||||||
|
ON CONFLICT(package) DO NOTHING""",
|
||||||
|
(package, now),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def remove_from_whitelist(self, package):
|
||||||
|
"""Remove a package from the whitelist."""
|
||||||
|
with self._lock:
|
||||||
|
self._ensure_db()
|
||||||
|
conn = self._connect()
|
||||||
|
try:
|
||||||
|
conn.execute("DELETE FROM whitelist_packages WHERE package = ?", (package,))
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def get_whitelist(self):
|
||||||
|
"""Return the set of whitelisted package names."""
|
||||||
|
with self._lock:
|
||||||
|
self._ensure_db()
|
||||||
|
conn = self._connect()
|
||||||
|
try:
|
||||||
|
rows = conn.execute("SELECT package FROM whitelist_packages").fetchall()
|
||||||
|
return {r[0] for r in rows}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
def reset(self):
|
def reset(self):
|
||||||
"""Clear all tracked data."""
|
"""Clear all tracked data."""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
@@ -490,6 +540,7 @@ class UsageTracker:
|
|||||||
conn.execute("DELETE FROM prompt_log")
|
conn.execute("DELETE FROM prompt_log")
|
||||||
conn.execute("DELETE FROM model_usage")
|
conn.execute("DELETE FROM model_usage")
|
||||||
conn.execute("DELETE FROM trial_packages")
|
conn.execute("DELETE FROM trial_packages")
|
||||||
|
conn.execute("DELETE FROM whitelist_packages")
|
||||||
conn.commit()
|
conn.commit()
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|||||||
Reference in New Issue
Block a user