Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d509c885e | ||
|
|
96ce361b82 | ||
|
|
9d058a0035 | ||
|
|
4aa71c4026 | ||
|
|
a695457cce | ||
|
|
c9d2b9c66b | ||
|
|
98ba01d670 | ||
|
|
6c19f0a228 | ||
|
|
a387643946 | ||
|
|
1a177e39a2 | ||
|
|
faac2d6f52 | ||
|
|
2bf3e5202d | ||
|
|
71b55bc630 | ||
|
|
4c9cb7f5ea |
+1
-4
@@ -19,7 +19,4 @@
|
||||
/.flake8
|
||||
/.pre-commit-config.yaml
|
||||
/.gitignore
|
||||
|
||||
# Stray images no code uses
|
||||
/image_meta_data.png
|
||||
/test_metadata_file.png
|
||||
/.gitattributes
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Pinned files are compared byte for byte with their recorded hashes
|
||||
# (npm run --prefix tools/vendor check). Git must never convert their line
|
||||
# endings, which Git for Windows does by default (core.autocrlf=true, #636).
|
||||
/web/lib/viewerjs/** -text
|
||||
/web/js/shared/toolkit/** -text
|
||||
/web/js/workspace/concept.css -text
|
||||
/docs/concepts/workspace/style.css -text
|
||||
@@ -0,0 +1,15 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
polar: # Replace with a single Polar username
|
||||
buy_me_a_coffee: veets
|
||||
thanks_dev: # Replace with a single thanks.dev username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
@@ -4,6 +4,10 @@ updates:
|
||||
# Python dependencies (requirements.txt / setup.cfg / pyproject.toml)
|
||||
- package-ecosystem: "pip"
|
||||
directory: "/"
|
||||
# Our requirements are minimum versions that install into ComfyUI's shared
|
||||
# environment. Leave a floor alone when it already allows the new release;
|
||||
# raising it would force-upgrade the package for every other custom node.
|
||||
versioning-strategy: "increase-if-necessary"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "sunday"
|
||||
|
||||
@@ -17,11 +17,39 @@ concurrency:
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads
|
||||
# them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The
|
||||
# jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so
|
||||
# the required context still reports. This workflow has no gate job, so the scan runs whenever the
|
||||
# class is not "docs" or "inert": a classifier that fails or prints nothing means a full scan. The clone has every commit but no file contents (blob:none): the
|
||||
# script only compares file names between the base and the head.
|
||||
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 || github.event.merge_group.base_sha || github.event.before }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }}
|
||||
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
security:
|
||||
name: bandit (high severity)
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
|
||||
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.
|
||||
# 40254137380, 40240706583 took 23s / 16s / 23s -> 5 min. change class (#639): 5 min, the floor.
|
||||
timeout-minutes: 5
|
||||
|
||||
steps:
|
||||
|
||||
@@ -35,26 +35,60 @@ env:
|
||||
# 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)
|
||||
# change class (#639): a file-less checkout and one stdlib script, 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:
|
||||
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads
|
||||
# them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The
|
||||
# jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so
|
||||
# the required contexts still report; "all tests" 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 only compares file names between the base and the head.
|
||||
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 || github.event.merge_group.base_sha || github.event.before }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }}
|
||||
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
test:
|
||||
name: py${{ matrix.python-version }} on ${{ matrix.os }}
|
||||
# A skipped matrix job reports under its unexpanded name, which would leave the required context
|
||||
# "py3.12 on ubuntu-latest" waiting for ever. So this job always runs: a docs change gets the 3.12
|
||||
# leg only, and for an inert change the leg starts and its steps are skipped (#639).
|
||||
needs: changes
|
||||
if: ${{ !cancelled() }}
|
||||
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"]') }}
|
||||
python-version: ${{ (github.event_name == 'pull_request' || needs.changes.outputs.class == 'docs' || needs.changes.outputs.class == 'inert') && fromJSON('["3.12"]') || fromJSON('["3.12", "3.13", "3.14"]') }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
if: needs.changes.outputs.class != 'inert'
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
if: needs.changes.outputs.class != 'inert'
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
@@ -62,18 +96,26 @@ jobs:
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
- name: Install dependencies
|
||||
if: needs.changes.outputs.class != 'inert'
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements-dev.txt
|
||||
|
||||
- name: Run tests
|
||||
if: needs.changes.outputs.class != 'inert'
|
||||
run: python -m tests.run_suite -v
|
||||
|
||||
- name: Nothing to test
|
||||
if: needs.changes.outputs.class == 'inert'
|
||||
run: echo "Only inert files changed (tools/ci/change_class.py); no test can be affected."
|
||||
|
||||
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'
|
||||
# required context never blocks a pull request; "all tests" fails if it is skipped anywhere else
|
||||
# for a code change. Docs and inert changes skip it everywhere (#639).
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && github.event_name != 'pull_request' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
|
||||
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
|
||||
@@ -174,6 +216,8 @@ jobs:
|
||||
|
||||
coverage:
|
||||
name: coverage gate (85%)
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
@@ -201,7 +245,8 @@ jobs:
|
||||
# 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'
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
@@ -225,6 +270,8 @@ jobs:
|
||||
|
||||
lint:
|
||||
name: black and flake8
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
@@ -241,6 +288,8 @@ jobs:
|
||||
|
||||
js-test:
|
||||
name: frontend modules
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
@@ -268,9 +317,11 @@ jobs:
|
||||
# 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.
|
||||
# For a docs or inert change (#639) the test matrix must still succeed and every other job must be
|
||||
# skipped. The classifier itself must succeed, and a class it does not print fails the gate.
|
||||
all-tests:
|
||||
name: all tests
|
||||
needs: [test, comfyui, coverage, lint, js-test]
|
||||
needs: [changes, test, comfyui, coverage, lint, js-test]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
@@ -278,18 +329,26 @@ jobs:
|
||||
- name: Require every test job for this event
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
CHANGES_RESULT: ${{ needs.changes.result }}
|
||||
CHANGE_CLASS: ${{ needs.changes.outputs.class }}
|
||||
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
|
||||
echo "change class: $CHANGE_CLASS (classifier: $CHANGES_RESULT)"
|
||||
test "$CHANGES_RESULT" = success
|
||||
case "$CHANGE_CLASS" in
|
||||
code) code_only=success; queue_only=success ;;
|
||||
docs|inert) code_only=skipped; queue_only=skipped ;;
|
||||
*) echo "::error::unknown change class"; exit 1 ;;
|
||||
esac
|
||||
if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi
|
||||
echo "event: $EVENT_NAME (real ComfyUI must be $queue_only)"
|
||||
echo "event: $EVENT_NAME (real ComfyUI must be $queue_only; coverage, lint and js-test must be $code_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"
|
||||
test "$TEST_RESULT" = success && test "$COVERAGE_RESULT" = "$code_only" && test "$LINT_RESULT" = "$code_only" && test "$JS_RESULT" = "$code_only" && test "$COMFYUI_RESULT" = "$queue_only"
|
||||
|
||||
@@ -45,9 +45,39 @@ concurrency:
|
||||
# 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.
|
||||
# change class (#639): a file-less checkout and one stdlib script, 5 min (the floor of test.yml).
|
||||
jobs:
|
||||
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads
|
||||
# them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The
|
||||
# jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so
|
||||
# the required contexts still report; "viewerjs" 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 only compares file names between the base and the head.
|
||||
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 || github.event.merge_group.base_sha || github.event.before }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }}
|
||||
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
frontend-coverage:
|
||||
name: frontend coverage (shard ${{ matrix.shard }}/4)
|
||||
# Code changes only (#639): no browser test reads a docs or inert file.
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
|
||||
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;
|
||||
@@ -117,7 +147,8 @@ jobs:
|
||||
|
||||
frontend-coverage-merge:
|
||||
name: frontend coverage (merge)
|
||||
needs: frontend-coverage
|
||||
needs: [changes, frontend-coverage]
|
||||
if: ${{ !cancelled() && needs.frontend-coverage.result == 'success' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
|
||||
runs-on: ubuntu-latest
|
||||
# Same image as the shards: the raw files name sources by the container's workspace path.
|
||||
container:
|
||||
@@ -186,7 +217,9 @@ jobs:
|
||||
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'
|
||||
# Code changes only (#639).
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && github.event_name != 'pull_request' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
|
||||
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;
|
||||
@@ -245,9 +278,10 @@ jobs:
|
||||
# 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.
|
||||
# Any failure, cancellation or other skip fails it. For a docs or inert change (#639) all three
|
||||
# must be skipped. The classifier itself must succeed, and a class it does not print fails the gate.
|
||||
viewerjs:
|
||||
needs: [frontend-coverage, frontend-coverage-merge, browser-workflows]
|
||||
needs: [changes, frontend-coverage, frontend-coverage-merge, browser-workflows]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
@@ -255,14 +289,22 @@ jobs:
|
||||
- name: Require every frontend job to succeed
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
CHANGES_RESULT: ${{ needs.changes.result }}
|
||||
CHANGE_CLASS: ${{ needs.changes.outputs.class }}
|
||||
COVERAGE_RESULT: ${{ needs.frontend-coverage.result }}
|
||||
MERGE_RESULT: ${{ needs.frontend-coverage-merge.result }}
|
||||
WORKFLOWS_RESULT: ${{ needs.browser-workflows.result }}
|
||||
run: |
|
||||
queue_only=success
|
||||
echo "change class: $CHANGE_CLASS (classifier: $CHANGES_RESULT)"
|
||||
test "$CHANGES_RESULT" = success
|
||||
case "$CHANGE_CLASS" in
|
||||
code) code_only=success; queue_only=success ;;
|
||||
docs|inert) code_only=skipped; queue_only=skipped ;;
|
||||
*) echo "::error::unknown change class"; exit 1 ;;
|
||||
esac
|
||||
if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi
|
||||
echo "event: $EVENT_NAME (browser-workflows must be $queue_only)"
|
||||
echo "event: $EVENT_NAME (browser-workflows must be $queue_only; coverage and its merge must be $code_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"
|
||||
test "$COVERAGE_RESULT" = "$code_only" && test "$MERGE_RESULT" = "$code_only" && test "$WORKFLOWS_RESULT" = "$queue_only"
|
||||
|
||||
@@ -22,9 +22,10 @@ repos:
|
||||
types: [python]
|
||||
exclude: ^(tests/|reference/)
|
||||
|
||||
# Skipped when the pushed commits only change inert files (tools/ci/change_class.py, #639).
|
||||
- id: tests
|
||||
name: tests
|
||||
entry: python -m tests.run_suite -q
|
||||
entry: python tools/ci/change_class.py --unless-inert python -m tests.run_suite -q
|
||||
language: system
|
||||
pass_filenames: false
|
||||
stages: [pre-push]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||

|
||||
|
||||
# ComfyUI Prompt Manager
|
||||
|
||||
**Every prompt you run, every image it made, and every negative you tried, in one searchable library inside ComfyUI.**
|
||||
@@ -12,10 +14,10 @@ Prompt Manager saves your prompts as you generate, links each image back to the
|
||||
|
||||
## What's new: rebuilt from the ground up
|
||||
|
||||
- **A new UI.** One app, the workspace, replaces the separate dashboard, gallery and metadata pages. The old pages still work if you want them.
|
||||
- **A new UI.** One app, the workspace, replaces the separate dashboard, gallery and metadata pages.
|
||||
- **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.
|
||||
- **Mac, Linux and Windows.** The Python suite runs on all three, on Python 3.12, 3.13 and 3.14.
|
||||
- **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.
|
||||
|
||||
## See it
|
||||
|
||||
@@ -101,7 +103,7 @@ Pick an open ComfyUI window and a node, then review the exact before and after.
|
||||
|
||||
### Deletes you can review
|
||||
|
||||
Choose what happens to the files before anything is removed: remove the image from the library and leave the file on disk, or on Linux and macOS also move it to the system trash. On Windows, images can only be removed from the library. A safety backup of the database is on by default, and removed images can be brought back.
|
||||
Choose what happens to the files before anything is removed: remove the image from the library and leave the file on disk, or on Linux and macOS also move it to the system trash. On a Linux or BSD server you can also delete the files permanently, for headless servers where a trash only fills up the disk; those files can't be recovered. On Windows, images can only be removed from the library. A safety backup of the database is on by default, and removed images can be brought back.
|
||||
|
||||

|
||||
|
||||
@@ -212,9 +214,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 still work
|
||||
## The old pages will be removed
|
||||
|
||||
They stay at their URLs, and System's Overview section links to them:
|
||||
They still work at their URLs for now and will be removed in a future release. Everything they do is moving to the workspace.
|
||||
|
||||
| Page | URL |
|
||||
| --- | --- |
|
||||
@@ -228,6 +230,7 @@ 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.
|
||||
|
||||
+58
-8
@@ -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/2
|
||||
npm run --prefix tools/vendor test:workflows -- --project webkit --shard 2/3
|
||||
```
|
||||
|
||||
`coverage:merge` refuses an empty raw directory; it does not count shards, so run
|
||||
@@ -193,8 +193,8 @@ waiting for the `frontend coverage` jobs.
|
||||
|
||||
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,
|
||||
`frontend coverage (merge)` to succeed on every event. The six
|
||||
`page workflows (firefox|webkit, shard N/3)` 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
|
||||
@@ -277,6 +277,22 @@ the process exits non-zero.
|
||||
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 `test.yml`, `code-quality.yml`, `viewerjs-check.yml` and
|
||||
`portability.yml` has `timeout-minutes` (`tests/vendor/ci-workflow.test.mjs`
|
||||
@@ -742,6 +758,33 @@ 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.
|
||||
|
||||
### Only changes that can affect code are tested (#639)
|
||||
|
||||
The table above is for a code change. Each of the three workflows starts with a
|
||||
`change class` job that runs `tools/ci/change_class.py` over the files the pull
|
||||
request, merge group or push touches, and the other jobs follow its answer:
|
||||
|
||||
| Class | Files (allowlists in the script) | What runs |
|
||||
| --- | --- | --- |
|
||||
| `inert` | `.github/FUNDING.yml`, `SECURITY.md`, `images/`, `.github/ISSUE_TEMPLATE/` | `change class` and the two gates. `py3.12 on ubuntu-latest` starts and skips its steps, because a skipped matrix job would never report that required context. |
|
||||
| `docs` | `README.md`, `README-legacy.md`, `assets/readme/`, `assets/brand/` (may include inert files) | The above plus the real `py3.12 on ubuntu-latest` suite, which holds the tests that read them (`tests/test_brand_assets.py`, `tests/test_package_contents.py`). |
|
||||
| `code` | Anything else | Everything in the table above. |
|
||||
|
||||
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. `docs/` is code, because the browser suite
|
||||
compares production against `docs/concepts/workspace/`; `TESTING.md` is code,
|
||||
because the tooling tests read its tables. Before adding a file to a list,
|
||||
check that no test and no shipped code opens it.
|
||||
|
||||
The gates enforce the class: for `docs` and `inert` they require the classifier
|
||||
to have succeeded, the Python matrix to have succeeded and every other job to
|
||||
have been skipped; a class the script does not print fails them. `bandit` has no
|
||||
gate, so it runs unless the class is `docs` or `inert`, which means a failed
|
||||
classifier gets a full scan. The required contexts do not change.
|
||||
|
||||
The pre-push hook uses the same script: it skips the Python suite when the
|
||||
pushed commits are `inert` and runs it otherwise.
|
||||
|
||||
## Required merge checks
|
||||
|
||||
`.github/branch-protection.json` records the required checks:
|
||||
@@ -2500,7 +2543,10 @@ 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. **No code path unlinks or overwrites a media file.**
|
||||
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.
|
||||
|
||||
- **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
|
||||
@@ -2735,7 +2781,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, linked only from System (#525, D165)
|
||||
`/prompt_manager/admin` by direct URL (#525, #620)
|
||||
(`tests/browser/workspace.spec.mjs`). `library comparison detects
|
||||
mutations` injects `.card-footer { padding: 2px }` and removes `.card-meta .chip.red`.
|
||||
|
||||
@@ -3243,7 +3289,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`) linked only from System (#525, D165). The page is the concept's `#metadata`
|
||||
(`/prompt_manager/gallery.html`) at its URL only (#525, #620). 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
|
||||
@@ -4665,6 +4711,9 @@ 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).
|
||||
- **D205** (Prompt library, #620, beyond the concept): 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,
|
||||
@@ -7492,7 +7541,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` linked only from System (#525, D165); tag search and sort, the untagged
|
||||
`/prompt_manager/admin#/tags` at its URL only (#525, #620); 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
|
||||
@@ -7624,7 +7673,8 @@ 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** (beyond the concept, maintainer ruling 2026-10-30): System's Overview section ends
|
||||
- **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
|
||||
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.
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 42 KiB |
@@ -291,13 +291,6 @@ 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.
|
||||
|
||||
|
||||
+2
-22
@@ -16,18 +16,17 @@ 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")
|
||||
|
||||
@@ -89,25 +88,6 @@ 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,6 +97,9 @@ _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 = Path(os.path.abspath(temp)).as_uri() + "?mode=ro"
|
||||
uri = readonly_uri(temp)
|
||||
try:
|
||||
with contextlib.closing(sqlite3.connect(uri, uri=True)) as conn:
|
||||
copied = _describe(conn)
|
||||
|
||||
+3
-4
@@ -14,6 +14,7 @@ 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,
|
||||
@@ -1199,7 +1200,7 @@ class PromptModel:
|
||||
if header != SQLITE_HEADER:
|
||||
return False, "Not a SQLite database file"
|
||||
|
||||
uri = Path(os.path.abspath(path)).as_uri() + "?mode=ro"
|
||||
uri = readonly_uri(path)
|
||||
try:
|
||||
conn = sqlite3.connect(uri, uri=True)
|
||||
except sqlite3.Error as e:
|
||||
@@ -1306,9 +1307,7 @@ 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(
|
||||
Path(src_path).resolve().as_uri() + "?mode=ro", uri=True
|
||||
)
|
||||
source = sqlite3.connect(readonly_uri(Path(src_path).resolve()), uri=True)
|
||||
try:
|
||||
target = self.get_connection()
|
||||
# The target is written under backup's step too: mark it in use
|
||||
|
||||
@@ -1049,7 +1049,8 @@ class PromptDatabase(
|
||||
if include_ancestors:
|
||||
ancestors = set()
|
||||
for folder in folders:
|
||||
parts = folder.replace("\\", "/").split("/")
|
||||
# #646: ``folder`` already uses ``/``; on POSIX ``\\`` is a name.
|
||||
parts = folder.split("/")
|
||||
for i in range(1, len(parts)):
|
||||
ancestors.add("/".join(parts[:i]))
|
||||
folders.update(ancestors)
|
||||
|
||||
@@ -42,6 +42,7 @@ 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")
|
||||
|
||||
@@ -114,7 +115,7 @@ def file_digest(path: str) -> str:
|
||||
|
||||
|
||||
def _readonly(path: str) -> sqlite3.Connection:
|
||||
return sqlite3.connect(Path(path).resolve().as_uri() + "?mode=ro", uri=True)
|
||||
return sqlite3.connect(readonly_uri(Path(path).resolve()), uri=True)
|
||||
|
||||
|
||||
def _schema(path: str) -> list:
|
||||
|
||||
@@ -31,7 +31,15 @@ MAX_STATE_BYTES = 4096
|
||||
MAX_TAGS = 20
|
||||
MAX_TAG_LENGTH = 50
|
||||
_IMAGE_SORTS = ("newest", "oldest", "name", "name-desc", "rating")
|
||||
_LIBRARY_SORTS = ("newest", "oldest", "name", "rating")
|
||||
_LIBRARY_SORTS = (
|
||||
"newest",
|
||||
"oldest",
|
||||
"name",
|
||||
"name-desc",
|
||||
"most-used",
|
||||
"last-used",
|
||||
"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).
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""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"
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 85 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 34 KiB |
@@ -3,7 +3,6 @@ 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__:
|
||||
@@ -259,19 +258,6 @@ 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
|
||||
)
|
||||
|
||||
@@ -19,7 +19,6 @@ 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
|
||||
@@ -38,7 +37,6 @@ 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
|
||||
@@ -86,7 +84,6 @@ 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")
|
||||
@@ -433,18 +430,6 @@ class PromptManagerBase:
|
||||
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:
|
||||
@@ -455,13 +440,6 @@ 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,7 +2,6 @@
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
if __package__:
|
||||
@@ -173,19 +172,6 @@ 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,7 +3,6 @@ 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__:
|
||||
@@ -230,19 +229,6 @@ 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,7 +89,6 @@ from .source_rescope import SourceRescopeMixin
|
||||
|
||||
try:
|
||||
from ...database.operations import PromptDatabase
|
||||
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 +100,6 @@ except ImportError:
|
||||
0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
)
|
||||
from database.operations import PromptDatabase
|
||||
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
|
||||
@@ -254,23 +252,6 @@ async def _read_json_body(request, max_bytes=JSON_BODY_MAX_BYTES):
|
||||
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 ────────────────────────────────────────
|
||||
_GZIP_MIN_SIZE = 1024 # Only compress bodies larger than 1 KB
|
||||
_GZIP_TYPES = frozenset(
|
||||
@@ -426,10 +407,6 @@ 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)
|
||||
@@ -486,26 +463,6 @@ 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."""
|
||||
@@ -1079,7 +1036,3 @@ class PromptManagerAPI(
|
||||
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)
|
||||
|
||||
+3
-1
@@ -30,8 +30,10 @@ 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:
|
||||
@@ -399,7 +401,7 @@ def _inspect_restore_upload(path):
|
||||
Returns:
|
||||
None when acceptable, otherwise a human-readable reason (blocking).
|
||||
"""
|
||||
uri = Path(os.path.abspath(path)).as_uri() + "?mode=ro"
|
||||
uri = readonly_uri(path)
|
||||
try:
|
||||
conn = sqlite3.connect(uri, uri=True)
|
||||
except sqlite3.Error as e:
|
||||
|
||||
@@ -943,16 +943,6 @@ 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:
|
||||
@@ -1421,7 +1411,8 @@ class AutotagRoutesMixin:
|
||||
)
|
||||
|
||||
model_type = service.get_loaded_model_type()
|
||||
service.unload_model()
|
||||
# Off the loop; a dropped request keeps the gate until it ends.
|
||||
await model_gate.run(owner, service.unload_model)
|
||||
finally:
|
||||
model_gate.release(owner)
|
||||
|
||||
|
||||
@@ -45,7 +45,6 @@ import os
|
||||
import sqlite3
|
||||
import tempfile
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
@@ -56,6 +55,7 @@ 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,6 +66,7 @@ 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 (
|
||||
@@ -186,7 +187,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 = Path(os.path.abspath(path)).as_uri() + "?mode=ro"
|
||||
uri = readonly_uri(path)
|
||||
with closing(sqlite3.connect(uri, uri=True)) as conn:
|
||||
row = conn.execute("PRAGMA integrity_check").fetchone()
|
||||
except (OSError, sqlite3.Error) as error:
|
||||
|
||||
@@ -304,7 +304,8 @@ def _relative_key(path, root):
|
||||
relative = os.path.relpath(str(path), str(root))
|
||||
except ValueError: # another drive (Windows)
|
||||
return None
|
||||
return os.path.normcase(relative).replace("\\", "/")
|
||||
# #646: on POSIX ``a\\b.png`` and ``a/b.png`` are two files.
|
||||
return os.path.normcase(relative).replace(os.sep, "/")
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -148,7 +148,7 @@ def folder_sets(root, files) -> tuple[frozenset, frozenset]:
|
||||
folders.add(rel_dir)
|
||||
with_ancestors = set(folders)
|
||||
for folder in folders:
|
||||
with_ancestors.update(_ancestors(folder))
|
||||
with_ancestors.update(_ancestors(folder, sep))
|
||||
return frozenset(folders), frozenset(with_ancestors)
|
||||
|
||||
|
||||
@@ -158,7 +158,7 @@ def add_folder(root, path, folders, with_ancestors) -> tuple[frozenset, frozense
|
||||
rel_dir = _folder_of(root, path, sep, prefix)
|
||||
if not rel_dir or rel_dir in folders:
|
||||
return folders, with_ancestors
|
||||
return folders | {rel_dir}, with_ancestors | {rel_dir, *_ancestors(rel_dir)}
|
||||
return folders | {rel_dir}, with_ancestors | {rel_dir, *_ancestors(rel_dir, sep)}
|
||||
|
||||
|
||||
def _root_prefix(root) -> tuple[str, str]:
|
||||
@@ -180,8 +180,10 @@ def _folder_of(root, path, sep, prefix) -> str:
|
||||
return "" if rel_dir == "." else rel_dir
|
||||
|
||||
|
||||
def _ancestors(folder: str) -> list[str]:
|
||||
parts = folder.replace("\\", "/").split("/")
|
||||
def _ancestors(folder: str, sep: str) -> list[str]:
|
||||
# #646: ``\\`` separates only in a Windows root (*sep*, the root flavour's
|
||||
# own); on POSIX it is part of a folder's name.
|
||||
parts = (folder.replace("\\", "/") if sep == "\\" else folder).split("/")
|
||||
return ["/".join(parts[:i]) for i in range(1, len(parts))]
|
||||
|
||||
|
||||
|
||||
+77
-18
@@ -1,9 +1,9 @@
|
||||
"""Delete selected images: remove them from the library, or trash them (#480).
|
||||
"""Delete images: remove from library, trash, or permanently delete.
|
||||
|
||||
``POST /prompt_manager/images/delete/preview {items | filter}`` reviews the
|
||||
selection for both modes at once and answers a reviewed plan (the System ›
|
||||
selection for all modes at once and answers a reviewed plan (the System ›
|
||||
Maintenance contract, ``py/api/maintenance.py``): the token, the counts of
|
||||
the records each file loses, the refused files with a coded reason (both
|
||||
the records each file loses, the refused files with a coded reason (all
|
||||
modes, and the trash-only ones), the prompts that lose their last image and
|
||||
the safety backup. It writes nothing. ``items`` are Images listing identities
|
||||
(at most 500); ``filter`` is "Select all N matching". Each target is matched
|
||||
@@ -19,12 +19,16 @@ again (containment and fingerprint) and
|
||||
in one transaction; the file stays on disk, hidden;
|
||||
- ``mode="trash"``: it is moved to the trash first (``utils/trash.py``); a
|
||||
refused move leaves the file and its records alone; after a move its
|
||||
records are deleted.
|
||||
records are deleted;
|
||||
- ``mode="permanent"``: it is unlinked from disk with ``os.remove``; a refused
|
||||
unlink leaves the file and its records alone; after removal its records are
|
||||
deleted. This mode is Linux/BSD only.
|
||||
|
||||
No path here unlinks a media file. A failed records write stops the job; the
|
||||
files after it are not attempted.
|
||||
Only ``mode="permanent"`` unlinks a media file from disk. A failed records
|
||||
write stops the job; the files after it are not attempted.
|
||||
"""
|
||||
|
||||
import errno
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -59,10 +63,11 @@ except ImportError:
|
||||
from utils.media_folders import is_trash_folder
|
||||
|
||||
IMAGE_DELETE = "delete_images"
|
||||
MODES = ("library", "trash")
|
||||
MODES = ("library", "trash", "permanent")
|
||||
TITLES = {
|
||||
"library": "Delete images (remove from the library)",
|
||||
"trash": "Delete images (move to the trash)",
|
||||
"permanent": "Delete images (permanently delete from disk)",
|
||||
}
|
||||
MAX_DETAIL_ROWS = 50
|
||||
# The system moved the file but its place in a trash could not be shown (#499).
|
||||
@@ -87,8 +92,8 @@ REASONS = {
|
||||
trash.LOCKED: "The file is open in another program. Close it and try again.",
|
||||
trash.FAILED: "The file could not be moved to the trash.",
|
||||
trash.NO_PERMISSION: (
|
||||
"PromptManager isn't allowed to move this file (no permission, or it is "
|
||||
"locked in Finder)."
|
||||
"PromptManager isn't allowed to remove this file (no permission, or it is "
|
||||
"locked)."
|
||||
),
|
||||
trash.CLOUD_SYNC: (
|
||||
"Files in iCloud Drive or a cloud-synced folder can't be moved to the "
|
||||
@@ -114,6 +119,16 @@ SOURCES_CHANGED = "The sources changed since the review; nothing was changed."
|
||||
RECORDS_FAILED = "The image records could not be removed; the job stopped."
|
||||
|
||||
|
||||
def _permanent_delete_code(error: OSError) -> str:
|
||||
"""Translate a removal ``OSError`` into a permanent-delete refusal code."""
|
||||
code = error.errno if error.errno else None
|
||||
if code in (errno.EACCES, errno.EPERM, errno.EROFS):
|
||||
return trash.NO_PERMISSION
|
||||
if code in (errno.ENETUNREACH, errno.ENETRESET, errno.EHOSTUNREACH):
|
||||
return trash.NETWORK
|
||||
return trash.LOCKED
|
||||
|
||||
|
||||
def lexical_problem(relative: str) -> str | None:
|
||||
"""The refusal code a root-relative POSIX path earns before any file access."""
|
||||
parts = relative.split("/")
|
||||
@@ -275,17 +290,23 @@ class ImageDeleteMixin:
|
||||
acted.append(target)
|
||||
counted = db.count_removal_records([t["removal"] for t in acted])
|
||||
library_count = len(acted)
|
||||
permanent_supported = permanent_delete_supported()
|
||||
public = {
|
||||
"operation": IMAGE_DELETE,
|
||||
"scope": {"count": library_count, "label": "images"},
|
||||
"library": {"count": library_count},
|
||||
"trash": {"count": library_count - len(trash_refused)},
|
||||
"permanent": {"count": library_count},
|
||||
"protected": {"count": len(refused), "reasons": []},
|
||||
"refused": _summary(refused),
|
||||
"trash_refused": _summary(trash_refused),
|
||||
"records": counted["records"],
|
||||
"orphaned_prompts": counted["orphaned_prompts"],
|
||||
"media": {"deletes_files": False, "label": "Chosen in the review"},
|
||||
"media": {
|
||||
"deletes_files": permanent_supported,
|
||||
"label": "Chosen in the review",
|
||||
},
|
||||
"permanent_delete_supported": permanent_supported,
|
||||
"details": [],
|
||||
}
|
||||
return {"targets": acted, "public": public}
|
||||
@@ -341,7 +362,11 @@ class ImageDeleteMixin:
|
||||
async def _delete_images(self, job, db, targets, mode, backup):
|
||||
job.update(total=len(targets), status_line=TITLES[mode])
|
||||
roots = [str(root) for root in self._get_all_output_dirs()]
|
||||
done_group = "trashed" if mode == "trash" else "removed"
|
||||
done_group = (
|
||||
"trashed"
|
||||
if mode == "trash"
|
||||
else ("deleted" if mode == "permanent" else "removed")
|
||||
)
|
||||
changed, failed = 0, None
|
||||
for done, target in enumerate(targets, start=1):
|
||||
if failed:
|
||||
@@ -366,17 +391,26 @@ class ImageDeleteMixin:
|
||||
)
|
||||
elif group == done_group:
|
||||
changed += 1
|
||||
detail = (
|
||||
f"Moved to the {label}" if label else "Removed from the library"
|
||||
)
|
||||
if mode == "trash":
|
||||
detail = (
|
||||
f"Moved to the {label}" if label else "Removed from the library"
|
||||
)
|
||||
elif mode == "permanent":
|
||||
detail = "Deleted from disk"
|
||||
else:
|
||||
detail = "Removed from the library"
|
||||
self._record_delete(job, group, target, None, detail)
|
||||
else:
|
||||
self._record_delete(job, group, target, code)
|
||||
job.update(processed=done, progress=int(done / len(targets) * 100))
|
||||
if changed:
|
||||
self.invalidate_gallery_cache()
|
||||
verb = "Moved" if mode == "trash" else "Removed"
|
||||
where = "to the trash" if mode == "trash" else "from the library"
|
||||
if mode == "trash":
|
||||
verb, where = "Moved", "to the trash"
|
||||
elif mode == "permanent":
|
||||
verb, where = "Permanently deleted", "from disk"
|
||||
else:
|
||||
verb, where = "Removed", "from the library"
|
||||
line = f"{verb} {changed:,} of {len(targets):,} images {where}"
|
||||
job.log_line(line)
|
||||
job.update(progress=100, status_line=f"{line} · {backup_note(backup)}")
|
||||
@@ -398,7 +432,7 @@ class ImageDeleteMixin:
|
||||
"code": code,
|
||||
"detail": text,
|
||||
}
|
||||
mark = {"removed": "-", "trashed": "-"}.get(group, "=")
|
||||
mark = {"removed": "-", "trashed": "-", "deleted": "-"}.get(group, "=")
|
||||
job.record(
|
||||
group, row, f"{mark} {target['root_label']}/{target['rel']} · {text}"
|
||||
)
|
||||
@@ -437,6 +471,21 @@ class ImageDeleteMixin:
|
||||
)
|
||||
return "errors", TRASH_UNCONFIRMED, None
|
||||
mark = None
|
||||
elif mode == "permanent":
|
||||
try:
|
||||
os.remove(target["abs"])
|
||||
except OSError as error:
|
||||
if error.errno == errno.ENOENT:
|
||||
pass
|
||||
else:
|
||||
code = _permanent_delete_code(error)
|
||||
self.logger.info(
|
||||
"Not permanently deleted (%s): %s",
|
||||
code,
|
||||
target["rel"],
|
||||
)
|
||||
return "not_changed", code, None
|
||||
mark = None
|
||||
else:
|
||||
mark = (target["size"], target["mtime_ns"])
|
||||
try:
|
||||
@@ -445,7 +494,11 @@ class ImageDeleteMixin:
|
||||
self.logger.exception("Removing an image's records failed")
|
||||
return "errors", None, label
|
||||
_remove_thumbnail(Path(target["root"]), Path(target["rel"]), self.logger)
|
||||
return ("trashed" if mode == "trash" else "removed"), None, label
|
||||
if mode == "trash":
|
||||
return "trashed", None, label
|
||||
if mode == "permanent":
|
||||
return "deleted", None, label
|
||||
return "removed", None, label
|
||||
|
||||
# ── the workspace listing ─────────────────────────────────────────
|
||||
|
||||
@@ -517,6 +570,12 @@ class ImageDeleteMixin:
|
||||
return [path for path in paths if not removed(path)]
|
||||
|
||||
|
||||
def permanent_delete_supported() -> bool:
|
||||
"""Permanent delete is offered only with the Freedesktop trash backend
|
||||
(Linux/BSD servers); the review and the apply both ask here (#644)."""
|
||||
return isinstance(trash.BACKEND, trash.FreedesktopBackend)
|
||||
|
||||
|
||||
def parse_mode(value):
|
||||
"""The apply's ``mode``, or None when it is not one of MODES."""
|
||||
return value if isinstance(value, str) and value in MODES else None
|
||||
|
||||
+22
-8
@@ -70,6 +70,8 @@ try:
|
||||
in_trash_below_roots,
|
||||
in_trash_folder,
|
||||
is_skipped_folder,
|
||||
path_separators,
|
||||
split_relative,
|
||||
)
|
||||
from ...utils.parallel import map_parallel
|
||||
from ...utils.json_strict import dumps_strict
|
||||
@@ -101,6 +103,8 @@ except ImportError:
|
||||
in_trash_below_roots,
|
||||
in_trash_folder,
|
||||
is_skipped_folder,
|
||||
path_separators,
|
||||
split_relative,
|
||||
)
|
||||
from utils.parallel import map_parallel
|
||||
from utils.json_strict import dumps_strict
|
||||
@@ -267,18 +271,23 @@ def _is_within(path, root):
|
||||
|
||||
|
||||
def _has_traversal(relative):
|
||||
"""True for absolute paths, drive-qualified paths or any ``..`` segment."""
|
||||
"""True for absolute paths, drive-qualified paths or any ``..`` segment.
|
||||
|
||||
Segments are split at this server's separators: on POSIX ``\\`` is part
|
||||
of a name, so ``a\\..\\b`` is one name below the root (#646).
|
||||
"""
|
||||
if not relative or os.path.isabs(relative) or os.path.splitdrive(relative)[0]:
|
||||
return True
|
||||
if relative[0] in ("/", "\\"):
|
||||
if relative[0] in path_separators():
|
||||
return True
|
||||
return ".." in re.split(r"[\\/]+", relative)
|
||||
return ".." in split_relative(relative)
|
||||
|
||||
|
||||
def _is_thumbnail_cache_path(relative):
|
||||
"""True when *relative* names something in a root's ``thumbnails/``
|
||||
cache (any case, either separator): never inspected as a media file."""
|
||||
first = re.split(r"[\\/]+", relative.lstrip("\\/"), maxsplit=1)[0]
|
||||
cache (any case, this server's separators, #646): never inspected as a
|
||||
media file."""
|
||||
first = split_relative(relative.lstrip(path_separators()))[0]
|
||||
return first.casefold() == "thumbnails"
|
||||
|
||||
|
||||
@@ -875,7 +884,7 @@ def _favorite_root_key(root) -> str:
|
||||
|
||||
|
||||
def _source_depth(source: str) -> int:
|
||||
return len([part for part in re.split(r"[\\/]+", source) if part])
|
||||
return len([part for part in split_relative(source) if part])
|
||||
|
||||
|
||||
def deepest_source(sources, absolute_path):
|
||||
@@ -1200,6 +1209,10 @@ def _output_image_entry(
|
||||
}
|
||||
if root_scope is not None:
|
||||
entry["root_scope"] = root_scope
|
||||
if "\\" in entry["path"]:
|
||||
# #646: only a POSIX server lists a name holding a backslash (Windows
|
||||
# turns it into ``/``); the workspace accepts it only with this mark.
|
||||
entry["path_style"] = "posix"
|
||||
return entry
|
||||
|
||||
|
||||
@@ -1221,9 +1234,10 @@ def _workspace_filters(query: Mapping) -> dict:
|
||||
folded = text.casefold()
|
||||
media = query.get("media", "all")
|
||||
order = query.get("sort", "newest")
|
||||
folder = query.get("subfolder", "").strip().replace("\\", "/")
|
||||
# #646: ``\\`` separates only on Windows; on POSIX it is part of a name.
|
||||
folder = "/".join(split_relative(query.get("subfolder", "").strip()))
|
||||
# ``path``: one exact relative path (Activity opens a scan row by it, D57).
|
||||
exact = query.get("path", "").strip().replace("\\", "/")
|
||||
exact = "/".join(split_relative(query.get("path", "").strip()))
|
||||
category = query.get("category", "").strip() or None
|
||||
tags = sorted(
|
||||
{tag.strip() for tag in query.get("tags", "").split(",") if tag.strip()}
|
||||
|
||||
+4
-2
@@ -42,6 +42,7 @@ open across the switch (#249 S8).
|
||||
import asyncio
|
||||
import itertools
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
@@ -127,7 +128,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", "not_changed", "errors")
|
||||
IMAGE_DELETE_GROUP_NAMES = ("trashed", "removed", "deleted", "not_changed", "errors")
|
||||
# The System health check (py/api/system.py): a read-only ``read`` job with
|
||||
# no file outcomes, so it may run beside a scan.
|
||||
HEALTH_JOB_KIND = "health"
|
||||
@@ -160,7 +161,8 @@ def _relative_path(path) -> str:
|
||||
or PureWindowsPath(text).drive
|
||||
):
|
||||
return re.split(r"[\\/]", text)[-1]
|
||||
return text.replace("\\", "/")
|
||||
# #646: on POSIX a backslash is part of a name, never a separator.
|
||||
return text.replace("\\", "/") if os.sep == "\\" else text
|
||||
|
||||
|
||||
class JobBusy(Exception):
|
||||
|
||||
+3
-1
@@ -377,7 +377,9 @@ class LibraryRoutesMixin:
|
||||
[parent["id"] for parent in result["items"]]
|
||||
)
|
||||
result["next_cursor"] = _encode(
|
||||
result.pop("next_key"), scope, name=options["sort"] == "name"
|
||||
result.pop("next_key"),
|
||||
scope,
|
||||
name=options["sort"] in ("name", "name-desc"),
|
||||
)
|
||||
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
|
||||
from .image_delete import IMAGE_DELETE, parse_mode, permanent_delete_supported
|
||||
|
||||
data, error = await self._read_maintenance_body(request, ("token", "mode"))
|
||||
if error is not None:
|
||||
@@ -531,7 +531,12 @@ class MaintenanceRoutesMixin:
|
||||
if plan.operation == IMAGE_DELETE:
|
||||
mode = parse_mode(data.get("mode"))
|
||||
if mode is None:
|
||||
return _invalid('mode must be "library" or "trash"')
|
||||
return _invalid('mode must be "library", "trash" or "permanent"')
|
||||
if mode == "permanent" and not permanent_delete_supported():
|
||||
# The review never offers it here; refuse a direct call (#644).
|
||||
return _invalid(
|
||||
"Permanent delete is only available on Linux and BSD servers"
|
||||
)
|
||||
elif "mode" in data:
|
||||
return _invalid("Unknown field: mode")
|
||||
store = self._maintenance_plans
|
||||
|
||||
@@ -14,10 +14,10 @@ from .prompts import bad_request
|
||||
|
||||
try:
|
||||
from ...utils.media_capture import CAPTURE_EXTENSIONS
|
||||
from ...utils.media_folders import in_trash_folder
|
||||
from ...utils.media_folders import in_trash_folder, path_separators
|
||||
except ImportError:
|
||||
from utils.media_capture import CAPTURE_EXTENSIONS
|
||||
from utils.media_folders import in_trash_folder
|
||||
from utils.media_folders import in_trash_folder, path_separators
|
||||
|
||||
MAX_TARGET_PATH = 1024
|
||||
TARGET_FIELDS = frozenset({"root_index", "root_scope", "path"})
|
||||
@@ -30,7 +30,8 @@ def media_target(data: object, *, media_message: str = TAGGING_MEDIA_MESSAGE):
|
||||
|
||||
Only the listing identity is accepted: an int root index, the root's
|
||||
64-hex scope and a bounded root-relative POSIX media path, never an
|
||||
absolute, drive-qualified, backslash or ``..`` path (a 400 for a malformed
|
||||
absolute, drive-qualified, ``..`` path, or (on Windows only, #646) one
|
||||
holding a backslash (a 400 for a malformed
|
||||
shape, a 403 for an unsafe or non-media path, carrying *media_message*, a
|
||||
404 for a path in a trash folder, #543). A link or a short-name spelling
|
||||
is refused later by the capture store's alias check.
|
||||
@@ -47,7 +48,7 @@ def media_target(data: object, *, media_message: str = TAGGING_MEDIA_MESSAGE):
|
||||
parts = relative.split("/")
|
||||
if (
|
||||
"\0" in relative
|
||||
or "\\" in relative
|
||||
or ("\\" in relative and "\\" in path_separators())
|
||||
or relative.startswith("/")
|
||||
or _has_traversal(relative)
|
||||
or any(part in ("", ".", "..") or ":" in part for part in parts)
|
||||
|
||||
@@ -672,12 +672,13 @@ def owns(root, path, location=None):
|
||||
def is_preview_text(filepath):
|
||||
"""URL text naming a preview: ``thumbnails/<...>/<name>_thumb<ext>``.
|
||||
|
||||
Text only, before any join: no backslash, drive or stream colon, and no
|
||||
Text only, before any join: no backslash (on Windows; on POSIX it is part
|
||||
of a name, #646), drive or stream colon, and no
|
||||
empty, ``.`` or ``..`` segment; ``thumbnails`` exactly as the first part
|
||||
and nowhere else among the folders; the extension, in any case, one a
|
||||
preview may carry (``X_thumb.JPG`` of an older release included).
|
||||
"""
|
||||
if not filepath or "\\" in filepath or ":" in filepath:
|
||||
if not filepath or ":" in filepath or (os.sep == "\\" and "\\" in filepath):
|
||||
return False
|
||||
parts = filepath.split("/")
|
||||
if len(parts) < 2 or parts[0] != PREVIEW_FOLDER:
|
||||
|
||||
+9
-1
@@ -727,7 +727,15 @@ class PromptRoutesMixin:
|
||||
async def save_prompt(self, request):
|
||||
"""Save a new prompt with metadata and duplicate detection."""
|
||||
try:
|
||||
data = await request.json()
|
||||
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,
|
||||
)
|
||||
|
||||
text = (data.get("text") or "").strip()
|
||||
if not text:
|
||||
|
||||
+6
-1
@@ -146,7 +146,9 @@ def format_review_target(spelled_path, locator, real_roots, *, pathmod=os.path):
|
||||
rest = rest[1:]
|
||||
parts = rest.split(sep)
|
||||
if any(
|
||||
part in ("", ".", "..") or "/" in part or "\\" in part or ":" in part
|
||||
part in ("", ".", "..") or "/" in part
|
||||
# #646: on POSIX a backslash is part of a name.
|
||||
or (sep == "\\" and "\\" in part) or ":" in part
|
||||
for part in parts
|
||||
):
|
||||
continue
|
||||
@@ -271,6 +273,9 @@ class ReviewRoutesMixin:
|
||||
"root_scope": self._gallery_root_scope(roots[index], index),
|
||||
"path": relative,
|
||||
}
|
||||
if "\\" in relative:
|
||||
# #646: the mark the Images listing sets (POSIX only).
|
||||
target["path_style"] = "posix"
|
||||
# The Images listing's media URL for the same file (formatting only).
|
||||
url = (
|
||||
"/prompt_manager/images/serve/"
|
||||
|
||||
@@ -205,7 +205,8 @@ def _is_preview_request(filepath):
|
||||
take as an anchor: a backslash, a drive or stream colon, and empty, ``.``
|
||||
or ``..`` segments (so a leading ``/`` and ``//server/share`` too).
|
||||
"""
|
||||
if "\\" in filepath or ":" in filepath:
|
||||
# #646: a backslash is a separator only on Windows.
|
||||
if ":" in filepath or (os.sep == "\\" and "\\" in filepath):
|
||||
return False
|
||||
parts = filepath.split("/")
|
||||
if len(parts) < 2 or parts[0] != "thumbnails":
|
||||
@@ -632,10 +633,6 @@ 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).
|
||||
@@ -967,15 +964,6 @@ 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, *, from_query=False):
|
||||
def thumbnail_options(raw):
|
||||
"""``(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, from_query=True)
|
||||
options, error = thumbnail_options(request.query)
|
||||
if error:
|
||||
return _invalid(error)
|
||||
try:
|
||||
|
||||
@@ -78,27 +78,6 @@ 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.
|
||||
|
||||
@@ -717,12 +696,6 @@ 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)."""
|
||||
@@ -1063,35 +1036,6 @@ 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.
|
||||
|
||||
+3
-2
@@ -1,10 +1,11 @@
|
||||
[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.5.1"
|
||||
version = "3.7.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"]
|
||||
@@ -17,7 +18,7 @@ Repository = "https://github.com/ComfyAssets/ComfyUI_PromptManager"
|
||||
[tool.comfy]
|
||||
PublisherId = "kiko9"
|
||||
DisplayName = "ComfyUI_PromptManager"
|
||||
Icon = "https://avatars.githubusercontent.com/u/213204677?s=200"
|
||||
Icon = "https://raw.githubusercontent.com/ComfyAssets/ComfyUI_PromptManager/main/assets/brand/icon-256.png"
|
||||
|
||||
[tool.black]
|
||||
line-length = 88
|
||||
|
||||
@@ -4,7 +4,7 @@ Pillow>=10.1.0
|
||||
aiohttp>=3.11.8
|
||||
|
||||
# Tests and coverage
|
||||
coverage>=7.17.0
|
||||
coverage>=7.17.2
|
||||
numpy>=1.25.0 # WD14 engine tests
|
||||
|
||||
# Code quality
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 1.5 MiB |
@@ -21,8 +21,9 @@ 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".
|
||||
if(item.id==='sort')return {...item,options:[...item.options.filter(option=>option!=='Highest rated'),'Oldest first']};
|
||||
// D14: the Library appends its Oldest first after the concept's sorts; D153 (#447) drops "Highest rated"; D205
|
||||
// (#620) appends the old Dashboard's three sorts.
|
||||
if(item.id==='sort')return {...item,options:[...item.options.filter(option=>option!=='Highest rated'),'Oldest first','Recently used','Most used','Name Z–A']};
|
||||
// D36: the category list is the Library's real list, sorted alphabetically; the concept lists prompt order.
|
||||
if(item.id==='category-filter')return {...item,options:[item.options[0],...item.options.slice(1).sort(nocase)]};
|
||||
return item;
|
||||
|
||||
@@ -655,6 +655,17 @@ def create_app(root: Path) -> web.Application:
|
||||
shutil.copyfile(root / "output" / "shared" / "same.png", destination)
|
||||
return web.json_response({"success": True})
|
||||
|
||||
@routes.post("/__test__/add-backslash-image")
|
||||
async def add_backslash_image(request: web.Request) -> web.Response:
|
||||
"""#646: a folder whose name holds a backslash, as a Windows-style
|
||||
``filename_prefix`` makes on a POSIX server."""
|
||||
if os.sep == "\\":
|
||||
return web.json_response({"success": False}, status=409)
|
||||
destination = root / "output" / "model.safetensors\\2026-11-17" / "slash.png"
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(root / "output" / "shared" / "same.png", destination)
|
||||
return web.json_response({"success": True})
|
||||
|
||||
@routes.post("/__test__/add-local-inspect-file")
|
||||
async def add_local_inspect_file(request: web.Request) -> web.Response:
|
||||
"""Serve one committed Inspect fixture from the output folder.
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Saving System settings in a spec (#631).
|
||||
*
|
||||
* A host save commits config.json durably (fsync, then an atomic replace). On a busy CI disk that write alone can
|
||||
* take seconds, longer than the five an expect gives the status line. So a spec waits for the save's answer before
|
||||
* it reads the status (TESTING.md: wait for a response, never for time). A save kept in this browser sends nothing
|
||||
* and needs no wait.
|
||||
*/
|
||||
|
||||
export const SETTINGS_URL = '/prompt_manager/settings';
|
||||
export const LORA_ENABLE_URL = '/prompt_manager/lora/enable';
|
||||
|
||||
/** The host's answer to the next save sent to `url`. Start it before the click that saves. */
|
||||
export const hostSaveAnswer = (page, url = SETTINGS_URL) =>
|
||||
page.waitForResponse(response => response.request().method() === 'POST' && response.url().endsWith(url));
|
||||
|
||||
/** Click `button` and wait for the host's answer to the save it sends to `url`; resolves to that response. */
|
||||
export async function clickHostSave(page, button, url = SETTINGS_URL) {
|
||||
const answer = hostSaveAnswer(page, url);
|
||||
await button.click();
|
||||
return answer;
|
||||
}
|
||||
@@ -167,8 +167,6 @@ 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 = {
|
||||
@@ -265,7 +263,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', 'tree.3', 'tree.length',
|
||||
'save.button.cursor', 'save.button.opacity', 'save.status.text',
|
||||
].sort();
|
||||
|
||||
test('system comparison detects mutations', async ({ page, request }) => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { clickHostSave, LORA_ENABLE_URL } from './settings-save.mjs';
|
||||
import { SIZES, THEMES, seedConcept, openConcept, openProduction, diffInventory, mutate } from './concept-inventory.mjs';
|
||||
|
||||
// #249 System S10 Task 28: System › Integrations (app.js renderSystem 682–684) and the LoRA import review against the
|
||||
@@ -300,7 +301,8 @@ async function productionReview(page, request, theme) {
|
||||
await expect(page.locator('#workspace-main #renderer-status')).toHaveText(RENDERER_NONE);
|
||||
// The import reviews what is enabled: save the integration on first.
|
||||
await page.locator('#workspace-main #lora-enable').check();
|
||||
await page.getByRole('button', { name: 'Save preferences', exact: true }).click();
|
||||
// The save writes config.json durably, which a busy CI disk can hold for seconds (#631): wait for its answer.
|
||||
await clickHostSave(page, page.getByRole('button', { name: 'Save preferences', exact: true }), LORA_ENABLE_URL);
|
||||
await expect(page.locator('#settings-status')).toHaveText('Saved to the server configuration.');
|
||||
const answer = page.waitForResponse(response => response.url().endsWith(PREVIEW_URL));
|
||||
await page.locator('#workspace-main').getByRole('button', { name: 'Review import', exact: true }).click();
|
||||
|
||||
@@ -2709,3 +2709,26 @@ test('all matching over 10,000 images says so before any dialog or request', asy
|
||||
}
|
||||
expect(posted).toBe(0);
|
||||
});
|
||||
|
||||
// #646: on a POSIX server a Windows-style filename_prefix makes one folder whose name holds a backslash. Its file opens
|
||||
// in the viewer, takes a star that survives a reload, and the folder filter names it with its backslash.
|
||||
test('a file in a folder whose name holds a backslash opens, stars and filters (#646)', async ({ page, request }) => {
|
||||
await expect(await request.post('/__test__/add-backslash-image')).toBeOK();
|
||||
await page.goto(workspace);
|
||||
await expect(cards(page)).toHaveCount(3);
|
||||
const card = page.locator('article[data-image-key="0:model.safetensors\\\\2026-11-17/slash.png"]');
|
||||
await card.locator('.image-open').click();
|
||||
const viewer = page.locator('dialog#viewer-dialog[open]');
|
||||
await expect(viewer.locator('#viewer-title')).toContainText('slash.png');
|
||||
await expect(viewer.locator('#viewer-details .panel-heading')).toBeVisible();
|
||||
await viewer.locator('#viewer-close').click();
|
||||
await expect(viewer).toHaveCount(0);
|
||||
await star(card, 'slash.png').click();
|
||||
await expectStar(star(card, 'slash.png'), true);
|
||||
await expect.poll(async () => (await listedFavorites(request))['0:model.safetensors\\2026-11-17/slash.png']).toBe(true);
|
||||
await page.reload();
|
||||
await expectStar(star(card, 'slash.png'), true);
|
||||
await refine(page, { Folder: 'model.safetensors\\2026-11-17' });
|
||||
await expect(cards(page)).toHaveCount(1);
|
||||
await expect(cards(page)).toContainText('slash.png');
|
||||
});
|
||||
|
||||
@@ -648,7 +648,10 @@ test('a video replaced while still starting is reset once it settles', async ({
|
||||
// page (TESTING.md D62), so it stays in place, inert and still playing its URL, with the new preview after it.
|
||||
// Once it reports metadata or an error it is paused, loses its src, is reset (load() with no src, which frees its
|
||||
// decoder) and leaves the page, and only then is its URL revoked. Fresh pages share one browser process.
|
||||
for (let attempt = 0; attempt < 15; attempt++) {
|
||||
// A busy WebKit can fire `loadstart` after the video already has data (#641, run 43732282629: readyState 4), so
|
||||
// keep going until at least one page saw it still starting.
|
||||
let startingSeen = 0;
|
||||
for (let attempt = 0; attempt < 15 || (startingSeen === 0 && attempt < 30); attempt++) {
|
||||
const page = await context.newPage();
|
||||
try {
|
||||
if (attempt === 0) await startCoverage(page, browserName);
|
||||
@@ -687,11 +690,11 @@ test('a video replaced while still starting is reset once it settles', async ({
|
||||
await choose(page, localFixture('core-tags.webm', 'video/webm'));
|
||||
await expect(preview(page).locator('img.local-file-preview')).toBeVisible({ timeout: 8000 });
|
||||
await expect(preview(page).locator('video')).toHaveCount(0);
|
||||
// Replaced while starting (always so at `loadstart` itself): kept in place and untouched. A video that had
|
||||
// Replaced while starting (usually so at `loadstart` itself): kept in place and untouched. A video that had
|
||||
// settled is released at once. Either way it is reset once, and its URL goes last.
|
||||
await expect.poll(() => page.evaluate(() => window.__starting.revoked ?? null)).toEqual({ src: false, connected: false, resets: 1 });
|
||||
const { readyState, replaced } = await page.evaluate(() => ({ readyState: window.__starting.readyState, replaced: window.__starting.replaced }));
|
||||
if (attempt % 5 === 0) expect(readyState).toBe(0);
|
||||
if (readyState === 0) startingSeen++;
|
||||
expect(replaced).toEqual(readyState === 0 ? { connected: true, src: true, inert: true, resets: 0 } : { connected: false, src: false, inert: false, resets: 1 });
|
||||
expect(await page.evaluate(() => window.__starting.node.__resets)).toBe(1);
|
||||
// The page still answers.
|
||||
@@ -702,6 +705,7 @@ test('a video replaced while still starting is reset once it settles', async ({
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
expect(startingSeen, 'no page saw the video still starting at its loadstart').toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('a new selection while the viewer\'s own video is still starting leaves it until it settles (#483)', async ({ context, browserName }) => {
|
||||
@@ -710,7 +714,10 @@ test('a new selection while the viewer\'s own video is still starting leaves it
|
||||
// selection from that video's own `loadstart` (readyState HAVE_NOTHING), or a few milliseconds after it, must not
|
||||
// reset it or take it off the page while it starts (WebKit, GStreamer: TESTING.md D62; merge-queue run
|
||||
// 40903238387). The viewer stays open until it reports metadata or an error, then closes; the URL goes last.
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
// A busy WebKit can fire `loadstart` after the video already has data (#641, run 43732282629: readyState 4), so
|
||||
// keep going until at least one page saw it still starting.
|
||||
let startingSeen = 0;
|
||||
for (let attempt = 0; attempt < 10 || (startingSeen === 0 && attempt < 20); attempt++) {
|
||||
const page = await context.newPage();
|
||||
try {
|
||||
if (attempt === 0) await startCoverage(page, browserName);
|
||||
@@ -750,7 +757,7 @@ test('a new selection while the viewer\'s own video is still starting leaves it
|
||||
await expect(preview(page).locator('img.local-file-preview')).toBeVisible({ timeout: 8000 });
|
||||
await expect.poll(() => page.evaluate(() => window.__starting?.revoked ?? null)).toEqual({ src: false, connected: false, resets: 1 });
|
||||
const { readyState, replaced } = await page.evaluate(() => ({ readyState: window.__starting.readyState, replaced: window.__starting.replaced }));
|
||||
if (attempt % 5 === 0) expect(readyState).toBe(0);
|
||||
if (readyState === 0) startingSeen++;
|
||||
// Starting when replaced: still on the page with its URL, never reset; settled: released at once.
|
||||
expect(replaced).toEqual(readyState === 0 ? { connected: true, src: true, resets: 0 } : { connected: false, src: false, resets: 1 });
|
||||
expect(await page.evaluate(() => window.__starting.node.__resets)).toBe(1);
|
||||
@@ -764,6 +771,7 @@ test('a new selection while the viewer\'s own video is still starting leaves it
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
expect(startingSeen, 'no page saw the video still starting at its loadstart').toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
/** #483: holds the viewer's video in HAVE_NOTHING (its `loadedmetadata` never fires) so a hold can be driven by hand. */
|
||||
@@ -850,7 +858,10 @@ test('leaving for another route while a video starts waits for it to settle', as
|
||||
// A WebKit (GStreamer) video detached before its pipeline had started deadlocked the page (TESTING.md D62); a
|
||||
// route change detaches the whole page, so the shell renders the next route once the video reports metadata or an
|
||||
// error. The route changes from the video's own `loadstart`, or a few milliseconds after it.
|
||||
for (let attempt = 0; attempt < 15; attempt++) {
|
||||
// A busy WebKit can fire `loadstart` after the video already has data (#641, run 43732282629: readyState 4), so
|
||||
// keep going until at least one page saw it still starting.
|
||||
let startingSeen = 0;
|
||||
for (let attempt = 0; attempt < 15 || (startingSeen === 0 && attempt < 30); attempt++) {
|
||||
const page = await context.newPage();
|
||||
try {
|
||||
if (attempt === 0) await startCoverage(page, browserName);
|
||||
@@ -878,7 +889,7 @@ test('leaving for another route while a video starts waits for it to settle', as
|
||||
await choose(page, localFixture('core-tags.webm', 'video/webm'));
|
||||
await expect(main(page).getByRole('heading', { level: 1, name: 'Overview', exact: true })).toBeVisible({ timeout: 8000 });
|
||||
const { readyState, reset } = await page.evaluate(() => ({ readyState: window.__starting.readyState, reset: window.__starting.reset }));
|
||||
if (attempt % 5 === 0) expect(readyState).toBe(0);
|
||||
if (readyState === 0) startingSeen++;
|
||||
// The video was reset and left the page only once it had settled.
|
||||
expect(reset.readyState >= 1 || reset.failed).toBe(true);
|
||||
expect(reset.connected).toBe(true);
|
||||
@@ -891,6 +902,7 @@ test('leaving for another route while a video starts waits for it to settle', as
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
expect(startingSeen, 'no page saw the video still starting at its loadstart').toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('closing the viewer on a video that just started never blocks the page', async ({ context, browserName }) => {
|
||||
|
||||
@@ -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']);
|
||||
await expect(toolbar.locator('#sort option')).toHaveText(['Recently added','Name A–Z','Oldest first','Recently used','Most used','Name Z–A']);
|
||||
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);
|
||||
|
||||
@@ -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: 'name-desc' }) });
|
||||
await raw({ page: 'library', name: '', state: JSON.stringify({ q: 'dog', sort: 'shuffle' }) });
|
||||
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,5 +1,6 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { hostSaveAnswer } from './settings-save.mjs';
|
||||
import { seedConcept } from './concept-inventory.mjs';
|
||||
import { followRestore, SEEN_RESTORE_PILL, SEEN_RESTORE_TOAST } from './unseen-restore.mjs';
|
||||
|
||||
@@ -387,9 +388,9 @@ test('safety backup toggle saves through Save preferences with revision (D104)',
|
||||
await expect(toggle).toBeChecked();
|
||||
await toggle.uncheck();
|
||||
await expect(settingsStatus(page)).toHaveText('Unsaved changes.');
|
||||
const saved = page.waitForRequest(item => item.url().endsWith('/prompt_manager/settings') && item.method() === 'POST');
|
||||
const saved = hostSaveAnswer(page);
|
||||
await save(page).click();
|
||||
const body = (await saved).postDataJSON();
|
||||
const body = (await saved).request().postDataJSON();
|
||||
expect(body).toEqual({ safety_backup: false, expected_revision: before.revision });
|
||||
await expect(settingsStatus(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, '/prompt_manager/settings')).settings.safety_backup).toBe(false);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { clickHostSave } from './settings-save.mjs';
|
||||
import { seedConcept } from './concept-inventory.mjs';
|
||||
|
||||
// System › Integrations (#249 System S10 Task 27) on the concept-shaped fixture with a fake LoraManager install
|
||||
@@ -65,7 +66,7 @@ async function openIntegrations(page) {
|
||||
async function enable(page, { triggers = false } = {}) {
|
||||
await settingOf(page, 'LoraManager integration').locator('input').check();
|
||||
if (triggers) await settingOf(page, 'Automatically include trigger words').locator('input').check();
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page), ENABLE_URL);
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
}
|
||||
|
||||
@@ -201,7 +202,7 @@ test('key never prefilled; blank keeps; Clear saved key clears; saved through Sa
|
||||
await field.fill('sk-test-key');
|
||||
await expect(key.locator('p.small')).toHaveText('The new key replaces the saved one when you save.');
|
||||
await expect(status(page)).toHaveText('Unsaved changes.');
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page), ENABLE_URL);
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
expect(enables).toHaveLength(1);
|
||||
expect(enables[0]).toMatchObject({ civitai_api_key: 'sk-test-key', enabled: false });
|
||||
@@ -243,7 +244,7 @@ test('key never prefilled; blank keeps; Clear saved key clears; saved through Sa
|
||||
await expect(key.locator('p.small')).toHaveText('The saved key is removed when you save.');
|
||||
await expect(clear).toHaveCount(0);
|
||||
await expect(field).toBeFocused();
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page), ENABLE_URL);
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
expect(enables.at(-1)).toMatchObject({ clear_civitai_api_key: true });
|
||||
expect(enables.at(-1)).not.toHaveProperty('civitai_api_key');
|
||||
@@ -261,7 +262,7 @@ test('a LoRA save over settings changed elsewhere is a conflict, never a blind w
|
||||
await expect(status(page)).toHaveText('Settings changed elsewhere. Reload this section to see them.');
|
||||
expect((await serverJson(request, '/__test__/integrations/state')).trigger_words).toBe(false);
|
||||
// The draft stays; the next Save carries the reread revision and succeeds.
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page), ENABLE_URL);
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, '/__test__/integrations/state')).trigger_words).toBe(true);
|
||||
});
|
||||
@@ -292,7 +293,7 @@ test('a save where only the LoRA part is written says so; the next save needs no
|
||||
// The next save carries the revision the saved part left: it saves, with no "changed elsewhere".
|
||||
await nav.getByRole('button', { name: 'Sources & scans', exact: true }).click();
|
||||
await sourceRow('unplugged').getByRole('button', { name: 'Remove', exact: true }).click();
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page));
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, '/prompt_manager/settings')).sources.configured.map(source => source.path)).toEqual(['output']);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { clickHostSave, hostSaveAnswer, SETTINGS_URL } from './settings-save.mjs';
|
||||
import { seedConcept } from './concept-inventory.mjs';
|
||||
|
||||
// System › Sources & scans (#249 System S4 Task 11) on the concept-shaped real fixture, whose two sources are this
|
||||
@@ -7,7 +8,6 @@ import { seedConcept } from './concept-inventory.mjs';
|
||||
// Add/Remove edit the host draft behind the one Save row, and every scan starts the session job through the shared
|
||||
// "Review metadata scan" (D55), scoped to one source from its row (S4 Task 10). The hooks are workspace_system_fixture.py's.
|
||||
const workspace = '/prompt_manager/workspace';
|
||||
const SETTINGS_URL = '/prompt_manager/settings';
|
||||
const NOTICE_KEY = 'pm_update_notice_dismissed';
|
||||
const OUTSIDE_REASON = 'Gallery root must be inside a ComfyUI directory (output, input, temp, user) or one listed in PROMPT_MANAGER_EXTRA_GALLERY_ROOTS';
|
||||
|
||||
@@ -152,9 +152,9 @@ test('Add source validates on the server, then marks the host draft dirty; Save
|
||||
]);
|
||||
await expect(statusOf(page)).toHaveText('Unsaved changes.');
|
||||
expect((await serverJson(request, SETTINGS_URL)).sources.effective).toHaveLength(2);
|
||||
const saved = page.waitForRequest(item => item.method() === 'POST' && item.url().endsWith(SETTINGS_URL));
|
||||
const saved = hostSaveAnswer(page);
|
||||
await saveButton(page).click();
|
||||
const body = (await saved).postDataJSON();
|
||||
const body = (await saved).request().postDataJSON();
|
||||
expect(body.gallery_root_paths).toEqual(['output', 'input', 'output/unthumbnailed']);
|
||||
expect(typeof body.expected_revision).toBe('string');
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
@@ -207,7 +207,7 @@ test('Remove marks the draft; removing the last entry states auto-detect', async
|
||||
await expect(statusOf(page)).toHaveText('Unsaved changes.');
|
||||
await sourceRow(page, 'ComfyUI output').getByRole('button', { name: 'Remove', exact: true }).click();
|
||||
expect(await rowsOf(page)).toEqual([['p', 'small', 'No source is configured. After saving, ComfyUI’s output folder is used.']]);
|
||||
await saveButton(page).click();
|
||||
await clickHostSave(page, saveButton(page));
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
// Saved: ComfyUI's output folder is detected and listed without Remove, its row saying it is the default.
|
||||
await expect.poll(rowsOf.bind(null, page)).toEqual([
|
||||
@@ -224,7 +224,7 @@ test('a configured source that does not exist says why and can be removed', asyn
|
||||
expect((await rowsOf(page)).at(-1)).toEqual(['unmounted-drive', `unmounted-drive · ${OUTSIDE_REASON}`, ['Remove']]);
|
||||
await sourceRow(page, 'unmounted-drive').getByRole('button', { name: 'Remove', exact: true }).click();
|
||||
await expect(sourceList(page).locator('.operation')).toHaveCount(2);
|
||||
await saveButton(page).click();
|
||||
await clickHostSave(page, saveButton(page));
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, SETTINGS_URL)).sources.configured.map(source => source.path)).toEqual(['output', 'input']);
|
||||
});
|
||||
@@ -266,7 +266,7 @@ test('Watch for new outputs saves monitoring_enabled; a restart applies it', asy
|
||||
await expect(sourceList(page).locator('.operation .row-actions > button:first-child')).toHaveText(['Scan changes', 'Scan changes']);
|
||||
// Switched back on before the restart: the observer still runs, so nothing waits for one.
|
||||
await monitoring.check();
|
||||
await saveButton(page).click();
|
||||
await clickHostSave(page, saveButton(page));
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
await expect(sourceList(page).locator('.operation p')).toHaveText(['output · watching', 'input · watching']);
|
||||
});
|
||||
@@ -327,9 +327,9 @@ test('D158: saved off while the monitor still watches until a restart, the forei
|
||||
await expect(layout.locator('.setting-row').filter({ has: page.locator('#foreign-runs') }).locator('p.small'))
|
||||
.toHaveText('Applies while Watch for new outputs is on.');
|
||||
await foreign.uncheck();
|
||||
const saved = page.waitForRequest(item => item.method() === 'POST' && item.url().endsWith(SETTINGS_URL));
|
||||
const saved = hostSaveAnswer(page);
|
||||
await saveButton(page).click();
|
||||
expect((await saved).postDataJSON()).toEqual({ save_foreign_runs: false, expected_revision: expect.any(String) });
|
||||
expect((await saved).request().postDataJSON()).toEqual({ save_foreign_runs: false, expected_revision: expect.any(String) });
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
} finally {
|
||||
await request.post(SETTINGS_URL, { data: { save_foreign_runs: true } });
|
||||
@@ -349,9 +349,9 @@ test('worker range max is cpu_count', async ({ page, request }) => {
|
||||
await workers.fill(String(next));
|
||||
await expect(statusOf(page)).toHaveText(next === settings.worker_threads ? 'No unsaved changes.' : 'Unsaved changes.');
|
||||
test.skip(next === settings.worker_threads, 'One core: the range has a single value');
|
||||
const saved = page.waitForRequest(item => item.method() === 'POST' && item.url().endsWith(SETTINGS_URL));
|
||||
const saved = hostSaveAnswer(page);
|
||||
await saveButton(page).click();
|
||||
expect((await saved).postDataJSON().worker_threads).toBe(next);
|
||||
expect((await saved).request().postDataJSON().worker_threads).toBe(next);
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, SETTINGS_URL)).settings.worker_threads).toBe(next);
|
||||
});
|
||||
@@ -601,7 +601,7 @@ test('a save refused for one unusable source names it and marks its row', async
|
||||
// Removed, the list saves.
|
||||
await sourceRow(page, 'unplugged').getByRole('button', { name: 'Remove', exact: true }).click();
|
||||
await expect(sourceList(page).locator('.operation[aria-invalid="true"]')).toHaveCount(0);
|
||||
await saveButton(page).click();
|
||||
await clickHostSave(page, saveButton(page));
|
||||
await expect(statusOf(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, SETTINGS_URL)).sources.configured.map(source => source.path)).toEqual(['output']);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { clickHostSave, hostSaveAnswer, SETTINGS_URL } from './settings-save.mjs';
|
||||
|
||||
// System › Auto-tagging (#328, System S11 Tasks 6–7) on the tagging fixture (workspace_tagging_fixture.py) with the
|
||||
// injected fake model: no model file exists and nothing is downloaded or run for real. The fake download waits on the
|
||||
@@ -8,7 +9,6 @@ import { test, expect } from './fixtures.mjs';
|
||||
const workspace = '/prompt_manager/workspace';
|
||||
const MODELS_URL = '/prompt_manager/autotag/models';
|
||||
const PREVIEW_URL = '/prompt_manager/autotag/batch/preview';
|
||||
const SETTINGS_URL = '/prompt_manager/settings';
|
||||
const MODEL_LABELS = ['WD14 SwinV2 · ~400 MB', 'WD14 ViT · ~400 MB', 'GGUF JoyCaption · ~4.5 GB', 'HuggingFace JoyCaption · ~16 GB'];
|
||||
const FIRST = 'tagging/dunes_00001.png';
|
||||
const SECOND = 'tagging/dunes_00002.png';
|
||||
@@ -169,9 +169,9 @@ test('defaults save through Save preferences and the Tag image dialog uses them'
|
||||
await page.locator('#threshold-general').press('Tab');
|
||||
await page.locator('#tag-suggestions').fill('15');
|
||||
await page.locator('#tag-suggestions').press('Tab');
|
||||
const posted = page.waitForRequest(item => item.method() === 'POST' && new URL(item.url()).pathname === SETTINGS_URL);
|
||||
const posted = hostSaveAnswer(page);
|
||||
await save(page).click();
|
||||
const body = (await posted).postDataJSON();
|
||||
const body = (await posted).request().postDataJSON();
|
||||
expect(body).toMatchObject({ autotag_existing: 'merge', autotag_general_threshold: 0.4, autotag_suggestion_limit: 15 });
|
||||
expect(typeof body.expected_revision).toBe('string');
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
@@ -468,7 +468,7 @@ test('skipped tags add, preview, remove, save and reload (D202)', async ({ page,
|
||||
await skippedChips(page).last().getByRole('button', { name: 'Remove zebra', exact: true }).click();
|
||||
await expect(skippedChips(page)).toHaveCount(2);
|
||||
await expect(status(page)).toHaveText('Unsaved changes.');
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page));
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
expect((await serverJson(request, SETTINGS_URL)).settings.autotag_skipped_tags).toEqual(['blurry', 'light']);
|
||||
await openTagging(page);
|
||||
@@ -526,7 +526,7 @@ test('saved instructions: new, edit, per-engine default, delete, save and reload
|
||||
await page.locator('#instruction-default-hf').selectOption({ label: 'Photo realism' });
|
||||
await expect(instructionOption(page, 'Photo realism').locator('.chip')).toHaveText(['Default for HuggingFace']);
|
||||
await expect(status(page)).toHaveText('Unsaved changes.');
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page));
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
let saved = (await serverJson(request, SETTINGS_URL)).settings;
|
||||
expect(saved.autotag_instructions.map(entry => [entry.name, entry.text])).toEqual([['Describe the image', 'Describe the image'],
|
||||
@@ -538,7 +538,7 @@ test('saved instructions: new, edit, per-engine default, delete, save and reload
|
||||
await page.locator('#instruction-delete').click();
|
||||
await expect(page.locator('#instruction-reset')).toHaveText('GGUF now uses Built-in.');
|
||||
await expect(page.locator('#instruction-default-gguf')).toHaveValue('builtin');
|
||||
await save(page).click();
|
||||
await clickHostSave(page, save(page));
|
||||
await expect(status(page)).toHaveText('Saved to the server configuration.');
|
||||
saved = (await serverJson(request, SETTINGS_URL)).settings;
|
||||
expect(saved.autotag_instructions.map(entry => entry.name)).toEqual(['Photo realism']);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { clickHostSave, SETTINGS_URL } from './settings-save.mjs';
|
||||
import { seedConcept } from './concept-inventory.mjs';
|
||||
import { readCoverageTable, parseControl, CONTROL_EXEMPTIONS } from '../../tools/vendor/legacy-coverage.mjs';
|
||||
|
||||
@@ -326,7 +327,7 @@ test('Appearance › Thumbnails saves the server thumbnail settings and never co
|
||||
await format.selectOption('jpeg');
|
||||
await surface.locator('#thumbnail-quality').fill('65');
|
||||
await surface.locator('#thumbnail-quality').dispatchEvent('change');
|
||||
await page.getByRole('button', { name: 'Save preferences', exact: true }).click();
|
||||
await clickHostSave(page, page.getByRole('button', { name: 'Save preferences', exact: true }));
|
||||
await expect(page.locator('#settings-status')).toHaveText('Saved to the server configuration.');
|
||||
const { settings } = await serverJson(request, '/prompt_manager/settings');
|
||||
expect([settings.thumbnail_format, settings.thumbnail_quality, settings.thumbnail_edge]).toEqual(['jpeg', 65, 512]);
|
||||
@@ -456,8 +457,8 @@ test('out-of-order overview responses never repaint a newer section', async ({ p
|
||||
|
||||
// System › Appearance (#249 System S3 Task 8): the browser display defaults (`gallerySettings`, preferences.mjs) and the
|
||||
// two host fields behind the one Save row, and the consumers that read them on their next visit.
|
||||
const SETTINGS_URL = '/prompt_manager/settings';
|
||||
const INSPECT_PATH = '/prompt_manager/images/inspect/';
|
||||
const HOST_SAVED = 'Saved to the server configuration.';
|
||||
const statusOf = page => page.locator('#workspace-main #settings-status');
|
||||
const saveOf = page => page.locator('#workspace-main .save-row > button');
|
||||
const storedSettings = page => page.evaluate(() => JSON.parse(localStorage.getItem('gallerySettings') || 'null'));
|
||||
@@ -473,7 +474,9 @@ async function openAppearance(page) {
|
||||
|
||||
async function saveAppearance(page, text) {
|
||||
await expect(saveOf(page)).not.toHaveAttribute('aria-disabled', 'true');
|
||||
await saveOf(page).click();
|
||||
// A save that reaches the server waits for its answer (#631); one kept in this browser sends nothing.
|
||||
if (text.includes(HOST_SAVED)) await clickHostSave(page, saveOf(page));
|
||||
else await saveOf(page).click();
|
||||
await expect(statusOf(page)).toHaveText(text);
|
||||
}
|
||||
|
||||
|
||||
@@ -311,3 +311,42 @@ test('on a video the image keys and Space do nothing, as the toolbar disables th
|
||||
await page.evaluate(() => new Promise(requestAnimationFrame));
|
||||
await expect(viewer(page)).not.toHaveClass(/\bviewer-fullscreen\b/);
|
||||
});
|
||||
|
||||
/** #646: the listing carries one file whose folder name holds a backslash, as a Windows-style prefix makes on Linux. */
|
||||
async function withBackslashFile(page) {
|
||||
await page.route(/\/prompt_manager\/images\/output\?/, async route => {
|
||||
const response = await route.fetch(), body = await response.json();
|
||||
if (body.images?.length > 1) {
|
||||
const copy = body.images[1];
|
||||
body.images.splice(1, 0, {...copy, path: `model.safetensors\\2026-11-17/${copy.filename}`, relative_path: `model.safetensors\\2026-11-17/${copy.filename}`});
|
||||
}
|
||||
await route.fulfill({response, json: body});
|
||||
});
|
||||
}
|
||||
|
||||
test('a file the viewer refuses is left out, and the others still open (#646)', async ({ page }) => {
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await withBackslashFile(page);
|
||||
await page.setViewportSize({ width: 1600, height: 1100 });
|
||||
await openProduction(page, 'images', 'dark');
|
||||
const cards = await page.locator(CARDS).count();
|
||||
await page.locator(CARDS).first().locator('.image-open').click();
|
||||
await expect(position(page)).toContainText(`1 of ${cards - 1}`);
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expect(position(page)).toContainText('2 of ');
|
||||
await expect(viewer(page).locator('#viewer-title')).not.toContainText('model.safetensors');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test('the refused file itself opens its details instead of the viewer (#646)', async ({ page }) => {
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await withBackslashFile(page);
|
||||
await page.setViewportSize({ width: 1600, height: 1100 });
|
||||
await openProduction(page, 'images', 'dark');
|
||||
await page.locator(`${CARDS}[data-image-key*="model.safetensors"] .image-open`).click();
|
||||
await expect(page.getByRole('complementary', {name: 'Selected image details'}).getByRole('alert')).toHaveText('Could not read prompts from this file.');
|
||||
await expect(viewer(page)).toHaveCount(0);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -135,34 +135,11 @@ 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();
|
||||
});
|
||||
|
||||
// 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 }) => {
|
||||
// #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 }) => {
|
||||
await page.goto(`${workspace}#/system/overview`);
|
||||
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);
|
||||
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 bootFailure = page => page.locator('#workspace-boot-failure');
|
||||
@@ -175,7 +152,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 still offers the legacy pages (#525)`, async ({ page }) => {
|
||||
test(`when ${label} fails to load the page offers a reload and ComfyUI (#525, #620)`, async ({ page }) => {
|
||||
const pageErrors = [];
|
||||
page.on('pageerror', error => pageErrors.push(error.message));
|
||||
await page.route(pattern, route => route.abort());
|
||||
@@ -183,19 +160,17 @@ 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');
|
||||
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$/);
|
||||
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);
|
||||
expect(pageErrors).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
test('when a module throws while starting the page still offers the legacy pages (#525)', async ({ page }) => {
|
||||
test('when a module throws while starting the page still offers a reload (#525, #620)', 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: 'Dashboard', exact: true })).toBeVisible();
|
||||
await expect(bootFailure(page).getByRole('link', { name: 'Reload the page', exact: true })).toBeVisible();
|
||||
// The broken module's own error is this test's premise, not a failure of the page.
|
||||
page.workspaceErrors.length = 0;
|
||||
});
|
||||
@@ -569,7 +544,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', 'p.small legacy-pages']);
|
||||
.toEqual(['div.heading', 'div.section-nav', 'div.settings-layout']);
|
||||
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,6 +35,10 @@ from utils.execution_outputs import OutputBundle, OutputReference, snapshot_outp
|
||||
from utils.pair_execution import EXECUTION_KEY
|
||||
from tests.browser.folder_trash import replace_folder
|
||||
|
||||
# Recorded outputs use the host's path style, as production does (#629): a
|
||||
# Windows temp root is not an absolute POSIX path and would get no root key.
|
||||
HOST_PATH_STYLE = "windows" if os.name == "nt" else "posix"
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from py.api import PromptManagerAPI
|
||||
|
||||
@@ -433,7 +437,9 @@ def seed_workspace_concept(
|
||||
|
||||
folder = root / "output" / "concepts"
|
||||
folder.mkdir()
|
||||
roots = snapshot_output_roots("posix", str(root / "output"), str(root / "temp"))
|
||||
roots = snapshot_output_roots(
|
||||
HOST_PATH_STYLE, str(root / "output"), str(root / "temp")
|
||||
)
|
||||
# The API package needs the host stubs the server installs before importing it.
|
||||
from py.api.images import _favorite_relative_key, _favorite_root_key
|
||||
|
||||
@@ -474,7 +480,7 @@ def seed_workspace_concept(
|
||||
"3", _snapshot(prompt.positive), _snapshot(negative), "inferred"
|
||||
)
|
||||
reference = OutputReference(
|
||||
"4", 0, "output", "concepts", name, "posix", roots.output_key
|
||||
"4", 0, "output", "concepts", name, HOST_PATH_STYLE, roots.output_key
|
||||
)
|
||||
runs.append(
|
||||
_record_run(
|
||||
|
||||
@@ -15,6 +15,7 @@ from aiohttp import web
|
||||
from PIL import Image
|
||||
from PIL.PngImagePlugin import PngInfo
|
||||
|
||||
from tests.browser.workspace_concept_fixture import HOST_PATH_STYLE
|
||||
from tests.browser.workspace_visual_fixture import _write_art, seed_workspace_visual
|
||||
from utils.execution_contexts import (
|
||||
ContextBundle,
|
||||
@@ -293,7 +294,9 @@ def seed_workspace_history(
|
||||
):
|
||||
conn.execute(f"DELETE FROM {table}")
|
||||
epoch = api.db.get_execution_epoch()
|
||||
roots = snapshot_output_roots("posix", str(root / "output"), str(root / "temp"))
|
||||
roots = snapshot_output_roots(
|
||||
HOST_PATH_STYLE, str(root / "output"), str(root / "temp")
|
||||
)
|
||||
folder = root / "output" / "history"
|
||||
folder.mkdir(exist_ok=True)
|
||||
for index, name in enumerate(("current.png", "other.png")):
|
||||
@@ -309,7 +312,7 @@ def seed_workspace_history(
|
||||
kind,
|
||||
"history",
|
||||
name,
|
||||
"posix",
|
||||
HOST_PATH_STYLE,
|
||||
roots.output_key if kind == "output" else roots.temp_key,
|
||||
)
|
||||
|
||||
|
||||
@@ -1033,7 +1033,9 @@ 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();
|
||||
const source = require('node:fs').readFileSync(require('node:path').join(__dirname, '../../py/tagging_defaults.py'), 'utf8');
|
||||
// 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 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']);
|
||||
assert.deepEqual(MODES.map(mode => mode.label), ['Remove from the library only', 'Also move the files to the trash', 'Permanently delete']);
|
||||
});
|
||||
|
||||
test('library rows: scope, refusals, links, details, backup and media', () => {
|
||||
@@ -149,3 +149,34 @@ 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.');
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -954,3 +954,15 @@ 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/);
|
||||
});
|
||||
|
||||
@@ -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']) assert.equal(await s.reset({sort}),0);s.dispose();
|
||||
for(const sort of ['newest','oldest','name','name-desc','most-used','last-used']) 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');
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// #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);
|
||||
});
|
||||
@@ -32,7 +32,7 @@ test('a saved state always holds every page key and keeps only values its page a
|
||||
{ ...full, q: '', folder: '', tags: [] });
|
||||
assert.deepEqual(normalizeViewState('images', { ...full, category: 'bad\u0007', tags: [' '] }), { ...full, category: '', tags: [] });
|
||||
// Library has no source or media, and no Name Z–A; its folder (#444) is the Library's own.
|
||||
assert.deepEqual(normalizeViewState('library', { ...full, sort: 'name-desc' }), { q: 'castle', category: 'Portraits', sort: 'newest', tags: ['moody', 'fog'], tag_mode: 'all', folder: 'a/b' });
|
||||
assert.deepEqual(normalizeViewState('library', { ...full, sort: 'rating' }), { q: 'castle', category: 'Portraits', sort: 'newest', tags: ['moody', 'fog'], tag_mode: 'all', folder: 'a/b' });
|
||||
assert.deepEqual(normalizeViewState('library', { sort: 'oldest' }), { ...LIBRARY_DEFAULTS, sort: 'oldest' });
|
||||
// The returned tags are a copy.
|
||||
const tags = ['one'];
|
||||
@@ -244,5 +244,7 @@ test('a view saved under the retired Highest rated sort opens on Recently added
|
||||
assert.equal(imagesFilters({ sort: 'rating' }).sort, 'newest');
|
||||
assert.equal(libraryFilters({ sort: 'rating' }).sort, 'newest');
|
||||
assert.equal(normalizeViewState('images', { sort: 'name-desc' }).sort, 'name-desc');
|
||||
assert.equal(normalizeViewState('library', { sort: 'oldest' }).sort, 'oldest');
|
||||
for (const sort of ['oldest', 'name-desc', 'most-used', 'last-used']) {
|
||||
assert.equal(normalizeViewState('library', { sort }).sort, sort);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -93,13 +93,6 @@ test('every Overview card opens its own native page, never a legacy one (#525)',
|
||||
}
|
||||
});
|
||||
|
||||
test('the legacy pages System links are the four that stay at their URLs (#525 D165)', async () => {
|
||||
const { LEGACY_PAGES } = await source;
|
||||
assert.deepEqual(LEGACY_PAGES.map(page => page.href), ['/prompt_manager/admin', '/prompt_manager/admin#/tags',
|
||||
'/prompt_manager/gallery', '/prompt_manager/gallery.html']);
|
||||
for (const page of LEGACY_PAGES) assert.ok(page.label);
|
||||
});
|
||||
|
||||
test('a job of the Activity page is its own deep link', async () => {
|
||||
const { resolveRoute, routeTitle, isHandoff } = await source;
|
||||
const id = '0123456789abcdef'.repeat(2);
|
||||
|
||||
@@ -38,6 +38,19 @@ test('viewer rejects empty duplicate or unknown identity', () => {
|
||||
assert.equal(view.state.index, 0); view.dispose();
|
||||
});
|
||||
|
||||
test('viewer leaves out an identity it refuses instead of refusing to open (#646)', () => {
|
||||
const items = entries().slice(0, 3);
|
||||
items.splice(1, 0, {...items[1], path: 'model.safetensors\\2026-11-17/x.png', filename: 'x.png'});
|
||||
const view = session({items, initialKey: '0:folder/0.png'});
|
||||
assert.deepEqual(view.state, {key:'0:folder/0.png',index:0,total:3,phase:'stopped',requested:false,mediaReady:false});
|
||||
view.navigate(1); assert.equal(view.state.key, '1:folder/1.png');
|
||||
view.navigate(1); assert.equal(view.state.key, '0:folder/2.png');
|
||||
view.dispose();
|
||||
// The refused file itself is not in the viewer, and a collection of refused files has nothing to open.
|
||||
assert.throws(() => session({items, initialKey: '1:model.safetensors\\2026-11-17/x.png'}), TypeError);
|
||||
assert.throws(() => session({items: [items[1]], initialKey: '0:folder/0.png'}), TypeError);
|
||||
});
|
||||
|
||||
test('viewer ignores stale readiness after navigation and disposal', () => {
|
||||
let calls = 0;
|
||||
const view = session({items:entries(),initialKey:'0:folder/0.png',onChange:() => calls++,
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Remove a folder that a killed test server may still hold for a moment (#636).
|
||||
|
||||
On Windows a virtual environment's ``python.exe`` is a launcher: it starts
|
||||
the real interpreter as a child process and ends it with itself. Killing the
|
||||
launcher returns at once, while Windows is still ending that child, which
|
||||
still has its log file open, so removing the folder at that moment fails with
|
||||
WinError 32. ``remove_when_released`` waits until the folder can be removed,
|
||||
up to a bound, and raises the last error after it.
|
||||
"""
|
||||
|
||||
import shutil
|
||||
import time
|
||||
|
||||
RELEASE_TIMEOUT_S = 30
|
||||
POLL_S = 0.05
|
||||
|
||||
|
||||
def remove_when_released(path: str, timeout: float = RELEASE_TIMEOUT_S) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
try:
|
||||
shutil.rmtree(path)
|
||||
return
|
||||
except FileNotFoundError:
|
||||
return
|
||||
except PermissionError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(POLL_S)
|
||||
@@ -225,7 +225,12 @@ class TestObserve(AnnotationAPITestCase):
|
||||
("dot segment", {"path": "./a.png"}, 403),
|
||||
("empty segment", {"path": "sub//a.png"}, 403),
|
||||
("absolute", {"path": "/etc/a.png"}, 403),
|
||||
("backslash", {"path": "sub\\a.png"}, 403),
|
||||
# #646: a backslash is a separator only on Windows.
|
||||
*(
|
||||
[("backslash", {"path": "sub\\a.png"}, 403)]
|
||||
if os.sep == "\\"
|
||||
else []
|
||||
),
|
||||
("drive", {"path": "C:/a.png"}, 403),
|
||||
("drive segment", {"path": "sub/C:a.png"}, 403),
|
||||
("nul", {"path": "a\x00.png"}, 403),
|
||||
@@ -399,6 +404,17 @@ class TestObserve(AnnotationAPITestCase):
|
||||
self.assertEqual(response.headers["Content-Type"], "video/mp4")
|
||||
self.assertEqual(await response.read(), clip.read_bytes())
|
||||
|
||||
@unittest.skipIf(os.sep == "\\", "a backslash cannot be in a Windows name")
|
||||
async def test_a_backslash_inside_a_name_can_be_tagged_on_posix(self):
|
||||
# #646: a Windows-style filename_prefix makes such a folder on POSIX.
|
||||
path = "m.safetensors\\2026-11-17/a.png"
|
||||
make_png(self.output_dir / "m.safetensors\\2026-11-17" / "a.png")
|
||||
observed = await self.observe_ok(path)
|
||||
self.assertEqual(observed["target"]["path"], path)
|
||||
status, body = await self.put_tags(self.save_body(observed, ["forest"]))
|
||||
self.assertEqual(status, 200, body)
|
||||
self.assertEqual((await self.observe_ok(path))["tags"], ["forest"])
|
||||
|
||||
async def test_observe_maps_capture_outcomes_to_codes(self):
|
||||
make_png(self.output_dir / "sub" / "a.png")
|
||||
outside = make_png(self.comfy_dir / "outside.png")
|
||||
|
||||
@@ -732,6 +732,32 @@ class TestAutotagErrorBodiesHideServerPaths(AutotagAPITestCase):
|
||||
|
||||
class TestUnloadAutotag(AutotagAPITestCase):
|
||||
|
||||
async def test_unload_runs_off_the_loop_and_holds_the_gate_until_done(self):
|
||||
started = threading.Event()
|
||||
release = threading.Event()
|
||||
self.addCleanup(release.set)
|
||||
threads = []
|
||||
|
||||
def unload():
|
||||
threads.append(threading.get_ident())
|
||||
started.set()
|
||||
release.wait(5)
|
||||
self.service._loaded_type = None
|
||||
|
||||
self.service._loaded_type = "gguf"
|
||||
self.service.unload_model = unload
|
||||
first = asyncio.ensure_future(
|
||||
self.client.request("POST", "/prompt_manager/autotag/unload")
|
||||
)
|
||||
self.assertTrue(await asyncio.to_thread(started.wait, 5))
|
||||
self.assertNotEqual(threads, [threading.get_ident()])
|
||||
second = await self.client.request("POST", "/prompt_manager/autotag/unload")
|
||||
self.assertEqual(second.status, 409)
|
||||
release.set()
|
||||
data = await (await first).json()
|
||||
self.assertEqual(data["message"], "GGUF model unloaded successfully")
|
||||
self.assertIsNone(model_gate.holder())
|
||||
|
||||
async def test_nothing_loaded(self):
|
||||
resp = await self.client.request("POST", "/prompt_manager/autotag/unload")
|
||||
data = await resp.json()
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import json
|
||||
import ntpath
|
||||
import os
|
||||
import sqlite3
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -178,7 +179,8 @@ class TestCollectionRoutes(CollectionRoutesTestCase):
|
||||
"../a.png",
|
||||
"sub/../../a.png",
|
||||
"C:/a.png",
|
||||
"a\\b.png",
|
||||
# #646: a backslash is a separator only on Windows.
|
||||
*(["a\\b.png"] if os.sep == "\\" else []),
|
||||
"/a.png",
|
||||
"notes.txt",
|
||||
):
|
||||
|
||||
+1
-54
@@ -343,7 +343,7 @@ class TestReadJsonBody(AioHTTPTestCase):
|
||||
|
||||
|
||||
class TestLongJobLock(unittest.TestCase):
|
||||
"""_acquire_long_job: one job per family at a time, released on exit."""
|
||||
"""The refusal a busy long job answers with."""
|
||||
|
||||
def setUp(self):
|
||||
database = MagicMock()
|
||||
@@ -353,33 +353,6 @@ class TestLongJobLock(unittest.TestCase):
|
||||
def _run(self, coro):
|
||||
return asyncio.run(coro)
|
||||
|
||||
def test_second_acquire_is_refused_until_first_releases(self):
|
||||
async def scenario():
|
||||
first = self.api._acquire_long_job("duplicates")
|
||||
self.assertIsNotNone(first)
|
||||
async with first:
|
||||
self.assertIsNone(self.api._acquire_long_job("duplicates"))
|
||||
# Other families are independent
|
||||
other = self.api._acquire_long_job("thumbnails")
|
||||
self.assertIsNotNone(other)
|
||||
async with other:
|
||||
pass
|
||||
again = self.api._acquire_long_job("duplicates")
|
||||
self.assertIsNotNone(again)
|
||||
async with again:
|
||||
pass
|
||||
|
||||
self._run(scenario())
|
||||
|
||||
def test_lock_is_released_when_the_job_raises(self):
|
||||
async def scenario():
|
||||
with self.assertRaises(RuntimeError):
|
||||
async with self.api._acquire_long_job("duplicates"):
|
||||
raise RuntimeError("boom")
|
||||
self.assertIsNotNone(self.api._acquire_long_job("duplicates"))
|
||||
|
||||
self._run(scenario())
|
||||
|
||||
def test_busy_response_is_409_with_envelope(self):
|
||||
resp = self.api._long_job_busy_response("Duplicate scan")
|
||||
self.assertEqual(resp.status, 409)
|
||||
@@ -953,32 +926,6 @@ class TestMetadataParsing(unittest.TestCase):
|
||||
f.write(b"nope")
|
||||
self.assertEqual(self.api._extract_comfyui_metadata(garbage), {})
|
||||
|
||||
def test_parse_a1111_parameters(self):
|
||||
meta = {"parameters": "a cat\nNegative prompt: dog\nSteps: 20"}
|
||||
parsed = self.api._parse_comfyui_prompt(meta)
|
||||
self.assertEqual(parsed["positive_prompt"], "a cat")
|
||||
self.assertEqual(parsed["negative_prompt"], "dog")
|
||||
self.assertEqual(parsed["parameters"]["parameters"], meta["parameters"])
|
||||
|
||||
def test_parse_comfyui_fields(self):
|
||||
meta = {
|
||||
"prompt": json.dumps({"1": {"class_type": "X", "inputs": {}}}),
|
||||
"workflow": "not json",
|
||||
"steps": "20",
|
||||
"cfg": "not-json-either",
|
||||
}
|
||||
parsed = self.api._parse_comfyui_prompt(meta)
|
||||
self.assertIsInstance(parsed["prompt"], dict)
|
||||
self.assertEqual(parsed["workflow"], "not json")
|
||||
self.assertEqual(parsed["parameters"]["steps"], 20)
|
||||
self.assertEqual(parsed["parameters"]["cfg"], "not-json-either")
|
||||
|
||||
parsed = self.api._parse_comfyui_prompt(
|
||||
{"prompt": "plain text", "workflow": json.dumps({"nodes": []})}
|
||||
)
|
||||
self.assertEqual(parsed["prompt"], "plain text")
|
||||
self.assertEqual(parsed["workflow"], {"nodes": []})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import json
|
||||
import ntpath
|
||||
import os
|
||||
import sqlite3
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -272,7 +273,9 @@ class TestRefusals(ImageCategoryTestCase):
|
||||
|
||||
async def test_unsafe_paths_are_403(self):
|
||||
(self.output_dir / "notes.txt").write_text("not media")
|
||||
for path in ("../outside.png", "/a.png", "C:/a.png", "a\\b.png", "a/./b.png"):
|
||||
# #646: a backslash is a separator only on Windows.
|
||||
windows = ["a\\b.png"] if os.sep == "\\" else []
|
||||
for path in ("../outside.png", "/a.png", "C:/a.png", *windows, "a/./b.png"):
|
||||
with self.subTest(path=path):
|
||||
await self.put([self.target(path)], "x", status=403)
|
||||
data = await self.put([self.target("notes.txt")], "x", status=403)
|
||||
|
||||
@@ -1268,7 +1268,12 @@ class TestPathHelpers(unittest.TestCase):
|
||||
def test_has_traversal(self):
|
||||
self.assertTrue(images_module._has_traversal(""))
|
||||
self.assertTrue(images_module._has_traversal("a/../b.png"))
|
||||
self.assertTrue(images_module._has_traversal("\\\\srv\\share\\x.png"))
|
||||
# #646: on POSIX a backslash is part of a name, so a UNC spelling is one
|
||||
# name below the root; on Windows it re-anchors the path.
|
||||
self.assertEqual(
|
||||
images_module._has_traversal("\\\\srv\\share\\x.png"), os.sep == "\\"
|
||||
)
|
||||
self.assertEqual(images_module._has_traversal("a\\..\\b.png"), os.sep == "\\")
|
||||
self.assertTrue(images_module._has_traversal(os.path.abspath(os.sep)))
|
||||
self.assertFalse(images_module._has_traversal("sub/x.png"))
|
||||
|
||||
@@ -2735,6 +2740,20 @@ class TestSharedListing(ImageAPITestCase):
|
||||
delay.start()
|
||||
self.addCleanup(delay.stop)
|
||||
|
||||
async def tearDownAsync(self):
|
||||
# A read that stores a listing starts the workspace cache build, which
|
||||
# opens the database on a worker thread; cancelling its task at cleanup
|
||||
# does not stop the thread. A test that ends on that read must let it
|
||||
# finish, or teardown can find its connection open (queue run
|
||||
# 44164234834, py3.14). No new build starts from here on; a held walk
|
||||
# is not waited for (its scan never opens the database).
|
||||
self.api._workspace_warm_enabled = False
|
||||
if self._warming():
|
||||
await asyncio.wait_for(
|
||||
asyncio.shield(self.api._workspace_warm_task), _HANG_LIMIT
|
||||
)
|
||||
await super().tearDownAsync()
|
||||
|
||||
async def _json(self, method, path, **kwargs):
|
||||
# Bounded, like every wait in this class: a stuck walk fails the test
|
||||
# with a traceback instead of hanging the whole run.
|
||||
|
||||
@@ -42,6 +42,37 @@ class TestLibraryAPI(ImageAPITestCase):
|
||||
self.assertEqual(len(media["images"]), 1)
|
||||
self.assertEqual(media["images"][0]["path"], "same.png")
|
||||
|
||||
async def test_used_and_reverse_name_sorts_page_through_every_prompt(self):
|
||||
ids = {text: self._save_prompt(text) for text in ("alpha", "beta", "gamma")}
|
||||
with self.api.db.model.get_connection() as conn:
|
||||
for text, runs, used in (
|
||||
("alpha", 1, "2026-01-01T00:00:00+00:00"),
|
||||
("beta", 9, "2026-02-01T00:00:00+00:00"),
|
||||
("gamma", 0, None),
|
||||
):
|
||||
conn.execute(
|
||||
"UPDATE prompts SET run_count=?, last_used_at=? WHERE id=?",
|
||||
(runs, used, ids[text]),
|
||||
)
|
||||
conn.commit()
|
||||
for sort, expected in (
|
||||
("most-used", ["beta", "alpha", "gamma"]),
|
||||
("last-used", ["beta", "alpha", "gamma"]),
|
||||
("name-desc", ["gamma", "beta", "alpha"]),
|
||||
):
|
||||
with self.subTest(sort=sort):
|
||||
seen, cursor = [], None
|
||||
for _ in expected:
|
||||
params = {"sort": sort, "limit": 1}
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
response, page = await self.get(**params)
|
||||
self.assertEqual(response.status, 200)
|
||||
seen.extend(item["text"] for item in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
self.assertEqual(seen, expected)
|
||||
self.assertIsNone(cursor)
|
||||
|
||||
async def test_scoped_cursor_tampering_filters_and_continuation(self):
|
||||
for text in ("one", "two", "three"):
|
||||
self._save_prompt(text)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import unittest
|
||||
@@ -151,7 +152,8 @@ class TestPromptInspector(ImageAPITestCase):
|
||||
for path in (
|
||||
"%2Fetc%2Fpasswd.png",
|
||||
"..%2Fsecret.png",
|
||||
"%5Csecret.png",
|
||||
# #646: on POSIX a backslash is part of a name (404 below).
|
||||
*(["%5Csecret.png"] if os.sep == "\\" else []),
|
||||
"bad.txt",
|
||||
"null%00.png",
|
||||
"C:%5Csecret.png",
|
||||
@@ -160,6 +162,9 @@ class TestPromptInspector(ImageAPITestCase):
|
||||
self.assertEqual(response.status, 403, path)
|
||||
response, result = await self.inspect("missing.png")
|
||||
self.assertEqual(response.status, 404)
|
||||
if os.sep == "/":
|
||||
response, result = await self.inspect("%5Csecret.png")
|
||||
self.assertEqual(response.status, 404)
|
||||
outside = png(self.comfy_dir / "outside.png", prompt=graph("private"))
|
||||
self._make_symlink(outside, self.output_dir / "escape.png")
|
||||
response, result = await self.inspect("escape.png")
|
||||
|
||||
@@ -684,6 +684,28 @@ class TestTagMutationRoutes(RouteCoverageCase):
|
||||
|
||||
class TestSaveRoute(RouteCoverageCase):
|
||||
|
||||
async def test_a_malformed_body_is_refused_and_saves_nothing(self):
|
||||
for body in (
|
||||
[],
|
||||
"text",
|
||||
{"text": 123},
|
||||
{"text": "fixture", "category": 123},
|
||||
{"text": "fixture", "notes": 123},
|
||||
{"text": "fixture", "tags": 123},
|
||||
{"text": "fixture", "rating": "high"},
|
||||
):
|
||||
with self.subTest(body=body):
|
||||
status, data = await self._json(
|
||||
"POST", "/prompt_manager/save", json=body
|
||||
)
|
||||
self.assertEqual(status, 400)
|
||||
self.assertFalse(data["success"])
|
||||
status, data = await self._json(
|
||||
"POST", "/prompt_manager/save", data=b"{not json"
|
||||
)
|
||||
self.assertEqual(status, 400)
|
||||
self.assertEqual(self.api.db.search_prompts(text="fixture"), [])
|
||||
|
||||
async def test_invalid_rating_is_400(self):
|
||||
status, data = await self._json(
|
||||
"POST", "/prompt_manager/save", json={"text": "ok", "rating": 99}
|
||||
|
||||
@@ -149,7 +149,8 @@ class TestRescopeRoute(ImageAPITestCase):
|
||||
{"target": {**good, "path": "../a.png"}},
|
||||
{"target": {**good, "path": "/abs.png"}},
|
||||
{"target": {**good, "path": "C:/a.png"}},
|
||||
{"target": {**good, "path": "sub\\a.png"}},
|
||||
# #646: a backslash is a separator only on Windows.
|
||||
*([{"target": {**good, "path": "sub\\a.png"}}] if os.sep == "\\" else []),
|
||||
{"target": {**good, "path": "sub//a.png"}},
|
||||
{"target": {**good, "path": "notes.txt"}},
|
||||
{"target": {**good, "path": "x" * 2000 + ".png"}},
|
||||
|
||||
@@ -14,6 +14,7 @@ import os
|
||||
import posixpath
|
||||
import sqlite3
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -452,6 +453,22 @@ class TestQueueReads(ReviewRoutesTestCase):
|
||||
)
|
||||
|
||||
|
||||
class TestBackslashNames(ReviewRoutesTestCase):
|
||||
"""#646: a review item in a folder whose name holds a backslash (POSIX)."""
|
||||
|
||||
@unittest.skipIf(os.sep == "\\", "a backslash cannot be in a Windows name")
|
||||
async def test_the_target_carries_the_posix_mark(self):
|
||||
self._require_routes()
|
||||
self._record(self._ambiguous("m.safetensors\\2026-11-17/a.png"))
|
||||
self._record(self._ambiguous("plain/b.png", color=(0, 255, 0)))
|
||||
items = {item["filename"]: item for item in (await self._list())["items"]}
|
||||
marked = items["a.png"]["target"]
|
||||
self.assertEqual(marked["path"], "m.safetensors\\2026-11-17/a.png")
|
||||
self.assertEqual(marked["path_style"], "posix")
|
||||
self.assertFalse(items["a.png"]["unavailable"])
|
||||
self.assertNotIn("path_style", items["b.png"]["target"])
|
||||
|
||||
|
||||
class TestDecisions(ReviewRoutesTestCase):
|
||||
async def test_apply_candidate_links_pair_and_records_decision_atomically(self):
|
||||
self._require_routes()
|
||||
|
||||
@@ -9,7 +9,6 @@ import json
|
||||
import ntpath
|
||||
import os
|
||||
import posixpath
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
@@ -378,25 +377,6 @@ class TestValidation(unittest.TestCase):
|
||||
self.assertTrue(text.endswith("."))
|
||||
|
||||
|
||||
class TestNoLegacySaveCallers(unittest.TestCase):
|
||||
def test_save_to_file_has_no_callers(self):
|
||||
offenders = []
|
||||
for folder in ("py", "utils", "database"):
|
||||
for path in (REPO / folder).rglob("*.py"):
|
||||
for number, line in enumerate(
|
||||
path.read_text(encoding="utf-8").splitlines(), 1
|
||||
):
|
||||
code = line.split("#", 1)[0]
|
||||
if (
|
||||
re.search(r"\bsave_to_file\(", code)
|
||||
and "def save_to_file" not in code
|
||||
):
|
||||
if "PromptManagerConfig.save_to_file('" in line:
|
||||
continue # its own docstring example
|
||||
offenders.append(f"{path.relative_to(REPO)}:{number}")
|
||||
self.assertEqual(offenders, [])
|
||||
|
||||
|
||||
try:
|
||||
from tests.test_api_images import ImageAPITestCase
|
||||
except ImportError: # discovered with tests/ as the top-level directory
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""The logo and icons are wired in where a user sees them (#632).
|
||||
|
||||
Every page Prompt Manager serves names the favicon, the files it names exist
|
||||
at the sizes they claim, the README and the Registry metadata point at files
|
||||
that are in the repository, and the Registry package keeps what the pages
|
||||
load at run time.
|
||||
"""
|
||||
|
||||
import re
|
||||
import tomllib
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
try:
|
||||
from tests.test_package_contents import _ignored
|
||||
except ImportError: # discovered with tests/ as the top-level directory
|
||||
from test_package_contents import _ignored
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
PAGES = ("workspace.html", "admin.html", "gallery.html", "metadata.html", "index.html")
|
||||
ICON_LINK = re.compile(
|
||||
r'<link rel="(icon|apple-touch-icon)"(?: type="image/png")?'
|
||||
r' sizes="(\d+)x(\d+)" href="(lib/brand/[a-z0-9-]+\.png)">'
|
||||
)
|
||||
RAW_PREFIX = "https://raw.githubusercontent.com/ComfyAssets/ComfyUI_PromptManager/main/"
|
||||
|
||||
|
||||
def _size(path: Path) -> tuple[int, int]:
|
||||
with Image.open(path) as image:
|
||||
return image.size
|
||||
|
||||
|
||||
class TestBrandAssets(unittest.TestCase):
|
||||
def test_every_page_links_icons_that_exist_at_the_stated_size(self):
|
||||
for page in PAGES:
|
||||
with self.subTest(page=page):
|
||||
html = (ROOT / "web" / page).read_text(encoding="utf-8")
|
||||
links = ICON_LINK.findall(html)
|
||||
self.assertEqual(
|
||||
[kind for kind, *_ in links], ["icon", "apple-touch-icon"]
|
||||
)
|
||||
for _kind, width, height, href in links:
|
||||
# Pages sit beside lib/ under /prompt_manager/, like their CSS.
|
||||
file = ROOT / "web" / href
|
||||
self.assertEqual(_size(file), (int(width), int(height)), href)
|
||||
|
||||
def test_page_icons_ship_in_the_registry_package(self):
|
||||
for file in sorted((ROOT / "web" / "lib" / "brand").iterdir()):
|
||||
relative = file.relative_to(ROOT).as_posix()
|
||||
self.assertFalse(_ignored(relative), relative)
|
||||
self.assertLess(file.stat().st_size, 16 * 1024, relative)
|
||||
|
||||
def test_readme_opens_with_the_banner(self):
|
||||
readme = (ROOT / "README.md").read_text(encoding="utf-8")
|
||||
first = next(line for line in readme.splitlines() if line.strip())
|
||||
match = re.fullmatch(r"!\[[^\]]+\]\((assets/brand/[a-z0-9-]+\.webp)\)", first)
|
||||
self.assertIsNotNone(match, first)
|
||||
self.assertEqual(_size(ROOT / match.group(1)), (1280, 640))
|
||||
|
||||
def test_registry_icon_is_the_app_icon_in_this_repository(self):
|
||||
with open(ROOT / "pyproject.toml", "rb") as handle:
|
||||
icon = tomllib.load(handle)["tool"]["comfy"]["Icon"]
|
||||
self.assertTrue(icon.startswith(RAW_PREFIX), icon)
|
||||
self.assertEqual(_size(ROOT / icon[len(RAW_PREFIX) :]), (256, 256))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -6,27 +6,36 @@ down when the launcher's end of its stdin pipe closes, and still removes its
|
||||
temp root. This runs on every OS in CI, where Windows is the strict case.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from tests.process_cleanup import remove_when_released
|
||||
except ImportError: # discovered with tests/ as the top-level directory
|
||||
from process_cleanup import remove_when_released
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
SERVER_TIMEOUT_S = 60
|
||||
|
||||
|
||||
class TestBrowserServerLifetime(unittest.TestCase):
|
||||
class BrowserServerCase(unittest.TestCase):
|
||||
"""Starts the test server in a temp folder of its own; holds no tests."""
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(remove_when_released, self.tmp)
|
||||
|
||||
def start(self, *extra):
|
||||
env = {**os.environ, "TMPDIR": self.tmp.name}
|
||||
env.update(TEMP=self.tmp.name, TMP=self.tmp.name)
|
||||
env = {**os.environ, "TMPDIR": self.tmp}
|
||||
env.update(TEMP=self.tmp, TMP=self.tmp)
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, "-m", "tests.browser.server", "--port", "0", *extra],
|
||||
cwd=REPO_ROOT,
|
||||
@@ -47,7 +56,8 @@ class TestBrowserServerLifetime(unittest.TestCase):
|
||||
self.addCleanup(stop)
|
||||
line = process.stdout.readline().decode()
|
||||
self.assertTrue(line.startswith("PM_TEST_SERVER_PORT="), line)
|
||||
url = f"http://127.0.0.1:{int(line.split('=', 1)[1])}/prompt_manager/test"
|
||||
self.origin = f"http://127.0.0.1:{int(line.split('=', 1)[1])}"
|
||||
url = f"{self.origin}/prompt_manager/test"
|
||||
deadline = time.monotonic() + SERVER_TIMEOUT_S
|
||||
while True:
|
||||
try:
|
||||
@@ -60,8 +70,10 @@ class TestBrowserServerLifetime(unittest.TestCase):
|
||||
time.sleep(0.1)
|
||||
|
||||
def roots(self):
|
||||
return sorted(path.name for path in Path(self.tmp.name).glob("pm-browser-*"))
|
||||
return sorted(path.name for path in Path(self.tmp).glob("pm-browser-*"))
|
||||
|
||||
|
||||
class TestBrowserServerLifetime(BrowserServerCase):
|
||||
def test_server_exits_and_removes_its_temp_root_when_stdin_closes(self):
|
||||
process = self.start("--exit-on-stdin-eof")
|
||||
self.assertEqual(len(self.roots()), 1, "the server works in its own temp root")
|
||||
@@ -79,6 +91,37 @@ class TestBrowserServerLifetime(unittest.TestCase):
|
||||
process.wait(timeout=1)
|
||||
|
||||
|
||||
class TestBrowserServerSeeding(BrowserServerCase):
|
||||
"""The fixtures seed on every OS (#629): Windows roots are not POSIX paths."""
|
||||
|
||||
def reset(self, path, body):
|
||||
request = urllib.request.Request(
|
||||
f"{self.origin}{path}",
|
||||
json.dumps(body).encode(),
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen( # nosec B310
|
||||
request, timeout=SERVER_TIMEOUT_S
|
||||
) as response:
|
||||
return response.status, json.loads(response.read())
|
||||
except urllib.error.HTTPError as error:
|
||||
with error:
|
||||
return error.code, error.read().decode(errors="replace")
|
||||
|
||||
def test_concept_fixture_seeds_its_recorded_runs(self):
|
||||
self.start()
|
||||
status, body = self.reset("/__test__/concept/reset", {})
|
||||
self.assertEqual(status, 200, body)
|
||||
self.assertTrue(body["success"])
|
||||
|
||||
def test_history_fixture_seeds_its_recorded_runs(self):
|
||||
self.start()
|
||||
status, body = self.reset("/__test__/reset", {"chronological_history": True})
|
||||
self.assertEqual(status, 200, body)
|
||||
self.assertTrue(body["success"])
|
||||
|
||||
|
||||
class TestBrowserServerLoraIsolation(unittest.TestCase):
|
||||
"""#355: page tests never read the developer's LoraManager settings."""
|
||||
|
||||
|
||||
@@ -22,6 +22,11 @@ from pathlib import Path
|
||||
from tests.browser import slow_reset_watch
|
||||
from tests.browser.slow_reset_watch import REPORT_PREFIX, ResetWatch, is_reset_path
|
||||
|
||||
try:
|
||||
from tests.process_cleanup import remove_when_released
|
||||
except ImportError: # discovered with tests/ as the top-level directory
|
||||
from process_cleanup import remove_when_released
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
SERVER_TIMEOUT_S = 60
|
||||
HOLD_SECONDS = slow_reset_watch.SLOW_RESET_SECONDS + 4
|
||||
@@ -108,10 +113,10 @@ class TestSlowResetOnTheServer(unittest.TestCase):
|
||||
"""A reset behind another process's write lock, on tests/browser/server.py."""
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
env = {**os.environ, "TMPDIR": self.tmp.name}
|
||||
env.update(TEMP=self.tmp.name, TMP=self.tmp.name)
|
||||
self.tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(remove_when_released, self.tmp)
|
||||
env = {**os.environ, "TMPDIR": self.tmp}
|
||||
env.update(TEMP=self.tmp, TMP=self.tmp)
|
||||
self.stderr = tempfile.TemporaryFile()
|
||||
self.addCleanup(self.stderr.close)
|
||||
process = subprocess.Popen(
|
||||
@@ -145,9 +150,7 @@ class TestSlowResetOnTheServer(unittest.TestCase):
|
||||
self.assertIsNone(process.poll(), "the server exited early")
|
||||
self.assertLess(time.monotonic(), deadline, "never ready")
|
||||
time.sleep(0.1)
|
||||
[self.db_path] = glob.glob(
|
||||
os.path.join(self.tmp.name, "pm-browser-*", "browser.db")
|
||||
)
|
||||
[self.db_path] = glob.glob(os.path.join(self.tmp, "pm-browser-*", "browser.db"))
|
||||
|
||||
def reset(self) -> tuple[int, float]:
|
||||
request = urllib.request.Request(
|
||||
|
||||
@@ -197,7 +197,6 @@ class JobCase(unittest.TestCase):
|
||||
node.logger = logging.getLogger("test.cached_runs")
|
||||
node.prompt_tracker = mock.Mock()
|
||||
self.trackers.append(node.prompt_tracker)
|
||||
node.comfyui_integration = mock.Mock()
|
||||
node._inject_lora_trigger_words = lambda text: text
|
||||
node.pending_first_use = self.pending
|
||||
node.pending_pair_first_use = self.pair_pending
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
"""CI runs tests only for changes that can affect code (#639).
|
||||
|
||||
``tools/ci/change_class.py`` sorts a change by the files it touches: ``inert``
|
||||
(nothing reads the file at run or test time), ``docs`` (a Python test reads
|
||||
it) or ``code`` (everything else, and every case of doubt).
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / "tools" / "ci"))
|
||||
import change_class # noqa: E402
|
||||
|
||||
SCRIPT = ROOT / "tools" / "ci" / "change_class.py"
|
||||
|
||||
|
||||
def _isolated_environment(**extra):
|
||||
"""The environment without git's own variables and the script's inputs.
|
||||
|
||||
A git hook exports ``GIT_DIR`` and ``GIT_INDEX_FILE`` for the repository
|
||||
being pushed. A child ``git`` that inherits them works on that repository
|
||||
instead of the temp one, so the pre-push hook must never pass them on.
|
||||
"""
|
||||
kept = {
|
||||
key: value
|
||||
for key, value in os.environ.items()
|
||||
if not key.startswith("GIT_") and key not in change_class.ENVIRONMENT
|
||||
}
|
||||
return {**kept, **extra}
|
||||
|
||||
|
||||
class TestClassify(unittest.TestCase):
|
||||
def test_files_nothing_reads_are_inert(self):
|
||||
for paths in (
|
||||
[".github/FUNDING.yml"],
|
||||
["SECURITY.md"],
|
||||
["images/pm-01.png", ".github/ISSUE_TEMPLATE/bug_report.md"],
|
||||
):
|
||||
self.assertEqual(change_class.classify(paths), "inert", paths)
|
||||
|
||||
def test_documents_a_test_reads_are_docs(self):
|
||||
for paths in (
|
||||
["README.md"],
|
||||
["README-legacy.md", "assets/readme/hero.webp"],
|
||||
["assets/brand/banner.webp", ".github/FUNDING.yml"],
|
||||
):
|
||||
self.assertEqual(change_class.classify(paths), "docs", paths)
|
||||
|
||||
def test_anything_else_is_code(self):
|
||||
for paths in (
|
||||
["py/api/images.py"],
|
||||
["README.md", "web/js/workspace/index.mjs"],
|
||||
[".github/FUNDING.yml", "pyproject.toml"],
|
||||
# The browser suite compares production against the concept.
|
||||
["docs/concepts/workspace/app.js"],
|
||||
# The tooling tests read the tables in it.
|
||||
["TESTING.md"],
|
||||
[".github/workflows/test.yml"],
|
||||
["LICENSE"],
|
||||
# Look-alikes of listed names are not listed.
|
||||
["docs/README.md"],
|
||||
["web/images/x.png"],
|
||||
["SECURITY.md.py"],
|
||||
[".github/funding.yml"],
|
||||
):
|
||||
self.assertEqual(change_class.classify(paths), "code", paths)
|
||||
|
||||
def test_no_files_is_code(self):
|
||||
self.assertEqual(change_class.classify([]), "code")
|
||||
|
||||
def test_every_document_a_test_reads_exists(self):
|
||||
for name in change_class.DOCS_FILES:
|
||||
self.assertTrue((ROOT / name).is_file(), name)
|
||||
for folder in change_class.DOCS_FOLDERS:
|
||||
self.assertTrue((ROOT / folder).is_dir(), folder)
|
||||
|
||||
|
||||
class TestCommandLine(unittest.TestCase):
|
||||
"""The script against a real repository with one commit per kind of change."""
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.repo = Path(self.tmp.name) / "repo"
|
||||
self.repo.mkdir()
|
||||
# As in a git hook: these name another repository, which must stay untouched.
|
||||
self.other = Path(self.tmp.name) / "other.git"
|
||||
patcher = unittest.mock.patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"GIT_DIR": str(self.other),
|
||||
"GIT_INDEX_FILE": str(self.other / "index"),
|
||||
"GIT_WORK_TREE": str(self.tmp.name),
|
||||
},
|
||||
)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.addCleanup(lambda: self.assertFalse(self.other.exists()))
|
||||
self.git("init", "-q", "-b", "main")
|
||||
self.commit({"py/a.py": "a\n", "README.md": "r\n"})
|
||||
self.base = self.head()
|
||||
|
||||
def git(self, *args):
|
||||
return subprocess.run(
|
||||
["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args],
|
||||
cwd=self.repo,
|
||||
env=_isolated_environment(),
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
|
||||
def commit(self, files):
|
||||
for name, text in files.items():
|
||||
path = self.repo / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
self.git("add", "-A")
|
||||
self.git("commit", "-q", "-m", "change")
|
||||
|
||||
def head(self):
|
||||
return self.git("rev-parse", "HEAD")
|
||||
|
||||
def run_script(self, *args, **env):
|
||||
return subprocess.run(
|
||||
[sys.executable, str(SCRIPT), *args],
|
||||
cwd=self.repo,
|
||||
env=_isolated_environment(**env),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
def class_of(self, **env):
|
||||
result = self.run_script(**env)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
return result.stdout.strip()
|
||||
|
||||
def test_a_pull_request_is_classed_by_its_own_files(self):
|
||||
self.git("checkout", "-q", "-b", "topic")
|
||||
self.commit({".github/FUNDING.yml": "x\n"})
|
||||
topic = self.head()
|
||||
# main moved on with code meanwhile: that is not this pull request's change.
|
||||
self.git("checkout", "-q", "main")
|
||||
self.commit({"py/a.py": "b\n"})
|
||||
self.assertEqual(
|
||||
self.class_of(
|
||||
EVENT_NAME="pull_request", BASE_SHA=self.head(), HEAD_SHA=topic
|
||||
),
|
||||
"class=inert",
|
||||
)
|
||||
|
||||
def test_a_merge_group_and_a_push_are_classed_by_their_range(self):
|
||||
self.commit({"README.md": "r2\n"})
|
||||
for event in ("merge_group", "push"):
|
||||
self.assertEqual(
|
||||
self.class_of(
|
||||
EVENT_NAME=event, BASE_SHA=self.base, HEAD_SHA=self.head()
|
||||
),
|
||||
"class=docs",
|
||||
event,
|
||||
)
|
||||
self.commit({"py/a.py": "c\n"})
|
||||
self.assertEqual(
|
||||
self.class_of(
|
||||
EVENT_NAME="merge_group", BASE_SHA=self.base, HEAD_SHA=self.head()
|
||||
),
|
||||
"class=code",
|
||||
)
|
||||
|
||||
def test_a_deleted_or_renamed_file_counts_under_both_names(self):
|
||||
self.git("mv", "py/a.py", "SECURITY.md")
|
||||
self.git("commit", "-q", "-m", "rename")
|
||||
self.assertEqual(
|
||||
self.class_of(
|
||||
EVENT_NAME="merge_group", BASE_SHA=self.base, HEAD_SHA=self.head()
|
||||
),
|
||||
"class=code",
|
||||
)
|
||||
|
||||
def test_doubt_is_code(self):
|
||||
self.commit({".github/FUNDING.yml": "x\n"})
|
||||
head = self.head()
|
||||
zero = "0" * 40
|
||||
for env in (
|
||||
{"EVENT_NAME": "workflow_dispatch", "BASE_SHA": self.base},
|
||||
{"EVENT_NAME": "schedule", "BASE_SHA": self.base, "HEAD_SHA": head},
|
||||
{"EVENT_NAME": "push", "BASE_SHA": zero, "HEAD_SHA": head},
|
||||
{"EVENT_NAME": "push", "BASE_SHA": "", "HEAD_SHA": head},
|
||||
{"EVENT_NAME": "push", "BASE_SHA": "f" * 40, "HEAD_SHA": head},
|
||||
{"EVENT_NAME": "push", "BASE_SHA": head, "HEAD_SHA": head},
|
||||
{},
|
||||
):
|
||||
self.assertEqual(self.class_of(**env), "class=code", env)
|
||||
|
||||
def test_the_pre_push_command_is_skipped_only_for_an_inert_push(self):
|
||||
marker = self.repo / "ran"
|
||||
command = (
|
||||
"--unless-inert",
|
||||
sys.executable,
|
||||
"-c",
|
||||
"open('ran', 'w').close()",
|
||||
)
|
||||
self.commit({".github/FUNDING.yml": "x\n"})
|
||||
refs = {"PRE_COMMIT_FROM_REF": self.base, "PRE_COMMIT_TO_REF": self.head()}
|
||||
result = self.run_script(*command, **refs)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertFalse(marker.exists())
|
||||
self.assertIn("inert", result.stdout)
|
||||
# No range from pre-commit (a manual run) and a docs push both run it.
|
||||
self.assertEqual(self.run_script(*command).returncode, 0)
|
||||
self.assertTrue(marker.exists())
|
||||
marker.unlink()
|
||||
self.commit({"README.md": "r3\n"})
|
||||
refs["PRE_COMMIT_TO_REF"] = self.head()
|
||||
self.assertEqual(self.run_script(*command, **refs).returncode, 0)
|
||||
self.assertTrue(marker.exists())
|
||||
|
||||
def test_the_pre_push_command_is_found_through_path(self):
|
||||
# On Windows a bare "npm" is npm.cmd: only a PATH lookup with PATHEXT finds it.
|
||||
found = unittest.mock.Mock(return_value=unittest.mock.Mock(returncode=3))
|
||||
with unittest.mock.patch.dict(os.environ, _isolated_environment(), clear=True):
|
||||
with (
|
||||
unittest.mock.patch.object(
|
||||
change_class.shutil, "which", return_value="C:/node/npm.cmd"
|
||||
) as which,
|
||||
unittest.mock.patch.object(change_class.subprocess, "run", found),
|
||||
):
|
||||
code = change_class.main(["--unless-inert", "npm", "test"])
|
||||
which.assert_called_once_with("npm")
|
||||
found.assert_called_once_with(["C:/node/npm.cmd", "test"], check=False)
|
||||
self.assertEqual(code, 3)
|
||||
|
||||
def test_a_missing_or_absent_pre_push_command_fails_clearly(self):
|
||||
with unittest.mock.patch.dict(os.environ, _isolated_environment(), clear=True):
|
||||
with (
|
||||
unittest.mock.patch.object(
|
||||
change_class.shutil, "which", return_value=None
|
||||
),
|
||||
unittest.mock.patch.object(change_class.subprocess, "run") as run,
|
||||
):
|
||||
self.assertEqual(change_class.main(["--unless-inert", "nope"]), 127)
|
||||
self.assertEqual(change_class.main(["--unless-inert"]), 2)
|
||||
run.assert_not_called()
|
||||
|
||||
def test_the_pre_push_command_keeps_its_exit_code(self):
|
||||
result = self.run_script(
|
||||
"--unless-inert", sys.executable, "-c", "raise SystemExit(7)"
|
||||
)
|
||||
self.assertEqual(result.returncode, 7)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,153 +0,0 @@
|
||||
"""Tests for utils.comfyui_integration."""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from utils.comfyui_integration import ComfyUIMetadataIntegration
|
||||
|
||||
|
||||
class TestSaveImageNotPatched(unittest.TestCase):
|
||||
"""Regression for #75: SaveImage must save each node's own prompt inputs.
|
||||
|
||||
The old SaveImage patch wrote the last-run PromptManager prompt into every
|
||||
PromptManager node, so negative prompts were saved as copies of the positive.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
def save_images(
|
||||
self_node,
|
||||
images,
|
||||
filename_prefix="ComfyUI",
|
||||
prompt=None,
|
||||
extra_pnginfo=None,
|
||||
):
|
||||
return {"prompt": prompt}
|
||||
|
||||
self.original_save_images = save_images
|
||||
fake_nodes = types.ModuleType("nodes")
|
||||
fake_nodes.SaveImage = type("SaveImage", (), {"save_images": save_images})
|
||||
self._saved_nodes = sys.modules.get("nodes")
|
||||
sys.modules["nodes"] = fake_nodes
|
||||
self.fake_nodes = fake_nodes
|
||||
ComfyUIMetadataIntegration._instance = None
|
||||
|
||||
def tearDown(self):
|
||||
ComfyUIMetadataIntegration._instance = None
|
||||
if self._saved_nodes is None:
|
||||
sys.modules.pop("nodes", None)
|
||||
else:
|
||||
sys.modules["nodes"] = self._saved_nodes
|
||||
|
||||
def test_save_images_is_left_untouched(self):
|
||||
ComfyUIMetadataIntegration()
|
||||
self.assertIs(self.fake_nodes.SaveImage.save_images, self.original_save_images)
|
||||
|
||||
def test_registered_prompt_does_not_rewrite_saved_metadata(self):
|
||||
integration = ComfyUIMetadataIntegration()
|
||||
integration.register_prompt("pm_1", "positive final text", {})
|
||||
prompt = {
|
||||
"39": {"class_type": "PromptManager", "inputs": {"text": "a cat"}},
|
||||
"40": {"class_type": "PromptManager", "inputs": {"text": "blurry"}},
|
||||
}
|
||||
|
||||
result = self.fake_nodes.SaveImage().save_images([], prompt=prompt)
|
||||
|
||||
self.assertEqual(result["prompt"]["39"]["inputs"]["text"], "a cat")
|
||||
self.assertEqual(result["prompt"]["40"]["inputs"]["text"], "blurry")
|
||||
|
||||
def test_prompt_registry_still_available_to_nodes(self):
|
||||
integration = ComfyUIMetadataIntegration()
|
||||
integration.register_prompt("pm_1", "hello", {})
|
||||
self.assertEqual(integration.get_current_prompt_text("pm_1"), "hello")
|
||||
|
||||
|
||||
import threading # noqa: E402
|
||||
import unittest.mock as mock # noqa: E402
|
||||
|
||||
from utils import comfyui_integration # noqa: E402
|
||||
from utils.comfyui_integration import get_comfyui_integration # noqa: E402
|
||||
|
||||
|
||||
class IntegrationTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
ComfyUIMetadataIntegration._instance = None
|
||||
comfyui_integration._integration_instance = None
|
||||
# Patch the module's own ``time`` name rather than ``time.time`` globally:
|
||||
# background threads from other tests (image monitor, watchdog) would
|
||||
# otherwise tick this clock and make fresh registrations look stale.
|
||||
self.clock = mock.patch.object(
|
||||
comfyui_integration, "time", types.SimpleNamespace(time=self._now)
|
||||
)
|
||||
self.clock.start()
|
||||
self.addCleanup(self.clock.stop)
|
||||
self._ticks = 1000.0
|
||||
self.integration = get_comfyui_integration()
|
||||
|
||||
def tearDown(self):
|
||||
ComfyUIMetadataIntegration._instance = None
|
||||
comfyui_integration._integration_instance = None
|
||||
|
||||
def _now(self):
|
||||
self._ticks += 1.0
|
||||
return self._ticks
|
||||
|
||||
|
||||
class TestSingletonAndRegistry(IntegrationTestCase):
|
||||
def test_singleton_keeps_registrations_across_constructions(self):
|
||||
self.assertIs(get_comfyui_integration(), self.integration)
|
||||
self.assertIs(ComfyUIMetadataIntegration(), self.integration)
|
||||
self.integration.register_prompt("n1", "hello", {"category": "x"})
|
||||
ComfyUIMetadataIntegration() # __init__ runs again: must not reset state
|
||||
self.assertEqual(self.integration.get_current_prompt_text("n1"), "hello")
|
||||
|
||||
def test_latest_prompt_of_this_thread_wins_without_a_node_id(self):
|
||||
self.integration.register_prompt("n1", "first", {})
|
||||
self.integration.register_prompt("n2", "second", {})
|
||||
self.assertEqual(self.integration.get_current_prompt_text(), "second")
|
||||
self.assertEqual(self.integration.get_current_prompt_text("missing"), "second")
|
||||
self.assertEqual(self.integration.get_current_prompt_text("n1"), "first")
|
||||
|
||||
def test_nothing_registered_returns_none(self):
|
||||
self.assertIsNone(self.integration.get_current_prompt_text())
|
||||
self.assertIsNone(self.integration.get_current_prompt_text("n1"))
|
||||
|
||||
|
||||
class TestCrossThreadLookup(IntegrationTestCase):
|
||||
def _register_in_thread(self, text):
|
||||
worker = threading.Thread(
|
||||
target=self.integration.register_prompt, args=("w1", text, {})
|
||||
)
|
||||
worker.start()
|
||||
worker.join()
|
||||
|
||||
def test_recent_prompt_from_another_thread_is_used(self):
|
||||
self._register_in_thread("from worker")
|
||||
self.assertEqual(self.integration.get_current_prompt_text(), "from worker")
|
||||
|
||||
def test_stale_prompt_from_another_thread_is_ignored(self):
|
||||
self._register_in_thread("from worker")
|
||||
self._ticks += 400.0
|
||||
self.assertIsNone(self.integration.get_current_prompt_text())
|
||||
|
||||
def test_global_entry_of_this_thread_is_found_without_thread_local(self):
|
||||
self.integration.register_prompt("n1", "mine", {})
|
||||
self.integration._thread_local = threading.local()
|
||||
self.assertEqual(self.integration.get_current_prompt_text(), "mine")
|
||||
|
||||
def test_cleanup_removes_old_registrations_only(self):
|
||||
self._register_in_thread("old")
|
||||
self._ticks += 700.0
|
||||
self.integration.register_prompt("n2", "new", {})
|
||||
self.integration.cleanup_old_prompts(max_age_seconds=600)
|
||||
texts = sorted(v["text"] for v in self.integration._current_prompts.values())
|
||||
self.assertEqual(texts, ["new"])
|
||||
self.integration.cleanup_old_prompts(max_age_seconds=600) # nothing to do
|
||||
self.assertEqual(len(self.integration._current_prompts), 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+4
-63
@@ -213,7 +213,8 @@ class TestPromptManagerConfig(unittest.TestCase):
|
||||
try:
|
||||
# Modify a value
|
||||
PromptManagerConfig.MAX_SEARCH_RESULTS = 42
|
||||
PromptManagerConfig.save_to_file(tmp.name)
|
||||
with open(tmp.name, "w", encoding="utf-8") as handle:
|
||||
json.dump(PromptManagerConfig.get_config(), handle)
|
||||
|
||||
# Reset and reload
|
||||
PromptManagerConfig.MAX_SEARCH_RESULTS = 100
|
||||
@@ -240,55 +241,6 @@ class TestPromptManagerConfig(unittest.TestCase):
|
||||
finally:
|
||||
os.unlink(tmp.name)
|
||||
|
||||
def test_save_creates_directory(self):
|
||||
tmp_dir = tempfile.mkdtemp()
|
||||
nested_path = os.path.join(tmp_dir, "subdir", "config.json")
|
||||
try:
|
||||
PromptManagerConfig.save_to_file(nested_path)
|
||||
self.assertTrue(os.path.exists(nested_path))
|
||||
with open(nested_path) as f:
|
||||
data = json.load(f)
|
||||
self.assertIn("database", data)
|
||||
finally:
|
||||
import shutil
|
||||
|
||||
shutil.rmtree(tmp_dir)
|
||||
|
||||
def test_saved_file_is_private_to_the_user(self):
|
||||
import stat
|
||||
|
||||
tmp_dir = tempfile.mkdtemp()
|
||||
try:
|
||||
path = os.path.join(tmp_dir, "config.json")
|
||||
PromptManagerConfig.save_to_file(path)
|
||||
mode = stat.S_IMODE(os.stat(path).st_mode)
|
||||
if os.name == "posix":
|
||||
self.assertEqual(mode, 0o600)
|
||||
with open(path) as f:
|
||||
self.assertIn("database", json.load(f))
|
||||
# Overwriting an existing, more open file tightens it as well
|
||||
os.chmod(path, 0o644)
|
||||
PromptManagerConfig.save_to_file(path)
|
||||
if os.name == "posix":
|
||||
self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), 0o600)
|
||||
finally:
|
||||
import shutil
|
||||
|
||||
shutil.rmtree(tmp_dir, ignore_errors=True)
|
||||
|
||||
def test_saved_file_is_valid_json(self):
|
||||
tmp = tempfile.NamedTemporaryFile(
|
||||
delete=False, suffix=".json", dir=tempfile.gettempdir()
|
||||
)
|
||||
tmp.close()
|
||||
try:
|
||||
PromptManagerConfig.save_to_file(tmp.name)
|
||||
with open(tmp.name) as f:
|
||||
data = json.load(f)
|
||||
self.assertIsInstance(data, dict)
|
||||
finally:
|
||||
os.unlink(tmp.name)
|
||||
|
||||
|
||||
class TestIntegrationConfig(unittest.TestCase):
|
||||
"""Test IntegrationConfig for LoRA Manager settings."""
|
||||
@@ -404,18 +356,6 @@ class TestConfigPathOverride(unittest.TestCase):
|
||||
os.environ[self.ENV] = custom
|
||||
self.assertEqual(PromptManagerConfig.get_config_path(), custom)
|
||||
|
||||
def test_save_without_path_uses_env_override(self):
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
custom = os.path.join(tmpdir, "nested", "custom.json")
|
||||
os.environ[self.ENV] = custom
|
||||
PromptManagerConfig.RESULT_TIMEOUT = 42
|
||||
|
||||
PromptManagerConfig.save_to_file()
|
||||
|
||||
with open(custom) as f:
|
||||
saved = json.load(f)
|
||||
self.assertEqual(saved["web_ui"]["result_timeout"], 42)
|
||||
|
||||
def test_load_without_path_uses_env_override(self):
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
custom = os.path.join(tmpdir, "custom.json")
|
||||
@@ -503,7 +443,8 @@ class TestAutotagConfig(unittest.TestCase):
|
||||
PromptManagerConfig.update_config(
|
||||
{"autotag": {"defaults": {"suggestion_limit": 25}}}
|
||||
)
|
||||
PromptManagerConfig.save_to_file(path)
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
json.dump(PromptManagerConfig.get_config(), handle)
|
||||
self.config_class.SUGGESTION_LIMIT = 10
|
||||
PromptManagerConfig.load_from_file(path)
|
||||
self.assertEqual(self.config_class.suggestion_limit(), 25)
|
||||
|
||||
@@ -15,12 +15,11 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
@patch("prompt_manager_base.get_image_monitor")
|
||||
@patch("prompt_manager_base.get_prompt_tracker")
|
||||
@patch("prompt_manager_base.get_comfyui_integration")
|
||||
@patch("prompt_manager_base.PromptDatabase")
|
||||
class TestPromptManagerTextEmptyInput(unittest.TestCase):
|
||||
"""Test PromptManagerText with empty/blank text inputs (issue #123)."""
|
||||
|
||||
def _make_node(self, mock_db_class, mock_integration, mock_tracker, mock_monitor):
|
||||
def _make_node(self, mock_db_class, mock_tracker, mock_monitor):
|
||||
mock_db = Mock()
|
||||
mock_db_class.return_value = mock_db
|
||||
mock_db.save_prompt.return_value = 1
|
||||
@@ -30,73 +29,64 @@ class TestPromptManagerTextEmptyInput(unittest.TestCase):
|
||||
|
||||
return PromptManagerText()
|
||||
|
||||
def test_empty_string(self, mock_db, mock_integ, mock_tracker, mock_monitor):
|
||||
def test_empty_string(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""Empty string should not raise UnboundLocalError."""
|
||||
node = self._make_node(mock_db, mock_integ, mock_tracker, mock_monitor)
|
||||
node = self._make_node(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.process_text(text="")
|
||||
self.assertIsInstance(result, tuple)
|
||||
self.assertEqual(result[0], "")
|
||||
|
||||
def test_whitespace_only(self, mock_db, mock_integ, mock_tracker, mock_monitor):
|
||||
def test_whitespace_only(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""Whitespace-only string should not raise UnboundLocalError."""
|
||||
node = self._make_node(mock_db, mock_integ, mock_tracker, mock_monitor)
|
||||
node = self._make_node(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.process_text(text=" ")
|
||||
self.assertIsInstance(result, tuple)
|
||||
|
||||
def test_none_coerced_empty(self, mock_db, mock_integ, mock_tracker, mock_monitor):
|
||||
def test_none_coerced_empty(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""Falsy text value should not raise UnboundLocalError."""
|
||||
node = self._make_node(mock_db, mock_integ, mock_tracker, mock_monitor)
|
||||
node = self._make_node(mock_db, mock_tracker, mock_monitor)
|
||||
# ComfyUI may pass empty string for unconnected inputs
|
||||
result = node.process_text(text="", category="", tags="")
|
||||
self.assertIsInstance(result, tuple)
|
||||
|
||||
def test_empty_text_with_prepend_append(
|
||||
self, mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
):
|
||||
def test_empty_text_with_prepend_append(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""Empty main text with prepend/append should produce single space, not
|
||||
double."""
|
||||
node = self._make_node(mock_db, mock_integ, mock_tracker, mock_monitor)
|
||||
node = self._make_node(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.process_text(text="", prepend_text="before", append_text="after")
|
||||
self.assertIsInstance(result, tuple)
|
||||
self.assertEqual(result[0], "before after")
|
||||
self.assertNotIn(" ", result[0])
|
||||
|
||||
def test_valid_text_still_works(
|
||||
self, mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
):
|
||||
def test_valid_text_still_works(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""Normal text input should continue to work correctly."""
|
||||
node = self._make_node(mock_db, mock_integ, mock_tracker, mock_monitor)
|
||||
node = self._make_node(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.process_text(text="a beautiful sunset")
|
||||
self.assertIsInstance(result, tuple)
|
||||
self.assertEqual(result[0], "a beautiful sunset")
|
||||
|
||||
def test_prepend_text_append_all_present(
|
||||
self, mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
):
|
||||
def test_prepend_text_append_all_present(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""All three parts should combine with single spaces."""
|
||||
node = self._make_node(mock_db, mock_integ, mock_tracker, mock_monitor)
|
||||
node = self._make_node(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.process_text(
|
||||
text="main prompt", prepend_text="before", append_text="after"
|
||||
)
|
||||
self.assertEqual(result[0], "before main prompt after")
|
||||
|
||||
def test_only_prepend(self, mock_db, mock_integ, mock_tracker, mock_monitor):
|
||||
def test_only_prepend(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""Prepend with empty text should output just prepend."""
|
||||
node = self._make_node(mock_db, mock_integ, mock_tracker, mock_monitor)
|
||||
node = self._make_node(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.process_text(text="", prepend_text="before")
|
||||
self.assertEqual(result[0], "before")
|
||||
|
||||
|
||||
@patch("prompt_manager_base.get_image_monitor")
|
||||
@patch("prompt_manager_base.get_prompt_tracker")
|
||||
@patch("prompt_manager_base.get_comfyui_integration")
|
||||
@patch("prompt_manager_base.PromptDatabase")
|
||||
class TestPromptManagerEmptyInput(unittest.TestCase):
|
||||
"""Test PromptManager (CLIP variant) with empty/blank text inputs (issue #123)."""
|
||||
|
||||
def _make_node_and_clip(
|
||||
self, mock_db_class, mock_integration, mock_tracker, mock_monitor
|
||||
):
|
||||
def _make_node_and_clip(self, mock_db_class, mock_tracker, mock_monitor):
|
||||
mock_db = Mock()
|
||||
mock_db_class.return_value = mock_db
|
||||
mock_db.save_prompt.return_value = 1
|
||||
@@ -110,30 +100,22 @@ class TestPromptManagerEmptyInput(unittest.TestCase):
|
||||
|
||||
return PromptManager(), mock_clip
|
||||
|
||||
def test_empty_string(self, mock_db, mock_integ, mock_tracker, mock_monitor):
|
||||
def test_empty_string(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""Empty string should not raise UnboundLocalError."""
|
||||
node, clip = self._make_node_and_clip(
|
||||
mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
)
|
||||
node, clip = self._make_node_and_clip(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.encode_prompt(clip=clip, text="")
|
||||
self.assertIsInstance(result, tuple)
|
||||
|
||||
def test_whitespace_only(self, mock_db, mock_integ, mock_tracker, mock_monitor):
|
||||
def test_whitespace_only(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""Whitespace-only string should not raise UnboundLocalError."""
|
||||
node, clip = self._make_node_and_clip(
|
||||
mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
)
|
||||
node, clip = self._make_node_and_clip(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.encode_prompt(clip=clip, text=" ")
|
||||
self.assertIsInstance(result, tuple)
|
||||
|
||||
def test_empty_text_with_prepend_append(
|
||||
self, mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
):
|
||||
def test_empty_text_with_prepend_append(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""Empty main text with prepend/append should produce single space, not
|
||||
double."""
|
||||
node, clip = self._make_node_and_clip(
|
||||
mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
)
|
||||
node, clip = self._make_node_and_clip(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.encode_prompt(
|
||||
clip=clip, text="", prepend_text="before", append_text="after"
|
||||
)
|
||||
@@ -141,24 +123,16 @@ class TestPromptManagerEmptyInput(unittest.TestCase):
|
||||
self.assertEqual(result[1], "before after")
|
||||
self.assertNotIn(" ", result[1])
|
||||
|
||||
def test_valid_text_still_works(
|
||||
self, mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
):
|
||||
def test_valid_text_still_works(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""Normal text input should continue to work correctly."""
|
||||
node, clip = self._make_node_and_clip(
|
||||
mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
)
|
||||
node, clip = self._make_node_and_clip(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.encode_prompt(clip=clip, text="a beautiful sunset")
|
||||
self.assertIsInstance(result, tuple)
|
||||
self.assertEqual(result[1], "a beautiful sunset")
|
||||
|
||||
def test_prepend_text_append_all_present(
|
||||
self, mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
):
|
||||
def test_prepend_text_append_all_present(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""All three parts should combine with single spaces."""
|
||||
node, clip = self._make_node_and_clip(
|
||||
mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
)
|
||||
node, clip = self._make_node_and_clip(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.encode_prompt(
|
||||
clip=clip, text="main prompt", prepend_text="before", append_text="after"
|
||||
)
|
||||
@@ -167,7 +141,6 @@ class TestPromptManagerEmptyInput(unittest.TestCase):
|
||||
|
||||
@patch("prompt_manager_base.get_image_monitor")
|
||||
@patch("prompt_manager_base.get_prompt_tracker")
|
||||
@patch("prompt_manager_base.get_comfyui_integration")
|
||||
@patch("prompt_manager_base.PromptDatabase")
|
||||
class TestConnectedTextInput(unittest.TestCase):
|
||||
"""Test that externally connected text is preserved in output (issue #123).
|
||||
@@ -177,7 +150,7 @@ class TestConnectedTextInput(unittest.TestCase):
|
||||
value reaches Python; these tests verify Python handles it correctly.
|
||||
"""
|
||||
|
||||
def _make_text_node(self, mock_db_class, mock_integ, mock_tracker, mock_monitor):
|
||||
def _make_text_node(self, mock_db_class, mock_tracker, mock_monitor):
|
||||
mock_db = Mock()
|
||||
mock_db_class.return_value = mock_db
|
||||
mock_db.save_prompt.return_value = 1
|
||||
@@ -186,7 +159,7 @@ class TestConnectedTextInput(unittest.TestCase):
|
||||
|
||||
return PromptManagerText()
|
||||
|
||||
def _make_clip_node(self, mock_db_class, mock_integ, mock_tracker, mock_monitor):
|
||||
def _make_clip_node(self, mock_db_class, mock_tracker, mock_monitor):
|
||||
mock_db = Mock()
|
||||
mock_db_class.return_value = mock_db
|
||||
mock_db.save_prompt.return_value = 1
|
||||
@@ -199,10 +172,10 @@ class TestConnectedTextInput(unittest.TestCase):
|
||||
return PromptManager(), mock_clip
|
||||
|
||||
def test_text_node_connected_text_with_prepend_append(
|
||||
self, mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
self, mock_db, mock_tracker, mock_monitor
|
||||
):
|
||||
"""Simulates screenshot: connected text + prepend + append must all appear."""
|
||||
node = self._make_text_node(mock_db, mock_integ, mock_tracker, mock_monitor)
|
||||
node = self._make_text_node(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.process_text(
|
||||
text="This is the prompt",
|
||||
prepend_text="This is prepend text",
|
||||
@@ -213,21 +186,17 @@ class TestConnectedTextInput(unittest.TestCase):
|
||||
"This is prepend text This is the prompt This is append text",
|
||||
)
|
||||
|
||||
def test_text_node_connected_text_only(
|
||||
self, mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
):
|
||||
def test_text_node_connected_text_only(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""Connected text without prepend/append passes through unchanged."""
|
||||
node = self._make_text_node(mock_db, mock_integ, mock_tracker, mock_monitor)
|
||||
node = self._make_text_node(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.process_text(text="This is the prompt")
|
||||
self.assertEqual(result[0], "This is the prompt")
|
||||
|
||||
def test_clip_node_connected_text_with_prepend_append(
|
||||
self, mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
self, mock_db, mock_tracker, mock_monitor
|
||||
):
|
||||
"""Same scenario for PromptManager (CLIP variant)."""
|
||||
node, clip = self._make_clip_node(
|
||||
mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
)
|
||||
node, clip = self._make_clip_node(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.encode_prompt(
|
||||
clip=clip,
|
||||
text="This is the prompt",
|
||||
@@ -239,13 +208,9 @@ class TestConnectedTextInput(unittest.TestCase):
|
||||
"This is prepend text This is the prompt This is append text",
|
||||
)
|
||||
|
||||
def test_clip_node_connected_text_only(
|
||||
self, mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
):
|
||||
def test_clip_node_connected_text_only(self, mock_db, mock_tracker, mock_monitor):
|
||||
"""Connected text without prepend/append passes through unchanged."""
|
||||
node, clip = self._make_clip_node(
|
||||
mock_db, mock_integ, mock_tracker, mock_monitor
|
||||
)
|
||||
node, clip = self._make_clip_node(mock_db, mock_tracker, mock_monitor)
|
||||
result = node.encode_prompt(clip=clip, text="This is the prompt")
|
||||
self.assertEqual(result[1], "This is the prompt")
|
||||
|
||||
|
||||
@@ -324,7 +324,6 @@ class CaptureTests(unittest.TestCase):
|
||||
node.db.save_prompt_pair.side_effect = RuntimeError("offline")
|
||||
node.logger = logging.getLogger("test.capture.nodes")
|
||||
node.prompt_tracker = Mock()
|
||||
node.comfyui_integration = Mock()
|
||||
node._inject_lora_trigger_words = lambda text: text + " TRIGGER"
|
||||
clip = Mock()
|
||||
clip.tokenize.side_effect = lambda text: text
|
||||
|
||||
@@ -24,7 +24,6 @@ class TestFocusedNode(unittest.TestCase):
|
||||
def test_focused_encodes_composition_and_tracks_main_text_and_graph(self):
|
||||
node = PromptManagerFocused.__new__(PromptManagerFocused)
|
||||
node.logger = logging.getLogger("test.focused")
|
||||
node.comfyui_integration = mock.Mock()
|
||||
node._inject_lora_trigger_words = lambda text: text
|
||||
node._track_prompt_execution = mock.Mock(return_value=42)
|
||||
clip = mock.Mock()
|
||||
|
||||
+1
-29
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
Tests for hashing utilities.
|
||||
|
||||
Tests is_duplicate_prompt and generate_prompt_hash, which are
|
||||
Tests and generate_prompt_hash, which are
|
||||
currently untested. generate_prompt_hash is covered in test_basic.py
|
||||
but we add edge cases here.
|
||||
"""
|
||||
@@ -15,7 +15,6 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from tests.background_stops import stop_tracker # noqa: E402
|
||||
from utils.hashing import (
|
||||
generate_prompt_hash,
|
||||
is_duplicate_prompt,
|
||||
STRIPPED_CODE_POINTS,
|
||||
prompt_key,
|
||||
register_prompt_functions,
|
||||
@@ -69,33 +68,6 @@ class TestSingleHashImplementation(unittest.TestCase):
|
||||
self.assertFalse(os.path.exists(os.path.join(ROOT, "restart_gallery.py")))
|
||||
|
||||
|
||||
class TestIsDuplicatePrompt(unittest.TestCase):
|
||||
"""Test is_duplicate_prompt function."""
|
||||
|
||||
def test_identical_texts_are_duplicates(self):
|
||||
self.assertTrue(is_duplicate_prompt("hello", "hello"))
|
||||
|
||||
def test_case_insensitive(self):
|
||||
self.assertTrue(is_duplicate_prompt("Hello World", "hello world"))
|
||||
|
||||
def test_whitespace_insensitive(self):
|
||||
self.assertTrue(is_duplicate_prompt(" hello ", "hello"))
|
||||
|
||||
def test_different_texts_not_duplicates(self):
|
||||
self.assertFalse(is_duplicate_prompt("text A", "text B"))
|
||||
|
||||
def test_threshold_parameter_accepted(self):
|
||||
# threshold is unused but should not cause errors
|
||||
self.assertTrue(is_duplicate_prompt("same", "same", threshold=0.5))
|
||||
|
||||
def test_empty_strings_are_duplicates(self):
|
||||
self.assertTrue(is_duplicate_prompt("", ""))
|
||||
|
||||
def test_unicode_comparison(self):
|
||||
self.assertTrue(is_duplicate_prompt("日本語", "日本語"))
|
||||
self.assertFalse(is_duplicate_prompt("日本語", "中文"))
|
||||
|
||||
|
||||
class TestGeneratePromptHashEdgeCases(unittest.TestCase):
|
||||
"""Additional edge cases for generate_prompt_hash."""
|
||||
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
"""Delete selected images: the review and the apply job (#480).
|
||||
|
||||
``POST /prompt_manager/images/delete/preview`` reviews both modes;
|
||||
``POST /prompt_manager/images/delete/preview`` reviews all three modes;
|
||||
``POST /prompt_manager/maintenance/apply {token, mode}`` removes the files'
|
||||
records (library mode, with a removal mark) or moves the files to the trash
|
||||
first (trash mode, the fake trash here). No path unlinks a media file.
|
||||
records (library mode, with a removal mark), moves the files to the trash
|
||||
first (trash mode, the fake trash here), or unlinks the files from disk
|
||||
(permanent mode, Linux/BSD only).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import errno
|
||||
import os
|
||||
import sys
|
||||
import sqlite3
|
||||
@@ -407,3 +409,89 @@ class TestNativeBackend(ImageDeleteTestCase):
|
||||
self.assertTrue((self.output_dir / "a.png").exists())
|
||||
self.assertEqual(self.count("SELECT COUNT(*) FROM generated_images"), 0)
|
||||
self.assertEqual(await self.listed(), [])
|
||||
|
||||
|
||||
class TestPermanentMode(ImageDeleteTestCase):
|
||||
"""Permanent delete: files are unlinked from disk (Linux/BSD only)."""
|
||||
|
||||
async def test_permanent_delete_supported_flag_and_plan_counts(self):
|
||||
from utils import trash
|
||||
|
||||
fake_trash.uninstall()
|
||||
self.addCleanup(fake_trash.uninstall)
|
||||
self.write("a.png", b"aaa", mtime=1_000_000)
|
||||
plan = await self.review(["a.png"])
|
||||
permanent_supported = isinstance(trash.BACKEND, trash.FreedesktopBackend)
|
||||
self.assertEqual(plan.get("permanent_delete_supported"), permanent_supported)
|
||||
if permanent_supported:
|
||||
self.assertEqual(plan["permanent"], {"count": 1})
|
||||
else:
|
||||
self.assertFalse(plan.get("permanent_delete_supported"))
|
||||
|
||||
async def test_permanent_is_refused_where_the_review_does_not_offer_it(self):
|
||||
"""#644: without the Freedesktop backend the apply answers 400 for
|
||||
"permanent" before any backup, and the file and its records stay."""
|
||||
from utils import trash
|
||||
|
||||
fake_trash.uninstall()
|
||||
self.addCleanup(fake_trash.uninstall)
|
||||
self.write("a.png", b"aaa", mtime=1_000_000)
|
||||
self.link("a.png")
|
||||
with patch.object(trash, "BACKEND", trash.UnavailableBackend()):
|
||||
plan = await self.review(["a.png"])
|
||||
self.assertFalse(plan["permanent_delete_supported"])
|
||||
with patch("os.remove") as remove:
|
||||
body = await self.post(
|
||||
APPLY, {"token": plan["token"], "mode": "permanent"}, 400
|
||||
)
|
||||
remove.assert_not_called()
|
||||
self.assertIn("Linux", body["error"])
|
||||
self.assertTrue((self.output_dir / "a.png").exists())
|
||||
self.assertEqual(self.count("SELECT COUNT(*) FROM generated_images"), 1)
|
||||
|
||||
async def test_permanent_delete_removes_the_file(self):
|
||||
fake_trash.uninstall()
|
||||
self.addCleanup(fake_trash.uninstall)
|
||||
if not image_delete.permanent_delete_supported():
|
||||
self.skipTest("permanent delete is Linux/BSD only")
|
||||
self.write("a.png", b"aaa", mtime=1_000_000)
|
||||
self.link("a.png")
|
||||
_plan, job = await self.delete(["a.png"], "permanent")
|
||||
self.assertEqual(job.state, "finished", job.summary())
|
||||
self.assertFalse((self.output_dir / "a.png").exists())
|
||||
self.assertEqual(self.count("SELECT COUNT(*) FROM generated_images"), 0)
|
||||
self.assertEqual(self.api.db.removal_marks(), {})
|
||||
self.assertEqual(job.counters["deleted"], 1)
|
||||
self.assertTrue(
|
||||
any(
|
||||
"Permanently deleted 1 of 1 images from disk" in line
|
||||
for line in job.log
|
||||
)
|
||||
)
|
||||
|
||||
async def test_a_refused_os_remove_leaves_the_file(self):
|
||||
from utils import trash
|
||||
|
||||
fake_trash.uninstall()
|
||||
self.addCleanup(fake_trash.uninstall)
|
||||
if not image_delete.permanent_delete_supported():
|
||||
self.skipTest("permanent delete is Linux/BSD only")
|
||||
self.write("a.png", b"aaa", mtime=1_000_000)
|
||||
self.link("a.png")
|
||||
plan = await self.review(["a.png"])
|
||||
with patch.object(self.api, "_backup_promised", return_value=False):
|
||||
with patch(
|
||||
"os.remove", side_effect=OSError(errno.EACCES, "Permission denied")
|
||||
):
|
||||
body = await self.post(
|
||||
APPLY, {"token": plan["token"], "mode": "permanent"}, 202
|
||||
)
|
||||
job = self.api._jobs.get(body["job"]["id"])
|
||||
await asyncio.wait_for(asyncio.shield(job.task), DISK_BOUND_SECONDS)
|
||||
self.assertTrue((self.output_dir / "a.png").exists())
|
||||
self.assertEqual(self.count("SELECT COUNT(*) FROM generated_images"), 1)
|
||||
self.assertEqual(job.counters["not_changed"], 1)
|
||||
self.assertEqual(
|
||||
self.details(job, "not_changed"),
|
||||
[image_delete.REASONS[trash.NO_PERMISSION]],
|
||||
)
|
||||
|
||||
@@ -21,7 +21,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
# Mock ComfyUI server before importing anything that touches config. Only the
|
||||
# first test module to run installs the stub; nothing else in sys.modules is
|
||||
# replaced, so later modules (test_comfyui_integration) see the real package.
|
||||
# replaced, so later modules see the real package.
|
||||
_mock_server = MagicMock()
|
||||
_mock_server.PromptServer.instance.routes = MagicMock()
|
||||
sys.modules.setdefault("server", _mock_server)
|
||||
@@ -881,17 +881,6 @@ class TestOutputListener(unittest.TestCase):
|
||||
self.assertTrue(monitor.stop_monitoring())
|
||||
|
||||
|
||||
class TestModuleIsolation(unittest.TestCase):
|
||||
"""This module must not leave mocks behind for later test modules."""
|
||||
|
||||
def test_comfyui_integration_is_not_replaced_by_a_mock(self):
|
||||
module = sys.modules.get("utils.comfyui_integration")
|
||||
self.assertFalse(
|
||||
isinstance(module, MagicMock),
|
||||
"utils.comfyui_integration was replaced by a MagicMock in sys.modules",
|
||||
)
|
||||
|
||||
|
||||
class TestMonitorThreadSafety(unittest.TestCase):
|
||||
"""Singleton creation must be thread-safe."""
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user