Compare commits

..
Author SHA1 Message Date
Vito 89ba820153 Update Buy Me a Coffee username to 'veets' 2026-11-15 06:24:40 -08:00
71 changed files with 173 additions and 1949 deletions
-1
View File
@@ -19,4 +19,3 @@
/.flake8
/.pre-commit-config.yaml
/.gitignore
/.gitattributes
-7
View File
@@ -1,7 +0,0 @@
# Pinned files are compared byte for byte with their recorded hashes
# (npm run --prefix tools/vendor check). Git must never convert their line
# endings, which Git for Windows does by default (core.autocrlf=true, #636).
/web/lib/viewerjs/** -text
/web/js/shared/toolkit/** -text
/web/js/workspace/concept.css -text
/docs/concepts/workspace/style.css -text
+1 -29
View File
@@ -17,39 +17,11 @@ 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. change class (#639): 5 min, the floor.
# 40254137380, 40240706583 took 23s / 16s / 23s -> 5 min.
timeout-minutes: 5
steps:
+8 -67
View File
@@ -35,60 +35,26 @@ 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' || needs.changes.outputs.class == 'docs' || needs.changes.outputs.class == 'inert') && fromJSON('["3.12"]') || fromJSON('["3.12", "3.13", "3.14"]') }}
python-version: ${{ github.event_name == 'pull_request' && 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 }}
@@ -96,26 +62,18 @@ 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
# 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' }}
# required context never blocks a pull request; "all tests" fails if it is skipped anywhere else.
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
# Chromium and its system libraries come from the pinned Playwright image (tag = @playwright/test in
# tools/vendor/package-lock.json; tests/vendor/browser-image.test.mjs checks it). The runner install
@@ -216,8 +174,6 @@ 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:
@@ -245,8 +201,7 @@ 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
needs: changes
if: ${{ !cancelled() && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
@@ -270,8 +225,6 @@ 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:
@@ -288,8 +241,6 @@ 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:
@@ -317,11 +268,9 @@ 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: [changes, test, comfyui, coverage, lint, js-test]
needs: [test, comfyui, coverage, lint, js-test]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
@@ -329,26 +278,18 @@ 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: |
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
queue_only=success
if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi
echo "event: $EVENT_NAME (real ComfyUI must be $queue_only; coverage, lint and js-test must be $code_only)"
echo "event: $EVENT_NAME (real ComfyUI must be $queue_only)"
echo "test matrix: $TEST_RESULT"
echo "comfyui: $COMFYUI_RESULT"
echo "coverage: $COVERAGE_RESULT"
echo "lint: $LINT_RESULT"
echo "js-test: $JS_RESULT"
test "$TEST_RESULT" = success && test "$COVERAGE_RESULT" = "$code_only" && test "$LINT_RESULT" = "$code_only" && test "$JS_RESULT" = "$code_only" && test "$COMFYUI_RESULT" = "$queue_only"
test "$TEST_RESULT" = success && test "$COVERAGE_RESULT" = success && test "$LINT_RESULT" = success && test "$JS_RESULT" = success && test "$COMFYUI_RESULT" = "$queue_only"
+7 -49
View File
@@ -45,39 +45,9 @@ 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;
@@ -147,8 +117,7 @@ jobs:
frontend-coverage-merge:
name: frontend coverage (merge)
needs: [changes, frontend-coverage]
if: ${{ !cancelled() && needs.frontend-coverage.result == 'success' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
needs: frontend-coverage
runs-on: ubuntu-latest
# Same image as the shards: the raw files name sources by the container's workspace path.
container:
@@ -217,9 +186,7 @@ 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.
# Code changes only (#639).
needs: changes
if: ${{ !cancelled() && github.event_name != 'pull_request' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
@@ -278,10 +245,9 @@ 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. 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.
# Any failure, cancellation or other skip fails it.
viewerjs:
needs: [changes, frontend-coverage, frontend-coverage-merge, browser-workflows]
needs: [frontend-coverage, frontend-coverage-merge, browser-workflows]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
@@ -289,22 +255,14 @@ 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: |
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
queue_only=success
if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi
echo "event: $EVENT_NAME (browser-workflows must be $queue_only; coverage and its merge must be $code_only)"
echo "event: $EVENT_NAME (browser-workflows must be $queue_only)"
echo "frontend-coverage: $COVERAGE_RESULT"
echo "frontend-coverage-merge: $MERGE_RESULT"
echo "browser-workflows: $WORKFLOWS_RESULT"
test "$COVERAGE_RESULT" = "$code_only" && test "$MERGE_RESULT" = "$code_only" && test "$WORKFLOWS_RESULT" = "$queue_only"
test "$COVERAGE_RESULT" = success && test "$MERGE_RESULT" = success && test "$WORKFLOWS_RESULT" = "$queue_only"
+1 -2
View File
@@ -22,10 +22,9 @@ repos:
types: [python]
exclude: ^(tests/|reference/)
# Skipped when the pushed commits only change inert files (tools/ci/change_class.py, #639).
- id: tests
name: tests
entry: python tools/ci/change_class.py --unless-inert python -m tests.run_suite -q
entry: python -m tests.run_suite -q
language: system
pass_filenames: false
stages: [pre-push]
+1 -2
View File
@@ -103,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 a Linux or BSD server you can also delete the files permanently, for headless servers where a trash only fills up the disk; those files can't be recovered. On Windows, images can only be removed from the library. A safety backup of the database is on by default, and removed images can be brought back.
Choose what happens to the files before anything is removed: remove the image from the library and leave the file on disk, or on Linux and macOS also move it to the system trash. On Windows, images can only be removed from the library. A safety backup of the database is on by default, and removed images can be brought back.
![Delete dialog offering to remove from the library only or move files to the trash](assets/readme/delete-review.webp)
@@ -230,7 +230,6 @@ The documentation for those pages is in [README-legacy.md](README-legacy.md).
## Known limits
- **Trash is Linux and macOS only.** Windows has no Recycle Bin option, because the bin can delete large files permanently without warning. On Windows you can only remove an image from the library, and the file stays on disk. Where a move to the trash isn't possible on Linux or macOS, the dialog lists why for each file.
- **Permanent delete is Linux and BSD only,** and can't be undone. The safety backup brings back the library records, not the files.
- **Show in folder** opens the file manager on the machine running ComfyUI, not necessarily the one with your browser.
- **Returned images** get their prompt links back, but not their tags, categories, collections or favorites.
- **Inspect a file** doesn't add the file to your library.
+1 -60
View File
@@ -277,22 +277,6 @@ 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`
@@ -491,19 +475,6 @@ differ are files whose pixel data is undecodable or cut short: legacy found
nothing, the walk keeps the text before the pixels. Animated PNGs still use
`.text`.
WebP, AVIF and JPEG keep the same records in EXIF, not in text chunks.
ComfyUI's `SaveAnimatedWEBP` writes `prompt:{json}` to EXIF tag 0x0110, then
`workflow:{json}` and every other `extra_pnginfo` key to 0x010F and down; the
AVIF writer uses that layout. `utils/exif_text.py` answers the `png_text` shape
through Pillow's `getexif()`, and both metadata readers fall back to it when a
file has no text chunks. Only a value shaped like a record counts (a key, a
colon, then a JSON object, array or string), so camera EXIF stays out.
`tests/test_exif_text.py` writes real still and animated WebP files, AVIF (where
Pillow has it) and JPEG in that layout; `tests/test_metadata_extraction.py` and
`tests/test_api_core.py` hold the two readers to it. No scan, monitor or
gallery list collects `.avif` yet, so AVIF files are read correctly but never
reach the readers; #652 tracks AVIF as a media type.
Image work runs on PromptManager's own threads (#523). glibc keeps each thread's
malloc arena at its high-water mark, so image buffers spread over the default
executor's threads stay resident. Interactive image work (view previews behind their
@@ -771,33 +742,6 @@ 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:
@@ -2556,10 +2500,7 @@ npm run --prefix tools/vendor test:workflows -- workspace-collections.spec.mjs c
Images › Delete… removes the checked images (or "Select all N matching", at most 500, or
the one file of the side panel or the viewer) from the library, and on request moves the
files to the system trash or (Linux/BSD servers only) deletes them permanently. **The only
code path that unlinks or overwrites a media file is the permanent-delete apply job.** Library
and trash modes never unlink media files; permanent-delete unlinks files only via the apply
job after `file_check` confirms containment and non-symlink, and the review step never unlinks.
files to the system trash. **No code path unlinks or overwrites a media file.**
- **D159** (#480, maintainer request): the concept's "Remove links…" (`danger`, app.js
432) returns as **Delete…** in the same place (after Export metadata, before Clear), and
+1 -2
View File
@@ -1049,8 +1049,7 @@ class PromptDatabase(
if include_ancestors:
ancestors = set()
for folder in folders:
# #646: ``folder`` already uses ``/``; on POSIX ``\\`` is a name.
parts = folder.split("/")
parts = folder.replace("\\", "/").split("/")
for i in range(1, len(parts)):
ancestors.add("/".join(parts[:i]))
folders.update(ancestors)
+2 -4
View File
@@ -99,21 +99,19 @@ class PromptManager(PromptManagerBase, ComfyNodeABC):
"prepend_text": (
IO.STRING,
{
"default": "",
"tooltip": (
"Text to prepend to the main prompt (connected STRING "
"nodes will be added before the main text)"
),
)
},
),
"append_text": (
IO.STRING,
{
"default": "",
"tooltip": (
"Text to append to the main prompt (connected STRING "
"nodes will be added after the main text)"
),
)
},
),
"save_to_library": SAVE_TO_LIBRARY_INPUT,
+3 -7
View File
@@ -89,7 +89,6 @@ from .source_rescope import SourceRescopeMixin
try:
from ...database.operations import PromptDatabase
from ...utils.exif_text import exif_text
from ...utils.logging_config import get_logger
from ...utils.native_memory import release_free_memory
from ...utils.png_text import png_text
@@ -101,7 +100,6 @@ except ImportError:
0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
)
from database.operations import PromptDatabase
from utils.exif_text import exif_text
from utils.logging_config import get_logger
from utils.native_memory import release_free_memory
from utils.png_text import png_text
@@ -1020,11 +1018,9 @@ class PromptManagerAPI(
return []
def _extract_comfyui_metadata(self, image_path):
"""Embedded ComfyUI metadata of an image (PNG text, EXIF) or a video.
"""Embedded ComfyUI metadata of an image (PNG text chunks) or a video.
PNG text is read without decoding the pixels (``utils.png_text``, #523);
WebP, AVIF and JPEG keep the same records as EXIF strings, read through
``utils.exif_text``.
PNG text is read without decoding the pixels (``utils.png_text``, #523).
Videos go through ffprobe (see utils/video_metadata). Unreadable files
are a warning, not an error: a scan over a large output tree meets
@@ -1034,7 +1030,7 @@ class PromptManagerAPI(
return read_video_metadata(image_path)
try:
with Image.open(image_path) as img:
return png_text(img) or exif_text(img)
return png_text(img)
except Exception as e:
self.logger.warning(
f"Unreadable image {os.path.basename(str(image_path))}: {e}"
+1 -2
View File
@@ -304,8 +304,7 @@ def _relative_key(path, root):
relative = os.path.relpath(str(path), str(root))
except ValueError: # another drive (Windows)
return None
# #646: on POSIX ``a\\b.png`` and ``a/b.png`` are two files.
return os.path.normcase(relative).replace(os.sep, "/")
return os.path.normcase(relative).replace("\\", "/")
@dataclass
+4 -6
View File
@@ -148,7 +148,7 @@ def folder_sets(root, files) -> tuple[frozenset, frozenset]:
folders.add(rel_dir)
with_ancestors = set(folders)
for folder in folders:
with_ancestors.update(_ancestors(folder, sep))
with_ancestors.update(_ancestors(folder))
return frozenset(folders), frozenset(with_ancestors)
@@ -158,7 +158,7 @@ def add_folder(root, path, folders, with_ancestors) -> tuple[frozenset, frozense
rel_dir = _folder_of(root, path, sep, prefix)
if not rel_dir or rel_dir in folders:
return folders, with_ancestors
return folders | {rel_dir}, with_ancestors | {rel_dir, *_ancestors(rel_dir, sep)}
return folders | {rel_dir}, with_ancestors | {rel_dir, *_ancestors(rel_dir)}
def _root_prefix(root) -> tuple[str, str]:
@@ -180,10 +180,8 @@ def _folder_of(root, path, sep, prefix) -> str:
return "" if rel_dir == "." else rel_dir
def _ancestors(folder: str, sep: str) -> list[str]:
# #646: ``\\`` separates only in a Windows root (*sep*, the root flavour's
# own); on POSIX it is part of a folder's name.
parts = (folder.replace("\\", "/") if sep == "\\" else folder).split("/")
def _ancestors(folder: str) -> list[str]:
parts = folder.replace("\\", "/").split("/")
return ["/".join(parts[:i]) for i in range(1, len(parts))]
+18 -77
View File
@@ -1,9 +1,9 @@
"""Delete images: remove from library, trash, or permanently delete.
"""Delete selected images: remove them from the library, or trash them (#480).
``POST /prompt_manager/images/delete/preview {items | filter}`` reviews the
selection for all modes at once and answers a reviewed plan (the System ›
selection for both modes at once and answers a reviewed plan (the System ›
Maintenance contract, ``py/api/maintenance.py``): the token, the counts of
the records each file loses, the refused files with a coded reason (all
the records each file loses, the refused files with a coded reason (both
modes, and the trash-only ones), the prompts that lose their last image and
the safety backup. It writes nothing. ``items`` are Images listing identities
(at most 500); ``filter`` is "Select all N matching". Each target is matched
@@ -19,16 +19,12 @@ again (containment and fingerprint) and
in one transaction; the file stays on disk, hidden;
- ``mode="trash"``: it is moved to the trash first (``utils/trash.py``); a
refused move leaves the file and its records alone; after a move its
records are deleted;
- ``mode="permanent"``: it is unlinked from disk with ``os.remove``; a refused
unlink leaves the file and its records alone; after removal its records are
deleted. This mode is Linux/BSD only.
records are deleted.
Only ``mode="permanent"`` unlinks a media file from disk. A failed records
write stops the job; the files after it are not attempted.
No path here unlinks a media file. A failed records write stops the job; the
files after it are not attempted.
"""
import errno
import hashlib
import json
import os
@@ -63,11 +59,10 @@ except ImportError:
from utils.media_folders import is_trash_folder
IMAGE_DELETE = "delete_images"
MODES = ("library", "trash", "permanent")
MODES = ("library", "trash")
TITLES = {
"library": "Delete images (remove from the library)",
"trash": "Delete images (move to the trash)",
"permanent": "Delete images (permanently delete from disk)",
}
MAX_DETAIL_ROWS = 50
# The system moved the file but its place in a trash could not be shown (#499).
@@ -92,8 +87,8 @@ REASONS = {
trash.LOCKED: "The file is open in another program. Close it and try again.",
trash.FAILED: "The file could not be moved to the trash.",
trash.NO_PERMISSION: (
"PromptManager isn't allowed to remove this file (no permission, or it is "
"locked)."
"PromptManager isn't allowed to move this file (no permission, or it is "
"locked in Finder)."
),
trash.CLOUD_SYNC: (
"Files in iCloud Drive or a cloud-synced folder can't be moved to the "
@@ -119,16 +114,6 @@ SOURCES_CHANGED = "The sources changed since the review; nothing was changed."
RECORDS_FAILED = "The image records could not be removed; the job stopped."
def _permanent_delete_code(error: OSError) -> str:
"""Translate a removal ``OSError`` into a permanent-delete refusal code."""
code = error.errno if error.errno else None
if code in (errno.EACCES, errno.EPERM, errno.EROFS):
return trash.NO_PERMISSION
if code in (errno.ENETUNREACH, errno.ENETRESET, errno.EHOSTUNREACH):
return trash.NETWORK
return trash.LOCKED
def lexical_problem(relative: str) -> str | None:
"""The refusal code a root-relative POSIX path earns before any file access."""
parts = relative.split("/")
@@ -290,23 +275,17 @@ class ImageDeleteMixin:
acted.append(target)
counted = db.count_removal_records([t["removal"] for t in acted])
library_count = len(acted)
permanent_supported = permanent_delete_supported()
public = {
"operation": IMAGE_DELETE,
"scope": {"count": library_count, "label": "images"},
"library": {"count": library_count},
"trash": {"count": library_count - len(trash_refused)},
"permanent": {"count": library_count},
"protected": {"count": len(refused), "reasons": []},
"refused": _summary(refused),
"trash_refused": _summary(trash_refused),
"records": counted["records"],
"orphaned_prompts": counted["orphaned_prompts"],
"media": {
"deletes_files": permanent_supported,
"label": "Chosen in the review",
},
"permanent_delete_supported": permanent_supported,
"media": {"deletes_files": False, "label": "Chosen in the review"},
"details": [],
}
return {"targets": acted, "public": public}
@@ -362,11 +341,7 @@ class ImageDeleteMixin:
async def _delete_images(self, job, db, targets, mode, backup):
job.update(total=len(targets), status_line=TITLES[mode])
roots = [str(root) for root in self._get_all_output_dirs()]
done_group = (
"trashed"
if mode == "trash"
else ("deleted" if mode == "permanent" else "removed")
)
done_group = "trashed" if mode == "trash" else "removed"
changed, failed = 0, None
for done, target in enumerate(targets, start=1):
if failed:
@@ -391,26 +366,17 @@ class ImageDeleteMixin:
)
elif group == done_group:
changed += 1
if mode == "trash":
detail = (
f"Moved to the {label}" if label else "Removed from the library"
)
elif mode == "permanent":
detail = "Deleted from disk"
else:
detail = "Removed from the library"
detail = (
f"Moved to the {label}" if label else "Removed from the library"
)
self._record_delete(job, group, target, None, detail)
else:
self._record_delete(job, group, target, code)
job.update(processed=done, progress=int(done / len(targets) * 100))
if changed:
self.invalidate_gallery_cache()
if mode == "trash":
verb, where = "Moved", "to the trash"
elif mode == "permanent":
verb, where = "Permanently deleted", "from disk"
else:
verb, where = "Removed", "from the library"
verb = "Moved" if mode == "trash" else "Removed"
where = "to the trash" if mode == "trash" else "from the library"
line = f"{verb} {changed:,} of {len(targets):,} images {where}"
job.log_line(line)
job.update(progress=100, status_line=f"{line} · {backup_note(backup)}")
@@ -432,7 +398,7 @@ class ImageDeleteMixin:
"code": code,
"detail": text,
}
mark = {"removed": "-", "trashed": "-", "deleted": "-"}.get(group, "=")
mark = {"removed": "-", "trashed": "-"}.get(group, "=")
job.record(
group, row, f"{mark} {target['root_label']}/{target['rel']} · {text}"
)
@@ -471,21 +437,6 @@ class ImageDeleteMixin:
)
return "errors", TRASH_UNCONFIRMED, None
mark = None
elif mode == "permanent":
try:
os.remove(target["abs"])
except OSError as error:
if error.errno == errno.ENOENT:
pass
else:
code = _permanent_delete_code(error)
self.logger.info(
"Not permanently deleted (%s): %s",
code,
target["rel"],
)
return "not_changed", code, None
mark = None
else:
mark = (target["size"], target["mtime_ns"])
try:
@@ -494,11 +445,7 @@ class ImageDeleteMixin:
self.logger.exception("Removing an image's records failed")
return "errors", None, label
_remove_thumbnail(Path(target["root"]), Path(target["rel"]), self.logger)
if mode == "trash":
return "trashed", None, label
if mode == "permanent":
return "deleted", None, label
return "removed", None, label
return ("trashed" if mode == "trash" else "removed"), None, label
# ── the workspace listing ─────────────────────────────────────────
@@ -570,12 +517,6 @@ class ImageDeleteMixin:
return [path for path in paths if not removed(path)]
def permanent_delete_supported() -> bool:
"""Permanent delete is offered only with the Freedesktop trash backend
(Linux/BSD servers); the review and the apply both ask here (#644)."""
return isinstance(trash.BACKEND, trash.FreedesktopBackend)
def parse_mode(value):
"""The apply's ``mode``, or None when it is not one of MODES."""
return value if isinstance(value, str) and value in MODES else None
+8 -22
View File
@@ -70,8 +70,6 @@ try:
in_trash_below_roots,
in_trash_folder,
is_skipped_folder,
path_separators,
split_relative,
)
from ...utils.parallel import map_parallel
from ...utils.json_strict import dumps_strict
@@ -103,8 +101,6 @@ except ImportError:
in_trash_below_roots,
in_trash_folder,
is_skipped_folder,
path_separators,
split_relative,
)
from utils.parallel import map_parallel
from utils.json_strict import dumps_strict
@@ -271,23 +267,18 @@ def _is_within(path, root):
def _has_traversal(relative):
"""True for absolute paths, drive-qualified paths or any ``..`` segment.
Segments are split at this server's separators: on POSIX ``\\`` is part
of a name, so ``a\\..\\b`` is one name below the root (#646).
"""
"""True for absolute paths, drive-qualified paths or any ``..`` segment."""
if not relative or os.path.isabs(relative) or os.path.splitdrive(relative)[0]:
return True
if relative[0] in path_separators():
if relative[0] in ("/", "\\"):
return True
return ".." in split_relative(relative)
return ".." in re.split(r"[\\/]+", relative)
def _is_thumbnail_cache_path(relative):
"""True when *relative* names something in a root's ``thumbnails/``
cache (any case, this server's separators, #646): never inspected as a
media file."""
first = split_relative(relative.lstrip(path_separators()))[0]
cache (any case, either separator): never inspected as a media file."""
first = re.split(r"[\\/]+", relative.lstrip("\\/"), maxsplit=1)[0]
return first.casefold() == "thumbnails"
@@ -884,7 +875,7 @@ def _favorite_root_key(root) -> str:
def _source_depth(source: str) -> int:
return len([part for part in split_relative(source) if part])
return len([part for part in re.split(r"[\\/]+", source) if part])
def deepest_source(sources, absolute_path):
@@ -1209,10 +1200,6 @@ def _output_image_entry(
}
if root_scope is not None:
entry["root_scope"] = root_scope
if "\\" in entry["path"]:
# #646: only a POSIX server lists a name holding a backslash (Windows
# turns it into ``/``); the workspace accepts it only with this mark.
entry["path_style"] = "posix"
return entry
@@ -1234,10 +1221,9 @@ def _workspace_filters(query: Mapping) -> dict:
folded = text.casefold()
media = query.get("media", "all")
order = query.get("sort", "newest")
# #646: ``\\`` separates only on Windows; on POSIX it is part of a name.
folder = "/".join(split_relative(query.get("subfolder", "").strip()))
folder = query.get("subfolder", "").strip().replace("\\", "/")
# ``path``: one exact relative path (Activity opens a scan row by it, D57).
exact = "/".join(split_relative(query.get("path", "").strip()))
exact = query.get("path", "").strip().replace("\\", "/")
category = query.get("category", "").strip() or None
tags = sorted(
{tag.strip() for tag in query.get("tags", "").split(",") if tag.strip()}
+2 -4
View File
@@ -42,7 +42,6 @@ open across the switch (#249 S8).
import asyncio
import itertools
import logging
import os
import re
import time
import uuid
@@ -128,7 +127,7 @@ DUPLICATE_CLEANUP_GROUP_NAMES = ("removed", "kept", "errors")
# ``records`` hold around its safety backup and write.
PROMPT_DELETE_JOB_KIND = "prompt_delete"
IMAGE_DELETE_JOB_KIND = "image_delete" # #480
IMAGE_DELETE_GROUP_NAMES = ("trashed", "removed", "deleted", "not_changed", "errors")
IMAGE_DELETE_GROUP_NAMES = ("trashed", "removed", "not_changed", "errors")
# The System health check (py/api/system.py): a read-only ``read`` job with
# no file outcomes, so it may run beside a scan.
HEALTH_JOB_KIND = "health"
@@ -161,8 +160,7 @@ def _relative_path(path) -> str:
or PureWindowsPath(text).drive
):
return re.split(r"[\\/]", text)[-1]
# #646: on POSIX a backslash is part of a name, never a separator.
return text.replace("\\", "/") if os.sep == "\\" else text
return text.replace("\\", "/")
class JobBusy(Exception):
+2 -7
View File
@@ -516,7 +516,7 @@ class MaintenanceRoutesMixin:
# ── apply ─────────────────────────────────────────────────────────
async def apply_maintenance_plan(self, request):
from .image_delete import IMAGE_DELETE, parse_mode, permanent_delete_supported
from .image_delete import IMAGE_DELETE, parse_mode
data, error = await self._read_maintenance_body(request, ("token", "mode"))
if error is not None:
@@ -531,12 +531,7 @@ class MaintenanceRoutesMixin:
if plan.operation == IMAGE_DELETE:
mode = parse_mode(data.get("mode"))
if mode is None:
return _invalid('mode must be "library", "trash" or "permanent"')
if mode == "permanent" and not permanent_delete_supported():
# The review never offers it here; refuse a direct call (#644).
return _invalid(
"Permanent delete is only available on Linux and BSD servers"
)
return _invalid('mode must be "library" or "trash"')
elif "mode" in data:
return _invalid("Unknown field: mode")
store = self._maintenance_plans
+4 -5
View File
@@ -14,10 +14,10 @@ from .prompts import bad_request
try:
from ...utils.media_capture import CAPTURE_EXTENSIONS
from ...utils.media_folders import in_trash_folder, path_separators
from ...utils.media_folders import in_trash_folder
except ImportError:
from utils.media_capture import CAPTURE_EXTENSIONS
from utils.media_folders import in_trash_folder, path_separators
from utils.media_folders import in_trash_folder
MAX_TARGET_PATH = 1024
TARGET_FIELDS = frozenset({"root_index", "root_scope", "path"})
@@ -30,8 +30,7 @@ def media_target(data: object, *, media_message: str = TAGGING_MEDIA_MESSAGE):
Only the listing identity is accepted: an int root index, the root's
64-hex scope and a bounded root-relative POSIX media path, never an
absolute, drive-qualified, ``..`` path, or (on Windows only, #646) one
holding a backslash (a 400 for a malformed
absolute, drive-qualified, backslash or ``..`` path (a 400 for a malformed
shape, a 403 for an unsafe or non-media path, carrying *media_message*, a
404 for a path in a trash folder, #543). A link or a short-name spelling
is refused later by the capture store's alias check.
@@ -48,7 +47,7 @@ def media_target(data: object, *, media_message: str = TAGGING_MEDIA_MESSAGE):
parts = relative.split("/")
if (
"\0" in relative
or ("\\" in relative and "\\" in path_separators())
or "\\" in relative
or relative.startswith("/")
or _has_traversal(relative)
or any(part in ("", ".", "..") or ":" in part for part in parts)
+2 -3
View File
@@ -672,13 +672,12 @@ def owns(root, path, location=None):
def is_preview_text(filepath):
"""URL text naming a preview: ``thumbnails/<...>/<name>_thumb<ext>``.
Text only, before any join: no backslash (on Windows; on POSIX it is part
of a name, #646), drive or stream colon, and no
Text only, before any join: no backslash, drive or stream colon, and no
empty, ``.`` or ``..`` segment; ``thumbnails`` exactly as the first part
and nowhere else among the folders; the extension, in any case, one a
preview may carry (``X_thumb.JPG`` of an older release included).
"""
if not filepath or ":" in filepath or (os.sep == "\\" and "\\" in filepath):
if not filepath or "\\" in filepath or ":" in filepath:
return False
parts = filepath.split("/")
if len(parts) < 2 or parts[0] != PREVIEW_FOLDER:
+1 -6
View File
@@ -146,9 +146,7 @@ def format_review_target(spelled_path, locator, real_roots, *, pathmod=os.path):
rest = rest[1:]
parts = rest.split(sep)
if any(
part in ("", ".", "..") or "/" in part
# #646: on POSIX a backslash is part of a name.
or (sep == "\\" and "\\" in part) or ":" in part
part in ("", ".", "..") or "/" in part or "\\" in part or ":" in part
for part in parts
):
continue
@@ -273,9 +271,6 @@ class ReviewRoutesMixin:
"root_scope": self._gallery_root_scope(roots[index], index),
"path": relative,
}
if "\\" in relative:
# #646: the mark the Images listing sets (POSIX only).
target["path_style"] = "posix"
# The Images listing's media URL for the same file (formatting only).
url = (
"/prompt_manager/images/serve/"
+1 -2
View File
@@ -205,8 +205,7 @@ def _is_preview_request(filepath):
take as an anchor: a backslash, a drive or stream colon, and empty, ``.``
or ``..`` segments (so a leading ``/`` and ``//server/share`` too).
"""
# #646: a backslash is a separator only on Windows.
if ":" in filepath or (os.sep == "\\" and "\\" in filepath):
if "\\" in filepath or ":" in filepath:
return False
parts = filepath.split("/")
if len(parts) < 2 or parts[0] != "thumbnails":
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "promptmanager"
description = "A powerful ComfyUI custom node that extends the standard text encoder with persistent prompt storage, advanced search capabilities, and an automatic image gallery system using SQLite."
version = "3.7.1"
version = "3.6.0"
license = {file = "LICENSE"}
requires-python = ">=3.12"
dependencies = ["watchdog>=2.1.0", "Pillow>=10.1.0"]
-11
View File
@@ -655,17 +655,6 @@ def create_app(root: Path) -> web.Application:
shutil.copyfile(root / "output" / "shared" / "same.png", destination)
return web.json_response({"success": True})
@routes.post("/__test__/add-backslash-image")
async def add_backslash_image(request: web.Request) -> web.Response:
"""#646: a folder whose name holds a backslash, as a Windows-style
``filename_prefix`` makes on a POSIX server."""
if os.sep == "\\":
return web.json_response({"success": False}, status=409)
destination = root / "output" / "model.safetensors\\2026-11-17" / "slash.png"
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(root / "output" / "shared" / "same.png", destination)
return web.json_response({"success": True})
@routes.post("/__test__/add-local-inspect-file")
async def add_local_inspect_file(request: web.Request) -> web.Response:
"""Serve one committed Inspect fixture from the output folder.
-23
View File
@@ -2709,26 +2709,3 @@ test('all matching over 10,000 images says so before any dialog or request', asy
}
expect(posted).toBe(0);
});
// #646: on a POSIX server a Windows-style filename_prefix makes one folder whose name holds a backslash. Its file opens
// in the viewer, takes a star that survives a reload, and the folder filter names it with its backslash.
test('a file in a folder whose name holds a backslash opens, stars and filters (#646)', async ({ page, request }) => {
await expect(await request.post('/__test__/add-backslash-image')).toBeOK();
await page.goto(workspace);
await expect(cards(page)).toHaveCount(3);
const card = page.locator('article[data-image-key="0:model.safetensors\\\\2026-11-17/slash.png"]');
await card.locator('.image-open').click();
const viewer = page.locator('dialog#viewer-dialog[open]');
await expect(viewer.locator('#viewer-title')).toContainText('slash.png');
await expect(viewer.locator('#viewer-details .panel-heading')).toBeVisible();
await viewer.locator('#viewer-close').click();
await expect(viewer).toHaveCount(0);
await star(card, 'slash.png').click();
await expectStar(star(card, 'slash.png'), true);
await expect.poll(async () => (await listedFavorites(request))['0:model.safetensors\\2026-11-17/slash.png']).toBe(true);
await page.reload();
await expectStar(star(card, 'slash.png'), true);
await refine(page, { Folder: 'model.safetensors\\2026-11-17' });
await expect(cards(page)).toHaveCount(1);
await expect(cards(page)).toContainText('slash.png');
});
+9 -23
View File
@@ -565,11 +565,9 @@ test('URLs and media end with their owning session', async ({ page }) => {
// Replacement.
await choose(page, parityPng('f02.png'));
await expect(preview(page).locator('img.local-file-preview')).toBeVisible();
// #653: a video still starting (inline, or in the viewer the selection opened) is held until it settles or
// STARTING_VIDEO_MS (15 s) passes, so its release can follow the new preview: wait for it, never check once.
let state = await urls(page);
await expect.poll(async () => (await urls(page)).revoked, { timeout: 20000 }).toEqual([state.created[0]]);
await expect.poll(() => page.evaluate(() => window.__loads), { timeout: 20000 }).toBeGreaterThanOrEqual(1);
expect(state.revoked).toEqual([state.created[0]]);
expect(await page.evaluate(() => window.__loads)).toBeGreaterThanOrEqual(1);
// Route change, from the page (D155: the selection opened the viewer, which makes the sidebar inert).
await closeOpened(page);
await page.locator('aside.sidebar nav').getByRole('link', { name: 'Overview', exact: true }).click();
@@ -650,10 +648,7 @@ test('a video replaced while still starting is reset once it settles', async ({
// page (TESTING.md D62), so it stays in place, inert and still playing its URL, with the new preview after it.
// Once it reports metadata or an error it is paused, loses its src, is reset (load() with no src, which frees its
// decoder) and leaves the page, and only then is its URL revoked. Fresh pages share one browser process.
// A busy WebKit can fire `loadstart` after the video already has data (#641, run 43732282629: readyState 4), so
// keep going until at least one page saw it still starting.
let startingSeen = 0;
for (let attempt = 0; attempt < 15 || (startingSeen === 0 && attempt < 30); attempt++) {
for (let attempt = 0; attempt < 15; attempt++) {
const page = await context.newPage();
try {
if (attempt === 0) await startCoverage(page, browserName);
@@ -692,11 +687,11 @@ test('a video replaced while still starting is reset once it settles', async ({
await choose(page, localFixture('core-tags.webm', 'video/webm'));
await expect(preview(page).locator('img.local-file-preview')).toBeVisible({ timeout: 8000 });
await expect(preview(page).locator('video')).toHaveCount(0);
// Replaced while starting (usually so at `loadstart` itself): kept in place and untouched. A video that had
// Replaced while starting (always so at `loadstart` itself): kept in place and untouched. A video that had
// settled is released at once. Either way it is reset once, and its URL goes last.
await expect.poll(() => page.evaluate(() => window.__starting.revoked ?? null)).toEqual({ src: false, connected: false, resets: 1 });
const { readyState, replaced } = await page.evaluate(() => ({ readyState: window.__starting.readyState, replaced: window.__starting.replaced }));
if (readyState === 0) startingSeen++;
if (attempt % 5 === 0) expect(readyState).toBe(0);
expect(replaced).toEqual(readyState === 0 ? { connected: true, src: true, inert: true, resets: 0 } : { connected: false, src: false, inert: false, resets: 1 });
expect(await page.evaluate(() => window.__starting.node.__resets)).toBe(1);
// The page still answers.
@@ -707,7 +702,6 @@ test('a video replaced while still starting is reset once it settles', async ({
await page.close();
}
}
expect(startingSeen, 'no page saw the video still starting at its loadstart').toBeGreaterThan(0);
});
test('a new selection while the viewer\'s own video is still starting leaves it until it settles (#483)', async ({ context, browserName }) => {
@@ -716,10 +710,7 @@ test('a new selection while the viewer\'s own video is still starting leaves it
// selection from that video's own `loadstart` (readyState HAVE_NOTHING), or a few milliseconds after it, must not
// reset it or take it off the page while it starts (WebKit, GStreamer: TESTING.md D62; merge-queue run
// 40903238387). The viewer stays open until it reports metadata or an error, then closes; the URL goes last.
// A busy WebKit can fire `loadstart` after the video already has data (#641, run 43732282629: readyState 4), so
// keep going until at least one page saw it still starting.
let startingSeen = 0;
for (let attempt = 0; attempt < 10 || (startingSeen === 0 && attempt < 20); attempt++) {
for (let attempt = 0; attempt < 10; attempt++) {
const page = await context.newPage();
try {
if (attempt === 0) await startCoverage(page, browserName);
@@ -759,7 +750,7 @@ test('a new selection while the viewer\'s own video is still starting leaves it
await expect(preview(page).locator('img.local-file-preview')).toBeVisible({ timeout: 8000 });
await expect.poll(() => page.evaluate(() => window.__starting?.revoked ?? null)).toEqual({ src: false, connected: false, resets: 1 });
const { readyState, replaced } = await page.evaluate(() => ({ readyState: window.__starting.readyState, replaced: window.__starting.replaced }));
if (readyState === 0) startingSeen++;
if (attempt % 5 === 0) expect(readyState).toBe(0);
// Starting when replaced: still on the page with its URL, never reset; settled: released at once.
expect(replaced).toEqual(readyState === 0 ? { connected: true, src: true, resets: 0 } : { connected: false, src: false, resets: 1 });
expect(await page.evaluate(() => window.__starting.node.__resets)).toBe(1);
@@ -773,7 +764,6 @@ test('a new selection while the viewer\'s own video is still starting leaves it
await page.close();
}
}
expect(startingSeen, 'no page saw the video still starting at its loadstart').toBeGreaterThan(0);
});
/** #483: holds the viewer's video in HAVE_NOTHING (its `loadedmetadata` never fires) so a hold can be driven by hand. */
@@ -860,10 +850,7 @@ test('leaving for another route while a video starts waits for it to settle', as
// A WebKit (GStreamer) video detached before its pipeline had started deadlocked the page (TESTING.md D62); a
// route change detaches the whole page, so the shell renders the next route once the video reports metadata or an
// error. The route changes from the video's own `loadstart`, or a few milliseconds after it.
// A busy WebKit can fire `loadstart` after the video already has data (#641, run 43732282629: readyState 4), so
// keep going until at least one page saw it still starting.
let startingSeen = 0;
for (let attempt = 0; attempt < 15 || (startingSeen === 0 && attempt < 30); attempt++) {
for (let attempt = 0; attempt < 15; attempt++) {
const page = await context.newPage();
try {
if (attempt === 0) await startCoverage(page, browserName);
@@ -891,7 +878,7 @@ test('leaving for another route while a video starts waits for it to settle', as
await choose(page, localFixture('core-tags.webm', 'video/webm'));
await expect(main(page).getByRole('heading', { level: 1, name: 'Overview', exact: true })).toBeVisible({ timeout: 8000 });
const { readyState, reset } = await page.evaluate(() => ({ readyState: window.__starting.readyState, reset: window.__starting.reset }));
if (readyState === 0) startingSeen++;
if (attempt % 5 === 0) expect(readyState).toBe(0);
// The video was reset and left the page only once it had settled.
expect(reset.readyState >= 1 || reset.failed).toBe(true);
expect(reset.connected).toBe(true);
@@ -904,7 +891,6 @@ test('leaving for another route while a video starts waits for it to settle', as
await page.close();
}
}
expect(startingSeen, 'no page saw the video still starting at its loadstart').toBeGreaterThan(0);
});
test('closing the viewer on a video that just started never blocks the page', async ({ context, browserName }) => {
@@ -311,42 +311,3 @@ test('on a video the image keys and Space do nothing, as the toolbar disables th
await page.evaluate(() => new Promise(requestAnimationFrame));
await expect(viewer(page)).not.toHaveClass(/\bviewer-fullscreen\b/);
});
/** #646: the listing carries one file whose folder name holds a backslash, as a Windows-style prefix makes on Linux. */
async function withBackslashFile(page) {
await page.route(/\/prompt_manager\/images\/output\?/, async route => {
const response = await route.fetch(), body = await response.json();
if (body.images?.length > 1) {
const copy = body.images[1];
body.images.splice(1, 0, {...copy, path: `model.safetensors\\2026-11-17/${copy.filename}`, relative_path: `model.safetensors\\2026-11-17/${copy.filename}`});
}
await route.fulfill({response, json: body});
});
}
test('a file the viewer refuses is left out, and the others still open (#646)', async ({ page }) => {
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await withBackslashFile(page);
await page.setViewportSize({ width: 1600, height: 1100 });
await openProduction(page, 'images', 'dark');
const cards = await page.locator(CARDS).count();
await page.locator(CARDS).first().locator('.image-open').click();
await expect(position(page)).toContainText(`1 of ${cards - 1}`);
await page.keyboard.press('ArrowRight');
await expect(position(page)).toContainText('2 of ');
await expect(viewer(page).locator('#viewer-title')).not.toContainText('model.safetensors');
expect(errors).toEqual([]);
});
test('the refused file itself opens its details instead of the viewer (#646)', async ({ page }) => {
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await withBackslashFile(page);
await page.setViewportSize({ width: 1600, height: 1100 });
await openProduction(page, 'images', 'dark');
await page.locator(`${CARDS}[data-image-key*="model.safetensors"] .image-open`).click();
await expect(page.getByRole('complementary', {name: 'Selected image details'}).getByRole('alert')).toHaveText('Could not read prompts from this file.');
await expect(viewer(page)).toHaveCount(0);
expect(errors).toEqual([]);
});
@@ -1033,9 +1033,7 @@ test('the bulk options pick and reset like the Tag image dialog (D204)', async (
test('the client Built-in copy equals the server DEFAULT_TAG_TEMPLATE (#431)', async () => {
const { BUILTIN_INSTRUCTIONS } = await load();
// A Windows checkout may hold the file with CRLF line endings (#636).
const source = require('node:fs').readFileSync(require('node:path').join(__dirname, '../../py/tagging_defaults.py'), 'utf8')
.replace(/\r\n/g, '\n');
const source = require('node:fs').readFileSync(require('node:path').join(__dirname, '../../py/tagging_defaults.py'), 'utf8');
const block = source.slice(source.indexOf('DEFAULT_TAG_TEMPLATE = ('), source.indexOf('\n)\n', source.indexOf('DEFAULT_TAG_TEMPLATE = (')));
const text = [...block.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map(([, part]) => JSON.parse(`"${part}"`)).join('');
assert.ok(text.length > 100);
+1 -32
View File
@@ -23,7 +23,7 @@ test('the words of the review and its routes', () => {
assert.equal(MAX_DELETE, 500);
assert.equal(TOO_MANY, 'Select at most 500 images.');
assert.equal(QUESTION, 'What should happen to the files?');
assert.deepEqual(MODES.map(mode => mode.label), ['Remove from the library only', 'Also move the files to the trash', 'Permanently delete']);
assert.deepEqual(MODES.map(mode => mode.label), ['Remove from the library only', 'Also move the files to the trash']);
});
test('library rows: scope, refusals, links, details, backup and media', () => {
@@ -149,34 +149,3 @@ test('apply refuses to send a delete without an explicit mode', async () => {
await assert.rejects(applyDelete({ api, store: null, plan: plan(), mode, notify: () => {} }), TypeError);
}
});
test('permanent rows: scope and media line', () => {
const { deleteRows } = module();
const rows = Object.fromEntries(deleteRows(plan({ permanent: { count: 3 } }), 'permanent'));
assert.equal(rows.Scope, '3 images');
assert.equal(rows['Media on disk'], 'Files are removed from disk. Disk space is freed immediately.');
});
test('permanent sentences', () => {
const { deleteSentences, SENTENCES } = module();
assert.deepEqual(deleteSentences(plan(), 'permanent'), [SENTENCES.permanent]);
});
test('permanent primary label and close-only reason', () => {
const { primaryLabel, closeOnlyReason } = module();
assert.equal(primaryLabel('permanent', 2), 'Permanently delete 2 images from disk');
assert.equal(closeOnlyReason(plan({ library: { count: 0 }, trash: { count: 0 }, permanent: { count: 0 } })), 'None of the selected images can be deleted.');
assert.equal(closeOnlyReason(plan({ library: { count: 3 } })), null);
});
test('permanent outcome toast', () => {
const { outcomeToast } = module();
assert.equal(outcomeToast({ scope: { mode: 'permanent' }, counters: { deleted: 3, not_changed: 0 }, total: 3 }),
'Permanently deleted 3 images from disk.');
assert.equal(outcomeToast({ scope: { mode: 'permanent' }, counters: { deleted: 2, not_changed: 1 }, total: 3 }),
'Permanently deleted 2 images from disk. 1 was not changed (see Activity).');
assert.equal(outcomeToast({ scope: { mode: 'permanent', failure: 'records-failed' }, counters: { deleted: 1 }, total: 4 }),
'Stopped after 1 of 4 images; the rest were not changed. See Activity.');
});
@@ -954,15 +954,3 @@ test('record accepts an image\'s own category on any link status (#332)', () =>
assert.equal(record.library.category_scope, 'image');
}
});
test('a backslash inside a name is accepted only from a POSIX listing (#646)', () => {
const inspectPath = contract('inspectPath');
const path = 'model.safetensors\\2026-11-17/a.png';
assert.equal(inspectPath({root_index:0, path, root_scope:scopeA, path_style:'posix'}),
`/prompt_manager/images/inspect/model.safetensors%5C2026-11-17/a.png?root=0&root_scope=${scopeA}`);
for (const path_style of [undefined, 'windows', 'POSIX'])
assert.throws(() => inspectPath({root_index:0, path, root_scope:scopeA, path_style}), /Invalid inspection identity/);
// The mark relaxes only the backslash: traversal, drives and empty names stay refused.
for (const bad of ['../a.png', 'a/../b.png', 'C:\\a.png', 'a//b.png', '/a.png'])
assert.throws(() => inspectPath({root_index:0, path:bad, root_scope:scopeA, path_style:'posix'}), /Invalid inspection identity/);
});
-25
View File
@@ -1,25 +0,0 @@
// #646: Needs review hands the viewer and inspector the same identity the Images listing does, the POSIX mark
// for a name holding a backslash included.
import test from 'node:test';
import assert from 'node:assert/strict';
import { imageOf } from '../../web/js/workspace/review.mjs';
import { inspectPath } from '../../web/js/workspace/inspection-state.mjs';
const scope = 'a'.repeat(64);
const item = target => ({ filename: 'a.png', target, url: '/u', thumbnail_url: null, is_video: false });
test('a review item keeps the POSIX mark of a name holding a backslash', () => {
const path = 'm.safetensors\\2026-11-17/a.png';
const image = imageOf(item({ root_index: 0, root_scope: scope, path, path_style: 'posix' }));
assert.equal(image.path_style, 'posix');
assert.equal(inspectPath(image), `/prompt_manager/images/inspect/m.safetensors%5C2026-11-17/a.png?root=0&root_scope=${scope}`);
});
test('a review item without the mark, or with another value, carries none', () => {
for (const path_style of [undefined, 'windows', 'POSIX']) {
const image = imageOf(item({ root_index: 0, root_scope: scope, path: 'a\\b.png', path_style }));
assert.equal(Object.hasOwn(image, 'path_style'), false);
assert.throws(() => inspectPath(image), /Invalid inspection identity/);
}
assert.equal(Object.hasOwn(imageOf(item({ root_index: 0, root_scope: scope, path: 'p/a.png' })), 'path_style'), false);
});
-13
View File
@@ -38,19 +38,6 @@ 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++,
-29
View File
@@ -1,29 +0,0 @@
"""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)
+1 -17
View File
@@ -225,12 +225,7 @@ class TestObserve(AnnotationAPITestCase):
("dot segment", {"path": "./a.png"}, 403),
("empty segment", {"path": "sub//a.png"}, 403),
("absolute", {"path": "/etc/a.png"}, 403),
# #646: a backslash is a separator only on Windows.
*(
[("backslash", {"path": "sub\\a.png"}, 403)]
if os.sep == "\\"
else []
),
("backslash", {"path": "sub\\a.png"}, 403),
("drive", {"path": "C:/a.png"}, 403),
("drive segment", {"path": "sub/C:a.png"}, 403),
("nul", {"path": "a\x00.png"}, 403),
@@ -404,17 +399,6 @@ 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")
+1 -3
View File
@@ -2,7 +2,6 @@
import json
import ntpath
import os
import sqlite3
from unittest.mock import patch
@@ -179,8 +178,7 @@ class TestCollectionRoutes(CollectionRoutesTestCase):
"../a.png",
"sub/../../a.png",
"C:/a.png",
# #646: a backslash is a separator only on Windows.
*(["a\\b.png"] if os.sep == "\\" else []),
"a\\b.png",
"/a.png",
"notes.txt",
):
-18
View File
@@ -926,24 +926,6 @@ class TestMetadataParsing(unittest.TestCase):
f.write(b"nope")
self.assertEqual(self.api._extract_comfyui_metadata(garbage), {})
def test_extract_metadata_from_webp_exif(self):
"""SaveAnimatedWEBP writes the records as EXIF, with no text chunks."""
from PIL import Image
path = os.path.join(self.tmpdir, "m.webp")
exif = Image.Exif()
exif[0x0110] = 'prompt:{"1": {"class_type": "KSampler"}}'
exif[0x010F] = 'workflow:{"nodes": [{"type": "CLIPTextEncode"}]}'
Image.new("RGB", (1, 1)).save(path, "WEBP", exif=exif)
self.assertEqual(
self.api._extract_comfyui_metadata(path),
{
"prompt": '{"1": {"class_type": "KSampler"}}',
"workflow": '{"nodes": [{"type": "CLIPTextEncode"}]}',
},
)
if __name__ == "__main__":
unittest.main()
+1 -4
View File
@@ -2,7 +2,6 @@
import json
import ntpath
import os
import sqlite3
from unittest.mock import patch
@@ -273,9 +272,7 @@ class TestRefusals(ImageCategoryTestCase):
async def test_unsafe_paths_are_403(self):
(self.output_dir / "notes.txt").write_text("not media")
# #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"):
for path in ("../outside.png", "/a.png", "C:/a.png", "a\\b.png", "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)
+1 -20
View File
@@ -1268,12 +1268,7 @@ class TestPathHelpers(unittest.TestCase):
def test_has_traversal(self):
self.assertTrue(images_module._has_traversal(""))
self.assertTrue(images_module._has_traversal("a/../b.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("\\\\srv\\share\\x.png"))
self.assertTrue(images_module._has_traversal(os.path.abspath(os.sep)))
self.assertFalse(images_module._has_traversal("sub/x.png"))
@@ -2740,20 +2735,6 @@ 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.
+1 -6
View File
@@ -2,7 +2,6 @@
import io
import json
import os
import shutil
import subprocess
import unittest
@@ -152,8 +151,7 @@ class TestPromptInspector(ImageAPITestCase):
for path in (
"%2Fetc%2Fpasswd.png",
"..%2Fsecret.png",
# #646: on POSIX a backslash is part of a name (404 below).
*(["%5Csecret.png"] if os.sep == "\\" else []),
"%5Csecret.png",
"bad.txt",
"null%00.png",
"C:%5Csecret.png",
@@ -162,9 +160,6 @@ 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")
+1 -2
View File
@@ -149,8 +149,7 @@ class TestRescopeRoute(ImageAPITestCase):
{"target": {**good, "path": "../a.png"}},
{"target": {**good, "path": "/abs.png"}},
{"target": {**good, "path": "C:/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": "sub//a.png"}},
{"target": {**good, "path": "notes.txt"}},
{"target": {**good, "path": "x" * 2000 + ".png"}},
-17
View File
@@ -14,7 +14,6 @@ import os
import posixpath
import sqlite3
import threading
import unittest
from pathlib import Path
from unittest.mock import patch
@@ -453,22 +452,6 @@ 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()
-6
View File
@@ -273,12 +273,6 @@ class TestNodeIntegration(unittest.TestCase):
# Check optional inputs
self.assertIn("search_text", input_types["optional"])
# Every optional STRING starts empty, so the schema offers "" and not
# null: the composition sockets used to be the only ones without a
# default, although the node already treats them as empty.
for name in ("category", "tags", "search_text", "prepend_text", "append_text"):
self.assertEqual(input_types["optional"][name][1]["default"], "", name)
if __name__ == "__main__":
unittest.main()
+5 -10
View File
@@ -17,11 +17,6 @@ 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
@@ -30,12 +25,12 @@ class BrowserServerCase(unittest.TestCase):
"""Starts the test server in a temp folder of its own; holds no tests."""
def setUp(self):
self.tmp = tempfile.mkdtemp()
self.addCleanup(remove_when_released, self.tmp)
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
def start(self, *extra):
env = {**os.environ, "TMPDIR": self.tmp}
env.update(TEMP=self.tmp, TMP=self.tmp)
env = {**os.environ, "TMPDIR": self.tmp.name}
env.update(TEMP=self.tmp.name, TMP=self.tmp.name)
process = subprocess.Popen(
[sys.executable, "-m", "tests.browser.server", "--port", "0", *extra],
cwd=REPO_ROOT,
@@ -70,7 +65,7 @@ class BrowserServerCase(unittest.TestCase):
time.sleep(0.1)
def roots(self):
return sorted(path.name for path in Path(self.tmp).glob("pm-browser-*"))
return sorted(path.name for path in Path(self.tmp.name).glob("pm-browser-*"))
class TestBrowserServerLifetime(BrowserServerCase):
+7 -10
View File
@@ -22,11 +22,6 @@ 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
@@ -113,10 +108,10 @@ class TestSlowResetOnTheServer(unittest.TestCase):
"""A reset behind another process's write lock, on tests/browser/server.py."""
def setUp(self):
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.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.stderr = tempfile.TemporaryFile()
self.addCleanup(self.stderr.close)
process = subprocess.Popen(
@@ -150,7 +145,9 @@ 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, "pm-browser-*", "browser.db"))
[self.db_path] = glob.glob(
os.path.join(self.tmp.name, "pm-browser-*", "browser.db")
)
def reset(self) -> tuple[int, float]:
request = urllib.request.Request(
-259
View File
@@ -1,259 +0,0 @@
"""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()
-131
View File
@@ -1,131 +0,0 @@
"""ComfyUI's EXIF records: what WebP, AVIF and JPEG carry instead of text.
ComfyUI's SaveAnimatedWEBP writes ``prompt:{json}`` to EXIF tag 0x0110, then
``workflow:{json}`` and every other ``extra_pnginfo`` key to 0x010F and down;
the AVIF writer uses that layout too. Pillow exposes them only through
``getexif()``, so a reader that looks at ``image.info`` or the text chunks
finds nothing. These tests write real files in that layout.
"""
import json
import os
import sys
import tempfile
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from PIL import Image, features
from utils.exif_text import exif_text
PROMPT = {"1": {"class_type": "KSampler", "inputs": {"seed": 7}}}
WORKFLOW = {"nodes": [{"type": "CLIPTextEncode", "inputs": {"text": "cat"}}]}
PAIRS = [{"positive": "cat", "negative": "dog"}]
def comfyui_exif(prompt=PROMPT, extra=None):
"""The tags ComfyUI writes: the prompt on 0x0110, extra_pnginfo from 0x010F."""
exif = Image.Exif()
if prompt is not None:
exif[0x0110] = f"prompt:{json.dumps(prompt)}"
tag = 0x010F
for key, value in ({"workflow": WORKFLOW} if extra is None else extra).items():
exif[tag] = f"{key}:{json.dumps(value)}"
tag -= 1
return exif
class ExifTextCase(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.folder = folder.name
def write(self, name, image_format, exif, **options):
path = os.path.join(self.folder, name)
Image.new("RGB", (8, 8), "red").save(path, image_format, exif=exif, **options)
return path
def read(self, path):
with Image.open(path) as image:
return exif_text(image)
class TestComfyuiRecords(ExifTextCase):
def test_reads_the_records_of_a_webp(self):
path = self.write("a.webp", "WEBP", comfyui_exif())
self.assertEqual(
self.read(path),
{"prompt": json.dumps(PROMPT), "workflow": json.dumps(WORKFLOW)},
)
def test_reads_an_animated_webp(self):
# SaveAnimatedWEBP writes the first frame's EXIF and appends the rest.
frames = [Image.new("RGB", (8, 8), color) for color in ("red", "blue")]
path = os.path.join(self.folder, "anim.webp")
frames[0].save(
path,
"WEBP",
save_all=True,
append_images=frames[1:],
duration=100,
exif=comfyui_exif(),
)
self.assertEqual(self.read(path)["workflow"], json.dumps(WORKFLOW))
def test_reads_every_extra_pnginfo_key_and_not_only_the_workflow(self):
exif = comfyui_exif(
extra={"workflow": WORKFLOW, "comfyassets_prompt_pairs": PAIRS}
)
path = self.write("pairs.webp", "WEBP", exif)
self.assertEqual(self.read(path)["comfyassets_prompt_pairs"], json.dumps(PAIRS))
def test_reads_a_jpeg_in_the_same_layout(self):
# Not a core saver, but a third-party one reusing the convention.
path = self.write("a.jpg", "JPEG", comfyui_exif())
self.assertEqual(self.read(path)["prompt"], json.dumps(PROMPT))
@unittest.skipUnless(features.check("avif"), "Pillow has no AVIF support")
def test_reads_an_avif(self):
path = self.write("a.avif", "AVIF", comfyui_exif())
self.assertEqual(self.read(path)["workflow"], json.dumps(WORKFLOW))
class TestOtherExif(ExifTextCase):
def test_a_camera_exif_is_not_a_comfyui_record(self):
exif = Image.Exif()
exif[0x010F] = "Canon" # Make
exif[0x0110] = "Canon EOS R5" # Model
exif[0x0131] = "GIMP 2.10.38" # Software
exif[0x0132] = "2024:01:02 03:04:05" # DateTime
path = self.write("camera.jpg", "JPEG", exif)
self.assertEqual(self.read(path), {})
def test_a_value_that_is_not_json_is_not_a_record(self):
exif = Image.Exif()
exif[0x010E] = "note:not json"
exif[0x010D] = "make:Canon"
path = self.write("notes.webp", "WEBP", exif)
self.assertEqual(self.read(path), {})
def test_a_png_answers_empty_its_records_are_text_chunks(self):
from PIL.PngImagePlugin import PngInfo
info = PngInfo()
info.add_text("workflow", json.dumps(WORKFLOW))
path = os.path.join(self.folder, "a.png")
Image.new("RGB", (8, 8)).save(path, pnginfo=info)
self.assertEqual(self.read(path), {})
if __name__ == "__main__":
unittest.main()
+3 -91
View File
@@ -1,14 +1,12 @@
"""Delete selected images: the review and the apply job (#480).
``POST /prompt_manager/images/delete/preview`` reviews all three modes;
``POST /prompt_manager/images/delete/preview`` reviews both modes;
``POST /prompt_manager/maintenance/apply {token, mode}`` removes the files'
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).
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.
"""
import asyncio
import errno
import os
import sys
import sqlite3
@@ -409,89 +407,3 @@ 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]],
)
+1 -5
View File
@@ -1045,8 +1045,7 @@ class TestRevealRoute(ImageAPITestCase):
for path in (
"../outside.png",
"sub/../../outside.png",
# #646: a separator only on Windows; on POSIX one name (below).
*(["sub\\..\\..\\outside.png"] if os.sep == "\\" else []),
"sub\\..\\..\\outside.png",
str(outside),
"/" + outside.name,
"C:/outside.png",
@@ -1055,9 +1054,6 @@ 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):
-61
View File
@@ -1,61 +0,0 @@
"""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()
-7
View File
@@ -312,13 +312,6 @@ 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
+1 -14
View File
@@ -135,18 +135,6 @@ 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)
@@ -224,8 +212,7 @@ class CaptureStoreTestCase(unittest.TestCase):
"",
"/a.png",
"C:/a.png",
# #646: a backslash separates folders only on Windows.
*(["a\\b.png"] if os.sep == "\\" else []),
"a\\b.png",
"a\x00.png",
"notes.txt",
"folder",
-38
View File
@@ -39,41 +39,3 @@ 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))
-41
View File
@@ -41,31 +41,6 @@ def _create_png(text_chunks=None, size=(64, 64)):
return tmp.name
def _create_webp(workflow=None, prompt=None, size=(64, 64)):
"""Create a minimal WebP with the EXIF records ComfyUI writes.
SaveAnimatedWEBP puts ``prompt:{json}`` at EXIF tag 0x0110 and
``workflow:{json}`` at 0x010F; the file has no text chunks at all.
Args:
workflow: Workflow dict to embed as the workflow record.
prompt: Prompt dict to embed as the prompt record.
size: tuple (width, height).
Returns:
Path to the temporary WebP file.
"""
exif = Image.Exif()
if prompt is not None:
exif[0x0110] = f"prompt:{json.dumps(prompt)}"
if workflow is not None:
exif[0x010F] = f"workflow:{json.dumps(workflow)}"
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".webp")
tmp.close()
Image.new("RGB", size, color=(128, 128, 128)).save(tmp.name, "WEBP", exif=exif)
return tmp.name
class MetadataTestCase(unittest.TestCase):
"""Base class that cleans up temp files."""
@@ -83,11 +58,6 @@ class MetadataTestCase(unittest.TestCase):
self.temp_files.append(path)
return path
def _webp(self, workflow=None, prompt=None, size=(64, 64)):
path = _create_webp(workflow, prompt, size)
self.temp_files.append(path)
return path
class TestExtractMetadata(MetadataTestCase):
"""Test extract_metadata method."""
@@ -112,17 +82,6 @@ class TestExtractMetadata(MetadataTestCase):
self.assertIsNotNone(result)
self.assertIn("prompt", result)
def test_extracts_metadata_from_webp_exif(self):
"""A WebP carries the records as EXIF, not as text chunks."""
workflow = {"nodes": [{"type": "CLIPTextEncode", "inputs": {"text": "hi"}}]}
prompt = {"1": {"class_type": "KSampler", "inputs": {}}}
path = self._webp(workflow=workflow, prompt=prompt)
result = self.extractor.extract_metadata(path)
self.assertIsNotNone(result)
self.assertEqual(result["workflow"]["nodes"][0]["type"], "CLIPTextEncode")
self.assertIn("prompt", result)
self.assertEqual(result["file_info"]["format"], "WEBP")
def test_extracts_text_encoder_nodes(self):
workflow = {
"nodes": [
-1
View File
@@ -22,7 +22,6 @@ DEVELOPMENT = (
"images/x.png",
"TESTING.md",
"requirements-dev.txt",
".gitattributes",
)
KEPT = (
"__init__.py",
-139
View File
@@ -1,139 +0,0 @@
"""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())
-64
View File
@@ -1,64 +0,0 @@
"""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()
+2 -7
View File
@@ -434,8 +434,7 @@ class TestThumbnailOnFirstView(AutoThumbnailCase):
for path in (
"thumbnails/D:/x_thumb.webp",
"thumbnails/D: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//server/share/x_thumb.webp",
"/thumbnails/x_thumb.webp",
"thumbnails/a/./x_thumb.webp",
@@ -452,11 +451,7 @@ class TestThumbnailOnFirstView(AutoThumbnailCase):
):
for path in (
"thumbnails/D:/x_thumb.webp",
*(
["thumbnails/\\\\server\\share/x_thumb.webp"]
if os.sep == "\\"
else []
),
"thumbnails/\\\\server\\share/x_thumb.webp",
"/thumbnails/x_thumb.webp",
):
answer = await self.api._serve_missing_thumbnail(
+1 -6
View File
@@ -7,9 +7,7 @@ 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
@@ -302,10 +300,7 @@ class TestPredicates(unittest.TestCase):
self.assertFalse(is_trash_folder(name), name)
def test_either_separator(self):
# #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.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):
+4 -13
View File
@@ -50,17 +50,6 @@ 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):
@@ -170,7 +159,9 @@ class TestComfyUIOutputCheck(DiagnosticsTestCase):
)
def test_nothing_found_is_a_warning(self):
self._chdir_without_comfyui()
empty = os.path.join(self.tmp.name, "empty")
os.makedirs(empty)
self._chdir(empty)
with mock.patch.dict(sys.modules, {"folder_paths": None, "py.config": None}):
result = self.diag.check_comfyui_output()
self.assertEqual(result["status"], "warning")
@@ -212,7 +203,7 @@ class TestDependenciesAndFullRun(DiagnosticsTestCase):
def test_full_diagnostic_reports_every_category(self):
self._populate()
self._chdir_without_comfyui()
self._chdir(self.tmp.name)
with mock.patch.dict(sys.modules, {"folder_paths": None, "py.config": None}):
results = self.diag.run_full_diagnostic()
self.assertEqual(
+1 -11
View File
@@ -51,17 +51,7 @@ 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()
# 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 _: first.add(threading.current_thread()), range(8), 2)
map_parallel(lambda _: second.add(threading.current_thread()), range(8), 2)
self.assertTrue(second <= first, (first, second))
self.assertLessEqual(len(_job_threads()), 2)
+31 -104
View File
@@ -67,16 +67,9 @@ 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 = jobIf(`!cancelled() && github.event_name != 'pull_request' && ${CODE_CLASS}`);
const QUEUE_ONLY_IF = /^ {4}if: github\.event_name != 'pull_request'$/m;
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)]
@@ -93,36 +86,21 @@ function runGate(jobText, env) {
}
}
// 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 = [] }) {
// 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) {
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);
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`);
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`);
}
}
}
@@ -135,20 +113,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', 'changes', 'frontend-coverage', 'frontend-coverage-merge']);
assert.deepEqual([...needs].sort(), ['browser-workflows', '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, and nothing for a docs or inert change', () => {
assertGateBehaviour(allJobs.get('viewerjs'), { queueOnly: ['browser-workflows'], codeOnly: ['frontend-coverage', 'frontend-coverage-merge'] });
test('viewerjs requires the browser shards everywhere but on a pull request', () => {
assertGateBehaviour(allJobs.get('viewerjs'), ['browser-workflows']);
});
test('Firefox/WebKit page workflows run only outside pull requests; coverage runs on every event; both for code changes only', () => {
test('Firefox/WebKit page workflows run only outside pull requests; coverage runs on every event', () => {
assert.match(allJobs.get('browser-workflows'), QUEUE_ONLY_IF);
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}`));
for (const id of ['frontend-coverage', 'frontend-coverage-merge']) {
assert.doesNotMatch(allJobs.get(id), /^ {4}if:/m, `${id} runs on every event`);
}
});
test('coverage runs as four shards that each upload their raw coverage', () => {
@@ -166,7 +144,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), ['changes', 'frontend-coverage']);
assert.deepEqual(needsOf(merge), ['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');
@@ -351,33 +329,16 @@ 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 or a docs or inert change and Linux 3.12-3.14 otherwise', () => {
test('the Python matrix is Linux 3.12 on a pull request and Linux 3.12-3.14 on every other event', () => {
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' \|\| 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'] });
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'] });
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:'));
@@ -413,14 +374,12 @@ 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; all for code changes only', () => {
test('real ComfyUI runs only outside pull requests; the other test.yml checks run on every event', () => {
const found = testJobs();
assert.match(found.get('comfyui'), QUEUE_ONLY_IF);
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`);
for (const id of ['test', 'coverage', 'lint', 'js-test']) {
assert.doesNotMatch(found.get(id), /^ {4}if:/m, `${id} runs on every event`);
}
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', () => {
@@ -432,7 +391,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, { queueOnly: ['comfyui'], codeOnly: ['coverage', 'lint', 'js-test'], always: ['test'] });
assertGateBehaviour(gate, ['comfyui']);
});
test('the CI workflows run on pull_request, merge_group and push without path filters', () => {
@@ -444,39 +403,7 @@ 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.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);
assert.doesNotMatch(jobs(readWorkflow('code-quality.yml')).get('security'), /^ {4}if:/m, 'bandit runs on every event');
});
test('every required check reports on a pull request and the gates carry the full matrix', () => {
-140
View File
@@ -1,140 +0,0 @@
#!/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:]))
-47
View File
@@ -1,47 +0,0 @@
"""ComfyUI's EXIF metadata records (WebP, AVIF, JPEG).
PNG keeps the workflow and the prompt in text chunks (``utils.png_text``).
The formats without text chunks carry the same records as EXIF strings:
``SaveAnimatedWEBP`` writes ``prompt:{json}`` to tag 0x0110, then
``workflow:{json}`` and every other ``extra_pnginfo`` key to 0x010F and down,
and the AVIF writer uses that layout too. Pillow answers those tags only
through ``getexif()``; ``image.info`` holds the raw EXIF blob, so reading it
as text found no metadata at all.
``exif_text`` returns the ``{key: json}`` shape of ``utils.png_text`` so a
caller reads either source the same way. Only a value shaped like a ComfyUI
record counts, a key and a colon followed by a JSON object, array or string;
a camera's ``Make`` or a ``DateTime`` is not metadata.
"""
import re
# A record's key: ``workflow``, ``prompt`` or an extra_pnginfo key.
_KEY = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
# What a record holds: the workflow and the prompt are objects, the pair
# records a list, a custom extra_pnginfo value may be a string. Numbers,
# dates and camera names start with anything else.
_STARTS = ("{", "[", '"')
def exif_text(image) -> dict:
"""ComfyUI's EXIF records of an opened image, or ``{}``.
The image stays usable and nothing is decoded but the EXIF block. Formats
whose records are text chunks (PNG) answer ``{}``; read those with
``utils.png_text.png_text`` first.
"""
try:
exif = image.getexif()
except Exception: # a broken EXIF block never fails a scan
return {}
records = {}
for value in exif.values():
if isinstance(value, bytes):
value = value.decode("utf-8", errors="replace")
if not isinstance(value, str):
continue
key, separator, payload = value.partition(":")
if separator and _KEY.match(key) and payload.lstrip()[:1] in _STARTS:
records[key] = payload
return records
+2 -2
View File
@@ -45,7 +45,7 @@ from .foreign_runs import (
store_foreign,
)
from .hashing import generate_prompt_hash
from .media_folders import in_skipped_folder, split_relative
from .media_folders import in_skipped_folder
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 split_relative(text)[:-1]
return text.replace("\\", "/").split("/")[:-1]
def process_new_image(self, image_path: str, prompt_snapshot=None):
"""Process a newly created image file for gallery integration.
+2 -6
View File
@@ -659,16 +659,12 @@ 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.
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.
"""
"""Split a safe relative POSIX media path; anything else is denied."""
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 and os.sep == "\\") or relative.startswith("/"):
if "\\" in relative or relative.startswith("/"):
raise CaptureDenied("Invalid file path")
parts = relative.split("/")
for part in parts:
+3 -21
View File
@@ -32,30 +32,12 @@ def is_skipped_folder(name: str) -> bool:
return name == PREVIEW_FOLDER or is_trash_folder(name)
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:
def in_trash_folder(relative: str) -> bool:
"""Whether a root-relative file path lies in a trash folder (#543).
Takes this server's separators (#646). Previews of it
(``thumbnails/.Trash-1000/...``) count.
Takes either separator. Previews of it (``thumbnails/.Trash-1000/...``) count.
"""
folders = split_relative(relative, pathmod)[:-1]
folders = relative.replace("\\", "/").split("/")[:-1]
return any(is_trash_folder(part) for part in folders)
+6 -8
View File
@@ -2,11 +2,11 @@
This module provides comprehensive metadata extraction capabilities for
ComfyUI-generated images. It can extract workflow information, prompt data, and
generation parameters from the text chunks of PNG images and the EXIF records
ComfyUI writes for WebP, AVIF and JPEG images.
generation parameters from PNG images that contain embedded ComfyUI metadata in
their text chunks.
The extractor supports:
- Complete workflow data extraction from PNG text chunks and EXIF records
- Complete workflow data extraction from PNG text chunks
- Text encoder node identification and analysis
- Generation parameter extraction (steps, cfg_scale, sampler, etc.)
- Basic file information fallback when metadata is unavailable
@@ -36,7 +36,6 @@ import json
from typing import Optional, Dict, Any
from PIL import Image
from .exif_text import exif_text
from .logging_config import get_logger
from .png_text import png_text
@@ -90,10 +89,9 @@ class ComfyUIMetadataExtractor:
# Add basic file information
metadata["file_info"] = self.get_file_info(image_path, image)
# ComfyUI writes PNG text chunks, read without decoding the
# pixels (#523). WebP (and AVIF, once collected: #652) carry
# the same records as EXIF text, so those images link too.
text = png_text(image) or exif_text(image)
# Extract ComfyUI-specific metadata from PNG text chunks,
# read without decoding the pixels (#523)
text = png_text(image)
if text:
# Look for ComfyUI workflow data
if "workflow" in text:
+12 -27
View File
@@ -5,12 +5,11 @@
* - 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" (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
* 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
* (`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.
* - Only the "permanent" mode unlinks a file from disk (via the apply job); library and trash modes leave the file intact.
* - Nothing here deletes a file: the server never unlinks one (it renames into the system trash or leaves it).
*/
import { createButton } from '../shared/toolkit/core.js';
import { closeWorkspaceDialog, openCloseOnlyReview, openContentDialog } from './workspace-dialogs.mjs';
@@ -27,7 +26,6 @@ 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.';
@@ -42,7 +40,6 @@ 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 };
@@ -114,9 +111,7 @@ 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.'
: mode === 'permanent'
? 'Files are removed from disk. Disk space is freed immediately.'
: 'Files stay on disk, hidden from Images.']);
: 'Files stay on disk, hidden from Images.']);
return rows;
}
@@ -127,7 +122,6 @@ 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);
@@ -135,16 +129,14 @@ export function deleteSentences(plan, mode) {
return sentences;
}
/** The primary's label: "Remove N images from the library", "Move N images to the trash", or "Permanently delete N from disk". */
/** The primary's label: "Remove N images from the library" or "Move N images to the trash". */
export function primaryLabel(mode, count) {
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`;
return mode === 'trash' ? `Move ${countOf(count, 'image')} to the trash` : `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 && modeCount(plan, 'permanent') === 0) return NONE_DELETABLE;
if (modeCount(plan, 'library') === 0 && modeCount(plan, 'trash') === 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)}).`;
@@ -167,31 +159,24 @@ 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.';
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 done = Number(mode === 'trash' ? counters.trashed : 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.`;
}
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 head = mode === 'trash' ? `Moved ${countOf(done, 'image')} to the trash.` : `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, plan) {
function modeGroup(onChange) {
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);
const choices = plan?.permanent_delete_supported ? MODES : MODES.filter(m => m.value !== 'permanent');
for (const choice of choices) {
for (const choice of MODES) {
const label = el('label');
const input = el('input');
Object.assign(input, {type: 'radio', name: 'image-delete-mode', value: choice.value, checked: false});
@@ -232,7 +217,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(); }, plan);
const group = modeGroup(value => { mode = value; render(); });
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.
+1 -3
View File
@@ -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, rootedFileAdapter } from './inspection-state.mjs';
import { createInspectionController } from './inspection-state.mjs';
import { mountSelectionBar } from './images-selection.mjs';
import { scrollToPageTop } from './sticky-chrome.mjs';
import { createPromptSender } from './prompt-sender.mjs';
@@ -374,8 +374,6 @@ 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). */
+1 -4
View File
@@ -31,12 +31,9 @@ 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 || backslashRefused(image) || /^[a-z]:/i.test(image.path) || /[\x00-\x1f\x7f]/.test(image.path) ||
typeof image.path !== 'string' || !image.path || image.path.includes('\\') || /^[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);
}
-2
View File
@@ -73,8 +73,6 @@ 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' };
}
+4 -9
View File
@@ -1,16 +1,11 @@
import {rootedFileAdapter} from './inspection-state.mjs';
/** 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. */
/** A viewer visits only the descriptors loaded by its opening query. */
export function createViewerSession({items, initialKey, onChange = () => {}, setTimer = setTimeout, clearTimer = clearTimeout, adapter = rootedFileAdapter}) {
const accepted = Array.isArray(items) ? items.filter(item => openable(adapter, item)) : [];
if (!accepted.length) throw new TypeError('A loaded media collection is required');
if (!Array.isArray(items) || !items.length) throw new TypeError('A loaded media collection is required');
const keys = new Set();
const loaded = Object.freeze(accepted.map(item => {
const loaded = Object.freeze(items.map(item => {
adapter.validate(item);
const key = adapter.key(item);
if (keys.has(key)) throw new TypeError('Duplicate viewer identity');
keys.add(key);