Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4845d3a5f8 | ||
|
|
d98849d3cd | ||
|
|
1926657f12 |
@@ -1,22 +0,0 @@
|
||||
# Left out of the Comfy Registry package (comfy node publish). Git clones still
|
||||
# have everything. tests/test_package_contents.py holds these rules to what
|
||||
# ComfyUI needs at run time; keep each one anchored to the root with a leading /.
|
||||
|
||||
# Development folders
|
||||
/tests/
|
||||
/tools/
|
||||
/docs/
|
||||
/.github/
|
||||
|
||||
# Screenshots used only by README-legacy.md on GitHub
|
||||
/images/
|
||||
|
||||
# Development files
|
||||
/TESTING.md
|
||||
/Makefile
|
||||
/requirements-dev.txt
|
||||
/.coveragerc
|
||||
/.flake8
|
||||
/.pre-commit-config.yaml
|
||||
/.gitignore
|
||||
/.gitattributes
|
||||
@@ -1,7 +0,0 @@
|
||||
# Pinned files are compared byte for byte with their recorded hashes
|
||||
# (npm run --prefix tools/vendor check). Git must never convert their line
|
||||
# endings, which Git for Windows does by default (core.autocrlf=true, #636).
|
||||
/web/lib/viewerjs/** -text
|
||||
/web/js/shared/toolkit/** -text
|
||||
/web/js/workspace/concept.css -text
|
||||
/docs/concepts/workspace/style.css -text
|
||||
@@ -1,15 +0,0 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
polar: # Replace with a single Polar username
|
||||
buy_me_a_coffee: veets
|
||||
thanks_dev: # Replace with a single thanks.dev username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
@@ -1,8 +1,15 @@
|
||||
{
|
||||
"required_status_checks": {
|
||||
"strict": true,
|
||||
"strict": false,
|
||||
"contexts": [
|
||||
"gate"
|
||||
"py3.12 on ubuntu-latest",
|
||||
"coverage gate (85%)",
|
||||
"black and flake8",
|
||||
"frontend modules",
|
||||
"all tests",
|
||||
"viewerjs",
|
||||
"real ComfyUI compatibility",
|
||||
"bandit (high severity)"
|
||||
]
|
||||
},
|
||||
"enforce_admins": true,
|
||||
|
||||
@@ -4,10 +4,6 @@ updates:
|
||||
# Python dependencies (requirements.txt / setup.cfg / pyproject.toml)
|
||||
- package-ecosystem: "pip"
|
||||
directory: "/"
|
||||
# Our requirements are minimum versions that install into ComfyUI's shared
|
||||
# environment. Leave a floor alone when it already allows the new release;
|
||||
# raising it would force-upgrade the package for every other custom node.
|
||||
versioning-strategy: "increase-if-necessary"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "sunday"
|
||||
|
||||
@@ -1,407 +0,0 @@
|
||||
name: CI
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# The gate (#666): everything a change must pass runs once, here, on the pull request. Nothing runs
|
||||
# again in a merge queue or on main; branch protection requires the one context "gate" on a branch
|
||||
# that is up to date with main, so the commit that was tested is the commit that merges. What only
|
||||
# other browsers, other Pythons, Windows or a real ComfyUI can catch runs in nightly.yml.
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
# A newer push to a pull request cancels the older run. A manual run is never cancelled.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
PYTHONFAULTHANDLER: "1"
|
||||
|
||||
# Every job has a time limit: ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never
|
||||
# under 5, timed as whole-job wall time. The 3 minutes leave room for the Python runner's watchdog
|
||||
# (120 s, tests/run_suite.py) to print its stack dump before GitHub cancels the job. A limit changes
|
||||
# only with new measurements written here (TESTING.md "Time limits and hangs"). A job with no three
|
||||
# green runs yet has an "estimate" line; replace it with its measurement after three green runs.
|
||||
# tests/vendor/ci-workflow.test.mjs recomputes every limit from these lines.
|
||||
# Measured 2026-11-21 on runs 44861123845 (a1f7447), 44547399478 (b3bb55f), 44519471869 (fa31644):
|
||||
# python: 7m20s / 7m36s / 7m58s -> 15 min
|
||||
# lint: 0m27s / 0m52s / 0m49s -> 5 min
|
||||
# js-test: 0m27s / 0m35s / 0m36s -> 5 min
|
||||
# changes: 0m10s / 0m06s / 0m07s -> 5 min
|
||||
# Measured 2026-11-21 on runs 44861123782 (a1f7447), 44547399248 (b3bb55f), 44519472003 (fa31644):
|
||||
# security: 0m22s / 0m20s / 0m24s -> 5 min
|
||||
# Measured 2026-11-21 on runs 44861123725 (a1f7447), 44547398683 (b3bb55f), 44519471975 (fa31644):
|
||||
# frontend-coverage-merge: 0m53s / 0m57s / 0m51s -> 5 min
|
||||
# gate: 0m02s / 0m06s / 0m03s -> 5 min
|
||||
# estimate package: one stdlib test module without an install, under 1 minute -> 5 min
|
||||
# estimate tooling: the pip and npm installs of a browser shard (about 1 minute) and 2 minutes of tests -> 8 min
|
||||
# estimate frontend-coverage: the same four shards ran Chromium and touch together in 7m55s-16m48s;
|
||||
# Chromium alone is about half of that, 9 minutes at most -> 17 min
|
||||
#
|
||||
# Browser jobs (#425): a job killed at its limit keeps no log and skips its upload steps, so the page
|
||||
# test step has its own timeout-minutes, 2 below the job's. At the step limit, SIGTERM makes
|
||||
# tools/vendor/running-tests-reporter.mjs print the tests still running and hand over to Playwright's
|
||||
# interrupt, which writes the blob report; the always() uploads then run. The limits assume the npm
|
||||
# cache hits: a cold cache adds up to 5 minutes to npm ci.
|
||||
jobs:
|
||||
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" and "docs"
|
||||
# (nothing here can break), "release" (only the version line of pyproject.toml), or "code" (anything
|
||||
# else, and every case of doubt). The jobs below run for one class only, and "gate" fails unless
|
||||
# this job succeeded and each job did what the class asks. The clone has every commit but no file
|
||||
# contents (blob:none): the script compares file names, and reads pyproject.toml only when it is
|
||||
# the one file that changed.
|
||||
changes:
|
||||
name: change class
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
class: ${{ steps.classify.outputs.class }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
filter: blob:none
|
||||
persist-credentials: false
|
||||
- name: Classify the changed files
|
||||
id: classify
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
# The suite runs once, under coverage: the same run proves the tests pass and the 85% floor holds.
|
||||
python:
|
||||
name: python 3.12 with coverage (85%)
|
||||
needs: changes
|
||||
if: ${{ needs.changes.outputs.class == 'code' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements-dev.txt
|
||||
|
||||
- name: Run the suite under coverage
|
||||
run: python -m coverage run -m tests.run_suite -v
|
||||
|
||||
- name: Coverage gate
|
||||
run: |
|
||||
python -m coverage combine
|
||||
python -m coverage report --fail-under=85
|
||||
|
||||
# A release (only the version line changed) cannot break a test, but it is what the Registry
|
||||
# publishes, so the package-content rules are checked. Standard library only: nothing to install.
|
||||
package:
|
||||
name: package contents
|
||||
needs: changes
|
||||
if: ${{ needs.changes.outputs.class == 'release' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- run: python -m unittest -v tests.test_package_contents
|
||||
|
||||
lint:
|
||||
name: black and flake8
|
||||
needs: changes
|
||||
if: ${{ needs.changes.outputs.class == 'code' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
# The exact black and flake8 pins from requirements-dev.txt, so a new release cannot turn CI red.
|
||||
- run: pip install $(grep -E '^(black|flake8)==' requirements-dev.txt)
|
||||
- run: black --check .
|
||||
- run: flake8 .
|
||||
|
||||
security:
|
||||
name: bandit (high severity)
|
||||
needs: changes
|
||||
if: ${{ needs.changes.outputs.class == 'code' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install bandit
|
||||
run: pip install bandit[toml]
|
||||
|
||||
# Medium findings are reported without failing until they are triaged.
|
||||
# High severity is a hard gate.
|
||||
- name: Security report (medium and above, informational)
|
||||
run: bandit -r . -ll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules --exit-zero
|
||||
- name: Security scan (high severity gate)
|
||||
run: bandit -r . -lll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules
|
||||
|
||||
js-test:
|
||||
name: frontend modules
|
||||
needs: changes
|
||||
if: ${{ needs.changes.outputs.class == 'code' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: "24"
|
||||
cache: npm
|
||||
cache-dependency-path: tools/vendor/package-lock.json
|
||||
|
||||
- name: Check shipped extension and page modules parse
|
||||
run: |
|
||||
shopt -s globstar nullglob
|
||||
for f in web/comfy/**/*.js web/comfy/**/*.mjs web/js/**/*.js web/js/**/*.mjs; do
|
||||
node --input-type=module --check < "$f" || exit 1
|
||||
done
|
||||
|
||||
- name: Install pinned shared test contracts
|
||||
run: npm ci --prefix tools/vendor --ignore-scripts
|
||||
|
||||
- name: Run JS tests
|
||||
run: node --test tests/js/*.test.js
|
||||
|
||||
# The vendor pins and the tooling tests (tests/vendor). Same image and Python as the browser shards:
|
||||
# some tooling tests start the browser test server.
|
||||
tooling:
|
||||
name: tooling tests and pins
|
||||
needs: changes
|
||||
if: ${{ needs.changes.outputs.class == 'code' }}
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
options: --user 1001
|
||||
timeout-minutes: 8
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- name: Python environment
|
||||
env:
|
||||
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
|
||||
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
|
||||
run: |
|
||||
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
|
||||
python3 -m venv --without-pip "$venv"
|
||||
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
|
||||
echo "$PIP_SHA256 $wheel" | sha256sum -c -
|
||||
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
|
||||
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
|
||||
echo "$venv/bin" >> "$GITHUB_PATH"
|
||||
- run: python --version && node --version && node --version | grep -q '^v24\.'
|
||||
- name: Cache npm downloads
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
|
||||
- run: npm ci --prefix tools/vendor --ignore-scripts
|
||||
- run: npm run --prefix tools/vendor check
|
||||
- run: npm run --prefix tools/vendor test
|
||||
|
||||
frontend-coverage:
|
||||
name: frontend coverage (shard ${{ matrix.shard }}/4)
|
||||
needs: changes
|
||||
if: ${{ needs.changes.outputs.class == 'code' }}
|
||||
runs-on: ubuntu-latest
|
||||
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
|
||||
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
|
||||
# tests/vendor/browser-image.test.mjs checks it). Browsers and fonts come from the image.
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
options: --user 1001
|
||||
timeout-minutes: 17
|
||||
# Public-repo ubuntu-latest runners have 4 vCPUs: three Playwright workers, each with its own test
|
||||
# server, leave one CPU for the servers and the runner.
|
||||
env:
|
||||
PM_TEST_WORKERS: 3
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4]
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
# The image's own Python 3.12 and Node 24: setup-python/setup-node install the runner's toolcache
|
||||
# builds, whose entry points name host paths that do not exist in the container. The image has no
|
||||
# ensurepip and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv.
|
||||
- name: Python environment
|
||||
env:
|
||||
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
|
||||
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
|
||||
run: |
|
||||
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
|
||||
python3 -m venv --without-pip "$venv"
|
||||
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
|
||||
echo "$PIP_SHA256 $wheel" | sha256sum -c -
|
||||
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
|
||||
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
|
||||
echo "$venv/bin" >> "$GITHUB_PATH"
|
||||
- run: python --version && node --version && node --version | grep -q '^v24\.'
|
||||
# npm's download cache, keyed on the lockfile; inside the container ~ is the job's HOME (/github/home),
|
||||
# which npm also uses. node_modules itself is still built fresh by npm ci.
|
||||
- name: Cache npm downloads
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
|
||||
- run: npm ci --prefix tools/vendor --ignore-scripts
|
||||
# Desktop Chromium only, without tests tagged @quarantine (tools/vendor/frontend-coverage.mjs).
|
||||
# Shard 1 also runs the node units and the viewer suite.
|
||||
- name: Page workflows with coverage, shard ${{ matrix.shard }}/4
|
||||
timeout-minutes: 15
|
||||
run: npm run --prefix tools/vendor test:coverage:shard -- ${{ matrix.shard }}/4
|
||||
- name: Upload raw coverage
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: coverage-raw-${{ matrix.shard }}
|
||||
path: coverage/js/raw/
|
||||
if-no-files-found: error
|
||||
retention-days: 3
|
||||
# Traces and the blob report (test-results/blob/) of a failed, timed-out or cancelled step.
|
||||
- name: Upload Chromium traces
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: frontend-traces-shard-${{ matrix.shard }}
|
||||
path: tools/vendor/test-results/
|
||||
retention-days: 14
|
||||
|
||||
frontend-coverage-merge:
|
||||
name: frontend coverage (merge)
|
||||
# Runs only when every shard succeeded (the implicit success() check).
|
||||
needs: [changes, frontend-coverage]
|
||||
if: ${{ needs.changes.outputs.class == 'code' }}
|
||||
runs-on: ubuntu-latest
|
||||
# Same image as the shards: the raw files name sources by the container's workspace path.
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
options: --user 1001
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- run: node --version && node --version | grep -q '^v24\.'
|
||||
# npm's download cache, keyed on the lockfile; inside the container ~ is the job's HOME (/github/home),
|
||||
# which npm also uses. node_modules itself is still built fresh by npm ci.
|
||||
- name: Cache npm downloads
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
|
||||
- run: npm ci --prefix tools/vendor --ignore-scripts
|
||||
# Each artifact lands in its own coverage-raw-N directory, so the next step can count them.
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: coverage-raw-*
|
||||
path: ${{ runner.temp }}/coverage-raw
|
||||
# coverage:merge only checks that raw files exist; merging three of four shards would report
|
||||
# partial coverage, so a missing or empty shard artifact fails here.
|
||||
- name: Verify every shard's raw coverage arrived
|
||||
shell: bash
|
||||
env:
|
||||
STAGED_RAW: ${{ runner.temp }}/coverage-raw
|
||||
EXPECTED_SHARDS: 4
|
||||
run: |
|
||||
found=0
|
||||
for shard in $(seq 1 "$EXPECTED_SHARDS"); do
|
||||
directory="$STAGED_RAW/coverage-raw-$shard"
|
||||
count=0
|
||||
if [ -d "$directory" ]; then count=$(find "$directory" -maxdepth 1 -type f -name '*.json' | wc -l); fi
|
||||
echo "coverage-raw-$shard: $count raw files"
|
||||
if [ "$count" -gt 0 ]; then found=$((found + 1)); fi
|
||||
done
|
||||
echo "shard artifacts with raw coverage: $found of $EXPECTED_SHARDS"
|
||||
if [ "$found" -ne "$EXPECTED_SHARDS" ]; then
|
||||
echo "::error::Expected raw coverage from $EXPECTED_SHARDS shards, got $found of $EXPECTED_SHARDS"
|
||||
exit 1
|
||||
fi
|
||||
staged=$(find "$STAGED_RAW" -mindepth 2 -maxdepth 2 -type f -name '*.json' | wc -l)
|
||||
mkdir -p coverage/js/raw
|
||||
# cp -n never overwrites; a clash shows up as fewer merged files than staged ones.
|
||||
find "$STAGED_RAW" -mindepth 2 -maxdepth 2 -type f -name '*.json' -exec cp -n -t coverage/js/raw {} + || true
|
||||
merged=$(find coverage/js/raw -maxdepth 1 -type f -name '*.json' | wc -l)
|
||||
if [ "$merged" -ne "$staged" ]; then
|
||||
echo "::error::Shards wrote clashing raw file names: $staged staged, $merged merged"
|
||||
exit 1
|
||||
fi
|
||||
echo "merged $merged raw files"
|
||||
- name: Frontend coverage report and baseline check
|
||||
run: npm run --prefix tools/vendor coverage:merge
|
||||
- name: Upload frontend coverage report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: frontend-test-reports
|
||||
path: |
|
||||
coverage/js/
|
||||
!coverage/js/raw/**
|
||||
retention-days: 14
|
||||
|
||||
# The one required context. Branch protection names only "gate", so renaming or adding a job above
|
||||
# never strands a pull request. It passes only when the classifier succeeded and every job did what
|
||||
# the class asks: for "code" every test job succeeded and the release check was skipped; for
|
||||
# "release" only the package check ran, and it succeeded; for "docs" and "inert" everything was
|
||||
# skipped. A failed, cancelled or wrongly skipped job fails it, and so does a class the classifier
|
||||
# does not print.
|
||||
gate:
|
||||
needs: [changes, python, package, lint, security, js-test, tooling, frontend-coverage, frontend-coverage-merge]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Require every job the change class asks for
|
||||
env:
|
||||
CHANGE_CLASS: ${{ needs.changes.outputs.class }}
|
||||
CHANGES_RESULT: ${{ needs.changes.result }}
|
||||
PYTHON_RESULT: ${{ needs.python.result }}
|
||||
PACKAGE_RESULT: ${{ needs.package.result }}
|
||||
LINT_RESULT: ${{ needs.lint.result }}
|
||||
SECURITY_RESULT: ${{ needs.security.result }}
|
||||
JS_RESULT: ${{ needs.js-test.result }}
|
||||
TOOLING_RESULT: ${{ needs.tooling.result }}
|
||||
COVERAGE_RESULT: ${{ needs.frontend-coverage.result }}
|
||||
MERGE_RESULT: ${{ needs.frontend-coverage-merge.result }}
|
||||
run: |
|
||||
echo "change class: $CHANGE_CLASS (classifier: $CHANGES_RESULT)"
|
||||
test "$CHANGES_RESULT" = success
|
||||
case "$CHANGE_CLASS" in
|
||||
code) code=success; release=skipped ;;
|
||||
release) code=skipped; release=success ;;
|
||||
docs|inert) code=skipped; release=skipped ;;
|
||||
*) echo "::error::unknown change class"; exit 1 ;;
|
||||
esac
|
||||
failed=0
|
||||
require() {
|
||||
echo "$1: $2 (must be $3)"
|
||||
if [ "$2" != "$3" ]; then echo "::error::$1 is $2, must be $3"; failed=1; fi
|
||||
}
|
||||
require python "$PYTHON_RESULT" "$code"
|
||||
require lint "$LINT_RESULT" "$code"
|
||||
require security "$SECURITY_RESULT" "$code"
|
||||
require js-test "$JS_RESULT" "$code"
|
||||
require tooling "$TOOLING_RESULT" "$code"
|
||||
require frontend-coverage "$COVERAGE_RESULT" "$code"
|
||||
require frontend-coverage-merge "$MERGE_RESULT" "$code"
|
||||
require package "$PACKAGE_RESULT" "$release"
|
||||
exit "$failed"
|
||||
@@ -0,0 +1,43 @@
|
||||
name: Code Quality
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
merge_group:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
# Superseded PR pushes cancel their older run. Every main push gets its own
|
||||
# group (run_id), so no main commit's run is ever cancelled or dropped as pending.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
security:
|
||||
name: bandit (high severity)
|
||||
runs-on: ubuntu-latest
|
||||
# ceil(1.5 x slowest of three green main runs) + 3, never under 5 (test.yml): runs 40257217665,
|
||||
# 40254137380, 40240706583 took 23s / 16s / 23s -> 5 min.
|
||||
timeout-minutes: 5
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python 3.12
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install bandit
|
||||
run: pip install bandit[toml]
|
||||
|
||||
# Medium findings are reported without failing until they are triaged.
|
||||
# High severity is a hard gate.
|
||||
- name: Security report (medium and above, informational)
|
||||
run: bandit -r . -ll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules --exit-zero
|
||||
- name: Security scan (high severity gate)
|
||||
run: bandit -r . -lll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules
|
||||
@@ -1,359 +0,0 @@
|
||||
name: Nightly
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Everything that is not in the gate (#666): other browsers, the phone-size project, other Pythons,
|
||||
# Windows, a real mount, a real ComfyUI and the wall-clock budget. It never runs on a pull request or
|
||||
# a merge and no context here is required. A failing job opens or updates one issue
|
||||
# ("nightly: <job> failing"); the next green run closes it. To try a branch before it merges:
|
||||
# gh workflow run nightly.yml --ref <branch> (a branch run files no issues).
|
||||
on:
|
||||
schedule:
|
||||
- cron: "17 3 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
# Every run gets its own group (run_id), so no run is ever cancelled or dropped as pending.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.run_id }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
PYTHONFAULTHANDLER: "1"
|
||||
|
||||
# Time limit rule as in ci.yml: ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never
|
||||
# under 5, timed as whole-job wall time; a matrix job takes its slowest leg. A job with no three
|
||||
# green runs yet has an "estimate" line. tests/vendor/ci-workflow.test.mjs recomputes every limit.
|
||||
# Measured 2026-11-21 on runs 44861123845 (a1f7447), 44547399478 (b3bb55f), 44519471869 (fa31644):
|
||||
# python-linux: 6m12s / 5m14s / 5m37s -> 13 min
|
||||
# comfyui: 20m21s / 20m39s / 21m06s -> 35 min
|
||||
# perf-budget: 0m23s / 0m29s / 0m28s -> 5 min
|
||||
# Measured 2026-11-21 on runs 44730775403 (b3bb55f), 44518136123 (9943a61), 44298521973 (1d509c8):
|
||||
# python-windows: 8m04s / 8m41s / 9m27s -> 18 min
|
||||
# native-trash-linux: 0m29s / 0m19s / 0m29s -> 5 min
|
||||
# Measured 2026-11-21 on runs 44861123725 (a1f7447), 44547398683 (b3bb55f), 44519471975 (fa31644):
|
||||
# browser-workflows: 12m44s / 15m55s / 14m55s -> 27 min
|
||||
# (the Firefox and WebKit legs; touch ran inside the coverage shards until #666 and has no
|
||||
# measurement of its own: about half of a 7m55s-16m48s shard)
|
||||
# estimate report: one script and a few API calls, under 1 minute -> 5 min
|
||||
#
|
||||
# Browser jobs (#425): the page test step has its own timeout-minutes, 2 below the job's, so a hang
|
||||
# ends inside the step and the log, the blob report and the traces survive (see ci.yml).
|
||||
jobs:
|
||||
python-linux:
|
||||
name: py${{ matrix.python-version }} on ubuntu-latest
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 13
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: ["3.13", "3.14"]
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements-dev.txt
|
||||
|
||||
- name: Run tests
|
||||
run: python -m tests.run_suite -v
|
||||
|
||||
python-windows:
|
||||
name: py${{ matrix.python-version }} on windows-latest
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 18
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: ["3.12", "3.13", "3.14"]
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements-dev.txt
|
||||
|
||||
# The runner's TEMP is on C:, the OS disk, where a flush took about 6 ms
|
||||
# and a test database's create-to-delete about 111 ms; on the D: work
|
||||
# disk the same took 0.5 ms and 23 ms. Tests write their
|
||||
# databases under TEMP, so it moves to a folder on D: (measured in #487,
|
||||
# run 40915866444). The runner's TEMP was an 8.3 short name
|
||||
# (C:\Users\RUNNER~1\...), so the new one is spelled by its short name too
|
||||
# and paths still have to be resolved. D: makes no short names by default
|
||||
# (run 40922502209), so they are switched on for it first.
|
||||
- name: Keep test files on the work disk
|
||||
shell: pwsh
|
||||
run: |
|
||||
fsutil 8dot3name set D: 0
|
||||
$folder = New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP "PromptManagerTests")
|
||||
$short = (New-Object -ComObject Scripting.FileSystemObject).GetFolder($folder.FullName).ShortPath
|
||||
Write-Output "test TEMP: $short (long name $($folder.FullName))"
|
||||
if ($short -eq $folder.FullName) { Write-Output "::warning::D: gave the test TEMP no 8.3 short name" }
|
||||
"TEMP=$short" >> $env:GITHUB_ENV
|
||||
"TMP=$short" >> $env:GITHUB_ENV
|
||||
|
||||
- name: Run tests
|
||||
env:
|
||||
PM_TEST_SLOWEST: "40"
|
||||
run: python -m tests.run_suite -v
|
||||
|
||||
# The same tests as the fake mount table, on a real ext4 mount used as the output root (#543). A
|
||||
# runner can mount with sudo; the tests run as the normal user, so owner and mode checks are real.
|
||||
native-trash-linux:
|
||||
name: native trash on a real mount
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements-dev.txt
|
||||
|
||||
- name: Mount an ext4 image
|
||||
run: |
|
||||
truncate -s 64M "$RUNNER_TEMP/drive.img"
|
||||
mkfs.ext4 -q "$RUNNER_TEMP/drive.img"
|
||||
mkdir "$RUNNER_TEMP/drive"
|
||||
sudo mount -o loop "$RUNNER_TEMP/drive.img" "$RUNNER_TEMP/drive"
|
||||
sudo rmdir "$RUNNER_TEMP/drive/lost+found"
|
||||
sudo chown "$(id -u):$(id -g)" "$RUNNER_TEMP/drive"
|
||||
findmnt "$RUNNER_TEMP/drive"
|
||||
|
||||
- name: Native trash proof
|
||||
timeout-minutes: 3
|
||||
run: PM_TRASH_MOUNT="$RUNNER_TEMP/drive" python -m unittest tests.test_trash_mount_root -v
|
||||
|
||||
perf-budget:
|
||||
# The reference wall-clock measurement (TESTING.md "Performance budgets"). Shared-runner timing
|
||||
# varies, so it never gates a pull request. A red run means fix the code.
|
||||
name: perf budget
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.13"
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements-dev.txt
|
||||
|
||||
- name: Workspace filter budget
|
||||
env:
|
||||
PROMPTMANAGER_PERF_BUDGET: "1"
|
||||
run: python -m unittest -v tests.test_api_workspace_images.TestWorkspaceImages.test_filter_budget
|
||||
|
||||
comfyui:
|
||||
name: real ComfyUI compatibility
|
||||
runs-on: ubuntu-latest
|
||||
# Chromium and its system libraries come from the pinned Playwright image (tag = @playwright/test in
|
||||
# tools/vendor/package-lock.json; tests/vendor/browser-image.test.mjs checks it). The runner install
|
||||
# pulled them from Ubuntu's apt mirror on every run, and three runs (#349, #378, #382) crawled at
|
||||
# ~26 kB/s for 11-12 minutes until the job hit its limit after every test had passed.
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
options: --user 1001
|
||||
timeout-minutes: 35
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Read the reviewed runtime pins
|
||||
id: runtime
|
||||
run: |
|
||||
node --input-type=module <<'JS' >> "$GITHUB_OUTPUT"
|
||||
import runtime from './tools/vendor/comfyui-runtime.json' with { type: 'json' };
|
||||
for (const [key, value] of Object.entries(runtime)) console.log(`${key}=${value}`);
|
||||
import crossPack from './tools/vendor/cross-pack-runtime.json' with { type: 'json' };
|
||||
console.log(`kikoRepository=${crossPack.repository}`);
|
||||
console.log(`kikoRevision=${crossPack.revision}`);
|
||||
JS
|
||||
- name: Check out pinned ComfyUI
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
repository: ${{ steps.runtime.outputs.repository }}
|
||||
ref: ${{ steps.runtime.outputs.revision }}
|
||||
path: .ci-comfyui
|
||||
persist-credentials: false
|
||||
- name: Check out pinned KikoTools for compatibility
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
repository: ${{ steps.runtime.outputs.kikoRepository }}
|
||||
ref: ${{ steps.runtime.outputs.kikoRevision }}
|
||||
path: .ci-kikotools
|
||||
persist-credentials: false
|
||||
# The image's own Python and Node 24: setup-python/setup-node install the runner's toolcache builds,
|
||||
# whose entry points name host paths that do not exist in the container. The image has no ensurepip
|
||||
# and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv. The image
|
||||
# Python must be the reviewed host Python, so a pin or image bump that disagrees fails here.
|
||||
- name: Python environment on the reviewed host Python
|
||||
env:
|
||||
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
|
||||
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
|
||||
PINNED_PYTHON: ${{ steps.runtime.outputs.pythonVersion }}
|
||||
run: |
|
||||
image="$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
|
||||
[ "$image" = "$PINNED_PYTHON" ] || { echo "::error::image Python $image is not the pinned $PINNED_PYTHON"; exit 1; }
|
||||
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
|
||||
python3 -m venv --without-pip "$venv"
|
||||
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
|
||||
echo "$PIP_SHA256 $wheel" | sha256sum -c -
|
||||
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
|
||||
echo "$venv/bin" >> "$GITHUB_PATH"
|
||||
- run: python --version && node --version && node --version | grep -q '^v24\.'
|
||||
# pip's download cache (torch alone is ~200 MB); inside the container ~ is the job's HOME (/github/home).
|
||||
- name: Cache pip downloads
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/.cache/pip
|
||||
key: pip-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('requirements-dev.txt', '.ci-comfyui/requirements.txt', 'tools/vendor/comfyui-runtime.json') }}
|
||||
- name: Install CPU runtime and test dependencies
|
||||
run: |
|
||||
pip install "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}" --index-url https://download.pytorch.org/whl/cpu
|
||||
pip install -r .ci-comfyui/requirements.txt -r requirements-dev.txt "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}"
|
||||
# npm's download cache, keyed on the lockfile. node_modules itself is still built fresh by npm ci.
|
||||
- name: Cache npm downloads
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
|
||||
- run: npm ci --prefix tools/vendor --ignore-scripts
|
||||
- name: Classic and Nodes 2.0 startup and compatibility
|
||||
env:
|
||||
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
|
||||
PM_TEST_PYTHON: python
|
||||
run: npm run --prefix tools/vendor test:comfyui
|
||||
- name: Real cached and headless execution history
|
||||
env:
|
||||
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
|
||||
PM_TEST_PYTHON: python
|
||||
run: npm run --prefix tools/vendor test:executions
|
||||
- name: Independent and combined pack compatibility
|
||||
env:
|
||||
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
|
||||
PM_KIKO_ROOT: ${{ github.workspace }}/.ci-kikotools
|
||||
PM_TEST_PYTHON: python
|
||||
run: npm run --prefix tools/vendor test:compat
|
||||
- name: Upload real-host reports and startup logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: real-comfyui-reports
|
||||
path: tools/vendor/test-results/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
browser-workflows:
|
||||
name: page workflows (${{ matrix.browser }}, shard ${{ matrix.shard }}/3)
|
||||
# Firefox, WebKit and touch (phone-size Chromium): not first-class, so they report here instead of
|
||||
# blocking a merge. Quarantined tests (@quarantine) run here too. One retry: a test that fails
|
||||
# and then passes is listed as flaky in the job summary (tools/vendor/flaky-tests-reporter.mjs)
|
||||
# instead of failing the job.
|
||||
runs-on: ubuntu-latest
|
||||
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
|
||||
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
|
||||
# tests/vendor/browser-image.test.mjs checks it). Browsers and fonts come from the image.
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
options: --user 1001
|
||||
timeout-minutes: 27
|
||||
# Public-repo ubuntu-latest runners have 4 vCPUs: three Playwright workers, each with its own test
|
||||
# server, leave one CPU for the servers and the runner.
|
||||
env:
|
||||
PM_TEST_WORKERS: 3
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
browser: [firefox, webkit, touch]
|
||||
shard: [1, 2, 3]
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
# The image's own Python 3.12 and Node 24: setup-python/setup-node install the runner's toolcache
|
||||
# builds, whose entry points name host paths that do not exist in the container. The image has no
|
||||
# ensurepip and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv.
|
||||
- name: Python environment
|
||||
env:
|
||||
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
|
||||
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
|
||||
run: |
|
||||
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
|
||||
python3 -m venv --without-pip "$venv"
|
||||
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
|
||||
echo "$PIP_SHA256 $wheel" | sha256sum -c -
|
||||
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
|
||||
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
|
||||
echo "$venv/bin" >> "$GITHUB_PATH"
|
||||
- run: python --version && node --version && node --version | grep -q '^v24\.'
|
||||
# npm's download cache, keyed on the lockfile; inside the container ~ is the job's HOME (/github/home),
|
||||
# which npm also uses. node_modules itself is still built fresh by npm ci.
|
||||
- name: Cache npm downloads
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
|
||||
- run: npm ci --prefix tools/vendor --ignore-scripts
|
||||
- name: Page workflows in ${{ matrix.browser }}, shard ${{ matrix.shard }}/3
|
||||
timeout-minutes: 25
|
||||
run: npm run --prefix tools/vendor test:workflows -- --project ${{ matrix.browser }} --shard ${{ matrix.shard }}/3 --retries 1
|
||||
# Traces and the blob report (test-results/blob/) of a failed, timed-out or cancelled step.
|
||||
- name: Upload browser traces
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: browser-traces-${{ matrix.browser }}-shard-${{ matrix.shard }}
|
||||
path: tools/vendor/test-results/
|
||||
retention-days: 14
|
||||
|
||||
# One issue per job (tools/ci/nightly_report.py): a job with a failed leg opens "nightly: <job>
|
||||
# failing" or comments on the open one; a job whose legs all passed closes its open issue. Shards
|
||||
# of one browser count as one job. Only runs of main report: a manual run of a branch changes no
|
||||
# issue.
|
||||
report:
|
||||
name: report by issue
|
||||
needs: [python-linux, python-windows, native-trash-linux, perf-budget, comfyui, browser-workflows]
|
||||
if: ${{ always() && github.ref == 'refs/heads/main' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Open, update or close one issue per job
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RUN_ATTEMPT: ${{ github.run_attempt }}
|
||||
run: python3 tools/ci/nightly_report.py
|
||||
@@ -0,0 +1,117 @@
|
||||
name: Windows
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Non-blocking Windows runs (#420; macOS dropped from CI in #571): never on pull requests or in the merge queue, and no context
|
||||
# here is a required check. A red run is fixed at its cause before the workspace cutover (#334).
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
schedule:
|
||||
- cron: "17 3 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
# Every run gets its own group (run_id), so no main commit's run is ever cancelled or dropped as pending.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.run_id }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
PYTHONFAULTHANDLER: "1"
|
||||
|
||||
# Time limit rule as in test.yml: ceil(1.5 x the slowest of three recent green runs on main) + 3
|
||||
# minutes, never under 5, timed as whole-job wall time. One matrix job, so the slowest leg of each
|
||||
# run counts (tests/vendor/ci-workflow.test.mjs recomputes it, #493).
|
||||
# Measured 2026-10-29 on main runs 40935337099 (dd247e3), 40938407252 (dd247e3), 40941240624 (dd247e3):
|
||||
# slowest leg: 7m24s (py3.12 windows) / 7m31s (py3.13 windows) / 7m32s (py3.14 windows) -> 15 min
|
||||
# (windows 4m56s-7m32s)
|
||||
# native-trash-linux (#543) has no green main runs yet: it installs the dev requirements and runs
|
||||
# one test module, about 1 minute by the same estimate, so ceil(1.5 x 2) + 3 gives it 6 minutes.
|
||||
# Recalibrate after three green runs.
|
||||
jobs:
|
||||
test:
|
||||
name: py${{ matrix.python-version }} on ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 15
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-latest]
|
||||
python-version: ["3.12", "3.13", "3.14"]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements-dev.txt
|
||||
|
||||
# The runner's TEMP is on C:, the OS disk, where a flush took about 6 ms
|
||||
# and a test database's create-to-delete about 111 ms; on the D: work
|
||||
# disk the same took 0.5 ms and 23 ms. Tests write their
|
||||
# databases under TEMP, so it moves to a folder on D: (measured in #487,
|
||||
# run 40915866444). The runner's TEMP was an 8.3 short name
|
||||
# (C:\Users\RUNNER~1\...), so the new one is spelled by its short name too
|
||||
# and paths still have to be resolved. D: makes no short names by default
|
||||
# (run 40922502209), so they are switched on for it first.
|
||||
- name: Keep test files on the work disk (Windows)
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
run: |
|
||||
fsutil 8dot3name set D: 0
|
||||
$folder = New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP "PromptManagerTests")
|
||||
$short = (New-Object -ComObject Scripting.FileSystemObject).GetFolder($folder.FullName).ShortPath
|
||||
Write-Output "test TEMP: $short (long name $($folder.FullName))"
|
||||
if ($short -eq $folder.FullName) { Write-Output "::warning::D: gave the test TEMP no 8.3 short name" }
|
||||
"TEMP=$short" >> $env:GITHUB_ENV
|
||||
"TMP=$short" >> $env:GITHUB_ENV
|
||||
|
||||
- name: Run tests
|
||||
env:
|
||||
PM_TEST_SLOWEST: "40"
|
||||
run: python -m tests.run_suite -v
|
||||
|
||||
# The same tests as the fake mount table, on a real ext4 mount used as the output root (#543). A
|
||||
# runner can mount with sudo; the tests run as the normal user, so owner and mode checks are real.
|
||||
native-trash-linux:
|
||||
name: native trash on a real mount
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 6
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements-dev.txt
|
||||
|
||||
- name: Mount an ext4 image
|
||||
run: |
|
||||
truncate -s 64M "$RUNNER_TEMP/drive.img"
|
||||
mkfs.ext4 -q "$RUNNER_TEMP/drive.img"
|
||||
mkdir "$RUNNER_TEMP/drive"
|
||||
sudo mount -o loop "$RUNNER_TEMP/drive.img" "$RUNNER_TEMP/drive"
|
||||
sudo rmdir "$RUNNER_TEMP/drive/lost+found"
|
||||
sudo chown "$(id -u):$(id -g)" "$RUNNER_TEMP/drive"
|
||||
findmnt "$RUNNER_TEMP/drive"
|
||||
|
||||
- name: Native trash proof
|
||||
timeout-minutes: 4
|
||||
run: PM_TRASH_MOUNT="$RUNNER_TEMP/drive" python -m unittest tests.test_trash_mount_root -v
|
||||
@@ -11,16 +11,10 @@ on:
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
# The only workflow a push to main starts (#666): the pull request's gate already tested the commit.
|
||||
# It runs when pyproject.toml changed, and the action publishes when the version is new.
|
||||
# Time limit rule as in ci.yml: ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never under 5.
|
||||
# Measured 2026-11-21 on runs 44547398738 (b3bb55f), 44189688689 (1d509c8), 41519786847 (71b55bc):
|
||||
# publish-node: 0m33s / 0m31s / 1m16s -> 5 min
|
||||
jobs:
|
||||
publish-node:
|
||||
name: Publish Custom Node to registry
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
if: ${{ github.repository_owner == 'ComfyAssets' }}
|
||||
steps:
|
||||
- name: Check out code
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
name: Tests
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
merge_group:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
# Superseded PR pushes cancel their older run. Every main push gets its own
|
||||
# group (run_id), so no main commit's run is ever cancelled or dropped as pending.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
PYTHONFAULTHANDLER: "1"
|
||||
|
||||
# Every job has a time limit: ceil(1.5 x the slowest of three recent green runs on main) + 3
|
||||
# minutes, never under 5. The 3 minutes leave room for the Python runner's watchdog (120 s, see
|
||||
# tests/run_suite.py) to print its stack dump before GitHub cancels the job. A limit changes only
|
||||
# with new measurements written here (TESTING.md "Time limits and hangs").
|
||||
# Measured 2026-10-26 on runs 40257217681 (3be0ada), 40240706568 (fb9134f), 40228167328 (f9835aa):
|
||||
# py matrix, slowest py3.10 on windows-latest: 12m43s / 15m54s / 14m53s -> 27 min
|
||||
# (ubuntu 5m27s-6m27s, macos 6m14s-8m30s, windows 11m42s-15m54s)
|
||||
# 3.10 and 3.11 left the matrix and 3.14 joined it in #356; re-measure after three green main runs.
|
||||
# Windows moved to portability.yml (#420; macOS left CI in #571), which has its own measured limit (#493);
|
||||
# this Linux-only matrix keeps 27 minutes until it is re-measured.
|
||||
# real ComfyUI compatibility: 13m32s / 8m55s / 11m46s -> 24 min
|
||||
# coverage gate (85%): 7m26s / 7m22s / 7m54s -> 15 min
|
||||
# perf budget 30s / 29s / 27s, black and flake8 39s / 37s / 39s,
|
||||
# frontend modules 23s / 19s / 29s -> 5 min (the floor)
|
||||
# all tests: a result check without setup, 5 min (the floor)
|
||||
#
|
||||
# Pull requests run a fast subset (#420): Python 3.12 on ubuntu-latest, coverage, lint and frontend
|
||||
# modules. The merge queue (merge_group), pushes to main and manual runs add Python 3.13 and 3.14 on
|
||||
# Linux and the real ComfyUI job. "all tests" is the required gate that holds the queue to that set.
|
||||
# Windows runs in portability.yml (push to main, nightly, on demand) and never gate a merge.
|
||||
jobs:
|
||||
test:
|
||||
name: py${{ matrix.python-version }} on ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 27
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest]
|
||||
python-version: ${{ github.event_name == 'pull_request' && fromJSON('["3.12"]') || fromJSON('["3.12", "3.13", "3.14"]') }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements-dev.txt
|
||||
|
||||
- name: Run tests
|
||||
run: python -m tests.run_suite -v
|
||||
|
||||
comfyui:
|
||||
name: real ComfyUI compatibility
|
||||
# Merge queue, main and manual runs only. A job skipped by its condition reports Success, so this
|
||||
# required context never blocks a pull request; "all tests" fails if it is skipped anywhere else.
|
||||
if: github.event_name != 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
# Chromium and its system libraries come from the pinned Playwright image (tag = @playwright/test in
|
||||
# tools/vendor/package-lock.json; tests/vendor/browser-image.test.mjs checks it). The runner install
|
||||
# pulled them from Ubuntu's apt mirror on every run, and three runs (#349, #378, #382) crawled at
|
||||
# ~26 kB/s for 11-12 minutes until the job hit its limit after every test had passed.
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@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"
|
||||
@@ -0,0 +1,268 @@
|
||||
name: Viewer.js vendor and compatibility
|
||||
|
||||
on:
|
||||
merge_group:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Superseded PR pushes cancel their older run. Every main push gets its own
|
||||
# group (run_id), so no main commit's run is ever cancelled or dropped as pending.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
# Timeouts are the measured job time plus at least 50%, and never under 20 minutes for a browser job,
|
||||
# because runner speed varies. Before sharding (main 2cecfcf, one worker): frontend coverage 32m10s,
|
||||
# page workflows firefox 18m59s, webkit 19m26s. First sharded run (PR #274 run 39712909047, 3 workers,
|
||||
# no npm cache, where npm ci stalled for 5m in six of eight jobs): coverage shards 11m19s/10m47s/10m49s
|
||||
# (tests 5m20s/4m42s/4m46s), merge 5m52s (report and check 4s), firefox shards 7m53s/9m27s (tests
|
||||
# 4m41s/3m29s), webkit shards 12m25s+ (cancelled at the old 12-minute limit after its 267 tests passed in
|
||||
# 6m29s) and 4m53s (tests 3m08s). With the npm cache hit (run 39725176320 at cbc8a61, npm ci 0-2s):
|
||||
# coverage shards 7m34s/6m04s/5m22s (tests 6m38s/4m53s/4m04s), merge 54s, firefox 7m57s/5m21s (tests
|
||||
# 7m08s/4m34s), webkit 8m16s/5m03s (tests 7m26s/3m58s); a cache miss adds up to 5m to npm ci, which
|
||||
# the 20-minute limits absorb.
|
||||
# Hangs (#425): a job killed at its limit keeps no log and skips its upload steps, so each browser
|
||||
# test step has its own timeout-minutes (18) below the job's 20. At the step limit, SIGTERM makes
|
||||
# tools/vendor/running-tests-reporter.mjs print the tests still running and hand over to Playwright's
|
||||
# interrupt, which writes the blob report; the always() uploads then run.
|
||||
# Measured on main (runs 40725289094, 40719375442, 40700439399): setup before the test step <= 52s,
|
||||
# uploads <= 35s; test steps up to 14m42s (webkit shard 1/2) and 13m05s for coverage (shard 1/3:
|
||||
# 12m53s, node units and the viewer suite before 11.8m of workflows), so coverage is the tight one
|
||||
# in its 18 minutes. This holds only when the npm cache hits: a cold cache adds up to 5m to npm ci,
|
||||
# and then the job limit can still end the job before the step limit does.
|
||||
# #473: firefox/webkit shard 1/2 reached its 18-minute step limit (queue run 40866252975: webkit 622 tests
|
||||
# passed in 17m56s, 48.5 worker-minutes vs 28.0 in shard 2/2; recent shard 1/2 jobs 13.7m-18.9m, shard 2/2
|
||||
# 7.3m-12.2m), because --shard splits by test count and the slow concept specs sort into shard 1. The page
|
||||
# workflows now run in three shards per browser with the limits unchanged; the per-shard times are
|
||||
# re-measured after three green main runs.
|
||||
# #563: coverage shards reached their 18-minute step limit three times on 2026-10-31 with no failing
|
||||
# test (PR #560 shard 2/3: 814 passed in 17.9m; queue run 41206495451 shard 1/3: 827 passed; PR #564
|
||||
# shard 2/3 twice), against recent green shards of 11m-17m. Coverage now runs in four shards with the
|
||||
# limits unchanged; the per-shard times are re-measured after three green main runs.
|
||||
jobs:
|
||||
frontend-coverage:
|
||||
name: frontend coverage (shard ${{ matrix.shard }}/4)
|
||||
runs-on: ubuntu-latest
|
||||
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
|
||||
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
|
||||
# tests/vendor/browser-image.test.mjs checks it). Browsers and fonts come from the image.
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@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,18 +17,9 @@ concurrency:
|
||||
group: viewerjs-update
|
||||
cancel-in-progress: false
|
||||
|
||||
# Time limit rule as in ci.yml (#662): ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never under 5.
|
||||
# Measured 2026-11-21 on runs 44771628562 (b3bb55f), 44568715421 (b3bb55f), 44349316383 (1d509c8):
|
||||
# these nightly runs found no new release and took 0m09s / 0m13s / 0m12s, the 5-minute floor. None of
|
||||
# the 35 green runs since 2026-10-17 took the update path (tests, Chromium, the PR), so it is estimated
|
||||
# from its parts until three green update runs can be measured:
|
||||
# estimate update: npm ci on a cold cache up to 5m (as recorded for the browser jobs), Playwright
|
||||
# Chromium with its system packages about 2m, the pin check, tooling and unit tests about 1m, the
|
||||
# viewer suite (38s locally, 2 workers) and setup about 2m: 10 min, ceil(1.5 x 10) + 3 -> 18 min
|
||||
jobs:
|
||||
update:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 18
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
@@ -13,7 +13,7 @@ repos:
|
||||
language: system
|
||||
types: [python]
|
||||
|
||||
# Fails at the severity CI enforces (ci.yml: -lll, high only), never stricter.
|
||||
# Fails at the severity CI enforces (code-quality.yml: -lll, high only), never stricter.
|
||||
# pre-commit appends the staged files, so no shell wrapper can drop the first one.
|
||||
- id: bandit
|
||||
name: bandit
|
||||
@@ -22,10 +22,9 @@ 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 tools/ci/change_class.py --unless-inert python -m tests.run_suite -q
|
||||
entry: python -m tests.run_suite -q
|
||||
language: system
|
||||
pass_filenames: false
|
||||
stages: [pre-push]
|
||||
|
||||
+2
-1
@@ -5,7 +5,8 @@
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||

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

|
||||

|
||||

|
||||

|
||||
|
||||
Prompt Manager saves your prompts as you generate, links each image back to the prompt that made it, and gives you one page to browse, tag, compare and reuse all of it. Your library is a local SQLite database on your own machine.
|
||||
|
||||
## What's new: rebuilt from the ground up
|
||||
|
||||
- **A new UI.** One app, the workspace, replaces the separate dashboard, gallery and metadata pages.
|
||||
- **A new UI.** One app, the workspace, replaces the separate dashboard, gallery and metadata pages. The old pages still work if you want them.
|
||||
- **Classic and Nodes 2.0.** The nodes work in both ComfyUI renderers. CI starts a real ComfyUI and checks both.
|
||||
- **Tested end to end.** Unit tests, browser tests in Chromium, Firefox, WebKit and touch emulation, and tests against a real ComfyUI.
|
||||
- **Linux and Windows.** The Python suite runs on both, on Python 3.12, 3.13 and 3.14. macOS should work but is not tested.
|
||||
- **Mac, Linux and Windows.** The Python suite runs on all three, on Python 3.12, 3.13 and 3.14.
|
||||
|
||||
## See it
|
||||
|
||||
@@ -103,7 +101,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 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.
|
||||
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.
|
||||
|
||||

|
||||
|
||||
@@ -214,9 +212,9 @@ 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 still work
|
||||
|
||||
They still work at their URLs for now and will be removed in a future release. Everything they do is moving to the workspace.
|
||||
They stay at their URLs, and System's Overview section links to them:
|
||||
|
||||
| Page | URL |
|
||||
| --- | --- |
|
||||
@@ -230,7 +228,6 @@ The documentation for those pages is in [README-legacy.md](README-legacy.md).
|
||||
## Known limits
|
||||
|
||||
- **Trash is Linux and macOS only.** Windows has no Recycle Bin option, because the bin can delete large files permanently without warning. On Windows you can only remove an image from the library, and the file stays on disk. Where a move to the trash isn't possible on Linux or macOS, the dialog lists 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.
|
||||
@@ -246,7 +243,7 @@ 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 |
|
||||
|
||||
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).
|
||||
Linux runs on every pull request and in the merge queue. Windows runs on every push to main and nightly. macOS is not tested; it should work, but support is best-effort. To run the tests yourself, see [TESTING.md](TESTING.md).
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+157
-403
@@ -35,8 +35,8 @@ python -m tests.run_suite -q # what CI runs; see "Time limits and hangs"
|
||||
npm ci --prefix tools/vendor --ignore-scripts
|
||||
npx --prefix tools/vendor playwright install --with-deps chromium firefox webkit
|
||||
npm run --prefix tools/vendor test
|
||||
npm run --prefix tools/vendor test:coverage # desktop Chromium: what the gate runs
|
||||
npm run --prefix tools/vendor test:workflows -- --project firefox --project webkit --project touch # what nightly runs
|
||||
npm run --prefix tools/vendor test:coverage
|
||||
npm run --prefix tools/vendor test:workflows -- --project firefox --project webkit
|
||||
```
|
||||
|
||||
`python -m unittest discover -s tests` still works and finds the same tests;
|
||||
@@ -77,7 +77,7 @@ PM_TEST_WORKERS=8 npm run --prefix tools/vendor test:coverage # whole
|
||||
npm run --prefix tools/vendor test:coverage:shard -- 1/4 # node units, viewer suite, workflows 1/4
|
||||
npm run --prefix tools/vendor test:coverage:shard -- 2/4 # workflows 2/4 (likewise 3/4, 4/4)
|
||||
npm run --prefix tools/vendor coverage:merge # report and baseline check of every raw file
|
||||
npm run --prefix tools/vendor test:workflows -- --project webkit --shard 2/3
|
||||
npm run --prefix tools/vendor test:workflows -- --project webkit --shard 2/2
|
||||
```
|
||||
|
||||
`coverage:merge` refuses an empty raw directory; it does not count shards, so run
|
||||
@@ -191,26 +191,23 @@ exists. It uses the gate's own `discoverSources`, and `npm test` runs the same
|
||||
check, so run it before pushing a new or deleted frontend file instead of
|
||||
waiting for the `frontend coverage` jobs.
|
||||
|
||||
Frontend coverage is measured with desktop Chromium alone (#666): the gate's
|
||||
four `frontend coverage (shard N/4)` jobs and `frontend coverage (merge)` run on
|
||||
every pull request with a code change, including backend-only ones (see "The
|
||||
gate and the nightly run"). The phone-size `touch` project, Firefox and WebKit
|
||||
run nightly and add no coverage. Measured on main a1f74470 in the pinned image
|
||||
(2026-11-21): with the node units and Chromium alone, without touch, all 126
|
||||
files met their floors; the closest were `workspace/images-state.mjs` branches
|
||||
(98.05 against 98) and `workspace/viewer-state.mjs` branches (95.06 against 95).
|
||||
Every browser job runs with `PM_TEST_WORKERS: 3` (the public
|
||||
The `viewerjs` check runs on every PR, including backend-only changes. It is an
|
||||
aggregate job. It requires the four `frontend coverage (shard N/4)` jobs and
|
||||
`frontend coverage (merge)` to succeed on every event. The four
|
||||
`page workflows (firefox|webkit, shard N/2)` jobs run only in the merge queue,
|
||||
on `main` and on `workflow_dispatch` (see "Pull requests and the merge queue").
|
||||
`viewerjs` requires them to be skipped on a pull request and to succeed
|
||||
everywhere else. Any other failed, cancelled or skipped job fails it. Every browser job runs with `PM_TEST_WORKERS: 3` (the public
|
||||
runners have 4 vCPUs). Each coverage shard runs `test:coverage:shard -- N/4`
|
||||
(shard 1 also runs the node units and the viewer suite) and uploads its raw V8
|
||||
files as `coverage-raw-N` (kept 3 days). The merge job downloads them, fails
|
||||
unless all four arrived with raw
|
||||
(shard 1 also runs the node units and the viewer suite, shard 4 the vendor pins
|
||||
and tooling tests) and uploads its raw V8 files as `coverage-raw-N` (kept 3
|
||||
days). The merge job downloads them, fails unless all three arrived with raw
|
||||
files and without clashing names, then runs `coverage:merge` (report plus
|
||||
baseline check). The vendor pins and the tooling tests run in their own job,
|
||||
`tooling tests and pins`. `tests/vendor/ci-workflow.test.mjs` checks this shape. GitHub
|
||||
baseline check). `tests/vendor/ci-workflow.test.mjs` checks this shape. GitHub
|
||||
artifacts named `frontend-test-reports` contain the merged HTML coverage and
|
||||
JSON summary; `frontend-traces-shard-N` hold the Chromium failure
|
||||
screenshots/traces and, from the nightly run, `browser-traces-<browser>-shard-N`
|
||||
the other projects' traces. Open traces with Playwright's `show-trace` tool.
|
||||
JSON summary; `frontend-traces-shard-N` hold the Chromium/touch failure
|
||||
screenshots/traces and `browser-traces-<browser>-shard-N` the other browsers'
|
||||
traces. Open traces with Playwright's `show-trace` tool.
|
||||
|
||||
Every `npm ci` first restores npm's download cache (`~/.npm`), keyed on the vendor
|
||||
lockfile and the job's pinned image tag (`tests/vendor/ci-workflow.test.mjs` checks
|
||||
@@ -238,8 +235,8 @@ need targeted validation.
|
||||
## Time limits and hangs
|
||||
|
||||
CI and the pre-push hook run the Python suite as `python -m tests.run_suite`
|
||||
(`-v`, `-q`, `-s START` and `-p PATTERN` as in `unittest discover`); the gate
|
||||
runs it once, under coverage, as `python -m coverage run -m tests.run_suite -v`. The runner
|
||||
(`-v`, `-q`, `-s START` and `-p PATTERN` as in `unittest discover`), and the
|
||||
coverage job as `python -m coverage run -m tests.run_suite`. The runner
|
||||
(`tests/run_suite.py`) discovers the same tests with the same `sys.path` and
|
||||
warning filters as `python -m unittest discover -s tests`, exits 0, 1, or 5 when
|
||||
no tests ran (Python 3.12+ behaviour, on every version), and adds a watchdog: it writes `start: <test id>` to stderr before every test, at every
|
||||
@@ -267,56 +264,35 @@ the process exits non-zero.
|
||||
job fails anyway and the dump is what matters.
|
||||
- `PM_TEST_SLOWEST=N` (off by default) lists the N slowest tests after the
|
||||
summary, each timed from its `start:` line to the next one like the hang
|
||||
limit. The Windows jobs (`nightly.yml`) set it to 40, so every
|
||||
limit. The Windows jobs (`portability.yml`) set it to 40, so every
|
||||
run shows where its time went (#487). The list prints only when the run
|
||||
ends: a job GitHub cancels or a watchdog exit prints none, so read the
|
||||
timestamps between `start:` lines instead.
|
||||
- On the Windows runners `TEMP` sits on the OS disk C:, where a flush took about
|
||||
6 ms and a test database's create-to-delete about 111 ms (D: 0.5 ms and 23 ms,
|
||||
macOS 19 ms). `nightly.yml` points `TEMP`/`TMP` at a folder under
|
||||
macOS 19 ms). `portability.yml` points `TEMP`/`TMP` at a folder under
|
||||
`RUNNER_TEMP` on D: before the suite. It switches 8.3 short names on for D:
|
||||
and spells the folder by its short name, as the runner's own TEMP was
|
||||
(`C:\Users\RUNNER~1\...`), logs it, and warns when there is none.
|
||||
A test that waits on a fixed busy timeout, a network name (`\\server\share`:
|
||||
use `\\localhost\<missing share>`) or a default TLS context (it reads the
|
||||
Windows certificate store) costs seconds there; the slowest list shows it.
|
||||
- On a Windows development machine (#636), give the suite a short `TEMP`
|
||||
(for example `C:\t`) or turn long paths on
|
||||
(`HKLM\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled` = 1).
|
||||
Under the default `C:\Users\<user>\AppData\Local\Temp`, the visual fixture's
|
||||
182-character file name passes Windows' 260-character limit once a test
|
||||
nests its own temp folder, and the chronological-history reset answers 500.
|
||||
Three other differences from the CI runner are handled in the tests:
|
||||
a virtual environment's `python.exe` is a launcher that runs the real
|
||||
interpreter as a child, so a test that kills a server it started removes its
|
||||
folder with `tests/process_cleanup.py`'s `remove_when_released`, which waits
|
||||
for that child to end (a handle the test process itself still holds never
|
||||
releases, so the bound still fails it); Git for Windows checks text files out
|
||||
with CRLF, so `.gitattributes` keeps the pinned vendored files byte for byte
|
||||
and a test that parses source text normalizes line endings; and a test that
|
||||
expects no ComfyUI nearby works two folders inside its temp folder, because
|
||||
the output-folder fallback looks two levels up.
|
||||
|
||||
Every job in `ci.yml`, `nightly.yml`, `publish.yml` and `viewerjs-update.yml`
|
||||
(#662) has `timeout-minutes`.
|
||||
The rule is 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. The three run ids, their times and the resulting limit are written in a
|
||||
comment above `jobs:`, one line per job id
|
||||
(`python: 7m20s / 7m36s / 7m58s -> 15 min`). A job that has no three green runs
|
||||
yet has an `estimate <job id>: <why> -> N min` line instead; replace it with
|
||||
the measurement once three green runs exist. `tests/vendor/ci-workflow.test.mjs`
|
||||
recomputes every measured limit from its line and checks that each job has
|
||||
exactly one line and uses its limit (#493). The 3 minutes leave room for one
|
||||
watchdog firing, so the dump prints before GitHub cancels the job. A job that
|
||||
hits its limit, or a watchdog dump, is a failure like any other: read the dump,
|
||||
find the blocking call, fix it. Never raise a limit or rerun to get green; a
|
||||
limit changes only with new measurements written next to it.
|
||||
Every job in `test.yml`, `code-quality.yml`, `viewerjs-check.yml` and
|
||||
`portability.yml` has `timeout-minutes` (`tests/vendor/ci-workflow.test.mjs`
|
||||
checks it). The rule is ceil(1.5 x the slowest of three recent green runs on
|
||||
`main`) + 3 minutes, never under 5, timed as whole-job wall time; the three run
|
||||
ids, their times and the resulting limits are written in a comment above
|
||||
`jobs:`. For `portability.yml` the tooling test recomputes the limit from that
|
||||
comment (#493); its one matrix job takes the slowest Windows or macOS leg. The 3 minutes leave room for one watchdog firing, so
|
||||
the dump prints before GitHub cancels the job. A job that hits its limit, or a
|
||||
watchdog dump, is a failure like any other: read the dump, find the blocking
|
||||
call, fix it. Never raise a limit or rerun to get green; a limit changes only
|
||||
with new measurements written next to it.
|
||||
|
||||
Browser jobs (#425): GitHub keeps no log of a job killed at its limit and skips
|
||||
its upload steps, so the page test step in each browser job (`frontend coverage`
|
||||
in `ci.yml`, `page workflows` in `nightly.yml`) has its own `timeout-minutes`,
|
||||
2 below the job's. At the step limit
|
||||
its upload steps, so the test step in each browser job in `viewerjs-check.yml`
|
||||
has its own `timeout-minutes` (18, below the job's 20). At the step limit
|
||||
GitHub sends SIGTERM, which would end Playwright without any report; under `CI`
|
||||
`tools/vendor/running-tests-reporter.mjs` catches the first one, prints
|
||||
`Still running when the run ended (SIGTERM): N` and one line per unfinished
|
||||
@@ -332,9 +308,10 @@ runs the script, and that shell exits without passing it on. Delivery in CI,
|
||||
where the step runs through `docker exec`, is not yet observed; the next real
|
||||
step timeout will show it. That directory and the traces
|
||||
upload with `if: always()`; `npx playwright merge-reports` opens the blob.
|
||||
Each test keeps the 30 s default and there is no `globalTimeout`. One limit
|
||||
Each test keeps the 30 s default and there is no `globalTimeout`. Two limits
|
||||
of this: it assumes the npm cache hits (a cold cache adds up to 5 minutes to
|
||||
`npm ci`, and the job limit can then still win). Local runs keep the `list`
|
||||
`npm ci`, and the job limit can then still win), and coverage shard 1 (12m53s
|
||||
measured) is the tight one in its 18-minute step. Local runs keep the `list`
|
||||
reporter only; reproduce with `CI=1 timeout -s TERM 40 npm run --prefix
|
||||
tools/vendor test:workflows -- --project=firefox`.
|
||||
|
||||
@@ -343,17 +320,18 @@ tools/vendor test:workflows -- --project=firefox`.
|
||||
Follow the run for the commit you pushed, never an older one:
|
||||
|
||||
```sh
|
||||
gh run list --commit <pushed sha> --workflow ci.yml # the run id for that commit
|
||||
gh run list --commit <pushed sha> --workflow test.yml # the run id for that commit
|
||||
gh run watch <run id> --exit-status # returns when the run ends
|
||||
gh run view <run id> --json jobs # shows a job that already failed
|
||||
gh run view --job <job id> --log-failed # that job's failed log, at once
|
||||
```
|
||||
|
||||
Everything that can block the merge is in that one run (#666). Firefox, WebKit,
|
||||
touch, Python 3.13/3.14, Windows and real ComfyUI failures show up the next
|
||||
morning, as an open `nightly: <job> failing` issue and in
|
||||
`gh run list --workflow nightly.yml`; to see them before merging, run
|
||||
`gh workflow run nightly.yml --ref <branch>`.
|
||||
Python 3.13/3.14, real ComfyUI and Firefox/WebKit failures first show up in the
|
||||
merge queue, on the merge-group commit rather than the
|
||||
pushed one. Find that run with `gh run list --event merge_group --workflow test.yml`
|
||||
(or `viewerjs-check.yml`) and match its head branch
|
||||
(`gh-readonly-queue/main/pr-<N>-...`). Windows failures show up only
|
||||
after the merge, in `gh run list --workflow portability.yml`.
|
||||
|
||||
Start fixing as soon as a failed log shows the cause, but push the fix only after
|
||||
the run for that commit has finished: pull-request runs use `cancel-in-progress`,
|
||||
@@ -374,18 +352,12 @@ and the time left. The steps, in order:
|
||||
observer join get what is left, which can be 0 s. `stop()` joins watchdog's
|
||||
emitters without a limit, so it runs on a daemon thread and is waited for
|
||||
only until the deadline; a later stop waits for that same call (#561).
|
||||
3. `stop_review_worker` stops the Needs review worker (`pm-review-recorder`,
|
||||
5 s, #659): it drops the queued and deferred paths (their count is logged;
|
||||
the next scan covers them), refuses every later `queue_review_file` and
|
||||
joins the thread, which finishes at most the file in hand. It always runs,
|
||||
so an image in hand cannot start the worker afterwards; it is reported as
|
||||
part `review` only when the worker started.
|
||||
4. `close_auto_thumbnails(final=True)` stops the preview worker (30 s),
|
||||
3. `close_auto_thumbnails(final=True)` stops the preview worker (30 s),
|
||||
kills ffmpeg and shuts the interactive image pool down.
|
||||
5. `shutdown_job_pool` (`utils/parallel.py`) cancels the long-lived job pool's
|
||||
4. `shutdown_job_pool` (`utils/parallel.py`) cancels the long-lived job pool's
|
||||
queued items and joins its threads (5 s; part `workers`, only when a job
|
||||
used the pool, #523).
|
||||
6. `PromptTracker.shutdown` stops the prompt cleanup thread (2 s).
|
||||
5. `PromptTracker.shutdown` stops the prompt cleanup thread (2 s).
|
||||
|
||||
A failing step, or a second Ctrl+C, is logged with its traceback and does not
|
||||
skip the later steps. A clean run logs one INFO line to PromptManager's log:
|
||||
@@ -438,7 +410,6 @@ exit waits for the call in flight, as before. `tests/test_exit_cancel.py` runs a
|
||||
child process with three such calls running and requires its exit within 15 s.
|
||||
|
||||
Stop contract: `PromptTracker.shutdown(timeout)`,
|
||||
`ReviewRecordingMixin.stop_review_worker(timeout)` (final),
|
||||
`ImageGenerationHandler.shutdown(timeout)` (restartable),
|
||||
`ImageGenerationHandler.close(timeout)` (final: `schedule()` refuses and a
|
||||
sealed run's re-check is dropped) and `ImageMonitor.stop_monitoring(timeout)`
|
||||
@@ -451,8 +422,7 @@ Test rules:
|
||||
- Every test that constructs a real `PromptTracker`, `ImageGenerationHandler`
|
||||
or `ImageMonitor` ends with its final stop and an assertion
|
||||
(`tests/background_stops.py`: `close_handler`, `stop_monitor`,
|
||||
`stop_tracker`). `ReviewTestCase.tearDownAsync` asserts
|
||||
`stop_review_worker` before its capture store and folder go. The stop comes before the folder and databases are removed.
|
||||
`stop_tracker`). The stop comes before the folder and databases are removed.
|
||||
`tearDown` runs before `addCleanup` callbacks, so a class whose `tearDown`
|
||||
removes files stops the thread there.
|
||||
- A test waits for a state through an `Event` set by the code under test, or
|
||||
@@ -505,19 +475,6 @@ differ are files whose pixel data is undecodable or cut short: legacy found
|
||||
nothing, the walk keeps the text before the pixels. Animated PNGs still use
|
||||
`.text`.
|
||||
|
||||
WebP, AVIF and JPEG keep the same records in EXIF, not in text chunks.
|
||||
ComfyUI's `SaveAnimatedWEBP` writes `prompt:{json}` to EXIF tag 0x0110, then
|
||||
`workflow:{json}` and every other `extra_pnginfo` key to 0x010F and down; the
|
||||
AVIF writer uses that layout. `utils/exif_text.py` answers the `png_text` shape
|
||||
through Pillow's `getexif()`, and both metadata readers fall back to it when a
|
||||
file has no text chunks. Only a value shaped like a record counts (a key, a
|
||||
colon, then a JSON object, array or string), so camera EXIF stays out.
|
||||
`tests/test_exif_text.py` writes real still and animated WebP files, AVIF (where
|
||||
Pillow has it) and JPEG in that layout; `tests/test_metadata_extraction.py` and
|
||||
`tests/test_api_core.py` hold the two readers to it. No scan, monitor or
|
||||
gallery list collects `.avif` yet, so AVIF files are read correctly but never
|
||||
reach the readers; #652 tracks AVIF as a media type.
|
||||
|
||||
Image work runs on PromptManager's own threads (#523). glibc keeps each thread's
|
||||
malloc arena at its high-water mark, so image buffers spread over the default
|
||||
executor's threads stay resident. Interactive image work (view previews behind their
|
||||
@@ -537,20 +494,20 @@ trim; `tests/test_utils_parallel.py` the pool's reuse, resize, nesting and shutd
|
||||
`tools/perf/memory_drive.py` (manual, Linux, never in CI) measures RSS, heap, threads
|
||||
and arenas under the #523 load against the disposable browser test server.
|
||||
|
||||
The `perf budget` job in `.github/workflows/nightly.yml` is the reference
|
||||
The `perf budget` job in `.github/workflows/test.yml` is the reference
|
||||
measurement: `ubuntu-latest`, one Python, no coverage, only the wall-clock tests.
|
||||
It runs nightly and on `workflow_dispatch`, never on pull
|
||||
requests, because shared-runner timing must not block a merge. Dispatch
|
||||
`nightly.yml` on a branch to measure before merging.
|
||||
It runs on every push to `main` and on `workflow_dispatch`, never on pull
|
||||
requests, because shared-runner timing must not block a merge. Dispatch it on a
|
||||
branch to measure before merging.
|
||||
Shared Windows runners do not run them; the structural tests cover
|
||||
portability. Run it locally with
|
||||
`PROMPTMANAGER_PERF_BUDGET=1 python -m unittest tests.test_api_workspace_images.TestWorkspaceImages.test_filter_budget`
|
||||
and quote the printed p95 in the PR body.
|
||||
|
||||
A red `perf budget` run means the code got slower: fix the code (or
|
||||
A red `perf budget` run on `main` means the code got slower: fix the code (or
|
||||
change the budget in the spec with a reason) in a follow-up PR. Never rerun it to
|
||||
green. It is not a required check: only `gate` is
|
||||
(`.github/branch-protection.json`).
|
||||
green. It is not a required check, and it cannot be one while it skips pull
|
||||
requests (`.github/branch-protection.json`).
|
||||
|
||||
## Images listing cache (#348)
|
||||
|
||||
@@ -711,10 +668,6 @@ Browser tests: `workspace-stale-source.spec.mjs` (`/__test__/sources/reverse` an
|
||||
`/__test__/scope-key/rotate`, both undone by every reset); the manual-Refresh
|
||||
recovery specs in `workspace-images.spec.mjs` answer every rescope 409.
|
||||
|
||||
## Registry package
|
||||
|
||||
`comfy node publish` zips the tracked files minus `.comfyignore`, so a new development file or folder at the root ships until it is listed there. `tests/test_package_contents.py` keeps each rule anchored to the root, checks that development paths are left out and that nothing ComfyUI needs at run time is. Git clones are unaffected.
|
||||
|
||||
## Windows portability preflight
|
||||
|
||||
Before changing paths, SQLite, streams, restore or cleanup:
|
||||
@@ -741,163 +694,87 @@ Before changing paths, SQLite, streams, restore or cleanup:
|
||||
open with `FirstWriterHold`) and give peers that must all succeed the
|
||||
ordinary busy timeout; cross-thread handoffs wait on events with generous
|
||||
ceilings, never a short wall clock (#242).
|
||||
- Run native Windows CI early for these changes. Pull requests run only Linux,
|
||||
so start Windows on the branch with
|
||||
`gh workflow run nightly.yml --ref <branch>` (a branch run files no issues).
|
||||
- Run native Windows CI early for these changes. Pull requests and the merge
|
||||
queue run only Linux, so start Windows on the branch with
|
||||
`gh workflow run portability.yml --ref <branch>`.
|
||||
Include a Windows impact and evidence note in the PR. All three Windows
|
||||
legs in that run, every Linux leg and every applicable
|
||||
exact-head check must pass before merge. Portable `ntpath`/`PureWindowsPath`
|
||||
controls do not establish native filesystem, locking or cleanup success.
|
||||
|
||||
## The gate and the nightly run
|
||||
## Pull requests and the merge queue
|
||||
|
||||
A change is tested once, on its pull request (#666). There is no merge queue
|
||||
and a push to `main` runs no test. Three workflows:
|
||||
Each PR runs the full matrix once, in the merge queue (#420). The event decides
|
||||
what runs:
|
||||
|
||||
| Workflow | Runs on | Jobs |
|
||||
| Job | `pull_request` | `merge_group`, push to `main`, `workflow_dispatch` |
|
||||
| --- | --- | --- |
|
||||
| `ci.yml` (the gate) | `pull_request`, `workflow_dispatch` | `change class`; `python 3.12 with coverage (85%)` (the suite, once, under coverage); `black and flake8`; `bandit (high severity)`; `frontend modules` (`tests/js`); `tooling tests and pins` (`tests/vendor`, vendor pins); `frontend coverage (shard N/4)` and `frontend coverage (merge)` (desktop Chromium page workflows with the per-file floors); `package contents` (a release only); `gate` |
|
||||
| `nightly.yml` | 03:17 UTC, `workflow_dispatch` | `page workflows (firefox\|webkit\|touch, shard N/3)`; `py3.13`/`py3.14 on ubuntu-latest`; `py3.12`-`3.14 on windows-latest`; `native trash on a real mount`; `real ComfyUI compatibility`; `perf budget`; `report by issue` |
|
||||
| `publish.yml` | push to `main` that changes `pyproject.toml`, `workflow_dispatch` | publishes to the Registry when the version is new |
|
||||
| `py3.12 on ubuntu-latest` | runs | runs |
|
||||
| `py3.13 on ubuntu-latest`, `py3.14 on ubuntu-latest` | not created | run |
|
||||
| `real ComfyUI compatibility` | skipped | runs |
|
||||
| `coverage gate (85%)`, `black and flake8`, `frontend modules`, `bandit (high severity)` | run | run |
|
||||
| `frontend coverage (shard N/4)`, `frontend coverage (merge)` (vendor pins and tooling tests on shard 4) | run | run |
|
||||
| `page workflows (firefox\|webkit, shard N/2)` | skipped | run |
|
||||
| `all tests`, `viewerjs` (gates) | run | run |
|
||||
| `perf budget` | skipped | push and dispatch only (not in the queue) |
|
||||
| `py3.12-3.14 on windows-latest` (`portability.yml`) | not run | push to `main`, nightly, `workflow_dispatch` only; never required |
|
||||
|
||||
`gate` is the only required check. It needs every other job of `ci.yml` and
|
||||
passes only when the classifier succeeded and each job did what the change
|
||||
class asks (below): the class's jobs succeeded and every other job was
|
||||
skipped. A failed, cancelled or wrongly skipped job fails it, and so does a
|
||||
class the classifier does not print. Because branch protection names only
|
||||
`gate`, adding or renaming a job never strands a pull request. Protection is
|
||||
strict: the branch must be up to date with `main`, so the commit the gate
|
||||
tested is the commit that merges. When `main` moved, press "Update branch" and
|
||||
the gate runs once more.
|
||||
GitHub has one required set for pull requests and the queue. A job skipped by
|
||||
its `if:` reports Success. A dropped matrix leg never reports, so it would stay
|
||||
pending. That is why `all tests` (in `test.yml`) and `viewerjs` carry the
|
||||
guarantee:
|
||||
- On a pull request they require the subset to succeed and the queue-only jobs
|
||||
to be skipped.
|
||||
- On every other event they require every job to succeed.
|
||||
|
||||
Only desktop Chromium blocks a merge (maintainer, 2026-11-21). Firefox, WebKit
|
||||
and the phone-size `touch` project are not first-class; with Python 3.13/3.14,
|
||||
Windows, the real mount, real ComfyUI and the wall-clock budget they run
|
||||
nightly on `main`. macOS is not tested in CI (maintainer, 2026-10-31, #571);
|
||||
its code stays and support is best-effort. The cost: a break only those can
|
||||
see is found the next morning, not before the merge. To see it before merging
|
||||
a risky change, run `gh workflow run nightly.yml --ref <branch>`.
|
||||
So a merge group cannot turn green unless all three Linux Python legs, real
|
||||
ComfyUI and the four browser shards passed.
|
||||
|
||||
### Nightly reports by issue
|
||||
|
||||
Nothing waits for the nightly run, so it reports by issue
|
||||
(`tools/ci/nightly_report.py`, the `report by issue` job, the only job in CI
|
||||
with a write permission: `issues: write`). For each job of the run:
|
||||
|
||||
- a failed or timed-out leg opens `nightly: <job> failing`, or comments on the
|
||||
open issue with that exact title, naming the run, the commit and the failed
|
||||
legs;
|
||||
- every leg green closes that issue with a comment naming the run;
|
||||
- a cancelled or skipped job changes nothing.
|
||||
|
||||
Shards of one browser are one job (`nightly: page workflows (webkit) failing`).
|
||||
Only a run of `main` reports; a manual run of a branch files nothing. A red
|
||||
nightly job is a failure like any other: read the log, fix the cause. It blocks
|
||||
no merge, and it is never rerun to green.
|
||||
|
||||
### Flaky tests and quarantine
|
||||
|
||||
- **No retries in the gate.** A retry hides a race. A gate test passes or fails
|
||||
on its one attempt (`retries: 0` in both Playwright configs).
|
||||
- **No rerun-to-green.** A red job is read and fixed at its cause. The one
|
||||
exception is unchanged: a pure timeout with every test passing may be rerun.
|
||||
- **A gate test that fails without a code cause is fixed or quarantined the
|
||||
same day.** Open an issue, then tag the test with that issue, in exactly this
|
||||
spelling (`tests/vendor/flake-policy.test.mjs` checks it):
|
||||
|
||||
```js
|
||||
test('closing the viewer never blocks the page', { tag: '@quarantine', annotation: { type: 'issue', description: '#613' } }, async ({ page }) => {
|
||||
```
|
||||
|
||||
The gate's page run passes `--grep-invert @quarantine`
|
||||
(`tools/vendor/frontend-coverage.mjs`), so the test no longer blocks a merge;
|
||||
the nightly run still runs it in Firefox, WebKit and touch. To run it in
|
||||
Chromium while fixing it: `npm run --prefix tools/vendor test:workflows --
|
||||
--project chromium --grep @quarantine`. Remove the tag in the PR that fixes
|
||||
the test and closes the issue. A quarantined test adds no coverage, so a
|
||||
floor that depended on it fails the merge job: that is the signal to fix
|
||||
the test rather than leave it.
|
||||
- **Nightly retries once** (`--retries 1`). A test that fails and then passes
|
||||
does not turn its job red; `tools/vendor/flaky-tests-reporter.mjs` lists it
|
||||
in the job summary under "Flaky tests". Treat a test listed there twice as a
|
||||
bug to fix.
|
||||
|
||||
Nothing is quarantined today. Measured at the switch (the last 100
|
||||
pull-request runs of the frontend workflow, 2026-10-31 to 2026-11-21): 9
|
||||
failed. Six were caused by the pull request's own change (three coverage
|
||||
floors, a tooling test, a new test that failed in touch, a Playwright bump),
|
||||
one by a re-pushed image tag (fixed by the digest pin, #609), and two by
|
||||
Chromium tests that failed without a cause in the pull request; both were
|
||||
fixed at their cause (a production race, #611, and a spec that read a status
|
||||
before its save answered, #631).
|
||||
|
||||
### Only changes that can affect code are tested (#639)
|
||||
|
||||
The table above is for a code change. `ci.yml` starts with a `change class` job
|
||||
that runs `tools/ci/change_class.py` over the files the pull request touches,
|
||||
and every other job runs for one class only:
|
||||
|
||||
| Class | Files | What runs |
|
||||
| --- | --- | --- |
|
||||
| `inert` | Only `.github/FUNDING.yml`, `SECURITY.md`, `images/`, `.github/ISSUE_TEMPLATE/` | `change class` and `gate`: green in seconds. |
|
||||
| `docs` | Only `README.md`, `README-legacy.md`, `assets/readme/`, `assets/brand/` (may include inert files) | `change class` and `gate`: green in seconds. |
|
||||
| `release` | `pyproject.toml` alone, and in it only the `version = "..."` line rewritten | The above and `package contents` (`tests/test_package_contents.py`). |
|
||||
| `code` | Anything else | The whole gate. |
|
||||
|
||||
A file on no list is code, and so is every case of doubt: no changed files, a
|
||||
manual run, a range git cannot read, a `pyproject.toml` change that is more
|
||||
than the version line. `docs/` is code, because the browser suite compares
|
||||
production against `docs/concepts/workspace/`; `TESTING.md` is code, because
|
||||
the tooling tests read its tables; a test-only change is code. Before adding a
|
||||
file to a list, check that no shipped code opens it.
|
||||
|
||||
Two Python tests read the `docs` files (`tests/test_brand_assets.py`,
|
||||
`tests/test_package_contents.py`). CI no longer runs them for a `docs` change
|
||||
(maintainer, 2026-11-21: documentation and image changes run no tests), so a
|
||||
README or brand-asset edit that breaks one is caught by the pre-push hook, or
|
||||
else by the next code change's gate. Run
|
||||
`python -m unittest tests.test_brand_assets tests.test_package_contents` after
|
||||
editing those files.
|
||||
|
||||
The pre-push hook uses the same script: it skips the Python suite when the
|
||||
pushed commits are `inert` and runs it otherwise.
|
||||
Windows (Python 3.12-3.14) is out of the blocking path for now
|
||||
(maintainer, 2026-10-28). macOS is not tested in CI (maintainer, 2026-10-31, #571);
|
||||
its code stays and support is best-effort. They run in `portability.yml` on every push to `main`,
|
||||
nightly and on demand, and no context there is required. A red portability run
|
||||
is still a failure: fix it at its cause, not by rerunning, and have every one
|
||||
green before the workspace cutover (#334). `tests/vendor/ci-workflow.test.mjs` pins the
|
||||
event split and runs both gate scripts for each event.
|
||||
|
||||
## Required merge checks
|
||||
|
||||
`.github/branch-protection.json` records the required checks: the one context
|
||||
`gate`, with `strict` (the branch must be up to date with `main`). It reports
|
||||
on every pull request, whatever the change class.
|
||||
`.github/branch-protection.json` records the required checks:
|
||||
`py3.12 on ubuntu-latest`, `coverage gate (85%)`, `black and flake8`,
|
||||
`frontend modules`, `all tests`, `viewerjs`, `real ComfyUI compatibility` and
|
||||
`bandit (high severity)`. Each one reports on a pull request.
|
||||
The same set lives in two places, and both must change together: the `main`
|
||||
ruleset (25960526) and the classic branch protection on `main`, which the
|
||||
manifest mirrors. GitHub requires the union of the two, so a context left in
|
||||
either one blocks every PR that does not report it. The ruleset has no
|
||||
`merge_queue` rule (#666). Merging is the squash button. It does not require an
|
||||
additional human approval.
|
||||
ruleset (25960526, which also holds the merge queue) and the classic branch
|
||||
protection on `main`, which the manifest mirrors. GitHub requires the union of
|
||||
the two, so a context left in either one blocks every PR that does not report it.
|
||||
It does not require an additional human approval.
|
||||
|
||||
A repository administrator applies the configuration, then verifies it:
|
||||
A repository administrator applies the configuration after the new workflow is
|
||||
passing, then verifies it:
|
||||
|
||||
```sh
|
||||
gh api repos/ComfyAssets/ComfyUI_PromptManager/rulesets/25960526 \
|
||||
| jq '.rules[] | select(.type == "required_status_checks") | .parameters'
|
||||
| jq '.rules[] | select(.type == "required_status_checks") | [.parameters.required_status_checks[].context]'
|
||||
```
|
||||
|
||||
A PUT replaces the whole `rules` array, so edit the current ruleset in place.
|
||||
Keep the `deletion` and `non_fast_forward` rules, and give the context
|
||||
`integration_id` 15368 (GitHub Actions), so no other integration can
|
||||
post the required check. Save the current ruleset first; it is the rollback:
|
||||
Keep the `deletion`, `non_fast_forward` and `merge_queue` rules, and give every
|
||||
context `integration_id` 15368 (GitHub Actions), so no other integration can
|
||||
post a required check. Save the current ruleset first; it is the rollback:
|
||||
|
||||
```sh
|
||||
gh api repos/ComfyAssets/ComfyUI_PromptManager/rulesets/25960526 > ruleset-before.json
|
||||
jq '{name, target, enforcement, conditions, bypass_actors, rules: [.rules[]
|
||||
| select(.type != "merge_queue")
|
||||
| if .type == "required_status_checks"
|
||||
then .parameters.required_status_checks = [{context: "gate", integration_id: 15368}]
|
||||
| .parameters.strict_required_status_checks_policy = true
|
||||
else . end]}' ruleset-before.json > ruleset-new.json
|
||||
then .parameters.required_status_checks = [$ARGS.positional[] | {context: ., integration_id: 15368}]
|
||||
else . end]}' ruleset-before.json --args "py3.12 on ubuntu-latest" "..." > ruleset-new.json
|
||||
gh api --method PUT repos/ComfyAssets/ComfyUI_PromptManager/rulesets/25960526 --input ruleset-new.json
|
||||
```
|
||||
|
||||
Then apply the manifest to the classic protection and read both back:
|
||||
Afterwards, read it back. Check that the `merge_queue` rule is still there and
|
||||
that every context keeps its `integration_id`. Then apply the manifest to the
|
||||
classic protection and read both back:
|
||||
|
||||
```sh
|
||||
gh api --method PUT repos/ComfyAssets/ComfyUI_PromptManager/branches/main/protection \
|
||||
@@ -905,9 +782,9 @@ gh api --method PUT repos/ComfyAssets/ComfyUI_PromptManager/branches/main/protec
|
||||
gh api repos/ComfyAssets/ComfyUI_PromptManager/branches/main/protection/required_status_checks
|
||||
gh api repos/ComfyAssets/ComfyUI_PromptManager/rules/branches/main
|
||||
```
|
||||
|
||||
Update the manifest whenever the required context changes. Keep `ci.yml`
|
||||
free of path filters so the required check is never silently skipped.
|
||||
Update the manifest whenever
|
||||
required job names change. Keep the frontend check
|
||||
free of path filters so a required check is never silently skipped.
|
||||
|
||||
## Unified workspace
|
||||
|
||||
@@ -1015,15 +892,7 @@ WanImageToVideo by output slot). `ConditioningZeroOut` is an explicit empty text
|
||||
with source `zeroed-conditioning`. `easy ifElse` with a literal boolean follows that
|
||||
branch only; with a linked boolean both branches are traced, equal texts resolve and
|
||||
different texts make the sampler `ambiguous` with one candidate per choice (at most
|
||||
32, else `work-limit`). A value is *proven* (#657, rgthree's `Any Switch (rgthree)`,
|
||||
strategy `first-present`, which outputs its first input that is not `None`) only by
|
||||
a literal or a traced path whose every node is a PromptManager node, a class the
|
||||
resolver handles in code (`Reroute`, `StringConcatenate`, `Text Concatenate`, the
|
||||
default string adapters) or an entry of the table's `encoders`, `strings`,
|
||||
`conditioning` or `composites` (`PROVEN_VALUE_CATEGORIES`). That allowlist is a rule
|
||||
for every future table entry: a class that can return `None` (a selector, an
|
||||
unknown node, a `runtime`, `facts` or `lineage` class) never goes into those four
|
||||
categories, and a test pins them. Both resolvers read the constant (`Semantics.proves_value`; the browser's copy in `local-resolver-support.mjs`), and `tests/test_proven_value_parity.py` fails when the browser copy drifts from it (#662). Otherwise the switch offers one candidate per distinct outcome of its inputs, and no PromptManager path is preferred. When a sampler is `ambiguous`, Inspect still shows a role every candidate resolves alike (same text, recipe and left-out parts) as resolved (#658); `resolution.state` stays `ambiguous`, so pair actions and ingestion are unchanged. ConditioningCombine/Concat/Average resolve only when every
|
||||
32, else `work-limit`). ConditioningCombine/Concat/Average resolve only when every
|
||||
part has the same text, otherwise `unresolved` with `composite` naming the node
|
||||
(but see the added-conditioning floor below for a later stage).
|
||||
Results that depend on a forced choice are never memoized. A `FaceDetailer`
|
||||
@@ -2627,10 +2496,7 @@ npm run --prefix tools/vendor test:workflows -- workspace-collections.spec.mjs c
|
||||
|
||||
Images › Delete… removes the checked images (or "Select all N matching", at most 500, or
|
||||
the one file of the side panel or the viewer) from the library, and on request moves the
|
||||
files to the system trash or (Linux/BSD servers only) deletes them permanently. **The only
|
||||
code path that unlinks or overwrites a media file is the permanent-delete apply job.** Library
|
||||
and trash modes never unlink media files; permanent-delete unlinks files only via the apply
|
||||
job after `file_check` confirms containment and non-symlink, and the review step never unlinks.
|
||||
files to the system trash. **No code path unlinks or overwrites a media file.**
|
||||
|
||||
- **D159** (#480, maintainer request): the concept's "Remove links…" (`danger`, app.js
|
||||
432) returns as **Delete…** in the same place (after Export metadata, before Clear), and
|
||||
@@ -2708,7 +2574,7 @@ job after `file_check` confirms containment and non-symlink, and the review step
|
||||
checks intact. A root above the mount, a mount nested under the root, a source that is or
|
||||
sits in the trash folder, and a link in place of the trash folder stay refused. Tests:
|
||||
`tests/test_trash_mount_root.py`, on a fake mount table in the suite and, with
|
||||
`PM_TRASH_MOUNT=<real mount>`, in nightly.yml's `native-trash-linux` job (loop-mounted
|
||||
`PM_TRASH_MOUNT=<real mount>`, in portability.yml's `native-trash-linux` job (loop-mounted
|
||||
ext4). Locally, without root: `unshare -Urm` over a tmpfs.
|
||||
- **D190** (#543, beyond the concept): a trash review where nothing can move shows a primary
|
||||
that clearly cannot act: `aria-disabled`, no danger colors (also on hover), and a press does
|
||||
@@ -2845,7 +2711,7 @@ Recorded deviations on this page:
|
||||
drive, UNC, non-ASCII, symlinked root, the any-tag union), `test_api_library.py`,
|
||||
`test_saved_views.py`, the library-state and saved-views JS units, and
|
||||
`tests/browser/workspace-library-filters.spec.mjs` (behavior, the Refine dialog against
|
||||
the concept Filters dialog, artifact captures). Windows: run `nightly.yml` on the PR's branch.
|
||||
the concept Filters dialog, artifact captures). Windows: run `portability.yml` on the PR.
|
||||
|
||||
`tests/browser/library-concept.spec.mjs` compares the shelf (#249 E3) on the
|
||||
concept-shaped fixture, which creates the concept's prompts last to first so Recently
|
||||
@@ -2865,7 +2731,7 @@ the grid) and D43 (sorted chips, checked against the concept with its chips sort
|
||||
D44 needs no mapping: the comparison runs with no Refine filter active, so the button
|
||||
reads "Filters" as the concept's does. Nothing else follows the grid: the legacy
|
||||
"Current prompt library" link is removed from the shelf; the legacy Library stays at
|
||||
`/prompt_manager/admin` by direct URL (#525, #620)
|
||||
`/prompt_manager/admin` by direct URL, linked only from System (#525, D165)
|
||||
(`tests/browser/workspace.spec.mjs`). `library comparison detects
|
||||
mutations` injects `.card-footer { padding: 2px }` and removes `.card-meta .chip.red`.
|
||||
|
||||
@@ -3373,7 +3239,7 @@ npm run --prefix tools/vendor test:workflows -- history-concept.spec.mjs \
|
||||
|
||||
`#/inspect` ("Inspect a file") is a native workspace route; it no longer hands off to
|
||||
the legacy metadata page, which stays at its URL
|
||||
(`/prompt_manager/gallery.html`) at its URL only (#525, #620). The page is the concept's `#metadata`
|
||||
(`/prompt_manager/gallery.html`) linked only from System (#525, D165). The page is the concept's `#metadata`
|
||||
(app.js `renderMetadata` a740–748, selection a1715–1729; style.css 709–722, 1180–1194,
|
||||
1543–1545, 1559–1564) in the concept's own classes (`.surface`, `.file-drop`,
|
||||
`.spaced-20`, `.local-file-preview`, all from the synced `concept.css`), with no
|
||||
@@ -4795,9 +4661,6 @@ the per-section hand-off panel, was retired by S12 (#329): every section is nati
|
||||
concept row's), `skipped tags add, preview, remove, save and reload (D202)`, `skipped
|
||||
tags preview checks library tags only …` (workspace-system-tagging.spec) and
|
||||
`suggestions omit skipped tags and say how many were hidden` (workspace-tagging.spec).
|
||||
- **D206** (Prompt library, #620, beyond the concept; numbered D205 until #662 found the id taken by #431): the sort menu appends Recently used, Most used and Name Z–A
|
||||
after Oldest first. These are the old Dashboard's sorts, kept before its removal because the community asked for
|
||||
them. A prompt never run sorts last in both use orders.
|
||||
- **D203** (Auto-tagging, #431, beyond the concept): "Saved instructions" replaces the
|
||||
concept's "LLM tag template" field (the mock's state 2): a `.setting-block`
|
||||
(`data-setting="tag-instructions"`, `data-key="autotag_instructions"`) with the label,
|
||||
@@ -6515,59 +6378,39 @@ never the metadata row.
|
||||
|
||||
Needs review items (#249, `utils/review_capture.py`, `database/review.py`,
|
||||
`tests/test_review.py`, `tests/test_review_outcome.py`,
|
||||
`tests/test_review_choosable.py`, `tests/test_review_collapsed.py`): a file is queued only when its final outcome
|
||||
is ambiguous and unlinked and there is something to choose. The scan and the
|
||||
live monitor queue the same files (maintainer decision 2026-11-19, #659; it
|
||||
replaces the 2026-10-23 ruling that only scans add items, made when the
|
||||
monitor's pass queued files the scan's fallback went on to link): one per-file
|
||||
decision, `review_dispatch` (`py/api/review_recording.py`), serves both. The
|
||||
output scan (Activity's
|
||||
`tests/test_review_choosable.py`): a file is queued only when its final outcome
|
||||
is ambiguous and unlinked and there is something to choose. Only scans produce
|
||||
items; the monitor links new outputs and clears pending items it resolves
|
||||
(maintainer rulings, 2026-10-23). The output scan (Activity's
|
||||
Scan for metadata and the legacy `/scan`) hands `record_ambiguous_file` a file
|
||||
the ingestion resolver finds `ambiguous` only when the browser-parser fallback
|
||||
then links nothing (status `ambiguous`) and no saved row links the file
|
||||
already; an ambiguous file a saved row links is reported `unchanged` ("Already
|
||||
linked to its prompt"), not Needs review. A file the fallback links, an exact
|
||||
pair the ingester stores, and `conflict` and `unresolved` files are not
|
||||
queued. Neither is an ambiguous file with nothing to choose: none of its
|
||||
candidates is `resolved` with non-blank positive text (`reviewable`,
|
||||
`MIN_CHOOSABLE` = 1). Such a file could not be traced: it reports `unresolved`
|
||||
("could not be traced"), is never linked, and its pending, undecided items
|
||||
whose own evidence offers no choice (a limited item counts as a choice when it
|
||||
holds at least one candidate) leave the queue on the next scan
|
||||
(`settle_untraced_review_items`). The maintainer's second live check found 39
|
||||
items whose 11 candidates were all "unresolved". One readable candidate is
|
||||
enough (#657 addendum D1, maintainer 2026-11-20: "fine that we cannot tell,
|
||||
not fine to show nothing"): the untraced branches may still have made the
|
||||
file, so it is never linked from that text, but it is queued with the other
|
||||
branches listed (disabled, e.g. "Text is decided at run time") and the user
|
||||
may confirm it or leave it unresolved. The live case is the sweep with an LLM
|
||||
enhancer on rgthree Any Switch `any_01` (`tests/sweep_graphs.py`
|
||||
`enhanced_sweep_graph`, `TestOneReadableChoiceIsQueued`, scan and monitor).
|
||||
A default choice that is partial (a branch beside it has no prompt to choose,
|
||||
or it offers fewer than two: `partial_choice`) still asks the inspection
|
||||
profile, and the item is recorded from that profile when it offers more
|
||||
choosable candidates (`offers_more`; #657 review, `mixed_edit_graph`:
|
||||
a Qwen image-edit sampler only the inspection profile reads beside a
|
||||
CLIPTextEncode one, `TestPartialDefaultAsksInspection`, scan, monitor and a
|
||||
rescan that keeps the item an inspection item).
|
||||
queued. Neither is an ambiguous file with nothing to choose: fewer than two of
|
||||
its candidates are `resolved` with non-blank positive text (`reviewable`). With
|
||||
none the file could not be traced; with exactly one, the untraced branches may
|
||||
still have made the file, so that text is not certain either. Both report
|
||||
`unresolved` ("could not be traced"), are never linked, and their pending,
|
||||
undecided items whose own evidence offers no choice (a limited item counts as
|
||||
a choice when it holds at least two candidates) leave the queue on the next
|
||||
scan (`settle_untraced_review_items`). The maintainer's
|
||||
second live check found 39 items whose 11 candidates were all "unresolved".
|
||||
Inspection-profile choices (`tests/test_review_inspection.py`, ruling a): when
|
||||
the default profile is ambiguous without a choice, or calls a file with a prompt
|
||||
graph `unresolved` (#659 C1/C2: `Decision.default_unresolved`, set before the
|
||||
blank-positive rewrite, so a blank positive does not count; "Unsupported latent
|
||||
ancestry" on the maintainer's model-compare sweep is the example), and nothing
|
||||
links the file, the scan and the monitor's review worker resolve it again with
|
||||
`INSPECTION_PROFILE`, which
|
||||
the default profile is ambiguous without a choice and nothing links the file,
|
||||
the scan (never the monitor) resolves it again with `INSPECTION_PROFILE`, which
|
||||
knows `TextEncodeQwenImageEdit`, `StringConstantMultiline`, `JoinStringMulti`
|
||||
and the rest of `web/js/inspection-semantics.json`. With a choosable
|
||||
candidate there, the file is `ambiguous` and is queued from that profile's
|
||||
and the rest of `web/js/inspection-semantics.json`. With at least two choosable
|
||||
candidates there, the file is `ambiguous` and is queued from that profile's
|
||||
evidence, which adds `profile: "inspection"` and `semantics`: the SHA-256 of
|
||||
`class_projection`, the table restricted to the graph's node classes plus its
|
||||
class-independent `schema` and `stage_inputs` (the resolver looks the table up
|
||||
only by a graph node's class). The item's `resolver_version` is
|
||||
`inspection_review_version(metadata)`, 2^40 plus 40 bits of SHA-256 over the
|
||||
profile with its budgets, `RESOLVER_VERSION`, `INSPECTION_RESOLVER_VERSION`
|
||||
(bump it when the inspection profile would resolve the same metadata otherwise),
|
||||
`REVIEW_RULE_VERSION`, `REVIEW_EVIDENCE_VERSION` and that fingerprint. A table edit about the
|
||||
(bump it when the inspection profile would resolve the same metadata otherwise)
|
||||
and that fingerprint. A table edit about the
|
||||
graph's classes behaves like a resolver change (I2); an edit about other
|
||||
classes changes nothing. One file never holds two pending items for the same
|
||||
bytes: a new version's item supersedes the byte record's other items when all
|
||||
@@ -6576,9 +6419,7 @@ delete); beside a decided or advanced item nothing new is stored, and the
|
||||
rescan's stat shortcut then skips those bytes under any version. A pending item
|
||||
stays applicable while the bytes still offer its chosen candidate.
|
||||
Apply re-resolves the capture with the profile the item recorded and re-checks
|
||||
the chosen hash against every projected, de-duplicated candidate hash of the
|
||||
bytes (`candidate_hashes`, before any bound or collapse, so a reorder that
|
||||
changes the collapsed representatives still applies); the link goes through the same compatible-only ingestion. The
|
||||
the chosen hash; the link goes through the same compatible-only ingestion. The
|
||||
inspection profile never links on its own, and ingestion keeps the default
|
||||
profile (D1). The heavier profile runs only for files already ambiguous without
|
||||
a choice, and once per file state: the capture reuses the scan's result when
|
||||
@@ -6605,59 +6446,19 @@ item versions, so older inspection items are recorded again once. Apply accepts
|
||||
the anchored pair and refuses a choice the anchor contradicts. Measured on the
|
||||
maintainer's 40,890 outputs: the queue is unchanged (249 files); the 242
|
||||
`gpu_unlock_bench` files the inspector resolves are linked by the parser
|
||||
floor. The 16-candidate collapse and the 8 MiB bound apply unchanged. The queue heals itself: after each batch, the scan removes the pending
|
||||
floor. The 16-candidate limited
|
||||
rule and the 8 MiB bound apply unchanged. The queue heals itself: after each batch, the scan removes the pending
|
||||
items of every listed file (read or skipped as known) that a saved row now
|
||||
links, and the monitor does the same for each ambiguous output it links
|
||||
(`settle_linked_review_items`; the review index revision moves). Only an
|
||||
undecided item goes (`pending`, revision 0, no decision row): a decision is
|
||||
never deleted or changed, so no schema state was added. The monitor queues a
|
||||
file only at its final unlinked outcome, after run history had its say
|
||||
(`tests/test_foreign_save_to_library.py` `TestFinalUnlinkedOutcomesQueueForReview`):
|
||||
the ladder wait's sealed re-check left it unlinked, the settle lookup found the
|
||||
run's record and no certain prompt, the file is outside ComfyUI's output folder
|
||||
(it is never sealed) at the PromptManager or foreign exit, or the keyless
|
||||
history re-check found no prompt. A wait that expires or an entry dropped at the
|
||||
wait's cap is only logged and left to the next scan. At that point the handler's
|
||||
recorder, `queue_review_file`, puts the path on the review worker's queue and
|
||||
returns at once; linked ambiguous outputs go the same way, so their pending items
|
||||
leave the queue. The worker (thread `pm-review-recorder`, a daemon, started on the
|
||||
first queued path) runs `record_review_file`: the job blocker, root and linked
|
||||
checks, then the scan's own per-file steps for that one file, read only: the
|
||||
scan's metadata read, the ladder under `Policy.SCAN` with the file's recorded
|
||||
history (`_BatchHistory`) and the recorded-run check. A file any step would link,
|
||||
or whose prompt does not save, is `skipped` (the next scan links it; the worker
|
||||
links nothing); otherwise the answer is `review_dispatch`'s record outcome
|
||||
(`recorded`, `duplicate`, `decided`, `untraced`, `limited`), so the next scan
|
||||
finds the item a `duplicate` (`test_monitor_pass_queues_and_the_next_scan_reports_a_duplicate`).
|
||||
An untraced file also loses its pending items without a choice, as in the scan.
|
||||
A file without a prompt graph is never captured. Inspect records too (#657
|
||||
addendum D2, `tests/test_inspection_review.py`): its `review` field (`{"state":
|
||||
"pending", "item_id"}`, `{"state": "decided"}` or null, asked only for an
|
||||
ambiguous role of an unlinked file under an output root) runs
|
||||
`record_review_file`, the worker's own path, in the executor when no item
|
||||
exists at the inspected stat, then reads the item again; Images and History's
|
||||
current-file inspection share the reader (`review_reader(..., record=)`). A
|
||||
file the scan would link, an untraced one or a deferred pass records nothing;
|
||||
a failure is logged and the field stays null, never failing the response.
|
||||
Inspect calls `inspect_review_file` (`py/api/review_recording.py`): a pending
|
||||
item of a current item version needs nothing; one of an older version (e.g. a
|
||||
choiceless limited item from before D3) is recorded again, so the new item
|
||||
supersedes it. A busy capture store (`CaptureCapacity`, the worker copying a
|
||||
fresh output) is expected and logged at debug level, and the item is read
|
||||
once more after any failed recording. A state Inspect found unrecordable
|
||||
(`skipped`, `untraced`) is remembered per process by a 16-byte digest of its
|
||||
locator, size, `mtime_ns`, default item version and semantics table version
|
||||
(at most `MAX_INSPECT_MEMORY` = 4,096, oldest forgotten first), so a repeated
|
||||
Inspect does not copy it again.
|
||||
The queue coalesces by path (a
|
||||
path queued while it runs runs once more afterwards; one thread, so two
|
||||
recordings of one path never overlap) and holds at most `REVIEW_QUEUE_LIMIT` =
|
||||
4,096 paths, dropping the oldest with a log line, so the image worker never
|
||||
waits for it. A recorder failure is logged by the worker and undoes no link.
|
||||
`tests/test_review.py` `TestReviewWorker` covers the queue. The
|
||||
never deleted or changed, so no schema state was added. The monitor never
|
||||
records an item (only scans add items, maintainer ruling 2026-10-23): an
|
||||
unlinked file passed to `record_review_file` is `skipped` with no capture,
|
||||
and only a linked one's pending items are settled
|
||||
(`test_monitor_never_records_an_unlinked_ambiguous_output`). The
|
||||
maintainer's live check of #284/#288 found the queue at 10,232 against a review
|
||||
group of 4,677: every fallback-linked ambiguous file had been queued; the
|
||||
worker's ladder pass is what keeps those files out now. It captures
|
||||
group of 4,677: every fallback-linked ambiguous file had been queued. It captures
|
||||
the file (scope `needs-review`), reads its metadata again from the capture,
|
||||
resolves it with the default profile and stores only an ambiguous result,
|
||||
bound to the capture's byte record (created or refreshed like an observe) and
|
||||
@@ -6665,26 +6466,8 @@ fenced by the capture's storage epoch. Evidence is the resolver reason plus one
|
||||
`{sampler_id, state, reason, positive, negative, hash}` per selectable
|
||||
candidate (nested ambiguous stages flattened, duplicates dropped; each side
|
||||
`{text, storage_text, provenance}`; `hash` = SHA-256 of the canonical candidate
|
||||
without it). More than 16 candidates are collapsed, not dropped (#657 addendum
|
||||
D3, the maintainer's ConsistentFace batch: 83 samplers, 81 prompts): the
|
||||
choosable ones are grouped by their (positive, negative) texts. With at most
|
||||
16 texts the item stays ordinary: one candidate per text, its first
|
||||
occurrence, and the branches without a prompt fill the remaining places in
|
||||
their order (20 samplers sharing three texts keep their run-time branches).
|
||||
With more than 16 texts the groups are ordered by size, largest first, then
|
||||
by first appearance, and the first 16 are kept, each by its first occurrence (its real sampler and hash, so Apply finds
|
||||
it again). The evidence is ordinary (not limited) and adds `collapsed:
|
||||
{shown, total, paths}` (groups shown, distinct choosable texts, candidates in
|
||||
all); the item detail returns it as `collapsed` (null otherwise) and the page
|
||||
reads "Showing the n most used of total prompts in this file". Evidence that
|
||||
cannot be projected, or is over 8 MiB, is a `limited` item without candidates.
|
||||
`REVIEW_EVIDENCE_VERSION` (`utils/review_capture.py`) names this shape and is
|
||||
folded into every item version: a default-profile item carries
|
||||
`default_item_version()` = `RESOLVER_VERSION` + `REVIEW_EVIDENCE_VERSION` (2
|
||||
now; items before it carry 1), an inspection item folds it into its seed. The
|
||||
next scan therefore records such a file again and the new item supersedes the
|
||||
pending, undecided limited one; a decided item is kept and no item is added
|
||||
beside it (`tests/test_review_collapsed.py`). Recording is idempotent per `(byte_id,
|
||||
without it). More than 16 candidates, or evidence over 8 MiB, is a `limited`
|
||||
item without candidates. Recording is idempotent per `(byte_id,
|
||||
resolver_version, evidence_hash)` and never touches an existing item or its
|
||||
decisions; changed bytes add a new pending item and keep the old one. The
|
||||
capture is released before the write; no model is loaded and no pixel is
|
||||
@@ -6702,21 +6485,14 @@ capture capacity), each only when N > 0. Recording captures in the background: i
|
||||
last worker or capture slot, which stay free for an interactive Tag dialog or
|
||||
Apply, and waits up to 2 s for room before counting the file as not added
|
||||
(`test_background_recording_leaves_a_worker_for_the_tag_dialog`). The monitor's
|
||||
pass is best effort: a failure is logged and any link stays. Recording follows the registry's `records`
|
||||
pass runs after its own link, best effort: a failure is logged and the link
|
||||
stays. Recording follows the registry's `records`
|
||||
admission (#289): the scan's recording runs under its own `records` job, and
|
||||
the monitor's pass (one file, not a job, which only settles) is refused
|
||||
while a `records` or `guarded` job or hold runs, except thumbnail work, which
|
||||
writes no records (S5 M7). It then writes nothing, logs it, and answers
|
||||
`deferred`. The worker keeps a deferred path in its own insertion-ordered set
|
||||
(`REVIEW_DEFERRED_LIMIT` = 1,000, oldest dropped first with a log line), waits on
|
||||
its queue with a `REVIEW_RETRY_SECONDS` = 5 s timeout while that set is not empty,
|
||||
and on each wake asks the registry's `blocker()` (a snapshot, safe from any
|
||||
thread); once none remains it replays the set through its queue, so the file is
|
||||
queued after the job ends with no other output, exactly once
|
||||
(`test_monitor_recording_is_refused_beside_record_changing_jobs`). A replay
|
||||
re-reads and re-decides: a file already queued is a `duplicate`, one the job
|
||||
linked is `linked`. The set lives in memory; a restart drops it and the next scan
|
||||
is the backstop. A new item moves `review_index_revision`. A
|
||||
writes no records (S5 M7). It then writes nothing, logs that the file waits
|
||||
for the next scan, and answers `deferred`; the next "new" scan reads the ambiguous file
|
||||
again (`test_monitor_recording_is_refused_beside_record_changing_jobs`). A new item moves `review_index_revision`. A
|
||||
rescan does not copy or hash an ambiguous file whose current size and
|
||||
`mtime_ns` equal the verified fingerprint of bytes an item already cites (a
|
||||
stat compare); the file still stays in the default "new" scope, because it is
|
||||
@@ -6761,10 +6537,9 @@ whose bytes are the item's, re-hashes the current file (`file-changed`
|
||||
otherwise, also for a fresh capture of new bytes), re-reads the capture and
|
||||
requires that its bytes are still ambiguous and still offer the chosen
|
||||
candidate (`review-conflict` otherwise; a resolver change that rewords the
|
||||
reason or reorders candidates leaves the item applicable;
|
||||
`RESOLVER_VERSION` in `utils/prompt_pair_resolver.py` is ingestion's
|
||||
provenance version, and a review item's version folds it with
|
||||
`REVIEW_EVIDENCE_VERSION`, see above), then in one `_pair_transaction`
|
||||
reason or reorders candidates leaves the item applicable, and
|
||||
`RESOLVER_VERSION` in `utils/prompt_pair_resolver.py` is the one version
|
||||
ingestion provenance and review share), then in one `_pair_transaction`
|
||||
checks the epoch, the item revision and state (`review-conflict` with the
|
||||
current item for a repeat), the re-hashed digest, the dependency fingerprint
|
||||
and the public ingester's compatible-only rules through
|
||||
@@ -7100,28 +6875,8 @@ handler's `_ingest_foreign`, `_recheck_foreign`, `_store_foreign`):
|
||||
file linked to another prompt is `conflict` and keeps its link. Logged at info
|
||||
"Foreign run: <status> prompt <id> for <file> (<source>)"; a failure is logged and
|
||||
the file stays unlinked.
|
||||
- **Never.** No tracker FIFO entry is read or consumed and nothing is counted (run
|
||||
count stays 0, no `last_used_at`). At its final unlinked outcome the file is handed
|
||||
to the Needs review worker (#659, see "Needs review items").
|
||||
- **PromptManager runs (#659 Part 3).** A PromptManager output its metadata and its
|
||||
tracked run cannot link (`_find_prompt_from_run` returns `(prompt, cause)`; causes
|
||||
`RUN_SEVERAL_KEYS`, `RUN_BATCH_LATEST`, `RUN_NO_ENTRY`) takes the same path with run
|
||||
kind `promptmanager`; one outside ComfyUI's output folder (`RUN_OUTSIDE_OUTPUT`)
|
||||
asks the ladder once with `in_output=False`. A keyless image keeps its own
|
||||
history-only wait and a placeholder batch entry stays unlinked; neither, nor a file
|
||||
whose metadata could not be read, asks the ladder. Wait entries are
|
||||
`(path, deadline, kind)` and due re-checks `ForeignRecheck(reference, kind)`;
|
||||
`awaiting_foreign()` lists foreign entries only, `awaiting_ladder()` all. The kind
|
||||
is read in one place, `ladder_gate(kind)`: `foreign` gives
|
||||
`(save_foreign_runs(), RUN_MARKS)`, `promptmanager` gives
|
||||
`(MONITORING_ENABLED is not False, SCAN_MARKS)`, so `SAVE_FOREIGN_RUNS` off stops
|
||||
only foreign entries and the node's own Save to library applies through the
|
||||
ladder's #90 steps. Stored as "PromptManager run: <status> prompt <id> for <file>
|
||||
(<source>)"; a file waiting for its run logs "No certain prompt for <file> yet;
|
||||
left unlinked until its run ends". `Policy.MONITOR` stores no fallback guess, so
|
||||
the only new links are inspector and recorded-run answers, which the next scan
|
||||
would make too (`tests/test_foreign_save_to_library.py`
|
||||
`TestPromptManagerRunsAskTheLadder`).
|
||||
- **Never.** No tracker FIFO entry is read or consumed, nothing is counted (run count
|
||||
stays 0, no `last_used_at`), and nothing is queued for Needs review.
|
||||
- **The setting.** `GalleryConfig.SAVE_FOREIGN_RUNS` (`gallery.monitoring.
|
||||
save_foreign_runs`, default true, only a bool applies) is read for every file, at
|
||||
settle, at the re-check and again just before the store, together with
|
||||
@@ -7733,7 +7488,7 @@ Deploying this backend needs a ComfyUI restart (Python and route changes).
|
||||
|
||||
`#/tags` ("Tags & categories", page title "Tags") is a native workspace route; it no
|
||||
longer hands off to the legacy tag manager. That page stays at
|
||||
`/prompt_manager/admin#/tags` at its URL only (#525, #620); tag search and sort, the untagged
|
||||
`/prompt_manager/admin#/tags` linked only from System (#525, D165); tag search and sort, the untagged
|
||||
entry (D149) and multi-tag OR (the Library's Tag match, D150) moved to the workspace
|
||||
(#444); bulk prompt delete stays on the legacy admin page (bulk tags: the Prompt
|
||||
library's selection bar, D151). A prompt's category is changed in the Prompt library
|
||||
@@ -7865,8 +7620,7 @@ The legacy pages (`/prompt_manager/admin`, `admin#/tags`, `gallery`, `gallery.ht
|
||||
their URLs, and admin's Metadata and Gallery buttons still open their legacy pages (maintainer
|
||||
ruling; pinned by `legacy-system-links.spec.mjs`).
|
||||
|
||||
- **D165 retired** (#620): the old pages show their removal notice since 3.5.1, so System no longer links them and the load failure below offers a reload and ComfyUI. The original ruling:
|
||||
**D165** (beyond the concept, maintainer ruling 2026-10-30): System's Overview section ends
|
||||
- **D165** (beyond the concept, maintainer ruling 2026-10-30): System's Overview section ends
|
||||
with one small line, "Legacy pages: Dashboard · Tags · Gallery · Metadata viewer"
|
||||
(`.legacy-pages`, new tabs), outside `.settings-layout`. The concept has no such line;
|
||||
`mapOverviewConcept` adds it to the page tree.
|
||||
|
||||
+12
-38
@@ -156,13 +156,12 @@ try:
|
||||
_global_prompt_tracker = get_prompt_tracker(_global_db)
|
||||
_global_image_monitor = get_image_monitor(_global_db, _global_prompt_tracker)
|
||||
|
||||
# The Needs review pass runs on the API's review worker (#659), through
|
||||
# the capture store the scan and the Tag dialog use: an output the
|
||||
# monitor leaves unlinked at its final outcome is queued as a scan would
|
||||
# queue it, and a linked one's pending items leave the queue. The package
|
||||
# teardown detaches it and stops the worker before that store is closed.
|
||||
# The Needs review pass for ambiguous new outputs runs through the API's
|
||||
# capture store (the one the scan and the Tag dialog use): a linked output
|
||||
# is never queued and its pending items leave the queue. The package
|
||||
# teardown detaches it before that store is closed at shutdown.
|
||||
if api is not None:
|
||||
_global_image_monitor.set_review_recorder(api.queue_review_file)
|
||||
_global_image_monitor.set_review_recorder(api.record_review_file)
|
||||
# Every settled output's preview is queued for the API's background
|
||||
# worker (#249): the workspace never asks to generate thumbnails.
|
||||
_global_image_monitor.set_thumbnail_queue(api.queue_capture_thumbnail)
|
||||
@@ -293,26 +292,15 @@ def _teardown_logger():
|
||||
return logging.getLogger("prompt_manager.init")
|
||||
|
||||
|
||||
def _review_worker_started(api_object):
|
||||
"""Whether the API's Needs review worker ever started (False without
|
||||
one, or when the check fails)."""
|
||||
try:
|
||||
return bool(api_object is not None and api_object.review_worker_started())
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _stop_background_work():
|
||||
"""Stop the image monitor, the Needs review worker, the preview worker,
|
||||
the job worker threads and the prompt cleanup thread against one
|
||||
TEARDOWN_SECONDS deadline, once.
|
||||
"""Stop the image monitor, the preview worker, the job worker threads
|
||||
and the prompt cleanup thread against one TEARDOWN_SECONDS deadline, once.
|
||||
|
||||
Returns ``{"monitor", "review", "thumbnails", "workers", "tracker"}``
|
||||
booleans (True: it stopped), leaving out parts that never started.
|
||||
Later calls return a copy of the first result. A Ctrl+C inside a step is
|
||||
logged and the step is False; one between steps is re-raised after the
|
||||
result (parts not reached are False) is stored and the ``atexit`` entry
|
||||
removed.
|
||||
Returns ``{"monitor", "thumbnails", "workers", "tracker"}`` booleans
|
||||
(True: it stopped), leaving out parts that never started. Later calls return a
|
||||
copy of the first result. A Ctrl+C inside a step is logged and the
|
||||
step is False; one between steps is re-raised after the result (parts
|
||||
not reached are False) is stored and the ``atexit`` entry removed.
|
||||
"""
|
||||
global _background_work_result
|
||||
with _background_work_lock:
|
||||
@@ -327,10 +315,8 @@ def _stop_background_work():
|
||||
|
||||
# A part whose global is set has started; False until its step says
|
||||
# otherwise, so an interrupt between steps leaves an honest result.
|
||||
reviews = thumbnails # the API also owns the review worker (#659)
|
||||
started = (
|
||||
("monitor", monitor),
|
||||
("review", _review_worker_started(reviews) or None),
|
||||
("thumbnails", thumbnails),
|
||||
("workers", parallel.job_pool_started() or None),
|
||||
("tracker", tracker),
|
||||
@@ -363,18 +349,6 @@ def _stop_background_work():
|
||||
result["monitor"] = _teardown_step(
|
||||
"the image monitor", stop_monitor, logger
|
||||
)
|
||||
if reviews is not None:
|
||||
|
||||
def stop_reviews():
|
||||
from .py.api.review_recording import REVIEW_STOP_SECONDS
|
||||
|
||||
return reviews.stop_review_worker(left(REVIEW_STOP_SECONDS))
|
||||
|
||||
# Always stopped, so no later output starts it; reported
|
||||
# only when it ran (an image in hand may have started it).
|
||||
stopped = _teardown_step("the review worker", stop_reviews, logger)
|
||||
if "review" in result or _review_worker_started(reviews):
|
||||
result["review"] = stopped
|
||||
if thumbnails is not None:
|
||||
|
||||
def close_previews():
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 26 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 42 KiB |
@@ -291,6 +291,13 @@ class AnnotationOperations:
|
||||
conn.execute(_BUMP_INDEX)
|
||||
return conn.execute(_REVISION, (byte_id,)).fetchone()[0]
|
||||
|
||||
def _current_set(self, conn, sha256, byte_id, revision) -> dict:
|
||||
return {
|
||||
"sha256": sha256,
|
||||
"tags": self._byte_tags(conn, byte_id),
|
||||
"tag_revision": revision,
|
||||
}
|
||||
|
||||
def read_image_tags(self, locator: str, sha256: str) -> dict:
|
||||
"""The stored set of these exact bytes, or an empty set at revision 0.
|
||||
|
||||
|
||||
+22
-2
@@ -16,17 +16,18 @@ check, and none of them carries a server path.
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
import ntpath
|
||||
import os
|
||||
import sqlite3
|
||||
from pathlib import PurePosixPath, PureWindowsPath
|
||||
from urllib.parse import quote
|
||||
|
||||
try:
|
||||
from ..utils.hashing import register_prompt_functions
|
||||
from .models import normalize_image_path
|
||||
from .sqlite_uri import readonly_uri
|
||||
except ImportError:
|
||||
from utils.hashing import register_prompt_functions
|
||||
from database.models import normalize_image_path
|
||||
from database.sqlite_uri import readonly_uri
|
||||
|
||||
logger = logging.getLogger("prompt_manager.database.health")
|
||||
|
||||
@@ -88,6 +89,25 @@ def _counted(lines):
|
||||
return _result(count, detail)
|
||||
|
||||
|
||||
def readonly_uri(db_path, *, windows=None):
|
||||
"""The ``mode=ro`` SQLite URI of *db_path*, on this platform or the given one.
|
||||
|
||||
pathlib spells a UNC path ``\\\\server\\share\\x.db`` as
|
||||
``file://server/share/x.db``, a remote authority SQLite refuses to open.
|
||||
With an empty authority (``file:////server/share/x.db``) SQLite hands
|
||||
Windows the ``//server/share`` path, which it opens as the UNC path.
|
||||
"""
|
||||
if windows is None:
|
||||
windows = os.name == "nt"
|
||||
db_path = os.path.abspath(db_path)
|
||||
if not windows:
|
||||
return PurePosixPath(db_path).as_uri() + "?mode=ro"
|
||||
path = PureWindowsPath(db_path)
|
||||
if ntpath.splitdrive(str(path))[0].startswith("\\\\"):
|
||||
return "file:" + quote("//" + path.as_posix()) + "?mode=ro"
|
||||
return path.as_uri() + "?mode=ro"
|
||||
|
||||
|
||||
def _integrity(conn, _roots):
|
||||
rows = [
|
||||
row[0] for row in conn.execute(f"PRAGMA integrity_check({INTEGRITY_LIMIT})")
|
||||
|
||||
@@ -97,9 +97,6 @@ _ORDERS = {
|
||||
"newest": ("COALESCE(julianday(p.created_at),0)", "DESC"),
|
||||
"oldest": ("COALESCE(julianday(p.created_at),0)", "ASC"),
|
||||
"name": (_NAME, "ASC"),
|
||||
"name-desc": (_NAME, "DESC"),
|
||||
"most-used": ("COALESCE(p.run_count,0)", "DESC"),
|
||||
"last-used": ("COALESCE(julianday(p.last_used_at),0)", "DESC"),
|
||||
"rating": ("COALESCE(p.rating,0)", "DESC"),
|
||||
}
|
||||
# Pair archive scopes for variant and image reads, as conditions on alias pp.
|
||||
|
||||
@@ -47,11 +47,11 @@ import sqlite3
|
||||
import time
|
||||
import types
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable, Dict, List, Optional, Tuple
|
||||
|
||||
from .models import BUSY_TIMEOUT_SECONDS, PromptModel
|
||||
from .sqlite_uri import readonly_uri
|
||||
|
||||
try:
|
||||
from ..utils import library_location as ll
|
||||
@@ -322,7 +322,7 @@ def _verify_copy(temp: str, counts, documents) -> None:
|
||||
"verify-failed",
|
||||
f"{MESSAGES['verify-failed']} {detail}" if detail else None,
|
||||
)
|
||||
uri = readonly_uri(temp)
|
||||
uri = Path(os.path.abspath(temp)).as_uri() + "?mode=ro"
|
||||
try:
|
||||
with contextlib.closing(sqlite3.connect(uri, uri=True)) as conn:
|
||||
copied = _describe(conn)
|
||||
|
||||
+4
-3
@@ -14,7 +14,6 @@ from contextlib import closing
|
||||
from pathlib import Path
|
||||
from typing import Optional, Set, Tuple
|
||||
|
||||
from .sqlite_uri import readonly_uri
|
||||
from .managed_connection import (
|
||||
ManagedConnection,
|
||||
await_closed,
|
||||
@@ -1200,7 +1199,7 @@ class PromptModel:
|
||||
if header != SQLITE_HEADER:
|
||||
return False, "Not a SQLite database file"
|
||||
|
||||
uri = readonly_uri(path)
|
||||
uri = Path(os.path.abspath(path)).as_uri() + "?mode=ro"
|
||||
try:
|
||||
conn = sqlite3.connect(uri, uri=True)
|
||||
except sqlite3.Error as e:
|
||||
@@ -1307,7 +1306,9 @@ class PromptModel:
|
||||
replacement (for example, incompatible page sizes in WAL mode),
|
||||
propagate the error rather than copy files under other open owners.
|
||||
"""
|
||||
source = sqlite3.connect(readonly_uri(Path(src_path).resolve()), uri=True)
|
||||
source = sqlite3.connect(
|
||||
Path(src_path).resolve().as_uri() + "?mode=ro", uri=True
|
||||
)
|
||||
try:
|
||||
target = self.get_connection()
|
||||
# The target is written under backup's step too: mark it in use
|
||||
|
||||
@@ -1049,8 +1049,7 @@ class PromptDatabase(
|
||||
if include_ancestors:
|
||||
ancestors = set()
|
||||
for folder in folders:
|
||||
# #646: ``folder`` already uses ``/``; on POSIX ``\\`` is a name.
|
||||
parts = folder.split("/")
|
||||
parts = folder.replace("\\", "/").split("/")
|
||||
for i in range(1, len(parts)):
|
||||
ancestors.add("/".join(parts[:i]))
|
||||
folders.update(ancestors)
|
||||
|
||||
@@ -42,7 +42,6 @@ from typing import Dict, Optional
|
||||
from . import workflow_documents as wd
|
||||
from .execution_history_schema import rotate_history_epoch
|
||||
from .safety_backup import take_safety_backup
|
||||
from .sqlite_uri import readonly_uri
|
||||
|
||||
logger = logging.getLogger("prompt_manager.database.restore_stage")
|
||||
|
||||
@@ -115,7 +114,7 @@ def file_digest(path: str) -> str:
|
||||
|
||||
|
||||
def _readonly(path: str) -> sqlite3.Connection:
|
||||
return sqlite3.connect(readonly_uri(Path(path).resolve()), uri=True)
|
||||
return sqlite3.connect(Path(path).resolve().as_uri() + "?mode=ro", uri=True)
|
||||
|
||||
|
||||
def _schema(path: str) -> list:
|
||||
|
||||
+1
-23
@@ -114,10 +114,6 @@ _PENDING_AT_STAT = (
|
||||
f"JOIN {ITEMS_TABLE} i ON i.byte_id=b.id "
|
||||
"WHERE f.locator=? AND b.size=? AND b.mtime_ns=? AND i.state='pending'"
|
||||
)
|
||||
# The newest pending item of the bytes verified at one stat (Inspect, #659).
|
||||
_NEWEST_PENDING_AT_STAT = (
|
||||
_PENDING_AT_STAT + " ORDER BY i.created_at DESC, i.rowid DESC LIMIT 1"
|
||||
)
|
||||
# Pending items of one file: the candidates a link settles.
|
||||
_PENDING_OF_LOCATOR = (
|
||||
f"SELECT i.id FROM {FILES_TABLE} f " # nosec B608
|
||||
@@ -463,24 +459,6 @@ class ReviewOperations:
|
||||
)
|
||||
return row is not None
|
||||
|
||||
def review_item_at(self, locator: str, size: int, mtime_ns: int) -> dict | None:
|
||||
"""Inspect's ``review`` facet of the bytes verified at this stat (#659).
|
||||
|
||||
``{"state": "pending", "item_id": ...}`` names the newest pending item
|
||||
(any version); otherwise ``{"state": "decided"}`` when such bytes carry
|
||||
a decided item; else None. Two indexed reads, no file access.
|
||||
"""
|
||||
_validate_locator(locator)
|
||||
conn = self.model.get_connection()
|
||||
row = conn.execute(
|
||||
_NEWEST_PENDING_AT_STAT, (locator, size, mtime_ns)
|
||||
).fetchone()
|
||||
if row is not None:
|
||||
return {"state": "pending", "item_id": row[0]}
|
||||
if conn.execute(_DECIDED_AT, (locator, size, mtime_ns)).fetchone() is not None:
|
||||
return {"state": "decided"}
|
||||
return None
|
||||
|
||||
def review_file_linked(self, spellings) -> bool:
|
||||
"""True when a saved row links the file under any of ``spellings``."""
|
||||
with self._annotation_read() as conn:
|
||||
@@ -558,7 +536,7 @@ class ReviewOperations:
|
||||
"""Remove the pending, undecided items that offer nothing to choose.
|
||||
|
||||
``locators`` are files the caller found ambiguous without a choice
|
||||
(no candidate carries a prompt). Of their items, one leaves
|
||||
(fewer than two candidates carry a prompt). Of their items, one leaves
|
||||
the queue only when its own stored evidence offers no choice either
|
||||
(``evidence_offers_choice``) and it is still ``pending`` at revision 0
|
||||
with no decision row, the same safe delete as
|
||||
|
||||
@@ -215,24 +215,22 @@ def choosable(candidate: Any) -> bool:
|
||||
|
||||
|
||||
# An item is worth a decision only when at least this many candidates offer
|
||||
# a prompt; with none there is nothing to choose (maintainer test of
|
||||
# #284/#288: 39 items whose candidates were all "unresolved"). One is enough
|
||||
# (#657 addendum D1, 2026-11-20): the other branches stay listed, disabled,
|
||||
# and the user may still leave the file unresolved.
|
||||
MIN_CHOOSABLE = 1
|
||||
# a prompt; with fewer there is nothing to choose between (maintainer test of
|
||||
# #284/#288: 39 items whose candidates were all "unresolved").
|
||||
MIN_CHOOSABLE = 2
|
||||
|
||||
|
||||
def evidence_offers_choice(evidence: Any) -> bool:
|
||||
"""False when stored evidence provably offers nothing to choose.
|
||||
|
||||
Unlimited evidence must list ``MIN_CHOOSABLE`` choosable candidates (the
|
||||
saver anchor's one pair, #390, counts like any other). A limited item
|
||||
stores none, only ``candidate_total``; it may offer a choice unless that
|
||||
total is too small.
|
||||
Unlimited evidence must list ``MIN_CHOOSABLE`` choosable candidates. A
|
||||
limited item stores none, only ``candidate_total``; it may offer a choice
|
||||
(more than ``MAX_CANDIDATES`` prompts) unless that total is too small.
|
||||
"""
|
||||
if not isinstance(evidence, dict):
|
||||
return False
|
||||
needed = MIN_CHOOSABLE
|
||||
# The saver anchor's one pair (#390) is a suggestion to confirm.
|
||||
needed = 1 if evidence.get("anchor") == "saver" else MIN_CHOOSABLE
|
||||
if evidence.get("limited"):
|
||||
total = evidence.get("candidate_total")
|
||||
return type(total) is int and total >= needed
|
||||
|
||||
@@ -31,15 +31,7 @@ MAX_STATE_BYTES = 4096
|
||||
MAX_TAGS = 20
|
||||
MAX_TAG_LENGTH = 50
|
||||
_IMAGE_SORTS = ("newest", "oldest", "name", "name-desc", "rating")
|
||||
_LIBRARY_SORTS = (
|
||||
"newest",
|
||||
"oldest",
|
||||
"name",
|
||||
"name-desc",
|
||||
"most-used",
|
||||
"last-used",
|
||||
"rating",
|
||||
)
|
||||
_LIBRARY_SORTS = ("newest", "oldest", "name", "rating")
|
||||
_MEDIA = ("all", "image", "video")
|
||||
# How a Library view's Tags match (#444): every tag, any of them, or parents
|
||||
# without tags ("untagged" never goes with tags; the listing refuses both).
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
"""The read-only SQLite URI of a path, safe for Windows network shares."""
|
||||
|
||||
import ntpath
|
||||
import os
|
||||
from pathlib import PurePosixPath, PureWindowsPath
|
||||
from urllib.parse import quote
|
||||
|
||||
|
||||
def readonly_uri(db_path, *, windows=None):
|
||||
"""The ``mode=ro`` SQLite URI of *db_path*, on this platform or the given one.
|
||||
|
||||
pathlib spells a UNC path ``\\\\server\\share\\x.db`` as
|
||||
``file://server/share/x.db``, a remote authority SQLite refuses to open.
|
||||
With an empty authority (``file:////server/share/x.db``) SQLite hands
|
||||
Windows the ``//server/share`` path, which it opens as the UNC path.
|
||||
"""
|
||||
if windows is None:
|
||||
windows = os.name == "nt"
|
||||
db_path = os.path.abspath(db_path)
|
||||
if not windows:
|
||||
return PurePosixPath(db_path).as_uri() + "?mode=ro"
|
||||
path = PureWindowsPath(db_path)
|
||||
if ntpath.splitdrive(str(path))[0].startswith("\\\\"):
|
||||
return "file:" + quote("//" + path.as_posix()) + "?mode=ro"
|
||||
return path.as_uri() + "?mode=ro"
|
||||
@@ -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 by its address and from the legacy admin page; the workspace no longer links it (#621); its capabilities map to the shared inspector, including its one-click COPY ALL summary, which is the shared inspector's "Copy settings summary" (D117, LI-4). PR L3 ([#286](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/286)) shipped that button and local roles equal to the server's resolver (`web/js/workspace/local-resolver.mjs`, TESTING.md "Local roles (#249 PR L3, decision LI-1)"). Recorded deviations D60–D66 and D117 are in [TESTING.md](../TESTING.md).
|
||||
- Local Inspect (#249, PRs L1–L3) replaces the `#/inspect` handoff with the concept's native "Inspect a file" page: one local image or video previews inline and opens the shared viewer and full inspector on a record read entirely in the browser, with nothing uploaded, imported or stored. The legacy metadata page (`web/metadata.html`, served at `/prompt_manager/gallery.html`) stays reachable from Overview; its capabilities map to the shared inspector, including its one-click COPY ALL summary, which is the shared inspector's "Copy settings summary" (D117, LI-4). PR L3 ([#286](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/286)) shipped that button and local roles equal to the server's resolver (`web/js/workspace/local-resolver.mjs`, TESTING.md "Local roles (#249 PR L3, decision LI-1)"). Recorded deviations D60–D66 and D117 are in [TESTING.md](../TESTING.md).
|
||||
- Collections ([#331](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/331), three PRs) adds named, hand-picked groups of images, stored in the library database by file location as favorites are: a COLLECTIONS sidebar group whose rows open Images filtered to one collection (`#/collection/<id>`) with rename and delete, Add to collection and Remove from collection in the Images selection bar, a Collections… checklist in the shared inspector for the side panel and the viewer, and saved views that keep a collection. Membership survives restarts, source reordering and System › Maintenance duplicate cleanup; no file is copied, moved or changed.
|
||||
|
||||
## Scope and compatibility
|
||||
@@ -69,16 +69,14 @@ regression coverage with mockup-only tests.
|
||||
|
||||
## GitHub and release gates
|
||||
|
||||
Extend existing required workflows: the Python suite on Linux (3.12 on a pull
|
||||
request, 3.12–3.14 in the merge queue; Windows 3.12–3.14 runs in `portability.yml`
|
||||
and does not gate a merge; macOS is not tested in CI, #571); 85% Python coverage;
|
||||
formatting; frontend units and per-file coverage floors; vendor checks; browser
|
||||
workflows; real ComfyUI compatibility. Python 3.12 is the floor.
|
||||
Extend existing required workflows: the Python 3.10–3.13 matrix on Linux,
|
||||
Windows and macOS; 85% Python coverage; formatting; frontend units and per-file
|
||||
coverage floors; vendor checks; browser workflows; real ComfyUI compatibility.
|
||||
Publish traces, screenshots, logs and coverage artifacts on failures. See
|
||||
[TESTING.md](../TESTING.md) for commands and fixture isolation requirements.
|
||||
|
||||
Every PR must map acceptance criteria to tests, report relevant checks and describe
|
||||
visual changes in words; never attach screenshots or other images to a PR. All required checks must pass before merging.
|
||||
Every PR must map acceptance criteria to tests, report relevant checks and include
|
||||
screenshots for visual changes. All required checks must pass before merging.
|
||||
Use maintainer live review at meaningful visual and host-integration milestones;
|
||||
capture discovered regressions in automated tests. Notify the maintainer when
|
||||
Python changes require a ComfyUI restart.
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 85 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
+16
-4
@@ -3,6 +3,7 @@ PromptManager: Main custom node implementation that extends CLIPTextEncode
|
||||
with persistent prompt storage and search capabilities.
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
if __package__:
|
||||
@@ -99,21 +100,19 @@ class PromptManager(PromptManagerBase, ComfyNodeABC):
|
||||
"prepend_text": (
|
||||
IO.STRING,
|
||||
{
|
||||
"default": "",
|
||||
"tooltip": (
|
||||
"Text to prepend to the main prompt (connected STRING "
|
||||
"nodes will be added before the main text)"
|
||||
),
|
||||
)
|
||||
},
|
||||
),
|
||||
"append_text": (
|
||||
IO.STRING,
|
||||
{
|
||||
"default": "",
|
||||
"tooltip": (
|
||||
"Text to append to the main prompt (connected STRING "
|
||||
"nodes will be added after the main text)"
|
||||
),
|
||||
)
|
||||
},
|
||||
),
|
||||
"save_to_library": SAVE_TO_LIBRARY_INPUT,
|
||||
@@ -260,6 +259,19 @@ class PromptManager(PromptManagerBase, ComfyNodeABC):
|
||||
if not save_to_library:
|
||||
return result # #90: no metadata registration, no history text
|
||||
|
||||
# Register with ComfyUI integration for standard metadata compatibility
|
||||
node_id = f"promptmanager_{int(time.time() * 1000)}"
|
||||
self.comfyui_integration.register_prompt(
|
||||
node_id,
|
||||
encoding_text.strip(),
|
||||
{
|
||||
"category": category.strip() if category else None,
|
||||
"tags": extended_tags,
|
||||
"prompt_id": prompt_id,
|
||||
"prepend_text": prepend_text.strip() if prepend_text else None,
|
||||
"append_text": append_text.strip() if append_text else None,
|
||||
},
|
||||
)
|
||||
record_runtime_context(
|
||||
type(self).__name__, text, prepend_text, append_text, encoding_text
|
||||
)
|
||||
|
||||
+57
-1
@@ -7,7 +7,7 @@ duplicate code in prompt_manager.py and prompt_manager_text.py.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
try:
|
||||
from .utils.logging_config import get_logger
|
||||
@@ -19,6 +19,7 @@ except ImportError:
|
||||
|
||||
try:
|
||||
from .database.operations import PromptDatabase
|
||||
from .utils.comfyui_integration import get_comfyui_integration
|
||||
from .utils.image_monitor import get_image_monitor
|
||||
from .utils.prompt_tracker import get_prompt_tracker
|
||||
from .utils.hashing import generate_prompt_hash
|
||||
@@ -37,6 +38,7 @@ except ImportError:
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from database.operations import PromptDatabase
|
||||
from utils.comfyui_integration import get_comfyui_integration
|
||||
from utils.image_monitor import get_image_monitor
|
||||
from utils.prompt_tracker import get_prompt_tracker
|
||||
from utils.hashing import generate_prompt_hash
|
||||
@@ -84,6 +86,7 @@ class PromptManagerBase:
|
||||
self.db = PromptDatabase()
|
||||
self.prompt_tracker = get_prompt_tracker(self.db)
|
||||
self.image_monitor = get_image_monitor(self.db, self.prompt_tracker)
|
||||
self.comfyui_integration = get_comfyui_integration()
|
||||
|
||||
self._start_gallery_system()
|
||||
self.logger.debug(f"{self.__class__.__name__} node initialization completed")
|
||||
@@ -396,6 +399,52 @@ class PromptManagerBase:
|
||||
tags = [tag.strip() for tag in tags_string.split(",") if tag.strip()]
|
||||
return tags if tags else None
|
||||
|
||||
def _search_prompts(self, search_text: str = "") -> List[Dict[str, Any]]:
|
||||
"""Search for past prompts by text content.
|
||||
|
||||
Args:
|
||||
search_text: Text to search for in prompt database
|
||||
|
||||
Returns:
|
||||
List of matching prompt dictionaries with metadata
|
||||
"""
|
||||
try:
|
||||
if not search_text or not search_text.strip():
|
||||
return []
|
||||
|
||||
try:
|
||||
from .py.config import PromptManagerConfig
|
||||
|
||||
max_results = PromptManagerConfig.MAX_SEARCH_RESULTS
|
||||
except Exception:
|
||||
max_results = 100
|
||||
|
||||
results = self.db.search_prompts(
|
||||
text=search_text.strip(),
|
||||
category=None,
|
||||
tags=None,
|
||||
rating_min=None,
|
||||
limit=max_results,
|
||||
)
|
||||
|
||||
return results
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error searching prompts: {e}")
|
||||
return []
|
||||
|
||||
def search_prompts_api(self, search_text: str = "") -> List[Dict[str, Any]]:
|
||||
"""API method for JavaScript UI to search prompts."""
|
||||
return self._search_prompts(search_text=search_text)
|
||||
|
||||
def get_recent_prompts_api(self, limit: int = 20) -> List[Dict[str, Any]]:
|
||||
"""API method for JavaScript UI to get recent prompts."""
|
||||
try:
|
||||
return self.db.get_recent_prompts(limit=limit)
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error getting recent prompts: {e}")
|
||||
return []
|
||||
|
||||
def _start_gallery_system(self):
|
||||
"""Initialize and start the gallery monitoring system."""
|
||||
try:
|
||||
@@ -406,6 +455,13 @@ class PromptManagerBase:
|
||||
self.logger.error(f"Failed to start gallery system: {e}")
|
||||
self.logger.warning("Gallery features will be disabled")
|
||||
|
||||
def get_gallery_status(self) -> Dict[str, Any]:
|
||||
"""Get status of the gallery system."""
|
||||
return {
|
||||
"image_monitor": self.image_monitor.get_status(),
|
||||
"prompt_tracker": self.prompt_tracker.get_status(),
|
||||
}
|
||||
|
||||
def cleanup_gallery_system(self):
|
||||
"""Clean up gallery system resources.
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
if __package__:
|
||||
@@ -172,6 +173,19 @@ class PromptManagerPair(PromptManagerFocused):
|
||||
self.logger.warning(f"Could not save or track paired prompt: {error}")
|
||||
if is_positive:
|
||||
self._mark_untracked(prompt, unique_id)
|
||||
try:
|
||||
self.comfyui_integration.register_prompt(
|
||||
f"promptmanager_pair_{time.time_ns()}",
|
||||
positive,
|
||||
{
|
||||
"prompt_id": prompt_id,
|
||||
"pair_id": pair_id if pair_used else None,
|
||||
"negative_text": negative_text,
|
||||
"category": category.strip() or None,
|
||||
},
|
||||
)
|
||||
except Exception as error:
|
||||
self.logger.warning(f"Could not register paired metadata: {error}")
|
||||
record_runtime_context(
|
||||
type(self).__name__,
|
||||
text,
|
||||
|
||||
@@ -3,6 +3,7 @@ PromptManagerText: A text-only version of PromptManager that outputs STRING
|
||||
without CLIP encoding, while maintaining all database and search features.
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
if __package__:
|
||||
@@ -229,6 +230,19 @@ class PromptManagerText(PromptManagerBase, ComfyNodeABC):
|
||||
if not save_to_library:
|
||||
return result # #90: no metadata registration, no history text
|
||||
|
||||
# Register with ComfyUI integration for standard metadata compatibility
|
||||
node_id = f"promptmanagertext_{int(time.time() * 1000)}"
|
||||
self.comfyui_integration.register_prompt(
|
||||
node_id,
|
||||
final_text.strip(),
|
||||
{
|
||||
"category": category.strip() if category else None,
|
||||
"tags": extended_tags,
|
||||
"prompt_id": prompt_id,
|
||||
"prepend_text": prepend_text.strip() if prepend_text else None,
|
||||
"append_text": append_text.strip() if append_text else None,
|
||||
},
|
||||
)
|
||||
record_runtime_context(
|
||||
type(self).__name__, text, prepend_text, append_text, final_text
|
||||
)
|
||||
|
||||
+89
-12
@@ -30,6 +30,7 @@ import asyncio
|
||||
import datetime
|
||||
import functools
|
||||
import gzip as gzip_module
|
||||
import json
|
||||
import math
|
||||
import ntpath
|
||||
import os
|
||||
@@ -40,7 +41,6 @@ from pathlib import Path
|
||||
from aiohttp import web
|
||||
from PIL import Image
|
||||
|
||||
from . import json_body as _json_body
|
||||
from .prompts import PromptRoutesMixin
|
||||
from .revalidation import revalidated_response
|
||||
from .pairs import PairRoutesMixin
|
||||
@@ -89,7 +89,7 @@ from .source_rescope import SourceRescopeMixin
|
||||
|
||||
try:
|
||||
from ...database.operations import PromptDatabase
|
||||
from ...utils.exif_text import exif_text
|
||||
from ...utils.file_prompt import parse_comfyui_prompt
|
||||
from ...utils.logging_config import get_logger
|
||||
from ...utils.native_memory import release_free_memory
|
||||
from ...utils.png_text import png_text
|
||||
@@ -101,7 +101,7 @@ except ImportError:
|
||||
0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
)
|
||||
from database.operations import PromptDatabase
|
||||
from utils.exif_text import exif_text
|
||||
from utils.file_prompt import parse_comfyui_prompt
|
||||
from utils.logging_config import get_logger
|
||||
from utils.native_memory import release_free_memory
|
||||
from utils.png_text import png_text
|
||||
@@ -214,10 +214,61 @@ def _resolve_static_file(root, filepath, allowed=STATIC_MIME_TYPES):
|
||||
|
||||
|
||||
# ── JSON request bodies ────────────────────────────────────────────────
|
||||
# One bounded reader (json_body.py); these names stay for the mixins and tests.
|
||||
JSON_BODY_MAX_BYTES = _json_body.JSON_BODY_MAX_BYTES
|
||||
_json_error = _json_body.json_error
|
||||
_read_json_body = _json_body.read_json_body
|
||||
JSON_BODY_MAX_BYTES = 1_000_000
|
||||
_JSON_READ_CHUNK = 64 * 1024
|
||||
|
||||
|
||||
def _json_error(message, status):
|
||||
return web.json_response({"success": False, "error": message}, status=status)
|
||||
|
||||
|
||||
async def _read_json_body(request, max_bytes=JSON_BODY_MAX_BYTES):
|
||||
"""Read and parse a JSON object body of at most ``max_bytes``.
|
||||
|
||||
The body is read in chunks so an oversized or chunked upload is refused
|
||||
as soon as it crosses the cap rather than buffered whole.
|
||||
|
||||
Returns:
|
||||
(data, None) on success, or (None, response) where ``response`` is a
|
||||
413 (body too large) or 400 (invalid JSON, or not a JSON object).
|
||||
"""
|
||||
too_large = _json_error(f"Request body too large (max {max_bytes} bytes)", 413)
|
||||
declared = request.content_length
|
||||
if declared is not None and declared > max_bytes:
|
||||
return None, too_large
|
||||
|
||||
chunks = []
|
||||
size = 0
|
||||
async for chunk in request.content.iter_chunked(_JSON_READ_CHUNK):
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
return None, too_large
|
||||
chunks.append(chunk)
|
||||
|
||||
try:
|
||||
data = json.loads(b"".join(chunks).decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
return None, _json_error("Request body must be valid JSON", 400)
|
||||
if not isinstance(data, dict):
|
||||
return None, _json_error("Request body must be a JSON object", 400)
|
||||
return data, None
|
||||
|
||||
|
||||
class _LongJobGuard:
|
||||
"""Async context manager handed out by ``_acquire_long_job``."""
|
||||
|
||||
def __init__(self, lock):
|
||||
self._lock = lock
|
||||
|
||||
async def __aenter__(self):
|
||||
# The caller checked ``locked()`` on this same loop iteration, so this
|
||||
# acquire never waits.
|
||||
await self._lock.acquire()
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb):
|
||||
self._lock.release()
|
||||
return False
|
||||
|
||||
|
||||
# ── Gzip compression middleware ────────────────────────────────────────
|
||||
@@ -375,6 +426,10 @@ class PromptManagerAPI(
|
||||
self._workspace_card_cache = {}
|
||||
# Favorite keys of each root's cached scan (images._favorite_listing).
|
||||
self._favorite_listing_cache = {}
|
||||
# Single-flight locks for long jobs, keyed by job family; see
|
||||
# _acquire_long_job(). Created lazily so no lock binds to an event
|
||||
# loop before the server's loop exists.
|
||||
self._long_jobs: dict = {}
|
||||
# This session's jobs (py/api/jobs.py): the metadata scan, and later
|
||||
# every other long operation the Activity page tracks.
|
||||
self._jobs = JobRegistry(self.logger)
|
||||
@@ -431,6 +486,26 @@ class PromptManagerAPI(
|
||||
_public_error = staticmethod(_public_error)
|
||||
_read_json_body = staticmethod(_read_json_body)
|
||||
|
||||
def _acquire_long_job(self, name):
|
||||
"""Claim the single-flight slot for a long job family, or None when busy.
|
||||
|
||||
Usage in a handler::
|
||||
|
||||
job = self._acquire_long_job("duplicates")
|
||||
if job is None:
|
||||
return self._long_job_busy_response("Duplicate scan")
|
||||
async with job:
|
||||
...
|
||||
|
||||
Families are free-form strings ("duplicates", "thumbnails",
|
||||
"autotag", ...); the lock is released when the ``async with`` block
|
||||
exits, including on exceptions. Must be called from the event loop.
|
||||
"""
|
||||
lock = self._long_jobs.setdefault(name, asyncio.Lock())
|
||||
if lock.locked():
|
||||
return None
|
||||
return _LongJobGuard(lock)
|
||||
|
||||
@staticmethod
|
||||
def _long_job_busy_response(label):
|
||||
"""409 envelope for a long job that is already running."""
|
||||
@@ -986,11 +1061,9 @@ class PromptManagerAPI(
|
||||
return []
|
||||
|
||||
def _extract_comfyui_metadata(self, image_path):
|
||||
"""Embedded ComfyUI metadata of an image (PNG text, EXIF) or a video.
|
||||
"""Embedded ComfyUI metadata of an image (PNG text chunks) or a video.
|
||||
|
||||
PNG text is read without decoding the pixels (``utils.png_text``, #523);
|
||||
WebP, AVIF and JPEG keep the same records as EXIF strings, read through
|
||||
``utils.exif_text``.
|
||||
PNG text is read without decoding the pixels (``utils.png_text``, #523).
|
||||
|
||||
Videos go through ffprobe (see utils/video_metadata). Unreadable files
|
||||
are a warning, not an error: a scan over a large output tree meets
|
||||
@@ -1000,9 +1073,13 @@ class PromptManagerAPI(
|
||||
return read_video_metadata(image_path)
|
||||
try:
|
||||
with Image.open(image_path) as img:
|
||||
return png_text(img) or exif_text(img)
|
||||
return png_text(img)
|
||||
except Exception as e:
|
||||
self.logger.warning(
|
||||
f"Unreadable image {os.path.basename(str(image_path))}: {e}"
|
||||
)
|
||||
return {}
|
||||
|
||||
def _parse_comfyui_prompt(self, metadata):
|
||||
"""Parse ComfyUI and A1111 prompt data from metadata."""
|
||||
return parse_comfyui_prompt(metadata)
|
||||
|
||||
+26
-15
@@ -30,10 +30,8 @@ from .jobs import (
|
||||
)
|
||||
|
||||
try:
|
||||
from ...database.sqlite_uri import readonly_uri
|
||||
from ...utils.parallel import map_parallel
|
||||
except ImportError:
|
||||
from database.sqlite_uri import readonly_uri
|
||||
from utils.parallel import map_parallel
|
||||
|
||||
try:
|
||||
@@ -401,7 +399,7 @@ def _inspect_restore_upload(path):
|
||||
Returns:
|
||||
None when acceptable, otherwise a human-readable reason (blocking).
|
||||
"""
|
||||
uri = readonly_uri(path)
|
||||
uri = Path(os.path.abspath(path)).as_uri() + "?mode=ro"
|
||||
try:
|
||||
conn = sqlite3.connect(uri, uri=True)
|
||||
except sqlite3.Error as e:
|
||||
@@ -1699,8 +1697,7 @@ class AdminRoutesMixin:
|
||||
review (best effort, counted in ``review`` when given); one a saved
|
||||
row already links is reported ``unchanged`` and never queued. An
|
||||
ambiguous file with nothing to choose is reported ``unresolved`` and
|
||||
its pending items without a choice leave the queue. The decision is
|
||||
``review_dispatch``'s, shared with the monitor's review worker (#659).
|
||||
its pending items without a choice leave the queue.
|
||||
"""
|
||||
counts = dict.fromkeys(SCAN_COUNT_KEYS, 0)
|
||||
|
||||
@@ -1714,12 +1711,14 @@ class AdminRoutesMixin:
|
||||
if self._scan_job and self._scan_job.cancelled:
|
||||
break
|
||||
counts["processed"] += 1
|
||||
records = {}
|
||||
ambiguous, untraced, records = [], [], {}
|
||||
try:
|
||||
outcome = self._ingest_scanned_file(
|
||||
media_file,
|
||||
metadata,
|
||||
detailed=True,
|
||||
ambiguous=ambiguous,
|
||||
untraced=untraced,
|
||||
records=records,
|
||||
history=history,
|
||||
)
|
||||
@@ -1728,9 +1727,24 @@ class AdminRoutesMixin:
|
||||
counts["failed"] += 1
|
||||
note(media_file, "error")
|
||||
continue
|
||||
outcome, _recorded = self.review_dispatch(
|
||||
media_file, roots, records.get("decision"), outcome, review
|
||||
)
|
||||
if ambiguous and outcome == "ambiguous":
|
||||
if self._review_file_linked(media_file, roots):
|
||||
outcome = "unchanged" # already linked: not a review case
|
||||
else:
|
||||
# The records name the item versions that count; the
|
||||
# saver anchor (#390) is checked on the captured bytes.
|
||||
self._record_scanned_review(
|
||||
media_file,
|
||||
roots,
|
||||
review,
|
||||
scanned=(records.get("canonical"), None),
|
||||
)
|
||||
elif untraced and outcome == "unresolved":
|
||||
# Untraced by the default profile: the inspection profile may
|
||||
# still offer a choice (queued for review, never linked).
|
||||
outcome = self._untraced_scan_outcome(
|
||||
media_file, roots, records.get("canonical"), review
|
||||
)
|
||||
if outcome is None:
|
||||
note(media_file, None)
|
||||
continue
|
||||
@@ -1767,12 +1781,11 @@ class AdminRoutesMixin:
|
||||
``ambiguous`` is a list, ``media_file`` is appended to it; only a file
|
||||
that then returns ``"ambiguous"`` (nothing linked it) is a Needs
|
||||
review case. An ambiguous result with nothing to choose
|
||||
(``reviewable`` is False: no candidate carries a prompt)
|
||||
(``reviewable`` is False: fewer than two candidates carry a prompt)
|
||||
goes to ``untraced`` instead and returns ``"unresolved"`` when nothing
|
||||
links it. The parsed records of either ambiguous file go to
|
||||
``records["canonical"]`` when ``records`` is a dict, and the ladder's
|
||||
``Decision`` to ``records["decision"]`` (``review_dispatch``'s input).
|
||||
``history`` is the batch's lazy recorded-history lookup.
|
||||
``records["canonical"]`` when ``records`` is a dict. ``history`` is
|
||||
the batch's lazy recorded-history lookup.
|
||||
"""
|
||||
path = str(media_file)
|
||||
if history is None: # one file: history is still asked once
|
||||
@@ -1785,8 +1798,6 @@ class AdminRoutesMixin:
|
||||
lookup=functools.partial(history.recorded, path),
|
||||
policy=Policy.SCAN,
|
||||
)
|
||||
if records is not None:
|
||||
records["decision"] = decision
|
||||
if decision.kind in (NOT_SAVED, NOT_SAVED_WIRED):
|
||||
# Save to library off (#90): no write, recorded-run fallback or
|
||||
# Needs review item
|
||||
|
||||
@@ -943,6 +943,16 @@ class AutotagRoutesMixin:
|
||||
return refusal.response
|
||||
return web.json_response({"success": True, "job": job.summary()}, status=202)
|
||||
|
||||
def _gated_runner(self, owner):
|
||||
"""Executor calls under the model gate *owner* holds (plain when None)."""
|
||||
if owner is None:
|
||||
return self._run_in_executor
|
||||
|
||||
async def run(func, *args, **kwargs):
|
||||
return await model_gate.run(owner, func, *args, **kwargs)
|
||||
|
||||
return run
|
||||
|
||||
def _resolve_allowed_image_path(self, raw_path: str) -> Optional[str]:
|
||||
"""Return the real path when it is a media file inside an output directory."""
|
||||
if Path(str(raw_path)).suffix.lower() not in _MEDIA_EXTENSIONS:
|
||||
@@ -1411,8 +1421,7 @@ class AutotagRoutesMixin:
|
||||
)
|
||||
|
||||
model_type = service.get_loaded_model_type()
|
||||
# Off the loop; a dropped request keeps the gate until it ends.
|
||||
await model_gate.run(owner, service.unload_model)
|
||||
service.unload_model()
|
||||
finally:
|
||||
model_gate.release(owner)
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ import os
|
||||
import sqlite3
|
||||
import tempfile
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
@@ -55,7 +56,6 @@ from .maintenance_plans import PlanExpired, PlanUsed
|
||||
from .restore_plans import RestorePlanStore
|
||||
|
||||
try:
|
||||
from ...database.sqlite_uri import readonly_uri
|
||||
from ...database import restore_stage
|
||||
from ...database.operations import PromptDatabase
|
||||
from ...database.safety_backup import (
|
||||
@@ -66,7 +66,6 @@ try:
|
||||
safety_temp,
|
||||
)
|
||||
except ImportError:
|
||||
from database.sqlite_uri import readonly_uri
|
||||
from database import restore_stage
|
||||
from database.operations import PromptDatabase
|
||||
from database.safety_backup import (
|
||||
@@ -187,7 +186,7 @@ def snapshot_corruption(path):
|
||||
with open(path, "rb") as handle:
|
||||
if handle.read(len(SQLITE_HEADER)) != SQLITE_HEADER:
|
||||
return "Not a SQLite database file"
|
||||
uri = readonly_uri(path)
|
||||
uri = Path(os.path.abspath(path)).as_uri() + "?mode=ro"
|
||||
with closing(sqlite3.connect(uri, uri=True)) as conn:
|
||||
row = conn.execute("PRAGMA integrity_check").fetchone()
|
||||
except (OSError, sqlite3.Error) as error:
|
||||
|
||||
@@ -304,8 +304,7 @@ def _relative_key(path, root):
|
||||
relative = os.path.relpath(str(path), str(root))
|
||||
except ValueError: # another drive (Windows)
|
||||
return None
|
||||
# #646: on POSIX ``a\\b.png`` and ``a/b.png`` are two files.
|
||||
return os.path.normcase(relative).replace(os.sep, "/")
|
||||
return os.path.normcase(relative).replace("\\", "/")
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -148,7 +148,7 @@ def folder_sets(root, files) -> tuple[frozenset, frozenset]:
|
||||
folders.add(rel_dir)
|
||||
with_ancestors = set(folders)
|
||||
for folder in folders:
|
||||
with_ancestors.update(_ancestors(folder, sep))
|
||||
with_ancestors.update(_ancestors(folder))
|
||||
return frozenset(folders), frozenset(with_ancestors)
|
||||
|
||||
|
||||
@@ -158,7 +158,7 @@ def add_folder(root, path, folders, with_ancestors) -> tuple[frozenset, frozense
|
||||
rel_dir = _folder_of(root, path, sep, prefix)
|
||||
if not rel_dir or rel_dir in folders:
|
||||
return folders, with_ancestors
|
||||
return folders | {rel_dir}, with_ancestors | {rel_dir, *_ancestors(rel_dir, sep)}
|
||||
return folders | {rel_dir}, with_ancestors | {rel_dir, *_ancestors(rel_dir)}
|
||||
|
||||
|
||||
def _root_prefix(root) -> tuple[str, str]:
|
||||
@@ -180,10 +180,8 @@ def _folder_of(root, path, sep, prefix) -> str:
|
||||
return "" if rel_dir == "." else rel_dir
|
||||
|
||||
|
||||
def _ancestors(folder: str, sep: str) -> list[str]:
|
||||
# #646: ``\\`` separates only in a Windows root (*sep*, the root flavour's
|
||||
# own); on POSIX it is part of a folder's name.
|
||||
parts = (folder.replace("\\", "/") if sep == "\\" else folder).split("/")
|
||||
def _ancestors(folder: str) -> list[str]:
|
||||
parts = folder.replace("\\", "/").split("/")
|
||||
return ["/".join(parts[:i]) for i in range(1, len(parts))]
|
||||
|
||||
|
||||
|
||||
+1
-35
@@ -3,7 +3,7 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
from functools import partial, wraps
|
||||
from functools import wraps
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -31,9 +31,7 @@ from .inspection_service import (
|
||||
CurrentFileChanged,
|
||||
image_tags_reader,
|
||||
inspect_current_file,
|
||||
review_reader,
|
||||
)
|
||||
from .admin import _scan_roots
|
||||
from .images import image_category_key
|
||||
|
||||
try:
|
||||
@@ -719,37 +717,6 @@ class HistoryRoutesMixin:
|
||||
)
|
||||
return OWN_CATEGORY_UNREAD
|
||||
|
||||
def _history_review(self, target) -> Callable:
|
||||
"""The ``review`` reader of a reported current file (#659, C4).
|
||||
|
||||
Located as the scan locates it (``_review_location`` over the scan
|
||||
roots, resolved like the canonical target), only when the inspector
|
||||
asks; a file under no scan root reads None. A file reached through a
|
||||
linked subfolder is keyed by its resolved path here, so an item the
|
||||
scan stored under the linked spelling is not found (None, no choice).
|
||||
A file without an item is recorded first through the review worker's
|
||||
path (#657 addendum D2). The read closes its connection, as this
|
||||
route's other reads do.
|
||||
"""
|
||||
|
||||
def read(size: int, mtime_ns: int) -> dict | None:
|
||||
roots = _scan_roots(
|
||||
[os.path.realpath(root) for root in self._get_all_output_dirs()]
|
||||
)
|
||||
located = self._review_location(target, roots)
|
||||
if located is None:
|
||||
return None
|
||||
locator = os.path.normcase(located[3])
|
||||
return review_reader(
|
||||
self.db,
|
||||
locator,
|
||||
self.logger,
|
||||
close=True,
|
||||
record=partial(self.inspect_review_file, str(target)),
|
||||
)(size, mtime_ns)
|
||||
|
||||
return read
|
||||
|
||||
async def _history_current(
|
||||
self, request: web.Request, kind: str
|
||||
) -> web.StreamResponse:
|
||||
@@ -826,7 +793,6 @@ class HistoryRoutesMixin:
|
||||
recorded=recorded_output_lookup(
|
||||
db, close=True, reference=receipt["reference"]
|
||||
),
|
||||
review=self._history_review(resolved.canonical_target),
|
||||
)
|
||||
_reauthorize_current_target(resolved, scope)
|
||||
identity = {
|
||||
|
||||
+18
-77
@@ -1,9 +1,9 @@
|
||||
"""Delete images: remove from library, trash, or permanently delete.
|
||||
"""Delete selected images: remove them from the library, or trash them (#480).
|
||||
|
||||
``POST /prompt_manager/images/delete/preview {items | filter}`` reviews the
|
||||
selection for all modes at once and answers a reviewed plan (the System ›
|
||||
selection for both modes at once and answers a reviewed plan (the System ›
|
||||
Maintenance contract, ``py/api/maintenance.py``): the token, the counts of
|
||||
the records each file loses, the refused files with a coded reason (all
|
||||
the records each file loses, the refused files with a coded reason (both
|
||||
modes, and the trash-only ones), the prompts that lose their last image and
|
||||
the safety backup. It writes nothing. ``items`` are Images listing identities
|
||||
(at most 500); ``filter`` is "Select all N matching". Each target is matched
|
||||
@@ -19,16 +19,12 @@ again (containment and fingerprint) and
|
||||
in one transaction; the file stays on disk, hidden;
|
||||
- ``mode="trash"``: it is moved to the trash first (``utils/trash.py``); a
|
||||
refused move leaves the file and its records alone; after a move its
|
||||
records are deleted;
|
||||
- ``mode="permanent"``: it is unlinked from disk with ``os.remove``; a refused
|
||||
unlink leaves the file and its records alone; after removal its records are
|
||||
deleted. This mode is Linux/BSD only.
|
||||
records are deleted.
|
||||
|
||||
Only ``mode="permanent"`` unlinks a media file from disk. A failed records
|
||||
write stops the job; the files after it are not attempted.
|
||||
No path here unlinks a media file. A failed records write stops the job; the
|
||||
files after it are not attempted.
|
||||
"""
|
||||
|
||||
import errno
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -63,11 +59,10 @@ except ImportError:
|
||||
from utils.media_folders import is_trash_folder
|
||||
|
||||
IMAGE_DELETE = "delete_images"
|
||||
MODES = ("library", "trash", "permanent")
|
||||
MODES = ("library", "trash")
|
||||
TITLES = {
|
||||
"library": "Delete images (remove from the library)",
|
||||
"trash": "Delete images (move to the trash)",
|
||||
"permanent": "Delete images (permanently delete from disk)",
|
||||
}
|
||||
MAX_DETAIL_ROWS = 50
|
||||
# The system moved the file but its place in a trash could not be shown (#499).
|
||||
@@ -92,8 +87,8 @@ REASONS = {
|
||||
trash.LOCKED: "The file is open in another program. Close it and try again.",
|
||||
trash.FAILED: "The file could not be moved to the trash.",
|
||||
trash.NO_PERMISSION: (
|
||||
"PromptManager isn't allowed to remove this file (no permission, or it is "
|
||||
"locked)."
|
||||
"PromptManager isn't allowed to move this file (no permission, or it is "
|
||||
"locked in Finder)."
|
||||
),
|
||||
trash.CLOUD_SYNC: (
|
||||
"Files in iCloud Drive or a cloud-synced folder can't be moved to the "
|
||||
@@ -119,16 +114,6 @@ SOURCES_CHANGED = "The sources changed since the review; nothing was changed."
|
||||
RECORDS_FAILED = "The image records could not be removed; the job stopped."
|
||||
|
||||
|
||||
def _permanent_delete_code(error: OSError) -> str:
|
||||
"""Translate a removal ``OSError`` into a permanent-delete refusal code."""
|
||||
code = error.errno if error.errno else None
|
||||
if code in (errno.EACCES, errno.EPERM, errno.EROFS):
|
||||
return trash.NO_PERMISSION
|
||||
if code in (errno.ENETUNREACH, errno.ENETRESET, errno.EHOSTUNREACH):
|
||||
return trash.NETWORK
|
||||
return trash.LOCKED
|
||||
|
||||
|
||||
def lexical_problem(relative: str) -> str | None:
|
||||
"""The refusal code a root-relative POSIX path earns before any file access."""
|
||||
parts = relative.split("/")
|
||||
@@ -290,23 +275,17 @@ class ImageDeleteMixin:
|
||||
acted.append(target)
|
||||
counted = db.count_removal_records([t["removal"] for t in acted])
|
||||
library_count = len(acted)
|
||||
permanent_supported = permanent_delete_supported()
|
||||
public = {
|
||||
"operation": IMAGE_DELETE,
|
||||
"scope": {"count": library_count, "label": "images"},
|
||||
"library": {"count": library_count},
|
||||
"trash": {"count": library_count - len(trash_refused)},
|
||||
"permanent": {"count": library_count},
|
||||
"protected": {"count": len(refused), "reasons": []},
|
||||
"refused": _summary(refused),
|
||||
"trash_refused": _summary(trash_refused),
|
||||
"records": counted["records"],
|
||||
"orphaned_prompts": counted["orphaned_prompts"],
|
||||
"media": {
|
||||
"deletes_files": permanent_supported,
|
||||
"label": "Chosen in the review",
|
||||
},
|
||||
"permanent_delete_supported": permanent_supported,
|
||||
"media": {"deletes_files": False, "label": "Chosen in the review"},
|
||||
"details": [],
|
||||
}
|
||||
return {"targets": acted, "public": public}
|
||||
@@ -362,11 +341,7 @@ class ImageDeleteMixin:
|
||||
async def _delete_images(self, job, db, targets, mode, backup):
|
||||
job.update(total=len(targets), status_line=TITLES[mode])
|
||||
roots = [str(root) for root in self._get_all_output_dirs()]
|
||||
done_group = (
|
||||
"trashed"
|
||||
if mode == "trash"
|
||||
else ("deleted" if mode == "permanent" else "removed")
|
||||
)
|
||||
done_group = "trashed" if mode == "trash" else "removed"
|
||||
changed, failed = 0, None
|
||||
for done, target in enumerate(targets, start=1):
|
||||
if failed:
|
||||
@@ -391,26 +366,17 @@ class ImageDeleteMixin:
|
||||
)
|
||||
elif group == done_group:
|
||||
changed += 1
|
||||
if mode == "trash":
|
||||
detail = (
|
||||
f"Moved to the {label}" if label else "Removed from the library"
|
||||
)
|
||||
elif mode == "permanent":
|
||||
detail = "Deleted from disk"
|
||||
else:
|
||||
detail = "Removed from the library"
|
||||
detail = (
|
||||
f"Moved to the {label}" if label else "Removed from the library"
|
||||
)
|
||||
self._record_delete(job, group, target, None, detail)
|
||||
else:
|
||||
self._record_delete(job, group, target, code)
|
||||
job.update(processed=done, progress=int(done / len(targets) * 100))
|
||||
if changed:
|
||||
self.invalidate_gallery_cache()
|
||||
if mode == "trash":
|
||||
verb, where = "Moved", "to the trash"
|
||||
elif mode == "permanent":
|
||||
verb, where = "Permanently deleted", "from disk"
|
||||
else:
|
||||
verb, where = "Removed", "from the library"
|
||||
verb = "Moved" if mode == "trash" else "Removed"
|
||||
where = "to the trash" if mode == "trash" else "from the library"
|
||||
line = f"{verb} {changed:,} of {len(targets):,} images {where}"
|
||||
job.log_line(line)
|
||||
job.update(progress=100, status_line=f"{line} · {backup_note(backup)}")
|
||||
@@ -432,7 +398,7 @@ class ImageDeleteMixin:
|
||||
"code": code,
|
||||
"detail": text,
|
||||
}
|
||||
mark = {"removed": "-", "trashed": "-", "deleted": "-"}.get(group, "=")
|
||||
mark = {"removed": "-", "trashed": "-"}.get(group, "=")
|
||||
job.record(
|
||||
group, row, f"{mark} {target['root_label']}/{target['rel']} · {text}"
|
||||
)
|
||||
@@ -471,21 +437,6 @@ class ImageDeleteMixin:
|
||||
)
|
||||
return "errors", TRASH_UNCONFIRMED, None
|
||||
mark = None
|
||||
elif mode == "permanent":
|
||||
try:
|
||||
os.remove(target["abs"])
|
||||
except OSError as error:
|
||||
if error.errno == errno.ENOENT:
|
||||
pass
|
||||
else:
|
||||
code = _permanent_delete_code(error)
|
||||
self.logger.info(
|
||||
"Not permanently deleted (%s): %s",
|
||||
code,
|
||||
target["rel"],
|
||||
)
|
||||
return "not_changed", code, None
|
||||
mark = None
|
||||
else:
|
||||
mark = (target["size"], target["mtime_ns"])
|
||||
try:
|
||||
@@ -494,11 +445,7 @@ class ImageDeleteMixin:
|
||||
self.logger.exception("Removing an image's records failed")
|
||||
return "errors", None, label
|
||||
_remove_thumbnail(Path(target["root"]), Path(target["rel"]), self.logger)
|
||||
if mode == "trash":
|
||||
return "trashed", None, label
|
||||
if mode == "permanent":
|
||||
return "deleted", None, label
|
||||
return "removed", None, label
|
||||
return ("trashed" if mode == "trash" else "removed"), None, label
|
||||
|
||||
# ── the workspace listing ─────────────────────────────────────────
|
||||
|
||||
@@ -570,12 +517,6 @@ class ImageDeleteMixin:
|
||||
return [path for path in paths if not removed(path)]
|
||||
|
||||
|
||||
def permanent_delete_supported() -> bool:
|
||||
"""Permanent delete is offered only with the Freedesktop trash backend
|
||||
(Linux/BSD servers); the review and the apply both ask here (#644)."""
|
||||
return isinstance(trash.BACKEND, trash.FreedesktopBackend)
|
||||
|
||||
|
||||
def parse_mode(value):
|
||||
"""The apply's ``mode``, or None when it is not one of MODES."""
|
||||
return value if isinstance(value, str) and value in MODES else None
|
||||
|
||||
@@ -259,8 +259,7 @@ def parse_image_tag_request(data: dict):
|
||||
``filter`` (a listing query object, parse_listing_filter) may stand in for
|
||||
``targets``; the start resolves it.
|
||||
"""
|
||||
mode = data.get("mode")
|
||||
fields = _FIELDS.get(mode) if isinstance(mode, str) else None
|
||||
fields = _FIELDS.get(data.get("mode"))
|
||||
if fields is None:
|
||||
return None, bad_request('mode must be "add" or "auto"')
|
||||
fields = fields | {"filter" if "filter" in data else "targets"}
|
||||
|
||||
+34
-54
@@ -25,7 +25,6 @@ from aiohttp import web
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from .jobs import MAX_OUTCOME_ROWS, THUMBNAILS_JOB_KIND
|
||||
from .json_body import BodyTooLarge, json_error, read_json_object
|
||||
from . import gallery_listing
|
||||
from .gallery_listing import (
|
||||
DISCARDED,
|
||||
@@ -57,7 +56,6 @@ from .inspection_service import (
|
||||
VIDEO_EXTENSIONS,
|
||||
image_tags_reader,
|
||||
inspect_current_file,
|
||||
review_reader,
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -72,8 +70,6 @@ try:
|
||||
in_trash_below_roots,
|
||||
in_trash_folder,
|
||||
is_skipped_folder,
|
||||
path_separators,
|
||||
split_relative,
|
||||
)
|
||||
from ...utils.parallel import map_parallel
|
||||
from ...utils.json_strict import dumps_strict
|
||||
@@ -105,8 +101,6 @@ except ImportError:
|
||||
in_trash_below_roots,
|
||||
in_trash_folder,
|
||||
is_skipped_folder,
|
||||
path_separators,
|
||||
split_relative,
|
||||
)
|
||||
from utils.parallel import map_parallel
|
||||
from utils.json_strict import dumps_strict
|
||||
@@ -273,23 +267,18 @@ def _is_within(path, root):
|
||||
|
||||
|
||||
def _has_traversal(relative):
|
||||
"""True for absolute paths, drive-qualified paths or any ``..`` segment.
|
||||
|
||||
Segments are split at this server's separators: on POSIX ``\\`` is part
|
||||
of a name, so ``a\\..\\b`` is one name below the root (#646).
|
||||
"""
|
||||
"""True for absolute paths, drive-qualified paths or any ``..`` segment."""
|
||||
if not relative or os.path.isabs(relative) or os.path.splitdrive(relative)[0]:
|
||||
return True
|
||||
if relative[0] in path_separators():
|
||||
if relative[0] in ("/", "\\"):
|
||||
return True
|
||||
return ".." in split_relative(relative)
|
||||
return ".." in re.split(r"[\\/]+", relative)
|
||||
|
||||
|
||||
def _is_thumbnail_cache_path(relative):
|
||||
"""True when *relative* names something in a root's ``thumbnails/``
|
||||
cache (any case, this server's separators, #646): never inspected as a
|
||||
media file."""
|
||||
first = split_relative(relative.lstrip(path_separators()))[0]
|
||||
cache (any case, either separator): never inspected as a media file."""
|
||||
first = re.split(r"[\\/]+", relative.lstrip("\\/"), maxsplit=1)[0]
|
||||
return first.casefold() == "thumbnails"
|
||||
|
||||
|
||||
@@ -550,6 +539,7 @@ def _thumbnail_is_fresh(src, dst):
|
||||
MAX_GALLERY_FILES = 50_000
|
||||
MAX_BULK_LIMIT = 5_000
|
||||
MAX_JSON_BODY_BYTES = 1024 * 1024
|
||||
_READ_CHUNK = 64 * 1024
|
||||
|
||||
|
||||
# Guards the first load of an API's workspace keys (#430, _workspace_keys).
|
||||
@@ -718,17 +708,36 @@ def _workspace_cursor_key(token: str, scope: str, order: str, secret: bytes) ->
|
||||
raise ValueError("Invalid gallery cursor; refresh the gallery") from None
|
||||
|
||||
|
||||
# The shared bounded reader, at this module's own cap.
|
||||
_BodyTooLarge = BodyTooLarge
|
||||
_json_error = json_error
|
||||
class _BodyTooLarge(Exception):
|
||||
"""Raised when a request body exceeds MAX_JSON_BODY_BYTES."""
|
||||
|
||||
|
||||
def _json_error(message, status):
|
||||
return web.json_response({"success": False, "error": message}, status=status)
|
||||
|
||||
|
||||
async def _read_json_body(request):
|
||||
"""The JSON object body, or raise _BodyTooLarge past MAX_JSON_BODY_BYTES.
|
||||
"""Read a JSON object body in bounded chunks.
|
||||
|
||||
Raises ValueError when the body is not a JSON object.
|
||||
Raises _BodyTooLarge past MAX_JSON_BODY_BYTES (declared or streamed) and
|
||||
ValueError when the body is not a JSON object.
|
||||
"""
|
||||
return await read_json_object(request, MAX_JSON_BODY_BYTES)
|
||||
limit = MAX_JSON_BODY_BYTES
|
||||
if request.content_length is not None and request.content_length > limit:
|
||||
raise _BodyTooLarge()
|
||||
chunks, size = [], 0
|
||||
while True:
|
||||
chunk = await request.content.read(_READ_CHUNK)
|
||||
if not chunk:
|
||||
break
|
||||
size += len(chunk)
|
||||
if size > limit:
|
||||
raise _BodyTooLarge()
|
||||
chunks.append(chunk)
|
||||
data = json.loads(b"".join(chunks).decode("utf-8"))
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("JSON body must be an object")
|
||||
return data
|
||||
|
||||
|
||||
async def _json_body_or_error(request):
|
||||
@@ -866,7 +875,7 @@ def _favorite_root_key(root) -> str:
|
||||
|
||||
|
||||
def _source_depth(source: str) -> int:
|
||||
return len([part for part in split_relative(source) if part])
|
||||
return len([part for part in re.split(r"[\\/]+", source) if part])
|
||||
|
||||
|
||||
def deepest_source(sources, absolute_path):
|
||||
@@ -1191,10 +1200,6 @@ def _output_image_entry(
|
||||
}
|
||||
if root_scope is not None:
|
||||
entry["root_scope"] = root_scope
|
||||
if "\\" in entry["path"]:
|
||||
# #646: only a POSIX server lists a name holding a backslash (Windows
|
||||
# turns it into ``/``); the workspace accepts it only with this mark.
|
||||
entry["path_style"] = "posix"
|
||||
return entry
|
||||
|
||||
|
||||
@@ -1216,10 +1221,9 @@ def _workspace_filters(query: Mapping) -> dict:
|
||||
folded = text.casefold()
|
||||
media = query.get("media", "all")
|
||||
order = query.get("sort", "newest")
|
||||
# #646: ``\\`` separates only on Windows; on POSIX it is part of a name.
|
||||
folder = "/".join(split_relative(query.get("subfolder", "").strip()))
|
||||
folder = query.get("subfolder", "").strip().replace("\\", "/")
|
||||
# ``path``: one exact relative path (Activity opens a scan row by it, D57).
|
||||
exact = "/".join(split_relative(query.get("path", "").strip()))
|
||||
exact = query.get("path", "").strip().replace("\\", "/")
|
||||
category = query.get("category", "").strip() or None
|
||||
tags = sorted(
|
||||
{tag.strip() for tag in query.get("tags", "").split(",") if tag.strip()}
|
||||
@@ -4131,9 +4135,6 @@ class ImageRoutesMixin:
|
||||
roots[index], Path(relative).parts
|
||||
),
|
||||
recorded=recorded_output_lookup(self.db),
|
||||
review=self._inspection_review(
|
||||
index, outputs, roots[index], Path(relative).parts
|
||||
),
|
||||
)
|
||||
except CurrentFileChanged:
|
||||
return None
|
||||
@@ -4178,27 +4179,6 @@ class ImageRoutesMixin:
|
||||
locator = os.path.normcase(os.path.join(os.path.realpath(root), *parts))
|
||||
return image_tags_reader(self.db, locator, self.logger)
|
||||
|
||||
def _inspection_review(
|
||||
self, index: int, outputs: list, root: Path, parts: tuple
|
||||
) -> Callable | None:
|
||||
"""The inspector's ``review`` reader for one rooted file (#659, C4).
|
||||
|
||||
Keyed as review items are (the normcased realpath of the root joined
|
||||
with the relative path). Only an output root is a scan root; a root
|
||||
past the output folders (a LoRA root) gives None. A file without an
|
||||
item is recorded first through the review worker's path (#657 D2).
|
||||
"""
|
||||
if index >= len(outputs):
|
||||
return None
|
||||
locator = os.path.normcase(os.path.join(os.path.realpath(root), *parts))
|
||||
path = os.path.join(str(root), *parts)
|
||||
return review_reader(
|
||||
self.db,
|
||||
locator,
|
||||
self.logger,
|
||||
record=functools.partial(self.inspect_review_file, path),
|
||||
)
|
||||
|
||||
def _read_own_category(self, sources, path):
|
||||
"""One file's own category, None, or OWN_CATEGORY_UNREAD (blocking).
|
||||
|
||||
|
||||
@@ -122,67 +122,6 @@ def image_tags_reader(
|
||||
return read
|
||||
|
||||
|
||||
def review_reader(
|
||||
db: Any,
|
||||
locator: str,
|
||||
logger: Any,
|
||||
*,
|
||||
close: bool = False,
|
||||
record: Callable[[dict | None], Any] | None = None,
|
||||
) -> Callable[[int, int], dict | None]:
|
||||
"""The inspector's ``review`` reader for one file *locator* (#659, C4).
|
||||
|
||||
The returned function takes the inspection's own stable stat and answers
|
||||
the file's Needs review item at exactly that ``(size, mtime_ns)``
|
||||
(``review_item_at``): pending with its id, decided, or None. A failed
|
||||
read is None, never an error. ``close`` closes the calling thread's
|
||||
connection afterwards, for routes that close theirs (History).
|
||||
|
||||
*record*, when given, is called with the found facet when there is no
|
||||
item at that stat or a pending one (#657 addendum D2: Inspect records the
|
||||
item, or records a stale one again, through the review worker's own
|
||||
per-file path; the caller decides whether anything needs doing). The
|
||||
item is then read once more, also after a failed recording (the worker
|
||||
may have recorded it meanwhile). A recording error is logged.
|
||||
"""
|
||||
|
||||
def read(size: int, mtime_ns: int) -> dict | None:
|
||||
try:
|
||||
found = db.review_item_at(locator, size, mtime_ns)
|
||||
if record is not None and (found is None or found["state"] == "pending"):
|
||||
_record(record, found, logger)
|
||||
found = db.review_item_at(locator, size, mtime_ns)
|
||||
return found
|
||||
except Exception:
|
||||
logger.warning("Inspection review item could not be read", exc_info=True)
|
||||
return None
|
||||
finally:
|
||||
if close:
|
||||
db.model.close()
|
||||
|
||||
return read
|
||||
|
||||
|
||||
def _record(record: Callable[[dict | None], Any], found, logger: Any) -> None:
|
||||
"""Run *record* for the *found* facet; an error is logged, not raised."""
|
||||
try:
|
||||
record(found)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Inspection could not add the file to Needs review", exc_info=True
|
||||
)
|
||||
|
||||
|
||||
def _asks_review(evidence: dict, library: dict) -> bool:
|
||||
"""Whether Inspect may offer a choice: an ambiguous role, an unlinked file."""
|
||||
prompts = evidence.get("prompts") or {}
|
||||
ambiguous = any(
|
||||
isinstance(side, dict) and side.get("status") == "ambiguous"
|
||||
for side in prompts.values()
|
||||
)
|
||||
return ambiguous and isinstance(library, dict) and library.get("status") == "none"
|
||||
|
||||
|
||||
def inspect_current_file(
|
||||
path: Path,
|
||||
*,
|
||||
@@ -191,7 +130,6 @@ def inspect_current_file(
|
||||
library: dict,
|
||||
image_tags: Callable[[int, int], dict] | None = None,
|
||||
recorded: Callable[[Path], Any] | None = None,
|
||||
review: Callable[[int, int], dict | None] | None = None,
|
||||
) -> dict:
|
||||
"""Current-file evidence read between two equal stats of *path*.
|
||||
|
||||
@@ -201,9 +139,6 @@ def inspect_current_file(
|
||||
*recorded*, when given, is asked within the same stat window for what
|
||||
recorded run history knows about *path* (``RecordedOutput`` or None: the
|
||||
save node that wrote it and the texts PromptManager recorded, #386).
|
||||
*review*, when given, is called with the same stat only when a role is
|
||||
ambiguous and ``library["status"]`` is ``none``; its answer (or None) is
|
||||
returned as ``review`` (#659).
|
||||
"""
|
||||
before = _current_file_facts(path)
|
||||
try:
|
||||
@@ -238,12 +173,6 @@ def inspect_current_file(
|
||||
recorded_saver_id=run.saver_id if run is not None else None,
|
||||
recorded_texts=run.texts if run is not None else None,
|
||||
)
|
||||
if review is not None:
|
||||
facets["review"] = (
|
||||
review(before.st_size, before.st_mtime_ns)
|
||||
if _asks_review(evidence, library)
|
||||
else None
|
||||
)
|
||||
return {
|
||||
"file": {
|
||||
"observation": "current-file",
|
||||
|
||||
+2
-4
@@ -42,7 +42,6 @@ open across the switch (#249 S8).
|
||||
import asyncio
|
||||
import itertools
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
@@ -128,7 +127,7 @@ DUPLICATE_CLEANUP_GROUP_NAMES = ("removed", "kept", "errors")
|
||||
# ``records`` hold around its safety backup and write.
|
||||
PROMPT_DELETE_JOB_KIND = "prompt_delete"
|
||||
IMAGE_DELETE_JOB_KIND = "image_delete" # #480
|
||||
IMAGE_DELETE_GROUP_NAMES = ("trashed", "removed", "deleted", "not_changed", "errors")
|
||||
IMAGE_DELETE_GROUP_NAMES = ("trashed", "removed", "not_changed", "errors")
|
||||
# The System health check (py/api/system.py): a read-only ``read`` job with
|
||||
# no file outcomes, so it may run beside a scan.
|
||||
HEALTH_JOB_KIND = "health"
|
||||
@@ -161,8 +160,7 @@ def _relative_path(path) -> str:
|
||||
or PureWindowsPath(text).drive
|
||||
):
|
||||
return re.split(r"[\\/]", text)[-1]
|
||||
# #646: on POSIX a backslash is part of a name, never a separator.
|
||||
return text.replace("\\", "/") if os.sep == "\\" else text
|
||||
return text.replace("\\", "/")
|
||||
|
||||
|
||||
class JobBusy(Exception):
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
"""The one bounded reader for JSON object request bodies.
|
||||
|
||||
The body is read in chunks, so an oversized or chunked upload is refused as
|
||||
soon as it crosses the cap rather than buffered whole. ``read_json_object``
|
||||
raises; ``read_json_body`` answers with the API's ``{"success": false}``
|
||||
envelope.
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
JSON_BODY_MAX_BYTES = 1_000_000
|
||||
_READ_CHUNK = 64 * 1024
|
||||
INVALID_JSON = "Request body must be valid JSON"
|
||||
NOT_AN_OBJECT = "Request body must be a JSON object"
|
||||
|
||||
|
||||
class BodyTooLarge(Exception):
|
||||
"""The request body is longer than the reader's ``max_bytes``."""
|
||||
|
||||
|
||||
def json_error(message, status):
|
||||
return web.json_response({"success": False, "error": message}, status=status)
|
||||
|
||||
|
||||
async def read_json_object(request, max_bytes=JSON_BODY_MAX_BYTES):
|
||||
"""The request's JSON object body of at most ``max_bytes``.
|
||||
|
||||
Raises:
|
||||
BodyTooLarge: the declared or streamed body crosses ``max_bytes``.
|
||||
ValueError: the body is not UTF-8 JSON (``INVALID_JSON``) or not a
|
||||
JSON object (``NOT_AN_OBJECT``).
|
||||
"""
|
||||
declared = request.content_length
|
||||
if declared is not None and declared > max_bytes:
|
||||
raise BodyTooLarge()
|
||||
chunks, size = [], 0
|
||||
async for chunk in request.content.iter_chunked(_READ_CHUNK):
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
raise BodyTooLarge()
|
||||
chunks.append(chunk)
|
||||
try:
|
||||
data = json.loads(b"".join(chunks).decode("utf-8"))
|
||||
except ValueError: # JSONDecodeError and UnicodeDecodeError are ValueErrors
|
||||
raise ValueError(INVALID_JSON) from None
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError(NOT_AN_OBJECT)
|
||||
return data
|
||||
|
||||
|
||||
async def read_json_body(request, max_bytes=JSON_BODY_MAX_BYTES):
|
||||
"""``(data, None)``, or ``(None, response)`` with a 413 or 400 refusal."""
|
||||
try:
|
||||
return await read_json_object(request, max_bytes), None
|
||||
except BodyTooLarge:
|
||||
return None, json_error(f"Request body too large (max {max_bytes} bytes)", 413)
|
||||
except ValueError as exc:
|
||||
return None, json_error(str(exc), 400)
|
||||
+1
-3
@@ -377,9 +377,7 @@ class LibraryRoutesMixin:
|
||||
[parent["id"] for parent in result["items"]]
|
||||
)
|
||||
result["next_cursor"] = _encode(
|
||||
result.pop("next_key"),
|
||||
scope,
|
||||
name=options["sort"] in ("name", "name-desc"),
|
||||
result.pop("next_key"), scope, name=options["sort"] == "name"
|
||||
)
|
||||
return result, records
|
||||
|
||||
|
||||
@@ -516,7 +516,7 @@ class MaintenanceRoutesMixin:
|
||||
# ── apply ─────────────────────────────────────────────────────────
|
||||
|
||||
async def apply_maintenance_plan(self, request):
|
||||
from .image_delete import IMAGE_DELETE, parse_mode, permanent_delete_supported
|
||||
from .image_delete import IMAGE_DELETE, parse_mode
|
||||
|
||||
data, error = await self._read_maintenance_body(request, ("token", "mode"))
|
||||
if error is not None:
|
||||
@@ -531,12 +531,7 @@ class MaintenanceRoutesMixin:
|
||||
if plan.operation == IMAGE_DELETE:
|
||||
mode = parse_mode(data.get("mode"))
|
||||
if mode is None:
|
||||
return _invalid('mode must be "library", "trash" or "permanent"')
|
||||
if mode == "permanent" and not permanent_delete_supported():
|
||||
# The review never offers it here; refuse a direct call (#644).
|
||||
return _invalid(
|
||||
"Permanent delete is only available on Linux and BSD servers"
|
||||
)
|
||||
return _invalid('mode must be "library" or "trash"')
|
||||
elif "mode" in data:
|
||||
return _invalid("Unknown field: mode")
|
||||
store = self._maintenance_plans
|
||||
|
||||
@@ -14,10 +14,10 @@ from .prompts import bad_request
|
||||
|
||||
try:
|
||||
from ...utils.media_capture import CAPTURE_EXTENSIONS
|
||||
from ...utils.media_folders import in_trash_folder, path_separators
|
||||
from ...utils.media_folders import in_trash_folder
|
||||
except ImportError:
|
||||
from utils.media_capture import CAPTURE_EXTENSIONS
|
||||
from utils.media_folders import in_trash_folder, path_separators
|
||||
from utils.media_folders import in_trash_folder
|
||||
|
||||
MAX_TARGET_PATH = 1024
|
||||
TARGET_FIELDS = frozenset({"root_index", "root_scope", "path"})
|
||||
@@ -30,8 +30,7 @@ def media_target(data: object, *, media_message: str = TAGGING_MEDIA_MESSAGE):
|
||||
|
||||
Only the listing identity is accepted: an int root index, the root's
|
||||
64-hex scope and a bounded root-relative POSIX media path, never an
|
||||
absolute, drive-qualified, ``..`` path, or (on Windows only, #646) one
|
||||
holding a backslash (a 400 for a malformed
|
||||
absolute, drive-qualified, backslash or ``..`` path (a 400 for a malformed
|
||||
shape, a 403 for an unsafe or non-media path, carrying *media_message*, a
|
||||
404 for a path in a trash folder, #543). A link or a short-name spelling
|
||||
is refused later by the capture store's alias check.
|
||||
@@ -48,7 +47,7 @@ def media_target(data: object, *, media_message: str = TAGGING_MEDIA_MESSAGE):
|
||||
parts = relative.split("/")
|
||||
if (
|
||||
"\0" in relative
|
||||
or ("\\" in relative and "\\" in path_separators())
|
||||
or "\\" in relative
|
||||
or relative.startswith("/")
|
||||
or _has_traversal(relative)
|
||||
or any(part in ("", ".", "..") or ":" in part for part in parts)
|
||||
|
||||
@@ -672,13 +672,12 @@ def owns(root, path, location=None):
|
||||
def is_preview_text(filepath):
|
||||
"""URL text naming a preview: ``thumbnails/<...>/<name>_thumb<ext>``.
|
||||
|
||||
Text only, before any join: no backslash (on Windows; on POSIX it is part
|
||||
of a name, #646), drive or stream colon, and no
|
||||
Text only, before any join: no backslash, drive or stream colon, and no
|
||||
empty, ``.`` or ``..`` segment; ``thumbnails`` exactly as the first part
|
||||
and nowhere else among the folders; the extension, in any case, one a
|
||||
preview may carry (``X_thumb.JPG`` of an older release included).
|
||||
"""
|
||||
if not filepath or ":" in filepath or (os.sep == "\\" and "\\" in filepath):
|
||||
if not filepath or "\\" in filepath or ":" in filepath:
|
||||
return False
|
||||
parts = filepath.split("/")
|
||||
if len(parts) < 2 or parts[0] != PREVIEW_FOLDER:
|
||||
|
||||
+39
-85
@@ -64,36 +64,6 @@ def bad_request(message):
|
||||
return web.json_response({"success": False, "error": message}, status=400)
|
||||
|
||||
|
||||
def legacy_id_error(value, name):
|
||||
"""A 400 unless *value* is an id as the legacy pages send it (#662).
|
||||
|
||||
They send a number or the text they read from the page; SQLite matches
|
||||
either against an INTEGER column. A boolean, float, list or object is no
|
||||
id (``True`` would otherwise match prompt 1).
|
||||
"""
|
||||
if type(value) is int or isinstance(value, str):
|
||||
return None
|
||||
return bad_request(f"{name} must be a prompt id")
|
||||
|
||||
|
||||
def legacy_ids_error(value):
|
||||
"""A 400 unless *value* is a list of ``legacy_id_error`` ids (#662)."""
|
||||
if not isinstance(value, list):
|
||||
return bad_request("prompt_ids must be a list")
|
||||
for item in value:
|
||||
error = legacy_id_error(item, "prompt_ids")
|
||||
if error is not None:
|
||||
return error
|
||||
return None
|
||||
|
||||
|
||||
def text_field_error(data, name):
|
||||
"""A 400 when *name* is present in *data* but is not text (#662)."""
|
||||
if data.get(name) is not None and not isinstance(data[name], str):
|
||||
return bad_request(f"{name} must be text")
|
||||
return None
|
||||
|
||||
|
||||
def tags_error(tags):
|
||||
"""A 400 response when *tags* fail ``validate_tags``, else None."""
|
||||
try:
|
||||
@@ -635,15 +605,18 @@ class PromptRoutesMixin:
|
||||
{"success": False, "error": "Tag name required"}, status=400
|
||||
)
|
||||
|
||||
body, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
try:
|
||||
body = await request.json()
|
||||
except Exception:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Invalid JSON body"}, status=400
|
||||
)
|
||||
raw_name = body.get("new_name")
|
||||
if not raw_name:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "New tag name required"}, status=400
|
||||
)
|
||||
error = text_field_error(body, "new_name") or tags_error([raw_name])
|
||||
error = tags_error([raw_name])
|
||||
if error is not None:
|
||||
return error
|
||||
new_name = raw_name.strip()
|
||||
@@ -705,9 +678,12 @@ class PromptRoutesMixin:
|
||||
async def merge_tags_endpoint(self, request):
|
||||
"""Merge source tags into a target tag."""
|
||||
try:
|
||||
body, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
try:
|
||||
body = await request.json()
|
||||
except Exception:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Invalid JSON body"}, status=400
|
||||
)
|
||||
source_tags = body.get("source_tags", [])
|
||||
raw_target = body.get("target_tag")
|
||||
|
||||
@@ -721,9 +697,7 @@ class PromptRoutesMixin:
|
||||
)
|
||||
if not isinstance(source_tags, list):
|
||||
return bad_request("Source tags must be a list")
|
||||
error = text_field_error(body, "target_tag") or tags_error(
|
||||
[*source_tags, raw_target]
|
||||
)
|
||||
error = tags_error([*source_tags, raw_target])
|
||||
if error is not None:
|
||||
return error
|
||||
target_tag = raw_target.strip()
|
||||
@@ -753,15 +727,7 @@ class PromptRoutesMixin:
|
||||
async def save_prompt(self, request):
|
||||
"""Save a new prompt with metadata and duplicate detection."""
|
||||
try:
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
for field in ("text", "category", "notes"):
|
||||
if data.get(field) is not None and not isinstance(data[field], str):
|
||||
return web.json_response(
|
||||
{"success": False, "error": f"{field} must be text"},
|
||||
status=400,
|
||||
)
|
||||
data = await request.json()
|
||||
|
||||
text = (data.get("text") or "").strip()
|
||||
if not text:
|
||||
@@ -877,11 +843,7 @@ class PromptRoutesMixin:
|
||||
"""Update prompt text."""
|
||||
try:
|
||||
prompt_id = int(request.match_info["prompt_id"])
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is None:
|
||||
error = text_field_error(data, "text")
|
||||
if error is not None:
|
||||
return error
|
||||
data = await request.json()
|
||||
new_text = (data.get("text") or "").strip()
|
||||
|
||||
if not new_text:
|
||||
@@ -935,9 +897,7 @@ class PromptRoutesMixin:
|
||||
"""Update prompt rating."""
|
||||
try:
|
||||
prompt_id = int(request.match_info["prompt_id"])
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
data = await request.json()
|
||||
rating = data.get("rating")
|
||||
|
||||
try:
|
||||
@@ -977,16 +937,14 @@ class PromptRoutesMixin:
|
||||
"""Add tag to prompt."""
|
||||
try:
|
||||
prompt_id = int(request.match_info["prompt_id"])
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
data = await request.json()
|
||||
raw_tag = data.get("tag")
|
||||
|
||||
if not raw_tag:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Tag cannot be empty"}, status=400
|
||||
)
|
||||
error = text_field_error(data, "tag") or tags_error([raw_tag])
|
||||
error = tags_error([raw_tag])
|
||||
if error is not None:
|
||||
return error
|
||||
new_tag = raw_tag.strip()
|
||||
@@ -1028,9 +986,7 @@ class PromptRoutesMixin:
|
||||
async def add_tags_to_prompt(self, request):
|
||||
"""Add multiple tags to a single prompt."""
|
||||
try:
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
data = await request.json()
|
||||
prompt_id = data.get("prompt_id")
|
||||
new_tags = data.get("tags", [])
|
||||
|
||||
@@ -1038,9 +994,6 @@ class PromptRoutesMixin:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Prompt ID is required"}, status=400
|
||||
)
|
||||
error = legacy_id_error(prompt_id, "prompt_id")
|
||||
if error is not None:
|
||||
return error
|
||||
|
||||
if not new_tags or not isinstance(new_tags, list):
|
||||
return web.json_response(
|
||||
@@ -1102,11 +1055,7 @@ class PromptRoutesMixin:
|
||||
"""Remove tag from prompt."""
|
||||
try:
|
||||
prompt_id = int(request.match_info["prompt_id"])
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is None:
|
||||
error = text_field_error(data, "tag")
|
||||
if error is not None:
|
||||
return error
|
||||
data = await request.json()
|
||||
tag_to_remove = (data.get("tag") or "").strip()
|
||||
|
||||
prompt = await self._run_in_executor(self.db.get_prompt_by_id, prompt_id)
|
||||
@@ -1146,18 +1095,13 @@ class PromptRoutesMixin:
|
||||
async def bulk_delete_prompts(self, request):
|
||||
"""Bulk delete prompts."""
|
||||
try:
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
data = await request.json()
|
||||
prompt_ids = data.get("prompt_ids", [])
|
||||
|
||||
if not prompt_ids:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "No prompt IDs provided"}, status=400
|
||||
)
|
||||
error = legacy_ids_error(prompt_ids)
|
||||
if error is not None:
|
||||
return error
|
||||
|
||||
deleted_count = await self._run_in_executor(
|
||||
self.db.bulk_delete_prompts, prompt_ids
|
||||
@@ -1186,9 +1130,12 @@ class PromptRoutesMixin:
|
||||
async def bulk_add_tags(self, request):
|
||||
"""Bulk add tags to prompts."""
|
||||
try:
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
try:
|
||||
data = await request.json()
|
||||
except ValueError:
|
||||
return bad_request("Invalid JSON body")
|
||||
if not isinstance(data, dict):
|
||||
return bad_request("Expected a JSON object")
|
||||
if "expected_epoch" in data:
|
||||
return await self._bulk_library_tags(data)
|
||||
prompt_ids = data.get("prompt_ids", [])
|
||||
@@ -1201,7 +1148,7 @@ class PromptRoutesMixin:
|
||||
)
|
||||
if not isinstance(new_tags, list):
|
||||
return bad_request("Tags must be a list")
|
||||
error = legacy_ids_error(prompt_ids) or tags_error(new_tags)
|
||||
error = tags_error(new_tags)
|
||||
if error is not None:
|
||||
return error
|
||||
|
||||
@@ -1230,9 +1177,16 @@ class PromptRoutesMixin:
|
||||
async def bulk_set_category(self, request):
|
||||
"""Bulk set category for prompts."""
|
||||
try:
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
try:
|
||||
data = await request.json()
|
||||
except ValueError:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Invalid JSON body"}, status=400
|
||||
)
|
||||
if not isinstance(data, dict):
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Expected a JSON object"}, status=400
|
||||
)
|
||||
if "images_filter" in data:
|
||||
return await self._bulk_category_by_filter(data)
|
||||
if "expected_epoch" in data:
|
||||
|
||||
+8
-31
@@ -45,20 +45,16 @@ try:
|
||||
from ...database.review_decisions import ReviewCommandError
|
||||
from ...utils.media_capture import CaptureError
|
||||
from ...utils.review_capture import (
|
||||
candidate_hashes,
|
||||
captured_review,
|
||||
item_profile,
|
||||
review_evidence,
|
||||
)
|
||||
except ImportError:
|
||||
from database.library import display_title
|
||||
from database.library_commands import LibraryCommandError
|
||||
from database.review_decisions import ReviewCommandError
|
||||
from utils.media_capture import CaptureError
|
||||
from utils.review_capture import (
|
||||
candidate_hashes,
|
||||
captured_review,
|
||||
item_profile,
|
||||
)
|
||||
from utils.review_capture import captured_review, item_profile, review_evidence
|
||||
|
||||
ITEMS_URL = "/prompt_manager/review/items"
|
||||
DEFAULT_LIMIT = 40
|
||||
@@ -150,9 +146,7 @@ def format_review_target(spelled_path, locator, real_roots, *, pathmod=os.path):
|
||||
rest = rest[1:]
|
||||
parts = rest.split(sep)
|
||||
if any(
|
||||
part in ("", ".", "..") or "/" in part
|
||||
# #646: on POSIX a backslash is part of a name.
|
||||
or (sep == "\\" and "\\" in part) or ":" in part
|
||||
part in ("", ".", "..") or "/" in part or "\\" in part or ":" in part
|
||||
for part in parts
|
||||
):
|
||||
continue
|
||||
@@ -277,9 +271,6 @@ class ReviewRoutesMixin:
|
||||
"root_scope": self._gallery_root_scope(roots[index], index),
|
||||
"path": relative,
|
||||
}
|
||||
if "\\" in relative:
|
||||
# #646: the mark the Images listing sets (POSIX only).
|
||||
target["path_style"] = "posix"
|
||||
# The Images listing's media URL for the same file (formatting only).
|
||||
url = (
|
||||
"/prompt_manager/images/serve/"
|
||||
@@ -397,13 +388,12 @@ class ReviewRoutesMixin:
|
||||
"library_epoch": item["epoch"],
|
||||
**view,
|
||||
"candidates": candidates,
|
||||
"collapsed": self._review_collapsed(item),
|
||||
"dependency_fingerprint": fingerprint,
|
||||
"sha256": item["sha256"],
|
||||
"total": item["total"],
|
||||
}
|
||||
if len(json.dumps(detail).encode("utf-8")) > MAX_DETAIL_BYTES:
|
||||
detail = {**detail, "candidates": [], "collapsed": None, "limited": True}
|
||||
detail = {**detail, "candidates": [], "limited": True}
|
||||
return web.json_response(detail, headers=_NO_STORE)
|
||||
|
||||
def _review_detail(self, item_id: str):
|
||||
@@ -418,20 +408,6 @@ class ReviewRoutesMixin:
|
||||
fingerprint = self.db.review_dependency_fingerprint(image_path, aliases)
|
||||
return item, view, fingerprint, self._review_candidates(item)
|
||||
|
||||
@staticmethod
|
||||
def _review_collapsed(item: dict):
|
||||
"""#657 D3: ``{shown, total, paths}`` when the stored list keeps only
|
||||
the most used prompts of the file, else None."""
|
||||
collapsed = None if item["limited"] else item["evidence"].get("collapsed")
|
||||
if not isinstance(collapsed, dict):
|
||||
return None
|
||||
counts = {key: collapsed.get(key) for key in ("shown", "total", "paths")}
|
||||
if not all(
|
||||
isinstance(n, int) and not isinstance(n, bool) for n in counts.values()
|
||||
):
|
||||
return None
|
||||
return counts
|
||||
|
||||
def _review_candidates(self, item: dict) -> list:
|
||||
"""The detail's candidates: role texts, a label and selectability."""
|
||||
if item["limited"]:
|
||||
@@ -768,6 +744,7 @@ def _candidate_still_offered(resolution: dict, choice: str) -> bool:
|
||||
resolution = {"state": "ambiguous", "candidates": [resolution]}
|
||||
if not isinstance(resolution, dict) or resolution.get("state") != "ambiguous":
|
||||
return False
|
||||
# Every candidate the bytes offer, before any bound or collapse: a
|
||||
# reorder that changes the collapsed representatives still applies.
|
||||
return choice in candidate_hashes(resolution)
|
||||
evidence, _count, limited = review_evidence(resolution)
|
||||
if limited:
|
||||
return False
|
||||
return any(c.get("hash") == choice for c in evidence.get("candidates", ()))
|
||||
|
||||
+57
-533
@@ -6,22 +6,12 @@ final outcome is ambiguous and unlinked. The strict resolver must find it
|
||||
``graph_prompt_text``) must not link it, and no saved row may link it
|
||||
already. A file the fallback links, an exact pair the ingester stored and an
|
||||
already linked file are never queued. Neither is an ambiguous file with
|
||||
nothing to choose: none of its candidates carries a prompt
|
||||
nothing to choose: fewer than two of its candidates carry a prompt
|
||||
(``utils.review_capture.reviewable``); the scan reports it unresolved ("could
|
||||
not be traced") unless the inspection profile finds a choice in it. A file
|
||||
the default profile calls unresolved gets the same inspection-profile chance
|
||||
(#659 C1). ``review_dispatch`` is that one per-file decision.
|
||||
not be traced") unless the inspection profile finds a choice in it.
|
||||
|
||||
The monitor queues what the scan would (maintainer decision 2026-11-19,
|
||||
#659; it replaces the 2026-10-23 ruling that only scans add items). At a
|
||||
file's final unlinked outcome, after run history had its say, the monitor
|
||||
hands the path to ``queue_review_file``. One review worker thread runs
|
||||
``record_review_file`` for it: the scan's own per-file steps for that file
|
||||
(the ladder under the scan policy with the sealed history, the recorded-run
|
||||
check), read only, then ``review_dispatch``. It never links a file, and a
|
||||
file the scan would link is left to the next scan. The queue coalesces by
|
||||
path and is bounded; a file deferred by a job blocker is kept and replayed
|
||||
once no blocker remains.
|
||||
Only scans add items (maintainer ruling, 2026-10-23). The monitor's pass
|
||||
records nothing: it only removes the pending items of an output it linked.
|
||||
|
||||
The queue heals itself: a pending item whose file is now linked (by the
|
||||
fallback, a later resolution or the monitor) is removed by the next scan
|
||||
@@ -35,38 +25,25 @@ changed (``settle_linked_review_items``).
|
||||
The scan records through ``_record_scanned_review`` (best effort: a failure
|
||||
is logged and counted), which goes through
|
||||
``utils.review_capture.record_ambiguous_file`` on the API's capture store;
|
||||
the review worker calls ``record_review_file``, also for an output the
|
||||
monitor linked (its pending items leave the queue). Nothing here links a
|
||||
file.
|
||||
the monitor calls ``record_review_file`` from its worker thread after its
|
||||
own link. Nothing here links a file.
|
||||
|
||||
Recording changes records, so it follows the registry's ``records``
|
||||
admission (#289). The scan records under its own ``records`` job. The
|
||||
monitor's pass lasts one file and is not a job: it is refused while a
|
||||
``records`` or ``guarded`` job runs (``deferred``); the review worker keeps
|
||||
the path (at most ``REVIEW_DEFERRED_LIMIT``, in memory) and replays it once
|
||||
the job registry reports no blocker. Thumbnail work (the job and the
|
||||
gallery's generate and clear holds, kind ``thumbnails``) is ``guarded`` but
|
||||
only writes and removes preview files under ``thumbnails/`` and never touches
|
||||
the database, so it does not defer the recording (#249 S5 M7): a long
|
||||
rebuild no longer holds Needs review back for its whole run.
|
||||
``records`` or ``guarded`` job runs (``deferred``), and the next scan reads
|
||||
the file again. Thumbnail work (the job and the gallery's generate and clear
|
||||
holds, kind ``thumbnails``) is ``guarded`` but only writes and removes preview
|
||||
files under ``thumbnails/`` and never touches the database, so it does not
|
||||
defer the recording (#249 S5 M7): a long rebuild no longer holds Needs review
|
||||
back for its whole run.
|
||||
"""
|
||||
|
||||
import functools
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from pathlib import Path
|
||||
|
||||
from .admin import (
|
||||
SCAN_LOG_PREFIXES,
|
||||
_BatchHistory,
|
||||
_file_size,
|
||||
_plural,
|
||||
_scan_location,
|
||||
_scan_roots,
|
||||
)
|
||||
from .admin import SCAN_LOG_PREFIXES, _plural, _scan_location, _scan_roots
|
||||
from .jobs import THUMBNAILS_JOB_KIND
|
||||
|
||||
# The kind the monitor's recording checks admission under (never registered).
|
||||
@@ -79,30 +56,11 @@ NEW_OUTCOMES = ("recorded", "limited")
|
||||
|
||||
try:
|
||||
from ...utils import review_capture
|
||||
from ...utils.file_prompt import NEVER, Policy, decide_file_prompt
|
||||
from ...utils.media_capture import CaptureCapacity
|
||||
from ...utils.parallel import note_refusal, refused_at_shutdown
|
||||
from ...utils.review_capture import record_ambiguous_file
|
||||
except ImportError:
|
||||
from utils import review_capture
|
||||
from utils.file_prompt import NEVER, Policy, decide_file_prompt
|
||||
from utils.media_capture import CaptureCapacity
|
||||
from utils.parallel import note_refusal, refused_at_shutdown
|
||||
from utils.review_capture import record_ambiguous_file
|
||||
|
||||
# The review worker (#659 C5): its thread's name, the bound of paths waiting
|
||||
# for it (the oldest is dropped beyond it), the bound of paths a job blocker
|
||||
# deferred, how often it asks the job registry again while paths are
|
||||
# deferred, and how long the package teardown waits for it.
|
||||
REVIEW_WORKER_NAME = "pm-review-recorder"
|
||||
REVIEW_QUEUE_LIMIT = 4096
|
||||
REVIEW_DEFERRED_LIMIT = 1000
|
||||
REVIEW_RETRY_SECONDS = 5
|
||||
REVIEW_STOP_SECONDS = 5
|
||||
_REVIEW_WORKER_LOCK = threading.Lock()
|
||||
# Guards the untraced memory, which the scan and the review worker share.
|
||||
_UNTRACED_MEMORY_LOCK = threading.Lock()
|
||||
|
||||
# Untraced files remembered per process so a rescan of an unchanged file does
|
||||
# not run the inspection profile again (oldest forgotten first). A plain dict
|
||||
# of 16-byte digests (the locator, and its size, mtime_ns and item version):
|
||||
@@ -120,15 +78,6 @@ def _memory_key(locator: str) -> bytes:
|
||||
return _digest(locator)
|
||||
|
||||
|
||||
# Files Inspect found it cannot record (#657 review), per process: a 16-byte
|
||||
# digest of the locator, its stat and the review versions, oldest forgotten
|
||||
# first. Inspect then does not run the recording again for that state.
|
||||
MAX_INSPECT_MEMORY = 4096
|
||||
# record_review_file outcomes that record nothing for the file's current
|
||||
# state (an expected outcome, not an error): remembered by Inspect.
|
||||
UNRECORDABLE_OUTCOMES = ("skipped", "untraced")
|
||||
|
||||
|
||||
# The scan log's reason for items that leave the queue with nothing to choose.
|
||||
NOTHING_TO_CHOOSE = "nothing to choose"
|
||||
|
||||
@@ -141,7 +90,6 @@ class ReviewRecordingMixin:
|
||||
|
||||
``scanned`` is the scan's ``(metadata, inspection_resolution)``; the
|
||||
resolution is None when the scan did not run the inspection profile.
|
||||
Returns the record outcome, None when recording failed.
|
||||
"""
|
||||
try:
|
||||
outcome = self._record_review_sync(
|
||||
@@ -154,13 +102,13 @@ class ReviewRecordingMixin:
|
||||
)
|
||||
if review is not None:
|
||||
review["errors"] += 1
|
||||
return None
|
||||
if review is not None:
|
||||
if outcome in NEW_OUTCOMES:
|
||||
review["added"] += 1
|
||||
if outcome in QUEUED_OUTCOMES:
|
||||
review["queued"] += 1
|
||||
return outcome
|
||||
return
|
||||
if review is None:
|
||||
return
|
||||
if outcome in NEW_OUTCOMES:
|
||||
review["added"] += 1
|
||||
if outcome in QUEUED_OUTCOMES:
|
||||
review["queued"] += 1
|
||||
|
||||
def _record_review_sync(
|
||||
self, media_file, roots, review=None, inspection=False, scanned=None
|
||||
@@ -189,55 +137,14 @@ class ReviewRecordingMixin:
|
||||
self._settle_untraced_reviews([media_file], roots, review)
|
||||
return outcome
|
||||
|
||||
def review_dispatch(self, media_file, roots, decision, outcome, review=None):
|
||||
"""The one per-file Needs review decision (#659): ``(scan_status,
|
||||
record_outcome)`` for a file the caller stored nothing for in this
|
||||
pass.
|
||||
|
||||
``decision`` is the scan-policy ladder's ``Decision`` (None: nothing
|
||||
to decide) and ``outcome`` the file's scan status. An ambiguous file
|
||||
with a choice is recorded unless a saved row links it
|
||||
(``unchanged``). An untraced file, or one the default profile calls
|
||||
unresolved that has a prompt graph, gets the inspection profile's
|
||||
choice and the saver anchor (``_untraced_scan_outcome``). Any other
|
||||
file keeps its status and records nothing (``record_outcome`` None).
|
||||
The scan uses ``scan_status``, the review worker ``record_outcome``.
|
||||
"""
|
||||
if decision is None:
|
||||
return outcome, None
|
||||
if decision.review == "ambiguous" and outcome == "ambiguous":
|
||||
if self._review_file_linked(media_file, roots):
|
||||
return "unchanged", None # already linked: not a review case
|
||||
# The records name the item versions that count; the saver
|
||||
# anchor (#390) is checked on the captured bytes.
|
||||
scanned = (decision.canonical, None)
|
||||
recorded = self._record_scanned_review(
|
||||
media_file, roots, review, scanned=scanned
|
||||
)
|
||||
return outcome, recorded
|
||||
untraced = decision.review == "untraced"
|
||||
unreadable = (
|
||||
decision.review is None
|
||||
and decision.default_unresolved
|
||||
and bool(decision.canonical.get("prompt"))
|
||||
)
|
||||
if outcome == "unresolved" and (untraced or unreadable):
|
||||
# The inspection profile may still offer a choice (queued for
|
||||
# review, never linked).
|
||||
return self._untraced_scan_outcome(
|
||||
media_file, roots, decision.canonical, review
|
||||
)
|
||||
return outcome, None
|
||||
|
||||
def _untraced_scan_outcome(self, media_file, roots, canonical, review=None):
|
||||
"""``(scan_status, record_outcome)`` of an unlinked file the default
|
||||
profile left ambiguous without a choice, or unresolved (blocking).
|
||||
"""The scan status of an unlinked file the default profile left
|
||||
ambiguous without a choice (blocking).
|
||||
|
||||
``ambiguous`` when the inspection profile offers a choice: the file is
|
||||
recorded for review from that profile (never linked), or ``unchanged``
|
||||
when a saved row links it already. Otherwise ``unresolved``
|
||||
(``untraced``), and its pending items without a choice leave the
|
||||
queue. The profile runs at
|
||||
when a saved row links it already. Otherwise ``unresolved``, and its
|
||||
pending items without a choice leave the queue. The profile runs at
|
||||
most once per file state: not for bytes already queued (or decided)
|
||||
at the file's current size and ``mtime_ns`` under the version that
|
||||
its records depend on, and not again for a state it already found
|
||||
@@ -253,17 +160,15 @@ class ReviewRecordingMixin:
|
||||
)
|
||||
if review is not None:
|
||||
review["errors"] += 1
|
||||
return "unresolved", None
|
||||
return "unresolved"
|
||||
if choice is None:
|
||||
self._settle_untraced_reviews([media_file], roots, review)
|
||||
self._settle_stale_reviews(media_file, roots, canonical, review)
|
||||
return "unresolved", "untraced"
|
||||
return "unresolved"
|
||||
if self._review_file_linked(media_file, roots):
|
||||
return "unchanged", None
|
||||
recorded = self._record_scanned_review(
|
||||
media_file, roots, review, scanned=choice
|
||||
)
|
||||
return "ambiguous", recorded
|
||||
return "unchanged"
|
||||
self._record_scanned_review(media_file, roots, review, scanned=choice)
|
||||
return "ambiguous"
|
||||
|
||||
def _inspection_choice(self, media_file, roots, canonical):
|
||||
"""``(canonical, resolution_or_None)`` when the file offers a choice.
|
||||
@@ -293,21 +198,17 @@ class ReviewRecordingMixin:
|
||||
return canonical, None
|
||||
memory = self._untraced_memory()
|
||||
key = _memory_key(locator)
|
||||
# The scan and the review worker (#659) share the memory: every
|
||||
# read and change holds its lock (the resolve below does not).
|
||||
with _UNTRACED_MEMORY_LOCK:
|
||||
if state is not None and memory.get(key) == state:
|
||||
return None
|
||||
if state is not None and memory.get(key) == state:
|
||||
return None
|
||||
resolution = review_capture.inspection_choice(canonical, media_file.name)
|
||||
with _UNTRACED_MEMORY_LOCK:
|
||||
if resolution is not None:
|
||||
memory.pop(key, None)
|
||||
return canonical, resolution
|
||||
if state is not None:
|
||||
memory.pop(key, None) # re-inserted last: the newest state
|
||||
memory[key] = state
|
||||
while len(memory) > MAX_UNTRACED_MEMORY:
|
||||
del memory[next(iter(memory))]
|
||||
if resolution is not None:
|
||||
memory.pop(key, None)
|
||||
return canonical, resolution
|
||||
if state is not None:
|
||||
memory.pop(key, None) # re-inserted last: the newest state
|
||||
memory[key] = state
|
||||
while len(memory) > MAX_UNTRACED_MEMORY:
|
||||
del memory[next(iter(memory))]
|
||||
return None
|
||||
|
||||
def _settle_stale_reviews(self, media_file, roots, canonical, review=None):
|
||||
@@ -347,11 +248,10 @@ class ReviewRecordingMixin:
|
||||
return removed
|
||||
|
||||
def _untraced_memory(self):
|
||||
with _UNTRACED_MEMORY_LOCK:
|
||||
memory = getattr(self, "_untraced_inspections", None)
|
||||
if memory is None:
|
||||
memory = self._untraced_inspections = {}
|
||||
return memory
|
||||
memory = getattr(self, "_untraced_inspections", None)
|
||||
if memory is None:
|
||||
memory = self._untraced_inspections = {}
|
||||
return memory
|
||||
|
||||
@staticmethod
|
||||
def _review_location(media_file, roots, real_roots=None):
|
||||
@@ -410,8 +310,8 @@ class ReviewRecordingMixin:
|
||||
def _settle_untraced_reviews(self, media_files, roots, review=None):
|
||||
"""Remove the pending items without a choice of untraced ``media_files``.
|
||||
|
||||
``media_files`` are files found ambiguous without a candidate that
|
||||
carries a prompt. Blocking; best effort like the linked
|
||||
``media_files`` are files found ambiguous with fewer than two
|
||||
candidates that carry a prompt. Blocking; best effort like the linked
|
||||
settle (a failure is logged and counted in ``review["errors"]``).
|
||||
Returns how many items left.
|
||||
"""
|
||||
@@ -435,23 +335,18 @@ class ReviewRecordingMixin:
|
||||
return removed
|
||||
|
||||
def record_review_file(self, image_path):
|
||||
"""Apply the Needs review rule to one monitor output (review worker).
|
||||
"""Apply the Needs review rule to one monitor output (its worker thread).
|
||||
|
||||
The monitor queues what the scan would (maintainer decision
|
||||
2026-11-19, #659): it hands a file over at its final unlinked
|
||||
outcome, after run history had its say, and after each ambiguous
|
||||
output it links. Maps ``image_path`` to the gallery root that lists
|
||||
it; a file under no current root is ``skipped``. A linked file's
|
||||
pending items are removed and the answer is ``linked``. Any other
|
||||
file runs the scan's own per-file steps, read only
|
||||
(``_review_unlinked_file``): a file the scan would link, or that
|
||||
does not save, is ``skipped`` (the next scan links it); otherwise
|
||||
the answer is ``review_dispatch``'s record outcome (``recorded``,
|
||||
``duplicate``, ``decided``, ``untraced``, ``limited``) or ``skipped``.
|
||||
While a job runs that a ``records`` job may not run beside, other
|
||||
than thumbnail work (``PREVIEW_ONLY_KINDS``), nothing is written and
|
||||
the answer is ``deferred`` (the worker replays it). Errors propagate:
|
||||
the worker logs them and the monitor keeps its link.
|
||||
Only scans add items (maintainer ruling, 2026-10-23): the monitor
|
||||
only clears the items of outputs it links. Maps ``image_path`` to the
|
||||
gallery root that lists it; a file under no current root is
|
||||
``skipped``. A linked file's pending items are removed and the answer
|
||||
is ``linked``. Any other file is ``skipped``: nothing is captured or
|
||||
recorded, and the next scan reads it. While a job runs that a
|
||||
``records`` job may not run beside, other than thumbnail work
|
||||
(``PREVIEW_ONLY_KINDS``), nothing is written and the answer is
|
||||
``deferred``. Errors propagate: the monitor logs them and keeps its
|
||||
link.
|
||||
"""
|
||||
busy = self._jobs.blocker(
|
||||
REVIEW_RECORDING_KIND, admission="records", compatible=PREVIEW_ONLY_KINDS
|
||||
@@ -471,166 +366,7 @@ class ReviewRecordingMixin:
|
||||
if self._review_file_linked(located, roots):
|
||||
self._settle_scanned_reviews([located], roots)
|
||||
return "linked"
|
||||
return self._review_unlinked_file(located, roots)
|
||||
|
||||
def _review_unlinked_file(self, media_file, roots):
|
||||
"""The scan's per-file steps for one unlinked file, read only.
|
||||
|
||||
The metadata read the scan uses, the ladder under ``Policy.SCAN``
|
||||
with the file's recorded history, then the recorded-run check; a
|
||||
file any step would link (or whose prompt does not save) is
|
||||
``skipped``. Otherwise ``review_dispatch`` decides, and its record
|
||||
outcome is the answer (``skipped`` when it records nothing).
|
||||
"""
|
||||
path = str(media_file)
|
||||
metadata = self._extract_comfyui_metadata(path)
|
||||
history = _BatchHistory(self, [media_file])
|
||||
decision = decide_file_prompt(
|
||||
metadata,
|
||||
file_name=media_file.name,
|
||||
file_size=functools.partial(_file_size, media_file),
|
||||
in_output=False, # only the monitor policy reads it
|
||||
lookup=functools.partial(history.recorded, path),
|
||||
policy=Policy.SCAN,
|
||||
)
|
||||
if decision.kind != NEVER:
|
||||
return "skipped" # it saves nothing, or the next scan links it
|
||||
if decision.try_recorded_run and history.get(path) is not None:
|
||||
return "skipped" # the scan's recorded-run step links it
|
||||
_status, recorded = self.review_dispatch(
|
||||
media_file, roots, decision, decision.unlinked_status
|
||||
)
|
||||
return recorded or "skipped"
|
||||
|
||||
def inspect_review_file(self, image_path, found=None):
|
||||
"""Inspect's recording of one file (#657 addendum D2, blocking).
|
||||
|
||||
``found`` is the file's ``review`` facet at the inspected stat (None
|
||||
or a pending item). A pending item of a current item version needs
|
||||
nothing (``current``); one of an older version is recorded again, so
|
||||
the new item supersedes it. Otherwise ``record_review_file`` runs,
|
||||
unless Inspect already found this state unrecordable (``skipped`` or
|
||||
``untraced``, remembered in ``MAX_INSPECT_MEMORY`` digests:
|
||||
``remembered``). A busy capture store (the worker copying a fresh
|
||||
output) is expected: logged at debug level, ``busy``.
|
||||
"""
|
||||
if found is not None and self._review_item_current(
|
||||
found["item_id"], image_path
|
||||
):
|
||||
return "current"
|
||||
key = self._inspect_memory_key(image_path)
|
||||
memory = self._inspect_memory()
|
||||
with _UNTRACED_MEMORY_LOCK:
|
||||
if key is not None and key in memory:
|
||||
return "remembered"
|
||||
try:
|
||||
outcome = self.record_review_file(image_path)
|
||||
except CaptureCapacity:
|
||||
self.logger.debug(
|
||||
"Inspect left Needs review to the worker: captures are busy"
|
||||
)
|
||||
return "busy"
|
||||
if key is not None and outcome in UNRECORDABLE_OUTCOMES:
|
||||
with _UNTRACED_MEMORY_LOCK:
|
||||
memory.pop(key, None)
|
||||
memory[key] = True
|
||||
while len(memory) > MAX_INSPECT_MEMORY:
|
||||
del memory[next(iter(memory))]
|
||||
return outcome
|
||||
|
||||
def _inspected_metadata(self, image_path):
|
||||
"""The file's metadata with its prompt graph decoded (or None)."""
|
||||
metadata = self._extract_comfyui_metadata(str(image_path)) or {}
|
||||
prompt = metadata.get("prompt")
|
||||
if isinstance(prompt, str):
|
||||
try:
|
||||
metadata = {**metadata, "prompt": json.loads(prompt)}
|
||||
except (ValueError, TypeError, RecursionError):
|
||||
return None
|
||||
return metadata if isinstance(metadata.get("prompt"), dict) else None
|
||||
|
||||
def _review_item_current(self, item_id, image_path):
|
||||
"""True when the item's version is one the file is queued under now
|
||||
(the file's metadata is read only for a non-default version)."""
|
||||
item = self.db.review_item(item_id)
|
||||
if item is None:
|
||||
return False
|
||||
version = item.get("resolver_version")
|
||||
if version == review_capture.default_item_version():
|
||||
return True
|
||||
metadata = self._inspected_metadata(image_path)
|
||||
return metadata is not None and version in review_capture.item_versions(
|
||||
metadata
|
||||
)
|
||||
|
||||
def _inspect_memory_key(self, image_path):
|
||||
"""The digest of the file's locator, stat and review versions."""
|
||||
full = os.path.abspath(str(image_path))
|
||||
located = os.path.join(
|
||||
os.path.realpath(os.path.dirname(full)), os.path.basename(full)
|
||||
)
|
||||
try:
|
||||
facts = os.lstat(located)
|
||||
except OSError:
|
||||
return None
|
||||
return _digest(
|
||||
f"{os.path.normcase(located)}:{facts.st_size}:{facts.st_mtime_ns}:"
|
||||
f"{review_capture.default_item_version()}:"
|
||||
f"{review_capture.semantics_version()}"
|
||||
)
|
||||
|
||||
def _inspect_memory(self):
|
||||
with _UNTRACED_MEMORY_LOCK:
|
||||
memory = getattr(self, "_inspect_unrecordable", None)
|
||||
if memory is None:
|
||||
memory = self._inspect_unrecordable = {}
|
||||
return memory
|
||||
|
||||
def _review_worker(self):
|
||||
"""The API's one review worker, made on first use (no thread yet)."""
|
||||
worker = getattr(self, "_review_recorder_worker", None)
|
||||
if worker is None:
|
||||
with _REVIEW_WORKER_LOCK:
|
||||
worker = getattr(self, "_review_recorder_worker", None)
|
||||
if worker is None:
|
||||
worker = ReviewWorker(
|
||||
# Late-bound on purpose: a record_review_file
|
||||
# replaced after the worker exists still runs.
|
||||
lambda path: self.record_review_file(path),
|
||||
self._review_admitted,
|
||||
self.logger,
|
||||
)
|
||||
self._review_recorder_worker = worker
|
||||
return worker
|
||||
|
||||
def _review_admitted(self):
|
||||
"""True while no job blocks Needs review writes (any thread)."""
|
||||
busy = self._jobs.blocker(
|
||||
REVIEW_RECORDING_KIND, admission="records", compatible=PREVIEW_ONLY_KINDS
|
||||
)
|
||||
return busy is None
|
||||
|
||||
def queue_review_file(self, image_path):
|
||||
"""Queue ``image_path`` for the review worker; never blocks.
|
||||
|
||||
The monitor's review recorder (#659). Returns ``queued``, or
|
||||
``stopped`` once the worker was stopped (the next scan reads it).
|
||||
"""
|
||||
return self._review_worker().queue(str(image_path))
|
||||
|
||||
def review_worker_started(self):
|
||||
"""Whether the review worker's thread was ever started."""
|
||||
worker = getattr(self, "_review_recorder_worker", None)
|
||||
return worker is not None and worker.started
|
||||
|
||||
def stop_review_worker(self, timeout=REVIEW_STOP_SECONDS):
|
||||
"""Stop the review worker for good and join it within ``timeout``.
|
||||
|
||||
Queued and deferred paths are dropped (their count is logged; the
|
||||
next scan covers them) and later ``queue_review_file`` calls are
|
||||
refused. True when no worker thread is left running.
|
||||
"""
|
||||
return self._review_worker().stop(timeout)
|
||||
return "skipped"
|
||||
|
||||
@staticmethod
|
||||
def _log_review_items(job, review):
|
||||
@@ -662,215 +398,3 @@ class ReviewRecordingMixin:
|
||||
f"{_plural(review['errors'], 'image')} could not be added to "
|
||||
"Needs review"
|
||||
)
|
||||
|
||||
|
||||
class ReviewWorker:
|
||||
"""One daemon thread that runs ``record(path)`` for queued paths (#659 C5).
|
||||
|
||||
The queue coalesces by path (a path queued again while it waits keeps
|
||||
its place; one queued while it runs runs once more afterwards) and holds
|
||||
at most ``REVIEW_QUEUE_LIMIT`` paths, dropping the oldest with a log
|
||||
line, so ``queue`` never blocks the monitor's image worker. One thread
|
||||
means two recordings of one path never run at once. A ``deferred``
|
||||
answer keeps the path in a bounded, insertion-ordered set; the thread
|
||||
waits on its queue with a ``REVIEW_RETRY_SECONDS`` timeout and, on each
|
||||
wake, replays that set once ``admitted()`` (no job blocker) says so.
|
||||
Everything lives in memory: a restart drops it and the next scan covers
|
||||
the files. A failure of ``record`` is logged and the worker goes on.
|
||||
"""
|
||||
|
||||
def __init__(self, record, admitted, logger):
|
||||
self._record = record
|
||||
self._admitted = admitted
|
||||
self._logger = logger
|
||||
self._changed = threading.Condition()
|
||||
self._pending = OrderedDict() # key -> path
|
||||
self._deferred = OrderedDict() # key -> path
|
||||
self._in_hand = None
|
||||
self._thread = None
|
||||
self._ever_started = False
|
||||
self._stopped = False
|
||||
|
||||
@property
|
||||
def started(self):
|
||||
return self._ever_started
|
||||
|
||||
@staticmethod
|
||||
def _key(path):
|
||||
return os.path.normcase(os.path.abspath(path))
|
||||
|
||||
def queue(self, path):
|
||||
"""Queue ``path``: ``queued``, or ``stopped`` after ``stop``."""
|
||||
key = self._key(path)
|
||||
with self._changed:
|
||||
if self._stopped:
|
||||
return "stopped"
|
||||
if key in self._pending:
|
||||
return "queued"
|
||||
self._pending[key] = path
|
||||
evicted = None
|
||||
if len(self._pending) > REVIEW_QUEUE_LIMIT:
|
||||
evicted = self._pending.popitem(last=False)[1]
|
||||
if self._thread is None and not self._start():
|
||||
self._pending.pop(key, None)
|
||||
return "stopped"
|
||||
self._changed.notify_all()
|
||||
if evicted is not None:
|
||||
self._logger.info(
|
||||
"Too many outputs wait for Needs review; "
|
||||
f"{os.path.basename(evicted)} is left to the next scan"
|
||||
)
|
||||
return "queued"
|
||||
|
||||
def _start(self):
|
||||
"""Start the thread (``_changed`` held); False when refused at exit."""
|
||||
thread = threading.Thread(
|
||||
target=self._run, name=REVIEW_WORKER_NAME, daemon=True
|
||||
)
|
||||
try:
|
||||
thread.start()
|
||||
except RuntimeError as error:
|
||||
if not refused_at_shutdown(error):
|
||||
raise
|
||||
note_refusal(self._logger, "The review worker")
|
||||
self._stopped = True
|
||||
return False
|
||||
self._thread = thread
|
||||
self._ever_started = True
|
||||
return True
|
||||
|
||||
def pending_count(self):
|
||||
with self._changed:
|
||||
return len(self._pending)
|
||||
|
||||
def deferred_count(self):
|
||||
with self._changed:
|
||||
return len(self._deferred)
|
||||
|
||||
def deferred_paths(self):
|
||||
with self._changed:
|
||||
return list(self._deferred.values())
|
||||
|
||||
def wait_idle(self, timeout):
|
||||
"""True once no path waits or is in hand (deferred ones may stay)."""
|
||||
with self._changed:
|
||||
return self._changed.wait_for(
|
||||
lambda: not self._pending and self._in_hand is None, timeout
|
||||
)
|
||||
|
||||
def _run(self):
|
||||
"""The thread body: an unexpected error ends it with a log line and
|
||||
clears the handle, so the next queued output starts a new thread
|
||||
(the paths still waiting stay queued)."""
|
||||
try:
|
||||
self._loop()
|
||||
except Exception:
|
||||
self._logger.error(
|
||||
"The review worker stopped on an unexpected error; "
|
||||
"the next output starts it again",
|
||||
exc_info=True,
|
||||
)
|
||||
finally:
|
||||
with self._changed:
|
||||
if self._thread is threading.current_thread():
|
||||
self._thread = None
|
||||
self._in_hand = None
|
||||
self._changed.notify_all()
|
||||
|
||||
def _loop(self):
|
||||
while True:
|
||||
with self._changed:
|
||||
path = self._next_locked()
|
||||
if path is None:
|
||||
return
|
||||
self._in_hand = path
|
||||
outcome = None
|
||||
try:
|
||||
outcome = self._run_one(path)
|
||||
finally:
|
||||
with self._changed:
|
||||
self._in_hand = None
|
||||
if outcome == "deferred":
|
||||
dropped = self._defer_locked(path)
|
||||
else:
|
||||
dropped = None
|
||||
self._changed.notify_all()
|
||||
if dropped is not None:
|
||||
self._logger.info(
|
||||
"Too many outputs wait for a job to end before Needs review; "
|
||||
f"{os.path.basename(dropped)} is left to the next scan"
|
||||
)
|
||||
|
||||
def _next_locked(self):
|
||||
"""The next path to record, waiting for one; None once stopped."""
|
||||
while not self._stopped:
|
||||
if self._deferred and self._replay_admitted():
|
||||
for key, path in self._deferred.items():
|
||||
self._pending.setdefault(key, path)
|
||||
self._deferred.clear()
|
||||
if self._pending:
|
||||
return self._pending.popitem(last=False)[1]
|
||||
self._changed.notify_all() # idle: ``wait_idle`` may return
|
||||
# Deferred paths: ask the job registry again after a while
|
||||
self._changed.wait(REVIEW_RETRY_SECONDS if self._deferred else None)
|
||||
return None
|
||||
|
||||
def _replay_admitted(self):
|
||||
try:
|
||||
return bool(self._admitted())
|
||||
except Exception:
|
||||
self._logger.debug("Job registry check failed", exc_info=True)
|
||||
return False
|
||||
|
||||
def _run_one(self, path):
|
||||
try:
|
||||
outcome = self._record(path)
|
||||
except Exception:
|
||||
self._logger.warning(
|
||||
f"{os.path.basename(path)} could not be added to Needs review",
|
||||
exc_info=True,
|
||||
)
|
||||
return None
|
||||
self._logger.debug(f"Needs review {outcome}: {os.path.basename(path)}")
|
||||
return outcome
|
||||
|
||||
def _defer_locked(self, path):
|
||||
"""Keep a deferred path; returns the path dropped at the cap."""
|
||||
if self._stopped:
|
||||
return None
|
||||
key = self._key(path)
|
||||
self._deferred.pop(key, None)
|
||||
self._deferred[key] = path
|
||||
if len(self._deferred) > REVIEW_DEFERRED_LIMIT:
|
||||
return self._deferred.popitem(last=False)[1]
|
||||
return None
|
||||
|
||||
def stop(self, timeout):
|
||||
"""Stop for good, drop waiting paths, join within ``timeout``.
|
||||
|
||||
True when no thread is left running. Called on the worker's own
|
||||
thread, it only signals (False).
|
||||
"""
|
||||
with self._changed:
|
||||
self._stopped = True
|
||||
dropped = len(self._pending) + len(self._deferred)
|
||||
self._pending.clear()
|
||||
self._deferred.clear()
|
||||
thread = self._thread
|
||||
self._changed.notify_all()
|
||||
if dropped:
|
||||
self._logger.info(
|
||||
f"{_plural(dropped, 'output')} left for the next scan's Needs review"
|
||||
)
|
||||
if thread is None:
|
||||
return True
|
||||
if thread is threading.current_thread():
|
||||
return False
|
||||
thread.join(max(0.0, timeout))
|
||||
if thread.is_alive():
|
||||
self._logger.warning(
|
||||
f"review worker still running after {timeout} s; "
|
||||
"it stops after the file in hand"
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -205,8 +205,7 @@ def _is_preview_request(filepath):
|
||||
take as an anchor: a backslash, a drive or stream colon, and empty, ``.``
|
||||
or ``..`` segments (so a leading ``/`` and ``//server/share`` too).
|
||||
"""
|
||||
# #646: a backslash is a separator only on Windows.
|
||||
if ":" in filepath or (os.sep == "\\" and "\\" in filepath):
|
||||
if "\\" in filepath or ":" in filepath:
|
||||
return False
|
||||
parts = filepath.split("/")
|
||||
if len(parts) < 2 or parts[0] != "thumbnails":
|
||||
@@ -388,6 +387,7 @@ class AutoThumbnailer:
|
||||
self._worker_running = False
|
||||
self._closed = False
|
||||
self._busy = False
|
||||
self._batch = 0
|
||||
|
||||
@property
|
||||
def failure_count(self):
|
||||
@@ -547,6 +547,7 @@ class AutoThumbnailer:
|
||||
with self._changed:
|
||||
self._worker_running = False
|
||||
self._busy = False
|
||||
self._batch = 0
|
||||
self._changed.notify_all()
|
||||
|
||||
def _drain(self):
|
||||
@@ -561,6 +562,7 @@ class AutoThumbnailer:
|
||||
workers = max(1, int(self._workers() or 1))
|
||||
take = min(len(self._queue), workers)
|
||||
batch = [self._queue.popleft() for _ in range(take)]
|
||||
self._batch = len(batch)
|
||||
self._changed.notify_all()
|
||||
try:
|
||||
# The job pool's size is the setting; a smaller batch uses
|
||||
@@ -568,6 +570,7 @@ class AutoThumbnailer:
|
||||
map_parallel(self._write_queued, batch, workers)
|
||||
finally:
|
||||
with self._changed:
|
||||
self._batch = 0
|
||||
for key, *_rest in batch:
|
||||
self._queued.discard(key)
|
||||
|
||||
@@ -629,6 +632,10 @@ class AutoThumbnailer:
|
||||
"""True once the worker has nothing queued or in hand."""
|
||||
return self._wait_for(lambda: not self._busy, timeout)
|
||||
|
||||
def wait_batch(self, size, timeout=None):
|
||||
"""True once the worker holds a batch of *size* files."""
|
||||
return self._wait_for(lambda: self._batch == size, timeout)
|
||||
|
||||
|
||||
class _PreviewGate:
|
||||
"""Admission of view requests on the event loop (#249 I2).
|
||||
@@ -960,6 +967,15 @@ class AutoThumbnailMixin:
|
||||
return "queued"
|
||||
return "skipped"
|
||||
|
||||
def _capture_target(self, image_path):
|
||||
"""``(src, dst, is_video)`` of a new output's preview now, or None."""
|
||||
located = self._capture_source(image_path)
|
||||
if located is None:
|
||||
return None
|
||||
src, root, rel, is_video = located
|
||||
dst = DeferredPreview(root, rel).resolve()
|
||||
return None if dst is None else (src, dst, is_video)
|
||||
|
||||
def _capture_source(self, image_path):
|
||||
"""``(src, root, rel, is_video)`` of a media file under a current
|
||||
root (not a preview, a link or in a trash folder), or None."""
|
||||
|
||||
@@ -90,7 +90,7 @@ class ThumbnailOptions:
|
||||
}
|
||||
|
||||
|
||||
def thumbnail_options(raw):
|
||||
def thumbnail_options(raw, *, from_query=False):
|
||||
"""``(ThumbnailOptions, None)`` from a body or query, or ``(None, message)``.
|
||||
|
||||
An absent mode is ``missing``; the settings are the server's now.
|
||||
@@ -136,7 +136,7 @@ class ThumbnailJobsMixin:
|
||||
``mode=prune`` lists the removed sources' thumbnails (#320)."""
|
||||
if request.query.get("mode") == "prune":
|
||||
return await self.get_prune_plan()
|
||||
options, error = thumbnail_options(request.query)
|
||||
options, error = thumbnail_options(request.query, from_query=True)
|
||||
if error:
|
||||
return _invalid(error)
|
||||
try:
|
||||
|
||||
@@ -78,6 +78,27 @@ def _canonical_path(path: str) -> str:
|
||||
return os.path.normcase(os.path.realpath(path))
|
||||
|
||||
|
||||
def write_private_json(path: str, data: Any) -> None:
|
||||
"""Write ``data`` as JSON to ``path`` readable by the current user only.
|
||||
|
||||
config.json can hold an API key (integrations.lora_manager), so it is
|
||||
created with mode 0600 and, on POSIX, an existing more open file is
|
||||
tightened too. Windows has no POSIX modes; there the chmod is a best
|
||||
effort that only affects the read-only bit. Parent directories are
|
||||
created as needed. Raises OSError when the file cannot be written.
|
||||
"""
|
||||
import json
|
||||
|
||||
parent_dir = os.path.dirname(path)
|
||||
if parent_dir:
|
||||
os.makedirs(parent_dir, exist_ok=True)
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
if os.name == "posix":
|
||||
os.chmod(path, 0o600)
|
||||
|
||||
|
||||
def _lexical_path(path: str) -> str:
|
||||
"""``path`` normalised for comparison without touching the filesystem.
|
||||
|
||||
@@ -696,6 +717,12 @@ class AutotagConfig:
|
||||
def suggestion_limit(cls) -> int:
|
||||
return cls.SUGGESTION_LIMIT
|
||||
|
||||
@staticmethod
|
||||
def valid_suggestion_limit(value: Any) -> bool:
|
||||
return (
|
||||
type(value) is int and 1 <= value <= MAX_SUGGESTION_LIMIT
|
||||
) # bool, float and str are rejected
|
||||
|
||||
@classmethod
|
||||
def all_instructions(cls) -> List[Dict[str, str]]:
|
||||
"""Built-in first, then the saved entries (copies)."""
|
||||
@@ -1036,6 +1063,35 @@ class PromptManagerConfig:
|
||||
else:
|
||||
config_logger.info(f"Config file not found: {config_path}, using defaults")
|
||||
|
||||
@classmethod
|
||||
def save_to_file(cls, config_path: Optional[str] = None):
|
||||
"""Save the current configuration to a JSON file.
|
||||
|
||||
Serializes the complete configuration (including gallery settings) to
|
||||
a JSON file. Creates the directory structure if it doesn't exist.
|
||||
|
||||
Args:
|
||||
config_path (str): Path where the JSON configuration file should be saved.
|
||||
Parent directories will be created if they don't exist.
|
||||
Defaults to :meth:`get_config_path`.
|
||||
|
||||
Raises:
|
||||
The method handles all exceptions internally and logs errors rather
|
||||
than propagating them.
|
||||
|
||||
Example:
|
||||
PromptManagerConfig.save_to_file('backup_config.json')
|
||||
PromptManagerConfig.save_to_file('/etc/comfyui/prompt_manager.json')
|
||||
"""
|
||||
if config_path is None:
|
||||
config_path = cls.get_config_path()
|
||||
|
||||
try:
|
||||
write_private_json(config_path, cls.get_config())
|
||||
config_logger.info(f"Saved configuration to {config_path}")
|
||||
except Exception as e:
|
||||
config_logger.error(f"Error saving config to {config_path}: {e}")
|
||||
|
||||
@classmethod
|
||||
def update_config(cls, new_config: Dict[str, Any]):
|
||||
"""Update configuration attributes from a dictionary.
|
||||
|
||||
+2
-3
@@ -1,11 +1,10 @@
|
||||
[project]
|
||||
name = "promptmanager"
|
||||
description = "A powerful ComfyUI custom node that extends the standard text encoder with persistent prompt storage, advanced search capabilities, and an automatic image gallery system using SQLite."
|
||||
version = "3.7.2"
|
||||
version = "3.5.0"
|
||||
license = {file = "LICENSE"}
|
||||
requires-python = ">=3.12"
|
||||
dependencies = ["watchdog>=2.1.0", "Pillow>=10.1.0"]
|
||||
classifiers = ["Operating System :: OS Independent"]
|
||||
|
||||
[build-system]
|
||||
requires = ["setuptools>=84.2.1"]
|
||||
@@ -18,7 +17,7 @@ Repository = "https://github.com/ComfyAssets/ComfyUI_PromptManager"
|
||||
[tool.comfy]
|
||||
PublisherId = "kiko9"
|
||||
DisplayName = "ComfyUI_PromptManager"
|
||||
Icon = "https://raw.githubusercontent.com/ComfyAssets/ComfyUI_PromptManager/main/assets/brand/icon-256.png"
|
||||
Icon = "https://avatars.githubusercontent.com/u/213204677?s=200"
|
||||
|
||||
[tool.black]
|
||||
line-length = 88
|
||||
|
||||
@@ -4,7 +4,7 @@ Pillow>=10.1.0
|
||||
aiohttp>=3.11.8
|
||||
|
||||
# Tests and coverage
|
||||
coverage>=7.17.2
|
||||
coverage>=7.17.0
|
||||
numpy>=1.25.0 # WD14 engine tests
|
||||
|
||||
# Code quality
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.5 MiB |
@@ -1,121 +0,0 @@
|
||||
// #659 (design Part 5): Inspect's Choose prompt. A queued ambiguous file (tests/browser/workspace_review_fixture.py,
|
||||
// recorded through the scan's recorder) shows its candidates in the Images details panel; choosing one links the file
|
||||
// and takes it out of Needs review, leaving it unresolved decides it, and an item with nothing to choose sends the user
|
||||
// to Needs review.
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
|
||||
const images = '/prompt_manager/workspace#/images';
|
||||
const details = page => page.getByRole('complementary', { name: 'Selected image details', exact: true });
|
||||
const choice = page => details(page).getByRole('region', { name: 'Choose prompt', exact: true });
|
||||
const context = page => choice(page).getByRole('combobox', { name: 'Sampler context', exact: true });
|
||||
const toast = page => page.locator('#workspace-toast');
|
||||
const OPTIONS = ['Sampler 11 · Golden dunes at dusk / Soft negative, blur', 'Sampler 13 · Harbor lights at night / Soft negative, blur'];
|
||||
|
||||
async function seed(request, data) {
|
||||
const response = await request.post('/__test__/review/reset', { data });
|
||||
await expect(response).toBeOK();
|
||||
return response.json();
|
||||
}
|
||||
const pending = async request => (await (await request.get('/prompt_manager/review/items?limit=1')).json()).total;
|
||||
const links = async request => (await (await request.get('/__test__/review/links')).json()).links;
|
||||
|
||||
/** The Images page with `filename`'s details open (a page may already have selected it). */
|
||||
async function inspect(page, filename) {
|
||||
await page.goto(images);
|
||||
const card = page.locator('article[data-image-key]').filter({ hasText: filename });
|
||||
await card.getByRole('button', { name: `Inspect ${filename}`, exact: true }).click();
|
||||
await expect(details(page).locator('.detail-inner > p.small').first()).toHaveText(filename);
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page, browserName }) => {
|
||||
await startCoverage(page, browserName);
|
||||
page.choiceErrors = [];
|
||||
page.on('pageerror', error => page.choiceErrors.push(error.message));
|
||||
});
|
||||
test.afterEach(async ({ page, browserName, request }) => {
|
||||
await saveCoverage(page, browserName);
|
||||
expect(page.choiceErrors).toEqual([]);
|
||||
await request.post('/__test__/jobs/restart');
|
||||
});
|
||||
|
||||
test('choosing a candidate in Inspect links the file and takes it out of Needs review', async ({ page, request }) => {
|
||||
await seed(request, { items: 1 });
|
||||
expect(await pending(request)).toBe(1);
|
||||
await inspect(page, 'review_0000.png');
|
||||
// The section follows the file's own prompt blocks.
|
||||
await expect(choice(page)).toBeVisible();
|
||||
await expect(details(page).locator('.detail-inner > .inspect-choice')).toHaveCount(1);
|
||||
await expect(context(page).locator('option')).toHaveText(OPTIONS);
|
||||
await expect(choice(page).locator('.prompt-section.positive .prompt-text')).toHaveText('Golden dunes at dusk');
|
||||
await context(page).selectOption({ label: OPTIONS[1] });
|
||||
await expect(choice(page).locator('.prompt-section.positive .prompt-text')).toHaveText('Harbor lights at night');
|
||||
await expect(choice(page).locator('.prompt-section.negative .prompt-text')).toHaveText('Soft negative, blur');
|
||||
await expect(choice(page).getByRole('button', { name: 'Copy chosen positive prompt', exact: true })).toBeVisible();
|
||||
await expect(choice(page).getByRole('button', { name: 'Send chosen positive prompt to ComfyUI', exact: true })).toBeVisible();
|
||||
|
||||
const decided = page.waitForResponse(response => /\/review\/items\/[^/]+\/decision$/.test(response.url()));
|
||||
const reread = page.waitForResponse(response => response.url().includes('/prompt_manager/images/inspect/') && response.ok());
|
||||
await choice(page).getByRole('button', { name: 'Use this prompt', exact: true }).click();
|
||||
expect((await decided).status()).toBe(200);
|
||||
await reread;
|
||||
await expect(toast(page)).toHaveText('Association accepted.');
|
||||
// The inspection is read again: the file is linked, so the section is gone and Prompt history opens its prompt.
|
||||
await expect(choice(page)).toHaveCount(0);
|
||||
await expect(details(page).getByRole('button', { name: 'Prompt history', exact: true })).toBeVisible();
|
||||
expect(await pending(request)).toBe(0);
|
||||
expect((await links(request)).map(row => [row.filename, row.prompt])).toEqual([['review_0000.png', 'Harbor lights at night']]);
|
||||
|
||||
await page.goto('/prompt_manager/workspace#/review');
|
||||
await expect(page.locator('#workspace-main .notice h2')).toHaveText('No images need a decision');
|
||||
});
|
||||
|
||||
test('Leave unresolved in Inspect decides the item and links nothing', async ({ page, request }) => {
|
||||
await seed(request, { items: 2 });
|
||||
await inspect(page, 'review_0001.png');
|
||||
await expect(context(page).locator('option')).toHaveText(OPTIONS);
|
||||
const decided = page.waitForResponse(response => /\/review\/items\/[^/]+\/decision$/.test(response.url()));
|
||||
await choice(page).getByRole('button', { name: 'Leave unresolved', exact: true }).click();
|
||||
expect((await decided).status()).toBe(200);
|
||||
await expect(toast(page)).toHaveText('Left unresolved.');
|
||||
// The item is decided: the section is gone and the file stays unlinked.
|
||||
await expect(choice(page)).toHaveCount(0);
|
||||
await expect(details(page).getByRole('button', { name: 'Prompt history', exact: true })).toHaveCount(0);
|
||||
expect(await pending(request)).toBe(1);
|
||||
expect(await links(request)).toEqual([]);
|
||||
});
|
||||
|
||||
test('an item with nothing to choose offers Open in Needs review', async ({ page, request }) => {
|
||||
await seed(request, { items: 0, limited: true });
|
||||
await inspect(page, 'limited.png');
|
||||
await expect(choice(page)).toContainText('None of the possible prompts can be applied here. Decide this image in Needs review.');
|
||||
await expect(context(page)).toBeHidden();
|
||||
await expect(choice(page).getByRole('button', { name: 'Use this prompt', exact: true })).toBeHidden();
|
||||
await choice(page).getByRole('button', { name: 'Open in Needs review', exact: true }).click();
|
||||
await expect(page).toHaveURL(/#\/review$/);
|
||||
await expect(page.locator('#workspace-main .notice h2')).toHaveText('1 image needs a decision');
|
||||
});
|
||||
|
||||
test('the viewer details show the same Choose prompt', async ({ page, request }) => {
|
||||
await seed(request, { items: 1 });
|
||||
await page.goto(images);
|
||||
const card = page.locator('article[data-image-key]').filter({ hasText: 'review_0000.png' });
|
||||
await card.getByRole('button', { name: 'Open review_0000.png', exact: true }).click();
|
||||
const viewer = page.locator('#viewer-dialog');
|
||||
await expect(viewer).toBeVisible();
|
||||
const section = viewer.getByRole('region', { name: 'Choose prompt', exact: true });
|
||||
await expect(section.getByRole('combobox', { name: 'Sampler context', exact: true }).locator('option')).toHaveText(OPTIONS);
|
||||
// Open in Needs review is offered only when nothing can be chosen.
|
||||
await expect(section.getByRole('button', { name: 'Open in Needs review', exact: true })).toBeHidden();
|
||||
});
|
||||
|
||||
test('#657 D3: Choose prompt says when the file\'s prompts were shortened to the most used', async ({ page, request }) => {
|
||||
await seed(request, { items: 1 });
|
||||
await page.route(url => /\/prompt_manager\/review\/items\/[0-9a-f-]{36}$/.test(url.pathname), async route => {
|
||||
const response = await route.fetch();
|
||||
await route.fulfill({ response, json: { ...(await response.json()), collapsed: { shown: 2, total: 81, paths: 165 } } });
|
||||
});
|
||||
await inspect(page, 'review_0000.png');
|
||||
await expect(context(page).locator('option')).toHaveText(OPTIONS);
|
||||
await expect(choice(page).locator('.review-collapsed')).toHaveText('Showing the 2 most used of 81 prompts in this file.');
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -21,9 +21,8 @@ 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"; 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']};
|
||||
// D14: the Library appends its Oldest first after the concept's sorts; D153 (#447) drops "Highest rated".
|
||||
if(item.id==='sort')return {...item,options:[...item.options.filter(option=>option!=='Highest rated'),'Oldest first']};
|
||||
// D36: the category list is the Library's real list, sorted alphabetically; the concept lists prompt order.
|
||||
if(item.id==='category-filter')return {...item,options:[item.options[0],...item.options.slice(1).sort(nocase)]};
|
||||
return item;
|
||||
|
||||
@@ -102,16 +102,11 @@ test('inspection failures retry and a delayed previous selection cannot replace
|
||||
release();await expect(role(details(page),'Positive')).toContainText('Dog landscape');
|
||||
});
|
||||
|
||||
test('sender chooses the only destination, previews full changes and acknowledges only the applied pair',async({page,context},testInfo)=>{
|
||||
test('sender requires explicit 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);
|
||||
// "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 sender=dialog(page);await expect(sender.getByRole('button',{name:'Apply to ComfyUI',exact:true})).toBeDisabled();
|
||||
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,17 +655,6 @@ 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.
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
@@ -167,6 +167,8 @@ const IMAGES_COUNT_URL = '/prompt_manager/images/output?mode=workspace&limit=1';
|
||||
|
||||
/** The concept's shell and Overview with the recorded deviations applied, given the server's real overview. */
|
||||
function mapOverviewConcept(reference, overview, images) {
|
||||
// D165: the discreet legacy-pages line follows the settings layout.
|
||||
reference = { ...reference, tree: [...reference.tree, 'p.legacy-pages.small'] };
|
||||
const relabel = { 'Database integrity': 'Not checked', 'Positive prompts': number(overview.library.positive_prompts),
|
||||
'Negative variants': number(overview.library.negative_variants), Images: number(images) };
|
||||
const rows = {
|
||||
@@ -263,7 +265,7 @@ const UNMAPPED_PATHS = [
|
||||
'columns.surfaces.0.rows.length', 'columns.surfaces.0.tree.4', 'columns.surfaces.0.tree.length',
|
||||
'columns.surfaces.1.rows.0.description', 'columns.surfaces.1.rows.1.title', 'columns.surfaces.1.rows.2.description',
|
||||
'heading.actions.0', 'heading.actions.length', 'metrics.items.3.value', 'nav.label',
|
||||
'save.button.cursor', 'save.button.opacity', 'save.status.text',
|
||||
'save.button.cursor', 'save.button.opacity', 'save.status.text', 'tree.3', 'tree.length',
|
||||
].sort();
|
||||
|
||||
test('system comparison detects mutations', async ({ page, request }) => {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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
|
||||
@@ -301,8 +300,7 @@ 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();
|
||||
// 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 page.getByRole('button', { name: 'Save preferences', exact: true }).click();
|
||||
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();
|
||||
|
||||
@@ -2709,26 +2709,3 @@ 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,11 +565,9 @@ 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);
|
||||
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);
|
||||
expect(state.revoked).toEqual([state.created[0]]);
|
||||
expect(await page.evaluate(() => window.__loads)).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();
|
||||
@@ -650,10 +648,7 @@ 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.
|
||||
// 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++) {
|
||||
for (let attempt = 0; attempt < 15; attempt++) {
|
||||
const page = await context.newPage();
|
||||
try {
|
||||
if (attempt === 0) await startCoverage(page, browserName);
|
||||
@@ -692,11 +687,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 (usually so at `loadstart` itself): kept in place and untouched. A video that had
|
||||
// Replaced while starting (always 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 (readyState === 0) startingSeen++;
|
||||
if (attempt % 5 === 0) expect(readyState).toBe(0);
|
||||
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.
|
||||
@@ -707,7 +702,6 @@ 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 }) => {
|
||||
@@ -716,10 +710,7 @@ 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.
|
||||
// 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++) {
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
const page = await context.newPage();
|
||||
try {
|
||||
if (attempt === 0) await startCoverage(page, browserName);
|
||||
@@ -759,7 +750,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 (readyState === 0) startingSeen++;
|
||||
if (attempt % 5 === 0) expect(readyState).toBe(0);
|
||||
// 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);
|
||||
@@ -773,7 +764,6 @@ 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. */
|
||||
@@ -860,10 +850,7 @@ 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.
|
||||
// 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++) {
|
||||
for (let attempt = 0; attempt < 15; attempt++) {
|
||||
const page = await context.newPage();
|
||||
try {
|
||||
if (attempt === 0) await startCoverage(page, browserName);
|
||||
@@ -891,7 +878,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 (readyState === 0) startingSeen++;
|
||||
if (attempt % 5 === 0) expect(readyState).toBe(0);
|
||||
// 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);
|
||||
@@ -904,7 +891,6 @@ 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 }) => {
|
||||
|
||||
@@ -191,7 +191,7 @@ test('library toolbar matches the concept and tags live in Refine this view',asy
|
||||
expect(await toolbar.evaluate(node=>[...node.children].map(child=>child.tagName.toLowerCase()+(child.id?`#${child.id}`:'')+(child.className?`.${child.className.split(' ').filter(name=>!name.startsWith('ca-')).join('.')}`:'')))).toEqual(['label.search-field','select#category-filter','select#sort','button','button']);
|
||||
await expect(toolbar.locator('#search')).toHaveAttribute('placeholder','Search prompts, tags, filenames…');
|
||||
// D153 (#447): no "Highest rated".
|
||||
await expect(toolbar.locator('#sort option')).toHaveText(['Recently added','Name A–Z','Oldest first','Recently used','Most used','Name Z–A']);
|
||||
await expect(toolbar.locator('#sort option')).toHaveText(['Recently added','Name A–Z','Oldest first']);
|
||||
await expect(toolbar.getByRole('button')).toHaveText(['Save view','Filters']);
|
||||
await expect(page.getByRole('button',{name:'Refresh library',exact:true})).toHaveCount(0);
|
||||
await expect(page.getByRole('textbox',{name:'Tags',exact:true})).toHaveCount(0);
|
||||
|
||||
@@ -269,77 +269,15 @@ test('an empty queue shows the empty notice only', async ({ page, request }) =>
|
||||
await expect(reviewRow(page)).toHaveText('Needs review0');
|
||||
});
|
||||
|
||||
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; });
|
||||
test('load more appends the next page', async ({ page, request }) => {
|
||||
await seed(request, 45);
|
||||
await open(page);
|
||||
await expect(cards(page)).toHaveCount(40);
|
||||
await expect(continuation(page).locator('p')).toHaveText('40 of 45 images');
|
||||
await continuation(page).getByRole('button', { name: 'Load more images', exact: true }).click();
|
||||
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(cards(page)).toHaveCount(45);
|
||||
await expect(continuation(page)).toHaveCount(0);
|
||||
await expect(continuation).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('a scan job with review items offers Review metadata in Activity', async ({ page, request }) => {
|
||||
@@ -643,7 +581,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 scrollToContinuation(page);
|
||||
await main(page).getByRole('button', { name: 'Load more images', exact: true }).click();
|
||||
await expect(cards(page)).toHaveCount(45);
|
||||
await cards(page).last().scrollIntoViewIfNeeded();
|
||||
const scrollTop = () => cards(page).first().evaluate(node => {
|
||||
@@ -745,151 +683,3 @@ 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);
|
||||
});
|
||||
|
||||
@@ -205,7 +205,7 @@ test('a view stored under older rules still lists and opens with its usable valu
|
||||
return (await response.json()).id;
|
||||
};
|
||||
const imagesId = await raw({ page: 'images', name: 'Old cats', state: JSON.stringify({ q: 'cat', sort: 'shuffle', layout: 'grid' }) });
|
||||
await raw({ page: 'library', name: '', state: JSON.stringify({ q: 'dog', sort: 'shuffle' }) });
|
||||
await raw({ page: 'library', name: '', state: JSON.stringify({ q: 'dog', sort: 'name-desc' }) });
|
||||
expect(await listed(request)).toEqual([
|
||||
{ id: imagesId, page: 'images', name: 'Old cats', state: { ...IMAGE_DEFAULTS, q: 'cat' } },
|
||||
expect.objectContaining({ page: 'library', name: 'Saved view', state: { q: 'dog', category: '', sort: 'newest', tags: [], tag_mode: 'all', folder: '' } }),
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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';
|
||||
|
||||
@@ -388,9 +387,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 = hostSaveAnswer(page);
|
||||
const saved = page.waitForRequest(item => item.url().endsWith('/prompt_manager/settings') && item.method() === 'POST');
|
||||
await save(page).click();
|
||||
const body = (await saved).request().postDataJSON();
|
||||
const body = (await saved).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);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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
|
||||
@@ -66,7 +65,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 clickHostSave(page, save(page), ENABLE_URL);
|
||||
await save(page).click();
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
}
|
||||
|
||||
@@ -202,7 +201,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 clickHostSave(page, save(page), ENABLE_URL);
|
||||
await save(page).click();
|
||||
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 });
|
||||
@@ -244,7 +243,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 clickHostSave(page, save(page), ENABLE_URL);
|
||||
await save(page).click();
|
||||
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');
|
||||
@@ -262,7 +261,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 clickHostSave(page, save(page), ENABLE_URL);
|
||||
await save(page).click();
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, '/__test__/integrations/state')).trigger_words).toBe(true);
|
||||
});
|
||||
@@ -293,7 +292,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 clickHostSave(page, save(page));
|
||||
await save(page).click();
|
||||
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']);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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
|
||||
@@ -8,6 +7,7 @@ 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 = hostSaveAnswer(page);
|
||||
const saved = page.waitForRequest(item => item.method() === 'POST' && item.url().endsWith(SETTINGS_URL));
|
||||
await saveButton(page).click();
|
||||
const body = (await saved).request().postDataJSON();
|
||||
const body = (await saved).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 clickHostSave(page, saveButton(page));
|
||||
await saveButton(page).click();
|
||||
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 clickHostSave(page, saveButton(page));
|
||||
await saveButton(page).click();
|
||||
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 clickHostSave(page, saveButton(page));
|
||||
await saveButton(page).click();
|
||||
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 = hostSaveAnswer(page);
|
||||
const saved = page.waitForRequest(item => item.method() === 'POST' && item.url().endsWith(SETTINGS_URL));
|
||||
await saveButton(page).click();
|
||||
expect((await saved).request().postDataJSON()).toEqual({ save_foreign_runs: false, expected_revision: expect.any(String) });
|
||||
expect((await saved).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 = hostSaveAnswer(page);
|
||||
const saved = page.waitForRequest(item => item.method() === 'POST' && item.url().endsWith(SETTINGS_URL));
|
||||
await saveButton(page).click();
|
||||
expect((await saved).request().postDataJSON().worker_threads).toBe(next);
|
||||
expect((await saved).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 clickHostSave(page, saveButton(page));
|
||||
await saveButton(page).click();
|
||||
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,6 +1,5 @@
|
||||
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
|
||||
@@ -9,6 +8,7 @@ import { clickHostSave, hostSaveAnswer, SETTINGS_URL } from './settings-save.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 = hostSaveAnswer(page);
|
||||
const posted = page.waitForRequest(item => item.method() === 'POST' && new URL(item.url()).pathname === SETTINGS_URL);
|
||||
await save(page).click();
|
||||
const body = (await posted).request().postDataJSON();
|
||||
const body = (await posted).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 clickHostSave(page, save(page));
|
||||
await save(page).click();
|
||||
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 clickHostSave(page, save(page));
|
||||
await save(page).click();
|
||||
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 clickHostSave(page, save(page));
|
||||
await save(page).click();
|
||||
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,6 +1,5 @@
|
||||
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';
|
||||
|
||||
@@ -327,7 +326,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 clickHostSave(page, page.getByRole('button', { name: 'Save preferences', exact: true }));
|
||||
await page.getByRole('button', { name: 'Save preferences', exact: true }).click();
|
||||
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]);
|
||||
@@ -457,8 +456,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'));
|
||||
@@ -474,9 +473,7 @@ async function openAppearance(page) {
|
||||
|
||||
async function saveAppearance(page, text) {
|
||||
await expect(saveOf(page)).not.toHaveAttribute('aria-disabled', 'true');
|
||||
// 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 saveOf(page).click();
|
||||
await expect(statusOf(page)).toHaveText(text);
|
||||
}
|
||||
|
||||
|
||||
@@ -311,42 +311,3 @@ 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([]);
|
||||
});
|
||||
|
||||
@@ -135,11 +135,34 @@ test('/prompt_manager/web lands on the workspace Library and Back does not bounc
|
||||
await expect(main.getByRole('heading', { level: 1, name: 'Overview', exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
// #620: the old pages are on their way out (notice since 3.5.1), so the workspace no longer links them.
|
||||
test('System no longer links the old pages (#620)', async ({ page }) => {
|
||||
// D165 (#525, maintainer ruling): a discreet line under System is the workspace's only visible way to the legacy pages.
|
||||
test('System Overview links the legacy pages discreetly, and each one loads (#525)', async ({ page, context }) => {
|
||||
await page.goto(`${workspace}#/system/overview`);
|
||||
await expect(page.locator('#workspace-main h1')).toHaveText('System');
|
||||
await expect(page.locator('#workspace-main a[href*="/admin"], #workspace-main a[href*="/gallery"]')).toHaveCount(0);
|
||||
const line = page.locator('#workspace-main .legacy-pages');
|
||||
await expect(line).toBeVisible();
|
||||
await expect(line).toContainText('Legacy pages');
|
||||
const links = line.getByRole('link');
|
||||
await expect(links).toHaveCount(4);
|
||||
for (const [name, url, ready] of [
|
||||
['Dashboard', '/prompt_manager/admin', '#addPromptBtn'],
|
||||
['Tags', '/prompt_manager/admin#/tags', '#addPromptBtn'],
|
||||
['Gallery', '/prompt_manager/gallery', 'body'],
|
||||
['Metadata viewer', '/prompt_manager/gallery.html', 'body'],
|
||||
]) {
|
||||
const opened = context.waitForEvent('page');
|
||||
await line.getByRole('link', { name, exact: true }).click();
|
||||
const tab = await opened;
|
||||
await tab.waitForLoadState('domcontentloaded');
|
||||
const target = new URL(tab.url());
|
||||
expect(target.pathname + target.hash).toBe(url);
|
||||
await expect(tab.locator(ready).first()).toBeAttached();
|
||||
await tab.close();
|
||||
}
|
||||
// Only on System's Overview section, and gone with the page.
|
||||
await page.locator('#workspace-main .section-nav').getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
await expect(line).toBeHidden();
|
||||
await page.goto(`${workspace}#/library`);
|
||||
await expect(page.locator('#workspace-main .legacy-pages')).toHaveCount(0);
|
||||
});
|
||||
|
||||
const bootFailure = page => page.locator('#workspace-boot-failure');
|
||||
@@ -152,7 +175,7 @@ test('a healthy workspace never shows the load failure message (#525)', async ({
|
||||
});
|
||||
|
||||
for (const [label, pattern] of [['the entry module', '**/js/workspace/index.mjs*'], ['a dependency', '**/js/workspace/state.mjs*']]) {
|
||||
test(`when ${label} fails to load the page offers a reload and ComfyUI (#525, #620)`, async ({ page }) => {
|
||||
test(`when ${label} fails to load the page still offers the legacy pages (#525)`, async ({ page }) => {
|
||||
const pageErrors = [];
|
||||
page.on('pageerror', error => pageErrors.push(error.message));
|
||||
await page.route(pattern, route => route.abort());
|
||||
@@ -160,17 +183,19 @@ for (const [label, pattern] of [['the entry module', '**/js/workspace/index.mjs*
|
||||
const failure = bootFailure(page);
|
||||
await expect(failure).toBeVisible();
|
||||
await expect(failure).toHaveAttribute('role', 'alert');
|
||||
await expect(failure.getByRole('link', { name: 'Reload the page', exact: true })).toHaveAttribute('href', 'workspace');
|
||||
await expect(failure.getByRole('link', { name: 'ComfyUI', exact: true })).toHaveAttribute('href', '../');
|
||||
await expect(failure.getByRole('link')).toHaveCount(2);
|
||||
const dashboard = failure.getByRole('link', { name: 'Dashboard', exact: true });
|
||||
await expect(dashboard).toBeVisible();
|
||||
await expect(failure.getByRole('link')).toHaveCount(4);
|
||||
await dashboard.click();
|
||||
await expect(page).toHaveURL(/\/prompt_manager\/admin$/);
|
||||
expect(pageErrors).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
test('when a module throws while starting the page still offers a reload (#525, #620)', async ({ page }) => {
|
||||
test('when a module throws while starting the page still offers the legacy pages (#525)', async ({ page }) => {
|
||||
await page.route('**/js/workspace/state.mjs*', route => route.fulfill({ contentType: 'text/javascript', body: "throw new Error('boot failure');" }));
|
||||
await page.goto(`${workspace}#/library`);
|
||||
await expect(bootFailure(page).getByRole('link', { name: 'Reload the page', exact: true })).toBeVisible();
|
||||
await expect(bootFailure(page).getByRole('link', { name: 'Dashboard', exact: true })).toBeVisible();
|
||||
// The broken module's own error is this test's premise, not a failure of the page.
|
||||
page.workspaceErrors.length = 0;
|
||||
});
|
||||
@@ -544,7 +569,7 @@ test('System is native: the concept shell, section navigation, sections and the
|
||||
// D92: no "Sample configuration" chip.
|
||||
await expect(main.locator('.heading .chip')).toHaveCount(0);
|
||||
expect(await main.evaluate(node => [...node.children].map(child => `${child.localName}.${child.className}`)))
|
||||
.toEqual(['div.heading', 'div.section-nav', 'div.settings-layout']);
|
||||
.toEqual(['div.heading', 'div.section-nav', 'div.settings-layout', 'p.small legacy-pages']);
|
||||
const nav = main.getByRole('group', { name: 'System sections', exact: true });
|
||||
await expect(nav.getByRole('button')).toHaveText(SYSTEM_SECTION_LABELS);
|
||||
await expect(nav.getByRole('button', { name: 'Overview', exact: true })).toHaveAttribute('aria-pressed', 'true');
|
||||
|
||||
@@ -35,10 +35,6 @@ 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
|
||||
|
||||
@@ -437,9 +433,7 @@ def seed_workspace_concept(
|
||||
|
||||
folder = root / "output" / "concepts"
|
||||
folder.mkdir()
|
||||
roots = snapshot_output_roots(
|
||||
HOST_PATH_STYLE, str(root / "output"), str(root / "temp")
|
||||
)
|
||||
roots = snapshot_output_roots("posix", 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
|
||||
|
||||
@@ -480,7 +474,7 @@ def seed_workspace_concept(
|
||||
"3", _snapshot(prompt.positive), _snapshot(negative), "inferred"
|
||||
)
|
||||
reference = OutputReference(
|
||||
"4", 0, "output", "concepts", name, HOST_PATH_STYLE, roots.output_key
|
||||
"4", 0, "output", "concepts", name, "posix", roots.output_key
|
||||
)
|
||||
runs.append(
|
||||
_record_run(
|
||||
|
||||
@@ -15,7 +15,6 @@ 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,
|
||||
@@ -294,9 +293,7 @@ def seed_workspace_history(
|
||||
):
|
||||
conn.execute(f"DELETE FROM {table}")
|
||||
epoch = api.db.get_execution_epoch()
|
||||
roots = snapshot_output_roots(
|
||||
HOST_PATH_STYLE, str(root / "output"), str(root / "temp")
|
||||
)
|
||||
roots = snapshot_output_roots("posix", str(root / "output"), str(root / "temp"))
|
||||
folder = root / "output" / "history"
|
||||
folder.mkdir(exist_ok=True)
|
||||
for index, name in enumerate(("current.png", "other.png")):
|
||||
@@ -312,7 +309,7 @@ def seed_workspace_history(
|
||||
kind,
|
||||
"history",
|
||||
name,
|
||||
HOST_PATH_STYLE,
|
||||
"posix",
|
||||
roots.output_key if kind == "output" else roots.temp_key,
|
||||
)
|
||||
|
||||
|
||||
@@ -15,9 +15,8 @@ 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``: 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).
|
||||
- ``limited``: a graph of 17 samplers, each with its own prompt, which the
|
||||
recorder stores ``limited`` (more than 16 candidates, so none are stored).
|
||||
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
|
||||
@@ -80,6 +79,8 @@ 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 = (
|
||||
@@ -209,23 +210,6 @@ 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
|
||||
|
||||
@@ -312,8 +296,9 @@ def seed_review(
|
||||
_png(path, (70, 40, 120))
|
||||
_unreadable(api, path)
|
||||
elif kind == "limited":
|
||||
_png(path, (90, 90, 90))
|
||||
_limited(api, path)
|
||||
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")
|
||||
else:
|
||||
_png(path, (20, 140, 90))
|
||||
_unavailable(api, root, path)
|
||||
|
||||
+1
-1
@@ -935,7 +935,7 @@
|
||||
"reason_code": "multistage-differs",
|
||||
"selection": null,
|
||||
"positive": null,
|
||||
"negative": "blurry, lowres",
|
||||
"negative": null,
|
||||
"candidate_count": 0,
|
||||
"facts": {
|
||||
"seed": {
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -289,19 +289,3 @@ test('a fallback after a re-render returns focus to the same-role copy button, n
|
||||
const {fallbacks,copy,current}=await copyWithClipboard({writeText:async()=>{throw new Error('Denied');}},{detach:true});
|
||||
assert.equal(fallbacks.length,1);assert.notEqual(current,copy);assert.equal(fallbacks[0].trigger,current);
|
||||
});
|
||||
// #658: an ambiguous file whose candidates share one role shows that role resolved; the other keeps the ambiguous
|
||||
// line. The shared role has Copy and Send; the pair action needs both roles, so it is absent.
|
||||
test('one shared role beside an ambiguous one has its own actions and no pair action',()=>{
|
||||
const f=dom(),scope=createScope(),container=new f.Element('div'),sent=[];
|
||||
try{
|
||||
module.mountPromptBlocks(container,{parentScope:scope,sender:{open:roles=>sent.push(roles)},
|
||||
prompts:{positive:{status:'ambiguous',text:null,source:null},negative:{status:'resolved',text:'shared negative',source:'graph-inferred'}}});
|
||||
assert.deepEqual(statusLines(f,container),['Multiple possible prompts. Source could not be determined.']);
|
||||
assert.equal(f.walk(container,node=>node.dataset.sendRole==='pair').length,0);
|
||||
assert.equal(f.walk(container,node=>node.dataset.sendRole==='positive').length,0);
|
||||
assert.equal(f.walk(container,node=>node.dataset.copyRole==='positive').length,0);
|
||||
assert.equal(f.walk(container,node=>node.dataset.copyRole==='negative').length,1);
|
||||
const send=f.walk(container,node=>node.dataset.sendRole==='negative')[0];container.click(send);
|
||||
assert.deepEqual(sent,[{negative:'shared negative'}]);
|
||||
}finally{scope.dispose();f.restore();}
|
||||
});
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
// Run with: node --test tests/js/workspace-file-inspector-choice.test.js
|
||||
// #659: the inspector mounts Choose prompt after its prompt blocks while the file's review item is pending.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mountedDom } from './helpers/mounted-dom.mjs';
|
||||
|
||||
const { createScope } = await import('../../web/js/shared/toolkit/core.js');
|
||||
const { mountFileInspector } = await import('../../web/js/workspace/file-inspector.mjs');
|
||||
|
||||
const ITEM = '0a1b2c3d-0000-4000-8000-00000000abcd';
|
||||
const OTHER = '0a1b2c3d-0000-4000-8000-00000000ffff';
|
||||
const EPOCH = '11111111-1111-4111-8111-111111111111';
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve));
|
||||
async function settle(times = 8) { for (let i = 0; i < times; i++) await flush(); }
|
||||
|
||||
function record(review) {
|
||||
return {
|
||||
identity: { kind: 'rooted-file', key: '0:a.png', root_index: 0, path: 'a.png', root_scope: 'a'.repeat(64) },
|
||||
file: { format: 'PNG' }, download: null, preview: null, historyTarget: null, imageTags: null, metadata: null,
|
||||
prompts: { positive: { status: 'ambiguous', text: null, source: null }, negative: { status: 'ambiguous', text: null, source: null } },
|
||||
generation: {}, library: { status: 'none', tags: [] }, review,
|
||||
};
|
||||
}
|
||||
function detail(id) {
|
||||
return {
|
||||
success: true, library_epoch: EPOCH, id, state: 'pending', revision: 0, filename: 'a.png',
|
||||
target: { root_index: 0, root_scope: 'c'.repeat(64), path: 'a.png' }, unavailable: false, limited: false,
|
||||
candidate_count: 2, total: 1, sha256: 'd'.repeat(64), dependency_fingerprint: 'e'.repeat(64),
|
||||
candidates: [
|
||||
{ hash: 'a'.repeat(64), sampler_id: '11', state: 'resolved', reason: '', label: 'Dunes / blur', positive: { text: 'dunes' }, negative: { text: 'blur' } },
|
||||
{ hash: 'b'.repeat(64), sampler_id: '13', state: 'resolved', reason: '', label: 'Harbor / blur', positive: { text: 'harbor' }, negative: { text: 'blur' } },
|
||||
],
|
||||
};
|
||||
}
|
||||
function fakeApi() {
|
||||
const calls = [];
|
||||
return {
|
||||
calls,
|
||||
api: {
|
||||
get: url => { calls.push(['GET', url]); return Promise.resolve(detail(url.split('/').at(-1))); },
|
||||
post: url => {
|
||||
calls.push(['POST', url]);
|
||||
return Promise.resolve(url.endsWith('/observe') ? { library_epoch: EPOCH, capture: { token: 't', sha256: 'd'.repeat(64) } }
|
||||
: { success: true, library_epoch: EPOCH, total: 0 });
|
||||
},
|
||||
del: () => Promise.resolve({}),
|
||||
},
|
||||
};
|
||||
}
|
||||
function mount(options = {}) {
|
||||
const f = mountedDom();
|
||||
f.doc.getElementById = () => null;
|
||||
const scope = createScope(), decided = [], { api, calls } = fakeApi();
|
||||
const view = mountFileInspector(f.container, { api, sender: { open() {} }, parentScope: scope, variant: 'panel',
|
||||
onReviewDecided: () => decided.push(true), ...options });
|
||||
const sections = () => f.walk(f.container, n => n.className === 'inspect-choice');
|
||||
return { f, view, calls, decided, sections, done() { view.dispose(); scope.dispose(); f.restore(); } };
|
||||
}
|
||||
|
||||
test('a pending review item mounts Choose prompt right after the prompt blocks', async () => {
|
||||
const m = mount();
|
||||
try {
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
const [section] = m.sections();
|
||||
assert.ok(section, 'Choose prompt is mounted');
|
||||
const inner = section.parent;
|
||||
const index = inner.children.indexOf(section);
|
||||
assert.ok(inner.children[index - 1].children.some(n => n.className === 'prompt-section positive'),
|
||||
'the section follows the prompt blocks');
|
||||
assert.deepEqual(m.calls, [['GET', `/prompt_manager/review/items/${ITEM}`]]);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('a re-render keeps the same section, and another item replaces it', async () => {
|
||||
const m = mount();
|
||||
try {
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
const [first] = m.sections();
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
assert.equal(m.sections()[0], first);
|
||||
assert.equal(m.calls.length, 1, 'the item is read once');
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: OTHER }) });
|
||||
await settle();
|
||||
assert.notEqual(m.sections()[0], first);
|
||||
assert.equal(m.sections().length, 1);
|
||||
assert.deepEqual(m.calls.at(-1), ['GET', `/prompt_manager/review/items/${OTHER}`]);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('no section without a pending item, or without a way to re-read the inspection', async () => {
|
||||
for (const review of [null, { state: 'decided' }, undefined]) {
|
||||
const m = mount();
|
||||
try {
|
||||
m.view.setState({ record: record(review) });
|
||||
await settle();
|
||||
assert.equal(m.sections().length, 0, JSON.stringify(review));
|
||||
assert.equal(m.calls.length, 0);
|
||||
} finally { m.done(); }
|
||||
}
|
||||
const m = mount({ onReviewDecided: undefined });
|
||||
try {
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
assert.equal(m.sections().length, 0);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('a decision re-reads the inspection; a record without the item removes the section', async () => {
|
||||
const m = mount();
|
||||
try {
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
const use = m.f.walk(m.sections()[0], n => n.tagName === 'button' && n.textContent === 'Use this prompt')[0];
|
||||
use.fire('click');
|
||||
await settle();
|
||||
assert.deepEqual(m.decided, [true]);
|
||||
m.view.setState({ record: { ...record(null), library: { status: 'linked', tags: [] } } });
|
||||
await settle();
|
||||
assert.equal(m.sections().length, 0);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('reading another file ends the section', async () => {
|
||||
const m = mount();
|
||||
try {
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
const [section] = m.sections();
|
||||
m.view.setState({ loading: true });
|
||||
assert.equal(m.sections().length, 0);
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
assert.notEqual(m.sections()[0], section, 'a new section for the newly read record');
|
||||
} finally { m.done(); }
|
||||
});
|
||||
@@ -748,24 +748,3 @@ test('category chip names its origin visibly and shows an own category for any l
|
||||
assert.equal(chips.some(chip => /category: /.test(chip)), false, JSON.stringify(library));
|
||||
}
|
||||
});
|
||||
|
||||
// #658: an ambiguous file whose candidates share one role. The shared role has Copy and Send; the footer
|
||||
// "Send to ComfyUI" sends a pair, so it needs both roles resolved and is absent here, in both variants.
|
||||
test('one resolved and one ambiguous role: no footer Send to ComfyUI, the resolved role keeps its actions', async () => {
|
||||
const base = await localRecord(localPng('Shared Negative.png'));
|
||||
const record = {...base, prompts:{positive:{status:'ambiguous', text:null, source:null}, negative:{status:'resolved', text:'blurry, lowres', source:'graph-inferred'}}};
|
||||
for (const variant of ['panel', 'full']) {
|
||||
const f = mountedDom(), scope = createScope();
|
||||
const forbidden = new Proxy({}, {get(_, key) {assert.fail(`api.${String(key)} touched by a local record`);}});
|
||||
const view = mountFileInspector(f.container, {api:forbidden, sender:{open() {}}, parentScope:scope, variant});
|
||||
try {
|
||||
view.setState({loading:false, error:false, record});
|
||||
const buttons = f.walk(f.container, n => n.tagName === 'button');
|
||||
assert.equal(buttons.filter(n => n.dataset.sendRole === 'pair').length, 0, variant);
|
||||
assert.equal(f.walk(f.container, n => n.textContent?.includes?.('Send to ComfyUI') && n.tagName === 'button').length, 0, variant);
|
||||
assert.equal(buttons.filter(n => n.dataset.sendRole === 'negative').length, 1, variant);
|
||||
assert.equal(buttons.filter(n => n.dataset.copyRole === 'negative').length, 1, variant);
|
||||
assert.equal(buttons.filter(n => n.dataset.sendRole === 'positive' || n.dataset.copyRole === 'positive').length, 0, variant);
|
||||
} finally { view.dispose(); scope.dispose(); f.restore(); }
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1033,9 +1033,7 @@ test('the bulk options pick and reset like the Tag image dialog (D204)', async (
|
||||
|
||||
test('the client Built-in copy equals the server DEFAULT_TAG_TEMPLATE (#431)', async () => {
|
||||
const { BUILTIN_INSTRUCTIONS } = await load();
|
||||
// A Windows checkout may hold the file with CRLF line endings (#636).
|
||||
const source = require('node:fs').readFileSync(require('node:path').join(__dirname, '../../py/tagging_defaults.py'), 'utf8')
|
||||
.replace(/\r\n/g, '\n');
|
||||
const source = require('node:fs').readFileSync(require('node:path').join(__dirname, '../../py/tagging_defaults.py'), 'utf8');
|
||||
const block = source.slice(source.indexOf('DEFAULT_TAG_TEMPLATE = ('), source.indexOf('\n)\n', source.indexOf('DEFAULT_TAG_TEMPLATE = (')));
|
||||
const text = [...block.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map(([, part]) => JSON.parse(`"${part}"`)).join('');
|
||||
assert.ok(text.length > 100);
|
||||
|
||||
@@ -23,7 +23,7 @@ test('the words of the review and its routes', () => {
|
||||
assert.equal(MAX_DELETE, 500);
|
||||
assert.equal(TOO_MANY, 'Select at most 500 images.');
|
||||
assert.equal(QUESTION, 'What should happen to the files?');
|
||||
assert.deepEqual(MODES.map(mode => mode.label), ['Remove from the library only', 'Also move the files to the trash', 'Permanently delete']);
|
||||
assert.deepEqual(MODES.map(mode => mode.label), ['Remove from the library only', 'Also move the files to the trash']);
|
||||
});
|
||||
|
||||
test('library rows: scope, refusals, links, details, backup and media', () => {
|
||||
@@ -149,34 +149,3 @@ test('apply refuses to send a delete without an explicit mode', async () => {
|
||||
await assert.rejects(applyDelete({ api, store: null, plan: plan(), mode, notify: () => {} }), TypeError);
|
||||
}
|
||||
});
|
||||
|
||||
test('permanent rows: scope and media line', () => {
|
||||
const { deleteRows } = module();
|
||||
const rows = Object.fromEntries(deleteRows(plan({ permanent: { count: 3 } }), 'permanent'));
|
||||
assert.equal(rows.Scope, '3 images');
|
||||
assert.equal(rows['Media on disk'], 'Files are removed from disk. Disk space is freed immediately.');
|
||||
});
|
||||
|
||||
test('permanent sentences', () => {
|
||||
const { deleteSentences, SENTENCES } = module();
|
||||
assert.deepEqual(deleteSentences(plan(), 'permanent'), [SENTENCES.permanent]);
|
||||
});
|
||||
|
||||
test('permanent primary label and close-only reason', () => {
|
||||
const { primaryLabel, closeOnlyReason } = module();
|
||||
assert.equal(primaryLabel('permanent', 2), 'Permanently delete 2 images from disk');
|
||||
assert.equal(closeOnlyReason(plan({ library: { count: 0 }, trash: { count: 0 }, permanent: { count: 0 } })), 'None of the selected images can be deleted.');
|
||||
assert.equal(closeOnlyReason(plan({ library: { count: 3 } })), null);
|
||||
});
|
||||
|
||||
test('permanent outcome toast', () => {
|
||||
const { outcomeToast } = module();
|
||||
assert.equal(outcomeToast({ scope: { mode: 'permanent' }, counters: { deleted: 3, not_changed: 0 }, total: 3 }),
|
||||
'Permanently deleted 3 images from disk.');
|
||||
assert.equal(outcomeToast({ scope: { mode: 'permanent' }, counters: { deleted: 2, not_changed: 1 }, total: 3 }),
|
||||
'Permanently deleted 2 images from disk. 1 was not changed (see Activity).');
|
||||
assert.equal(outcomeToast({ scope: { mode: 'permanent', failure: 'records-failed' }, counters: { deleted: 1 }, total: 4 }),
|
||||
'Stopped after 1 of 4 images; the rest were not changed. See Activity.');
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -1,296 +0,0 @@
|
||||
// Run with: node --test tests/js/workspace-inspect-choice.test.js
|
||||
// #659 (design Part 5): Inspect's Choose prompt over the review controller's single-item mode.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { mountedDom } from './helpers/mounted-dom.mjs';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { createApiClient } = require('../../web/js/api-client.js');
|
||||
const { createScope } = await import('../../web/js/shared/toolkit/core.js');
|
||||
const module = await import('../../web/js/workspace/inspect-choice.mjs').catch(error => {
|
||||
if (error.code !== 'ERR_MODULE_NOT_FOUND') throw error;
|
||||
return {};
|
||||
});
|
||||
|
||||
const ITEM = '0a1b2c3d-0000-4000-8000-00000000abcd';
|
||||
const EPOCH = '11111111-1111-4111-8111-111111111111';
|
||||
const SCOPE = 'c'.repeat(64);
|
||||
const HASH_A = 'a'.repeat(64), HASH_B = 'b'.repeat(64), HASH_C = 'f'.repeat(64);
|
||||
const ITEMS = '/prompt_manager/review/items';
|
||||
const OBSERVE = '/prompt_manager/image-annotations/observe';
|
||||
const CAPTURE = '/prompt_manager/image-annotations/capture/';
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve));
|
||||
async function settle(times = 8) { for (let i = 0; i < times; i++) await flush(); }
|
||||
const response = (status, body) => ({ ok: status >= 200 && status < 300, status, statusText: `Status ${status}`, json: async () => body });
|
||||
const fail = (status, code, error) => response(status, { success: false, code, error });
|
||||
const candidate = (hash, sampler, label, positive, negative, state = 'resolved', reason = '') => ({
|
||||
hash, sampler_id: sampler, state, reason, label,
|
||||
positive: positive === null ? null : { text: positive }, negative: negative === null ? null : { text: negative },
|
||||
});
|
||||
function detail(overrides = {}) {
|
||||
return {
|
||||
success: true, library_epoch: EPOCH, id: ITEM, state: 'pending', revision: 0, filename: 'a.png',
|
||||
target: { root_index: 0, root_scope: SCOPE, path: 'a.png' }, unavailable: false, candidate_count: 3, limited: false,
|
||||
total: 1, sha256: 'd'.repeat(64), dependency_fingerprint: 'e'.repeat(64),
|
||||
candidates: [
|
||||
candidate(HASH_C, '9', 'No positive / Soft negative', null, 'blur', 'unresolved', 'Unsupported latent ancestry'),
|
||||
candidate(HASH_A, '12', 'Dunes / Soft negative', 'golden dunes', 'blur'),
|
||||
candidate(HASH_B, '28', 'Harbor / Soft negative', 'harbor lights', 'blur'),
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
const observed = { success: true, library_epoch: EPOCH, capture: { token: 'capture-1', sha256: 'd'.repeat(64) } };
|
||||
function harness(routes = {}) {
|
||||
const calls = [];
|
||||
const fetch = (url, init = {}) => {
|
||||
const call = { url, method: init.method, body: init.body === undefined ? undefined : JSON.parse(init.body) };
|
||||
calls.push(call);
|
||||
const path = url.startsWith(CAPTURE) ? CAPTURE : url.split('?')[0];
|
||||
const all = {
|
||||
[`GET ${ITEMS}/${ITEM}`]: () => response(200, detail()),
|
||||
[`POST ${OBSERVE}`]: () => response(200, observed),
|
||||
[`POST ${ITEMS}/${ITEM}/decision`]: () => response(200, { success: true, library_epoch: EPOCH, total: 0 }),
|
||||
...routes,
|
||||
};
|
||||
const route = all[`${call.method} ${path}`];
|
||||
return Promise.resolve().then(() => (route ? route(call) : response(200, { success: true })));
|
||||
};
|
||||
return { api: createApiClient(fetch), calls, of: (method, prefix) => calls.filter(c => c.method === method && c.url.startsWith(prefix)) };
|
||||
}
|
||||
|
||||
function contract() {
|
||||
assert.equal(typeof module.mountInspectChoice, 'function', 'inspect-choice.mjs is not implemented');
|
||||
return module;
|
||||
}
|
||||
/** The section mounted in a minimal DOM, with its parts found by text and class. */
|
||||
async function mounted(routes, options = {}) {
|
||||
const { mountInspectChoice } = contract();
|
||||
const f = mountedDom();
|
||||
f.doc.getElementById = () => null;
|
||||
const h = harness(routes), scope = createScope(), decided = [], sent = [];
|
||||
const sender = { open: (roles, trigger) => sent.push({ roles, trigger }) };
|
||||
const view = mountInspectChoice({ api: h.api, itemId: ITEM, sender, parentScope: scope, onDecided: () => decided.push(true), ...options });
|
||||
f.container.append(view.root);
|
||||
await settle();
|
||||
const find = predicate => f.walk(view.root, predicate);
|
||||
const button = text => find(n => n.tagName === 'button' && n.textContent === text)[0];
|
||||
const visible = node => { for (let n = node; n && n !== view.root.parent; n = n.parent) if (n.hidden) return false; return true; };
|
||||
return {
|
||||
f, h, view, scope, decided, sent, button, visible,
|
||||
select: () => find(n => n.tagName === 'select')[0],
|
||||
options: () => find(n => n.tagName === 'option').map(n => [n.textContent, n.disabled]),
|
||||
warning: () => find(n => n.className === 'warning-note')[0],
|
||||
status: () => find(n => /inspect-choice-status/.test(n.className ?? ''))[0],
|
||||
texts: role => find(n => n.tagName === 'section' && n.className === `prompt-section ${role}`)
|
||||
.flatMap(section => f.walk(section, n => n.className === 'prompt-text').map(n => n.textContent)),
|
||||
done() { scope.dispose(); f.restore(); },
|
||||
};
|
||||
}
|
||||
const click = node => node.fire('click');
|
||||
|
||||
test('the section lists the server labels, with a disabled candidate and its reason', async () => {
|
||||
const m = await mounted();
|
||||
try {
|
||||
assert.equal(m.view.itemId, ITEM);
|
||||
assert.equal(m.view.root.className, 'inspect-choice');
|
||||
assert.ok(m.f.walk(m.view.root, n => n.textContent === 'Choose prompt').length);
|
||||
assert.deepEqual(m.options(), [
|
||||
['Sampler 9 · No positive / Soft negative (Unsupported latent ancestry)', true],
|
||||
['Sampler 12 · Dunes / Soft negative', false],
|
||||
['Sampler 28 · Harbor / Soft negative', false],
|
||||
]);
|
||||
assert.equal(m.select().value, HASH_A);
|
||||
assert.deepEqual(m.texts('positive'), ['golden dunes']);
|
||||
assert.deepEqual(m.texts('negative'), ['blur']);
|
||||
assert.equal(m.visible(m.button('Use this prompt')), true);
|
||||
assert.equal(m.visible(m.button('Leave unresolved')), true);
|
||||
assert.equal(m.visible(m.button('Open in Needs review')), false);
|
||||
assert.equal(m.visible(m.warning()), false);
|
||||
// Choosing another option shows its prompts; the prompt blocks' Send opens the shared sender.
|
||||
m.select().value = HASH_B;
|
||||
m.select().fire('change');
|
||||
assert.deepEqual(m.texts('positive'), ['harbor lights']);
|
||||
const send = m.f.walk(m.view.root, n => n.dataset?.sendRole === 'positive')[0];
|
||||
// The prompt blocks listen on their container (the section's parent).
|
||||
m.f.walk(m.view.root, n => n.className === 'prompt-section positive')[0].parent.fire('click', { target: send });
|
||||
assert.deepEqual(m.sent.map(entry => entry.roles), [{ positive: 'harbor lights' }]);
|
||||
assert.equal(m.h.of('GET', ITEMS).length, 1, 'only the item is read, never the queue');
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('Use this prompt decides the chosen candidate and re-reads the inspection', async () => {
|
||||
const m = await mounted();
|
||||
try {
|
||||
m.select().value = HASH_B;
|
||||
m.select().fire('change');
|
||||
click(m.button('Use this prompt'));
|
||||
await settle();
|
||||
const [decision] = m.h.of('POST', `${ITEMS}/${ITEM}/decision`);
|
||||
assert.equal(decision.body.choice, HASH_B);
|
||||
assert.equal(decision.body.capture_token, 'capture-1');
|
||||
assert.equal(m.h.of('POST', OBSERVE).length, 1);
|
||||
assert.deepEqual(m.decided, [true]);
|
||||
// A decided item offers nothing more.
|
||||
assert.equal(m.visible(m.button('Use this prompt')), false);
|
||||
click(m.button('Use this prompt'));
|
||||
await settle();
|
||||
assert.equal(m.h.of('POST', `${ITEMS}/${ITEM}/decision`).length, 1);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('a refusal shows the server sentence and keeps the choice', async () => {
|
||||
const m = await mounted({ [`POST ${ITEMS}/${ITEM}/decision`]: () => fail(409, 'file-changed', 'The file changed since it was queued.') });
|
||||
try {
|
||||
click(m.button('Use this prompt'));
|
||||
await settle();
|
||||
assert.equal(m.warning().textContent, 'The file changed since it was queued.');
|
||||
assert.equal(m.visible(m.warning()), true);
|
||||
assert.deepEqual(m.decided, []);
|
||||
assert.equal(m.select().value, HASH_A);
|
||||
assert.equal(m.button('Use this prompt').getAttribute('aria-disabled'), null);
|
||||
// The refused capture is released.
|
||||
assert.equal(m.h.of('DELETE', CAPTURE).length, 1);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('an unanswered decision is resent once by the next press', async () => {
|
||||
let attempts = 0;
|
||||
const m = await mounted({
|
||||
[`POST ${ITEMS}/${ITEM}/decision`]: () => (++attempts === 1 ? Promise.reject(new TypeError('Failed to fetch'))
|
||||
: response(200, { success: true, library_epoch: EPOCH, total: 0 })),
|
||||
});
|
||||
try {
|
||||
click(m.button('Use this prompt'));
|
||||
await settle();
|
||||
assert.equal(m.warning().textContent, 'The decision may not have been saved. Apply again to send the same decision once more.');
|
||||
click(m.button('Use this prompt'));
|
||||
await settle();
|
||||
const [first, second] = m.h.of('POST', `${ITEMS}/${ITEM}/decision`);
|
||||
assert.deepEqual(second.body, first.body);
|
||||
assert.equal(m.h.of('POST', OBSERVE).length, 1);
|
||||
assert.deepEqual(m.decided, [true]);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('Leave unresolved decides the item as unresolved', async () => {
|
||||
const m = await mounted();
|
||||
try {
|
||||
click(m.button('Leave unresolved'));
|
||||
await settle();
|
||||
const [decision] = m.h.of('POST', `${ITEMS}/${ITEM}/decision`);
|
||||
assert.equal(decision.body.choice, 'unresolved');
|
||||
assert.deepEqual(m.decided, [true]);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
for (const [name, overrides] of [
|
||||
['a limited item', { limited: true, candidates: [], candidate_count: 0 }],
|
||||
['an item whose candidates cannot be applied', {
|
||||
candidates: [candidate(HASH_C, '9', 'No positive / Soft negative', null, 'blur', 'unresolved', 'Unsupported latent ancestry')],
|
||||
}],
|
||||
['an unavailable file', { target: null, unavailable: true }],
|
||||
]) {
|
||||
test(`${name} offers Open in Needs review instead of options`, async () => {
|
||||
const m = await mounted({ [`GET ${ITEMS}/${ITEM}`]: () => response(200, detail(overrides)) });
|
||||
try {
|
||||
assert.equal(m.status().textContent, 'None of the possible prompts can be applied here. Decide this image in Needs review.');
|
||||
const open = m.button('Open in Needs review');
|
||||
assert.equal(m.visible(open), true);
|
||||
for (const text of ['Use this prompt', 'Leave unresolved']) assert.equal(m.visible(m.button(text)), false, text);
|
||||
assert.equal(m.visible(m.select()), false);
|
||||
click(open);
|
||||
assert.equal(m.f.win.location.hash, '#/review');
|
||||
} finally { m.done(); }
|
||||
});
|
||||
}
|
||||
|
||||
test('a failed read offers Retry and Open in Needs review; Retry reads the item again', async () => {
|
||||
let reads = 0;
|
||||
const m = await mounted({
|
||||
[`GET ${ITEMS}/${ITEM}`]: () => (++reads === 1 ? fail(500, 'review-failed', 'The review queue could not be read.') : response(200, detail())),
|
||||
});
|
||||
try {
|
||||
assert.equal(m.visible(m.button('Retry')), true);
|
||||
assert.equal(m.visible(m.button('Open in Needs review')), true);
|
||||
assert.equal(m.warning().textContent, 'This item could not be read. Select it again to retry.');
|
||||
click(m.button('Retry'));
|
||||
await settle();
|
||||
assert.equal(reads, 2);
|
||||
assert.equal(m.visible(m.button('Retry')), false);
|
||||
assert.equal(m.visible(m.button('Use this prompt')), true);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('the loading state says so, and disposing stops the section', async () => {
|
||||
let answer;
|
||||
const m = await mounted({ [`GET ${ITEMS}/${ITEM}`]: () => new Promise(resolve => { answer = resolve; }) });
|
||||
try {
|
||||
assert.equal(m.status().textContent, 'Loading the possible prompts…');
|
||||
assert.equal(m.visible(m.button('Use this prompt')), false);
|
||||
m.view.dispose();
|
||||
m.view.dispose();
|
||||
answer(response(200, detail()));
|
||||
await settle();
|
||||
assert.equal(m.view.root.parent, null);
|
||||
assert.equal(m.status().textContent, 'Loading the possible prompts…');
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('an aborted parent mounts nothing', () => {
|
||||
const { mountInspectChoice } = contract();
|
||||
const f = mountedDom();
|
||||
try {
|
||||
const scope = createScope();
|
||||
scope.dispose();
|
||||
const view = mountInspectChoice({ api: null, itemId: ITEM, sender: null, parentScope: scope });
|
||||
assert.equal(view.root.children.length, 0);
|
||||
view.dispose();
|
||||
} finally { f.restore(); }
|
||||
});
|
||||
|
||||
test('choiceMode names what the section shows', () => {
|
||||
const { choiceMode } = contract();
|
||||
const ready = { detailStatus: 'ready', detail: detail(), options: [{ disabled: false }], decided: false };
|
||||
assert.equal(choiceMode(ready), 'choose');
|
||||
assert.equal(choiceMode({ ...ready, decided: true }), 'decided');
|
||||
assert.equal(choiceMode({ ...ready, detailStatus: 'error' }), 'error');
|
||||
assert.equal(choiceMode({ ...ready, detailStatus: 'loading', detail: null }), 'loading');
|
||||
assert.equal(choiceMode({ ...ready, options: [{ disabled: true }] }), 'review');
|
||||
});
|
||||
|
||||
test('an item decided elsewhere hides the section and re-reads the inspection once', async () => {
|
||||
const m = await mounted({ [`GET ${ITEMS}/${ITEM}`]: () => response(200, detail({ state: 'selected', revision: 1 })) });
|
||||
try {
|
||||
assert.equal(m.view.root.hidden, true);
|
||||
assert.deepEqual(m.decided, [true]);
|
||||
await settle();
|
||||
assert.deepEqual(m.decided, [true]);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('#657 D3: collapsedLine names how many of the file\'s prompts are listed, or nothing', async () => {
|
||||
const { collapsedLine } = await import('../../web/js/workspace/review-options.mjs');
|
||||
assert.equal(collapsedLine({ collapsed: { shown: 16, total: 81, paths: 165 } }),
|
||||
'Showing the 16 most used of 81 prompts in this file.');
|
||||
assert.equal(collapsedLine({ collapsed: { shown: 16, total: 1234, paths: 2000 } }),
|
||||
'Showing the 16 most used of 1,234 prompts in this file.');
|
||||
assert.equal(collapsedLine({ collapsed: null }), '');
|
||||
assert.equal(collapsedLine({}), '');
|
||||
assert.equal(collapsedLine(null), '');
|
||||
});
|
||||
|
||||
test('#657 D3: a collapsed candidate list says so under the options, and only then', async () => {
|
||||
const m = await mounted({ [`GET ${ITEMS}/${ITEM}`]: () => response(200, detail({ collapsed: { shown: 2, total: 40, paths: 90 } })) });
|
||||
try {
|
||||
const line = m.f.walk(m.view.root, n => /review-collapsed/.test(n.className ?? ''))[0];
|
||||
assert.equal(line.textContent, 'Showing the 2 most used of 40 prompts in this file.');
|
||||
assert.equal(m.visible(line), true);
|
||||
} finally { m.done(); }
|
||||
const plain = await mounted();
|
||||
try {
|
||||
const line = plain.f.walk(plain.view.root, n => /review-collapsed/.test(n.className ?? ''))[0];
|
||||
assert.equal(plain.visible(line), false);
|
||||
} finally { plain.done(); }
|
||||
});
|
||||
@@ -954,42 +954,3 @@ test('record accepts an image\'s own category on any link status (#332)', () =>
|
||||
assert.equal(record.library.category_scope, 'image');
|
||||
}
|
||||
});
|
||||
|
||||
test('a backslash inside a name is accepted only from a POSIX listing (#646)', () => {
|
||||
const inspectPath = contract('inspectPath');
|
||||
const path = 'model.safetensors\\2026-11-17/a.png';
|
||||
assert.equal(inspectPath({root_index:0, path, root_scope:scopeA, path_style:'posix'}),
|
||||
`/prompt_manager/images/inspect/model.safetensors%5C2026-11-17/a.png?root=0&root_scope=${scopeA}`);
|
||||
for (const path_style of [undefined, 'windows', 'POSIX'])
|
||||
assert.throws(() => inspectPath({root_index:0, path, root_scope:scopeA, path_style}), /Invalid inspection identity/);
|
||||
// The mark relaxes only the backslash: traversal, drives and empty names stay refused.
|
||||
for (const bad of ['../a.png', 'a/../b.png', 'C:\\a.png', 'a//b.png', '/a.png'])
|
||||
assert.throws(() => inspectPath({root_index:0, path:bad, root_scope:scopeA, path_style:'posix'}), /Invalid inspection identity/);
|
||||
});
|
||||
|
||||
// #659: the file's Needs review item (`review`), kept as the server names it.
|
||||
test('record keeps the review facet: a pending item, decided, or null', () => {
|
||||
const toInspectionRecord = contract('toInspectionRecord'), entry = image();
|
||||
const item = '0a1b2c3d-0000-4000-8000-00000000abcd';
|
||||
const of = review => {
|
||||
const data = envelope(entry);
|
||||
if (review !== undefined) data.review = review;
|
||||
return toInspectionRecord(data, entry, extractGenerationFacts).review;
|
||||
};
|
||||
assert.deepEqual(of({ state: 'pending', item_id: item }), { state: 'pending', item_id: item });
|
||||
assert.deepEqual(of({ state: 'decided' }), { state: 'decided' });
|
||||
assert.equal(of(null), null);
|
||||
assert.equal(of(undefined), null);
|
||||
// Anything else offers no choice (and never fails the inspection).
|
||||
for (const review of ['pending', [], {}, { state: 'pending' }, { state: 'pending', item_id: 7 }, { state: 'pending', item_id: 'x' },
|
||||
{ state: 'pending', item_id: item.toUpperCase() }, { state: 'pending', item_id: item, extra: 1 }, { state: 'decided', item_id: item },
|
||||
{ state: 'unresolved' }]) assert.equal(of(review), null, JSON.stringify(review));
|
||||
const record = of({ state: 'pending', item_id: item });
|
||||
assert.ok(Object.isFrozen(record));
|
||||
});
|
||||
|
||||
test('a legacy payload carries no review facet', () => {
|
||||
const data = envelope(); delete data.inspection_version;
|
||||
const record = contract('projectInspectionPayload')({ ...data, review: { state: 'decided' } }, {}, null, () => ({}), true);
|
||||
assert.equal(record.review, null);
|
||||
});
|
||||
|
||||
@@ -143,7 +143,7 @@ test('the shelf no longer sorts by rating (D153)',async()=>{
|
||||
const {createLibraryStream}=await source;const s=createLibraryStream({api:{get:async()=>page([])}});
|
||||
await assert.rejects(s.reset({sort:'rating'}),/Invalid library sort/);
|
||||
assert.throws(()=>createLibraryStream({api:{get:async()=>page([])},restore:{filters:{sort:'rating'},state:{}}}),/Invalid library sort/);
|
||||
for(const sort of ['newest','oldest','name','name-desc','most-used','last-used']) assert.equal(await s.reset({sort}),0);s.dispose();
|
||||
for(const sort of ['newest','oldest','name']) assert.equal(await s.reset({sort}),0);s.dispose();
|
||||
});
|
||||
test('Refine › Folder nests each folder under its exact parent, by path segment (#444 live B1)',async()=>{
|
||||
const {libraryFolderOptions}=await source;assert.equal(typeof libraryFolderOptions,'function');
|
||||
|
||||
@@ -41,25 +41,3 @@ test("without the API client nothing is fetched", async () => {
|
||||
assert.equal(await module.loadInspectionSemantics(), null);
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
|
||||
// #657: a `first-present` selector (rgthree Any Switch) has exactly `strategy` and a non-empty `input_prefix` of at most
|
||||
// 128 characters, as utils/inspection_semantics.py checks; the browser rejected nothing about a selector before.
|
||||
test("the compiler checks a first-present selector as strictly as the server", async () => {
|
||||
const { compileSemantics, SemanticsError } = await import("../../web/js/workspace/local-resolver.mjs");
|
||||
const real = compileSemantics(JSON.parse(TABLE));
|
||||
assert.deepEqual(real.selectors.get("Any Switch (rgthree)"), { strategy: "first-present", input_prefix: "any_" });
|
||||
const valid = { strategy: "first-present", input_prefix: "any_" };
|
||||
for (const entry of [{ ...valid, condition: "boolean" }, { strategy: "first-present" }, { ...valid, input_prefix: "" },
|
||||
{ ...valid, input_prefix: "a".repeat(129) }, { ...valid, input_prefix: 1 }]) {
|
||||
const doc = JSON.parse(TABLE);
|
||||
doc.selectors["Any Switch (rgthree)"] = entry;
|
||||
assert.throws(() => compileSemantics(doc), SemanticsError, JSON.stringify(entry));
|
||||
}
|
||||
// 128 code points, as Python's len(): an emoji is one, though two UTF-16 units.
|
||||
for (const [prefix, ok] of [["a".repeat(128), true], ["\u{1F600}".repeat(128), true], ["\u{1F600}".repeat(129), false]]) {
|
||||
const doc = JSON.parse(TABLE);
|
||||
doc.selectors["Any Switch (rgthree)"] = { ...valid, input_prefix: prefix };
|
||||
if (ok) assert.doesNotThrow(() => compileSemantics(doc));
|
||||
else assert.throws(() => compileSemantics(doc), SemanticsError);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
// #646: Needs review hands the viewer and inspector the same identity the Images listing does, the POSIX mark
|
||||
// for a name holding a backslash included.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { imageOf } from '../../web/js/workspace/review.mjs';
|
||||
import { inspectPath } from '../../web/js/workspace/inspection-state.mjs';
|
||||
|
||||
const scope = 'a'.repeat(64);
|
||||
const item = target => ({ filename: 'a.png', target, url: '/u', thumbnail_url: null, is_video: false });
|
||||
|
||||
test('a review item keeps the POSIX mark of a name holding a backslash', () => {
|
||||
const path = 'm.safetensors\\2026-11-17/a.png';
|
||||
const image = imageOf(item({ root_index: 0, root_scope: scope, path, path_style: 'posix' }));
|
||||
assert.equal(image.path_style, 'posix');
|
||||
assert.equal(inspectPath(image), `/prompt_manager/images/inspect/m.safetensors%5C2026-11-17/a.png?root=0&root_scope=${scope}`);
|
||||
});
|
||||
|
||||
test('a review item without the mark, or with another value, carries none', () => {
|
||||
for (const path_style of [undefined, 'windows', 'POSIX']) {
|
||||
const image = imageOf(item({ root_index: 0, root_scope: scope, path: 'a\\b.png', path_style }));
|
||||
assert.equal(Object.hasOwn(image, 'path_style'), false);
|
||||
assert.throws(() => inspectPath(image), /Invalid inspection identity/);
|
||||
}
|
||||
assert.equal(Object.hasOwn(imageOf(item({ root_index: 0, root_scope: scope, path: 'p/a.png' })), 'path_style'), false);
|
||||
});
|
||||
@@ -197,57 +197,6 @@ test('nothing selectable: the reasons are summed, there is no choice and apply s
|
||||
const linkRoute = (body = {}) => ({ [`POST ${ITEMS}/one/link`]: call => response(200, { success: true, library_epoch: EPOCH, total: 1,
|
||||
item: { ...QUEUE[0], state: 'selected', revision: 1 }, pair: { id: call.body.pair_id ?? 7, image_id: 3, status: 'added' }, ...body }) });
|
||||
|
||||
test('#657 D4: imageChoices lists the choosable candidates once per prompt pair, with non-blank positive text', async () => {
|
||||
const { imageChoices, contextOptions } = await load();
|
||||
const detail = detailOf(QUEUE[0], { candidates: [
|
||||
candidate(HASH_C, '9', 'No positive / Soft negative', null, 'blur', 'unresolved'),
|
||||
candidate(HASH_A, '12', 'Dunes / Soft negative', 'golden dunes', 'blur'),
|
||||
candidate('1'.repeat(64), '13', 'Dunes / Soft negative', 'golden dunes', 'blur'),
|
||||
candidate('2'.repeat(64), '14', ' / Soft negative', ' ', 'blur'),
|
||||
candidate(HASH_B, '28', 'Dunes / No negative', 'golden dunes', ''),
|
||||
] });
|
||||
const choices = imageChoices(contextOptions(detail));
|
||||
assert.deepEqual(choices.map(choice => [choice.value, choice.positive, choice.negative]),
|
||||
[[HASH_A, 'golden dunes', 'blur'], [HASH_B, 'golden dunes', '']]);
|
||||
assert.ok(Object.isFrozen(choices));
|
||||
// An unavailable file has nothing to apply.
|
||||
assert.deepEqual(imageChoices(contextOptions({ ...detail, target: null })), []);
|
||||
});
|
||||
|
||||
test('#657 D4: applyCandidate decides the open item with that candidate, as Apply association does', async () => {
|
||||
const { c, h } = await loaded();
|
||||
assert.equal(await c.applyCandidate({ itemId: 'two', hash: HASH_B }), false, 'not the open item');
|
||||
assert.equal(c.state.warning, '');
|
||||
assert.equal(await c.applyCandidate({ itemId: 'one', hash: HASH_C }), false, 'a disabled candidate');
|
||||
// The dialog's choice is no longer offered (the detail was read again meanwhile): it says so.
|
||||
assert.equal(c.state.warning, 'This prompt is no longer offered for this file. Choose again.');
|
||||
assert.equal(await c.applyCandidate({ itemId: 'one', hash: 'gone' }), false, 'a candidate the detail no longer lists');
|
||||
assert.equal(c.state.warning, 'This prompt is no longer offered for this file. Choose again.');
|
||||
assert.equal(h.of('POST', OBSERVE).length, 0);
|
||||
assert.equal(await c.applyCandidate({ itemId: 'one', hash: HASH_B }), true);
|
||||
const [decision] = h.of('POST', `${ITEMS}/one/decision`);
|
||||
assert.equal(decision.body.choice, HASH_B);
|
||||
assert.equal(c.state.toast, 'Association accepted.');
|
||||
assert.equal(c.state.selectedId, 'two');
|
||||
});
|
||||
|
||||
test('#657 D4: an unanswered applyCandidate asks to press Link image again, and that resends the same body once', async () => {
|
||||
let attempts = 0;
|
||||
const { c, h } = await loaded({
|
||||
[`POST ${ITEMS}/one/decision`]: () => {
|
||||
attempts += 1;
|
||||
if (attempts === 1) return Promise.reject(new TypeError('Failed to fetch'));
|
||||
return response(200, { success: true, library_epoch: EPOCH, total: 1, item: { ...QUEUE[0], state: 'selected', revision: 1 } });
|
||||
},
|
||||
});
|
||||
assert.equal(await c.applyCandidate({ itemId: 'one', hash: HASH_B }), false);
|
||||
assert.equal(c.state.warning, 'The link may not have been saved. Press Link image again to send the same choice once more.');
|
||||
assert.equal(await c.applyCandidate({ itemId: 'one', hash: HASH_B }), true);
|
||||
const [first, second] = h.of('POST', `${ITEMS}/one/decision`);
|
||||
assert.deepEqual(second.body, first.body);
|
||||
assert.equal(h.of('POST', OBSERVE).length, 1);
|
||||
});
|
||||
|
||||
test('link posts the chosen prompt and recipe with a fresh capture, then the next item opens', async () => {
|
||||
const { c, h } = await loaded({ ...linkRoute(), [`GET ${ITEMS}/one`]: () => response(200, unreadable()) });
|
||||
assert.equal(await c.link({ itemId: 'one', positiveId: 4, pairId: 9, title: 'Harbor' }), true);
|
||||
@@ -915,175 +864,3 @@ test('M5: an unanswered decision that landed finishes as recorded, not as decide
|
||||
assert.doesNotMatch(c.state.warning, /decided elsewhere/);
|
||||
assert.equal(h.of('DELETE', CAPTURE).length, 0, 'the server used the capture');
|
||||
});
|
||||
|
||||
// #659: the single-item mode Inspect's Choose prompt runs: one named item, its detail, one decision, no queue.
|
||||
async function single(extra, itemId = 'one') {
|
||||
const { createReviewController } = await load();
|
||||
const h = harness(routes(extra));
|
||||
const c = createReviewController({ api: h.api, itemId });
|
||||
await c.load();
|
||||
await settle();
|
||||
return { c, h };
|
||||
}
|
||||
const listReads = h => h.calls.filter(call => call.method === 'GET' && call.url.split('?')[0] === ITEMS);
|
||||
const detailReads = (h, id = 'one') => h.of('GET', `${ITEMS}/${id}`);
|
||||
|
||||
test('single-item mode never reads the list and loads its item', async () => {
|
||||
const { c, h } = await single();
|
||||
assert.equal(listReads(h).length, 0);
|
||||
assert.equal(detailReads(h).length, 1);
|
||||
assert.equal(c.state.status, 'ready');
|
||||
assert.equal(c.state.selectedId, 'one');
|
||||
assert.equal(c.state.detailStatus, 'ready');
|
||||
assert.equal(c.state.phase, 'idle');
|
||||
assert.equal(c.state.decided, false);
|
||||
assert.deepEqual(c.state.options.map(option => [option.label, option.disabled]), [
|
||||
['Sampler 9 · No positive / Soft negative', true],
|
||||
['Sampler 12 · Dunes / Soft negative', false],
|
||||
['Sampler 28 · Dunes / Harsh negative', false],
|
||||
]);
|
||||
assert.equal(c.state.choice, HASH_A);
|
||||
assert.equal(c.state.warning, '');
|
||||
c.choose(HASH_B);
|
||||
assert.equal(c.state.prompts.negative.text, 'noise');
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
test('single-item mode ends decided after a recorded decision, without reading the queue', async () => {
|
||||
const { c, h } = await single();
|
||||
c.choose(HASH_B);
|
||||
assert.equal(await c.apply(), true);
|
||||
await settle();
|
||||
const [decision] = h.of('POST', `${ITEMS}/one/decision`);
|
||||
assert.equal(decision.body.choice, HASH_B);
|
||||
assert.equal(decision.body.capture_token, 'capture-1');
|
||||
assert.equal(decision.body.expected_epoch, EPOCH);
|
||||
assert.equal(c.state.phase, 'decided');
|
||||
assert.equal(c.state.decided, true);
|
||||
assert.equal(c.state.decisions, 1);
|
||||
assert.equal(c.state.toast, 'Association accepted.');
|
||||
assert.equal(listReads(h).length, 0);
|
||||
assert.equal(detailReads(h).length, 1);
|
||||
// A decided controller decides nothing more.
|
||||
assert.equal(await c.apply(), false);
|
||||
assert.equal(await c.leaveUnresolved(), false);
|
||||
assert.equal(h.of('POST', `${ITEMS}/one/decision`).length, 1);
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
test('single-item Leave unresolved decides the item as unresolved', async () => {
|
||||
const { c, h } = await single();
|
||||
assert.equal(await c.leaveUnresolved(), true);
|
||||
const [decision] = h.of('POST', `${ITEMS}/one/decision`);
|
||||
assert.equal(decision.body.choice, 'unresolved');
|
||||
assert.equal(c.state.decided, true);
|
||||
assert.equal(c.state.toast, 'Left unresolved.');
|
||||
assert.equal(listReads(h).length, 0);
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
for (const code of ['review-conflict', 'review-missing']) {
|
||||
test(`single-item mode re-reads its detail after a ${code} refusal`, async () => {
|
||||
let reads = 0;
|
||||
const { c, h } = await single({
|
||||
[`GET ${ITEMS}/one`]: () => {
|
||||
reads += 1;
|
||||
return reads === 1 || code === 'review-conflict' ? response(200, detailOf(QUEUE[0], { revision: reads }))
|
||||
: fail(404, 'review-missing', 'This review item no longer exists. Reload the queue.');
|
||||
},
|
||||
[`POST ${ITEMS}/one/decision`]: () => fail(code === 'review-missing' ? 404 : 409, code, `refused: ${code}`),
|
||||
});
|
||||
assert.equal(await c.apply(), false);
|
||||
await settle();
|
||||
assert.equal(listReads(h).length, 0);
|
||||
assert.equal(detailReads(h).length, 2);
|
||||
assert.equal(c.state.phase, 'idle');
|
||||
assert.equal(c.state.decided, false);
|
||||
// The refused capture is released.
|
||||
assert.equal(h.of('DELETE', CAPTURE).length, 1);
|
||||
if (code === 'review-conflict') {
|
||||
assert.equal(c.state.detailStatus, 'ready');
|
||||
assert.equal(c.state.detail.revision, 2);
|
||||
assert.equal(c.state.warning, `refused: ${code}`);
|
||||
} else {
|
||||
// The item is gone: its sentence, and nothing more is read.
|
||||
assert.equal(c.state.detailStatus, 'error');
|
||||
assert.equal(c.state.warning, 'This review item no longer exists. Reload the queue.');
|
||||
await settle();
|
||||
assert.equal(detailReads(h).length, 2);
|
||||
}
|
||||
c.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
test('single-item refusal keeps the item open with the server sentence', async () => {
|
||||
const { c, h } = await single({
|
||||
[`POST ${ITEMS}/one/decision`]: () => fail(409, 'file-changed', 'The file changed since it was queued.'),
|
||||
});
|
||||
assert.equal(await c.apply(), false);
|
||||
assert.equal(c.state.phase, 'idle');
|
||||
assert.equal(c.state.warning, 'The file changed since it was queued.');
|
||||
assert.equal(c.state.detailStatus, 'ready');
|
||||
assert.equal(detailReads(h).length, 1);
|
||||
assert.equal(listReads(h).length, 0);
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
test('single-item unanswered decision resends the same body once', async () => {
|
||||
let attempts = 0;
|
||||
const { c, h } = await single({
|
||||
[`POST ${ITEMS}/one/decision`]: call => {
|
||||
attempts += 1;
|
||||
if (attempts === 1) return Promise.reject(new TypeError('Failed to fetch'));
|
||||
return response(200, { success: true, library_epoch: EPOCH, total: 1, item: { ...QUEUE[0], state: 'selected', revision: 1 } });
|
||||
},
|
||||
});
|
||||
assert.equal(await c.apply(), false);
|
||||
assert.equal(c.state.canRetry, true);
|
||||
assert.equal(c.state.warning, 'The decision may not have been saved. Apply again to send the same decision once more.');
|
||||
assert.equal(await c.retry(), true);
|
||||
const [first, second] = h.of('POST', `${ITEMS}/one/decision`);
|
||||
assert.deepEqual(second.body, first.body);
|
||||
assert.equal(h.of('POST', OBSERVE).length, 1);
|
||||
assert.equal(c.state.decided, true);
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
test('single-item mode opens an item already decided as decided', async () => {
|
||||
const { c, h } = await single({
|
||||
[`GET ${ITEMS}/one`]: () => response(200, detailOf({ ...QUEUE[0], state: 'selected', revision: 1 })),
|
||||
});
|
||||
assert.equal(c.state.decided, true);
|
||||
assert.equal(c.state.phase, 'decided');
|
||||
assert.equal(await c.apply(), false);
|
||||
assert.equal(h.of('POST', OBSERVE).length, 0);
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
test('single-item refresh re-reads the detail, never the list; leave does nothing', async () => {
|
||||
const { c, h } = await single();
|
||||
await c.refresh();
|
||||
await c.sync({ library_epoch: EPOCH, review_revision: 9 });
|
||||
await c.leave();
|
||||
await settle();
|
||||
assert.equal(listReads(h).length, 0);
|
||||
assert.ok(detailReads(h).length >= 2);
|
||||
assert.equal(c.state.selectedId, 'one');
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
test('single-item failed detail read is an error with its retry', async () => {
|
||||
let reads = 0;
|
||||
const { c, h } = await single({
|
||||
[`GET ${ITEMS}/one`]: () => (++reads === 1 ? fail(500, 'review-failed', 'The review queue could not be read.') : response(200, detailOf(QUEUE[0]))),
|
||||
});
|
||||
assert.equal(c.state.detailStatus, 'error');
|
||||
assert.equal(c.state.warning, COPY_DETAIL_FAILED);
|
||||
await c.load();
|
||||
await settle();
|
||||
assert.equal(c.state.detailStatus, 'ready');
|
||||
assert.equal(c.state.warning, '');
|
||||
assert.equal(listReads(h).length, 0);
|
||||
c.dispose();
|
||||
});
|
||||
const COPY_DETAIL_FAILED = 'This item could not be read. Select it again to retry.';
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user