Compare commits

..
Author SHA1 Message Date
Vito Sansevero c14e1af87f test(memory): let the musl test fake os.confstr on Windows (#523)
The portability run on main fails since #523: Windows has no
os.confstr, so patching it without create=True raises before the test
runs.
2026-10-31 20:09:07 -07:00
Vito Sansevero 981639740b fix(thumbnails): never follow a marker or a link out of the thumbnail folder (#320)
Marker keys are data, not paths: only a single <slug>-<hex> folder name
is ever joined onto the thumbnail folder; anything else is dropped and
logged. Every preview write and delete passes one ownership check (below a
key folder, lexically and resolved, no link, junction or reparse point on
the way); make_parent refuses anything else and writes nothing while the
folder lacks this install's marker (an unmounted mount point). Clear never
descends into a junction.

The configured location is in force before any request (unchecked folder
mode is unavailable), and a startup check that fails leaves it invalid,
never the sources. Older listings that run on the event loop no longer
touch the store in folder mode. A leftover under another case of
thumbnails/ on a case-insensitive disk is refused too.
2026-10-31 19:51:06 -07:00
Vito Sansevero 57ab85b002 feat(thumbnails): keep previews in one folder, set from config.json (#320)
thumbnails.location in config.json can now name one folder for every
source's previews: <folder>/<source key>/<rel>_thumb<ext>. A source key is
a readable slug plus a short hash of the source's identity, stored in the
folder's marker (.promptmanager-thumbnails.json) with the install that
made it. Serving, on-demand and capture writes, listings, clear, delete,
duplicates, the temp sweep and History covers all follow it; a leftover in
<source>/thumbnails is never served and other text under thumbnails/ is
refused.

A missing, unplugged or foreign folder is unavailable (a probe checks it
every 5 s within 2 s; a stalled or failing store call flips it at once):
originals are served, nothing is written anywhere, the folder is never
re-created, and generate, convert and clear answer 409
location-unavailable. A bad config value is unavailable too, never a
fall-back to the sources.

No UI yet: POST /settings refuses thumbnail_location (409
location-needs-move); GET /settings reports it with its path, the
thumbnail status without one. Sources inside or around the folder and a
library move into it are refused.
2026-10-31 19:35:30 -07:00
Vito Sansevero 38f5491da1 refactor(thumbnails): keep the after-scan queue's store rule and pin the write lock (#320)
A planned target keeps the plan's own containment rule (inside the
store, as the thumbnail job writes it); captures keep the serve rule.
The structural test also covers PREVIEW_FOLDER joins and the
repo-root modules; the write-lock test asserts the lock instead of
waiting on a timer; new tests cover nested roots in the after-scan
queue and a legacy upper-case preview served through the resolver.
2026-10-31 19:11:21 -07:00
Vito Sansevero c0328e993a refactor(thumbnails): one resolver for where previews live on disk (#320)
Add py/api/preview_store.py: the store of a source, a preview's path,
URL parts to disk, containment (owns), a write generation and the lock
around every preview's final rename. Every preview reader, writer and
remover now asks it instead of joining <source>/thumbnails by hand:
serve, on-demand, capture (its path resolved when the write starts),
the after-scan queue, the thumbnail plans and job payloads, clear, the
temp sweep, History covers, the auto-tag listing and the owned-preview
lookups.

Source mode only: every path is the one built before, so nothing
changes on disk or on the wire. A structural test keeps new
thumbnails joins out of the backend.
2026-10-31 18:51:18 -07:00
418 changed files with 17553 additions and 25937 deletions
-21
View File
@@ -1,21 +0,0 @@
# Left out of the Comfy Registry package (comfy node publish). Git clones still
# have everything. tests/test_package_contents.py holds these rules to what
# ComfyUI needs at run time; keep each one anchored to the root with a leading /.
# Development folders
/tests/
/tools/
/docs/
/.github/
# Screenshots used only by README-legacy.md on GitHub
/images/
# Development files
/TESTING.md
/requirements-dev.txt
/.coveragerc
/.flake8
/.pre-commit-config.yaml
/.gitignore
/.gitattributes
-7
View File
@@ -1,7 +0,0 @@
# Pinned files are compared byte for byte with their recorded hashes
# (npm run --prefix tools/vendor check). Git must never convert their line
# endings, which Git for Windows does by default (core.autocrlf=true, #636).
/web/lib/viewerjs/** -text
/web/js/shared/toolkit/** -text
/web/js/workspace/concept.css -text
/docs/concepts/workspace/style.css -text
-15
View File
@@ -1,15 +0,0 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: veets
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+9 -2
View File
@@ -1,8 +1,15 @@
{
"required_status_checks": {
"strict": true,
"strict": false,
"contexts": [
"gate"
"py3.12 on ubuntu-latest",
"coverage gate (85%)",
"black and flake8",
"frontend modules",
"all tests",
"viewerjs",
"real ComfyUI compatibility",
"bandit (high severity)"
]
},
"enforce_admins": true,
-9
View File
@@ -4,10 +4,6 @@ updates:
# Python dependencies (requirements.txt / setup.cfg / pyproject.toml)
- package-ecosystem: "pip"
directory: "/"
# Our requirements are minimum versions that install into ComfyUI's shared
# environment. Leave a floor alone when it already allows the new release;
# raising it would force-upgrade the package for every other custom node.
versioning-strategy: "increase-if-necessary"
schedule:
interval: "weekly"
day: "sunday"
@@ -21,11 +17,6 @@ updates:
prefix: "deps(pip)"
include: "scope"
rebase-strategy: "auto"
# These floors follow ComfyUI's requirements.txt, never the newest release.
ignore:
- dependency-name: "Pillow"
- dependency-name: "aiohttp"
- dependency-name: "numpy"
# Optional: group non-breaking updates to reduce PR noise
groups:
python-minor-and-patch:
-407
View File
@@ -1,407 +0,0 @@
name: CI
permissions:
contents: read
# The gate (#666): everything a change must pass runs once, here, on the pull request. Nothing runs
# again in a merge queue or on main; branch protection requires the one context "gate" on a branch
# that is up to date with main, so the commit that was tested is the commit that merges. What only
# other browsers, other Pythons, Windows or a real ComfyUI can catch runs in nightly.yml.
on:
pull_request:
branches: [main]
workflow_dispatch:
# A newer push to a pull request cancels the older run. A manual run is never cancelled.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
PYTHONFAULTHANDLER: "1"
# Every job has a time limit: ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never
# under 5, timed as whole-job wall time. The 3 minutes leave room for the Python runner's watchdog
# (120 s, tests/run_suite.py) to print its stack dump before GitHub cancels the job. A limit changes
# only with new measurements written here (TESTING.md "Time limits and hangs"). A job with no three
# green runs yet has an "estimate" line; replace it with its measurement after three green runs.
# tests/vendor/ci-workflow.test.mjs recomputes every limit from these lines.
# Measured 2026-11-21 on runs 44861123845 (a1f7447), 44547399478 (b3bb55f), 44519471869 (fa31644):
# python: 7m20s / 7m36s / 7m58s -> 15 min
# lint: 0m27s / 0m52s / 0m49s -> 5 min
# js-test: 0m27s / 0m35s / 0m36s -> 5 min
# changes: 0m10s / 0m06s / 0m07s -> 5 min
# Measured 2026-11-21 on runs 44861123782 (a1f7447), 44547399248 (b3bb55f), 44519472003 (fa31644):
# security: 0m22s / 0m20s / 0m24s -> 5 min
# Measured 2026-11-21 on runs 44861123725 (a1f7447), 44547398683 (b3bb55f), 44519471975 (fa31644):
# frontend-coverage-merge: 0m53s / 0m57s / 0m51s -> 5 min
# gate: 0m02s / 0m06s / 0m03s -> 5 min
# estimate package: one stdlib test module without an install, under 1 minute -> 5 min
# estimate tooling: the pip and npm installs of a browser shard (about 1 minute) and 2 minutes of tests -> 8 min
# estimate frontend-coverage: the same four shards ran Chromium and touch together in 7m55s-16m48s;
# Chromium alone is about half of that, 9 minutes at most -> 17 min
#
# Browser jobs (#425): a job killed at its limit keeps no log and skips its upload steps, so the page
# test step has its own timeout-minutes, 2 below the job's. At the step limit, SIGTERM makes
# tools/vendor/running-tests-reporter.mjs print the tests still running and hand over to Playwright's
# interrupt, which writes the blob report; the always() uploads then run. The limits assume the npm
# cache hits: a cold cache adds up to 5 minutes to npm ci.
jobs:
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" and "docs"
# (nothing here can break), "release" (only the version line of pyproject.toml), or "code" (anything
# else, and every case of doubt). The jobs below run for one class only, and "gate" fails unless
# this job succeeded and each job did what the class asks. The clone has every commit but no file
# contents (blob:none): the script compares file names, and reads pyproject.toml only when it is
# the one file that changed.
changes:
name: change class
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
class: ${{ steps.classify.outputs.class }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
filter: blob:none
persist-credentials: false
- name: Classify the changed files
id: classify
env:
EVENT_NAME: ${{ github.event_name }}
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
# The suite runs once, under coverage: the same run proves the tests pass and the 85% floor holds.
python:
name: python 3.12 with coverage (85%)
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Run the suite under coverage
run: python -m coverage run -m tests.run_suite -v
- name: Coverage gate
run: |
python -m coverage combine
python -m coverage report --fail-under=85
# A release (only the version line changed) cannot break a test, but it is what the Registry
# publishes, so the package-content rules are checked. Standard library only: nothing to install.
package:
name: package contents
needs: changes
if: ${{ needs.changes.outputs.class == 'release' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
- run: python -m unittest -v tests.test_package_contents
lint:
name: black and flake8
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
# The exact black and flake8 pins from requirements-dev.txt, so a new release cannot turn CI red.
- run: pip install $(grep -E '^(black|flake8)==' requirements-dev.txt)
- run: black --check .
- run: flake8 .
security:
name: bandit (high severity)
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
- name: Install bandit
run: pip install bandit[toml]
# Medium findings are reported without failing until they are triaged.
# High severity is a hard gate.
- name: Security report (medium and above, informational)
run: bandit -r . -ll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules --exit-zero
- name: Security scan (high severity gate)
run: bandit -r . -lll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules
js-test:
name: frontend modules
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
cache-dependency-path: tools/vendor/package-lock.json
- name: Check shipped extension and page modules parse
run: |
shopt -s globstar nullglob
for f in web/comfy/**/*.js web/comfy/**/*.mjs web/js/**/*.js web/js/**/*.mjs; do
node --input-type=module --check < "$f" || exit 1
done
- name: Install pinned shared test contracts
run: npm ci --prefix tools/vendor --ignore-scripts
- name: Run JS tests
run: node --test tests/js/*.test.js
# The vendor pins and the tooling tests (tests/vendor). Same image and Python as the browser shards:
# some tooling tests start the browser test server.
tooling:
name: tooling tests and pins
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 8
steps:
- uses: actions/checkout@v7
- name: Python environment
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
run: |
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- run: npm run --prefix tools/vendor check
- run: npm run --prefix tools/vendor test
frontend-coverage:
name: frontend coverage (shard ${{ matrix.shard }}/4)
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
# tests/vendor/browser-image.test.mjs checks it). Browsers and fonts come from the image.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 17
# Public-repo ubuntu-latest runners have 4 vCPUs: three Playwright workers, each with its own test
# server, leave one CPU for the servers and the runner.
env:
PM_TEST_WORKERS: 3
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v7
# The image's own Python 3.12 and Node 24: setup-python/setup-node install the runner's toolcache
# builds, whose entry points name host paths that do not exist in the container. The image has no
# ensurepip and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv.
- name: Python environment
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
run: |
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# npm's download cache, keyed on the lockfile; inside the container ~ is the job's HOME (/github/home),
# which npm also uses. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
# Desktop Chromium only, without tests tagged @quarantine (tools/vendor/frontend-coverage.mjs).
# Shard 1 also runs the node units and the viewer suite.
- name: Page workflows with coverage, shard ${{ matrix.shard }}/4
timeout-minutes: 15
run: npm run --prefix tools/vendor test:coverage:shard -- ${{ matrix.shard }}/4
- name: Upload raw coverage
uses: actions/upload-artifact@v7
with:
name: coverage-raw-${{ matrix.shard }}
path: coverage/js/raw/
if-no-files-found: error
retention-days: 3
# Traces and the blob report (test-results/blob/) of a failed, timed-out or cancelled step.
- name: Upload Chromium traces
if: always()
uses: actions/upload-artifact@v7
with:
name: frontend-traces-shard-${{ matrix.shard }}
path: tools/vendor/test-results/
retention-days: 14
frontend-coverage-merge:
name: frontend coverage (merge)
# Runs only when every shard succeeded (the implicit success() check).
needs: [changes, frontend-coverage]
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
# Same image as the shards: the raw files name sources by the container's workspace path.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- run: node --version && node --version | grep -q '^v24\.'
# npm's download cache, keyed on the lockfile; inside the container ~ is the job's HOME (/github/home),
# which npm also uses. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
# Each artifact lands in its own coverage-raw-N directory, so the next step can count them.
- uses: actions/download-artifact@v8
with:
pattern: coverage-raw-*
path: ${{ runner.temp }}/coverage-raw
# coverage:merge only checks that raw files exist; merging three of four shards would report
# partial coverage, so a missing or empty shard artifact fails here.
- name: Verify every shard's raw coverage arrived
shell: bash
env:
STAGED_RAW: ${{ runner.temp }}/coverage-raw
EXPECTED_SHARDS: 4
run: |
found=0
for shard in $(seq 1 "$EXPECTED_SHARDS"); do
directory="$STAGED_RAW/coverage-raw-$shard"
count=0
if [ -d "$directory" ]; then count=$(find "$directory" -maxdepth 1 -type f -name '*.json' | wc -l); fi
echo "coverage-raw-$shard: $count raw files"
if [ "$count" -gt 0 ]; then found=$((found + 1)); fi
done
echo "shard artifacts with raw coverage: $found of $EXPECTED_SHARDS"
if [ "$found" -ne "$EXPECTED_SHARDS" ]; then
echo "::error::Expected raw coverage from $EXPECTED_SHARDS shards, got $found of $EXPECTED_SHARDS"
exit 1
fi
staged=$(find "$STAGED_RAW" -mindepth 2 -maxdepth 2 -type f -name '*.json' | wc -l)
mkdir -p coverage/js/raw
# cp -n never overwrites; a clash shows up as fewer merged files than staged ones.
find "$STAGED_RAW" -mindepth 2 -maxdepth 2 -type f -name '*.json' -exec cp -n -t coverage/js/raw {} + || true
merged=$(find coverage/js/raw -maxdepth 1 -type f -name '*.json' | wc -l)
if [ "$merged" -ne "$staged" ]; then
echo "::error::Shards wrote clashing raw file names: $staged staged, $merged merged"
exit 1
fi
echo "merged $merged raw files"
- name: Frontend coverage report and baseline check
run: npm run --prefix tools/vendor coverage:merge
- name: Upload frontend coverage report
if: always()
uses: actions/upload-artifact@v7
with:
name: frontend-test-reports
path: |
coverage/js/
!coverage/js/raw/**
retention-days: 14
# The one required context. Branch protection names only "gate", so renaming or adding a job above
# never strands a pull request. It passes only when the classifier succeeded and every job did what
# the class asks: for "code" every test job succeeded and the release check was skipped; for
# "release" only the package check ran, and it succeeded; for "docs" and "inert" everything was
# skipped. A failed, cancelled or wrongly skipped job fails it, and so does a class the classifier
# does not print.
gate:
needs: [changes, python, package, lint, security, js-test, tooling, frontend-coverage, frontend-coverage-merge]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Require every job the change class asks for
env:
CHANGE_CLASS: ${{ needs.changes.outputs.class }}
CHANGES_RESULT: ${{ needs.changes.result }}
PYTHON_RESULT: ${{ needs.python.result }}
PACKAGE_RESULT: ${{ needs.package.result }}
LINT_RESULT: ${{ needs.lint.result }}
SECURITY_RESULT: ${{ needs.security.result }}
JS_RESULT: ${{ needs.js-test.result }}
TOOLING_RESULT: ${{ needs.tooling.result }}
COVERAGE_RESULT: ${{ needs.frontend-coverage.result }}
MERGE_RESULT: ${{ needs.frontend-coverage-merge.result }}
run: |
echo "change class: $CHANGE_CLASS (classifier: $CHANGES_RESULT)"
test "$CHANGES_RESULT" = success
case "$CHANGE_CLASS" in
code) code=success; release=skipped ;;
release) code=skipped; release=success ;;
docs|inert) code=skipped; release=skipped ;;
*) echo "::error::unknown change class"; exit 1 ;;
esac
failed=0
require() {
echo "$1: $2 (must be $3)"
if [ "$2" != "$3" ]; then echo "::error::$1 is $2, must be $3"; failed=1; fi
}
require python "$PYTHON_RESULT" "$code"
require lint "$LINT_RESULT" "$code"
require security "$SECURITY_RESULT" "$code"
require js-test "$JS_RESULT" "$code"
require tooling "$TOOLING_RESULT" "$code"
require frontend-coverage "$COVERAGE_RESULT" "$code"
require frontend-coverage-merge "$MERGE_RESULT" "$code"
require package "$PACKAGE_RESULT" "$release"
exit "$failed"
+43
View File
@@ -0,0 +1,43 @@
name: Code Quality
permissions:
contents: read
on:
merge_group:
push:
branches: [main]
pull_request:
branches: [main]
# Superseded PR pushes cancel their older run. Every main push gets its own
# group (run_id), so no main commit's run is ever cancelled or dropped as pending.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
security:
name: bandit (high severity)
runs-on: ubuntu-latest
# ceil(1.5 x slowest of three green main runs) + 3, never under 5 (test.yml): runs 40257217665,
# 40254137380, 40240706583 took 23s / 16s / 23s -> 5 min.
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- name: Set up Python 3.12
uses: actions/setup-python@v7
with:
python-version: "3.12"
- name: Install bandit
run: pip install bandit[toml]
# Medium findings are reported without failing until they are triaged.
# High severity is a hard gate.
- name: Security report (medium and above, informational)
run: bandit -r . -ll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules --exit-zero
- name: Security scan (high severity gate)
run: bandit -r . -lll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules
-359
View File
@@ -1,359 +0,0 @@
name: Nightly
permissions:
contents: read
# Everything that is not in the gate (#666): other browsers, the phone-size project, other Pythons,
# Windows, a real mount, a real ComfyUI and the wall-clock budget. It never runs on a pull request or
# a merge and no context here is required. A failing job opens or updates one issue
# ("nightly: <job> failing"); the next green run closes it. To try a branch before it merges:
# gh workflow run nightly.yml --ref <branch> (a branch run files no issues).
on:
schedule:
- cron: "17 3 * * *"
workflow_dispatch:
# Every run gets its own group (run_id), so no run is ever cancelled or dropped as pending.
concurrency:
group: ${{ github.workflow }}-${{ github.run_id }}
cancel-in-progress: false
env:
PYTHONFAULTHANDLER: "1"
# Time limit rule as in ci.yml: ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never
# under 5, timed as whole-job wall time; a matrix job takes its slowest leg. A job with no three
# green runs yet has an "estimate" line. tests/vendor/ci-workflow.test.mjs recomputes every limit.
# Measured 2026-11-21 on runs 44861123845 (a1f7447), 44547399478 (b3bb55f), 44519471869 (fa31644):
# python-linux: 6m12s / 5m14s / 5m37s -> 13 min
# comfyui: 20m21s / 20m39s / 21m06s -> 35 min
# perf-budget: 0m23s / 0m29s / 0m28s -> 5 min
# Measured 2026-11-21 on runs 44730775403 (b3bb55f), 44518136123 (9943a61), 44298521973 (1d509c8):
# python-windows: 8m04s / 8m41s / 9m27s -> 18 min
# native-trash-linux: 0m29s / 0m19s / 0m29s -> 5 min
# Measured 2026-11-21 on runs 44861123725 (a1f7447), 44547398683 (b3bb55f), 44519471975 (fa31644):
# browser-workflows: 12m44s / 15m55s / 14m55s -> 27 min
# (the Firefox and WebKit legs; touch ran inside the coverage shards until #666 and has no
# measurement of its own: about half of a 7m55s-16m48s shard)
# estimate report: one script and a few API calls, under 1 minute -> 5 min
#
# Browser jobs (#425): the page test step has its own timeout-minutes, 2 below the job's, so a hang
# ends inside the step and the log, the blob report and the traces survive (see ci.yml).
jobs:
python-linux:
name: py${{ matrix.python-version }} on ubuntu-latest
runs-on: ubuntu-latest
timeout-minutes: 13
strategy:
fail-fast: false
matrix:
python-version: ["3.13", "3.14"]
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Run tests
run: python -m tests.run_suite -v
python-windows:
name: py${{ matrix.python-version }} on windows-latest
runs-on: windows-latest
timeout-minutes: 18
strategy:
fail-fast: false
matrix:
python-version: ["3.12", "3.13", "3.14"]
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
# The runner's TEMP is on C:, the OS disk, where a flush took about 6 ms
# and a test database's create-to-delete about 111 ms; on the D: work
# disk the same took 0.5 ms and 23 ms. Tests write their
# databases under TEMP, so it moves to a folder on D: (measured in #487,
# run 40915866444). The runner's TEMP was an 8.3 short name
# (C:\Users\RUNNER~1\...), so the new one is spelled by its short name too
# and paths still have to be resolved. D: makes no short names by default
# (run 40922502209), so they are switched on for it first.
- name: Keep test files on the work disk
shell: pwsh
run: |
fsutil 8dot3name set D: 0
$folder = New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP "PromptManagerTests")
$short = (New-Object -ComObject Scripting.FileSystemObject).GetFolder($folder.FullName).ShortPath
Write-Output "test TEMP: $short (long name $($folder.FullName))"
if ($short -eq $folder.FullName) { Write-Output "::warning::D: gave the test TEMP no 8.3 short name" }
"TEMP=$short" >> $env:GITHUB_ENV
"TMP=$short" >> $env:GITHUB_ENV
- name: Run tests
env:
PM_TEST_SLOWEST: "40"
run: python -m tests.run_suite -v
# The same tests as the fake mount table, on a real ext4 mount used as the output root (#543). A
# runner can mount with sudo; the tests run as the normal user, so owner and mode checks are real.
native-trash-linux:
name: native trash on a real mount
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Mount an ext4 image
run: |
truncate -s 64M "$RUNNER_TEMP/drive.img"
mkfs.ext4 -q "$RUNNER_TEMP/drive.img"
mkdir "$RUNNER_TEMP/drive"
sudo mount -o loop "$RUNNER_TEMP/drive.img" "$RUNNER_TEMP/drive"
sudo rmdir "$RUNNER_TEMP/drive/lost+found"
sudo chown "$(id -u):$(id -g)" "$RUNNER_TEMP/drive"
findmnt "$RUNNER_TEMP/drive"
- name: Native trash proof
timeout-minutes: 3
run: PM_TRASH_MOUNT="$RUNNER_TEMP/drive" python -m unittest tests.test_trash_mount_root -v
perf-budget:
# The reference wall-clock measurement (TESTING.md "Performance budgets"). Shared-runner timing
# varies, so it never gates a pull request. A red run means fix the code.
name: perf budget
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Workspace filter budget
env:
PROMPTMANAGER_PERF_BUDGET: "1"
run: python -m unittest -v tests.test_api_workspace_images.TestWorkspaceImages.test_filter_budget
comfyui:
name: real ComfyUI compatibility
runs-on: ubuntu-latest
# Chromium and its system libraries come from the pinned Playwright image (tag = @playwright/test in
# tools/vendor/package-lock.json; tests/vendor/browser-image.test.mjs checks it). The runner install
# pulled them from Ubuntu's apt mirror on every run, and three runs (#349, #378, #382) crawled at
# ~26 kB/s for 11-12 minutes until the job hit its limit after every test had passed.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 35
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Read the reviewed runtime pins
id: runtime
run: |
node --input-type=module <<'JS' >> "$GITHUB_OUTPUT"
import runtime from './tools/vendor/comfyui-runtime.json' with { type: 'json' };
for (const [key, value] of Object.entries(runtime)) console.log(`${key}=${value}`);
import crossPack from './tools/vendor/cross-pack-runtime.json' with { type: 'json' };
console.log(`kikoRepository=${crossPack.repository}`);
console.log(`kikoRevision=${crossPack.revision}`);
JS
- name: Check out pinned ComfyUI
uses: actions/checkout@v7
with:
repository: ${{ steps.runtime.outputs.repository }}
ref: ${{ steps.runtime.outputs.revision }}
path: .ci-comfyui
persist-credentials: false
- name: Check out pinned KikoTools for compatibility
uses: actions/checkout@v7
with:
repository: ${{ steps.runtime.outputs.kikoRepository }}
ref: ${{ steps.runtime.outputs.kikoRevision }}
path: .ci-kikotools
persist-credentials: false
# The image's own Python and Node 24: setup-python/setup-node install the runner's toolcache builds,
# whose entry points name host paths that do not exist in the container. The image has no ensurepip
# and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv. The image
# Python must be the reviewed host Python, so a pin or image bump that disagrees fails here.
- name: Python environment on the reviewed host Python
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
PINNED_PYTHON: ${{ steps.runtime.outputs.pythonVersion }}
run: |
image="$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
[ "$image" = "$PINNED_PYTHON" ] || { echo "::error::image Python $image is not the pinned $PINNED_PYTHON"; exit 1; }
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# pip's download cache (torch alone is ~200 MB); inside the container ~ is the job's HOME (/github/home).
- name: Cache pip downloads
uses: actions/cache@v6
with:
path: ~/.cache/pip
key: pip-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('requirements-dev.txt', '.ci-comfyui/requirements.txt', 'tools/vendor/comfyui-runtime.json') }}
- name: Install CPU runtime and test dependencies
run: |
pip install "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}" --index-url https://download.pytorch.org/whl/cpu
pip install -r .ci-comfyui/requirements.txt -r requirements-dev.txt "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}"
# npm's download cache, keyed on the lockfile. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- name: Classic and Nodes 2.0 startup and compatibility
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:comfyui
- name: Real cached and headless execution history
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:executions
- name: Independent and combined pack compatibility
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_KIKO_ROOT: ${{ github.workspace }}/.ci-kikotools
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:compat
- name: Upload real-host reports and startup logs
if: always()
uses: actions/upload-artifact@v7
with:
name: real-comfyui-reports
path: tools/vendor/test-results/
if-no-files-found: ignore
retention-days: 14
browser-workflows:
name: page workflows (${{ matrix.browser }}, shard ${{ matrix.shard }}/3)
# Firefox, WebKit and touch (phone-size Chromium): not first-class, so they report here instead of
# blocking a merge. Quarantined tests (@quarantine) run here too. One retry: a test that fails
# and then passes is listed as flaky in the job summary (tools/vendor/flaky-tests-reporter.mjs)
# instead of failing the job.
runs-on: ubuntu-latest
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
# tests/vendor/browser-image.test.mjs checks it). Browsers and fonts come from the image.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 27
# Public-repo ubuntu-latest runners have 4 vCPUs: three Playwright workers, each with its own test
# server, leave one CPU for the servers and the runner.
env:
PM_TEST_WORKERS: 3
strategy:
fail-fast: false
matrix:
browser: [firefox, webkit, touch]
shard: [1, 2, 3]
steps:
- uses: actions/checkout@v7
# The image's own Python 3.12 and Node 24: setup-python/setup-node install the runner's toolcache
# builds, whose entry points name host paths that do not exist in the container. The image has no
# ensurepip and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv.
- name: Python environment
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
run: |
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# npm's download cache, keyed on the lockfile; inside the container ~ is the job's HOME (/github/home),
# which npm also uses. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- name: Page workflows in ${{ matrix.browser }}, shard ${{ matrix.shard }}/3
timeout-minutes: 25
run: npm run --prefix tools/vendor test:workflows -- --project ${{ matrix.browser }} --shard ${{ matrix.shard }}/3 --retries 1
# Traces and the blob report (test-results/blob/) of a failed, timed-out or cancelled step.
- name: Upload browser traces
if: always()
uses: actions/upload-artifact@v7
with:
name: browser-traces-${{ matrix.browser }}-shard-${{ matrix.shard }}
path: tools/vendor/test-results/
retention-days: 14
# One issue per job (tools/ci/nightly_report.py): a job with a failed leg opens "nightly: <job>
# failing" or comments on the open one; a job whose legs all passed closes its open issue. Shards
# of one browser count as one job. Only runs of main report: a manual run of a branch changes no
# issue.
report:
name: report by issue
needs: [python-linux, python-windows, native-trash-linux, perf-budget, comfyui, browser-workflows]
if: ${{ always() && github.ref == 'refs/heads/main' }}
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: read
contents: read
issues: write
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Open, update or close one issue per job
env:
GH_TOKEN: ${{ github.token }}
RUN_ATTEMPT: ${{ github.run_attempt }}
run: python3 tools/ci/nightly_report.py
+117
View File
@@ -0,0 +1,117 @@
name: Windows
permissions:
contents: read
# Non-blocking Windows runs (#420; macOS dropped from CI in #571): never on pull requests or in the merge queue, and no context
# here is a required check. A red run is fixed at its cause before the workspace cutover (#334).
on:
push:
branches: [main]
schedule:
- cron: "17 3 * * *"
workflow_dispatch:
# Every run gets its own group (run_id), so no main commit's run is ever cancelled or dropped as pending.
concurrency:
group: ${{ github.workflow }}-${{ github.run_id }}
cancel-in-progress: false
env:
PYTHONFAULTHANDLER: "1"
# Time limit rule as in test.yml: ceil(1.5 x the slowest of three recent green runs on main) + 3
# minutes, never under 5, timed as whole-job wall time. One matrix job, so the slowest leg of each
# run counts (tests/vendor/ci-workflow.test.mjs recomputes it, #493).
# Measured 2026-10-29 on main runs 40935337099 (dd247e3), 40938407252 (dd247e3), 40941240624 (dd247e3):
# slowest leg: 7m24s (py3.12 windows) / 7m31s (py3.13 windows) / 7m32s (py3.14 windows) -> 15 min
# (windows 4m56s-7m32s)
# native-trash-linux (#543) has no green main runs yet: it installs the dev requirements and runs
# one test module, about 1 minute by the same estimate, so ceil(1.5 x 2) + 3 gives it 6 minutes.
# Recalibrate after three green runs.
jobs:
test:
name: py${{ matrix.python-version }} on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
os: [windows-latest]
python-version: ["3.12", "3.13", "3.14"]
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
# The runner's TEMP is on C:, the OS disk, where a flush took about 6 ms
# and a test database's create-to-delete about 111 ms; on the D: work
# disk the same took 0.5 ms and 23 ms. Tests write their
# databases under TEMP, so it moves to a folder on D: (measured in #487,
# run 40915866444). The runner's TEMP was an 8.3 short name
# (C:\Users\RUNNER~1\...), so the new one is spelled by its short name too
# and paths still have to be resolved. D: makes no short names by default
# (run 40922502209), so they are switched on for it first.
- name: Keep test files on the work disk (Windows)
if: runner.os == 'Windows'
shell: pwsh
run: |
fsutil 8dot3name set D: 0
$folder = New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP "PromptManagerTests")
$short = (New-Object -ComObject Scripting.FileSystemObject).GetFolder($folder.FullName).ShortPath
Write-Output "test TEMP: $short (long name $($folder.FullName))"
if ($short -eq $folder.FullName) { Write-Output "::warning::D: gave the test TEMP no 8.3 short name" }
"TEMP=$short" >> $env:GITHUB_ENV
"TMP=$short" >> $env:GITHUB_ENV
- name: Run tests
env:
PM_TEST_SLOWEST: "40"
run: python -m tests.run_suite -v
# The same tests as the fake mount table, on a real ext4 mount used as the output root (#543). A
# runner can mount with sudo; the tests run as the normal user, so owner and mode checks are real.
native-trash-linux:
name: native trash on a real mount
runs-on: ubuntu-latest
timeout-minutes: 6
steps:
- uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Mount an ext4 image
run: |
truncate -s 64M "$RUNNER_TEMP/drive.img"
mkfs.ext4 -q "$RUNNER_TEMP/drive.img"
mkdir "$RUNNER_TEMP/drive"
sudo mount -o loop "$RUNNER_TEMP/drive.img" "$RUNNER_TEMP/drive"
sudo rmdir "$RUNNER_TEMP/drive/lost+found"
sudo chown "$(id -u):$(id -g)" "$RUNNER_TEMP/drive"
findmnt "$RUNNER_TEMP/drive"
- name: Native trash proof
timeout-minutes: 4
run: PM_TRASH_MOUNT="$RUNNER_TEMP/drive" python -m unittest tests.test_trash_mount_root -v
-6
View File
@@ -11,16 +11,10 @@ on:
permissions:
issues: write
# The only workflow a push to main starts (#666): the pull request's gate already tested the commit.
# It runs when pyproject.toml changed, and the action publishes when the version is new.
# Time limit rule as in ci.yml: ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never under 5.
# Measured 2026-11-21 on runs 44547398738 (b3bb55f), 44189688689 (1d509c8), 41519786847 (71b55bc):
# publish-node: 0m33s / 0m31s / 1m16s -> 5 min
jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
timeout-minutes: 5
if: ${{ github.repository_owner == 'ComfyAssets' }}
steps:
- name: Check out code
+295
View File
@@ -0,0 +1,295 @@
name: Tests
permissions:
contents: read
on:
merge_group:
pull_request:
branches: [main]
push:
branches: [main]
workflow_dispatch:
# Superseded PR pushes cancel their older run. Every main push gets its own
# group (run_id), so no main commit's run is ever cancelled or dropped as pending.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
PYTHONFAULTHANDLER: "1"
# Every job has a time limit: ceil(1.5 x the slowest of three recent green runs on main) + 3
# minutes, never under 5. The 3 minutes leave room for the Python runner's watchdog (120 s, see
# tests/run_suite.py) to print its stack dump before GitHub cancels the job. A limit changes only
# with new measurements written here (TESTING.md "Time limits and hangs").
# Measured 2026-10-26 on runs 40257217681 (3be0ada), 40240706568 (fb9134f), 40228167328 (f9835aa):
# py matrix, slowest py3.10 on windows-latest: 12m43s / 15m54s / 14m53s -> 27 min
# (ubuntu 5m27s-6m27s, macos 6m14s-8m30s, windows 11m42s-15m54s)
# 3.10 and 3.11 left the matrix and 3.14 joined it in #356; re-measure after three green main runs.
# Windows moved to portability.yml (#420; macOS left CI in #571), which has its own measured limit (#493);
# this Linux-only matrix keeps 27 minutes until it is re-measured.
# real ComfyUI compatibility: 13m32s / 8m55s / 11m46s -> 24 min
# coverage gate (85%): 7m26s / 7m22s / 7m54s -> 15 min
# perf budget 30s / 29s / 27s, black and flake8 39s / 37s / 39s,
# frontend modules 23s / 19s / 29s -> 5 min (the floor)
# all tests: a result check without setup, 5 min (the floor)
#
# Pull requests run a fast subset (#420): Python 3.12 on ubuntu-latest, coverage, lint and frontend
# modules. The merge queue (merge_group), pushes to main and manual runs add Python 3.13 and 3.14 on
# Linux and the real ComfyUI job. "all tests" is the required gate that holds the queue to that set.
# Windows runs in portability.yml (push to main, nightly, on demand) and never gate a merge.
jobs:
test:
name: py${{ matrix.python-version }} on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
timeout-minutes: 27
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
python-version: ${{ github.event_name == 'pull_request' && fromJSON('["3.12"]') || fromJSON('["3.12", "3.13", "3.14"]') }}
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Run tests
run: python -m tests.run_suite -v
comfyui:
name: real ComfyUI compatibility
# Merge queue, main and manual runs only. A job skipped by its condition reports Success, so this
# required context never blocks a pull request; "all tests" fails if it is skipped anywhere else.
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
# Chromium and its system libraries come from the pinned Playwright image (tag = @playwright/test in
# tools/vendor/package-lock.json; tests/vendor/browser-image.test.mjs checks it). The runner install
# pulled them from Ubuntu's apt mirror on every run, and three runs (#349, #378, #382) crawled at
# ~26 kB/s for 11-12 minutes until the job hit its limit after every test had passed.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble
options: --user 1001
timeout-minutes: 24
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Read the reviewed runtime pins
id: runtime
run: |
node --input-type=module <<'JS' >> "$GITHUB_OUTPUT"
import runtime from './tools/vendor/comfyui-runtime.json' with { type: 'json' };
for (const [key, value] of Object.entries(runtime)) console.log(`${key}=${value}`);
import crossPack from './tools/vendor/cross-pack-runtime.json' with { type: 'json' };
console.log(`kikoRepository=${crossPack.repository}`);
console.log(`kikoRevision=${crossPack.revision}`);
JS
- name: Check out pinned ComfyUI
uses: actions/checkout@v7
with:
repository: ${{ steps.runtime.outputs.repository }}
ref: ${{ steps.runtime.outputs.revision }}
path: .ci-comfyui
persist-credentials: false
- name: Check out pinned KikoTools for compatibility
uses: actions/checkout@v7
with:
repository: ${{ steps.runtime.outputs.kikoRepository }}
ref: ${{ steps.runtime.outputs.kikoRevision }}
path: .ci-kikotools
persist-credentials: false
# The image's own Python and Node 24: setup-python/setup-node install the runner's toolcache builds,
# whose entry points name host paths that do not exist in the container. The image has no ensurepip
# and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv. The image
# Python must be the reviewed host Python, so a pin or image bump that disagrees fails here.
- name: Python environment on the reviewed host Python
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
PINNED_PYTHON: ${{ steps.runtime.outputs.pythonVersion }}
run: |
image="$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
[ "$image" = "$PINNED_PYTHON" ] || { echo "::error::image Python $image is not the pinned $PINNED_PYTHON"; exit 1; }
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# pip's download cache (torch alone is ~200 MB); inside the container ~ is the job's HOME (/github/home).
- name: Cache pip downloads
uses: actions/cache@v6
with:
path: ~/.cache/pip
key: pip-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('requirements-dev.txt', '.ci-comfyui/requirements.txt', 'tools/vendor/comfyui-runtime.json') }}
- name: Install CPU runtime and test dependencies
run: |
pip install "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}" --index-url https://download.pytorch.org/whl/cpu
pip install -r .ci-comfyui/requirements.txt -r requirements-dev.txt "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}"
# npm's download cache, keyed on the lockfile. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- name: Classic and Nodes 2.0 startup and compatibility
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:comfyui
- name: Real cached and headless execution history
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:executions
- name: Independent and combined pack compatibility
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_KIKO_ROOT: ${{ github.workspace }}/.ci-kikotools
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:compat
- name: Upload real-host reports and startup logs
if: always()
uses: actions/upload-artifact@v7
with:
name: real-comfyui-reports
path: tools/vendor/test-results/
if-no-files-found: ignore
retention-days: 14
coverage:
name: coverage gate (85%)
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Measure coverage
run: |
python -m coverage run -m tests.run_suite
python -m coverage combine
python -m coverage report --fail-under=85
perf-budget:
# The reference wall-clock measurement (TESTING.md "Performance budgets").
# Shared-runner timing varies, so it never gates a pull request: it runs on
# each push to main and on demand. A red run on main means fix the code.
name: perf budget
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Workspace filter budget
env:
PROMPTMANAGER_PERF_BUDGET: "1"
run: python -m unittest -v tests.test_api_workspace_images.TestWorkspaceImages.test_filter_budget
lint:
name: black and flake8
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
# The exact black and flake8 pins from requirements-dev.txt, so a new release cannot turn CI red.
- run: pip install $(grep -E '^(black|flake8)==' requirements-dev.txt)
- run: black --check .
- run: flake8 .
js-test:
name: frontend modules
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
cache-dependency-path: tools/vendor/package-lock.json
- name: Check shipped extension and page modules parse
run: |
shopt -s globstar nullglob
for f in web/comfy/**/*.js web/comfy/**/*.mjs web/js/**/*.js web/js/**/*.mjs; do
node --input-type=module --check < "$f" || exit 1
done
- name: Install pinned shared test contracts
run: npm ci --prefix tools/vendor --ignore-scripts
- name: Run JS tests
run: node --test tests/js/*.test.js
# The required context "all tests". A dropped matrix leg never reports a check at all, so the eight
# legs that pull requests skip cannot be required by name; this gate requires them instead. Every
# job must succeed; real ComfyUI must be skipped on a pull request and succeed on every other event.
all-tests:
name: all tests
needs: [test, comfyui, coverage, lint, js-test]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Require every test job for this event
env:
EVENT_NAME: ${{ github.event_name }}
TEST_RESULT: ${{ needs.test.result }}
COMFYUI_RESULT: ${{ needs.comfyui.result }}
COVERAGE_RESULT: ${{ needs.coverage.result }}
LINT_RESULT: ${{ needs.lint.result }}
JS_RESULT: ${{ needs.js-test.result }}
run: |
queue_only=success
if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi
echo "event: $EVENT_NAME (real ComfyUI must be $queue_only)"
echo "test matrix: $TEST_RESULT"
echo "comfyui: $COMFYUI_RESULT"
echo "coverage: $COVERAGE_RESULT"
echo "lint: $LINT_RESULT"
echo "js-test: $JS_RESULT"
test "$TEST_RESULT" = success && test "$COVERAGE_RESULT" = success && test "$LINT_RESULT" = success && test "$JS_RESULT" = success && test "$COMFYUI_RESULT" = "$queue_only"
+268
View File
@@ -0,0 +1,268 @@
name: Viewer.js vendor and compatibility
on:
merge_group:
pull_request:
branches: [main]
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
# Superseded PR pushes cancel their older run. Every main push gets its own
# group (run_id), so no main commit's run is ever cancelled or dropped as pending.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# Timeouts are the measured job time plus at least 50%, and never under 20 minutes for a browser job,
# because runner speed varies. Before sharding (main 2cecfcf, one worker): frontend coverage 32m10s,
# page workflows firefox 18m59s, webkit 19m26s. First sharded run (PR #274 run 39712909047, 3 workers,
# no npm cache, where npm ci stalled for 5m in six of eight jobs): coverage shards 11m19s/10m47s/10m49s
# (tests 5m20s/4m42s/4m46s), merge 5m52s (report and check 4s), firefox shards 7m53s/9m27s (tests
# 4m41s/3m29s), webkit shards 12m25s+ (cancelled at the old 12-minute limit after its 267 tests passed in
# 6m29s) and 4m53s (tests 3m08s). With the npm cache hit (run 39725176320 at cbc8a61, npm ci 0-2s):
# coverage shards 7m34s/6m04s/5m22s (tests 6m38s/4m53s/4m04s), merge 54s, firefox 7m57s/5m21s (tests
# 7m08s/4m34s), webkit 8m16s/5m03s (tests 7m26s/3m58s); a cache miss adds up to 5m to npm ci, which
# the 20-minute limits absorb.
# Hangs (#425): a job killed at its limit keeps no log and skips its upload steps, so each browser
# test step has its own timeout-minutes (18) below the job's 20. At the step limit, SIGTERM makes
# tools/vendor/running-tests-reporter.mjs print the tests still running and hand over to Playwright's
# interrupt, which writes the blob report; the always() uploads then run.
# Measured on main (runs 40725289094, 40719375442, 40700439399): setup before the test step <= 52s,
# uploads <= 35s; test steps up to 14m42s (webkit shard 1/2) and 13m05s for coverage (shard 1/3:
# 12m53s, node units and the viewer suite before 11.8m of workflows), so coverage is the tight one
# in its 18 minutes. This holds only when the npm cache hits: a cold cache adds up to 5m to npm ci,
# and then the job limit can still end the job before the step limit does.
# #473: firefox/webkit shard 1/2 reached its 18-minute step limit (queue run 40866252975: webkit 622 tests
# passed in 17m56s, 48.5 worker-minutes vs 28.0 in shard 2/2; recent shard 1/2 jobs 13.7m-18.9m, shard 2/2
# 7.3m-12.2m), because --shard splits by test count and the slow concept specs sort into shard 1. The page
# workflows now run in three shards per browser with the limits unchanged; the per-shard times are
# re-measured after three green main runs.
# #563: coverage shards reached their 18-minute step limit three times on 2026-10-31 with no failing
# test (PR #560 shard 2/3: 814 passed in 17.9m; queue run 41206495451 shard 1/3: 827 passed; PR #564
# shard 2/3 twice), against recent green shards of 11m-17m. Coverage now runs in four shards with the
# limits unchanged; the per-shard times are re-measured after three green main runs.
jobs:
frontend-coverage:
name: frontend coverage (shard ${{ matrix.shard }}/4)
runs-on: ubuntu-latest
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
# tests/vendor/browser-image.test.mjs checks it). Browsers and fonts come from the image.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble
options: --user 1001
timeout-minutes: 20
# Public-repo ubuntu-latest runners have 4 vCPUs: three Playwright workers, each with its own test
# server, leave one CPU for the servers and the runner.
env:
PM_TEST_WORKERS: 3
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v7
# The image's own Python 3.12 and Node 24: setup-python/setup-node install the runner's toolcache
# builds, whose entry points name host paths that do not exist in the container. The image has no
# ensurepip and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv.
- name: Python environment
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
run: |
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# npm's download cache, keyed on the lockfile; inside the container ~ is the job's HOME (/github/home),
# which npm also uses. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
# Shard 1 also runs the node units and the viewer suite, so the vendor pins and the tooling tests
# run on the lightest shard instead.
- if: matrix.shard == 4
run: npm run --prefix tools/vendor check
- if: matrix.shard == 4
run: npm run --prefix tools/vendor test
- name: Page workflows with coverage, shard ${{ matrix.shard }}/4
timeout-minutes: 18
run: npm run --prefix tools/vendor test:coverage:shard -- ${{ matrix.shard }}/4
- name: Upload raw coverage
uses: actions/upload-artifact@v7
with:
name: coverage-raw-${{ matrix.shard }}
path: coverage/js/raw/
if-no-files-found: error
retention-days: 3
# Traces and the blob report (test-results/blob/) of a failed, timed-out or cancelled step.
- name: Upload Chromium and touch traces
if: always()
uses: actions/upload-artifact@v7
with:
name: frontend-traces-shard-${{ matrix.shard }}
path: tools/vendor/test-results/
retention-days: 14
frontend-coverage-merge:
name: frontend coverage (merge)
needs: frontend-coverage
runs-on: ubuntu-latest
# Same image as the shards: the raw files name sources by the container's workspace path.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble
options: --user 1001
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- run: node --version && node --version | grep -q '^v24\.'
# npm's download cache, keyed on the lockfile; inside the container ~ is the job's HOME (/github/home),
# which npm also uses. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
# Each artifact lands in its own coverage-raw-N directory, so the next step can count them.
- uses: actions/download-artifact@v8
with:
pattern: coverage-raw-*
path: ${{ runner.temp }}/coverage-raw
# coverage:merge only checks that raw files exist; merging three of four shards would report
# partial coverage, so a missing or empty shard artifact fails here.
- name: Verify every shard's raw coverage arrived
shell: bash
env:
STAGED_RAW: ${{ runner.temp }}/coverage-raw
EXPECTED_SHARDS: 4
run: |
found=0
for shard in $(seq 1 "$EXPECTED_SHARDS"); do
directory="$STAGED_RAW/coverage-raw-$shard"
count=0
if [ -d "$directory" ]; then count=$(find "$directory" -maxdepth 1 -type f -name '*.json' | wc -l); fi
echo "coverage-raw-$shard: $count raw files"
if [ "$count" -gt 0 ]; then found=$((found + 1)); fi
done
echo "shard artifacts with raw coverage: $found of $EXPECTED_SHARDS"
if [ "$found" -ne "$EXPECTED_SHARDS" ]; then
echo "::error::Expected raw coverage from $EXPECTED_SHARDS shards, got $found of $EXPECTED_SHARDS"
exit 1
fi
staged=$(find "$STAGED_RAW" -mindepth 2 -maxdepth 2 -type f -name '*.json' | wc -l)
mkdir -p coverage/js/raw
# cp -n never overwrites; a clash shows up as fewer merged files than staged ones.
find "$STAGED_RAW" -mindepth 2 -maxdepth 2 -type f -name '*.json' -exec cp -n -t coverage/js/raw {} + || true
merged=$(find coverage/js/raw -maxdepth 1 -type f -name '*.json' | wc -l)
if [ "$merged" -ne "$staged" ]; then
echo "::error::Shards wrote clashing raw file names: $staged staged, $merged merged"
exit 1
fi
echo "merged $merged raw files"
- name: Frontend coverage report and baseline check
run: npm run --prefix tools/vendor coverage:merge
- name: Upload frontend coverage report
if: always()
uses: actions/upload-artifact@v7
with:
name: frontend-test-reports
path: |
coverage/js/
!coverage/js/raw/**
retention-days: 14
browser-workflows:
name: page workflows (${{ matrix.browser }}, shard ${{ matrix.shard }}/3)
# Merge queue, main and manual runs only (#420); pull requests run the Chromium/touch coverage shards.
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
# tests/vendor/browser-image.test.mjs checks it). Browsers and fonts come from the image.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble
options: --user 1001
timeout-minutes: 20
# Public-repo ubuntu-latest runners have 4 vCPUs: three Playwright workers, each with its own test
# server, leave one CPU for the servers and the runner.
env:
PM_TEST_WORKERS: 3
strategy:
fail-fast: false
matrix:
browser: [firefox, webkit]
shard: [1, 2, 3]
steps:
- uses: actions/checkout@v7
# The image's own Python 3.12 and Node 24: setup-python/setup-node install the runner's toolcache
# builds, whose entry points name host paths that do not exist in the container. The image has no
# ensurepip and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv.
- name: Python environment
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
run: |
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# npm's download cache, keyed on the lockfile; inside the container ~ is the job's HOME (/github/home),
# which npm also uses. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- name: Page workflows in ${{ matrix.browser }}, shard ${{ matrix.shard }}/3
timeout-minutes: 18
run: npm run --prefix tools/vendor test:workflows -- --project ${{ matrix.browser }} --shard ${{ matrix.shard }}/3
# Traces and the blob report (test-results/blob/) of a failed, timed-out or cancelled step.
- name: Upload browser traces
if: always()
uses: actions/upload-artifact@v7
with:
name: browser-traces-${{ matrix.browser }}-shard-${{ matrix.shard }}
path: tools/vendor/test-results/
retention-days: 14
# Branch protection requires the exact context "viewerjs". This job keeps that
# name and fails unless every coverage shard and the coverage merge succeeded and
# the browser shards succeeded, or, on a pull request only, were skipped (#420).
# Any failure, cancellation or other skip fails it.
viewerjs:
needs: [frontend-coverage, frontend-coverage-merge, browser-workflows]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Require every frontend job to succeed
env:
EVENT_NAME: ${{ github.event_name }}
COVERAGE_RESULT: ${{ needs.frontend-coverage.result }}
MERGE_RESULT: ${{ needs.frontend-coverage-merge.result }}
WORKFLOWS_RESULT: ${{ needs.browser-workflows.result }}
run: |
queue_only=success
if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi
echo "event: $EVENT_NAME (browser-workflows must be $queue_only)"
echo "frontend-coverage: $COVERAGE_RESULT"
echo "frontend-coverage-merge: $MERGE_RESULT"
echo "browser-workflows: $WORKFLOWS_RESULT"
test "$COVERAGE_RESULT" = success && test "$MERGE_RESULT" = success && test "$WORKFLOWS_RESULT" = "$queue_only"
-9
View File
@@ -17,18 +17,9 @@ concurrency:
group: viewerjs-update
cancel-in-progress: false
# Time limit rule as in ci.yml (#662): ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never under 5.
# Measured 2026-11-21 on runs 44771628562 (b3bb55f), 44568715421 (b3bb55f), 44349316383 (1d509c8):
# these nightly runs found no new release and took 0m09s / 0m13s / 0m12s, the 5-minute floor. None of
# the 35 green runs since 2026-10-17 took the update path (tests, Chromium, the PR), so it is estimated
# from its parts until three green update runs can be measured:
# estimate update: npm ci on a cold cache up to 5m (as recorded for the browser jobs), Playwright
# Chromium with its system packages about 2m, the pin check, tooling and unit tests about 1m, the
# viewer suite (38s locally, 2 workers) and setup about 2m: 10 min, ceil(1.5 x 10) + 3 -> 18 min
jobs:
update:
runs-on: ubuntu-latest
timeout-minutes: 18
permissions:
contents: write
pull-requests: write
+3
View File
@@ -1,3 +1,6 @@
# Tailwind standalone CLI (downloaded by `make css-setup`)
tailwindcss
# AI tooling / local config
.claude/
.playwright-mcp/
+2 -4
View File
@@ -13,7 +13,7 @@ repos:
language: system
types: [python]
# Fails at the severity CI enforces (ci.yml: -lll, high only), never stricter.
# Fails at the severity CI enforces (code-quality.yml: -lll, high only), never stricter.
# pre-commit appends the staged files, so no shell wrapper can drop the first one.
- id: bandit
name: bandit
@@ -22,11 +22,9 @@ repos:
types: [python]
exclude: ^(tests/|reference/)
# Skipped for an inert push; a docs push runs only the two tests that read the docs
# (tools/ci/change_class.py, #639, #679).
- id: tests
name: tests
entry: python tools/ci/change_class.py --unless-inert python -m tests.run_suite -q
entry: python -m tests.run_suite -q
language: system
pass_filenames: false
stages: [pre-push]
-258
View File
@@ -1,258 +0,0 @@
# Changelog
What changed in each release of ComfyUI Prompt Manager, newest first. Full notes for each version are on the [releases page](https://github.com/ComfyAssets/ComfyUI_PromptManager/releases).
Thank you to everyone whose pull requests are part of these releases. They are named beside their changes and listed under [Contributors](#contributors).
## v3.8.0 (Old pages removed, Tag cleanup, AVIF)
- **🧹 Tag cleanup**: System › Maintenance finds tags that are whole comma lists and tags used nowhere. You review them and remove only what you tick; a safety backup is always taken first. Later cleanups will be added to the same place ([#618](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/618))
- **🏷️ LoRA import tags**: a LoRA's trained words become a tag only when they are one short phrase. Lists and sentences are no longer saved as tags, and the import review says how many were left out ([#618](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/618))
- **🖼️ AVIF images**: collected, thumbnailed and linked to their prompts like PNG and WebP, where your Pillow can read AVIF. By [@LacklusterOpsec](https://github.com/LacklusterOpsec) ([#673](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/673), [#652](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/652))
- **🗑️ Old pages removed**: the old Dashboard, Gallery and Metadata viewer are gone, after the notice in 3.5.1. Their addresses open the matching workspace page, and old tag bookmarks open the Prompt library with that filter ([#668](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/668))
- **🔗 Tag filters in the address**: `#/library?tag=cats&tag=dogs&tag_mode=any` can be bookmarked and shared; Reload, Back and Forward keep the filter ([#668](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/668))
- **🐛 LoRA import label**: an import that had already saved when ComfyUI closed is shown as finished, not cancelled. By [@aryankalantri](https://github.com/aryankalantri) ([#672](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/672), [#619](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/619))
- **🪟 Windows**: two installs writing one shared thumbnail folder at the same moment no longer fail with "Permission denied" ([#674](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/674))
- **⚠️ Known limit**: Inspect shows a WebP or AVIF file but not its embedded prompt yet; the image still links to its prompt ([#656](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/656))
## v3.7.2 (Always a way to choose the prompt)
- **🎯 Choose prompt in Inspect**: an image with several possible prompts shows a Choose prompt section; Inspect creates the Needs review item itself, also for older images ([#659](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/659))
- **📥 Needs review without a scan**: the live monitor queues an ambiguous output as soon as its run ends ([#659](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/659))
- **🔢 Big workflows**: a file with more than 16 different prompts offers the 16 most used instead of none
- **🔗 Link to a prompt** lists the image's own prompts first; the Needs review queue loads as you scroll
- **🐛 rgthree Any Switch** no longer makes a decided prompt look ambiguous ([#657](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/657)); a role every candidate agrees on shows as resolved ([#658](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/658))
- **🧪 CI**: every change is tested once, on its pull request; other browsers, Python versions and Windows run nightly ([#666](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/666))
## v3.7.1 (WebP linking)
- **🖼️ WebP images link to their prompts**: ComfyUI's Save Animated WEBP stores the prompt in EXIF, which is now read. By [@LacklusterOpsec](https://github.com/LacklusterOpsec) ([#650](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/650))
- **🐛 Prepend and append text** start empty instead of `null`. By [@LacklusterOpsec](https://github.com/LacklusterOpsec) ([#651](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/651))
## v3.7.0 (Permanent delete, new logo)
- **🗑️ Permanent delete** for images on Linux and BSD servers, beside remove-from-library and trash. By [@k98kurz](https://github.com/k98kurz) ([#643](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/643))
- **🎨 New logo** in the README, the Comfy Registry and the browser tabs ([#632](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/632))
- **🐛 Folders with a backslash in their name** work on Linux and macOS; one odd file no longer stops the viewer opening ([#646](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/646))
## v3.6.0 (Library sorts)
- **↕️ Three more Prompt library sorts**: Recently used, Most used and Name Z–A
- **🐛 Windows network shares**: backup checks, restore, Move library and history reads open a library on a network path ([#620](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/620))
- **🐛 Unloading a tagging model** no longer freezes the server ([#620](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/620))
## v3.5.1 (Smaller download)
- **📦 Smaller package**: the Registry download drops from 17.4 MB to about 3.9 MB ([#615](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/615))
- **📣 Notice**: the old pages say they will be removed
## v3.5.0 (Thumbnail location, Send to all, Skipped tags)
- **📁 Thumbnail location**: keep thumbnails inside each source or in one folder of your choice, with a reviewed move ([#320](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/320))
- **📤 Send to every node**: Send to ComfyUI offers all eligible nodes of a window at once ([#542](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/542))
- **🚫 Skipped tags** and **saved tagging instructions** for auto-tagging ([#431](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/431))
- **🔧 Pair category and tags repair** in System › Maintenance ([#550](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/550))
- **⚡ Less memory** for scans and image work ([#523](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/523))
- **🐛 Prompt Search List** text is no longer saved as a prompt ([#548](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/548))
## v3.4.1 (Fix release)
- **🪟 Windows**: ComfyUI could hang on exit with watchdog 7.0.0
- **🔒 LoRA import errors** no longer show server details
## v3.4.0 (The workspace)
- **✨ Rebuilt around one page**, the workspace: Images, Prompt library, Tags & categories, Collections, Favorites, Needs review, Inspect a file, Activity and System
- **🖼️ Viewer** with keyboard shortcuts, zoom, rotate and slideshow; **Send to ComfyUI** from any prompt
- **🏷️ Per-image tags and auto-tagging** with WD14 or JoyCaption
- **🧩 Nodes**: Focused, Split and Prompt Manager (+/-) join Classic, Text and Search List; all run in Classic and Nodes 2.0
- **📁 Library outside the node folder**: new installs keep the library in `ComfyUI/user/__promptmanager/`; an existing library moves only when you choose
- **🗜️ Smaller database**: each workflow and prompt graph is stored once, compressed
- **⚠️ Requires Python 3.12 or newer**; downgrading is not supported
## Earlier versions
Releases from before the workspace, as they were written at the time.
## v3.3.1 (Proxy Routing Fix)
- **🌐 Proxy support**: the dashboard, gallery, tag page and metadata viewer now work when ComfyUI is reached through a proxy mount such as SwarmUI's `/ComfyBackendDirect/`. Scripts, images, API calls, progress streams and gallery folder filters stay under the mount, and the canvas node's buttons use ComfyUI's `fileURL()`. Direct ComfyUI URLs are unchanged. Thanks to @ghosttigerllc-bit ([#164](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/164))
- **📦 Dependencies**: the runtime minimums stay at `Pillow>=8.0.0` and `watchdog>=2.1.0`, so updating Prompt Manager never forces upgrades in the shared ComfyUI environment
## v3.3.0 (Hardening, Background Jobs & Worker Threads)
- **🔒 Security**: gallery roots restricted to ComfyUI directories and validated wherever they are read; media-only, fail-closed image serving; Windows path escape in static routes closed; quote-safe HTML escaping with inline handlers moved to data attributes; the CivitAI key is never returned and only sent to HTTPS CivitAI hosts; auto-tag paths contained; side-effect routes are POST-only; backups include the WAL and restores are size-capped, integrity-checked and applied through SQLite's online backup API
- **🧵 Worker Threads**: a Settings slider (default half the cores) used by the image rescan, thumbnail generation and duplicate detection. Measured: a 1 GB sample scanned in 2.5 s instead of 18 s at 8 threads
- **🔁 Background Jobs**: the image rescan and the duplicate scan run on the server, stream progress, survive a closed tab, minimize to a progress pill and re-attach after a reload
- **🎬 Video Prompts**: the scan reads the prompt ComfyUI's video savers embed in MP4/MOV/WebM containers (needs `ffprobe`)
- **🖼️ Thumbnails**: written atomically and served under versioned URLs so a regenerated thumbnail never shows a stale cached copy; the per-run cap applies only to thumbnails that still need generating and the gallery says how many remain
- **🏷️ Tag Autocomplete**: the dashboard tag box suggests tags, narrowed to those that co-occur with the tags already typed
- **♾️ Infinite Scrolling**: optional in the gallery and the dashboard list (saved default plus a session toggle)
- **⚙️ Gallery Settings** now apply at load; grid columns, media info and the Rescan button work as labelled
- **🐛 Correctness**: run counts increment when ComfyUI dequeues a prompt; negative prompts are never traced; per-thread SQLite connections and idempotent migrations (an old rebuild could delete every image row); `truncate_logs` no longer rolls the log over; the ComfyUI canvas loads only the canvas extension; Windows console banners are ASCII-safe; subfolders use `/` on every platform
- **🧪 Tests & CI**: 1,460 Python and 142 JavaScript tests (from 510 and 26), coverage 96% with an 85% gate, CI on Linux, Windows and macOS for Python 3.10–3.12, flake8 clean
- **⚠️ API changes**: image paths in responses are relative to the ComfyUI tree (use `url`); `autotag/download`, `autotag/start` and the thumbnail progress stream are POST-only; `lora/status` returns `has_civitai_api_key` instead of the key; `/search` is paginated
## v3.2.4 (Recently Used Sorting & Queue-Time Run Counts)
- **🕒 Recently Used Sort**: sort the dashboard by last use, most used or rating, server-side across pages
- **🔢 Run Counts**: `run_count` and `last_used_at` are recorded through the ComfyUI queue hook, so cached nodes still count
- **🔗 Positive-Prompt Image Linking**: generated images link to the positive prompt traced through the queued graph
## v3.2.1 (LoRA Manager Integration)
- **🔗 LoRA Manager Integration**: Import LoRA metadata, trigger words, and CivitAI example images from [ComfyUI-Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) into your prompt database
- **💉 Auto-Inject Trigger Words**: Optionally append LoRA trigger words when `<lora:name:weight>` is detected in prompts during encoding
- **🔑 CivitAI API Key Support**: Authenticate with CivitAI to download NSFW preview images
- **📥 Import Progress Modal**: Real-time SSE streaming progress during LoRA import with per-model status
> **Note:** LoRA Manager support is a WIP — this was a highly requested feature. Please [open issues](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues) for any bugs or feature requests.
## v3.2.0 (Folder Filter & QoL Improvements)
- **📁 Folder Filter**: New folder dropdown in the search panel to filter prompts by output subdirectory
- **📂 Multi-Directory Gallery Scan**: Configure multiple output directories and browse them all in one gallery
- **🖼️ Filmstrip Prompt Display**: Show prompt text and copy button in the filmstrip image viewer
- **🖱️ Click-to-Close Viewer**: Click outside the image viewer to close it
- **🐛 Bug Fixes**: Fixed database path config, UnboundLocalError in text inputs, node caching skip, diagnostics singleton lifecycle
## v3.1.0 (WD14 Tagger, Tailwind v4 & Major Refactors)
- **🏷️ WD14 Tagger Support**: Added WD14 SwinV2 and WD14 ViT as new auto-tag model options — fast ONNX-based classifiers (~400MB) that output Danbooru tags with confidence scores, no prompt needed
- **🎚️ Threshold Controls**: Adjustable general tag (default 0.35) and character tag (default 0.85) confidence thresholds for WD14 models via UI sliders
- **🎨 Tailwind v4 Migration**: Complete frontend redesign with ComfyUI theme token system (`--pm-*` design tokens) that adapts to ComfyUI's color palette
- **🏗️ API Refactor**: Split monolithic `api.py` into domain-specific route modules for better maintainability
- **🗃️ Junction Table Tags**: Migrated tag storage from JSON column to normalized junction tables with proper foreign keys
- **📄 Tags Page**: Dedicated tag management page with search, rename, merge, and delete operations
- **🔍 Load More Button**: Progressive prompt loading instead of traditional pagination
- **🔒 Security Hardening**: Resolved 15 GitHub code scanning alerts, prevented stack trace exposure in SSE errors
- **🧪 Test Coverage**: Added comprehensive unit tests for validators, hashing, metadata, config, and prompt tracker; API integration tests; database tests with CI pipeline
- **⚙️ CI/CD Improvements**: Added code quality scanning, security scanning, Dependabot, and pre-commit hooks with Black formatting
- **🐛 Bug Fixes**: Fixed custom image scan directory config (#108), gallery crash on thumbnail linking, broken imports after API refactor, widget value sync issues, and prepend/append metadata tag filtering in auto-tagger
## v3.0.26 (Top Bar Button)
- **🔘 Top Bar PM Button**: Added a "PM" button to the ComfyUI top bar for quick access to the admin dashboard
- **🚀 No Node Required**: Open PromptManager without having to add the node to your workflow first
- **🎨 Teal Button Design**: Distinctive teal-colored button positioned before the settings gear
- **🔄 Frontend Compatibility**: Works with both new ComfyUI frontend (v1.3.1+) and legacy versions
## v3.0.25 (Film Strip & QoL Improvements)
- **🎞️ Film Strip Preview**: Backported from V2 - thumbnail strip under each prompt showing linked images
- **🖼️ Quick Image Viewer**: Click any filmstrip thumbnail to open full-size image viewer
- **📸 Smart Thumbnails**: Automatically uses generated thumbnails for faster loading, falls back to full images
- **⬆️ Auto-Scroll on Pagination**: Page navigation now smoothly scrolls to top after loading
## v3.0.24 (Manual Prompt Creation)
- **➕ Add Prompt Button**: New "Add Prompt" button in the admin dashboard Bulk Actions bar
- **📝 Direct Prompt Creation**: Create prompts directly from the UI without generating images
- **🛡️ Protection from Pruning**: New prompts are automatically protected from orphan cleanup by default
- **🏷️ Full Metadata Support**: Set category, tags, rating, and notes when creating prompts
- **🔒 Orphan Protection Toggle**: Option to protect or unprotect prompts from maintenance cleanup
## v3.0.23 (AI AutoTag Release)
- **🏷️ AI AutoTag**: Automatically tag your entire image collection using JoyCaption vision models
- **🤖 Dual Model Support**: Choose between JoyCaption Beta One FP16 (high quality) or GGUF FP8 (lower VRAM)
- **📋 Two Tagging Modes**: Batch mode for bulk tagging, Review mode for one-by-one approval
- **⚙️ Smart Tag Handling**: Skip already-tagged images or re-tag all - respects your existing work
- **✏️ Customizable Prompts**: Adjust the system prompt to match your collection style and tag vocabulary
- **🔄 Real-time Progress**: SSE-based streaming progress updates during batch operations
- **📦 Tag Accordion UI**: Collapsible tag display shows first row with expandable section for large tag sets
- **🎯 Review Confirmation**: Prompts before overwriting existing tags in review mode
## v3.0.10 (Batch Processing Node)
- **📋 PromptSearchList Node**: New node that searches the prompt database and outputs results as a list
- **🔗 Batch Processing Support**: Uses `OUTPUT_IS_LIST` for native ComfyUI batch processing compatibility
- **🔍 Full Search Capabilities**: Search by text, category, tags, minimum rating, and result limit
- **⚡ Lightweight Operation**: Read-only search with no database writes
- **🎯 Workflow Integration**: Connect directly to batch processing nodes like String OutputList
## v3.0.9 (Output-Wide Gallery & Video Support)
- **📁 Output-Wide Gallery Mode**: Complete gallery redesign to show ALL content from ComfyUI output directory
- **🎬 Full Video Support**: Native video playback with HTML5 player for .mp4, .webm, .avi, .mov, .mkv, .m4v, .wmv formats
- **🖼️ Video Thumbnail Generation**: Automatic video thumbnails using OpenCV, ffmpeg, or placeholder fallback
- **⚙️ Video Settings Panel**: Configurable autoplay, mute, and loop settings with persistent preferences
- **🎮 Video Navigation**: Seamless navigation between videos with keyboard shortcuts and custom controls
- **📊 Video Metadata Display**: Show duration, resolution, aspect ratio, and detailed file information
- **🔄 Mixed Media Integration**: Videos and images seamlessly integrated in the same gallery interface
- **⚡ Enhanced Performance**: Optimized thumbnail generation for both images and videos
- **🎛️ Advanced Gallery Settings**: Comprehensive settings panel with video controls and performance options
- **🖱️ Improved Click Handling**: Fixed thumbnail failures to preserve click functionality
- **📱 Mobile Compatibility**: Enhanced responsive design for video playback on all devices
## v3.0.5 (Text-Only Node Release)
- **📝 PromptManagerText Node**: New text-only variant that outputs STRING instead of CONDITIONING
- **🔗 Text Concatenation**: Built-in prepend/append functionality for dynamic text assembly
- **⚡ Lightweight Processing**: No CLIP encoding overhead for pure text workflows
- **🔄 Dual Node Architecture**: Choose between CLIP encoding (PromptManager) or text-only (PromptManagerText)
- **🏷️ Shared Metadata System**: Both nodes use the same database and metadata features
- **🖼️ Unified Gallery**: Images from both node types appear in the same gallery system
- **📊 Enhanced Tracking**: Improved prompt tracking with prepend/append context preservation
- **📊 Enhanced Tracking**: Improved prompt tracking with prepend/append context preservation
## v3.0.3 (ViewerJS Integration & Enhanced Gallery)
- **🖼️ Professional Image Viewer**: Complete gallery redesign with [ViewerJS](https://github.com/fengyuanchen/viewerjs) integration
- **⚡ Advanced Image Navigation**: Zoom, rotation, slideshow, and professional viewing controls
- **🎨 Dark Theme Integration**: Seamless ViewerJS styling that matches the admin interface
- **🔬 Enhanced Metadata Parsing**: Improved ComfyUI workflow parameter extraction with targeted parsing
- **📊 Real-time Parameter Display**: Live CFG, steps, sampler, and seed extraction from workflow nodes
- **📋 Integrated Copy Functionality**: One-click copying of prompts and generation parameters
- **🛠️ Robust Value Detection**: Smart parsing that targets specific node types and validates parameters
- **⌨️ Keyboard Navigation**: Full keyboard support for gallery navigation and viewer controls
- **📱 Responsive Design**: Enhanced mobile and tablet compatibility
## v3.0.0 (Metadata Analysis Release)
- **🔬 PNG Metadata Analysis**: Advanced ComfyUI workflow extraction from PNG images
- **📋 Standalone Metadata Viewer**: Dedicated tool at `/web/metadata.html` for analyzing any ComfyUI image
- **🖼️ Integrated Metadata Panel**: Real-time workflow analysis in the image viewer
- **📸 Bulk Image Scanning**: Mass import and analysis of existing ComfyUI output directories
- **🛠️ System Management Suite**: Complete backup, restore, maintenance, and diagnostic tools
- **🚮 Orphaned Prompt Cleanup**: Remove prompts that have no linked images for database optimization
- **📋 Advanced Logging**: Comprehensive logging system with web-based log viewer
- **🎨 Enhanced Admin Dashboard**: Modern dark theme with improved UX and management tools
- **🔧 Robust Error Handling**: Advanced PNG parsing with NaN value cleaning and error recovery
- **📁 File Path Integration**: Direct file path display and system integration
- **⚡ Performance Optimizations**: Improved metadata extraction and database operations
## v2.0.0 (Gallery Release)
- **🖼️ Automatic Image Gallery**: Complete image tracking and gallery system
- **🌐 Advanced Web Interface**: Comprehensive admin dashboard with responsive design
- **📱 Image Viewer**: Full-screen modal with navigation and keyboard shortcuts
- **🔍 Enhanced Search**: Real-time search with advanced filtering options
- **⚡ Performance Improvements**: Optimized database operations
- **🛠️ Basic Diagnostics**: Initial system diagnostics and health monitoring
- **📊 Bulk Operations**: Multi-select prompt editing and management
## v1.0.0 (Initial Release)
- Core text encoding with database storage
- Search and filtering functionality
- Metadata support (categories, tags, ratings, notes)
- Hash-based deduplication
- SQLite backend with optimized schema
- Basic web interface
- Export functionality
## Contributors
Pull requests from the community that were merged into Prompt Manager:
| Contributor | Pull requests |
| --- | --- |
| [@LacklusterOpsec](https://github.com/LacklusterOpsec) | [#673](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/673) AVIF as a media type · [#650](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/650) WebP images link to their prompts · [#651](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/651) prepend/append defaults |
| [@aryankalantri](https://github.com/aryankalantri) | [#672](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/672) LoRA import finishes when it saved at exit |
| [@k98kurz](https://github.com/k98kurz) | [#643](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/643) permanent delete for images (Linux/BSD) |
| [@ghosttigerllc-bit](https://github.com/ghosttigerllc-bit) | [#165](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/165) A1111/Forge generation parameters · [#164](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/164) routing behind a ComfyUI proxy · [#140](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/140) recursive subfolder filtering and gallery tree |
| [@develop1st](https://github.com/develop1st) | [#141](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/141) collapsible sidebar setting and mobile overlap fix |
| [@logicalor](https://github.com/logicalor) | [#87](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/87) thumbnails in subfolders |
| [@x0x0b](https://github.com/x0x0b) | [#73](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/73) star icon alignment |
| [@robinjhuang](https://github.com/robinjhuang) | [#2](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/2) Registry publishing action · [#1](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/1) `pyproject.toml` for the Registry |
+43
View File
@@ -0,0 +1,43 @@
TAILWIND_VERSION := 4.1.18
TAILWIND_CLI := ./tailwindcss
UNAME_S := $(shell uname -s)
UNAME_M := $(shell uname -m)
ifeq ($(UNAME_S),Darwin)
ifeq ($(UNAME_M),arm64)
TAILWIND_PLATFORM := tailwindcss-macos-arm64
else
TAILWIND_PLATFORM := tailwindcss-macos-x64
endif
else
ifeq ($(UNAME_M),aarch64)
TAILWIND_PLATFORM := tailwindcss-linux-arm64
else
TAILWIND_PLATFORM := tailwindcss-linux-x64
endif
endif
TAILWIND_URL := https://github.com/tailwindlabs/tailwindcss/releases/download/v$(TAILWIND_VERSION)/$(TAILWIND_PLATFORM)
.PHONY: css css-watch css-setup clean-css
## Download Tailwind standalone CLI (dev only, not committed)
css-setup:
@if [ ! -f $(TAILWIND_CLI) ]; then \
echo "Downloading Tailwind CSS v$(TAILWIND_VERSION) CLI..."; \
curl -sLo $(TAILWIND_CLI) $(TAILWIND_URL) && chmod +x $(TAILWIND_CLI); \
else \
echo "Tailwind CLI already present"; \
fi
## Rebuild compiled CSS (run after changing Tailwind classes in HTML/JS)
css: css-setup
$(TAILWIND_CLI) -i web/lib/tailwind/input.css -o web/lib/tailwind/styles.css --minify
## Watch mode for development
css-watch: css-setup
$(TAILWIND_CLI) -i web/lib/tailwind/input.css -o web/lib/tailwind/styles.css --watch
## Remove downloaded CLI binary
clean-css:
rm -f $(TAILWIND_CLI)
+6 -5
View File
@@ -1,11 +1,12 @@
> **This is the old README.** It describes Prompt Manager before the workspace rewrite and is kept for reference, including the full changelog up to v3.3.1. The dashboard, tags page, gallery and metadata viewer it describes have been removed; their URLs now open the matching workspace page. For the current version, see the [README](README.md).
> **This is the old README.** It describes Prompt Manager before the workspace rewrite and is kept for reference, including the full changelog up to v3.3.1 and the legacy pages. Some details here are out of date. For the current version, see the [README](README.md).
# ComfyUI Prompt Manager
![License](https://img.shields.io/badge/license-MIT-blue.svg)
![Python](https://img.shields.io/badge/python-3.12%2B-blue.svg)
![ComfyUI](https://img.shields.io/badge/ComfyUI-compatible-green.svg)
![Nightly tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/actions/workflows/nightly.yml/badge.svg)
![Tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/workflows/Tests/badge.svg)
![Code Quality](https://github.com/ComfyAssets/ComfyUI_PromptManager/workflows/Code%20Quality/badge.svg)
A comprehensive ComfyUI custom node that extends the standard text encoder with persistent prompt storage, advanced search capabilities, automatic image gallery system, folder-based organization, LoRA Manager integration, and powerful ComfyUI workflow metadata analysis using SQLite.
@@ -253,8 +254,8 @@ match Classic and Focused.
5. **Access the web interface**:
- **Workspace**: click **PM** in ComfyUI's top bar or **Web UI** on a node, or open `http://localhost:8188/prompt_manager/workspace`
- **The old pages have been removed.** Their URLs open the matching workspace page:
`/prompt_manager/admin` (Prompt library), `/prompt_manager/admin#/tags` (Tags & categories), `/prompt_manager/gallery` (Images), `/prompt_manager/gallery.html` (Inspect a file)
- **Legacy pages** still work at their URLs, and System's Overview section links to them:
`/prompt_manager/admin` (dashboard), `/prompt_manager/admin#/tags` (tags), `/prompt_manager/gallery` (gallery), `/prompt_manager/gallery.html` (metadata viewer)
### Prerequisites
@@ -328,7 +329,7 @@ The comprehensive gallery system provides complete access to all your ComfyUI ou
1. **Open the workspace's Images page** at `http://localhost:8188/prompt_manager/workspace#/images`
2. **Browse all content** from your ComfyUI output directory
The old gallery URL, `http://localhost:8188/prompt_manager/gallery`, now opens the workspace's Images page.
The legacy gallery stays at `http://localhost:8188/prompt_manager/gallery`.
#### **🎬 Video & Image Support**
+53 -75
View File
@@ -1,5 +1,3 @@
![PromptManager by ComfyAssets](assets/brand/banner.webp)
# ComfyUI Prompt Manager
**Every prompt you run, every image it made, and every negative you tried, in one searchable library inside ComfyUI.**
@@ -8,24 +6,24 @@
![License](https://img.shields.io/badge/license-MIT-blue.svg)
![Python](https://img.shields.io/badge/python-3.12%2B-blue.svg)
![Nightly tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/actions/workflows/nightly.yml/badge.svg)
![Tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/workflows/Tests/badge.svg)
Prompt Manager saves your prompts as you generate and links each image to the prompt that made it. One page, the workspace, lets you browse, tag, compare and reuse them. Your library is a local SQLite database on your own machine.
Prompt Manager saves your prompts as you generate, links each image back to the prompt that made it, and gives you one page to browse, tag, compare and reuse all of it. Your library is a local SQLite database on your own machine.
## What's new
## What's new: rebuilt from the ground up
- **A new UI.** The workspace replaces the separate dashboard, gallery and metadata pages.
- **A new UI.** One app, the workspace, replaces the separate dashboard, gallery and metadata pages. The old pages still work if you want them.
- **Classic and Nodes 2.0.** The nodes work in both ComfyUI renderers. CI starts a real ComfyUI and checks both.
- **Automated tests.** Unit tests, browser tests in Chromium, Firefox, WebKit and touch emulation, and tests against a real ComfyUI.
- **Linux and Windows.** The Python suite runs on both, on Python 3.12, 3.13 and 3.14. macOS should work but is not tested.
- **Tested end to end.** Unit tests, browser tests in Chromium, Firefox, WebKit and touch emulation, and tests against a real ComfyUI.
- **Mac, Linux and Windows.** The Python suite runs on all three, on Python 3.12, 3.13 and 3.14.
## See it
All images on this page were generated and recorded through Prompt Manager in a clean demo library.
### Browse your whole output folder
### Your whole output folder, finally browsable
The Images page shows your output as masonry, a grid or a list. Search, categories, filters and saved views narrow it. Images and videos appear together, and selecting one shows its prompts and settings on the same page.
Masonry, grid or list, with search, categories, filters and saved views. Images and videos sit side by side, and selecting one shows its prompts and settings without leaving the page.
![Images page in grid layout](assets/readme/images-grid.webp)
@@ -35,63 +33,63 @@ The viewer shows the positive and negative prompts, tags, seed, steps, CFG, samp
![The viewer with an image on the left and its prompts and generation settings on the right](assets/readme/viewer.webp)
### Keyboard shortcuts
### Keep your hands on the keyboard
The viewer has shortcuts for moving between files, the slideshow, zoom, rotate, flip, full screen, details, download and delete. Press `?` to see them all.
![The viewer's keyboard shortcuts overlay](assets/readme/viewer-shortcuts.webp)
### Select and act while you scroll
### Long libraries stay easy to work in
The selection bar stays pinned while you scroll, so you can keep picking images and act on them from any position on the page. A Back to top button appears once you scroll down.
The selection bar stays pinned while you scroll, so you can keep picking images and act on them from anywhere. Back to top appears once you've scrolled down the page.
![Images page scrolled down, with the selection bar pinned at the top and a Back to top button](assets/readme/pinned-bar.webp)
### One positive prompt, many experiments
The Prompt library groups everything by positive prompt. Repeat runs and negative variants stay with their positive prompt and don't add near-duplicate entries to your list.
The Prompt library groups everything by positive prompt, so repeat runs and negative variants stay together instead of filling your list with near-duplicates.
![Prompt library cards showing each prompt's images, negative variants, runs and tags](assets/readme/library.webp)
### See negative variants on a timeline
### Watch your negatives branch on a timeline
Each prompt has its own page with a timeline of its negative variants. Click a red dot and the gallery filters to the images that negative variant made. Small dots mark repeat runs.
Each prompt has its own page with a timeline of its negative variants. Click a red dot and the gallery filters to the images that negative made. Small dots mark repeat runs.
![Clicking through negative variants on the timeline filters the gallery below](assets/readme/timeline.anim.webp)
### Compare negatives term by term
Compare negatives shows two negative variants side by side and lists the terms one adds, so you can see what changed between runs.
Compare negatives shows two variants side by side and lists the terms one adds, so you can see what actually changed between runs.
![Two negative prompts side by side with the added terms highlighted](assets/readme/compare-negatives.webp)
### Auto-tag your images and approve the suggestions
### Auto-tag your images, and approve what sticks
Tag one image, a selection or your whole output with WD14 or JoyCaption. WD14 suggestions come with confidence scores, and you can review suggestions before Prompt Manager saves anything. Auto-tags belong to the image, so they never change your prompts.
Tag one image, a selection or your whole output with WD14 or JoyCaption. WD14 suggestions come with confidence scores, and you can review suggestions before anything is saved. Auto-tags belong to the image, so they never change your prompts.
![Tag image dialog with WD14 suggestions and their confidence scores](assets/readme/autotag.webp)
### Manage tags and categories
### Keep your vocabulary tidy
Tags & categories lists every tag and category with how often you use it. Rename, merge and delete tags, and preview a category change before you apply it.
Tags & categories lists every tag and category with how often it's used. Rename, merge and delete tags, and preview a category change before you apply it.
![Tags and categories page](assets/readme/tags.webp)
### Group images your own way
Collections are sets of images you pick by hand. They are separate from favorites and saved views. Add images from the selection bar and the collection appears in the sidebar.
Collections are hand-picked sets of images, on top of favorites and saved views. Add from the selection bar and they appear in the sidebar.
![A collection called Book cover ideas open in the workspace](assets/readme/collections.webp)
### Nothing gets guessed
When a file's metadata has more than one possible prompt, Prompt Manager doesn't pick for you. The file waits in Needs review, where you can choose the sampler path, link the file to any prompt in your library, or leave it unresolved.
When a file's metadata has more than one possible prompt, Prompt Manager doesn't pick for you. The file waits in Needs review, where you can choose the sampler path, link it to any prompt in your library, or leave it unresolved.
![Link to a prompt dialog searching the library from Needs review](assets/readme/needs-review.webp)
### Inspect any file without importing it
### Inspect any file, without importing it
Pick an image or video from your computer to read its prompts, settings and workflow. Your browser reads the file. Prompt Manager doesn't upload it or add it to your library.
Pick an image or video from your computer to read its prompts, settings and workflow. The file is read in your browser. It isn't uploaded or added to your library.
![Inspecting a local file in the viewer](assets/readme/inspect.webp)
@@ -103,13 +101,7 @@ Pick an open ComfyUI window and a node, then review the exact before and after.
### Deletes you can review
Before Prompt Manager removes anything, you choose what happens to the files:
- **Remove from the library.** The file stays on disk. This is the only choice on Windows.
- **Move to the system trash.** Linux and macOS only.
- **Delete permanently.** Linux and BSD servers only. This is for headless servers, where a trash fills the disk. You can't recover these files.
A safety backup of the database is on by default, and you can bring removed images back.
Choose what happens to the files before anything is removed: remove the image from the library and leave the file on disk, or on Linux and macOS also move it to the system trash. On Windows, images can only be removed from the library. A safety backup of the database is on by default, and removed images can be brought back.
![Delete dialog offering to remove from the library only or move files to the trash](assets/readme/delete-review.webp)
@@ -123,17 +115,17 @@ System holds settings, image sources, auto-tag models, integrations, maintenance
### Works on your phone too
The workspace adapts to narrow screens, and the browser test suite includes touch.
The workspace adapts to narrow screens, and touch is part of the browser test suite.
![Images page and viewer at phone width](assets/readme/phone.webp)
## The nodes
The six nodes are under **ComfyAssets > Prompts** in the Add Node menu. They all share one library. Every screenshot below is a small real workflow that ran.
Six nodes, under **ComfyAssets > Prompts** in the Add Node menu. Pick the one that suits your workflow; they all share one library. Every screenshot below is a small real workflow that ran.
### Prompt Manager (Classic)
This node replaces CLIP Text Encode. It has the same CLIP input and the same CONDITIONING output, and it saves the prompt as it runs. It also outputs the text as a STRING.
The drop-in replacement for CLIP Text Encode: same CLIP input, same CONDITIONING output, with the prompt saved as it runs. It also outputs the text as a STRING.
![Prompt Manager Classic node in a workflow, Classic renderer](assets/readme/node-classic.webp)
@@ -143,19 +135,19 @@ The same workflow in Nodes 2.0:
### Prompt Manager (Focused)
This node puts the editor first. Composition and metadata collapse, and **Browse library** lets you search, preview and use a saved prompt on the node.
An editor-first layout. Composition and metadata fold away, and **Browse library** lets you search, preview and use a saved prompt right on the node.
![Prompt Manager Focused node in a workflow](assets/readme/node-focused.webp)
### Prompt Manager (Split)
This node has the same editor with the library always visible. A wide node shows them side by side. A narrow node stacks them.
The same editor with the library always visible. Wide nodes put them side by side; narrow nodes stack them.
![Prompt Manager Split node in a workflow](assets/readme/node-split.webp)
### Prompt Manager (+/-)
This node holds the positive and the negative prompt and saves them as a pair. The timeline's negative variants come from this node. It outputs CONDITIONING and STRING for both sides.
Positive and negative in one node, saved as a pair. This is the node that feeds the negative-variant timeline. It outputs CONDITIONING and STRING for both sides.
![Prompt Manager plus/minus node in a workflow](assets/readme/node-pair.webp)
@@ -165,23 +157,23 @@ The same workflow in Nodes 2.0:
### Prompt Manager Text
This node saves the prompt and outputs a STRING, not CONDITIONING. Use it in workflows that send text to another node. Prepend and append inputs let you build the final text.
Saves the prompt and outputs a STRING instead of CONDITIONING, for workflows that send text to another node. Prepend and append inputs let you build the final text.
![Prompt Manager Text node feeding a CLIP Text Encode node](assets/readme/node-text.webp)
### Prompt Search List
This node searches your library by text, category, tags and minimum rating. It outputs the matches as a list, so ComfyUI runs each one. This workflow found three prompts tagged `mushroom` and made three images.
Searches your library by text, category, tags and minimum rating, then outputs the matches as a list so ComfyUI runs each one. This workflow found three prompts tagged `mushroom` and made three images.
![Prompt Search List node producing three images](assets/readme/node-search.webp)
To link the images of a Search List batch to their prompts, wire the Search List output into a Prompt Manager Text node, not straight into CLIP Text Encode. Wired straight in, the images stay unlinked, because nothing saves the search text as a prompt.
To get the images of a Search List batch linked to their prompts, wire the Search List output into a Prompt Manager Text node, not straight into CLIP Text Encode. Wired straight in, the images stay unlinked: the search text is never saved as a prompt.
## Install
Prompt Manager requires ComfyUI and Python 3.12 or newer. Its only dependencies of its own are `watchdog` and `Pillow`. The rest comes with ComfyUI.
**Requirements:** ComfyUI and Python 3.12 or newer. `watchdog` and `Pillow` are the only dependencies of their own; the rest comes with ComfyUI.
Install from the Comfy Registry or ComfyUI-Manager by searching for Prompt Manager, or install by hand:
Install from the Comfy Registry or ComfyUI-Manager (search for Prompt Manager), or by hand:
```bash
cd ComfyUI/custom_nodes/
@@ -191,7 +183,7 @@ pip install -r ComfyUI_PromptManager/requirements.txt
Restart ComfyUI. Click **PM** in the top bar, or **Web UI** on a node, or open `http://localhost:8188/prompt_manager/workspace`.
**Optional extras.** Prompt Manager installs none of these for you:
**Optional extras.** Nothing here is installed for you:
| To use | You need |
| --- | --- |
@@ -199,7 +191,7 @@ Restart ComfyUI. Click **PM** in the top bar, or **Web UI** on a node, or open `
| GGUF JoyCaption (about 4.5 GB) | `llama-cpp-python` |
| HuggingFace JoyCaption (about 16 GB) | `transformers`, `accelerate`, `bitsandbytes` |
| Prompts embedded in videos | `ffprobe` on PATH |
| [LoRA Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) import | LoRA Manager installed. Turn the import on in System > Integrations. |
| [LoRA Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) import | LoRA Manager installed; turn it on in System > Integrations |
Download or unload tagging models in System > Auto-tagging.
@@ -216,40 +208,30 @@ Set `PROMPT_MANAGER_DATA_DIR` to an absolute folder to keep the library somewher
## Upgrading from an earlier version
- **Python 3.12 or newer is now required.**
- **Your library stays where it is until you choose.** The workspace offers two choices. **Move library** makes a verified copy in `user/__promptmanager/` and renames the old files without deleting them. **Keep it here** leaves the library in place.
- **Older images.** A one-time notice offers a metadata scan that links them to prompts and negatives. Scans don't count as new runs.
- **Going back isn't supported.** Prompt Manager now stores each workflow once, and an older version shows new records without their workflow or prompt graph. Back up first in System > Backup & export. See [the old README's changelog](README-legacy.md#changelog) for the manual way back.
- **Your library stays where it is** until you choose. The workspace offers **Move library**, which makes a verified copy in `user/__promptmanager/` and renames the old files instead of deleting them, or **Keep it here**.
- **Older images:** a one-time notice offers a metadata scan that links them to prompts and negatives. Scans don't count as new runs.
- **Going back isn't supported.** Workflows are now stored once, and an older version shows new records without their workflow or prompt graph. Back up first in System > Backup & export. See [the old README's changelog](README-legacy.md#changelog) for the manual way back.
## The old pages are gone
## The old pages still work
This version removes the dashboard, tags page, gallery and metadata viewer. The workspace does everything they did. Their URLs and bookmarks still work, and each one opens the matching workspace page.
They stay at their URLs, and System's Overview section links to them:
| Old URL | Opens |
| Page | URL |
| --- | --- |
| `/prompt_manager/admin` | Prompt library |
| `/prompt_manager/admin#/tags` | Tags & categories |
| `/prompt_manager/admin#/tags/cats,dogs?mode=or` | Prompt library, filtered to prompts tagged `cats` or `dogs` |
| `/prompt_manager/gallery` | Images |
| `/prompt_manager/gallery.html` | Inspect a file |
| Dashboard | `/prompt_manager/admin` |
| Tags | `/prompt_manager/admin#/tags` |
| Gallery | `/prompt_manager/gallery` |
| Metadata viewer | `/prompt_manager/gallery.html` |
A tag bookmark opens the Prompt library with that filter, and the filter stays in the address: `/prompt_manager/workspace#/library?tag=cats&tag=dogs&tag_mode=any`.
- Reload, Back and Forward keep the filter.
- The address follows the tags you set in **Filters**.
- You can bookmark such a link or write one yourself. Leave out `tag_mode` to match all the tags. `tag_mode=untagged` lists prompts without a tag.
- The sidebar's Prompt library link always shows the whole library.
- Search, category and sort aren't part of the address. **Save view** keeps those.
[README-legacy.md](README-legacy.md) still describes the old pages, for reference.
The documentation for those pages is in [README-legacy.md](README-legacy.md).
## Known limits
- **Trash is Linux and macOS only.** Windows has no Recycle Bin option, because the bin can delete large files permanently without warning. On Windows you can only remove an image from the library, and the file stays on disk. Where a move to the trash isn't possible on Linux or macOS, the dialog lists the reason for each file.
- **Permanent delete is Linux and BSD only.** You can't undo it. The safety backup brings back the library records, not the files.
- **Show in folder** opens the file manager on the machine running ComfyUI, which may not be the machine with your browser.
- **Trash is Linux and macOS only.** Windows has no Recycle Bin option, because the bin can delete large files permanently without warning. On Windows you can only remove an image from the library, and the file stays on disk. Where a move to the trash isn't possible on Linux or macOS, the dialog lists why for each file.
- **Show in folder** opens the file manager on the machine running ComfyUI, not necessarily the one with your browser.
- **Returned images** get their prompt links back, but not their tags, categories, collections or favorites.
- **Inspect a file** doesn't add the file to your library.
- **Leave unresolved is permanent.** Needs review doesn't offer the file again unless its bytes change.
- **Leave unresolved is permanent.** A file you leave unresolved in Needs review isn't offered again unless its bytes change.
- **Pair prompts saved by earlier versions** stay Uncategorized. You can set the category with Edit metadata.
## How it's tested
@@ -261,12 +243,8 @@ A tag bookmark opens the Prompt library with that filter, and the filter stays i
| Browser | Over 60 Playwright spec files in Chromium, Firefox, WebKit and touch emulation |
| Real ComfyUI | A pinned CPU ComfyUI, started in Classic and Nodes 2.0, running real workflows |
Every pull request runs the Python suite, the frontend tests and the browser tests in Chromium, once. Firefox, WebKit, touch emulation, Python 3.13 and 3.14, Windows and the real ComfyUI run every night. Nothing tests macOS. It should work, but support is best-effort. To run the tests yourself, see [TESTING.md](TESTING.md).
## Changelog
[CHANGELOG.md](CHANGELOG.md) lists what changed in each release and the contributors whose pull requests are part of it. Full notes are on the [releases page](https://github.com/ComfyAssets/ComfyUI_PromptManager/releases).
Linux runs on every pull request and in the merge queue. Windows runs on every push to main and nightly. macOS is not tested; it should work, but support is best-effort. To run the tests yourself, see [TESTING.md](TESTING.md).
## License
The license is MIT. See [LICENSE](LICENSE).
MIT. See [LICENSE](LICENSE).
+281 -903
View File
File diff suppressed because it is too large Load Diff
+14 -46
View File
@@ -102,7 +102,6 @@ try:
def _preview_startup():
api.start_preview_location()
api.recover_thumbnail_move() # an interrupted move, before the sweep
api.sweep_thumbnail_temps()
threading.Thread(
@@ -119,8 +118,6 @@ try:
# Build each output root's Images listing once the server's loop runs,
# so the first open does not wait for the walk (#348).
host_app.on_startup.append(api.warm_gallery_listings)
# #320: old thumbnails a move left to remove, once it is checked.
host_app.on_startup.append(api.finish_thumbnail_move)
if host_app is not None and hasattr(host_app, "on_shutdown"):
# Open Needs review change streams end before the server waits on them.
host_app.on_shutdown.append(api.close_review_events)
@@ -156,13 +153,12 @@ try:
_global_prompt_tracker = get_prompt_tracker(_global_db)
_global_image_monitor = get_image_monitor(_global_db, _global_prompt_tracker)
# The Needs review pass runs on the API's review worker (#659), through
# the capture store the scan and the Tag dialog use: an output the
# monitor leaves unlinked at its final outcome is queued as a scan would
# queue it, and a linked one's pending items leave the queue. The package
# teardown detaches it and stops the worker before that store is closed.
# The Needs review pass for ambiguous new outputs runs through the API's
# capture store (the one the scan and the Tag dialog use): a linked output
# is never queued and its pending items leave the queue. The package
# teardown detaches it before that store is closed at shutdown.
if api is not None:
_global_image_monitor.set_review_recorder(api.queue_review_file)
_global_image_monitor.set_review_recorder(api.record_review_file)
# Every settled output's preview is queued for the API's background
# worker (#249): the workspace never asks to generate thumbnails.
_global_image_monitor.set_thumbnail_queue(api.queue_capture_thumbnail)
@@ -293,26 +289,15 @@ def _teardown_logger():
return logging.getLogger("prompt_manager.init")
def _review_worker_started(api_object):
"""Whether the API's Needs review worker ever started (False without
one, or when the check fails)."""
try:
return bool(api_object is not None and api_object.review_worker_started())
except Exception:
return False
def _stop_background_work():
"""Stop the image monitor, the Needs review worker, the preview worker,
the job worker threads and the prompt cleanup thread against one
TEARDOWN_SECONDS deadline, once.
"""Stop the image monitor, the preview worker, the job worker threads
and the prompt cleanup thread against one TEARDOWN_SECONDS deadline, once.
Returns ``{"monitor", "review", "thumbnails", "workers", "tracker"}``
booleans (True: it stopped), leaving out parts that never started.
Later calls return a copy of the first result. A Ctrl+C inside a step is
logged and the step is False; one between steps is re-raised after the
result (parts not reached are False) is stored and the ``atexit`` entry
removed.
Returns ``{"monitor", "thumbnails", "workers", "tracker"}`` booleans
(True: it stopped), leaving out parts that never started. Later calls return a
copy of the first result. A Ctrl+C inside a step is logged and the
step is False; one between steps is re-raised after the result (parts
not reached are False) is stored and the ``atexit`` entry removed.
"""
global _background_work_result
with _background_work_lock:
@@ -327,10 +312,8 @@ def _stop_background_work():
# A part whose global is set has started; False until its step says
# otherwise, so an interrupt between steps leaves an honest result.
reviews = thumbnails # the API also owns the review worker (#659)
started = (
("monitor", monitor),
("review", _review_worker_started(reviews) or None),
("thumbnails", thumbnails),
("workers", parallel.job_pool_started() or None),
("tracker", tracker),
@@ -363,18 +346,6 @@ def _stop_background_work():
result["monitor"] = _teardown_step(
"the image monitor", stop_monitor, logger
)
if reviews is not None:
def stop_reviews():
from .py.api.review_recording import REVIEW_STOP_SECONDS
return reviews.stop_review_worker(left(REVIEW_STOP_SECONDS))
# Always stopped, so no later output starts it; reported
# only when it ran (an image in hand may have started it).
stopped = _teardown_step("the review worker", stop_reviews, logger)
if "review" in result or _review_worker_started(reviews):
result["review"] = stopped
if thumbnails is not None:
def close_previews():
@@ -487,11 +458,8 @@ except Exception as e:
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
# One startup line, printed at import on purpose: it is the package's banner on
# stdout, as ComfyUI's other custom nodes print theirs. Not a log record: the
# console log handler hides INFO by default, so a logger would drop it. ASCII
# only: a Windows console using a legacy code page cannot print emoji, and a
# UnicodeEncodeError here would abort loading the node.
# One startup line. ASCII only: a Windows console using a legacy code page
# cannot print emoji, and a UnicodeEncodeError here would abort loading the node.
print(
f"\033[94m[ComfyUI-PromptManager] Version:\033[0m {get_version()}"
f" - {len(NODE_CLASS_MAPPINGS)} tools loaded"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

+7
View File
@@ -291,6 +291,13 @@ class AnnotationOperations:
conn.execute(_BUMP_INDEX)
return conn.execute(_REVISION, (byte_id,)).fetchone()[0]
def _current_set(self, conn, sha256, byte_id, revision) -> dict:
return {
"sha256": sha256,
"tags": self._byte_tags(conn, byte_id),
"tag_revision": revision,
}
def read_image_tags(self, locator: str, sha256: str) -> dict:
"""The stored set of these exact bytes, or an empty set at revision 0.
+25 -20
View File
@@ -16,17 +16,18 @@ check, and none of them carries a server path.
import datetime
import logging
import ntpath
import os
import sqlite3
from pathlib import PurePosixPath, PureWindowsPath
from urllib.parse import quote
try:
from ..utils.hashing import register_prompt_functions
from .models import normalize_image_path
from .sqlite_uri import readonly_uri
except ImportError:
from utils.hashing import register_prompt_functions
from database.models import normalize_image_path
from database.sqlite_uri import readonly_uri
logger = logging.getLogger("prompt_manager.database.health")
@@ -88,6 +89,25 @@ def _counted(lines):
return _result(count, detail)
def readonly_uri(db_path, *, windows=None):
"""The ``mode=ro`` SQLite URI of *db_path*, on this platform or the given one.
pathlib spells a UNC path ``\\\\server\\share\\x.db`` as
``file://server/share/x.db``, a remote authority SQLite refuses to open.
With an empty authority (``file:////server/share/x.db``) SQLite hands
Windows the ``//server/share`` path, which it opens as the UNC path.
"""
if windows is None:
windows = os.name == "nt"
db_path = os.path.abspath(db_path)
if not windows:
return PurePosixPath(db_path).as_uri() + "?mode=ro"
path = PureWindowsPath(db_path)
if ntpath.splitdrive(str(path))[0].startswith("\\\\"):
return "file:" + quote("//" + path.as_posix()) + "?mode=ro"
return path.as_uri() + "?mode=ro"
def _integrity(conn, _roots):
rows = [
row[0] for row in conn.execute(f"PRAGMA integrity_check({INTEGRITY_LIMIT})")
@@ -179,23 +199,6 @@ def link_states(rows, roots, readable):
check's ``missing_files`` and the maintenance missing-link plan both
judge links this way, so their counts agree.
"""
for row, owner, state in _placed_links(rows, roots, readable):
if state is None:
state = "present" if os.path.exists(row[1]) else "missing"
yield row, owner, state
def held_links(rows, roots, readable):
"""``(row, owner, state)`` for each link ``link_states`` holds back
(``unavailable`` or ``outside``), without looking at any file (#586)."""
for row, owner, state in _placed_links(rows, roots, readable):
if state is not None:
yield row, owner, state
def _placed_links(rows, roots, readable):
"""``link_states`` before any file is looked at: state None means the
link lies under a readable source."""
prefixes = [_root_prefix(root) for root in roots]
for row in rows:
owner = _image_owner(row[1], row[3], prefixes)
@@ -203,8 +206,10 @@ def _placed_links(rows, roots, readable):
yield row, None, "outside"
elif not readable[owner]:
yield row, owner, "unavailable"
elif os.path.exists(row[1]):
yield row, owner, "present"
else:
yield row, owner, None
yield row, owner, "missing"
def _unavailable_line(unavailable, *, partial):
-3
View File
@@ -97,9 +97,6 @@ _ORDERS = {
"newest": ("COALESCE(julianday(p.created_at),0)", "DESC"),
"oldest": ("COALESCE(julianday(p.created_at),0)", "ASC"),
"name": (_NAME, "ASC"),
"name-desc": (_NAME, "DESC"),
"most-used": ("COALESCE(p.run_count,0)", "DESC"),
"last-used": ("COALESCE(julianday(p.last_used_at),0)", "DESC"),
"rating": ("COALESCE(p.rating,0)", "DESC"),
}
# Pair archive scopes for variant and image reads, as conditions on alias pp.
+2 -2
View File
@@ -47,11 +47,11 @@ import sqlite3
import time
import types
import uuid
from pathlib import Path
from dataclasses import dataclass, field
from typing import Callable, Dict, List, Optional, Tuple
from .models import BUSY_TIMEOUT_SECONDS, PromptModel
from .sqlite_uri import readonly_uri
try:
from ..utils import library_location as ll
@@ -322,7 +322,7 @@ def _verify_copy(temp: str, counts, documents) -> None:
"verify-failed",
f"{MESSAGES['verify-failed']} {detail}" if detail else None,
)
uri = readonly_uri(temp)
uri = Path(os.path.abspath(temp)).as_uri() + "?mode=ro"
try:
with contextlib.closing(sqlite3.connect(uri, uri=True)) as conn:
copied = _describe(conn)
+24 -112
View File
@@ -2,8 +2,7 @@
Four operations, each the native owner of a legacy ``/maintenance`` one and
built on the same queries, so a preview counts what the legacy cleanup would
change (``workflow_storage`` and #550's ``pair_metadata``, which fills old
Pair prompts' empty category and tags, live in their own modules):
change:
- ``duplicate_prompts``: prompts whose text is equal ignoring case and outer
spaces (``DUPLICATE_PROMPTS_SQL``, legacy ``cleanup_duplicates``); each
@@ -19,10 +18,6 @@ Pair prompts' empty category and tags, live in their own modules):
It also forgets the removal marks (#480) that hide nothing any more: the
file is gone or changed, under a readable source (#501, ``_stale_marks``).
#618's ``tag_cleanup`` (``database/tag_cleanup.py``) is planned from a tag
search's findings, never previewed here; its apply rechecks each target and
keeps the ones that changed instead of refusing the whole plan.
``preview_maintenance`` reads one snapshot on its own ``mode=ro`` connection
(``health.readonly_uri``) and closes it in ``finally``; files are looked at
after the snapshot ended. It returns a ``MaintenanceDraft``: the public plan
@@ -47,7 +42,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from .execution_contexts import LIVE_HINT_CTES
from .health import BATCH_ROWS, held_links, link_states, readable_roots, readonly_uri
from .health import BATCH_ROWS, link_states, readable_roots, readonly_uri
from .image_removal_schema import TABLE as MARKS_TABLE
from .image_removal_schema import clear_marks, has_marks_table
from .pairs import PairDependencyError
@@ -65,12 +60,6 @@ MAINTENANCE_OPERATIONS = (
"missing_links",
# Applied as its own batched job (database/workflow_storage.py).
"workflow_storage",
# #550: fill old Pair prompts' empty category and tags
# (database/pair_metadata_repair.py).
"pair_metadata",
# #618: tags to clean up, found by a job and planned from its findings
# (database/tag_cleanup.py); never previewed without them.
"tag_cleanup",
)
MAX_DETAILS = 50 # detail rows a plan lists
MAX_RESULT_ROWS = 200 # changed records an apply describes (the job lists 200)
@@ -137,16 +126,6 @@ _UNLINKED_PROTECTIONS_SQL = (
+ "), 0) FROM prompts p WHERE NOT EXISTS "
"(SELECT 1 FROM generated_images gi WHERE gi.prompt_id = p.id)"
)
# Each prompt no image links to, with which protections keep it (#586); the
# ones with none are filtered out in Python, so each predicate runs once.
_UNLINKED_KEPT_SQL = (
"WITH "
+ LIVE_HINT_CTES
+ " SELECT p.id, "
+ ", ".join(f"({predicate})" for predicate, _many, _one in PROTECTIONS)
+ " FROM prompts p WHERE NOT EXISTS "
"(SELECT 1 FROM generated_images gi WHERE gi.prompt_id = p.id) ORDER BY p.id"
)
# Duplicate prompt groups, as the legacy cleanup finds them (case-insensitive
# text; GROUP_CONCAT order is sorted by created_at afterwards).
@@ -176,14 +155,6 @@ _PROMPT_STATE_SQL = (
"ORDER BY id",
)
# Why the missing-link cleanup holds a link back: (one, many) (#586).
HELD_LINK_REASONS = {
"unavailable": (
"link under an unavailable source",
"links under unavailable sources",
),
"outside": ("link outside the image sources", "links outside the image sources"),
}
NO_FILES_DELETED = "No image file is deleted."
LINKS_ONLY = "Database links only; no image file is deleted."
UNUSED_DETAIL = "No image, saved pair, Library state or recorded run uses it"
@@ -197,7 +168,6 @@ CONFLICT_REASONS = {
"groups have their own Library titles",
),
}
PAIRED_DETAIL = "Kept: belongs to a saved pair"
CONFLICT_DETAILS = {
"collision": "Kept: two copies link the same image",
"title": "Kept: a copy has its own Library title",
@@ -439,35 +409,6 @@ def _source_name(root, index):
return os.path.basename(str(root).rstrip("\\/")) or f"Source {index + 1}"
def _kept_duplicates(paired, conflicted):
"""``{prompt_id, reasons}`` for each prompt of a group kept whole (#586).
The reasons are the review's details without "Kept: ".
"""
held = [(ids, PAIRED_DETAIL) for ids in paired] + [
(ids, CONFLICT_DETAILS[reason]) for ids, reason in conflicted
]
return [
{"prompt_id": prompt_id, "reasons": [detail.removeprefix("Kept: ")]}
for ids, detail in held
for prompt_id in ids
]
def _kept_unused(conn):
"""``{prompt_id, reasons}`` for each prompt the unused prune keeps (#586).
The reasons are the review's, one per protection that applies, in the
order the plan names them.
"""
kept = []
for row in conn.execute(_UNLINKED_KEPT_SQL):
reasons = [one for flag, (_p, _m, one) in zip(row[1:], PROTECTIONS) if flag]
if reasons:
kept.append({"prompt_id": row[0], "reasons": reasons})
return kept
class MaintenanceOperations:
"""Mixin for PromptDatabase: maintenance previews and their apply."""
@@ -581,9 +522,6 @@ class MaintenanceOperations:
"""
if operation not in MAINTENANCE_OPERATIONS:
raise ValueError(f"Unknown maintenance operation {operation!r}")
if operation == "tag_cleanup":
# Planned from a find's findings (tag_cleanup.plan_tag_cleanup).
raise ValueError("tag_cleanup is planned from a tag search")
roots = [str(root) for root in roots]
if operation == "optimize":
return self._plan_optimize()
@@ -595,10 +533,6 @@ class MaintenanceOperations:
lambda conn: (self._link_rows(conn), _mark_rows(conn)),
)
return self._plan_missing_links(rows, roots, _stale_marks(marks, roots))
if operation == "pair_metadata":
from .pair_metadata_repair import plan_pair_metadata
return _read_snapshot(self.model.db_path, plan_pair_metadata)
reader = (
self._plan_duplicate_prompts
if operation == "duplicate_prompts"
@@ -650,7 +584,7 @@ class MaintenanceOperations:
+ [
{
"label": _excerpt(texts.get(group[0])),
"detail": PAIRED_DETAIL,
"detail": "Kept: belongs to a saved pair",
}
for group in paired
]
@@ -728,24 +662,6 @@ class MaintenanceOperations:
],
)
def kept_links(self, roots):
"""``{image_path, owner, reason}`` for each link the missing-link
cleanup holds back under ``roots`` (blocking, reads only, no file
opened); ``owner`` indexes ``roots`` (None outside every source).
``reason`` is the review's (``HELD_LINK_REASONS``), one link each.
"""
roots = [str(root) for root in roots]
rows = _read_snapshot(self.model.db_path, self._link_rows)
return [
{
"image_path": row[1],
"owner": owner,
"reason": HELD_LINK_REASONS[state][0],
}
for row, owner, state in held_links(rows, roots, readable_roots(roots))
]
@staticmethod
def _links_fingerprint(candidates, stale=()):
fingerprint = _Fingerprint("missing_links")
@@ -765,11 +681,23 @@ class MaintenanceOperations:
unavailable += 1
elif state == "outside":
outside += 1
reasons = [
_plural(count, *HELD_LINK_REASONS[state])
for state, count in (("unavailable", unavailable), ("outside", outside))
if count
]
reasons = []
if unavailable:
reasons.append(
_plural(
unavailable,
"link under an unavailable source",
"links under unavailable sources",
)
)
if outside:
reasons.append(
_plural(
outside,
"link outside the image sources",
"links outside the image sources",
)
)
count = len(candidates)
parts = []
if count:
@@ -872,13 +800,7 @@ class MaintenanceOperations:
records changed and up to ``MAX_RESULT_ROWS`` descriptions of them
(``{prompt_id[, kept_id]}`` or ``{image_path}``). ``marks`` are a
missing-links plan's stale removal marks; that apply also returns
``marks``, how many it forgot. ``pair_metadata`` returns every filled
prompt, uncapped (its job keeps the complete record, #550). The
prompt operations also return ``kept``: every prompt the plan keeps,
``{prompt_id, reasons}`` in the review's wording (#550, #586); the
links a missing-links plan keeps are read by ``kept_links``.
``tag_cleanup`` (#618) does not compare the fingerprint: it rechecks
each target and returns every deleted and kept tag, uncapped.
``marks``, how many it forgot.
"""
if operation not in MAINTENANCE_OPERATIONS or operation == "workflow_storage":
raise ValueError(f"Unknown maintenance operation {operation!r}")
@@ -893,15 +815,6 @@ class MaintenanceOperations:
"unused_components": self._apply_unused_components,
}
with self._pair_transaction() as conn:
if operation == "pair_metadata":
from .pair_metadata_repair import apply_pair_metadata
return apply_pair_metadata(conn, fingerprint, targets)
if operation == "tag_cleanup":
# #618: each target is rechecked; a changed one is kept.
from .tag_cleanup import apply_tag_cleanup
return apply_tag_cleanup(conn, targets)
if operation == "missing_links":
return self._apply_missing_links(
conn, fingerprint, targets, roots, list(marks)
@@ -909,11 +822,10 @@ class MaintenanceOperations:
return appliers[operation](conn, fingerprint, targets, roots)
def _apply_duplicate_prompts(self, conn, fingerprint, targets, _roots):
groups, paired, conflicted, current = self._duplicates_fingerprint(conn)
groups, _paired, _conflicted, current = self._duplicates_fingerprint(conn)
if current != fingerprint or groups != targets:
raise PlanChanged("duplicate_prompts")
changed, rows = 0, []
kept = _kept_duplicates(paired, conflicted)
for sorted_ids in groups:
removed, _moved = self._merge_duplicate_group(conn, sorted_ids, strict=True)
changed += removed
@@ -921,7 +833,7 @@ class MaintenanceOperations:
{"prompt_id": duplicate_id, "kept_id": sorted_ids[0]}
for duplicate_id in sorted_ids[1:]
)
return {"changed": changed, "rows": rows[:MAX_RESULT_ROWS], "kept": kept}
return {"changed": changed, "rows": rows[:MAX_RESULT_ROWS]}
def _apply_unused_components(self, conn, fingerprint, targets, _roots):
ids, current = self._unused_fingerprint(conn)
@@ -933,7 +845,7 @@ class MaintenanceOperations:
{"prompt_id": prompt_id, "text": _excerpt(texts.get(prompt_id))}
for prompt_id in ids[:MAX_RESULT_ROWS]
]
return {"changed": changed, "rows": rows, "kept": _kept_unused(conn)}
return {"changed": changed, "rows": rows}
def _apply_missing_links(self, conn, fingerprint, targets, roots, marks):
rows = []
+4 -3
View File
@@ -14,7 +14,6 @@ from contextlib import closing
from pathlib import Path
from typing import Optional, Set, Tuple
from .sqlite_uri import readonly_uri
from .managed_connection import (
ManagedConnection,
await_closed,
@@ -1200,7 +1199,7 @@ class PromptModel:
if header != SQLITE_HEADER:
return False, "Not a SQLite database file"
uri = readonly_uri(path)
uri = Path(os.path.abspath(path)).as_uri() + "?mode=ro"
try:
conn = sqlite3.connect(uri, uri=True)
except sqlite3.Error as e:
@@ -1307,7 +1306,9 @@ class PromptModel:
replacement (for example, incompatible page sizes in WAL mode),
propagate the error rather than copy files under other open owners.
"""
source = sqlite3.connect(readonly_uri(Path(src_path).resolve()), uri=True)
source = sqlite3.connect(
Path(src_path).resolve().as_uri() + "?mode=ro", uri=True
)
try:
target = self.get_connection()
# The target is written under backup's step too: mark it in use
+22 -7
View File
@@ -26,7 +26,7 @@ from .review_decisions import ReviewDecisionOperations
from .saved_views import SavedViewOperations
from .library_commands import LibraryCommandOperations
from .library_archive import LibraryArchiveOperations, delete_prompt_rows
from .vocabulary import VocabularyOperations, bump_image_tag_bytes
from .vocabulary import VocabularyOperations
from .execution_history import ExecutionHistoryOperations
from .execution_contexts import ExecutionContextOperations
from .execution_outputs import ExecutionOutputOperations
@@ -1049,8 +1049,7 @@ class PromptDatabase(
if include_ancestors:
ancestors = set()
for folder in folders:
# #646: ``folder`` already uses ``/``; on POSIX ``\\`` is a name.
parts = folder.split("/")
parts = folder.replace("\\", "/").split("/")
for i in range(1, len(parts)):
ancestors.add("/".join(parts[:i]))
folders.update(ancestors)
@@ -1262,10 +1261,26 @@ class PromptDatabase(
"has_more": (offset + limit) < total,
}
# Vocabulary rename, merge and delete bump image tag revisions through
# the connection-level helper (database/vocabulary.py, shared with #618's
# tag cleanup).
_bump_image_tag_bytes = staticmethod(bump_image_tag_bytes)
@staticmethod
def _bump_image_tag_bytes(conn: sqlite3.Connection, tag_id: int) -> int:
"""Move the tag revision of every image set that carries *tag_id*.
Vocabulary rename, merge and delete change what an image's set reads
as, so a Tag dialog opened before the change must see ``tag-conflict``
on Save instead of recreating the old name. Bumps the image index
revision once when any set was affected; returns that count.
"""
cursor = conn.execute(
"UPDATE media_annotation_bytes SET tag_revision = tag_revision + 1 "
"WHERE id IN (SELECT byte_id FROM media_image_tags WHERE tag_id = ?)",
(tag_id,),
)
if cursor.rowcount > 0:
conn.execute(
"UPDATE media_annotation_metadata SET "
"image_index_revision = image_index_revision + 1 WHERE singleton_id = 1"
)
return cursor.rowcount
@classmethod
def _move_tag_links(
-452
View File
@@ -1,452 +0,0 @@
"""Pair category and tags repair (#550): the ``pair_metadata`` maintenance plan.
Before #546 a Pair node run saved its category and tags on the saved pair
only; the positive prompt it created stayed Uncategorized and untagged. This
plan fills the **empty** category and the **empty** tag set of those prompts
from their saved pairs (``docs/egm/post-3.4.1/550-design.md``):
- Considered: prompts the Pair node created as a positive (their earliest
pair, in either role, has them as the positive and its ``created_at`` is
within ``PAIR_CREATED_TOLERANCE`` of theirs) whose category is blank
and/or that have no tags.
- Sources: the prompt's non-archived pairs where it is the positive. Pairs
with a blank category or no tags are ignored for that field. A field fills
when exactly one value remains (category: trimmed, case-sensitive; tags:
the tag-id set).
- Kept (protected), in this order: archived prompt, edited prompt
(``updated_at`` not within the tolerance of ``created_at``), pairs that
disagree, a tag set over ``MAX_LIBRARY_TAGS``.
The apply runs in the caller's ``BEGIN IMMEDIATE`` transaction, recomputes
the fingerprint, then writes guarded statements (the field must still be
empty) that never touch a pair, a negative or ``updated_at``. A guard that
hits nothing raises ``PlanChanged`` so the whole transaction rolls back.
"""
import datetime
from . import maintenance as _maintenance
from .library_commands import MAX_LIBRARY_TAGS
from .maintenance import (
MAX_DETAILS,
MaintenanceDraft,
PlanChanged,
_excerpt,
_Fingerprint,
_marks,
_plural,
)
OPERATION = "pair_metadata"
# Seconds: the Pair save stamps its new prompt and its pair with separate
# utc_now_iso() calls in one transaction (microseconds apart).
PAIR_CREATED_TOLERANCE = 2.0
# Fill prompts one plan applies; the rest are applied by the next review.
# Bounds the complete record a job keeps in memory (about 100 bytes a row).
MAX_PLAN_FILLS = 20000
DETAIL_VALUES = 3
DETAIL_TAGS = 5
MEDIA_LABEL = "No image file or saved pair is changed."
EMPTY_LABEL = "No Pair prompts are missing a category or tags"
RECORD_NOTE = (
"The job's report lists every filled field. Download it to keep it: "
"Activity forgets jobs after a restart."
)
# Protected classes in precedence order: (key, detail, reason one, many).
EDITED_DETAIL = (
"Kept: edited after it was saved; its empty category or tags may be intentional"
)
PROTECTED = (
(
"archived",
"Kept: archived in the Library",
"archived in the Library",
"archived in the Library",
),
(
"edited",
EDITED_DETAIL,
"edited after it was saved",
"edited after they were saved",
),
("conflict", None, "where pairs disagree", "where pairs disagree"),
(
"too-many-tags",
f"Kept: its pair has more than {MAX_LIBRARY_TAGS} tags",
f"whose pair has more than {MAX_LIBRARY_TAGS} tags",
f"whose pair has more than {MAX_LIBRARY_TAGS} tags",
),
)
_PROTECTED_ORDER = [key for key, *_rest in PROTECTED]
# Detail rows: what the user can act on (a conflict) first.
DETAIL_ORDER = ("conflict", "edited", "archived", "too-many-tags")
_CANDIDATES_SQL = """
SELECT p.id, p.hash, p.text, p.created_at, p.updated_at,
COALESCE(TRIM(p.category), '') = '' AS blank_category,
NOT EXISTS (SELECT 1 FROM prompt_tags pt WHERE pt.prompt_id = p.id)
AS untagged,
EXISTS (SELECT 1 FROM prompt_archive pa WHERE pa.prompt_id = p.id)
AS archived,
(SELECT CASE WHEN pp.positive_prompt_id = p.id
THEN pp.created_at END
FROM prompt_pairs pp
WHERE pp.positive_prompt_id = p.id OR pp.negative_prompt_id = p.id
ORDER BY pp.id LIMIT 1) AS first_pair_at
FROM prompts p
WHERE EXISTS (SELECT 1 FROM prompt_pairs pp WHERE pp.positive_prompt_id = p.id)
AND (COALESCE(TRIM(p.category), '') = ''
OR NOT EXISTS (SELECT 1 FROM prompt_tags pt WHERE pt.prompt_id = p.id))
ORDER BY p.id
"""
_SOURCES_SQL = (
"SELECT id, positive_prompt_id, TRIM(COALESCE(category, '')) FROM prompt_pairs "
"WHERE archived = 0 AND positive_prompt_id IN ({marks}) ORDER BY id"
)
_PAIR_TAGS_SQL = (
"SELECT ppt.pair_id, t.id, t.name FROM prompt_pair_tags ppt "
"JOIN tags t ON t.id = ppt.tag_id WHERE ppt.pair_id IN ({marks}) "
"ORDER BY ppt.pair_id, t.id"
)
def parse_stamp(value):
"""A stored timestamp as an aware UTC datetime, or None when unreadable."""
if not isinstance(value, str) or not value.strip():
return None
try:
stamp = datetime.datetime.fromisoformat(value.strip())
except ValueError:
return None
if stamp.tzinfo is None:
stamp = stamp.replace(tzinfo=datetime.timezone.utc)
return stamp
def _close(first, second):
"""Whether two stored stamps parse and lie within the tolerance."""
a, b = parse_stamp(first), parse_stamp(second)
if a is None or b is None:
return False
return abs((a - b).total_seconds()) <= PAIR_CREATED_TOLERANCE
def _batches(ids):
size = _maintenance.ID_BATCH
for start in range(0, len(ids), size):
yield ids[start : start + size]
def _sources(conn, ids):
"""``{prompt_id: [(pair_id, category, ((tag_id, name), ...)), ...]}``."""
pairs = {}
for batch in _batches(ids):
for pair_id, prompt_id, category in conn.execute(
_SOURCES_SQL.format(marks=_marks(batch)), batch
):
pairs.setdefault(prompt_id, []).append([pair_id, category, []])
by_pair = {pair[0]: pair for group in pairs.values() for pair in group}
pair_ids = sorted(by_pair)
for batch in _batches(pair_ids):
for pair_id, tag_id, name in conn.execute(
_PAIR_TAGS_SQL.format(marks=_marks(batch)), batch
):
by_pair[pair_id][2].append((tag_id, name))
return {
prompt_id: [(pid, category, tuple(tags)) for pid, category, tags in group]
for prompt_id, group in pairs.items()
}
def _field(values, guard):
"""``(class, value)`` of one field from its distinct values, or None."""
if not values:
return None
if guard:
return (guard, None)
if len(values) > 1:
return ("conflict", sorted(values))
return ("fill", next(iter(values)))
def _classify(row, sources):
"""The result of one considered prompt, or None when nothing applies."""
guard = None
if row["archived"]:
guard = "archived"
elif not _close(row["updated_at"], row["created_at"]):
guard = "edited"
category = tags = None
tag_pair = None
if row["blank_category"]:
category = _field({c for _p, c, _t in sources if c}, guard)
if row["untagged"]:
sets = {}
for pair_id, _category, pair_tags in sources:
if pair_tags:
sets.setdefault(frozenset(pair_tags), pair_id)
tags = _field(set(sets), guard)
if tags and tags[0] == "fill":
tag_pair = sets[tags[1]]
if len(tags[1]) > MAX_LIBRARY_TAGS:
tags = ("too-many-tags", None)
else:
tags = ("fill", tuple(sorted(tags[1])))
elif tags and tags[0] == "conflict":
tags = ("conflict", [sorted(s) for s in sorted(sets, key=sorted)])
if category is None and tags is None:
return None
return {
"id": row["id"],
"hash": row["hash"],
"text": row["text"],
"category": category,
"tags": tags,
"tag_pair": tag_pair if tags and tags[0] == "fill" else None,
"pairs": [pair_id for pair_id, _c, _t in sources],
}
def _state(conn):
"""``(results, fingerprint)``: every considered prompt's result, by id."""
considered = []
for row in conn.execute(_CANDIDATES_SQL):
row = dict(
zip(
(
"id",
"hash",
"text",
"created_at",
"updated_at",
"blank_category",
"untagged",
"archived",
"first_pair_at",
),
tuple(row),
)
)
if _close(row["created_at"], row["first_pair_at"]):
considered.append(row)
sources = _sources(conn, [row["id"] for row in considered])
fingerprint = _Fingerprint(OPERATION)
results = []
for row in considered:
result = _classify(row, sources.get(row["id"], []))
if result is None:
continue
results.append(result)
fingerprint.add(
[
result["id"],
result["hash"],
result["category"],
result["tags"],
result["tag_pair"],
result["pairs"],
]
)
return results, fingerprint.hexdigest()
def _fills(result):
return (
bool(result["category"] and result["category"][0] == "fill"),
bool(result["tags"] and result["tags"][0] == "fill"),
)
def _targets(results):
targets = []
for result in results:
category, tags = _fills(result)
if category or tags:
targets.append([result["id"], category, tags])
return targets[:MAX_PLAN_FILLS]
def _protected_classes(result):
"""The protected classes of a result's fields, in precedence order."""
found = {
field[0]
for field in (result["category"], result["tags"])
if field and field[0] != "fill"
}
return [key for key in _PROTECTED_ORDER if key in found]
def _more(values, limit):
shown = ", ".join(values[:limit])
return shown + (", …" if len(values) > limit else "")
def _fill_detail(result):
parts = []
category, tags = _fills(result)
if category:
parts.append(f"category “{result['category'][1]}”")
if tags:
names = sorted(name for _id, name in result["tags"][1])
noun = "tag" if len(names) == 1 else "tags"
parts.append(f"{len(names)} {noun}: {_more(names, DETAIL_TAGS)}")
pairs = [str(pair_id) for pair_id in result["pairs"]]
label = "pair" if len(pairs) == 1 else "pairs"
return f"Fills {' and '.join(parts)} ({label} {_more(pairs, DETAIL_VALUES)})"
def _protected_detail(result, key):
if key != "conflict":
return next(detail for k, detail, *_r in PROTECTED if k == key)
if result["category"] and result["category"][0] == "conflict":
values = result["category"][1]
return f"Kept: pairs disagree on category: {_more(values, DETAIL_VALUES)}"
return "Kept: pairs disagree on tags"
def _kept(results):
"""One row per kept prompt, its review reasons without "Kept: " (#550)."""
rows = []
for result in results:
classes = set(_protected_classes(result))
if classes:
rows.append(
{
"prompt_id": result["id"],
"reasons": [
_protected_detail(result, key).removeprefix("Kept: ")
for key in DETAIL_ORDER
if key in classes
],
}
)
return rows
def _details(results, targets):
rows = []
for key in DETAIL_ORDER:
for result in results:
if key in _protected_classes(result):
rows.append(
{
"label": _excerpt(result["text"]),
"detail": _protected_detail(result, key),
}
)
planned = {target[0] for target in targets}
for result in results:
if result["id"] in planned:
rows.append(
{"label": _excerpt(result["text"]), "detail": _fill_detail(result)}
)
if not targets:
return rows[:MAX_DETAILS]
return rows[: MAX_DETAILS - 1] + [{"label": "Record", "detail": RECORD_NOTE}]
def _scope_label(targets, total):
if not targets:
return EMPTY_LABEL
categories = sum(1 for _id, category, _tags in targets if category)
tag_sets = sum(1 for _id, _category, tags in targets if tags)
label = (
f"{_plural(len(targets), 'prompt')} to fill: "
f"{_plural(categories, 'category', 'categories')}, "
f"{_plural(tag_sets, 'tag set')}"
)
if total > len(targets):
label += (
f" (the first {len(targets):,} of {total:,}; review again for the rest)"
)
return label
def plan_pair_metadata(conn):
"""The reviewed ``pair_metadata`` plan on ``conn``'s snapshot."""
results, fingerprint = _state(conn)
targets = _targets(results)
total = sum(1 for result in results if any(_fills(result)))
counts = {key: 0 for key in _PROTECTED_ORDER}
held = 0
for result in results:
classes = _protected_classes(result)
held += bool(classes)
for key in classes:
counts[key] += 1
reasons = [
f"{counts[key]:,} {one if counts[key] == 1 else many}"
for key, _detail, one, many in PROTECTED
if counts[key]
]
return MaintenanceDraft(
operation=OPERATION,
fingerprint=fingerprint,
targets=targets,
scope={"count": len(targets), "label": _scope_label(targets, total)},
protected={"count": held, "reasons": reasons},
media={"deletes_files": False, "label": MEDIA_LABEL},
details=_details(results, targets),
)
def _fill_categories(conn, fills):
"""Set each blank category; raises PlanChanged when one is no longer blank."""
cursor = conn.executemany(
"UPDATE prompts SET category = ? WHERE id = ? "
"AND COALESCE(TRIM(category), '') = ''",
fills,
)
if cursor.rowcount != len(fills):
raise PlanChanged(OPERATION)
def _fill_tags(conn, fills, expected):
"""Copy each source pair's tags onto its untagged prompt."""
cursor = conn.executemany(
"INSERT INTO prompt_tags(prompt_id, tag_id) "
"SELECT ?, ppt.tag_id FROM prompt_pair_tags ppt "
"JOIN tags t ON t.id = ppt.tag_id WHERE ppt.pair_id = ? "
"AND NOT EXISTS (SELECT 1 FROM prompt_tags WHERE prompt_id = ?)",
fills,
)
if cursor.rowcount != expected:
raise PlanChanged(OPERATION)
def apply_pair_metadata(conn, fingerprint, targets):
"""Apply the reviewed fills on ``conn`` (inside BEGIN IMMEDIATE).
Returns ``{changed, categories, tag_sets, rows, kept}``; ``rows`` lists
every filled prompt (``{prompt_id, category?, tags?}``) and ``kept`` every
prompt the plan keeps (``{prompt_id, reasons}``, in the review's wording
and order), both never capped.
"""
results, current = _state(conn)
if current != fingerprint or _targets(results) != targets:
raise PlanChanged(OPERATION)
by_id = {result["id"]: result for result in results}
categories, tags, rows = [], [], []
tag_count = 0
for prompt_id, fill_category, fill_tags in targets:
result = by_id[prompt_id]
row = {"prompt_id": prompt_id}
if fill_category:
row["category"] = result["category"][1]
categories.append((row["category"], prompt_id))
if fill_tags:
row["tags"] = sorted(name for _id, name in result["tags"][1])
tags.append((prompt_id, result["tag_pair"], prompt_id))
tag_count += len(result["tags"][1])
rows.append(row)
if categories:
_fill_categories(conn, categories)
if tags:
_fill_tags(conn, tags, tag_count)
return {
"changed": len(rows),
"categories": len(categories),
"tag_sets": len(tags),
"rows": rows,
"kept": _kept(results),
}
+1 -2
View File
@@ -42,7 +42,6 @@ from typing import Dict, Optional
from . import workflow_documents as wd
from .execution_history_schema import rotate_history_epoch
from .safety_backup import take_safety_backup
from .sqlite_uri import readonly_uri
logger = logging.getLogger("prompt_manager.database.restore_stage")
@@ -115,7 +114,7 @@ def file_digest(path: str) -> str:
def _readonly(path: str) -> sqlite3.Connection:
return sqlite3.connect(readonly_uri(Path(path).resolve()), uri=True)
return sqlite3.connect(Path(path).resolve().as_uri() + "?mode=ro", uri=True)
def _schema(path: str) -> list:
+1 -23
View File
@@ -114,10 +114,6 @@ _PENDING_AT_STAT = (
f"JOIN {ITEMS_TABLE} i ON i.byte_id=b.id "
"WHERE f.locator=? AND b.size=? AND b.mtime_ns=? AND i.state='pending'"
)
# The newest pending item of the bytes verified at one stat (Inspect, #659).
_NEWEST_PENDING_AT_STAT = (
_PENDING_AT_STAT + " ORDER BY i.created_at DESC, i.rowid DESC LIMIT 1"
)
# Pending items of one file: the candidates a link settles.
_PENDING_OF_LOCATOR = (
f"SELECT i.id FROM {FILES_TABLE} f " # nosec B608
@@ -463,24 +459,6 @@ class ReviewOperations:
)
return row is not None
def review_item_at(self, locator: str, size: int, mtime_ns: int) -> dict | None:
"""Inspect's ``review`` facet of the bytes verified at this stat (#659).
``{"state": "pending", "item_id": ...}`` names the newest pending item
(any version); otherwise ``{"state": "decided"}`` when such bytes carry
a decided item; else None. Two indexed reads, no file access.
"""
_validate_locator(locator)
conn = self.model.get_connection()
row = conn.execute(
_NEWEST_PENDING_AT_STAT, (locator, size, mtime_ns)
).fetchone()
if row is not None:
return {"state": "pending", "item_id": row[0]}
if conn.execute(_DECIDED_AT, (locator, size, mtime_ns)).fetchone() is not None:
return {"state": "decided"}
return None
def review_file_linked(self, spellings) -> bool:
"""True when a saved row links the file under any of ``spellings``."""
with self._annotation_read() as conn:
@@ -558,7 +536,7 @@ class ReviewOperations:
"""Remove the pending, undecided items that offer nothing to choose.
``locators`` are files the caller found ambiguous without a choice
(no candidate carries a prompt). Of their items, one leaves
(fewer than two candidates carry a prompt). Of their items, one leaves
the queue only when its own stored evidence offers no choice either
(``evidence_offers_choice``) and it is still ``pending`` at revision 0
with no decision row, the same safe delete as
+8 -10
View File
@@ -215,24 +215,22 @@ def choosable(candidate: Any) -> bool:
# An item is worth a decision only when at least this many candidates offer
# a prompt; with none there is nothing to choose (maintainer test of
# #284/#288: 39 items whose candidates were all "unresolved"). One is enough
# (#657 addendum D1, 2026-11-20): the other branches stay listed, disabled,
# and the user may still leave the file unresolved.
MIN_CHOOSABLE = 1
# a prompt; with fewer there is nothing to choose between (maintainer test of
# #284/#288: 39 items whose candidates were all "unresolved").
MIN_CHOOSABLE = 2
def evidence_offers_choice(evidence: Any) -> bool:
"""False when stored evidence provably offers nothing to choose.
Unlimited evidence must list ``MIN_CHOOSABLE`` choosable candidates (the
saver anchor's one pair, #390, counts like any other). A limited item
stores none, only ``candidate_total``; it may offer a choice unless that
total is too small.
Unlimited evidence must list ``MIN_CHOOSABLE`` choosable candidates. A
limited item stores none, only ``candidate_total``; it may offer a choice
(more than ``MAX_CANDIDATES`` prompts) unless that total is too small.
"""
if not isinstance(evidence, dict):
return False
needed = MIN_CHOOSABLE
# The saver anchor's one pair (#390) is a suggestion to confirm.
needed = 1 if evidence.get("anchor") == "saver" else MIN_CHOOSABLE
if evidence.get("limited"):
total = evidence.get("candidate_total")
return type(total) is int and total >= needed
+1 -9
View File
@@ -31,15 +31,7 @@ MAX_STATE_BYTES = 4096
MAX_TAGS = 20
MAX_TAG_LENGTH = 50
_IMAGE_SORTS = ("newest", "oldest", "name", "name-desc", "rating")
_LIBRARY_SORTS = (
"newest",
"oldest",
"name",
"name-desc",
"most-used",
"last-used",
"rating",
)
_LIBRARY_SORTS = ("newest", "oldest", "name", "rating")
_MEDIA = ("all", "image", "video")
# How a Library view's Tags match (#444): every tag, any of them, or parents
# without tags ("untagged" never goes with tags; the listing refuses both).
-25
View File
@@ -1,25 +0,0 @@
"""The read-only SQLite URI of a path, safe for Windows network shares."""
import ntpath
import os
from pathlib import PurePosixPath, PureWindowsPath
from urllib.parse import quote
def readonly_uri(db_path, *, windows=None):
"""The ``mode=ro`` SQLite URI of *db_path*, on this platform or the given one.
pathlib spells a UNC path ``\\\\server\\share\\x.db`` as
``file://server/share/x.db``, a remote authority SQLite refuses to open.
With an empty authority (``file:////server/share/x.db``) SQLite hands
Windows the ``//server/share`` path, which it opens as the UNC path.
"""
if windows is None:
windows = os.name == "nt"
db_path = os.path.abspath(db_path)
if not windows:
return PurePosixPath(db_path).as_uri() + "?mode=ro"
path = PureWindowsPath(db_path)
if ntpath.splitdrive(str(path))[0].startswith("\\\\"):
return "file:" + quote("//" + path.as_posix()) + "?mode=ro"
return path.as_uri() + "?mode=ro"
-440
View File
@@ -1,440 +0,0 @@
"""Tag cleanup: a registry of rules over the tag registry (#618).
Each ``TagRule`` finds tag ids on a read-only connection, rechecks one
reviewed target on the write connection and applies it there. ``RULES`` is
the registry; its order is the review's order and decides ownership: a tag
belongs to the first rule that finds it and is listed only there. Two rules
ship:
- ``comma``: tags whose name holds an ASCII or a fullwidth comma (a whole
list saved as one tag, usually from a LoRA's trained words). A tag whose
name starts with ``lora:`` is never one: it is the LoRA import's identity
tag, which the next import makes again (maintainer ruling, 2026-11-22).
Applying removes the tag from its prompts, pairs and images and deletes it.
- ``unused``: tags no prompt, saved pair or image carries. Deleted.
``find_tag_cleanup`` reads one ``mode=ro`` snapshot and returns every rule's
findings (at most ``MAX_FINDINGS`` held per rule, totals exact).
``plan_tag_cleanup`` re-reads the selected findings on another snapshot; one
whose fingerprint ``(tag_id, name, links)`` changed since the find is
protected, not planned. ``links`` hashes the sorted prompt ids, pair ids and
``(byte_id, position)`` rows carrying the tag, so a tag moved from one prompt
to another is seen. ``apply_tag_cleanup`` runs inside the caller's ``BEGIN
IMMEDIATE`` and rechecks each target: one that changed is kept with its
reason and the rest still apply (one edited tag must not block hundreds).
Saved views are never rewritten; a finding says how many name it. The
auto-tag marks (``media_image_autotags``) are never read or written.
"""
import hashlib
import json
import sqlite3
from dataclasses import dataclass
from typing import Callable, Optional
from .maintenance import (
MAX_DETAILS,
MaintenanceDraft,
_Fingerprint,
_plural,
_read_snapshot,
)
from .vocabulary import VocabularyOperations, _delete_tag
OPERATION = "tag_cleanup"
MAX_FINDINGS = 2000 # findings a find holds and lists per rule
COMMAS = (",", ",")
LORA_PREFIX = "lora:"
CHANGED_SINCE_SEARCH = "changed since the search"
NO_FILES = "No files are removed"
# Findings are listed by name (case-insensitive), then id.
_COMMA_SQL = (
"SELECT id FROM tags WHERE (instr(name, ?) > 0 OR instr(name, ?) > 0) "
"AND substr(name, 1, ?) != ? ORDER BY name COLLATE NOCASE, id"
)
_UNUSED_SQL = (
"SELECT id FROM tags t WHERE "
"NOT EXISTS (SELECT 1 FROM prompt_tags x WHERE x.tag_id = t.id) AND "
"NOT EXISTS (SELECT 1 FROM prompt_pair_tags x WHERE x.tag_id = t.id) "
"ORDER BY name COLLATE NOCASE, id"
)
_UNUSED_WITH_IMAGES_SQL = (
"SELECT id FROM tags t WHERE "
"NOT EXISTS (SELECT 1 FROM prompt_tags x WHERE x.tag_id = t.id) AND "
"NOT EXISTS (SELECT 1 FROM prompt_pair_tags x WHERE x.tag_id = t.id) AND "
"NOT EXISTS (SELECT 1 FROM media_image_tags x WHERE x.tag_id = t.id) "
"ORDER BY name COLLATE NOCASE, id"
)
_ANNOTATION_TABLES = ("media_image_tags", "media_annotation_bytes")
@dataclass(frozen=True)
class TagRule:
"""One cleanup rule: its copy and its three functions."""
id: str
title: str
explanation: str
action_label: str
find: Callable[[sqlite3.Connection], list]
recheck: Callable[[sqlite3.Connection, dict], Optional[str]]
apply: Callable[[sqlite3.Connection, dict], None]
def _has_image_links(conn):
"""Whether the image annotation tables exist (else images link nothing)."""
found = conn.execute(
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN (?, ?)",
_ANNOTATION_TABLES,
).fetchone()[0]
return found == len(_ANNOTATION_TABLES)
def _links(conn, tag_id):
"""sha256 of the link rows carrying ``tag_id``: prompts, pairs, images."""
prompts = [
r[0]
for r in conn.execute(
"SELECT prompt_id FROM prompt_tags WHERE tag_id=? ORDER BY 1", (tag_id,)
)
]
pairs = [
r[0]
for r in conn.execute(
"SELECT pair_id FROM prompt_pair_tags WHERE tag_id=? ORDER BY 1",
(tag_id,),
)
]
images = []
if _has_image_links(conn):
images = [
[r[0], r[1]]
for r in conn.execute(
"SELECT byte_id, position FROM media_image_tags WHERE tag_id=? "
"ORDER BY 1, 2",
(tag_id,),
)
]
return _hash_links(prompts, pairs, images)
def _hash_links(prompts, pairs, images):
encoded = json.dumps([prompts, pairs, images], separators=(",", ":"))
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
NO_LINKS = _hash_links([], [], [])
def _find_comma(conn):
params = (*COMMAS, len(LORA_PREFIX), LORA_PREFIX)
return [row[0] for row in conn.execute(_COMMA_SQL, params)]
def _find_unused(conn):
sql = _UNUSED_WITH_IMAGES_SQL if _has_image_links(conn) else _UNUSED_SQL
return [row[0] for row in conn.execute(sql)]
def _identity_reason(conn, target):
"""``already deleted`` or ``renamed since the review``, else None."""
row = conn.execute("SELECT name FROM tags WHERE id=?", (target["tag_id"],))
row = row.fetchone()
if row is None:
return "already deleted"
if row[0] != target["name"]:
return "renamed since the review"
return None
def _recheck_comma(conn, target):
reason = _identity_reason(conn, target)
if reason is None and _links(conn, target["tag_id"]) != target["links"]:
reason = "its links changed since the review"
return reason
def _recheck_unused(conn, target):
reason = _identity_reason(conn, target)
if reason is None and _links(conn, target["tag_id"]) != target["links"]:
reason = "it is used now"
return reason
def _delete_target(conn, target):
"""Both shipped rules' apply: delete the tag; its links cascade."""
_delete_tag(conn, target["tag_id"])
def _apply_target(conn, target):
# Looked up at call time, so a test can stand in for the delete.
_delete_target(conn, target)
RULES = (
TagRule(
id="comma",
title="Tags containing a comma",
explanation=(
"A whole list saved as one tag, usually from a LoRA's trained words."
),
action_label=(
"Removes the tag from its prompts, pairs and images and deletes it."
),
find=_find_comma,
recheck=_recheck_comma,
apply=_apply_target,
),
TagRule(
id="unused",
title="Tags with no links",
explanation="No prompt, saved pair or image carries the tag.",
action_label="Deletes the tag.",
find=_find_unused,
recheck=_recheck_unused,
apply=_apply_target,
),
)
RULE_IDS = tuple(rule.id for rule in RULES)
_BY_ID = {rule.id: rule for rule in RULES}
def rule(rule_id):
"""The registered rule ``rule_id`` (KeyError when there is none)."""
return _BY_ID[rule_id]
def _saved_view_names(conn):
"""``{tag name: views naming it}`` from every saved view's state."""
exists = conn.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='saved_views'"
).fetchone()
if not exists:
return {}
counts = {}
for (state,) in conn.execute("SELECT state FROM saved_views"):
try:
tags = json.loads(state).get("tags") or []
except (TypeError, ValueError, AttributeError):
continue
for name in {tag for tag in tags if isinstance(tag, str)}:
counts[name] = counts.get(name, 0) + 1
return counts
def _finding(conn, rule_id, tag_id, views):
row = conn.execute("SELECT name FROM tags WHERE id=?", (tag_id,)).fetchone()
if row is None:
return None
counts = (
VocabularyOperations._tag_owner_counts(conn, tag_id)
if _has_image_links(conn)
else _counts_without_images(conn, tag_id)
)
return {
"rule": rule_id,
"tag_id": tag_id,
"name": row[0],
"prompts": counts["components_changed"],
"pairs": counts["pairs_changed"],
"images": counts["images_changed"],
"saved_views": views.get(row[0], 0),
"links": _links(conn, tag_id),
}
def _counts_without_images(conn, tag_id):
prompts = conn.execute(
"SELECT COUNT(DISTINCT prompt_id) FROM prompt_tags WHERE tag_id=?", (tag_id,)
).fetchone()[0]
pairs = conn.execute(
"SELECT COUNT(DISTINCT pair_id) FROM prompt_pair_tags WHERE tag_id=?",
(tag_id,),
).fetchone()[0]
return {"components_changed": prompts, "pairs_changed": pairs, "images_changed": 0}
def _owners_text(finding):
parts = [
_plural(finding[key], noun)
for key, noun in (("prompts", "prompt"), ("pairs", "pair"), ("images", "image"))
if finding[key]
]
return " · ".join(parts)
def finding_detail(finding):
"""The server's line for a finding: ``3 prompts · 1 pair``, ``no links``,
with `` · in 1 saved view`` when a saved view names it."""
detail = _owners_text(finding) or "no links"
views = finding.get("saved_views", 0)
if views:
detail += f" · in {_plural(views, 'saved view')}"
return detail
def find_tag_cleanup(db_path):
"""Every rule's findings on one ``mode=ro`` snapshot (blocking, read-only).
``{"rules": {rule_id: [finding, ...]}, "totals": {rule_id: int}}``:
findings by name (case-insensitive), then id; at most ``MAX_FINDINGS``
held per rule, totals exact. A tag is listed under the first rule that
finds it only.
"""
def read(conn):
owned = set()
views = _saved_view_names(conn)
rules, totals = {}, {}
for item in RULES:
ids = [tag_id for tag_id in item.find(conn) if tag_id not in owned]
owned.update(ids)
totals[item.id] = len(ids)
findings = []
for tag_id in ids[:MAX_FINDINGS]:
finding = _finding(conn, item.id, tag_id, views)
if finding is not None:
findings.append(finding)
rules[item.id] = findings
return {"rules": rules, "totals": totals}
return _read_snapshot(db_path, read)
def _target(finding):
return {
key: finding[key]
for key in (
"rule",
"tag_id",
"name",
"prompts",
"pairs",
"images",
"saved_views",
"links",
)
}
def _scope_label(targets):
if not targets:
return "No tags to delete"
prompts = sum(t["prompts"] for t in targets)
pairs = sum(t["pairs"] for t in targets)
images = sum(t["images"] for t in targets)
return (
f"Delete {_plural(len(targets), 'tag')} (removed from "
f"{_plural(prompts, 'prompt')}, {_plural(pairs, 'pair')} and "
f"{_plural(images, 'image')})"
)
def plan_tag_cleanup(db_path, held, tag_ids_by_rule):
"""The reviewed plan for the selected findings (blocking, read-only).
``held`` is a ``find_tag_cleanup`` result and ``tag_ids_by_rule``
``{rule_id: [tag_id, ...]}`` of its findings (the caller validated
both). Each selected finding is read again on one snapshot; one whose
``(tag_id, name, links)`` changed since the find is protected
(``changed since the search``), not planned. Targets follow the
registry's order, then the find's.
"""
reviewed = {
(finding["rule"], finding["tag_id"]): finding
for findings in held["rules"].values()
for finding in findings
}
def read(conn):
views = _saved_view_names(conn)
targets, protected = [], []
for item in RULES:
for tag_id in tag_ids_by_rule.get(item.id, ()):
before = reviewed[(item.id, tag_id)]
now = _finding(conn, item.id, tag_id, views)
same = now is not None and (now["name"], now["links"]) == (
before["name"],
before["links"],
)
if same:
targets.append(_target(now))
else:
protected.append(
{**_target(before), "reason": CHANGED_SINCE_SEARCH}
)
return targets, protected
targets, protected = _read_snapshot(db_path, read)
fingerprint = _Fingerprint(OPERATION)
for target in targets:
fingerprint.add([target["rule"], target["tag_id"], target["name"]])
fingerprint.add(target["links"])
reasons = (
[f"{_plural(len(protected), 'tag')} {CHANGED_SINCE_SEARCH}"]
if protected
else []
)
draft = MaintenanceDraft(
operation=OPERATION,
fingerprint=fingerprint.hexdigest(),
targets=targets,
scope={"count": len(targets), "label": _scope_label(targets)},
protected={"count": len(protected), "reasons": reasons},
media={"deletes_files": False, "label": NO_FILES},
details=[
{
"label": target["name"],
"detail": f"{rule(target['rule']).title} · {finding_detail(target)}",
}
for target in targets[:MAX_DETAILS]
],
)
draft.held = protected
return draft
def held_rows(draft):
"""The findings a plan protected, each with its reason."""
return list(getattr(draft, "held", ()))
def _empties_legacy_tags(conn):
"""Whether deleting one more tag would empty ``tags`` while a prompt still
holds legacy JSON tags: the start-up migration would then bring every
legacy tag and link back (``models._migrate_json_tags_to_junction``)."""
if conn.execute("SELECT COUNT(*) FROM tags").fetchone()[0] > 1:
return False
legacy = conn.execute(
"SELECT 1 FROM prompts WHERE tags IS NOT NULL AND tags != '' "
"AND tags != '[]' LIMIT 1"
).fetchone()
return legacy is not None
LAST_TAG = "kept so the old tag migration does not run again"
def apply_tag_cleanup(conn, targets):
"""Apply the reviewed targets in the caller's transaction (blocking).
Each target's rule rechecks it on ``conn``; one that changed is kept with
its reason and the rest still apply. ``{"changed": n, "rows": [every
deleted target], "kept": [{...target, "reason"}]}``. Any exception
propagates, so the caller's transaction rolls back as a whole.
"""
changed, rows, kept = 0, [], []
for target in targets:
item = rule(target["rule"])
reason = item.recheck(conn, target)
if reason is None and _empties_legacy_tags(conn):
reason = LAST_TAG
if reason is not None:
kept.append({**target, "reason": reason})
continue
item.apply(conn, target)
changed += 1
rows.append(dict(target))
return {"changed": changed, "rows": rows, "kept": kept}
+2 -33
View File
@@ -295,38 +295,6 @@ def _category_after(after: object) -> tuple[int, str] | None:
return after[0], after[1]
def bump_image_tag_bytes(conn: sqlite3.Connection, tag_id: int) -> int:
"""Move the tag revision of every image set that carries *tag_id*.
Vocabulary rename, merge and delete change what an image's set reads as,
so a Tag dialog opened before the change must see ``tag-conflict`` on Save
instead of recreating the old name. Bumps the image index revision once
when any set was affected; returns that count.
"""
cursor = conn.execute(
"UPDATE media_annotation_bytes SET tag_revision = tag_revision + 1 "
"WHERE id IN (SELECT byte_id FROM media_image_tags WHERE tag_id = ?)",
(tag_id,),
)
if cursor.rowcount > 0:
conn.execute(
"UPDATE media_annotation_metadata SET "
"image_index_revision = image_index_revision + 1 WHERE singleton_id = 1"
)
return cursor.rowcount
def _delete_tag(conn: sqlite3.Connection, tag_id: int) -> None:
"""Delete the registry row *tag_id* in the caller's transaction.
Image sets carrying it get a new tag revision first; its component, pair
and image links cascade. Shared by ``delete_vocabulary_tag`` and the tag
cleanup rules (#618, ``database/tag_cleanup.py``).
"""
bump_image_tag_bytes(conn, tag_id)
conn.execute("DELETE FROM tags WHERE id=?", (tag_id,))
class VocabularyOperations:
"""Vocabulary reads and tag commands.
@@ -437,7 +405,8 @@ class VocabularyOperations:
epoch = self._library_epoch(conn, expected_epoch)
self._vocabulary_identity(conn, epoch, tag_id, name)
counts = self._tag_owner_counts(conn, tag_id)
_delete_tag(conn, tag_id)
self._bump_image_tag_bytes(conn, tag_id)
conn.execute("DELETE FROM tags WHERE id=?", (tag_id,))
return {"library_epoch": epoch, "deleted": True, **counts}
def vocabulary_tag_impact(self, tag_id: int) -> dict | None:
+11 -16
View File
@@ -112,22 +112,20 @@ QUERY_PLAN_STATEMENTS = {
def _rewrite_row(conn, image_id, row, verified, checked):
"""Store the row's inline texts as documents; returns (changed, kept, size).
``kept`` names the columns whose value stays inline (not text).
"""Store the row's inline texts as documents; returns (changed, protected, size).
``verified`` maps document ids already read back in this batch to their
text, and ``checked`` holds the reused ids ``store_text`` already
checked, so a document shared by many rows is decompressed once.
"""
changes, replaced, kept = {}, [], []
size = 0
changes, replaced = {}, []
protected = size = 0
for index, (column, reference) in enumerate(TEXT_COLUMNS):
value, current = row[index], row[index + len(TEXT_COLUMNS)]
if value is None:
continue
if not storable(value):
kept.append(column)
protected += 1
continue
document_id = store_text(conn, value, checked)
if document_id not in verified:
@@ -145,7 +143,7 @@ def _rewrite_row(conn, image_id, row, verified, checked):
[*changes.values(), image_id],
)
release_documents(conn, replaced)
return bool(changes), kept, size
return bool(changes), protected, size
def migrate_batch(
@@ -162,10 +160,9 @@ def migrate_batch(
savepoint: a row that cannot be rewritten (``_row_error``) is rolled
back alone, stays inline and is listed in ``errors``; anything else rolls
the whole batch back and propagates. Returns ``{last_id, rows,
protected, kept, errors, done}``: the last row looked at, rows
rewritten, inline values kept (not text) and each of them as ``(image
id, column)`` (#586), the ids kept by an error and whether there was
nothing left to look at.
protected, errors, done}``: the last row looked at, rows rewritten,
inline values kept (not text), the ids kept by an error and whether
there was nothing left to look at.
"""
if conn.in_transaction:
raise RuntimeError("The migration needs its own transaction")
@@ -177,7 +174,6 @@ def migrate_batch(
"last_id": after_id,
"rows": 0,
"protected": 0,
"kept": [],
"errors": [],
"done": not ids,
}
@@ -186,7 +182,7 @@ def migrate_batch(
conn.execute("SAVEPOINT workflow_row")
try:
row = conn.execute(ROW_SQL, (image_id,)).fetchone()
changed, kept, row_size = _rewrite_row(
changed, protected, row_size = _rewrite_row(
conn, image_id, row, verified, checked
)
except Exception as error:
@@ -198,12 +194,11 @@ def migrate_batch(
checked.clear()
logger.warning(f"Image record {image_id} kept inline: {error}")
result["errors"].append(image_id)
changed, kept, row_size = False, [], 0
changed, protected, row_size = False, 0, 0
else:
conn.execute("RELEASE workflow_row")
result["rows"] += int(changed)
result["protected"] += len(kept)
result["kept"].extend((image_id, column) for column in kept)
result["protected"] += protected
result["last_id"] = image_id
size += row_size
if size >= max_bytes or _clock() - started >= max_seconds:
+6 -8
View File
@@ -12,7 +12,7 @@ code. This plan proposes implementation order and acceptance gates.
- The native Prompt Library merged in [#210](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/210) for [#208](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/208): one positive parent, saved negative variants, full selected text and a shared filtered image gallery. It does not invent chronological runs from counters or scan dates.
- [Durable history storage](prompt-history-storage.md) records job attempts and outcomes from [#212](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/212), frozen prompt contexts from [#213](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/213), and observed run-owned output locators from [#214](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/214). Those locators do not verify file bytes or establish gallery-image associations. That association contract and the chronological execution timeline remain pending under [#209](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/209).
- [#215](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/215) brings the shell, Images and natural-height Prompt Library presentation into the approved geometry and themes while retaining their existing operations. [#216](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/216) adds the shared current-file inspector with exact generation facts, scoped provenance, raw/download evidence and loaded-collection viewer controls, including a slideshow that pauses at native video. This delivery does not establish whole-application parity, change the default entry point or constitute a release. Recorded chronological run/context browsing continues under [#209](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/209); image tagging/review, System consolidation and remaining organization capabilities continue under #196.
- Local Inspect (#249, PRs L1–L3) replaces the `#/inspect` handoff with the concept's native "Inspect a file" page: one local image or video previews inline and opens the shared viewer and full inspector on a record read entirely in the browser, with nothing uploaded, imported or stored. The legacy metadata page (`web/metadata.html`, served at `/prompt_manager/gallery.html`) was removed in #668, and its address now opens this page; its capabilities map to the shared inspector, including its one-click COPY ALL summary, which is the shared inspector's "Copy settings summary" (D117, LI-4). PR L3 ([#286](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/286)) shipped that button and local roles equal to the server's resolver (`web/js/workspace/local-resolver.mjs`, TESTING.md "Local roles (#249 PR L3, decision LI-1)"). Recorded deviations D60–D66 and D117 are in [TESTING.md](../TESTING.md).
- Local Inspect (#249, PRs L1–L3) replaces the `#/inspect` handoff with the concept's native "Inspect a file" page: one local image or video previews inline and opens the shared viewer and full inspector on a record read entirely in the browser, with nothing uploaded, imported or stored. The legacy metadata page (`web/metadata.html`, served at `/prompt_manager/gallery.html`) stays reachable from Overview; its capabilities map to the shared inspector, including its one-click COPY ALL summary, which is the shared inspector's "Copy settings summary" (D117, LI-4). PR L3 ([#286](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/286)) shipped that button and local roles equal to the server's resolver (`web/js/workspace/local-resolver.mjs`, TESTING.md "Local roles (#249 PR L3, decision LI-1)"). Recorded deviations D60–D66 and D117 are in [TESTING.md](../TESTING.md).
- Collections ([#331](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/331), three PRs) adds named, hand-picked groups of images, stored in the library database by file location as favorites are: a COLLECTIONS sidebar group whose rows open Images filtered to one collection (`#/collection/<id>`) with rename and delete, Add to collection and Remove from collection in the Images selection bar, a Collections… checklist in the shared inspector for the side panel and the viewer, and saved views that keep a collection. Membership survives restarts, source reordering and System › Maintenance duplicate cleanup; no file is copied, moved or changed.
## Scope and compatibility
@@ -69,16 +69,14 @@ regression coverage with mockup-only tests.
## GitHub and release gates
Extend existing required workflows: the Python suite on Linux (3.12 on a pull
request, 3.12–3.14 in the merge queue; Windows 3.12–3.14 runs in `portability.yml`
and does not gate a merge; macOS is not tested in CI, #571); 85% Python coverage;
formatting; frontend units and per-file coverage floors; vendor checks; browser
workflows; real ComfyUI compatibility. Python 3.12 is the floor.
Extend existing required workflows: the Python 3.10–3.13 matrix on Linux,
Windows and macOS; 85% Python coverage; formatting; frontend units and per-file
coverage floors; vendor checks; browser workflows; real ComfyUI compatibility.
Publish traces, screenshots, logs and coverage artifacts on failures. See
[TESTING.md](../TESTING.md) for commands and fixture isolation requirements.
Every PR must map acceptance criteria to tests, report relevant checks and describe
visual changes in words; never attach screenshots or other images to a PR. All required checks must pass before merging.
Every PR must map acceptance criteria to tests, report relevant checks and include
screenshots for visual changes. All required checks must pass before merging.
Use maintainer live review at meaningful visual and host-integration milestones;
capture discovered regressions in automated tests. Notify the maintainer when
Python changes require a ComfyUI restart.
Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

+16 -4
View File
@@ -3,6 +3,7 @@ PromptManager: Main custom node implementation that extends CLIPTextEncode
with persistent prompt storage and search capabilities.
"""
import time
from typing import Any, Dict, Optional, Tuple
if __package__:
@@ -99,21 +100,19 @@ class PromptManager(PromptManagerBase, ComfyNodeABC):
"prepend_text": (
IO.STRING,
{
"default": "",
"tooltip": (
"Text to prepend to the main prompt (connected STRING "
"nodes will be added before the main text)"
),
)
},
),
"append_text": (
IO.STRING,
{
"default": "",
"tooltip": (
"Text to append to the main prompt (connected STRING "
"nodes will be added after the main text)"
),
)
},
),
"save_to_library": SAVE_TO_LIBRARY_INPUT,
@@ -260,6 +259,19 @@ class PromptManager(PromptManagerBase, ComfyNodeABC):
if not save_to_library:
return result # #90: no metadata registration, no history text
# Register with ComfyUI integration for standard metadata compatibility
node_id = f"promptmanager_{int(time.time() * 1000)}"
self.comfyui_integration.register_prompt(
node_id,
encoding_text.strip(),
{
"category": category.strip() if category else None,
"tags": extended_tags,
"prompt_id": prompt_id,
"prepend_text": prepend_text.strip() if prepend_text else None,
"append_text": append_text.strip() if append_text else None,
},
)
record_runtime_context(
type(self).__name__, text, prepend_text, append_text, encoding_text
)
+57 -1
View File
@@ -7,7 +7,7 @@ duplicate code in prompt_manager.py and prompt_manager_text.py.
"""
import os
from typing import Any, Dict, Optional
from typing import Any, Dict, List, Optional
try:
from .utils.logging_config import get_logger
@@ -19,6 +19,7 @@ except ImportError:
try:
from .database.operations import PromptDatabase
from .utils.comfyui_integration import get_comfyui_integration
from .utils.image_monitor import get_image_monitor
from .utils.prompt_tracker import get_prompt_tracker
from .utils.hashing import generate_prompt_hash
@@ -37,6 +38,7 @@ except ImportError:
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from database.operations import PromptDatabase
from utils.comfyui_integration import get_comfyui_integration
from utils.image_monitor import get_image_monitor
from utils.prompt_tracker import get_prompt_tracker
from utils.hashing import generate_prompt_hash
@@ -84,6 +86,7 @@ class PromptManagerBase:
self.db = PromptDatabase()
self.prompt_tracker = get_prompt_tracker(self.db)
self.image_monitor = get_image_monitor(self.db, self.prompt_tracker)
self.comfyui_integration = get_comfyui_integration()
self._start_gallery_system()
self.logger.debug(f"{self.__class__.__name__} node initialization completed")
@@ -396,6 +399,52 @@ class PromptManagerBase:
tags = [tag.strip() for tag in tags_string.split(",") if tag.strip()]
return tags if tags else None
def _search_prompts(self, search_text: str = "") -> List[Dict[str, Any]]:
"""Search for past prompts by text content.
Args:
search_text: Text to search for in prompt database
Returns:
List of matching prompt dictionaries with metadata
"""
try:
if not search_text or not search_text.strip():
return []
try:
from .py.config import PromptManagerConfig
max_results = PromptManagerConfig.MAX_SEARCH_RESULTS
except Exception:
max_results = 100
results = self.db.search_prompts(
text=search_text.strip(),
category=None,
tags=None,
rating_min=None,
limit=max_results,
)
return results
except Exception as e:
self.logger.error(f"Error searching prompts: {e}")
return []
def search_prompts_api(self, search_text: str = "") -> List[Dict[str, Any]]:
"""API method for JavaScript UI to search prompts."""
return self._search_prompts(search_text=search_text)
def get_recent_prompts_api(self, limit: int = 20) -> List[Dict[str, Any]]:
"""API method for JavaScript UI to get recent prompts."""
try:
return self.db.get_recent_prompts(limit=limit)
except Exception as e:
self.logger.error(f"Error getting recent prompts: {e}")
return []
def _start_gallery_system(self):
"""Initialize and start the gallery monitoring system."""
try:
@@ -406,6 +455,13 @@ class PromptManagerBase:
self.logger.error(f"Failed to start gallery system: {e}")
self.logger.warning("Gallery features will be disabled")
def get_gallery_status(self) -> Dict[str, Any]:
"""Get status of the gallery system."""
return {
"image_monitor": self.image_monitor.get_status(),
"prompt_tracker": self.prompt_tracker.get_status(),
}
def cleanup_gallery_system(self):
"""Clean up gallery system resources.
+14
View File
@@ -2,6 +2,7 @@
import hashlib
import json
import time
from typing import Any, Dict, Optional, Tuple
if __package__:
@@ -172,6 +173,19 @@ class PromptManagerPair(PromptManagerFocused):
self.logger.warning(f"Could not save or track paired prompt: {error}")
if is_positive:
self._mark_untracked(prompt, unique_id)
try:
self.comfyui_integration.register_prompt(
f"promptmanager_pair_{time.time_ns()}",
positive,
{
"prompt_id": prompt_id,
"pair_id": pair_id if pair_used else None,
"negative_text": negative_text,
"category": category.strip() or None,
},
)
except Exception as error:
self.logger.warning(f"Could not register paired metadata: {error}")
record_runtime_context(
type(self).__name__,
text,
+14
View File
@@ -3,6 +3,7 @@ PromptManagerText: A text-only version of PromptManager that outputs STRING
without CLIP encoding, while maintaining all database and search features.
"""
import time
from typing import Any, Dict, Optional, Tuple
if __package__:
@@ -229,6 +230,19 @@ class PromptManagerText(PromptManagerBase, ComfyNodeABC):
if not save_to_library:
return result # #90: no metadata registration, no history text
# Register with ComfyUI integration for standard metadata compatibility
node_id = f"promptmanagertext_{int(time.time() * 1000)}"
self.comfyui_integration.register_prompt(
node_id,
final_text.strip(),
{
"category": category.strip() if category else None,
"tags": extended_tags,
"prompt_id": prompt_id,
"prepend_text": prepend_text.strip() if prepend_text else None,
"append_text": append_text.strip() if append_text else None,
},
)
record_runtime_context(
type(self).__name__, text, prepend_text, append_text, final_text
)
+97 -54
View File
@@ -23,7 +23,6 @@ Split into domain-specific mixins for maintainability:
- LibraryDeleteRoutesMixin: the Library's Delete… (archive paired) and Restore
- WorkflowStorageRoutesMixin: store each workflow once, then Reclaim space
- DuplicateFilesMixin: duplicate image files as find and removal jobs
- TagCleanupMixin: tag cleanup (#618) as a find job, its findings and a plan
- LoraImportRoutesMixin: the reviewed, staged LoRA reference import job
"""
@@ -31,6 +30,7 @@ import asyncio
import datetime
import functools
import gzip as gzip_module
import json
import math
import ntpath
import os
@@ -41,7 +41,6 @@ from pathlib import Path
from aiohttp import web
from PIL import Image
from . import json_body as _json_body
from .prompts import PromptRoutesMixin
from .revalidation import revalidated_response
from .pairs import PairRoutesMixin
@@ -63,10 +62,6 @@ from .job_routes import JobRoutesMixin
from .image_tag_jobs import ImageTagJobsMixin
from .thumbnail_jobs import ThumbnailJobsMixin
from .thumbnail_location import ThumbnailLocationMixin
from .thumbnail_move import ThumbnailMoveMixin
from .thumbnail_move_plan import ThumbnailMovePlanMixin
from .thumbnail_move_recovery import ThumbnailMoveRecoveryMixin
from .thumbnail_prune import ThumbnailPruneMixin
from .thumbnail_convert import ThumbnailConvertMixin
from .thumbnail_auto import AutoThumbnailMixin
from .system import SystemRoutesMixin
@@ -75,7 +70,6 @@ from .maintenance import MaintenanceRoutesMixin
from .backup_restore import BackupRestoreRoutesMixin
from .workflow_storage import WorkflowStorageRoutesMixin
from .duplicate_files import DuplicateFilesMixin
from .tag_cleanup import TagCleanupMixin
from .maintenance_plans import PlanStore
from .jobs import JobRegistry
from .logging_routes import LoggingRoutesMixin
@@ -91,7 +85,7 @@ from .source_rescope import SourceRescopeMixin
try:
from ...database.operations import PromptDatabase
from ...utils.exif_text import exif_text
from ...utils.file_prompt import parse_comfyui_prompt
from ...utils.logging_config import get_logger
from ...utils.native_memory import release_free_memory
from ...utils.png_text import png_text
@@ -103,7 +97,7 @@ except ImportError:
0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
)
from database.operations import PromptDatabase
from utils.exif_text import exif_text
from utils.file_prompt import parse_comfyui_prompt
from utils.logging_config import get_logger
from utils.native_memory import release_free_memory
from utils.png_text import png_text
@@ -216,10 +210,61 @@ def _resolve_static_file(root, filepath, allowed=STATIC_MIME_TYPES):
# ── JSON request bodies ────────────────────────────────────────────────
# One bounded reader (json_body.py); these names stay for the mixins and tests.
JSON_BODY_MAX_BYTES = _json_body.JSON_BODY_MAX_BYTES
_json_error = _json_body.json_error
_read_json_body = _json_body.read_json_body
JSON_BODY_MAX_BYTES = 1_000_000
_JSON_READ_CHUNK = 64 * 1024
def _json_error(message, status):
return web.json_response({"success": False, "error": message}, status=status)
async def _read_json_body(request, max_bytes=JSON_BODY_MAX_BYTES):
"""Read and parse a JSON object body of at most ``max_bytes``.
The body is read in chunks so an oversized or chunked upload is refused
as soon as it crosses the cap rather than buffered whole.
Returns:
(data, None) on success, or (None, response) where ``response`` is a
413 (body too large) or 400 (invalid JSON, or not a JSON object).
"""
too_large = _json_error(f"Request body too large (max {max_bytes} bytes)", 413)
declared = request.content_length
if declared is not None and declared > max_bytes:
return None, too_large
chunks = []
size = 0
async for chunk in request.content.iter_chunked(_JSON_READ_CHUNK):
size += len(chunk)
if size > max_bytes:
return None, too_large
chunks.append(chunk)
try:
data = json.loads(b"".join(chunks).decode("utf-8"))
except (UnicodeDecodeError, ValueError):
return None, _json_error("Request body must be valid JSON", 400)
if not isinstance(data, dict):
return None, _json_error("Request body must be a JSON object", 400)
return data, None
class _LongJobGuard:
"""Async context manager handed out by ``_acquire_long_job``."""
def __init__(self, lock):
self._lock = lock
async def __aenter__(self):
# The caller checked ``locked()`` on this same loop iteration, so this
# acquire never waits.
await self._lock.acquire()
return self
async def __aexit__(self, exc_type, exc, tb):
self._lock.release()
return False
# ── Gzip compression middleware ────────────────────────────────────────
@@ -276,17 +321,6 @@ async def _gzip_middleware(request, handler):
return response
def _workspace_redirect(route: str) -> web.Response:
"""Send the browser of a retired page's URL to a workspace route (#668).
The Location is relative to the old URL, so a reverse-proxy mount prefix
in front of ``/prompt_manager/`` is kept, and 302 is not stored for good.
A plain response, not a raised ``HTTPFound``, so the host's middlewares
see it like any other.
"""
return web.Response(status=302, headers={"Location": f"workspace{route}"})
class PromptManagerAPI(
PairRoutesMixin,
LibraryRoutesMixin,
@@ -307,10 +341,6 @@ class PromptManagerAPI(
ImageTagJobsMixin,
ThumbnailJobsMixin,
ThumbnailLocationMixin,
ThumbnailMovePlanMixin,
ThumbnailMoveMixin,
ThumbnailMoveRecoveryMixin,
ThumbnailPruneMixin,
ThumbnailConvertMixin,
AutoThumbnailMixin,
SystemRoutesMixin,
@@ -319,7 +349,6 @@ class PromptManagerAPI(
BackupRestoreRoutesMixin,
WorkflowStorageRoutesMixin,
DuplicateFilesMixin,
TagCleanupMixin,
LoggingRoutesMixin,
LogCleanupMixin,
DiagnosticsReportMixin,
@@ -389,6 +418,10 @@ class PromptManagerAPI(
self._workspace_card_cache = {}
# Favorite keys of each root's cached scan (images._favorite_listing).
self._favorite_listing_cache = {}
# Single-flight locks for long jobs, keyed by job family; see
# _acquire_long_job(). Created lazily so no lock binds to an event
# loop before the server's loop exists.
self._long_jobs: dict = {}
# This session's jobs (py/api/jobs.py): the metadata scan, and later
# every other long operation the Activity page tracks.
self._jobs = JobRegistry(self.logger)
@@ -397,9 +430,6 @@ class PromptManagerAPI(
# Duplicate-file finds by job id, with the groups each one holds for
# review (py/api/duplicate_files.py); the last few only.
self._duplicate_finds = {}
# Tag cleanup finds by job id with the findings each holds (#618,
# py/api/tag_cleanup.py); None while a find runs or after it failed.
self._tag_cleanup_finds = {}
# The last System health report this session and the database
# generation it describes, bumped when a restore replaces self.db
# (py/api/system.py).
@@ -448,6 +478,26 @@ class PromptManagerAPI(
_public_error = staticmethod(_public_error)
_read_json_body = staticmethod(_read_json_body)
def _acquire_long_job(self, name):
"""Claim the single-flight slot for a long job family, or None when busy.
Usage in a handler::
job = self._acquire_long_job("duplicates")
if job is None:
return self._long_job_busy_response("Duplicate scan")
async with job:
...
Families are free-form strings ("duplicates", "thumbnails",
"autotag", ...); the lock is released when the ``async with`` block
exits, including on exceptions. Must be called from the event loop.
"""
lock = self._long_jobs.setdefault(name, asyncio.Lock())
if lock.locked():
return None
return _LongJobGuard(lock)
@staticmethod
def _long_job_busy_response(label):
"""409 envelope for a long job that is already running."""
@@ -638,24 +688,17 @@ class PromptManagerAPI(
async def serve_web_ui(request):
return self._serve_html_page(request, "index.html", "Web UI", cache=False)
# The old admin, gallery and metadata pages are gone (#668, D207); their
# URLs stay and lead into the workspace.
@routes.get("/prompt_manager/gallery.html")
async def redirect_old_metadata_page(request):
return _workspace_redirect("#/inspect")
async def serve_gallery_ui(request):
return self._serve_html_page(request, "metadata.html", "Gallery")
@routes.get("/prompt_manager/admin")
async def serve_admin_ui(request):
return self._serve_html_page(request, "admin.html", "Admin UI")
@routes.get("/prompt_manager/gallery")
async def redirect_old_gallery_page(request):
return _workspace_redirect("#/images")
# The dashboard's tag bookmarks (admin#/tags/a,b?mode=or) live in the
# hash, which only the browser sees: this page maps it and moves on.
@routes.get("/prompt_manager/admin")
async def serve_old_admin_redirect(request):
return self._serve_html_page(
request, "admin-redirect.html", "Workspace redirect"
)
async def serve_gallery_admin_ui(request):
return self._serve_html_page(request, "gallery.html", "Gallery")
# ── Static file serving ───────────────────────────────────────
@@ -676,7 +719,6 @@ class PromptManagerAPI(
# ── Register domain-specific routes from mixins ───────────────
self._register_pair_routes(routes)
self._register_thumbnail_move_routes(routes)
self._register_library_routes(routes)
self._register_library_delete_routes(routes)
self._register_vocabulary_routes(routes)
@@ -697,7 +739,6 @@ class PromptManagerAPI(
self._register_maintenance_routes(routes)
self._register_backup_restore_routes(routes)
self._register_duplicate_routes(routes)
self._register_tag_cleanup_routes(routes)
self._register_logging_routes(routes)
self._register_autotag_routes(routes)
self._register_lora_routes(routes)
@@ -1011,11 +1052,9 @@ class PromptManagerAPI(
return []
def _extract_comfyui_metadata(self, image_path):
"""Embedded ComfyUI metadata of an image (PNG text, EXIF) or a video.
"""Embedded ComfyUI metadata of an image (PNG text chunks) or a video.
PNG text is read without decoding the pixels (``utils.png_text``, #523);
WebP, AVIF and JPEG keep the same records as EXIF strings, read through
``utils.exif_text``.
PNG text is read without decoding the pixels (``utils.png_text``, #523).
Videos go through ffprobe (see utils/video_metadata). Unreadable files
are a warning, not an error: a scan over a large output tree meets
@@ -1025,9 +1064,13 @@ class PromptManagerAPI(
return read_video_metadata(image_path)
try:
with Image.open(image_path) as img:
return png_text(img) or exif_text(img)
return png_text(img)
except Exception as e:
self.logger.warning(
f"Unreadable image {os.path.basename(str(image_path))}: {e}"
)
return {}
def _parse_comfyui_prompt(self, metadata):
"""Parse ComfyUI and A1111 prompt data from metadata."""
return parse_comfyui_prompt(metadata)
+28 -21
View File
@@ -30,10 +30,8 @@ from .jobs import (
)
try:
from ...database.sqlite_uri import readonly_uri
from ...utils.parallel import map_parallel
except ImportError:
from database.sqlite_uri import readonly_uri
from utils.parallel import map_parallel
try:
@@ -43,7 +41,6 @@ try:
in_trash_folder,
is_skipped_folder,
)
from ...utils.media_formats import collectable
except ImportError:
from utils import exit_signal
from utils.media_folders import (
@@ -51,7 +48,6 @@ except ImportError:
in_trash_folder,
is_skipped_folder,
)
from utils.media_formats import collectable
try:
from ...database.image_removal import mark_hides
@@ -102,7 +98,7 @@ try:
except ImportError:
from database.library import display_title
IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".avif")
IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff")
VIDEO_EXTENSIONS = (".mp4", ".avi", ".mov", ".mkv", ".webm", ".m4v", ".wmv")
SCAN_BATCH_SIZE = 50 # Files per executor call during the output scan
# '<db>.backup_*' files kept next to the live database: one pool for the
@@ -158,9 +154,7 @@ def _collect_media_files(output_dirs, extensions):
and not os.path.islink(os.path.join(current, d))
)
for name in sorted(filenames):
suffix = os.path.splitext(name)[1].lower()
# #652: AVIF is listed but only collected where Pillow reads it.
if suffix not in wanted or not collectable(suffix):
if os.path.splitext(name)[1].lower() not in wanted:
continue
full = os.path.join(current, name)
if os.path.islink(full) or not os.path.isfile(full):
@@ -405,7 +399,7 @@ def _inspect_restore_upload(path):
Returns:
None when acceptable, otherwise a human-readable reason (blocking).
"""
uri = readonly_uri(path)
uri = Path(os.path.abspath(path)).as_uri() + "?mode=ro"
try:
conn = sqlite3.connect(uri, uri=True)
except sqlite3.Error as e:
@@ -1703,8 +1697,7 @@ class AdminRoutesMixin:
review (best effort, counted in ``review`` when given); one a saved
row already links is reported ``unchanged`` and never queued. An
ambiguous file with nothing to choose is reported ``unresolved`` and
its pending items without a choice leave the queue. The decision is
``review_dispatch``'s, shared with the monitor's review worker (#659).
its pending items without a choice leave the queue.
"""
counts = dict.fromkeys(SCAN_COUNT_KEYS, 0)
@@ -1718,12 +1711,14 @@ class AdminRoutesMixin:
if self._scan_job and self._scan_job.cancelled:
break
counts["processed"] += 1
records = {}
ambiguous, untraced, records = [], [], {}
try:
outcome = self._ingest_scanned_file(
media_file,
metadata,
detailed=True,
ambiguous=ambiguous,
untraced=untraced,
records=records,
history=history,
)
@@ -1732,9 +1727,24 @@ class AdminRoutesMixin:
counts["failed"] += 1
note(media_file, "error")
continue
outcome, _recorded = self.review_dispatch(
media_file, roots, records.get("decision"), outcome, review
)
if ambiguous and outcome == "ambiguous":
if self._review_file_linked(media_file, roots):
outcome = "unchanged" # already linked: not a review case
else:
# The records name the item versions that count; the
# saver anchor (#390) is checked on the captured bytes.
self._record_scanned_review(
media_file,
roots,
review,
scanned=(records.get("canonical"), None),
)
elif untraced and outcome == "unresolved":
# Untraced by the default profile: the inspection profile may
# still offer a choice (queued for review, never linked).
outcome = self._untraced_scan_outcome(
media_file, roots, records.get("canonical"), review
)
if outcome is None:
note(media_file, None)
continue
@@ -1771,12 +1781,11 @@ class AdminRoutesMixin:
``ambiguous`` is a list, ``media_file`` is appended to it; only a file
that then returns ``"ambiguous"`` (nothing linked it) is a Needs
review case. An ambiguous result with nothing to choose
(``reviewable`` is False: no candidate carries a prompt)
(``reviewable`` is False: fewer than two candidates carry a prompt)
goes to ``untraced`` instead and returns ``"unresolved"`` when nothing
links it. The parsed records of either ambiguous file go to
``records["canonical"]`` when ``records`` is a dict, and the ladder's
``Decision`` to ``records["decision"]`` (``review_dispatch``'s input).
``history`` is the batch's lazy recorded-history lookup.
``records["canonical"]`` when ``records`` is a dict. ``history`` is
the batch's lazy recorded-history lookup.
"""
path = str(media_file)
if history is None: # one file: history is still asked once
@@ -1789,8 +1798,6 @@ class AdminRoutesMixin:
lookup=functools.partial(history.recorded, path),
policy=Policy.SCAN,
)
if records is not None:
records["decision"] = decision
if decision.kind in (NOT_SAVED, NOT_SAVED_WIRED):
# Save to library off (#90): no write, recorded-run fallback or
# Needs review item
+2 -6
View File
@@ -102,14 +102,11 @@ def model_refusal(status: dict, model_type: str, model_name: str):
return None
def run_suggestions(
service, capture_path: str, model_type: str, options: dict, skip=None
):
def run_suggestions(service, capture_path: str, model_type: str, options: dict):
"""Blocking: load (or swap to) *model_type*, then suggest for the capture.
The caller holds the model gate for the whole call; nothing is ever
downloaded (``load_model`` refuses a model that is not on disk). ``skip``
is the request's or job's compiled Skipped tags (#431).
downloaded (``load_model`` refuses a model that is not on disk).
"""
if not service.is_model_loaded() or service.get_loaded_model_type() != model_type:
service.load_model(model_type, options["use_gpu"])
@@ -119,7 +116,6 @@ def run_suggestions(
prompt=options.get("instructions"),
general_threshold=options.get("general_threshold"),
character_threshold=options.get("character_threshold"),
skip=skip,
)
+2 -9
View File
@@ -35,7 +35,6 @@ from .media_target import media_target as _target
from .images import _unavailable_link, _verified_title
from .prompts import bad_request
from .. import model_gate
from ..tagging_defaults import SkipMatcher
try:
from ...database.annotations import (
@@ -91,7 +90,6 @@ _PREVIEW_TYPES = {
".bmp": "image/bmp",
".tiff": "image/tiff",
".tif": "image/tiff",
".avif": "image/avif", # #652
".mp4": "video/mp4",
".m4v": "video/mp4",
".webm": "video/webm",
@@ -642,8 +640,6 @@ class AnnotationRoutesMixin:
owner = model_gate.new_owner("image-annotations")
if not model_gate.try_acquire(owner):
return model_busy_response()
# #431: the Skipped tags as they are when the request is accepted.
skip = SkipMatcher(AutotagConfig.SKIPPED_TAGS).counting()
try:
# From here the pin is the gate's to end: the worker ends it,
# or ``on_skipped`` does when the worker never starts.
@@ -657,7 +653,6 @@ class AnnotationRoutesMixin:
capture,
model_type,
options,
skip,
on_skipped=functools.partial(store.release_use, token),
)
except MissingBackendPackages as exc:
@@ -682,8 +677,6 @@ class AnnotationRoutesMixin:
"model_type": model_type,
"options": options,
"suggestions": suggestion_rows(pairs),
# How many distinct suggestions the Skipped tags hid (#431).
"skipped": len(skip.hidden),
},
headers={"Cache-Control": "no-store"},
)
@@ -739,10 +732,10 @@ def _byte_range(request: web.Request, size: int):
return start, stop
def _pinned_suggestions(store, token, service, capture, model_type, options, skip=None):
def _pinned_suggestions(store, token, service, capture, model_type, options):
"""Worker thread: infer on the capture, then end its pin (even on error)."""
try:
return run_suggestions(service, capture.path, model_type, options, skip)
return run_suggestions(service, capture.path, model_type, options)
finally:
store.release_use(token)
+17 -128
View File
@@ -25,10 +25,8 @@ from .. import model_gate
try:
from ...utils.media_folders import in_trash_below_roots, is_skipped_folder
from ...utils.media_formats import collectable
except ImportError:
from utils.media_folders import in_trash_below_roots, is_skipped_folder
from utils.media_formats import collectable
from aiohttp import web
@@ -42,12 +40,6 @@ BATCH_PREVIEW_BODY_MAX = 1024
APPLY_BODY_MAX = 64 * 1024 # POST /autotag/apply: one image and its tags
_HEX64 = re.compile(r"[0-9a-f]{64}")
BATCH_JOB_BODY_MAX = 32 * 1024
# Skipped tags preview (#431): 200 entries of 50 characters, with room for JSON.
SKIPPED_PREVIEW_BODY_MAX = 64 * 1024
SKIPPED_PREVIEW_LEASE = "Skipped tags preview"
SKIPPED_PREVIEW_SAMPLE = 12
# WD14 label lists the preview found missing or unreadable (logged once each).
_MISSING_LABEL_LISTS = set()
REVIEW_REQUIRED = (
"Replacing tags needs a review of each image. Use Preview tagging review, "
"or choose Skip or Merge for a batch run."
@@ -80,12 +72,6 @@ MODEL_DOWNLOAD_BODY_MAX = 1024
_download_titles = {}
def _instruction_engine(model_type: str) -> str:
"""The language-model engine whose default instructions ``model_type``
reads: itself, or GGUF for a WD14 engine (which takes none)."""
return model_type if model_type in ("gguf", "hf") else "gguf"
def _holder_label(holder: Optional[str]) -> str:
if not holder:
return ANOTHER_OPERATION
@@ -158,9 +144,8 @@ def public_models(status: dict, loaded_type: Optional[str]) -> dict:
# Only these may be handed to the tagging engine or listed by the scanner.
# #652: AVIF is listed and skipped where Pillow cannot read it (collectable).
_MEDIA_EXTENSIONS = frozenset(
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff", ".tif", ".avif"}
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff", ".tif"}
)
# Bounds for scan_output_dir: a runaway output tree must not pin the server.
_SCAN_MAX_FILES = 50_000
@@ -262,10 +247,6 @@ class AutotagRoutesMixin:
async def preview_autotag_batch_route(request):
return await self.preview_autotag_batch(request)
@routes.post("/prompt_manager/autotag/skipped-tags/preview")
async def preview_skipped_tags_route(request):
return await self.preview_skipped_tags(request)
@routes.post("/prompt_manager/autotag/start")
async def start_autotag_route(request):
return await self.start_autotag(request)
@@ -303,15 +284,7 @@ class AutotagRoutesMixin:
"success": True,
"models": public_models(status, loaded_type),
# The saved tagging defaults (#328, System › Auto-tagging).
# The saved engine's default instructions (GGUF for a
# WD14 engine); kept one release for cached pages (#431).
"default_prompt": AutotagConfig.default_instructions_text(
_instruction_engine(AutotagConfig.MODEL_TYPE)
),
# #431: Built-in first, with every text, and each
# language-model engine's default.
"instructions": AutotagConfig.all_instructions(),
"default_instructions": dict(AutotagConfig.DEFAULT_INSTRUCTIONS),
"default_prompt": AutotagConfig.TEMPLATE,
"model_loaded": loaded,
"loaded_model_type": loaded_type,
"wd14_general_threshold": AutotagConfig.GENERAL_THRESHOLD,
@@ -566,10 +539,7 @@ class AutotagRoutesMixin:
else:
prompt = params.get("prompt")
template = prompt if isinstance(prompt, str) and prompt.strip() else None
options = {
"instructions": template
or AutotagConfig.default_instructions_text(model_type)
}
options = {"instructions": template or AutotagConfig.TEMPLATE}
try:
_model, options = validate_options(
model_type,
@@ -729,86 +699,6 @@ class AutotagRoutesMixin:
return None, "existing must be one of " + ", ".join(EXISTING_POLICIES)
return MODELS[model_type], None
async def preview_skipped_tags(self, request):
"""Which known tags a Skipped tags list would hide (#431); no write.
``{entries}`` is checked as a save checks it (the same 400 sentence).
The known tags are the library's plus the general and character names
of each downloaded WD14 label list; no model is loaded and no image is
opened. Refused (409 ``busy``) while an exclusive job runs.
"""
from ..tagging_defaults import validate_skipped_tags
data, error = await self._batch_body(
request, ("entries",), SKIPPED_PREVIEW_BODY_MAX
)
if error is not None:
return error
try:
entries = validate_skipped_tags(data["entries"])
except ValueError as exc:
return web.json_response({"success": False, "error": str(exc)}, status=400)
try:
async with self._jobs.lease(SKIPPED_PREVIEW_LEASE):
result = await self._run_in_executor(self._skipped_preview, entries)
except JobBusy as busy:
return busy_response(busy)
except Exception:
self.logger.exception("The Skipped tags preview failed")
return web.json_response(
{"success": False, "error": _INTERNAL_ERROR}, status=500
)
return web.json_response({"success": True, **result})
def _skipped_preview(self, entries):
"""Worker thread: the preview's counts over the known tags."""
from ..autotag import MODELS, get_autotag_service
from ..tagging_defaults import (
WD14_MODEL_TYPES,
SkipMatcher,
wd14_label_names,
)
library = self.db.get_all_tags()
known = {} # case-folded -> (0 library / 1 label list, spelling)
for name in library:
known.setdefault(name.casefold(), (0, name))
lists = []
models_dir = getattr(get_autotag_service(), "models_dir", None)
for model_type in sorted(WD14_MODEL_TYPES, key=lambda t: MODELS[t]["name"]):
if models_dir is None:
break
path = Path(models_dir) / MODELS[model_type]["subdir"] / "selected_tags.csv"
try:
names = wd14_label_names(path)
except (OSError, ValueError) as exc:
if path not in _MISSING_LABEL_LISTS: # logged once per list
_MISSING_LABEL_LISTS.add(path)
self.logger.debug(f"No WD14 label list for {model_type}: {exc}")
continue
_MISSING_LABEL_LISTS.discard(path)
lists.append(MODELS[model_type]["name"])
for name in names:
known.setdefault(name.casefold(), (1, name))
matchers = [(entry, SkipMatcher([entry])) for entry in entries]
whole = SkipMatcher(entries)
hidden = [item for item in known.values() if whole.matches(item[1])]
hidden.sort(key=lambda item: (item[0], item[1].casefold()))
per_entry = [
{
"entry": entry,
"count": sum(1 for _, name in hidden if matcher.matches(name)),
}
for entry, matcher in matchers
]
return {
"count": len(hidden),
"sample": [name for _, name in hidden[:SKIPPED_PREVIEW_SAMPLE]],
"sample_limit": SKIPPED_PREVIEW_SAMPLE,
"per_entry": per_entry,
"sources": {"library": len(library), "wd14": lists},
}
async def preview_autotag_batch(self, request):
"""Review Tag output images: counts, model, backup and disk; no write.
@@ -946,10 +836,19 @@ class AutotagRoutesMixin:
return refusal.response
return web.json_response({"success": True, "job": job.summary()}, status=202)
def _gated_runner(self, owner):
"""Executor calls under the model gate *owner* holds (plain when None)."""
if owner is None:
return self._run_in_executor
async def run(func, *args, **kwargs):
return await model_gate.run(owner, func, *args, **kwargs)
return run
def _resolve_allowed_image_path(self, raw_path: str) -> Optional[str]:
"""Return the real path when it is a media file inside an output directory."""
suffix = Path(str(raw_path)).suffix.lower()
if suffix not in _MEDIA_EXTENSIONS or not collectable(suffix):
if Path(str(raw_path)).suffix.lower() not in _MEDIA_EXTENSIONS:
return None
roots = list(self._get_all_output_dirs())
for output_dir in roots:
@@ -1103,10 +1002,7 @@ class AutotagRoutesMixin:
else:
prompt = data.get("prompt")
template = prompt if isinstance(prompt, str) and prompt.strip() else None
options = {
"instructions": template
or AutotagConfig.default_instructions_text(model_type)
}
options = {"instructions": template or AutotagConfig.TEMPLATE}
use_gpu = data.get("use_gpu", True)
options["use_gpu"] = use_gpu if isinstance(use_gpu, bool) else True
return validate_options(
@@ -1200,8 +1096,6 @@ class AutotagRoutesMixin:
async def _suggest_single(self, target, model_type, options, base):
from ..autotag import MODELS, MissingBackendPackages, get_autotag_service
from ..config import AutotagConfig
from ..tagging_defaults import SkipMatcher
from .annotation_suggest import model_refusal
from .annotations import _pinned_suggestions, _settled, _submit
@@ -1218,8 +1112,6 @@ class AutotagRoutesMixin:
owner = model_gate.new_owner("legacy-single")
if not model_gate.try_acquire(owner):
return model_busy_response()
# #431: the legacy review hides the Skipped tags too (19A).
skip = SkipMatcher(AutotagConfig.SKIPPED_TAGS)
store = self._capture_store()
try:
epoch = await self._run_in_executor(self.db.get_execution_epoch)
@@ -1259,7 +1151,6 @@ class AutotagRoutesMixin:
capture,
model_type,
options,
skip,
on_skipped=functools.partial(store.release_use, capture.token),
)
except MissingBackendPackages as exc:
@@ -1415,8 +1306,7 @@ class AutotagRoutesMixin:
)
model_type = service.get_loaded_model_type()
# Off the loop; a dropped request keeps the gate until it ends.
await model_gate.run(owner, service.unload_model)
service.unload_model()
finally:
model_gate.release(owner)
@@ -1453,8 +1343,7 @@ class AutotagRoutesMixin:
if not is_skipped_folder(name) and depth + 1 <= _SCAN_MAX_DEPTH
)
for name in sorted(filenames):
suffix = Path(name).suffix.lower()
if suffix not in _MEDIA_EXTENSIONS or not collectable(suffix):
if Path(name).suffix.lower() not in _MEDIA_EXTENSIONS:
continue
candidate = Path(dirpath) / name
if candidate.is_symlink():
+2 -3
View File
@@ -45,6 +45,7 @@ import os
import sqlite3
import tempfile
from contextlib import closing
from pathlib import Path
from aiohttp import web
@@ -55,7 +56,6 @@ from .maintenance_plans import PlanExpired, PlanUsed
from .restore_plans import RestorePlanStore
try:
from ...database.sqlite_uri import readonly_uri
from ...database import restore_stage
from ...database.operations import PromptDatabase
from ...database.safety_backup import (
@@ -66,7 +66,6 @@ try:
safety_temp,
)
except ImportError:
from database.sqlite_uri import readonly_uri
from database import restore_stage
from database.operations import PromptDatabase
from database.safety_backup import (
@@ -187,7 +186,7 @@ def snapshot_corruption(path):
with open(path, "rb") as handle:
if handle.read(len(SQLITE_HEADER)) != SQLITE_HEADER:
return "Not a SQLite database file"
uri = readonly_uri(path)
uri = Path(os.path.abspath(path)).as_uri() + "?mode=ro"
with closing(sqlite3.connect(uri, uri=True)) as conn:
row = conn.execute("PRAGMA integrity_check").fetchone()
except (OSError, sqlite3.Error) as error:
+1 -12
View File
@@ -65,7 +65,6 @@ from .duplicate_review import ( # noqa: F401 (CHANGED, OUTSIDE_SOURCE: public)
NOT_ATTEMPTED,
OUTSIDE_SOURCE,
RECORDS_FAILED,
REVIEW_KEPT_DETAILS,
ROW_DETAILS,
SAME_FILE,
SOURCES_CHANGED,
@@ -435,7 +434,6 @@ class DuplicateFilesMixin:
{
"targets": review["targets"],
"kept": review["kept"],
"held": review["held"],
"protected": review["public"]["protected"]["count"],
},
)
@@ -448,7 +446,7 @@ class DuplicateFilesMixin:
job hashes each file again right before it unlinks it.
"""
listed = self._listed_sources()
targets, kept, protected, held = [], [], {}, []
targets, kept, protected = [], [], {}
for group, keepers in selection.values():
removals = [r for r in group["files"] if r not in keepers]
for record in removals:
@@ -469,7 +467,6 @@ class DuplicateFilesMixin:
problem = _bound_problem(record, group, keeper)
if problem:
protected[problem] = protected.get(problem, 0) + 1
held.append(self._copy_row(record, REVIEW_KEPT_DETAILS[problem]))
continue
reviewed.append(self._target(group, record, keeper))
if reviewed:
@@ -491,7 +488,6 @@ class DuplicateFilesMixin:
return {
"targets": targets,
"kept": kept,
"held": held,
"fingerprint": _fingerprint(targets),
"public": _public_plan(targets, protected, records),
}
@@ -588,13 +584,6 @@ class DuplicateFilesMixin:
async def _remove_duplicates(self, job, db, plan, backup):
targets = plan.payload["targets"]
# #586: every copy the review protected, with its reason, and the
# whole group in the report.
held = plan.payload["held"]
job.record_counted("kept", len(held), held, complete=True)
if held:
copies = _plural(len(held), "copy", "copies")
job.log_line(f"Kept {copies} the review protected")
for row in plan.payload["kept"]:
job.record("kept", row, f"= {row['root']}/{row['path']} · {KEPT_COPY}")
job.update(total=len(targets), status_line="Removing duplicate files")
+1 -14
View File
@@ -70,18 +70,6 @@ PROTECTED_REASONS = {
"files kept: their kept copy changed or is gone",
),
}
# The job's row for a copy the review protected (#586): the review's reason.
REVIEW_KEPT_DETAILS = {
MAYBE_SAME: "Kept: may be the same file reached through another mount or share",
NO_FILE_ID: "Kept: can't confirm this is a separate file on this drive",
SAME: "Kept: the same file as its kept copy",
OUTSIDE_SOURCE: "Kept: not inside a configured source",
LINK: "Kept: a link, not a regular file",
CHANGED_CONTENT: "Kept: changed since the search",
GONE: "Kept: no longer exists",
UNREADABLE: "Kept: could not be read",
KEEPER: "Kept: its kept copy changed or is gone",
}
# Job outcome rows (never an OS error text).
CHANGED = "The file changed since the review; it was kept."
KEEPER_CHANGED = "The kept copy changed or is gone; this file was kept."
@@ -304,8 +292,7 @@ def _relative_key(path, root):
relative = os.path.relpath(str(path), str(root))
except ValueError: # another drive (Windows)
return None
# #646: on POSIX ``a\\b.png`` and ``a/b.png`` are two files.
return os.path.normcase(relative).replace(os.sep, "/")
return os.path.normcase(relative).replace("\\", "/")
@dataclass
+4 -6
View File
@@ -148,7 +148,7 @@ def folder_sets(root, files) -> tuple[frozenset, frozenset]:
folders.add(rel_dir)
with_ancestors = set(folders)
for folder in folders:
with_ancestors.update(_ancestors(folder, sep))
with_ancestors.update(_ancestors(folder))
return frozenset(folders), frozenset(with_ancestors)
@@ -158,7 +158,7 @@ def add_folder(root, path, folders, with_ancestors) -> tuple[frozenset, frozense
rel_dir = _folder_of(root, path, sep, prefix)
if not rel_dir or rel_dir in folders:
return folders, with_ancestors
return folders | {rel_dir}, with_ancestors | {rel_dir, *_ancestors(rel_dir, sep)}
return folders | {rel_dir}, with_ancestors | {rel_dir, *_ancestors(rel_dir)}
def _root_prefix(root) -> tuple[str, str]:
@@ -180,10 +180,8 @@ def _folder_of(root, path, sep, prefix) -> str:
return "" if rel_dir == "." else rel_dir
def _ancestors(folder: str, sep: str) -> list[str]:
# #646: ``\\`` separates only in a Windows root (*sep*, the root flavour's
# own); on POSIX it is part of a folder's name.
parts = (folder.replace("\\", "/") if sep == "\\" else folder).split("/")
def _ancestors(folder: str) -> list[str]:
parts = folder.replace("\\", "/").split("/")
return ["/".join(parts[:i]) for i in range(1, len(parts))]
+1 -35
View File
@@ -3,7 +3,7 @@
import asyncio
import base64
import binascii
from functools import partial, wraps
from functools import wraps
import json
import os
import re
@@ -31,9 +31,7 @@ from .inspection_service import (
CurrentFileChanged,
image_tags_reader,
inspect_current_file,
review_reader,
)
from .admin import _scan_roots
from .images import image_category_key
try:
@@ -719,37 +717,6 @@ class HistoryRoutesMixin:
)
return OWN_CATEGORY_UNREAD
def _history_review(self, target) -> Callable:
"""The ``review`` reader of a reported current file (#659, C4).
Located as the scan locates it (``_review_location`` over the scan
roots, resolved like the canonical target), only when the inspector
asks; a file under no scan root reads None. A file reached through a
linked subfolder is keyed by its resolved path here, so an item the
scan stored under the linked spelling is not found (None, no choice).
A file without an item is recorded first through the review worker's
path (#657 addendum D2). The read closes its connection, as this
route's other reads do.
"""
def read(size: int, mtime_ns: int) -> dict | None:
roots = _scan_roots(
[os.path.realpath(root) for root in self._get_all_output_dirs()]
)
located = self._review_location(target, roots)
if located is None:
return None
locator = os.path.normcase(located[3])
return review_reader(
self.db,
locator,
self.logger,
close=True,
record=partial(self.inspect_review_file, str(target)),
)(size, mtime_ns)
return read
async def _history_current(
self, request: web.Request, kind: str
) -> web.StreamResponse:
@@ -826,7 +793,6 @@ class HistoryRoutesMixin:
recorded=recorded_output_lookup(
db, close=True, reference=receipt["reference"]
),
review=self._history_review(resolved.canonical_target),
)
_reauthorize_current_target(resolved, scope)
identity = {
+18 -77
View File
@@ -1,9 +1,9 @@
"""Delete images: remove from library, trash, or permanently delete.
"""Delete selected images: remove them from the library, or trash them (#480).
``POST /prompt_manager/images/delete/preview {items | filter}`` reviews the
selection for all modes at once and answers a reviewed plan (the System ›
selection for both modes at once and answers a reviewed plan (the System ›
Maintenance contract, ``py/api/maintenance.py``): the token, the counts of
the records each file loses, the refused files with a coded reason (all
the records each file loses, the refused files with a coded reason (both
modes, and the trash-only ones), the prompts that lose their last image and
the safety backup. It writes nothing. ``items`` are Images listing identities
(at most 500); ``filter`` is "Select all N matching". Each target is matched
@@ -19,16 +19,12 @@ again (containment and fingerprint) and
in one transaction; the file stays on disk, hidden;
- ``mode="trash"``: it is moved to the trash first (``utils/trash.py``); a
refused move leaves the file and its records alone; after a move its
records are deleted;
- ``mode="permanent"``: it is unlinked from disk with ``os.remove``; a refused
unlink leaves the file and its records alone; after removal its records are
deleted. This mode is Linux/BSD only.
records are deleted.
Only ``mode="permanent"`` unlinks a media file from disk. A failed records
write stops the job; the files after it are not attempted.
No path here unlinks a media file. A failed records write stops the job; the
files after it are not attempted.
"""
import errno
import hashlib
import json
import os
@@ -63,11 +59,10 @@ except ImportError:
from utils.media_folders import is_trash_folder
IMAGE_DELETE = "delete_images"
MODES = ("library", "trash", "permanent")
MODES = ("library", "trash")
TITLES = {
"library": "Delete images (remove from the library)",
"trash": "Delete images (move to the trash)",
"permanent": "Delete images (permanently delete from disk)",
}
MAX_DETAIL_ROWS = 50
# The system moved the file but its place in a trash could not be shown (#499).
@@ -92,8 +87,8 @@ REASONS = {
trash.LOCKED: "The file is open in another program. Close it and try again.",
trash.FAILED: "The file could not be moved to the trash.",
trash.NO_PERMISSION: (
"PromptManager isn't allowed to remove this file (no permission, or it is "
"locked)."
"PromptManager isn't allowed to move this file (no permission, or it is "
"locked in Finder)."
),
trash.CLOUD_SYNC: (
"Files in iCloud Drive or a cloud-synced folder can't be moved to the "
@@ -119,16 +114,6 @@ SOURCES_CHANGED = "The sources changed since the review; nothing was changed."
RECORDS_FAILED = "The image records could not be removed; the job stopped."
def _permanent_delete_code(error: OSError) -> str:
"""Translate a removal ``OSError`` into a permanent-delete refusal code."""
code = error.errno if error.errno else None
if code in (errno.EACCES, errno.EPERM, errno.EROFS):
return trash.NO_PERMISSION
if code in (errno.ENETUNREACH, errno.ENETRESET, errno.EHOSTUNREACH):
return trash.NETWORK
return trash.LOCKED
def lexical_problem(relative: str) -> str | None:
"""The refusal code a root-relative POSIX path earns before any file access."""
parts = relative.split("/")
@@ -290,23 +275,17 @@ class ImageDeleteMixin:
acted.append(target)
counted = db.count_removal_records([t["removal"] for t in acted])
library_count = len(acted)
permanent_supported = permanent_delete_supported()
public = {
"operation": IMAGE_DELETE,
"scope": {"count": library_count, "label": "images"},
"library": {"count": library_count},
"trash": {"count": library_count - len(trash_refused)},
"permanent": {"count": library_count},
"protected": {"count": len(refused), "reasons": []},
"refused": _summary(refused),
"trash_refused": _summary(trash_refused),
"records": counted["records"],
"orphaned_prompts": counted["orphaned_prompts"],
"media": {
"deletes_files": permanent_supported,
"label": "Chosen in the review",
},
"permanent_delete_supported": permanent_supported,
"media": {"deletes_files": False, "label": "Chosen in the review"},
"details": [],
}
return {"targets": acted, "public": public}
@@ -362,11 +341,7 @@ class ImageDeleteMixin:
async def _delete_images(self, job, db, targets, mode, backup):
job.update(total=len(targets), status_line=TITLES[mode])
roots = [str(root) for root in self._get_all_output_dirs()]
done_group = (
"trashed"
if mode == "trash"
else ("deleted" if mode == "permanent" else "removed")
)
done_group = "trashed" if mode == "trash" else "removed"
changed, failed = 0, None
for done, target in enumerate(targets, start=1):
if failed:
@@ -391,26 +366,17 @@ class ImageDeleteMixin:
)
elif group == done_group:
changed += 1
if mode == "trash":
detail = (
f"Moved to the {label}" if label else "Removed from the library"
)
elif mode == "permanent":
detail = "Deleted from disk"
else:
detail = "Removed from the library"
detail = (
f"Moved to the {label}" if label else "Removed from the library"
)
self._record_delete(job, group, target, None, detail)
else:
self._record_delete(job, group, target, code)
job.update(processed=done, progress=int(done / len(targets) * 100))
if changed:
self.invalidate_gallery_cache()
if mode == "trash":
verb, where = "Moved", "to the trash"
elif mode == "permanent":
verb, where = "Permanently deleted", "from disk"
else:
verb, where = "Removed", "from the library"
verb = "Moved" if mode == "trash" else "Removed"
where = "to the trash" if mode == "trash" else "from the library"
line = f"{verb} {changed:,} of {len(targets):,} images {where}"
job.log_line(line)
job.update(progress=100, status_line=f"{line} · {backup_note(backup)}")
@@ -432,7 +398,7 @@ class ImageDeleteMixin:
"code": code,
"detail": text,
}
mark = {"removed": "-", "trashed": "-", "deleted": "-"}.get(group, "=")
mark = {"removed": "-", "trashed": "-"}.get(group, "=")
job.record(
group, row, f"{mark} {target['root_label']}/{target['rel']} · {text}"
)
@@ -471,21 +437,6 @@ class ImageDeleteMixin:
)
return "errors", TRASH_UNCONFIRMED, None
mark = None
elif mode == "permanent":
try:
os.remove(target["abs"])
except OSError as error:
if error.errno == errno.ENOENT:
pass
else:
code = _permanent_delete_code(error)
self.logger.info(
"Not permanently deleted (%s): %s",
code,
target["rel"],
)
return "not_changed", code, None
mark = None
else:
mark = (target["size"], target["mtime_ns"])
try:
@@ -494,11 +445,7 @@ class ImageDeleteMixin:
self.logger.exception("Removing an image's records failed")
return "errors", None, label
_remove_thumbnail(Path(target["root"]), Path(target["rel"]), self.logger)
if mode == "trash":
return "trashed", None, label
if mode == "permanent":
return "deleted", None, label
return "removed", None, label
return ("trashed" if mode == "trash" else "removed"), None, label
# ── the workspace listing ─────────────────────────────────────────
@@ -570,12 +517,6 @@ class ImageDeleteMixin:
return [path for path in paths if not removed(path)]
def permanent_delete_supported() -> bool:
"""Permanent delete is offered only with the Freedesktop trash backend
(Linux/BSD servers); the review and the apply both ask here (#644)."""
return isinstance(trash.BACKEND, trash.FreedesktopBackend)
def parse_mode(value):
"""The apply's ``mode``, or None when it is not one of MODES."""
return value if isinstance(value, str) and value in MODES else None
+5 -42
View File
@@ -39,7 +39,6 @@ from typing import NamedTuple
from aiohttp import web
from .. import model_gate
from ..tagging_defaults import SkipMatcher
from .admin import _plural, _time_left
from .annotation_suggest import (
OptionError,
@@ -171,8 +170,6 @@ class _Run:
owner: object
service: object = None
roots: dict = field(default_factory=dict)
# The job's Skipped tags, compiled once at its start (#431).
skip: object = None
@dataclass(frozen=True)
@@ -186,9 +183,6 @@ class _Spec:
options: dict | None = None
# A listing filter the start resolves into ``targets`` (#392).
filter: dict | None = None
# The Skipped tags when the job was requested (#431); a later save does
# not change a running job.
skip: tuple = ()
@property
def title(self) -> str:
@@ -244,11 +238,7 @@ def _parse_auto(targets, data):
)
except OptionError as exc:
return None, bad_request(str(exc))
skip = tuple(AutotagConfig.SKIPPED_TAGS)
return (
_Spec("auto", targets, model_type=model_type, options=options, skip=skip),
None,
)
return _Spec("auto", targets, model_type=model_type, options=options), None
def parse_image_tag_request(data: dict):
@@ -259,8 +249,7 @@ def parse_image_tag_request(data: dict):
``filter`` (a listing query object, parse_listing_filter) may stand in for
``targets``; the start resolves it.
"""
mode = data.get("mode")
fields = _FIELDS.get(mode) if isinstance(mode, str) else None
fields = _FIELDS.get(data.get("mode"))
if fields is None:
return None, bad_request('mode must be "add" or "auto"')
fields = fields | {"filter" if "filter" in data else "targets"}
@@ -340,8 +329,6 @@ class AutotagRun:
keep_in_memory: bool
backup_on: bool
owner: object
# The Skipped tags when the job was started (#431).
skip: tuple = ()
@dataclass(frozen=True)
@@ -413,14 +400,6 @@ def _load_model(service, model_type: str, use_gpu: bool) -> None:
raise RuntimeError(f"{model_type} could not be loaded")
def _skipped_tags_line(entries: tuple) -> str:
"""The job log's one line about the Skipped tags it runs with (#431)."""
if not entries:
return "Skipped tags: none"
count = len(entries)
return f"Skipped tags: {count} {'entry' if count == 1 else 'entries'}"
def _refusal(status: int, code: str, message: str) -> Refusal:
response = web.json_response(
{"success": False, "code": code, "error": message}, status=status
@@ -528,7 +507,6 @@ class ImageTagJobsMixin:
released when the task ends, also before its runner ever starts.
"""
from ..autotag import MODELS, get_autotag_service
from ..config import AutotagConfig
backup_on = self._safety_backup_policy() == "on"
status = await self._run_in_executor(get_autotag_service().get_models_status)
@@ -551,13 +529,7 @@ class ImageTagJobsMixin:
response = model_busy_response()
return None, Refusal(409, "model-busy", MODEL_BUSY_ERROR, response)
run = AutotagRun(
model_type,
existing,
options,
keep_in_memory,
backup_on,
owner,
skip=tuple(AutotagConfig.SKIPPED_TAGS),
model_type, existing, options, keep_in_memory, backup_on, owner
)
admitted = False
try:
@@ -626,9 +598,7 @@ class ImageTagJobsMixin:
return _batch_cancelled(job)
job.publish({"type": "phase", "phase": "model"})
job.update(status_line="Loading the tagging model")
spec = _Spec(
"auto", (), model_type=run.model_type, options=run.options, skip=run.skip
)
spec = _Spec("auto", (), model_type=run.model_type, options=run.options)
service = await self._prepare_tagging_model(job, spec, run.owner)
if service is None:
return "failed"
@@ -654,7 +624,6 @@ class ImageTagJobsMixin:
f"Tagging started · {job.scope.get('label') or run.model_type} · "
f"{_plural(total, 'image')} · {policy}"
)
job.log_line(_skipped_tags_line(spec.skip))
if job.cancelled:
return _batch_cancelled(job)
remaining = await self._autotag_prepass(job, targets, run.existing == "skip")
@@ -664,9 +633,7 @@ class ImageTagJobsMixin:
spec = dataclasses.replace(
spec, targets=tuple(item.target for item in remaining)
)
loop_run = _Run(
job, spec, epoch, run.owner, service, skip=SkipMatcher(spec.skip)
)
loop_run = _Run(job, spec, epoch, run.owner, service)
if not await self._tag_each_file(loop_run, done_before=done):
job.update(status_line=STORAGE_RESTORED)
job.log_line(f"Tagging stopped · {STORAGE_RESTORED}")
@@ -772,9 +739,6 @@ class ImageTagJobsMixin:
started += f" · {spec.model_type}"
job.log_line(started)
run = _Run(job, spec, epoch, owner)
if spec.mode == "auto":
job.log_line(_skipped_tags_line(spec.skip))
run.skip = SkipMatcher(spec.skip)
try:
if spec.mode == "auto":
run.service = await self._prepare_tagging_model(job, spec, owner)
@@ -930,7 +894,6 @@ class ImageTagJobsMixin:
capture,
spec.model_type,
spec.options,
run.skip,
on_skipped=functools.partial(store.release_use, capture.token),
)
except Exception:
+37 -65
View File
@@ -25,7 +25,6 @@ from aiohttp import web
from PIL import Image, UnidentifiedImageError
from .jobs import MAX_OUTCOME_ROWS, THUMBNAILS_JOB_KIND
from .json_body import BodyTooLarge, json_error, read_json_object
from . import gallery_listing
from .gallery_listing import (
DISCARDED,
@@ -57,7 +56,6 @@ from .inspection_service import (
VIDEO_EXTENSIONS,
image_tags_reader,
inspect_current_file,
review_reader,
)
try:
@@ -72,11 +70,8 @@ try:
in_trash_below_roots,
in_trash_folder,
is_skipped_folder,
path_separators,
split_relative,
)
from ...utils.parallel import map_parallel
from ...utils.media_formats import collectable
from ...utils.json_strict import dumps_strict
from ...utils.inspection_response import (
OWN_CATEGORY_UNREAD,
@@ -106,11 +101,8 @@ except ImportError:
in_trash_below_roots,
in_trash_folder,
is_skipped_folder,
path_separators,
split_relative,
)
from utils.parallel import map_parallel
from utils.media_formats import collectable
from utils.json_strict import dumps_strict
from utils.inspection_response import (
OWN_CATEGORY_UNREAD,
@@ -275,23 +267,18 @@ def _is_within(path, root):
def _has_traversal(relative):
"""True for absolute paths, drive-qualified paths or any ``..`` segment.
Segments are split at this server's separators: on POSIX ``\\`` is part
of a name, so ``a\\..\\b`` is one name below the root (#646).
"""
"""True for absolute paths, drive-qualified paths or any ``..`` segment."""
if not relative or os.path.isabs(relative) or os.path.splitdrive(relative)[0]:
return True
if relative[0] in path_separators():
if relative[0] in ("/", "\\"):
return True
return ".." in split_relative(relative)
return ".." in re.split(r"[\\/]+", relative)
def _is_thumbnail_cache_path(relative):
"""True when *relative* names something in a root's ``thumbnails/``
cache (any case, this server's separators, #646): never inspected as a
media file."""
first = split_relative(relative.lstrip(path_separators()))[0]
cache (any case, either separator): never inspected as a media file."""
first = re.split(r"[\\/]+", relative.lstrip("\\/"), maxsplit=1)[0]
return first.casefold() == "thumbnails"
@@ -326,10 +313,7 @@ def _media_access_error(path, allowed_dirs):
# Media types the gallery scans and thumbnails (a superset is never served).
# #652: AVIF is named here and skipped by the walks when Pillow cannot read it.
GALLERY_IMAGE_EXTENSIONS = frozenset(
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".avif"}
)
GALLERY_IMAGE_EXTENSIONS = frozenset({".png", ".jpg", ".jpeg", ".webp", ".gif"})
MEDIA_EXTENSIONS = GALLERY_IMAGE_EXTENSIONS | VIDEO_EXTENSIONS
# Caps on request-triggered filesystem work.
@@ -555,6 +539,7 @@ def _thumbnail_is_fresh(src, dst):
MAX_GALLERY_FILES = 50_000
MAX_BULK_LIMIT = 5_000
MAX_JSON_BODY_BYTES = 1024 * 1024
_READ_CHUNK = 64 * 1024
# Guards the first load of an API's workspace keys (#430, _workspace_keys).
@@ -723,17 +708,36 @@ def _workspace_cursor_key(token: str, scope: str, order: str, secret: bytes) ->
raise ValueError("Invalid gallery cursor; refresh the gallery") from None
# The shared bounded reader, at this module's own cap.
_BodyTooLarge = BodyTooLarge
_json_error = json_error
class _BodyTooLarge(Exception):
"""Raised when a request body exceeds MAX_JSON_BODY_BYTES."""
def _json_error(message, status):
return web.json_response({"success": False, "error": message}, status=status)
async def _read_json_body(request):
"""The JSON object body, or raise _BodyTooLarge past MAX_JSON_BODY_BYTES.
"""Read a JSON object body in bounded chunks.
Raises ValueError when the body is not a JSON object.
Raises _BodyTooLarge past MAX_JSON_BODY_BYTES (declared or streamed) and
ValueError when the body is not a JSON object.
"""
return await read_json_object(request, MAX_JSON_BODY_BYTES)
limit = MAX_JSON_BODY_BYTES
if request.content_length is not None and request.content_length > limit:
raise _BodyTooLarge()
chunks, size = [], 0
while True:
chunk = await request.content.read(_READ_CHUNK)
if not chunk:
break
size += len(chunk)
if size > limit:
raise _BodyTooLarge()
chunks.append(chunk)
data = json.loads(b"".join(chunks).decode("utf-8"))
if not isinstance(data, dict):
raise ValueError("JSON body must be an object")
return data
async def _json_body_or_error(request):
@@ -871,7 +875,7 @@ def _favorite_root_key(root) -> str:
def _source_depth(source: str) -> int:
return len([part for part in split_relative(source) if part])
return len([part for part in re.split(r"[\\/]+", source) if part])
def deepest_source(sources, absolute_path):
@@ -956,9 +960,7 @@ def _walk_media(output_path, max_files):
except OSError:
continue # as os.walk: an unreadable folder is skipped
for entry in sorted(files, key=lambda item: item.name):
suffix = _name_suffix(entry.name).lower()
# #652: AVIF is listed but only collected where Pillow reads it.
if suffix not in MEDIA_EXTENSIONS or not collectable(suffix):
if _name_suffix(entry.name).lower() not in MEDIA_EXTENSIONS:
continue
if entry.is_symlink():
continue # never read through a link out of the output tree
@@ -991,8 +993,7 @@ def _settled_entry(root, relative):
if on_disk is not None and not on_disk.endswith(os.sep + relative):
raise OSError(f"{relative} is spelled differently on disk")
*folders, name = relative.split(os.sep)
suffix = _name_suffix(name).lower()
if suffix not in MEDIA_EXTENSIONS or not collectable(suffix):
if _name_suffix(name).lower() not in MEDIA_EXTENSIONS:
return None
if in_skipped_folder(folders) or len(folders) > MAX_SCAN_DEPTH:
return None
@@ -1199,10 +1200,6 @@ def _output_image_entry(
}
if root_scope is not None:
entry["root_scope"] = root_scope
if "\\" in entry["path"]:
# #646: only a POSIX server lists a name holding a backslash (Windows
# turns it into ``/``); the workspace accepts it only with this mark.
entry["path_style"] = "posix"
return entry
@@ -1224,10 +1221,9 @@ def _workspace_filters(query: Mapping) -> dict:
folded = text.casefold()
media = query.get("media", "all")
order = query.get("sort", "newest")
# #646: ``\\`` separates only on Windows; on POSIX it is part of a name.
folder = "/".join(split_relative(query.get("subfolder", "").strip()))
folder = query.get("subfolder", "").strip().replace("\\", "/")
# ``path``: one exact relative path (Activity opens a scan row by it, D57).
exact = "/".join(split_relative(query.get("path", "").strip()))
exact = query.get("path", "").strip().replace("\\", "/")
category = query.get("category", "").strip() or None
tags = sorted(
{tag.strip() for tag in query.get("tags", "").split(",") if tag.strip()}
@@ -4139,9 +4135,6 @@ class ImageRoutesMixin:
roots[index], Path(relative).parts
),
recorded=recorded_output_lookup(self.db),
review=self._inspection_review(
index, outputs, roots[index], Path(relative).parts
),
)
except CurrentFileChanged:
return None
@@ -4186,27 +4179,6 @@ class ImageRoutesMixin:
locator = os.path.normcase(os.path.join(os.path.realpath(root), *parts))
return image_tags_reader(self.db, locator, self.logger)
def _inspection_review(
self, index: int, outputs: list, root: Path, parts: tuple
) -> Callable | None:
"""The inspector's ``review`` reader for one rooted file (#659, C4).
Keyed as review items are (the normcased realpath of the root joined
with the relative path). Only an output root is a scan root; a root
past the output folders (a LoRA root) gives None. A file without an
item is recorded first through the review worker's path (#657 D2).
"""
if index >= len(outputs):
return None
locator = os.path.normcase(os.path.join(os.path.realpath(root), *parts))
path = os.path.join(str(root), *parts)
return review_reader(
self.db,
locator,
self.logger,
record=functools.partial(self.inspect_review_file, path),
)
def _read_own_category(self, sources, path):
"""One file's own category, None, or OWN_CATEGORY_UNREAD (blocking).
-73
View File
@@ -42,8 +42,6 @@ IMAGE_EXTENSIONS = frozenset(
".bmp",
".tiff",
".tif",
# #652: served and inspected; the scan collects it where Pillow reads it
".avif",
".mp4",
".webm",
".mov",
@@ -124,67 +122,6 @@ def image_tags_reader(
return read
def review_reader(
db: Any,
locator: str,
logger: Any,
*,
close: bool = False,
record: Callable[[dict | None], Any] | None = None,
) -> Callable[[int, int], dict | None]:
"""The inspector's ``review`` reader for one file *locator* (#659, C4).
The returned function takes the inspection's own stable stat and answers
the file's Needs review item at exactly that ``(size, mtime_ns)``
(``review_item_at``): pending with its id, decided, or None. A failed
read is None, never an error. ``close`` closes the calling thread's
connection afterwards, for routes that close theirs (History).
*record*, when given, is called with the found facet when there is no
item at that stat or a pending one (#657 addendum D2: Inspect records the
item, or records a stale one again, through the review worker's own
per-file path; the caller decides whether anything needs doing). The
item is then read once more, also after a failed recording (the worker
may have recorded it meanwhile). A recording error is logged.
"""
def read(size: int, mtime_ns: int) -> dict | None:
try:
found = db.review_item_at(locator, size, mtime_ns)
if record is not None and (found is None or found["state"] == "pending"):
_record(record, found, logger)
found = db.review_item_at(locator, size, mtime_ns)
return found
except Exception:
logger.warning("Inspection review item could not be read", exc_info=True)
return None
finally:
if close:
db.model.close()
return read
def _record(record: Callable[[dict | None], Any], found, logger: Any) -> None:
"""Run *record* for the *found* facet; an error is logged, not raised."""
try:
record(found)
except Exception:
logger.warning(
"Inspection could not add the file to Needs review", exc_info=True
)
def _asks_review(evidence: dict, library: dict) -> bool:
"""Whether Inspect may offer a choice: an ambiguous role, an unlinked file."""
prompts = evidence.get("prompts") or {}
ambiguous = any(
isinstance(side, dict) and side.get("status") == "ambiguous"
for side in prompts.values()
)
return ambiguous and isinstance(library, dict) and library.get("status") == "none"
def inspect_current_file(
path: Path,
*,
@@ -193,7 +130,6 @@ def inspect_current_file(
library: dict,
image_tags: Callable[[int, int], dict] | None = None,
recorded: Callable[[Path], Any] | None = None,
review: Callable[[int, int], dict | None] | None = None,
) -> dict:
"""Current-file evidence read between two equal stats of *path*.
@@ -203,9 +139,6 @@ def inspect_current_file(
*recorded*, when given, is asked within the same stat window for what
recorded run history knows about *path* (``RecordedOutput`` or None: the
save node that wrote it and the texts PromptManager recorded, #386).
*review*, when given, is called with the same stat only when a role is
ambiguous and ``library["status"]`` is ``none``; its answer (or None) is
returned as ``review`` (#659).
"""
before = _current_file_facts(path)
try:
@@ -240,12 +173,6 @@ def inspect_current_file(
recorded_saver_id=run.saver_id if run is not None else None,
recorded_texts=run.texts if run is not None else None,
)
if review is not None:
facets["review"] = (
review(before.st_size, before.st_mtime_ns)
if _asks_review(evidence, library)
else None
)
return {
"file": {
"observation": "current-file",
+27 -47
View File
@@ -42,7 +42,6 @@ open across the switch (#249 S8).
import asyncio
import itertools
import logging
import os
import re
import time
import uuid
@@ -124,15 +123,11 @@ MODEL_DOWNLOAD_JOB_KIND = "model_download"
DUPLICATES_JOB_KIND = "duplicates"
DUPLICATE_GROUP_NAMES = ("groups_found",)
DUPLICATE_CLEANUP_GROUP_NAMES = ("removed", "kept", "errors")
# Tag cleanup (#618, py/api/tag_cleanup.py): the find is a ``read`` job that
# holds its findings; the reviewed apply is a ``maintenance`` job.
TAG_CLEANUP_JOB_KIND = "tag_cleanup"
TAG_CLEANUP_GROUP_NAMES = ("found",)
# The workspace Library's Delete… (#443, py/api/library_delete.py): a
# ``records`` hold around its safety backup and write.
PROMPT_DELETE_JOB_KIND = "prompt_delete"
IMAGE_DELETE_JOB_KIND = "image_delete" # #480
IMAGE_DELETE_GROUP_NAMES = ("trashed", "removed", "deleted", "not_changed", "errors")
IMAGE_DELETE_GROUP_NAMES = ("trashed", "removed", "not_changed", "errors")
# The System health check (py/api/system.py): a read-only ``read`` job with
# no file outcomes, so it may run beside a scan.
HEALTH_JOB_KIND = "health"
@@ -165,8 +160,7 @@ def _relative_path(path) -> str:
or PureWindowsPath(text).drive
):
return re.split(r"[\\/]", text)[-1]
# #646: on POSIX a backslash is part of a name, never a separator.
return text.replace("\\", "/") if os.sep == "\\" else text
return text.replace("\\", "/")
class JobBusy(Exception):
@@ -210,8 +204,6 @@ class Job:
self.total = 0
self.counters = dict.fromkeys(groups, 0)
self.outcomes = {group: [] for group in groups}
# Groups whose report lists every row, beyond MAX_OUTCOME_ROWS (#550).
self.complete = {}
self.log = []
self._cancel_requested = False
self.last_event = None
@@ -294,48 +286,42 @@ class Job:
index = row.get("root_index")
if isinstance(index, bool) or not isinstance(index, int) or index < 0:
index = None
shaped = {
"path": path,
"root": str(row.get("root") or ""),
"root_index": index,
"detail": str(row.get("detail") or ""),
}
if group in self.complete: # a group kept whole for the report (#586)
self.complete[group].append(dict(shaped))
if len(rows) < MAX_OUTCOME_ROWS:
rows.append(shaped)
rows.append(
{
"path": path,
"root": str(row.get("root") or ""),
"root_index": index,
"detail": str(row.get("detail") or ""),
}
)
self.log_line(log_line)
def record_counted(self, group, count, rows=(), *, complete=False):
def record_counted(self, group, count, rows=()):
"""Count ``count`` outcomes in ``group`` at once, listing ``rows``.
For outcomes that need no log line each (a thumbnail job's already
fresh previews): the counter is exact, ``rows`` (``record``'s row
shape) are listed up to MAX_OUTCOME_ROWS, and nothing is logged.
``complete`` also keeps every row for the report (#550: a record of
each change that must not be cut short; the caller bounds it).
"""
if group not in self.counters:
raise ValueError(f"Unknown outcome group {group!r} for {self.kind}")
self.counters[group] += max(0, int(count))
listed = self.outcomes[group]
kept = self.complete.setdefault(group, []) if complete else None
for row in rows:
if kept is None and len(listed) >= MAX_OUTCOME_ROWS:
if len(listed) >= MAX_OUTCOME_ROWS:
break
index = row.get("root_index")
if isinstance(index, bool) or not isinstance(index, int) or index < 0:
index = None
shaped = {
"path": _relative_path(row.get("path")),
"root": str(row.get("root") or ""),
"root_index": index,
"detail": str(row.get("detail") or ""),
}
if kept is not None:
kept.append(shaped)
if len(listed) < MAX_OUTCOME_ROWS:
listed.append(dict(shaped))
listed.append(
{
"path": _relative_path(row.get("path")),
"root": str(row.get("root") or ""),
"root_index": index,
"detail": str(row.get("detail") or ""),
}
)
def finish(self, state="finished"):
"""End the job in ``state`` and release every subscriber.
@@ -420,9 +406,8 @@ class Job:
"""The downloadable report: the summary, every outcome group and the log.
Each group carries its exact count, its listed rows (at most
MAX_OUTCOME_ROWS, or every row of a ``complete`` group) and whether
the list is cut short. Rows and log lines already hold root-relative
paths only.
MAX_OUTCOME_ROWS) and whether the list is cut short. Rows and log lines
already hold root-relative paths only.
"""
summary = self.summary()
summary.pop("listed", None)
@@ -432,21 +417,16 @@ class Job:
"generated_at": self._clock(),
"job": summary,
"outcomes": {
group: self._report_group(group, rows)
group: {
"count": self.counters.get(group, len(rows)),
"rows": [dict(row) for row in rows],
"truncated": self.counters.get(group, len(rows)) > len(rows),
}
for group, rows in self.outcomes.items()
},
"log": list(self.log),
}
def _report_group(self, group, listed):
rows = self.complete.get(group, listed)
count = self.counters.get(group, len(rows))
return {
"count": count,
"rows": [dict(row) for row in rows],
"truncated": count > len(rows),
}
def report_filename(self):
"""The download name: prompt-manager-KIND-YYYYMMDD-HHMM.json (local time)."""
stamp = time.strftime("%Y%m%d-%H%M", time.localtime(self._clock()))
-60
View File
@@ -1,60 +0,0 @@
"""The one bounded reader for JSON object request bodies.
The body is read in chunks, so an oversized or chunked upload is refused as
soon as it crosses the cap rather than buffered whole. ``read_json_object``
raises; ``read_json_body`` answers with the API's ``{"success": false}``
envelope.
"""
import json
from aiohttp import web
JSON_BODY_MAX_BYTES = 1_000_000
_READ_CHUNK = 64 * 1024
INVALID_JSON = "Request body must be valid JSON"
NOT_AN_OBJECT = "Request body must be a JSON object"
class BodyTooLarge(Exception):
"""The request body is longer than the reader's ``max_bytes``."""
def json_error(message, status):
return web.json_response({"success": False, "error": message}, status=status)
async def read_json_object(request, max_bytes=JSON_BODY_MAX_BYTES):
"""The request's JSON object body of at most ``max_bytes``.
Raises:
BodyTooLarge: the declared or streamed body crosses ``max_bytes``.
ValueError: the body is not UTF-8 JSON (``INVALID_JSON``) or not a
JSON object (``NOT_AN_OBJECT``).
"""
declared = request.content_length
if declared is not None and declared > max_bytes:
raise BodyTooLarge()
chunks, size = [], 0
async for chunk in request.content.iter_chunked(_READ_CHUNK):
size += len(chunk)
if size > max_bytes:
raise BodyTooLarge()
chunks.append(chunk)
try:
data = json.loads(b"".join(chunks).decode("utf-8"))
except ValueError: # JSONDecodeError and UnicodeDecodeError are ValueErrors
raise ValueError(INVALID_JSON) from None
if not isinstance(data, dict):
raise ValueError(NOT_AN_OBJECT)
return data
async def read_json_body(request, max_bytes=JSON_BODY_MAX_BYTES):
"""``(data, None)``, or ``(None, response)`` with a 413 or 400 refusal."""
try:
return await read_json_object(request, max_bytes), None
except BodyTooLarge:
return None, json_error(f"Request body too large (max {max_bytes} bytes)", 413)
except ValueError as exc:
return None, json_error(str(exc), 400)
+1 -3
View File
@@ -377,9 +377,7 @@ class LibraryRoutesMixin:
[parent["id"] for parent in result["items"]]
)
result["next_cursor"] = _encode(
result.pop("next_key"),
scope,
name=options["sort"] in ("name", "name-desc"),
result.pop("next_key"), scope, name=options["sort"] == "name"
)
return result, records
-10
View File
@@ -75,14 +75,6 @@ def _failure(message, status, code):
)
def _thumbnail_folder():
"""The thumbnail folder in use, or None (previews inside each source)."""
from . import preview_store
setting = preview_store.setting()
return setting.path if setting.mode == preview_store.FOLDER_MODE else None
def _inside_thumbnail_folder(path):
"""Whether *path* lies in the thumbnail folder in use (#320)."""
from . import preview_store
@@ -244,8 +236,6 @@ class LibraryLocationRoutesMixin:
),
"problem": location.problem or self._node_folder_risk(location),
"size_bytes": size,
# #320 D201: thumbnails kept in one folder stay there (D8A).
"thumbnails_folder": _thumbnail_folder(),
}
# The node folder (tests point it at a temp tree).
+2 -23
View File
@@ -68,23 +68,6 @@ def _count(count, singular, plural):
return f"{count} {singular if count == 1 else plural}"
# Each kept entry's row in the job (#586), in the review's "Kept: ..." words.
KEPT_DETAILS = {
"active": "Kept: the active log",
"link": "Kept: a link",
"other": "Kept: another file",
}
def _kept_files(rows):
"""``{name, kind}`` of each entry the cleanup keeps, in folder order."""
return [
{"name": row["name"], "kind": row["kind"]}
for row in rows
if row["kind"] in KEPT_DETAILS
]
def _protected_reasons(rows):
"""The plan's Protected reasons: what the cleanup keeps, zero counts left out."""
active = sum(1 for row in rows if row["kind"] == "active")
@@ -146,7 +129,7 @@ class LogCleanupMixin:
token = store.issue(
ROTATED_LOGS,
json.dumps(files, sort_keys=True),
{"files": files, "protected": protected, "kept": _kept_files(rows)},
{"files": files, "protected": protected},
(),
)
except ScopeTooLarge:
@@ -215,11 +198,7 @@ class LogCleanupMixin:
job.record(
"errors", {"path": name, "detail": detail}, f"! {name} · {detail}"
)
kept = [
{"path": row["name"], "detail": KEPT_DETAILS[row["kind"]]}
for row in plan.payload["kept"]
]
job.record_counted("protected", len(kept), kept, complete=True)
job.record_counted("protected", plan.payload["protected"])
removed, failed = len(result["removed"]), len(result["failed"])
line = f"Deleted {_count(removed, 'rotated log copy', 'rotated log copies')}"
if failed:
+3 -24
View File
@@ -6,12 +6,9 @@ current imports, those a saved pair uses and the example images an import
would download. It writes nothing and requests nothing. It answers a
``Plan`` (the maintenance plan's shape, ``py/api/maintenance.py``) plus
``{lora_files, with_metadata, skipped, with_local_media, current_imports,
blocked_by_pairs, planned_downloads, trigger_tags, trigger_not_tags,
network:{planned_downloads, api_key}, layout}`` (#355: ``layout`` says which
LoraManager settings file, storage mode and library the import read, and
``error`` when they cannot be used; #618: ``trigger_tags`` and
``trigger_not_tags`` count the trained-words entries that become tags and
those that are lists or sentences, which the job log repeats). A plan
blocked_by_pairs, planned_downloads, network:{planned_downloads, api_key},
layout}`` (#355: ``layout`` says which LoraManager settings file, storage mode
and library the import read, and ``error`` when they cannot be used). A plan
that saved pairs block, or whose layout is unusable, carries no token
(nothing can be applied).
@@ -107,13 +104,6 @@ def _import_line(result, skipped):
return " · ".join(parts)
def not_tags_line(count):
"""The job log's count of trained-words entries not made tags (#618)."""
entries = _count(count, "trained-words entry", "trained-words entries")
verb = "was" if count == 1 else "were"
return f"{entries} {verb} not made tags (lists or sentences)"
def _all_downloads_failed(errors):
"""The warning when every planned download failed (#337)."""
if errors == 1:
@@ -325,8 +315,6 @@ class LoraImportRoutesMixin:
"current_imports": current,
"blocked_by_pairs": blocked,
"planned_downloads": downloads,
"trigger_tags": int(found.get("trigger_tags", 0)),
"trigger_not_tags": int(found.get("trigger_not_tags", 0)),
"scope": {
"count": found["with_metadata"],
"label": (
@@ -453,9 +441,6 @@ class LoraImportRoutesMixin:
self.logger.exception("LoRA import staging failed")
return _fail_job(job, "import-failed", f"{FAILED} {CACHE_NOTE}")
self._count_downloads(job, staged)
not_tags = staged.stats.get("trigger_not_tags", 0)
if not_tags:
job.log_line(not_tags_line(not_tags))
# M4: what staging skipped stays on the job whatever happens next.
job.record_counted(
"skipped",
@@ -481,12 +466,6 @@ class LoraImportRoutesMixin:
return _fail_job(job, "plan-changed", f"{SOURCE_CHANGED} {CACHE_NOTE}")
job.update(status_line="Replacing the LoRA collection", progress=95)
await self._replace_in_job(job, db, plan, staged)
# #619: the replace is one transaction and has committed by now, so
# the import is finished even when ComfyUI is exiting: end it here,
# before the exit signal can relabel it "cancelled" on the way out.
# A failed replace already ended the job "failed"; a second finish
# is a no-op.
job.finish("finished")
return None
def _count_downloads(self, job, staged):
+17 -162
View File
@@ -1,13 +1,10 @@
"""Maintenance routes: reviewed, read-only plans (#249 System S6).
``POST /prompt_manager/maintenance/preview {operation, options:{}}`` reviews
one operation (``duplicate_prompts``, ``optimize``, ``unused_components``,
``missing_links`` or ``pair_metadata``, #550; ``database/maintenance.py``;
``duplicate_files``,
one operation (``duplicate_prompts``, ``optimize``, ``unused_components`` or
``missing_links``; ``database/maintenance.py``; ``duplicate_files``,
``py/api/duplicate_files.py``; ``rotated_logs``, the rotated log copies,
``py/api/log_cleanup.py``, which has its own apply job; ``tag_cleanup``,
#618, the ticked findings of a tag search, ``py/api/tag_cleanup.py``) off the
event loop and
``py/api/log_cleanup.py``, which has its own apply job) off the event loop and
answers a ``Plan``: ``{success, token, operation, expires_at, scope:{count,
label}, protected:{count, reasons}, backup:{policy, destination_label},
media:{deletes_files, label}, details:[≤50 {label, detail}]}``. The preview
@@ -31,17 +28,13 @@ The token is consumed when the job starts (on the same loop turn, before its
runner runs); a refused start keeps it. The runner:
1. takes a safety backup when the plan was reviewed with the policy on or the
policy (``maintenance.safety_backup``, default on) is on now, and always
for ``workflow_storage`` and ``tag_cleanup`` (``ALWAYS_BACKED_UP``, policy
``required``): SQLite's
policy (``maintenance.safety_backup``, default on) is on now: SQLite's
backup API into a temp file beside the database, ``verify_database_file``,
fsync, ``0o600`` on POSIX, then ``os.replace`` onto a unique
``<db>.backup_<YYYYmmdd_HHMMSS_ffffff>[_n]`` name. Any failure removes
what it wrote and ends the job ``backup-failed`` with nothing changed;
2. applies the plan, which first rechecks the reviewed fingerprint inside
``BEGIN IMMEDIATE`` (``plan-changed`` writes nothing); ``tag_cleanup``
rechecks each tag instead and keeps, with its reason, each one that
changed, while the rest still apply;
``BEGIN IMMEDIATE`` (``plan-changed`` writes nothing);
3. counts the changed and protected records, and prunes old safety backups.
The job log names the backup by its file name only, and the job says "No
@@ -93,13 +86,6 @@ MAINTENANCE_PREVIEW_LEASE = "Maintenance preview"
DUPLICATE_PREVIEW_BODY_MAX = 1024 * 1024
DUPLICATE_FILES = "duplicate_files"
WORKFLOW_STORAGE = "workflow_storage" # applied by py/api/workflow_storage.py
# #618: planned from a tag search's findings (py/api/tag_cleanup.py).
TAG_CLEANUP = "tag_cleanup"
# Previews whose options list many ids, read up to the large body cap.
LARGE_PREVIEWS = frozenset({DUPLICATE_FILES, TAG_CLEANUP})
# Always backed up first, whatever the safety-backup setting: Store each
# workflow once (the way back) and Tag cleanup (maintainer ruling, #618).
ALWAYS_BACKED_UP = frozenset({WORKFLOW_STORAGE, TAG_CLEANUP})
# rotated_logs (#329, py/api/log_cleanup.py) reviews log files, not records.
PREVIEW_OPERATIONS = MAINTENANCE_OPERATIONS + (DUPLICATE_FILES, ROTATED_LOGS)
# Room left over beyond what a step writes, so a disk is never filled to 0.
@@ -111,14 +97,7 @@ MAINTENANCE_TITLES = {
"unused_components": "Unused prompt components",
"missing_links": "Missing-file links",
"workflow_storage": "Store each workflow once",
# #550, beyond the concept: fills old Pair prompts' empty category and tags.
"pair_metadata": "Pair category and tags",
# #618 (D210), beyond the concept: deletes comma-list and unused tags.
TAG_CLEANUP: "Tag cleanup",
}
# Operations whose job keeps every changed row for its report (#550; #618:
# the report and the backup are the only record of the deleted tag names).
COMPLETE_RECORD = frozenset({"pair_metadata", TAG_CLEANUP})
_OPERATION_ERROR = "operation must be one of: " + ", ".join(PREVIEW_OPERATIONS)
MAINTENANCE_GROUPS = ("changed", "protected", "errors")
MAX_TOKEN_LENGTH = 128
@@ -302,29 +281,9 @@ def short_space_message(short):
)
def _pair_metadata_line(result):
count = result["changed"]
noun = (
"prompt from its saved pairs"
if count == 1
else "prompts from their saved pairs"
)
categories = result.get("categories", 0)
tag_sets = result.get("tag_sets", 0)
return (
f"Filled {count:,} {noun} "
f"({categories:,} {'category' if categories == 1 else 'categories'}, "
f"{tag_sets:,} {'tag set' if tag_sets == 1 else 'tag sets'})"
)
def _changed_line(operation, count, marks=0, result=None):
def _changed_line(operation, count, marks=0):
if operation == "optimize":
return "Optimized the database"
if operation == "pair_metadata":
return _pair_metadata_line(result or {"changed": count})
if operation == TAG_CLEANUP:
return f"Deleted {count:,} {'tag' if count == 1 else 'tags'}"
if operation == "duplicate_prompts":
noun = "duplicate prompt" if count == 1 else "duplicate prompts"
return f"Merged {count:,} {noun}"
@@ -426,7 +385,7 @@ class MaintenanceRoutesMixin:
("operation", "options"),
cap=lambda body: (
DUPLICATE_PREVIEW_BODY_MAX
if body.get("operation") in LARGE_PREVIEWS
if body.get("operation") == DUPLICATE_FILES
else PREVIEW_BODY_MAX
),
)
@@ -438,8 +397,6 @@ class MaintenanceRoutesMixin:
return _invalid(_OPERATION_ERROR)
if operation == DUPLICATE_FILES:
return await self.preview_duplicate_files(options)
if operation == TAG_CLEANUP:
return await self.preview_tag_cleanup(options)
if not isinstance(options, dict) or options:
return _invalid(f"{operation} takes no options")
if operation == ROTATED_LOGS:
@@ -490,12 +447,10 @@ class MaintenanceRoutesMixin:
)
policy = self._safety_backup_policy()
destination = "backup"
if operation in ALWAYS_BACKED_UP:
# Always backed up first, whatever the policy.
policy = "required"
if operation == WORKFLOW_STORAGE:
# The way back: one kept pre-migration backup ever, pooled ones
# after it.
# Always backed up first, whatever the policy (the way back);
# one kept pre-migration backup ever, pooled ones after it.
policy = "required"
kept = await self._run_in_executor(pre_migration_backups, db.model.db_path)
destination = "backup" if kept else PRE_MIGRATION_LABEL
try:
@@ -538,7 +493,7 @@ class MaintenanceRoutesMixin:
# ── apply ─────────────────────────────────────────────────────────
async def apply_maintenance_plan(self, request):
from .image_delete import IMAGE_DELETE, parse_mode, permanent_delete_supported
from .image_delete import IMAGE_DELETE, parse_mode
data, error = await self._read_maintenance_body(request, ("token", "mode"))
if error is not None:
@@ -553,12 +508,7 @@ class MaintenanceRoutesMixin:
if plan.operation == IMAGE_DELETE:
mode = parse_mode(data.get("mode"))
if mode is None:
return _invalid('mode must be "library", "trash" or "permanent"')
if mode == "permanent" and not permanent_delete_supported():
# The review never offers it here; refuse a direct call (#644).
return _invalid(
"Permanent delete is only available on Linux and BSD servers"
)
return _invalid('mode must be "library" or "trash"')
elif "mode" in data:
return _invalid("Unknown field: mode")
store = self._maintenance_plans
@@ -657,8 +607,8 @@ class MaintenanceRoutesMixin:
Decided once, when the apply starts (the disk check measured it), and
handed to the job.
"""
if plan.operation in ALWAYS_BACKED_UP:
return True # never without its backup (pre-migration, or #618's)
if plan.operation == WORKFLOW_STORAGE:
return True # never without its pre-migration backup
return plan.payload["backup"] == "on" or self._safety_backup_policy() == "on"
async def _safety_backup_step(self, job, db, backup_on):
@@ -718,74 +668,13 @@ class MaintenanceRoutesMixin:
rows = await self._run_in_executor(
self._maintenance_rows, plan.operation, result["rows"]
)
job.record_counted(
"changed",
result["changed"],
rows,
complete=plan.operation in COMPLETE_RECORD,
)
kept = await self._run_in_executor(self._kept_rows, db, plan, result)
if kept is None:
job.record_counted("protected", payload["protected"]) # none kept
else:
# #550, #586: each kept record with its reason, like the changed
# ones, and every one of them in the report.
job.record_counted("protected", len(kept), kept, complete=True)
line = _changed_line(
plan.operation, result["changed"], result.get("marks", 0), result
)
job.record_counted("changed", result["changed"], rows)
job.record_counted("protected", payload["protected"])
line = _changed_line(plan.operation, result["changed"], result.get("marks", 0))
job.log_line(line)
job.update(progress=100, status_line=f"{line} · {backup_note(backup)}")
return None
def _kept_rows(self, db, plan, result):
"""Outcome rows for the records the apply kept (blocking), or None.
Prompts are records (no path); a missing-links plan's kept links
name their file, relative to its output root, so Activity can open
and locate it (#586); one under a source that is gone keeps its path
under that source's label. None for an operation that keeps nothing
(Optimize).
"""
if plan.operation == "missing_links":
roots = _scan_roots(self._get_all_output_dirs())
judged = plan.payload["roots"]
rows = []
for item in db.kept_links(judged):
path, label, index = _scan_location(item["image_path"], roots)
if index is None and item["owner"] is not None:
# A source that is gone is not listed: name the file
# under it, with no listing index to open it by.
source = judged[item["owner"]]
where = [(os.path.abspath(source), self._public_path(source), None)]
path, label, index = _scan_location(item["image_path"], where)
rows.append(
{
"path": path,
"root": label,
"root_index": index,
"detail": f"Kept: {item['reason']}",
}
)
return rows
if plan.operation == TAG_CLEANUP:
# The findings the review protected, then each target the apply
# kept, every one with its reason (#618).
return [
{"path": "", "detail": f"Kept tag “{item['name']}”: {item['reason']}"}
for item in [*plan.payload.get("held", ()), *result["kept"]]
]
if "kept" not in result:
return None
return [
{
"path": "",
"detail": f"Prompt {item['prompt_id']}: kept, "
+ "; ".join(item["reasons"]),
}
for item in result["kept"]
]
def _maintenance_rows(self, operation, described):
"""Outcome rows for the changed records (root-relative paths only)."""
if operation == "missing_links":
@@ -802,10 +691,6 @@ class MaintenanceRoutesMixin:
}
)
return rows
if operation == "pair_metadata":
return [{"path": "", "detail": _filled_detail(item)} for item in described]
if operation == TAG_CLEANUP:
return [{"path": "", "detail": _deleted_tag_detail(i)} for i in described]
if operation == "duplicate_prompts":
return [
{
@@ -823,36 +708,6 @@ class MaintenanceRoutesMixin:
]
def _deleted_tag_detail(item):
"""``Deleted tag “a, b” (Tags containing a comma) · removed from 3 prompts``."""
from .tag_cleanup import rules
line = f"Deleted tag “{item['name']}” ({rules.rule(item['rule']).title})"
owners = [
f"{item[key]:,} {noun if item[key] == 1 else noun + 's'}"
for key, noun in (("prompts", "prompt"), ("pairs", "pair"), ("images", "image"))
if item.get(key)
]
if not owners:
return line
joined = (
owners[0]
if len(owners) == 1
else (", ".join(owners[:-1]) + " and " + owners[-1])
)
return f"{line} · removed from {joined}"
def _filled_detail(item):
"""``Prompt 12: category “portrait”; tags a, b``: one filled prompt (#550)."""
parts = []
if "category" in item:
parts.append(f"category “{item['category']}”")
if item.get("tags"):
parts.append("tags " + ", ".join(item["tags"]))
return f"Prompt {item['prompt_id']}: " + "; ".join(parts)
def backup_note(backup):
"""The status line's backup part: the file name, or that there is none."""
return f"Safety backup {backup}" if backup else NO_BACKUP
+4 -5
View File
@@ -14,10 +14,10 @@ from .prompts import bad_request
try:
from ...utils.media_capture import CAPTURE_EXTENSIONS
from ...utils.media_folders import in_trash_folder, path_separators
from ...utils.media_folders import in_trash_folder
except ImportError:
from utils.media_capture import CAPTURE_EXTENSIONS
from utils.media_folders import in_trash_folder, path_separators
from utils.media_folders import in_trash_folder
MAX_TARGET_PATH = 1024
TARGET_FIELDS = frozenset({"root_index", "root_scope", "path"})
@@ -30,8 +30,7 @@ def media_target(data: object, *, media_message: str = TAGGING_MEDIA_MESSAGE):
Only the listing identity is accepted: an int root index, the root's
64-hex scope and a bounded root-relative POSIX media path, never an
absolute, drive-qualified, ``..`` path, or (on Windows only, #646) one
holding a backslash (a 400 for a malformed
absolute, drive-qualified, backslash or ``..`` path (a 400 for a malformed
shape, a 403 for an unsafe or non-media path, carrying *media_message*, a
404 for a path in a trash folder, #543). A link or a short-name spelling
is refused later by the capture store's alias check.
@@ -48,7 +47,7 @@ def media_target(data: object, *, media_message: str = TAGGING_MEDIA_MESSAGE):
parts = relative.split("/")
if (
"\0" in relative
or ("\\" in relative and "\\" in path_separators())
or "\\" in relative
or relative.startswith("/")
or _has_traversal(relative)
or any(part in ("", ".", "..") or ":" in part for part in parts)
+3 -98
View File
@@ -29,10 +29,8 @@ import posixpath
import re
import stat as stat_module
import threading
import time
import unicodedata
import uuid
from contextlib import contextmanager
from dataclasses import dataclass, field
try:
@@ -46,11 +44,6 @@ SOURCE_MODE = "source"
FOLDER_MODE = "folder"
MARKER_NAME = ".promptmanager-thumbnails.json"
MARKER_VERSION = 1
# Beside the marker while one process re-reads, changes and replaces it.
MARKER_LOCK_NAME = ".promptmanager-thumbnails.lock"
MARKER_LOCK_TIMEOUT = 1.5 # a writer waits this long (under preview_store.IO_BUDGET)
MARKER_LOCK_STALE = 30.0 # a lock this old was left by a writer that died
MARKER_LOCK_POLL = 0.02
# A source key: one folder name, a slug and a 8-16 hex hash (``source_key``).
KEY_PATTERN = re.compile(r"^[a-z0-9_-]{1,24}-[0-9a-f]{8,16}$")
# A marker is a few keys; anything larger is not ours.
@@ -103,11 +96,6 @@ MESSAGES = {
"This folder contains an image source. Choose a folder beside it instead.",
),
"location-same": (400, "Thumbnails are already stored here."),
"location-inside-current": (
400,
"This folder is inside the thumbnail folder in use. Choose a folder "
"outside it.",
),
"location-parent-missing": (
400,
"The folder that would hold it doesn't exist. Check the path and that its "
@@ -131,11 +119,6 @@ MESSAGES = {
400,
"This path is too long for Windows. Choose a shorter folder path.",
),
"insufficient-space": (
507,
"There is not enough space for the thumbnails. Free some space or choose "
"another folder.",
),
"location-needs-move": (
409,
"Use Move thumbnails in System › Sources & scans.",
@@ -425,80 +408,10 @@ def valid_keys(keys):
return kept
@contextmanager
def _marker_lock(folder):
"""Hold the folder's marker lock: a file made with ``O_CREAT | O_EXCL``
(atomic on local disks and SMB/NFS shares, unlike ``flock``), so installs
sharing the folder change the marker one at a time. A lock older than
MARKER_LOCK_STALE was left by a writer that died and is taken over;
waiting longer than MARKER_LOCK_TIMEOUT raises TimeoutError.
On Windows a lock another writer just unlinked stays delete-pending while
any handle to it is open, and creating it then answers "access denied"
instead of "exists" (#674). That is waited out like a held lock; a folder
that stays denied until the timeout reports its PermissionError."""
lock = os.path.join(folder, MARKER_LOCK_NAME)
deadline = time.monotonic() + MARKER_LOCK_TIMEOUT
while True:
try:
handle = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
except PermissionError:
if time.monotonic() >= deadline:
raise
time.sleep(MARKER_LOCK_POLL)
continue
except FileExistsError:
_break_stale_lock(lock)
if time.monotonic() >= deadline:
raise TimeoutError(
errno.ETIMEDOUT, "the thumbnail folder marker is locked", lock
)
time.sleep(MARKER_LOCK_POLL)
continue
try:
os.write(handle, f"{os.getpid()}\n".encode("ascii"))
finally:
os.close(handle) # closed before any unlink (Windows)
break
try:
yield
finally:
try:
os.unlink(lock)
except FileNotFoundError:
pass # taken over as stale by another writer: nothing to release
def _break_stale_lock(lock):
"""Remove *lock* when it is older than MARKER_LOCK_STALE (its writer
died); a lock that changed since it was looked at is left alone."""
try:
before = os.stat(lock)
except FileNotFoundError:
return
if time.time() - before.st_mtime < MARKER_LOCK_STALE:
return
logger.warning(f"Taking over a stale thumbnail folder lock: {lock}")
try:
after = os.stat(lock)
if (after.st_ino, after.st_mtime_ns) == (before.st_ino, before.st_mtime_ns):
os.unlink(lock)
except FileNotFoundError:
pass # another writer took it over first
def write_marker(folder, mutate):
"""Re-read the marker, apply ``mutate(marker)`` and write it atomically
(a temp sibling renamed over it), all under the folder's marker lock so a
second install sharing the folder never drops this one's change (and
the other way round). Callers hold ``preview_store.write_lock`` (threads
of this process). Returns the marker written; TimeoutError when another
writer holds the lock too long."""
with _marker_lock(folder):
return _write_marker_locked(folder, mutate)
def _write_marker_locked(folder, mutate):
(a temp sibling renamed over it). Callers hold ``preview_store.write_lock``.
Returns the marker written."""
current = read_marker(folder) or {}
marker = {
"version": MARKER_VERSION,
@@ -613,7 +526,7 @@ def _timed(func, timeout):
def run():
try:
result["value"] = func()
except BaseException as error: # _timed() re-raises it in the caller
except BaseException as error: # handed to the caller
result["error"] = error
finally:
done.set()
@@ -707,14 +620,6 @@ def _filesystem_problem(path, purpose, context, default):
)
):
return "location-same"
if (
purpose == "move"
and context.current_path
and _inside(path, [context.current_path])
):
# The old key folders are removed after the move, and with them a
# target nested inside one of them.
return "location-inside-current"
# Windows, or a test injecting its limit (``long_paths=False``).
if os.name == "nt" or context.long_paths is False:
if too_long_for_windows(path, context.long_paths):
+24 -82
View File
@@ -3,7 +3,7 @@
Every mapping between an image source (a "root"), one of its media files and
that file's preview on disk goes through this module. URL text stays in
``thumbnail_settings`` (``thumbnail_rel``: ``thumbnails/<rel>_thumb<ext>``,
the shape the serve route and ``inspection-state.mjs`` share);
the shape the serve route, ``inspection-state.mjs`` and ``admin.js`` share);
this module answers where such a preview is on disk.
The store of a source is where its previews live. With the default location
@@ -69,8 +69,6 @@ _state_lock = threading.Lock()
_parsed = preview_location.ParsedLocation()
_available = True
_problem = None
# The newest check whose answer was published.
_published_order = 0
_keys = {}
_key_cache = {}
_clock = time.monotonic
@@ -169,13 +167,10 @@ def refresh():
if parsed.mode != FOLDER_MODE or parsed.problem is not None:
return parsed.mode == SOURCE_MODE
try:
(available, problem, marker), order = _probe.ordered_check(
parsed.path, parsed.id
)
available, problem, marker = _probe.check(parsed.path, parsed.id)
except (OSError, TimeoutError, RuntimeError):
available, problem, marker = False, "unreachable", None
order = _probe.latest_order()
_set_state(parsed, available, problem, marker, order)
_set_state(parsed, available, problem, marker)
return available
@@ -191,13 +186,6 @@ def _set_keys(parsed, marker):
_key_cache.clear()
def set_cleanup(entries):
"""The setting's ``cleanup`` after a removal was committed."""
global _parsed
with _state_lock:
_parsed = replace(_parsed, cleanup=tuple(entries))
def mark_invalid():
"""The setting cannot be used (a startup check that failed): folder
mode stays in force, unavailable, so nothing is written anywhere."""
@@ -212,16 +200,11 @@ def mark_invalid():
_available, _problem = False, "invalid"
def _set_state(parsed, available, problem, marker, order):
"""Publish a check's answer, unless a check that started later already
published (two callers can finish out of order, #611)."""
global _available, _problem, _published_order
def _set_state(parsed, available, problem, marker):
global _available, _problem
with _state_lock:
if _parsed is not parsed:
return # the setting changed meanwhile
if order < _published_order:
return
_published_order = order
_available, _problem = available, problem
keys = dict((marker or {}).get("keys") or {})
if keys != _keys:
@@ -271,64 +254,34 @@ class _Probe:
self._stop = threading.Event()
self._thread = None
self._checking = None
self._order = 0
def check(self, path, expected_id):
"""``folder_state`` within IO_BUDGET; see :meth:`ordered_check`."""
return self.ordered_check(path, expected_id)[0]
def latest_order(self):
"""The order number of the check started last."""
"""``folder_state`` within IO_BUDGET; raises TimeoutError. A check
already running (the probe's, or a stuck one) is joined, never run
twice at once."""
with self._lock:
return self._order
def ordered_check(self, path, expected_id):
"""``(folder_state, order)`` within IO_BUDGET; raises TimeoutError.
``order`` grows with each check started, so answers can be published
in the order they looked. The answer comes from a check that started
after this call: one already running may have looked before what the
caller just did, so it is waited for (never run twice at once; a stuck
one times out here) and followed by a new one."""
key = (path, expected_id)
with self._lock:
earlier = self._running(key)
pending = None if earlier else self._start_check(path, expected_id)
if earlier:
self._wait(earlier)
with self._lock:
# One another caller started meanwhile is new enough to join.
pending = self._running(key) or self._start_check(path, expected_id)
self._wait(pending)
pending = self._checking
if pending is None or pending[0] != (path, expected_id):
pending = self._start_check(path, expected_id)
key, done, result = pending
if not done.wait(IO_BUDGET):
raise TimeoutError("the thumbnail folder did not answer in time")
with self._lock:
if self._checking is pending:
self._checking = None
if "error" in pending[2]:
raise pending[2]["error"]
return pending[2]["value"], pending[2]["order"]
def _running(self, key):
"""The check of *key* still running (lock held), else None."""
pending = self._checking
if pending is None or pending[0] != key or pending[1].is_set():
return None
return pending
@staticmethod
def _wait(pending):
if not pending[1].wait(IO_BUDGET):
raise TimeoutError("the thumbnail folder did not answer in time")
if "error" in result:
raise result["error"]
return result["value"]
def _start_check(self, path, expected_id):
"""Start one check on its own thread (lock held)."""
self._order += 1
result = {"order": self._order}
result = {}
done = threading.Event()
def run():
try:
result["value"] = preview_location.folder_state(path, expected_id)
except BaseException as error: # check() re-raises it in the caller
except BaseException as error: # handed to the caller
result["error"] = error
finally:
done.set()
@@ -454,9 +407,7 @@ def _key_folder(folder, key):
def ensure_store(root, location=None, *, create=False):
"""``store_dir`` for a writer: in folder mode a source without a key gets
one (recorded in the marker); with *create* its key folder is made (never
the thumbnail folder itself). None while the folder is unavailable, and
for a key folder that is a link, junction or reparse point: nothing is
planned, written or removed through it."""
the thumbnail folder itself). None while the folder is unavailable."""
location = location or current()
store = store_dir(root, location)
if location.mode == SOURCE_MODE or (store is None and not location.available):
@@ -465,20 +416,12 @@ def ensure_store(root, location=None, *, create=False):
store = _assign_key(root, location)
if store is None:
return None
try:
with store_io():
linked = preview_location.is_link_like(store)
except OSError:
return None
if linked:
logger.warning(f"Skipping the thumbnail folder {store}: it is a link")
return None
if create:
try:
with store_io():
os.mkdir(store)
except FileExistsError:
pass # already there: another writer made the key folder
pass
except OSError:
return None
return store
@@ -578,7 +521,7 @@ def make_parent(dst, location=None):
try:
os.mkdir(current_folder)
except FileExistsError:
pass # already there: another writer made this folder
pass
if preview_location.is_link_like(current_folder):
raise PermissionError(errno.EACCES, "a link in the thumbnail folder")
@@ -672,13 +615,12 @@ def owns(root, path, location=None):
def is_preview_text(filepath):
"""URL text naming a preview: ``thumbnails/<...>/<name>_thumb<ext>``.
Text only, before any join: no backslash (on Windows; on POSIX it is part
of a name, #646), drive or stream colon, and no
Text only, before any join: no backslash, drive or stream colon, and no
empty, ``.`` or ``..`` segment; ``thumbnails`` exactly as the first part
and nowhere else among the folders; the extension, in any case, one a
preview may carry (``X_thumb.JPG`` of an older release included).
"""
if not filepath or ":" in filepath or (os.sep == "\\" and "\\" in filepath):
if not filepath or "\\" in filepath or ":" in filepath:
return False
parts = filepath.split("/")
if len(parts) < 2 or parts[0] != PREVIEW_FOLDER:
+39 -85
View File
@@ -64,36 +64,6 @@ def bad_request(message):
return web.json_response({"success": False, "error": message}, status=400)
def legacy_id_error(value, name):
"""A 400 unless *value* is an id as the legacy pages send it (#662).
They send a number or the text they read from the page; SQLite matches
either against an INTEGER column. A boolean, float, list or object is no
id (``True`` would otherwise match prompt 1).
"""
if type(value) is int or isinstance(value, str):
return None
return bad_request(f"{name} must be a prompt id")
def legacy_ids_error(value):
"""A 400 unless *value* is a list of ``legacy_id_error`` ids (#662)."""
if not isinstance(value, list):
return bad_request("prompt_ids must be a list")
for item in value:
error = legacy_id_error(item, "prompt_ids")
if error is not None:
return error
return None
def text_field_error(data, name):
"""A 400 when *name* is present in *data* but is not text (#662)."""
if data.get(name) is not None and not isinstance(data[name], str):
return bad_request(f"{name} must be text")
return None
def tags_error(tags):
"""A 400 response when *tags* fail ``validate_tags``, else None."""
try:
@@ -635,15 +605,18 @@ class PromptRoutesMixin:
{"success": False, "error": "Tag name required"}, status=400
)
body, error = await self._read_json_body(request)
if error is not None:
return error
try:
body = await request.json()
except Exception:
return web.json_response(
{"success": False, "error": "Invalid JSON body"}, status=400
)
raw_name = body.get("new_name")
if not raw_name:
return web.json_response(
{"success": False, "error": "New tag name required"}, status=400
)
error = text_field_error(body, "new_name") or tags_error([raw_name])
error = tags_error([raw_name])
if error is not None:
return error
new_name = raw_name.strip()
@@ -705,9 +678,12 @@ class PromptRoutesMixin:
async def merge_tags_endpoint(self, request):
"""Merge source tags into a target tag."""
try:
body, error = await self._read_json_body(request)
if error is not None:
return error
try:
body = await request.json()
except Exception:
return web.json_response(
{"success": False, "error": "Invalid JSON body"}, status=400
)
source_tags = body.get("source_tags", [])
raw_target = body.get("target_tag")
@@ -721,9 +697,7 @@ class PromptRoutesMixin:
)
if not isinstance(source_tags, list):
return bad_request("Source tags must be a list")
error = text_field_error(body, "target_tag") or tags_error(
[*source_tags, raw_target]
)
error = tags_error([*source_tags, raw_target])
if error is not None:
return error
target_tag = raw_target.strip()
@@ -753,15 +727,7 @@ class PromptRoutesMixin:
async def save_prompt(self, request):
"""Save a new prompt with metadata and duplicate detection."""
try:
data, error = await self._read_json_body(request)
if error is not None:
return error
for field in ("text", "category", "notes"):
if data.get(field) is not None and not isinstance(data[field], str):
return web.json_response(
{"success": False, "error": f"{field} must be text"},
status=400,
)
data = await request.json()
text = (data.get("text") or "").strip()
if not text:
@@ -877,11 +843,7 @@ class PromptRoutesMixin:
"""Update prompt text."""
try:
prompt_id = int(request.match_info["prompt_id"])
data, error = await self._read_json_body(request)
if error is None:
error = text_field_error(data, "text")
if error is not None:
return error
data = await request.json()
new_text = (data.get("text") or "").strip()
if not new_text:
@@ -935,9 +897,7 @@ class PromptRoutesMixin:
"""Update prompt rating."""
try:
prompt_id = int(request.match_info["prompt_id"])
data, error = await self._read_json_body(request)
if error is not None:
return error
data = await request.json()
rating = data.get("rating")
try:
@@ -977,16 +937,14 @@ class PromptRoutesMixin:
"""Add tag to prompt."""
try:
prompt_id = int(request.match_info["prompt_id"])
data, error = await self._read_json_body(request)
if error is not None:
return error
data = await request.json()
raw_tag = data.get("tag")
if not raw_tag:
return web.json_response(
{"success": False, "error": "Tag cannot be empty"}, status=400
)
error = text_field_error(data, "tag") or tags_error([raw_tag])
error = tags_error([raw_tag])
if error is not None:
return error
new_tag = raw_tag.strip()
@@ -1028,9 +986,7 @@ class PromptRoutesMixin:
async def add_tags_to_prompt(self, request):
"""Add multiple tags to a single prompt."""
try:
data, error = await self._read_json_body(request)
if error is not None:
return error
data = await request.json()
prompt_id = data.get("prompt_id")
new_tags = data.get("tags", [])
@@ -1038,9 +994,6 @@ class PromptRoutesMixin:
return web.json_response(
{"success": False, "error": "Prompt ID is required"}, status=400
)
error = legacy_id_error(prompt_id, "prompt_id")
if error is not None:
return error
if not new_tags or not isinstance(new_tags, list):
return web.json_response(
@@ -1102,11 +1055,7 @@ class PromptRoutesMixin:
"""Remove tag from prompt."""
try:
prompt_id = int(request.match_info["prompt_id"])
data, error = await self._read_json_body(request)
if error is None:
error = text_field_error(data, "tag")
if error is not None:
return error
data = await request.json()
tag_to_remove = (data.get("tag") or "").strip()
prompt = await self._run_in_executor(self.db.get_prompt_by_id, prompt_id)
@@ -1146,18 +1095,13 @@ class PromptRoutesMixin:
async def bulk_delete_prompts(self, request):
"""Bulk delete prompts."""
try:
data, error = await self._read_json_body(request)
if error is not None:
return error
data = await request.json()
prompt_ids = data.get("prompt_ids", [])
if not prompt_ids:
return web.json_response(
{"success": False, "error": "No prompt IDs provided"}, status=400
)
error = legacy_ids_error(prompt_ids)
if error is not None:
return error
deleted_count = await self._run_in_executor(
self.db.bulk_delete_prompts, prompt_ids
@@ -1186,9 +1130,12 @@ class PromptRoutesMixin:
async def bulk_add_tags(self, request):
"""Bulk add tags to prompts."""
try:
data, error = await self._read_json_body(request)
if error is not None:
return error
try:
data = await request.json()
except ValueError:
return bad_request("Invalid JSON body")
if not isinstance(data, dict):
return bad_request("Expected a JSON object")
if "expected_epoch" in data:
return await self._bulk_library_tags(data)
prompt_ids = data.get("prompt_ids", [])
@@ -1201,7 +1148,7 @@ class PromptRoutesMixin:
)
if not isinstance(new_tags, list):
return bad_request("Tags must be a list")
error = legacy_ids_error(prompt_ids) or tags_error(new_tags)
error = tags_error(new_tags)
if error is not None:
return error
@@ -1230,9 +1177,16 @@ class PromptRoutesMixin:
async def bulk_set_category(self, request):
"""Bulk set category for prompts."""
try:
data, error = await self._read_json_body(request)
if error is not None:
return error
try:
data = await request.json()
except ValueError:
return web.json_response(
{"success": False, "error": "Invalid JSON body"}, status=400
)
if not isinstance(data, dict):
return web.json_response(
{"success": False, "error": "Expected a JSON object"}, status=400
)
if "images_filter" in data:
return await self._bulk_category_by_filter(data)
if "expected_epoch" in data:
+8 -31
View File
@@ -45,20 +45,16 @@ try:
from ...database.review_decisions import ReviewCommandError
from ...utils.media_capture import CaptureError
from ...utils.review_capture import (
candidate_hashes,
captured_review,
item_profile,
review_evidence,
)
except ImportError:
from database.library import display_title
from database.library_commands import LibraryCommandError
from database.review_decisions import ReviewCommandError
from utils.media_capture import CaptureError
from utils.review_capture import (
candidate_hashes,
captured_review,
item_profile,
)
from utils.review_capture import captured_review, item_profile, review_evidence
ITEMS_URL = "/prompt_manager/review/items"
DEFAULT_LIMIT = 40
@@ -150,9 +146,7 @@ def format_review_target(spelled_path, locator, real_roots, *, pathmod=os.path):
rest = rest[1:]
parts = rest.split(sep)
if any(
part in ("", ".", "..") or "/" in part
# #646: on POSIX a backslash is part of a name.
or (sep == "\\" and "\\" in part) or ":" in part
part in ("", ".", "..") or "/" in part or "\\" in part or ":" in part
for part in parts
):
continue
@@ -277,9 +271,6 @@ class ReviewRoutesMixin:
"root_scope": self._gallery_root_scope(roots[index], index),
"path": relative,
}
if "\\" in relative:
# #646: the mark the Images listing sets (POSIX only).
target["path_style"] = "posix"
# The Images listing's media URL for the same file (formatting only).
url = (
"/prompt_manager/images/serve/"
@@ -397,13 +388,12 @@ class ReviewRoutesMixin:
"library_epoch": item["epoch"],
**view,
"candidates": candidates,
"collapsed": self._review_collapsed(item),
"dependency_fingerprint": fingerprint,
"sha256": item["sha256"],
"total": item["total"],
}
if len(json.dumps(detail).encode("utf-8")) > MAX_DETAIL_BYTES:
detail = {**detail, "candidates": [], "collapsed": None, "limited": True}
detail = {**detail, "candidates": [], "limited": True}
return web.json_response(detail, headers=_NO_STORE)
def _review_detail(self, item_id: str):
@@ -418,20 +408,6 @@ class ReviewRoutesMixin:
fingerprint = self.db.review_dependency_fingerprint(image_path, aliases)
return item, view, fingerprint, self._review_candidates(item)
@staticmethod
def _review_collapsed(item: dict):
"""#657 D3: ``{shown, total, paths}`` when the stored list keeps only
the most used prompts of the file, else None."""
collapsed = None if item["limited"] else item["evidence"].get("collapsed")
if not isinstance(collapsed, dict):
return None
counts = {key: collapsed.get(key) for key in ("shown", "total", "paths")}
if not all(
isinstance(n, int) and not isinstance(n, bool) for n in counts.values()
):
return None
return counts
def _review_candidates(self, item: dict) -> list:
"""The detail's candidates: role texts, a label and selectability."""
if item["limited"]:
@@ -768,6 +744,7 @@ def _candidate_still_offered(resolution: dict, choice: str) -> bool:
resolution = {"state": "ambiguous", "candidates": [resolution]}
if not isinstance(resolution, dict) or resolution.get("state") != "ambiguous":
return False
# Every candidate the bytes offer, before any bound or collapse: a
# reorder that changes the collapsed representatives still applies.
return choice in candidate_hashes(resolution)
evidence, _count, limited = review_evidence(resolution)
if limited:
return False
return any(c.get("hash") == choice for c in evidence.get("candidates", ()))
+57 -533
View File
@@ -6,22 +6,12 @@ final outcome is ambiguous and unlinked. The strict resolver must find it
``graph_prompt_text``) must not link it, and no saved row may link it
already. A file the fallback links, an exact pair the ingester stored and an
already linked file are never queued. Neither is an ambiguous file with
nothing to choose: none of its candidates carries a prompt
nothing to choose: fewer than two of its candidates carry a prompt
(``utils.review_capture.reviewable``); the scan reports it unresolved ("could
not be traced") unless the inspection profile finds a choice in it. A file
the default profile calls unresolved gets the same inspection-profile chance
(#659 C1). ``review_dispatch`` is that one per-file decision.
not be traced") unless the inspection profile finds a choice in it.
The monitor queues what the scan would (maintainer decision 2026-11-19,
#659; it replaces the 2026-10-23 ruling that only scans add items). At a
file's final unlinked outcome, after run history had its say, the monitor
hands the path to ``queue_review_file``. One review worker thread runs
``record_review_file`` for it: the scan's own per-file steps for that file
(the ladder under the scan policy with the sealed history, the recorded-run
check), read only, then ``review_dispatch``. It never links a file, and a
file the scan would link is left to the next scan. The queue coalesces by
path and is bounded; a file deferred by a job blocker is kept and replayed
once no blocker remains.
Only scans add items (maintainer ruling, 2026-10-23). The monitor's pass
records nothing: it only removes the pending items of an output it linked.
The queue heals itself: a pending item whose file is now linked (by the
fallback, a later resolution or the monitor) is removed by the next scan
@@ -35,38 +25,25 @@ changed (``settle_linked_review_items``).
The scan records through ``_record_scanned_review`` (best effort: a failure
is logged and counted), which goes through
``utils.review_capture.record_ambiguous_file`` on the API's capture store;
the review worker calls ``record_review_file``, also for an output the
monitor linked (its pending items leave the queue). Nothing here links a
file.
the monitor calls ``record_review_file`` from its worker thread after its
own link. Nothing here links a file.
Recording changes records, so it follows the registry's ``records``
admission (#289). The scan records under its own ``records`` job. The
monitor's pass lasts one file and is not a job: it is refused while a
``records`` or ``guarded`` job runs (``deferred``); the review worker keeps
the path (at most ``REVIEW_DEFERRED_LIMIT``, in memory) and replays it once
the job registry reports no blocker. Thumbnail work (the job and the
gallery's generate and clear holds, kind ``thumbnails``) is ``guarded`` but
only writes and removes preview files under ``thumbnails/`` and never touches
the database, so it does not defer the recording (#249 S5 M7): a long
rebuild no longer holds Needs review back for its whole run.
``records`` or ``guarded`` job runs (``deferred``), and the next scan reads
the file again. Thumbnail work (the job and the gallery's generate and clear
holds, kind ``thumbnails``) is ``guarded`` but only writes and removes preview
files under ``thumbnails/`` and never touches the database, so it does not
defer the recording (#249 S5 M7): a long rebuild no longer holds Needs review
back for its whole run.
"""
import functools
import hashlib
import json
import os
import threading
from collections import OrderedDict
from pathlib import Path
from .admin import (
SCAN_LOG_PREFIXES,
_BatchHistory,
_file_size,
_plural,
_scan_location,
_scan_roots,
)
from .admin import SCAN_LOG_PREFIXES, _plural, _scan_location, _scan_roots
from .jobs import THUMBNAILS_JOB_KIND
# The kind the monitor's recording checks admission under (never registered).
@@ -79,30 +56,11 @@ NEW_OUTCOMES = ("recorded", "limited")
try:
from ...utils import review_capture
from ...utils.file_prompt import NEVER, Policy, decide_file_prompt
from ...utils.media_capture import CaptureCapacity
from ...utils.parallel import note_refusal, refused_at_shutdown
from ...utils.review_capture import record_ambiguous_file
except ImportError:
from utils import review_capture
from utils.file_prompt import NEVER, Policy, decide_file_prompt
from utils.media_capture import CaptureCapacity
from utils.parallel import note_refusal, refused_at_shutdown
from utils.review_capture import record_ambiguous_file
# The review worker (#659 C5): its thread's name, the bound of paths waiting
# for it (the oldest is dropped beyond it), the bound of paths a job blocker
# deferred, how often it asks the job registry again while paths are
# deferred, and how long the package teardown waits for it.
REVIEW_WORKER_NAME = "pm-review-recorder"
REVIEW_QUEUE_LIMIT = 4096
REVIEW_DEFERRED_LIMIT = 1000
REVIEW_RETRY_SECONDS = 5
REVIEW_STOP_SECONDS = 5
_REVIEW_WORKER_LOCK = threading.Lock()
# Guards the untraced memory, which the scan and the review worker share.
_UNTRACED_MEMORY_LOCK = threading.Lock()
# Untraced files remembered per process so a rescan of an unchanged file does
# not run the inspection profile again (oldest forgotten first). A plain dict
# of 16-byte digests (the locator, and its size, mtime_ns and item version):
@@ -120,15 +78,6 @@ def _memory_key(locator: str) -> bytes:
return _digest(locator)
# Files Inspect found it cannot record (#657 review), per process: a 16-byte
# digest of the locator, its stat and the review versions, oldest forgotten
# first. Inspect then does not run the recording again for that state.
MAX_INSPECT_MEMORY = 4096
# record_review_file outcomes that record nothing for the file's current
# state (an expected outcome, not an error): remembered by Inspect.
UNRECORDABLE_OUTCOMES = ("skipped", "untraced")
# The scan log's reason for items that leave the queue with nothing to choose.
NOTHING_TO_CHOOSE = "nothing to choose"
@@ -141,7 +90,6 @@ class ReviewRecordingMixin:
``scanned`` is the scan's ``(metadata, inspection_resolution)``; the
resolution is None when the scan did not run the inspection profile.
Returns the record outcome, None when recording failed.
"""
try:
outcome = self._record_review_sync(
@@ -154,13 +102,13 @@ class ReviewRecordingMixin:
)
if review is not None:
review["errors"] += 1
return None
if review is not None:
if outcome in NEW_OUTCOMES:
review["added"] += 1
if outcome in QUEUED_OUTCOMES:
review["queued"] += 1
return outcome
return
if review is None:
return
if outcome in NEW_OUTCOMES:
review["added"] += 1
if outcome in QUEUED_OUTCOMES:
review["queued"] += 1
def _record_review_sync(
self, media_file, roots, review=None, inspection=False, scanned=None
@@ -189,55 +137,14 @@ class ReviewRecordingMixin:
self._settle_untraced_reviews([media_file], roots, review)
return outcome
def review_dispatch(self, media_file, roots, decision, outcome, review=None):
"""The one per-file Needs review decision (#659): ``(scan_status,
record_outcome)`` for a file the caller stored nothing for in this
pass.
``decision`` is the scan-policy ladder's ``Decision`` (None: nothing
to decide) and ``outcome`` the file's scan status. An ambiguous file
with a choice is recorded unless a saved row links it
(``unchanged``). An untraced file, or one the default profile calls
unresolved that has a prompt graph, gets the inspection profile's
choice and the saver anchor (``_untraced_scan_outcome``). Any other
file keeps its status and records nothing (``record_outcome`` None).
The scan uses ``scan_status``, the review worker ``record_outcome``.
"""
if decision is None:
return outcome, None
if decision.review == "ambiguous" and outcome == "ambiguous":
if self._review_file_linked(media_file, roots):
return "unchanged", None # already linked: not a review case
# The records name the item versions that count; the saver
# anchor (#390) is checked on the captured bytes.
scanned = (decision.canonical, None)
recorded = self._record_scanned_review(
media_file, roots, review, scanned=scanned
)
return outcome, recorded
untraced = decision.review == "untraced"
unreadable = (
decision.review is None
and decision.default_unresolved
and bool(decision.canonical.get("prompt"))
)
if outcome == "unresolved" and (untraced or unreadable):
# The inspection profile may still offer a choice (queued for
# review, never linked).
return self._untraced_scan_outcome(
media_file, roots, decision.canonical, review
)
return outcome, None
def _untraced_scan_outcome(self, media_file, roots, canonical, review=None):
"""``(scan_status, record_outcome)`` of an unlinked file the default
profile left ambiguous without a choice, or unresolved (blocking).
"""The scan status of an unlinked file the default profile left
ambiguous without a choice (blocking).
``ambiguous`` when the inspection profile offers a choice: the file is
recorded for review from that profile (never linked), or ``unchanged``
when a saved row links it already. Otherwise ``unresolved``
(``untraced``), and its pending items without a choice leave the
queue. The profile runs at
when a saved row links it already. Otherwise ``unresolved``, and its
pending items without a choice leave the queue. The profile runs at
most once per file state: not for bytes already queued (or decided)
at the file's current size and ``mtime_ns`` under the version that
its records depend on, and not again for a state it already found
@@ -253,17 +160,15 @@ class ReviewRecordingMixin:
)
if review is not None:
review["errors"] += 1
return "unresolved", None
return "unresolved"
if choice is None:
self._settle_untraced_reviews([media_file], roots, review)
self._settle_stale_reviews(media_file, roots, canonical, review)
return "unresolved", "untraced"
return "unresolved"
if self._review_file_linked(media_file, roots):
return "unchanged", None
recorded = self._record_scanned_review(
media_file, roots, review, scanned=choice
)
return "ambiguous", recorded
return "unchanged"
self._record_scanned_review(media_file, roots, review, scanned=choice)
return "ambiguous"
def _inspection_choice(self, media_file, roots, canonical):
"""``(canonical, resolution_or_None)`` when the file offers a choice.
@@ -293,21 +198,17 @@ class ReviewRecordingMixin:
return canonical, None
memory = self._untraced_memory()
key = _memory_key(locator)
# The scan and the review worker (#659) share the memory: every
# read and change holds its lock (the resolve below does not).
with _UNTRACED_MEMORY_LOCK:
if state is not None and memory.get(key) == state:
return None
if state is not None and memory.get(key) == state:
return None
resolution = review_capture.inspection_choice(canonical, media_file.name)
with _UNTRACED_MEMORY_LOCK:
if resolution is not None:
memory.pop(key, None)
return canonical, resolution
if state is not None:
memory.pop(key, None) # re-inserted last: the newest state
memory[key] = state
while len(memory) > MAX_UNTRACED_MEMORY:
del memory[next(iter(memory))]
if resolution is not None:
memory.pop(key, None)
return canonical, resolution
if state is not None:
memory.pop(key, None) # re-inserted last: the newest state
memory[key] = state
while len(memory) > MAX_UNTRACED_MEMORY:
del memory[next(iter(memory))]
return None
def _settle_stale_reviews(self, media_file, roots, canonical, review=None):
@@ -347,11 +248,10 @@ class ReviewRecordingMixin:
return removed
def _untraced_memory(self):
with _UNTRACED_MEMORY_LOCK:
memory = getattr(self, "_untraced_inspections", None)
if memory is None:
memory = self._untraced_inspections = {}
return memory
memory = getattr(self, "_untraced_inspections", None)
if memory is None:
memory = self._untraced_inspections = {}
return memory
@staticmethod
def _review_location(media_file, roots, real_roots=None):
@@ -410,8 +310,8 @@ class ReviewRecordingMixin:
def _settle_untraced_reviews(self, media_files, roots, review=None):
"""Remove the pending items without a choice of untraced ``media_files``.
``media_files`` are files found ambiguous without a candidate that
carries a prompt. Blocking; best effort like the linked
``media_files`` are files found ambiguous with fewer than two
candidates that carry a prompt. Blocking; best effort like the linked
settle (a failure is logged and counted in ``review["errors"]``).
Returns how many items left.
"""
@@ -435,23 +335,18 @@ class ReviewRecordingMixin:
return removed
def record_review_file(self, image_path):
"""Apply the Needs review rule to one monitor output (review worker).
"""Apply the Needs review rule to one monitor output (its worker thread).
The monitor queues what the scan would (maintainer decision
2026-11-19, #659): it hands a file over at its final unlinked
outcome, after run history had its say, and after each ambiguous
output it links. Maps ``image_path`` to the gallery root that lists
it; a file under no current root is ``skipped``. A linked file's
pending items are removed and the answer is ``linked``. Any other
file runs the scan's own per-file steps, read only
(``_review_unlinked_file``): a file the scan would link, or that
does not save, is ``skipped`` (the next scan links it); otherwise
the answer is ``review_dispatch``'s record outcome (``recorded``,
``duplicate``, ``decided``, ``untraced``, ``limited``) or ``skipped``.
While a job runs that a ``records`` job may not run beside, other
than thumbnail work (``PREVIEW_ONLY_KINDS``), nothing is written and
the answer is ``deferred`` (the worker replays it). Errors propagate:
the worker logs them and the monitor keeps its link.
Only scans add items (maintainer ruling, 2026-10-23): the monitor
only clears the items of outputs it links. Maps ``image_path`` to the
gallery root that lists it; a file under no current root is
``skipped``. A linked file's pending items are removed and the answer
is ``linked``. Any other file is ``skipped``: nothing is captured or
recorded, and the next scan reads it. While a job runs that a
``records`` job may not run beside, other than thumbnail work
(``PREVIEW_ONLY_KINDS``), nothing is written and the answer is
``deferred``. Errors propagate: the monitor logs them and keeps its
link.
"""
busy = self._jobs.blocker(
REVIEW_RECORDING_KIND, admission="records", compatible=PREVIEW_ONLY_KINDS
@@ -471,166 +366,7 @@ class ReviewRecordingMixin:
if self._review_file_linked(located, roots):
self._settle_scanned_reviews([located], roots)
return "linked"
return self._review_unlinked_file(located, roots)
def _review_unlinked_file(self, media_file, roots):
"""The scan's per-file steps for one unlinked file, read only.
The metadata read the scan uses, the ladder under ``Policy.SCAN``
with the file's recorded history, then the recorded-run check; a
file any step would link (or whose prompt does not save) is
``skipped``. Otherwise ``review_dispatch`` decides, and its record
outcome is the answer (``skipped`` when it records nothing).
"""
path = str(media_file)
metadata = self._extract_comfyui_metadata(path)
history = _BatchHistory(self, [media_file])
decision = decide_file_prompt(
metadata,
file_name=media_file.name,
file_size=functools.partial(_file_size, media_file),
in_output=False, # only the monitor policy reads it
lookup=functools.partial(history.recorded, path),
policy=Policy.SCAN,
)
if decision.kind != NEVER:
return "skipped" # it saves nothing, or the next scan links it
if decision.try_recorded_run and history.get(path) is not None:
return "skipped" # the scan's recorded-run step links it
_status, recorded = self.review_dispatch(
media_file, roots, decision, decision.unlinked_status
)
return recorded or "skipped"
def inspect_review_file(self, image_path, found=None):
"""Inspect's recording of one file (#657 addendum D2, blocking).
``found`` is the file's ``review`` facet at the inspected stat (None
or a pending item). A pending item of a current item version needs
nothing (``current``); one of an older version is recorded again, so
the new item supersedes it. Otherwise ``record_review_file`` runs,
unless Inspect already found this state unrecordable (``skipped`` or
``untraced``, remembered in ``MAX_INSPECT_MEMORY`` digests:
``remembered``). A busy capture store (the worker copying a fresh
output) is expected: logged at debug level, ``busy``.
"""
if found is not None and self._review_item_current(
found["item_id"], image_path
):
return "current"
key = self._inspect_memory_key(image_path)
memory = self._inspect_memory()
with _UNTRACED_MEMORY_LOCK:
if key is not None and key in memory:
return "remembered"
try:
outcome = self.record_review_file(image_path)
except CaptureCapacity:
self.logger.debug(
"Inspect left Needs review to the worker: captures are busy"
)
return "busy"
if key is not None and outcome in UNRECORDABLE_OUTCOMES:
with _UNTRACED_MEMORY_LOCK:
memory.pop(key, None)
memory[key] = True
while len(memory) > MAX_INSPECT_MEMORY:
del memory[next(iter(memory))]
return outcome
def _inspected_metadata(self, image_path):
"""The file's metadata with its prompt graph decoded (or None)."""
metadata = self._extract_comfyui_metadata(str(image_path)) or {}
prompt = metadata.get("prompt")
if isinstance(prompt, str):
try:
metadata = {**metadata, "prompt": json.loads(prompt)}
except (ValueError, TypeError, RecursionError):
return None
return metadata if isinstance(metadata.get("prompt"), dict) else None
def _review_item_current(self, item_id, image_path):
"""True when the item's version is one the file is queued under now
(the file's metadata is read only for a non-default version)."""
item = self.db.review_item(item_id)
if item is None:
return False
version = item.get("resolver_version")
if version == review_capture.default_item_version():
return True
metadata = self._inspected_metadata(image_path)
return metadata is not None and version in review_capture.item_versions(
metadata
)
def _inspect_memory_key(self, image_path):
"""The digest of the file's locator, stat and review versions."""
full = os.path.abspath(str(image_path))
located = os.path.join(
os.path.realpath(os.path.dirname(full)), os.path.basename(full)
)
try:
facts = os.lstat(located)
except OSError:
return None
return _digest(
f"{os.path.normcase(located)}:{facts.st_size}:{facts.st_mtime_ns}:"
f"{review_capture.default_item_version()}:"
f"{review_capture.semantics_version()}"
)
def _inspect_memory(self):
with _UNTRACED_MEMORY_LOCK:
memory = getattr(self, "_inspect_unrecordable", None)
if memory is None:
memory = self._inspect_unrecordable = {}
return memory
def _review_worker(self):
"""The API's one review worker, made on first use (no thread yet)."""
worker = getattr(self, "_review_recorder_worker", None)
if worker is None:
with _REVIEW_WORKER_LOCK:
worker = getattr(self, "_review_recorder_worker", None)
if worker is None:
worker = ReviewWorker(
# Late-bound on purpose: a record_review_file
# replaced after the worker exists still runs.
lambda path: self.record_review_file(path),
self._review_admitted,
self.logger,
)
self._review_recorder_worker = worker
return worker
def _review_admitted(self):
"""True while no job blocks Needs review writes (any thread)."""
busy = self._jobs.blocker(
REVIEW_RECORDING_KIND, admission="records", compatible=PREVIEW_ONLY_KINDS
)
return busy is None
def queue_review_file(self, image_path):
"""Queue ``image_path`` for the review worker; never blocks.
The monitor's review recorder (#659). Returns ``queued``, or
``stopped`` once the worker was stopped (the next scan reads it).
"""
return self._review_worker().queue(str(image_path))
def review_worker_started(self):
"""Whether the review worker's thread was ever started."""
worker = getattr(self, "_review_recorder_worker", None)
return worker is not None and worker.started
def stop_review_worker(self, timeout=REVIEW_STOP_SECONDS):
"""Stop the review worker for good and join it within ``timeout``.
Queued and deferred paths are dropped (their count is logged; the
next scan covers them) and later ``queue_review_file`` calls are
refused. True when no worker thread is left running.
"""
return self._review_worker().stop(timeout)
return "skipped"
@staticmethod
def _log_review_items(job, review):
@@ -662,215 +398,3 @@ class ReviewRecordingMixin:
f"{_plural(review['errors'], 'image')} could not be added to "
"Needs review"
)
class ReviewWorker:
"""One daemon thread that runs ``record(path)`` for queued paths (#659 C5).
The queue coalesces by path (a path queued again while it waits keeps
its place; one queued while it runs runs once more afterwards) and holds
at most ``REVIEW_QUEUE_LIMIT`` paths, dropping the oldest with a log
line, so ``queue`` never blocks the monitor's image worker. One thread
means two recordings of one path never run at once. A ``deferred``
answer keeps the path in a bounded, insertion-ordered set; the thread
waits on its queue with a ``REVIEW_RETRY_SECONDS`` timeout and, on each
wake, replays that set once ``admitted()`` (no job blocker) says so.
Everything lives in memory: a restart drops it and the next scan covers
the files. A failure of ``record`` is logged and the worker goes on.
"""
def __init__(self, record, admitted, logger):
self._record = record
self._admitted = admitted
self._logger = logger
self._changed = threading.Condition()
self._pending = OrderedDict() # key -> path
self._deferred = OrderedDict() # key -> path
self._in_hand = None
self._thread = None
self._ever_started = False
self._stopped = False
@property
def started(self):
return self._ever_started
@staticmethod
def _key(path):
return os.path.normcase(os.path.abspath(path))
def queue(self, path):
"""Queue ``path``: ``queued``, or ``stopped`` after ``stop``."""
key = self._key(path)
with self._changed:
if self._stopped:
return "stopped"
if key in self._pending:
return "queued"
self._pending[key] = path
evicted = None
if len(self._pending) > REVIEW_QUEUE_LIMIT:
evicted = self._pending.popitem(last=False)[1]
if self._thread is None and not self._start():
self._pending.pop(key, None)
return "stopped"
self._changed.notify_all()
if evicted is not None:
self._logger.info(
"Too many outputs wait for Needs review; "
f"{os.path.basename(evicted)} is left to the next scan"
)
return "queued"
def _start(self):
"""Start the thread (``_changed`` held); False when refused at exit."""
thread = threading.Thread(
target=self._run, name=REVIEW_WORKER_NAME, daemon=True
)
try:
thread.start()
except RuntimeError as error:
if not refused_at_shutdown(error):
raise
note_refusal(self._logger, "The review worker")
self._stopped = True
return False
self._thread = thread
self._ever_started = True
return True
def pending_count(self):
with self._changed:
return len(self._pending)
def deferred_count(self):
with self._changed:
return len(self._deferred)
def deferred_paths(self):
with self._changed:
return list(self._deferred.values())
def wait_idle(self, timeout):
"""True once no path waits or is in hand (deferred ones may stay)."""
with self._changed:
return self._changed.wait_for(
lambda: not self._pending and self._in_hand is None, timeout
)
def _run(self):
"""The thread body: an unexpected error ends it with a log line and
clears the handle, so the next queued output starts a new thread
(the paths still waiting stay queued)."""
try:
self._loop()
except Exception:
self._logger.error(
"The review worker stopped on an unexpected error; "
"the next output starts it again",
exc_info=True,
)
finally:
with self._changed:
if self._thread is threading.current_thread():
self._thread = None
self._in_hand = None
self._changed.notify_all()
def _loop(self):
while True:
with self._changed:
path = self._next_locked()
if path is None:
return
self._in_hand = path
outcome = None
try:
outcome = self._run_one(path)
finally:
with self._changed:
self._in_hand = None
if outcome == "deferred":
dropped = self._defer_locked(path)
else:
dropped = None
self._changed.notify_all()
if dropped is not None:
self._logger.info(
"Too many outputs wait for a job to end before Needs review; "
f"{os.path.basename(dropped)} is left to the next scan"
)
def _next_locked(self):
"""The next path to record, waiting for one; None once stopped."""
while not self._stopped:
if self._deferred and self._replay_admitted():
for key, path in self._deferred.items():
self._pending.setdefault(key, path)
self._deferred.clear()
if self._pending:
return self._pending.popitem(last=False)[1]
self._changed.notify_all() # idle: ``wait_idle`` may return
# Deferred paths: ask the job registry again after a while
self._changed.wait(REVIEW_RETRY_SECONDS if self._deferred else None)
return None
def _replay_admitted(self):
try:
return bool(self._admitted())
except Exception:
self._logger.debug("Job registry check failed", exc_info=True)
return False
def _run_one(self, path):
try:
outcome = self._record(path)
except Exception:
self._logger.warning(
f"{os.path.basename(path)} could not be added to Needs review",
exc_info=True,
)
return None
self._logger.debug(f"Needs review {outcome}: {os.path.basename(path)}")
return outcome
def _defer_locked(self, path):
"""Keep a deferred path; returns the path dropped at the cap."""
if self._stopped:
return None
key = self._key(path)
self._deferred.pop(key, None)
self._deferred[key] = path
if len(self._deferred) > REVIEW_DEFERRED_LIMIT:
return self._deferred.popitem(last=False)[1]
return None
def stop(self, timeout):
"""Stop for good, drop waiting paths, join within ``timeout``.
True when no thread is left running. Called on the worker's own
thread, it only signals (False).
"""
with self._changed:
self._stopped = True
dropped = len(self._pending) + len(self._deferred)
self._pending.clear()
self._deferred.clear()
thread = self._thread
self._changed.notify_all()
if dropped:
self._logger.info(
f"{_plural(dropped, 'output')} left for the next scan's Needs review"
)
if thread is None:
return True
if thread is threading.current_thread():
return False
thread.join(max(0.0, timeout))
if thread.is_alive():
self._logger.warning(
f"review worker still running after {timeout} s; "
"it stops after the file in hand"
)
return False
return True
+14 -116
View File
@@ -55,25 +55,9 @@ _SETTINGS_FILE_KEYS = {
"AUTOTAG_EXISTING": ("autotag", "defaults", "existing"),
"AUTOTAG_GENERAL_THRESHOLD": ("autotag", "defaults", "general_threshold"),
"AUTOTAG_CHARACTER_THRESHOLD": ("autotag", "defaults", "character_threshold"),
"AUTOTAG_TEMPLATE": ("autotag", "defaults", "template"),
"AUTOTAG_SUGGESTION_LIMIT": ("autotag", "defaults", "suggestion_limit"),
"AUTOTAG_SKIPPED_TAGS": ("autotag", "defaults", "skipped_tags"),
# #431: the saved instructions and each engine's default, always written
# together (server-side pairing).
"AUTOTAG_INSTRUCTIONS": ("autotag", "defaults", "instructions"),
"AUTOTAG_DEFAULT_INSTRUCTIONS": ("autotag", "defaults", "default_instructions"),
}
# The old single template: written only as the GGUF default's mirror for a
# downgrade (#431 B1.1), deleted when that default is Built-in.
_TEMPLATE_MIRROR_KEY = ("autotag", "defaults", "template")
TEMPLATE_REPLACED_ERROR = (
"LLM tag template was replaced by Saved instructions. Reload the page."
)
# Whole-list settings (#431): a save without ``expected_revision`` would merge
# a stale copy over a list changed elsewhere, so it is refused.
_REVISION_REQUIRED = frozenset(
{"autotag_skipped_tags", "autotag_instructions", "autotag_default_instructions"}
)
REVISION_REQUIRED_ERROR = "Reload the page and try again."
# The thumbnail settings a running Convert outdated job fixes (#317).
_THUMBNAIL_SETTINGS = ("THUMBNAIL_FORMAT", "THUMBNAIL_QUALITY", "THUMBNAIL_EDGE")
# Attributes that live on GalleryConfig; the others on PromptManagerConfig.
@@ -154,20 +138,13 @@ def _settings_mutation(updates, new_roots):
"""The config commit for a settings save: only the submitted keys change.
Every other section and key (integrations and the CivitAI key, database,
unknown sections) is kept as it is on disk. A save of the instructions
also writes the old ``template`` key as the GGUF default's mirror.
unknown sections) is kept as it is on disk.
"""
def mutate(config):
for name, value in updates.items():
*sections, key = _SETTINGS_FILE_KEYS[name]
_set_nested(config, sections, key, _jsonable(value))
if "AUTOTAG_INSTRUCTIONS" in updates:
*sections, key = _TEMPLATE_MIRROR_KEY
mirror = _mirror_text(
updates["AUTOTAG_INSTRUCTIONS"], updates["AUTOTAG_DEFAULT_INSTRUCTIONS"]
)
_set_nested(config, sections, key, _DELETE if mirror is None else mirror)
_set_nested(config, sections, key, value)
if new_roots is not None:
gallery = _section(config, "gallery")
monitoring = _section(gallery, "monitoring")
@@ -179,37 +156,10 @@ def _settings_mutation(updates, new_roots):
return mutate
# ``_set_nested``'s value that removes the key instead of setting it.
_DELETE = object()
def _jsonable(value):
"""A runtime value as config.json holds it (tuples become lists)."""
if isinstance(value, (list, tuple)):
return [_jsonable(item) for item in value]
if isinstance(value, dict):
return {key: _jsonable(item) for key, item in value.items()}
return value
def _mirror_text(entries, defaults):
"""The GGUF default's text, or None when it is Built-in (#431 B1.1)."""
from ..tagging_defaults import BUILTIN_INSTRUCTIONS_ID
for item in entries:
if item["id"] == defaults["gguf"] != BUILTIN_INSTRUCTIONS_ID:
return item["text"]
return None
def _set_nested(config, sections, key, value):
"""``config[s1][s2]...[key] = value``, each section a fresh dict;
``_DELETE`` removes the key."""
"""``config[s1][s2]...[key] = value``, each section a fresh dict."""
if not sections:
if value is _DELETE:
config.pop(key, None)
else:
config[key] = value
config[key] = value
return
merged = _section(config, sections[0])
_set_nested(merged, sections[1:], key, value)
@@ -227,7 +177,7 @@ def _validate_autotag_settings(data):
MAX_SUGGESTION_LIMIT,
MODEL_TYPES,
validate_saved_threshold,
validate_skipped_tags,
validate_template,
)
updates = {}
@@ -256,7 +206,12 @@ def _validate_autotag_settings(data):
raise ValueError(f"{error}.") from None
updates[key.upper()] = value
if "autotag_template" in data:
raise ValueError(TEMPLATE_REPLACED_ERROR)
try:
updates["AUTOTAG_TEMPLATE"] = validate_template(
data["autotag_template"], "LLM tag template"
)
except ValueError as error:
raise ValueError(f"{error}.") from None
if "autotag_suggestion_limit" in data:
value = data["autotag_suggestion_limit"]
if type(value) is not int or not 1 <= value <= MAX_SUGGESTION_LIMIT:
@@ -265,41 +220,9 @@ def _validate_autotag_settings(data):
f"{MAX_SUGGESTION_LIMIT}."
)
updates["AUTOTAG_SUGGESTION_LIMIT"] = value
if "autotag_skipped_tags" in data:
updates["AUTOTAG_SKIPPED_TAGS"] = tuple(
validate_skipped_tags(data["autotag_skipped_tags"])
)
updates.update(_validate_instruction_settings(data))
return updates
def _validate_instruction_settings(data):
"""Server-side pairing (#431): a save that carries either instruction key
gets the other from the running configuration (which holds the migrated
list), the defaults are checked against the merged list, and both are
written. Empty when the save carries neither."""
from ..config import AutotagConfig
from ..tagging_defaults import (
validate_default_instructions,
validate_instructions,
)
if not {"autotag_instructions", "autotag_default_instructions"} & set(data):
return {}
if "autotag_instructions" in data:
entries = validate_instructions(data["autotag_instructions"])
else:
entries = [dict(item) for item in AutotagConfig.INSTRUCTIONS]
defaults = data.get(
"autotag_default_instructions", dict(AutotagConfig.DEFAULT_INSTRUCTIONS)
)
defaults = validate_default_instructions(defaults, entries)
return {
"AUTOTAG_INSTRUCTIONS": tuple(entries),
"AUTOTAG_DEFAULT_INSTRUCTIONS": defaults,
}
async def _read_json(request):
"""Parse a JSON object body through the package's capped reader."""
from . import _read_json_body
@@ -327,7 +250,6 @@ class SettingsRoutesMixin:
"""Get current settings."""
try:
from ..config import AutotagConfig, PromptManagerConfig, GalleryConfig
from ..tagging_defaults import DEFAULT_TAG_TEMPLATE
root_paths = [
self._public_path(d) for d in GalleryConfig.MONITORING_DIRECTORIES
@@ -366,21 +288,8 @@ class SettingsRoutesMixin:
"autotag_character_threshold": (
AutotagConfig.CHARACTER_THRESHOLD
),
# Read-only for one release (#431): a page cached
# from before the upgrade still renders.
"autotag_template": AutotagConfig.default_instructions_text(
"gguf"
),
"autotag_instructions": [
dict(item) for item in AutotagConfig.INSTRUCTIONS
],
"autotag_default_instructions": dict(
AutotagConfig.DEFAULT_INSTRUCTIONS
),
# Built-in's text, which System shows read-only.
"autotag_builtin_instructions": DEFAULT_TAG_TEMPLATE,
"autotag_template": AutotagConfig.TEMPLATE,
"autotag_suggestion_limit": AutotagConfig.SUGGESTION_LIMIT,
"autotag_skipped_tags": list(AutotagConfig.SKIPPED_TAGS),
"cpu_count": PromptManagerConfig.max_worker_threads(),
"gallery_root_paths": root_paths,
"gallery_root_path": root_paths[0] if root_paths else "",
@@ -484,10 +393,6 @@ class SettingsRoutesMixin:
{"success": False, "error": "expected_revision must be a string"},
status=400,
)
if expected_revision is None and _REVISION_REQUIRED & set(data):
return web.json_response(
{"success": False, "error": REVISION_REQUIRED_ERROR}, status=400
)
try:
updates = self._validate_settings(data)
except ValueError as ve:
@@ -586,8 +491,7 @@ class SettingsRoutesMixin:
for key in _THUMBNAIL_SETTINGS
)
job = self._jobs.active(THUMBNAILS_JOB_KIND) if changed else None
# A move copies previews of the current settings (#320).
if job is None or job.scope.get("mode") not in ("convert", "move"):
if job is None or job.scope.get("mode") != "convert":
return None
return web.json_response(
{
@@ -617,12 +521,6 @@ class SettingsRoutesMixin:
if name in _AUTOTAG_SETTINGS:
setattr(AutotagConfig, name[len(_AUTOTAG_PREFIX) :], value)
continue
if "AUTOTAG_INSTRUCTIONS" in updates:
# What config.json now holds as the old key (the mirror).
AutotagConfig._LEGACY_TEMPLATE = AutotagConfig.mirror_template()
for name, value in updates.items():
if name in _AUTOTAG_SETTINGS:
continue
owner = GalleryConfig if name in _GALLERY_SETTINGS else PromptManagerConfig
setattr(owner, name, value)
restart_fields = []
-245
View File
@@ -1,245 +0,0 @@
"""Tag cleanup as a find job, its findings and a reviewed plan (#618).
- ``POST /prompt_manager/jobs/tag_cleanup`` (body ignored) starts the find
(202 ``{job}``): kind ``tag_cleanup``, "Find tags to clean up", admission
``read``, not cancellable (one snapshot read), outcome group ``found``. It
runs every rule of ``database/tag_cleanup.py`` on one read-only snapshot,
holds the result under the job id (the last ``MAX_HELD_FINDS``), records one
``found`` row per tag and writes nothing. 409 ``busy`` while a find or an
exclusive job runs.
- ``GET /prompt_manager/maintenance/tag_cleanup/{job_id}`` answers every held
finding at once: ``{success, job:{id, state}, rules:[{id, title,
explanation, action_label, total, findings:[{tag_id, name, detail}]}]}``,
at most ``MAX_FINDINGS`` per rule (``total`` is exact). 404 ``not-found``,
409 ``job-running``, 409 ``no-groups`` (the find failed).
- ``POST /prompt_manager/maintenance/preview {operation:"tag_cleanup",
options:{job_id, select:[{rule, tag_ids}]}}`` reviews the ticked findings
(``preview_tag_cleanup``): each selected tag must be a held finding of that
rule. The plan always takes a safety backup first (policy ``required``,
maintainer ruling 2026-11-22) and its apply, the ``maintenance`` job "Tag
cleanup", rechecks each tag and keeps, with its reason, each one that
changed (``py/api/maintenance.py``).
"""
from aiohttp import web
from .job_routes import busy_response
from .jobs import TAG_CLEANUP_GROUP_NAMES, TAG_CLEANUP_JOB_KIND, JobBusy
from .maintenance import _failure, _invalid
try:
from ...database import tag_cleanup as rules
except ImportError:
from database import tag_cleanup as rules
TAG_CLEANUP = rules.OPERATION
FIND_TITLE = "Find tags to clean up"
FIND_FAILED = "The tag search failed."
MAX_HELD_FINDS = 3 # finds whose findings the server keeps for review
MAX_JOB_ID = 64
def _parse_select(entry, seen):
"""``(rule_id, tag_ids, None)`` for one select entry, else a message."""
if not isinstance(entry, dict) or set(entry) != {"rule", "tag_ids"}:
return None, None, "Each select entry is {rule, tag_ids}"
rule_id, tag_ids = entry["rule"], entry["tag_ids"]
if not isinstance(rule_id, str) or rule_id not in rules.RULE_IDS:
return None, None, "rule must be one of: " + ", ".join(rules.RULE_IDS)
if rule_id in seen:
return None, None, "Each rule is selected once"
limit = rules.MAX_FINDINGS
if not isinstance(tag_ids, list) or not 0 < len(tag_ids) <= limit:
return None, None, f"tag_ids must list 1 to {limit:,} tags"
for tag_id in tag_ids:
if type(tag_id) is not int or tag_id < 1:
return None, None, "tag_ids must be tag ids"
if len(set(tag_ids)) != len(tag_ids):
return None, None, "tag_ids must not repeat a tag"
return rule_id, tag_ids, None
def parse_options(options):
"""``(job_id, {rule_id: [tag_id]}, None)`` or ``(None, None, message)``."""
if not isinstance(options, dict) or set(options) != {"job_id", "select"}:
return None, None, "tag_cleanup takes options {job_id, select}"
job_id, select = options["job_id"], options["select"]
if not isinstance(job_id, str) or not 0 < len(job_id) <= MAX_JOB_ID:
return None, None, "job_id must be a tag search's job id"
if not isinstance(select, list) or not 0 < len(select) <= len(rules.RULES):
return None, None, f"select must list 1 to {len(rules.RULES)} rules"
chosen = {}
for entry in select:
rule_id, tag_ids, message = _parse_select(entry, chosen)
if message:
return None, None, message
chosen[rule_id] = tag_ids
return job_id, chosen, None
def _found_rows(result):
return [
{"path": "", "detail": f"{f['name']} · {rules.rule(rule_id).title}"}
for rule_id in rules.RULE_IDS
for f in result["rules"][rule_id]
]
def _public_rules(result):
return [
{
"id": item.id,
"title": item.title,
"explanation": item.explanation,
"action_label": item.action_label,
"total": result["totals"][item.id],
"findings": [
{
"tag_id": f["tag_id"],
"name": f["name"],
"detail": rules.finding_detail(f),
}
for f in result["rules"][item.id]
],
}
for item in rules.RULES
]
class TagCleanupMixin:
"""Mixin providing the tag cleanup find, its findings and its plan."""
def _register_tag_cleanup_routes(self, routes):
@routes.post("/prompt_manager/jobs/tag_cleanup")
async def start_tag_cleanup_find_route(request):
return await self.start_tag_cleanup_find(request)
@routes.get("/prompt_manager/maintenance/tag_cleanup/{job_id}")
async def tag_cleanup_findings_route(request):
return await self.tag_cleanup_findings(request)
# ── find ──────────────────────────────────────────────────────────
async def start_tag_cleanup_find(self, request):
"""Start the tag search (202), or 409 naming the job in the way."""
db = self.db
try:
job = self._jobs.start(
TAG_CLEANUP_JOB_KIND,
FIND_TITLE,
admission="read",
cancellable=False,
groups=TAG_CLEANUP_GROUP_NAMES,
runner=lambda job: self._run_tag_cleanup_find(job, db),
)
except JobBusy as busy:
return busy_response(busy)
self._remember_tag_cleanup_find(job.id)
return web.json_response({"success": True, "job": job.summary()}, status=202)
def _remember_tag_cleanup_find(self, job_id):
"""Hold a slot for ``job_id`` (None until it found); keep the last few."""
finds = self._tag_cleanup_finds
finds[job_id] = None
for held in list(finds):
if self._jobs.get(held) is None:
del finds[held]
while len(finds) > MAX_HELD_FINDS:
del finds[next(iter(finds))]
async def _run_tag_cleanup_find(self, job, db):
job.update(status_line="Looking for tags to clean up")
try:
result = await self._run_in_executor(
rules.find_tag_cleanup, db.model.db_path
)
except Exception:
self.logger.exception("Tag search failed")
job.update(status_line=FIND_FAILED)
job.log_line(FIND_FAILED)
job.finish("failed")
return
if job.id in self._tag_cleanup_finds:
self._tag_cleanup_finds[job.id] = result
count = sum(result["totals"].values())
job.record_counted("found", count, _found_rows(result))
line = (
f"Found {count:,} {'tag' if count == 1 else 'tags'} to clean up"
if count
else "No tags need cleaning up"
)
job.log_line(line)
job.update(progress=100, status_line=line)
# ── findings ──────────────────────────────────────────────────────
def _held_tag_cleanup(self, job_id):
"""``(result, None)`` for a finished search's findings, else a reply."""
job = self._jobs.get(job_id)
finds = self._tag_cleanup_finds
if job_id not in finds or job is None or job.kind != TAG_CLEANUP_JOB_KIND:
return None, _failure(
"No tag search with this id. Search again.", 404, "not-found"
)
if job.running:
return None, _failure(
"The tag search is still running.", 409, "job-running"
)
if finds[job_id] is None:
return None, _failure(
"This search did not finish. Search again.", 409, "no-groups"
)
return finds[job_id], None
async def tag_cleanup_findings(self, request):
job_id = request.match_info["job_id"]
result, error = self._held_tag_cleanup(job_id)
if error is not None:
return error
job = self._jobs.get(job_id)
return web.json_response(
{
"success": True,
"job": {"id": job.id, "state": job.state},
"rules": _public_rules(result),
},
headers={"Cache-Control": "no-store"},
)
# ── review ────────────────────────────────────────────────────────
async def preview_tag_cleanup(self, options):
"""The ``tag_cleanup`` plan for the ticked findings of one search."""
job_id, chosen, message = parse_options(options)
if message:
return _invalid(message)
held, error = self._held_tag_cleanup(job_id)
if error is not None:
return error
for rule_id, tag_ids in chosen.items():
listed = {f["tag_id"] for f in held["rules"][rule_id]}
if not listed.issuperset(tag_ids):
return _invalid("A selected tag is not a finding of its rule")
db = self.db
identity = self._database_identity(db)
try:
draft = await self._run_in_executor(
rules.plan_tag_cleanup, db.model.db_path, held, chosen
)
except Exception:
self.logger.exception("Tag cleanup review failed")
return _failure("Failed to review maintenance", 500)
return await self._plan_response(
db,
identity,
TAG_CLEANUP,
draft.fingerprint,
draft.public(),
{
"targets": draft.targets,
"roots": [],
"held": rules.held_rows(draft),
"protected": draft.protected["count"],
"rows": len(draft.targets),
},
)
+18 -5
View File
@@ -205,8 +205,7 @@ def _is_preview_request(filepath):
take as an anchor: a backslash, a drive or stream colon, and empty, ``.``
or ``..`` segments (so a leading ``/`` and ``//server/share`` too).
"""
# #646: a backslash is a separator only on Windows.
if ":" in filepath or (os.sep == "\\" and "\\" in filepath):
if "\\" in filepath or ":" in filepath:
return False
parts = filepath.split("/")
if len(parts) < 2 or parts[0] != "thumbnails":
@@ -388,6 +387,7 @@ class AutoThumbnailer:
self._worker_running = False
self._closed = False
self._busy = False
self._batch = 0
@property
def failure_count(self):
@@ -547,6 +547,7 @@ class AutoThumbnailer:
with self._changed:
self._worker_running = False
self._busy = False
self._batch = 0
self._changed.notify_all()
def _drain(self):
@@ -561,6 +562,7 @@ class AutoThumbnailer:
workers = max(1, int(self._workers() or 1))
take = min(len(self._queue), workers)
batch = [self._queue.popleft() for _ in range(take)]
self._batch = len(batch)
self._changed.notify_all()
try:
# The job pool's size is the setting; a smaller batch uses
@@ -568,6 +570,7 @@ class AutoThumbnailer:
map_parallel(self._write_queued, batch, workers)
finally:
with self._changed:
self._batch = 0
for key, *_rest in batch:
self._queued.discard(key)
@@ -629,6 +632,10 @@ class AutoThumbnailer:
"""True once the worker has nothing queued or in hand."""
return self._wait_for(lambda: not self._busy, timeout)
def wait_batch(self, size, timeout=None):
"""True once the worker holds a batch of *size* files."""
return self._wait_for(lambda: self._batch == size, timeout)
class _PreviewGate:
"""Admission of view requests on the event loop (#249 I2).
@@ -768,9 +775,6 @@ class AutoThumbnailMixin:
return job
if job.kind == THUMBNAILS_JOB_KIND and job.title == THUMBNAIL_CLEAR_TITLE:
return job
# Move thumbnails holds automatic previews for its whole run (D2A).
if job.kind == THUMBNAILS_JOB_KIND and job.scope.get("mode") == "move":
return job
return None
# ── the view admission ────────────────────────────────────────────
@@ -960,6 +964,15 @@ class AutoThumbnailMixin:
return "queued"
return "skipped"
def _capture_target(self, image_path):
"""``(src, dst, is_video)`` of a new output's preview now, or None."""
located = self._capture_source(image_path)
if located is None:
return None
src, root, rel, is_video = located
dst = DeferredPreview(root, rel).resolve()
return None if dst is None else (src, dst, is_video)
def _capture_source(self, image_path):
"""``(src, root, rel, is_video)`` of a media file under a current
root (not a preview, a link or in a trash folder), or None."""
+1 -7
View File
@@ -44,7 +44,7 @@ import os
import time
from pathlib import Path
from . import preview_store, thumbnail_settings
from . import thumbnail_settings
from .thumbnail_encode import ThumbnailVerifyError, verify_thumbnail, writer_settings
from .admin import _plural, _scan_location, _scan_roots, _scan_status_line
from .images import _thumbnail_is_fresh, _worker_threads, _thumbnail_batch_size
@@ -393,12 +393,6 @@ class ThumbnailConvertMixin:
removed, with no bytes (another run or a sibling removed it)."""
removed, kept = 0, []
for path, size in old:
if not preview_store.may_write(path):
# Folder mode: never a file outside a key folder, or one
# reached through a link (checked at the moment of the delete).
self.logger.warning(f"Not removing {path}: outside the thumbnails")
kept.append(path)
continue
try:
os.remove(path)
except FileNotFoundError:
+6 -38
View File
@@ -46,7 +46,7 @@ from pathlib import Path
from PIL import Image
from . import preview_location, preview_store, thumbnail_settings
from . import preview_store, thumbnail_settings
try:
from ...utils.logging_config import get_logger
@@ -114,7 +114,6 @@ def replace_unless_held(tmp, dst, guard=None):
# ``temp_sibling``'s names: ``.<stem>.<tag>-<pid>-<thread id><ext>``.
_TEMP_NAME = re.compile(r"^\..+\.(?:part|src)-(\d+)-\d+\.[A-Za-z0-9]+$")
_MOVE_TEMP_NAME = re.compile(r"\.pm-move-[0-9a-f]{8}\.tmp$")
# A temp at least this old (seconds) outlived its write: no encode runs longer.
STRAY_TEMP_AGE = 4 * ENCODE_TIMEOUT
# When this process started (this module's import): a temp carrying its PID
@@ -126,10 +125,7 @@ def sweep_stray_temps(folder, min_age=None):
"""Remove the temp files a crashed write left under *folder* (a preview
folder, walked without following links); returns ``(count, bytes)``.
Only ``temp_sibling`` names are touched, never a link: a folder that is a
link, junction or reparse point is not walked into (Windows walks into a
junction even without ``followlinks``), and each file passes
``preview_store.may_write`` before it goes. With *min_age*
Only ``temp_sibling`` names are touched, never a link. With *min_age*
(seconds, the startup sweep) a temp younger than that, or one this
process wrote since it started (it may still be writing it), is left;
``min_age=0`` (the clear, which holds every preview write) removes them
@@ -139,39 +135,19 @@ def sweep_stray_temps(folder, min_age=None):
now = time.time()
own = str(os.getpid())
count = size = 0
try:
if preview_location.is_link_like(folder):
return count, size
except OSError as exc:
logger.debug(f"Not sweeping {folder}: {exc}")
return count, size
for root, dirs, files in os.walk(folder):
dirs[:] = [d for d in dirs if not _link_like(Path(root) / d)]
for root, _dirs, files in os.walk(folder):
for name in files:
match = _TEMP_NAME.match(name)
# A move's copy temp (#320): ``<name>.pm-move-<8 hex>.tmp``.
move_temp = match is None and _MOVE_TEMP_NAME.search(name)
if match is None and not move_temp:
if match is None:
continue
path = Path(root) / name
try:
stat = path.lstat()
if (
path.is_symlink()
or not path.is_file()
or _link_like(path)
or not preview_store.may_write(path)
):
if path.is_symlink() or not path.is_file():
continue
if min_age and (
now - stat.st_mtime < min_age
or move_temp
and stat.st_mtime >= PROCESS_STARTED
or (
match is not None
and match.group(1) == own
and stat.st_mtime >= PROCESS_STARTED
)
or (match.group(1) == own and stat.st_mtime >= PROCESS_STARTED)
):
continue
path.unlink()
@@ -183,14 +159,6 @@ def sweep_stray_temps(folder, min_age=None):
return count, size
def _link_like(path):
"""``is_link_like``, with a path that cannot be checked counted as one."""
try:
return preview_location.is_link_like(path)
except OSError:
return True
def _unlink_quietly(path):
try:
Path(path).unlink()
+5 -33
View File
@@ -90,7 +90,7 @@ class ThumbnailOptions:
}
def thumbnail_options(raw):
def thumbnail_options(raw, *, from_query=False):
"""``(ThumbnailOptions, None)`` from a body or query, or ``(None, message)``.
An absent mode is ``missing``; the settings are the server's now.
@@ -132,11 +132,8 @@ class ThumbnailJobsMixin:
"""The thumbnail plan, the thumbnail job and the legacy stream on it."""
async def get_thumbnail_plan(self, request):
"""What a thumbnail run would do (read-only; capped like a run).
``mode=prune`` lists the removed sources' thumbnails (#320)."""
if request.query.get("mode") == "prune":
return await self.get_prune_plan()
options, error = thumbnail_options(request.query)
"""What a thumbnail run would do (read-only; capped like a run)."""
options, error = thumbnail_options(request.query, from_query=True)
if error:
return _invalid(error)
try:
@@ -183,8 +180,6 @@ class ThumbnailJobsMixin:
)
except (ValueError, UnicodeDecodeError):
return _invalid(_OPTIONS_ERROR)
if isinstance(body, dict) and body.get("mode") in ("move", "prune"):
return await self._start_location_job(body)
options, error = thumbnail_options(body)
if error:
return _invalid(error)
@@ -197,25 +192,6 @@ class ThumbnailJobsMixin:
return busy_response(busy)
return web.json_response({"success": True, "job": job.summary()}, status=202)
async def _start_location_job(self, body):
"""Move thumbnails or Remove thumbnails of removed sources (#320)."""
if body["mode"] == "prune":
refused = location_refusal()
if refused is not None:
return refused
try:
if body["mode"] == "move":
started = self.start_thumbnail_move(body)
else:
started = self.start_thumbnail_prune()
except JobBusy as busy:
return busy_response(busy)
if isinstance(started, web.Response):
return started
return web.json_response(
{"success": True, "job": started.summary()}, status=202
)
def _start_thumbnail_job(self, options):
"""Register the thumbnail job synchronously; raises JobBusy.
@@ -539,12 +515,8 @@ class ThumbnailJobsMixin:
the way.
"""
running = self._jobs.active(THUMBNAILS_JOB_KIND)
if running is not None and running.scope.get("mode") in (
"convert",
"move",
"prune",
):
return None, False, running # no legacy frames to follow (#317, #320)
if running is not None and running.scope.get("mode") == "convert":
return None, False, running # no legacy frames to follow (#317)
if running is not None and running.cancellable:
return running, False, None
busy = self._jobs.blocker(THUMBNAILS_JOB_KIND, admission="guarded")
+1 -3
View File
@@ -82,7 +82,7 @@ class ThumbnailLocationMixin:
if folder:
contained.append(str(folder))
except ImportError:
pass # folder_paths exists only inside ComfyUI (tests run without it)
pass
try:
contained.append(library_location.config_location()[1])
except Exception: # no data folder can be decided
@@ -157,6 +157,4 @@ class ThumbnailLocationMixin:
if with_path:
payload["path"] = location.path
payload["default_path"] = default_path()
# Old copies a move still has to remove (#320 Part 3).
payload["cleanup_pending"] = len(preview_store.setting().cleanup)
return payload
-579
View File
@@ -1,579 +0,0 @@
"""Move thumbnails (#320 Part 3): the reviewed job that changes where previews
live, the removal of old copies after it, recovery at startup and the
"Remove thumbnails of removed sources" scope (Part 5).
Kind ``thumbnails`` with ``mode: "move"`` (D1A): admission ``guarded``, so
scans, deletes, tagging, source changes and every other thumbnail job wait
for it, while the monitor's Needs review recording runs beside it.
Automatic previews are held for the whole job (D2A, ``_auto_thumbnail_blocker``).
Phases: review (``POST /images/thumbnails/plan``, no writes but the
validation probe), start (a plan token), hold (generation bump, journal,
target folder), copy (cancellable at every file boundary, on the job pool
in small chunks, D3A), switch (one config commit sets the location and
records the old stores under ``cleanup``; not cancellable from here),
remove old copies, end. Per-file errors switch anyway (D10A); a folder-wide
error or a cancel before the switch removes what the job wrote and changes
nothing. The move is the only writer of the setting (D4B).
Moving away from a thumbnail folder also removes the previews of this
install's sources that are no longer listed (Q320-8: remove).
"""
import functools
import os
import time
from pathlib import Path
from aiohttp import web
from . import preview_location, preview_store
from . import thumbnail_move_files as files
from .jobs import THUMBNAILS_JOB_KIND
from .thumbnail_move_plan import (
MOVE_GROUPS,
MOVE_TITLE,
PLAN_TTL,
_number,
_plural,
_remove,
_roots_revision,
_volume,
_is_network,
_write_json,
)
from . import thumbnail_move_plan as move_plan
try:
from ...utils import exit_signal
from ...utils.parallel import map_parallel
except ImportError: # tests import the package top-level
from utils import exit_signal
from utils.parallel import map_parallel
class ThumbnailMoveMixin:
"""Start and run the move job; the removal of old copies."""
# ── start ─────────────────────────────────────────────────────────
def _take_move_plan(self, body):
"""The plan a start names, or ``(status, code)``."""
token = body.get("token")
plan = (self._move_plans or {}).get(token) if isinstance(token, str) else None
if plan is None or time.monotonic() - plan.created > PLAN_TTL:
return 409, "plan-stale"
roots = [str(root) for root in self._get_all_output_dirs()]
if _roots_revision(roots) != plan.revision:
return 409, "plan-stale"
if preview_store.setting() != plan.old:
return 409, "plan-stale"
if plan.confirm_required and body.get("confirmed") is not True:
return 400, "confirmation-required"
return plan
def start_thumbnail_move(self, body):
"""Start the move job (sync, on the loop); raises JobBusy. Returns
the job or a refusal response."""
if not self._move_recovered:
blocker = self._jobs.active(THUMBNAILS_JOB_KIND)
return web.json_response(
{
"success": False,
"code": "busy",
"error": "Prompt Manager is still checking an earlier move. "
"Try again in a moment.",
"running": None if blocker is None else {"id": blocker.id},
},
status=409,
)
taken = self._take_move_plan(body)
if isinstance(taken, tuple):
status, code = taken
text = {
"plan-stale": "The review is out of date. Review the move again.",
"confirmation-required": "Confirm that Prompt Manager may "
"create its folders there.",
}[code]
return web.json_response(
{"success": False, "code": code, "error": text}, status=status
)
plan = taken
self._move_plans.pop(plan.token, None)
return self._jobs.start(
THUMBNAILS_JOB_KIND,
MOVE_TITLE,
admission="guarded",
cancellable=True,
scope={
"mode": "move",
"from": plan.old.mode,
"to": plan.target["mode"],
"to_path": plan.target["path"],
},
groups=MOVE_GROUPS,
runner=functools.partial(self._run_thumbnail_move, plan=plan),
)
# ── the job ───────────────────────────────────────────────────────
async def _run_thumbnail_move(self, job, *, plan):
state = {"written": [], "created": [], "created_folder": False}
try:
await self._run_in_executor(self._move_hold, job, plan, state)
except (OSError, ValueError) as error:
await self._run_in_executor(self._move_rollback, plan, state)
self._end_move(
job, "failed", "The new folder could not be made; nothing changed."
)
self.logger.warning(f"Move thumbnails could not start: {error}")
return
left = [
{
"path": "/".join(item),
"root": s.label,
"detail": "Not a thumbnail; left in place",
}
for s in plan.sources
if s.scan is not None
for item in s.scan.left
]
if left:
job.record_counted("left", len(left), left)
items = [
(source, item)
for source in plan.sources
if source.scan is not None
for item in source.scan.copy
]
total = len(items)
job.update(total=total, processed=0, progress=0)
chunk = await self._run_in_executor(self._move_chunk, plan)
workers = self._move_workers()
done = 0
for start in range(0, total, chunk):
if job.cancelled:
await self._move_cancelled(job, plan, state)
return
batch = items[start : start + chunk]
try:
results = await self._run_in_executor(
map_parallel,
functools.partial(self._move_copy_one, state=state),
batch,
workers,
)
except exit_signal.ExitRequested:
return # exiting: the next start undoes the copies (journal)
except files.FolderGone as error:
self.logger.warning(f"Move thumbnails stopped: {error}")
await self._run_in_executor(self._move_rollback, plan, state)
self._end_move(
job,
"failed",
"The new folder could not be reached or is full; nothing changed.",
)
return
except Exception:
# Anything else before the switch: undo, never half a move.
self.logger.exception("Move thumbnails failed while copying")
await self._run_in_executor(self._move_rollback, plan, state)
self._end_move(job, "failed", "The copy failed; nothing changed.")
return
for (source, item), (outcome, detail) in zip(batch, results):
row = {
"path": "/".join(item[0]),
"root": source.label,
"detail": detail,
}
job.record(
"moved" if outcome == "moved" else outcome,
row,
f"{outcome}: {source.label} · {'/'.join(item[0])}",
)
done += len(batch)
label = batch[-1][0].label
job.update(
processed=done,
progress=int(done * 90 / total) if total else 90,
status_line=(
f"Copying {_number(done)} of {_number(total)} previews · {label}"
),
)
job.publish({"type": "progress", "summary": job.summary()})
if job.cancelled:
await self._move_cancelled(job, plan, state)
return
# The switch: not cancellable from here (an exit still stops between
# files and leaves the cleanup to the next start).
job.cancellable = False
job.update(status_line="Switching to the new location", progress=92)
job.publish({"type": "progress", "summary": job.summary()})
try:
await self._run_in_executor(self._move_switch, plan)
except Exception:
self.logger.exception("Move thumbnails could not switch")
await self._run_in_executor(self._move_rollback, plan, state)
self._end_move(
job, "failed", "The setting could not be saved; nothing changed."
)
return
await self._remove_old_copies(job, plan)
moved = job.counters.get("moved", 0) + job.counters.get("skipped", 0)
errors = job.counters.get("errors", 0)
where = plan.target["path"] or "inside each source"
parts = [f"{_number(moved)} moved"]
if errors:
parts.append(_plural(errors, "error"))
parts.append(
"old copies removed"
if not job.scope.get("cleanup_left")
else "some old copies are removed at the next start"
)
self._end_move(
job, "finished", f"Thumbnails moved to {where}: " + " · ".join(parts) + "."
)
def _end_move(self, job, state, line):
job.update(status_line=line, progress=100)
job.log_line(line)
job.publish({"type": "complete", "summary": job.summary()})
job.finish(state)
def _move_workers(self):
from .images import _worker_threads
return max(1, int(_worker_threads() or 1))
def _move_chunk(self, plan):
"""2 files at a time across volumes or to/from a share, else 4, never
more than Worker threads (D3A: the pool keeps its size)."""
sides = [plan.target["path"] or ""] + [s.old_store or "" for s in plan.sources]
sides += [s.new_store for s in plan.sources]
network = any(_is_network(side) for side in sides if side)
volumes = {_volume(side) for side in sides if side}
size = 2 if network or len(volumes) > 1 else 4
return max(1, min(size, self._move_workers()))
def _move_hold(self, job, plan, state):
"""Phase 3: bump the generation, write the journal, make the target."""
preview_store.bump_generation()
if plan.to_folder:
folder = plan.target["path"]
if not os.path.isdir(folder):
if plan.target_default:
os.makedirs(folder, exist_ok=True)
else:
os.mkdir(folder)
state["created_folder"] = True
plan.target_id = preview_location.init_folder(
folder, created_by_pm=state["created_folder"]
)
install = plan.install
def add_keys(marker):
for source in plan.sources:
if source.key and source.key not in marker["keys"]:
marker["keys"][source.key] = {
"path": source.root,
"identity": os.path.normcase(os.path.realpath(source.root)),
"dev_ino": preview_location.file_identity(source.root),
"install": install,
}
with preview_store.write_lock:
preview_location.write_marker(folder, add_keys)
_write_json(
move_plan.journal_path(),
{
"state": "copying",
"from": plan.old.to_config(),
"to": plan.target,
"stores": [s.new_store for s in plan.sources],
# Stores that do not exist yet are made by this job only:
# after a crash everything in them goes (B4).
"created_dirs": [
s.new_store for s in plan.sources if not os.path.isdir(s.new_store)
],
"created_folder": state["created_folder"],
"install": plan.install,
},
)
job.log_line(
f"Move thumbnails started: {plan.old.path or 'inside each source'} → "
f"{plan.target['path'] or 'inside each source'}"
)
def _move_copy_one(self, pair, *, state):
"""Copy one preview (a pool thread); ``(group, detail)``."""
source, (relative, size, mtime_ns) = pair
destination = Path(source.new_store).joinpath(*relative)
try:
if not os.path.isdir(destination.parent):
base = Path(source.new_store)
if not base.is_dir():
if plan_parent_missing(base):
raise files.FolderGone("the new folder is gone")
created = []
files._make_folders(base.parent, (base.name,), created)
state["created"].extend(created)
created = []
files._make_folders(base, relative[:-1], created)
state["created"].extend(created)
# Also when the folders already exist (Codex P1 on #592).
files.refuse_links(source.new_store, relative[:-1])
outcome = files.copy_one(
Path(source.old_store).joinpath(*relative),
destination,
size,
mtime_ns,
state["created"],
)
except files.CopyFailed as error:
return "errors", str(error)
if outcome == "moved":
state["written"].append(str(destination))
return "moved", "Copied and checked"
return "skipped", "Already there"
async def _move_cancelled(self, job, plan, state):
if exit_signal.requested():
return # the next start removes the partial copies (journal)
await self._run_in_executor(self._move_rollback, plan, state)
self._end_move(job, "cancelled", "Move cancelled: nothing changed.")
def _move_rollback(self, plan, state):
"""Remove what this job wrote (files, folders it made, a folder and
marker it created) and the journal: nothing changed."""
for path in state["written"]:
files.remove_file(path)
for folder in reversed(state["created"]):
files.remove_empty_folders(folder)
if plan.to_folder and state.get("created_folder"):
folder = plan.target["path"]
try:
names = os.listdir(folder)
except OSError:
names = None
if names is not None and set(names) <= {preview_location.MARKER_NAME}:
_remove(preview_location.marker_path(folder))
files.remove_empty_folders(folder)
_remove(move_plan.journal_path())
def _move_switch(self, plan):
"""Phase 5: one config commit sets the location and records the old
stores under ``cleanup``; the runtime follows under the write lock."""
from ..config import PromptManagerConfig
from ..config_store import get_config_store
entry = {
"from": plan.old.mode,
"folder": plan.old.path if plan.from_folder else None,
"stores": [s.old_store for s in plan.sources if s.old_store],
"drop_keys": self._old_keys_to_drop(plan),
"install": plan.install,
}
# An older entry never removes a store the move just filled (a move
# back while old copies still waited).
filled = {os.path.normcase(s.new_store) for s in plan.sources}
cleanup = []
for old_entry in plan.old.cleanup:
stores = [
store
for store in old_entry.get("stores") or []
if isinstance(store, str) and os.path.normcase(store) not in filled
]
folder = old_entry.get("folder")
drop = [
key
for key in old_entry.get("drop_keys") or []
if not folder
or os.path.normcase(os.path.join(folder, key)) not in filled
]
cleanup.append({**old_entry, "stores": stores, "drop_keys": drop})
cleanup.append(entry)
if plan.to_folder:
value = {
"mode": preview_store.FOLDER_MODE,
"path": plan.target["path"],
"id": plan.target_id,
"install": plan.install,
"cleanup": cleanup,
}
else:
value = {
"mode": preview_store.SOURCE_MODE,
"install": plan.install,
"cleanup": cleanup,
}
def mutate(config):
section = config.get("thumbnails")
if not isinstance(section, dict):
section = {}
section["location"] = value
config["thumbnails"] = section
return config
def publish(_config):
PromptManagerConfig.THUMBNAIL_LOCATION = value
preview_store.configure(value, check=False)
get_config_store().commit(mutate, expected_revision=None, publish=publish)
# The switch is made: what follows never undoes it.
try:
preview_store.refresh()
_remove(move_plan.journal_path())
except OSError as error:
self.logger.warning(
f"The thumbnail move journal stays until the next start: {error}"
)
def _old_keys_to_drop(self, plan):
if not plan.from_folder:
return []
keys = [s.old_store and os.path.basename(s.old_store) for s in plan.sources]
keys = [key for key in keys if key]
if plan.to_folder and os.path.normcase(plan.old.path or "") == os.path.normcase(
plan.target["path"] or ""
):
return []
return keys + [key for key, _store, _scan in plan.unlisted]
async def _remove_old_copies(self, job, plan):
"""Phase 6: run the cleanup the switch recorded (and earlier ones)."""
job.update(status_line="Removing old copies", progress=95)
job.publish({"type": "progress", "summary": job.summary()})
left = await self._run_in_executor(self._run_cleanup, job)
if left:
job.scope["cleanup_left"] = True
def _run_cleanup(self, job=None):
"""Remove every recorded old store's previews, temps and empty
folders; keep in ``cleanup`` what could not go. Returns how many
entries are left (blocking)."""
setting = preview_store.setting()
remaining = []
for entry in setting.cleanup:
if not self._cleanup_entry(entry, job):
remaining.append(entry)
if list(setting.cleanup) != remaining:
self._commit_cleanup(remaining)
return len(remaining)
def _cleanup_entry(self, entry, job):
"""One recorded removal; True when it is complete."""
folder = entry.get("folder")
stores = [
store for store in entry.get("stores") or [] if isinstance(store, str)
]
if folder:
if not os.path.isdir(folder):
return False # the old folder is not reachable: kept for later
folder_marker = preview_location.read_marker(folder) or {}
keys = folder_marker.get("keys") or {}
stores += [
os.path.join(folder, key)
for key in entry.get("drop_keys") or []
if preview_location.valid_key(key) and key in keys
]
complete = True
for store in dict.fromkeys(stores):
if not self._remove_store(store, folder, job):
complete = False
if folder and complete:
drop = set(entry.get("drop_keys") or [])
def forget(marker):
for key in drop:
marker["keys"].pop(key, None)
try:
with preview_store.write_lock:
marker = preview_location.write_marker(folder, forget)
except (OSError, ValueError):
return False
if not marker["keys"] and marker.get("created_by_pm"):
names = set(os.listdir(folder))
rest = {n for n in names if not files.is_os_metadata(n)}
if rest <= {preview_location.MARKER_NAME}:
_remove(preview_location.marker_path(folder))
files.remove_empty_folders(folder)
return complete
def _remove_store(self, store, folder, job):
"""Remove the previews and temps of one old store; True when done."""
store = Path(store)
if folder:
# A key folder directly in the old thumbnail folder, nothing else.
if not preview_location.valid_key(store.name) or os.path.normcase(
str(store.parent)
) != os.path.normcase(str(folder)):
return True
elif store.name != "thumbnails":
return True # a hand-edited entry never names another folder
if not store.exists():
return True
if preview_location.is_link_like(store):
return True # never through a link; nothing of ours there
complete = True
removed = 0
for current, dirs, names in os.walk(store):
dirs[:] = [
d for d in dirs if not preview_location.is_link_like(Path(current) / d)
]
for name in names:
path = Path(current) / name
if files.is_temp_name(name) or files._preview_parts(name):
if preview_location.is_link_like(path):
continue
if exit_signal.requested():
return False # exiting: the next start finishes it
if files.remove_file(path):
removed += 1
else:
complete = False
relative = path.relative_to(store).as_posix()
self.logger.warning(
f"Could not remove the old thumbnail {path}; it is "
"removed at the next start"
)
if job is not None:
# D10A: a removal that failed is an error the job lists.
job.record(
"errors",
{
"path": relative,
"root": store.name,
"detail": "In use by another program; removed "
"at the next start",
},
f"In use by another program; removed at the next "
f"start: {store.name}/{relative}",
)
files.remove_empty_folders(store)
if job is not None and removed:
job.log_line(f"Removed {_number(removed)} old files from {store.name}")
return complete
def _commit_cleanup(self, remaining):
from ..config import PromptManagerConfig
from ..config_store import get_config_store
def mutate(config):
section = config.get("thumbnails")
if isinstance(section, dict) and isinstance(section.get("location"), dict):
section["location"]["cleanup"] = remaining
return config
def publish(config):
value = (config.get("thumbnails") or {}).get("location")
PromptManagerConfig.THUMBNAIL_LOCATION = value
preview_store.set_cleanup(remaining)
get_config_store().commit(mutate, expected_revision=None, publish=publish)
def plan_parent_missing(store):
"""A key folder's parent (the thumbnail folder) is gone mid-copy."""
return not Path(store).parent.is_dir()
-348
View File
@@ -1,348 +0,0 @@
"""The file side of Move thumbnails (#320 Part 3): what is copied, how a
copy is made and checked, and how old copies are removed.
No job, HTTP or config code lives here; ``thumbnail_move`` drives it.
Copy set (B5): each old store is walked with ``os.scandir``, never through a
symlink, junction or reparse point (counted as "skipped link"). A regular
file is
- copied when it has the preview grammar (``<name>_thumb<ext>``, any written
or legacy extension) and its original still exists in the source;
- removed with the old copies, not copied, when it is an orphan (no
original), lies under a trash folder, or is a temp sibling of a write
(``.<stem>.part-…``) or of a move (``….pm-move-<8 hex>.tmp``);
- left in place otherwise ("Left in place"). OS metadata files (``Thumbs.db``,
``desktop.ini``, ``.DS_Store``, ``._*``) are removed only when they alone
keep a preview folder from being removed.
A copy goes to ``<name>.pm-move-<8 hex>.tmp`` beside its destination, its
size is compared, its mtime is set to the source preview's rounded up to the
next 2-second step (FAT/exFAT keep it fresh, a stale preview stays stale),
then it is renamed into place. Every handle is closed before a rename or an
unlink (Windows).
"""
import errno
import logging
import os
import re
import secrets
import shutil
import stat as stat_module
import time
from dataclasses import dataclass, field
from pathlib import Path
from . import preview_location, thumbnail_settings
from .thumbnail_encode import _TEMP_NAME
try:
from ...utils.media_folders import in_trash_folder
except ImportError: # tests import the package top-level
from utils.media_folders import in_trash_folder
logger = logging.getLogger("prompt_manager.thumbnails")
MOVE_TEMP = re.compile(r"\.pm-move-[0-9a-f]{8}\.tmp$")
MOVE_TEMP_SUFFIX = ".pm-move-{token}.tmp"
# The temp name adds this much to a destination path (".pm-move-xxxxxxxx.tmp").
TEMP_EXTRA = 21
WINDOWS_FILE_LIMIT = 259
MTIME_STEP_NS = 2_000_000_000
# A file another program holds open (Windows) is retried this often.
REMOVE_RETRIES = (0.5, 1.0, 2.0)
_WINDOWS_IN_USE = {32, 33} # ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION
def is_os_metadata(name):
folded = name.lower()
return folded in preview_location.OS_METADATA or folded.startswith("._")
def is_temp_name(name):
return bool(_TEMP_NAME.match(name) or MOVE_TEMP.search(name))
def _preview_parts(name):
"""``(base, extension)`` of a preview file name, or None."""
stem, extension = os.path.splitext(name)
suffix = thumbnail_settings.THUMB_SUFFIX
if not stem.endswith(suffix) or len(stem) <= len(suffix):
return None
if extension.lower() not in thumbnail_settings.THUMBNAIL_EXTENSIONS:
return None
return stem[: -len(suffix)], extension
def _has_original(root, rel_dir, base, extension):
"""Whether a media file in ``<root>/<rel_dir>`` owns this preview."""
folder = Path(root).joinpath(*rel_dir)
try:
with os.scandir(folder) as entries:
for entry in entries:
stem, source_ext = os.path.splitext(entry.name)
if stem != base or not source_ext:
continue
if not thumbnail_settings.owns(extension, source_ext):
continue
if entry.is_file(follow_symlinks=False):
return True
except OSError:
return False
return False
@dataclass
class StoreScan:
"""One old store's files, sorted into what the move does with them."""
store: Path
copy: list = field(default_factory=list) # (relative parts, size, mtime_ns)
orphans: list = field(default_factory=list) # relative parts
temps: list = field(default_factory=list)
left: list = field(default_factory=list)
links: int = 0
bytes: int = 0
@property
def removable(self):
return [item[0] for item in self.copy] + self.orphans + self.temps
def scan_store(store, root, *, stop=None):
"""Sort the files of *store* (the previews of the source *root*).
A store that does not exist, or is itself a link, scans empty (a link
counts once).
"""
store = Path(store)
scan = StoreScan(store)
try:
if preview_location.is_link_like(store):
scan.links += 1
return scan
if not store.is_dir():
return scan
except OSError:
return scan
_walk(scan, store, (), root, stop)
return scan
def _walk(scan, folder, rel_dir, root, stop):
try:
with os.scandir(folder) as iterator:
entries = list(iterator)
except OSError:
return
for entry in entries:
if stop is not None and stop():
return
relative = rel_dir + (entry.name,)
path = Path(entry.path)
try:
if preview_location.is_link_like(path):
scan.links += 1
continue
info = entry.stat(follow_symlinks=False)
except OSError:
continue
if stat_module.S_ISDIR(info.st_mode):
_walk(scan, path, relative, root, stop)
continue
if not stat_module.S_ISREG(info.st_mode):
scan.left.append(relative)
continue
if is_temp_name(entry.name):
scan.temps.append(relative)
continue
if is_os_metadata(entry.name):
continue # removed only when it alone keeps a folder (rmdir)
parts = _preview_parts(entry.name)
if parts is None:
scan.left.append(relative)
continue
if in_trash_folder("/".join(relative)) or not _has_original(
root, rel_dir, *parts
):
scan.orphans.append(relative)
continue
scan.copy.append((relative, info.st_size, info.st_mtime_ns))
scan.bytes += info.st_size
# ── copying ──────────────────────────────────────────────────────────
def rounded_mtime_ns(mtime_ns):
"""*mtime_ns* rounded up to the next 2-second step (FAT/exFAT)."""
return -(-mtime_ns // MTIME_STEP_NS) * MTIME_STEP_NS
def too_long(path, long_paths=None):
"""A destination (with its temp name) over Windows' file limit."""
if os.name != "nt" and long_paths is not False:
return False
if long_paths is None:
long_paths = preview_location.long_paths_enabled()
if long_paths:
return False
return len(str(path)) + TEMP_EXTRA > WINDOWS_FILE_LIMIT
class CopyFailed(Exception):
"""One preview could not be copied (a per-file error, D10A)."""
class FolderGone(Exception):
"""The destination cannot take writes any more (abort the move)."""
def _make_folders(base, relative_dir, created):
"""Make ``base/relative_dir`` one folder at a time (*base* must exist);
every folder made is added to *created*."""
current = Path(base)
for part in relative_dir:
current = current / part
try:
os.mkdir(current)
created.append(str(current))
except FileExistsError:
pass # already there: made by an earlier copy into this folder
except OSError as error:
if error.errno in (errno.ENOSPC, errno.EDQUOT, errno.EROFS):
raise FolderGone(str(error)) from error
raise CopyFailed(
"Its folder could not be made; made again on view"
) from error
if preview_location.is_link_like(current):
raise CopyFailed("a link in the destination")
def refuse_links(base, relative_dir):
"""Raise CopyFailed when *base* or an existing folder on the way to
``base/relative_dir`` is a link (never copy through one)."""
current = Path(base)
for part in (None, *relative_dir):
if part is not None:
current = current / part
if preview_location.is_link_like(current):
raise CopyFailed("a link in the destination")
def copy_one(source, destination, size, mtime_ns, created, *, long_paths=None):
"""Copy one preview; returns ``"moved"`` or ``"skipped"`` (already
there). Raises CopyFailed (this file) or FolderGone (the destination)."""
destination = Path(destination)
if too_long(destination, long_paths):
raise CopyFailed("Path too long for Windows; the original is shown")
wanted = rounded_mtime_ns(mtime_ns)
try:
existing = os.stat(destination, follow_symlinks=False)
except FileNotFoundError:
existing = None
except OSError as error:
raise FolderGone(str(error)) from error
if (
existing is not None
and stat_module.S_ISREG(existing.st_mode)
and existing.st_size == size
and existing.st_mtime_ns == wanted
):
return "skipped"
temp = destination.with_name(
destination.name + MOVE_TEMP_SUFFIX.format(token=secrets.token_hex(4))
)
try:
shutil.copyfile(source, temp)
if os.stat(temp).st_size != size:
raise CopyFailed("The copy did not match; made again on view")
os.utime(temp, ns=(wanted, wanted))
os.replace(temp, destination)
except CopyFailed:
_unlink(temp)
raise
except FileNotFoundError as error:
_unlink(temp)
if not Path(source).exists():
raise CopyFailed("Could not be read; made again on view") from error
raise FolderGone(str(error)) from error
except OSError as error:
_unlink(temp)
if error.errno in (errno.ENOSPC, errno.EDQUOT, errno.EROFS):
raise FolderGone(str(error)) from error
raise CopyFailed("Could not be copied; made again on view") from error
return "moved"
def _unlink(path):
"""Remove a copy's temp file after a failed copy; True when it is gone.
One that cannot go (a Windows lock, permissions) is logged with its path;
the next start's temp sweep removes it (``.pm-move-*.tmp``)."""
try:
os.unlink(path)
return True
except FileNotFoundError:
return True # never written, or already renamed into place
except OSError as error:
logger.warning(f"Could not remove the move's temp file {path}: {error}")
return False
# ── removing ─────────────────────────────────────────────────────────
def _in_use(error):
return getattr(error, "winerror", None) in _WINDOWS_IN_USE
def remove_file(path, *, sleep=time.sleep):
"""Remove one file; a file another program holds open (Windows) is
retried 3 times. Returns True when it is gone."""
for wait in (0.0,) + REMOVE_RETRIES:
if wait:
sleep(wait)
try:
os.unlink(path)
return True
except FileNotFoundError:
return True
except OSError as error:
if not _in_use(error):
return False
return False
def remove_empty_folders(top, *, keep_top=False):
"""``rmdir`` the empty folders below *top* (and *top*), bottom-up, never
through a link. A folder holding only OS metadata files loses them first.
Returns the folders that could not be removed."""
top = Path(top)
left = []
if not top.is_dir() or preview_location.is_link_like(top):
return left
# Top-down, pruning every link, junction or reparse point, then bottom-up:
# never into a folder outside *top* (Windows junctions included).
folders = []
for folder, dirs, _files in os.walk(top):
folder = Path(folder)
dirs[:] = [d for d in dirs if not preview_location.is_link_like(folder / d)]
folders.append(folder)
for folder in reversed(folders):
if folder == top and keep_top:
continue
try:
names = os.listdir(folder)
except OSError:
left.append(folder)
continue
if names and all(is_os_metadata(name) for name in names):
for name in names:
remove_file(folder / name)
try:
os.rmdir(folder)
except OSError:
left.append(folder)
return left
-492
View File
@@ -1,492 +0,0 @@
"""Move thumbnails, the review (#320 Part 3 phase 1): what a move would copy,
remove and leave, checked before anything is written."""
import hashlib
import json
import os
import secrets
import shutil
import time
import uuid
from dataclasses import dataclass, field
from pathlib import Path
from aiohttp import web
from . import preview_location, preview_store
from . import thumbnail_move_files as files
from .job_routes import busy_response
from .jobs import THUMBNAILS_JOB_KIND, JobBusy
from .thumbnail_location import default_path
try:
from ...utils import library_location
except ImportError: # tests import the package top-level
from utils import library_location
MOVE_TITLE = "Move thumbnails"
FINISHING_TITLE = "Move thumbnails (finishing)"
PRUNE_TITLE = "Remove thumbnails of removed sources"
MOVE_GROUPS = ("moved", "skipped", "left", "errors")
PRUNE_GROUPS = ("removed", "left", "errors")
PLAN_TTL = 600.0
JOURNAL_NAME = "thumbnail-move.json"
SPACE_MARGIN = 64 * 2**20
SPACE_SHARE = 0.05
LISTED = 5
SENTENCE = (
"Every thumbnail is copied and checked before Prompt Manager switches. "
"Scans, deletes and tagging wait until it finishes; closing this page does "
"not stop it."
)
def _number(value):
return f"{value:,}"
def _plural(count, one, many=None):
return f"{_number(count)} {one if count == 1 else (many or one + 's')}"
def _size(value):
size = float(value)
for unit in ("B", "KB", "MB", "GB"):
if size < 1024 or unit == "GB":
return f"{size:.1f} {unit}" if unit != "B" else f"{int(size)} B"
size /= 1024
return f"{size:.1f} GB"
def _refusal(code, status=None, **extra):
known_status, text = preview_location.MESSAGES.get(code, (400, code))
return web.json_response(
{"success": False, "code": code, "error": text, **extra},
status=status or known_status,
)
def journal_path():
"""``<data folder>/data/thumbnail-move.json`` (only while a move copies)."""
return library_location.cache_dir(JOURNAL_NAME)
def _read_json(path):
try:
with open(path, "r", encoding="utf-8") as handle:
data = json.load(handle)
except (OSError, ValueError):
return None
return data if isinstance(data, dict) else None
def _write_json(path, data):
os.makedirs(os.path.dirname(path), exist_ok=True)
temp = f"{path}.{os.getpid()}.tmp"
with open(temp, "w", encoding="utf-8") as handle:
json.dump(data, handle, indent=2)
handle.flush()
os.fsync(handle.fileno())
os.replace(temp, path)
def _remove(path):
try:
os.unlink(path)
except FileNotFoundError:
pass # already gone: removing it is the goal
def _is_network(path):
text = str(path)
if text.startswith(("\\\\", "//")):
return True
if os.name == "nt":
try:
import ctypes
drive = os.path.splitdrive(os.path.abspath(text))[0] + "\\"
return ctypes.windll.kernel32.GetDriveTypeW(drive) == 4 # DRIVE_REMOTE
except (AttributeError, OSError):
return False
return False
def _volume(path):
current = Path(os.path.abspath(path))
while not current.exists() and current.parent != current:
current = current.parent
try:
return os.stat(current).st_dev
except OSError:
return None
def _free(path):
current = Path(os.path.abspath(path))
while not current.exists() and current.parent != current:
current = current.parent
try:
return shutil.disk_usage(current).free
except OSError:
return None
# ── the plan ─────────────────────────────────────────────────────────
@dataclass
class SourcePlan:
"""One listed source: its old store, its new store and what moves."""
root: str
label: str
key: str | None
old_store: str | None
new_store: str
scan: files.StoreScan | None
available: bool = True
too_long: list = field(default_factory=list)
@dataclass
class MovePlan:
"""A reviewed move: from, to, the sources and the removals."""
token: str
created: float
revision: str
old: preview_location.ParsedLocation
target: dict # {"mode", "path"}
target_id: str | None
target_exists: bool
target_default: bool
install: str
sources: list
unlisted: list # (key, store path, scan)
needs_bytes: int
confirm_required: bool
@property
def to_folder(self):
return self.target["mode"] == preview_store.FOLDER_MODE
@property
def from_folder(self):
return self.old.mode == preview_store.FOLDER_MODE
def _roots_revision(roots):
text = json.dumps(sorted(str(root) for root in roots))
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
class ThumbnailMovePlanMixin:
"""The move's review and its routes."""
_move_plans = None
# ── routes ────────────────────────────────────────────────────────
def _register_thumbnail_move_routes(self, routes):
@routes.post("/prompt_manager/images/thumbnails/plan")
async def thumbnail_move_plan_route(request):
return await self.plan_thumbnail_move(request)
@routes.post("/prompt_manager/images/thumbnails/location/recreate")
async def thumbnail_location_recreate_route(request):
return await self.recreate_thumbnail_folder(request)
@routes.post("/prompt_manager/images/thumbnails/location/adopt")
async def thumbnail_location_adopt_route(request):
return await self.adopt_thumbnail_folder(request)
# ── review ────────────────────────────────────────────────────────
async def plan_thumbnail_move(self, request):
try:
body = await request.json()
except (ValueError, UnicodeDecodeError):
body = None
if not isinstance(body, dict) or body.get("mode") != "move":
return web.json_response(
{
"success": False,
"code": "invalid-request",
"error": "mode must be move",
},
status=400,
)
target = body.get("location")
if not isinstance(target, dict) or target.get("mode") not in (
preview_store.SOURCE_MODE,
preview_store.FOLDER_MODE,
):
return web.json_response(
{
"success": False,
"code": "invalid-request",
"error": "location must name a mode",
},
status=400,
)
blocker = self._jobs.blocker(THUMBNAILS_JOB_KIND, admission="guarded")
if blocker is not None:
return busy_response(JobBusy(blocker))
try:
outcome = await self._run_in_executor(self._build_move_plan, target)
except Exception:
self.logger.exception("The thumbnail move could not be planned")
return web.json_response(
{
"success": False,
"code": None,
"error": "The move could not be planned",
},
status=500,
)
if isinstance(outcome, str):
return _refusal(outcome)
plan, payload = outcome
if payload.get("insufficient"):
return _refusal(
"insufficient-space",
status=507,
error_detail=payload["insufficient"],
plan=payload,
)
self._store_move_plan(plan)
return web.json_response({"success": True, **payload})
def _store_move_plan(self, plan):
if self._move_plans is None:
self._move_plans = {}
now = time.monotonic()
self._move_plans = {
token: kept
for token, kept in self._move_plans.items()
if now - kept.created < PLAN_TTL
}
self._move_plans[plan.token] = plan
def _build_move_plan(self, target):
"""``(plan, payload)`` or a refusal code (blocking)."""
old = preview_store.setting()
location = preview_store.current()
install = old.install or str(uuid.uuid4())
target_path = None
default = default_path()
if target["mode"] == preview_store.FOLDER_MODE:
raw = target.get("path")
if not isinstance(raw, str):
return "location-not-absolute"
context = self._thumbnail_location_context()
code = preview_location.location_problem(
raw, purpose="move", context=context
)
if code is not None:
return code
target_path = os.path.abspath(raw)
elif old.mode == preview_store.SOURCE_MODE and not old.problem:
return "location-same"
target_default = bool(default) and os.path.normcase(
target_path or ""
) == os.path.normcase(os.path.abspath(default))
target_exists = bool(target_path) and os.path.isdir(target_path)
target_marker = (
preview_location.read_marker(target_path) if target_exists else None
)
roots = [str(root) for root in self._get_all_output_dirs()]
labels = self._source_labels(roots)
old_keys = {}
if old.mode == preview_store.FOLDER_MODE and location.available:
marker = preview_location.read_marker(old.path) or {}
old_keys = marker.get("keys") or {}
new_keys = dict((target_marker or {}).get("keys") or {})
taken = {key: entry.get("identity") for key, entry in new_keys.items()}
sources = []
for root in roots:
identity = os.path.normcase(os.path.realpath(root))
dev_ino = preview_location.file_identity(root)
old_key = None
old_store = None
available = True
if old.mode == preview_store.SOURCE_MODE:
old_store = str(preview_store.source_folder(root))
elif location.available:
old_key = preview_location.find_key(old_keys, root, identity, dev_ino)
if old_key:
old_store = os.path.join(old.path, old_key)
else:
available = False
key = None
if target_path:
key = old_key or preview_location.find_key(
new_keys, root, identity, dev_ino
)
if key is None or taken.get(key, identity) != identity:
key = preview_location.source_key(root, identity, taken)
taken[key] = identity
new_store = os.path.join(target_path, key)
else:
new_store = str(preview_store.source_folder(root))
scan = None
if old_store:
scan = files.scan_store(old_store, root)
plan = SourcePlan(
root, labels.get(root, root), key, old_store, new_store, scan, available
)
if scan is not None and target_path:
plan.too_long = [
item[0]
for item in scan.copy
if files.too_long(Path(new_store).joinpath(*item[0]))
]
sources.append(plan)
unlisted = self._unlisted_keys(old, location, old_keys, install)
needs = sum(source.scan.bytes for source in sources if source.scan is not None)
plan = MovePlan(
token=secrets.token_urlsafe(16),
created=time.monotonic(),
revision=_roots_revision(roots),
old=old,
target={"mode": target["mode"], "path": target_path},
target_id=(target_marker or {}).get("id"),
target_exists=target_exists,
target_default=target_default,
install=install,
sources=sources,
unlisted=unlisted,
needs_bytes=needs,
confirm_required=bool(target_path) and not target_default,
)
return plan, self._plan_payload(plan, location)
def _unlisted_keys(self, old, location, keys, install):
"""This install's keys whose source no longer is in any root list
(``(key, store, scan)``), in the folder in use."""
if old.mode != preview_store.FOLDER_MODE or not location.available:
return []
listed = {
os.path.normcase(os.path.realpath(root))
for root in self._all_source_roots()
}
found = []
for key, entry in sorted(keys.items()):
if not preview_location.valid_key(key) or not isinstance(entry, dict):
continue # a marker is data: never a path out of the folder
if entry.get("install") not in (install, None):
continue
if entry.get("identity") in listed:
continue
store = os.path.join(old.path, key)
found.append(
(key, store, files.scan_store(store, entry.get("path") or store))
)
return found
def _source_labels(self, roots):
from . import sources
labels = sources._comfyui_labels()
return {root: sources.source_label(root, labels) for root in roots}
def _plan_payload(self, plan, location):
sources = plan.sources
copies = sum(len(s.scan.copy) for s in sources if s.scan)
orphans = sum(len(s.scan.orphans) for s in sources if s.scan)
temps = sum(len(s.scan.temps) for s in sources if s.scan)
links = sum(s.scan.links for s in sources if s.scan)
left = [
f"{s.label} · {'/'.join(item)}"
for s in sources
if s.scan
for item in s.scan.left
]
too_long = [
f"{s.label} · {'/'.join(item)}" for s in sources for item in s.too_long
]
unlisted_count = sum(
len(scan.copy) + len(scan.orphans) for _k, _s, scan in plan.unlisted
)
free = None
insufficient = None
if plan.needs_bytes:
volumes = {}
for source in sources:
if source.scan is None or not source.scan.bytes:
continue
volume = _volume(source.new_store)
entry = volumes.setdefault(volume, [source.new_store, 0])
entry[1] += source.scan.bytes
for where, needed in volumes.values():
available = _free(where)
if available is None:
continue
free = available if free is None else min(free, available)
margin = max(SPACE_MARGIN, int(needed * SPACE_SHARE))
if needed + margin > available:
insufficient = {
"needed": needed + margin,
"free": available,
"text": (
f"There is not enough space for the thumbnails: "
f"{_size(available)} free, {_size(needed + margin)} "
"needed. Free some space or choose another folder."
),
}
payload = {
"mode": "move",
"from": {
"mode": plan.old.mode,
"path": plan.old.path,
"available": location.available,
},
"to": {
"mode": plan.target["mode"],
"path": plan.target["path"],
"exists": plan.target_exists,
"will_create": bool(plan.target["path"]) and not plan.target_exists,
"default": plan.target_default,
},
"sources": [
{
"label": s.label,
"key": s.key,
"files": len(s.scan.copy) if s.scan else 0,
"bytes": s.scan.bytes if s.scan else 0,
"too_long": len(s.too_long),
"links": s.scan.links if s.scan else 0,
"orphans": len(s.scan.orphans) if s.scan else 0,
"left_in_place": len(s.scan.left) if s.scan else 0,
"available": s.available,
}
for s in sources
],
"totals": {
"sources": len(sources),
"files": copies,
"bytes": plan.needs_bytes,
"orphans": orphans,
"temps": temps,
"links": links,
"left_in_place": len(left),
"too_long": len(too_long),
"unlisted_sources": len(plan.unlisted),
"unlisted_files": unlisted_count,
},
"too_long_listed": too_long[:LISTED],
"left_listed": left[:LISTED],
"unlisted": [
{"key": key, "files": len(scan.copy) + len(scan.orphans)}
for key, _store, scan in plan.unlisted
],
"needs_bytes": plan.needs_bytes,
"free_bytes": free,
"confirm_required": plan.confirm_required,
"token": plan.token,
"sentence": SENTENCE,
}
if insufficient:
payload["insufficient"] = insufficient
return payload
-246
View File
@@ -1,246 +0,0 @@
"""Move thumbnails after a restart and the unavailable folder's actions
(#320 Parts 3 and 4): undo an interrupted copy, finish a removal that
waited, Recreate folder and Use this folder."""
import os
import threading
from pathlib import Path
from aiohttp import web
from . import preview_location, preview_store
from . import thumbnail_move_files as files
from .job_routes import busy_response
from .jobs import THUMBNAILS_JOB_KIND, JobBusy
from .thumbnail_move_plan import (
FINISHING_TITLE,
MOVE_GROUPS,
_read_json,
_refusal,
_remove,
)
from . import thumbnail_move_plan as move_plan
class ThumbnailMoveRecoveryMixin:
"""Startup recovery, the finishing job, Recreate and Use this folder."""
_move_recover_lock = threading.Lock()
# Per API: set once recover_thumbnail_move has run (a move waits for it).
_move_recovered = False
# ── startup ───────────────────────────────────────────────────────
def recover_thumbnail_move(self):
"""Startup (B4): undo an interrupted copy, or forget a journal the
switch already made true. Idempotent; the move start waits for it."""
with self._move_recover_lock:
if self._move_recovered:
return
try:
self._recover_journal()
except Exception:
self.logger.warning(
"The interrupted thumbnail move check failed", exc_info=True
)
self._move_recovered = True
def _recover_journal(self):
path = move_plan.journal_path()
journal = _read_json(path)
if journal is None:
return
setting = preview_store.setting()
target = journal.get("to") or {}
now = setting.path if setting.mode == preview_store.FOLDER_MODE else None
if setting.mode == target.get("mode") and (
now is None
or os.path.normcase(now) == os.path.normcase(target.get("path") or "")
):
_remove(path) # the switch happened; only the journal was left
return
for store in journal.get("stores") or []:
if not isinstance(store, str) or not os.path.isdir(store):
continue
for current, dirs, names in os.walk(store):
dirs[:] = [
d
for d in dirs
if not preview_location.is_link_like(Path(current) / d)
]
for name in names:
if files.MOVE_TEMP.search(name):
files.remove_file(Path(current) / name)
for folder in reversed(journal.get("created_dirs") or []):
if not isinstance(folder, str) or not os.path.isdir(folder):
continue
for current, dirs, names in os.walk(folder):
dirs[:] = [
d
for d in dirs
if not preview_location.is_link_like(Path(current) / d)
]
for name in names:
if files._preview_parts(name) or files.is_temp_name(name):
files.remove_file(Path(current) / name)
files.remove_empty_folders(folder)
folder = target.get("path")
if journal.get("created_folder") and folder and os.path.isdir(folder):
names = set(os.listdir(folder))
if names <= {preview_location.MARKER_NAME}:
_remove(preview_location.marker_path(folder))
files.remove_empty_folders(folder)
_remove(path)
self.logger.info("An interrupted thumbnail move was undone; nothing changed")
def _cleanup_reachable(self, entry):
folder = entry.get("folder")
if folder:
return os.path.isdir(folder)
return True
async def finish_thumbnail_move(self, _app=None):
"""Startup: recover, then start "Move thumbnails (finishing)" when old
copies wait and every one is reachable (on the server's loop)."""
await self._run_in_executor(self.recover_thumbnail_move)
cleanup = list(preview_store.setting().cleanup)
if not cleanup:
return None
reachable = await self._run_in_executor(
lambda: all(self._cleanup_reachable(entry) for entry in cleanup)
)
if not reachable:
return None
try:
return self._jobs.start(
THUMBNAILS_JOB_KIND,
FINISHING_TITLE,
admission="guarded",
cancellable=False,
scope={"mode": "move", "phase": "remove"},
groups=MOVE_GROUPS,
runner=self._run_finishing,
)
except JobBusy:
return None
async def _run_finishing(self, job):
await self._remove_old_copies(job, None)
left = len(preview_store.setting().cleanup)
self._end_move(
job,
"finished",
(
"Old thumbnails removed."
if not left
else (
"Some old thumbnails are still in use; they are removed at "
"the next start."
)
),
)
# ── Recreate and Use this folder (Part 4) ─────────────────────────
async def recreate_thumbnail_folder(self, _request):
blocker = self._jobs.blocker(THUMBNAILS_JOB_KIND, admission="guarded")
if blocker is not None:
return busy_response(JobBusy(blocker))
code = await self._run_in_executor(self._recreate_folder)
if code is not None:
status = (
409 if code in ("location-has-marker", "location-not-empty") else 400
)
if code == "location-has-marker":
return web.json_response(
{
"success": False,
"code": code,
"error": "The folder is back with its thumbnails. Nothing "
"was recreated.",
},
status=status,
)
return _refusal(code, status=status)
return web.json_response(
{
"success": True,
"location": self._thumbnail_location_payload(with_path=True),
}
)
def _recreate_folder(self):
setting = preview_store.setting()
if setting.mode != preview_store.FOLDER_MODE or not setting.path:
return "location-same"
folder = setting.path
if os.path.isdir(folder):
if preview_location.read_marker(folder) is not None:
return "location-has-marker"
if not preview_location.holds_only_metadata(folder):
return "location-not-empty"
elif not os.path.isdir(os.path.dirname(folder)):
return "location-parent-missing"
else:
try:
os.mkdir(folder)
except OSError:
return "location-not-writable"
try:
marker_id = preview_location.init_folder(folder, created_by_pm=True)
except OSError:
return "location-not-writable"
return self._commit_location_id(marker_id)
async def adopt_thumbnail_folder(self, _request):
blocker = self._jobs.blocker(THUMBNAILS_JOB_KIND, admission="guarded")
if blocker is not None:
return busy_response(JobBusy(blocker))
code = await self._run_in_executor(self._adopt_folder)
if code is not None:
return _refusal(code)
return web.json_response(
{
"success": True,
"location": self._thumbnail_location_payload(with_path=True),
}
)
def _adopt_folder(self):
setting = preview_store.setting()
if setting.mode != preview_store.FOLDER_MODE or not setting.path:
return "location-same"
try:
marker = preview_location.read_marker(setting.path)
except OSError:
return "location-unavailable"
if marker is None:
return "location-unavailable"
return self._commit_location_id(marker["id"])
def _commit_location_id(self, marker_id):
from ..config import PromptManagerConfig
from ..config_store import get_config_store
value = dict(preview_store.setting().to_config())
value["id"] = marker_id
def mutate(config):
section = config.get("thumbnails")
if not isinstance(section, dict):
section = {}
section["location"] = value
config["thumbnails"] = section
return config
def publish(_config):
PromptManagerConfig.THUMBNAIL_LOCATION = value
preview_store.configure(value, check=False)
try:
get_config_store().commit(mutate, expected_revision=None, publish=publish)
except Exception:
self.logger.exception("The thumbnail folder could not be saved")
return "location-not-writable"
preview_store.refresh()
return None
-175
View File
@@ -1,175 +0,0 @@
"""Remove thumbnails of removed sources (#320 Part 5, D200): a Thumbnail
maintenance scope, offered only in folder mode (31A).
*Removed* means a key of this install in the thumbnail folder's marker whose
identity matches no root in any root list. The job removes the
preview-grammar files and temps of those key folders, ``rmdir``s the empty
folders, drops the keys from the marker and lists anything else as "Left in
place". Kind ``thumbnails``, ``mode: "prune"``.
"""
import functools
import os
from pathlib import Path
from aiohttp import web
from . import preview_location, preview_store
from . import thumbnail_move_files as files
from .jobs import THUMBNAILS_JOB_KIND
from .thumbnail_location import location_refusal
from .thumbnail_move_plan import _number, _plural, _size
PRUNE_TITLE = "Remove thumbnails of removed sources"
PRUNE_GROUPS = ("removed", "left", "errors")
def _prune_line(count, files_count, size):
if not count:
return "No sources were removed: nothing to remove."
return (
f"{_plural(count, 'source')} no longer listed: "
f"{_plural(files_count, 'thumbnail')} ({_size(size)}) are removed."
)
class ThumbnailPruneMixin:
"""The prune plan and job."""
def _prune_targets(self):
"""``[(key, store, scan)]`` of this install's unlisted keys (blocking)."""
setting = preview_store.setting()
location = preview_store.current()
if setting.mode != preview_store.FOLDER_MODE or not location.available:
return []
marker = preview_location.read_marker(setting.path) or {}
install = setting.install
return self._unlisted_keys(setting, location, marker.get("keys") or {}, install)
def _prune_payload(self, targets):
files_count = sum(
len(scan.copy) + len(scan.orphans) for _k, _s, scan in targets
)
size = sum(scan.bytes for _k, _s, scan in targets)
return {
"success": True,
"mode": "prune",
"sources": [
{
"key": key,
"files": len(scan.copy) + len(scan.orphans),
"bytes": scan.bytes,
"left_in_place": len(scan.left),
}
for key, _store, scan in targets
],
"targets": files_count,
"bytes": size,
"line": _prune_line(len(targets), files_count, size),
"folder": preview_store.setting().path,
}
async def get_prune_plan(self):
refused = location_refusal()
if refused is not None:
return refused
if preview_store.current().mode != preview_store.FOLDER_MODE:
return web.json_response(
{
"success": False,
"code": "invalid-request",
"error": "Thumbnails are kept inside each source: no removed "
"source has thumbnails here.",
},
status=400,
)
targets = await self._run_in_executor(self._prune_targets)
return web.json_response(
self._prune_payload(targets), headers={"Cache-Control": "no-store"}
)
def start_thumbnail_prune(self):
"""Start the prune job (sync, on the loop); raises JobBusy."""
return self._jobs.start(
THUMBNAILS_JOB_KIND,
PRUNE_TITLE,
admission="guarded",
cancellable=True,
scope={"mode": "prune"},
groups=PRUNE_GROUPS,
runner=self._run_thumbnail_prune,
)
async def _run_thumbnail_prune(self, job):
targets = await self._run_in_executor(self._prune_targets)
job.update(total=len(targets), processed=0)
setting = preview_store.setting()
for done, (key, store, scan) in enumerate(targets, 1):
if job.cancelled:
break
removed, failed = await self._run_in_executor(
functools.partial(self._prune_store, store)
)
job.record_counted(
"removed", removed, [{"path": key, "detail": "Thumbnails removed"}]
)
if failed:
job.record_counted("errors", failed)
if scan.left:
job.record_counted(
"left",
len(scan.left),
[{"path": f"{key}/{'/'.join(item)}"} for item in scan.left],
)
await self._run_in_executor(
functools.partial(self._forget_key, setting.path, key, store)
)
job.update(
processed=done,
progress=int(done * 100 / len(targets)),
status_line=f"Removing thumbnails of {_number(done)} of "
f"{_number(len(targets))} removed sources",
)
job.publish({"type": "progress", "summary": job.summary()})
line = f"{_number(job.counters.get('removed', 0))} thumbnails removed"
if job.counters.get("errors"):
line += f" · {_plural(job.counters['errors'], 'error')}"
job.update(status_line=line, progress=100)
job.log_line(line)
job.finish("cancelled" if job.cancelled else "finished")
@staticmethod
def _prune_store(store):
"""Remove the previews and temps of one key folder; ``(removed, failed)``."""
removed = failed = 0
store = Path(store)
if not store.is_dir() or preview_location.is_link_like(store):
return 0, 0
for current, dirs, names in os.walk(store):
dirs[:] = [
d for d in dirs if not preview_location.is_link_like(Path(current) / d)
]
for name in names:
path = Path(current) / name
if not (files.is_temp_name(name) or files._preview_parts(name)):
continue
if preview_location.is_link_like(path):
continue
if files.remove_file(path):
removed += 1
else:
failed += 1
files.remove_empty_folders(store)
return removed, failed
@staticmethod
def _forget_key(folder, key, store):
"""Drop *key* from the marker once its folder is gone."""
if os.path.exists(store):
return
def forget(marker):
marker["keys"].pop(key, None)
with preview_store.write_lock:
preview_location.write_marker(folder, forget)
+1 -4
View File
@@ -43,7 +43,6 @@ CONTENT_TYPES = {
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".avif": "image/avif", # #652: served as itself, never a preview
}
THUMB_SUFFIX = "_thumb"
@@ -134,9 +133,7 @@ def thumbnail_rel(rel_path, extension=None):
# Ruling R2: files sharing a stem share one preview, made from the first
# source in this order: these images, then videos (by extension name).
# #652: AVIF comes last among the stills, so an existing stack keeps the
# source its preview was made from.
IMAGE_SOURCE_ORDER = (".png", ".jpg", ".jpeg", ".webp", ".gif", ".avif")
IMAGE_SOURCE_ORDER = (".png", ".jpg", ".jpeg", ".webp", ".gif")
def source_rank(source_extension):
+1 -16
View File
@@ -59,9 +59,6 @@ REWRITE_FAILED = (
)
RECLAIM_FAILED = "Reclaim space failed; the database is unchanged."
ROW_KEPT = "could not be rewritten; it keeps its inline text and reads as before"
# A protected value's row (#586), in the review's "not text; kept as is".
VALUE_KEPT = "stored value not text; kept as is"
KEPT_COLUMNS = {"workflow_data": "workflow", "prompt_metadata": "prompt graph"}
NOTHING_LEFT = "Every image record already stores its workflow once"
@@ -180,19 +177,7 @@ class WorkflowStorageRoutesMixin:
protected += batch["protected"]
errors += len(batch["errors"])
job.record_counted("changed", batch["rows"])
job.record_counted(
"protected",
batch["protected"],
[
{
"path": "",
"detail": f"Image record {image_id}: "
f"{KEPT_COLUMNS.get(column, column)}, {VALUE_KEPT}",
}
for image_id, column in batch["kept"]
],
complete=True,
)
job.record_counted("protected", batch["protected"])
for image_id in batch["errors"]:
job.record(
"errors",
+10 -10
View File
@@ -30,9 +30,9 @@ except ImportError:
# The tag template and thresholds live with the saved tagging defaults
# (#328), so config.py never imports PIL.
try:
from .tagging_defaults import DEFAULT_TAG_TEMPLATE, read_wd14_label_rows
from .tagging_defaults import DEFAULT_TAG_TEMPLATE
except ImportError:
from py.tagging_defaults import DEFAULT_TAG_TEMPLATE, read_wd14_label_rows
from py.tagging_defaults import DEFAULT_TAG_TEMPLATE
try:
from ..utils import exit_signal
@@ -559,6 +559,7 @@ class AutoTagService:
# A missing onnxruntime is refused by load_model before this runs
# (#424); a ModuleNotFoundError here becomes the same refusal.
import onnxruntime as ort
import csv
config = MODELS[model_type]
model_dir = self.models_dir / config["subdir"]
@@ -575,8 +576,12 @@ class AutoTagService:
session = ort.InferenceSession(str(model_path), providers=providers)
# Read tag list from CSV (the reader the Skipped tags preview shares)
tags_list = read_wd14_label_rows(tags_path)
# Read tag list from CSV
tags_list = []
with open(tags_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
tags_list.append(row)
self.logger.info(
f"WD14 model loaded ({len(tags_list)} tags, "
@@ -987,7 +992,6 @@ class AutoTagService:
prompt: Optional[str] = None,
general_threshold: Optional[float] = None,
character_threshold: Optional[float] = None,
skip: Any = None,
) -> List[Tuple[str, Optional[float]]]:
"""The top ``limit`` suggestions as ``(name, confidence)`` pairs.
@@ -996,9 +1000,7 @@ class AutoTagService:
``None``. Names are distinct case-insensitively (first one wins).
A name Save would reject (over 50 characters, a control character
such as a newline, a comma) is skipped before the dedupe and the
``limit`` count. A name ``skip`` matches (a ``SkipMatcher``, the
Skipped tags compiled for this request or job, #431) is dropped next,
so it uses up no slot. ``prompt`` is used for this call only;
``limit`` count. ``prompt`` is used for this call only;
``custom_prompt`` is never changed.
"""
if type(limit) is not int or not 1 <= limit <= MAX_SUGGESTION_LIMIT:
@@ -1015,8 +1017,6 @@ class AutoTagService:
name = validate_vocabulary_tag_name(raw)
except ValueError:
continue
if skip is not None and skip.matches(name):
continue
key = name.casefold()
if key in seen:
continue
+68 -230
View File
@@ -30,7 +30,6 @@ routes = server_instance.routes
# Extension info
extension_uri = None # Will be set in __init__.py
import hashlib # noqa: E402
import os # noqa: E402
from typing import Any, Dict, List, Optional, Tuple # noqa: E402
@@ -38,7 +37,6 @@ from typing import Any, Dict, List, Optional, Tuple # noqa: E402
try:
from ..utils.logging_config import get_logger
from ..utils import library_location
from ..utils.media_formats import AVIF_EXTENSION
except ImportError:
import sys
@@ -46,7 +44,6 @@ except ImportError:
sys.path.insert(0, current_dir)
from utils.logging_config import get_logger
from utils import library_location
from utils.media_formats import AVIF_EXTENSION
# Initialize logger for config operations
config_logger = get_logger("prompt_manager.config")
@@ -80,6 +77,27 @@ def _canonical_path(path: str) -> str:
return os.path.normcase(os.path.realpath(path))
def write_private_json(path: str, data: Any) -> None:
"""Write ``data`` as JSON to ``path`` readable by the current user only.
config.json can hold an API key (integrations.lora_manager), so it is
created with mode 0600 and, on POSIX, an existing more open file is
tightened too. Windows has no POSIX modes; there the chmod is a best
effort that only affects the read-only bit. Parent directories are
created as needed. Raises OSError when the file cannot be written.
"""
import json
parent_dir = os.path.dirname(path)
if parent_dir:
os.makedirs(parent_dir, exist_ok=True)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
if os.name == "posix":
os.chmod(path, 0o600)
def _lexical_path(path: str) -> str:
"""``path`` normalised for comparison without touching the filesystem.
@@ -197,9 +215,7 @@ class GalleryConfig:
# Read by the monitor for every file, so a save applies without a restart
SAVE_FOREIGN_RUNS = True
MONITORING_DIRECTORIES = [] # Auto-detect if empty
# #652: AVIF is named here and skipped at collection when Pillow cannot
# read it (utils.media_formats.collectable).
SUPPORTED_EXTENSIONS = [".png", ".jpg", ".jpeg", ".webp", ".gif", AVIF_EXTENSION]
SUPPORTED_EXTENSIONS = [".png", ".jpg", ".jpeg", ".webp", ".gif"]
PROCESSING_DELAY = 2.0 # Seconds to wait before processing new files
# Prompt tracking settings
@@ -305,9 +321,7 @@ class GalleryConfig:
if directories is not None:
cls.MONITORING_DIRECTORIES = directories
if "extensions" in monitoring:
extensions = cls._validated_extensions(monitoring["extensions"])
if extensions is not None:
cls.SUPPORTED_EXTENSIONS = extensions
cls.SUPPORTED_EXTENSIONS = monitoring["extensions"]
if "processing_delay" in monitoring:
cls.PROCESSING_DELAY = monitoring["processing_delay"]
@@ -361,45 +375,6 @@ class GalleryConfig:
config_logger.warning(f"Ignoring gallery root {label!r}: {reason}")
return kept
@classmethod
def _validated_extensions(cls, extensions: Any) -> Optional[List[str]]:
"""Monitor extensions from a saved config, with AVIF added back (#652).
``gallery.monitoring.extensions`` is saved in each user's config.json
and overrides the default, so an install that saved its settings
before #652 names no ``.avif`` and keeps not collecting AVIF files.
It is appended here, after the user's own entries, so an existing
install gains the new type without losing anything it chose.
A hand-edited config.json is as untrusted as a settings request: a
value that is not a list is ignored entirely (``None`` keeps the
current list), a non-string entry is dropped with a warning, and the
rest is normalised to lowercase dot-extensions.
"""
if not isinstance(extensions, list):
config_logger.warning(
"Ignoring gallery monitoring extensions: expected a list"
)
return None
kept = []
for entry in extensions:
if not isinstance(entry, str):
config_logger.warning(
"Ignoring gallery monitoring extension: expected a string"
)
continue
normalized = entry.strip().lower()
if not normalized:
continue
if not normalized.startswith("."):
normalized = "." + normalized
if normalized not in kept:
kept.append(normalized)
# An empty list is a deliberate "collect nothing", so it stays empty.
if kept and AVIF_EXTENSION not in kept:
kept.append(AVIF_EXTENSION)
return kept
@classmethod
def allowed_gallery_parents(cls) -> List[str]:
"""Canonical directories under which gallery roots may live.
@@ -612,15 +587,8 @@ try:
MODEL_TYPES,
WD14_MODEL_TYPES,
validate_saved_threshold,
validate_skipped_tags,
validate_template,
validate_threshold,
BUILTIN_INSTRUCTIONS_ID,
INSTRUCTION_ENGINES,
MAX_SAVED_INSTRUCTIONS,
builtin_instructions,
validate_default_instructions,
validate_instructions,
)
except ImportError:
from py.tagging_defaults import ( # noqa: F401 - re-exported
@@ -632,15 +600,8 @@ except ImportError:
MODEL_TYPES,
WD14_MODEL_TYPES,
validate_saved_threshold,
validate_skipped_tags,
validate_template,
validate_threshold,
BUILTIN_INSTRUCTIONS_ID,
INSTRUCTION_ENGINES,
MAX_SAVED_INSTRUCTIONS,
builtin_instructions,
validate_default_instructions,
validate_instructions,
)
@@ -656,31 +617,6 @@ def _valid_existing(value: Any) -> str:
return value
def _valid_skipped_tags(value: Any) -> Tuple[str, ...]:
return tuple(validate_skipped_tags(value))
def _reason(error: ValueError) -> str:
"""A settings sentence as a load warning's reason ("entry 2 is empty")."""
text = str(error).rstrip(".")
for prefix in ("Skipped tags", "Saved instructions"):
if text.startswith(prefix):
return text.removeprefix(prefix).lstrip(": ")
return text
def _text_id(text: str) -> str:
"""A migrated entry's id: deterministic, so every load gives the same."""
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]
def _fallback_warning(key: str, error: ValueError, default: Any) -> str:
"""The one load warning of a saved tagging default that fails its check."""
if key == "skipped_tags":
return f"autotag.defaults.skipped_tags {_reason(error)}; using no skipped tags"
return f"autotag.defaults.{key} {error}; using {default!r}"
def _valid_suggestion_limit(value: Any) -> int:
if type(value) is not int or not 1 <= value <= MAX_SUGGESTION_LIMIT:
raise ValueError(f"must be an integer from 1 to {MAX_SUGGESTION_LIMIT}")
@@ -701,18 +637,8 @@ class AutotagConfig:
EXISTING = "skip"
GENERAL_THRESHOLD = 0.35
CHARACTER_THRESHOLD = 0.85
TEMPLATE = DEFAULT_TAG_TEMPLATE
SUGGESTION_LIMIT = DEFAULT_SUGGESTION_LIMIT
SKIPPED_TAGS: Tuple[str, ...] = ()
# #431: the saved instructions (Built-in is never stored) and the default
# of each language-model engine, by id.
INSTRUCTIONS: Tuple[Dict[str, str], ...] = ()
DEFAULT_INSTRUCTIONS: Dict[str, str] = {
"gguf": BUILTIN_INSTRUCTIONS_ID,
"hf": BUILTIN_INSTRUCTIONS_ID,
}
# The old single template as read at load (None when absent or invalid);
# only the migration reads it. Saves keep it as the GGUF default's mirror.
_LEGACY_TEMPLATE: Optional[str] = None
# config.json key -> (attribute, validator, default)
_KEYS = {
@@ -728,155 +654,35 @@ class AutotagConfig:
lambda v: validate_saved_threshold("value", v),
0.85,
),
"template": ("TEMPLATE", validate_template, DEFAULT_TAG_TEMPLATE),
"suggestion_limit": (
"SUGGESTION_LIMIT",
_valid_suggestion_limit,
DEFAULT_SUGGESTION_LIMIT,
),
# #431: words whose suggested tags are never offered.
"skipped_tags": ("SKIPPED_TAGS", _valid_skipped_tags, ()),
}
@classmethod
def suggestion_limit(cls) -> int:
return cls.SUGGESTION_LIMIT
@classmethod
def all_instructions(cls) -> List[Dict[str, str]]:
"""Built-in first, then the saved entries (copies)."""
return [builtin_instructions()] + [dict(item) for item in cls.INSTRUCTIONS]
@classmethod
def default_instructions_text(cls, engine: str) -> str:
"""The text of ``engine``'s (``gguf`` or ``hf``) default instructions."""
if engine not in INSTRUCTION_ENGINES:
raise ValueError(f"{engine} takes no instructions")
wanted = cls.DEFAULT_INSTRUCTIONS.get(engine, BUILTIN_INSTRUCTIONS_ID)
for item in cls.INSTRUCTIONS:
if item["id"] == wanted:
return item["text"]
return DEFAULT_TAG_TEMPLATE
@classmethod
def mirror_template(cls) -> Optional[str]:
"""What an older build reads as its one template (#431 B1.1): the
GGUF default's text, or None (no key) when that default is Built-in."""
if cls.DEFAULT_INSTRUCTIONS.get("gguf") == BUILTIN_INSTRUCTIONS_ID:
return None
return cls.default_instructions_text("gguf")
@staticmethod
def valid_suggestion_limit(value: Any) -> bool:
return (
type(value) is int and 1 <= value <= MAX_SUGGESTION_LIMIT
) # bool, float and str are rejected
@classmethod
def get_config(cls) -> Dict[str, Any]:
"""The saved defaults; ``template`` only as the GGUF default's mirror."""
"""The saved defaults; the template only when it is not the built-in
one, so a later built-in template still reaches who never set one."""
defaults = {
key: getattr(cls, attr) for key, (attr, _v, _d) in cls._KEYS.items()
}
defaults["skipped_tags"] = list(defaults["skipped_tags"])
defaults["instructions"] = [dict(item) for item in cls.INSTRUCTIONS]
defaults["default_instructions"] = dict(cls.DEFAULT_INSTRUCTIONS)
mirror = cls.mirror_template()
if mirror is not None:
defaults["template"] = mirror
if defaults["template"] == DEFAULT_TAG_TEMPLATE:
del defaults["template"]
return {"defaults": defaults}
@classmethod
def _load_instructions(cls, defaults: Dict[str, Any]) -> None:
"""Each instruction key alone, then the cross-key default check, then
the in-memory migration of the old template (#431). Nothing is
written here, so the revision never changes at load."""
cls._LEGACY_TEMPLATE = None
if "template" in defaults:
try:
cls._LEGACY_TEMPLATE = validate_template(defaults["template"])
except ValueError as error:
config_logger.warning(
f"autotag.defaults.template {error}; using the built-in one"
)
entries: List[Dict[str, str]] = []
damaged = False
if "instructions" in defaults:
try:
entries = validate_instructions(defaults["instructions"])
except ValueError as error:
damaged = True
config_logger.warning(
f"autotag.defaults.instructions {_reason(error)}; "
"using Built-in only"
)
chosen = {engine: BUILTIN_INSTRUCTIONS_ID for engine in INSTRUCTION_ENGINES}
stored = defaults.get("default_instructions")
if damaged:
# Both defaults fall back with the list (its one warning says so);
# the old template is migrated as on a first upgrade.
pass
elif "default_instructions" in defaults and (
not isinstance(stored, dict) or set(stored) != set(INSTRUCTION_ENGINES)
):
config_logger.warning(
"autotag.defaults.default_instructions must name gguf and hf; "
"using Built-in"
)
elif isinstance(stored, dict):
ids = {item["id"] for item in entries}
for engine in INSTRUCTION_ENGINES:
value = stored[engine]
if isinstance(value, str) and (
value == BUILTIN_INSTRUCTIONS_ID or value in ids
):
chosen[engine] = value
else:
config_logger.warning(
f"autotag.defaults.default_instructions.{engine} names no "
"saved instructions; using Built-in"
)
cls._migrate_template(
entries,
chosen,
first=damaged or "instructions" not in defaults,
keep_defaults=not damaged and "default_instructions" in defaults,
)
cls.INSTRUCTIONS = tuple(entries)
cls.DEFAULT_INSTRUCTIONS = chosen
@classmethod
def _migrate_template(cls, entries, chosen, *, first, keep_defaults) -> None:
"""Bring a template saved by an older build in as a named entry."""
legacy = cls._LEGACY_TEMPLATE
if legacy is None or legacy == DEFAULT_TAG_TEMPLATE:
return
if first:
# The first upgrade: it becomes "Custom template", the default for
# both engines unless defaults are stored already (20A).
entries.append(
{"id": _text_id(legacy), "name": "Custom template", "text": legacy}
)
if not keep_defaults:
for engine in INSTRUCTION_ENGINES:
chosen[engine] = entries[-1]["id"]
return
if any(item["text"] == legacy for item in entries):
return # the mirror of a saved default
# Edited on an older build after an upgrade (B1.2): import it.
if len(entries) >= MAX_SAVED_INSTRUCTIONS:
config_logger.warning(
"The tagging template edited on an older version was not imported: "
f"the saved instructions are full ({MAX_SAVED_INSTRUCTIONS})"
)
return
names = {item["name"].casefold() for item in entries}
number = 2
while f"custom template ({number})" in names:
number += 1
name = f"Custom template ({number})"
ids = {item["id"] for item in entries}
new_id, n = _text_id(legacy), 2
while new_id in ids:
new_id, n = _text_id(f"{legacy}\n{n}"), n + 1
entries.append({"id": new_id, "name": name, "text": legacy})
config_logger.info(
"Imported the tagging template edited on an older version as " f"'{name}'"
)
@classmethod
def update_config(cls, new_config: Any) -> None:
if not isinstance(new_config, dict):
@@ -892,9 +698,12 @@ class AutotagConfig:
try:
setattr(cls, attr, validate(defaults[key]))
except ValueError as error:
config_logger.warning(_fallback_warning(key, error, default))
config_logger.warning(
f"autotag.defaults.{key} {error}; using {default!r}"
if key != "template"
else f"autotag.defaults.template {error}; using the built-in one"
)
setattr(cls, attr, default)
cls._load_instructions(defaults)
class PromptManagerConfig:
@@ -1081,6 +890,35 @@ class PromptManagerConfig:
else:
config_logger.info(f"Config file not found: {config_path}, using defaults")
@classmethod
def save_to_file(cls, config_path: Optional[str] = None):
"""Save the current configuration to a JSON file.
Serializes the complete configuration (including gallery settings) to
a JSON file. Creates the directory structure if it doesn't exist.
Args:
config_path (str): Path where the JSON configuration file should be saved.
Parent directories will be created if they don't exist.
Defaults to :meth:`get_config_path`.
Raises:
The method handles all exceptions internally and logs errors rather
than propagating them.
Example:
PromptManagerConfig.save_to_file('backup_config.json')
PromptManagerConfig.save_to_file('/etc/comfyui/prompt_manager.json')
"""
if config_path is None:
config_path = cls.get_config_path()
try:
write_private_json(config_path, cls.get_config())
config_logger.info(f"Saved configuration to {config_path}")
except Exception as e:
config_logger.error(f"Error saving config to {config_path}: {e}")
@classmethod
def update_config(cls, new_config: Dict[str, Any]):
"""Update configuration attributes from a dictionary.
+9 -27
View File
@@ -111,29 +111,23 @@ def preview(
"""The review's counts (blocking; reads only, requests nothing).
``{lora_files, with_metadata, skipped, with_local_media,
planned_downloads, trigger_tags, trigger_not_tags, fingerprint, names,
layout}``: the metadata files seen, the kept LoRAs whose sidecar parses,
the rest, the LoRAs with a local image, the CivitAI images an import would
download for the LoRAs without one (not yet in the cache), the trained-words
entries that become tags and those that do not (#618), the first LoRA
names and what the layout says (``layout_summary``).
planned_downloads, fingerprint, names, layout}``: the metadata files
seen, the kept LoRAs whose sidecar parses, the rest, the LoRAs with a
local image, the CivitAI images an import would download for the LoRAs
without one (not yet in the cache), the first LoRA names and what the
layout says (``layout_summary``).
"""
discovery = discover(lora_manager_path)
layout = discovery.layout
with_metadata = 0
with_local_media = 0
planned = 0
trigger_tags = 0
trigger_not_tags = 0
names = []
for sidecar in discovery.sidecars:
metadata = lora_utils.read_lora_metadata(sidecar.metadata_path)
if not metadata:
continue
with_metadata += 1
words, not_tags = lora_utils.trigger_word_tags(metadata)
trigger_tags += len(words)
trigger_not_tags += not_tags
if local_media(sidecar, metadata, layout, media_extensions):
with_local_media += 1
else:
@@ -148,8 +142,6 @@ def preview(
"skipped": discovery.scanned - with_metadata,
"with_local_media": with_local_media,
"planned_downloads": planned,
"trigger_tags": trigger_tags,
"trigger_not_tags": trigger_not_tags,
"fingerprint": fingerprint(discovery),
"names": names,
"layout": layout_summary(layout, Path.home()),
@@ -157,22 +149,17 @@ def preview(
def build_record(metadata: Dict, path: Path, images: List[str]) -> Dict:
"""The prompt a LoRA becomes: its example prompt (else its name), tags, images.
Only the trained words that are one short clean phrase become tags
(#618, ``lora_utils.is_tag_phrase``); ``trigger_not_tags`` counts the rest.
"""
"""The prompt a LoRA becomes: its example prompt (else its name), tags, images."""
model_name = lora_utils.get_model_name_from_metadata(metadata)
text = lora_utils.get_example_prompt_from_metadata(metadata) or model_name
words, not_tags = lora_utils.trigger_word_tags(metadata)
tags = ["lora-manager", f"lora:{model_name}", *words]
tags = ["lora-manager", f"lora:{model_name}"]
tags.extend(lora_utils.get_trigger_words_from_metadata(metadata))
return {
"name": model_name,
"text": text,
"hash": generate_prompt_hash(text),
"tags": list(dict.fromkeys(tags)),
"images": images,
"trigger_not_tags": not_tags,
}
@@ -184,11 +171,7 @@ class StagedImport:
records: List[Dict] = field(default_factory=list)
skipped: List[str] = field(default_factory=list)
stats: Dict[str, int] = field(
default_factory=lambda: {
"downloaded": 0,
"download_errors": 0,
"trigger_not_tags": 0,
}
default_factory=lambda: {"downloaded": 0, "download_errors": 0}
)
@@ -236,7 +219,6 @@ def stage(
images = list(dict.fromkeys([*local, *remote]))
record = build_record(metadata, path, images)
staged.records.append(record)
staged.stats["trigger_not_tags"] += record["trigger_not_tags"]
except Exception as error: # one LoRA never stops the import
name = lora_utils.get_model_name_from_metadata(metadata)
if logger is not None:
-40
View File
@@ -22,13 +22,11 @@ from urllib.parse import urljoin, urlsplit
try:
from ..utils.logging_config import get_logger
from ..utils.validators import validate_tags
except ImportError:
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utils.logging_config import get_logger
from utils.validators import validate_tags
from dataclasses import replace
@@ -389,44 +387,6 @@ def get_trigger_words_from_metadata(metadata: Dict) -> List[str]:
return []
# #618: what a prompt weight looks like, ``(masterpiece:1.2)``: an instruction
# to the sampler, never a label.
_PROMPT_WEIGHT = re.compile(r"\([^()]*:\s*-?\d*\.?\d+\s*\)")
# The ASCII and the fullwidth comma: an entry holding either is a list.
_COMMAS = (",", ",")
def is_tag_phrase(entry: object) -> bool:
"""Whether a trained-words entry is one short clean phrase (#618, Option A).
The existing tag rule (``validate_tags``: not empty, at most 50
characters, no control character), and no comma (ASCII or fullwidth), no
``<``/``>`` (``<lora:name:0.8>`` loads a model) and no prompt weight.
Plain parentheses stay allowed (``hatsune miku (vocaloid)``).
"""
if not isinstance(entry, str):
return False
phrase = entry.strip()
try:
validate_tags([phrase])
except ValueError:
return False
if any(comma in phrase for comma in _COMMAS):
return False
if "<" in phrase or ">" in phrase:
return False
return _PROMPT_WEIGHT.search(phrase) is None
def trigger_word_tags(metadata: Dict) -> Tuple[List[str], int]:
"""``(tags, not_tags)``: the trigger words that are tag phrases, stripped
and in order, and how many were not (#618). The trigger-word lookup
(``get_trigger_words_from_metadata``) still sees every entry."""
words = get_trigger_words_from_metadata(metadata)
tags = [word for word in words if is_tag_phrase(word)]
return tags, len(words) - len(tags)
def get_example_prompt_from_metadata(metadata: Dict) -> Optional[str]:
"""Extract an example prompt from civitai image metadata.
+1 -233
View File
@@ -4,13 +4,8 @@ Server-free on purpose: ``py.api`` must import without ComfyUI's ``server``
module, which ``py/config.py`` needs; config re-exports all of this.
"""
import csv
import math
import os
import re
import threading
import unicodedata
from typing import Any, Dict, Iterable, List, Set, Tuple
from typing import Any
# The tagging engines (``py/autotag.py`` MODELS) and the options they take.
WD14_MODEL_TYPES = frozenset({"wd14-swinv2", "wd14-vit"})
@@ -93,230 +88,3 @@ def validate_template(value: Any, name: str = "instructions") -> str:
if len(encoded) > MAX_INSTRUCTION_BYTES:
raise ValueError(f"{name} {'are' if name == 'instructions' else 'is'} too long")
return value
# Skipped tags (#431): words whose suggested tags are never offered.
MAX_SKIPPED_TAGS = 200
MAX_SKIPPED_TAG_CHARS = 50
_WORD_SEPARATORS = re.compile(r"[ _-]+")
_FORBIDDEN_IN_ENTRY = re.compile(r"[,\x00-\x1f\x7f-\x9f\u2028\u2029]")
def tag_words(text: str) -> Tuple[str, ...]:
"""The words of a tag or a skipped entry: NFC, case-folded, split on runs
of space, ``_`` and ``-``. Every other character belongs to a word."""
folded = unicodedata.normalize("NFC", text).casefold()
return tuple(word for word in _WORD_SEPARATORS.split(folded) if word)
def validate_skipped_tags(value: Any) -> List[str]:
"""The Skipped tags list, each entry trimmed, or ValueError with the
sentence the System page shows (entries are numbered from 1)."""
if not isinstance(value, list):
raise ValueError("Skipped tags must be a list of words.")
if len(value) > MAX_SKIPPED_TAGS:
raise ValueError(f"Skipped tags: at most {MAX_SKIPPED_TAGS} entries.")
entries: List[str] = []
seen: Dict[Tuple[str, ...], int] = {}
for number, raw in enumerate(value, 1):
if not isinstance(raw, str):
raise ValueError(f"Skipped tags: entry {number} must be text.")
entry = raw.strip()
if not entry:
raise ValueError(f"Skipped tags: entry {number} is empty.")
if len(entry) > MAX_SKIPPED_TAG_CHARS:
raise ValueError(
f"Skipped tags: entry {number} must be at most "
f"{MAX_SKIPPED_TAG_CHARS} characters."
)
if _FORBIDDEN_IN_ENTRY.search(entry):
raise ValueError(
f"Skipped tags: entry {number} must not contain a comma "
"or a line break."
)
words = tag_words(entry)
if not words:
raise ValueError(f"Skipped tags: entry {number} is empty.")
if words in seen:
raise ValueError(
f"Skipped tags: entry {number} repeats entry {seen[words]}."
)
seen[words] = number
entries.append(entry)
return entries
class SkipMatcher:
"""Whether a suggested tag contains a skipped entry's words, consecutive
and whole (#431, 17B). Compiled once per request or job; the cost of a
check depends on the tag's words, not on the number of entries."""
def __init__(self, entries: Iterable[str] = ()):
self._entries = frozenset(filter(None, (tag_words(e) for e in entries)))
self._longest = max((len(words) for words in self._entries), default=0)
def __bool__(self) -> bool:
return bool(self._entries)
def matches(self, name: str) -> bool:
if not self._entries:
return False
words = tag_words(name)
for start in range(len(words)):
stop = min(len(words), start + self._longest)
for end in range(start + 1, stop + 1):
if words[start:end] in self._entries:
return True
return False
def counting(self) -> "CountingSkip":
"""A per-request view that also remembers which names it hid."""
return CountingSkip(self)
class CountingSkip:
"""A :class:`SkipMatcher` that records the distinct names it hid, so the
Tag image dialog can say how many skipped tags were not suggested."""
def __init__(self, matcher: SkipMatcher):
self._matcher = matcher
self.hidden: Set[str] = set()
def matches(self, name: str) -> bool:
if self._matcher.matches(name):
self.hidden.add(name.casefold())
return True
return False
# A WD14 label list's tags the engine can suggest: general (0) and character (4).
WD14_SUGGESTED_CATEGORIES = frozenset({"0", "4"})
_label_cache: Dict[str, Tuple[Tuple[int, int], Tuple[str, ...]]] = {}
_label_cache_lock = threading.Lock()
def read_wd14_label_rows(path) -> List[Dict[str, str]]:
"""Every row of a WD14 ``selected_tags.csv``, read as UTF-8 and closed
before returning (the handle never outlives the call, for Windows)."""
with open(path, "r", encoding="utf-8", newline="") as handle:
return list(csv.DictReader(handle))
def wd14_label_names(path) -> Tuple[str, ...]:
"""The names a WD14 label list can suggest (categories 0 and 4), cached
by ``(mtime_ns, size)``. OSError (missing) and ValueError (unreadable)
propagate; the caller skips that list."""
key = os.fspath(path)
stat = os.stat(key)
stamp = (stat.st_mtime_ns, stat.st_size)
with _label_cache_lock:
cached = _label_cache.get(key)
if cached is not None and cached[0] == stamp:
return cached[1]
try:
rows = read_wd14_label_rows(key)
except csv.Error as exc: # a damaged list (a NUL byte, an oversized field)
raise ValueError(f"unreadable label list: {exc}") from None
names = tuple(
name
for row in rows
if row.get("category", "0") in WD14_SUGGESTED_CATEGORIES
and (name := (row.get("name") or "").strip())
)
with _label_cache_lock:
_label_cache[key] = (stamp, names)
return names
# Saved instructions (#431): named language-model instructions with a default
# per engine. Built-in is never stored; readers put it first.
BUILTIN_INSTRUCTIONS_ID = "builtin"
BUILTIN_INSTRUCTIONS_NAME = "Built-in"
MAX_SAVED_INSTRUCTIONS = 20
MAX_INSTRUCTION_NAME_CHARS = 60
INSTRUCTION_ENGINES = ("gguf", "hf")
ENGINE_LABELS = {"gguf": "GGUF JoyCaption", "hf": "HuggingFace JoyCaption"}
_INSTRUCTION_ID = re.compile(r"[0-9a-f]{12}")
_CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f

]")
def builtin_instructions() -> Dict[str, str]:
"""The read-only Built-in entry, always the shipped template."""
return {
"id": BUILTIN_INSTRUCTIONS_ID,
"name": BUILTIN_INSTRUCTIONS_NAME,
"text": DEFAULT_TAG_TEMPLATE,
}
def _instruction_entry(raw: Any, number: int) -> Dict[str, str]:
prefix = f"Saved instructions: entry {number}"
if (
not isinstance(raw, dict)
or set(raw) != {"id", "name", "text"}
or not isinstance(raw["id"], str)
or _INSTRUCTION_ID.fullmatch(raw["id"]) is None
):
raise ValueError(f"{prefix} has an invalid id.")
name = raw["name"].strip() if isinstance(raw["name"], str) else ""
if not name:
raise ValueError(f"{prefix} needs a name.")
if len(name) > MAX_INSTRUCTION_NAME_CHARS:
raise ValueError(
f"{prefix} name must be at most {MAX_INSTRUCTION_NAME_CHARS} characters."
)
if _CONTROL.search(name):
raise ValueError(f"{prefix} name must not contain a line break.")
if name.casefold() == BUILTIN_INSTRUCTIONS_NAME.casefold():
raise ValueError("Saved instructions: the name “Built-in” is reserved.")
try:
text = validate_template(raw["text"], f"{prefix} text")
except ValueError as error:
raise ValueError(f"{error}.") from None
return {"id": raw["id"], "name": name, "text": text}
def validate_instructions(value: Any) -> List[Dict[str, str]]:
"""The saved entries ``[{id, name, text}]`` in order (names trimmed), or
ValueError with the sentence System shows (Built-in is not counted)."""
if not isinstance(value, list):
raise ValueError("Saved instructions must be a list.")
if len(value) > MAX_SAVED_INSTRUCTIONS:
raise ValueError(
f"Saved instructions: at most {MAX_SAVED_INSTRUCTIONS} entries besides "
"Built-in."
)
entries: List[Dict[str, str]] = []
ids: Dict[str, int] = {}
names: Dict[str, int] = {}
for number, raw in enumerate(value, 1):
item = _instruction_entry(raw, number)
if item["id"] in ids:
raise ValueError(
f"Saved instructions: entry {number} repeats the id of entry "
f"{ids[item['id']]}."
)
key = item["name"].casefold()
if key in names:
raise ValueError(
f"Saved instructions: entry {number} name “{item['name']}” is "
"already used."
)
ids[item["id"]] = number
names[key] = number
entries.append(item)
return entries
def validate_default_instructions(value: Any, entries) -> Dict[str, str]:
"""``{gguf: id, hf: id}``, each Built-in or an id of ``entries``."""
if not isinstance(value, dict) or set(value) != set(INSTRUCTION_ENGINES):
raise ValueError("Default instructions must name GGUF and HuggingFace.")
ids = {BUILTIN_INSTRUCTIONS_ID} | {item["id"] for item in entries}
for engine in INSTRUCTION_ENGINES:
if not isinstance(value[engine], str) or value[engine] not in ids:
raise ValueError(
f"Default for {ENGINE_LABELS[engine]} must be one of the saved "
"instructions."
)
return {engine: value[engine] for engine in INSTRUCTION_ENGINES}
+3 -4
View File
@@ -1,11 +1,10 @@
[project]
name = "promptmanager"
description = "A powerful ComfyUI custom node that extends the standard text encoder with persistent prompt storage, advanced search capabilities, and an automatic image gallery system using SQLite."
version = "3.8.0"
version = "3.4.1"
license = {file = "LICENSE"}
requires-python = ">=3.12"
dependencies = ["watchdog>=2.1.0", "Pillow>=10.1.0"]
classifiers = ["Operating System :: OS Independent"]
dependencies = ["watchdog>=2.1.0", "Pillow>=8.0.0"]
[build-system]
requires = ["setuptools>=84.2.1"]
@@ -18,7 +17,7 @@ Repository = "https://github.com/ComfyAssets/ComfyUI_PromptManager"
[tool.comfy]
PublisherId = "kiko9"
DisplayName = "ComfyUI_PromptManager"
Icon = "https://raw.githubusercontent.com/ComfyAssets/ComfyUI_PromptManager/main/assets/brand/icon-256.png"
Icon = "https://avatars.githubusercontent.com/u/213204677?s=200"
[tool.black]
line-length = 88
+7 -7
View File
@@ -1,18 +1,18 @@
# Runtime dependencies (Pillow, aiohttp and numpy floors match ComfyUI requirements.txt)
# Runtime dependencies
watchdog>=6.0.0
Pillow>=10.1.0
aiohttp>=3.11.8
Pillow>=12.3.0
aiohttp>=3.14.5
# Tests and coverage
coverage>=7.17.2
numpy>=1.25.0 # WD14 engine tests
coverage>=7.16.2
numpy>=2.2.6 # WD14 engine tests
# Code quality
black==26.10.1
flake8==7.5.0
flake8==7.4.1
# Security scanning
bandit[toml]>=1.9.4
# Pre-commit hooks
pre-commit>=4.7.0
pre-commit>=4.6.2
+1 -1
View File
@@ -1,4 +1,4 @@
# Runtime dependencies for PromptManager.
# aiohttp, numpy and torch come from ComfyUI itself and are not listed here.
watchdog>=2.1.0 # Output directory monitoring
Pillow>=10.1.0 # Image metadata extraction and thumbnails
Pillow>=8.0.0 # Image metadata extraction and thumbnails
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

+3 -2
View File
@@ -8,8 +8,9 @@
// browser that exits abnormally prints one `pm-browser-exit|` line, and a test
// that fails on a closed or crashed target gets that log attached as
// `browser-stderr`.
// The one-time older-images notice (#527) shows above every workspace page until
// dismissed, so every context starts with it dismissed. A spec about the notice sets `test.use({ olderImagesNotice: true })`.
// The one-time older-images notice (#527) shows above every workspace page and as
// a modal on the admin page until dismissed, so every context starts with it
// dismissed. A spec about the notice sets `test.use({ olderImagesNotice: true })`.
import { test as base, expect } from '../../tools/vendor/node_modules/@playwright/test/index.mjs';
import { attachServerStderr, createServerSupervisor, startBrowserServer } from '../../tools/vendor/start-browser-server.mjs';
import { attachBrowserLogs, createBrowserLogRecorder } from '../../tools/vendor/browser-logs.mjs';
-121
View File
@@ -1,121 +0,0 @@
// #659 (design Part 5): Inspect's Choose prompt. A queued ambiguous file (tests/browser/workspace_review_fixture.py,
// recorded through the scan's recorder) shows its candidates in the Images details panel; choosing one links the file
// and takes it out of Needs review, leaving it unresolved decides it, and an item with nothing to choose sends the user
// to Needs review.
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
import { test, expect } from './fixtures.mjs';
const images = '/prompt_manager/workspace#/images';
const details = page => page.getByRole('complementary', { name: 'Selected image details', exact: true });
const choice = page => details(page).getByRole('region', { name: 'Choose prompt', exact: true });
const context = page => choice(page).getByRole('combobox', { name: 'Sampler context', exact: true });
const toast = page => page.locator('#workspace-toast');
const OPTIONS = ['Sampler 11 · Golden dunes at dusk / Soft negative, blur', 'Sampler 13 · Harbor lights at night / Soft negative, blur'];
async function seed(request, data) {
const response = await request.post('/__test__/review/reset', { data });
await expect(response).toBeOK();
return response.json();
}
const pending = async request => (await (await request.get('/prompt_manager/review/items?limit=1')).json()).total;
const links = async request => (await (await request.get('/__test__/review/links')).json()).links;
/** The Images page with `filename`'s details open (a page may already have selected it). */
async function inspect(page, filename) {
await page.goto(images);
const card = page.locator('article[data-image-key]').filter({ hasText: filename });
await card.getByRole('button', { name: `Inspect ${filename}`, exact: true }).click();
await expect(details(page).locator('.detail-inner > p.small').first()).toHaveText(filename);
}
test.beforeEach(async ({ page, browserName }) => {
await startCoverage(page, browserName);
page.choiceErrors = [];
page.on('pageerror', error => page.choiceErrors.push(error.message));
});
test.afterEach(async ({ page, browserName, request }) => {
await saveCoverage(page, browserName);
expect(page.choiceErrors).toEqual([]);
await request.post('/__test__/jobs/restart');
});
test('choosing a candidate in Inspect links the file and takes it out of Needs review', async ({ page, request }) => {
await seed(request, { items: 1 });
expect(await pending(request)).toBe(1);
await inspect(page, 'review_0000.png');
// The section follows the file's own prompt blocks.
await expect(choice(page)).toBeVisible();
await expect(details(page).locator('.detail-inner > .inspect-choice')).toHaveCount(1);
await expect(context(page).locator('option')).toHaveText(OPTIONS);
await expect(choice(page).locator('.prompt-section.positive .prompt-text')).toHaveText('Golden dunes at dusk');
await context(page).selectOption({ label: OPTIONS[1] });
await expect(choice(page).locator('.prompt-section.positive .prompt-text')).toHaveText('Harbor lights at night');
await expect(choice(page).locator('.prompt-section.negative .prompt-text')).toHaveText('Soft negative, blur');
await expect(choice(page).getByRole('button', { name: 'Copy chosen positive prompt', exact: true })).toBeVisible();
await expect(choice(page).getByRole('button', { name: 'Send chosen positive prompt to ComfyUI', exact: true })).toBeVisible();
const decided = page.waitForResponse(response => /\/review\/items\/[^/]+\/decision$/.test(response.url()));
const reread = page.waitForResponse(response => response.url().includes('/prompt_manager/images/inspect/') && response.ok());
await choice(page).getByRole('button', { name: 'Use this prompt', exact: true }).click();
expect((await decided).status()).toBe(200);
await reread;
await expect(toast(page)).toHaveText('Association accepted.');
// The inspection is read again: the file is linked, so the section is gone and Prompt history opens its prompt.
await expect(choice(page)).toHaveCount(0);
await expect(details(page).getByRole('button', { name: 'Prompt history', exact: true })).toBeVisible();
expect(await pending(request)).toBe(0);
expect((await links(request)).map(row => [row.filename, row.prompt])).toEqual([['review_0000.png', 'Harbor lights at night']]);
await page.goto('/prompt_manager/workspace#/review');
await expect(page.locator('#workspace-main .notice h2')).toHaveText('No images need a decision');
});
test('Leave unresolved in Inspect decides the item and links nothing', async ({ page, request }) => {
await seed(request, { items: 2 });
await inspect(page, 'review_0001.png');
await expect(context(page).locator('option')).toHaveText(OPTIONS);
const decided = page.waitForResponse(response => /\/review\/items\/[^/]+\/decision$/.test(response.url()));
await choice(page).getByRole('button', { name: 'Leave unresolved', exact: true }).click();
expect((await decided).status()).toBe(200);
await expect(toast(page)).toHaveText('Left unresolved.');
// The item is decided: the section is gone and the file stays unlinked.
await expect(choice(page)).toHaveCount(0);
await expect(details(page).getByRole('button', { name: 'Prompt history', exact: true })).toHaveCount(0);
expect(await pending(request)).toBe(1);
expect(await links(request)).toEqual([]);
});
test('an item with nothing to choose offers Open in Needs review', async ({ page, request }) => {
await seed(request, { items: 0, limited: true });
await inspect(page, 'limited.png');
await expect(choice(page)).toContainText('None of the possible prompts can be applied here. Decide this image in Needs review.');
await expect(context(page)).toBeHidden();
await expect(choice(page).getByRole('button', { name: 'Use this prompt', exact: true })).toBeHidden();
await choice(page).getByRole('button', { name: 'Open in Needs review', exact: true }).click();
await expect(page).toHaveURL(/#\/review$/);
await expect(page.locator('#workspace-main .notice h2')).toHaveText('1 image needs a decision');
});
test('the viewer details show the same Choose prompt', async ({ page, request }) => {
await seed(request, { items: 1 });
await page.goto(images);
const card = page.locator('article[data-image-key]').filter({ hasText: 'review_0000.png' });
await card.getByRole('button', { name: 'Open review_0000.png', exact: true }).click();
const viewer = page.locator('#viewer-dialog');
await expect(viewer).toBeVisible();
const section = viewer.getByRole('region', { name: 'Choose prompt', exact: true });
await expect(section.getByRole('combobox', { name: 'Sampler context', exact: true }).locator('option')).toHaveText(OPTIONS);
// Open in Needs review is offered only when nothing can be chosen.
await expect(section.getByRole('button', { name: 'Open in Needs review', exact: true })).toBeHidden();
});
test('#657 D3: Choose prompt says when the file\'s prompts were shortened to the most used', async ({ page, request }) => {
await seed(request, { items: 1 });
await page.route(url => /\/prompt_manager\/review\/items\/[0-9a-f-]{36}$/.test(url.pathname), async route => {
const response = await route.fetch();
await route.fulfill({ response, json: { ...(await response.json()), collapsed: { shown: 2, total: 81, paths: 165 } } });
});
await inspect(page, 'review_0000.png');
await expect(context(page).locator('option')).toHaveText(OPTIONS);
await expect(choice(page).locator('.review-collapsed')).toHaveText('Showing the 2 most used of 81 prompts in this file.');
});
+182
View File
@@ -0,0 +1,182 @@
// #328: the legacy admin and gallery auto-tag batch and review keep working beside System › Auto-tagging. Since #330
// the pages download and unload models only through System (legacy-system-links.spec.mjs); a batch never downloads
// one. The fixture's fake download (`/__test__/tagging/download`) is held so nothing is ever fetched.
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
import { test, expect } from './fixtures.mjs';
async function post(request, url, data) {
await expect(await request.post(url, data === undefined ? {} : { data })).toBeOK();
}
async function downloads(request) {
const response = await request.get('/prompt_manager/jobs');
await expect(response).toBeOK();
return (await response.json()).jobs.filter(job => job.kind === 'model_download');
}
test.beforeEach(async ({ page, request, browserName }) => {
await startCoverage(page, browserName);
// The 3.2.0 update notice would cover the admin page's toolbar.
await page.addInitScript(() => { localStorage.setItem('pm_update_notice_dismissed', '3.2.0'); });
await post(request, '/__test__/jobs/restart');
await post(request, '/__test__/tagging/reset');
await post(request, '/__test__/tagging/models', { unavailable: ['wd14-vit'] });
await post(request, '/__test__/tagging/download', { mode: 'hold' });
});
test.afterEach(async ({ page, request, browserName }) => {
await saveCoverage(page, browserName);
// Releases a download a failed test left held, and puts the raising default back.
await post(request, '/__test__/tagging/reset');
await post(request, '/__test__/jobs/restart');
});
// (wd14-vit is not downloaded in these tests: beforeEach marks it so the download tests can offer it.)
// The gallery's batch reader keyed on `data.status` values the server never sends, so its modal never moved or
// closed (#328 Problem 5). It now reads `type` frames as the admin page does.
async function watchProgress(page) {
await page.evaluate(() => {
window.progressSeen = [];
const node = document.getElementById('autoTagProgressPercent');
// Each change from its own record: frames that land in one task share one
// callback, and the node's text by then is only the last of them.
new MutationObserver(records => {
for (const record of records) {
if (record.type === 'characterData') window.progressSeen.push(record.target.data);
for (const added of record.addedNodes) window.progressSeen.push(added.textContent);
}
}).observe(node, { childList: true, characterData: true, subtree: true });
});
}
async function runGalleryBatch(page) {
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
await watchProgress(page);
const done = page.waitForResponse(response => response.url().includes('/prompt_manager/autotag/start'));
await page.locator('#startAutoTagBtn').click();
await done;
await expect(page.locator('#autoTagProgressModal')).toBeHidden();
// #379: the batch counts images, never prompts.
await expect(page.getByText(/^Auto tagging complete! Tagged \d+ images?\.$/)).toBeVisible();
}
const CLOSE_NOTE = 'Closing this window stops tagging. Tags already added are kept. Prompt Manager\'s Activity page shows the '
+ 'time left.';
async function serverJobs(request) {
const response = await request.get('/prompt_manager/jobs');
await expect(response).toBeOK();
return (await response.json()).jobs;
}
async function runNativeBatch(request) {
const started = await request.post('/prompt_manager/jobs/autotag', { data: { model_type: 'wd14-swinv2', existing: 'skip',
options: { general_threshold: 0.35, character_threshold: 0.85 } } });
expect(started.status()).toBe(202);
const { job } = await started.json();
await expect.poll(async () => (await serverJobs(request)).find(item => item.id === job.id)?.state).toBe('finished');
}
test('gallery batch modal counts progress and closes on complete', async ({ page, request }) => {
await page.goto('/prompt_manager/gallery');
await runGalleryBatch(page);
const seen = await page.evaluate(() => window.progressSeen);
// The phase frames (model 5%, listing 8%) then the per-image frames (from 10%) move the bar.
expect(seen).toContain('8%');
expect(seen.some(value => parseInt(value, 10) >= 10)).toBe(true);
await expect(page.locator('#autoTagCloseNote')).toHaveText(CLOSE_NOTE);
// The batch ran as the autotag job of the legacy page.
expect((await serverJobs(request)).filter(job => job.kind === 'autotag').map(job => [job.title, job.state]))
.toEqual([['Tag output images (legacy page)', 'finished']]);
expect((await downloads(request)).length).toBe(0);
});
test('admin batch copy names images, not prompts (#379)', async ({ page }) => {
await page.goto('/prompt_manager/admin');
await page.locator('#autoTagBtn').click();
await expect(page.locator('input[name="autoTagMode"][value="skip"] + span')).toHaveText('Skip images already auto-tagged');
await expect(page.getByText('"auto-scanned" is not counted as a real tag')).toHaveCount(0);
await expect(page.locator('#autoTagCloseNote')).toHaveText(CLOSE_NOTE);
await expect(page.locator('#retagConfirmModal h3')).toHaveText('Image Already Auto-tagged');
await expect(page.locator('#retagConfirmModal')).toContainText('A tagging model already tagged this image. Generate new tags?');
});
test('admin review opens the first image', async ({ page }) => {
await page.goto('/prompt_manager/admin');
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
await page.locator('#startReviewBtn').click();
// #379: no image is auto-tagged yet (prompt tags no longer count), so the review opens on the first image.
await expect(page.locator('#retagConfirmModal')).toBeHidden();
await expect(page.locator('#autoTagReviewModal')).toBeVisible();
await expect(page.locator('#reviewImageName')).not.toHaveText(/^(image_name\.png|Unknown|)$/);
await expect(page.getByText('Failed to start review mode')).toHaveCount(0);
});
/** The admin review lists every row, videos too: Skip any image that is not one until the confirmation shows. */
async function untilAutoTagged(page, confirm) {
// Each image's skip check answers before its confirmation or its error shows.
const failed = page.locator('#reviewTagsVisible .text-pm-error');
for (let tries = 0; tries < 5; tries++) {
await expect.poll(async () => (await confirm.isVisible()) || (await failed.count()) > 0).toBe(true);
if (await confirm.isVisible()) return;
const answered = page.waitForResponse(item => item.url().endsWith('/prompt_manager/autotag/single'));
await page.locator('#skipReviewBtn').click();
await answered;
}
await expect(confirm).toBeVisible();
}
// #379: the admin review asks before re-tagging an image a model already tagged, and Apply & Next writes that image's
// tags (its bytes, never its prompt).
test('admin review: an auto-tagged image asks first; Re-tag then Apply & Next tags the image', async ({ page, request }) => {
await runNativeBatch(request);
await page.goto('/prompt_manager/admin');
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
await page.locator('#startReviewBtn').click();
const confirm = page.locator('#retagConfirmModal');
await untilAutoTagged(page, confirm);
await expect(confirm.locator('#retagExistingTags span').first()).toHaveText('sandstone');
await page.locator('#retagConfirmBtn').click();
await expect(page.locator('#autoTagReviewModal')).toBeVisible();
await expect(page.locator('#reviewTagsVisible .tag-chip').first()).toContainText('sandstone');
const applied = page.waitForRequest(item => item.url().endsWith('/prompt_manager/autotag/apply'));
const answer = page.waitForResponse(item => item.url().endsWith('/prompt_manager/autotag/apply'));
await page.locator('#applyReviewBtn').click();
const body = (await applied).postDataJSON();
expect(body.prompt_id).toBeUndefined();
expect(body.sha256).toMatch(/^[0-9a-f]{64}$/);
expect((await answer).status()).toBe(200);
});
test('admin review: Skip All Tagged passes every auto-tagged image', async ({ page, request }) => {
await runNativeBatch(request);
await page.goto('/prompt_manager/admin');
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
await page.locator('#startReviewBtn').click();
const confirm = page.locator('#retagConfirmModal');
await untilAutoTagged(page, confirm);
await page.locator('#retagSkipAllBtn').click();
await expect(page.locator('#retagConfirmModal')).toBeHidden();
await expect(page.getByText('Review complete!')).toBeVisible();
});
test('gallery review: Apply & Next tags the image by its path and bytes', async ({ page }) => {
await page.goto('/prompt_manager/gallery');
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
const suggested = page.waitForRequest(item => item.url().endsWith('/prompt_manager/autotag/single'));
await page.locator('#startReviewBtn').click();
expect((await suggested).postDataJSON().existing).toBe('merge');
await expect(page.locator('#reviewTagsContainer .tag-chip').first()).toContainText('sandstone');
const applied = page.waitForRequest(item => item.url().endsWith('/prompt_manager/autotag/apply'));
const answer = page.waitForResponse(item => item.url().endsWith('/prompt_manager/autotag/apply'));
await page.locator('#applyReviewBtn').click();
const body = (await applied).postDataJSON();
expect(Object.keys(body).sort()).toEqual(['path', 'root_index', 'sha256', 'tags'].filter(key => key in body).sort());
expect(body.prompt_id).toBeUndefined();
expect((await answer).status()).toBe(200);
});
+286
View File
@@ -0,0 +1,286 @@
// System S13 (#330): the legacy admin and gallery pages open native System for their System tools. Each replaced
// control is a plain link (`workspace#/system/<id>`, a new tab), and the legacy flows S13 keeps still work.
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
import { test, expect } from './fixtures.mjs';
const PAGES = Object.freeze({ admin: '/prompt_manager/admin', gallery: '/prompt_manager/gallery' });
const LABELS = Object.freeze({
overview: 'Overview',
appearance: 'Appearance',
sources: 'Sources & scans',
integrations: 'Integrations',
tagging: 'Auto-tagging',
maintenance: 'Maintenance',
backups: 'Backup & export',
diagnostics: 'Diagnostics & logs',
});
async function openPageOptions(page) {
await page.locator('#pageOptionsBtn').click();
await expect(page.locator('#settingsModal')).toBeVisible();
}
/** The auto-tag modal with its model rows read from /autotag/models. */
async function openAutoTag(page) {
const read = page.waitForResponse(item => item.url().endsWith('/prompt_manager/autotag/models'));
await page.locator('#autoTagBtn').click();
await read;
await expect(page.locator('#autoTagModal')).toBeVisible();
}
const notDownloaded = (page, request) => post(request, '/__test__/tagging/models', { unavailable: ['gguf'] });
const modelLoaded = (page, request) => post(request, '/__test__/tagging/loaded', { model: 'wd14-vit' });
// One row per System link of the design's §2 map: the page, the control's label, how to find it, the section it opens
// and what a test must arrange before the control shows.
const LINKS = Object.freeze([
{ page: 'admin', label: 'Settings', locate: page => page.locator('#settingsBtn'), section: 'overview' },
{ page: 'admin', label: 'Maintenance', locate: page => page.locator('#maintenanceBtn'), section: 'maintenance' },
{ page: 'admin', label: 'Backup DB', locate: page => page.locator('#backupBtn'), section: 'backups' },
{ page: 'admin', label: 'Restore DB', locate: page => page.locator('#restoreBtn'), section: 'backups' },
{ page: 'gallery', label: 'Settings', locate: page => page.locator('#settingsBtn'), section: 'appearance' },
{ page: 'admin', label: 'Manage in System (model row)', arrange: notDownloaded, reveal: openAutoTag,
locate: page => page.locator('#ggufModelStatus a'), section: 'tagging' },
{ page: 'gallery', label: 'Manage in System (model row)', arrange: notDownloaded, reveal: openAutoTag,
locate: page => page.locator('#ggufModelStatus a'), section: 'tagging' },
{ page: 'gallery', label: 'Manage in System (Unload Model)', arrange: modelLoaded, reveal: openAutoTag,
locate: page => page.locator('#unloadModelBtn'), section: 'tagging' },
{ page: 'gallery', label: 'Page options Maintenance', reveal: openPageOptions,
locate: page => page.locator('#pageOptionsMaintenanceLink'), section: 'maintenance' },
{ page: 'gallery', label: 'Page options Sources & scans', reveal: openPageOptions,
locate: page => page.locator('#pageOptionsSourcesLink'), section: 'sources' },
{ page: 'admin', label: 'Diagnostics', locate: page => page.locator('#diagnosticsBtn'), section: 'diagnostics' },
{ page: 'admin', label: 'View Logs', locate: page => page.locator('#logsBtn'), section: 'diagnostics' },
]);
async function post(request, url, data) {
await expect(await request.post(url, data === undefined ? {} : { data })).toBeOK();
}
test.beforeEach(async ({ page, request, browserName }) => {
await startCoverage(page, browserName);
await post(request, '/__test__/reset');
await post(request, '/__test__/system/reset');
await post(request, '/__test__/tagging/reset');
// The 3.2.0 update notice would cover the admin page's toolbar.
await page.addInitScript(() => { localStorage.setItem('pm_update_notice_dismissed', '3.2.0'); });
page.legacyErrors = [];
page.on('pageerror', error => page.legacyErrors.push(error.message));
});
test.afterEach(async ({ page, request, browserName }) => {
await saveCoverage(page, browserName);
await post(request, '/__test__/tagging/reset');
await post(request, '/__test__/system/reset');
expect(page.legacyErrors).toEqual([]);
});
/** Opens the legacy page with the link showing; returns the link. */
async function openLink(page, request, link) {
if (link.arrange) await link.arrange(page, request);
await page.goto(PAGES[link.page]);
if (link.reveal) await link.reveal(page);
const control = link.locate(page);
await expect(control).toBeVisible();
return control;
}
// Each row opens its section in a new tab and sends no request from the legacy page (the design's `a System link sends
// no request from the legacy page`, checked per row so one slow page never times out the whole table).
for (const link of LINKS) {
test(`legacy ${link.page} ${link.label} opens System ${link.section}`, async ({ page, context, request }) => {
// The gallery's thumbnail startup check (K9) reads its status on a timer of its own; it is off here.
await page.addInitScript(() => {
localStorage.setItem('gallerySettings', JSON.stringify({ checkThumbnailsAtStartup: false }));
});
const control = await openLink(page, request, link);
const legacyUrl = page.url();
await expect(control).toHaveAttribute('href', `workspace#/system/${link.section}`);
await expect(control).toHaveAttribute('target', '_blank');
await expect(control).toHaveAttribute('rel', 'noopener');
// The page's own start-up reads (list, film strips, settings) finish first; then the click must add none.
// Lazy thumbnails may still load whenever the layout changes; they are not the click's.
await page.waitForLoadState('networkidle');
const sent = [];
const record = item => { if (item.resourceType() !== 'image') sent.push(`${item.method()} ${item.url()}`); };
page.on('request', record);
const opened = context.waitForEvent('page');
await control.click();
const system = await opened;
await expect(system).toHaveURL(new RegExp(`/prompt_manager/workspace#/system/${link.section}$`));
page.off('request', record);
expect(sent, 'a System link sends no request from the legacy page').toEqual([]);
// System's page heading is "System"; the open section is the pressed button of its section switcher.
const main = system.locator('#workspace-main');
await expect(main.getByRole('heading', { level: 1, name: 'System', exact: true })).toBeVisible();
await expect(main.getByRole('group', { name: 'System sections', exact: true })
.getByRole('button', { name: LABELS[link.section], exact: true })).toHaveAttribute('aria-pressed', 'true');
expect(page.url()).toBe(legacyUrl);
await system.close();
});
}
test('kept admin flows still work', async ({ page, context }) => {
await page.goto(PAGES.admin);
const texts = page.locator('#resultsList .prompt-text');
await expect(texts.first()).toBeVisible();
// K1: sorting reorders the list.
for (const [value, order] of [['text_asc', 1], ['text_desc', -1]]) {
const listed = page.waitForResponse(item => /\/prompt_manager\/(recent|search)\?/.test(item.url()) && item.url().includes(`sort=${value}`));
await page.locator('#sortBy').selectOption(value);
await listed;
await expect.poll(async () => {
const shown = await texts.allTextContents();
// The server sorts case-insensitively (SQLite NOCASE), not by locale.
const key = text => text.toLowerCase();
const sorted = [...shown].sort((a, b) => order * (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
return shown.length > 1 && shown.join('\n') === sorted.join('\n');
}).toBe(true);
}
// K3: Add Prompt saves a prompt the list then shows.
await page.locator('#addPromptBtn').click();
await page.locator('#addPromptText').fill('Kept flow lighthouse');
const saved = page.waitForResponse(item => item.request().method() === 'POST' && item.url().endsWith('/prompt_manager/save'));
await page.locator('#saveNewPromptBtn').click();
expect((await saved).ok()).toBe(true);
await expect(page.locator('#addPromptModal')).toBeHidden();
await expect(texts.filter({ hasText: 'Kept flow lighthouse' })).toBeVisible();
// K1: a search narrows the list, and a selection enables the bulk buttons.
const all = await texts.allTextContents();
const word = all[0].trim().split(/\s+/)[0];
const searched = page.waitForResponse(item => item.url().includes('/prompt_manager/search?') && item.url().includes('text='));
await page.locator('#searchText').fill(word);
await page.locator('#searchBtn').click();
await searched;
await expect.poll(async () => {
const shown = await texts.allTextContents();
return shown.length > 0 && shown.length < all.length && shown.every(text => text.toLowerCase().includes(word.toLowerCase()));
}).toBe(true);
await expect(page.locator('#bulkDeleteBtn')).toBeDisabled();
await page.locator('#resultsList .prompt-checkbox').first().check();
for (const id of ['#bulkDeleteBtn', '#bulkTagBtn', '#bulkCategoryBtn']) await expect(page.locator(id)).toBeEnabled();
// K4: Stats reads the statistics again; Export downloads the prompts.
const stats = page.waitForResponse(item => item.url().endsWith('/prompt_manager/stats') && item.ok());
await page.locator('#statsBtn').click();
await stats;
await expect(page.getByText('Stats refreshed successfully!')).toBeVisible();
const download = page.waitForEvent('download');
await page.locator('#exportBtn').click();
expect((await download).suggestedFilename()).toMatch(/^prompts-\d{4}-\d{2}-\d{2}\.json$/);
// K5: Scan Images opens its dialog (with the quick backup) without starting a scan.
await page.locator('#scanBtn').click();
await expect(page.locator('#scanModal')).toBeVisible();
await expect(page.locator('#quickBackupBtn')).toBeVisible();
await page.locator('#cancelScan').click();
await expect(page.locator('#scanModal')).toBeHidden();
// K7: Metadata and Gallery open their pages in a new tab.
for (const [id, path] of [['#metadataBtn', '/prompt_manager/gallery.html'], ['#galleryBtn', '/prompt_manager/gallery']]) {
const opened = context.waitForEvent('page');
await page.locator(id).click();
const tab = await opened;
await tab.waitForLoadState('domcontentloaded');
expect(new URL(tab.url()).pathname).toBe(path);
await tab.close();
}
});
test('Page options keeps the page-only settings admin', async ({ page, request }) => {
const before = (await (await request.get('/prompt_manager/settings')).json()).settings;
await page.goto(PAGES.admin);
await expect(page.locator('#resultsList .prompt-text').first()).toBeVisible();
await page.locator('#pageOptionsBtn').click();
const dialog = page.locator('#settingsModal');
await expect(dialog).toBeVisible();
await expect(dialog.locator('h3')).toHaveText('Page options');
// Exactly the page-only setting (G5): the list's Infinite Scrolling default.
expect(await dialog.locator('input, select, textarea').evaluateAll(fields => fields.map(field => field.id)))
.toEqual(['infiniteScrollDefault']);
await expect(page.locator('#infiniteScrollDefault')).not.toBeChecked();
await page.locator('#infiniteScrollDefault').check();
const saved = page.waitForRequest(item => item.method() === 'POST' && item.url().endsWith('/prompt_manager/settings'));
await page.locator('#saveSettings').click();
expect((await saved).postDataJSON()).toEqual({ infinite_scroll: true });
await expect(dialog).toBeHidden();
// The list header follows the saved default at once; nothing else changed.
await expect(page.locator('#infiniteScrollSession')).toBeChecked();
const after = (await (await request.get('/prompt_manager/settings')).json()).settings;
expect(after).toEqual({ ...before, infinite_scroll: true });
await page.reload();
// The dialog shows the saved default once the page has read it (the header follows it first).
await expect(page.locator('#infiniteScrollSession')).toBeChecked();
await page.locator('#pageOptionsBtn').click();
await expect(page.locator('#infiniteScrollDefault')).toBeChecked();
});
test('Page options keeps the page-only settings gallery', async ({ page }) => {
// Native Appearance keys and the startup prompt's own keys are in the shared object before the page opens.
const stored = { imageQuality: 'high', showImageInfo: false, videoMute: false,
autoLoadMetadata: false, workspaceLayout: 'masonry', thumbnailPromptDismissed: 'sig', thumbnailsGenerated: true,
checkThumbnailsAtStartup: false, defaultViewMode: 'list' };
await page.addInitScript(value => {
if (!sessionStorage.getItem('seeded')) {
sessionStorage.setItem('seeded', '1');
localStorage.setItem('gallerySettings', value);
}
}, JSON.stringify(stored));
const listed = page.waitForResponse(item => item.url().includes('/prompt_manager/images/output?'));
await page.goto(PAGES.gallery);
await listed;
// With no Page options control, a stored default view still opens the page in it.
await expect(page.locator('#listViewBtn')).toHaveClass(/bg-pm-accent/);
await openPageOptions(page);
const dialog = page.locator('#settingsModal');
await expect(dialog.locator('h3')).toHaveText('Page options');
// Exactly the page-only settings (G5); the default view is System › Appearance's Default layout.
expect(await dialog.locator('input, select, textarea').evaluateAll(fields => fields.map(field => field.id))).toEqual([
'checkThumbnailsAtStartup', 'lazyLoadingToggle', 'defaultLimitSelect', 'gridColumnsSelect',
'infiniteScrollToggle', 'debugModeToggle', 'apiTimeoutInput']);
await expect(dialog.getByText('Default View Mode')).toHaveCount(0);
await page.locator('#defaultLimitSelect').selectOption('50');
await page.locator('#debugModeToggle').check();
await page.locator('#saveSettingsBtn').click();
await expect(dialog).toBeHidden();
const read = () => page.evaluate(() => JSON.parse(localStorage.getItem('gallerySettings')));
let saved = await read();
expect(saved).toMatchObject({ ...stored, defaultLimit: 50, debugMode: true });
// Reset puts back only the page options' defaults; the Appearance, startup-prompt and default-view keys stay.
await openPageOptions(page);
page.once('dialog', dialog => dialog.accept());
await page.locator('#resetSettingsBtn').click();
await expect(page.getByText('Page options reset to defaults')).toBeVisible();
await expect(page.locator('#defaultLimitSelect')).toHaveValue('100');
saved = await read();
expect(saved).toMatchObject({ defaultViewMode: 'list', imageQuality: 'high', showImageInfo: false, videoMute: false,
autoLoadMetadata: false, workspaceLayout: 'masonry', thumbnailPromptDismissed: 'sig', thumbnailsGenerated: true,
defaultLimit: 100, debugMode: false, checkThumbnailsAtStartup: true, lazyLoading: true, gridColumns: 8,
infiniteScroll: false, apiTimeout: 30 });
});
test('the legacy auto-tag modal stays open after Manage in System', async ({ page, context, request }) => {
for (const legacy of ['admin', 'gallery']) {
await post(request, '/__test__/tagging/models', { unavailable: ['gguf'] });
await page.goto(PAGES[legacy]);
await openAutoTag(page);
const link = page.locator('#ggufModelStatus').getByRole('link', { name: 'Manage in System', exact: true });
await expect(link).toHaveAttribute('title', 'Opens System › Auto-tagging in a new tab');
// A downloaded model keeps its status text.
await expect(page.locator('#wd14VitModelStatus')).toHaveText('\u2713 Downloaded');
const opened = context.waitForEvent('page');
await link.click();
const system = await opened;
await expect(system).toHaveURL(/#\/system\/tagging$/);
await expect(page.locator('#autoTagModal')).toBeVisible();
await system.close();
// Downloaded in System meanwhile: reopening the modal reads the models again (CUJ 4).
await post(request, '/__test__/tagging/models', { unavailable: [] });
await page.goto(PAGES[legacy]);
await openAutoTag(page);
await expect(page.locator('#ggufModelStatus')).toHaveText('\u2713 Downloaded');
}
});

Some files were not shown because too many files have changed in this diff Show More