Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d509c885e | ||
|
|
96ce361b82 | ||
|
|
9d058a0035 | ||
|
|
4aa71c4026 | ||
|
|
a695457cce | ||
|
|
c9d2b9c66b | ||
|
|
98ba01d670 | ||
|
|
6c19f0a228 | ||
|
|
a387643946 | ||
|
|
1a177e39a2 | ||
|
|
faac2d6f52 | ||
|
|
2bf3e5202d | ||
|
|
71b55bc630 | ||
|
|
4c9cb7f5ea |
@@ -19,3 +19,4 @@
|
||||
/.flake8
|
||||
/.pre-commit-config.yaml
|
||||
/.gitignore
|
||||
/.gitattributes
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Pinned files are compared byte for byte with their recorded hashes
|
||||
# (npm run --prefix tools/vendor check). Git must never convert their line
|
||||
# endings, which Git for Windows does by default (core.autocrlf=true, #636).
|
||||
/web/lib/viewerjs/** -text
|
||||
/web/js/shared/toolkit/** -text
|
||||
/web/js/workspace/concept.css -text
|
||||
/docs/concepts/workspace/style.css -text
|
||||
@@ -0,0 +1,15 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
polar: # Replace with a single Polar username
|
||||
buy_me_a_coffee: veets
|
||||
thanks_dev: # Replace with a single thanks.dev username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
@@ -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.**
|
||||
@@ -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.
|
||||
|
||||

|
||||
|
||||
@@ -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.
|
||||
|
||||
+47
-1
@@ -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
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 42 KiB |
@@ -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)
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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:
|
||||
|
||||
+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":
|
||||
|
||||
+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
|
||||
|
||||
@@ -655,6 +655,17 @@ def create_app(root: Path) -> web.Application:
|
||||
shutil.copyfile(root / "output" / "shared" / "same.png", destination)
|
||||
return web.json_response({"success": True})
|
||||
|
||||
@routes.post("/__test__/add-backslash-image")
|
||||
async def add_backslash_image(request: web.Request) -> web.Response:
|
||||
"""#646: a folder whose name holds a backslash, as a Windows-style
|
||||
``filename_prefix`` makes on a POSIX server."""
|
||||
if os.sep == "\\":
|
||||
return web.json_response({"success": False}, status=409)
|
||||
destination = root / "output" / "model.safetensors\\2026-11-17" / "slash.png"
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(root / "output" / "shared" / "same.png", destination)
|
||||
return web.json_response({"success": True})
|
||||
|
||||
@routes.post("/__test__/add-local-inspect-file")
|
||||
async def add_local_inspect_file(request: web.Request) -> web.Response:
|
||||
"""Serve one committed Inspect fixture from the output folder.
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Saving System settings in a spec (#631).
|
||||
*
|
||||
* A host save commits config.json durably (fsync, then an atomic replace). On a busy CI disk that write alone can
|
||||
* take seconds, longer than the five an expect gives the status line. So a spec waits for the save's answer before
|
||||
* it reads the status (TESTING.md: wait for a response, never for time). A save kept in this browser sends nothing
|
||||
* and needs no wait.
|
||||
*/
|
||||
|
||||
export const SETTINGS_URL = '/prompt_manager/settings';
|
||||
export const LORA_ENABLE_URL = '/prompt_manager/lora/enable';
|
||||
|
||||
/** The host's answer to the next save sent to `url`. Start it before the click that saves. */
|
||||
export const hostSaveAnswer = (page, url = SETTINGS_URL) =>
|
||||
page.waitForResponse(response => response.request().method() === 'POST' && response.url().endsWith(url));
|
||||
|
||||
/** Click `button` and wait for the host's answer to the save it sends to `url`; resolves to that response. */
|
||||
export async function clickHostSave(page, button, url = SETTINGS_URL) {
|
||||
const answer = hostSaveAnswer(page, url);
|
||||
await button.click();
|
||||
return answer;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { clickHostSave, LORA_ENABLE_URL } from './settings-save.mjs';
|
||||
import { SIZES, THEMES, seedConcept, openConcept, openProduction, diffInventory, mutate } from './concept-inventory.mjs';
|
||||
|
||||
// #249 System S10 Task 28: System › Integrations (app.js renderSystem 682–684) and the LoRA import review against the
|
||||
@@ -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 }) => {
|
||||
|
||||
@@ -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([]);
|
||||
});
|
||||
|
||||
@@ -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/);
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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")
|
||||
|
||||
@@ -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",
|
||||
):
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,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]],
|
||||
)
|
||||
|
||||
@@ -1045,7 +1045,8 @@ class TestRevealRoute(ImageAPITestCase):
|
||||
for path in (
|
||||
"../outside.png",
|
||||
"sub/../../outside.png",
|
||||
"sub\\..\\..\\outside.png",
|
||||
# #646: a separator only on Windows; on POSIX one name (below).
|
||||
*(["sub\\..\\..\\outside.png"] if os.sep == "\\" else []),
|
||||
str(outside),
|
||||
"/" + outside.name,
|
||||
"C:/outside.png",
|
||||
@@ -1054,6 +1055,9 @@ class TestRevealRoute(ImageAPITestCase):
|
||||
with self.subTest(path=path):
|
||||
status, data = await self.post(self.body(path=path))
|
||||
self.assertEqual(status, 400, data)
|
||||
if os.sep == "/":
|
||||
status, data = await self.post(self.body(path="sub\\..\\..\\outside.png"))
|
||||
self.assertEqual(status, 404, data)
|
||||
self.assertEqual(self.opened, [])
|
||||
|
||||
async def test_symlink_out_of_the_root_is_refused(self):
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Pinned files keep their bytes in every clone (#636).
|
||||
|
||||
``npm run --prefix tools/vendor check`` compares the vendored Viewer.js and
|
||||
ComfyAssets Toolkit files, and the workspace's copy of the concept
|
||||
stylesheet, with recorded hashes. Git for Windows converts text files to CRLF
|
||||
on checkout by default, which changes those bytes, so ``.gitattributes`` marks
|
||||
them as never converted. This holds that for every tracked file under them.
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess # nosec B404 - fixed git arguments, no shell
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PINNED = (
|
||||
"web/lib/viewerjs",
|
||||
"web/js/shared/toolkit",
|
||||
"web/js/workspace/concept.css",
|
||||
"docs/concepts/workspace/style.css",
|
||||
)
|
||||
|
||||
|
||||
def _git(*args: str) -> str:
|
||||
# Without GIT_* variables: the pre-push hook exports GIT_DIR and
|
||||
# GIT_INDEX_FILE, which must not choose the repository read here.
|
||||
env = {
|
||||
key: value for key, value in os.environ.items() if not key.startswith("GIT_")
|
||||
}
|
||||
return subprocess.run( # nosec B603 B607 - fixed git arguments, no shell
|
||||
["git", *args], cwd=ROOT, env=env, check=True, capture_output=True, text=True
|
||||
).stdout
|
||||
|
||||
|
||||
@unittest.skipUnless(
|
||||
shutil.which("git") and (ROOT / ".git").exists(), "needs a git checkout"
|
||||
)
|
||||
class TestPinnedLineEndings(unittest.TestCase):
|
||||
def test_every_pinned_file_is_never_converted(self):
|
||||
files = _git("ls-files", "-z", "--", *PINNED).split("\0")
|
||||
files = [name for name in files if name]
|
||||
self.assertGreater(len(files), 8, files)
|
||||
report = _git("check-attr", "-z", "text", "--", *files).split("\0")
|
||||
# -z output: path, attribute, value, repeated.
|
||||
values = dict(zip(report[0::3], report[2::3]))
|
||||
for name in files:
|
||||
with self.subTest(path=name):
|
||||
self.assertEqual(values[name], "unset")
|
||||
|
||||
def test_the_repository_stores_them_with_lf(self):
|
||||
report = _git("ls-files", "--eol", "--", *PINNED).splitlines()
|
||||
self.assertTrue(report)
|
||||
for line in report:
|
||||
with self.subTest(line=line):
|
||||
self.assertNotIn("i/crlf", line)
|
||||
self.assertNotIn("i/mixed", line)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -312,6 +312,13 @@ class LoraImportAPITestCase(LoraAPITestCase):
|
||||
class LoraImportRouteTests(LoraImportAPITestCase):
|
||||
|
||||
async def test_preview_writes_nothing_and_makes_no_requests(self):
|
||||
# The review shows a settings file under the home folder as ~/...
|
||||
# (test_lora_manager_layout). Home is pinned beside the temp root, so
|
||||
# the full path below holds wherever TEMP is: on Windows it sits
|
||||
# under the profile (#636).
|
||||
home = patch.object(Path, "home", return_value=self.tmp_root / "home")
|
||||
home.start()
|
||||
self.addCleanup(home.stop)
|
||||
self._two_loras()
|
||||
(self.loras / "broken.metadata.json").write_text("{{{")
|
||||
db_path = self.api.db.model.db_path
|
||||
|
||||
@@ -135,6 +135,18 @@ class CaptureStoreTestCase(unittest.TestCase):
|
||||
|
||||
# -- exact bytes and identity -------------------------------------------
|
||||
|
||||
@unittest.skipIf(os.sep == "\\", "a backslash cannot be in a Windows name")
|
||||
def test_a_backslash_inside_a_name_is_captured_on_posix(self):
|
||||
# #646: a Windows-style filename_prefix makes such a folder on POSIX.
|
||||
data = png_bytes(2, 2, b"backslash")
|
||||
self.write("m.safetensors\\2026-11-17/a.png", data)
|
||||
store = self.make_store()
|
||||
cap = self.capture(store, "m.safetensors\\2026-11-17/a.png")
|
||||
try:
|
||||
self.assertEqual(Path(cap.path).read_bytes(), data)
|
||||
finally:
|
||||
store.release(cap.token)
|
||||
|
||||
def test_capture_hashes_and_copies_exact_bytes_owner_only(self):
|
||||
source_bytes = png_bytes(3, 2, os.urandom(40))
|
||||
source = self.write("a.png", source_bytes)
|
||||
@@ -212,7 +224,8 @@ class CaptureStoreTestCase(unittest.TestCase):
|
||||
"",
|
||||
"/a.png",
|
||||
"C:/a.png",
|
||||
"a\\b.png",
|
||||
# #646: a backslash separates folders only on Windows.
|
||||
*(["a\\b.png"] if os.sep == "\\" else []),
|
||||
"a\x00.png",
|
||||
"notes.txt",
|
||||
"folder",
|
||||
|
||||
@@ -39,3 +39,41 @@ class TrashFolderNameTests(unittest.TestCase):
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
class ServerSeparatorTests(unittest.TestCase):
|
||||
"""#646: ``\\`` separates names only on Windows; on POSIX it is part of one."""
|
||||
|
||||
def test_posix_keeps_a_backslash_inside_one_name(self):
|
||||
import posixpath
|
||||
|
||||
from utils.media_folders import path_separators, split_relative
|
||||
|
||||
self.assertEqual(path_separators(posixpath), "/")
|
||||
self.assertEqual(
|
||||
split_relative("m.safetensors\\2026-11-17/x.png", posixpath),
|
||||
["m.safetensors\\2026-11-17", "x.png"],
|
||||
)
|
||||
self.assertEqual(split_relative("a\\..\\b", posixpath), ["a\\..\\b"])
|
||||
|
||||
def test_windows_splits_on_both(self):
|
||||
import ntpath
|
||||
|
||||
from utils.media_folders import path_separators, split_relative
|
||||
|
||||
self.assertEqual(path_separators(ntpath), "/\\")
|
||||
self.assertEqual(
|
||||
split_relative("m.safetensors\\2026-11-17/x.png", ntpath),
|
||||
["m.safetensors", "2026-11-17", "x.png"],
|
||||
)
|
||||
self.assertEqual(split_relative("a\\..\\b", ntpath), ["a", "..", "b"])
|
||||
|
||||
def test_trash_detection_follows_the_server_separators(self):
|
||||
import ntpath
|
||||
import posixpath
|
||||
|
||||
from utils.media_folders import in_trash_folder
|
||||
|
||||
self.assertTrue(in_trash_folder(".Trash-1000\\x.png", ntpath))
|
||||
self.assertFalse(in_trash_folder(".Trash-1000\\x.png", posixpath))
|
||||
self.assertTrue(in_trash_folder("a/.Trash-1000/x.png", posixpath))
|
||||
|
||||
@@ -22,6 +22,7 @@ DEVELOPMENT = (
|
||||
"images/x.png",
|
||||
"TESTING.md",
|
||||
"requirements-dev.txt",
|
||||
".gitattributes",
|
||||
)
|
||||
KEPT = (
|
||||
"__init__.py",
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""A backslash inside a file or folder name on a POSIX server (#646).
|
||||
|
||||
A Windows-style ``filename_prefix`` (``model\\2026-11-17/name``) makes, on
|
||||
Linux or macOS, one folder whose name holds a backslash. The listing names it;
|
||||
every route that takes a listing path accepts it there, and keeps refusing it
|
||||
on Windows, where a backslash separates folders.
|
||||
"""
|
||||
|
||||
import ntpath
|
||||
import os
|
||||
import posixpath
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
try:
|
||||
from tests.test_image_delete_routes import ImageDeleteTestCase
|
||||
except ImportError: # discovered with tests/ as the top-level directory
|
||||
from test_image_delete_routes import ImageDeleteTestCase
|
||||
|
||||
from py.api import images, media_target as media_target_module
|
||||
from py.api.media_target import media_target
|
||||
from utils.media_folders import split_relative
|
||||
|
||||
POSIX_ONLY = unittest.skipIf(os.sep == "\\", "a backslash cannot be in a Windows name")
|
||||
FOLDER = "model.safetensors\\2026-11-17"
|
||||
NAME = f"{FOLDER}/a.png"
|
||||
SCOPE = "a" * 64
|
||||
|
||||
|
||||
class TestTargetsOnEitherServer(unittest.TestCase):
|
||||
"""``media_target`` follows the server's separators; patched to try both."""
|
||||
|
||||
def check(self, separators, path):
|
||||
pathmod = ntpath if "\\" in separators else posixpath
|
||||
with (
|
||||
patch.object(media_target_module, "path_separators", lambda: separators),
|
||||
patch.object(images, "path_separators", lambda: separators),
|
||||
patch.object(
|
||||
images, "split_relative", lambda text: split_relative(text, pathmod)
|
||||
),
|
||||
):
|
||||
return media_target({"root_index": 0, "root_scope": SCOPE, "path": path})
|
||||
|
||||
def test_posix_accepts_a_backslash_inside_a_name(self):
|
||||
for path in (NAME, "a\\..\\b.png", "a\\b.png"):
|
||||
with self.subTest(path=path):
|
||||
target, error = self.check("/", path)
|
||||
self.assertIsNone(error)
|
||||
self.assertEqual(target, (0, SCOPE, path))
|
||||
|
||||
def test_posix_still_refuses_traversal_and_absolute_paths(self):
|
||||
for path in ("../a.png", "a/../b.png", "/a.png", "a//b.png", "./a.png"):
|
||||
with self.subTest(path=path):
|
||||
self.assertIsNotNone(self.check("/", path)[1])
|
||||
|
||||
def test_windows_refuses_every_backslash(self):
|
||||
for path in (NAME, "a\\..\\b.png", "\\a.png", "C:\\a.png", "a\\b.png"):
|
||||
with self.subTest(path=path):
|
||||
self.assertIsNotNone(self.check("/\\", path)[1])
|
||||
|
||||
def test_traversal_check_splits_at_the_server_separators(self):
|
||||
self.assertEqual(split_relative("a\\..\\b", posixpath), ["a\\..\\b"])
|
||||
self.assertIn("..", split_relative("a\\..\\b", ntpath))
|
||||
if os.sep == "/":
|
||||
self.assertFalse(images._has_traversal("a\\..\\b.png"))
|
||||
self.assertFalse(images._has_traversal(NAME))
|
||||
self.assertTrue(images._has_traversal("a/../b.png"))
|
||||
self.assertTrue(images._has_traversal("/a.png"))
|
||||
|
||||
|
||||
@POSIX_ONLY
|
||||
class TestPosixRoutes(ImageDeleteTestCase):
|
||||
async def page(self, **params):
|
||||
response = await self.client.get(
|
||||
"/prompt_manager/images/output", params={"mode": "workspace", **params}
|
||||
)
|
||||
self.assertEqual(response.status, 200)
|
||||
return {image["path"]: image for image in (await response.json())["images"]}
|
||||
|
||||
async def test_the_listing_marks_only_a_path_with_a_backslash(self):
|
||||
self.write(NAME, b"aaa")
|
||||
self.write("plain/b.png", b"bbb")
|
||||
listed = await self.page()
|
||||
self.assertEqual(listed[NAME]["path_style"], "posix")
|
||||
self.assertNotIn("path_style", listed["plain/b.png"])
|
||||
|
||||
async def test_the_folder_filter_names_the_folder_with_its_backslash(self):
|
||||
self.write(NAME, b"aaa")
|
||||
self.write("model.safetensors/2026-11-17/b.png", b"bbb")
|
||||
self.assertEqual(list(await self.page(subfolder=FOLDER)), [NAME])
|
||||
self.assertEqual(
|
||||
list(await self.page(subfolder="model.safetensors/2026-11-17")),
|
||||
["model.safetensors/2026-11-17/b.png"],
|
||||
)
|
||||
self.assertEqual(list(await self.page(path=NAME)), [NAME])
|
||||
|
||||
async def test_a_favorite_lands_on_the_file_it_names(self):
|
||||
self.write(NAME, b"aaa")
|
||||
self.write("model.safetensors/2026-11-17/a.png", b"bbb")
|
||||
response = await self.client.put(
|
||||
"/prompt_manager/images/favorite",
|
||||
json={"root_index": 0, "path": NAME, "favorite": True},
|
||||
)
|
||||
self.assertEqual(response.status, 200, await response.text())
|
||||
listed = await self.page()
|
||||
self.assertTrue(listed[NAME]["favorite"])
|
||||
self.assertFalse(listed["model.safetensors/2026-11-17/a.png"]["favorite"])
|
||||
|
||||
async def test_a_collection_takes_the_file(self):
|
||||
self.write(NAME, b"aaa")
|
||||
response = await self.client.post(
|
||||
"/prompt_manager/collections/items",
|
||||
json={"name": "c", "items": [self.target(NAME)]},
|
||||
)
|
||||
self.assertLess(response.status, 300, await response.text())
|
||||
collections = await (
|
||||
await self.client.get("/prompt_manager/collections")
|
||||
).json()
|
||||
[collection] = [c["id"] for c in collections["collections"] if c["name"] == "c"]
|
||||
self.assertEqual(list(await self.page(collection=str(collection))), [NAME])
|
||||
|
||||
async def test_delete_moves_only_that_file_to_the_trash(self):
|
||||
self.write(NAME, b"aaa")
|
||||
twin = self.write("model.safetensors/2026-11-17/a.png", b"bbb")
|
||||
_plan, job = await self.delete([NAME], "trash")
|
||||
self.assertEqual(job.state, "finished", job.summary())
|
||||
self.assertFalse((self.output_dir / NAME).exists())
|
||||
self.assertTrue(twin.exists())
|
||||
[(source, _destination)] = self.fake.moved
|
||||
self.assertEqual(source, str(self.output_dir / NAME))
|
||||
|
||||
async def test_a_backslash_never_reaches_outside_the_root(self):
|
||||
# ``a\..\b.png`` is one name below the root on POSIX, not a way out of it.
|
||||
self.write("a\\..\\b.png", b"aaa")
|
||||
outside = self.write("b.png", b"bbb", folder=self.outside_dir)
|
||||
_plan, job = await self.delete(["a\\..\\b.png"], "trash")
|
||||
self.assertEqual(job.state, "finished", job.summary())
|
||||
self.assertTrue(outside.exists())
|
||||
self.assertFalse((self.output_dir / "a\\..\\b.png").exists())
|
||||
@@ -0,0 +1,64 @@
|
||||
"""remove_when_released waits for a dying process's files, within a bound (#636)."""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
try:
|
||||
from tests import process_cleanup
|
||||
except ImportError: # discovered with tests/ as the top-level directory
|
||||
import process_cleanup
|
||||
|
||||
|
||||
class TestRemoveWhenReleased(unittest.TestCase):
|
||||
def test_removes_the_folder(self):
|
||||
folder = tempfile.mkdtemp()
|
||||
with open(os.path.join(folder, "server.log"), "w") as handle:
|
||||
handle.write("x")
|
||||
process_cleanup.remove_when_released(folder)
|
||||
self.assertFalse(os.path.exists(folder))
|
||||
|
||||
def test_a_missing_folder_is_already_removed(self):
|
||||
folder = tempfile.mkdtemp()
|
||||
os.rmdir(folder)
|
||||
process_cleanup.remove_when_released(folder)
|
||||
|
||||
def test_retries_while_another_process_still_holds_a_file(self):
|
||||
held = PermissionError(32, "being used by another process")
|
||||
with (
|
||||
unittest.mock.patch.object(
|
||||
process_cleanup.shutil, "rmtree", side_effect=[held, held, None]
|
||||
) as rmtree,
|
||||
unittest.mock.patch.object(process_cleanup.time, "sleep") as sleep,
|
||||
):
|
||||
process_cleanup.remove_when_released("folder")
|
||||
self.assertEqual(rmtree.call_count, 3)
|
||||
self.assertEqual(sleep.call_count, 2)
|
||||
|
||||
def test_raises_the_last_error_after_the_bound(self):
|
||||
held = PermissionError(32, "being used by another process")
|
||||
clock = iter([0.0, 0.0, 5.0, 11.0])
|
||||
with (
|
||||
unittest.mock.patch.object(
|
||||
process_cleanup.shutil, "rmtree", side_effect=held
|
||||
),
|
||||
unittest.mock.patch.object(process_cleanup.time, "sleep"),
|
||||
unittest.mock.patch.object(
|
||||
process_cleanup.time, "monotonic", side_effect=lambda: next(clock)
|
||||
),
|
||||
):
|
||||
with self.assertRaises(PermissionError):
|
||||
process_cleanup.remove_when_released("folder", timeout=10)
|
||||
|
||||
def test_other_errors_are_not_retried(self):
|
||||
with unittest.mock.patch.object(
|
||||
process_cleanup.shutil, "rmtree", side_effect=OSError("disk gone")
|
||||
) as rmtree:
|
||||
with self.assertRaises(OSError):
|
||||
process_cleanup.remove_when_released("folder")
|
||||
self.assertEqual(rmtree.call_count, 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -434,7 +434,8 @@ class TestThumbnailOnFirstView(AutoThumbnailCase):
|
||||
for path in (
|
||||
"thumbnails/D:/x_thumb.webp",
|
||||
"thumbnails/D:x_thumb.webp",
|
||||
"thumbnails/\\\\server\\share/x_thumb.webp",
|
||||
# #646: a backslash re-anchors a join only on Windows.
|
||||
*(["thumbnails/\\\\server\\share/x_thumb.webp"] if os.sep == "\\" else []),
|
||||
"thumbnails//server/share/x_thumb.webp",
|
||||
"/thumbnails/x_thumb.webp",
|
||||
"thumbnails/a/./x_thumb.webp",
|
||||
@@ -451,7 +452,11 @@ class TestThumbnailOnFirstView(AutoThumbnailCase):
|
||||
):
|
||||
for path in (
|
||||
"thumbnails/D:/x_thumb.webp",
|
||||
"thumbnails/\\\\server\\share/x_thumb.webp",
|
||||
*(
|
||||
["thumbnails/\\\\server\\share/x_thumb.webp"]
|
||||
if os.sep == "\\"
|
||||
else []
|
||||
),
|
||||
"/thumbnails/x_thumb.webp",
|
||||
):
|
||||
answer = await self.api._serve_missing_thumbnail(
|
||||
|
||||
@@ -7,7 +7,9 @@ developer's machine a missing short name or symlink right is a failure.
|
||||
"""
|
||||
|
||||
import ctypes
|
||||
import ntpath
|
||||
import os
|
||||
import posixpath
|
||||
import unittest
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
@@ -300,7 +302,10 @@ class TestPredicates(unittest.TestCase):
|
||||
self.assertFalse(is_trash_folder(name), name)
|
||||
|
||||
def test_either_separator(self):
|
||||
self.assertTrue(in_trash_folder("a\\.Trash\\b.png"))
|
||||
# #646: a backslash separates only on Windows.
|
||||
self.assertTrue(in_trash_folder("a\\.Trash\\b.png", ntpath))
|
||||
self.assertFalse(in_trash_folder("a\\.Trash\\b.png", posixpath))
|
||||
self.assertTrue(in_trash_folder("a/.Trash/b.png"))
|
||||
self.assertFalse(in_trash_folder(".Trash"))
|
||||
|
||||
def test_a_path_no_root_visibly_holds_fails_closed(self):
|
||||
|
||||
@@ -50,6 +50,17 @@ class DiagnosticsTestCase(unittest.TestCase):
|
||||
os.chdir(path)
|
||||
self.addCleanup(os.chdir, previous)
|
||||
|
||||
def _chdir_without_comfyui(self):
|
||||
"""Work two levels inside the temp folder (#636).
|
||||
|
||||
The fallback looks up to two levels above the working folder for
|
||||
``output`` and ``ComfyUI/output``; from here that never leaves the
|
||||
temp folder, wherever the machine keeps it or installs ComfyUI.
|
||||
"""
|
||||
folder = os.path.join(self.tmp.name, "a", "b")
|
||||
os.makedirs(folder)
|
||||
self._chdir(folder)
|
||||
|
||||
|
||||
class TestDatabaseChecks(DiagnosticsTestCase):
|
||||
def test_missing_database_is_an_error(self):
|
||||
@@ -159,9 +170,7 @@ class TestComfyUIOutputCheck(DiagnosticsTestCase):
|
||||
)
|
||||
|
||||
def test_nothing_found_is_a_warning(self):
|
||||
empty = os.path.join(self.tmp.name, "empty")
|
||||
os.makedirs(empty)
|
||||
self._chdir(empty)
|
||||
self._chdir_without_comfyui()
|
||||
with mock.patch.dict(sys.modules, {"folder_paths": None, "py.config": None}):
|
||||
result = self.diag.check_comfyui_output()
|
||||
self.assertEqual(result["status"], "warning")
|
||||
@@ -203,7 +212,7 @@ class TestDependenciesAndFullRun(DiagnosticsTestCase):
|
||||
|
||||
def test_full_diagnostic_reports_every_category(self):
|
||||
self._populate()
|
||||
self._chdir(self.tmp.name)
|
||||
self._chdir_without_comfyui()
|
||||
with mock.patch.dict(sys.modules, {"folder_paths": None, "py.config": None}):
|
||||
results = self.diag.run_full_diagnostic()
|
||||
self.assertEqual(
|
||||
|
||||
@@ -51,7 +51,17 @@ class TestMapParallel(unittest.TestCase):
|
||||
def test_jobs_reuse_the_same_long_lived_threads(self):
|
||||
"""Arenas are reused instead of a new set of threads per job."""
|
||||
first, second = set(), set()
|
||||
map_parallel(lambda _: first.add(threading.current_thread()), range(8), 2)
|
||||
# The pool starts threads lazily: tiny tasks could all run on the first
|
||||
# thread and leave the second to start in the next job (queue run
|
||||
# 44169912829). The barrier makes the first job run on both.
|
||||
both = threading.Barrier(2)
|
||||
|
||||
def meet(_):
|
||||
first.add(threading.current_thread())
|
||||
both.wait(WAIT)
|
||||
|
||||
map_parallel(meet, range(8), 2)
|
||||
self.assertEqual(len(first), 2, first)
|
||||
map_parallel(lambda _: second.add(threading.current_thread()), range(8), 2)
|
||||
self.assertTrue(second <= first, (first, second))
|
||||
self.assertLessEqual(len(_job_threads()), 2)
|
||||
|
||||
Vendored
+104
-31
@@ -67,9 +67,16 @@ const browserJobIds = [...allJobs].filter(([, body]) => /npm run --prefix tools\
|
||||
const mergeJob = () => allJobs.get('frontend-coverage-merge');
|
||||
const verifyStep = () => steps(mergeJob()).find(step => /name: Verify every shard's raw coverage arrived/.test(step));
|
||||
|
||||
// #639: each workflow classifies the change first (tools/ci/change_class.py). Jobs that only a code
|
||||
// change can affect skip for the classes "docs" and "inert", and run when the classifier failed.
|
||||
const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const jobIf = condition => new RegExp(`^ {4}if: ${escapeRegExp(`\${{ ${condition} }}`)}$`, 'm');
|
||||
const CODE_CLASS = "needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert'";
|
||||
const CODE_ONLY_IF = jobIf(`!cancelled() && ${CODE_CLASS}`);
|
||||
// Jobs that run only in the merge queue, on main and on demand (#420): skipped on pull_request.
|
||||
const QUEUE_ONLY_IF = /^ {4}if: github\.event_name != 'pull_request'$/m;
|
||||
const QUEUE_ONLY_IF = jobIf(`!cancelled() && github.event_name != 'pull_request' && ${CODE_CLASS}`);
|
||||
const EVENTS = ['pull_request', 'merge_group', 'push', 'workflow_dispatch'];
|
||||
const CLASSES = ['code', 'docs', 'inert'];
|
||||
|
||||
function gateVariables(jobText) {
|
||||
return new Map([...jobText.matchAll(/^ {10}([A-Z_]+): \$\{\{ needs\.([\w-]+)\.result \}\}$/gm)]
|
||||
@@ -86,21 +93,36 @@ function runGate(jobText, env) {
|
||||
}
|
||||
}
|
||||
|
||||
// A gate passes only when every always-on job succeeded and every queue-only job is skipped on a
|
||||
// pull request and succeeded on every other event. Anything else fails it.
|
||||
function assertGateBehaviour(jobText, queueOnly) {
|
||||
// A gate passes only when the classifier succeeded and every job did what the change class and the
|
||||
// event ask (#639). For a code change: every always-on and code-only job succeeded, and every
|
||||
// queue-only job is skipped on a pull request and succeeded on every other event. For a docs or
|
||||
// inert change: every always-on job succeeded and every other job is skipped. Anything else fails
|
||||
// it, and so does a class the classifier does not print.
|
||||
function assertGateBehaviour(jobText, { queueOnly, codeOnly, always = [] }) {
|
||||
assert.match(jobText, /^ {10}EVENT_NAME: \$\{\{ github\.event_name \}\}$/m, 'the gate knows the event');
|
||||
assert.match(jobText, /^ {10}CHANGE_CLASS: \$\{\{ needs\.changes\.outputs\.class \}\}$/m, 'the gate knows the change class');
|
||||
const variables = gateVariables(jobText);
|
||||
for (const id of queueOnly) assert.ok(variables.has(id), `${id} reaches the gate`);
|
||||
for (const event of EVENTS) {
|
||||
const expected = id => (queueOnly.includes(id) && event === 'pull_request' ? 'skipped' : 'success');
|
||||
const green = Object.fromEntries([...variables].map(([id, name]) => [name, expected(id)]));
|
||||
assert.equal(runGate(jobText, { ...green, EVENT_NAME: event }), true, `${event}: the expected results pass`);
|
||||
for (const [id, name] of variables) {
|
||||
for (const result of ['success', 'failure', 'cancelled', 'skipped']) {
|
||||
if (result === expected(id)) continue;
|
||||
assert.equal(runGate(jobText, { ...green, EVENT_NAME: event, [name]: result }), false,
|
||||
`${event}: ${id}=${result} must fail the gate`);
|
||||
assert.deepEqual([...variables.keys()].sort(), ['changes', ...queueOnly, ...codeOnly, ...always].sort(),
|
||||
'every job the gate reads has an expected result');
|
||||
for (const changeClass of CLASSES) {
|
||||
for (const event of EVENTS) {
|
||||
const expected = id => {
|
||||
if (id === 'changes' || always.includes(id)) return 'success';
|
||||
if (changeClass !== 'code') return 'skipped';
|
||||
return queueOnly.includes(id) && event === 'pull_request' ? 'skipped' : 'success';
|
||||
};
|
||||
const where = `${changeClass} change on ${event}`;
|
||||
const green = { EVENT_NAME: event, CHANGE_CLASS: changeClass,
|
||||
...Object.fromEntries([...variables].map(([id, name]) => [name, expected(id)])) };
|
||||
assert.equal(runGate(jobText, green), true, `${where}: the expected results pass`);
|
||||
for (const [id, name] of variables) {
|
||||
for (const result of ['success', 'failure', 'cancelled', 'skipped']) {
|
||||
if (result === expected(id)) continue;
|
||||
assert.equal(runGate(jobText, { ...green, [name]: result }), false, `${where}: ${id}=${result} must fail the gate`);
|
||||
}
|
||||
}
|
||||
for (const unknown of ['', 'other', 'code ']) {
|
||||
assert.equal(runGate(jobText, { ...green, CHANGE_CLASS: unknown }), false, `${where}: class "${unknown}" must fail the gate`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,20 +135,20 @@ test('viewerjs keeps its name and needs every frontend job', () => {
|
||||
const needs = needsOf(viewerjs);
|
||||
const others = [...allJobs.keys()].filter(id => id !== 'viewerjs');
|
||||
assert.deepEqual([...needs].sort(), [...others].sort(), 'viewerjs needs every other job in the workflow');
|
||||
assert.deepEqual([...needs].sort(), ['browser-workflows', 'frontend-coverage', 'frontend-coverage-merge']);
|
||||
assert.deepEqual([...needs].sort(), ['browser-workflows', 'changes', 'frontend-coverage', 'frontend-coverage-merge']);
|
||||
assert.match(viewerjs, /^ {4}if: always\(\)$/m, 'viewerjs runs (and fails) when a needed job failed or was skipped');
|
||||
assert.deepEqual([...gateVariables(viewerjs).keys()].sort(), [...needs].sort(), 'every needed result reaches the check');
|
||||
});
|
||||
|
||||
test('viewerjs requires the browser shards everywhere but on a pull request', () => {
|
||||
assertGateBehaviour(allJobs.get('viewerjs'), ['browser-workflows']);
|
||||
test('viewerjs requires the browser shards everywhere but on a pull request, and nothing for a docs or inert change', () => {
|
||||
assertGateBehaviour(allJobs.get('viewerjs'), { queueOnly: ['browser-workflows'], codeOnly: ['frontend-coverage', 'frontend-coverage-merge'] });
|
||||
});
|
||||
|
||||
test('Firefox/WebKit page workflows run only outside pull requests; coverage runs on every event', () => {
|
||||
test('Firefox/WebKit page workflows run only outside pull requests; coverage runs on every event; both for code changes only', () => {
|
||||
assert.match(allJobs.get('browser-workflows'), QUEUE_ONLY_IF);
|
||||
for (const id of ['frontend-coverage', 'frontend-coverage-merge']) {
|
||||
assert.doesNotMatch(allJobs.get(id), /^ {4}if:/m, `${id} runs on every event`);
|
||||
}
|
||||
assert.match(allJobs.get('frontend-coverage'), CODE_ONLY_IF);
|
||||
// !cancelled() replaces the implicit success() check, so the merge names the shards' success itself.
|
||||
assert.match(allJobs.get('frontend-coverage-merge'), jobIf(`!cancelled() && needs.frontend-coverage.result == 'success' && ${CODE_CLASS}`));
|
||||
});
|
||||
|
||||
test('coverage runs as four shards that each upload their raw coverage', () => {
|
||||
@@ -144,7 +166,7 @@ test('coverage runs as four shards that each upload their raw coverage', () => {
|
||||
test('merge job downloads every shard and runs the merge-only report and check', () => {
|
||||
const merge = mergeJob();
|
||||
assert.ok(merge, 'frontend-coverage-merge exists');
|
||||
assert.deepEqual(needsOf(merge), ['frontend-coverage']);
|
||||
assert.deepEqual(needsOf(merge), ['changes', 'frontend-coverage']);
|
||||
assert.match(merge, /^ {4}name: frontend coverage \(merge\)$/m);
|
||||
const download = steps(merge).find(step => /uses: actions\/download-artifact@/.test(step));
|
||||
assert.ok(download, 'merge downloads the shard artifacts');
|
||||
@@ -329,16 +351,33 @@ test('the bandit pre-commit hook fails at the severity CI enforces and passes ev
|
||||
// Event split (#420): pull requests run a fast subset, the merge queue and main run everything.
|
||||
const testJobs = () => jobs(readWorkflow('test.yml'));
|
||||
|
||||
test('the Python matrix is Linux 3.12 on a pull request and Linux 3.12-3.14 on every other event', () => {
|
||||
test('the Python matrix is Linux 3.12 on a pull request or a docs or inert change and Linux 3.12-3.14 otherwise', () => {
|
||||
const body = testJobs().get('test');
|
||||
assert.deepEqual(matrixList(body, 'os'), ['ubuntu-latest'], 'Windows never gates a merge');
|
||||
const match = /^ {8}python-version: \$\{\{ github\.event_name == 'pull_request' && fromJSON\('(\[[^\]]*\])'\) \|\| fromJSON\('(\[[^\]]*\])'\) \}\}$/m.exec(body);
|
||||
assert.ok(match, 'python-version is chosen by event');
|
||||
assert.deepEqual({ pr: JSON.parse(match[1]), other: JSON.parse(match[2]) }, { pr: ['3.12'], other: ['3.12', '3.13', '3.14'] });
|
||||
const match = /^ {8}python-version: \$\{\{ \(github\.event_name == 'pull_request' \|\| needs\.changes\.outputs\.class == 'docs' \|\| needs\.changes\.outputs\.class == 'inert'\) && fromJSON\('(\[[^\]]*\])'\) \|\| fromJSON\('(\[[^\]]*\])'\) \}\}$/m.exec(body);
|
||||
assert.ok(match, 'python-version is chosen by event and change class');
|
||||
assert.deepEqual({ small: JSON.parse(match[1]), other: JSON.parse(match[2]) }, { small: ['3.12'], other: ['3.12', '3.13', '3.14'] });
|
||||
assert.match(body, /^ {6}fail-fast: false$/m);
|
||||
assert.match(body, /^ {4}name: py\$\{\{ matrix\.python-version \}\} on \$\{\{ matrix\.os \}\}$/m);
|
||||
});
|
||||
|
||||
// #639: a skipped matrix job reports under its unexpanded name, so the required context
|
||||
// "py3.12 on ubuntu-latest" would never report. The job therefore always starts, and an inert change
|
||||
// skips its steps instead.
|
||||
test('the Python matrix always starts and skips its steps for an inert change', () => {
|
||||
const body = testJobs().get('test');
|
||||
assert.deepEqual(needsOf(body), ['changes']);
|
||||
assert.match(body, jobIf('!cancelled()'), 'it also runs, in full, when the classifier failed');
|
||||
const jobSteps = steps(body);
|
||||
const nothing = jobSteps.filter(step => /^ {8}if: needs\.changes\.outputs\.class == 'inert'$/m.test(step));
|
||||
assert.equal(nothing.length, 1, 'one step says nothing needs testing');
|
||||
assert.match(nothing[0], /^ {8}run: echo /m, 'and it only prints that');
|
||||
for (const step of jobSteps.filter(step => step !== nothing[0])) {
|
||||
assert.match(step, /^ {8}if: needs\.changes\.outputs\.class != 'inert'$/m, `every real step is skipped for an inert change: ${step.trim().split('\n')[0]}`);
|
||||
}
|
||||
assert.equal(jobSteps.length, 5);
|
||||
});
|
||||
|
||||
test('Windows runs 3.12-3.14 on main, nightly and on demand, never on a PR or in the queue', () => {
|
||||
const text = readWorkflow('portability.yml');
|
||||
const triggers = text.slice(text.indexOf('\non:'), text.indexOf('\nconcurrency:'));
|
||||
@@ -374,12 +413,14 @@ test('the portability limit is computed from three measured green main runs', ()
|
||||
assert.equal(limit, expected, 'the job uses the written limit');
|
||||
});
|
||||
|
||||
test('real ComfyUI runs only outside pull requests; the other test.yml checks run on every event', () => {
|
||||
test('real ComfyUI runs only outside pull requests; the other test.yml checks run on every event; all for code changes only', () => {
|
||||
const found = testJobs();
|
||||
assert.match(found.get('comfyui'), QUEUE_ONLY_IF);
|
||||
for (const id of ['test', 'coverage', 'lint', 'js-test']) {
|
||||
assert.doesNotMatch(found.get(id), /^ {4}if:/m, `${id} runs on every event`);
|
||||
for (const id of ['coverage', 'lint', 'js-test']) {
|
||||
assert.match(found.get(id), CODE_ONLY_IF, `${id} runs on every event for a code change`);
|
||||
}
|
||||
assert.match(found.get('perf-budget'),
|
||||
jobIf(`!cancelled() && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && ${CODE_CLASS}`));
|
||||
});
|
||||
|
||||
test('all tests needs every gating test.yml job and requires the full set outside pull requests', () => {
|
||||
@@ -391,7 +432,7 @@ test('all tests needs every gating test.yml job and requires the full set outsid
|
||||
const gating = [...found.keys()].filter(id => !['all-tests', 'perf-budget'].includes(id));
|
||||
assert.deepEqual([...needsOf(gate)].sort(), gating.sort(), 'the gate needs every job but the non-gating perf budget');
|
||||
assert.deepEqual([...gateVariables(gate).keys()].sort(), gating.sort(), 'every needed result reaches the gate');
|
||||
assertGateBehaviour(gate, ['comfyui']);
|
||||
assertGateBehaviour(gate, { queueOnly: ['comfyui'], codeOnly: ['coverage', 'lint', 'js-test'], always: ['test'] });
|
||||
});
|
||||
|
||||
test('the CI workflows run on pull_request, merge_group and push without path filters', () => {
|
||||
@@ -403,7 +444,39 @@ test('the CI workflows run on pull_request, merge_group and push without path fi
|
||||
}
|
||||
assert.doesNotMatch(text, /^ {4}paths(-ignore)?:/m, `${name} has no path filter that would leave a required check pending`);
|
||||
}
|
||||
assert.doesNotMatch(jobs(readWorkflow('code-quality.yml')).get('security'), /^ {4}if:/m, 'bandit runs on every event');
|
||||
assert.match(jobs(readWorkflow('code-quality.yml')).get('security'), CODE_ONLY_IF, 'bandit runs on every event for a code change');
|
||||
});
|
||||
|
||||
// #639: the change is classified once per workflow, before anything else, from file names alone.
|
||||
test('each gating workflow classifies the change first and every other job waits for it', () => {
|
||||
for (const name of GATING_WORKFLOWS) {
|
||||
const found = jobs(readWorkflow(name));
|
||||
assert.equal([...found.keys()][0], 'changes', `${name} starts with the classifier`);
|
||||
const changes = found.get('changes');
|
||||
assert.match(changes, /^ {4}name: change class$/m);
|
||||
assert.doesNotMatch(changes, /^ {4}(needs|if):/m, `${name}: the classifier waits for nothing and always runs`);
|
||||
assert.match(changes, /^ {6}class: \$\{\{ steps\.classify\.outputs\.class \}\}$/m);
|
||||
const [checkout, classify] = steps(changes);
|
||||
assert.match(checkout, /uses: actions\/checkout@v\d+/);
|
||||
assert.match(checkout, /^ {10}fetch-depth: 0$/m, 'the base commit must be in the clone');
|
||||
assert.match(checkout, /^ {10}filter: blob:none$/m, 'file names need no file contents');
|
||||
assert.match(checkout, /^ {10}persist-credentials: false$/m);
|
||||
assert.match(classify, /^ {8}id: classify$/m);
|
||||
assert.match(classify, /^ {10}EVENT_NAME: \$\{\{ github\.event_name \}\}$/m);
|
||||
assert.match(classify, /^ {10}BASE_SHA: \$\{\{ github\.event\.pull_request\.base\.sha \|\| github\.event\.merge_group\.base_sha \|\| github\.event\.before \}\}$/m);
|
||||
assert.match(classify, /^ {10}HEAD_SHA: \$\{\{ github\.event\.pull_request\.head\.sha \|\| github\.event\.merge_group\.head_sha \|\| github\.sha \}\}$/m);
|
||||
assert.match(classify, /^ {8}run: python3 tools\/ci\/change_class\.py \| tee -a "\$GITHUB_OUTPUT"$/m);
|
||||
for (const [id, body] of found) {
|
||||
if (id !== 'changes') assert.ok(needsOf(body).includes('changes'), `${name} job ${id} waits for the classifier`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('the pre-push hook runs the suite through the classifier', () => {
|
||||
const hook = /- id: tests\n([\s\S]*?)(?=\n {6}(?:- id:|#)|\n*$)/.exec(readRepoFile('.pre-commit-config.yaml'))?.[1];
|
||||
assert.ok(hook, 'the tests hook exists');
|
||||
assert.match(hook, /^ {8}entry: python tools\/ci\/change_class\.py --unless-inert python -m tests\.run_suite -q$/m);
|
||||
assert.match(hook, /^ {8}stages: \[pre-push\]$/m);
|
||||
});
|
||||
|
||||
test('every required check reports on a pull request and the gates carry the full matrix', () => {
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sort a change by the files it touches, so CI tests only what can break (#639).
|
||||
|
||||
Three classes, decided from allowlists:
|
||||
|
||||
- ``inert``: every file is one nothing reads at run or test time (the funding
|
||||
file, the security policy, the old README's screenshots, issue templates).
|
||||
No test job runs.
|
||||
- ``docs``: every file is inert or a document a Python test reads (the
|
||||
READMEs and their images, checked by ``tests/test_brand_assets.py`` and
|
||||
``tests/test_package_contents.py``). Only the Python 3.12 suite runs.
|
||||
- ``code``: anything else. A file on no list is code, and so is every case of
|
||||
doubt: no files, an unknown event, a range git cannot read.
|
||||
|
||||
``docs/`` is code (the browser suite compares production against
|
||||
``docs/concepts/workspace/``) and so is ``TESTING.md`` (the tooling tests read
|
||||
its tables). To add a file to a list, first check that no test and no shipped
|
||||
code opens it.
|
||||
|
||||
Usage:
|
||||
|
||||
``change_class.py``
|
||||
Prints ``class=<inert|docs|code>`` for the workflow's ``$GITHUB_OUTPUT``,
|
||||
from ``EVENT_NAME``, ``BASE_SHA`` and ``HEAD_SHA``. A pull request is
|
||||
compared with its merge base, so commits that landed on main meanwhile
|
||||
do not count; a merge group and a push are compared end to end.
|
||||
|
||||
``change_class.py --unless-inert <command...>``
|
||||
The pre-push hook: runs the command unless pre-commit's pushed range
|
||||
(``PRE_COMMIT_FROM_REF``..``PRE_COMMIT_TO_REF``) is inert, and exits
|
||||
with the command's code. The command is looked up on ``PATH`` first, so a
|
||||
bare ``npm`` finds ``npm.cmd`` on Windows, which ``subprocess`` alone
|
||||
does not do.
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import Iterable, Optional
|
||||
|
||||
INERT_FILES = frozenset({".github/FUNDING.yml", "SECURITY.md"})
|
||||
INERT_FOLDERS = ("images/", ".github/ISSUE_TEMPLATE/")
|
||||
DOCS_FILES = frozenset({"README.md", "README-legacy.md"})
|
||||
DOCS_FOLDERS = ("assets/readme/", "assets/brand/")
|
||||
|
||||
RANGE_EVENTS = frozenset({"pull_request", "merge_group", "push"})
|
||||
ENVIRONMENT = frozenset(
|
||||
{
|
||||
"EVENT_NAME",
|
||||
"BASE_SHA",
|
||||
"HEAD_SHA",
|
||||
"PRE_COMMIT_FROM_REF",
|
||||
"PRE_COMMIT_TO_REF",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def classify(paths: Iterable[str]) -> str:
|
||||
"""``inert``, ``docs`` or ``code`` for the repository paths of one change."""
|
||||
found = "code"
|
||||
for path in paths:
|
||||
if path in INERT_FILES or path.startswith(INERT_FOLDERS):
|
||||
if found == "code":
|
||||
found = "inert"
|
||||
elif path in DOCS_FILES or path.startswith(DOCS_FOLDERS):
|
||||
found = "docs"
|
||||
else:
|
||||
return "code"
|
||||
return found
|
||||
|
||||
|
||||
def changed_paths(base: str, head: str, three_dot: bool) -> Optional[list[str]]:
|
||||
"""Paths that differ between two commits, or None when git cannot say.
|
||||
|
||||
Renames are listed under both names, so a file moved onto a listed name
|
||||
still counts as the code file it was.
|
||||
"""
|
||||
if not base or not head or not base.strip("0") or not head.strip("0"):
|
||||
return None
|
||||
span = f"{base}...{head}" if three_dot else f"{base}..{head}"
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git", "diff", "--name-only", "--no-renames", "-z", span, "--"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
except OSError:
|
||||
return None
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
return [path for path in result.stdout.split("\0") if path]
|
||||
|
||||
|
||||
def class_of_range(base: str, head: str, three_dot: bool = False) -> str:
|
||||
paths = changed_paths(base, head, three_dot)
|
||||
if paths is None:
|
||||
return "code"
|
||||
for path in paths:
|
||||
print(f"changed: {path}", file=sys.stderr)
|
||||
return classify(paths)
|
||||
|
||||
|
||||
def run_command(argv: list[str]) -> int:
|
||||
"""Run ``argv`` with its program resolved through ``PATH``; its exit code."""
|
||||
if not argv:
|
||||
print("change_class: --unless-inert needs a command", file=sys.stderr)
|
||||
return 2
|
||||
program = shutil.which(argv[0])
|
||||
if program is None:
|
||||
print(f"change_class: command not found: {argv[0]}", file=sys.stderr)
|
||||
return 127
|
||||
return subprocess.run([program, *argv[1:]], check=False).returncode
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv[:1] == ["--unless-inert"]:
|
||||
found = class_of_range(
|
||||
os.environ.get("PRE_COMMIT_FROM_REF", ""),
|
||||
os.environ.get("PRE_COMMIT_TO_REF", ""),
|
||||
)
|
||||
if found == "inert":
|
||||
print("Skipped: this push only changes inert files (tools/ci).")
|
||||
return 0
|
||||
return run_command(argv[1:])
|
||||
event = os.environ.get("EVENT_NAME", "")
|
||||
found = "code"
|
||||
if event in RANGE_EVENTS:
|
||||
found = class_of_range(
|
||||
os.environ.get("BASE_SHA", ""),
|
||||
os.environ.get("HEAD_SHA", ""),
|
||||
three_dot=event == "pull_request",
|
||||
)
|
||||
print(f"class={found}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -45,7 +45,7 @@ from .foreign_runs import (
|
||||
store_foreign,
|
||||
)
|
||||
from .hashing import generate_prompt_hash
|
||||
from .media_folders import in_skipped_folder
|
||||
from .media_folders import in_skipped_folder, split_relative
|
||||
from .metadata_extractor import ComfyUIMetadataExtractor
|
||||
from .parallel import note_refusal, refused_at_shutdown
|
||||
from .logging_config import get_logger
|
||||
@@ -519,7 +519,7 @@ class ImageGenerationHandler(FileSystemEventHandler):
|
||||
]
|
||||
if holding:
|
||||
text = text[len(os.path.join(max(holding, key=len), "")) :]
|
||||
return text.replace("\\", "/").split("/")[:-1]
|
||||
return split_relative(text)[:-1]
|
||||
|
||||
def process_new_image(self, image_path: str, prompt_snapshot=None):
|
||||
"""Process a newly created image file for gallery integration.
|
||||
|
||||
@@ -659,12 +659,16 @@ def header_dimensions(path: str) -> tuple[int, int]:
|
||||
|
||||
|
||||
def _relative_parts(relative) -> tuple[list[str], str]:
|
||||
"""Split a safe relative POSIX media path; anything else is denied."""
|
||||
"""Split a safe relative POSIX media path; anything else is denied.
|
||||
|
||||
A backslash is denied on Windows, where it separates folders; on POSIX it
|
||||
is part of a name (#646), and ``_resolve`` still checks the joined path.
|
||||
"""
|
||||
if not isinstance(relative, str) or not relative:
|
||||
raise CaptureDenied("Invalid file path")
|
||||
if len(relative) > MAX_RELATIVE_LENGTH or "\x00" in relative:
|
||||
raise CaptureDenied("Invalid file path")
|
||||
if "\\" in relative or relative.startswith("/"):
|
||||
if ("\\" in relative and os.sep == "\\") or relative.startswith("/"):
|
||||
raise CaptureDenied("Invalid file path")
|
||||
parts = relative.split("/")
|
||||
for part in parts:
|
||||
|
||||
+21
-3
@@ -32,12 +32,30 @@ def is_skipped_folder(name: str) -> bool:
|
||||
return name == PREVIEW_FOLDER or is_trash_folder(name)
|
||||
|
||||
|
||||
def in_trash_folder(relative: str) -> bool:
|
||||
def path_separators(pathmod=os.path) -> str:
|
||||
"""The characters that separate names in a root-relative path on this server.
|
||||
|
||||
``/`` always; ``\\`` only on Windows, where it cannot be part of a name. On
|
||||
POSIX ``\\`` is an ordinary character (a Windows-style ``filename_prefix``
|
||||
makes such a folder, #646).
|
||||
"""
|
||||
return "/\\" if pathmod.sep == "\\" else "/"
|
||||
|
||||
|
||||
def split_relative(relative: str, pathmod=os.path) -> list[str]:
|
||||
"""*relative* split into its names at this server's separators (#646)."""
|
||||
if pathmod.sep == "\\":
|
||||
relative = relative.replace("\\", "/")
|
||||
return relative.split("/")
|
||||
|
||||
|
||||
def in_trash_folder(relative: str, pathmod=os.path) -> bool:
|
||||
"""Whether a root-relative file path lies in a trash folder (#543).
|
||||
|
||||
Takes either separator. Previews of it (``thumbnails/.Trash-1000/...``) count.
|
||||
Takes this server's separators (#646). Previews of it
|
||||
(``thumbnails/.Trash-1000/...``) count.
|
||||
"""
|
||||
folders = relative.replace("\\", "/").split("/")[:-1]
|
||||
folders = split_relative(relative, pathmod)[:-1]
|
||||
return any(is_trash_folder(part) for part in folders)
|
||||
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="lib/brand/icon-32.png">
|
||||
<link rel="apple-touch-icon" sizes="128x128" href="lib/brand/icon-128.png">
|
||||
<title>PromptManager - Admin Dashboard</title>
|
||||
<script src="js/theme-bridge.js"></script>
|
||||
<script src="js/html-escape.js"></script>
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="lib/brand/icon-32.png">
|
||||
<link rel="apple-touch-icon" sizes="128x128" href="lib/brand/icon-128.png">
|
||||
<title>PromptManager - Gallery</title>
|
||||
<script src="js/theme-bridge.js"></script>
|
||||
<script src="js/html-escape.js"></script>
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="lib/brand/icon-32.png">
|
||||
<link rel="apple-touch-icon" sizes="128x128" href="lib/brand/icon-128.png">
|
||||
<title>PromptManager - Opening the workspace</title>
|
||||
<style>
|
||||
body {
|
||||
|
||||
@@ -5,11 +5,12 @@
|
||||
* - The concept's selection bar has "Remove links…" (`danger`) opening its `maintenancePlan` review (`dl.meta-grid`
|
||||
* Scope / Protected / Backup / Media on disk, Cancel and a primary). Production names it "Delete…" and asks each
|
||||
* time (maintainer ruling): a radio group "What should happen to the files?" with nothing checked, "Remove from the
|
||||
* library only" (records go, the file stays on disk, hidden from Images) or "Also move the files to the trash".
|
||||
* - One preview (`POST /images/delete/preview`) answers both modes; choosing a mode only redraws the rows. The primary
|
||||
* library only" (records go, the file stays on disk, hidden from Images) or "Also move the files to the trash" (or,
|
||||
* on Linux/BSD servers, "Permanently delete" from disk).
|
||||
* - One preview (`POST /images/delete/preview`) answers all three modes; choosing a mode only redraws the rows. The primary
|
||||
* (`danger`) is enabled once a mode with images to act on is chosen. Apply sends `{token, mode}` to the reviewed-plan
|
||||
* apply; the job is followed in the Activity store and `onDeleted(job)` runs when it ends.
|
||||
* - Nothing here deletes a file: the server never unlinks one (it renames into the system trash or leaves it).
|
||||
* - Only the "permanent" mode unlinks a file from disk (via the apply job); library and trash modes leave the file intact.
|
||||
*/
|
||||
import { createButton } from '../shared/toolkit/core.js';
|
||||
import { closeWorkspaceDialog, openCloseOnlyReview, openContentDialog } from './workspace-dialogs.mjs';
|
||||
@@ -26,6 +27,7 @@ export const MODES = Object.freeze([
|
||||
Object.freeze({value: 'library', label: 'Remove from the library only', hint: 'Files stay on disk, hidden from Images.'}),
|
||||
Object.freeze({value: 'trash', label: 'Also move the files to the trash',
|
||||
hint: 'You can restore them from the trash until it is emptied.'}),
|
||||
Object.freeze({value: 'permanent', label: 'Permanently delete', hint: 'Files are removed from disk permanently.'}),
|
||||
]);
|
||||
export const NONE_DELETABLE = 'None of the selected images can be deleted.';
|
||||
export const REVIEW_FAILED = 'The review failed. Nothing was changed.';
|
||||
@@ -40,6 +42,7 @@ const SENTENCES = Object.freeze({
|
||||
+ 'collections and favorite cannot be recovered.',
|
||||
trash: 'A file restored from the trash shows again without its tags, category, collections or favorite; a scan '
|
||||
+ 'links it to its prompt again.',
|
||||
permanent: 'Permanently deleted files are gone from disk. Records can only be restored via the safety database backup; the files themselves cannot be recovered.',
|
||||
});
|
||||
export { SENTENCES };
|
||||
|
||||
@@ -111,7 +114,9 @@ export function deleteRows(plan, mode) {
|
||||
: 'Off: no safety backup (System › Backup & export › Recovery policy)']);
|
||||
rows.push(['Media on disk', mode === 'trash'
|
||||
? 'Files move to the trash. Nothing is deleted permanently. Disk space is freed when you empty the trash.'
|
||||
: 'Files stay on disk, hidden from Images.']);
|
||||
: mode === 'permanent'
|
||||
? 'Files are removed from disk. Disk space is freed immediately.'
|
||||
: 'Files stay on disk, hidden from Images.']);
|
||||
return rows;
|
||||
}
|
||||
|
||||
@@ -122,6 +127,7 @@ function backupOn(plan) {
|
||||
/** The `p.small` sentences for `mode`. */
|
||||
export function deleteSentences(plan, mode) {
|
||||
if (mode === 'library') return [backupOn(plan) ? SENTENCES.libraryBackup : SENTENCES.libraryNoBackup];
|
||||
if (mode === 'permanent') return [SENTENCES.permanent];
|
||||
const sentences = [SENTENCES.trash];
|
||||
const trashRefused = Number(plan?.trash_refused?.count ?? 0);
|
||||
if (trashRefused && trashRefused >= modeCount(plan, 'library')) sentences.push(NO_TRASH_HERE);
|
||||
@@ -129,14 +135,16 @@ export function deleteSentences(plan, mode) {
|
||||
return sentences;
|
||||
}
|
||||
|
||||
/** The primary's label: "Remove N images from the library" or "Move N images to the trash". */
|
||||
/** The primary's label: "Remove N images from the library", "Move N images to the trash", or "Permanently delete N from disk". */
|
||||
export function primaryLabel(mode, count) {
|
||||
return mode === 'trash' ? `Move ${countOf(count, 'image')} to the trash` : `Remove ${countOf(count, 'image')} from the library`;
|
||||
if (mode === 'trash') return `Move ${countOf(count, 'image')} to the trash`;
|
||||
if (mode === 'permanent') return `Permanently delete ${countOf(count, 'image')} from disk`;
|
||||
return `Remove ${countOf(count, 'image')} from the library`;
|
||||
}
|
||||
|
||||
/** Why the review cannot start at all, or null. */
|
||||
export function closeOnlyReason(plan) {
|
||||
if (modeCount(plan, 'library') === 0 && modeCount(plan, 'trash') === 0) return NONE_DELETABLE;
|
||||
if (modeCount(plan, 'library') === 0 && modeCount(plan, 'trash') === 0 && modeCount(plan, 'permanent') === 0) return NONE_DELETABLE;
|
||||
if (plan?.disk && plan.disk.sufficient === false) {
|
||||
return `There is not enough free space for the safety backup (needs ${number(plan.disk.required_bytes)} bytes, `
|
||||
+ `has ${number(plan.disk.free_bytes)}).`;
|
||||
@@ -159,24 +167,31 @@ export function outcomeToast(job) {
|
||||
const mode = job?.scope?.mode;
|
||||
if (job?.scope?.failure === 'backup-failed') return 'The safety backup failed; nothing was changed.';
|
||||
if (job?.scope?.failure === 'sources-changed') return 'The sources changed; nothing was changed.';
|
||||
const done = Number(mode === 'trash' ? counters.trashed : counters.removed) || 0;
|
||||
let done;
|
||||
if (mode === 'trash') done = Number(counters.trashed) || 0;
|
||||
else if (mode === 'permanent') done = Number(counters.deleted) || 0;
|
||||
else done = Number(counters.removed) || 0;
|
||||
const total = Number(job?.total ?? 0);
|
||||
if (job?.scope?.failure === 'records-failed') {
|
||||
return `Stopped after ${number(done)} of ${countOf(total, 'image')}; the rest were not changed. See Activity.`;
|
||||
}
|
||||
const head = mode === 'trash' ? `Moved ${countOf(done, 'image')} to the trash.` : `Removed ${countOf(done, 'image')} from the library.`;
|
||||
let head;
|
||||
if (mode === 'trash') head = `Moved ${countOf(done, 'image')} to the trash.`;
|
||||
else if (mode === 'permanent') head = `Permanently deleted ${countOf(done, 'image')} from disk.`;
|
||||
else head = `Removed ${countOf(done, 'image')} from the library.`;
|
||||
const unchanged = Number(counters.not_changed ?? 0);
|
||||
return unchanged ? `${head} ${number(unchanged)} ${unchanged === 1 ? 'was' : 'were'} not changed (see Activity).` : head;
|
||||
}
|
||||
|
||||
function modeGroup(onChange) {
|
||||
function modeGroup(onChange, plan) {
|
||||
const group = el('div', undefined, 'field');
|
||||
group.setAttribute('role', 'radiogroup');
|
||||
const caption = el('span', QUESTION);
|
||||
caption.id = 'image-delete-mode-label';
|
||||
group.setAttribute('aria-labelledby', caption.id);
|
||||
group.append(caption);
|
||||
for (const choice of MODES) {
|
||||
const choices = plan?.permanent_delete_supported ? MODES : MODES.filter(m => m.value !== 'permanent');
|
||||
for (const choice of choices) {
|
||||
const label = el('label');
|
||||
const input = el('input');
|
||||
Object.assign(input, {type: 'radio', name: 'image-delete-mode', value: choice.value, checked: false});
|
||||
@@ -217,7 +232,7 @@ export function showDeleteReview(plan, {scope, count, trigger = null, onApply})
|
||||
start.textContent = primaryLabel(mode, acting);
|
||||
start.setAttribute('aria-disabled', String(acting === 0));
|
||||
}
|
||||
const group = modeGroup(value => { mode = value; render(); });
|
||||
const group = modeGroup(value => { mode = value; render(); }, plan);
|
||||
cancel.addEventListener('click', () => closeWorkspaceDialog());
|
||||
// Nothing starts without an explicit mode: an aria-disabled primary ignores every activation (click, Enter, Space),
|
||||
// and a chosen one starts once however often it is pressed. The dialog has no form, so Enter elsewhere submits nothing.
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createImageStream, withItem, imageKey, countLine, captionDate, scopeLab
|
||||
import { createImageCard } from './image-card.mjs';
|
||||
import { layoutImages, visibleImages, gridMetrics, stacksCardInfo } from './image-layout.mjs';
|
||||
import { mountFileInspector } from './file-inspector.mjs';
|
||||
import { createInspectionController } from './inspection-state.mjs';
|
||||
import { createInspectionController, rootedFileAdapter } from './inspection-state.mjs';
|
||||
import { mountSelectionBar } from './images-selection.mjs';
|
||||
import { scrollToPageTop } from './sticky-chrome.mjs';
|
||||
import { createPromptSender } from './prompt-sender.mjs';
|
||||
@@ -374,6 +374,8 @@ export function mountImages(main, api, parentScope, {embedded = false, fetchPage
|
||||
}
|
||||
function previewImage(image) {
|
||||
if (!image) return;
|
||||
// #646: a file the viewer can't open (a backslash in a folder name) shows its details panel instead.
|
||||
try { rootedFileAdapter.validate(image); } catch { inspect(image); return; }
|
||||
mediaViewer.open({items:state.items,selectedKey:imageKey(image),trigger:document.activeElement});
|
||||
}
|
||||
/** The concept media card (image-card.mjs): the image opens the viewer, Info inspects (D7–D11, D19). */
|
||||
|
||||
@@ -31,9 +31,12 @@ function descriptorScope(image) {
|
||||
return image.root_scope;
|
||||
}
|
||||
|
||||
/** #646: a POSIX server marks a path whose names hold a backslash; anywhere else a backslash stays refused. */
|
||||
const backslashRefused = image => image.path.includes('\\') && image.path_style !== 'posix';
|
||||
|
||||
function validateIdentity(image) {
|
||||
if (!object(image) || !Number.isSafeInteger(image.root_index) || image.root_index < 0 ||
|
||||
typeof image.path !== 'string' || !image.path || image.path.includes('\\') || /^[a-z]:/i.test(image.path) || /[\x00-\x1f\x7f]/.test(image.path) ||
|
||||
typeof image.path !== 'string' || !image.path || backslashRefused(image) || /^[a-z]:/i.test(image.path) || /[\x00-\x1f\x7f]/.test(image.path) ||
|
||||
image.path.split('/').some(part => !part || part === '.' || part === '..')) throw new TypeError('Invalid inspection identity');
|
||||
return descriptorScope(image);
|
||||
}
|
||||
|
||||
@@ -73,6 +73,8 @@ const isDisabled = button => button.getAttribute('aria-disabled') === 'true';
|
||||
export function imageOf(item) {
|
||||
const target = item.target ?? {};
|
||||
return { filename: item.filename, root_index: target.root_index, root_scope: target.root_scope, path: target.path,
|
||||
// #646: a POSIX server's mark for a name holding a backslash, as the Images listing sends it.
|
||||
...(target.path_style === 'posix' ? { path_style: 'posix' } : {}),
|
||||
url: item.url, thumbnail_url: item.thumbnail_url ?? null, is_video: item.is_video === true,
|
||||
media_type: item.is_video ? 'video' : 'image' };
|
||||
}
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import {rootedFileAdapter} from './inspection-state.mjs';
|
||||
|
||||
/** A viewer visits only the descriptors loaded by its opening query. */
|
||||
/** One descriptor the adapter refuses is left out, so it never keeps the viewer from opening on the others (#646). */
|
||||
function openable(adapter, item) {
|
||||
try { adapter.validate(item); return true; } catch (error) { if (error instanceof TypeError) return false; throw error; }
|
||||
}
|
||||
|
||||
/** A viewer visits only the descriptors loaded by its opening query that its adapter accepts. */
|
||||
export function createViewerSession({items, initialKey, onChange = () => {}, setTimer = setTimeout, clearTimer = clearTimeout, adapter = rootedFileAdapter}) {
|
||||
if (!Array.isArray(items) || !items.length) throw new TypeError('A loaded media collection is required');
|
||||
const accepted = Array.isArray(items) ? items.filter(item => openable(adapter, item)) : [];
|
||||
if (!accepted.length) throw new TypeError('A loaded media collection is required');
|
||||
const keys = new Set();
|
||||
const loaded = Object.freeze(items.map(item => {
|
||||
adapter.validate(item);
|
||||
const loaded = Object.freeze(accepted.map(item => {
|
||||
const key = adapter.key(item);
|
||||
if (keys.has(key)) throw new TypeError('Duplicate viewer identity');
|
||||
keys.add(key);
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.4 KiB |
@@ -3,6 +3,8 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="lib/brand/icon-32.png">
|
||||
<link rel="apple-touch-icon" sizes="128x128" href="lib/brand/icon-128.png">
|
||||
<title>Image Gallery - Generation Data</title>
|
||||
<script src="js/theme-bridge.js"></script>
|
||||
<script src="js/html-escape.js"></script>
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="lib/brand/icon-32.png">
|
||||
<link rel="apple-touch-icon" sizes="128x128" href="lib/brand/icon-128.png">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>Prompt Manager · Workspace</title>
|
||||
<link rel="stylesheet" href="js/shared/toolkit/controls.css">
|
||||
|
||||
Reference in New Issue
Block a user