Compare commits

...
Author SHA1 Message Date
Vito Sansevero 45bb6f76f6 fix(viewer): a file the viewer refuses no longer stops it opening for every image (#646)
The viewer checked every loaded image before opening and threw on the first
identity it refused, such as a folder name holding a backslash. It now leaves
those files out of the arrow-through list, and clicking one shows its details
panel instead of the viewer.
2026-11-17 09:53:00 -08:00
Jon Tyler 4aa71c4026 Add permanent delete mode for images (Linux/BSD) (#643)
- Adds a "permanent" mode to the delete preview plan and apply job
  that unlinks files from disk (Linux/BSD only).
- Unlinks media files with os.remove; refused unlinks leave files intact.
- Flags permanent_delete_supported based on the Freedesktop backend.
- Frontend offers the mode only when the server supports it.
- Includes Python and JavaScript test coverage for the new mode.
- Update TESTING.md claims around the use of `unlink` to reflect this new mode.
2026-11-17 00:42:40 +00:00
Vito a695457cce fix: Windows dev machines: pinned files survive a default clone; four tests stop depending on the machine (#636) (#637)
* fix: a default Windows clone keeps pinned files byte for byte; LoRA test no longer depends on TEMP (#636)

Git for Windows converts text files to CRLF on checkout by default, so a
fresh clone failed npm run --prefix tools/vendor check with Viewer.js
drift. .gitattributes now marks the pinned Viewer.js, Toolkit and concept
stylesheet files as never converted, and a test holds that for every
tracked file under them. .gitattributes stays out of the Registry package.

test_preview_writes_nothing_and_makes_no_requests expected the full
settings path, which only holds when the temp folder is outside the home
folder. On Windows %TEMP% is under the profile, so the review showed
~\... and the test failed. It now pins the home folder beside the temp
root.

* fix(tests): the Built-in instructions test reads Python source with either line ending (#636)

In a default Windows clone py/tagging_defaults.py is checked out with CRLF,
so the test's search for the closing paren missed and JSON.parse failed on
a carriage return: 1453 of 1454 frontend tests passed. The test now
normalizes CRLF before it slices the source.

* fix(tests): two more Windows machine failures: killed test servers, nearby ComfyUI (#636)

On a Windows machine with a virtual environment, the tests that start
tests/browser/server.py failed their cleanup with WinError 32 on the
server's log file, 3 of 3 runs. The venv's python.exe is a launcher that
runs the real interpreter as a child; killing the launcher returns while
Windows is still ending that child. The temp folder is now removed by
remove_when_released, which waits until the files are released, up to
30 s. CI never saw it: its Windows job runs a plain interpreter.

The diagnostics tests that expect no output folder ran in the temp root,
so the fallback's ../../ComfyUI/output could reach a real ComfyUI next to
it. They now run two folders deep inside the temp folder.

* docs(testing): what a Windows development machine needs for the suite (#636)

* fix(tests): one import style in test_process_cleanup; the line-ending test ignores GIT_* (#636)

Code quality flagged unittest imported both ways. The line-ending test
shells out to git, which inside the pre-push hook would follow the
exported GIT_DIR; it now runs git without GIT_* variables, proved with
GIT_DIR and GIT_INDEX_FILE pointing at a decoy repository that stays
untouched.
2026-11-15 17:09:25 +00:00
Vito c9d2b9c66b ci: test only changes that can affect code (#639) (#640)
* ci: test only changes that can affect code (#639)

Each gating workflow starts with a change class job that sorts the
pull request, merge group or push by the files it touches
(tools/ci/change_class.py): inert (nothing reads them), docs (a Python
test reads them) or code (anything else and every case of doubt).

- inert: only the classifier and the two gates do work. The required
  py3.12 leg starts and skips its steps, because a skipped matrix job
  would never report that context.
- docs: the Python 3.12 suite runs as well; it holds the README tests.
- code: everything runs, as before.

The gates require the classifier to succeed and every job to do what
the class asks; an unknown class fails them. bandit has no gate, so it
runs unless the class is docs or inert. The required contexts are
unchanged. The pre-push hook skips the suite for an inert push.

* test(ci): keep the classifier tests out of a git hook's repository (#639)

Inside the pre-push hook git exports GIT_DIR and GIT_INDEX_FILE for the
repository being pushed. The test's own git calls inherited them and so
ran git init, add and commit against that repository instead of their
temp one. They now drop every GIT_ variable, and the tests run with
those variables pointing at another repository that must stay absent.

* test(ci): import unittest.mock one way

* fix(ci): find the pre-push command through PATH before running it

The pre-push wrapper ran its command with subprocess and a bare name.
On Windows the frontend hook's npm is npm.cmd, which subprocess does
not find without a PATH and PATHEXT lookup, so every non-inert push
failed with FileNotFoundError (Codex review). The wrapper now resolves
the program with shutil.which first, and says so when it is missing.
Reproduced and verified on Windows 11: before, FileNotFoundError; after,
npm --version runs.

* test(inspect): keep trying until a video is seen still starting at loadstart (#641)

A busy WebKit fired the viewer video's loadstart after it already had
HAVE_ENOUGH_DATA (merge-queue run 43732282629, readyState 4), so the
per-attempt readyState === 0 assertion failed although the settled path
behaved correctly. The three #483 tests now count the attempts that saw
the video still starting, run up to twice as many pages until one does,
and fail only if none did.
2026-11-15 17:03:10 +00:00
Vito 98ba01d670 Update Buy Me a Coffee username to 'veets' (#638) 2026-11-15 14:42:13 +00:00
30 changed files with 1202 additions and 113 deletions
+1
View File
@@ -19,3 +19,4 @@
/.flake8
/.pre-commit-config.yaml
/.gitignore
/.gitattributes
+7
View File
@@ -0,0 +1,7 @@
# Pinned files are compared byte for byte with their recorded hashes
# (npm run --prefix tools/vendor check). Git must never convert their line
# endings, which Git for Windows does by default (core.autocrlf=true, #636).
/web/lib/viewerjs/** -text
/web/js/shared/toolkit/** -text
/web/js/workspace/concept.css -text
/docs/concepts/workspace/style.css -text
+15
View File
@@ -0,0 +1,15 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: veets
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+29 -1
View File
@@ -17,11 +17,39 @@ concurrency:
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads
# them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The
# jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so
# the required context still reports. This workflow has no gate job, so the scan runs whenever the
# class is not "docs" or "inert": a classifier that fails or prints nothing means a full scan. The clone has every commit but no file contents (blob:none): the
# script only compares file names between the base and the head.
changes:
name: change class
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
class: ${{ steps.classify.outputs.class }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
filter: blob:none
persist-credentials: false
- name: Classify the changed files
id: classify
env:
EVENT_NAME: ${{ github.event_name }}
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }}
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
security:
name: bandit (high severity)
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
# ceil(1.5 x slowest of three green main runs) + 3, never under 5 (test.yml): runs 40257217665,
# 40254137380, 40240706583 took 23s / 16s / 23s -> 5 min.
# 40254137380, 40240706583 took 23s / 16s / 23s -> 5 min. change class (#639): 5 min, the floor.
timeout-minutes: 5
steps:
+67 -8
View File
@@ -35,26 +35,60 @@ env:
# perf budget 30s / 29s / 27s, black and flake8 39s / 37s / 39s,
# frontend modules 23s / 19s / 29s -> 5 min (the floor)
# all tests: a result check without setup, 5 min (the floor)
# change class (#639): a file-less checkout and one stdlib script, 5 min (the floor)
#
# Pull requests run a fast subset (#420): Python 3.12 on ubuntu-latest, coverage, lint and frontend
# modules. The merge queue (merge_group), pushes to main and manual runs add Python 3.13 and 3.14 on
# Linux and the real ComfyUI job. "all tests" is the required gate that holds the queue to that set.
# Windows runs in portability.yml (push to main, nightly, on demand) and never gate a merge.
jobs:
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads
# them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The
# jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so
# the required contexts still report; "all tests" fails unless this job succeeded and each
# job did what the class asks. The clone has every commit but no file contents (blob:none): the
# script only compares file names between the base and the head.
changes:
name: change class
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
class: ${{ steps.classify.outputs.class }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
filter: blob:none
persist-credentials: false
- name: Classify the changed files
id: classify
env:
EVENT_NAME: ${{ github.event_name }}
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }}
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
test:
name: py${{ matrix.python-version }} on ${{ matrix.os }}
# A skipped matrix job reports under its unexpanded name, which would leave the required context
# "py3.12 on ubuntu-latest" waiting for ever. So this job always runs: a docs change gets the 3.12
# leg only, and for an inert change the leg starts and its steps are skipped (#639).
needs: changes
if: ${{ !cancelled() }}
runs-on: ${{ matrix.os }}
timeout-minutes: 27
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
python-version: ${{ github.event_name == 'pull_request' && fromJSON('["3.12"]') || fromJSON('["3.12", "3.13", "3.14"]') }}
python-version: ${{ (github.event_name == 'pull_request' || needs.changes.outputs.class == 'docs' || needs.changes.outputs.class == 'inert') && fromJSON('["3.12"]') || fromJSON('["3.12", "3.13", "3.14"]') }}
steps:
- uses: actions/checkout@v7
if: needs.changes.outputs.class != 'inert'
- name: Set up Python ${{ matrix.python-version }}
if: needs.changes.outputs.class != 'inert'
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
@@ -62,18 +96,26 @@ jobs:
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
if: needs.changes.outputs.class != 'inert'
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Run tests
if: needs.changes.outputs.class != 'inert'
run: python -m tests.run_suite -v
- name: Nothing to test
if: needs.changes.outputs.class == 'inert'
run: echo "Only inert files changed (tools/ci/change_class.py); no test can be affected."
comfyui:
name: real ComfyUI compatibility
# Merge queue, main and manual runs only. A job skipped by its condition reports Success, so this
# required context never blocks a pull request; "all tests" fails if it is skipped anywhere else.
if: github.event_name != 'pull_request'
# required context never blocks a pull request; "all tests" fails if it is skipped anywhere else
# for a code change. Docs and inert changes skip it everywhere (#639).
needs: changes
if: ${{ !cancelled() && github.event_name != 'pull_request' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
# Chromium and its system libraries come from the pinned Playwright image (tag = @playwright/test in
# tools/vendor/package-lock.json; tests/vendor/browser-image.test.mjs checks it). The runner install
@@ -174,6 +216,8 @@ jobs:
coverage:
name: coverage gate (85%)
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
@@ -201,7 +245,8 @@ jobs:
# Shared-runner timing varies, so it never gates a pull request: it runs on
# each push to main and on demand. A red run on main means fix the code.
name: perf budget
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
needs: changes
if: ${{ !cancelled() && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
@@ -225,6 +270,8 @@ jobs:
lint:
name: black and flake8
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
@@ -241,6 +288,8 @@ jobs:
js-test:
name: frontend modules
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
@@ -268,9 +317,11 @@ jobs:
# The required context "all tests". A dropped matrix leg never reports a check at all, so the eight
# legs that pull requests skip cannot be required by name; this gate requires them instead. Every
# job must succeed; real ComfyUI must be skipped on a pull request and succeed on every other event.
# For a docs or inert change (#639) the test matrix must still succeed and every other job must be
# skipped. The classifier itself must succeed, and a class it does not print fails the gate.
all-tests:
name: all tests
needs: [test, comfyui, coverage, lint, js-test]
needs: [changes, test, comfyui, coverage, lint, js-test]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
@@ -278,18 +329,26 @@ jobs:
- name: Require every test job for this event
env:
EVENT_NAME: ${{ github.event_name }}
CHANGES_RESULT: ${{ needs.changes.result }}
CHANGE_CLASS: ${{ needs.changes.outputs.class }}
TEST_RESULT: ${{ needs.test.result }}
COMFYUI_RESULT: ${{ needs.comfyui.result }}
COVERAGE_RESULT: ${{ needs.coverage.result }}
LINT_RESULT: ${{ needs.lint.result }}
JS_RESULT: ${{ needs.js-test.result }}
run: |
queue_only=success
echo "change class: $CHANGE_CLASS (classifier: $CHANGES_RESULT)"
test "$CHANGES_RESULT" = success
case "$CHANGE_CLASS" in
code) code_only=success; queue_only=success ;;
docs|inert) code_only=skipped; queue_only=skipped ;;
*) echo "::error::unknown change class"; exit 1 ;;
esac
if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi
echo "event: $EVENT_NAME (real ComfyUI must be $queue_only)"
echo "event: $EVENT_NAME (real ComfyUI must be $queue_only; coverage, lint and js-test must be $code_only)"
echo "test matrix: $TEST_RESULT"
echo "comfyui: $COMFYUI_RESULT"
echo "coverage: $COVERAGE_RESULT"
echo "lint: $LINT_RESULT"
echo "js-test: $JS_RESULT"
test "$TEST_RESULT" = success && test "$COVERAGE_RESULT" = success && test "$LINT_RESULT" = success && test "$JS_RESULT" = success && test "$COMFYUI_RESULT" = "$queue_only"
test "$TEST_RESULT" = success && test "$COVERAGE_RESULT" = "$code_only" && test "$LINT_RESULT" = "$code_only" && test "$JS_RESULT" = "$code_only" && test "$COMFYUI_RESULT" = "$queue_only"
+49 -7
View File
@@ -45,9 +45,39 @@ concurrency:
# test (PR #560 shard 2/3: 814 passed in 17.9m; queue run 41206495451 shard 1/3: 827 passed; PR #564
# shard 2/3 twice), against recent green shards of 11m-17m. Coverage now runs in four shards with the
# limits unchanged; the per-shard times are re-measured after three green main runs.
# change class (#639): a file-less checkout and one stdlib script, 5 min (the floor of test.yml).
jobs:
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads
# them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The
# jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so
# the required contexts still report; "viewerjs" fails unless this job succeeded and each
# job did what the class asks. The clone has every commit but no file contents (blob:none): the
# script only compares file names between the base and the head.
changes:
name: change class
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
class: ${{ steps.classify.outputs.class }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
filter: blob:none
persist-credentials: false
- name: Classify the changed files
id: classify
env:
EVENT_NAME: ${{ github.event_name }}
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }}
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
frontend-coverage:
name: frontend coverage (shard ${{ matrix.shard }}/4)
# Code changes only (#639): no browser test reads a docs or inert file.
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
@@ -117,7 +147,8 @@ jobs:
frontend-coverage-merge:
name: frontend coverage (merge)
needs: frontend-coverage
needs: [changes, frontend-coverage]
if: ${{ !cancelled() && needs.frontend-coverage.result == 'success' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
# Same image as the shards: the raw files name sources by the container's workspace path.
container:
@@ -186,7 +217,9 @@ jobs:
browser-workflows:
name: page workflows (${{ matrix.browser }}, shard ${{ matrix.shard }}/3)
# Merge queue, main and manual runs only (#420); pull requests run the Chromium/touch coverage shards.
if: github.event_name != 'pull_request'
# Code changes only (#639).
needs: changes
if: ${{ !cancelled() && github.event_name != 'pull_request' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
@@ -245,9 +278,10 @@ jobs:
# Branch protection requires the exact context "viewerjs". This job keeps that
# name and fails unless every coverage shard and the coverage merge succeeded and
# the browser shards succeeded, or, on a pull request only, were skipped (#420).
# Any failure, cancellation or other skip fails it.
# Any failure, cancellation or other skip fails it. For a docs or inert change (#639) all three
# must be skipped. The classifier itself must succeed, and a class it does not print fails the gate.
viewerjs:
needs: [frontend-coverage, frontend-coverage-merge, browser-workflows]
needs: [changes, frontend-coverage, frontend-coverage-merge, browser-workflows]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
@@ -255,14 +289,22 @@ jobs:
- name: Require every frontend job to succeed
env:
EVENT_NAME: ${{ github.event_name }}
CHANGES_RESULT: ${{ needs.changes.result }}
CHANGE_CLASS: ${{ needs.changes.outputs.class }}
COVERAGE_RESULT: ${{ needs.frontend-coverage.result }}
MERGE_RESULT: ${{ needs.frontend-coverage-merge.result }}
WORKFLOWS_RESULT: ${{ needs.browser-workflows.result }}
run: |
queue_only=success
echo "change class: $CHANGE_CLASS (classifier: $CHANGES_RESULT)"
test "$CHANGES_RESULT" = success
case "$CHANGE_CLASS" in
code) code_only=success; queue_only=success ;;
docs|inert) code_only=skipped; queue_only=skipped ;;
*) echo "::error::unknown change class"; exit 1 ;;
esac
if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi
echo "event: $EVENT_NAME (browser-workflows must be $queue_only)"
echo "event: $EVENT_NAME (browser-workflows must be $queue_only; coverage and its merge must be $code_only)"
echo "frontend-coverage: $COVERAGE_RESULT"
echo "frontend-coverage-merge: $MERGE_RESULT"
echo "browser-workflows: $WORKFLOWS_RESULT"
test "$COVERAGE_RESULT" = success && test "$MERGE_RESULT" = success && test "$WORKFLOWS_RESULT" = "$queue_only"
test "$COVERAGE_RESULT" = "$code_only" && test "$MERGE_RESULT" = "$code_only" && test "$WORKFLOWS_RESULT" = "$queue_only"
+2 -1
View File
@@ -22,9 +22,10 @@ repos:
types: [python]
exclude: ^(tests/|reference/)
# Skipped when the pushed commits only change inert files (tools/ci/change_class.py, #639).
- id: tests
name: tests
entry: python -m tests.run_suite -q
entry: python tools/ci/change_class.py --unless-inert python -m tests.run_suite -q
language: system
pass_filenames: false
stages: [pre-push]
+47 -1
View File
@@ -277,6 +277,22 @@ the process exits non-zero.
A test that waits on a fixed busy timeout, a network name (`\\server\share`:
use `\\localhost\<missing share>`) or a default TLS context (it reads the
Windows certificate store) costs seconds there; the slowest list shows it.
- On a Windows development machine (#636), give the suite a short `TEMP`
(for example `C:\t`) or turn long paths on
(`HKLM\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled` = 1).
Under the default `C:\Users\<user>\AppData\Local\Temp`, the visual fixture's
182-character file name passes Windows' 260-character limit once a test
nests its own temp folder, and the chronological-history reset answers 500.
Three other differences from the CI runner are handled in the tests:
a virtual environment's `python.exe` is a launcher that runs the real
interpreter as a child, so a test that kills a server it started removes its
folder with `tests/process_cleanup.py`'s `remove_when_released`, which waits
for that child to end (a handle the test process itself still holds never
releases, so the bound still fails it); Git for Windows checks text files out
with CRLF, so `.gitattributes` keeps the pinned vendored files byte for byte
and a test that parses source text normalizes line endings; and a test that
expects no ComfyUI nearby works two folders inside its temp folder, because
the output-folder fallback looks two levels up.
Every job in `test.yml`, `code-quality.yml`, `viewerjs-check.yml` and
`portability.yml` has `timeout-minutes` (`tests/vendor/ci-workflow.test.mjs`
@@ -742,6 +758,33 @@ is still a failure: fix it at its cause, not by rerunning, and have every one
green before the workspace cutover (#334). `tests/vendor/ci-workflow.test.mjs` pins the
event split and runs both gate scripts for each event.
### Only changes that can affect code are tested (#639)
The table above is for a code change. Each of the three workflows starts with a
`change class` job that runs `tools/ci/change_class.py` over the files the pull
request, merge group or push touches, and the other jobs follow its answer:
| Class | Files (allowlists in the script) | What runs |
| --- | --- | --- |
| `inert` | `.github/FUNDING.yml`, `SECURITY.md`, `images/`, `.github/ISSUE_TEMPLATE/` | `change class` and the two gates. `py3.12 on ubuntu-latest` starts and skips its steps, because a skipped matrix job would never report that required context. |
| `docs` | `README.md`, `README-legacy.md`, `assets/readme/`, `assets/brand/` (may include inert files) | The above plus the real `py3.12 on ubuntu-latest` suite, which holds the tests that read them (`tests/test_brand_assets.py`, `tests/test_package_contents.py`). |
| `code` | Anything else | Everything in the table above. |
A file on no list is code, and so is every case of doubt: no changed files, a
manual run, a range git cannot read. `docs/` is code, because the browser suite
compares production against `docs/concepts/workspace/`; `TESTING.md` is code,
because the tooling tests read its tables. Before adding a file to a list,
check that no test and no shipped code opens it.
The gates enforce the class: for `docs` and `inert` they require the classifier
to have succeeded, the Python matrix to have succeeded and every other job to
have been skipped; a class the script does not print fails them. `bandit` has no
gate, so it runs unless the class is `docs` or `inert`, which means a failed
classifier gets a full scan. The required contexts do not change.
The pre-push hook uses the same script: it skips the Python suite when the
pushed commits are `inert` and runs it otherwise.
## Required merge checks
`.github/branch-protection.json` records the required checks:
@@ -2500,7 +2543,10 @@ npm run --prefix tools/vendor test:workflows -- workspace-collections.spec.mjs c
Images › Delete… removes the checked images (or "Select all N matching", at most 500, or
the one file of the side panel or the viewer) from the library, and on request moves the
files to the system trash. **No code path unlinks or overwrites a media file.**
files to the system trash or (Linux/BSD servers only) deletes them permanently. **The only
code path that unlinks or overwrites a media file is the permanent-delete apply job.** Library
and trash modes never unlink media files; permanent-delete unlinks files only via the apply
job after `file_check` confirms containment and non-symlink, and the review step never unlinks.
- **D159** (#480, maintainer request): the concept's "Remove links…" (`danger`, app.js
432) returns as **Delete…** in the same place (after Export metadata, before Clear), and
+71 -18
View File
@@ -1,9 +1,9 @@
"""Delete selected images: remove them from the library, or trash them (#480).
"""Delete images: remove from library, trash, or permanently delete.
``POST /prompt_manager/images/delete/preview {items | filter}`` reviews the
selection for both modes at once and answers a reviewed plan (the System ›
selection for all modes at once and answers a reviewed plan (the System ›
Maintenance contract, ``py/api/maintenance.py``): the token, the counts of
the records each file loses, the refused files with a coded reason (both
the records each file loses, the refused files with a coded reason (all
modes, and the trash-only ones), the prompts that lose their last image and
the safety backup. It writes nothing. ``items`` are Images listing identities
(at most 500); ``filter`` is "Select all N matching". Each target is matched
@@ -19,12 +19,16 @@ again (containment and fingerprint) and
in one transaction; the file stays on disk, hidden;
- ``mode="trash"``: it is moved to the trash first (``utils/trash.py``); a
refused move leaves the file and its records alone; after a move its
records are deleted.
records are deleted;
- ``mode="permanent"``: it is unlinked from disk with ``os.remove``; a refused
unlink leaves the file and its records alone; after removal its records are
deleted. This mode is Linux/BSD only.
No path here unlinks a media file. A failed records write stops the job; the
files after it are not attempted.
Only ``mode="permanent"`` unlinks a media file from disk. A failed records
write stops the job; the files after it are not attempted.
"""
import errno
import hashlib
import json
import os
@@ -59,10 +63,11 @@ except ImportError:
from utils.media_folders import is_trash_folder
IMAGE_DELETE = "delete_images"
MODES = ("library", "trash")
MODES = ("library", "trash", "permanent")
TITLES = {
"library": "Delete images (remove from the library)",
"trash": "Delete images (move to the trash)",
"permanent": "Delete images (permanently delete from disk)",
}
MAX_DETAIL_ROWS = 50
# The system moved the file but its place in a trash could not be shown (#499).
@@ -87,8 +92,8 @@ REASONS = {
trash.LOCKED: "The file is open in another program. Close it and try again.",
trash.FAILED: "The file could not be moved to the trash.",
trash.NO_PERMISSION: (
"PromptManager isn't allowed to move this file (no permission, or it is "
"locked in Finder)."
"PromptManager isn't allowed to remove this file (no permission, or it is "
"locked)."
),
trash.CLOUD_SYNC: (
"Files in iCloud Drive or a cloud-synced folder can't be moved to the "
@@ -114,6 +119,16 @@ SOURCES_CHANGED = "The sources changed since the review; nothing was changed."
RECORDS_FAILED = "The image records could not be removed; the job stopped."
def _permanent_delete_code(error: OSError) -> str:
"""Translate a removal ``OSError`` into a permanent-delete refusal code."""
code = error.errno if error.errno else None
if code in (errno.EACCES, errno.EPERM, errno.EROFS):
return trash.NO_PERMISSION
if code in (errno.ENETUNREACH, errno.ENETRESET, errno.EHOSTUNREACH):
return trash.NETWORK
return trash.LOCKED
def lexical_problem(relative: str) -> str | None:
"""The refusal code a root-relative POSIX path earns before any file access."""
parts = relative.split("/")
@@ -275,17 +290,23 @@ class ImageDeleteMixin:
acted.append(target)
counted = db.count_removal_records([t["removal"] for t in acted])
library_count = len(acted)
permanent_supported = isinstance(trash.BACKEND, trash.FreedesktopBackend)
public = {
"operation": IMAGE_DELETE,
"scope": {"count": library_count, "label": "images"},
"library": {"count": library_count},
"trash": {"count": library_count - len(trash_refused)},
"permanent": {"count": library_count},
"protected": {"count": len(refused), "reasons": []},
"refused": _summary(refused),
"trash_refused": _summary(trash_refused),
"records": counted["records"],
"orphaned_prompts": counted["orphaned_prompts"],
"media": {"deletes_files": False, "label": "Chosen in the review"},
"media": {
"deletes_files": permanent_supported,
"label": "Chosen in the review",
},
"permanent_delete_supported": permanent_supported,
"details": [],
}
return {"targets": acted, "public": public}
@@ -341,7 +362,11 @@ class ImageDeleteMixin:
async def _delete_images(self, job, db, targets, mode, backup):
job.update(total=len(targets), status_line=TITLES[mode])
roots = [str(root) for root in self._get_all_output_dirs()]
done_group = "trashed" if mode == "trash" else "removed"
done_group = (
"trashed"
if mode == "trash"
else ("deleted" if mode == "permanent" else "removed")
)
changed, failed = 0, None
for done, target in enumerate(targets, start=1):
if failed:
@@ -366,17 +391,26 @@ class ImageDeleteMixin:
)
elif group == done_group:
changed += 1
detail = (
f"Moved to the {label}" if label else "Removed from the library"
)
if mode == "trash":
detail = (
f"Moved to the {label}" if label else "Removed from the library"
)
elif mode == "permanent":
detail = "Deleted from disk"
else:
detail = "Removed from the library"
self._record_delete(job, group, target, None, detail)
else:
self._record_delete(job, group, target, code)
job.update(processed=done, progress=int(done / len(targets) * 100))
if changed:
self.invalidate_gallery_cache()
verb = "Moved" if mode == "trash" else "Removed"
where = "to the trash" if mode == "trash" else "from the library"
if mode == "trash":
verb, where = "Moved", "to the trash"
elif mode == "permanent":
verb, where = "Permanently deleted", "from disk"
else:
verb, where = "Removed", "from the library"
line = f"{verb} {changed:,} of {len(targets):,} images {where}"
job.log_line(line)
job.update(progress=100, status_line=f"{line} · {backup_note(backup)}")
@@ -398,7 +432,7 @@ class ImageDeleteMixin:
"code": code,
"detail": text,
}
mark = {"removed": "-", "trashed": "-"}.get(group, "=")
mark = {"removed": "-", "trashed": "-", "deleted": "-"}.get(group, "=")
job.record(
group, row, f"{mark} {target['root_label']}/{target['rel']} · {text}"
)
@@ -437,6 +471,21 @@ class ImageDeleteMixin:
)
return "errors", TRASH_UNCONFIRMED, None
mark = None
elif mode == "permanent":
try:
os.remove(target["abs"])
except OSError as error:
if error.errno == errno.ENOENT:
pass
else:
code = _permanent_delete_code(error)
self.logger.info(
"Not permanently deleted (%s): %s",
code,
target["rel"],
)
return "not_changed", code, None
mark = None
else:
mark = (target["size"], target["mtime_ns"])
try:
@@ -445,7 +494,11 @@ class ImageDeleteMixin:
self.logger.exception("Removing an image's records failed")
return "errors", None, label
_remove_thumbnail(Path(target["root"]), Path(target["rel"]), self.logger)
return ("trashed" if mode == "trash" else "removed"), None, label
if mode == "trash":
return "trashed", None, label
if mode == "permanent":
return "deleted", None, label
return "removed", None, label
# ── the workspace listing ─────────────────────────────────────────
+1 -1
View File
@@ -127,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", "not_changed", "errors")
IMAGE_DELETE_GROUP_NAMES = ("trashed", "removed", "deleted", "not_changed", "errors")
# The System health check (py/api/system.py): a read-only ``read`` job with
# no file outcomes, so it may run beside a scan.
HEALTH_JOB_KIND = "health"
+19 -7
View File
@@ -648,7 +648,10 @@ test('a video replaced while still starting is reset once it settles', async ({
// page (TESTING.md D62), so it stays in place, inert and still playing its URL, with the new preview after it.
// Once it reports metadata or an error it is paused, loses its src, is reset (load() with no src, which frees its
// decoder) and leaves the page, and only then is its URL revoked. Fresh pages share one browser process.
for (let attempt = 0; attempt < 15; attempt++) {
// A busy WebKit can fire `loadstart` after the video already has data (#641, run 43732282629: readyState 4), so
// keep going until at least one page saw it still starting.
let startingSeen = 0;
for (let attempt = 0; attempt < 15 || (startingSeen === 0 && attempt < 30); attempt++) {
const page = await context.newPage();
try {
if (attempt === 0) await startCoverage(page, browserName);
@@ -687,11 +690,11 @@ test('a video replaced while still starting is reset once it settles', async ({
await choose(page, localFixture('core-tags.webm', 'video/webm'));
await expect(preview(page).locator('img.local-file-preview')).toBeVisible({ timeout: 8000 });
await expect(preview(page).locator('video')).toHaveCount(0);
// Replaced while starting (always so at `loadstart` itself): kept in place and untouched. A video that had
// Replaced while starting (usually so at `loadstart` itself): kept in place and untouched. A video that had
// settled is released at once. Either way it is reset once, and its URL goes last.
await expect.poll(() => page.evaluate(() => window.__starting.revoked ?? null)).toEqual({ src: false, connected: false, resets: 1 });
const { readyState, replaced } = await page.evaluate(() => ({ readyState: window.__starting.readyState, replaced: window.__starting.replaced }));
if (attempt % 5 === 0) expect(readyState).toBe(0);
if (readyState === 0) startingSeen++;
expect(replaced).toEqual(readyState === 0 ? { connected: true, src: true, inert: true, resets: 0 } : { connected: false, src: false, inert: false, resets: 1 });
expect(await page.evaluate(() => window.__starting.node.__resets)).toBe(1);
// The page still answers.
@@ -702,6 +705,7 @@ test('a video replaced while still starting is reset once it settles', async ({
await page.close();
}
}
expect(startingSeen, 'no page saw the video still starting at its loadstart').toBeGreaterThan(0);
});
test('a new selection while the viewer\'s own video is still starting leaves it until it settles (#483)', async ({ context, browserName }) => {
@@ -710,7 +714,10 @@ test('a new selection while the viewer\'s own video is still starting leaves it
// selection from that video's own `loadstart` (readyState HAVE_NOTHING), or a few milliseconds after it, must not
// reset it or take it off the page while it starts (WebKit, GStreamer: TESTING.md D62; merge-queue run
// 40903238387). The viewer stays open until it reports metadata or an error, then closes; the URL goes last.
for (let attempt = 0; attempt < 10; attempt++) {
// A busy WebKit can fire `loadstart` after the video already has data (#641, run 43732282629: readyState 4), so
// keep going until at least one page saw it still starting.
let startingSeen = 0;
for (let attempt = 0; attempt < 10 || (startingSeen === 0 && attempt < 20); attempt++) {
const page = await context.newPage();
try {
if (attempt === 0) await startCoverage(page, browserName);
@@ -750,7 +757,7 @@ test('a new selection while the viewer\'s own video is still starting leaves it
await expect(preview(page).locator('img.local-file-preview')).toBeVisible({ timeout: 8000 });
await expect.poll(() => page.evaluate(() => window.__starting?.revoked ?? null)).toEqual({ src: false, connected: false, resets: 1 });
const { readyState, replaced } = await page.evaluate(() => ({ readyState: window.__starting.readyState, replaced: window.__starting.replaced }));
if (attempt % 5 === 0) expect(readyState).toBe(0);
if (readyState === 0) startingSeen++;
// Starting when replaced: still on the page with its URL, never reset; settled: released at once.
expect(replaced).toEqual(readyState === 0 ? { connected: true, src: true, resets: 0 } : { connected: false, src: false, resets: 1 });
expect(await page.evaluate(() => window.__starting.node.__resets)).toBe(1);
@@ -764,6 +771,7 @@ test('a new selection while the viewer\'s own video is still starting leaves it
await page.close();
}
}
expect(startingSeen, 'no page saw the video still starting at its loadstart').toBeGreaterThan(0);
});
/** #483: holds the viewer's video in HAVE_NOTHING (its `loadedmetadata` never fires) so a hold can be driven by hand. */
@@ -850,7 +858,10 @@ test('leaving for another route while a video starts waits for it to settle', as
// A WebKit (GStreamer) video detached before its pipeline had started deadlocked the page (TESTING.md D62); a
// route change detaches the whole page, so the shell renders the next route once the video reports metadata or an
// error. The route changes from the video's own `loadstart`, or a few milliseconds after it.
for (let attempt = 0; attempt < 15; attempt++) {
// A busy WebKit can fire `loadstart` after the video already has data (#641, run 43732282629: readyState 4), so
// keep going until at least one page saw it still starting.
let startingSeen = 0;
for (let attempt = 0; attempt < 15 || (startingSeen === 0 && attempt < 30); attempt++) {
const page = await context.newPage();
try {
if (attempt === 0) await startCoverage(page, browserName);
@@ -878,7 +889,7 @@ test('leaving for another route while a video starts waits for it to settle', as
await choose(page, localFixture('core-tags.webm', 'video/webm'));
await expect(main(page).getByRole('heading', { level: 1, name: 'Overview', exact: true })).toBeVisible({ timeout: 8000 });
const { readyState, reset } = await page.evaluate(() => ({ readyState: window.__starting.readyState, reset: window.__starting.reset }));
if (attempt % 5 === 0) expect(readyState).toBe(0);
if (readyState === 0) startingSeen++;
// The video was reset and left the page only once it had settled.
expect(reset.readyState >= 1 || reset.failed).toBe(true);
expect(reset.connected).toBe(true);
@@ -891,6 +902,7 @@ test('leaving for another route while a video starts waits for it to settle', as
await page.close();
}
}
expect(startingSeen, 'no page saw the video still starting at its loadstart').toBeGreaterThan(0);
});
test('closing the viewer on a video that just started never blocks the page', async ({ context, browserName }) => {
@@ -311,3 +311,42 @@ test('on a video the image keys and Space do nothing, as the toolbar disables th
await page.evaluate(() => new Promise(requestAnimationFrame));
await expect(viewer(page)).not.toHaveClass(/\bviewer-fullscreen\b/);
});
/** #646: the listing carries one file whose folder name holds a backslash, as a Windows-style prefix makes on Linux. */
async function withBackslashFile(page) {
await page.route(/\/prompt_manager\/images\/output\?/, async route => {
const response = await route.fetch(), body = await response.json();
if (body.images?.length > 1) {
const copy = body.images[1];
body.images.splice(1, 0, {...copy, path: `model.safetensors\\2026-11-17/${copy.filename}`, relative_path: `model.safetensors\\2026-11-17/${copy.filename}`});
}
await route.fulfill({response, json: body});
});
}
test('a file the viewer refuses is left out, and the others still open (#646)', async ({ page }) => {
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await withBackslashFile(page);
await page.setViewportSize({ width: 1600, height: 1100 });
await openProduction(page, 'images', 'dark');
const cards = await page.locator(CARDS).count();
await page.locator(CARDS).first().locator('.image-open').click();
await expect(position(page)).toContainText(`1 of ${cards - 1}`);
await page.keyboard.press('ArrowRight');
await expect(position(page)).toContainText('2 of ');
await expect(viewer(page).locator('#viewer-title')).not.toContainText('model.safetensors');
expect(errors).toEqual([]);
});
test('the refused file itself opens its details instead of the viewer (#646)', async ({ page }) => {
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await withBackslashFile(page);
await page.setViewportSize({ width: 1600, height: 1100 });
await openProduction(page, 'images', 'dark');
await page.locator(`${CARDS}[data-image-key*="model.safetensors"] .image-open`).click();
await expect(page.getByRole('complementary', {name: 'Selected image details'}).getByRole('alert')).toHaveText('Could not read prompts from this file.');
await expect(viewer(page)).toHaveCount(0);
expect(errors).toEqual([]);
});
@@ -1033,7 +1033,9 @@ test('the bulk options pick and reset like the Tag image dialog (D204)', async (
test('the client Built-in copy equals the server DEFAULT_TAG_TEMPLATE (#431)', async () => {
const { BUILTIN_INSTRUCTIONS } = await load();
const source = require('node:fs').readFileSync(require('node:path').join(__dirname, '../../py/tagging_defaults.py'), 'utf8');
// A Windows checkout may hold the file with CRLF line endings (#636).
const source = require('node:fs').readFileSync(require('node:path').join(__dirname, '../../py/tagging_defaults.py'), 'utf8')
.replace(/\r\n/g, '\n');
const block = source.slice(source.indexOf('DEFAULT_TAG_TEMPLATE = ('), source.indexOf('\n)\n', source.indexOf('DEFAULT_TAG_TEMPLATE = (')));
const text = [...block.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map(([, part]) => JSON.parse(`"${part}"`)).join('');
assert.ok(text.length > 100);
+32 -1
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']);
assert.deepEqual(MODES.map(mode => mode.label), ['Remove from the library only', 'Also move the files to the trash', 'Permanently delete']);
});
test('library rows: scope, refusals, links, details, backup and media', () => {
@@ -149,3 +149,34 @@ test('apply refuses to send a delete without an explicit mode', async () => {
await assert.rejects(applyDelete({ api, store: null, plan: plan(), mode, notify: () => {} }), TypeError);
}
});
test('permanent rows: scope and media line', () => {
const { deleteRows } = module();
const rows = Object.fromEntries(deleteRows(plan({ permanent: { count: 3 } }), 'permanent'));
assert.equal(rows.Scope, '3 images');
assert.equal(rows['Media on disk'], 'Files are removed from disk. Disk space is freed immediately.');
});
test('permanent sentences', () => {
const { deleteSentences, SENTENCES } = module();
assert.deepEqual(deleteSentences(plan(), 'permanent'), [SENTENCES.permanent]);
});
test('permanent primary label and close-only reason', () => {
const { primaryLabel, closeOnlyReason } = module();
assert.equal(primaryLabel('permanent', 2), 'Permanently delete 2 images from disk');
assert.equal(closeOnlyReason(plan({ library: { count: 0 }, trash: { count: 0 }, permanent: { count: 0 } })), 'None of the selected images can be deleted.');
assert.equal(closeOnlyReason(plan({ library: { count: 3 } })), null);
});
test('permanent outcome toast', () => {
const { outcomeToast } = module();
assert.equal(outcomeToast({ scope: { mode: 'permanent' }, counters: { deleted: 3, not_changed: 0 }, total: 3 }),
'Permanently deleted 3 images from disk.');
assert.equal(outcomeToast({ scope: { mode: 'permanent' }, counters: { deleted: 2, not_changed: 1 }, total: 3 }),
'Permanently deleted 2 images from disk. 1 was not changed (see Activity).');
assert.equal(outcomeToast({ scope: { mode: 'permanent', failure: 'records-failed' }, counters: { deleted: 1 }, total: 4 }),
'Stopped after 1 of 4 images; the rest were not changed. See Activity.');
});
+13
View File
@@ -38,6 +38,19 @@ test('viewer rejects empty duplicate or unknown identity', () => {
assert.equal(view.state.index, 0); view.dispose();
});
test('viewer leaves out an identity it refuses instead of refusing to open (#646)', () => {
const items = entries().slice(0, 3);
items.splice(1, 0, {...items[1], path: 'model.safetensors\\2026-11-17/x.png', filename: 'x.png'});
const view = session({items, initialKey: '0:folder/0.png'});
assert.deepEqual(view.state, {key:'0:folder/0.png',index:0,total:3,phase:'stopped',requested:false,mediaReady:false});
view.navigate(1); assert.equal(view.state.key, '1:folder/1.png');
view.navigate(1); assert.equal(view.state.key, '0:folder/2.png');
view.dispose();
// The refused file itself is not in the viewer, and a collection of refused files has nothing to open.
assert.throws(() => session({items, initialKey: '1:model.safetensors\\2026-11-17/x.png'}), TypeError);
assert.throws(() => session({items: [items[1]], initialKey: '0:folder/0.png'}), TypeError);
});
test('viewer ignores stale readiness after navigation and disposal', () => {
let calls = 0;
const view = session({items:entries(),initialKey:'0:folder/0.png',onChange:() => calls++,
+29
View File
@@ -0,0 +1,29 @@
"""Remove a folder that a killed test server may still hold for a moment (#636).
On Windows a virtual environment's ``python.exe`` is a launcher: it starts
the real interpreter as a child process and ends it with itself. Killing the
launcher returns at once, while Windows is still ending that child, which
still has its log file open, so removing the folder at that moment fails with
WinError 32. ``remove_when_released`` waits until the folder can be removed,
up to a bound, and raises the last error after it.
"""
import shutil
import time
RELEASE_TIMEOUT_S = 30
POLL_S = 0.05
def remove_when_released(path: str, timeout: float = RELEASE_TIMEOUT_S) -> None:
deadline = time.monotonic() + timeout
while True:
try:
shutil.rmtree(path)
return
except FileNotFoundError:
return
except PermissionError:
if time.monotonic() >= deadline:
raise
time.sleep(POLL_S)
+10 -5
View File
@@ -17,6 +17,11 @@ 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
@@ -25,12 +30,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.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.tmp = tempfile.mkdtemp()
self.addCleanup(remove_when_released, self.tmp)
def start(self, *extra):
env = {**os.environ, "TMPDIR": self.tmp.name}
env.update(TEMP=self.tmp.name, TMP=self.tmp.name)
env = {**os.environ, "TMPDIR": self.tmp}
env.update(TEMP=self.tmp, TMP=self.tmp)
process = subprocess.Popen(
[sys.executable, "-m", "tests.browser.server", "--port", "0", *extra],
cwd=REPO_ROOT,
@@ -65,7 +70,7 @@ class BrowserServerCase(unittest.TestCase):
time.sleep(0.1)
def roots(self):
return sorted(path.name for path in Path(self.tmp.name).glob("pm-browser-*"))
return sorted(path.name for path in Path(self.tmp).glob("pm-browser-*"))
class TestBrowserServerLifetime(BrowserServerCase):
+10 -7
View File
@@ -22,6 +22,11 @@ from pathlib import Path
from tests.browser import slow_reset_watch
from tests.browser.slow_reset_watch import REPORT_PREFIX, ResetWatch, is_reset_path
try:
from tests.process_cleanup import remove_when_released
except ImportError: # discovered with tests/ as the top-level directory
from process_cleanup import remove_when_released
REPO_ROOT = Path(__file__).resolve().parent.parent
SERVER_TIMEOUT_S = 60
HOLD_SECONDS = slow_reset_watch.SLOW_RESET_SECONDS + 4
@@ -108,10 +113,10 @@ class TestSlowResetOnTheServer(unittest.TestCase):
"""A reset behind another process's write lock, on tests/browser/server.py."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
env = {**os.environ, "TMPDIR": self.tmp.name}
env.update(TEMP=self.tmp.name, TMP=self.tmp.name)
self.tmp = tempfile.mkdtemp()
self.addCleanup(remove_when_released, self.tmp)
env = {**os.environ, "TMPDIR": self.tmp}
env.update(TEMP=self.tmp, TMP=self.tmp)
self.stderr = tempfile.TemporaryFile()
self.addCleanup(self.stderr.close)
process = subprocess.Popen(
@@ -145,9 +150,7 @@ class TestSlowResetOnTheServer(unittest.TestCase):
self.assertIsNone(process.poll(), "the server exited early")
self.assertLess(time.monotonic(), deadline, "never ready")
time.sleep(0.1)
[self.db_path] = glob.glob(
os.path.join(self.tmp.name, "pm-browser-*", "browser.db")
)
[self.db_path] = glob.glob(os.path.join(self.tmp, "pm-browser-*", "browser.db"))
def reset(self) -> tuple[int, float]:
request = urllib.request.Request(
+259
View File
@@ -0,0 +1,259 @@
"""CI runs tests only for changes that can affect code (#639).
``tools/ci/change_class.py`` sorts a change by the files it touches: ``inert``
(nothing reads the file at run or test time), ``docs`` (a Python test reads
it) or ``code`` (everything else, and every case of doubt).
"""
import os
import subprocess
import sys
import tempfile
import unittest
import unittest.mock
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "tools" / "ci"))
import change_class # noqa: E402
SCRIPT = ROOT / "tools" / "ci" / "change_class.py"
def _isolated_environment(**extra):
"""The environment without git's own variables and the script's inputs.
A git hook exports ``GIT_DIR`` and ``GIT_INDEX_FILE`` for the repository
being pushed. A child ``git`` that inherits them works on that repository
instead of the temp one, so the pre-push hook must never pass them on.
"""
kept = {
key: value
for key, value in os.environ.items()
if not key.startswith("GIT_") and key not in change_class.ENVIRONMENT
}
return {**kept, **extra}
class TestClassify(unittest.TestCase):
def test_files_nothing_reads_are_inert(self):
for paths in (
[".github/FUNDING.yml"],
["SECURITY.md"],
["images/pm-01.png", ".github/ISSUE_TEMPLATE/bug_report.md"],
):
self.assertEqual(change_class.classify(paths), "inert", paths)
def test_documents_a_test_reads_are_docs(self):
for paths in (
["README.md"],
["README-legacy.md", "assets/readme/hero.webp"],
["assets/brand/banner.webp", ".github/FUNDING.yml"],
):
self.assertEqual(change_class.classify(paths), "docs", paths)
def test_anything_else_is_code(self):
for paths in (
["py/api/images.py"],
["README.md", "web/js/workspace/index.mjs"],
[".github/FUNDING.yml", "pyproject.toml"],
# The browser suite compares production against the concept.
["docs/concepts/workspace/app.js"],
# The tooling tests read the tables in it.
["TESTING.md"],
[".github/workflows/test.yml"],
["LICENSE"],
# Look-alikes of listed names are not listed.
["docs/README.md"],
["web/images/x.png"],
["SECURITY.md.py"],
[".github/funding.yml"],
):
self.assertEqual(change_class.classify(paths), "code", paths)
def test_no_files_is_code(self):
self.assertEqual(change_class.classify([]), "code")
def test_every_document_a_test_reads_exists(self):
for name in change_class.DOCS_FILES:
self.assertTrue((ROOT / name).is_file(), name)
for folder in change_class.DOCS_FOLDERS:
self.assertTrue((ROOT / folder).is_dir(), folder)
class TestCommandLine(unittest.TestCase):
"""The script against a real repository with one commit per kind of change."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.repo = Path(self.tmp.name) / "repo"
self.repo.mkdir()
# As in a git hook: these name another repository, which must stay untouched.
self.other = Path(self.tmp.name) / "other.git"
patcher = unittest.mock.patch.dict(
os.environ,
{
"GIT_DIR": str(self.other),
"GIT_INDEX_FILE": str(self.other / "index"),
"GIT_WORK_TREE": str(self.tmp.name),
},
)
patcher.start()
self.addCleanup(patcher.stop)
self.addCleanup(lambda: self.assertFalse(self.other.exists()))
self.git("init", "-q", "-b", "main")
self.commit({"py/a.py": "a\n", "README.md": "r\n"})
self.base = self.head()
def git(self, *args):
return subprocess.run(
["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args],
cwd=self.repo,
env=_isolated_environment(),
check=True,
capture_output=True,
text=True,
).stdout.strip()
def commit(self, files):
for name, text in files.items():
path = self.repo / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
self.git("add", "-A")
self.git("commit", "-q", "-m", "change")
def head(self):
return self.git("rev-parse", "HEAD")
def run_script(self, *args, **env):
return subprocess.run(
[sys.executable, str(SCRIPT), *args],
cwd=self.repo,
env=_isolated_environment(**env),
capture_output=True,
text=True,
)
def class_of(self, **env):
result = self.run_script(**env)
self.assertEqual(result.returncode, 0, result.stderr)
return result.stdout.strip()
def test_a_pull_request_is_classed_by_its_own_files(self):
self.git("checkout", "-q", "-b", "topic")
self.commit({".github/FUNDING.yml": "x\n"})
topic = self.head()
# main moved on with code meanwhile: that is not this pull request's change.
self.git("checkout", "-q", "main")
self.commit({"py/a.py": "b\n"})
self.assertEqual(
self.class_of(
EVENT_NAME="pull_request", BASE_SHA=self.head(), HEAD_SHA=topic
),
"class=inert",
)
def test_a_merge_group_and_a_push_are_classed_by_their_range(self):
self.commit({"README.md": "r2\n"})
for event in ("merge_group", "push"):
self.assertEqual(
self.class_of(
EVENT_NAME=event, BASE_SHA=self.base, HEAD_SHA=self.head()
),
"class=docs",
event,
)
self.commit({"py/a.py": "c\n"})
self.assertEqual(
self.class_of(
EVENT_NAME="merge_group", BASE_SHA=self.base, HEAD_SHA=self.head()
),
"class=code",
)
def test_a_deleted_or_renamed_file_counts_under_both_names(self):
self.git("mv", "py/a.py", "SECURITY.md")
self.git("commit", "-q", "-m", "rename")
self.assertEqual(
self.class_of(
EVENT_NAME="merge_group", BASE_SHA=self.base, HEAD_SHA=self.head()
),
"class=code",
)
def test_doubt_is_code(self):
self.commit({".github/FUNDING.yml": "x\n"})
head = self.head()
zero = "0" * 40
for env in (
{"EVENT_NAME": "workflow_dispatch", "BASE_SHA": self.base},
{"EVENT_NAME": "schedule", "BASE_SHA": self.base, "HEAD_SHA": head},
{"EVENT_NAME": "push", "BASE_SHA": zero, "HEAD_SHA": head},
{"EVENT_NAME": "push", "BASE_SHA": "", "HEAD_SHA": head},
{"EVENT_NAME": "push", "BASE_SHA": "f" * 40, "HEAD_SHA": head},
{"EVENT_NAME": "push", "BASE_SHA": head, "HEAD_SHA": head},
{},
):
self.assertEqual(self.class_of(**env), "class=code", env)
def test_the_pre_push_command_is_skipped_only_for_an_inert_push(self):
marker = self.repo / "ran"
command = (
"--unless-inert",
sys.executable,
"-c",
"open('ran', 'w').close()",
)
self.commit({".github/FUNDING.yml": "x\n"})
refs = {"PRE_COMMIT_FROM_REF": self.base, "PRE_COMMIT_TO_REF": self.head()}
result = self.run_script(*command, **refs)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertFalse(marker.exists())
self.assertIn("inert", result.stdout)
# No range from pre-commit (a manual run) and a docs push both run it.
self.assertEqual(self.run_script(*command).returncode, 0)
self.assertTrue(marker.exists())
marker.unlink()
self.commit({"README.md": "r3\n"})
refs["PRE_COMMIT_TO_REF"] = self.head()
self.assertEqual(self.run_script(*command, **refs).returncode, 0)
self.assertTrue(marker.exists())
def test_the_pre_push_command_is_found_through_path(self):
# On Windows a bare "npm" is npm.cmd: only a PATH lookup with PATHEXT finds it.
found = unittest.mock.Mock(return_value=unittest.mock.Mock(returncode=3))
with unittest.mock.patch.dict(os.environ, _isolated_environment(), clear=True):
with (
unittest.mock.patch.object(
change_class.shutil, "which", return_value="C:/node/npm.cmd"
) as which,
unittest.mock.patch.object(change_class.subprocess, "run", found),
):
code = change_class.main(["--unless-inert", "npm", "test"])
which.assert_called_once_with("npm")
found.assert_called_once_with(["C:/node/npm.cmd", "test"], check=False)
self.assertEqual(code, 3)
def test_a_missing_or_absent_pre_push_command_fails_clearly(self):
with unittest.mock.patch.dict(os.environ, _isolated_environment(), clear=True):
with (
unittest.mock.patch.object(
change_class.shutil, "which", return_value=None
),
unittest.mock.patch.object(change_class.subprocess, "run") as run,
):
self.assertEqual(change_class.main(["--unless-inert", "nope"]), 127)
self.assertEqual(change_class.main(["--unless-inert"]), 2)
run.assert_not_called()
def test_the_pre_push_command_keeps_its_exit_code(self):
result = self.run_script(
"--unless-inert", sys.executable, "-c", "raise SystemExit(7)"
)
self.assertEqual(result.returncode, 7)
if __name__ == "__main__":
unittest.main()
+70 -3
View File
@@ -1,12 +1,14 @@
"""Delete selected images: the review and the apply job (#480).
``POST /prompt_manager/images/delete/preview`` reviews both modes;
``POST /prompt_manager/images/delete/preview`` reviews all three modes;
``POST /prompt_manager/maintenance/apply {token, mode}`` removes the files'
records (library mode, with a removal mark) or moves the files to the trash
first (trash mode, the fake trash here). No path unlinks a media file.
records (library mode, with a removal mark), moves the files to the trash
first (trash mode, the fake trash here), or unlinks the files from disk
(permanent mode, Linux/BSD only).
"""
import asyncio
import errno
import os
import sys
import sqlite3
@@ -407,3 +409,68 @@ 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_delete_removes_the_file(self):
fake_trash.uninstall()
self.addCleanup(fake_trash.uninstall)
if sys.platform == "win32":
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 sys.platform == "win32":
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]],
)
+61
View File
@@ -0,0 +1,61 @@
"""Pinned files keep their bytes in every clone (#636).
``npm run --prefix tools/vendor check`` compares the vendored Viewer.js and
ComfyAssets Toolkit files, and the workspace's copy of the concept
stylesheet, with recorded hashes. Git for Windows converts text files to CRLF
on checkout by default, which changes those bytes, so ``.gitattributes`` marks
them as never converted. This holds that for every tracked file under them.
"""
import os
import shutil
import subprocess # nosec B404 - fixed git arguments, no shell
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
PINNED = (
"web/lib/viewerjs",
"web/js/shared/toolkit",
"web/js/workspace/concept.css",
"docs/concepts/workspace/style.css",
)
def _git(*args: str) -> str:
# Without GIT_* variables: the pre-push hook exports GIT_DIR and
# GIT_INDEX_FILE, which must not choose the repository read here.
env = {
key: value for key, value in os.environ.items() if not key.startswith("GIT_")
}
return subprocess.run( # nosec B603 B607 - fixed git arguments, no shell
["git", *args], cwd=ROOT, env=env, check=True, capture_output=True, text=True
).stdout
@unittest.skipUnless(
shutil.which("git") and (ROOT / ".git").exists(), "needs a git checkout"
)
class TestPinnedLineEndings(unittest.TestCase):
def test_every_pinned_file_is_never_converted(self):
files = _git("ls-files", "-z", "--", *PINNED).split("\0")
files = [name for name in files if name]
self.assertGreater(len(files), 8, files)
report = _git("check-attr", "-z", "text", "--", *files).split("\0")
# -z output: path, attribute, value, repeated.
values = dict(zip(report[0::3], report[2::3]))
for name in files:
with self.subTest(path=name):
self.assertEqual(values[name], "unset")
def test_the_repository_stores_them_with_lf(self):
report = _git("ls-files", "--eol", "--", *PINNED).splitlines()
self.assertTrue(report)
for line in report:
with self.subTest(line=line):
self.assertNotIn("i/crlf", line)
self.assertNotIn("i/mixed", line)
if __name__ == "__main__":
unittest.main()
+7
View File
@@ -312,6 +312,13 @@ class LoraImportAPITestCase(LoraAPITestCase):
class LoraImportRouteTests(LoraImportAPITestCase):
async def test_preview_writes_nothing_and_makes_no_requests(self):
# The review shows a settings file under the home folder as ~/...
# (test_lora_manager_layout). Home is pinned beside the temp root, so
# the full path below holds wherever TEMP is: on Windows it sits
# under the profile (#636).
home = patch.object(Path, "home", return_value=self.tmp_root / "home")
home.start()
self.addCleanup(home.stop)
self._two_loras()
(self.loras / "broken.metadata.json").write_text("{{{")
db_path = self.api.db.model.db_path
+1
View File
@@ -22,6 +22,7 @@ DEVELOPMENT = (
"images/x.png",
"TESTING.md",
"requirements-dev.txt",
".gitattributes",
)
KEPT = (
"__init__.py",
+64
View File
@@ -0,0 +1,64 @@
"""remove_when_released waits for a dying process's files, within a bound (#636)."""
import os
import tempfile
import unittest
import unittest.mock
try:
from tests import process_cleanup
except ImportError: # discovered with tests/ as the top-level directory
import process_cleanup
class TestRemoveWhenReleased(unittest.TestCase):
def test_removes_the_folder(self):
folder = tempfile.mkdtemp()
with open(os.path.join(folder, "server.log"), "w") as handle:
handle.write("x")
process_cleanup.remove_when_released(folder)
self.assertFalse(os.path.exists(folder))
def test_a_missing_folder_is_already_removed(self):
folder = tempfile.mkdtemp()
os.rmdir(folder)
process_cleanup.remove_when_released(folder)
def test_retries_while_another_process_still_holds_a_file(self):
held = PermissionError(32, "being used by another process")
with (
unittest.mock.patch.object(
process_cleanup.shutil, "rmtree", side_effect=[held, held, None]
) as rmtree,
unittest.mock.patch.object(process_cleanup.time, "sleep") as sleep,
):
process_cleanup.remove_when_released("folder")
self.assertEqual(rmtree.call_count, 3)
self.assertEqual(sleep.call_count, 2)
def test_raises_the_last_error_after_the_bound(self):
held = PermissionError(32, "being used by another process")
clock = iter([0.0, 0.0, 5.0, 11.0])
with (
unittest.mock.patch.object(
process_cleanup.shutil, "rmtree", side_effect=held
),
unittest.mock.patch.object(process_cleanup.time, "sleep"),
unittest.mock.patch.object(
process_cleanup.time, "monotonic", side_effect=lambda: next(clock)
),
):
with self.assertRaises(PermissionError):
process_cleanup.remove_when_released("folder", timeout=10)
def test_other_errors_are_not_retried(self):
with unittest.mock.patch.object(
process_cleanup.shutil, "rmtree", side_effect=OSError("disk gone")
) as rmtree:
with self.assertRaises(OSError):
process_cleanup.remove_when_released("folder")
self.assertEqual(rmtree.call_count, 1)
if __name__ == "__main__":
unittest.main()
+13 -4
View File
@@ -50,6 +50,17 @@ class DiagnosticsTestCase(unittest.TestCase):
os.chdir(path)
self.addCleanup(os.chdir, previous)
def _chdir_without_comfyui(self):
"""Work two levels inside the temp folder (#636).
The fallback looks up to two levels above the working folder for
``output`` and ``ComfyUI/output``; from here that never leaves the
temp folder, wherever the machine keeps it or installs ComfyUI.
"""
folder = os.path.join(self.tmp.name, "a", "b")
os.makedirs(folder)
self._chdir(folder)
class TestDatabaseChecks(DiagnosticsTestCase):
def test_missing_database_is_an_error(self):
@@ -159,9 +170,7 @@ class TestComfyUIOutputCheck(DiagnosticsTestCase):
)
def test_nothing_found_is_a_warning(self):
empty = os.path.join(self.tmp.name, "empty")
os.makedirs(empty)
self._chdir(empty)
self._chdir_without_comfyui()
with mock.patch.dict(sys.modules, {"folder_paths": None, "py.config": None}):
result = self.diag.check_comfyui_output()
self.assertEqual(result["status"], "warning")
@@ -203,7 +212,7 @@ class TestDependenciesAndFullRun(DiagnosticsTestCase):
def test_full_diagnostic_reports_every_category(self):
self._populate()
self._chdir(self.tmp.name)
self._chdir_without_comfyui()
with mock.patch.dict(sys.modules, {"folder_paths": None, "py.config": None}):
results = self.diag.run_full_diagnostic()
self.assertEqual(
+104 -31
View File
@@ -67,9 +67,16 @@ const browserJobIds = [...allJobs].filter(([, body]) => /npm run --prefix tools\
const mergeJob = () => allJobs.get('frontend-coverage-merge');
const verifyStep = () => steps(mergeJob()).find(step => /name: Verify every shard's raw coverage arrived/.test(step));
// #639: each workflow classifies the change first (tools/ci/change_class.py). Jobs that only a code
// change can affect skip for the classes "docs" and "inert", and run when the classifier failed.
const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const jobIf = condition => new RegExp(`^ {4}if: ${escapeRegExp(`\${{ ${condition} }}`)}$`, 'm');
const CODE_CLASS = "needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert'";
const CODE_ONLY_IF = jobIf(`!cancelled() && ${CODE_CLASS}`);
// Jobs that run only in the merge queue, on main and on demand (#420): skipped on pull_request.
const QUEUE_ONLY_IF = /^ {4}if: github\.event_name != 'pull_request'$/m;
const QUEUE_ONLY_IF = jobIf(`!cancelled() && github.event_name != 'pull_request' && ${CODE_CLASS}`);
const EVENTS = ['pull_request', 'merge_group', 'push', 'workflow_dispatch'];
const CLASSES = ['code', 'docs', 'inert'];
function gateVariables(jobText) {
return new Map([...jobText.matchAll(/^ {10}([A-Z_]+): \$\{\{ needs\.([\w-]+)\.result \}\}$/gm)]
@@ -86,21 +93,36 @@ function runGate(jobText, env) {
}
}
// A gate passes only when every always-on job succeeded and every queue-only job is skipped on a
// pull request and succeeded on every other event. Anything else fails it.
function assertGateBehaviour(jobText, queueOnly) {
// A gate passes only when the classifier succeeded and every job did what the change class and the
// event ask (#639). For a code change: every always-on and code-only job succeeded, and every
// queue-only job is skipped on a pull request and succeeded on every other event. For a docs or
// inert change: every always-on job succeeded and every other job is skipped. Anything else fails
// it, and so does a class the classifier does not print.
function assertGateBehaviour(jobText, { queueOnly, codeOnly, always = [] }) {
assert.match(jobText, /^ {10}EVENT_NAME: \$\{\{ github\.event_name \}\}$/m, 'the gate knows the event');
assert.match(jobText, /^ {10}CHANGE_CLASS: \$\{\{ needs\.changes\.outputs\.class \}\}$/m, 'the gate knows the change class');
const variables = gateVariables(jobText);
for (const id of queueOnly) assert.ok(variables.has(id), `${id} reaches the gate`);
for (const event of EVENTS) {
const expected = id => (queueOnly.includes(id) && event === 'pull_request' ? 'skipped' : 'success');
const green = Object.fromEntries([...variables].map(([id, name]) => [name, expected(id)]));
assert.equal(runGate(jobText, { ...green, EVENT_NAME: event }), true, `${event}: the expected results pass`);
for (const [id, name] of variables) {
for (const result of ['success', 'failure', 'cancelled', 'skipped']) {
if (result === expected(id)) continue;
assert.equal(runGate(jobText, { ...green, EVENT_NAME: event, [name]: result }), false,
`${event}: ${id}=${result} must fail the gate`);
assert.deepEqual([...variables.keys()].sort(), ['changes', ...queueOnly, ...codeOnly, ...always].sort(),
'every job the gate reads has an expected result');
for (const changeClass of CLASSES) {
for (const event of EVENTS) {
const expected = id => {
if (id === 'changes' || always.includes(id)) return 'success';
if (changeClass !== 'code') return 'skipped';
return queueOnly.includes(id) && event === 'pull_request' ? 'skipped' : 'success';
};
const where = `${changeClass} change on ${event}`;
const green = { EVENT_NAME: event, CHANGE_CLASS: changeClass,
...Object.fromEntries([...variables].map(([id, name]) => [name, expected(id)])) };
assert.equal(runGate(jobText, green), true, `${where}: the expected results pass`);
for (const [id, name] of variables) {
for (const result of ['success', 'failure', 'cancelled', 'skipped']) {
if (result === expected(id)) continue;
assert.equal(runGate(jobText, { ...green, [name]: result }), false, `${where}: ${id}=${result} must fail the gate`);
}
}
for (const unknown of ['', 'other', 'code ']) {
assert.equal(runGate(jobText, { ...green, CHANGE_CLASS: unknown }), false, `${where}: class "${unknown}" must fail the gate`);
}
}
}
@@ -113,20 +135,20 @@ test('viewerjs keeps its name and needs every frontend job', () => {
const needs = needsOf(viewerjs);
const others = [...allJobs.keys()].filter(id => id !== 'viewerjs');
assert.deepEqual([...needs].sort(), [...others].sort(), 'viewerjs needs every other job in the workflow');
assert.deepEqual([...needs].sort(), ['browser-workflows', 'frontend-coverage', 'frontend-coverage-merge']);
assert.deepEqual([...needs].sort(), ['browser-workflows', 'changes', 'frontend-coverage', 'frontend-coverage-merge']);
assert.match(viewerjs, /^ {4}if: always\(\)$/m, 'viewerjs runs (and fails) when a needed job failed or was skipped');
assert.deepEqual([...gateVariables(viewerjs).keys()].sort(), [...needs].sort(), 'every needed result reaches the check');
});
test('viewerjs requires the browser shards everywhere but on a pull request', () => {
assertGateBehaviour(allJobs.get('viewerjs'), ['browser-workflows']);
test('viewerjs requires the browser shards everywhere but on a pull request, and nothing for a docs or inert change', () => {
assertGateBehaviour(allJobs.get('viewerjs'), { queueOnly: ['browser-workflows'], codeOnly: ['frontend-coverage', 'frontend-coverage-merge'] });
});
test('Firefox/WebKit page workflows run only outside pull requests; coverage runs on every event', () => {
test('Firefox/WebKit page workflows run only outside pull requests; coverage runs on every event; both for code changes only', () => {
assert.match(allJobs.get('browser-workflows'), QUEUE_ONLY_IF);
for (const id of ['frontend-coverage', 'frontend-coverage-merge']) {
assert.doesNotMatch(allJobs.get(id), /^ {4}if:/m, `${id} runs on every event`);
}
assert.match(allJobs.get('frontend-coverage'), CODE_ONLY_IF);
// !cancelled() replaces the implicit success() check, so the merge names the shards' success itself.
assert.match(allJobs.get('frontend-coverage-merge'), jobIf(`!cancelled() && needs.frontend-coverage.result == 'success' && ${CODE_CLASS}`));
});
test('coverage runs as four shards that each upload their raw coverage', () => {
@@ -144,7 +166,7 @@ test('coverage runs as four shards that each upload their raw coverage', () => {
test('merge job downloads every shard and runs the merge-only report and check', () => {
const merge = mergeJob();
assert.ok(merge, 'frontend-coverage-merge exists');
assert.deepEqual(needsOf(merge), ['frontend-coverage']);
assert.deepEqual(needsOf(merge), ['changes', 'frontend-coverage']);
assert.match(merge, /^ {4}name: frontend coverage \(merge\)$/m);
const download = steps(merge).find(step => /uses: actions\/download-artifact@/.test(step));
assert.ok(download, 'merge downloads the shard artifacts');
@@ -329,16 +351,33 @@ test('the bandit pre-commit hook fails at the severity CI enforces and passes ev
// Event split (#420): pull requests run a fast subset, the merge queue and main run everything.
const testJobs = () => jobs(readWorkflow('test.yml'));
test('the Python matrix is Linux 3.12 on a pull request and Linux 3.12-3.14 on every other event', () => {
test('the Python matrix is Linux 3.12 on a pull request or a docs or inert change and Linux 3.12-3.14 otherwise', () => {
const body = testJobs().get('test');
assert.deepEqual(matrixList(body, 'os'), ['ubuntu-latest'], 'Windows never gates a merge');
const match = /^ {8}python-version: \$\{\{ github\.event_name == 'pull_request' && fromJSON\('(\[[^\]]*\])'\) \|\| fromJSON\('(\[[^\]]*\])'\) \}\}$/m.exec(body);
assert.ok(match, 'python-version is chosen by event');
assert.deepEqual({ pr: JSON.parse(match[1]), other: JSON.parse(match[2]) }, { pr: ['3.12'], other: ['3.12', '3.13', '3.14'] });
const match = /^ {8}python-version: \$\{\{ \(github\.event_name == 'pull_request' \|\| needs\.changes\.outputs\.class == 'docs' \|\| needs\.changes\.outputs\.class == 'inert'\) && fromJSON\('(\[[^\]]*\])'\) \|\| fromJSON\('(\[[^\]]*\])'\) \}\}$/m.exec(body);
assert.ok(match, 'python-version is chosen by event and change class');
assert.deepEqual({ small: JSON.parse(match[1]), other: JSON.parse(match[2]) }, { small: ['3.12'], other: ['3.12', '3.13', '3.14'] });
assert.match(body, /^ {6}fail-fast: false$/m);
assert.match(body, /^ {4}name: py\$\{\{ matrix\.python-version \}\} on \$\{\{ matrix\.os \}\}$/m);
});
// #639: a skipped matrix job reports under its unexpanded name, so the required context
// "py3.12 on ubuntu-latest" would never report. The job therefore always starts, and an inert change
// skips its steps instead.
test('the Python matrix always starts and skips its steps for an inert change', () => {
const body = testJobs().get('test');
assert.deepEqual(needsOf(body), ['changes']);
assert.match(body, jobIf('!cancelled()'), 'it also runs, in full, when the classifier failed');
const jobSteps = steps(body);
const nothing = jobSteps.filter(step => /^ {8}if: needs\.changes\.outputs\.class == 'inert'$/m.test(step));
assert.equal(nothing.length, 1, 'one step says nothing needs testing');
assert.match(nothing[0], /^ {8}run: echo /m, 'and it only prints that');
for (const step of jobSteps.filter(step => step !== nothing[0])) {
assert.match(step, /^ {8}if: needs\.changes\.outputs\.class != 'inert'$/m, `every real step is skipped for an inert change: ${step.trim().split('\n')[0]}`);
}
assert.equal(jobSteps.length, 5);
});
test('Windows runs 3.12-3.14 on main, nightly and on demand, never on a PR or in the queue', () => {
const text = readWorkflow('portability.yml');
const triggers = text.slice(text.indexOf('\non:'), text.indexOf('\nconcurrency:'));
@@ -374,12 +413,14 @@ test('the portability limit is computed from three measured green main runs', ()
assert.equal(limit, expected, 'the job uses the written limit');
});
test('real ComfyUI runs only outside pull requests; the other test.yml checks run on every event', () => {
test('real ComfyUI runs only outside pull requests; the other test.yml checks run on every event; all for code changes only', () => {
const found = testJobs();
assert.match(found.get('comfyui'), QUEUE_ONLY_IF);
for (const id of ['test', 'coverage', 'lint', 'js-test']) {
assert.doesNotMatch(found.get(id), /^ {4}if:/m, `${id} runs on every event`);
for (const id of ['coverage', 'lint', 'js-test']) {
assert.match(found.get(id), CODE_ONLY_IF, `${id} runs on every event for a code change`);
}
assert.match(found.get('perf-budget'),
jobIf(`!cancelled() && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && ${CODE_CLASS}`));
});
test('all tests needs every gating test.yml job and requires the full set outside pull requests', () => {
@@ -391,7 +432,7 @@ test('all tests needs every gating test.yml job and requires the full set outsid
const gating = [...found.keys()].filter(id => !['all-tests', 'perf-budget'].includes(id));
assert.deepEqual([...needsOf(gate)].sort(), gating.sort(), 'the gate needs every job but the non-gating perf budget');
assert.deepEqual([...gateVariables(gate).keys()].sort(), gating.sort(), 'every needed result reaches the gate');
assertGateBehaviour(gate, ['comfyui']);
assertGateBehaviour(gate, { queueOnly: ['comfyui'], codeOnly: ['coverage', 'lint', 'js-test'], always: ['test'] });
});
test('the CI workflows run on pull_request, merge_group and push without path filters', () => {
@@ -403,7 +444,39 @@ test('the CI workflows run on pull_request, merge_group and push without path fi
}
assert.doesNotMatch(text, /^ {4}paths(-ignore)?:/m, `${name} has no path filter that would leave a required check pending`);
}
assert.doesNotMatch(jobs(readWorkflow('code-quality.yml')).get('security'), /^ {4}if:/m, 'bandit runs on every event');
assert.match(jobs(readWorkflow('code-quality.yml')).get('security'), CODE_ONLY_IF, 'bandit runs on every event for a code change');
});
// #639: the change is classified once per workflow, before anything else, from file names alone.
test('each gating workflow classifies the change first and every other job waits for it', () => {
for (const name of GATING_WORKFLOWS) {
const found = jobs(readWorkflow(name));
assert.equal([...found.keys()][0], 'changes', `${name} starts with the classifier`);
const changes = found.get('changes');
assert.match(changes, /^ {4}name: change class$/m);
assert.doesNotMatch(changes, /^ {4}(needs|if):/m, `${name}: the classifier waits for nothing and always runs`);
assert.match(changes, /^ {6}class: \$\{\{ steps\.classify\.outputs\.class \}\}$/m);
const [checkout, classify] = steps(changes);
assert.match(checkout, /uses: actions\/checkout@v\d+/);
assert.match(checkout, /^ {10}fetch-depth: 0$/m, 'the base commit must be in the clone');
assert.match(checkout, /^ {10}filter: blob:none$/m, 'file names need no file contents');
assert.match(checkout, /^ {10}persist-credentials: false$/m);
assert.match(classify, /^ {8}id: classify$/m);
assert.match(classify, /^ {10}EVENT_NAME: \$\{\{ github\.event_name \}\}$/m);
assert.match(classify, /^ {10}BASE_SHA: \$\{\{ github\.event\.pull_request\.base\.sha \|\| github\.event\.merge_group\.base_sha \|\| github\.event\.before \}\}$/m);
assert.match(classify, /^ {10}HEAD_SHA: \$\{\{ github\.event\.pull_request\.head\.sha \|\| github\.event\.merge_group\.head_sha \|\| github\.sha \}\}$/m);
assert.match(classify, /^ {8}run: python3 tools\/ci\/change_class\.py \| tee -a "\$GITHUB_OUTPUT"$/m);
for (const [id, body] of found) {
if (id !== 'changes') assert.ok(needsOf(body).includes('changes'), `${name} job ${id} waits for the classifier`);
}
}
});
test('the pre-push hook runs the suite through the classifier', () => {
const hook = /- id: tests\n([\s\S]*?)(?=\n {6}(?:- id:|#)|\n*$)/.exec(readRepoFile('.pre-commit-config.yaml'))?.[1];
assert.ok(hook, 'the tests hook exists');
assert.match(hook, /^ {8}entry: python tools\/ci\/change_class\.py --unless-inert python -m tests\.run_suite -q$/m);
assert.match(hook, /^ {8}stages: \[pre-push\]$/m);
});
test('every required check reports on a pull request and the gates carry the full matrix', () => {
+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env python3
"""Sort a change by the files it touches, so CI tests only what can break (#639).
Three classes, decided from allowlists:
- ``inert``: every file is one nothing reads at run or test time (the funding
file, the security policy, the old README's screenshots, issue templates).
No test job runs.
- ``docs``: every file is inert or a document a Python test reads (the
READMEs and their images, checked by ``tests/test_brand_assets.py`` and
``tests/test_package_contents.py``). Only the Python 3.12 suite runs.
- ``code``: anything else. A file on no list is code, and so is every case of
doubt: no files, an unknown event, a range git cannot read.
``docs/`` is code (the browser suite compares production against
``docs/concepts/workspace/``) and so is ``TESTING.md`` (the tooling tests read
its tables). To add a file to a list, first check that no test and no shipped
code opens it.
Usage:
``change_class.py``
Prints ``class=<inert|docs|code>`` for the workflow's ``$GITHUB_OUTPUT``,
from ``EVENT_NAME``, ``BASE_SHA`` and ``HEAD_SHA``. A pull request is
compared with its merge base, so commits that landed on main meanwhile
do not count; a merge group and a push are compared end to end.
``change_class.py --unless-inert <command...>``
The pre-push hook: runs the command unless pre-commit's pushed range
(``PRE_COMMIT_FROM_REF``..``PRE_COMMIT_TO_REF``) is inert, and exits
with the command's code. The command is looked up on ``PATH`` first, so a
bare ``npm`` finds ``npm.cmd`` on Windows, which ``subprocess`` alone
does not do.
"""
import os
import shutil
import subprocess
import sys
from typing import Iterable, Optional
INERT_FILES = frozenset({".github/FUNDING.yml", "SECURITY.md"})
INERT_FOLDERS = ("images/", ".github/ISSUE_TEMPLATE/")
DOCS_FILES = frozenset({"README.md", "README-legacy.md"})
DOCS_FOLDERS = ("assets/readme/", "assets/brand/")
RANGE_EVENTS = frozenset({"pull_request", "merge_group", "push"})
ENVIRONMENT = frozenset(
{
"EVENT_NAME",
"BASE_SHA",
"HEAD_SHA",
"PRE_COMMIT_FROM_REF",
"PRE_COMMIT_TO_REF",
}
)
def classify(paths: Iterable[str]) -> str:
"""``inert``, ``docs`` or ``code`` for the repository paths of one change."""
found = "code"
for path in paths:
if path in INERT_FILES or path.startswith(INERT_FOLDERS):
if found == "code":
found = "inert"
elif path in DOCS_FILES or path.startswith(DOCS_FOLDERS):
found = "docs"
else:
return "code"
return found
def changed_paths(base: str, head: str, three_dot: bool) -> Optional[list[str]]:
"""Paths that differ between two commits, or None when git cannot say.
Renames are listed under both names, so a file moved onto a listed name
still counts as the code file it was.
"""
if not base or not head or not base.strip("0") or not head.strip("0"):
return None
span = f"{base}...{head}" if three_dot else f"{base}..{head}"
try:
result = subprocess.run(
["git", "diff", "--name-only", "--no-renames", "-z", span, "--"],
capture_output=True,
text=True,
check=False,
)
except OSError:
return None
if result.returncode != 0:
return None
return [path for path in result.stdout.split("\0") if path]
def class_of_range(base: str, head: str, three_dot: bool = False) -> str:
paths = changed_paths(base, head, three_dot)
if paths is None:
return "code"
for path in paths:
print(f"changed: {path}", file=sys.stderr)
return classify(paths)
def run_command(argv: list[str]) -> int:
"""Run ``argv`` with its program resolved through ``PATH``; its exit code."""
if not argv:
print("change_class: --unless-inert needs a command", file=sys.stderr)
return 2
program = shutil.which(argv[0])
if program is None:
print(f"change_class: command not found: {argv[0]}", file=sys.stderr)
return 127
return subprocess.run([program, *argv[1:]], check=False).returncode
def main(argv: list[str]) -> int:
if argv[:1] == ["--unless-inert"]:
found = class_of_range(
os.environ.get("PRE_COMMIT_FROM_REF", ""),
os.environ.get("PRE_COMMIT_TO_REF", ""),
)
if found == "inert":
print("Skipped: this push only changes inert files (tools/ci).")
return 0
return run_command(argv[1:])
event = os.environ.get("EVENT_NAME", "")
found = "code"
if event in RANGE_EVENTS:
found = class_of_range(
os.environ.get("BASE_SHA", ""),
os.environ.get("HEAD_SHA", ""),
three_dot=event == "pull_request",
)
print(f"class={found}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+27 -12
View File
@@ -5,11 +5,12 @@
* - The concept's selection bar has "Remove links…" (`danger`) opening its `maintenancePlan` review (`dl.meta-grid`
* Scope / Protected / Backup / Media on disk, Cancel and a primary). Production names it "Delete…" and asks each
* time (maintainer ruling): a radio group "What should happen to the files?" with nothing checked, "Remove from the
* library only" (records go, the file stays on disk, hidden from Images) or "Also move the files to the trash".
* - One preview (`POST /images/delete/preview`) answers both modes; choosing a mode only redraws the rows. The primary
* library only" (records go, the file stays on disk, hidden from Images) or "Also move the files to the trash" (or,
* on Linux/BSD servers, "Permanently delete" from disk).
* - One preview (`POST /images/delete/preview`) answers all three modes; choosing a mode only redraws the rows. The primary
* (`danger`) is enabled once a mode with images to act on is chosen. Apply sends `{token, mode}` to the reviewed-plan
* apply; the job is followed in the Activity store and `onDeleted(job)` runs when it ends.
* - Nothing here deletes a file: the server never unlinks one (it renames into the system trash or leaves it).
* - Only the "permanent" mode unlinks a file from disk (via the apply job); library and trash modes leave the file intact.
*/
import { createButton } from '../shared/toolkit/core.js';
import { closeWorkspaceDialog, openCloseOnlyReview, openContentDialog } from './workspace-dialogs.mjs';
@@ -26,6 +27,7 @@ export const MODES = Object.freeze([
Object.freeze({value: 'library', label: 'Remove from the library only', hint: 'Files stay on disk, hidden from Images.'}),
Object.freeze({value: 'trash', label: 'Also move the files to the trash',
hint: 'You can restore them from the trash until it is emptied.'}),
Object.freeze({value: 'permanent', label: 'Permanently delete', hint: 'Files are removed from disk permanently.'}),
]);
export const NONE_DELETABLE = 'None of the selected images can be deleted.';
export const REVIEW_FAILED = 'The review failed. Nothing was changed.';
@@ -40,6 +42,7 @@ const SENTENCES = Object.freeze({
+ 'collections and favorite cannot be recovered.',
trash: 'A file restored from the trash shows again without its tags, category, collections or favorite; a scan '
+ 'links it to its prompt again.',
permanent: 'Permanently deleted files are gone from disk. Records can only be restored via the safety database backup; the files themselves cannot be recovered.',
});
export { SENTENCES };
@@ -111,7 +114,9 @@ export function deleteRows(plan, mode) {
: 'Off: no safety backup (System › Backup & export › Recovery policy)']);
rows.push(['Media on disk', mode === 'trash'
? 'Files move to the trash. Nothing is deleted permanently. Disk space is freed when you empty the trash.'
: 'Files stay on disk, hidden from Images.']);
: mode === 'permanent'
? 'Files are removed from disk. Disk space is freed immediately.'
: 'Files stay on disk, hidden from Images.']);
return rows;
}
@@ -122,6 +127,7 @@ function backupOn(plan) {
/** The `p.small` sentences for `mode`. */
export function deleteSentences(plan, mode) {
if (mode === 'library') return [backupOn(plan) ? SENTENCES.libraryBackup : SENTENCES.libraryNoBackup];
if (mode === 'permanent') return [SENTENCES.permanent];
const sentences = [SENTENCES.trash];
const trashRefused = Number(plan?.trash_refused?.count ?? 0);
if (trashRefused && trashRefused >= modeCount(plan, 'library')) sentences.push(NO_TRASH_HERE);
@@ -129,14 +135,16 @@ export function deleteSentences(plan, mode) {
return sentences;
}
/** The primary's label: "Remove N images from the library" or "Move N images to the trash". */
/** The primary's label: "Remove N images from the library", "Move N images to the trash", or "Permanently delete N from disk". */
export function primaryLabel(mode, count) {
return mode === 'trash' ? `Move ${countOf(count, 'image')} to the trash` : `Remove ${countOf(count, 'image')} from the library`;
if (mode === 'trash') return `Move ${countOf(count, 'image')} to the trash`;
if (mode === 'permanent') return `Permanently delete ${countOf(count, 'image')} from disk`;
return `Remove ${countOf(count, 'image')} from the library`;
}
/** Why the review cannot start at all, or null. */
export function closeOnlyReason(plan) {
if (modeCount(plan, 'library') === 0 && modeCount(plan, 'trash') === 0) return NONE_DELETABLE;
if (modeCount(plan, 'library') === 0 && modeCount(plan, 'trash') === 0 && modeCount(plan, 'permanent') === 0) return NONE_DELETABLE;
if (plan?.disk && plan.disk.sufficient === false) {
return `There is not enough free space for the safety backup (needs ${number(plan.disk.required_bytes)} bytes, `
+ `has ${number(plan.disk.free_bytes)}).`;
@@ -159,24 +167,31 @@ export function outcomeToast(job) {
const mode = job?.scope?.mode;
if (job?.scope?.failure === 'backup-failed') return 'The safety backup failed; nothing was changed.';
if (job?.scope?.failure === 'sources-changed') return 'The sources changed; nothing was changed.';
const done = Number(mode === 'trash' ? counters.trashed : counters.removed) || 0;
let done;
if (mode === 'trash') done = Number(counters.trashed) || 0;
else if (mode === 'permanent') done = Number(counters.deleted) || 0;
else done = Number(counters.removed) || 0;
const total = Number(job?.total ?? 0);
if (job?.scope?.failure === 'records-failed') {
return `Stopped after ${number(done)} of ${countOf(total, 'image')}; the rest were not changed. See Activity.`;
}
const head = mode === 'trash' ? `Moved ${countOf(done, 'image')} to the trash.` : `Removed ${countOf(done, 'image')} from the library.`;
let head;
if (mode === 'trash') head = `Moved ${countOf(done, 'image')} to the trash.`;
else if (mode === 'permanent') head = `Permanently deleted ${countOf(done, 'image')} from disk.`;
else head = `Removed ${countOf(done, 'image')} from the library.`;
const unchanged = Number(counters.not_changed ?? 0);
return unchanged ? `${head} ${number(unchanged)} ${unchanged === 1 ? 'was' : 'were'} not changed (see Activity).` : head;
}
function modeGroup(onChange) {
function modeGroup(onChange, plan) {
const group = el('div', undefined, 'field');
group.setAttribute('role', 'radiogroup');
const caption = el('span', QUESTION);
caption.id = 'image-delete-mode-label';
group.setAttribute('aria-labelledby', caption.id);
group.append(caption);
for (const choice of MODES) {
const choices = plan?.permanent_delete_supported ? MODES : MODES.filter(m => m.value !== 'permanent');
for (const choice of choices) {
const label = el('label');
const input = el('input');
Object.assign(input, {type: 'radio', name: 'image-delete-mode', value: choice.value, checked: false});
@@ -217,7 +232,7 @@ export function showDeleteReview(plan, {scope, count, trigger = null, onApply})
start.textContent = primaryLabel(mode, acting);
start.setAttribute('aria-disabled', String(acting === 0));
}
const group = modeGroup(value => { mode = value; render(); });
const group = modeGroup(value => { mode = value; render(); }, plan);
cancel.addEventListener('click', () => closeWorkspaceDialog());
// Nothing starts without an explicit mode: an aria-disabled primary ignores every activation (click, Enter, Space),
// and a chosen one starts once however often it is pressed. The dialog has no form, so Enter elsewhere submits nothing.
+3 -1
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 } from './inspection-state.mjs';
import { createInspectionController, rootedFileAdapter } from './inspection-state.mjs';
import { mountSelectionBar } from './images-selection.mjs';
import { scrollToPageTop } from './sticky-chrome.mjs';
import { createPromptSender } from './prompt-sender.mjs';
@@ -374,6 +374,8 @@ export function mountImages(main, api, parentScope, {embedded = false, fetchPage
}
function previewImage(image) {
if (!image) return;
// #646: a file the viewer can't open (a backslash in a folder name) shows its details panel instead.
try { rootedFileAdapter.validate(image); } catch { inspect(image); return; }
mediaViewer.open({items:state.items,selectedKey:imageKey(image),trigger:document.activeElement});
}
/** The concept media card (image-card.mjs): the image opens the viewer, Info inspects (D7–D11, D19). */
+9 -4
View File
@@ -1,11 +1,16 @@
import {rootedFileAdapter} from './inspection-state.mjs';
/** A viewer visits only the descriptors loaded by its opening query. */
/** One descriptor the adapter refuses is left out, so it never keeps the viewer from opening on the others (#646). */
function openable(adapter, item) {
try { adapter.validate(item); return true; } catch (error) { if (error instanceof TypeError) return false; throw error; }
}
/** A viewer visits only the descriptors loaded by its opening query that its adapter accepts. */
export function createViewerSession({items, initialKey, onChange = () => {}, setTimer = setTimeout, clearTimer = clearTimeout, adapter = rootedFileAdapter}) {
if (!Array.isArray(items) || !items.length) throw new TypeError('A loaded media collection is required');
const accepted = Array.isArray(items) ? items.filter(item => openable(adapter, item)) : [];
if (!accepted.length) throw new TypeError('A loaded media collection is required');
const keys = new Set();
const loaded = Object.freeze(items.map(item => {
adapter.validate(item);
const loaded = Object.freeze(accepted.map(item => {
const key = adapter.key(item);
if (keys.has(key)) throw new TypeError('Duplicate viewer identity');
keys.add(key);