Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92920bf0f9 | ||
|
|
9847664b9e | ||
|
|
a7d54e0ecf | ||
|
|
1439a5ef19 | ||
|
|
9f3a1bf96d | ||
|
|
def5deb113 | ||
|
|
6375be1a92 | ||
|
|
6f02277a1c | ||
|
|
8aad090c09 | ||
|
|
3d32e9183a | ||
|
|
a1f744708e | ||
|
|
b3bb55f2dc | ||
|
|
fa31644c4c | ||
|
|
0c023c7ec9 | ||
|
|
9943a61619 | ||
|
|
1d509c885e | ||
|
|
96ce361b82 | ||
|
|
9d058a0035 | ||
|
|
4aa71c4026 | ||
|
|
a695457cce | ||
|
|
c9d2b9c66b | ||
|
|
98ba01d670 | ||
|
|
6c19f0a228 | ||
|
|
a387643946 | ||
|
|
1a177e39a2 | ||
|
|
faac2d6f52 | ||
|
|
2bf3e5202d |
+1
-1
@@ -13,9 +13,9 @@
|
||||
|
||||
# Development files
|
||||
/TESTING.md
|
||||
/Makefile
|
||||
/requirements-dev.txt
|
||||
/.coveragerc
|
||||
/.flake8
|
||||
/.pre-commit-config.yaml
|
||||
/.gitignore
|
||||
/.gitattributes
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# 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
|
||||
@@ -0,0 +1,15 @@
|
||||
# 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']
|
||||
@@ -1,15 +1,8 @@
|
||||
{
|
||||
"required_status_checks": {
|
||||
"strict": false,
|
||||
"strict": true,
|
||||
"contexts": [
|
||||
"py3.12 on ubuntu-latest",
|
||||
"coverage gate (85%)",
|
||||
"black and flake8",
|
||||
"frontend modules",
|
||||
"all tests",
|
||||
"viewerjs",
|
||||
"real ComfyUI compatibility",
|
||||
"bandit (high severity)"
|
||||
"gate"
|
||||
]
|
||||
},
|
||||
"enforce_admins": true,
|
||||
|
||||
@@ -4,6 +4,10 @@ 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"
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
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"
|
||||
@@ -1,43 +0,0 @@
|
||||
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
|
||||
@@ -0,0 +1,359 @@
|
||||
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
|
||||
@@ -1,117 +0,0 @@
|
||||
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
|
||||
@@ -11,10 +11,16 @@ 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
|
||||
|
||||
@@ -1,295 +0,0 @@
|
||||
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@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
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"
|
||||
@@ -1,268 +0,0 @@
|
||||
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@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
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@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
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@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
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"
|
||||
@@ -17,9 +17,18 @@ 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
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# Tailwind standalone CLI (downloaded by `make css-setup`)
|
||||
tailwindcss
|
||||
|
||||
# AI tooling / local config
|
||||
.claude/
|
||||
.playwright-mcp/
|
||||
|
||||
@@ -13,7 +13,7 @@ repos:
|
||||
language: system
|
||||
types: [python]
|
||||
|
||||
# Fails at the severity CI enforces (code-quality.yml: -lll, high only), never stricter.
|
||||
# Fails at the severity CI enforces (ci.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,9 +22,10 @@ repos:
|
||||
types: [python]
|
||||
exclude: ^(tests/|reference/)
|
||||
|
||||
# Skipped when the pushed commits only change inert files (tools/ci/change_class.py, #639).
|
||||
- id: tests
|
||||
name: tests
|
||||
entry: python -m tests.run_suite -q
|
||||
entry: python tools/ci/change_class.py --unless-inert python -m tests.run_suite -q
|
||||
language: system
|
||||
pass_filenames: false
|
||||
stages: [pre-push]
|
||||
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
# 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 |
|
||||
@@ -1,43 +0,0 @@
|
||||
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)
|
||||
+5
-6
@@ -1,12 +1,11 @@
|
||||
> **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).
|
||||
> **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).
|
||||
|
||||
# ComfyUI Prompt Manager
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
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.
|
||||
|
||||
@@ -254,8 +253,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`
|
||||
- **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)
|
||||
- **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)
|
||||
|
||||
### Prerequisites
|
||||
|
||||
@@ -329,7 +328,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 legacy gallery stays at `http://localhost:8188/prompt_manager/gallery`.
|
||||
The old gallery URL, `http://localhost:8188/prompt_manager/gallery`, now opens the workspace's Images page.
|
||||
|
||||
#### **🎬 Video & Image Support**
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||

|
||||
|
||||
# ComfyUI Prompt Manager
|
||||
|
||||
**Every prompt you run, every image it made, and every negative you tried, in one searchable library inside ComfyUI.**
|
||||
@@ -6,7 +8,7 @@
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
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.
|
||||
|
||||
@@ -101,7 +103,7 @@ Pick an open ComfyUI window and a node, then review the exact before and after.
|
||||
|
||||
### Deletes you can review
|
||||
|
||||
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.
|
||||
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 a Linux or BSD server you can also delete the files permanently, for headless servers where a trash only fills up the disk; those files can't be recovered. 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.
|
||||
|
||||

|
||||
|
||||
@@ -212,22 +214,26 @@ Set `PROMPT_MANAGER_DATA_DIR` to an absolute folder to keep the library somewher
|
||||
- **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 will be removed
|
||||
## The old pages are gone
|
||||
|
||||
They still work at their URLs for now and will be removed in a future release. Everything they do is moving to the workspace.
|
||||
The dashboard, tags page, gallery and metadata viewer have been removed. Everything they did is in the workspace, and their URLs and bookmarks still work: each one opens the matching workspace page.
|
||||
|
||||
| Page | URL |
|
||||
| Old URL | Opens |
|
||||
| --- | --- |
|
||||
| Dashboard | `/prompt_manager/admin` |
|
||||
| Tags | `/prompt_manager/admin#/tags` |
|
||||
| Gallery | `/prompt_manager/gallery` |
|
||||
| Metadata viewer | `/prompt_manager/gallery.html` |
|
||||
| `/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 |
|
||||
|
||||
The documentation for those pages is in [README-legacy.md](README-legacy.md).
|
||||
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 it, the address follows the tags you set in **Filters**, and you can bookmark or write such a link 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.
|
||||
|
||||
## 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 why for each file.
|
||||
- **Permanent delete is Linux and BSD only,** and can't be undone. The safety backup brings back the library records, not the files.
|
||||
- **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.
|
||||
@@ -243,7 +249,11 @@ The documentation for those pages is in [README-legacy.md](README-legacy.md).
|
||||
| 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 |
|
||||
|
||||
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).
|
||||
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. macOS is not tested; it should work, but support is best-effort. To run the tests yourself, see [TESTING.md](TESTING.md).
|
||||
|
||||
## Changelog
|
||||
|
||||
What changed in each release, and the contributors whose pull requests are part of it: [CHANGELOG.md](CHANGELOG.md). Full notes are on the [releases page](https://github.com/ComfyAssets/ComfyUI_PromptManager/releases).
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+636
-269
File diff suppressed because it is too large
Load Diff
+39
-13
@@ -156,12 +156,13 @@ try:
|
||||
_global_prompt_tracker = get_prompt_tracker(_global_db)
|
||||
_global_image_monitor = get_image_monitor(_global_db, _global_prompt_tracker)
|
||||
|
||||
# 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.
|
||||
# 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.
|
||||
if api is not None:
|
||||
_global_image_monitor.set_review_recorder(api.record_review_file)
|
||||
_global_image_monitor.set_review_recorder(api.queue_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)
|
||||
@@ -292,15 +293,26 @@ def _teardown_logger():
|
||||
return logging.getLogger("prompt_manager.init")
|
||||
|
||||
|
||||
def _stop_background_work():
|
||||
"""Stop the image monitor, the preview worker, the job worker threads
|
||||
and the prompt cleanup thread against one TEARDOWN_SECONDS deadline, once.
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
"""
|
||||
global _background_work_result
|
||||
with _background_work_lock:
|
||||
@@ -315,8 +327,10 @@ 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),
|
||||
@@ -349,6 +363,18 @@ 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():
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 42 KiB |
@@ -19,6 +19,10 @@ 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
|
||||
@@ -64,6 +68,9 @@ MAINTENANCE_OPERATIONS = (
|
||||
# #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)
|
||||
@@ -574,6 +581,9 @@ 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()
|
||||
@@ -867,6 +877,8 @@ class MaintenanceOperations:
|
||||
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.
|
||||
"""
|
||||
if operation not in MAINTENANCE_OPERATIONS or operation == "workflow_storage":
|
||||
raise ValueError(f"Unknown maintenance operation {operation!r}")
|
||||
@@ -885,6 +897,11 @@ class MaintenanceOperations:
|
||||
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)
|
||||
|
||||
+7
-22
@@ -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
|
||||
from .vocabulary import VocabularyOperations, bump_image_tag_bytes
|
||||
from .execution_history import ExecutionHistoryOperations
|
||||
from .execution_contexts import ExecutionContextOperations
|
||||
from .execution_outputs import ExecutionOutputOperations
|
||||
@@ -1049,7 +1049,8 @@ class PromptDatabase(
|
||||
if include_ancestors:
|
||||
ancestors = set()
|
||||
for folder in folders:
|
||||
parts = folder.replace("\\", "/").split("/")
|
||||
# #646: ``folder`` already uses ``/``; on POSIX ``\\`` is a name.
|
||||
parts = folder.split("/")
|
||||
for i in range(1, len(parts)):
|
||||
ancestors.add("/".join(parts[:i]))
|
||||
folders.update(ancestors)
|
||||
@@ -1261,26 +1262,10 @@ class PromptDatabase(
|
||||
"has_more": (offset + limit) < total,
|
||||
}
|
||||
|
||||
@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
|
||||
# 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)
|
||||
|
||||
@classmethod
|
||||
def _move_tag_links(
|
||||
|
||||
+23
-1
@@ -114,6 +114,10 @@ _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
|
||||
@@ -459,6 +463,24 @@ 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:
|
||||
@@ -536,7 +558,7 @@ class ReviewOperations:
|
||||
"""Remove the pending, undecided items that offer nothing to choose.
|
||||
|
||||
``locators`` are files the caller found ambiguous without a choice
|
||||
(fewer than two candidates carry a prompt). Of their items, one leaves
|
||||
(no candidate carries 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
|
||||
|
||||
@@ -215,22 +215,24 @@ def choosable(candidate: Any) -> bool:
|
||||
|
||||
|
||||
# An item is worth a decision only when at least this many candidates offer
|
||||
# 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
|
||||
# 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
|
||||
|
||||
|
||||
def evidence_offers_choice(evidence: Any) -> bool:
|
||||
"""False when stored evidence provably offers nothing to choose.
|
||||
|
||||
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.
|
||||
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.
|
||||
"""
|
||||
if not isinstance(evidence, dict):
|
||||
return False
|
||||
# The saver anchor's one pair (#390) is a suggestion to confirm.
|
||||
needed = 1 if evidence.get("anchor") == "saver" else MIN_CHOOSABLE
|
||||
needed = MIN_CHOOSABLE
|
||||
if evidence.get("limited"):
|
||||
total = evidence.get("candidate_total")
|
||||
return type(total) is int and total >= needed
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
"""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}
|
||||
+33
-2
@@ -295,6 +295,38 @@ 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.
|
||||
|
||||
@@ -405,8 +437,7 @@ 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)
|
||||
self._bump_image_tag_bytes(conn, tag_id)
|
||||
conn.execute("DELETE FROM tags WHERE id=?", (tag_id,))
|
||||
_delete_tag(conn, tag_id)
|
||||
return {"library_epoch": epoch, "deleted": True, **counts}
|
||||
|
||||
def vocabulary_tag_impact(self, tag_id: int) -> dict | None:
|
||||
|
||||
@@ -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`) 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).
|
||||
- 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).
|
||||
- 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,14 +69,16 @@ regression coverage with mockup-only tests.
|
||||
|
||||
## GitHub and release gates
|
||||
|
||||
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.
|
||||
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.
|
||||
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 include
|
||||
screenshots for visual changes. All required checks must pass before merging.
|
||||
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.
|
||||
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.
|
||||
|
||||
+4
-2
@@ -99,19 +99,21 @@ 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,
|
||||
|
||||
+1
-35
@@ -7,7 +7,7 @@ duplicate code in prompt_manager.py and prompt_manager_text.py.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
try:
|
||||
from .utils.logging_config import get_logger
|
||||
@@ -396,40 +396,6 @@ 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 _start_gallery_system(self):
|
||||
"""Initialize and start the gallery monitoring system."""
|
||||
try:
|
||||
|
||||
+45
-50
@@ -23,6 +23,7 @@ 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
|
||||
"""
|
||||
|
||||
@@ -30,7 +31,6 @@ import asyncio
|
||||
import datetime
|
||||
import functools
|
||||
import gzip as gzip_module
|
||||
import json
|
||||
import math
|
||||
import ntpath
|
||||
import os
|
||||
@@ -41,6 +41,7 @@ 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
|
||||
@@ -74,6 +75,7 @@ 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
|
||||
@@ -89,6 +91,7 @@ from .source_rescope import SourceRescopeMixin
|
||||
|
||||
try:
|
||||
from ...database.operations import PromptDatabase
|
||||
from ...utils.exif_text import exif_text
|
||||
from ...utils.logging_config import get_logger
|
||||
from ...utils.native_memory import release_free_memory
|
||||
from ...utils.png_text import png_text
|
||||
@@ -100,6 +103,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.logging_config import get_logger
|
||||
from utils.native_memory import release_free_memory
|
||||
from utils.png_text import png_text
|
||||
@@ -212,44 +216,10 @@ def _resolve_static_file(root, filepath, allowed=STATIC_MIME_TYPES):
|
||||
|
||||
|
||||
# ── JSON request bodies ────────────────────────────────────────────────
|
||||
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
|
||||
# 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
|
||||
|
||||
|
||||
# ── Gzip compression middleware ────────────────────────────────────────
|
||||
@@ -306,6 +276,17 @@ 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,
|
||||
@@ -338,6 +319,7 @@ class PromptManagerAPI(
|
||||
BackupRestoreRoutesMixin,
|
||||
WorkflowStorageRoutesMixin,
|
||||
DuplicateFilesMixin,
|
||||
TagCleanupMixin,
|
||||
LoggingRoutesMixin,
|
||||
LogCleanupMixin,
|
||||
DiagnosticsReportMixin,
|
||||
@@ -415,6 +397,9 @@ 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).
|
||||
@@ -653,17 +638,24 @@ class PromptManagerAPI(
|
||||
async def serve_web_ui(request):
|
||||
return self._serve_html_page(request, "index.html", "Web UI", cache=False)
|
||||
|
||||
@routes.get("/prompt_manager/gallery.html")
|
||||
async def serve_gallery_ui(request):
|
||||
return self._serve_html_page(request, "metadata.html", "Gallery")
|
||||
# The old admin, gallery and metadata pages are gone (#668, D207); their
|
||||
# URLs stay and lead into the workspace.
|
||||
|
||||
@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.html")
|
||||
async def redirect_old_metadata_page(request):
|
||||
return _workspace_redirect("#/inspect")
|
||||
|
||||
@routes.get("/prompt_manager/gallery")
|
||||
async def serve_gallery_admin_ui(request):
|
||||
return self._serve_html_page(request, "gallery.html", "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"
|
||||
)
|
||||
|
||||
# ── Static file serving ───────────────────────────────────────
|
||||
|
||||
@@ -705,6 +697,7 @@ 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)
|
||||
@@ -1018,9 +1011,11 @@ class PromptManagerAPI(
|
||||
return []
|
||||
|
||||
def _extract_comfyui_metadata(self, image_path):
|
||||
"""Embedded ComfyUI metadata of an image (PNG text chunks) or a video.
|
||||
"""Embedded ComfyUI metadata of an image (PNG text, EXIF) or a video.
|
||||
|
||||
PNG text is read without decoding the pixels (``utils.png_text``, #523).
|
||||
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``.
|
||||
|
||||
Videos go through ffprobe (see utils/video_metadata). Unreadable files
|
||||
are a warning, not an error: a scan over a large output tree meets
|
||||
@@ -1030,7 +1025,7 @@ class PromptManagerAPI(
|
||||
return read_video_metadata(image_path)
|
||||
try:
|
||||
with Image.open(image_path) as img:
|
||||
return png_text(img)
|
||||
return png_text(img) or exif_text(img)
|
||||
except Exception as e:
|
||||
self.logger.warning(
|
||||
f"Unreadable image {os.path.basename(str(image_path))}: {e}"
|
||||
|
||||
+18
-27
@@ -43,6 +43,7 @@ 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 (
|
||||
@@ -50,6 +51,7 @@ except ImportError:
|
||||
in_trash_folder,
|
||||
is_skipped_folder,
|
||||
)
|
||||
from utils.media_formats import collectable
|
||||
|
||||
try:
|
||||
from ...database.image_removal import mark_hides
|
||||
@@ -100,7 +102,7 @@ try:
|
||||
except ImportError:
|
||||
from database.library import display_title
|
||||
|
||||
IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff")
|
||||
IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".avif")
|
||||
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
|
||||
@@ -156,7 +158,9 @@ def _collect_media_files(output_dirs, extensions):
|
||||
and not os.path.islink(os.path.join(current, d))
|
||||
)
|
||||
for name in sorted(filenames):
|
||||
if os.path.splitext(name)[1].lower() not in wanted:
|
||||
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):
|
||||
continue
|
||||
full = os.path.join(current, name)
|
||||
if os.path.islink(full) or not os.path.isfile(full):
|
||||
@@ -1699,7 +1703,8 @@ 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.
|
||||
its pending items without a choice leave the queue. The decision is
|
||||
``review_dispatch``'s, shared with the monitor's review worker (#659).
|
||||
"""
|
||||
counts = dict.fromkeys(SCAN_COUNT_KEYS, 0)
|
||||
|
||||
@@ -1713,14 +1718,12 @@ class AdminRoutesMixin:
|
||||
if self._scan_job and self._scan_job.cancelled:
|
||||
break
|
||||
counts["processed"] += 1
|
||||
ambiguous, untraced, records = [], [], {}
|
||||
records = {}
|
||||
try:
|
||||
outcome = self._ingest_scanned_file(
|
||||
media_file,
|
||||
metadata,
|
||||
detailed=True,
|
||||
ambiguous=ambiguous,
|
||||
untraced=untraced,
|
||||
records=records,
|
||||
history=history,
|
||||
)
|
||||
@@ -1729,24 +1732,9 @@ class AdminRoutesMixin:
|
||||
counts["failed"] += 1
|
||||
note(media_file, "error")
|
||||
continue
|
||||
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
|
||||
)
|
||||
outcome, _recorded = self.review_dispatch(
|
||||
media_file, roots, records.get("decision"), outcome, review
|
||||
)
|
||||
if outcome is None:
|
||||
note(media_file, None)
|
||||
continue
|
||||
@@ -1783,11 +1771,12 @@ 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: fewer than two candidates carry a prompt)
|
||||
(``reviewable`` is False: no candidate carries 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. ``history`` is
|
||||
the batch's lazy recorded-history lookup.
|
||||
``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.
|
||||
"""
|
||||
path = str(media_file)
|
||||
if history is None: # one file: history is still asked once
|
||||
@@ -1800,6 +1789,8 @@ 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
|
||||
|
||||
@@ -91,6 +91,7 @@ _PREVIEW_TYPES = {
|
||||
".bmp": "image/bmp",
|
||||
".tiff": "image/tiff",
|
||||
".tif": "image/tiff",
|
||||
".avif": "image/avif", # #652
|
||||
".mp4": "video/mp4",
|
||||
".m4v": "video/mp4",
|
||||
".webm": "video/webm",
|
||||
|
||||
@@ -25,8 +25,10 @@ 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
|
||||
|
||||
@@ -156,8 +158,9 @@ 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"}
|
||||
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff", ".tif", ".avif"}
|
||||
)
|
||||
# Bounds for scan_output_dir: a runaway output tree must not pin the server.
|
||||
_SCAN_MAX_FILES = 50_000
|
||||
@@ -945,7 +948,8 @@ class AutotagRoutesMixin:
|
||||
|
||||
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."""
|
||||
if Path(str(raw_path)).suffix.lower() not in _MEDIA_EXTENSIONS:
|
||||
suffix = Path(str(raw_path)).suffix.lower()
|
||||
if suffix not in _MEDIA_EXTENSIONS or not collectable(suffix):
|
||||
return None
|
||||
roots = list(self._get_all_output_dirs())
|
||||
for output_dir in roots:
|
||||
@@ -1449,7 +1453,8 @@ class AutotagRoutesMixin:
|
||||
if not is_skipped_folder(name) and depth + 1 <= _SCAN_MAX_DEPTH
|
||||
)
|
||||
for name in sorted(filenames):
|
||||
if Path(name).suffix.lower() not in _MEDIA_EXTENSIONS:
|
||||
suffix = Path(name).suffix.lower()
|
||||
if suffix not in _MEDIA_EXTENSIONS or not collectable(suffix):
|
||||
continue
|
||||
candidate = Path(dirpath) / name
|
||||
if candidate.is_symlink():
|
||||
|
||||
@@ -304,7 +304,8 @@ def _relative_key(path, root):
|
||||
relative = os.path.relpath(str(path), str(root))
|
||||
except ValueError: # another drive (Windows)
|
||||
return None
|
||||
return os.path.normcase(relative).replace("\\", "/")
|
||||
# #646: on POSIX ``a\\b.png`` and ``a/b.png`` are two files.
|
||||
return os.path.normcase(relative).replace(os.sep, "/")
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -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))
|
||||
with_ancestors.update(_ancestors(folder, sep))
|
||||
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)}
|
||||
return folders | {rel_dir}, with_ancestors | {rel_dir, *_ancestors(rel_dir, sep)}
|
||||
|
||||
|
||||
def _root_prefix(root) -> tuple[str, str]:
|
||||
@@ -180,8 +180,10 @@ def _folder_of(root, path, sep, prefix) -> str:
|
||||
return "" if rel_dir == "." else rel_dir
|
||||
|
||||
|
||||
def _ancestors(folder: str) -> list[str]:
|
||||
parts = folder.replace("\\", "/").split("/")
|
||||
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("/")
|
||||
return ["/".join(parts[:i]) for i in range(1, len(parts))]
|
||||
|
||||
|
||||
|
||||
+35
-1
@@ -3,7 +3,7 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
from functools import wraps
|
||||
from functools import partial, wraps
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -31,7 +31,9 @@ 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:
|
||||
@@ -717,6 +719,37 @@ 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:
|
||||
@@ -793,6 +826,7 @@ 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 = {
|
||||
|
||||
+77
-18
@@ -1,9 +1,9 @@
|
||||
"""Delete selected images: remove them from the library, or trash them (#480).
|
||||
"""Delete images: remove from library, trash, or permanently delete.
|
||||
|
||||
``POST /prompt_manager/images/delete/preview {items | filter}`` reviews the
|
||||
selection for both modes at once and answers a reviewed plan (the System ›
|
||||
selection for all 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 (both
|
||||
the records each file loses, the refused files with a coded reason (all
|
||||
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,12 +19,16 @@ 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.
|
||||
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.
|
||||
|
||||
No path here unlinks a media file. A failed records write stops the job; the
|
||||
files after it are not attempted.
|
||||
Only ``mode="permanent"`` unlinks a media file from disk. A failed records
|
||||
write stops the job; the files after it are not attempted.
|
||||
"""
|
||||
|
||||
import errno
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -59,10 +63,11 @@ except ImportError:
|
||||
from utils.media_folders import is_trash_folder
|
||||
|
||||
IMAGE_DELETE = "delete_images"
|
||||
MODES = ("library", "trash")
|
||||
MODES = ("library", "trash", "permanent")
|
||||
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).
|
||||
@@ -87,8 +92,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 move this file (no permission, or it is "
|
||||
"locked in Finder)."
|
||||
"PromptManager isn't allowed to remove this file (no permission, or it is "
|
||||
"locked)."
|
||||
),
|
||||
trash.CLOUD_SYNC: (
|
||||
"Files in iCloud Drive or a cloud-synced folder can't be moved to the "
|
||||
@@ -114,6 +119,16 @@ 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("/")
|
||||
@@ -275,17 +290,23 @@ 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": False, "label": "Chosen in the review"},
|
||||
"media": {
|
||||
"deletes_files": permanent_supported,
|
||||
"label": "Chosen in the review",
|
||||
},
|
||||
"permanent_delete_supported": permanent_supported,
|
||||
"details": [],
|
||||
}
|
||||
return {"targets": acted, "public": public}
|
||||
@@ -341,7 +362,11 @@ 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 "removed"
|
||||
done_group = (
|
||||
"trashed"
|
||||
if mode == "trash"
|
||||
else ("deleted" if mode == "permanent" else "removed")
|
||||
)
|
||||
changed, failed = 0, None
|
||||
for done, target in enumerate(targets, start=1):
|
||||
if failed:
|
||||
@@ -366,17 +391,26 @@ class ImageDeleteMixin:
|
||||
)
|
||||
elif group == done_group:
|
||||
changed += 1
|
||||
detail = (
|
||||
f"Moved to the {label}" if label else "Removed from the library"
|
||||
)
|
||||
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"
|
||||
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()
|
||||
verb = "Moved" if mode == "trash" else "Removed"
|
||||
where = "to the trash" if mode == "trash" else "from the library"
|
||||
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"
|
||||
line = f"{verb} {changed:,} of {len(targets):,} images {where}"
|
||||
job.log_line(line)
|
||||
job.update(progress=100, status_line=f"{line} · {backup_note(backup)}")
|
||||
@@ -398,7 +432,7 @@ class ImageDeleteMixin:
|
||||
"code": code,
|
||||
"detail": text,
|
||||
}
|
||||
mark = {"removed": "-", "trashed": "-"}.get(group, "=")
|
||||
mark = {"removed": "-", "trashed": "-", "deleted": "-"}.get(group, "=")
|
||||
job.record(
|
||||
group, row, f"{mark} {target['root_label']}/{target['rel']} · {text}"
|
||||
)
|
||||
@@ -437,6 +471,21 @@ 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:
|
||||
@@ -445,7 +494,11 @@ 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)
|
||||
return ("trashed" if mode == "trash" else "removed"), None, label
|
||||
if mode == "trash":
|
||||
return "trashed", None, label
|
||||
if mode == "permanent":
|
||||
return "deleted", None, label
|
||||
return "removed", None, label
|
||||
|
||||
# ── the workspace listing ─────────────────────────────────────────
|
||||
|
||||
@@ -517,6 +570,12 @@ 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
|
||||
|
||||
@@ -259,7 +259,8 @@ def parse_image_tag_request(data: dict):
|
||||
``filter`` (a listing query object, parse_listing_filter) may stand in for
|
||||
``targets``; the start resolves it.
|
||||
"""
|
||||
fields = _FIELDS.get(data.get("mode"))
|
||||
mode = data.get("mode")
|
||||
fields = _FIELDS.get(mode) if isinstance(mode, str) else None
|
||||
if fields is None:
|
||||
return None, bad_request('mode must be "add" or "auto"')
|
||||
fields = fields | {"filter" if "filter" in data else "targets"}
|
||||
|
||||
+65
-37
@@ -25,6 +25,7 @@ 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,
|
||||
@@ -56,6 +57,7 @@ from .inspection_service import (
|
||||
VIDEO_EXTENSIONS,
|
||||
image_tags_reader,
|
||||
inspect_current_file,
|
||||
review_reader,
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -70,8 +72,11 @@ 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,
|
||||
@@ -101,8 +106,11 @@ 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,
|
||||
@@ -267,18 +275,23 @@ def _is_within(path, root):
|
||||
|
||||
|
||||
def _has_traversal(relative):
|
||||
"""True for absolute paths, drive-qualified paths or any ``..`` segment."""
|
||||
"""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).
|
||||
"""
|
||||
if not relative or os.path.isabs(relative) or os.path.splitdrive(relative)[0]:
|
||||
return True
|
||||
if relative[0] in ("/", "\\"):
|
||||
if relative[0] in path_separators():
|
||||
return True
|
||||
return ".." in re.split(r"[\\/]+", relative)
|
||||
return ".." in split_relative(relative)
|
||||
|
||||
|
||||
def _is_thumbnail_cache_path(relative):
|
||||
"""True when *relative* names something in a root's ``thumbnails/``
|
||||
cache (any case, either separator): never inspected as a media file."""
|
||||
first = re.split(r"[\\/]+", relative.lstrip("\\/"), maxsplit=1)[0]
|
||||
cache (any case, this server's separators, #646): never inspected as a
|
||||
media file."""
|
||||
first = split_relative(relative.lstrip(path_separators()))[0]
|
||||
return first.casefold() == "thumbnails"
|
||||
|
||||
|
||||
@@ -313,7 +326,10 @@ def _media_access_error(path, allowed_dirs):
|
||||
|
||||
|
||||
# Media types the gallery scans and thumbnails (a superset is never served).
|
||||
GALLERY_IMAGE_EXTENSIONS = frozenset({".png", ".jpg", ".jpeg", ".webp", ".gif"})
|
||||
# #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"}
|
||||
)
|
||||
MEDIA_EXTENSIONS = GALLERY_IMAGE_EXTENSIONS | VIDEO_EXTENSIONS
|
||||
|
||||
# Caps on request-triggered filesystem work.
|
||||
@@ -539,7 +555,6 @@ 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).
|
||||
@@ -708,36 +723,17 @@ def _workspace_cursor_key(token: str, scope: str, order: str, secret: bytes) ->
|
||||
raise ValueError("Invalid gallery cursor; refresh the gallery") from None
|
||||
|
||||
|
||||
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)
|
||||
# The shared bounded reader, at this module's own cap.
|
||||
_BodyTooLarge = BodyTooLarge
|
||||
_json_error = json_error
|
||||
|
||||
|
||||
async def _read_json_body(request):
|
||||
"""Read a JSON object body in bounded chunks.
|
||||
"""The JSON object body, or raise _BodyTooLarge past MAX_JSON_BODY_BYTES.
|
||||
|
||||
Raises _BodyTooLarge past MAX_JSON_BODY_BYTES (declared or streamed) and
|
||||
ValueError when the body is not a JSON object.
|
||||
Raises ValueError when the body is not a JSON object.
|
||||
"""
|
||||
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
|
||||
return await read_json_object(request, MAX_JSON_BODY_BYTES)
|
||||
|
||||
|
||||
async def _json_body_or_error(request):
|
||||
@@ -875,7 +871,7 @@ def _favorite_root_key(root) -> str:
|
||||
|
||||
|
||||
def _source_depth(source: str) -> int:
|
||||
return len([part for part in re.split(r"[\\/]+", source) if part])
|
||||
return len([part for part in split_relative(source) if part])
|
||||
|
||||
|
||||
def deepest_source(sources, absolute_path):
|
||||
@@ -960,7 +956,9 @@ 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):
|
||||
if _name_suffix(entry.name).lower() not in MEDIA_EXTENSIONS:
|
||||
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):
|
||||
continue
|
||||
if entry.is_symlink():
|
||||
continue # never read through a link out of the output tree
|
||||
@@ -993,7 +991,8 @@ 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)
|
||||
if _name_suffix(name).lower() not in MEDIA_EXTENSIONS:
|
||||
suffix = _name_suffix(name).lower()
|
||||
if suffix not in MEDIA_EXTENSIONS or not collectable(suffix):
|
||||
return None
|
||||
if in_skipped_folder(folders) or len(folders) > MAX_SCAN_DEPTH:
|
||||
return None
|
||||
@@ -1200,6 +1199,10 @@ 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
|
||||
|
||||
|
||||
@@ -1221,9 +1224,10 @@ def _workspace_filters(query: Mapping) -> dict:
|
||||
folded = text.casefold()
|
||||
media = query.get("media", "all")
|
||||
order = query.get("sort", "newest")
|
||||
folder = query.get("subfolder", "").strip().replace("\\", "/")
|
||||
# #646: ``\\`` separates only on Windows; on POSIX it is part of a name.
|
||||
folder = "/".join(split_relative(query.get("subfolder", "").strip()))
|
||||
# ``path``: one exact relative path (Activity opens a scan row by it, D57).
|
||||
exact = query.get("path", "").strip().replace("\\", "/")
|
||||
exact = "/".join(split_relative(query.get("path", "").strip()))
|
||||
category = query.get("category", "").strip() or None
|
||||
tags = sorted(
|
||||
{tag.strip() for tag in query.get("tags", "").split(",") if tag.strip()}
|
||||
@@ -4135,6 +4139,9 @@ 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
|
||||
@@ -4179,6 +4186,27 @@ 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).
|
||||
|
||||
|
||||
@@ -42,6 +42,8 @@ IMAGE_EXTENSIONS = frozenset(
|
||||
".bmp",
|
||||
".tiff",
|
||||
".tif",
|
||||
# #652: served and inspected; the scan collects it where Pillow reads it
|
||||
".avif",
|
||||
".mp4",
|
||||
".webm",
|
||||
".mov",
|
||||
@@ -122,6 +124,67 @@ 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,
|
||||
*,
|
||||
@@ -130,6 +193,7 @@ 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*.
|
||||
|
||||
@@ -139,6 +203,9 @@ 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:
|
||||
@@ -173,6 +240,12 @@ 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",
|
||||
|
||||
+8
-2
@@ -42,6 +42,7 @@ open across the switch (#249 S8).
|
||||
import asyncio
|
||||
import itertools
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
@@ -123,11 +124,15 @@ 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", "not_changed", "errors")
|
||||
IMAGE_DELETE_GROUP_NAMES = ("trashed", "removed", "deleted", "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"
|
||||
@@ -160,7 +165,8 @@ def _relative_path(path) -> str:
|
||||
or PureWindowsPath(text).drive
|
||||
):
|
||||
return re.split(r"[\\/]", text)[-1]
|
||||
return text.replace("\\", "/")
|
||||
# #646: on POSIX a backslash is part of a name, never a separator.
|
||||
return text.replace("\\", "/") if os.sep == "\\" else text
|
||||
|
||||
|
||||
class JobBusy(Exception):
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"""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)
|
||||
@@ -6,9 +6,12 @@ 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, 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
|
||||
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
|
||||
that saved pairs block, or whose layout is unusable, carries no token
|
||||
(nothing can be applied).
|
||||
|
||||
@@ -104,6 +107,13 @@ 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:
|
||||
@@ -315,6 +325,8 @@ 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": (
|
||||
@@ -441,6 +453,9 @@ 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",
|
||||
@@ -466,6 +481,12 @@ 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):
|
||||
|
||||
+69
-13
@@ -5,7 +5,9 @@ one operation (``duplicate_prompts``, ``optimize``, ``unused_components``,
|
||||
``missing_links`` or ``pair_metadata``, #550; ``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) off the event loop and
|
||||
``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
|
||||
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
|
||||
@@ -29,13 +31,17 @@ 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: SQLite's
|
||||
policy (``maintenance.safety_backup``, default on) is on now, and always
|
||||
for ``workflow_storage`` and ``tag_cleanup`` (``ALWAYS_BACKED_UP``, policy
|
||||
``required``): 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);
|
||||
``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;
|
||||
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
|
||||
@@ -87,6 +93,13 @@ 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.
|
||||
@@ -100,9 +113,12 @@ MAINTENANCE_TITLES = {
|
||||
"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).
|
||||
COMPLETE_RECORD = frozenset({"pair_metadata"})
|
||||
# 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
|
||||
@@ -307,6 +323,8 @@ def _changed_line(operation, count, marks=0, result=None):
|
||||
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}"
|
||||
@@ -408,7 +426,7 @@ class MaintenanceRoutesMixin:
|
||||
("operation", "options"),
|
||||
cap=lambda body: (
|
||||
DUPLICATE_PREVIEW_BODY_MAX
|
||||
if body.get("operation") == DUPLICATE_FILES
|
||||
if body.get("operation") in LARGE_PREVIEWS
|
||||
else PREVIEW_BODY_MAX
|
||||
),
|
||||
)
|
||||
@@ -420,6 +438,8 @@ 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:
|
||||
@@ -470,10 +490,12 @@ class MaintenanceRoutesMixin:
|
||||
)
|
||||
policy = self._safety_backup_policy()
|
||||
destination = "backup"
|
||||
if operation == WORKFLOW_STORAGE:
|
||||
# Always backed up first, whatever the policy (the way back);
|
||||
# one kept pre-migration backup ever, pooled ones after it.
|
||||
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.
|
||||
kept = await self._run_in_executor(pre_migration_backups, db.model.db_path)
|
||||
destination = "backup" if kept else PRE_MIGRATION_LABEL
|
||||
try:
|
||||
@@ -516,7 +538,7 @@ class MaintenanceRoutesMixin:
|
||||
# ── apply ─────────────────────────────────────────────────────────
|
||||
|
||||
async def apply_maintenance_plan(self, request):
|
||||
from .image_delete import IMAGE_DELETE, parse_mode
|
||||
from .image_delete import IMAGE_DELETE, parse_mode, permanent_delete_supported
|
||||
|
||||
data, error = await self._read_maintenance_body(request, ("token", "mode"))
|
||||
if error is not None:
|
||||
@@ -531,7 +553,12 @@ class MaintenanceRoutesMixin:
|
||||
if plan.operation == IMAGE_DELETE:
|
||||
mode = parse_mode(data.get("mode"))
|
||||
if mode is None:
|
||||
return _invalid('mode must be "library" or "trash"')
|
||||
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"
|
||||
)
|
||||
elif "mode" in data:
|
||||
return _invalid("Unknown field: mode")
|
||||
store = self._maintenance_plans
|
||||
@@ -630,8 +657,8 @@ class MaintenanceRoutesMixin:
|
||||
Decided once, when the apply starts (the disk check measured it), and
|
||||
handed to the job.
|
||||
"""
|
||||
if plan.operation == WORKFLOW_STORAGE:
|
||||
return True # never without its pre-migration backup
|
||||
if plan.operation in ALWAYS_BACKED_UP:
|
||||
return True # never without its backup (pre-migration, or #618's)
|
||||
return plan.payload["backup"] == "on" or self._safety_backup_policy() == "on"
|
||||
|
||||
async def _safety_backup_step(self, job, db, backup_on):
|
||||
@@ -741,6 +768,13 @@ class MaintenanceRoutesMixin:
|
||||
}
|
||||
)
|
||||
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 [
|
||||
@@ -770,6 +804,8 @@ 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 [
|
||||
{
|
||||
@@ -787,6 +823,26 @@ 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 = []
|
||||
|
||||
@@ -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
|
||||
from ...utils.media_folders import in_trash_folder, path_separators
|
||||
except ImportError:
|
||||
from utils.media_capture import CAPTURE_EXTENSIONS
|
||||
from utils.media_folders import in_trash_folder
|
||||
from utils.media_folders import in_trash_folder, path_separators
|
||||
|
||||
MAX_TARGET_PATH = 1024
|
||||
TARGET_FIELDS = frozenset({"root_index", "root_scope", "path"})
|
||||
@@ -30,7 +30,8 @@ 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, backslash or ``..`` path (a 400 for a malformed
|
||||
absolute, drive-qualified, ``..`` path, or (on Windows only, #646) one
|
||||
holding a backslash (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.
|
||||
@@ -47,7 +48,7 @@ def media_target(data: object, *, media_message: str = TAGGING_MEDIA_MESSAGE):
|
||||
parts = relative.split("/")
|
||||
if (
|
||||
"\0" in relative
|
||||
or "\\" in relative
|
||||
or ("\\" in relative and "\\" in path_separators())
|
||||
or relative.startswith("/")
|
||||
or _has_traversal(relative)
|
||||
or any(part in ("", ".", "..") or ":" in part for part in parts)
|
||||
|
||||
@@ -431,12 +431,22 @@ def _marker_lock(folder):
|
||||
(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."""
|
||||
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:
|
||||
|
||||
@@ -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, ``inspection-state.mjs`` and ``admin.js`` share);
|
||||
the shape the serve route and ``inspection-state.mjs`` 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
|
||||
@@ -672,12 +672,13 @@ 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, drive or stream colon, and no
|
||||
Text only, before any join: no backslash (on Windows; on POSIX it is part
|
||||
of a name, #646), 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 ":" in filepath:
|
||||
if not filepath or ":" in filepath or (os.sep == "\\" and "\\" in filepath):
|
||||
return False
|
||||
parts = filepath.split("/")
|
||||
if len(parts) < 2 or parts[0] != PREVIEW_FOLDER:
|
||||
|
||||
+76
-38
@@ -64,6 +64,36 @@ 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:
|
||||
@@ -605,18 +635,15 @@ class PromptRoutesMixin:
|
||||
{"success": False, "error": "Tag name required"}, status=400
|
||||
)
|
||||
|
||||
try:
|
||||
body = await request.json()
|
||||
except Exception:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Invalid JSON body"}, status=400
|
||||
)
|
||||
body, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
raw_name = body.get("new_name")
|
||||
if not raw_name:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "New tag name required"}, status=400
|
||||
)
|
||||
error = tags_error([raw_name])
|
||||
error = text_field_error(body, "new_name") or tags_error([raw_name])
|
||||
if error is not None:
|
||||
return error
|
||||
new_name = raw_name.strip()
|
||||
@@ -678,12 +705,9 @@ class PromptRoutesMixin:
|
||||
async def merge_tags_endpoint(self, request):
|
||||
"""Merge source tags into a target tag."""
|
||||
try:
|
||||
try:
|
||||
body = await request.json()
|
||||
except Exception:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Invalid JSON body"}, status=400
|
||||
)
|
||||
body, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
source_tags = body.get("source_tags", [])
|
||||
raw_target = body.get("target_tag")
|
||||
|
||||
@@ -697,7 +721,9 @@ class PromptRoutesMixin:
|
||||
)
|
||||
if not isinstance(source_tags, list):
|
||||
return bad_request("Source tags must be a list")
|
||||
error = tags_error([*source_tags, raw_target])
|
||||
error = text_field_error(body, "target_tag") or tags_error(
|
||||
[*source_tags, raw_target]
|
||||
)
|
||||
if error is not None:
|
||||
return error
|
||||
target_tag = raw_target.strip()
|
||||
@@ -851,7 +877,11 @@ class PromptRoutesMixin:
|
||||
"""Update prompt text."""
|
||||
try:
|
||||
prompt_id = int(request.match_info["prompt_id"])
|
||||
data = await request.json()
|
||||
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
|
||||
new_text = (data.get("text") or "").strip()
|
||||
|
||||
if not new_text:
|
||||
@@ -905,7 +935,9 @@ class PromptRoutesMixin:
|
||||
"""Update prompt rating."""
|
||||
try:
|
||||
prompt_id = int(request.match_info["prompt_id"])
|
||||
data = await request.json()
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
rating = data.get("rating")
|
||||
|
||||
try:
|
||||
@@ -945,14 +977,16 @@ class PromptRoutesMixin:
|
||||
"""Add tag to prompt."""
|
||||
try:
|
||||
prompt_id = int(request.match_info["prompt_id"])
|
||||
data = await request.json()
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
raw_tag = data.get("tag")
|
||||
|
||||
if not raw_tag:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Tag cannot be empty"}, status=400
|
||||
)
|
||||
error = tags_error([raw_tag])
|
||||
error = text_field_error(data, "tag") or tags_error([raw_tag])
|
||||
if error is not None:
|
||||
return error
|
||||
new_tag = raw_tag.strip()
|
||||
@@ -994,7 +1028,9 @@ class PromptRoutesMixin:
|
||||
async def add_tags_to_prompt(self, request):
|
||||
"""Add multiple tags to a single prompt."""
|
||||
try:
|
||||
data = await request.json()
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
prompt_id = data.get("prompt_id")
|
||||
new_tags = data.get("tags", [])
|
||||
|
||||
@@ -1002,6 +1038,9 @@ 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(
|
||||
@@ -1063,7 +1102,11 @@ class PromptRoutesMixin:
|
||||
"""Remove tag from prompt."""
|
||||
try:
|
||||
prompt_id = int(request.match_info["prompt_id"])
|
||||
data = await request.json()
|
||||
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
|
||||
tag_to_remove = (data.get("tag") or "").strip()
|
||||
|
||||
prompt = await self._run_in_executor(self.db.get_prompt_by_id, prompt_id)
|
||||
@@ -1103,13 +1146,18 @@ class PromptRoutesMixin:
|
||||
async def bulk_delete_prompts(self, request):
|
||||
"""Bulk delete prompts."""
|
||||
try:
|
||||
data = await request.json()
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
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
|
||||
@@ -1138,12 +1186,9 @@ class PromptRoutesMixin:
|
||||
async def bulk_add_tags(self, request):
|
||||
"""Bulk add tags to prompts."""
|
||||
try:
|
||||
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")
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
if "expected_epoch" in data:
|
||||
return await self._bulk_library_tags(data)
|
||||
prompt_ids = data.get("prompt_ids", [])
|
||||
@@ -1156,7 +1201,7 @@ class PromptRoutesMixin:
|
||||
)
|
||||
if not isinstance(new_tags, list):
|
||||
return bad_request("Tags must be a list")
|
||||
error = tags_error(new_tags)
|
||||
error = legacy_ids_error(prompt_ids) or tags_error(new_tags)
|
||||
if error is not None:
|
||||
return error
|
||||
|
||||
@@ -1185,16 +1230,9 @@ class PromptRoutesMixin:
|
||||
async def bulk_set_category(self, request):
|
||||
"""Bulk set category for prompts."""
|
||||
try:
|
||||
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
|
||||
)
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
if "images_filter" in data:
|
||||
return await self._bulk_category_by_filter(data)
|
||||
if "expected_epoch" in data:
|
||||
|
||||
+31
-8
@@ -45,16 +45,20 @@ 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 captured_review, item_profile, review_evidence
|
||||
from utils.review_capture import (
|
||||
candidate_hashes,
|
||||
captured_review,
|
||||
item_profile,
|
||||
)
|
||||
|
||||
ITEMS_URL = "/prompt_manager/review/items"
|
||||
DEFAULT_LIMIT = 40
|
||||
@@ -146,7 +150,9 @@ 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 or "\\" in part or ":" in part
|
||||
part in ("", ".", "..") or "/" in part
|
||||
# #646: on POSIX a backslash is part of a name.
|
||||
or (sep == "\\" and "\\" in part) or ":" in part
|
||||
for part in parts
|
||||
):
|
||||
continue
|
||||
@@ -271,6 +277,9 @@ 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/"
|
||||
@@ -388,12 +397,13 @@ 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": [], "limited": True}
|
||||
detail = {**detail, "candidates": [], "collapsed": None, "limited": True}
|
||||
return web.json_response(detail, headers=_NO_STORE)
|
||||
|
||||
def _review_detail(self, item_id: str):
|
||||
@@ -408,6 +418,20 @@ 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"]:
|
||||
@@ -744,7 +768,6 @@ 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
|
||||
evidence, _count, limited = review_evidence(resolution)
|
||||
if limited:
|
||||
return False
|
||||
return any(c.get("hash") == choice for c in evidence.get("candidates", ()))
|
||||
# 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)
|
||||
|
||||
+533
-57
@@ -6,12 +6,22 @@ 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: fewer than two of its candidates carry a prompt
|
||||
nothing to choose: none of its candidates carries a prompt
|
||||
(``utils.review_capture.reviewable``); the scan reports it unresolved ("could
|
||||
not be traced") unless the inspection profile finds a choice in it.
|
||||
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.
|
||||
|
||||
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 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.
|
||||
|
||||
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
|
||||
@@ -25,25 +35,38 @@ 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 monitor calls ``record_review_file`` from its worker thread after its
|
||||
own link. Nothing here links a file.
|
||||
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.
|
||||
|
||||
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``), 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.
|
||||
``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.
|
||||
"""
|
||||
|
||||
import functools
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from pathlib import Path
|
||||
|
||||
from .admin import SCAN_LOG_PREFIXES, _plural, _scan_location, _scan_roots
|
||||
from .admin import (
|
||||
SCAN_LOG_PREFIXES,
|
||||
_BatchHistory,
|
||||
_file_size,
|
||||
_plural,
|
||||
_scan_location,
|
||||
_scan_roots,
|
||||
)
|
||||
from .jobs import THUMBNAILS_JOB_KIND
|
||||
|
||||
# The kind the monitor's recording checks admission under (never registered).
|
||||
@@ -56,11 +79,30 @@ 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):
|
||||
@@ -78,6 +120,15 @@ 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"
|
||||
|
||||
@@ -90,6 +141,7 @@ 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(
|
||||
@@ -102,13 +154,13 @@ class ReviewRecordingMixin:
|
||||
)
|
||||
if review is not None:
|
||||
review["errors"] += 1
|
||||
return
|
||||
if review is None:
|
||||
return
|
||||
if outcome in NEW_OUTCOMES:
|
||||
review["added"] += 1
|
||||
if outcome in QUEUED_OUTCOMES:
|
||||
review["queued"] += 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
|
||||
|
||||
def _record_review_sync(
|
||||
self, media_file, roots, review=None, inspection=False, scanned=None
|
||||
@@ -137,14 +189,55 @@ 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):
|
||||
"""The scan status of an unlinked file the default profile left
|
||||
ambiguous without a choice (blocking).
|
||||
"""``(scan_status, record_outcome)`` of an unlinked file the default
|
||||
profile left ambiguous without a choice, or unresolved (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``, and its
|
||||
pending items without a choice leave the queue. The profile runs at
|
||||
when a saved row links it already. Otherwise ``unresolved``
|
||||
(``untraced``), 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
|
||||
@@ -160,15 +253,17 @@ class ReviewRecordingMixin:
|
||||
)
|
||||
if review is not None:
|
||||
review["errors"] += 1
|
||||
return "unresolved"
|
||||
return "unresolved", None
|
||||
if choice is None:
|
||||
self._settle_untraced_reviews([media_file], roots, review)
|
||||
self._settle_stale_reviews(media_file, roots, canonical, review)
|
||||
return "unresolved"
|
||||
return "unresolved", "untraced"
|
||||
if self._review_file_linked(media_file, roots):
|
||||
return "unchanged"
|
||||
self._record_scanned_review(media_file, roots, review, scanned=choice)
|
||||
return "ambiguous"
|
||||
return "unchanged", None
|
||||
recorded = self._record_scanned_review(
|
||||
media_file, roots, review, scanned=choice
|
||||
)
|
||||
return "ambiguous", recorded
|
||||
|
||||
def _inspection_choice(self, media_file, roots, canonical):
|
||||
"""``(canonical, resolution_or_None)`` when the file offers a choice.
|
||||
@@ -198,17 +293,21 @@ class ReviewRecordingMixin:
|
||||
return canonical, None
|
||||
memory = self._untraced_memory()
|
||||
key = _memory_key(locator)
|
||||
if state is not None and memory.get(key) == state:
|
||||
return None
|
||||
# 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
|
||||
resolution = review_capture.inspection_choice(canonical, media_file.name)
|
||||
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))]
|
||||
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))]
|
||||
return None
|
||||
|
||||
def _settle_stale_reviews(self, media_file, roots, canonical, review=None):
|
||||
@@ -248,10 +347,11 @@ class ReviewRecordingMixin:
|
||||
return removed
|
||||
|
||||
def _untraced_memory(self):
|
||||
memory = getattr(self, "_untraced_inspections", None)
|
||||
if memory is None:
|
||||
memory = self._untraced_inspections = {}
|
||||
return memory
|
||||
with _UNTRACED_MEMORY_LOCK:
|
||||
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):
|
||||
@@ -310,8 +410,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 with fewer than two
|
||||
candidates that carry a prompt. Blocking; best effort like the linked
|
||||
``media_files`` are files found ambiguous without a candidate that
|
||||
carries a prompt. Blocking; best effort like the linked
|
||||
settle (a failure is logged and counted in ``review["errors"]``).
|
||||
Returns how many items left.
|
||||
"""
|
||||
@@ -335,18 +435,23 @@ class ReviewRecordingMixin:
|
||||
return removed
|
||||
|
||||
def record_review_file(self, image_path):
|
||||
"""Apply the Needs review rule to one monitor output (its worker thread).
|
||||
"""Apply the Needs review rule to one monitor output (review worker).
|
||||
|
||||
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.
|
||||
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.
|
||||
"""
|
||||
busy = self._jobs.blocker(
|
||||
REVIEW_RECORDING_KIND, admission="records", compatible=PREVIEW_ONLY_KINDS
|
||||
@@ -366,7 +471,166 @@ class ReviewRecordingMixin:
|
||||
if self._review_file_linked(located, roots):
|
||||
self._settle_scanned_reviews([located], roots)
|
||||
return "linked"
|
||||
return "skipped"
|
||||
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)
|
||||
|
||||
@staticmethod
|
||||
def _log_review_items(job, review):
|
||||
@@ -398,3 +662,215 @@ 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
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
"""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),
|
||||
},
|
||||
)
|
||||
@@ -205,7 +205,8 @@ 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).
|
||||
"""
|
||||
if "\\" in filepath or ":" in filepath:
|
||||
# #646: a backslash is a separator only on Windows.
|
||||
if ":" in filepath or (os.sep == "\\" and "\\" in filepath):
|
||||
return False
|
||||
parts = filepath.split("/")
|
||||
if len(parts) < 2 or parts[0] != "thumbnails":
|
||||
@@ -387,7 +388,6 @@ class AutoThumbnailer:
|
||||
self._worker_running = False
|
||||
self._closed = False
|
||||
self._busy = False
|
||||
self._batch = 0
|
||||
|
||||
@property
|
||||
def failure_count(self):
|
||||
@@ -547,7 +547,6 @@ class AutoThumbnailer:
|
||||
with self._changed:
|
||||
self._worker_running = False
|
||||
self._busy = False
|
||||
self._batch = 0
|
||||
self._changed.notify_all()
|
||||
|
||||
def _drain(self):
|
||||
@@ -562,7 +561,6 @@ 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
|
||||
@@ -570,7 +568,6 @@ 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)
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ CONTENT_TYPES = {
|
||||
".jpeg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
".gif": "image/gif",
|
||||
".avif": "image/avif", # #652: served as itself, never a preview
|
||||
}
|
||||
THUMB_SUFFIX = "_thumb"
|
||||
|
||||
@@ -133,7 +134,9 @@ 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).
|
||||
IMAGE_SOURCE_ORDER = (".png", ".jpg", ".jpeg", ".webp", ".gif")
|
||||
# #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")
|
||||
|
||||
|
||||
def source_rank(source_extension):
|
||||
|
||||
+47
-2
@@ -38,6 +38,7 @@ 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
|
||||
|
||||
@@ -45,6 +46,7 @@ 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")
|
||||
@@ -195,7 +197,9 @@ 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
|
||||
SUPPORTED_EXTENSIONS = [".png", ".jpg", ".jpeg", ".webp", ".gif"]
|
||||
# #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]
|
||||
PROCESSING_DELAY = 2.0 # Seconds to wait before processing new files
|
||||
|
||||
# Prompt tracking settings
|
||||
@@ -301,7 +305,9 @@ class GalleryConfig:
|
||||
if directories is not None:
|
||||
cls.MONITORING_DIRECTORIES = directories
|
||||
if "extensions" in monitoring:
|
||||
cls.SUPPORTED_EXTENSIONS = monitoring["extensions"]
|
||||
extensions = cls._validated_extensions(monitoring["extensions"])
|
||||
if extensions is not None:
|
||||
cls.SUPPORTED_EXTENSIONS = extensions
|
||||
if "processing_delay" in monitoring:
|
||||
cls.PROCESSING_DELAY = monitoring["processing_delay"]
|
||||
|
||||
@@ -355,6 +361,45 @@ 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.
|
||||
|
||||
+27
-9
@@ -111,23 +111,29 @@ def preview(
|
||||
"""The review's counts (blocking; reads only, requests nothing).
|
||||
|
||||
``{lora_files, with_metadata, skipped, with_local_media,
|
||||
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``).
|
||||
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``).
|
||||
"""
|
||||
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:
|
||||
@@ -142,6 +148,8 @@ 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()),
|
||||
@@ -149,17 +157,22 @@ 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."""
|
||||
"""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.
|
||||
"""
|
||||
model_name = lora_utils.get_model_name_from_metadata(metadata)
|
||||
text = lora_utils.get_example_prompt_from_metadata(metadata) or model_name
|
||||
tags = ["lora-manager", f"lora:{model_name}"]
|
||||
tags.extend(lora_utils.get_trigger_words_from_metadata(metadata))
|
||||
words, not_tags = lora_utils.trigger_word_tags(metadata)
|
||||
tags = ["lora-manager", f"lora:{model_name}", *words]
|
||||
return {
|
||||
"name": model_name,
|
||||
"text": text,
|
||||
"hash": generate_prompt_hash(text),
|
||||
"tags": list(dict.fromkeys(tags)),
|
||||
"images": images,
|
||||
"trigger_not_tags": not_tags,
|
||||
}
|
||||
|
||||
|
||||
@@ -171,7 +184,11 @@ 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}
|
||||
default_factory=lambda: {
|
||||
"downloaded": 0,
|
||||
"download_errors": 0,
|
||||
"trigger_not_tags": 0,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -219,6 +236,7 @@ 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:
|
||||
|
||||
@@ -22,11 +22,13 @@ 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
|
||||
|
||||
@@ -387,6 +389,44 @@ 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.
|
||||
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
[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.6.0"
|
||||
version = "3.8.0"
|
||||
license = {file = "LICENSE"}
|
||||
requires-python = ">=3.12"
|
||||
dependencies = ["watchdog>=2.1.0", "Pillow>=10.1.0"]
|
||||
@@ -18,7 +18,7 @@ Repository = "https://github.com/ComfyAssets/ComfyUI_PromptManager"
|
||||
[tool.comfy]
|
||||
PublisherId = "kiko9"
|
||||
DisplayName = "ComfyUI_PromptManager"
|
||||
Icon = "https://avatars.githubusercontent.com/u/213204677?s=200"
|
||||
Icon = "https://raw.githubusercontent.com/ComfyAssets/ComfyUI_PromptManager/main/assets/brand/icon-256.png"
|
||||
|
||||
[tool.black]
|
||||
line-length = 88
|
||||
|
||||
@@ -4,7 +4,7 @@ Pillow>=10.1.0
|
||||
aiohttp>=3.11.8
|
||||
|
||||
# Tests and coverage
|
||||
coverage>=7.17.0
|
||||
coverage>=7.17.2
|
||||
numpy>=1.25.0 # WD14 engine tests
|
||||
|
||||
# Code quality
|
||||
|
||||
@@ -8,9 +8,8 @@
|
||||
// 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 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 })`.
|
||||
// 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 })`.
|
||||
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';
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// #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.');
|
||||
});
|
||||
@@ -1,182 +0,0 @@
|
||||
// #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);
|
||||
});
|
||||
@@ -1,47 +0,0 @@
|
||||
// #615: each old page says it will be removed and links to where its job lives now. The page keeps working, and the
|
||||
// notice takes its own room: nothing is pushed off a page whose layout fills the window.
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
|
||||
const PAGES = Object.freeze([
|
||||
{ path: '/prompt_manager/admin', section: 'library', heading: 'Prompt library' },
|
||||
{ path: '/prompt_manager/gallery', section: 'images', heading: 'Images' },
|
||||
{ path: '/prompt_manager/gallery.html', section: 'inspect', heading: 'Inspect a file' },
|
||||
]);
|
||||
|
||||
test.beforeEach(async ({ page, request, browserName }) => {
|
||||
await startCoverage(page, browserName);
|
||||
await expect(await request.post('/__test__/reset', {})).toBeOK();
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem('pm_update_notice_dismissed', '3.2.0');
|
||||
localStorage.setItem('gallerySettings', JSON.stringify({ checkThumbnailsAtStartup: false }));
|
||||
});
|
||||
});
|
||||
|
||||
test.afterEach(async ({ page, browserName }) => {
|
||||
await saveCoverage(page, browserName);
|
||||
});
|
||||
|
||||
for (const { path, section, heading } of PAGES) {
|
||||
test(`${path} says it will be removed and links to ${section}`, async ({ page }) => {
|
||||
await page.goto(path);
|
||||
const notice = page.locator('#legacy-removal-notice');
|
||||
await expect(notice).toBeVisible();
|
||||
await expect(notice).toContainText('This page will be removed in a future release.');
|
||||
await notice.getByRole('link', { name: 'Open the workspace' }).click();
|
||||
await expect(page).toHaveURL(new RegExp(`/prompt_manager/workspace#/${section}$`));
|
||||
await expect(page.locator('#workspace-main h1')).toHaveText(heading);
|
||||
});
|
||||
}
|
||||
|
||||
test('the notice leaves the metadata page filling the window', async ({ page }) => {
|
||||
await page.goto('/prompt_manager/gallery.html');
|
||||
await expect(page.locator('#legacy-removal-notice')).toBeVisible();
|
||||
const { bottom, height, scroll } = await page.locator('#image-area').evaluate(area => ({
|
||||
bottom: area.getBoundingClientRect().bottom,
|
||||
height: window.innerHeight,
|
||||
scroll: document.documentElement.scrollHeight,
|
||||
}));
|
||||
expect(bottom).toBeLessThanOrEqual(height);
|
||||
expect(scroll).toBeLessThanOrEqual(height);
|
||||
});
|
||||
@@ -1,286 +0,0 @@
|
||||
// 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');
|
||||
}
|
||||
});
|
||||
@@ -21,7 +21,7 @@ export function mapLibraryConcept(reference) {
|
||||
// Save view is the concept's own (saved views, #249 D16 retired).
|
||||
const toolbar={...library.toolbar};
|
||||
toolbar.items=toolbar.items.map(item=>{
|
||||
// D14: the Library appends its Oldest first after the concept's sorts; D153 (#447) drops "Highest rated"; D205
|
||||
// D14: the Library appends its Oldest first after the concept's sorts; D153 (#447) drops "Highest rated"; D206
|
||||
// (#620) appends the old Dashboard's three sorts.
|
||||
if(item.id==='sort')return {...item,options:[...item.options.filter(option=>option!=='Highest rated'),'Oldest first','Recently used','Most used','Name Z–A']};
|
||||
// D36: the category list is the Library's real list, sorted alphabetically; the concept lists prompt order.
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
// #668 (D207): the old admin, gallery and metadata pages are gone. Their URLs, and the old tag bookmarks, lead into
|
||||
// the workspace, against the real server.
|
||||
import {startCoverage,saveCoverage} from '../../tools/vendor/browser-coverage.mjs';
|
||||
import {test,expect} from './fixtures.mjs';
|
||||
|
||||
const cards=page=>page.locator('article[data-prompt-id]');
|
||||
const card=(page,text)=>cards(page).filter({has:page.getByText(text,{exact:true})});
|
||||
const filtersButton=page=>page.locator('#workspace-main search.toolbar').getByRole('button',{name:/^Filters(?: · \d)?$/});
|
||||
const caption=page=>page.locator('#workspace-main .section-caption > span').first();
|
||||
const heading=page=>page.locator('#workspace-main h1').first();
|
||||
/** The workspace at exactly this hash. */
|
||||
const at=hash=>url=>url.pathname.endsWith('/prompt_manager/workspace')&&url.search===''&&url.hash===hash;
|
||||
|
||||
test.beforeEach(async({page,request,browserName})=>{
|
||||
await startCoverage(page,browserName);await expect(await request.post('/__test__/reset',{data:{native_library:true}})).toBeOK();
|
||||
page.oldUrlErrors=[];page.on('pageerror',error=>page.oldUrlErrors.push(error.message));
|
||||
// A deleted page asset that is still requested would answer 404.
|
||||
page.missing=[];page.on('response',response=>{if(response.status()===404)page.missing.push(new URL(response.url()).pathname);});
|
||||
});
|
||||
test.afterEach(async({page,browserName})=>{
|
||||
await saveCoverage(page,browserName);expect(page.oldUrlErrors).toEqual([]);expect(page.missing).toEqual([]);
|
||||
});
|
||||
|
||||
for(const [url,hash,title] of [
|
||||
['/prompt_manager/admin','#/library','Prompt library'],
|
||||
['/prompt_manager/admin#/tags','#/tags','Tags & categories'],
|
||||
['/prompt_manager/admin#/tags/','#/tags','Tags & categories'],
|
||||
['/prompt_manager/admin#/something-else','#/library','Prompt library'],
|
||||
['/prompt_manager/gallery','#/images','Images'],
|
||||
['/prompt_manager/gallery.html','#/inspect','Inspect a file'],
|
||||
['/prompt_manager/web','#/library','Prompt library'],
|
||||
]) {
|
||||
test(`${url} opens the workspace's ${title}`,async({page})=>{
|
||||
await page.goto(url);
|
||||
await expect(page).toHaveURL(at(hash));
|
||||
await expect(heading(page)).toHaveText(title);
|
||||
});
|
||||
}
|
||||
|
||||
test('an old one-tag bookmark opens the Library filtered by that tag',async({page})=>{
|
||||
await page.goto('/prompt_manager/admin#/tags/cats');
|
||||
await expect(page).toHaveURL(at('#/library?tag=cats'));
|
||||
await expect(caption(page)).toHaveText(/^1 positive prompt · /);
|
||||
await expect(card(page,'Cat portrait')).toHaveCount(1);await expect(cards(page)).toHaveCount(1);
|
||||
await expect(filtersButton(page)).toHaveText('Filters · 1');
|
||||
});
|
||||
|
||||
test('an old two-tag bookmark matches all of the tags, and any of them with ?mode=or',async({page})=>{
|
||||
await page.goto('/prompt_manager/admin#/tags/cats,dogs');
|
||||
await expect(caption(page)).toHaveText(/^0 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters · 1');
|
||||
await page.goto('about:blank');
|
||||
await page.goto('/prompt_manager/admin#/tags/cats,dogs?mode=or');
|
||||
await expect(page).toHaveURL(at('#/library?tag=cats&tag=dogs&tag_mode=any'));
|
||||
await expect(caption(page)).toHaveText(/^2 positive prompts · /);
|
||||
await expect(card(page,'Cat portrait')).toHaveCount(1);await expect(card(page,'Dog landscape')).toHaveCount(1);
|
||||
await expect(filtersButton(page)).toHaveText('Filters · 2');
|
||||
});
|
||||
|
||||
test('an old untagged bookmark asks the Library for the prompts without a tag',async({page})=>{
|
||||
const listed=page.waitForResponse(item=>{const url=new URL(item.url());return url.pathname==='/prompt_manager/library'&&url.searchParams.get('tag_mode')==='untagged';});
|
||||
await page.goto('/prompt_manager/admin#/tags/__untagged__');
|
||||
expect((await (await listed).json()).tag_mode).toBe('untagged');
|
||||
await expect(page).toHaveURL(at('#/library?tag_mode=untagged'));await expect(filtersButton(page)).toHaveText('Filters · 1');
|
||||
});
|
||||
|
||||
test('the old dashboard URL shows the whole Library even after a tag bookmark in the same tab',async({page})=>{
|
||||
await page.goto('/prompt_manager/admin#/tags/cats');
|
||||
await expect(caption(page)).toHaveText(/^1 positive prompt · /);
|
||||
await page.goto('/prompt_manager/admin');
|
||||
await expect(page).toHaveURL(at('#/library'));
|
||||
await expect(caption(page)).toHaveText(/^3 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters');
|
||||
});
|
||||
|
||||
test('Back from the workspace skips the old URL instead of bouncing through it',async({page})=>{
|
||||
await page.goto('/prompt_manager/workspace#/overview');
|
||||
await expect(heading(page)).toHaveText('Overview');
|
||||
for(const [url,title] of [['/prompt_manager/admin#/tags/cats','Prompt library'],['/prompt_manager/gallery','Images']]) {
|
||||
await page.goto(url);
|
||||
await expect(heading(page)).toHaveText(title);
|
||||
await page.goBack();
|
||||
await expect(page).toHaveURL(at('#/overview'));
|
||||
await expect(heading(page)).toHaveText('Overview');
|
||||
}
|
||||
});
|
||||
|
||||
test('the old pages\' scripts and stylesheet are no longer served',async({request})=>{
|
||||
for(const asset of ['js/admin.js','js/gallery.js','js/tags-page.js','lib/tailwind/styles.css']) {
|
||||
expect((await request.get(`/prompt_manager/${asset}`)).status(),asset).toBe(404);
|
||||
}
|
||||
});
|
||||
|
||||
test('the server itself redirects the two old pages that had no hash routes',async({request})=>{
|
||||
for(const [url,target] of [['/prompt_manager/gallery','workspace#/images'],['/prompt_manager/gallery.html','workspace#/inspect']]) {
|
||||
const response=await request.get(url,{maxRedirects:0});
|
||||
expect([response.status(),response.headers().location]).toEqual([302,target]);
|
||||
}
|
||||
});
|
||||
@@ -102,11 +102,16 @@ test('inspection failures retry and a delayed previous selection cannot replace
|
||||
release();await expect(role(details(page),'Positive')).toContainText('Dog landscape');
|
||||
});
|
||||
|
||||
test('sender requires explicit destination, previews full changes and acknowledges only the applied pair',async({page,context},testInfo)=>{
|
||||
test('sender chooses the only destination, previews full changes and acknowledges only the applied pair',async({page,context},testInfo)=>{
|
||||
const host=await fakeHost(context,page);
|
||||
try {
|
||||
await page.goto(workspace);await select(page,'0:shared/same.png');await details(page).getByRole('button',{name:/^Send prompt pair to ComfyUI: /}).click();
|
||||
const sender=dialog(page);await expect(sender.getByRole('button',{name:'Apply to ComfyUI',exact:true})).toBeDisabled();
|
||||
const sender=dialog(page);
|
||||
// "One eligible node selects that node" (TESTING.md, D173); wait for discovery's
|
||||
// answer, since Apply is disabled only while the sender is still looking for windows.
|
||||
await expect(sender).toContainText('Sending to #pair-1 My prompt pair in Test ComfyUI.');
|
||||
await expect(sender.getByRole('button',{name:'Apply to ComfyUI',exact:true})).toBeEnabled();
|
||||
expect(await host.evaluate(()=>window.applied)).toEqual([]);
|
||||
const chosen=await chooseDestination(page);await chosen.getByRole('button',{name:'Preview changes',exact:true}).click();
|
||||
for(const text of ['Existing positive','Existing negative','Cat portrait','blurry, watermark','trigger Cat portrait detail'])await expect(chosen).toContainText(text);
|
||||
expect(await host.evaluate(()=>window.applied)).toEqual([]);
|
||||
|
||||
@@ -655,6 +655,17 @@ def create_app(root: Path) -> web.Application:
|
||||
shutil.copyfile(root / "output" / "shared" / "same.png", destination)
|
||||
return web.json_response({"success": True})
|
||||
|
||||
@routes.post("/__test__/add-backslash-image")
|
||||
async def add_backslash_image(request: web.Request) -> web.Response:
|
||||
"""#646: a folder whose name holds a backslash, as a Windows-style
|
||||
``filename_prefix`` makes on a POSIX server."""
|
||||
if os.sep == "\\":
|
||||
return web.json_response({"success": False}, status=409)
|
||||
destination = root / "output" / "model.safetensors\\2026-11-17" / "slash.png"
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(root / "output" / "shared" / "same.png", destination)
|
||||
return web.json_response({"success": True})
|
||||
|
||||
@routes.post("/__test__/add-local-inspect-file")
|
||||
async def add_local_inspect_file(request: web.Request) -> web.Response:
|
||||
"""Serve one committed Inspect fixture from the output folder.
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Saving System settings in a spec (#631).
|
||||
*
|
||||
* A host save commits config.json durably (fsync, then an atomic replace). On a busy CI disk that write alone can
|
||||
* take seconds, longer than the five an expect gives the status line. So a spec waits for the save's answer before
|
||||
* it reads the status (TESTING.md: wait for a response, never for time). A save kept in this browser sends nothing
|
||||
* and needs no wait.
|
||||
*/
|
||||
|
||||
export const SETTINGS_URL = '/prompt_manager/settings';
|
||||
export const LORA_ENABLE_URL = '/prompt_manager/lora/enable';
|
||||
|
||||
/** The host's answer to the next save sent to `url`. Start it before the click that saves. */
|
||||
export const hostSaveAnswer = (page, url = SETTINGS_URL) =>
|
||||
page.waitForResponse(response => response.request().method() === 'POST' && response.url().endsWith(url));
|
||||
|
||||
/** Click `button` and wait for the host's answer to the save it sends to `url`; resolves to that response. */
|
||||
export async function clickHostSave(page, button, url = SETTINGS_URL) {
|
||||
const answer = hostSaveAnswer(page, url);
|
||||
await button.click();
|
||||
return answer;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { clickHostSave, LORA_ENABLE_URL } from './settings-save.mjs';
|
||||
import { SIZES, THEMES, seedConcept, openConcept, openProduction, diffInventory, mutate } from './concept-inventory.mjs';
|
||||
|
||||
// #249 System S10 Task 28: System › Integrations (app.js renderSystem 682–684) and the LoRA import review against the
|
||||
@@ -260,7 +261,8 @@ function measureReview() {
|
||||
|
||||
/**
|
||||
* D107: the server's import plan in the concept's review: "Review LoRA import" with "LoRA reference data" as its `h3`,
|
||||
* the concept's four rows with the plan's values plus Found and Network, the LoRAs it found (`details`), the hold
|
||||
* the concept's four rows with the plan's values plus Found, Trigger words (#618, D210) and Network, the LoRAs it
|
||||
* found (`details`), the hold
|
||||
* line with the cache sentence in the concept's `p.small`, the D55 backup box, and Cancel / "Start import".
|
||||
*/
|
||||
function mapImportConcept(reference, plan) {
|
||||
@@ -272,6 +274,7 @@ function mapImportConcept(reference, plan) {
|
||||
heading: { ...reference.heading, text: 'LoRA reference data' },
|
||||
grid: { ...reference.grid, rows: [['LoraManager', 'environment settings · alongside storage · library default'],
|
||||
['Scope', plan.scope.label], ['Found', '2 metadata files · 2 LoRAs · 0 with local images'],
|
||||
['Trigger words', '2 become tags'],
|
||||
['Protected', 'Nothing is protected'], ['Network', 'Downloads up to 2 example images from CivitAI'],
|
||||
['Backup', `Create and verify before changes (${plan.backup.destination_label})`],
|
||||
['Media on disk', 'No files are removed; image links are replaced']] },
|
||||
@@ -300,7 +303,8 @@ async function productionReview(page, request, theme) {
|
||||
await expect(page.locator('#workspace-main #renderer-status')).toHaveText(RENDERER_NONE);
|
||||
// The import reviews what is enabled: save the integration on first.
|
||||
await page.locator('#workspace-main #lora-enable').check();
|
||||
await page.getByRole('button', { name: 'Save preferences', exact: true }).click();
|
||||
// The save writes config.json durably, which a busy CI disk can hold for seconds (#631): wait for its answer.
|
||||
await clickHostSave(page, page.getByRole('button', { name: 'Save preferences', exact: true }), LORA_ENABLE_URL);
|
||||
await expect(page.locator('#settings-status')).toHaveText('Saved to the server configuration.');
|
||||
const answer = page.waitForResponse(response => response.url().endsWith(PREVIEW_URL));
|
||||
await page.locator('#workspace-main').getByRole('button', { name: 'Review import', exact: true }).click();
|
||||
@@ -331,9 +335,10 @@ test('LoRA import review comparison detects mutations', async ({ page, request }
|
||||
const expected = mapImportConcept(concept, plan);
|
||||
const paths = async () => diffInventory(expected, await page.evaluate(measureReview)).map(item => item.path);
|
||||
expect(await paths()).toEqual([]);
|
||||
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[4].textContent = 'Downloads'; });
|
||||
expect(await paths()).toEqual(['grid.rows.4.0']);
|
||||
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[4].textContent = 'Network'; });
|
||||
// Network is the sixth row (after #618's Trigger words).
|
||||
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[5].textContent = 'Downloads'; });
|
||||
expect(await paths()).toEqual(['grid.rows.5.0']);
|
||||
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[5].textContent = 'Network'; });
|
||||
const undoGrid = await mutate(page, { css: 'dialog#modal dl.meta-grid { column-gap: 3px; }' });
|
||||
expect(await paths()).toEqual(expect.arrayContaining(['grid.columnGap']));
|
||||
await undoGrid();
|
||||
|
||||
@@ -83,9 +83,29 @@ function mapPairRow(reference) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* D210 (#618, beyond the concept): Database adds "Tag cleanup" after "Pair category and tags", shaped like the concept's
|
||||
* danger row (Unused prompt components') with its own button label, "Find tags".
|
||||
*/
|
||||
function mapTagRow(reference) {
|
||||
return {
|
||||
...reference,
|
||||
surfaces: reference.surfaces.map(surface => {
|
||||
const danger = surface.rows.find(row => row.title === 'Unused prompt components');
|
||||
const at = surface.rows.findIndex(row => row.title === 'Pair category and tags');
|
||||
if (!danger || at < 0) return surface;
|
||||
return { ...surface, tree: [...surface.tree, 'div.operation'], rows: [...surface.rows.slice(0, at + 1),
|
||||
{ ...danger, title: 'Tag cleanup', description: 'Find tags that are whole comma lists or are used nowhere. ' +
|
||||
'Review them, then remove only what you tick.',
|
||||
actions: danger.actions.map(action => ({ ...action, text: 'Find tags' })) },
|
||||
...surface.rows.slice(at + 1)] };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** D102: the Metadata cache row says why its review is unavailable and its button is aria-disabled (D93's dimmed style). */
|
||||
function mapMaintenanceConcept(reference) {
|
||||
const mapped = mapPairRow(reference);
|
||||
const mapped = mapTagRow(mapPairRow(reference));
|
||||
return {
|
||||
...mapped,
|
||||
surfaces: mapped.surfaces.map(surface => ({ ...surface, rows: surface.rows.map(row => row.title !== 'Metadata cache' ? row : {
|
||||
@@ -229,8 +249,8 @@ test('maintenance comparison detects mutations', async ({ page, request }) => {
|
||||
const expected = mapMaintenanceConcept(concept);
|
||||
const production = await productionMaintenance(page, 'dark');
|
||||
expect(diffInventory(expected, production)).toEqual([]);
|
||||
// Mapped only for the D192 row, the section differs only on the D102 row.
|
||||
expect(diffInventory(mapPairRow(concept), production).map(item => item.path).sort()).toEqual([
|
||||
// Mapped only for the D192 and D210 rows, the section differs only on the D102 row.
|
||||
expect(diffInventory(mapTagRow(mapPairRow(concept)), production).map(item => item.path).sort()).toEqual([
|
||||
'surfaces.1.rows.3.actions.0.cursor', 'surfaces.1.rows.3.actions.0.opacity', 'surfaces.1.rows.3.description']);
|
||||
const measure = () => page.evaluate(measureMaintenance, '#workspace-main');
|
||||
const paths = async () => diffInventory(expected, await measure()).map(item => item.path);
|
||||
|
||||
@@ -1,280 +0,0 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
|
||||
test.beforeEach(async ({ request, page, browserName }) => {
|
||||
await startCoverage(page, browserName);
|
||||
await expect(await request.post('/__test__/reset')).toBeOK();
|
||||
page.workflowErrors = [];
|
||||
page.on('pageerror', error => page.workflowErrors.push(error.message));
|
||||
page.on('response', response => {
|
||||
if (response.status() >= 500 && response.url().includes('/prompt_manager/')) {
|
||||
page.workflowErrors.push(`${response.status()} ${response.url()}`);
|
||||
}
|
||||
});
|
||||
await page.addInitScript(() => { localStorage.setItem('pm_update_notice_dismissed', '3.2.0'); });
|
||||
});
|
||||
|
||||
test.afterEach(async ({ page, browserName }) => {
|
||||
await saveCoverage(page, browserName);
|
||||
expect(page.workflowErrors).toEqual([]);
|
||||
});
|
||||
|
||||
// #249 S6b: the legacy admin page says where the library lives (the fixture's database is configured explicitly).
|
||||
test('the admin page names the library location', async ({ page }) => {
|
||||
await page.goto('/prompt_manager/admin');
|
||||
await expect(page.locator('#libraryLocation')).toHaveText('Library: browser.db (set in config.json)');
|
||||
await expect(page.locator('#totalPrompts')).not.toHaveText('-');
|
||||
});
|
||||
|
||||
test('actual gallery form saves a prompt that the admin page can edit and reload', async ({ page, request }) => {
|
||||
await page.goto('/prompt_manager/gallery');
|
||||
await page.locator('#addPromptBtn').click();
|
||||
await page.locator('#addPromptText').fill('Browser saved landscape');
|
||||
await page.locator('#addPromptCategory').fill('Browser tests');
|
||||
await page.locator('#addPromptTagInput').fill('browser-tag');
|
||||
await page.locator('#addPromptTagInput').press('Enter');
|
||||
await page.locator('#saveNewPromptBtn').click();
|
||||
await expect(page.locator('#addPromptModal')).toBeHidden();
|
||||
await page.goto('/prompt_manager/admin');
|
||||
const text = page.locator('.prompt-text').filter({ hasText: 'Browser saved landscape' });
|
||||
await expect(text).toBeVisible();
|
||||
const id = await text.getAttribute('data-id');
|
||||
await page.locator(`[data-action="edit"][data-prompt-id="${id}"]`).click();
|
||||
const editor = page.locator(`.prompt-text[data-id="${id}"]`);
|
||||
await editor.fill('Browser edited portrait');
|
||||
// The page shows the edit at once and saves it after: reload only once the save answered (a reload that wins the
|
||||
// race abandons the PUT, as seen on WebKit in CI).
|
||||
const savedEdit = page.waitForResponse(item => item.request().method() === 'PUT'
|
||||
&& item.url().endsWith(`/prompt_manager/prompts/${id}`));
|
||||
await editor.press('Enter');
|
||||
await expect(page.locator('.prompt-text').filter({ hasText: 'Browser edited portrait' })).toBeVisible();
|
||||
expect((await savedEdit).ok()).toBe(true);
|
||||
await page.reload();
|
||||
await expect(page.locator('.prompt-text').filter({ hasText: 'Browser edited portrait' })).toBeVisible();
|
||||
const saved = await request.post('/prompt_manager/save', { data: { text: 'Browser saved landscape' } });
|
||||
expect((await saved.json()).prompt_id).not.toBe(Number(id));
|
||||
});
|
||||
|
||||
// WebKit fails a fetch that a leaving page starts ("Fetch API cannot load … due to access control checks."), and
|
||||
// Playwright reports that console error as a page error. A save's follow-up reads must not start once the page hides:
|
||||
// here the statistics read after an in-place edit is held at the server while the page reloads.
|
||||
test('an in-place edit whose follow-up reads outlive the page starts no read while it leaves', async ({ page, request }) => {
|
||||
await page.goto('/prompt_manager/admin');
|
||||
const text = page.locator('.prompt-text').filter({ hasText: 'Cat portrait' });
|
||||
const id = await text.getAttribute('data-id');
|
||||
await expect(await request.post('/__test__/hold', { data: { path: '/prompt_manager/stats' } })).toBeOK();
|
||||
await page.locator(`[data-action="edit"][data-prompt-id="${id}"]`).click();
|
||||
const editor = page.locator(`.prompt-text[data-id="${id}"]`);
|
||||
await editor.fill('Cat portrait at dusk');
|
||||
await editor.press('Enter');
|
||||
const held = async () => (await (await request.get('/__test__/hold')).json()).held['/prompt_manager/stats'];
|
||||
await expect.poll(held).toBe(1);
|
||||
await page.reload({ waitUntil: 'commit' });
|
||||
await expect(await request.post('/__test__/release')).toBeOK();
|
||||
await expect(page.locator('.prompt-text').filter({ hasText: 'Cat portrait at dusk' })).toBeVisible();
|
||||
});
|
||||
|
||||
// A leave that never happens (a stopped navigation, or one answered with a download) must not leave the list dead.
|
||||
test('a page whose leave was called off reads its list again on the next input', async ({ page }) => {
|
||||
await page.goto('/prompt_manager/admin');
|
||||
await expect(page.locator('.prompt-text').first()).toBeVisible();
|
||||
await page.evaluate(() => window.dispatchEvent(new Event('beforeunload')));
|
||||
await page.mouse.click(1, 1);
|
||||
const reread = page.waitForResponse(response => new URL(response.url()).pathname === '/prompt_manager/recent');
|
||||
await page.locator('#sortBy').selectOption('created_asc');
|
||||
expect(new URL((await reread).url()).searchParams.get('sort')).toBe('created_asc');
|
||||
await expect(page.locator('#resultsTitle')).toHaveText('Recent Prompts');
|
||||
});
|
||||
|
||||
// The gallery's startup thumbnail check runs a second after load. When that second ends while the page is leaving,
|
||||
// the check must start no read: WebKit fails it with "Fetch API cannot load … due to access control checks." and
|
||||
// Playwright reports a page error (seen in CI on PR #289). The page clock makes the second end after the leave began.
|
||||
for (const leave of ['beforeunload', 'pagehide']) {
|
||||
test(`the gallery startup check starts no read after ${leave}`, async ({ page }) => {
|
||||
await page.clock.install();
|
||||
const statusReads = [];
|
||||
page.on('request', req => { if (req.url().includes('/images/thumbnails/status')) statusReads.push(req.url()); });
|
||||
await page.goto('/prompt_manager/gallery');
|
||||
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
|
||||
await page.evaluate(type => window.dispatchEvent(new Event(type)), leave);
|
||||
await page.clock.runFor(1500);
|
||||
// A read made after the clock ran is listed, so the listener saw every status read.
|
||||
await page.evaluate(() => fetch('/prompt_manager/images/thumbnails/status?probe=1'));
|
||||
expect(statusReads.map(url => new URL(url).search)).toEqual(['?probe=1']);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// #379: the reviewed tags are that image's own tags; no prompt changes.
|
||||
test('actual gallery review generates and persists tags for the selected root\'s image', async ({ page, request }) => {
|
||||
await page.goto('/prompt_manager/gallery');
|
||||
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
|
||||
await page.locator('#autoTagBtn').click();
|
||||
const generated = page.waitForResponse(response => response.url().endsWith('/prompt_manager/autotag/single'));
|
||||
await page.locator('#startReviewBtn').click();
|
||||
const generation = await generated;
|
||||
expect(generation.request().postDataJSON().root_index).toBe(0);
|
||||
await expect(page.locator('#reviewTagsContainer')).toContainText('sandstone');
|
||||
const result = page.waitForResponse(response => response.url().endsWith('/prompt_manager/autotag/apply'));
|
||||
await page.locator('#applyReviewBtn').click();
|
||||
expect((await (await result).json()).success).toBe(true);
|
||||
const data = await (await request.get('/prompt_manager/recent?limit=20')).json();
|
||||
expect(data.results.find(prompt => prompt.text === 'Cat portrait').tags).toEqual(['cats']);
|
||||
expect(data.results.find(prompt => prompt.text === 'Dog landscape').tags).toEqual(['dogs']);
|
||||
const tagged = await (await request.get('/prompt_manager/images/output?mode=workspace&tags=sandstone')).json();
|
||||
expect(tagged.images.map(image => `${image.root_index}:${image.path}`)).toEqual(['0:shared/same.png']);
|
||||
});
|
||||
|
||||
test('actual Tags page reloads the selected filter and opens its image viewer', async ({ page }) => {
|
||||
await page.goto('/prompt_manager/admin#/tags');
|
||||
await page.locator('[data-tag-name="cats"]').click();
|
||||
await expect(page.locator('#tagPromptsGrid')).toContainText('Cat portrait');
|
||||
const dogs = page.waitForResponse(response => response.url().includes('/tags/dogs/prompts?'));
|
||||
await page.locator('[data-tag-name="dogs"]').click();
|
||||
const [shown] = (await (await dogs).json()).prompts[0].images;
|
||||
await expect(page.locator('#tagPromptsGrid')).toContainText('Dog landscape');
|
||||
await expect(page.locator('#tagPromptsGrid')).not.toContainText('Cat portrait');
|
||||
await page.locator('#tagPromptsGrid img').first().click();
|
||||
await expect(page.locator('.viewer-canvas img')).toBeVisible();
|
||||
// The viewer's title names the shown image through the page's title callback. ViewerJS renders it only once the
|
||||
// image is viewed, so closing at "visible" alone left the callback unrun on slower hosts (CI coverage missed it).
|
||||
await expect(page.locator('.viewer-title')).toHaveText(shown.filename);
|
||||
await page.locator('.viewer-container').getByRole('button', { name: 'Close', exact: true }).click();
|
||||
await expect(page.locator('.viewer-container')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('actual gallery serves colliding filenames and shows the matching prompt', async ({ page }) => {
|
||||
await page.goto('/prompt_manager/gallery');
|
||||
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
|
||||
const images = page.locator('#galleryGrid img[data-original]');
|
||||
const first = await images.nth(0).getAttribute('data-original');
|
||||
const second = await images.nth(1).getAttribute('data-original');
|
||||
expect(first).not.toBe(second);
|
||||
await page.locator('#galleryGrid .image-item[data-image-index="0"]').click();
|
||||
await expect(page.locator('#metadata-content')).toContainText('Cat portrait');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expect(page.locator('#metadata-content')).toContainText('Dog landscape');
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('#metadata-sidebar')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('an edit collision is rejected by the backend and the page restores the original text', async ({ page }) => {
|
||||
await page.goto('/prompt_manager/admin');
|
||||
const original = page.locator('.prompt-text').filter({ hasText: 'Cat portrait' });
|
||||
const id = await original.getAttribute('data-id');
|
||||
await page.locator(`[data-action="edit"][data-prompt-id="${id}"]`).click();
|
||||
const editor = page.locator(`.prompt-text[data-id="${id}"]`);
|
||||
await editor.fill('Dog landscape');
|
||||
const rejected = page.waitForResponse(response => response.request().method() === 'PUT' && response.url().endsWith(`/prompts/${id}`));
|
||||
await editor.press('Enter');
|
||||
expect((await rejected).status()).toBe(409);
|
||||
await expect(editor).toHaveText('Cat portrait');
|
||||
await page.reload();
|
||||
await expect(page.locator(`.prompt-text[data-id="${id}"]`)).toHaveText('Cat portrait');
|
||||
});
|
||||
|
||||
test('a delayed real Tags response cannot replace a newer selection', async ({ page }) => {
|
||||
let release;
|
||||
const delayed = new Promise(resolve => { release = resolve; });
|
||||
let received;
|
||||
const waiting = new Promise(resolve => { received = resolve; });
|
||||
await page.route('**/prompt_manager/tags/cats/prompts?*', async route => {
|
||||
const response = await route.fetch();
|
||||
received();
|
||||
await delayed;
|
||||
await route.fulfill({ response });
|
||||
});
|
||||
await page.goto('/prompt_manager/admin#/tags');
|
||||
await page.locator('[data-tag-name="cats"]').click();
|
||||
await waiting;
|
||||
await page.locator('[data-tag-name="dogs"]').click();
|
||||
await expect(page.locator('#tagPromptsGrid')).toContainText('Dog landscape');
|
||||
const completed = page.waitForResponse(response => response.url().includes('/tags/cats/prompts?'));
|
||||
release();
|
||||
await completed;
|
||||
await expect(page.locator('#tagPromptsGrid')).not.toContainText('Cat portrait');
|
||||
});
|
||||
|
||||
test('gallery infinite scroll appends a real backend page while retaining existing cards', async ({ page, request }) => {
|
||||
await expect(await request.post('/__test__/reset', { data: { extra_images: 108 } })).toBeOK();
|
||||
await page.goto('/prompt_manager/gallery');
|
||||
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(100);
|
||||
await page.locator('#pageOptionsBtn').click();
|
||||
await page.locator('#infiniteScrollToggle').check();
|
||||
await page.locator('#saveSettingsBtn').click();
|
||||
await expect(page.locator('#settingsModal')).toBeHidden();
|
||||
const first = page.locator('#galleryGrid .image-item').first();
|
||||
await first.evaluate(element => { element.dataset.preserved = 'yes'; });
|
||||
await page.locator('#galleryScroll').evaluate(element => { element.scrollTop = element.scrollHeight; });
|
||||
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(110);
|
||||
await expect(first).toHaveAttribute('data-preserved', 'yes');
|
||||
});
|
||||
|
||||
async function promptSnapshot(request) {
|
||||
const response = await request.get('/prompt_manager/recent?limit=100');
|
||||
await expect(response).toBeOK();
|
||||
return (await response.json()).results.map(({ id, text, tags, images }) => ({
|
||||
id, text, tags: [...tags].sort(),
|
||||
images: images.map(image => image.image_path).sort(),
|
||||
})).sort((a, b) => a.id - b.id);
|
||||
}
|
||||
|
||||
function confirmNextDialog(page, accept, message) {
|
||||
page.once('dialog', async dialog => {
|
||||
expect(dialog.type()).toBe('confirm');
|
||||
expect(dialog.message()).toContain(message);
|
||||
await (accept ? dialog.accept() : dialog.dismiss());
|
||||
});
|
||||
}
|
||||
|
||||
async function deletePromptButton(page, text) {
|
||||
const prompt = page.locator('.prompt-text').filter({ hasText: text });
|
||||
await expect(prompt).toBeVisible();
|
||||
const id = await prompt.getAttribute('data-id');
|
||||
return page.locator(`[data-action="delete"][data-prompt-id="${id}"]`);
|
||||
}
|
||||
|
||||
test('prompt deletion requires confirmation and can retry after a network failure', async ({ page, request }) => {
|
||||
await page.goto('/prompt_manager/admin');
|
||||
const before = await promptSnapshot(request);
|
||||
const button = await deletePromptButton(page, 'Cat portrait');
|
||||
let deletes = 0;
|
||||
page.on('request', request => { if (request.method() === 'DELETE') deletes++; });
|
||||
confirmNextDialog(page, false, 'delete this prompt');
|
||||
await button.click();
|
||||
expect(deletes).toBe(0);
|
||||
expect(await promptSnapshot(request)).toEqual(before);
|
||||
await page.route('**/prompt_manager/delete/*', route => route.abort('failed'), { times: 1 });
|
||||
confirmNextDialog(page, true, 'delete this prompt');
|
||||
await button.click();
|
||||
await expect(page.getByText('Failed to delete prompt', { exact: true })).toBeVisible();
|
||||
expect(await promptSnapshot(request)).toEqual(before);
|
||||
confirmNextDialog(page, true, 'delete this prompt');
|
||||
await button.click();
|
||||
await expect(page.locator('.prompt-text')).toHaveCount(1);
|
||||
await page.reload();
|
||||
await expect(page.locator('.prompt-text')).toHaveCount(1);
|
||||
expect(await promptSnapshot(request)).toEqual(before.filter(prompt => prompt.text !== 'Cat portrait'));
|
||||
await page.goto('/prompt_manager/gallery');
|
||||
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
|
||||
for (const url of await page.locator('#galleryGrid img[data-original]').evaluateAll(images => images.map(image => image.dataset.original))) {
|
||||
await expect(await request.get(url)).toBeOK();
|
||||
}
|
||||
});
|
||||
|
||||
// #320: with previews in one folder, the legacy gallery still shows them, made
|
||||
// and served from that folder (the fixture's own previews inside the sources
|
||||
// are never served then).
|
||||
test('the legacy gallery shows thumbnails kept in one folder', async ({ page, request }) => {
|
||||
await expect(await request.post('/__test__/thumbnail-location', { data: { mode: 'folder' } })).toBeOK();
|
||||
const served = page.waitForResponse(response =>
|
||||
response.url().includes('/prompt_manager/images/serve/thumbnails/') && response.status() === 200);
|
||||
await page.goto('/prompt_manager/gallery');
|
||||
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
|
||||
const response = await served; // made in the folder before it was served
|
||||
const name = decodeURIComponent(new URL(response.url()).pathname.split('/serve/thumbnails/')[1]);
|
||||
const files = await (await request.get('/__test__/thumbnail-files')).json();
|
||||
const stem = name.replace(/\.[^.]+$/, '');
|
||||
expect(files.folder.some(file => /^[a-z0-9_-]+-[0-9a-f]{8}\//.test(file)
|
||||
&& file.slice(file.indexOf('/') + 1).replace(/\.[^.]+$/, '') === stem)).toBe(true);
|
||||
});
|
||||
@@ -2709,3 +2709,26 @@ test('all matching over 10,000 images says so before any dialog or request', asy
|
||||
}
|
||||
expect(posted).toBe(0);
|
||||
});
|
||||
|
||||
// #646: on a POSIX server a Windows-style filename_prefix makes one folder whose name holds a backslash. Its file opens
|
||||
// in the viewer, takes a star that survives a reload, and the folder filter names it with its backslash.
|
||||
test('a file in a folder whose name holds a backslash opens, stars and filters (#646)', async ({ page, request }) => {
|
||||
await expect(await request.post('/__test__/add-backslash-image')).toBeOK();
|
||||
await page.goto(workspace);
|
||||
await expect(cards(page)).toHaveCount(3);
|
||||
const card = page.locator('article[data-image-key="0:model.safetensors\\\\2026-11-17/slash.png"]');
|
||||
await card.locator('.image-open').click();
|
||||
const viewer = page.locator('dialog#viewer-dialog[open]');
|
||||
await expect(viewer.locator('#viewer-title')).toContainText('slash.png');
|
||||
await expect(viewer.locator('#viewer-details .panel-heading')).toBeVisible();
|
||||
await viewer.locator('#viewer-close').click();
|
||||
await expect(viewer).toHaveCount(0);
|
||||
await star(card, 'slash.png').click();
|
||||
await expectStar(star(card, 'slash.png'), true);
|
||||
await expect.poll(async () => (await listedFavorites(request))['0:model.safetensors\\2026-11-17/slash.png']).toBe(true);
|
||||
await page.reload();
|
||||
await expectStar(star(card, 'slash.png'), true);
|
||||
await refine(page, { Folder: 'model.safetensors\\2026-11-17' });
|
||||
await expect(cards(page)).toHaveCount(1);
|
||||
await expect(cards(page)).toContainText('slash.png');
|
||||
});
|
||||
|
||||
@@ -565,9 +565,11 @@ test('URLs and media end with their owning session', async ({ page }) => {
|
||||
// Replacement.
|
||||
await choose(page, parityPng('f02.png'));
|
||||
await expect(preview(page).locator('img.local-file-preview')).toBeVisible();
|
||||
// #653: a video still starting (inline, or in the viewer the selection opened) is held until it settles or
|
||||
// STARTING_VIDEO_MS (15 s) passes, so its release can follow the new preview: wait for it, never check once.
|
||||
let state = await urls(page);
|
||||
expect(state.revoked).toEqual([state.created[0]]);
|
||||
expect(await page.evaluate(() => window.__loads)).toBeGreaterThanOrEqual(1);
|
||||
await expect.poll(async () => (await urls(page)).revoked, { timeout: 20000 }).toEqual([state.created[0]]);
|
||||
await expect.poll(() => page.evaluate(() => window.__loads), { timeout: 20000 }).toBeGreaterThanOrEqual(1);
|
||||
// Route change, from the page (D155: the selection opened the viewer, which makes the sidebar inert).
|
||||
await closeOpened(page);
|
||||
await page.locator('aside.sidebar nav').getByRole('link', { name: 'Overview', exact: true }).click();
|
||||
@@ -648,7 +650,10 @@ test('a video replaced while still starting is reset once it settles', async ({
|
||||
// page (TESTING.md D62), so it stays in place, inert and still playing its URL, with the new preview after it.
|
||||
// Once it reports metadata or an error it is paused, loses its src, is reset (load() with no src, which frees its
|
||||
// decoder) and leaves the page, and only then is its URL revoked. Fresh pages share one browser process.
|
||||
for (let attempt = 0; attempt < 15; attempt++) {
|
||||
// A busy WebKit can fire `loadstart` after the video already has data (#641, run 43732282629: readyState 4), so
|
||||
// keep going until at least one page saw it still starting.
|
||||
let startingSeen = 0;
|
||||
for (let attempt = 0; attempt < 15 || (startingSeen === 0 && attempt < 30); attempt++) {
|
||||
const page = await context.newPage();
|
||||
try {
|
||||
if (attempt === 0) await startCoverage(page, browserName);
|
||||
@@ -687,11 +692,11 @@ test('a video replaced while still starting is reset once it settles', async ({
|
||||
await choose(page, localFixture('core-tags.webm', 'video/webm'));
|
||||
await expect(preview(page).locator('img.local-file-preview')).toBeVisible({ timeout: 8000 });
|
||||
await expect(preview(page).locator('video')).toHaveCount(0);
|
||||
// Replaced while starting (always so at `loadstart` itself): kept in place and untouched. A video that had
|
||||
// Replaced while starting (usually so at `loadstart` itself): kept in place and untouched. A video that had
|
||||
// settled is released at once. Either way it is reset once, and its URL goes last.
|
||||
await expect.poll(() => page.evaluate(() => window.__starting.revoked ?? null)).toEqual({ src: false, connected: false, resets: 1 });
|
||||
const { readyState, replaced } = await page.evaluate(() => ({ readyState: window.__starting.readyState, replaced: window.__starting.replaced }));
|
||||
if (attempt % 5 === 0) expect(readyState).toBe(0);
|
||||
if (readyState === 0) startingSeen++;
|
||||
expect(replaced).toEqual(readyState === 0 ? { connected: true, src: true, inert: true, resets: 0 } : { connected: false, src: false, inert: false, resets: 1 });
|
||||
expect(await page.evaluate(() => window.__starting.node.__resets)).toBe(1);
|
||||
// The page still answers.
|
||||
@@ -702,6 +707,7 @@ test('a video replaced while still starting is reset once it settles', async ({
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
expect(startingSeen, 'no page saw the video still starting at its loadstart').toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('a new selection while the viewer\'s own video is still starting leaves it until it settles (#483)', async ({ context, browserName }) => {
|
||||
@@ -710,7 +716,10 @@ test('a new selection while the viewer\'s own video is still starting leaves it
|
||||
// selection from that video's own `loadstart` (readyState HAVE_NOTHING), or a few milliseconds after it, must not
|
||||
// reset it or take it off the page while it starts (WebKit, GStreamer: TESTING.md D62; merge-queue run
|
||||
// 40903238387). The viewer stays open until it reports metadata or an error, then closes; the URL goes last.
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
// A busy WebKit can fire `loadstart` after the video already has data (#641, run 43732282629: readyState 4), so
|
||||
// keep going until at least one page saw it still starting.
|
||||
let startingSeen = 0;
|
||||
for (let attempt = 0; attempt < 10 || (startingSeen === 0 && attempt < 20); attempt++) {
|
||||
const page = await context.newPage();
|
||||
try {
|
||||
if (attempt === 0) await startCoverage(page, browserName);
|
||||
@@ -750,7 +759,7 @@ test('a new selection while the viewer\'s own video is still starting leaves it
|
||||
await expect(preview(page).locator('img.local-file-preview')).toBeVisible({ timeout: 8000 });
|
||||
await expect.poll(() => page.evaluate(() => window.__starting?.revoked ?? null)).toEqual({ src: false, connected: false, resets: 1 });
|
||||
const { readyState, replaced } = await page.evaluate(() => ({ readyState: window.__starting.readyState, replaced: window.__starting.replaced }));
|
||||
if (attempt % 5 === 0) expect(readyState).toBe(0);
|
||||
if (readyState === 0) startingSeen++;
|
||||
// Starting when replaced: still on the page with its URL, never reset; settled: released at once.
|
||||
expect(replaced).toEqual(readyState === 0 ? { connected: true, src: true, resets: 0 } : { connected: false, src: false, resets: 1 });
|
||||
expect(await page.evaluate(() => window.__starting.node.__resets)).toBe(1);
|
||||
@@ -764,6 +773,7 @@ test('a new selection while the viewer\'s own video is still starting leaves it
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
expect(startingSeen, 'no page saw the video still starting at its loadstart').toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
/** #483: holds the viewer's video in HAVE_NOTHING (its `loadedmetadata` never fires) so a hold can be driven by hand. */
|
||||
@@ -850,7 +860,10 @@ test('leaving for another route while a video starts waits for it to settle', as
|
||||
// A WebKit (GStreamer) video detached before its pipeline had started deadlocked the page (TESTING.md D62); a
|
||||
// route change detaches the whole page, so the shell renders the next route once the video reports metadata or an
|
||||
// error. The route changes from the video's own `loadstart`, or a few milliseconds after it.
|
||||
for (let attempt = 0; attempt < 15; attempt++) {
|
||||
// A busy WebKit can fire `loadstart` after the video already has data (#641, run 43732282629: readyState 4), so
|
||||
// keep going until at least one page saw it still starting.
|
||||
let startingSeen = 0;
|
||||
for (let attempt = 0; attempt < 15 || (startingSeen === 0 && attempt < 30); attempt++) {
|
||||
const page = await context.newPage();
|
||||
try {
|
||||
if (attempt === 0) await startCoverage(page, browserName);
|
||||
@@ -878,7 +891,7 @@ test('leaving for another route while a video starts waits for it to settle', as
|
||||
await choose(page, localFixture('core-tags.webm', 'video/webm'));
|
||||
await expect(main(page).getByRole('heading', { level: 1, name: 'Overview', exact: true })).toBeVisible({ timeout: 8000 });
|
||||
const { readyState, reset } = await page.evaluate(() => ({ readyState: window.__starting.readyState, reset: window.__starting.reset }));
|
||||
if (attempt % 5 === 0) expect(readyState).toBe(0);
|
||||
if (readyState === 0) startingSeen++;
|
||||
// The video was reset and left the page only once it had settled.
|
||||
expect(reset.readyState >= 1 || reset.failed).toBe(true);
|
||||
expect(reset.connected).toBe(true);
|
||||
@@ -891,6 +904,7 @@ test('leaving for another route while a video starts waits for it to settle', as
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
expect(startingSeen, 'no page saw the video still starting at its loadstart').toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('closing the viewer on a video that just started never blocks the page', async ({ context, browserName }) => {
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
// #668 (D207): `workspace#/library?tag=…&tag_mode=…` is the Prompt library with those Tags and that Tag match, against
|
||||
// the real server. The filter stays in the address (Reload, Back and Forward keep it) and the address follows the
|
||||
// shelf's tag filter. Old tag bookmarks are sent to this form (old-urls.spec.mjs).
|
||||
import {startCoverage,saveCoverage} from '../../tools/vendor/browser-coverage.mjs';
|
||||
import {test,expect} from './fixtures.mjs';
|
||||
|
||||
const workspace='/prompt_manager/workspace';
|
||||
const cards=page=>page.locator('article[data-prompt-id]');
|
||||
const card=(page,text)=>cards(page).filter({has:page.getByText(text,{exact:true})});
|
||||
const toolbar=page=>page.locator('#workspace-main search.toolbar');
|
||||
const filtersButton=page=>toolbar(page).getByRole('button',{name:/^Filters(?: · \d)?$/});
|
||||
const refine=page=>page.getByRole('dialog',{name:'Refine this view',exact:true});
|
||||
const caption=page=>page.locator('#workspace-main .section-caption > span').first();
|
||||
const toast=page=>page.locator('#workspace-toast');
|
||||
/** The workspace at exactly this hash. */
|
||||
const at=hash=>url=>url.pathname.endsWith('/prompt_manager/workspace')&&url.search===''&&url.hash===hash;
|
||||
const heading=page=>page.locator('#workspace-main h1').first();
|
||||
const tagsField=page=>refine(page).getByRole('textbox',{name:'Tags',exact:true});
|
||||
const matchField=page=>refine(page).getByRole('combobox',{name:'Tag match',exact:true});
|
||||
const apply=page=>refine(page).getByRole('button',{name:'Apply filters',exact:true});
|
||||
const sidebarLibrary=page=>page.locator('aside.sidebar nav [data-route="library"]');
|
||||
|
||||
test.beforeEach(async({page,request,browserName})=>{
|
||||
await startCoverage(page,browserName);await expect(await request.post('/__test__/reset',{data:{native_library:true}})).toBeOK();
|
||||
page.libraryErrors=[];page.on('pageerror',error=>page.libraryErrors.push(error.message));
|
||||
});
|
||||
test.afterEach(async({page,browserName})=>{await saveCoverage(page,browserName);expect(page.libraryErrors).toEqual([]);});
|
||||
|
||||
async function openRefine(page) {
|
||||
const folders=page.waitForResponse(item=>new URL(item.url()).pathname==='/prompt_manager/library/options'&&new URL(item.url()).searchParams.get('include')==='folders');
|
||||
await filtersButton(page).click();await expect(refine(page)).toBeVisible();await folders;
|
||||
}
|
||||
async function expectCats(page) {
|
||||
await expect(caption(page)).toHaveText(/^1 positive prompt · /);
|
||||
await expect(cards(page)).toHaveCount(1);await expect(card(page,'Cat portrait')).toHaveCount(1);
|
||||
await expect(filtersButton(page)).toHaveText('Filters · 1');
|
||||
}
|
||||
|
||||
test('a Library link opens the shelf filtered by its tags, keeps them in the address and shows them in Refine',async({page})=>{
|
||||
await page.goto(`${workspace}#/library?tag=cats`);
|
||||
await expectCats(page);
|
||||
await expect(page).toHaveURL(at('#/library?tag=cats'));
|
||||
await expect(heading(page)).toHaveText('Prompt library');
|
||||
// As for any route, the title takes focus on a navigation inside the workspace, never on the first render.
|
||||
await expect(heading(page)).not.toBeFocused();
|
||||
await openRefine(page);
|
||||
await expect(tagsField(page)).toHaveValue('cats');await expect(matchField(page)).toHaveValue('all');
|
||||
});
|
||||
|
||||
test('Reload keeps the filter of a Library link',async({page})=>{
|
||||
await page.goto(`${workspace}#/library?tag=cats&tag=dogs&tag_mode=any`);
|
||||
await expect(caption(page)).toHaveText(/^2 positive prompts · /);
|
||||
await page.reload();
|
||||
await expect(page).toHaveURL(at('#/library?tag=cats&tag=dogs&tag_mode=any'));
|
||||
await expect(caption(page)).toHaveText(/^2 positive prompts · /);
|
||||
await expect(card(page,'Cat portrait')).toHaveCount(1);await expect(card(page,'Dog landscape')).toHaveCount(1);
|
||||
await expect(filtersButton(page)).toHaveText('Filters · 2');
|
||||
});
|
||||
|
||||
test('a Library link with two tags matches all of them unless it asks for any, and its address is made canonical',async({page})=>{
|
||||
await page.goto(`${workspace}#/library?tag=cats&tag=dogs`);
|
||||
await expect(caption(page)).toHaveText(/^0 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters · 1');
|
||||
await page.goto('about:blank');
|
||||
await page.goto(`${workspace}#/library?tag_mode=any&sort=name&tag=cats&tag=dogs&tag=cats`);
|
||||
await expect(caption(page)).toHaveText(/^2 positive prompts · /);
|
||||
await expect(filtersButton(page)).toHaveText('Filters · 2');
|
||||
await expect(page).toHaveURL(at('#/library?tag=cats&tag=dogs&tag_mode=any'));
|
||||
});
|
||||
|
||||
test('opening a prompt and going Back returns to the filtered address and filter, and Forward to the prompt',async({page})=>{
|
||||
await page.goto(`${workspace}#/library?tag=cats`);
|
||||
await expectCats(page);
|
||||
await card(page,'Cat portrait').locator('[data-history]').first().click();
|
||||
await expect(page).toHaveURL(/\/prompt_manager\/workspace#\/library\/\d+$/);
|
||||
const promptUrl=page.url();
|
||||
await page.goBack();
|
||||
await expect(page).toHaveURL(at('#/library?tag=cats'));await expectCats(page);
|
||||
await page.goForward();
|
||||
await expect(page).toHaveURL(promptUrl);
|
||||
await expect(page.locator('#workspace-main article[data-prompt-id]')).toHaveCount(0);
|
||||
await page.goBack();
|
||||
await expect(page).toHaveURL(at('#/library?tag=cats'));await expectCats(page);
|
||||
// The prompt page's own way back keeps the filter too.
|
||||
await card(page,'Cat portrait').locator('[data-history]').first().click();
|
||||
await expect(page).toHaveURL(promptUrl);
|
||||
await page.locator('#workspace-main').getByRole('button',{name:'← Prompt library',exact:true}).click();
|
||||
await expect(page).toHaveURL(at('#/library?tag=cats'));await expectCats(page);
|
||||
});
|
||||
|
||||
test('changing the tag filter in Refine updates the address without adding history entries, and clearing it returns to the plain address',async({page})=>{
|
||||
await page.goto(`${workspace}#/overview`);
|
||||
await expect(heading(page)).toHaveText('Overview');
|
||||
await sidebarLibrary(page).click();
|
||||
await expect(caption(page)).toHaveText(/^3 positive prompts · /);await expect(page).toHaveURL(at('#/library'));
|
||||
const entries=await page.evaluate(()=>window.history.length);
|
||||
await openRefine(page);await tagsField(page).fill('cats');await apply(page).click();
|
||||
await expectCats(page);await expect(page).toHaveURL(at('#/library?tag=cats'));
|
||||
await openRefine(page);await tagsField(page).fill('dogs, cats');await matchField(page).selectOption('any');await apply(page).click();
|
||||
await expect(caption(page)).toHaveText(/^2 positive prompts · /);
|
||||
await expect(page).toHaveURL(at('#/library?tag=dogs&tag=cats&tag_mode=any'));
|
||||
await openRefine(page);await matchField(page).selectOption('untagged');await apply(page).click();
|
||||
await expect(page).toHaveURL(at('#/library?tag_mode=untagged'));await expect(filtersButton(page)).toHaveText('Filters · 1');
|
||||
// Search, category and sort are not in the address.
|
||||
await page.locator('#workspace-main search.toolbar').getByRole('searchbox').fill('zzz');
|
||||
await expect(caption(page)).toHaveText(/^0 positive prompts · /);
|
||||
await expect(page).toHaveURL(at('#/library?tag_mode=untagged'));
|
||||
await page.locator('#workspace-main search.toolbar').getByRole('searchbox').fill('');
|
||||
await openRefine(page);await refine(page).getByRole('button',{name:'Clear filters',exact:true}).click();
|
||||
await expect(caption(page)).toHaveText(/^3 positive prompts · /);await expect(page).toHaveURL(at('#/library'));
|
||||
expect(await page.evaluate(()=>window.history.length)).toBe(entries);
|
||||
// One step back leaves the Library: no filter change made an entry.
|
||||
await page.goBack();
|
||||
await expect(page).toHaveURL(at('#/overview'));
|
||||
});
|
||||
|
||||
test('the sidebar Library link shows the whole Library after a link filter and after a filter set in Refine',async({page})=>{
|
||||
await page.goto(`${workspace}#/library?tag=cats`);
|
||||
await expectCats(page);
|
||||
await sidebarLibrary(page).click();
|
||||
await expect(page).toHaveURL(at('#/library'));
|
||||
await expect(caption(page)).toHaveText(/^3 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters');
|
||||
await openRefine(page);await tagsField(page).fill('dogs');await apply(page).click();
|
||||
await expect(page).toHaveURL(at('#/library?tag=dogs'));await expect(caption(page)).toHaveText(/^1 positive prompt · /);
|
||||
await sidebarLibrary(page).click();
|
||||
await expect(page).toHaveURL(at('#/library'));
|
||||
await expect(caption(page)).toHaveText(/^3 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters');
|
||||
// Leaving for another page and coming back by the sidebar is the whole Library too.
|
||||
await page.evaluate(()=>{window.location.hash='#/library?tag=cats';});
|
||||
await expectCats(page);await expect(heading(page)).toBeFocused();
|
||||
await page.locator('aside.sidebar nav [data-route="tags"]').click();
|
||||
await expect(heading(page)).toHaveText('Tags & categories');
|
||||
await sidebarLibrary(page).click();
|
||||
await expect(page).toHaveURL(at('#/library'));await expect(caption(page)).toHaveText(/^3 positive prompts · /);
|
||||
});
|
||||
|
||||
test('a Library link replaces the filter of a shelf that is already open',async({page})=>{
|
||||
await page.goto(`${workspace}#/library?tag=cats`);
|
||||
await expectCats(page);
|
||||
await page.evaluate(()=>{window.location.hash='#/library?tag=dogs';});
|
||||
await expect(card(page,'Dog landscape')).toHaveCount(1);await expect(cards(page)).toHaveCount(1);
|
||||
await expect(filtersButton(page)).toHaveText('Filters · 1');await expect(page).toHaveURL(at('#/library?tag=dogs'));
|
||||
// Back is the earlier link's filter.
|
||||
await page.goBack();
|
||||
await expect(page).toHaveURL(at('#/library?tag=cats'));await expectCats(page);
|
||||
});
|
||||
|
||||
test('Browse on Tags & categories lands on the filtered address',async({page})=>{
|
||||
await page.goto(`${workspace}#/tags`);
|
||||
await expect(heading(page)).toHaveText('Tags & categories');
|
||||
const row=page.locator('#workspace-main tbody tr').filter({has:page.locator('td:first-child').getByText('cats',{exact:true})});
|
||||
await row.getByRole('button',{name:'Browse',exact:true}).click();
|
||||
await expect(page).toHaveURL(at('#/library?tag=cats'));await expectCats(page);
|
||||
await page.reload();
|
||||
await expect(page).toHaveURL(at('#/library?tag=cats'));await expectCats(page);
|
||||
});
|
||||
|
||||
test('a saved view with a tag filter keeps its own address, and the Library link after it is the whole Library',async({page})=>{
|
||||
await page.goto(`${workspace}#/library?tag=cats&tag=dogs&tag_mode=any`);
|
||||
await expect(caption(page)).toHaveText(/^2 positive prompts · /);
|
||||
await page.locator('#workspace-main search.toolbar').getByRole('button',{name:'Save view',exact:true}).click();
|
||||
const save=page.getByRole('dialog',{name:'Save this view',exact:true});
|
||||
await save.getByRole('textbox',{name:'View name',exact:true}).fill('Cats or dogs');
|
||||
await save.getByRole('button',{name:'Save',exact:true}).click();
|
||||
const link=page.getByRole('navigation',{name:'Saved views',exact:true}).getByRole('link',{name:'Cats or dogs',exact:true});
|
||||
await expect(link).toBeVisible();
|
||||
await sidebarLibrary(page).click();
|
||||
await expect(page).toHaveURL(at('#/library'));await expect(caption(page)).toHaveText(/^3 positive prompts · /);
|
||||
await link.click();
|
||||
await expect(page).toHaveURL(/\/prompt_manager\/workspace#\/saved\/\d+$/);
|
||||
await expect(caption(page)).toHaveText(/^2 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters · 2');
|
||||
const savedUrl=page.url();
|
||||
// A filter change inside the saved view never rewrites its address.
|
||||
await openRefine(page);await tagsField(page).fill('cats');await apply(page).click();
|
||||
await expect(caption(page)).toHaveText(/^1 positive prompt · /);
|
||||
await expect(page).toHaveURL(savedUrl);
|
||||
await sidebarLibrary(page).click();
|
||||
await expect(page).toHaveURL(at('#/library'));await expect(caption(page)).toHaveText(/^3 positive prompts · /);
|
||||
});
|
||||
|
||||
test('a Library link for untagged prompts asks the server for them',async({page})=>{
|
||||
const listed=page.waitForResponse(item=>{const url=new URL(item.url());return url.pathname==='/prompt_manager/library'&&url.searchParams.get('tag_mode')==='untagged';});
|
||||
await page.goto(`${workspace}#/library?tag_mode=untagged`);
|
||||
const body=await (await listed).json();
|
||||
expect(body.tag_mode).toBe('untagged');
|
||||
await expect(cards(page)).toHaveCount(body.items.length);
|
||||
await expect(filtersButton(page)).toHaveText('Filters · 1');await expect(page).toHaveURL(at('#/library?tag_mode=untagged'));
|
||||
});
|
||||
|
||||
test('a Library link that cannot be read opens the whole shelf at the plain address and says so',async({page})=>{
|
||||
await page.goto(`${workspace}#/library?tag=cats&tag_mode=either`);
|
||||
await expect(caption(page)).toHaveText(/^3 positive prompts · /);
|
||||
await expect(filtersButton(page)).toHaveText('Filters');
|
||||
await expect(toast(page)).toHaveText("This link's tag filter couldn't be read. Showing the whole prompt library.");
|
||||
await expect(page).toHaveURL(at('#/library'));
|
||||
});
|
||||
|
||||
test('a Library link with an unknown tag shows the empty shelf, not the whole library',async({page})=>{
|
||||
await page.goto(`${workspace}#/library?tag=no-such-tag`);
|
||||
await expect(caption(page)).toHaveText(/^0 positive prompts · /);
|
||||
await expect(page.locator('#workspace-main').getByText('No matching prompts. Try changing the filters.',{exact:true})).toBeVisible();
|
||||
await expect(filtersButton(page)).toHaveText('Filters · 1');await expect(page).toHaveURL(at('#/library?tag=no-such-tag'));
|
||||
});
|
||||
@@ -1,15 +1,13 @@
|
||||
// The one-time older-images notice in the workspace shell (#527, D166). Its dismissal is the legacy admin page's key,
|
||||
// so dismissing it in any place dismisses it everywhere.
|
||||
// The one-time older-images notice in the workspace shell (#527, D166). Its dismissal is the key the old admin page
|
||||
// used (`pm_update_notice_dismissed`), so a browser that dismissed it there before #668 stays dismissed.
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
|
||||
const WORKSPACE = '/prompt_manager/workspace';
|
||||
const ADMIN = '/prompt_manager/admin';
|
||||
const NOTICE_KEY = 'pm_update_notice_dismissed';
|
||||
|
||||
const shellNotice = page => page.locator('#older-images-notice > .notice');
|
||||
const sourcesNotice = page => page.locator('#workspace-main .settings-layout > .notice');
|
||||
const dialog = page => page.locator('dialog#modal[open]');
|
||||
const adminModal = page => page.locator('#updateNoticeModal');
|
||||
const stored = page => page.evaluate(key => localStorage.getItem(key), NOTICE_KEY);
|
||||
|
||||
async function openRoute(page, route) {
|
||||
@@ -105,49 +103,11 @@ test.describe('with the notice not dismissed', () => {
|
||||
await expect(shellNotice(page)).toHaveCount(0);
|
||||
await other.close();
|
||||
});
|
||||
});
|
||||
|
||||
test('the admin modal still works: Later without the checkbox keeps the notice everywhere', async ({ page }) => {
|
||||
await page.goto(ADMIN);
|
||||
await expect(adminModal(page)).toBeVisible();
|
||||
await page.locator('#updateNoticeDismiss').click();
|
||||
await expect(adminModal(page)).toBeHidden();
|
||||
expect(await stored(page)).toBeNull();
|
||||
await openRoute(page, 'library');
|
||||
await expect(shellNotice(page)).toHaveCount(1);
|
||||
});
|
||||
|
||||
test('dismissing on the admin page dismisses it in the workspace', async ({ page }) => {
|
||||
await page.goto(ADMIN);
|
||||
await page.locator('#dismissUpdateNotice').check();
|
||||
await page.locator('#updateNoticeDismiss').click();
|
||||
await expect(adminModal(page)).toBeHidden();
|
||||
await openRoute(page, 'library');
|
||||
test('specs start with the notice dismissed, on every page', async ({ page }) => {
|
||||
for (const route of ['library', 'images', 'system/sources']) {
|
||||
await openRoute(page, route);
|
||||
await expect(shellNotice(page)).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('dismissing in the workspace dismisses it on the admin page', async ({ page }) => {
|
||||
await openRoute(page, 'library');
|
||||
await shellNotice(page).getByRole('button', { name: 'Later', exact: true }).click();
|
||||
await page.goto(ADMIN);
|
||||
await page.waitForLoadState('load');
|
||||
await expect(adminModal(page)).toBeHidden();
|
||||
});
|
||||
|
||||
test('the admin Scan still dismisses it and opens the scan modal', async ({ page }) => {
|
||||
await page.goto(ADMIN);
|
||||
await page.locator('#updateNoticeScan').click();
|
||||
await expect(adminModal(page)).toBeHidden();
|
||||
expect(await stored(page)).toBe('3.2.0');
|
||||
});
|
||||
});
|
||||
|
||||
test('specs start with the notice dismissed, on every page', async ({ page, browser, baseURL }) => {
|
||||
await openRoute(page, 'library');
|
||||
await expect(shellNotice(page)).toHaveCount(0);
|
||||
const context = await browser.newContext({ baseURL });
|
||||
const other = await context.newPage();
|
||||
await other.goto(ADMIN);
|
||||
await other.waitForLoadState('load');
|
||||
await expect(adminModal(other)).toBeHidden();
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -269,15 +269,77 @@ test('an empty queue shows the empty notice only', async ({ page, request }) =>
|
||||
await expect(reviewRow(page)).toHaveText('Needs review0');
|
||||
});
|
||||
|
||||
test('load more appends the next page', async ({ page, request }) => {
|
||||
const continuation = page => main(page).locator('.infinite-continuation');
|
||||
const scrollToContinuation = page => continuation(page).evaluate(node => node.scrollIntoView({ block: 'end' }));
|
||||
|
||||
test('#657 D5: scrolling to the end of the queue loads the next page', async ({ page, request }) => {
|
||||
await seed(request, 45);
|
||||
const reads = reviewReads(page);
|
||||
await open(page);
|
||||
await expect(cards(page)).toHaveCount(40);
|
||||
await expect(continuation(page).locator('p')).toHaveText('40 of 45 images · more load as you scroll');
|
||||
// Scrolling does the work, so there is no button.
|
||||
await expect(continuation(page).getByRole('button')).toHaveCount(0);
|
||||
await scrollToContinuation(page);
|
||||
await expect(cards(page)).toHaveCount(45);
|
||||
await expect(continuation(page)).toHaveCount(0);
|
||||
expect(reads.filter(read => read === 'more')).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('#657 D5: a page that could not be read says so, and Retry reads it', async ({ page, request }) => {
|
||||
await seed(request, 45);
|
||||
await open(page);
|
||||
let failing = true;
|
||||
await page.route(url => url.pathname === '/prompt_manager/review/items' && url.searchParams.has('cursor'),
|
||||
route => (failing ? route.fulfill({ status: 500, contentType: 'application/json',
|
||||
body: JSON.stringify({ success: false, error: 'Internal error' }) }) : route.continue()));
|
||||
const failed = page.waitForResponse(item => item.url().includes('cursor=') && item.status() === 500);
|
||||
await scrollToContinuation(page);
|
||||
await failed;
|
||||
await expect(continuation(page).locator('p')).toHaveText('More items could not be loaded. Try again.');
|
||||
const retry = continuation(page).getByRole('button', { name: 'Retry', exact: true });
|
||||
await expect(retry).toBeVisible();
|
||||
await expect(cards(page)).toHaveCount(40);
|
||||
failing = false;
|
||||
await retry.click();
|
||||
await expect(cards(page)).toHaveCount(45);
|
||||
await expect(continuation(page)).toHaveCount(0);
|
||||
});
|
||||
|
||||
const frames = page => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
|
||||
test('#657 D5: nothing loads behind an open dialog; closing it loads the page in view', async ({ page, request }) => {
|
||||
// Two columns, so Link to a prompt… sits in the sticky panel beside the queue. At one column (touch) the panel
|
||||
// follows the queue just above the continuation: bringing Link into view there loads the next page by itself.
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
await seed(request, 45);
|
||||
const reads = reviewReads(page);
|
||||
await open(page);
|
||||
await linkButton(page).scrollIntoViewIfNeeded();
|
||||
await frames(page);
|
||||
expect(await continuation(page).evaluate(node => node.getBoundingClientRect().top > window.innerHeight + 250)).toBe(true);
|
||||
await linkButton(page).click();
|
||||
await expect(linkDialog(page)).toBeVisible();
|
||||
await scrollToContinuation(page);
|
||||
// Two frames: the observer's callback and the load it would schedule.
|
||||
await frames(page);
|
||||
await expect(cards(page)).toHaveCount(40);
|
||||
expect(reads).not.toContain('more');
|
||||
await linkDialog(page).getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||
await expect(linkDialog(page)).toHaveCount(0);
|
||||
// The continuation is still in view, where the observer stays silent: closing the dialog loads the page.
|
||||
await expect(cards(page)).toHaveCount(45);
|
||||
});
|
||||
|
||||
test('#657 D5: without IntersectionObserver, Load more pages the queue', async ({ page, request }) => {
|
||||
await page.addInitScript(() => { delete window.IntersectionObserver; });
|
||||
await seed(request, 45);
|
||||
await open(page);
|
||||
await expect(cards(page)).toHaveCount(40);
|
||||
const continuation = main(page).locator('.infinite-continuation');
|
||||
await expect(continuation.locator('p')).toHaveText('40 of 45 images');
|
||||
await continuation.getByRole('button', { name: 'Load more images', exact: true }).click();
|
||||
await expect(continuation(page).locator('p')).toHaveText('40 of 45 images');
|
||||
await continuation(page).getByRole('button', { name: 'Load more images', exact: true }).click();
|
||||
await expect(cards(page)).toHaveCount(45);
|
||||
await expect(continuation).toHaveCount(0);
|
||||
await expect(continuation(page)).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('a scan job with review items offers Review metadata in Activity', async ({ page, request }) => {
|
||||
@@ -581,7 +643,7 @@ test('a live re-read keeps the loaded depth and the scroll position', async ({ p
|
||||
await seed(request, 45);
|
||||
await open(page);
|
||||
await expect.poll(async () => (await streams(request)).streams).toBe(1);
|
||||
await main(page).getByRole('button', { name: 'Load more images', exact: true }).click();
|
||||
await scrollToContinuation(page);
|
||||
await expect(cards(page)).toHaveCount(45);
|
||||
await cards(page).last().scrollIntoViewIfNeeded();
|
||||
const scrollTop = () => cards(page).first().evaluate(node => {
|
||||
@@ -683,3 +745,151 @@ test('#536: a refused link stays in the dialog with the server\'s sentence', asy
|
||||
expect(await pending(request)).toBe(1);
|
||||
expect(await links(request)).toEqual([]);
|
||||
});
|
||||
|
||||
test('#657 D4: Link to a prompt first lists the image\'s own prompts, and choosing one applies it', async ({ page, request }) => {
|
||||
await seed(request, 2);
|
||||
await open(page);
|
||||
const harborHash = await context(page).locator('option', { hasText: 'Harbor lights at night' }).getAttribute('value');
|
||||
await linkButton(page).click();
|
||||
const dialog = linkDialog(page);
|
||||
const own = dialog.getByRole('group', { name: 'From this image', exact: true });
|
||||
await expect(dialog.locator('.review-link-heading')).toHaveText(['From this image', 'Library']);
|
||||
await expect(own.getByRole('button')).toHaveText(['Golden dunes at dusk / Soft negative, blur',
|
||||
'Harbor lights at night / Soft negative, blur']);
|
||||
// Typing searches the Library only; an empty box lists the image's prompts again.
|
||||
const search = dialog.getByRole('searchbox');
|
||||
await search.fill('zzz');
|
||||
await expect(own).toBeHidden();
|
||||
await expect(dialog.getByRole('status').first()).toHaveText('No prompt in the Library matches.');
|
||||
await search.fill('');
|
||||
await expect(own).toBeVisible();
|
||||
const submit = dialog.getByRole('button', { name: 'Link image', exact: true });
|
||||
await expect(submit).toHaveAttribute('aria-disabled', 'true');
|
||||
const harbor = own.getByRole('button', { name: 'Harbor lights at night / Soft negative, blur', exact: true });
|
||||
await harbor.click();
|
||||
await expect(harbor).toHaveAttribute('aria-pressed', 'true');
|
||||
// The candidate carries its own negative.
|
||||
await expect(dialog.getByRole('combobox', { name: 'Negative prompt', exact: true })).toBeHidden();
|
||||
await expect(submit).not.toHaveAttribute('aria-disabled', 'true');
|
||||
const decided = page.waitForResponse(item => /\/review\/items\/[^/]+\/decision$/.test(item.url()));
|
||||
await submit.click();
|
||||
const response = await decided;
|
||||
expect(response.status()).toBe(200);
|
||||
expect(response.request().postDataJSON().choice).toBe(harborHash);
|
||||
await expect(dialog).toHaveCount(0);
|
||||
await expect(toast(page)).toHaveText('Association accepted.');
|
||||
await expect(panel(page).locator('p.small')).toHaveText('review_0001.png');
|
||||
expect(await links(request)).toEqual([{ filename: 'review_0000.png', prompt: 'Harbor lights at night',
|
||||
pair_id: expect.any(Number), positive: 'Harbor lights at night', negative: 'Soft negative, blur' }]);
|
||||
});
|
||||
|
||||
test('#657 D4: a refused candidate stays in the dialog with the server\'s sentence', async ({ page, request }) => {
|
||||
await seed(request, 1);
|
||||
await open(page);
|
||||
await linkButton(page).click();
|
||||
const dialog = linkDialog(page);
|
||||
await dialog.getByRole('group', { name: 'From this image', exact: true }).getByRole('button').first().click();
|
||||
await page.route(/\/decision$/, route => route.fulfill({ status: 409, contentType: 'application/json',
|
||||
body: JSON.stringify({ success: false, code: 'association-conflict', error: 'This image is already linked.' }) }));
|
||||
await dialog.getByRole('button', { name: 'Link image', exact: true }).click();
|
||||
await expect(dialog.locator('.warning-note')).toHaveText('This image is already linked.');
|
||||
await dialog.getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||
await expect(dialog).toHaveCount(0);
|
||||
expect(await pending(request)).toBe(1);
|
||||
});
|
||||
|
||||
test('#657 D3: a file whose prompts were shortened to the most used says so', async ({ page, request }) => {
|
||||
await seed(request, 2);
|
||||
await page.route(url => /\/prompt_manager\/review\/items\/[0-9a-f-]{36}$/.test(url.pathname), async route => {
|
||||
const response = await route.fetch();
|
||||
const body = await response.json();
|
||||
const collapsed = body.filename === 'review_0000.png' ? { shown: 2, total: 81, paths: 165 } : null;
|
||||
await route.fulfill({ response, json: { ...body, collapsed } });
|
||||
});
|
||||
await open(page);
|
||||
const line = panel(page).locator('.review-collapsed');
|
||||
await expect(line).toHaveText('Showing the 2 most used of 81 prompts in this file.');
|
||||
await cards(page).nth(1).getByRole('button', { name: 'Inspect review_0001.png', exact: true }).click();
|
||||
await expect(panel(page).locator('p.small')).toHaveText('review_0001.png');
|
||||
await expect(line).toBeHidden();
|
||||
});
|
||||
|
||||
test('#657 D4: typing drops a choice from the image; Link waits for a Library prompt and links it', async ({ page, request }) => {
|
||||
await seed(request, 1, { unreadable: true });
|
||||
await open(page);
|
||||
await expect(panel(page).locator('p.small')).toHaveText('review_0000.png');
|
||||
await linkButton(page).click();
|
||||
const dialog = linkDialog(page);
|
||||
const own = dialog.getByRole('group', { name: 'From this image', exact: true });
|
||||
const submit = dialog.getByRole('button', { name: 'Link image', exact: true });
|
||||
await own.getByRole('button', { name: 'Harbor lights at night / Soft negative, blur', exact: true }).click();
|
||||
await expect(submit).not.toHaveAttribute('aria-disabled', 'true');
|
||||
const search = dialog.getByRole('searchbox');
|
||||
await search.fill('harbor');
|
||||
await expect(own).toBeHidden();
|
||||
await expect(submit).toHaveAttribute('aria-disabled', 'true');
|
||||
// An empty box lists the image's prompts again, none chosen.
|
||||
await search.fill('');
|
||||
await expect(own).toBeVisible();
|
||||
await expect(own.locator('button[aria-pressed="true"]')).toHaveCount(0);
|
||||
await expect(submit).toHaveAttribute('aria-disabled', 'true');
|
||||
await search.fill('harbor');
|
||||
await dialog.getByRole('button', { name: 'Quiet harbor', exact: true }).click();
|
||||
await dialog.getByRole('combobox', { name: 'Negative prompt', exact: true }).selectOption({ label: 'grainy' });
|
||||
await expect(submit).not.toHaveAttribute('aria-disabled', 'true');
|
||||
const sent = page.waitForRequest(item => /\/review\/items\/[^/]+\/(link|decision)$/.test(item.url()));
|
||||
await submit.click();
|
||||
const sentRequest = await sent;
|
||||
expect(sentRequest.url()).toMatch(/\/link$/);
|
||||
expect(sentRequest.postDataJSON()).toEqual(expect.objectContaining({ positive_id: expect.any(Number), pair_id: expect.any(Number) }));
|
||||
await expect(toast(page)).toHaveText('Linked to Quiet harbor.');
|
||||
const link = (await links(request)).find(row => row.filename === 'review_0000.png');
|
||||
expect([link.positive, link.negative]).toEqual(['Quiet harbor', 'grainy']);
|
||||
});
|
||||
|
||||
test('#657 D5: at one column, Info brings the panel into view without loading more until the reader moves', async ({ page, request }) => {
|
||||
await page.setViewportSize({ width: 420, height: 900 });
|
||||
await seed(request, 45);
|
||||
const reads = reviewReads(page);
|
||||
await open(page);
|
||||
await expect(cards(page)).toHaveCount(40);
|
||||
// The first cards are in view and the continuation, past the queue and the panel, is far away.
|
||||
expect(await continuation(page).evaluate(node => node.getBoundingClientRect().top > window.innerHeight + 250)).toBe(true);
|
||||
await cards(page).nth(1).getByRole('button', { name: 'Inspect review_0001.png', exact: true }).click();
|
||||
await expect(panel(page).locator('p.small')).toHaveText('review_0001.png');
|
||||
await expect(panel(page)).toBeInViewport();
|
||||
// The continuation is near, but the panel stays put: two frames for the observer and the load it would schedule.
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
expect(await continuation(page).evaluate(node => node.getBoundingClientRect().top <= window.innerHeight + 250)).toBe(true);
|
||||
expect(reads).not.toContain('more');
|
||||
await expect(cards(page)).toHaveCount(40);
|
||||
// The reader's next move releases it.
|
||||
await page.mouse.wheel(0, 200);
|
||||
await expect(cards(page)).toHaveCount(45);
|
||||
});
|
||||
|
||||
test('#657 D4: a re-read that no longer offers the chosen image prompt drops it from the dialog', async ({ page, request }) => {
|
||||
await seed(request, 1);
|
||||
await open(page);
|
||||
await linkButton(page).click();
|
||||
const dialog = linkDialog(page);
|
||||
const own = dialog.getByRole('group', { name: 'From this image', exact: true });
|
||||
await own.getByRole('button', { name: 'Harbor lights at night / Soft negative, blur', exact: true }).click();
|
||||
// The decision is refused as stale, so the item is read again, and this time its Harbor path cannot be applied.
|
||||
await page.route(/\/decision$/, route => route.fulfill({ status: 409, contentType: 'application/json',
|
||||
body: JSON.stringify({ success: false, code: 'review-conflict', error: 'This item changed. Choose again.' }) }));
|
||||
await page.route(url => /\/prompt_manager\/review\/items\/[0-9a-f-]{36}$/.test(url.pathname), async route => {
|
||||
const response = await route.fetch();
|
||||
const body = await response.json();
|
||||
const candidates = body.candidates.map(candidate => (candidate.positive?.text === 'Harbor lights at night'
|
||||
? { ...candidate, state: 'unresolved', reason: 'Text is decided at run time' } : candidate));
|
||||
await route.fulfill({ response, json: { ...body, candidates } });
|
||||
});
|
||||
const submit = dialog.getByRole('button', { name: 'Link image', exact: true });
|
||||
await submit.click();
|
||||
await expect(own.getByRole('button')).toHaveText(['Golden dunes at dusk / Soft negative, blur']);
|
||||
await expect(own.locator('button[aria-pressed="true"]')).toHaveCount(0);
|
||||
await expect(submit).toHaveAttribute('aria-disabled', 'true');
|
||||
await expect(dialog.locator('.warning-note')).toHaveText('This item changed. Choose again.');
|
||||
expect(await pending(request)).toBe(1);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { hostSaveAnswer } from './settings-save.mjs';
|
||||
import { seedConcept } from './concept-inventory.mjs';
|
||||
import { followRestore, SEEN_RESTORE_PILL, SEEN_RESTORE_TOAST } from './unseen-restore.mjs';
|
||||
|
||||
@@ -387,9 +388,9 @@ test('safety backup toggle saves through Save preferences with revision (D104)',
|
||||
await expect(toggle).toBeChecked();
|
||||
await toggle.uncheck();
|
||||
await expect(settingsStatus(page)).toHaveText('Unsaved changes.');
|
||||
const saved = page.waitForRequest(item => item.url().endsWith('/prompt_manager/settings') && item.method() === 'POST');
|
||||
const saved = hostSaveAnswer(page);
|
||||
await save(page).click();
|
||||
const body = (await saved).postDataJSON();
|
||||
const body = (await saved).request().postDataJSON();
|
||||
expect(body).toEqual({ safety_backup: false, expected_revision: before.revision });
|
||||
await expect(settingsStatus(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, '/prompt_manager/settings')).settings.safety_backup).toBe(false);
|
||||
@@ -431,15 +432,12 @@ test('a failed settings read leaves the policy disabled with the reason', async
|
||||
await expect(row.locator('input')).toBeDisabled();
|
||||
});
|
||||
|
||||
test('the legacy Backup and Restore routes keep working and the admin page links to System', async ({ page, request }) => {
|
||||
test('the legacy Backup and Restore routes keep working', async ({ request }) => {
|
||||
const bytes = await backupBytes(request);
|
||||
const restored = await request.post('/prompt_manager/restore', { multipart: { database_file: {
|
||||
name: 'prompts_backup.db', mimeType: 'application/octet-stream', buffer: bytes } } });
|
||||
await expect(restored).toBeOK();
|
||||
expect((await restored.json()).success).toBe(true);
|
||||
// #330: the admin page's Backup DB and Restore DB open System › Backup & export.
|
||||
await page.goto('/prompt_manager/admin');
|
||||
for (const id of ['#backupBtn', '#restoreBtn']) await expect(page.locator(id)).toHaveAttribute('href', 'workspace#/system/backups');
|
||||
});
|
||||
|
||||
/** Start a fake running job (a metadata scan another tab started), which an exclusive restore must wait for. */
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { clickHostSave } from './settings-save.mjs';
|
||||
import { seedConcept } from './concept-inventory.mjs';
|
||||
|
||||
// System › Integrations (#249 System S10 Task 27) on the concept-shaped fixture with a fake LoraManager install
|
||||
@@ -65,7 +66,7 @@ async function openIntegrations(page) {
|
||||
async function enable(page, { triggers = false } = {}) {
|
||||
await settingOf(page, 'LoraManager integration').locator('input').check();
|
||||
if (triggers) await settingOf(page, 'Automatically include trigger words').locator('input').check();
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page), ENABLE_URL);
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
}
|
||||
|
||||
@@ -201,7 +202,7 @@ test('key never prefilled; blank keeps; Clear saved key clears; saved through Sa
|
||||
await field.fill('sk-test-key');
|
||||
await expect(key.locator('p.small')).toHaveText('The new key replaces the saved one when you save.');
|
||||
await expect(status(page)).toHaveText('Unsaved changes.');
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page), ENABLE_URL);
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
expect(enables).toHaveLength(1);
|
||||
expect(enables[0]).toMatchObject({ civitai_api_key: 'sk-test-key', enabled: false });
|
||||
@@ -243,7 +244,7 @@ test('key never prefilled; blank keeps; Clear saved key clears; saved through Sa
|
||||
await expect(key.locator('p.small')).toHaveText('The saved key is removed when you save.');
|
||||
await expect(clear).toHaveCount(0);
|
||||
await expect(field).toBeFocused();
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page), ENABLE_URL);
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
expect(enables.at(-1)).toMatchObject({ clear_civitai_api_key: true });
|
||||
expect(enables.at(-1)).not.toHaveProperty('civitai_api_key');
|
||||
@@ -261,7 +262,7 @@ test('a LoRA save over settings changed elsewhere is a conflict, never a blind w
|
||||
await expect(status(page)).toHaveText('Settings changed elsewhere. Reload this section to see them.');
|
||||
expect((await serverJson(request, '/__test__/integrations/state')).trigger_words).toBe(false);
|
||||
// The draft stays; the next Save carries the reread revision and succeeds.
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page), ENABLE_URL);
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, '/__test__/integrations/state')).trigger_words).toBe(true);
|
||||
});
|
||||
@@ -292,7 +293,7 @@ test('a save where only the LoRA part is written says so; the next save needs no
|
||||
// The next save carries the revision the saved part left: it saves, with no "changed elsewhere".
|
||||
await nav.getByRole('button', { name: 'Sources & scans', exact: true }).click();
|
||||
await sourceRow('unplugged').getByRole('button', { name: 'Remove', exact: true }).click();
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page));
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, '/prompt_manager/settings')).sources.configured.map(source => source.path)).toEqual(['output']);
|
||||
});
|
||||
@@ -342,6 +343,7 @@ test('Review import shows replacement, blocked items and network effects with th
|
||||
['LoraManager', 'environment settings · alongside storage · library default'],
|
||||
['Scope', 'Replace 2 imported prompts with 3 LoRAs'],
|
||||
['Found', '3 metadata files · 3 LoRAs · 0 with local images'],
|
||||
['Trigger words', '3 become tags'],
|
||||
['Protected', 'Nothing is protected'],
|
||||
['Network', 'Downloads up to 3 example images from CivitAI'],
|
||||
['Backup', 'Create and verify before changes (browser.db.backup_<date and time>)'],
|
||||
@@ -386,7 +388,8 @@ test('saved pairs block the import: the review explains it and offers only Close
|
||||
await enable(page);
|
||||
await layoutOf(page).getByRole('button', { name: 'Review import', exact: true }).click();
|
||||
// gridOf reads once; poll until the review has rendered its rows.
|
||||
await expect.poll(async () => (await gridOf(page))[3]).toEqual(['Protected', '1 imported prompt used by saved pairs']);
|
||||
await expect.poll(async () => (await gridOf(page)).find(([term]) => term === 'Protected'))
|
||||
.toEqual(['Protected', '1 imported prompt used by saved pairs']);
|
||||
await expect(dialog(page).locator('p.small')).toHaveText(
|
||||
'Delete or change the saved pairs that use these prompts, then review the import again. Nothing was changed.');
|
||||
expect(await dialog(page).locator('.dialog-actions button').allTextContents()).toEqual(['Close']);
|
||||
@@ -394,6 +397,18 @@ test('saved pairs block the import: the review explains it and offers only Close
|
||||
await expect(dialog(page)).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('the import review counts the trained words that are lists or sentences and not made tags (#618)',
|
||||
async ({ page, request }) => {
|
||||
await lora(request, { loras: 2, junk: true });
|
||||
await openIntegrations(page);
|
||||
await enable(page);
|
||||
await layoutOf(page).getByRole('button', { name: 'Review import', exact: true }).click();
|
||||
await expect.poll(async () => (await gridOf(page)).find(([term]) => term === 'Trigger words'))
|
||||
.toEqual(['Trigger words', '2 become tags · 4 not made tags (lists or sentences)']);
|
||||
await dialog(page).getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||
await expect(dialog(page)).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('unusable LoraManager settings: the review says why and offers only Close (#355)', async ({ page, request }) => {
|
||||
await lora(request, { previous: 1, settings: 'invalid' });
|
||||
await openIntegrations(page);
|
||||
|
||||
@@ -65,8 +65,8 @@ test('the section shows the concept rows; Metadata cache follows Q5 (D102)', asy
|
||||
]))).toEqual([
|
||||
['Database', [['Integrity & relationship checks', 'Check', ''], ['Duplicate prompt text', 'Review plan', ''],
|
||||
['Optimize database', 'Review plan', ''], ['Unused prompt components', 'Review plan', 'danger'],
|
||||
// D192 (#550): beyond the concept.
|
||||
['Pair category and tags', 'Review plan', '']]],
|
||||
// D192 (#550) and D210 (#618): beyond the concept.
|
||||
['Pair category and tags', 'Review plan', ''], ['Tag cleanup', 'Find tags', 'danger']]],
|
||||
['Images & cache', [['Missing-file links', 'Review plan', 'danger'], ['Duplicate image files', 'Find duplicates', ''],
|
||||
['Thumbnail cache', 'Review options', ''], ['Metadata cache', 'Review plan', '']]],
|
||||
]);
|
||||
@@ -482,6 +482,104 @@ test('Find duplicates starts a job; its view links Review groups; Keep radios bu
|
||||
expect((await request.get('/prompt_manager/images/serve/s7-dupes/copy.png?root=0')).status()).toBe(404);
|
||||
});
|
||||
|
||||
test('D210: Tag cleanup finds comma and unused tags, reviews only the ticked rule and deletes only it (#618)',
|
||||
async ({ page, request }) => {
|
||||
await expect(await request.post('/__test__/system/tag-cleanup')).toBeOK();
|
||||
const previews = [];
|
||||
page.on('request', item => { if (item.url().endsWith(PREVIEW_URL)) previews.push(item.postDataJSON()); });
|
||||
const before = (await serverJson(request, '/__test__/system/backups')).safety.length;
|
||||
await openMaintenance(page);
|
||||
const tagRow = row(page, 'Tag cleanup');
|
||||
await expect(tagRow.locator('p')).toHaveText('Find tags that are whole comma lists or are used nowhere. Review them, '
|
||||
+ 'then remove only what you tick.');
|
||||
await tagRow.getByRole('button', { name: 'Find tags', exact: true }).click();
|
||||
await expect(page).toHaveURL(/#\/activity\/[0-9a-f]{32}$/);
|
||||
const findId = page.url().split('/').pop();
|
||||
const main = page.locator('#workspace-main');
|
||||
await expect(main.locator('h1')).toHaveText('Find tags to clean up');
|
||||
const reviewTags = main.getByRole('button', { name: 'Review tags', exact: true });
|
||||
await expect(reviewTags).toBeVisible();
|
||||
await expect(main.locator('.stat-row .stat dt')).toHaveText(['Found']);
|
||||
await expect(main.locator('.stat-row .stat dd')).toHaveText(['4']);
|
||||
// The found rows are tags (records): plain text, never an open action; no lora: tag is a comma finding.
|
||||
const results = main.getByRole('region', { name: 'Results', exact: true });
|
||||
await expect(results.locator('.outcome-files > .file-row')).toHaveText(['s618 a, b · Tags containing a comma',
|
||||
's618 x,y · Tags containing a comma', 's618-ghost · Tags with no links', 's618-spirit · Tags with no links']);
|
||||
await expect(results.locator('.outcome-files button')).toHaveCount(0);
|
||||
|
||||
await reviewTags.click();
|
||||
const review = dialog(page);
|
||||
await expect(review.locator('#modal-title')).toHaveText('Review tag cleanup');
|
||||
const status = review.locator('#modal-body > p[role="status"]');
|
||||
await expect(status).toHaveText('0 tags selected');
|
||||
const start = review.getByRole('button', { name: 'Review cleanup', exact: true });
|
||||
await expect(start).toBeDisabled();
|
||||
const comma = review.locator('.tag-cleanup-rule[data-rule="comma"]');
|
||||
const unused = review.locator('.tag-cleanup-rule[data-rule="unused"]');
|
||||
await expect(comma.locator(':scope > label')).toHaveText('Tags containing a comma (2)');
|
||||
await expect(unused.locator(':scope > label')).toHaveText('Tags with no links (2)');
|
||||
await expect(comma.locator(':scope > p.small')).toHaveText('A whole list saved as one tag, usually from a LoRA\'s '
|
||||
+ 'trained words. Removes the tag from its prompts, pairs and images and deletes it.');
|
||||
await expect(review.locator('#modal-body > p.small').last()).toHaveText(/^Nothing is deleted until you review and apply/);
|
||||
// Nothing is ticked; the tag rows are built when Show tags first opens.
|
||||
await expect(comma.locator('details input')).toHaveCount(0);
|
||||
await comma.locator(':scope > label input').check();
|
||||
await expect(status).toHaveText('2 tags selected');
|
||||
await expect(start).toBeEnabled();
|
||||
await comma.locator('details > summary').click();
|
||||
const tags = comma.locator('details label');
|
||||
await expect(tags).toHaveText(['s618 a, b · 1 prompt', 's618 x,y · no links']);
|
||||
await expect(tags.locator('input')).toHaveCount(2);
|
||||
for (const box of await tags.locator('input').all()) await expect(box).toBeChecked();
|
||||
await tags.nth(1).locator('input').uncheck();
|
||||
await expect(status).toHaveText('1 tag selected');
|
||||
expect(await comma.locator(':scope > label input').evaluate(box => [box.checked, box.indeterminate])).toEqual([false, true]);
|
||||
await tags.nth(1).locator('input').check();
|
||||
await expect(status).toHaveText('2 tags selected');
|
||||
|
||||
await start.click();
|
||||
await expect(dialog(page).locator('#modal-title')).toHaveText('Review maintenance plan');
|
||||
await expect(dialog(page).locator('#modal-body > h3')).toHaveText('Tag cleanup');
|
||||
expect(previews).toHaveLength(1);
|
||||
expect(previews[0].operation).toBe('tag_cleanup');
|
||||
expect(previews[0].options.job_id).toBe(findId);
|
||||
expect(previews[0].options.select.map(entry => [entry.rule, entry.tag_ids.length])).toEqual([['comma', 2]]);
|
||||
const grid = await gridOf(page);
|
||||
expect(grid.slice(0, 2)).toEqual([['Scope', 'Delete 2 tags (removed from 1 prompt, 0 pairs and 0 images)'],
|
||||
['Protected', 'Nothing is protected']]);
|
||||
expect(grid[2][1]).toMatch(/^Always created and verified first \(.+\.backup_<date and time>\)$/);
|
||||
expect(grid[3]).toEqual(['Media on disk', 'No files are removed']);
|
||||
await dialog(page).getByRole('button', { name: 'Apply reviewed operation', exact: true }).click();
|
||||
await expect(page).not.toHaveURL(new RegExp(findId));
|
||||
await expect(page).toHaveURL(/#\/activity\/[0-9a-f]{32}$/);
|
||||
const job = await ended(request, page.url().split('/').pop());
|
||||
expect([job.kind, job.title, job.state, job.counters.changed, job.counters.protected])
|
||||
.toEqual(['maintenance', 'Tag cleanup', 'finished', 2, 0]);
|
||||
await expect(main.locator('h1')).toHaveText('Tag cleanup');
|
||||
await results.locator('.outcome-list > button').filter({ hasText: 'Changed' }).click();
|
||||
await expect(results.locator('.outcome-files > .file-row')).toHaveText([
|
||||
'Deleted tag “s618 a, b” (Tags containing a comma) · removed from 1 prompt',
|
||||
'Deleted tag “s618 x,y” (Tags containing a comma)']);
|
||||
// The safety backup is always taken.
|
||||
expect((await serverJson(request, '/__test__/system/backups')).safety.length).toBe(before + 1);
|
||||
// Tags & categories: the other rule's tags and the lora: tag are still there.
|
||||
const names = (await serverJson(request, '/prompt_manager/vocabulary/tags?limit=200')).tags.map(tag => tag.name);
|
||||
expect(names).toEqual(expect.arrayContaining(['s618-ghost', 's618-spirit', 's618-clean', 'lora:S618, v2']));
|
||||
expect(names).not.toContain('s618 a, b');
|
||||
expect(names).not.toContain('s618 x,y');
|
||||
|
||||
// A second search finds only the rest.
|
||||
await openMaintenance(page);
|
||||
await row(page, 'Tag cleanup').getByRole('button', { name: 'Find tags', exact: true }).click();
|
||||
await expect(page).not.toHaveURL(new RegExp(job.id));
|
||||
await expect(page).toHaveURL(/#\/activity\/[0-9a-f]{32}$/);
|
||||
const again = await ended(request, page.url().split('/').pop());
|
||||
expect(again.counters.found).toBe(2);
|
||||
const body = await serverJson(request, `/prompt_manager/maintenance/tag_cleanup/${again.id}`);
|
||||
expect(body.rules.map(rule => [rule.id, rule.findings.map(finding => finding.name)]))
|
||||
.toEqual([['comma', []], ['unused', ['s618-ghost', 's618-spirit']]]);
|
||||
});
|
||||
|
||||
test('the duplicates review pages ten groups at a time and keeps each choice (D101)', async ({ page, request }) => {
|
||||
await expect(await request.post('/__test__/system/duplicate-files', { data: { groups: 11 } })).toBeOK();
|
||||
const groupReads = [];
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { clickHostSave, hostSaveAnswer, SETTINGS_URL } from './settings-save.mjs';
|
||||
import { seedConcept } from './concept-inventory.mjs';
|
||||
|
||||
// System › Sources & scans (#249 System S4 Task 11) on the concept-shaped real fixture, whose two sources are this
|
||||
@@ -7,7 +8,6 @@ import { seedConcept } from './concept-inventory.mjs';
|
||||
// Add/Remove edit the host draft behind the one Save row, and every scan starts the session job through the shared
|
||||
// "Review metadata scan" (D55), scoped to one source from its row (S4 Task 10). The hooks are workspace_system_fixture.py's.
|
||||
const workspace = '/prompt_manager/workspace';
|
||||
const SETTINGS_URL = '/prompt_manager/settings';
|
||||
const NOTICE_KEY = 'pm_update_notice_dismissed';
|
||||
const OUTSIDE_REASON = 'Gallery root must be inside a ComfyUI directory (output, input, temp, user) or one listed in PROMPT_MANAGER_EXTRA_GALLERY_ROOTS';
|
||||
|
||||
@@ -152,9 +152,9 @@ test('Add source validates on the server, then marks the host draft dirty; Save
|
||||
]);
|
||||
await expect(statusOf(page)).toHaveText('Unsaved changes.');
|
||||
expect((await serverJson(request, SETTINGS_URL)).sources.effective).toHaveLength(2);
|
||||
const saved = page.waitForRequest(item => item.method() === 'POST' && item.url().endsWith(SETTINGS_URL));
|
||||
const saved = hostSaveAnswer(page);
|
||||
await saveButton(page).click();
|
||||
const body = (await saved).postDataJSON();
|
||||
const body = (await saved).request().postDataJSON();
|
||||
expect(body.gallery_root_paths).toEqual(['output', 'input', 'output/unthumbnailed']);
|
||||
expect(typeof body.expected_revision).toBe('string');
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
@@ -207,7 +207,7 @@ test('Remove marks the draft; removing the last entry states auto-detect', async
|
||||
await expect(statusOf(page)).toHaveText('Unsaved changes.');
|
||||
await sourceRow(page, 'ComfyUI output').getByRole('button', { name: 'Remove', exact: true }).click();
|
||||
expect(await rowsOf(page)).toEqual([['p', 'small', 'No source is configured. After saving, ComfyUI’s output folder is used.']]);
|
||||
await saveButton(page).click();
|
||||
await clickHostSave(page, saveButton(page));
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
// Saved: ComfyUI's output folder is detected and listed without Remove, its row saying it is the default.
|
||||
await expect.poll(rowsOf.bind(null, page)).toEqual([
|
||||
@@ -224,7 +224,7 @@ test('a configured source that does not exist says why and can be removed', asyn
|
||||
expect((await rowsOf(page)).at(-1)).toEqual(['unmounted-drive', `unmounted-drive · ${OUTSIDE_REASON}`, ['Remove']]);
|
||||
await sourceRow(page, 'unmounted-drive').getByRole('button', { name: 'Remove', exact: true }).click();
|
||||
await expect(sourceList(page).locator('.operation')).toHaveCount(2);
|
||||
await saveButton(page).click();
|
||||
await clickHostSave(page, saveButton(page));
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, SETTINGS_URL)).sources.configured.map(source => source.path)).toEqual(['output', 'input']);
|
||||
});
|
||||
@@ -266,7 +266,7 @@ test('Watch for new outputs saves monitoring_enabled; a restart applies it', asy
|
||||
await expect(sourceList(page).locator('.operation .row-actions > button:first-child')).toHaveText(['Scan changes', 'Scan changes']);
|
||||
// Switched back on before the restart: the observer still runs, so nothing waits for one.
|
||||
await monitoring.check();
|
||||
await saveButton(page).click();
|
||||
await clickHostSave(page, saveButton(page));
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
await expect(sourceList(page).locator('.operation p')).toHaveText(['output · watching', 'input · watching']);
|
||||
});
|
||||
@@ -327,9 +327,9 @@ test('D158: saved off while the monitor still watches until a restart, the forei
|
||||
await expect(layout.locator('.setting-row').filter({ has: page.locator('#foreign-runs') }).locator('p.small'))
|
||||
.toHaveText('Applies while Watch for new outputs is on.');
|
||||
await foreign.uncheck();
|
||||
const saved = page.waitForRequest(item => item.method() === 'POST' && item.url().endsWith(SETTINGS_URL));
|
||||
const saved = hostSaveAnswer(page);
|
||||
await saveButton(page).click();
|
||||
expect((await saved).postDataJSON()).toEqual({ save_foreign_runs: false, expected_revision: expect.any(String) });
|
||||
expect((await saved).request().postDataJSON()).toEqual({ save_foreign_runs: false, expected_revision: expect.any(String) });
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
} finally {
|
||||
await request.post(SETTINGS_URL, { data: { save_foreign_runs: true } });
|
||||
@@ -349,9 +349,9 @@ test('worker range max is cpu_count', async ({ page, request }) => {
|
||||
await workers.fill(String(next));
|
||||
await expect(statusOf(page)).toHaveText(next === settings.worker_threads ? 'No unsaved changes.' : 'Unsaved changes.');
|
||||
test.skip(next === settings.worker_threads, 'One core: the range has a single value');
|
||||
const saved = page.waitForRequest(item => item.method() === 'POST' && item.url().endsWith(SETTINGS_URL));
|
||||
const saved = hostSaveAnswer(page);
|
||||
await saveButton(page).click();
|
||||
expect((await saved).postDataJSON().worker_threads).toBe(next);
|
||||
expect((await saved).request().postDataJSON().worker_threads).toBe(next);
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, SETTINGS_URL)).settings.worker_threads).toBe(next);
|
||||
});
|
||||
@@ -601,7 +601,7 @@ test('a save refused for one unusable source names it and marks its row', async
|
||||
// Removed, the list saves.
|
||||
await sourceRow(page, 'unplugged').getByRole('button', { name: 'Remove', exact: true }).click();
|
||||
await expect(sourceList(page).locator('.operation[aria-invalid="true"]')).toHaveCount(0);
|
||||
await saveButton(page).click();
|
||||
await clickHostSave(page, saveButton(page));
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, SETTINGS_URL)).sources.configured.map(source => source.path)).toEqual(['output']);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { clickHostSave, hostSaveAnswer, SETTINGS_URL } from './settings-save.mjs';
|
||||
|
||||
// System › Auto-tagging (#328, System S11 Tasks 6–7) on the tagging fixture (workspace_tagging_fixture.py) with the
|
||||
// injected fake model: no model file exists and nothing is downloaded or run for real. The fake download waits on the
|
||||
@@ -8,7 +9,6 @@ import { test, expect } from './fixtures.mjs';
|
||||
const workspace = '/prompt_manager/workspace';
|
||||
const MODELS_URL = '/prompt_manager/autotag/models';
|
||||
const PREVIEW_URL = '/prompt_manager/autotag/batch/preview';
|
||||
const SETTINGS_URL = '/prompt_manager/settings';
|
||||
const MODEL_LABELS = ['WD14 SwinV2 · ~400 MB', 'WD14 ViT · ~400 MB', 'GGUF JoyCaption · ~4.5 GB', 'HuggingFace JoyCaption · ~16 GB'];
|
||||
const FIRST = 'tagging/dunes_00001.png';
|
||||
const SECOND = 'tagging/dunes_00002.png';
|
||||
@@ -169,9 +169,9 @@ test('defaults save through Save preferences and the Tag image dialog uses them'
|
||||
await page.locator('#threshold-general').press('Tab');
|
||||
await page.locator('#tag-suggestions').fill('15');
|
||||
await page.locator('#tag-suggestions').press('Tab');
|
||||
const posted = page.waitForRequest(item => item.method() === 'POST' && new URL(item.url()).pathname === SETTINGS_URL);
|
||||
const posted = hostSaveAnswer(page);
|
||||
await save(page).click();
|
||||
const body = (await posted).postDataJSON();
|
||||
const body = (await posted).request().postDataJSON();
|
||||
expect(body).toMatchObject({ autotag_existing: 'merge', autotag_general_threshold: 0.4, autotag_suggestion_limit: 15 });
|
||||
expect(typeof body.expected_revision).toBe('string');
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
@@ -468,7 +468,7 @@ test('skipped tags add, preview, remove, save and reload (D202)', async ({ page,
|
||||
await skippedChips(page).last().getByRole('button', { name: 'Remove zebra', exact: true }).click();
|
||||
await expect(skippedChips(page)).toHaveCount(2);
|
||||
await expect(status(page)).toHaveText('Unsaved changes.');
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page));
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, SETTINGS_URL)).settings.autotag_skipped_tags).toEqual(['blurry', 'light']);
|
||||
await openTagging(page);
|
||||
@@ -526,7 +526,7 @@ test('saved instructions: new, edit, per-engine default, delete, save and reload
|
||||
await page.locator('#instruction-default-hf').selectOption({ label: 'Photo realism' });
|
||||
await expect(instructionOption(page, 'Photo realism').locator('.chip')).toHaveText(['Default for HuggingFace']);
|
||||
await expect(status(page)).toHaveText('Unsaved changes.');
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page));
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
let saved = (await serverJson(request, SETTINGS_URL)).settings;
|
||||
expect(saved.autotag_instructions.map(entry => [entry.name, entry.text])).toEqual([['Describe the image', 'Describe the image'],
|
||||
@@ -538,7 +538,7 @@ test('saved instructions: new, edit, per-engine default, delete, save and reload
|
||||
await page.locator('#instruction-delete').click();
|
||||
await expect(page.locator('#instruction-reset')).toHaveText('GGUF now uses Built-in.');
|
||||
await expect(page.locator('#instruction-default-gguf')).toHaveValue('builtin');
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page));
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
saved = (await serverJson(request, SETTINGS_URL)).settings;
|
||||
expect(saved.autotag_instructions.map(entry => entry.name)).toEqual(['Photo realism']);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { clickHostSave, SETTINGS_URL } from './settings-save.mjs';
|
||||
import { seedConcept } from './concept-inventory.mjs';
|
||||
import { readCoverageTable, parseControl, CONTROL_EXEMPTIONS } from '../../tools/vendor/legacy-coverage.mjs';
|
||||
|
||||
@@ -326,7 +327,7 @@ test('Appearance › Thumbnails saves the server thumbnail settings and never co
|
||||
await format.selectOption('jpeg');
|
||||
await surface.locator('#thumbnail-quality').fill('65');
|
||||
await surface.locator('#thumbnail-quality').dispatchEvent('change');
|
||||
await page.getByRole('button', { name: 'Save preferences', exact: true }).click();
|
||||
await clickHostSave(page, page.getByRole('button', { name: 'Save preferences', exact: true }));
|
||||
await expect(page.locator('#settings-status')).toHaveText('Saved to the server configuration.');
|
||||
const { settings } = await serverJson(request, '/prompt_manager/settings');
|
||||
expect([settings.thumbnail_format, settings.thumbnail_quality, settings.thumbnail_edge]).toEqual(['jpeg', 65, 512]);
|
||||
@@ -456,8 +457,8 @@ test('out-of-order overview responses never repaint a newer section', async ({ p
|
||||
|
||||
// System › Appearance (#249 System S3 Task 8): the browser display defaults (`gallerySettings`, preferences.mjs) and the
|
||||
// two host fields behind the one Save row, and the consumers that read them on their next visit.
|
||||
const SETTINGS_URL = '/prompt_manager/settings';
|
||||
const INSPECT_PATH = '/prompt_manager/images/inspect/';
|
||||
const HOST_SAVED = 'Saved to the server configuration.';
|
||||
const statusOf = page => page.locator('#workspace-main #settings-status');
|
||||
const saveOf = page => page.locator('#workspace-main .save-row > button');
|
||||
const storedSettings = page => page.evaluate(() => JSON.parse(localStorage.getItem('gallerySettings') || 'null'));
|
||||
@@ -473,7 +474,9 @@ async function openAppearance(page) {
|
||||
|
||||
async function saveAppearance(page, text) {
|
||||
await expect(saveOf(page)).not.toHaveAttribute('aria-disabled', 'true');
|
||||
await saveOf(page).click();
|
||||
// A save that reaches the server waits for its answer (#631); one kept in this browser sends nothing.
|
||||
if (text.includes(HOST_SAVED)) await clickHostSave(page, saveOf(page));
|
||||
else await saveOf(page).click();
|
||||
await expect(statusOf(page)).toHaveText(text);
|
||||
}
|
||||
|
||||
|
||||
@@ -311,3 +311,42 @@ test('on a video the image keys and Space do nothing, as the toolbar disables th
|
||||
await page.evaluate(() => new Promise(requestAnimationFrame));
|
||||
await expect(viewer(page)).not.toHaveClass(/\bviewer-fullscreen\b/);
|
||||
});
|
||||
|
||||
/** #646: the listing carries one file whose folder name holds a backslash, as a Windows-style prefix makes on Linux. */
|
||||
async function withBackslashFile(page) {
|
||||
await page.route(/\/prompt_manager\/images\/output\?/, async route => {
|
||||
const response = await route.fetch(), body = await response.json();
|
||||
if (body.images?.length > 1) {
|
||||
const copy = body.images[1];
|
||||
body.images.splice(1, 0, {...copy, path: `model.safetensors\\2026-11-17/${copy.filename}`, relative_path: `model.safetensors\\2026-11-17/${copy.filename}`});
|
||||
}
|
||||
await route.fulfill({response, json: body});
|
||||
});
|
||||
}
|
||||
|
||||
test('a file the viewer refuses is left out, and the others still open (#646)', async ({ page }) => {
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await withBackslashFile(page);
|
||||
await page.setViewportSize({ width: 1600, height: 1100 });
|
||||
await openProduction(page, 'images', 'dark');
|
||||
const cards = await page.locator(CARDS).count();
|
||||
await page.locator(CARDS).first().locator('.image-open').click();
|
||||
await expect(position(page)).toContainText(`1 of ${cards - 1}`);
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expect(position(page)).toContainText('2 of ');
|
||||
await expect(viewer(page).locator('#viewer-title')).not.toContainText('model.safetensors');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test('the refused file itself opens its details instead of the viewer (#646)', async ({ page }) => {
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await withBackslashFile(page);
|
||||
await page.setViewportSize({ width: 1600, height: 1100 });
|
||||
await openProduction(page, 'images', 'dark');
|
||||
await page.locator(`${CARDS}[data-image-key*="model.safetensors"] .image-open`).click();
|
||||
await expect(page.getByRole('complementary', {name: 'Selected image details'}).getByRole('alert')).toHaveText('Could not read prompts from this file.');
|
||||
await expect(viewer(page)).toHaveCount(0);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -99,7 +99,7 @@ test('a rename while searching re-reads the same search and sort',async({page})=
|
||||
test('Untagged prompts Browse opens the Library on exactly the prompts without tags',async({page})=>{
|
||||
await open(page);
|
||||
await untagged(page).getByRole('button',{name:'Browse',exact:true}).click();
|
||||
await expect(page).toHaveURL(/#\/library$/);
|
||||
await expect(page).toHaveURL(url=>url.hash==='#/library?tag_mode=untagged');
|
||||
await expect(main(page).getByRole('heading',{level:1})).toBeFocused();
|
||||
await expect(shelf(page)).toHaveCount(2);
|
||||
await expect(page.locator('#workspace-main .section-caption > span').first()).toHaveText(/^2 positive prompts · /);
|
||||
|
||||
@@ -23,7 +23,9 @@ async function seed(request,data={}) {
|
||||
const response=await request.post('/__test__/vocabulary/reset',{data});await expect(response).toBeOK();return response.json();
|
||||
}
|
||||
async function expectLibrary(page,{tags='',category='',count}) {
|
||||
await expect(page).toHaveURL(/#\/library$/);
|
||||
// #668 (D207): a tag Browse lands on the filtered address; a category is not in the address.
|
||||
const hash=tags?`#/library?${new URLSearchParams({tag:tags})}`:'#/library';
|
||||
await expect(page).toHaveURL(url=>url.hash===hash);
|
||||
await expect(main(page).getByRole('heading',{level:1})).toHaveText('Prompt library');
|
||||
await expect(main(page).getByRole('heading',{level:1})).toBeFocused();
|
||||
await expect(page.getByRole('searchbox',{name:'Search workspace',exact:true})).toHaveValue('');
|
||||
|
||||
@@ -118,9 +118,9 @@ test('all shell destinations deep-link, reload and expose working existing appli
|
||||
await expect(page.locator('#workspace-main').getByRole('link', { name: 'Open Images', exact: true })).toBeVisible();
|
||||
await expect(page.locator('a[href*="/prompt_manager/admin"], a[href*="/prompt_manager/gallery"]')).toHaveCount(0);
|
||||
await expect(page.locator('#workspace-main').getByText('Your existing tools remain available')).toHaveCount(0);
|
||||
// The legacy pages themselves stay at their URLs.
|
||||
for (const legacy of ['/prompt_manager/admin', '/prompt_manager/gallery', '/prompt_manager/gallery.html']) {
|
||||
await expect(await request.get(legacy)).toBeOK();
|
||||
// The old pages' URLs stay and lead into the workspace (#668; old-urls.spec.mjs follows each one).
|
||||
for (const old of ['/prompt_manager/admin', '/prompt_manager/gallery', '/prompt_manager/gallery.html']) {
|
||||
await expect(await request.get(old)).toBeOK();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -35,6 +35,10 @@ from utils.execution_outputs import OutputBundle, OutputReference, snapshot_outp
|
||||
from utils.pair_execution import EXECUTION_KEY
|
||||
from tests.browser.folder_trash import replace_folder
|
||||
|
||||
# Recorded outputs use the host's path style, as production does (#629): a
|
||||
# Windows temp root is not an absolute POSIX path and would get no root key.
|
||||
HOST_PATH_STYLE = "windows" if os.name == "nt" else "posix"
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from py.api import PromptManagerAPI
|
||||
|
||||
@@ -433,7 +437,9 @@ def seed_workspace_concept(
|
||||
|
||||
folder = root / "output" / "concepts"
|
||||
folder.mkdir()
|
||||
roots = snapshot_output_roots("posix", str(root / "output"), str(root / "temp"))
|
||||
roots = snapshot_output_roots(
|
||||
HOST_PATH_STYLE, str(root / "output"), str(root / "temp")
|
||||
)
|
||||
# The API package needs the host stubs the server installs before importing it.
|
||||
from py.api.images import _favorite_relative_key, _favorite_root_key
|
||||
|
||||
@@ -474,7 +480,7 @@ def seed_workspace_concept(
|
||||
"3", _snapshot(prompt.positive), _snapshot(negative), "inferred"
|
||||
)
|
||||
reference = OutputReference(
|
||||
"4", 0, "output", "concepts", name, "posix", roots.output_key
|
||||
"4", 0, "output", "concepts", name, HOST_PATH_STYLE, roots.output_key
|
||||
)
|
||||
runs.append(
|
||||
_record_run(
|
||||
|
||||
@@ -15,6 +15,7 @@ from aiohttp import web
|
||||
from PIL import Image
|
||||
from PIL.PngImagePlugin import PngInfo
|
||||
|
||||
from tests.browser.workspace_concept_fixture import HOST_PATH_STYLE
|
||||
from tests.browser.workspace_visual_fixture import _write_art, seed_workspace_visual
|
||||
from utils.execution_contexts import (
|
||||
ContextBundle,
|
||||
@@ -293,7 +294,9 @@ def seed_workspace_history(
|
||||
):
|
||||
conn.execute(f"DELETE FROM {table}")
|
||||
epoch = api.db.get_execution_epoch()
|
||||
roots = snapshot_output_roots("posix", str(root / "output"), str(root / "temp"))
|
||||
roots = snapshot_output_roots(
|
||||
HOST_PATH_STYLE, str(root / "output"), str(root / "temp")
|
||||
)
|
||||
folder = root / "output" / "history"
|
||||
folder.mkdir(exist_ok=True)
|
||||
for index, name in enumerate(("current.png", "other.png")):
|
||||
@@ -309,7 +312,7 @@ def seed_workspace_history(
|
||||
kind,
|
||||
"history",
|
||||
name,
|
||||
"posix",
|
||||
HOST_PATH_STYLE,
|
||||
roots.output_key if kind == "output" else roots.temp_key,
|
||||
)
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ reaches a real LoraManager, ComfyUI install or the network:
|
||||
the image cache, forgets every LoRA import and injected failure, and opens
|
||||
the download gate;
|
||||
- ``POST /__test__/integrations/lora-manager``
|
||||
``{loras, civitai, preview, previous, settings}`` writes
|
||||
``{loras, civitai, preview, previous, settings, junk}`` writes
|
||||
``custom_nodes/ComfyUI-Lora-Manager`` (detected through the
|
||||
``folder_paths`` stub's base path) and ``loras`` LoRAs under
|
||||
``models/loras``: each a ``<stem>.safetensors`` model beside its
|
||||
@@ -18,7 +18,9 @@ reaches a real LoraManager, ComfyUI install or the network:
|
||||
downloads it only for a LoRA without a local preview); ``previous`` saves
|
||||
that many earlier ``lora-manager`` imports with tags and image links;
|
||||
``settings: "invalid"`` makes LoraManager's settings file unreadable JSON
|
||||
(the server's own isolated settings folder, ``LORA_MANAGER_SETTINGS_DIR``);
|
||||
(the server's own isolated settings folder, ``LORA_MANAGER_SETTINGS_DIR``); ``junk``
|
||||
adds a comma list and a ``<lora:…>`` call to each LoRA's trained words, which
|
||||
the import does not make tags (#618);
|
||||
- ``POST /__test__/integrations/gate`` ``{hold}`` holds every CivitAI
|
||||
download until it is released (``{"hold": false}``), so a test sees the job
|
||||
while it downloads;
|
||||
@@ -145,6 +147,9 @@ def register_integrations_commands(app, routes, api, root: Path):
|
||||
for number in range(count):
|
||||
stem = f"style_{number + 1:02}"
|
||||
civitai = {"trainedWords": [f"trigger{number + 1}"]}
|
||||
if data.get("junk") is True:
|
||||
# #618: a comma list and a model call, never made tags.
|
||||
civitai["trainedWords"] += ["score_9, score_8_up,", "<lora:x:0.8>"]
|
||||
if data.get("civitai") is True:
|
||||
civitai["images"] = [
|
||||
{
|
||||
|
||||
@@ -15,8 +15,9 @@ after the plain ones in this order:
|
||||
- ``conflict``: an item whose file was linked to another prompt ("Misty
|
||||
forest path") after it was queued (the next scan or monitor pass would
|
||||
remove the item); applying a sampler path then conflicts with that link.
|
||||
- ``limited``: a graph of 17 samplers, each with its own prompt, which the
|
||||
recorder stores ``limited`` (more than 16 candidates, so none are stored).
|
||||
- ``limited``: an item recorded while its evidence is over the 8 MiB bound
|
||||
(simulated), so the recorder stores it ``limited`` without candidates.
|
||||
More than 16 candidates are collapsed instead (#657 addendum D3).
|
||||
An A1111 block with two negative lines is not queued any more: it offers
|
||||
no candidate to choose (#284).
|
||||
- ``unreadable`` (#536): an item whose stored candidates are all
|
||||
@@ -79,8 +80,6 @@ CONCEPT_POSITIVE = (
|
||||
"mountain peaks, cinematic composition, atmospheric mist, fine detail"
|
||||
)
|
||||
CONCEPT_NEGATIVE = "blurry, low quality, low resolution"
|
||||
# More candidates than an item stores (16): the ``limited`` item.
|
||||
LIMITED_SAMPLERS = 17
|
||||
# More than one queue page (40), so Load more has a second page.
|
||||
MAX_ITEMS = 45
|
||||
_TABLES = (
|
||||
@@ -210,6 +209,23 @@ def _linked_after_queueing(api: PromptManagerAPI, path: Path) -> None:
|
||||
api.db.link_image_to_prompt(prompt_id, str(path))
|
||||
|
||||
|
||||
def _limited(api: PromptManagerAPI, path: Path) -> None:
|
||||
"""Record ``path`` as if its evidence were over the 8 MiB bound."""
|
||||
from unittest.mock import patch
|
||||
|
||||
from utils import review_capture
|
||||
|
||||
real = review_capture.canonical_evidence
|
||||
|
||||
def capped(value):
|
||||
if value.get("candidates"):
|
||||
raise ValueError("Review evidence is larger than 8 MiB")
|
||||
return real(value)
|
||||
|
||||
with patch.object(review_capture, "canonical_evidence", side_effect=capped):
|
||||
_record(api, path, "limited")
|
||||
|
||||
|
||||
def _unavailable(api: PromptManagerAPI, root: Path, path: Path) -> None:
|
||||
from py.config import GalleryConfig
|
||||
|
||||
@@ -296,9 +312,8 @@ def seed_review(
|
||||
_png(path, (70, 40, 120))
|
||||
_unreadable(api, path)
|
||||
elif kind == "limited":
|
||||
many = tuple(f"{POSITIVES[0]} {n}" for n in range(LIMITED_SAMPLERS))
|
||||
_png(path, (90, 90, 90), graph=_graph(positives=many))
|
||||
_record(api, path, "limited")
|
||||
_png(path, (90, 90, 90))
|
||||
_limited(api, path)
|
||||
else:
|
||||
_png(path, (20, 140, 90))
|
||||
_unavailable(api, root, path)
|
||||
|
||||
@@ -52,6 +52,10 @@ read. These per-server hooks only change what a System test needs on top:
|
||||
``{"groups": n}`` adds ``n`` more groups of two copies each, and
|
||||
``{"trio": false}`` leaves the three ``same.png``/``copy.png`` copies out,
|
||||
and ``{"long": true}`` adds a group under long names with no spaces;
|
||||
- ``POST /__test__/system/tag-cleanup`` (#618) saves ``S618 owner`` tagged
|
||||
``s618 a, b`` (a comma list), ``s618-clean`` and ``lora:S618, v2`` (a LoRA's
|
||||
identity tag, never a comma finding), and adds the unused tags
|
||||
``s618 x,y`` (a fullwidth comma), ``s618-ghost`` and ``s618-spirit``;
|
||||
- ``GET /__test__/system/digest`` (S7) answers the sha256 of the database's
|
||||
rows (a read-only dump) and of every media file under ``output`` and
|
||||
``input`` (not the automatic previews in ``thumbnails``), so a test proves
|
||||
@@ -349,6 +353,24 @@ def register_system_commands(app, routes, api, root: Path):
|
||||
conn.commit()
|
||||
return web.json_response({"success": True})
|
||||
|
||||
@routes.post("/__test__/system/tag-cleanup")
|
||||
async def tag_cleanup(request):
|
||||
def seed():
|
||||
text = "S618 owner"
|
||||
api.db.save_prompt(
|
||||
text,
|
||||
prompt_hash=hashlib.sha256(text.lower().encode()).hexdigest(),
|
||||
tags=["s618 a, b", "s618-clean", "lora:S618, v2"],
|
||||
)
|
||||
with api.db.model.get_connection() as conn:
|
||||
conn.executemany(
|
||||
"INSERT INTO tags(name) VALUES(?)",
|
||||
[("s618 x\uff0cy",), ("s618-ghost",), ("s618-spirit",)],
|
||||
)
|
||||
|
||||
await api._run_in_executor(seed)
|
||||
return web.json_response({"success": True})
|
||||
|
||||
@routes.post("/__test__/system/pair-metadata")
|
||||
async def pair_metadata(request):
|
||||
def seed():
|
||||
|
||||
@@ -210,7 +210,7 @@ test(`${label} follows actual ComfyUI light and dark palettes`, async ({ page },
|
||||
}
|
||||
});
|
||||
|
||||
test(`${label} Web UI button opens the workspace; legacy pages still load`, async ({ page }) => {
|
||||
test(`${label} Web UI button opens the workspace; the old gallery URL leads to Images`, async ({ page }) => {
|
||||
await addEditor(page, type);
|
||||
const popupPromise = page.waitForEvent('popup');
|
||||
await page.locator('.pm-focused').getByRole('button', { name: 'Web UI ↗', exact: true }).click();
|
||||
@@ -219,8 +219,10 @@ test(`${label} Web UI button opens the workspace; legacy pages still load`, asyn
|
||||
await expect(popup).toHaveURL(/\/prompt_manager\/workspace#\/library$/);
|
||||
await expect(popup.locator('#workspace-main h1')).toHaveText('Prompt library');
|
||||
await expect(page.locator('.pm-focused').getByRole('status').filter({ hasText: 'Web UI opened.' })).toHaveText('Web UI opened.');
|
||||
// #668: the old gallery URL leads to the workspace's Images page.
|
||||
await popup.goto(new URL('/prompt_manager/gallery', page.url()).href);
|
||||
await expect(popup.locator('#addPromptBtn')).toBeVisible();
|
||||
await expect(popup).toHaveURL(/\/prompt_manager\/workspace#\/images$/);
|
||||
await expect(popup.locator('#workspace-main h1')).toHaveText('Images');
|
||||
await popup.close();
|
||||
});
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ test('all node schemas and extension entrypoints load from the real host', async
|
||||
});
|
||||
|
||||
for (const type of ['PromptManager', 'PromptManagerText']) {
|
||||
test(`${type} Web UI button opens the workspace; legacy pages still load`, async ({ page }) => {
|
||||
test(`${type} Web UI button opens the workspace; the old gallery URL leads to Images`, async ({ page }) => {
|
||||
await page.evaluate(async type => {
|
||||
const { app } = await import('/scripts/app.js');
|
||||
const node = LiteGraph.createNode(type);
|
||||
@@ -97,8 +97,10 @@ for (const type of ['PromptManager', 'PromptManagerText']) {
|
||||
await popup.waitForLoadState('domcontentloaded');
|
||||
await expect(popup).toHaveURL(/\/prompt_manager\/workspace#\/library$/);
|
||||
await expect(popup.locator('#workspace-main h1')).toHaveText('Prompt library');
|
||||
// #668: the old gallery URL leads to the workspace's Images page.
|
||||
await popup.goto(new URL('/prompt_manager/gallery', page.url()).href);
|
||||
await expect(popup.locator('#addPromptBtn')).toBeVisible();
|
||||
await expect(popup).toHaveURL(/\/prompt_manager\/workspace#\/images$/);
|
||||
await expect(popup.locator('#workspace-main h1')).toHaveText('Images');
|
||||
await popup.close();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -37,12 +37,14 @@ test('workspace serves real library data beside either ComfyUI renderer', async
|
||||
await expect(workspace.getByText('No matching images · 0 images', { exact: true })).toBeVisible();
|
||||
await expect(workspace.locator('.gallery-body > .empty')).toHaveText('No matching images. Try another search or category.');
|
||||
}
|
||||
// D29: Images no longer links the legacy gallery; #525: nor does Overview. The page stays at its URL.
|
||||
// D29: Images no longer links the old gallery; #525: nor does Overview. #668: its URL leads to the workspace.
|
||||
await expect(workspace.locator('#workspace-main a[href="/prompt_manager/gallery"]')).toHaveCount(0);
|
||||
await workspace.evaluate(() => { location.hash = '/overview'; });
|
||||
const imagesCard = workspace.locator('#workspace-main').getByRole('link', { name: 'Open Images', exact: true });
|
||||
await expect(imagesCard).toHaveAttribute('href', '#/images');
|
||||
expect((await workspace.request.get('/prompt_manager/gallery')).ok()).toBe(true);
|
||||
const oldGallery = await workspace.request.get('/prompt_manager/gallery');
|
||||
expect(oldGallery.ok()).toBe(true);
|
||||
expect(new URL(oldGallery.url()).pathname).toMatch(/\/prompt_manager\/workspace$/);
|
||||
await workspace.evaluate(() => { location.hash = '/images'; });
|
||||
await workspace.reload();
|
||||
await expect(workspace.locator('#workspace-main h1')).toHaveText('Images');
|
||||
|
||||
Vendored
+16
@@ -13,6 +13,22 @@ ffmpeg -f lavfi -i testsrc=size=32x32:rate=4:duration=1 \
|
||||
|
||||
Browser tests use the committed file; FFmpeg is not required to run them.
|
||||
|
||||
# AVIF metadata fixture
|
||||
|
||||
`media/comfyui_avif.avif` (96x96, about 1 KB) is an original synthetic gradient
|
||||
written by ComfyUI's own AVIF writer, `SaveImageAdvanced` (PyAV with SVT-AV1,
|
||||
then `inject_avif_metadata`), so it carries the EXIF item ComfyUI writes:
|
||||
`prompt:{json}` at tag 0x0110 and `workflow:{json}` at 0x010F. It is dedicated
|
||||
to the public domain under CC0-1.0. `utils/exif_text`, the scan and the monitor
|
||||
read it; `tests/test_avif_media_type.py` and `tests/test_api_admin.py` cover it.
|
||||
|
||||
Reproduce from a ComfyUI checkout with ComfyUI's Python (torch and PyAV with
|
||||
SVT-AV1), where `comfy_extras` imports:
|
||||
|
||||
```sh
|
||||
python custom_nodes/ComfyUI-PromptManager/tools/make_avif_fixture.py
|
||||
```
|
||||
|
||||
# Local Inspect header fixtures
|
||||
|
||||
`local-inspect/tiny.jpg` (48x32) and `local-inspect/tiny.webp` (40x24) are original
|
||||
|
||||
+1
-1
@@ -935,7 +935,7 @@
|
||||
"reason_code": "multistage-differs",
|
||||
"selection": null,
|
||||
"positive": null,
|
||||
"negative": null,
|
||||
"negative": "blurry, lowres",
|
||||
"candidate_count": 0,
|
||||
"facts": {
|
||||
"seed": {
|
||||
|
||||
@@ -63,6 +63,7 @@
|
||||
"GET /prompt_manager/lora/status",
|
||||
"GET /prompt_manager/lora/trigger-words",
|
||||
"GET /prompt_manager/maintenance/duplicates/{job_id}",
|
||||
"GET /prompt_manager/maintenance/tag_cleanup/{job_id}",
|
||||
"GET /prompt_manager/pairs",
|
||||
"GET /prompt_manager/pairs/export",
|
||||
"GET /prompt_manager/pairs/{pair_id}",
|
||||
@@ -134,6 +135,7 @@
|
||||
"POST /prompt_manager/jobs/image-tags",
|
||||
"POST /prompt_manager/jobs/model-download",
|
||||
"POST /prompt_manager/jobs/scan",
|
||||
"POST /prompt_manager/jobs/tag_cleanup",
|
||||
"POST /prompt_manager/jobs/thumbnails",
|
||||
"POST /prompt_manager/jobs/{job_id}/cancel",
|
||||
"POST /prompt_manager/library",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user