Compare commits

..
Author SHA1 Message Date
Vito 16d2d85f11 fix(ci): a docs-only push runs just the tests that read the docs (#679) (#681)
The pre-push hook ran the whole Python suite for a README edit. Only
tests.test_brand_assets and tests.test_package_contents open docs-class
files, so a docs push now runs those two. An inert push still runs
nothing and every other push still runs the full suite.
2026-11-22 11:17:01 -08:00
Vito 03c49a0689 docs(readme): plain wording, whole sentences and literal headings (#680)
Rewrites the README without changing its facts, images, links or tables:
figurative headings become literal, fragments become sentences, the
delete and tag-address paragraphs become lists.
2026-11-22 11:05:05 -08:00
Vito 92920bf0f9 chore: release 3.8.0, with a CHANGELOG and its contributors (#677) 2026-11-22 06:36:40 -08:00
Vito 9847664b9e feat: tag cleanup in Maintenance and short-phrase LoRA tags (#618) (#676)
* feat(lora): make tags only from short trigger phrases (#618)

A trained-words entry becomes a tag only when it is one short clean
phrase: the existing tag rule (at most 50 characters, no control
character), no ASCII or fullwidth comma, no <...> model call and no
prompt weight. The trigger-word lookup still sees every entry.

The import review gains a Trigger words row (N become tags, M not made
tags) and the import job logs how many entries were not made tags.

* feat(maintenance): tag cleanup rules, find job and plan (#618)

database/tag_cleanup.py holds a registry of tag rules; two ship: tags
containing a comma (never a lora: tag; removed from every owner and
deleted) and tags with no links (deleted). A tag belongs to the first
rule that finds it.

POST /prompt_manager/jobs/tag_cleanup runs the find as a read job that
holds its findings; GET /prompt_manager/maintenance/tag_cleanup/{job_id}
answers every rule with them; the tag_cleanup preview plans only the
ticked findings, protecting any changed since the search. The apply is
the maintenance job Tag cleanup: always after a safety backup, it
rechecks each tag in one transaction and keeps, with its reason, each
one that changed while the rest still apply.

delete_vocabulary_tag and the rules share the new connection-level
_delete_tag.

* feat(system): Tag cleanup in Maintenance (#618)

System > Maintenance > Database gains Tag cleanup (D210): Find tags
starts the tag search as an Activity job (Finding tags, one Found
tile, no Cancel); a search that found tags offers Review tags. Review
tag cleanup draws whatever rules the server returns, nothing ticked at
first: a rule tick ticks all its listed tags, each tag has its own
tick, and Review cleanup opens the tag_cleanup plan. A failed Tag
cleanup job's Review again goes to Maintenance.

* docs: tag cleanup (#618)

TESTING.md records D210 (the Tag cleanup row, its Activity kind, the
review dialog and the import review's Trigger words row), the
tag_cleanup operation in the Maintenance contract (rules, find job,
per-target rechecks, forced backup) and the trained-words phrase rule
in the LoRA reference import contract.
2026-11-22 06:17:43 -08:00
Vito a7d54e0ecf fix(thumbnails): wait out a marker lock Windows is still deleting (#674) (#675) 2026-11-22 04:10:29 -08:00
1439a5ef19 feat(images): collect AVIF as a media type (#652) (#673)
* Fix DB threading, recent ordering, restore size, and scan timestamps

* Fix subfolders API missing include_ancestors param

* refactor: move api code into promptmanager_core package

* chore: ignore local config, tracking state, and db backups

* Fix: fall back to original source when thumbnail img fails to load

* fix(core): apply code review fixes, optimizations, and schema compliance

- Fix KeyError in image_monitor _get_fallback_prompt dictionary handling
- Add secondary LoRA hash stripping in image_monitor prompt lookup
- Protect dual PromptManager workflows from metadata overwrite in patched_save_images
- Support WebP, JPEG, and GIF metadata extraction via image.info
- Add default values for prepend_text and append_text in INPUT_TYPES
- Add **kwargs to encode_prompt, process_text, search, and IS_CHANGED
- Declare explicit RETURN_NAMES across PromptManager and PromptManagerText
- Add close() proxy to PromptDatabase and fix Windows SQLite connection locks
- Normalize database and subfolder paths for cross-platform consistency
- Update test suite teardown handlers and mock targets across 17 test modules
- Add comprehensive CHANGELOG.md and issue.txt tracking documentation

* Close test databases before unlinking temp files

The usage and image-linking tests unlinked their temp database while the
persistent SQLite connection was still open, so Windows raised WinError 32
from tearDown (POSIX allows unlinking an open file, so upstream CI never
saw it). Close the database first and ignore a transient lock, matching
tests/test_database.py.

* Ignore local tracking state and prebackfill database backup

* style: restore black formatting after 3.6.0 merge

The fork-only default:" additions to prepend_text/append_text dropped the
trailing commas, which black reformats. This is the entire cause of Tests #4
on main: black --check failed with 'would reformat prompt_manager.py'
while every other job (test matrix, coverage, comfyui, js-test) passed.

No behaviour change.

* feat(images): collect AVIF as a media type (#652)

The EXIF reader from #650 reads the prompt and workflow records ComfyUI's
SaveImageAdvanced writes into an AVIF, but no file-type list named .avif, so
neither the scan nor the monitor ever handed it one.

Every list now names .avif: the scan and its deletion allowlist, the monitor's
default and fallback, the gallery and thumbnail walks, serving and Inspect,
auto-tagging's listing and its path check, the capture store, the preview
source order and the diagnostics count.

Pillow's floor here is >= 10.1.0 (ComfyUI's) and Pillow opens AVIF only from
11.0, and only when built with an AVIF decoder. utils/media_formats.collectable
asks PIL.features.check("avif") at every collection point, so a Pillow without
AVIF skips the file quietly and behaves exactly as before #652; the tests pin
both answers on the gallery walk, the monitor, auto-tagging, the capture store
and the scan.

gallery.monitoring.extensions is saved per install and overrides the default,
so a list saved before #652 gains .avif last on load, keeping every entry the
install chose; an empty list stays empty, and a value that is not a list keeps
the current one.

The fixture is tests/fixtures/media/comfyui_avif.avif: a 1 KB still written by
ComfyUI's own _save_avif (tools/make_avif_fixture.py regenerates it) carrying a
PromptManager graph. The scan stores and links its prompt and pair; the monitor
links the same positive prompt from the file's own EXIF.

The local browser-only Inspect reader is unchanged: the bundled front-end
reader does not parse AVIF, so the chooser still offers what it can read.
Library Inspect reads an AVIF through the server, where Pillow answers.

* chore: drop two local ignore rules that are not part of AVIF support (#652)

---------

Co-authored-by: LacklusterOpsec <LacklusterOpsec@users.noreply.github.com>
Co-authored-by: Vito Sansevero <vito.sansevero@gmail.com>
2026-11-21 17:25:59 -08:00
aryankalantri 9f3a1bf96d fix(lora): finish the import when the replace commits, even at exit (#619) (#672)
* fix(lora): finish the import when the replace commits, even at exit (#619)

* test(lora): exit during the replace still finishes the import (#619)
2026-11-21 16:42:15 -08:00
Vito def5deb113 chore: retire the old admin, gallery and metadata pages (#668) (#669)
* feat(library): open the shelf filtered from a #/library?tag= link (#668)

workspace#/library?tag=<name>&tag=<name>&tag_mode=all|any|untagged opens the
Prompt library with those Tags and that Tag match, as Refine and Browse do.
Old tag bookmarks are sent to this form.

The filter stays in the hash until the shelf has mounted with it, then the
address becomes #/library. A link is rendered even when the shelf is already
open. A link that cannot be read opens the whole shelf and says so.

* feat: old admin, gallery and metadata URLs lead into the workspace (#668)

/prompt_manager/gallery answers 302 to workspace#/images and
/prompt_manager/gallery.html to workspace#/inspect. The Location is relative,
so a reverse-proxy prefix is kept.

/prompt_manager/admin serves a small page that maps the old hash in the
browser (the server never sees it): the dashboard opens the Prompt library,
#/tags opens Tags & categories, and a tag bookmark such as
#/tags/a,b?mode=or opens the Library filtered by those tags
(workspace#/library?tag=a&tag=b&tag_mode=any). The mapping is
web/js/legacy-links.js.

The browser specs that drove the old pages go; the specs that only checked
the old URLs now follow the redirects. The page files themselves are removed
in the next commit.

* chore: delete the old admin, gallery and metadata pages (#668)

Removes web/admin.html, gallery.html, metadata.html, their controllers
(admin.js, gallery.js, tags-page.js) and the ten helper modules only they
loaded, with their unit tests. The vendored Tailwind build and the Makefile
that rebuilt it go too: nothing else used them.

Kept and still tested: comfy-metadata.js (its PromptManagerPair tests move to
comfy-metadata.test.js), api-client.js, gallery-settings.js, png-metadata.js,
cache-ownership.js. The inspector's Copy settings summary keeps its pinned
COPY ALL template as a frozen copy in its test.

The Viewer.js fixture suite drove the old controllers; it is now a smoke of
the vendored build alone. The System coverage table has no row kept in
legacy any more (the four become approved removals), and the table of ids
removed from the old pages goes with the pages it checked. Coverage floors
of the remaining files are unchanged; the deleted files' entries are
removed.

* docs: the old pages are gone, their URLs lead into the workspace (#668)

README lists where each old URL now opens, with a tag-bookmark example and
the workspace link form. README-legacy says the pages it describes were
removed. TESTING.md records D207 (redirects, the bookmark mapping and the
#/library?tag= form), D208 (no editing surface for records used only as a
negative; data and exports kept) and D209 (the four System rows that were
kept in legacy), and no longer says the old pages stay at their URLs.

* fix(library): a Library link leaves title focus to the shell (#668)

The shell focuses a page title on a navigation inside the workspace and never
on the first render. A Library link followed that for the first, but also
focused the title when the page was loaded directly on the link.

* test: compare old-URL landings without building patterns from text (#668)

Code scanning flagged two test lines: a regular expression built from a hash
with only / and # escaped, and a regular expression used to cut <noscript>
and <script> out of the redirect page. The address is now compared by its
parts, and the page's inline script is found by plain string search.

* feat(library): keep the tag filter in the address (#668)

Ruling after the live test: a tag link used to become #/library once the
shelf had its filter, so Reload and Back then Forward showed the whole
Library.

The address now stays #/library?tag=a&tag=b&tag_mode=any|untagged, in one
canonical spelling. It is the truth for Tags and Tag match: Reload, Back and
Forward restore the filter, a change in Refine replaces the address without
a history entry, and #/library (the sidebar link, the old dashboard URL)
always means no tag filter. Search, category, folder, sort and the archived
shelf stay out of the address. The way back from a prompt's page and Browse
on Tags & categories go to the filtered address. A saved view keeps its own
address.
2026-11-21 12:50:35 -08:00
Vito 6375be1a92 chore: release 3.7.2 (#661) 2026-11-21 09:49:30 -08:00
147 changed files with 4716 additions and 14221 deletions
-1
View File
@@ -13,7 +13,6 @@
# Development files
/TESTING.md
/Makefile
/requirements-dev.txt
/.coveragerc
/.flake8
-3
View File
@@ -1,6 +1,3 @@
# Tailwind standalone CLI (downloaded by `make css-setup`)
tailwindcss
# AI tooling / local config
.claude/
.playwright-mcp/
+2 -1
View File
@@ -22,7 +22,8 @@ repos:
types: [python]
exclude: ^(tests/|reference/)
# Skipped when the pushed commits only change inert files (tools/ci/change_class.py, #639).
# Skipped for an inert push; a docs push runs only the two tests that read the docs
# (tools/ci/change_class.py, #639, #679).
- id: tests
name: tests
entry: python tools/ci/change_class.py --unless-inert python -m tests.run_suite -q
+258
View File
@@ -0,0 +1,258 @@
# Changelog
What changed in each release of ComfyUI Prompt Manager, newest first. Full notes for each version are on the [releases page](https://github.com/ComfyAssets/ComfyUI_PromptManager/releases).
Thank you to everyone whose pull requests are part of these releases. They are named beside their changes and listed under [Contributors](#contributors).
## v3.8.0 (Old pages removed, Tag cleanup, AVIF)
- **🧹 Tag cleanup**: System › Maintenance finds tags that are whole comma lists and tags used nowhere. You review them and remove only what you tick; a safety backup is always taken first. Later cleanups will be added to the same place ([#618](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/618))
- **🏷️ LoRA import tags**: a LoRA's trained words become a tag only when they are one short phrase. Lists and sentences are no longer saved as tags, and the import review says how many were left out ([#618](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/618))
- **🖼️ AVIF images**: collected, thumbnailed and linked to their prompts like PNG and WebP, where your Pillow can read AVIF. By [@LacklusterOpsec](https://github.com/LacklusterOpsec) ([#673](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/673), [#652](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/652))
- **🗑️ Old pages removed**: the old Dashboard, Gallery and Metadata viewer are gone, after the notice in 3.5.1. Their addresses open the matching workspace page, and old tag bookmarks open the Prompt library with that filter ([#668](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/668))
- **🔗 Tag filters in the address**: `#/library?tag=cats&tag=dogs&tag_mode=any` can be bookmarked and shared; Reload, Back and Forward keep the filter ([#668](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/668))
- **🐛 LoRA import label**: an import that had already saved when ComfyUI closed is shown as finished, not cancelled. By [@aryankalantri](https://github.com/aryankalantri) ([#672](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/672), [#619](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/619))
- **🪟 Windows**: two installs writing one shared thumbnail folder at the same moment no longer fail with "Permission denied" ([#674](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/674))
- **⚠️ Known limit**: Inspect shows a WebP or AVIF file but not its embedded prompt yet; the image still links to its prompt ([#656](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/656))
## v3.7.2 (Always a way to choose the prompt)
- **🎯 Choose prompt in Inspect**: an image with several possible prompts shows a Choose prompt section; Inspect creates the Needs review item itself, also for older images ([#659](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/659))
- **📥 Needs review without a scan**: the live monitor queues an ambiguous output as soon as its run ends ([#659](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/659))
- **🔢 Big workflows**: a file with more than 16 different prompts offers the 16 most used instead of none
- **🔗 Link to a prompt** lists the image's own prompts first; the Needs review queue loads as you scroll
- **🐛 rgthree Any Switch** no longer makes a decided prompt look ambiguous ([#657](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/657)); a role every candidate agrees on shows as resolved ([#658](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/658))
- **🧪 CI**: every change is tested once, on its pull request; other browsers, Python versions and Windows run nightly ([#666](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/666))
## v3.7.1 (WebP linking)
- **🖼️ WebP images link to their prompts**: ComfyUI's Save Animated WEBP stores the prompt in EXIF, which is now read. By [@LacklusterOpsec](https://github.com/LacklusterOpsec) ([#650](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/650))
- **🐛 Prepend and append text** start empty instead of `null`. By [@LacklusterOpsec](https://github.com/LacklusterOpsec) ([#651](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/651))
## v3.7.0 (Permanent delete, new logo)
- **🗑️ Permanent delete** for images on Linux and BSD servers, beside remove-from-library and trash. By [@k98kurz](https://github.com/k98kurz) ([#643](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/643))
- **🎨 New logo** in the README, the Comfy Registry and the browser tabs ([#632](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/632))
- **🐛 Folders with a backslash in their name** work on Linux and macOS; one odd file no longer stops the viewer opening ([#646](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/646))
## v3.6.0 (Library sorts)
- **↕️ Three more Prompt library sorts**: Recently used, Most used and Name Z–A
- **🐛 Windows network shares**: backup checks, restore, Move library and history reads open a library on a network path ([#620](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/620))
- **🐛 Unloading a tagging model** no longer freezes the server ([#620](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/620))
## v3.5.1 (Smaller download)
- **📦 Smaller package**: the Registry download drops from 17.4 MB to about 3.9 MB ([#615](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/615))
- **📣 Notice**: the old pages say they will be removed
## v3.5.0 (Thumbnail location, Send to all, Skipped tags)
- **📁 Thumbnail location**: keep thumbnails inside each source or in one folder of your choice, with a reviewed move ([#320](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/320))
- **📤 Send to every node**: Send to ComfyUI offers all eligible nodes of a window at once ([#542](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/542))
- **🚫 Skipped tags** and **saved tagging instructions** for auto-tagging ([#431](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/431))
- **🔧 Pair category and tags repair** in System › Maintenance ([#550](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/550))
- **⚡ Less memory** for scans and image work ([#523](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/523))
- **🐛 Prompt Search List** text is no longer saved as a prompt ([#548](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/548))
## v3.4.1 (Fix release)
- **🪟 Windows**: ComfyUI could hang on exit with watchdog 7.0.0
- **🔒 LoRA import errors** no longer show server details
## v3.4.0 (The workspace)
- **✨ Rebuilt around one page**, the workspace: Images, Prompt library, Tags & categories, Collections, Favorites, Needs review, Inspect a file, Activity and System
- **🖼️ Viewer** with keyboard shortcuts, zoom, rotate and slideshow; **Send to ComfyUI** from any prompt
- **🏷️ Per-image tags and auto-tagging** with WD14 or JoyCaption
- **🧩 Nodes**: Focused, Split and Prompt Manager (+/-) join Classic, Text and Search List; all run in Classic and Nodes 2.0
- **📁 Library outside the node folder**: new installs keep the library in `ComfyUI/user/__promptmanager/`; an existing library moves only when you choose
- **🗜️ Smaller database**: each workflow and prompt graph is stored once, compressed
- **⚠️ Requires Python 3.12 or newer**; downgrading is not supported
## Earlier versions
Releases from before the workspace, as they were written at the time.
## v3.3.1 (Proxy Routing Fix)
- **🌐 Proxy support**: the dashboard, gallery, tag page and metadata viewer now work when ComfyUI is reached through a proxy mount such as SwarmUI's `/ComfyBackendDirect/`. Scripts, images, API calls, progress streams and gallery folder filters stay under the mount, and the canvas node's buttons use ComfyUI's `fileURL()`. Direct ComfyUI URLs are unchanged. Thanks to @ghosttigerllc-bit ([#164](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/164))
- **📦 Dependencies**: the runtime minimums stay at `Pillow>=8.0.0` and `watchdog>=2.1.0`, so updating Prompt Manager never forces upgrades in the shared ComfyUI environment
## v3.3.0 (Hardening, Background Jobs & Worker Threads)
- **🔒 Security**: gallery roots restricted to ComfyUI directories and validated wherever they are read; media-only, fail-closed image serving; Windows path escape in static routes closed; quote-safe HTML escaping with inline handlers moved to data attributes; the CivitAI key is never returned and only sent to HTTPS CivitAI hosts; auto-tag paths contained; side-effect routes are POST-only; backups include the WAL and restores are size-capped, integrity-checked and applied through SQLite's online backup API
- **🧵 Worker Threads**: a Settings slider (default half the cores) used by the image rescan, thumbnail generation and duplicate detection. Measured: a 1 GB sample scanned in 2.5 s instead of 18 s at 8 threads
- **🔁 Background Jobs**: the image rescan and the duplicate scan run on the server, stream progress, survive a closed tab, minimize to a progress pill and re-attach after a reload
- **🎬 Video Prompts**: the scan reads the prompt ComfyUI's video savers embed in MP4/MOV/WebM containers (needs `ffprobe`)
- **🖼️ Thumbnails**: written atomically and served under versioned URLs so a regenerated thumbnail never shows a stale cached copy; the per-run cap applies only to thumbnails that still need generating and the gallery says how many remain
- **🏷️ Tag Autocomplete**: the dashboard tag box suggests tags, narrowed to those that co-occur with the tags already typed
- **♾️ Infinite Scrolling**: optional in the gallery and the dashboard list (saved default plus a session toggle)
- **⚙️ Gallery Settings** now apply at load; grid columns, media info and the Rescan button work as labelled
- **🐛 Correctness**: run counts increment when ComfyUI dequeues a prompt; negative prompts are never traced; per-thread SQLite connections and idempotent migrations (an old rebuild could delete every image row); `truncate_logs` no longer rolls the log over; the ComfyUI canvas loads only the canvas extension; Windows console banners are ASCII-safe; subfolders use `/` on every platform
- **🧪 Tests & CI**: 1,460 Python and 142 JavaScript tests (from 510 and 26), coverage 96% with an 85% gate, CI on Linux, Windows and macOS for Python 3.10–3.12, flake8 clean
- **⚠️ API changes**: image paths in responses are relative to the ComfyUI tree (use `url`); `autotag/download`, `autotag/start` and the thumbnail progress stream are POST-only; `lora/status` returns `has_civitai_api_key` instead of the key; `/search` is paginated
## v3.2.4 (Recently Used Sorting & Queue-Time Run Counts)
- **🕒 Recently Used Sort**: sort the dashboard by last use, most used or rating, server-side across pages
- **🔢 Run Counts**: `run_count` and `last_used_at` are recorded through the ComfyUI queue hook, so cached nodes still count
- **🔗 Positive-Prompt Image Linking**: generated images link to the positive prompt traced through the queued graph
## v3.2.1 (LoRA Manager Integration)
- **🔗 LoRA Manager Integration**: Import LoRA metadata, trigger words, and CivitAI example images from [ComfyUI-Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) into your prompt database
- **💉 Auto-Inject Trigger Words**: Optionally append LoRA trigger words when `<lora:name:weight>` is detected in prompts during encoding
- **🔑 CivitAI API Key Support**: Authenticate with CivitAI to download NSFW preview images
- **📥 Import Progress Modal**: Real-time SSE streaming progress during LoRA import with per-model status
> **Note:** LoRA Manager support is a WIP — this was a highly requested feature. Please [open issues](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues) for any bugs or feature requests.
## v3.2.0 (Folder Filter & QoL Improvements)
- **📁 Folder Filter**: New folder dropdown in the search panel to filter prompts by output subdirectory
- **📂 Multi-Directory Gallery Scan**: Configure multiple output directories and browse them all in one gallery
- **🖼️ Filmstrip Prompt Display**: Show prompt text and copy button in the filmstrip image viewer
- **🖱️ Click-to-Close Viewer**: Click outside the image viewer to close it
- **🐛 Bug Fixes**: Fixed database path config, UnboundLocalError in text inputs, node caching skip, diagnostics singleton lifecycle
## v3.1.0 (WD14 Tagger, Tailwind v4 & Major Refactors)
- **🏷️ WD14 Tagger Support**: Added WD14 SwinV2 and WD14 ViT as new auto-tag model options — fast ONNX-based classifiers (~400MB) that output Danbooru tags with confidence scores, no prompt needed
- **🎚️ Threshold Controls**: Adjustable general tag (default 0.35) and character tag (default 0.85) confidence thresholds for WD14 models via UI sliders
- **🎨 Tailwind v4 Migration**: Complete frontend redesign with ComfyUI theme token system (`--pm-*` design tokens) that adapts to ComfyUI's color palette
- **🏗️ API Refactor**: Split monolithic `api.py` into domain-specific route modules for better maintainability
- **🗃️ Junction Table Tags**: Migrated tag storage from JSON column to normalized junction tables with proper foreign keys
- **📄 Tags Page**: Dedicated tag management page with search, rename, merge, and delete operations
- **🔍 Load More Button**: Progressive prompt loading instead of traditional pagination
- **🔒 Security Hardening**: Resolved 15 GitHub code scanning alerts, prevented stack trace exposure in SSE errors
- **🧪 Test Coverage**: Added comprehensive unit tests for validators, hashing, metadata, config, and prompt tracker; API integration tests; database tests with CI pipeline
- **⚙️ CI/CD Improvements**: Added code quality scanning, security scanning, Dependabot, and pre-commit hooks with Black formatting
- **🐛 Bug Fixes**: Fixed custom image scan directory config (#108), gallery crash on thumbnail linking, broken imports after API refactor, widget value sync issues, and prepend/append metadata tag filtering in auto-tagger
## v3.0.26 (Top Bar Button)
- **🔘 Top Bar PM Button**: Added a "PM" button to the ComfyUI top bar for quick access to the admin dashboard
- **🚀 No Node Required**: Open PromptManager without having to add the node to your workflow first
- **🎨 Teal Button Design**: Distinctive teal-colored button positioned before the settings gear
- **🔄 Frontend Compatibility**: Works with both new ComfyUI frontend (v1.3.1+) and legacy versions
## v3.0.25 (Film Strip & QoL Improvements)
- **🎞️ Film Strip Preview**: Backported from V2 - thumbnail strip under each prompt showing linked images
- **🖼️ Quick Image Viewer**: Click any filmstrip thumbnail to open full-size image viewer
- **📸 Smart Thumbnails**: Automatically uses generated thumbnails for faster loading, falls back to full images
- **⬆️ Auto-Scroll on Pagination**: Page navigation now smoothly scrolls to top after loading
## v3.0.24 (Manual Prompt Creation)
- **➕ Add Prompt Button**: New "Add Prompt" button in the admin dashboard Bulk Actions bar
- **📝 Direct Prompt Creation**: Create prompts directly from the UI without generating images
- **🛡️ Protection from Pruning**: New prompts are automatically protected from orphan cleanup by default
- **🏷️ Full Metadata Support**: Set category, tags, rating, and notes when creating prompts
- **🔒 Orphan Protection Toggle**: Option to protect or unprotect prompts from maintenance cleanup
## v3.0.23 (AI AutoTag Release)
- **🏷️ AI AutoTag**: Automatically tag your entire image collection using JoyCaption vision models
- **🤖 Dual Model Support**: Choose between JoyCaption Beta One FP16 (high quality) or GGUF FP8 (lower VRAM)
- **📋 Two Tagging Modes**: Batch mode for bulk tagging, Review mode for one-by-one approval
- **⚙️ Smart Tag Handling**: Skip already-tagged images or re-tag all - respects your existing work
- **✏️ Customizable Prompts**: Adjust the system prompt to match your collection style and tag vocabulary
- **🔄 Real-time Progress**: SSE-based streaming progress updates during batch operations
- **📦 Tag Accordion UI**: Collapsible tag display shows first row with expandable section for large tag sets
- **🎯 Review Confirmation**: Prompts before overwriting existing tags in review mode
## v3.0.10 (Batch Processing Node)
- **📋 PromptSearchList Node**: New node that searches the prompt database and outputs results as a list
- **🔗 Batch Processing Support**: Uses `OUTPUT_IS_LIST` for native ComfyUI batch processing compatibility
- **🔍 Full Search Capabilities**: Search by text, category, tags, minimum rating, and result limit
- **⚡ Lightweight Operation**: Read-only search with no database writes
- **🎯 Workflow Integration**: Connect directly to batch processing nodes like String OutputList
## v3.0.9 (Output-Wide Gallery & Video Support)
- **📁 Output-Wide Gallery Mode**: Complete gallery redesign to show ALL content from ComfyUI output directory
- **🎬 Full Video Support**: Native video playback with HTML5 player for .mp4, .webm, .avi, .mov, .mkv, .m4v, .wmv formats
- **🖼️ Video Thumbnail Generation**: Automatic video thumbnails using OpenCV, ffmpeg, or placeholder fallback
- **⚙️ Video Settings Panel**: Configurable autoplay, mute, and loop settings with persistent preferences
- **🎮 Video Navigation**: Seamless navigation between videos with keyboard shortcuts and custom controls
- **📊 Video Metadata Display**: Show duration, resolution, aspect ratio, and detailed file information
- **🔄 Mixed Media Integration**: Videos and images seamlessly integrated in the same gallery interface
- **⚡ Enhanced Performance**: Optimized thumbnail generation for both images and videos
- **🎛️ Advanced Gallery Settings**: Comprehensive settings panel with video controls and performance options
- **🖱️ Improved Click Handling**: Fixed thumbnail failures to preserve click functionality
- **📱 Mobile Compatibility**: Enhanced responsive design for video playback on all devices
## v3.0.5 (Text-Only Node Release)
- **📝 PromptManagerText Node**: New text-only variant that outputs STRING instead of CONDITIONING
- **🔗 Text Concatenation**: Built-in prepend/append functionality for dynamic text assembly
- **⚡ Lightweight Processing**: No CLIP encoding overhead for pure text workflows
- **🔄 Dual Node Architecture**: Choose between CLIP encoding (PromptManager) or text-only (PromptManagerText)
- **🏷️ Shared Metadata System**: Both nodes use the same database and metadata features
- **🖼️ Unified Gallery**: Images from both node types appear in the same gallery system
- **📊 Enhanced Tracking**: Improved prompt tracking with prepend/append context preservation
- **📊 Enhanced Tracking**: Improved prompt tracking with prepend/append context preservation
## v3.0.3 (ViewerJS Integration & Enhanced Gallery)
- **🖼️ Professional Image Viewer**: Complete gallery redesign with [ViewerJS](https://github.com/fengyuanchen/viewerjs) integration
- **⚡ Advanced Image Navigation**: Zoom, rotation, slideshow, and professional viewing controls
- **🎨 Dark Theme Integration**: Seamless ViewerJS styling that matches the admin interface
- **🔬 Enhanced Metadata Parsing**: Improved ComfyUI workflow parameter extraction with targeted parsing
- **📊 Real-time Parameter Display**: Live CFG, steps, sampler, and seed extraction from workflow nodes
- **📋 Integrated Copy Functionality**: One-click copying of prompts and generation parameters
- **🛠️ Robust Value Detection**: Smart parsing that targets specific node types and validates parameters
- **⌨️ Keyboard Navigation**: Full keyboard support for gallery navigation and viewer controls
- **📱 Responsive Design**: Enhanced mobile and tablet compatibility
## v3.0.0 (Metadata Analysis Release)
- **🔬 PNG Metadata Analysis**: Advanced ComfyUI workflow extraction from PNG images
- **📋 Standalone Metadata Viewer**: Dedicated tool at `/web/metadata.html` for analyzing any ComfyUI image
- **🖼️ Integrated Metadata Panel**: Real-time workflow analysis in the image viewer
- **📸 Bulk Image Scanning**: Mass import and analysis of existing ComfyUI output directories
- **🛠️ System Management Suite**: Complete backup, restore, maintenance, and diagnostic tools
- **🚮 Orphaned Prompt Cleanup**: Remove prompts that have no linked images for database optimization
- **📋 Advanced Logging**: Comprehensive logging system with web-based log viewer
- **🎨 Enhanced Admin Dashboard**: Modern dark theme with improved UX and management tools
- **🔧 Robust Error Handling**: Advanced PNG parsing with NaN value cleaning and error recovery
- **📁 File Path Integration**: Direct file path display and system integration
- **⚡ Performance Optimizations**: Improved metadata extraction and database operations
## v2.0.0 (Gallery Release)
- **🖼️ Automatic Image Gallery**: Complete image tracking and gallery system
- **🌐 Advanced Web Interface**: Comprehensive admin dashboard with responsive design
- **📱 Image Viewer**: Full-screen modal with navigation and keyboard shortcuts
- **🔍 Enhanced Search**: Real-time search with advanced filtering options
- **⚡ Performance Improvements**: Optimized database operations
- **🛠️ Basic Diagnostics**: Initial system diagnostics and health monitoring
- **📊 Bulk Operations**: Multi-select prompt editing and management
## v1.0.0 (Initial Release)
- Core text encoding with database storage
- Search and filtering functionality
- Metadata support (categories, tags, ratings, notes)
- Hash-based deduplication
- SQLite backend with optimized schema
- Basic web interface
- Export functionality
## Contributors
Pull requests from the community that were merged into Prompt Manager:
| Contributor | Pull requests |
| --- | --- |
| [@LacklusterOpsec](https://github.com/LacklusterOpsec) | [#673](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/673) AVIF as a media type · [#650](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/650) WebP images link to their prompts · [#651](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/651) prepend/append defaults |
| [@aryankalantri](https://github.com/aryankalantri) | [#672](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/672) LoRA import finishes when it saved at exit |
| [@k98kurz](https://github.com/k98kurz) | [#643](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/643) permanent delete for images (Linux/BSD) |
| [@ghosttigerllc-bit](https://github.com/ghosttigerllc-bit) | [#165](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/165) A1111/Forge generation parameters · [#164](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/164) routing behind a ComfyUI proxy · [#140](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/140) recursive subfolder filtering and gallery tree |
| [@develop1st](https://github.com/develop1st) | [#141](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/141) collapsible sidebar setting and mobile overlap fix |
| [@logicalor](https://github.com/logicalor) | [#87](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/87) thumbnails in subfolders |
| [@x0x0b](https://github.com/x0x0b) | [#73](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/73) star icon alignment |
| [@robinjhuang](https://github.com/robinjhuang) | [#2](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/2) Registry publishing action · [#1](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/1) `pyproject.toml` for the Registry |
-43
View File
@@ -1,43 +0,0 @@
TAILWIND_VERSION := 4.1.18
TAILWIND_CLI := ./tailwindcss
UNAME_S := $(shell uname -s)
UNAME_M := $(shell uname -m)
ifeq ($(UNAME_S),Darwin)
ifeq ($(UNAME_M),arm64)
TAILWIND_PLATFORM := tailwindcss-macos-arm64
else
TAILWIND_PLATFORM := tailwindcss-macos-x64
endif
else
ifeq ($(UNAME_M),aarch64)
TAILWIND_PLATFORM := tailwindcss-linux-arm64
else
TAILWIND_PLATFORM := tailwindcss-linux-x64
endif
endif
TAILWIND_URL := https://github.com/tailwindlabs/tailwindcss/releases/download/v$(TAILWIND_VERSION)/$(TAILWIND_PLATFORM)
.PHONY: css css-watch css-setup clean-css
## Download Tailwind standalone CLI (dev only, not committed)
css-setup:
@if [ ! -f $(TAILWIND_CLI) ]; then \
echo "Downloading Tailwind CSS v$(TAILWIND_VERSION) CLI..."; \
curl -sLo $(TAILWIND_CLI) $(TAILWIND_URL) && chmod +x $(TAILWIND_CLI); \
else \
echo "Tailwind CLI already present"; \
fi
## Rebuild compiled CSS (run after changing Tailwind classes in HTML/JS)
css: css-setup
$(TAILWIND_CLI) -i web/lib/tailwind/input.css -o web/lib/tailwind/styles.css --minify
## Watch mode for development
css-watch: css-setup
$(TAILWIND_CLI) -i web/lib/tailwind/input.css -o web/lib/tailwind/styles.css --watch
## Remove downloaded CLI binary
clean-css:
rm -f $(TAILWIND_CLI)
+4 -4
View File
@@ -1,4 +1,4 @@
> **This is the old README.** It describes Prompt Manager before the workspace rewrite and is kept for reference, including the full changelog up to v3.3.1 and the legacy pages. Some details here are out of date. For the current version, see the [README](README.md).
> **This is the old README.** It describes Prompt Manager before the workspace rewrite and is kept for reference, including the full changelog up to v3.3.1. The dashboard, tags page, gallery and metadata viewer it describes have been removed; their URLs now open the matching workspace page. For the current version, see the [README](README.md).
# ComfyUI Prompt Manager
@@ -253,8 +253,8 @@ match Classic and Focused.
5. **Access the web interface**:
- **Workspace**: click **PM** in ComfyUI's top bar or **Web UI** on a node, or open `http://localhost:8188/prompt_manager/workspace`
- **Legacy pages** still work at their URLs, and System's Overview section links to them:
`/prompt_manager/admin` (dashboard), `/prompt_manager/admin#/tags` (tags), `/prompt_manager/gallery` (gallery), `/prompt_manager/gallery.html` (metadata viewer)
- **The old pages have been removed.** Their URLs open the matching workspace page:
`/prompt_manager/admin` (Prompt library), `/prompt_manager/admin#/tags` (Tags & categories), `/prompt_manager/gallery` (Images), `/prompt_manager/gallery.html` (Inspect a file)
### Prerequisites
@@ -328,7 +328,7 @@ The comprehensive gallery system provides complete access to all your ComfyUI ou
1. **Open the workspace's Images page** at `http://localhost:8188/prompt_manager/workspace#/images`
2. **Browse all content** from your ComfyUI output directory
The legacy gallery stays at `http://localhost:8188/prompt_manager/gallery`.
The old gallery URL, `http://localhost:8188/prompt_manager/gallery`, now opens the workspace's Images page.
#### **🎬 Video & Image Support**
+71 -52
View File
@@ -10,22 +10,22 @@
![Python](https://img.shields.io/badge/python-3.12%2B-blue.svg)
![Nightly tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/actions/workflows/nightly.yml/badge.svg)
Prompt Manager saves your prompts as you generate, links each image back to the prompt that made it, and gives you one page to browse, tag, compare and reuse all of it. Your library is a local SQLite database on your own machine.
Prompt Manager saves your prompts as you generate and links each image to the prompt that made it. One page, the workspace, lets you browse, tag, compare and reuse them. Your library is a local SQLite database on your own machine.
## What's new: rebuilt from the ground up
## What's new
- **A new UI.** One app, the workspace, replaces the separate dashboard, gallery and metadata pages.
- **A new UI.** The workspace replaces the separate dashboard, gallery and metadata pages.
- **Classic and Nodes 2.0.** The nodes work in both ComfyUI renderers. CI starts a real ComfyUI and checks both.
- **Tested end to end.** Unit tests, browser tests in Chromium, Firefox, WebKit and touch emulation, and tests against a real ComfyUI.
- **Automated tests.** Unit tests, browser tests in Chromium, Firefox, WebKit and touch emulation, and tests against a real ComfyUI.
- **Linux and Windows.** The Python suite runs on both, on Python 3.12, 3.13 and 3.14. macOS should work but is not tested.
## See it
All images on this page were generated and recorded through Prompt Manager in a clean demo library.
### Your whole output folder, finally browsable
### Browse your whole output folder
Masonry, grid or list, with search, categories, filters and saved views. Images and videos sit side by side, and selecting one shows its prompts and settings without leaving the page.
The Images page shows your output as masonry, a grid or a list. Search, categories, filters and saved views narrow it. Images and videos appear together, and selecting one shows its prompts and settings on the same page.
![Images page in grid layout](assets/readme/images-grid.webp)
@@ -35,63 +35,63 @@ The viewer shows the positive and negative prompts, tags, seed, steps, CFG, samp
![The viewer with an image on the left and its prompts and generation settings on the right](assets/readme/viewer.webp)
### Keep your hands on the keyboard
### Keyboard shortcuts
The viewer has shortcuts for moving between files, the slideshow, zoom, rotate, flip, full screen, details, download and delete. Press `?` to see them all.
![The viewer's keyboard shortcuts overlay](assets/readme/viewer-shortcuts.webp)
### Long libraries stay easy to work in
### Select and act while you scroll
The selection bar stays pinned while you scroll, so you can keep picking images and act on them from anywhere. Back to top appears once you've scrolled down the page.
The selection bar stays pinned while you scroll, so you can keep picking images and act on them from any position on the page. A Back to top button appears once you scroll down.
![Images page scrolled down, with the selection bar pinned at the top and a Back to top button](assets/readme/pinned-bar.webp)
### One positive prompt, many experiments
The Prompt library groups everything by positive prompt, so repeat runs and negative variants stay together instead of filling your list with near-duplicates.
The Prompt library groups everything by positive prompt. Repeat runs and negative variants stay with their positive prompt and don't add near-duplicate entries to your list.
![Prompt library cards showing each prompt's images, negative variants, runs and tags](assets/readme/library.webp)
### Watch your negatives branch on a timeline
### See negative variants on a timeline
Each prompt has its own page with a timeline of its negative variants. Click a red dot and the gallery filters to the images that negative made. Small dots mark repeat runs.
Each prompt has its own page with a timeline of its negative variants. Click a red dot and the gallery filters to the images that negative variant made. Small dots mark repeat runs.
![Clicking through negative variants on the timeline filters the gallery below](assets/readme/timeline.anim.webp)
### Compare negatives term by term
Compare negatives shows two variants side by side and lists the terms one adds, so you can see what actually changed between runs.
Compare negatives shows two negative variants side by side and lists the terms one adds, so you can see what changed between runs.
![Two negative prompts side by side with the added terms highlighted](assets/readme/compare-negatives.webp)
### Auto-tag your images, and approve what sticks
### Auto-tag your images and approve the suggestions
Tag one image, a selection or your whole output with WD14 or JoyCaption. WD14 suggestions come with confidence scores, and you can review suggestions before anything is saved. Auto-tags belong to the image, so they never change your prompts.
Tag one image, a selection or your whole output with WD14 or JoyCaption. WD14 suggestions come with confidence scores, and you can review suggestions before Prompt Manager saves anything. Auto-tags belong to the image, so they never change your prompts.
![Tag image dialog with WD14 suggestions and their confidence scores](assets/readme/autotag.webp)
### Keep your vocabulary tidy
### Manage tags and categories
Tags & categories lists every tag and category with how often it's used. Rename, merge and delete tags, and preview a category change before you apply it.
Tags & categories lists every tag and category with how often you use it. Rename, merge and delete tags, and preview a category change before you apply it.
![Tags and categories page](assets/readme/tags.webp)
### Group images your own way
Collections are hand-picked sets of images, on top of favorites and saved views. Add from the selection bar and they appear in the sidebar.
Collections are sets of images you pick by hand. They are separate from favorites and saved views. Add images from the selection bar and the collection appears in the sidebar.
![A collection called Book cover ideas open in the workspace](assets/readme/collections.webp)
### Nothing gets guessed
When a file's metadata has more than one possible prompt, Prompt Manager doesn't pick for you. The file waits in Needs review, where you can choose the sampler path, link it to any prompt in your library, or leave it unresolved.
When a file's metadata has more than one possible prompt, Prompt Manager doesn't pick for you. The file waits in Needs review, where you can choose the sampler path, link the file to any prompt in your library, or leave it unresolved.
![Link to a prompt dialog searching the library from Needs review](assets/readme/needs-review.webp)
### Inspect any file, without importing it
### Inspect any file without importing it
Pick an image or video from your computer to read its prompts, settings and workflow. The file is read in your browser. It isn't uploaded or added to your library.
Pick an image or video from your computer to read its prompts, settings and workflow. Your browser reads the file. Prompt Manager doesn't upload it or add it to your library.
![Inspecting a local file in the viewer](assets/readme/inspect.webp)
@@ -103,7 +103,13 @@ Pick an open ComfyUI window and a node, then review the exact before and after.
### Deletes you can review
Choose what happens to the files before anything is removed: remove the image from the library and leave the file on disk, or on Linux and macOS also move it to the system trash. On a Linux or BSD server you can also delete the files permanently, for headless servers where a trash only fills up the disk; those files can't be recovered. On Windows, images can only be removed from the library. A safety backup of the database is on by default, and removed images can be brought back.
Before Prompt Manager removes anything, you choose what happens to the files:
- **Remove from the library.** The file stays on disk. This is the only choice on Windows.
- **Move to the system trash.** Linux and macOS only.
- **Delete permanently.** Linux and BSD servers only. This is for headless servers, where a trash fills the disk. You can't recover these files.
A safety backup of the database is on by default, and you can bring removed images back.
![Delete dialog offering to remove from the library only or move files to the trash](assets/readme/delete-review.webp)
@@ -117,17 +123,17 @@ System holds settings, image sources, auto-tag models, integrations, maintenance
### Works on your phone too
The workspace adapts to narrow screens, and touch is part of the browser test suite.
The workspace adapts to narrow screens, and the browser test suite includes touch.
![Images page and viewer at phone width](assets/readme/phone.webp)
## The nodes
Six nodes, under **ComfyAssets > Prompts** in the Add Node menu. Pick the one that suits your workflow; they all share one library. Every screenshot below is a small real workflow that ran.
The six nodes are under **ComfyAssets > Prompts** in the Add Node menu. They all share one library. Every screenshot below is a small real workflow that ran.
### Prompt Manager (Classic)
The drop-in replacement for CLIP Text Encode: same CLIP input, same CONDITIONING output, with the prompt saved as it runs. It also outputs the text as a STRING.
This node replaces CLIP Text Encode. It has the same CLIP input and the same CONDITIONING output, and it saves the prompt as it runs. It also outputs the text as a STRING.
![Prompt Manager Classic node in a workflow, Classic renderer](assets/readme/node-classic.webp)
@@ -137,19 +143,19 @@ The same workflow in Nodes 2.0:
### Prompt Manager (Focused)
An editor-first layout. Composition and metadata fold away, and **Browse library** lets you search, preview and use a saved prompt right on the node.
This node puts the editor first. Composition and metadata collapse, and **Browse library** lets you search, preview and use a saved prompt on the node.
![Prompt Manager Focused node in a workflow](assets/readme/node-focused.webp)
### Prompt Manager (Split)
The same editor with the library always visible. Wide nodes put them side by side; narrow nodes stack them.
This node has the same editor with the library always visible. A wide node shows them side by side. A narrow node stacks them.
![Prompt Manager Split node in a workflow](assets/readme/node-split.webp)
### Prompt Manager (+/-)
Positive and negative in one node, saved as a pair. This is the node that feeds the negative-variant timeline. It outputs CONDITIONING and STRING for both sides.
This node holds the positive and the negative prompt and saves them as a pair. The timeline's negative variants come from this node. It outputs CONDITIONING and STRING for both sides.
![Prompt Manager plus/minus node in a workflow](assets/readme/node-pair.webp)
@@ -159,23 +165,23 @@ The same workflow in Nodes 2.0:
### Prompt Manager Text
Saves the prompt and outputs a STRING instead of CONDITIONING, for workflows that send text to another node. Prepend and append inputs let you build the final text.
This node saves the prompt and outputs a STRING, not CONDITIONING. Use it in workflows that send text to another node. Prepend and append inputs let you build the final text.
![Prompt Manager Text node feeding a CLIP Text Encode node](assets/readme/node-text.webp)
### Prompt Search List
Searches your library by text, category, tags and minimum rating, then outputs the matches as a list so ComfyUI runs each one. This workflow found three prompts tagged `mushroom` and made three images.
This node searches your library by text, category, tags and minimum rating. It outputs the matches as a list, so ComfyUI runs each one. This workflow found three prompts tagged `mushroom` and made three images.
![Prompt Search List node producing three images](assets/readme/node-search.webp)
To get the images of a Search List batch linked to their prompts, wire the Search List output into a Prompt Manager Text node, not straight into CLIP Text Encode. Wired straight in, the images stay unlinked: the search text is never saved as a prompt.
To link the images of a Search List batch to their prompts, wire the Search List output into a Prompt Manager Text node, not straight into CLIP Text Encode. Wired straight in, the images stay unlinked, because nothing saves the search text as a prompt.
## Install
**Requirements:** ComfyUI and Python 3.12 or newer. `watchdog` and `Pillow` are the only dependencies of their own; the rest comes with ComfyUI.
Prompt Manager requires ComfyUI and Python 3.12 or newer. Its only dependencies of its own are `watchdog` and `Pillow`. The rest comes with ComfyUI.
Install from the Comfy Registry or ComfyUI-Manager (search for Prompt Manager), or by hand:
Install from the Comfy Registry or ComfyUI-Manager by searching for Prompt Manager, or install by hand:
```bash
cd ComfyUI/custom_nodes/
@@ -185,7 +191,7 @@ pip install -r ComfyUI_PromptManager/requirements.txt
Restart ComfyUI. Click **PM** in the top bar, or **Web UI** on a node, or open `http://localhost:8188/prompt_manager/workspace`.
**Optional extras.** Nothing here is installed for you:
**Optional extras.** Prompt Manager installs none of these for you:
| To use | You need |
| --- | --- |
@@ -193,7 +199,7 @@ Restart ComfyUI. Click **PM** in the top bar, or **Web UI** on a node, or open `
| GGUF JoyCaption (about 4.5 GB) | `llama-cpp-python` |
| HuggingFace JoyCaption (about 16 GB) | `transformers`, `accelerate`, `bitsandbytes` |
| Prompts embedded in videos | `ffprobe` on PATH |
| [LoRA Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) import | LoRA Manager installed; turn it on in System > Integrations |
| [LoRA Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) import | LoRA Manager installed. Turn the import on in System > Integrations. |
Download or unload tagging models in System > Auto-tagging.
@@ -210,31 +216,40 @@ Set `PROMPT_MANAGER_DATA_DIR` to an absolute folder to keep the library somewher
## Upgrading from an earlier version
- **Python 3.12 or newer is now required.**
- **Your library stays where it is** until you choose. The workspace offers **Move library**, which makes a verified copy in `user/__promptmanager/` and renames the old files instead of deleting them, or **Keep it here**.
- **Older images:** a one-time notice offers a metadata scan that links them to prompts and negatives. Scans don't count as new runs.
- **Going back isn't supported.** Workflows are now stored once, and an older version shows new records without their workflow or prompt graph. Back up first in System > Backup & export. See [the old README's changelog](README-legacy.md#changelog) for the manual way back.
- **Your library stays where it is until you choose.** The workspace offers two choices. **Move library** makes a verified copy in `user/__promptmanager/` and renames the old files without deleting them. **Keep it here** leaves the library in place.
- **Older images.** A one-time notice offers a metadata scan that links them to prompts and negatives. Scans don't count as new runs.
- **Going back isn't supported.** Prompt Manager now stores each workflow once, and an older version shows new records without their workflow or prompt graph. Back up first in System > Backup & export. See [the old README's changelog](README-legacy.md#changelog) for the manual way back.
## The old pages will be removed
## The old pages are gone
They still work at their URLs for now and will be removed in a future release. Everything they do is moving to the workspace.
This version removes the dashboard, tags page, gallery and metadata viewer. The workspace does everything they did. Their URLs and bookmarks still work, and each one opens the matching workspace page.
| Page | URL |
| Old URL | Opens |
| --- | --- |
| Dashboard | `/prompt_manager/admin` |
| Tags | `/prompt_manager/admin#/tags` |
| Gallery | `/prompt_manager/gallery` |
| Metadata viewer | `/prompt_manager/gallery.html` |
| `/prompt_manager/admin` | Prompt library |
| `/prompt_manager/admin#/tags` | Tags & categories |
| `/prompt_manager/admin#/tags/cats,dogs?mode=or` | Prompt library, filtered to prompts tagged `cats` or `dogs` |
| `/prompt_manager/gallery` | Images |
| `/prompt_manager/gallery.html` | Inspect a file |
The documentation for those pages is in [README-legacy.md](README-legacy.md).
A tag bookmark opens the Prompt library with that filter, and the filter stays in the address: `/prompt_manager/workspace#/library?tag=cats&tag=dogs&tag_mode=any`.
- Reload, Back and Forward keep the filter.
- The address follows the tags you set in **Filters**.
- You can bookmark such a link or write one yourself. Leave out `tag_mode` to match all the tags. `tag_mode=untagged` lists prompts without a tag.
- The sidebar's Prompt library link always shows the whole library.
- Search, category and sort aren't part of the address. **Save view** keeps those.
[README-legacy.md](README-legacy.md) still describes the old pages, for reference.
## Known limits
- **Trash is Linux and macOS only.** Windows has no Recycle Bin option, because the bin can delete large files permanently without warning. On Windows you can only remove an image from the library, and the file stays on disk. Where a move to the trash isn't possible on Linux or macOS, the dialog lists why for each file.
- **Permanent delete is Linux and BSD only,** and can't be undone. The safety backup brings back the library records, not the files.
- **Show in folder** opens the file manager on the machine running ComfyUI, not necessarily the one with your browser.
- **Trash is Linux and macOS only.** Windows has no Recycle Bin option, because the bin can delete large files permanently without warning. On Windows you can only remove an image from the library, and the file stays on disk. Where a move to the trash isn't possible on Linux or macOS, the dialog lists the reason for each file.
- **Permanent delete is Linux and BSD only.** You can't undo it. The safety backup brings back the library records, not the files.
- **Show in folder** opens the file manager on the machine running ComfyUI, which may not be the machine with your browser.
- **Returned images** get their prompt links back, but not their tags, categories, collections or favorites.
- **Inspect a file** doesn't add the file to your library.
- **Leave unresolved is permanent.** A file you leave unresolved in Needs review isn't offered again unless its bytes change.
- **Leave unresolved is permanent.** Needs review doesn't offer the file again unless its bytes change.
- **Pair prompts saved by earlier versions** stay Uncategorized. You can set the category with Edit metadata.
## How it's tested
@@ -246,8 +261,12 @@ The documentation for those pages is in [README-legacy.md](README-legacy.md).
| Browser | Over 60 Playwright spec files in Chromium, Firefox, WebKit and touch emulation |
| Real ComfyUI | A pinned CPU ComfyUI, started in Classic and Nodes 2.0, running real workflows |
Every pull request runs the Python suite, the frontend tests and the browser tests in Chromium, once. Firefox, WebKit, touch emulation, Python 3.13 and 3.14, Windows and the real ComfyUI run every night. macOS is not tested; it should work, but support is best-effort. To run the tests yourself, see [TESTING.md](TESTING.md).
Every pull request runs the Python suite, the frontend tests and the browser tests in Chromium, once. Firefox, WebKit, touch emulation, Python 3.13 and 3.14, Windows and the real ComfyUI run every night. Nothing tests macOS. It should work, but support is best-effort. To run the tests yourself, see [TESTING.md](TESTING.md).
## Changelog
[CHANGELOG.md](CHANGELOG.md) lists what changed in each release and the contributors whose pull requests are part of it. Full notes are on the [releases page](https://github.com/ComfyAssets/ComfyUI_PromptManager/releases).
## License
MIT. See [LICENSE](LICENSE).
The license is MIT. See [LICENSE](LICENSE).
+251 -121
View File
@@ -514,9 +514,24 @@ file has no text chunks. Only a value shaped like a record counts (a key, a
colon, then a JSON object, array or string), so camera EXIF stays out.
`tests/test_exif_text.py` writes real still and animated WebP files, AVIF (where
Pillow has it) and JPEG in that layout; `tests/test_metadata_extraction.py` and
`tests/test_api_core.py` hold the two readers to it. No scan, monitor or
gallery list collects `.avif` yet, so AVIF files are read correctly but never
reach the readers; #652 tracks AVIF as a media type.
`tests/test_api_core.py` hold the two readers to it.
AVIF is a collected media type since #652. Every file-type list names `.avif`
(scan and deletion, the monitor's default, the gallery and thumbnail walks,
serving and Inspect, auto-tagging's listing, the capture store, the preview
source order), but Pillow's floor here is >= 10.1.0 (ComfyUI's) and Pillow
opens AVIF only from 11.0, and only when built with an AVIF decoder. So the
collection points ask `utils.media_formats.collectable` and skip an AVIF file
quietly when `PIL.features.check("avif")` is false, which leaves a Pillow
without AVIF behaving exactly as it did before. A saved
`gallery.monitoring.extensions` list that predates #652 gains `.avif` last on
load, keeping every entry the install chose. `tests/fixtures/media/comfyui_avif.avif`
is a 1 KB still written by ComfyUI's own `_save_avif` (see
`tools/make_avif_fixture.py` and `tests/fixtures/README.md`);
`tests/test_avif_media_type.py` covers both Pillow answers on the gallery
walk, the monitor, auto-tagging and the capture store, and
`tests/test_api_admin.py` holds the scan to the same fixture, prompt link
included.
Image work runs on PromptManager's own threads (#523). glibc keeps each thread's
malloc arena at its high-water mark, so image buffers spread over the default
@@ -840,7 +855,7 @@ and every other job runs for one class only:
| Class | Files | What runs |
| --- | --- | --- |
| `inert` | Only `.github/FUNDING.yml`, `SECURITY.md`, `images/`, `.github/ISSUE_TEMPLATE/` | `change class` and `gate`: green in seconds. |
| `docs` | Only `README.md`, `README-legacy.md`, `assets/readme/`, `assets/brand/` (may include inert files) | `change class` and `gate`: green in seconds. |
| `docs` | Only `README.md`, `README-legacy.md`, `CHANGELOG.md`, `assets/readme/`, `assets/brand/` (may include inert files) | `change class` and `gate`: green in seconds. |
| `release` | `pyproject.toml` alone, and in it only the `version = "..."` line rewritten | The above and `package contents` (`tests/test_package_contents.py`). |
| `code` | Anything else | The whole gate. |
@@ -860,7 +875,8 @@ else by the next code change's gate. Run
editing those files.
The pre-push hook uses the same script: it skips the Python suite when the
pushed commits are `inert` and runs it otherwise.
pushed commits are `inert`, runs only those two test modules when they are
`docs` (#679), and runs the whole suite otherwise.
## Required merge checks
@@ -1619,8 +1635,7 @@ The Images page renders the concept's DOM with real data. Its controls, top to b
(a "Media controls" group), the shared file inspector beside the stage, and Escape
returns focus to the opening image.
How the earlier workspace Images filters moved (old → new). The legacy `/gallery`,
`/admin` and `/metadata` pages are unchanged.
How the earlier workspace Images filters moved (old → new).
| Before PR C | Now |
| --- | --- |
@@ -2864,8 +2879,8 @@ applied), D35 (singular captions), D36 (sorted categories), D40 (the continuatio
the grid) and D43 (sorted chips, checked against the concept with its chips sorted).
D44 needs no mapping: the comparison runs with no Refine filter active, so the button
reads "Filters" as the concept's does. Nothing else follows the grid: the legacy
"Current prompt library" link is removed from the shelf; the legacy Library stays at
`/prompt_manager/admin` by direct URL (#525, #620)
"Current prompt library" link is removed from the shelf, and `/prompt_manager/admin` now
leads to this page (#668, D207)
(`tests/browser/workspace.spec.mjs`). `library comparison detects
mutations` injects `.card-footer { padding: 2px }` and removes `.card-meta .chip.red`.
@@ -3248,8 +3263,8 @@ appears in four places, and production draws none of them:
Data and API are unchanged: the `rating` column (`CHECK` 1–5), `PUT
/prompt_manager/prompts/{id}/rating`, `rating` in Library, Images and statistics
answers, and the server's `rating` sorts. The legacy pages keep their ratings until the
cutover (#334). Favorites (the image star) are unchanged.
answers, and the server's `rating` sorts. The old pages, which showed ratings, are gone (#668); the stored
ratings and the routes stay. Favorites (the image star) are unchanged.
Tests: units `tests/js/workspace-library-editor-state.test.js` (a prompt rated 4 edited
and saved keeps 4, no `rating` in any body, no rating field),
@@ -3372,8 +3387,8 @@ npm run --prefix tools/vendor test:workflows -- history-concept.spec.mjs \
### Inspect a file page and recorded deviations (#249 local Inspect, PR L2)
`#/inspect` ("Inspect a file") is a native workspace route; it no longer hands off to
the legacy metadata page, which stays at its URL
(`/prompt_manager/gallery.html`) at its URL only (#525, #620). The page is the concept's `#metadata`
the legacy metadata page, whose URL (`/prompt_manager/gallery.html`) now leads here (#668,
D207). The page is the concept's `#metadata`
(app.js `renderMetadata` a740–748, selection a1715–1729; style.css 709–722, 1180–1194,
1543–1545, 1559–1564) in the concept's own classes (`.surface`, `.file-drop`,
`.spaced-20`, `.local-file-preview`, all from the synced `concept.css`), with no
@@ -3576,8 +3591,8 @@ mapped differences"):
differ: numbers keep the server's spelling ("8.0" where the legacy page wrote 8); a fact
the legacy parse could not read can be known; and a negative the #249 ZeroOut guard
zeroed reads "No negative prompt found" where the legacy parse read the positive's text
through the zero-out. `workspace-file-inspector.test.js` runs the template taken from
`web/metadata.html` itself on the legacy parse of every parity PNG: 22 of 25 are
through the zero-out. `workspace-file-inspector.test.js` runs that template (a frozen copy of
`web/metadata.html`'s, taken at 3.7.2 before the page was removed in #668) on the legacy parse of every parity PNG: 22 of 25 are
byte-equal, f01b and f23 differ by the ZeroOut guard and f17 by facts the legacy parse
missed. Copying works as the concept's prompt copy: the toast "Settings summary
copied.", or, without a clipboard or when it is refused, the select-to-copy dialog
@@ -3848,13 +3863,10 @@ production hub `#/overview` is unchanged (D28); its System card opens
the pressed section button and disposes the previous section's scope, so its reads,
listeners and dialogs never outlive it.
System is the home for settings and maintenance (#330 System S13). The legacy pages keep
their prompt list, tags, Scan Images, auto-tag batch and review and gallery browsing; their
Settings, Diagnostics, View Logs, Maintenance, Backup DB, Restore DB, the gallery's
thumbnail, cache, rescan and duplicate tools and the auto-tag model downloads open the
System section that owns them in a new tab (`legacy-system-links.spec.mjs`). Each page
keeps only its own settings in Page options. What left the legacy pages is listed in
"Legacy System UI removed by S13".
System is the home for settings and maintenance (#330 System S13). The old admin and
gallery pages, which first handed these jobs to System through links, are gone (#668,
D207); "Legacy System capability coverage" names the System control or the ruling for
each capability they had.
Drafts (`system-state.mjs`) live for the page session (Q10). Save writes the dirty
browser fields, then the host fields (`POST /prompt_manager/settings` with
@@ -3875,8 +3887,7 @@ Optimized→`medium`, Original→`high`, Fast→`low`; the thumbnail dialog's pr
once S5 lands), the three video rows (`videoAutoplay`, `videoMute`, `videoLoop`) and Show
file paths (`showFilePaths`). A write re-reads the stored object and writes back only the
changed keys, every other key (legacy paging, thumbnail state, unknown keys) as stored;
the legacy gallery's Save also keeps the keys it does not edit, so the two pages stay in
sync. The workspace never reads the legacy paging keys (`defaultLimit`, `gridColumns`,
so a key the old gallery page stored (removed in #668, D209) is never lost. The workspace never reads the legacy paging keys (`defaultLimit`, `gridColumns`,
`infiniteScroll`; README continuous-browsing ruling). A browser that refuses storage
(denied, or a full quota that leaves the stored bytes as they were) keeps the change for
this tab only and the status says "Saved for this tab only; browser storage is
@@ -4003,7 +4014,7 @@ batch and all 9 previews are written, where a stream that stops on disconnect le
The gallery's Cancel (its settings panel and the startup dialog) cancels by that id,
and only a job its own stream started: a Cancel before the `job` frame keeps the stream
open until it arrives, a double Cancel posts once, and a job another tab or System
started keeps running while the gallery stops following it (`tests/js/gallery-thumbnails.test.js`).
started keeps running while the gallery stops following it. The gallery page that used this stream is gone (#668); the route stays.
A job cancelled from Activity ends the stream with the error frame "Thumbnail
generation was cancelled". The blocking
`POST /images/generate-thumbnails` and the clear stay legacy holds.
@@ -4452,6 +4463,38 @@ the per-section hand-off panel, was retired by S12 (#329): every section is nati
node runs saved, from their saved pairs. Only empty fields of never-edited prompts."
`system-maintenance-concept.spec.mjs` maps it (`mapPairRow`) as a copy of Optimize
database's row.
- **D210** (Maintenance and Integrations, #618, beyond the concept): Database adds "Tag
cleanup" after "Pair category and tags", with the line "Find tags that are whole comma
lists or are used nowhere. Review them, then remove only what you tick." and the button
"Find tags" with a danger mark (it ends in deleting tags, like Unused prompt
components). The button starts the tag search as an Activity job and opens it, as Find
duplicates does (`startFind`): kind `tag_cleanup`, pill "Finding tags", toasts "Tag
search started." and "Tag search finished · N tags found", one tile and outcome
"Found", log "Search log", no Cancel; its rows are tags (records, never opened). A
finished search that found tags adds **Review tags** (primary) after Download report.
It opens "Review tag cleanup" (`web/js/workspace/tag-cleanup-review.mjs`), drawn from
whatever rules the server returns: a `p.small[role=status]` "N tags selected", then per
rule with findings a checkbox "<title> (<total>)" that ticks or clears every listed tag
(indeterminate while only some are), a `p.small` with its explanation and what applying
does, a closed `details` "Show tags" whose checkbox rows "<name> · <detail>" are built
when it first opens (names wrap anywhere, CSS under D210), and, when the server's cap
of 2,000 cut the list, "Only the first 2,000 are listed. Clean these up, then search
again."; then "Nothing is deleted until you review and apply the cleanup. Prompts, pairs
and images are kept; only the tag is removed from them." and Cancel / "Review cleanup"
(disabled while nothing is ticked). Nothing is ticked when it opens. Review cleanup
opens the D100 plan "Tag cleanup" (Scope "Delete N tags (removed from P prompts, Q
pairs and R images)", Protected "N tags changed since the search", Backup "Always
created and verified first", Media "No files are removed"). A failed Tag cleanup job's
Review again goes to Maintenance (its plan needs a search). Integrations' LoRA import
review adds the row **Trigger words** after Found, only when a count is above 0: "N
become tags · M not made tags (lists or sentences)", or "N become tags" when M is 0.
`system-maintenance-concept.spec.mjs` maps the row (`mapTagRow`) as a copy of Unused
prompt components' row with the label "Find tags"; `system-integrations-concept.spec.mjs`
maps the Trigger words row. Tests: `D210: Tag cleanup finds comma and unused tags,
reviews only the ticked rule and deletes only it (#618)`
(workspace-system-maintenance.spec, hook `/__test__/system/tag-cleanup`),
`workspace-tag-cleanup-review.test.js`, `tests/test_tag_cleanup.py`,
`tests/test_api_tag_cleanup.py`.
- **D102** (Maintenance, S7, Q5, #222): Metadata cache clears only the browser entries
Prompt Manager owns as a cache (`web/js/cache-ownership.js`). The inventory of every
storage writer has none (see "Browser cache ownership" below), so the row's line adds
@@ -5115,6 +5158,54 @@ Tests: `tests/test_maintenance_pair_metadata.py`, `tests/test_api_maintenance_pa
`tests/browser/workspace-system-maintenance.spec.mjs` (hook `/__test__/system/pair-metadata`).
A Python change: ComfyUI needs a restart.
#### Tag cleanup (#618)
`tag_cleanup` ("Tag cleanup", D210) is in `MAINTENANCE_OPERATIONS` but is never
previewed alone (`preview_maintenance("tag_cleanup")` raises): it is planned from a tag
search's findings. `database/tag_cleanup.py` holds a registry of rules (`RULES`, each a
`TagRule` with `find`, `recheck` and `apply`); registry order is review order and
ownership: a tag is listed only under the first rule that finds it. Two rules ship:
- `comma`, "Tags containing a comma": a name holding `,` or `,` (U+FF0C), except a name
starting with `lora:` (the LoRA import's identity tag, made again by every import;
maintainer ruling 2026-11-22). Applying removes the tag from its prompts, pairs and
images and deletes it. Removed only: never split.
- `unused`, "Tags with no links": no `prompt_tags`, `prompt_pair_tags` or
`media_image_tags` row (image links count as none when the annotation tables are
missing). Deleted. A tag made by hand and not used yet is listed too (the schema does
not record who made a tag); nothing is pre-ticked.
`POST /prompt_manager/jobs/tag_cleanup` (body ignored) starts the find: kind
`tag_cleanup`, "Find tags to clean up", admission `read`, not cancellable, group `found`
(one row "<name> · <rule title>" per tag). It reads one `mode=ro` snapshot, writes
nothing, holds the result under the job id (the last 3 finds) and ends "Found N tags to
clean up" or "No tags need cleaning up"; a failure ends it "The tag search failed." A
second find while one runs, or beside an exclusive job, is 409 `busy`. `GET
/prompt_manager/maintenance/tag_cleanup/{job_id}` (`no-store`) answers every rule with
its findings `{tag_id, name, detail}` (at most 2,000 per rule; `total` exact; `detail`
"3 prompts · 1 pair", "no links", plus " · in N saved views" when saved views name it);
404 `not-found`, 409 `job-running`, 409 `no-groups`. The preview's options are exactly
`{job_id, select:[{rule, tag_ids}]}`: a known rule once each, 1 to 2,000 distinct tag ids,
each a held finding of that rule, else 400 `invalid-request`; the body has the large cap
(500 ids are not 413). Each selected finding is read again: one whose `(tag_id, name,
links)` changed since the search (`links` hashes its prompt ids, pair ids and image
`(byte_id, position)` rows, so a tag moved between owners is seen) is protected, "N tags
changed since the search". The plan's backup policy is always `required`: the apply
takes a safety backup first even when the setting is off (`ALWAYS_BACKED_UP`, with
`workflow_storage`). The apply job ("Tag cleanup", `maintenance`, `records`) runs in one
`BEGIN IMMEDIATE` transaction and does not compare the plan's fingerprint: each target's
rule rechecks it and keeps it with its reason (`already deleted`, `renamed since the
review`, `it is used now`, `its links changed since the review`, or `kept so the old tag
migration does not run again` when deleting it would empty `tags` while a prompt still
holds legacy JSON tags), and the rest still apply; an exception rolls everything back.
Changed rows read "Deleted tag “<name>” (<rule title>) · removed from 3 prompts",
Protected rows "Kept tag “<name>”: <reason>" (the review's protected findings first),
both complete in the report. Saved views, the auto-tag marks, the LoRA trigger cache and
history are never written. Tests: `tests/test_tag_cleanup.py`,
`tests/test_api_tag_cleanup.py`, `tests/test_vocabulary.py` (the shared `_delete_tag`),
`tests/browser/workspace-system-maintenance.spec.mjs`. A Python change: ComfyUI needs a
restart.
The legacy restore (`POST /prompt_manager/restore`) takes a backup of any size the disks
have room for, so a real library's safety backup restores: the upload, its staged copy
and the swap (the upload twice in the temporary folder, once more plus the current
@@ -5347,7 +5438,8 @@ legacy scan refuses it.
nothing (`test_preview_writes_nothing_and_makes_no_requests`: DB and `-wal` bytes, `-shm`
size, rows, no cache folder, the downloader never called) and answers the maintenance
`Plan` shape plus `lora_files`, `with_metadata`, `current_imports`, `blocked_by_pairs`,
`planned_downloads` and `network`; a blocked plan has no token. `POST
`planned_downloads`, `trigger_tags`, `trigger_not_tags` and `network`; a blocked plan
has no token. `POST
/prompt_manager/lora/import/apply {token}` starts the `lora_import` job (202): title "LoRA
reference import", admission `records`, cancellable only while it stages, the safety
backup the policy promises before the replace. Refusals: `plan-changed` (409, the files
@@ -5380,6 +5472,19 @@ refused while a restore runs; the review is a request lease ("LoRA import review
accepts the optional `expected_revision`. LoraManager detection also searches every
`custom_nodes` folder ComfyUI registers through `folder_paths` (#144), main folder first.
**Trained words as tags (#618).** A CivitAI `trainedWords` entry becomes a tag only when
it is one short clean phrase (`lora_utils.is_tag_phrase`, Option A): stripped, it passes
the tag rule (`validate_tags`: not empty, at most 50 characters, no control character),
holds no ASCII or fullwidth comma, no `<` or `>` (`<lora:x:0.8>`) and no prompt weight
(`(masterpiece:1.2)`); plain parentheses stay (`hatsune miku (vocaloid)`), and `ratio
(16:9)` is a recorded loss. `trigger_word_tags` returns the tags and how many entries were
not made tags; `build_record` adds `trigger_not_tags`, the preview sums `trigger_tags` and
`trigger_not_tags`, the review's Trigger words row shows them (D210) and the job logs "M
trained-words entries were not made tags (lists or sentences)". The trigger-word lookup
(`get_trigger_words_from_metadata`, the trigger cache) still sees every entry. Tests:
`TestTriggerWordTags`, `test_build_record_makes_tags_only_from_short_phrases`,
`test_preview_and_job_say_how_many_entries_were_not_made_tags`.
**Where LoraManager keeps its files (#355).** `py/lora_manager_layout.py` repeats
LoraManager's rules without importing it (`tests/test_lora_manager_layout.py`). The
settings file is `<LORA_MANAGER_SETTINGS_DIR>/settings.json`, else the plugin's own
@@ -5615,8 +5720,9 @@ images", "Tag output images (legacy page)", "Tagging one image (legacy page)",
is pinned by `tests/test_autotag_schema.py` (forward-only: one empty `WITHOUT ROWID`
table, optional in old backups, refused without the annotation group).
- **The legacy pages (#379, PR 2)** write image tags, never prompt tags.
`POST /autotag/start` (the admin and gallery batch) reads `model_type`, `prompt`,
- **The old pages' auto-tag routes (#379, PR 2)** write image tags, never prompt tags.
The pages that called them are gone (#668); the routes stay until each is reviewed.
`POST /autotag/start` (the old admin and gallery batch) reads `model_type`, `prompt`,
`skip_tagged` (Skip or Merge), `keep_in_memory` and the thresholds (else the saved
ones), checks them with `validate_options` (WD14: both thresholds; GGUF/HF:
`instructions` = the non-blank `prompt`, else the saved template; the saved
@@ -5624,8 +5730,7 @@ images", "Tag output images (legacy page)", "Tagging one image (legacy page)",
page)" (gate owner `legacy-batch`) through the native start, so the safety backup and
the disk check apply. A second legacy batch answers JSON 409 `{success: false, error:
"Auto-tagging is already running"}` (also when another legacy start wins the race past
that check); `SseStream` hands a non-2xx JSON `error` to `onerror` as `serverMessage`,
which both pages show instead of "Connection lost during auto tagging". Any other refusal (a job in the way: "<title>
that check). Any other refusal (a job in the way: "<title>
already running", `model-unavailable`, `insufficient-space`, `model-busy`, a bad
option) is one `{type: "error", status: "error", message}` frame. The stream relays
the job: the phases as `{type: "progress", progress: 0 | 5 | 8, status: "Taking a
@@ -5650,15 +5755,7 @@ images", "Tag output images (legacy page)", "Tagging one image (legacy page)",
added_tags, total_tags}`; an empty list only marks the image. A body with `prompt_id`
is `400` "This page is out of date. Reload it."; a changed file `409 file-changed`
("The image changed since its tags were generated."); a full set `409 tag-limit`; a
restore `409 storage-changed`. The admin review asks each image with Skip first: an
auto-tagged one shows "Image Already Auto-tagged" / "A tagging model already tagged
this image. Generate new tags?" with its image tags (Skip, Skip All Tagged, Re-tag asks
again with Merge); the gallery review always merges. Apply & Next sends the image and
its `sha256` (linked or not). The batch copy: "Skip images already auto-tagged",
"Auto tagging complete! Tagged N images." ("1 image"), and under both progress bars
"Closing this window stops tagging. Tags already added are kept. Prompt Manager's
Activity page shows the time left.". Pinned by `tests/test_autotag_legacy.py`,
`tests/js/image-helpers.test.js` and `legacy-autotag.spec`.
restore `409 storage-changed`. Pinned by `tests/test_autotag_legacy.py`.
- **Tag image dialog marks (DEC4).** A save after Generate suggestions ran on that
capture marks the image auto-tagged (also a replayed save, and a saved retry after
`tag-conflict`); a save without Generate does not. The API keeps the suggested capture
@@ -5758,9 +5855,10 @@ line read `database_info.size_bytes`, a key the report does not have, so it alwa
### Legacy System capability coverage
Every System capability of the legacy admin and gallery pages has an owner (#249 System
S12, #329). Status is `covered` (a native control replaces it), `kept in legacy` (it stays
on the legacy page, which keeps working) or `approved removal` (a ruling retired it). Native
Every System capability the old admin and gallery pages had has an owner (#249 System
S12, #329). Status is `covered` (a native control replaces it) or `approved removal` (a
ruling retired it). The old pages are gone (#668, D207), so nothing is "kept in legacy" any
more: D209 records where its four rows went. Native
control is `` `<section>` · <role> · "<accessible name>" ``, `<section>` a System hash id
and `<role>` one of button, combobox, switch, slider, spinbutton, textbox, group, status or
term, followed by ` · in "<row title>"` when several rows of the section share the name.
@@ -5768,13 +5866,10 @@ Every `covered` row names one, except the rows in `CONTROL_EXEMPTIONS`
(`tools/vendor/legacy-coverage.mjs`), each with its reason: today only "Gallery per-image
auto-tag / review", which the Images selection bar owns, not a System section. A row that
is not `covered` names none (`—`). Test is the exact title of a test that runs, then its
file. Anchors are line numbers on `main` at this PR.
S13 (#330) removed the legacy copy of the `covered` rows the legacy pages linked to System;
"Legacy System UI removed by S13" below lists every removed element against its row.
file. Legacy anchor is history: the lines are those of the deleted files in 3.7.2.
`tests/vendor/legacy-coverage.test.mjs` fails on a row with any of these problems:
- no owner, or a status outside the three;
- no owner, or a status outside the two;
- a malformed Native control cell;
- a covered row without a control (unless exempt), or a control on a row that is not
covered;
@@ -5796,7 +5891,7 @@ list stay unscoped: any row's control proves them.
| Monitoring enabled | `py/config.py:212,248` | S4 Sources | covered | `sources` · switch · "Watch for new outputs" | Watch for new outputs saves monitoring_enabled; a restart applies it (workspace-system-sources.spec.mjs) |
| Search results auto-hide `result_timeout` | `admin.html:407–412` | S3 Appearance | covered | `appearance` · spinbutton · "Node search auto-hide (seconds)" | host fields round-trip through /settings with revision (workspace-system.spec.mjs) |
| Web UI display mode | `admin.html:414–422` | S3 Appearance | covered | `appearance` · combobox · "Open from ComfyUI" | host fields round-trip through /settings with revision (workspace-system.spec.mjs) |
| Infinite scrolling default | `admin.html:424–430`; `admin.js:689–727` | Legacy prompt list (README continuous browsing); read-only in the report | kept in legacy | — | shouldLoadMore asks for the next page only near the bottom with pages left (list-state.test.js) |
| Infinite scrolling default | `admin.html:424–430`; `admin.js:689–727` | Retired with the old prompt list (D209): the Library always continues; `web_ui.infinite_scroll` stays read-only in the report | approved removal | — | library infinite loading keeps unique parents and keyboard-accessible history controls (workspace-library.spec.mjs) |
| Worker threads | `admin.html:437–445` | S4 Sources | covered | `sources` · slider · "Worker threads" | worker range max is cpu_count (workspace-system-sources.spec.mjs) |
| LoraManager badge, enable, path, trigger words, CivitAI key, clear key | `admin.html:448–490`; `admin.js:1052–1156` | S10 Integrations | covered | `integrations` · switch · "LoraManager integration" | LoRA rows show detected / enabled / cache-loaded separately (workspace-system-integrations.spec.mjs) |
| LoRA data import with progress | `admin.html:492–498,517–541`; `admin.js:1157` | S10 Integrations | covered | `integrations` · button · "Review import" | Review import shows replacement, blocked items and network effects with the backup box; Start opens the job (D107) (workspace-system-integrations.spec.mjs) |
@@ -5839,69 +5934,13 @@ list stay unscoped: any row's control proves them.
| Video autoplay, mute, loop | `gallery-settings.js:40–42` | S3 Appearance | covered | `appearance` · switch · "Autoplay videos" | video defaults reach the viewer (workspace-system.spec.mjs) |
| Image info on cards; sidebar collapsed | `gallery-settings.js:30,34` | S3 Appearance | covered | `appearance` · switch · "Show image details on cards" | added rows reach their consumers (workspace-system.spec.mjs) |
| Reset gallery settings | `gallery.js:1813` | S3 Appearance | covered | `appearance` · button · "Reset" | reset restores defaults without touching other keys (workspace-system.spec.mjs) |
| Lazy loading | `gallery-settings.js:25` | Legacy gallery (native always lazy) | kept in legacy | — | a legacy gallery Save keeps the workspace keys and every other stored key (gallery-settings.test.js) |
| Lazy loading | `gallery-settings.js:25` | Retired with the old gallery (D209): Images always loads lazily; the stored key is kept | approved removal | — | stored values override defaults and unknown keys are kept (gallery-settings.test.js) |
| Results per page / grid columns / paged mode | `gallery-settings.js:28–29,35` | README continuous browsing | approved removal | — | numeric strings from <select> values are accepted and columns are clamped (gallery-settings.test.js) |
| Startup thumbnail prompt | `gallery-settings.js:38–39`; `gallery.js:2578` | README; Overview thumbnail row | approved removal | — | thumbnail row reflects the status endpoint (workspace-system.spec.mjs) |
| Client debug output `debugMode` | `gallery-settings.js:36` | Legacy gallery (S12-10) | kept in legacy | — | a legacy gallery Save keeps the workspace keys and every other stored key (gallery-settings.test.js) |
| API timeout `apiTimeout` | `gallery-settings.js:37` | Legacy gallery (S12-10; read by no request) | kept in legacy | — | defaults are a complete, sane settings object (gallery-settings.test.js) |
| Client debug output `debugMode` | `gallery-settings.js:36` | Retired with the old gallery (D209, S12-10): Diagnostics & logs is the workspace's tool; the stored key is kept | approved removal | — | stored values override defaults and unknown keys are kept (gallery-settings.test.js) |
| API timeout `apiTimeout` | `gallery-settings.js:37` | Retired with the old gallery (D209, S12-10): no request ever read it; the stored key is kept | approved removal | — | defaults are a complete, sane settings object (gallery-settings.test.js) |
| config.json-only keys | `py/config.py:212–234,722–739`; `py/api/diagnostics_report.py:185` | S12 report (read-only) | covered | `diagnostics` · button · "Download diagnostic report" | test_report_lists_config_only_keys (test_api_diagnostics_report.py) |
### Legacy System UI removed by S13
System S13 (#330) points the legacy pages' System buttons at native System (a link that
opens `workspace#/system/<id>` in a new tab) and removes the legacy copy of a capability
only when its row above is `covered`. One row per removed capability: Capability is the
exact Capability cell of its coverage row, Page is `admin` or `gallery`, Removed ids and
Removed methods list what went (`—` for none), and Native test copies that row's Test
cell. An id that stays on a System link is not listed, only its handler. The gallery's
Default View Mode left Page options too: System › Appearance's Default layout is the one
default-layout control. Nothing writes the legacy `defaultViewMode` any more; a stored
value still picks the view the legacy gallery opens in (grid otherwise), and Page options
Save and Reset keep it.
`tests/vendor/legacy-coverage.test.mjs` fails when a row cites a capability that is not
`covered` or copies another test, when an id or method is listed twice for one page, or
when a listed id is still on its page (`id="…"` in the markup or the script, a
`getElementById`/`querySelector('#…')` lookup, an entry of a modal-id list) or a listed
method is still defined or called (`.name(`). A deletion listed nowhere is caught by the
kept-flow tests (`kept admin flows still work` in `legacy-system-links.spec.mjs` and the
legacy page workflows), not by this check.
| Capability | Page | Removed ids | Removed methods | Native test |
| --- | --- | --- | --- | --- |
| Diagnostics run | admin | `#diagnosticsModal`, `#runDiagnosticsBtn`, `#diagnosticsContent` | `showDiagnosticsModal()`, `closeDiagnostics()`, `runDiagnostics()`, `renderDiagnostics()` | Run checks opens the shared Health report (workspace-system-diagnostics.spec.mjs) |
| Synthetic image-link test | admin | `#testImageLinkBtn` | `testImageLink()` | Create test link confirms first and names the prompt (workspace-system-diagnostics.spec.mjs) |
| View logs with level and limit | admin | `#logsModal`, `#logLevel`, `#logLimit`, `#refreshLogsBtn`, `#logsContainer` | `showLogsModal()`, `closeLogs()`, `refreshLogs()`, `displayLogs()` | level filter is minimum-level over all six choices (workspace-system-diagnostics.spec.mjs) |
| Log statistics | admin | `#logStatsTotal`, `#logStatsErrors`, `#logStatsWarnings`, `#logStatsLevel`, `#logStatsSize` | `loadLogStats()`, `formatBytes()` | log statistics show entries, errors, warnings, files and size (workspace-system-diagnostics.spec.mjs) |
| Log files list and download | admin | `#downloadLogsBtn`, `#logFilesList` | `loadLogFiles()`, `downloadLogs()`, `downloadLogFile()` | each listed file downloads by its returned name and a link has no Download (workspace-system-diagnostics.spec.mjs) |
| Clear/truncate logs | admin | `#clearLogsBtn` | `clearLogs()` | Clear all logs states both counts, confirms first and reads everything again (workspace-system-diagnostics.spec.mjs) |
| Set log level (incl. CRITICAL), console logging | admin | `#updateLogConfigBtn`, `#setLogLevel`, `#consoleLogging` | `loadLogConfig()`, `updateLogConfig()` | runtime level (including CRITICAL) and console logging save and say they apply until the server restarts (workspace-system-diagnostics.spec.mjs) |
| Image scan directories add/remove | admin | `#scanPathsList`, `#addScanPathBtn` | `renderScanPaths()`, `addScanPath()`, `removeScanPath()`, `_collectScanPaths()` | Add source validates on the server, then marks the host draft dirty; Save persists (workspace-system-sources.spec.mjs) |
| Currently monitoring list + Refresh | admin | `#refreshMonitoringStatus`, `#monitoringStatus` | `updateMonitoringStatus()` | watching only with a live observer; restart pending otherwise (workspace-system-sources.spec.mjs) |
| Search results auto-hide `result_timeout` | admin | `#resultTimeout` | — | host fields round-trip through /settings with revision (workspace-system.spec.mjs) |
| Web UI display mode | admin | `#webuiDisplayMode` | — | host fields round-trip through /settings with revision (workspace-system.spec.mjs) |
| Worker threads | admin | `#workerThreads`, `#workerThreadsValue` | `renderWorkerThreads()` | worker range max is cpu_count (workspace-system-sources.spec.mjs) |
| LoraManager badge, enable, path, trigger words, CivitAI key, clear key | admin | `#loraDetectionBadge`, `#loraEnabled`, `#loraSettings`, `#loraManagerPath`, `#loraTriggerWords`, `#civitaiApiKey`, `#clearCivitaiKey` | `detectLoraManager()`, `_bindLoraEvents()`, `saveLoraSettings()` | LoRA rows show detected / enabled / cache-loaded separately (workspace-system-integrations.spec.mjs) |
| LoRA data import with progress | admin | `#loraImportModal`, `#loraImportBtn`, `#loraImportStatus`, `#loraImportPercent`, `#loraImportBar`, `#loraImportProcessed`, `#loraImportImported` | `runLoraImport()` | Review import shows replacement, blocked items and network effects with the backup box; Start opens the job (D107) (workspace-system-integrations.spec.mjs) |
| Maintenance cleanup_duplicates, vacuum, cleanup_orphaned_images, prune_orphaned_prompts | admin | `#maintenanceModal`, `#cleanup_duplicates`, `#vacuum`, `#cleanup_orphaned_images`, `#prune_orphaned_prompts`, `#runMaintenanceBtn`, `#maintenanceResults` | `showMaintenanceModal()`, `closeMaintenance()`, `runMaintenance()`, `renderMaintenanceResults()` | Apply reviewed operation closes, toasts, opens the job in Activity (workspace-system-maintenance.spec.mjs) |
| Maintenance check_hash_duplicates, check_consistency | admin | `#check_hash_duplicates`, `#check_consistency` | — | Run health checks opens Health report and updates metric 4 (workspace-system.spec.mjs) |
| Maintenance statistics (database info) | admin | `#statistics` | — | meta-grid shows real database and source status, the pinned Viewer.js version and the host renderers (workspace-system-diagnostics.spec.mjs) |
| Maintenance select all / clear all / run | admin | `#selectAllMaintenanceBtn`, `#clearAllMaintenanceBtn` | `selectAllMaintenance()`, `clearAllMaintenance()` | plan dialog shows the server's scope, protected, backup policy and media lines with the backup box (D100); Cancel writes nothing (workspace-system-maintenance.spec.mjs) |
| Database backup | admin | — | `backupDatabase()` | Back up downloads through the api client and revokes the object URL (D103) (workspace-system-backups.spec.mjs) |
| Restore from file | admin | `#restoreModal`, `#restoreFileInput`, `#confirmRestore`, `#cancelRestore` | `showRestoreModal()`, `confirmRestore()` | Review restore stages the chosen file and shows the real summary with the backup box (D105) (workspace-system-backups.spec.mjs) |
| Gallery thumbnail generation | gallery | `#generateThumbnailsBtn`, `#thumbnailStatus`, `#thumbnailProgress`, `#progressText`, `#progressPercent`, `#cancelThumbnailsBtn`, `#progressBar`, `#progressDetails`, `#progressETA` | `generateThumbnails()`, `generateThumbnailsWithProgress()` | Start closes the dialog, toasts, and opens the job in Activity (workspace-system-sources.spec.mjs) |
| Default view mode, image quality | gallery | `#defaultViewModeSelect`, `#imageQualitySelect` | — | defaults apply to a new visit but not to the current view or a saved view (workspace-system.spec.mjs) |
| Image info on cards; sidebar collapsed | gallery | `#showImageInfoToggle`, `#sidebarCollapsedByDefaultToggle` | — | added rows reach their consumers (workspace-system.spec.mjs) |
| Video autoplay, mute, loop | gallery | `#videoAutoplayToggle`, `#videoMuteToggle`, `#videoLoopToggle` | — | video defaults reach the viewer (workspace-system.spec.mjs) |
| Auto-load metadata, cache metadata, show file paths | gallery | `#autoLoadMetadataToggle`, `#cacheMetadataToggle`, `#showFilePathsToggle` | — | metadata off shows an explicit load and loads once on request (workspace-system.spec.mjs) |
| Browser cache clear | gallery | `#clearCacheBtn` | `clearCache()` | Metadata cache reviews and clears only owned browser entries when there are some (D102) (workspace-system-maintenance.spec.mjs) |
| Clear server thumbnails | gallery | — | — | Thumbnail cache opens the S5 dialog (workspace-system-maintenance.spec.mjs) |
| Refresh file listing | gallery | `#rescanFolderBtn` | `rescanFolder()` | Refresh files calls /gallery/rescan and toasts its counts (workspace-system-sources.spec.mjs) |
| Duplicate image scan, review, delete | gallery | `#scanDuplicatesBtn`, `#dupScanPill`, `#dupScanPillText`, `#duplicatesModal`, `#closeDuplicatesBtn`, `#duplicatesScanStatus`, `#dupProgressText`, `#dupProgressBar`, `#duplicatesContent`, `#duplicatesList`, `#duplicatesFooter`, `#duplicatesCount`, `#selectAllBtn`, `#removeDuplicatesBtn` | `scanDuplicates()`, `attachDuplicateStream()`, `resumeDuplicateScan()`, `applyDuplicateEvent()`, `renderDuplicateProgress()`, `setDuplicateButton()`, `showDuplicatePill()`, `hideDuplicatePill()`, `openDuplicatesModal()`, `showDuplicatesModal()`, `hideDuplicatesModal()`, `displayDuplicates()`, `selectAllDuplicates()`, `removeDuplicates()` | Find duplicates starts a job; its view links Review groups; Keep radios build a duplicate_files plan (D101) (workspace-system-maintenance.spec.mjs) |
| Auto-tag model download | admin | `#autoTagDownloadModal`, `#downloadModelName`, `#downloadStatus`, `#downloadProgressPercent`, `#downloadProgressBar`, `#cancelDownloadBtn` | `downloadModel()`, `cancelDownload()` | Download starts the job and Activity shows it without Cancel (workspace-system-tagging.spec.mjs) |
| Auto-tag model download | gallery | `#autoTagDownloadModal`, `#downloadModelName`, `#downloadStatus`, `#downloadProgressPercent`, `#downloadProgressBar`, `#cancelDownloadBtn` | `downloadModel()`, `cancelDownload()` | Download starts the job and Activity shows it without Cancel (workspace-system-tagging.spec.mjs) |
| Unload model | gallery | — | `unloadModel()` | Unload is enabled only while a model is loaded, and a held gate's refusal names the operation (workspace-system-tagging.spec.mjs) |
### Browser cache ownership (#222)
The legacy gallery's Clear cache used to delete every localStorage key starting `pm_` or
@@ -5921,8 +5960,8 @@ storage` pins those patterns. It skips `web/lib` (third-party builds) and the pi
Toolkit build (`web/js/shared/toolkit`, never hand-edited, verified by `npm run check`;
its storage belongs to the Toolkit repository and a new pin is reviewed on its own). Since
System S13 (#330) the legacy gallery no longer offers Clear cache: System › Maintenance's
Metadata cache and Thumbnail cache reviews own both parts (removal table above), and
`cache-ownership.js` serves the native review.
Metadata cache and Thumbnail cache reviews own both parts, and
`cache-ownership.js` serves the native review. The old gallery itself is gone (#668).
The duplicates dialog's View Full named its source (`?root=<index>`, with the path
URL-encoded) when the gallery's output folder is a listed source
@@ -6078,8 +6117,7 @@ anywhere else. The setting is `thumbnails.location` in config.json, and only the
- **Remove thumbnails of removed sources** (`scope.mode` `prune`). It is offered in Thumbnail maintenance only in
folder mode, and it touches only this install's keys.
- **Page tests.** `tests/browser/workspace-thumbnail-location.spec.mjs` covers the row, both moves, the in-place
refusal, the confirmation, the notice with Recreate and with Use this folder. The legacy gallery runs once in
folder mode (`workflows.spec.mjs`). The hooks are `tests/browser/thumbnail_location_fixture.py`.
refusal, the confirmation, the notice with Recreate and with Use this folder. The hooks are `tests/browser/thumbnail_location_fixture.py`.
Beyond the concept, against the approved static mock `docs/egm/post-3.4.1/320-mock`:
@@ -7732,13 +7770,13 @@ Deploying this backend needs a ComfyUI restart (Python and route changes).
## Native vocabulary UI (#236)
`#/tags` ("Tags & categories", page title "Tags") is a native workspace route; it no
longer hands off to the legacy tag manager. That page stays at
`/prompt_manager/admin#/tags` at its URL only (#525, #620); tag search and sort, the untagged
longer hands off to the legacy tag manager, whose URL `/prompt_manager/admin#/tags` now leads
here and whose tag-filter bookmarks open the filtered Library (#668, D207); tag search and sort, the untagged
entry (D149) and multi-tag OR (the Library's Tag match, D150) moved to the workspace
(#444); bulk prompt delete stays on the legacy admin page (bulk tags: the Prompt
library's selection bar, D151). A prompt's category is changed in the Prompt library
editor, on many prompts at once with the Prompt library's selection bar (D148, #437), or
with the legacy admin page's "Set Category" (both `POST /prompt_manager/bulk/category`);
(#444); bulk prompt delete is the Prompt library's Delete… (#443, D152) and bulk tags its
selection bar (D151). A prompt's category is changed in the Prompt library
editor, or on many prompts at once with the Prompt library's selection bar (D148, #437;
`POST /prompt_manager/bulk/category`);
the Images selection bar's Set category sets images' own categories only (D140, #332),
and Manage category renames a value on prompts, recipes and images together (D144). The screen consumes only the `/prompt_manager/vocabulary/*` routes
above and adds no route, so PR B needed no ComfyUI restart; D149 (#444) adds read
@@ -7861,9 +7899,8 @@ floors in `frontend-coverage-baseline.json`.
The top-bar PM button, both Web UI buttons and `/prompt_manager/web` open
`/prompt_manager/workspace#/library` (`web/js/workspace-entry.js`; `web/index.html` keeps its
own copy, pinned by `tests/js/workspace-entry.test.js`). Overview's cards open native hashes.
The legacy pages (`/prompt_manager/admin`, `admin#/tags`, `gallery`, `gallery.html`) stay at
their URLs, and admin's Metadata and Gallery buttons still open their legacy pages (maintainer
ruling; pinned by `legacy-system-links.spec.mjs`).
The old pages' URLs (`/prompt_manager/admin`, `admin#/tags`, `gallery`, `gallery.html`) lead into
the workspace since #668 ("Old pages retired" below).
- **D165 retired** (#620): the old pages show their removal notice since 3.5.1, so System no longer links them and the load failure below offers a reload and ComfyUI. The original ruling:
**D165** (beyond the concept, maintainer ruling 2026-10-30): System's Overview section ends
@@ -7871,8 +7908,101 @@ ruling; pinned by `legacy-system-links.spec.mjs`).
(`.legacy-pages`, new tabs), outside `.settings-layout`. The concept has no such line;
`mapOverviewConcept` adds it to the page tree.
- **Load failure** (maintainer ruling 2026-10-30): `web/workspace.html` holds static
`#workspace-boot-failure` with the same four links, styled inline so it needs no stylesheet.
`#workspace-boot-failure` (since #620 a reload link and a link back to ComfyUI), styled inline so it needs no stylesheet.
An inline guard shows it at `load` unless `index.mjs` set `data-workspace-booted`, so a failed
fetch of any module and a throw while starting are both covered; `workspace.spec.mjs` tests
both. Editing `workspace.html` needs a ComfyUI restart, because the server caches it. The PM button has no
page-fixture test; it is proven on the managed host (`tests/comfyui/prompt-manager.spec.mjs`).
## Old pages retired (#668)
The old admin, gallery and metadata pages, their controllers (`admin.js`, `gallery.js`,
`tags-page.js`), the ten helper modules only they loaded and the vendored Tailwind build are
deleted. The removal notice shipped in 3.5.1. Backend routes only those pages called are
unchanged; each is reviewed on its own later, and
`tests/test_legacy_contract_snapshot.py` still pins the whole route table and the settings
keys. Older sections of this file still say "legacy route" or "legacy page" where they
describe those routes' contracts.
- **D207** (maintainer ruling 2026-11-02; bookmark form ruled 2026-11-21): every old URL leads
into the workspace.
| Old URL | Lands on |
| --- | --- |
| `/prompt_manager/gallery` | `workspace#/images` (HTTP 302) |
| `/prompt_manager/gallery.html` | `workspace#/inspect` (HTTP 302) |
| `/prompt_manager/admin`, or with a hash that is not a tags route | `workspace#/library` |
| `/prompt_manager/admin#/tags`, or `#/tags/` with an empty list | `workspace#/tags` |
| `/prompt_manager/admin#/tags/a,b` | `workspace#/library?tag=a&tag=b` |
| `/prompt_manager/admin#/tags/a,b?mode=or` | `workspace#/library?tag=a&tag=b&tag_mode=any` |
| `/prompt_manager/admin#/tags/__untagged__` (alone or among tags) | `workspace#/library?tag_mode=untagged` |
The two 302 answers carry a relative `Location`, so a reverse-proxy prefix is kept, and
are never stored for good (`test_old_gallery_urls_redirect_into_the_workspace`). The
server never sees a hash, so `/prompt_manager/admin` serves `web/admin-redirect.html`,
which maps `location.hash` with `web/js/legacy-links.js` and replaces the address (Back
does not bounce through it). Its link to the Library is always visible, and a failed
script still leaves for the Library. The mapping follows the old page's own parsing
(`tests/js/legacy-links.test.js`): tags before the first `?`, split on commas, each
decoded; any `mode` but `or` matches all. It differs on purpose in three places: a tag
is trimmed after decoding too; a segment that cannot be decoded is used as written (the
old page failed on it); and `tag_mode=any` is written only for two or more tags.
The workspace form `#/library?tag=<name>&tag=<name>&tag_mode=all|any|untagged` is the
Prompt library with those Tags and that Tag match, as Refine and Browse set them (`tag`
repeats, one name each, trimmed, without empties or repeats; no comma splitting; the
first `tag_mode` counts; other keys are ignored). No tag with `all` or `any` is the
plain Library. An unknown `tag_mode`, or `untagged` with a tag, opens the whole Library
at `#/library` with the toast "This link's tag filter couldn't be read. Showing the
whole prompt library." Count and length limits are the server's (30 tags, 200
characters), shown by the shelf's own error.
The tag filter stays in the address (maintainer ruling 2026-11-21, after the live test:
with the first version, which replaced the hash with `#/library`, Reload and
Back then Forward showed the whole Library):
- The address is canonical: tags in the shelf's order, `tag_mode` left out for All
(`libraryLinkHash`, read back by `libraryLinkFilters`; the router replaces another
spelling). Reload, Back and Forward restore exactly that filter.
- The address is the truth for Tags and Tag match. `#/library` (the sidebar link, the
old dashboard URL) is the Library without a tag filter, whatever the last visit had.
Only those two are in the address: search, category, folder, sort and the archived
shelf stay in memory and return with the last visit as before. The loaded cards and
the scroll place return only when the last visit's tag filter is the address's (Back
from a prompt).
- When Tags or Tag match change in Refine (Clear filters included), the shelf replaces
the address (`replaceRouteHash`: `history.replaceState`, no history entry, no
render; the router learns the new address, so the plain Library link is a new route
afterwards). With no tag filter left it is `#/library`.
- Ways back to the shelf from inside the Library ("← Prompt library" on a prompt's
page, after a delete there) go to the address of the remembered visit, and Browse on
Tags & categories goes to the filtered address too.
- A saved view keeps its own address (`#/saved/<id>`): its tag filter comes from the
view, filter changes inside it never rewrite the address, and the Library link after
it is the whole Library.
Pinned by `tests/js/workspace-state.test.js`, `workspace-library-links.spec.mjs` and
`old-urls.spec.mjs`.
- **D208** (maintainer ruling 2026-11-02, audit item B2): a record used only as the
negative of saved pairs gets no editing surface of its own. The workspace groups by
positive prompt and offers no edit of such a record's own category, tags, notes or
text; the old admin page, which listed it as a prompt, is gone. Its data stays, and it
is still in every export ("Export all prompts JSON", "Export saved pairs JSON") and
backup. No new screen.
- **D209** (#668): the four System rows that were "kept in legacy" are approved removals,
retired with their pages. No native setting replaces them, and every stored key stays
readable (`gallery-settings.js` is unchanged; `web_ui.infinite_scroll` stays in
`config.json`, `/settings` and the diagnostic report).
| Row | What it was | Now |
| --- | --- | --- |
| Infinite scrolling default | The old prompt list scrolled on or paged | The Library always continues (it loads the next page near the end, with "Load more prompts") |
| Lazy loading | A gallery page option | Images always loads lazily |
| Client debug output `debugMode` | Console output of the gallery page | System › Diagnostics & logs |
| API timeout `apiTimeout` | A gallery page option no request read | Nothing: it never had an effect |
**Tests that went with the pages:** the four browser specs that drove them
(`workflows`, `legacy-autotag`, `legacy-removal-notice`, `legacy-system-links`), the unit
tests of the deleted modules, and the Viewer.js fixture suite's controller tests. The
fixture suite (`npm run --prefix tools/vendor test:browser`) is now a smoke of the vendored
Viewer.js build alone; the workspace viewer is proven by `workspace-viewer-keys.spec.mjs`,
`workspace-viewer-mode.spec.mjs` and the Images and history specs.
+17
View File
@@ -19,6 +19,10 @@ Pair prompts' empty category and tags, live in their own modules):
It also forgets the removal marks (#480) that hide nothing any more: the
file is gone or changed, under a readable source (#501, ``_stale_marks``).
#618's ``tag_cleanup`` (``database/tag_cleanup.py``) is planned from a tag
search's findings, never previewed here; its apply rechecks each target and
keeps the ones that changed instead of refusing the whole plan.
``preview_maintenance`` reads one snapshot on its own ``mode=ro`` connection
(``health.readonly_uri``) and closes it in ``finally``; files are looked at
after the snapshot ended. It returns a ``MaintenanceDraft``: the public plan
@@ -64,6 +68,9 @@ MAINTENANCE_OPERATIONS = (
# #550: fill old Pair prompts' empty category and tags
# (database/pair_metadata_repair.py).
"pair_metadata",
# #618: tags to clean up, found by a job and planned from its findings
# (database/tag_cleanup.py); never previewed without them.
"tag_cleanup",
)
MAX_DETAILS = 50 # detail rows a plan lists
MAX_RESULT_ROWS = 200 # changed records an apply describes (the job lists 200)
@@ -574,6 +581,9 @@ class MaintenanceOperations:
"""
if operation not in MAINTENANCE_OPERATIONS:
raise ValueError(f"Unknown maintenance operation {operation!r}")
if operation == "tag_cleanup":
# Planned from a find's findings (tag_cleanup.plan_tag_cleanup).
raise ValueError("tag_cleanup is planned from a tag search")
roots = [str(root) for root in roots]
if operation == "optimize":
return self._plan_optimize()
@@ -867,6 +877,8 @@ class MaintenanceOperations:
prompt operations also return ``kept``: every prompt the plan keeps,
``{prompt_id, reasons}`` in the review's wording (#550, #586); the
links a missing-links plan keeps are read by ``kept_links``.
``tag_cleanup`` (#618) does not compare the fingerprint: it rechecks
each target and returns every deleted and kept tag, uncapped.
"""
if operation not in MAINTENANCE_OPERATIONS or operation == "workflow_storage":
raise ValueError(f"Unknown maintenance operation {operation!r}")
@@ -885,6 +897,11 @@ class MaintenanceOperations:
from .pair_metadata_repair import apply_pair_metadata
return apply_pair_metadata(conn, fingerprint, targets)
if operation == "tag_cleanup":
# #618: each target is rechecked; a changed one is kept.
from .tag_cleanup import apply_tag_cleanup
return apply_tag_cleanup(conn, targets)
if operation == "missing_links":
return self._apply_missing_links(
conn, fingerprint, targets, roots, list(marks)
+5 -21
View File
@@ -26,7 +26,7 @@ from .review_decisions import ReviewDecisionOperations
from .saved_views import SavedViewOperations
from .library_commands import LibraryCommandOperations
from .library_archive import LibraryArchiveOperations, delete_prompt_rows
from .vocabulary import VocabularyOperations
from .vocabulary import VocabularyOperations, bump_image_tag_bytes
from .execution_history import ExecutionHistoryOperations
from .execution_contexts import ExecutionContextOperations
from .execution_outputs import ExecutionOutputOperations
@@ -1262,26 +1262,10 @@ class PromptDatabase(
"has_more": (offset + limit) < total,
}
@staticmethod
def _bump_image_tag_bytes(conn: sqlite3.Connection, tag_id: int) -> int:
"""Move the tag revision of every image set that carries *tag_id*.
Vocabulary rename, merge and delete change what an image's set reads
as, so a Tag dialog opened before the change must see ``tag-conflict``
on Save instead of recreating the old name. Bumps the image index
revision once when any set was affected; returns that count.
"""
cursor = conn.execute(
"UPDATE media_annotation_bytes SET tag_revision = tag_revision + 1 "
"WHERE id IN (SELECT byte_id FROM media_image_tags WHERE tag_id = ?)",
(tag_id,),
)
if cursor.rowcount > 0:
conn.execute(
"UPDATE media_annotation_metadata SET "
"image_index_revision = image_index_revision + 1 WHERE singleton_id = 1"
)
return cursor.rowcount
# Vocabulary rename, merge and delete bump image tag revisions through
# the connection-level helper (database/vocabulary.py, shared with #618's
# tag cleanup).
_bump_image_tag_bytes = staticmethod(bump_image_tag_bytes)
@classmethod
def _move_tag_links(
+440
View File
@@ -0,0 +1,440 @@
"""Tag cleanup: a registry of rules over the tag registry (#618).
Each ``TagRule`` finds tag ids on a read-only connection, rechecks one
reviewed target on the write connection and applies it there. ``RULES`` is
the registry; its order is the review's order and decides ownership: a tag
belongs to the first rule that finds it and is listed only there. Two rules
ship:
- ``comma``: tags whose name holds an ASCII or a fullwidth comma (a whole
list saved as one tag, usually from a LoRA's trained words). A tag whose
name starts with ``lora:`` is never one: it is the LoRA import's identity
tag, which the next import makes again (maintainer ruling, 2026-11-22).
Applying removes the tag from its prompts, pairs and images and deletes it.
- ``unused``: tags no prompt, saved pair or image carries. Deleted.
``find_tag_cleanup`` reads one ``mode=ro`` snapshot and returns every rule's
findings (at most ``MAX_FINDINGS`` held per rule, totals exact).
``plan_tag_cleanup`` re-reads the selected findings on another snapshot; one
whose fingerprint ``(tag_id, name, links)`` changed since the find is
protected, not planned. ``links`` hashes the sorted prompt ids, pair ids and
``(byte_id, position)`` rows carrying the tag, so a tag moved from one prompt
to another is seen. ``apply_tag_cleanup`` runs inside the caller's ``BEGIN
IMMEDIATE`` and rechecks each target: one that changed is kept with its
reason and the rest still apply (one edited tag must not block hundreds).
Saved views are never rewritten; a finding says how many name it. The
auto-tag marks (``media_image_autotags``) are never read or written.
"""
import hashlib
import json
import sqlite3
from dataclasses import dataclass
from typing import Callable, Optional
from .maintenance import (
MAX_DETAILS,
MaintenanceDraft,
_Fingerprint,
_plural,
_read_snapshot,
)
from .vocabulary import VocabularyOperations, _delete_tag
OPERATION = "tag_cleanup"
MAX_FINDINGS = 2000 # findings a find holds and lists per rule
COMMAS = (",", ",")
LORA_PREFIX = "lora:"
CHANGED_SINCE_SEARCH = "changed since the search"
NO_FILES = "No files are removed"
# Findings are listed by name (case-insensitive), then id.
_COMMA_SQL = (
"SELECT id FROM tags WHERE (instr(name, ?) > 0 OR instr(name, ?) > 0) "
"AND substr(name, 1, ?) != ? ORDER BY name COLLATE NOCASE, id"
)
_UNUSED_SQL = (
"SELECT id FROM tags t WHERE "
"NOT EXISTS (SELECT 1 FROM prompt_tags x WHERE x.tag_id = t.id) AND "
"NOT EXISTS (SELECT 1 FROM prompt_pair_tags x WHERE x.tag_id = t.id) "
"ORDER BY name COLLATE NOCASE, id"
)
_UNUSED_WITH_IMAGES_SQL = (
"SELECT id FROM tags t WHERE "
"NOT EXISTS (SELECT 1 FROM prompt_tags x WHERE x.tag_id = t.id) AND "
"NOT EXISTS (SELECT 1 FROM prompt_pair_tags x WHERE x.tag_id = t.id) AND "
"NOT EXISTS (SELECT 1 FROM media_image_tags x WHERE x.tag_id = t.id) "
"ORDER BY name COLLATE NOCASE, id"
)
_ANNOTATION_TABLES = ("media_image_tags", "media_annotation_bytes")
@dataclass(frozen=True)
class TagRule:
"""One cleanup rule: its copy and its three functions."""
id: str
title: str
explanation: str
action_label: str
find: Callable[[sqlite3.Connection], list]
recheck: Callable[[sqlite3.Connection, dict], Optional[str]]
apply: Callable[[sqlite3.Connection, dict], None]
def _has_image_links(conn):
"""Whether the image annotation tables exist (else images link nothing)."""
found = conn.execute(
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN (?, ?)",
_ANNOTATION_TABLES,
).fetchone()[0]
return found == len(_ANNOTATION_TABLES)
def _links(conn, tag_id):
"""sha256 of the link rows carrying ``tag_id``: prompts, pairs, images."""
prompts = [
r[0]
for r in conn.execute(
"SELECT prompt_id FROM prompt_tags WHERE tag_id=? ORDER BY 1", (tag_id,)
)
]
pairs = [
r[0]
for r in conn.execute(
"SELECT pair_id FROM prompt_pair_tags WHERE tag_id=? ORDER BY 1",
(tag_id,),
)
]
images = []
if _has_image_links(conn):
images = [
[r[0], r[1]]
for r in conn.execute(
"SELECT byte_id, position FROM media_image_tags WHERE tag_id=? "
"ORDER BY 1, 2",
(tag_id,),
)
]
return _hash_links(prompts, pairs, images)
def _hash_links(prompts, pairs, images):
encoded = json.dumps([prompts, pairs, images], separators=(",", ":"))
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
NO_LINKS = _hash_links([], [], [])
def _find_comma(conn):
params = (*COMMAS, len(LORA_PREFIX), LORA_PREFIX)
return [row[0] for row in conn.execute(_COMMA_SQL, params)]
def _find_unused(conn):
sql = _UNUSED_WITH_IMAGES_SQL if _has_image_links(conn) else _UNUSED_SQL
return [row[0] for row in conn.execute(sql)]
def _identity_reason(conn, target):
"""``already deleted`` or ``renamed since the review``, else None."""
row = conn.execute("SELECT name FROM tags WHERE id=?", (target["tag_id"],))
row = row.fetchone()
if row is None:
return "already deleted"
if row[0] != target["name"]:
return "renamed since the review"
return None
def _recheck_comma(conn, target):
reason = _identity_reason(conn, target)
if reason is None and _links(conn, target["tag_id"]) != target["links"]:
reason = "its links changed since the review"
return reason
def _recheck_unused(conn, target):
reason = _identity_reason(conn, target)
if reason is None and _links(conn, target["tag_id"]) != target["links"]:
reason = "it is used now"
return reason
def _delete_target(conn, target):
"""Both shipped rules' apply: delete the tag; its links cascade."""
_delete_tag(conn, target["tag_id"])
def _apply_target(conn, target):
# Looked up at call time, so a test can stand in for the delete.
_delete_target(conn, target)
RULES = (
TagRule(
id="comma",
title="Tags containing a comma",
explanation=(
"A whole list saved as one tag, usually from a LoRA's trained words."
),
action_label=(
"Removes the tag from its prompts, pairs and images and deletes it."
),
find=_find_comma,
recheck=_recheck_comma,
apply=_apply_target,
),
TagRule(
id="unused",
title="Tags with no links",
explanation="No prompt, saved pair or image carries the tag.",
action_label="Deletes the tag.",
find=_find_unused,
recheck=_recheck_unused,
apply=_apply_target,
),
)
RULE_IDS = tuple(rule.id for rule in RULES)
_BY_ID = {rule.id: rule for rule in RULES}
def rule(rule_id):
"""The registered rule ``rule_id`` (KeyError when there is none)."""
return _BY_ID[rule_id]
def _saved_view_names(conn):
"""``{tag name: views naming it}`` from every saved view's state."""
exists = conn.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='saved_views'"
).fetchone()
if not exists:
return {}
counts = {}
for (state,) in conn.execute("SELECT state FROM saved_views"):
try:
tags = json.loads(state).get("tags") or []
except (TypeError, ValueError, AttributeError):
continue
for name in {tag for tag in tags if isinstance(tag, str)}:
counts[name] = counts.get(name, 0) + 1
return counts
def _finding(conn, rule_id, tag_id, views):
row = conn.execute("SELECT name FROM tags WHERE id=?", (tag_id,)).fetchone()
if row is None:
return None
counts = (
VocabularyOperations._tag_owner_counts(conn, tag_id)
if _has_image_links(conn)
else _counts_without_images(conn, tag_id)
)
return {
"rule": rule_id,
"tag_id": tag_id,
"name": row[0],
"prompts": counts["components_changed"],
"pairs": counts["pairs_changed"],
"images": counts["images_changed"],
"saved_views": views.get(row[0], 0),
"links": _links(conn, tag_id),
}
def _counts_without_images(conn, tag_id):
prompts = conn.execute(
"SELECT COUNT(DISTINCT prompt_id) FROM prompt_tags WHERE tag_id=?", (tag_id,)
).fetchone()[0]
pairs = conn.execute(
"SELECT COUNT(DISTINCT pair_id) FROM prompt_pair_tags WHERE tag_id=?",
(tag_id,),
).fetchone()[0]
return {"components_changed": prompts, "pairs_changed": pairs, "images_changed": 0}
def _owners_text(finding):
parts = [
_plural(finding[key], noun)
for key, noun in (("prompts", "prompt"), ("pairs", "pair"), ("images", "image"))
if finding[key]
]
return " · ".join(parts)
def finding_detail(finding):
"""The server's line for a finding: ``3 prompts · 1 pair``, ``no links``,
with `` · in 1 saved view`` when a saved view names it."""
detail = _owners_text(finding) or "no links"
views = finding.get("saved_views", 0)
if views:
detail += f" · in {_plural(views, 'saved view')}"
return detail
def find_tag_cleanup(db_path):
"""Every rule's findings on one ``mode=ro`` snapshot (blocking, read-only).
``{"rules": {rule_id: [finding, ...]}, "totals": {rule_id: int}}``:
findings by name (case-insensitive), then id; at most ``MAX_FINDINGS``
held per rule, totals exact. A tag is listed under the first rule that
finds it only.
"""
def read(conn):
owned = set()
views = _saved_view_names(conn)
rules, totals = {}, {}
for item in RULES:
ids = [tag_id for tag_id in item.find(conn) if tag_id not in owned]
owned.update(ids)
totals[item.id] = len(ids)
findings = []
for tag_id in ids[:MAX_FINDINGS]:
finding = _finding(conn, item.id, tag_id, views)
if finding is not None:
findings.append(finding)
rules[item.id] = findings
return {"rules": rules, "totals": totals}
return _read_snapshot(db_path, read)
def _target(finding):
return {
key: finding[key]
for key in (
"rule",
"tag_id",
"name",
"prompts",
"pairs",
"images",
"saved_views",
"links",
)
}
def _scope_label(targets):
if not targets:
return "No tags to delete"
prompts = sum(t["prompts"] for t in targets)
pairs = sum(t["pairs"] for t in targets)
images = sum(t["images"] for t in targets)
return (
f"Delete {_plural(len(targets), 'tag')} (removed from "
f"{_plural(prompts, 'prompt')}, {_plural(pairs, 'pair')} and "
f"{_plural(images, 'image')})"
)
def plan_tag_cleanup(db_path, held, tag_ids_by_rule):
"""The reviewed plan for the selected findings (blocking, read-only).
``held`` is a ``find_tag_cleanup`` result and ``tag_ids_by_rule``
``{rule_id: [tag_id, ...]}`` of its findings (the caller validated
both). Each selected finding is read again on one snapshot; one whose
``(tag_id, name, links)`` changed since the find is protected
(``changed since the search``), not planned. Targets follow the
registry's order, then the find's.
"""
reviewed = {
(finding["rule"], finding["tag_id"]): finding
for findings in held["rules"].values()
for finding in findings
}
def read(conn):
views = _saved_view_names(conn)
targets, protected = [], []
for item in RULES:
for tag_id in tag_ids_by_rule.get(item.id, ()):
before = reviewed[(item.id, tag_id)]
now = _finding(conn, item.id, tag_id, views)
same = now is not None and (now["name"], now["links"]) == (
before["name"],
before["links"],
)
if same:
targets.append(_target(now))
else:
protected.append(
{**_target(before), "reason": CHANGED_SINCE_SEARCH}
)
return targets, protected
targets, protected = _read_snapshot(db_path, read)
fingerprint = _Fingerprint(OPERATION)
for target in targets:
fingerprint.add([target["rule"], target["tag_id"], target["name"]])
fingerprint.add(target["links"])
reasons = (
[f"{_plural(len(protected), 'tag')} {CHANGED_SINCE_SEARCH}"]
if protected
else []
)
draft = MaintenanceDraft(
operation=OPERATION,
fingerprint=fingerprint.hexdigest(),
targets=targets,
scope={"count": len(targets), "label": _scope_label(targets)},
protected={"count": len(protected), "reasons": reasons},
media={"deletes_files": False, "label": NO_FILES},
details=[
{
"label": target["name"],
"detail": f"{rule(target['rule']).title} · {finding_detail(target)}",
}
for target in targets[:MAX_DETAILS]
],
)
draft.held = protected
return draft
def held_rows(draft):
"""The findings a plan protected, each with its reason."""
return list(getattr(draft, "held", ()))
def _empties_legacy_tags(conn):
"""Whether deleting one more tag would empty ``tags`` while a prompt still
holds legacy JSON tags: the start-up migration would then bring every
legacy tag and link back (``models._migrate_json_tags_to_junction``)."""
if conn.execute("SELECT COUNT(*) FROM tags").fetchone()[0] > 1:
return False
legacy = conn.execute(
"SELECT 1 FROM prompts WHERE tags IS NOT NULL AND tags != '' "
"AND tags != '[]' LIMIT 1"
).fetchone()
return legacy is not None
LAST_TAG = "kept so the old tag migration does not run again"
def apply_tag_cleanup(conn, targets):
"""Apply the reviewed targets in the caller's transaction (blocking).
Each target's rule rechecks it on ``conn``; one that changed is kept with
its reason and the rest still apply. ``{"changed": n, "rows": [every
deleted target], "kept": [{...target, "reason"}]}``. Any exception
propagates, so the caller's transaction rolls back as a whole.
"""
changed, rows, kept = 0, [], []
for target in targets:
item = rule(target["rule"])
reason = item.recheck(conn, target)
if reason is None and _empties_legacy_tags(conn):
reason = LAST_TAG
if reason is not None:
kept.append({**target, "reason": reason})
continue
item.apply(conn, target)
changed += 1
rows.append(dict(target))
return {"changed": changed, "rows": rows, "kept": kept}
+33 -2
View File
@@ -295,6 +295,38 @@ def _category_after(after: object) -> tuple[int, str] | None:
return after[0], after[1]
def bump_image_tag_bytes(conn: sqlite3.Connection, tag_id: int) -> int:
"""Move the tag revision of every image set that carries *tag_id*.
Vocabulary rename, merge and delete change what an image's set reads as,
so a Tag dialog opened before the change must see ``tag-conflict`` on Save
instead of recreating the old name. Bumps the image index revision once
when any set was affected; returns that count.
"""
cursor = conn.execute(
"UPDATE media_annotation_bytes SET tag_revision = tag_revision + 1 "
"WHERE id IN (SELECT byte_id FROM media_image_tags WHERE tag_id = ?)",
(tag_id,),
)
if cursor.rowcount > 0:
conn.execute(
"UPDATE media_annotation_metadata SET "
"image_index_revision = image_index_revision + 1 WHERE singleton_id = 1"
)
return cursor.rowcount
def _delete_tag(conn: sqlite3.Connection, tag_id: int) -> None:
"""Delete the registry row *tag_id* in the caller's transaction.
Image sets carrying it get a new tag revision first; its component, pair
and image links cascade. Shared by ``delete_vocabulary_tag`` and the tag
cleanup rules (#618, ``database/tag_cleanup.py``).
"""
bump_image_tag_bytes(conn, tag_id)
conn.execute("DELETE FROM tags WHERE id=?", (tag_id,))
class VocabularyOperations:
"""Vocabulary reads and tag commands.
@@ -405,8 +437,7 @@ class VocabularyOperations:
epoch = self._library_epoch(conn, expected_epoch)
self._vocabulary_identity(conn, epoch, tag_id, name)
counts = self._tag_owner_counts(conn, tag_id)
self._bump_image_tag_bytes(conn, tag_id)
conn.execute("DELETE FROM tags WHERE id=?", (tag_id,))
_delete_tag(conn, tag_id)
return {"library_epoch": epoch, "deleted": True, **counts}
def vocabulary_tag_impact(self, tag_id: int) -> dict | None:
+1 -1
View File
@@ -12,7 +12,7 @@ code. This plan proposes implementation order and acceptance gates.
- The native Prompt Library merged in [#210](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/210) for [#208](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/208): one positive parent, saved negative variants, full selected text and a shared filtered image gallery. It does not invent chronological runs from counters or scan dates.
- [Durable history storage](prompt-history-storage.md) records job attempts and outcomes from [#212](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/212), frozen prompt contexts from [#213](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/213), and observed run-owned output locators from [#214](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/214). Those locators do not verify file bytes or establish gallery-image associations. That association contract and the chronological execution timeline remain pending under [#209](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/209).
- [#215](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/215) brings the shell, Images and natural-height Prompt Library presentation into the approved geometry and themes while retaining their existing operations. [#216](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/216) adds the shared current-file inspector with exact generation facts, scoped provenance, raw/download evidence and loaded-collection viewer controls, including a slideshow that pauses at native video. This delivery does not establish whole-application parity, change the default entry point or constitute a release. Recorded chronological run/context browsing continues under [#209](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/209); image tagging/review, System consolidation and remaining organization capabilities continue under #196.
- Local Inspect (#249, PRs L1–L3) replaces the `#/inspect` handoff with the concept's native "Inspect a file" page: one local image or video previews inline and opens the shared viewer and full inspector on a record read entirely in the browser, with nothing uploaded, imported or stored. The legacy metadata page (`web/metadata.html`, served at `/prompt_manager/gallery.html`) stays reachable by its address and from the legacy admin page; the workspace no longer links it (#621); its capabilities map to the shared inspector, including its one-click COPY ALL summary, which is the shared inspector's "Copy settings summary" (D117, LI-4). PR L3 ([#286](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/286)) shipped that button and local roles equal to the server's resolver (`web/js/workspace/local-resolver.mjs`, TESTING.md "Local roles (#249 PR L3, decision LI-1)"). Recorded deviations D60–D66 and D117 are in [TESTING.md](../TESTING.md).
- Local Inspect (#249, PRs L1–L3) replaces the `#/inspect` handoff with the concept's native "Inspect a file" page: one local image or video previews inline and opens the shared viewer and full inspector on a record read entirely in the browser, with nothing uploaded, imported or stored. The legacy metadata page (`web/metadata.html`, served at `/prompt_manager/gallery.html`) was removed in #668, and its address now opens this page; its capabilities map to the shared inspector, including its one-click COPY ALL summary, which is the shared inspector's "Copy settings summary" (D117, LI-4). PR L3 ([#286](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/286)) shipped that button and local roles equal to the server's resolver (`web/js/workspace/local-resolver.mjs`, TESTING.md "Local roles (#249 PR L3, decision LI-1)"). Recorded deviations D60–D66 and D117 are in [TESTING.md](../TESTING.md).
- Collections ([#331](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/331), three PRs) adds named, hand-picked groups of images, stored in the library database by file location as favorites are: a COLLECTIONS sidebar group whose rows open Images filtered to one collection (`#/collection/<id>`) with rename and delete, Add to collection and Remove from collection in the Images selection bar, a Collections… checklist in the shared inspector for the side panel and the viewer, and saved views that keep a collection. Membership survives restarts, source reordering and System › Maintenance duplicate cleanup; no file is copied, moved or changed.
## Scope and compatibility
+33 -8
View File
@@ -23,6 +23,7 @@ Split into domain-specific mixins for maintainability:
- LibraryDeleteRoutesMixin: the Library's Delete… (archive paired) and Restore
- WorkflowStorageRoutesMixin: store each workflow once, then Reclaim space
- DuplicateFilesMixin: duplicate image files as find and removal jobs
- TagCleanupMixin: tag cleanup (#618) as a find job, its findings and a plan
- LoraImportRoutesMixin: the reviewed, staged LoRA reference import job
"""
@@ -74,6 +75,7 @@ from .maintenance import MaintenanceRoutesMixin
from .backup_restore import BackupRestoreRoutesMixin
from .workflow_storage import WorkflowStorageRoutesMixin
from .duplicate_files import DuplicateFilesMixin
from .tag_cleanup import TagCleanupMixin
from .maintenance_plans import PlanStore
from .jobs import JobRegistry
from .logging_routes import LoggingRoutesMixin
@@ -274,6 +276,17 @@ async def _gzip_middleware(request, handler):
return response
def _workspace_redirect(route: str) -> web.Response:
"""Send the browser of a retired page's URL to a workspace route (#668).
The Location is relative to the old URL, so a reverse-proxy mount prefix
in front of ``/prompt_manager/`` is kept, and 302 is not stored for good.
A plain response, not a raised ``HTTPFound``, so the host's middlewares
see it like any other.
"""
return web.Response(status=302, headers={"Location": f"workspace{route}"})
class PromptManagerAPI(
PairRoutesMixin,
LibraryRoutesMixin,
@@ -306,6 +319,7 @@ class PromptManagerAPI(
BackupRestoreRoutesMixin,
WorkflowStorageRoutesMixin,
DuplicateFilesMixin,
TagCleanupMixin,
LoggingRoutesMixin,
LogCleanupMixin,
DiagnosticsReportMixin,
@@ -383,6 +397,9 @@ class PromptManagerAPI(
# Duplicate-file finds by job id, with the groups each one holds for
# review (py/api/duplicate_files.py); the last few only.
self._duplicate_finds = {}
# Tag cleanup finds by job id with the findings each holds (#618,
# py/api/tag_cleanup.py); None while a find runs or after it failed.
self._tag_cleanup_finds = {}
# The last System health report this session and the database
# generation it describes, bumped when a restore replaces self.db
# (py/api/system.py).
@@ -621,17 +638,24 @@ class PromptManagerAPI(
async def serve_web_ui(request):
return self._serve_html_page(request, "index.html", "Web UI", cache=False)
@routes.get("/prompt_manager/gallery.html")
async def serve_gallery_ui(request):
return self._serve_html_page(request, "metadata.html", "Gallery")
# The old admin, gallery and metadata pages are gone (#668, D207); their
# URLs stay and lead into the workspace.
@routes.get("/prompt_manager/admin")
async def serve_admin_ui(request):
return self._serve_html_page(request, "admin.html", "Admin UI")
@routes.get("/prompt_manager/gallery.html")
async def redirect_old_metadata_page(request):
return _workspace_redirect("#/inspect")
@routes.get("/prompt_manager/gallery")
async def serve_gallery_admin_ui(request):
return self._serve_html_page(request, "gallery.html", "Gallery")
async def redirect_old_gallery_page(request):
return _workspace_redirect("#/images")
# The dashboard's tag bookmarks (admin#/tags/a,b?mode=or) live in the
# hash, which only the browser sees: this page maps it and moves on.
@routes.get("/prompt_manager/admin")
async def serve_old_admin_redirect(request):
return self._serve_html_page(
request, "admin-redirect.html", "Workspace redirect"
)
# ── Static file serving ───────────────────────────────────────
@@ -673,6 +697,7 @@ class PromptManagerAPI(
self._register_maintenance_routes(routes)
self._register_backup_restore_routes(routes)
self._register_duplicate_routes(routes)
self._register_tag_cleanup_routes(routes)
self._register_logging_routes(routes)
self._register_autotag_routes(routes)
self._register_lora_routes(routes)
+6 -2
View File
@@ -43,6 +43,7 @@ try:
in_trash_folder,
is_skipped_folder,
)
from ...utils.media_formats import collectable
except ImportError:
from utils import exit_signal
from utils.media_folders import (
@@ -50,6 +51,7 @@ except ImportError:
in_trash_folder,
is_skipped_folder,
)
from utils.media_formats import collectable
try:
from ...database.image_removal import mark_hides
@@ -100,7 +102,7 @@ try:
except ImportError:
from database.library import display_title
IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff")
IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".avif")
VIDEO_EXTENSIONS = (".mp4", ".avi", ".mov", ".mkv", ".webm", ".m4v", ".wmv")
SCAN_BATCH_SIZE = 50 # Files per executor call during the output scan
# '<db>.backup_*' files kept next to the live database: one pool for the
@@ -156,7 +158,9 @@ def _collect_media_files(output_dirs, extensions):
and not os.path.islink(os.path.join(current, d))
)
for name in sorted(filenames):
if os.path.splitext(name)[1].lower() not in wanted:
suffix = os.path.splitext(name)[1].lower()
# #652: AVIF is listed but only collected where Pillow reads it.
if suffix not in wanted or not collectable(suffix):
continue
full = os.path.join(current, name)
if os.path.islink(full) or not os.path.isfile(full):
+1
View File
@@ -91,6 +91,7 @@ _PREVIEW_TYPES = {
".bmp": "image/bmp",
".tiff": "image/tiff",
".tif": "image/tiff",
".avif": "image/avif", # #652
".mp4": "video/mp4",
".m4v": "video/mp4",
".webm": "video/webm",
+8 -3
View File
@@ -25,8 +25,10 @@ from .. import model_gate
try:
from ...utils.media_folders import in_trash_below_roots, is_skipped_folder
from ...utils.media_formats import collectable
except ImportError:
from utils.media_folders import in_trash_below_roots, is_skipped_folder
from utils.media_formats import collectable
from aiohttp import web
@@ -156,8 +158,9 @@ def public_models(status: dict, loaded_type: Optional[str]) -> dict:
# Only these may be handed to the tagging engine or listed by the scanner.
# #652: AVIF is listed and skipped where Pillow cannot read it (collectable).
_MEDIA_EXTENSIONS = frozenset(
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff", ".tif"}
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff", ".tif", ".avif"}
)
# Bounds for scan_output_dir: a runaway output tree must not pin the server.
_SCAN_MAX_FILES = 50_000
@@ -945,7 +948,8 @@ class AutotagRoutesMixin:
def _resolve_allowed_image_path(self, raw_path: str) -> Optional[str]:
"""Return the real path when it is a media file inside an output directory."""
if Path(str(raw_path)).suffix.lower() not in _MEDIA_EXTENSIONS:
suffix = Path(str(raw_path)).suffix.lower()
if suffix not in _MEDIA_EXTENSIONS or not collectable(suffix):
return None
roots = list(self._get_all_output_dirs())
for output_dir in roots:
@@ -1449,7 +1453,8 @@ class AutotagRoutesMixin:
if not is_skipped_folder(name) and depth + 1 <= _SCAN_MAX_DEPTH
)
for name in sorted(filenames):
if Path(name).suffix.lower() not in _MEDIA_EXTENSIONS:
suffix = Path(name).suffix.lower()
if suffix not in _MEDIA_EXTENSIONS or not collectable(suffix):
continue
candidate = Path(dirpath) / name
if candidate.is_symlink():
+11 -3
View File
@@ -76,6 +76,7 @@ try:
split_relative,
)
from ...utils.parallel import map_parallel
from ...utils.media_formats import collectable
from ...utils.json_strict import dumps_strict
from ...utils.inspection_response import (
OWN_CATEGORY_UNREAD,
@@ -109,6 +110,7 @@ except ImportError:
split_relative,
)
from utils.parallel import map_parallel
from utils.media_formats import collectable
from utils.json_strict import dumps_strict
from utils.inspection_response import (
OWN_CATEGORY_UNREAD,
@@ -324,7 +326,10 @@ def _media_access_error(path, allowed_dirs):
# Media types the gallery scans and thumbnails (a superset is never served).
GALLERY_IMAGE_EXTENSIONS = frozenset({".png", ".jpg", ".jpeg", ".webp", ".gif"})
# #652: AVIF is named here and skipped by the walks when Pillow cannot read it.
GALLERY_IMAGE_EXTENSIONS = frozenset(
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".avif"}
)
MEDIA_EXTENSIONS = GALLERY_IMAGE_EXTENSIONS | VIDEO_EXTENSIONS
# Caps on request-triggered filesystem work.
@@ -951,7 +956,9 @@ def _walk_media(output_path, max_files):
except OSError:
continue # as os.walk: an unreadable folder is skipped
for entry in sorted(files, key=lambda item: item.name):
if _name_suffix(entry.name).lower() not in MEDIA_EXTENSIONS:
suffix = _name_suffix(entry.name).lower()
# #652: AVIF is listed but only collected where Pillow reads it.
if suffix not in MEDIA_EXTENSIONS or not collectable(suffix):
continue
if entry.is_symlink():
continue # never read through a link out of the output tree
@@ -984,7 +991,8 @@ def _settled_entry(root, relative):
if on_disk is not None and not on_disk.endswith(os.sep + relative):
raise OSError(f"{relative} is spelled differently on disk")
*folders, name = relative.split(os.sep)
if _name_suffix(name).lower() not in MEDIA_EXTENSIONS:
suffix = _name_suffix(name).lower()
if suffix not in MEDIA_EXTENSIONS or not collectable(suffix):
return None
if in_skipped_folder(folders) or len(folders) > MAX_SCAN_DEPTH:
return None
+2
View File
@@ -42,6 +42,8 @@ IMAGE_EXTENSIONS = frozenset(
".bmp",
".tiff",
".tif",
# #652: served and inspected; the scan collects it where Pillow reads it
".avif",
".mp4",
".webm",
".mov",
+4
View File
@@ -124,6 +124,10 @@ MODEL_DOWNLOAD_JOB_KIND = "model_download"
DUPLICATES_JOB_KIND = "duplicates"
DUPLICATE_GROUP_NAMES = ("groups_found",)
DUPLICATE_CLEANUP_GROUP_NAMES = ("removed", "kept", "errors")
# Tag cleanup (#618, py/api/tag_cleanup.py): the find is a ``read`` job that
# holds its findings; the reviewed apply is a ``maintenance`` job.
TAG_CLEANUP_JOB_KIND = "tag_cleanup"
TAG_CLEANUP_GROUP_NAMES = ("found",)
# The workspace Library's Delete… (#443, py/api/library_delete.py): a
# ``records`` hold around its safety backup and write.
PROMPT_DELETE_JOB_KIND = "prompt_delete"
+24 -3
View File
@@ -6,9 +6,12 @@ current imports, those a saved pair uses and the example images an import
would download. It writes nothing and requests nothing. It answers a
``Plan`` (the maintenance plan's shape, ``py/api/maintenance.py``) plus
``{lora_files, with_metadata, skipped, with_local_media, current_imports,
blocked_by_pairs, planned_downloads, network:{planned_downloads, api_key},
layout}`` (#355: ``layout`` says which LoraManager settings file, storage mode
and library the import read, and ``error`` when they cannot be used). A plan
blocked_by_pairs, planned_downloads, trigger_tags, trigger_not_tags,
network:{planned_downloads, api_key}, layout}`` (#355: ``layout`` says which
LoraManager settings file, storage mode and library the import read, and
``error`` when they cannot be used; #618: ``trigger_tags`` and
``trigger_not_tags`` count the trained-words entries that become tags and
those that are lists or sentences, which the job log repeats). A plan
that saved pairs block, or whose layout is unusable, carries no token
(nothing can be applied).
@@ -104,6 +107,13 @@ def _import_line(result, skipped):
return " · ".join(parts)
def not_tags_line(count):
"""The job log's count of trained-words entries not made tags (#618)."""
entries = _count(count, "trained-words entry", "trained-words entries")
verb = "was" if count == 1 else "were"
return f"{entries} {verb} not made tags (lists or sentences)"
def _all_downloads_failed(errors):
"""The warning when every planned download failed (#337)."""
if errors == 1:
@@ -315,6 +325,8 @@ class LoraImportRoutesMixin:
"current_imports": current,
"blocked_by_pairs": blocked,
"planned_downloads": downloads,
"trigger_tags": int(found.get("trigger_tags", 0)),
"trigger_not_tags": int(found.get("trigger_not_tags", 0)),
"scope": {
"count": found["with_metadata"],
"label": (
@@ -441,6 +453,9 @@ class LoraImportRoutesMixin:
self.logger.exception("LoRA import staging failed")
return _fail_job(job, "import-failed", f"{FAILED} {CACHE_NOTE}")
self._count_downloads(job, staged)
not_tags = staged.stats.get("trigger_not_tags", 0)
if not_tags:
job.log_line(not_tags_line(not_tags))
# M4: what staging skipped stays on the job whatever happens next.
job.record_counted(
"skipped",
@@ -466,6 +481,12 @@ class LoraImportRoutesMixin:
return _fail_job(job, "plan-changed", f"{SOURCE_CHANGED} {CACHE_NOTE}")
job.update(status_line="Replacing the LoRA collection", progress=95)
await self._replace_in_job(job, db, plan, staged)
# #619: the replace is one transaction and has committed by now, so
# the import is finished even when ComfyUI is exiting: end it here,
# before the exit signal can relabel it "cancelled" on the way out.
# A failed replace already ended the job "failed"; a second finish
# is a no-op.
job.finish("finished")
return None
def _count_downloads(self, job, staged):
+62 -11
View File
@@ -5,7 +5,9 @@ one operation (``duplicate_prompts``, ``optimize``, ``unused_components``,
``missing_links`` or ``pair_metadata``, #550; ``database/maintenance.py``;
``duplicate_files``,
``py/api/duplicate_files.py``; ``rotated_logs``, the rotated log copies,
``py/api/log_cleanup.py``, which has its own apply job) off the event loop and
``py/api/log_cleanup.py``, which has its own apply job; ``tag_cleanup``,
#618, the ticked findings of a tag search, ``py/api/tag_cleanup.py``) off the
event loop and
answers a ``Plan``: ``{success, token, operation, expires_at, scope:{count,
label}, protected:{count, reasons}, backup:{policy, destination_label},
media:{deletes_files, label}, details:[≤50 {label, detail}]}``. The preview
@@ -29,13 +31,17 @@ The token is consumed when the job starts (on the same loop turn, before its
runner runs); a refused start keeps it. The runner:
1. takes a safety backup when the plan was reviewed with the policy on or the
policy (``maintenance.safety_backup``, default on) is on now: SQLite's
policy (``maintenance.safety_backup``, default on) is on now, and always
for ``workflow_storage`` and ``tag_cleanup`` (``ALWAYS_BACKED_UP``, policy
``required``): SQLite's
backup API into a temp file beside the database, ``verify_database_file``,
fsync, ``0o600`` on POSIX, then ``os.replace`` onto a unique
``<db>.backup_<YYYYmmdd_HHMMSS_ffffff>[_n]`` name. Any failure removes
what it wrote and ends the job ``backup-failed`` with nothing changed;
2. applies the plan, which first rechecks the reviewed fingerprint inside
``BEGIN IMMEDIATE`` (``plan-changed`` writes nothing);
``BEGIN IMMEDIATE`` (``plan-changed`` writes nothing); ``tag_cleanup``
rechecks each tag instead and keeps, with its reason, each one that
changed, while the rest still apply;
3. counts the changed and protected records, and prunes old safety backups.
The job log names the backup by its file name only, and the job says "No
@@ -87,6 +93,13 @@ MAINTENANCE_PREVIEW_LEASE = "Maintenance preview"
DUPLICATE_PREVIEW_BODY_MAX = 1024 * 1024
DUPLICATE_FILES = "duplicate_files"
WORKFLOW_STORAGE = "workflow_storage" # applied by py/api/workflow_storage.py
# #618: planned from a tag search's findings (py/api/tag_cleanup.py).
TAG_CLEANUP = "tag_cleanup"
# Previews whose options list many ids, read up to the large body cap.
LARGE_PREVIEWS = frozenset({DUPLICATE_FILES, TAG_CLEANUP})
# Always backed up first, whatever the safety-backup setting: Store each
# workflow once (the way back) and Tag cleanup (maintainer ruling, #618).
ALWAYS_BACKED_UP = frozenset({WORKFLOW_STORAGE, TAG_CLEANUP})
# rotated_logs (#329, py/api/log_cleanup.py) reviews log files, not records.
PREVIEW_OPERATIONS = MAINTENANCE_OPERATIONS + (DUPLICATE_FILES, ROTATED_LOGS)
# Room left over beyond what a step writes, so a disk is never filled to 0.
@@ -100,9 +113,12 @@ MAINTENANCE_TITLES = {
"workflow_storage": "Store each workflow once",
# #550, beyond the concept: fills old Pair prompts' empty category and tags.
"pair_metadata": "Pair category and tags",
# #618 (D210), beyond the concept: deletes comma-list and unused tags.
TAG_CLEANUP: "Tag cleanup",
}
# Operations whose job keeps every changed row for its report (#550).
COMPLETE_RECORD = frozenset({"pair_metadata"})
# Operations whose job keeps every changed row for its report (#550; #618:
# the report and the backup are the only record of the deleted tag names).
COMPLETE_RECORD = frozenset({"pair_metadata", TAG_CLEANUP})
_OPERATION_ERROR = "operation must be one of: " + ", ".join(PREVIEW_OPERATIONS)
MAINTENANCE_GROUPS = ("changed", "protected", "errors")
MAX_TOKEN_LENGTH = 128
@@ -307,6 +323,8 @@ def _changed_line(operation, count, marks=0, result=None):
return "Optimized the database"
if operation == "pair_metadata":
return _pair_metadata_line(result or {"changed": count})
if operation == TAG_CLEANUP:
return f"Deleted {count:,} {'tag' if count == 1 else 'tags'}"
if operation == "duplicate_prompts":
noun = "duplicate prompt" if count == 1 else "duplicate prompts"
return f"Merged {count:,} {noun}"
@@ -408,7 +426,7 @@ class MaintenanceRoutesMixin:
("operation", "options"),
cap=lambda body: (
DUPLICATE_PREVIEW_BODY_MAX
if body.get("operation") == DUPLICATE_FILES
if body.get("operation") in LARGE_PREVIEWS
else PREVIEW_BODY_MAX
),
)
@@ -420,6 +438,8 @@ class MaintenanceRoutesMixin:
return _invalid(_OPERATION_ERROR)
if operation == DUPLICATE_FILES:
return await self.preview_duplicate_files(options)
if operation == TAG_CLEANUP:
return await self.preview_tag_cleanup(options)
if not isinstance(options, dict) or options:
return _invalid(f"{operation} takes no options")
if operation == ROTATED_LOGS:
@@ -470,10 +490,12 @@ class MaintenanceRoutesMixin:
)
policy = self._safety_backup_policy()
destination = "backup"
if operation == WORKFLOW_STORAGE:
# Always backed up first, whatever the policy (the way back);
# one kept pre-migration backup ever, pooled ones after it.
if operation in ALWAYS_BACKED_UP:
# Always backed up first, whatever the policy.
policy = "required"
if operation == WORKFLOW_STORAGE:
# The way back: one kept pre-migration backup ever, pooled ones
# after it.
kept = await self._run_in_executor(pre_migration_backups, db.model.db_path)
destination = "backup" if kept else PRE_MIGRATION_LABEL
try:
@@ -635,8 +657,8 @@ class MaintenanceRoutesMixin:
Decided once, when the apply starts (the disk check measured it), and
handed to the job.
"""
if plan.operation == WORKFLOW_STORAGE:
return True # never without its pre-migration backup
if plan.operation in ALWAYS_BACKED_UP:
return True # never without its backup (pre-migration, or #618's)
return plan.payload["backup"] == "on" or self._safety_backup_policy() == "on"
async def _safety_backup_step(self, job, db, backup_on):
@@ -746,6 +768,13 @@ class MaintenanceRoutesMixin:
}
)
return rows
if plan.operation == TAG_CLEANUP:
# The findings the review protected, then each target the apply
# kept, every one with its reason (#618).
return [
{"path": "", "detail": f"Kept tag “{item['name']}”: {item['reason']}"}
for item in [*plan.payload.get("held", ()), *result["kept"]]
]
if "kept" not in result:
return None
return [
@@ -775,6 +804,8 @@ class MaintenanceRoutesMixin:
return rows
if operation == "pair_metadata":
return [{"path": "", "detail": _filled_detail(item)} for item in described]
if operation == TAG_CLEANUP:
return [{"path": "", "detail": _deleted_tag_detail(i)} for i in described]
if operation == "duplicate_prompts":
return [
{
@@ -792,6 +823,26 @@ class MaintenanceRoutesMixin:
]
def _deleted_tag_detail(item):
"""``Deleted tag “a, b” (Tags containing a comma) · removed from 3 prompts``."""
from .tag_cleanup import rules
line = f"Deleted tag “{item['name']}” ({rules.rule(item['rule']).title})"
owners = [
f"{item[key]:,} {noun if item[key] == 1 else noun + 's'}"
for key, noun in (("prompts", "prompt"), ("pairs", "pair"), ("images", "image"))
if item.get(key)
]
if not owners:
return line
joined = (
owners[0]
if len(owners) == 1
else (", ".join(owners[:-1]) + " and " + owners[-1])
)
return f"{line} · removed from {joined}"
def _filled_detail(item):
"""``Prompt 12: category “portrait”; tags a, b``: one filled prompt (#550)."""
parts = []
+11 -1
View File
@@ -431,12 +431,22 @@ def _marker_lock(folder):
(atomic on local disks and SMB/NFS shares, unlike ``flock``), so installs
sharing the folder change the marker one at a time. A lock older than
MARKER_LOCK_STALE was left by a writer that died and is taken over;
waiting longer than MARKER_LOCK_TIMEOUT raises TimeoutError."""
waiting longer than MARKER_LOCK_TIMEOUT raises TimeoutError.
On Windows a lock another writer just unlinked stays delete-pending while
any handle to it is open, and creating it then answers "access denied"
instead of "exists" (#674). That is waited out like a held lock; a folder
that stays denied until the timeout reports its PermissionError."""
lock = os.path.join(folder, MARKER_LOCK_NAME)
deadline = time.monotonic() + MARKER_LOCK_TIMEOUT
while True:
try:
handle = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
except PermissionError:
if time.monotonic() >= deadline:
raise
time.sleep(MARKER_LOCK_POLL)
continue
except FileExistsError:
_break_stale_lock(lock)
if time.monotonic() >= deadline:
+1 -1
View File
@@ -3,7 +3,7 @@
Every mapping between an image source (a "root"), one of its media files and
that file's preview on disk goes through this module. URL text stays in
``thumbnail_settings`` (``thumbnail_rel``: ``thumbnails/<rel>_thumb<ext>``,
the shape the serve route, ``inspection-state.mjs`` and ``admin.js`` share);
the shape the serve route and ``inspection-state.mjs`` share);
this module answers where such a preview is on disk.
The store of a source is where its previews live. With the default location
+245
View File
@@ -0,0 +1,245 @@
"""Tag cleanup as a find job, its findings and a reviewed plan (#618).
- ``POST /prompt_manager/jobs/tag_cleanup`` (body ignored) starts the find
(202 ``{job}``): kind ``tag_cleanup``, "Find tags to clean up", admission
``read``, not cancellable (one snapshot read), outcome group ``found``. It
runs every rule of ``database/tag_cleanup.py`` on one read-only snapshot,
holds the result under the job id (the last ``MAX_HELD_FINDS``), records one
``found`` row per tag and writes nothing. 409 ``busy`` while a find or an
exclusive job runs.
- ``GET /prompt_manager/maintenance/tag_cleanup/{job_id}`` answers every held
finding at once: ``{success, job:{id, state}, rules:[{id, title,
explanation, action_label, total, findings:[{tag_id, name, detail}]}]}``,
at most ``MAX_FINDINGS`` per rule (``total`` is exact). 404 ``not-found``,
409 ``job-running``, 409 ``no-groups`` (the find failed).
- ``POST /prompt_manager/maintenance/preview {operation:"tag_cleanup",
options:{job_id, select:[{rule, tag_ids}]}}`` reviews the ticked findings
(``preview_tag_cleanup``): each selected tag must be a held finding of that
rule. The plan always takes a safety backup first (policy ``required``,
maintainer ruling 2026-11-22) and its apply, the ``maintenance`` job "Tag
cleanup", rechecks each tag and keeps, with its reason, each one that
changed (``py/api/maintenance.py``).
"""
from aiohttp import web
from .job_routes import busy_response
from .jobs import TAG_CLEANUP_GROUP_NAMES, TAG_CLEANUP_JOB_KIND, JobBusy
from .maintenance import _failure, _invalid
try:
from ...database import tag_cleanup as rules
except ImportError:
from database import tag_cleanup as rules
TAG_CLEANUP = rules.OPERATION
FIND_TITLE = "Find tags to clean up"
FIND_FAILED = "The tag search failed."
MAX_HELD_FINDS = 3 # finds whose findings the server keeps for review
MAX_JOB_ID = 64
def _parse_select(entry, seen):
"""``(rule_id, tag_ids, None)`` for one select entry, else a message."""
if not isinstance(entry, dict) or set(entry) != {"rule", "tag_ids"}:
return None, None, "Each select entry is {rule, tag_ids}"
rule_id, tag_ids = entry["rule"], entry["tag_ids"]
if not isinstance(rule_id, str) or rule_id not in rules.RULE_IDS:
return None, None, "rule must be one of: " + ", ".join(rules.RULE_IDS)
if rule_id in seen:
return None, None, "Each rule is selected once"
limit = rules.MAX_FINDINGS
if not isinstance(tag_ids, list) or not 0 < len(tag_ids) <= limit:
return None, None, f"tag_ids must list 1 to {limit:,} tags"
for tag_id in tag_ids:
if type(tag_id) is not int or tag_id < 1:
return None, None, "tag_ids must be tag ids"
if len(set(tag_ids)) != len(tag_ids):
return None, None, "tag_ids must not repeat a tag"
return rule_id, tag_ids, None
def parse_options(options):
"""``(job_id, {rule_id: [tag_id]}, None)`` or ``(None, None, message)``."""
if not isinstance(options, dict) or set(options) != {"job_id", "select"}:
return None, None, "tag_cleanup takes options {job_id, select}"
job_id, select = options["job_id"], options["select"]
if not isinstance(job_id, str) or not 0 < len(job_id) <= MAX_JOB_ID:
return None, None, "job_id must be a tag search's job id"
if not isinstance(select, list) or not 0 < len(select) <= len(rules.RULES):
return None, None, f"select must list 1 to {len(rules.RULES)} rules"
chosen = {}
for entry in select:
rule_id, tag_ids, message = _parse_select(entry, chosen)
if message:
return None, None, message
chosen[rule_id] = tag_ids
return job_id, chosen, None
def _found_rows(result):
return [
{"path": "", "detail": f"{f['name']} · {rules.rule(rule_id).title}"}
for rule_id in rules.RULE_IDS
for f in result["rules"][rule_id]
]
def _public_rules(result):
return [
{
"id": item.id,
"title": item.title,
"explanation": item.explanation,
"action_label": item.action_label,
"total": result["totals"][item.id],
"findings": [
{
"tag_id": f["tag_id"],
"name": f["name"],
"detail": rules.finding_detail(f),
}
for f in result["rules"][item.id]
],
}
for item in rules.RULES
]
class TagCleanupMixin:
"""Mixin providing the tag cleanup find, its findings and its plan."""
def _register_tag_cleanup_routes(self, routes):
@routes.post("/prompt_manager/jobs/tag_cleanup")
async def start_tag_cleanup_find_route(request):
return await self.start_tag_cleanup_find(request)
@routes.get("/prompt_manager/maintenance/tag_cleanup/{job_id}")
async def tag_cleanup_findings_route(request):
return await self.tag_cleanup_findings(request)
# ── find ──────────────────────────────────────────────────────────
async def start_tag_cleanup_find(self, request):
"""Start the tag search (202), or 409 naming the job in the way."""
db = self.db
try:
job = self._jobs.start(
TAG_CLEANUP_JOB_KIND,
FIND_TITLE,
admission="read",
cancellable=False,
groups=TAG_CLEANUP_GROUP_NAMES,
runner=lambda job: self._run_tag_cleanup_find(job, db),
)
except JobBusy as busy:
return busy_response(busy)
self._remember_tag_cleanup_find(job.id)
return web.json_response({"success": True, "job": job.summary()}, status=202)
def _remember_tag_cleanup_find(self, job_id):
"""Hold a slot for ``job_id`` (None until it found); keep the last few."""
finds = self._tag_cleanup_finds
finds[job_id] = None
for held in list(finds):
if self._jobs.get(held) is None:
del finds[held]
while len(finds) > MAX_HELD_FINDS:
del finds[next(iter(finds))]
async def _run_tag_cleanup_find(self, job, db):
job.update(status_line="Looking for tags to clean up")
try:
result = await self._run_in_executor(
rules.find_tag_cleanup, db.model.db_path
)
except Exception:
self.logger.exception("Tag search failed")
job.update(status_line=FIND_FAILED)
job.log_line(FIND_FAILED)
job.finish("failed")
return
if job.id in self._tag_cleanup_finds:
self._tag_cleanup_finds[job.id] = result
count = sum(result["totals"].values())
job.record_counted("found", count, _found_rows(result))
line = (
f"Found {count:,} {'tag' if count == 1 else 'tags'} to clean up"
if count
else "No tags need cleaning up"
)
job.log_line(line)
job.update(progress=100, status_line=line)
# ── findings ──────────────────────────────────────────────────────
def _held_tag_cleanup(self, job_id):
"""``(result, None)`` for a finished search's findings, else a reply."""
job = self._jobs.get(job_id)
finds = self._tag_cleanup_finds
if job_id not in finds or job is None or job.kind != TAG_CLEANUP_JOB_KIND:
return None, _failure(
"No tag search with this id. Search again.", 404, "not-found"
)
if job.running:
return None, _failure(
"The tag search is still running.", 409, "job-running"
)
if finds[job_id] is None:
return None, _failure(
"This search did not finish. Search again.", 409, "no-groups"
)
return finds[job_id], None
async def tag_cleanup_findings(self, request):
job_id = request.match_info["job_id"]
result, error = self._held_tag_cleanup(job_id)
if error is not None:
return error
job = self._jobs.get(job_id)
return web.json_response(
{
"success": True,
"job": {"id": job.id, "state": job.state},
"rules": _public_rules(result),
},
headers={"Cache-Control": "no-store"},
)
# ── review ────────────────────────────────────────────────────────
async def preview_tag_cleanup(self, options):
"""The ``tag_cleanup`` plan for the ticked findings of one search."""
job_id, chosen, message = parse_options(options)
if message:
return _invalid(message)
held, error = self._held_tag_cleanup(job_id)
if error is not None:
return error
for rule_id, tag_ids in chosen.items():
listed = {f["tag_id"] for f in held["rules"][rule_id]}
if not listed.issuperset(tag_ids):
return _invalid("A selected tag is not a finding of its rule")
db = self.db
identity = self._database_identity(db)
try:
draft = await self._run_in_executor(
rules.plan_tag_cleanup, db.model.db_path, held, chosen
)
except Exception:
self.logger.exception("Tag cleanup review failed")
return _failure("Failed to review maintenance", 500)
return await self._plan_response(
db,
identity,
TAG_CLEANUP,
draft.fingerprint,
draft.public(),
{
"targets": draft.targets,
"roots": [],
"held": rules.held_rows(draft),
"protected": draft.protected["count"],
"rows": len(draft.targets),
},
)
+4 -1
View File
@@ -43,6 +43,7 @@ CONTENT_TYPES = {
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".avif": "image/avif", # #652: served as itself, never a preview
}
THUMB_SUFFIX = "_thumb"
@@ -133,7 +134,9 @@ def thumbnail_rel(rel_path, extension=None):
# Ruling R2: files sharing a stem share one preview, made from the first
# source in this order: these images, then videos (by extension name).
IMAGE_SOURCE_ORDER = (".png", ".jpg", ".jpeg", ".webp", ".gif")
# #652: AVIF comes last among the stills, so an existing stack keeps the
# source its preview was made from.
IMAGE_SOURCE_ORDER = (".png", ".jpg", ".jpeg", ".webp", ".gif", ".avif")
def source_rank(source_extension):
+47 -2
View File
@@ -38,6 +38,7 @@ from typing import Any, Dict, List, Optional, Tuple # noqa: E402
try:
from ..utils.logging_config import get_logger
from ..utils import library_location
from ..utils.media_formats import AVIF_EXTENSION
except ImportError:
import sys
@@ -45,6 +46,7 @@ except ImportError:
sys.path.insert(0, current_dir)
from utils.logging_config import get_logger
from utils import library_location
from utils.media_formats import AVIF_EXTENSION
# Initialize logger for config operations
config_logger = get_logger("prompt_manager.config")
@@ -195,7 +197,9 @@ class GalleryConfig:
# Read by the monitor for every file, so a save applies without a restart
SAVE_FOREIGN_RUNS = True
MONITORING_DIRECTORIES = [] # Auto-detect if empty
SUPPORTED_EXTENSIONS = [".png", ".jpg", ".jpeg", ".webp", ".gif"]
# #652: AVIF is named here and skipped at collection when Pillow cannot
# read it (utils.media_formats.collectable).
SUPPORTED_EXTENSIONS = [".png", ".jpg", ".jpeg", ".webp", ".gif", AVIF_EXTENSION]
PROCESSING_DELAY = 2.0 # Seconds to wait before processing new files
# Prompt tracking settings
@@ -301,7 +305,9 @@ class GalleryConfig:
if directories is not None:
cls.MONITORING_DIRECTORIES = directories
if "extensions" in monitoring:
cls.SUPPORTED_EXTENSIONS = monitoring["extensions"]
extensions = cls._validated_extensions(monitoring["extensions"])
if extensions is not None:
cls.SUPPORTED_EXTENSIONS = extensions
if "processing_delay" in monitoring:
cls.PROCESSING_DELAY = monitoring["processing_delay"]
@@ -355,6 +361,45 @@ class GalleryConfig:
config_logger.warning(f"Ignoring gallery root {label!r}: {reason}")
return kept
@classmethod
def _validated_extensions(cls, extensions: Any) -> Optional[List[str]]:
"""Monitor extensions from a saved config, with AVIF added back (#652).
``gallery.monitoring.extensions`` is saved in each user's config.json
and overrides the default, so an install that saved its settings
before #652 names no ``.avif`` and keeps not collecting AVIF files.
It is appended here, after the user's own entries, so an existing
install gains the new type without losing anything it chose.
A hand-edited config.json is as untrusted as a settings request: a
value that is not a list is ignored entirely (``None`` keeps the
current list), a non-string entry is dropped with a warning, and the
rest is normalised to lowercase dot-extensions.
"""
if not isinstance(extensions, list):
config_logger.warning(
"Ignoring gallery monitoring extensions: expected a list"
)
return None
kept = []
for entry in extensions:
if not isinstance(entry, str):
config_logger.warning(
"Ignoring gallery monitoring extension: expected a string"
)
continue
normalized = entry.strip().lower()
if not normalized:
continue
if not normalized.startswith("."):
normalized = "." + normalized
if normalized not in kept:
kept.append(normalized)
# An empty list is a deliberate "collect nothing", so it stays empty.
if kept and AVIF_EXTENSION not in kept:
kept.append(AVIF_EXTENSION)
return kept
@classmethod
def allowed_gallery_parents(cls) -> List[str]:
"""Canonical directories under which gallery roots may live.
+27 -9
View File
@@ -111,23 +111,29 @@ def preview(
"""The review's counts (blocking; reads only, requests nothing).
``{lora_files, with_metadata, skipped, with_local_media,
planned_downloads, fingerprint, names, layout}``: the metadata files
seen, the kept LoRAs whose sidecar parses, the rest, the LoRAs with a
local image, the CivitAI images an import would download for the LoRAs
without one (not yet in the cache), the first LoRA names and what the
layout says (``layout_summary``).
planned_downloads, trigger_tags, trigger_not_tags, fingerprint, names,
layout}``: the metadata files seen, the kept LoRAs whose sidecar parses,
the rest, the LoRAs with a local image, the CivitAI images an import would
download for the LoRAs without one (not yet in the cache), the trained-words
entries that become tags and those that do not (#618), the first LoRA
names and what the layout says (``layout_summary``).
"""
discovery = discover(lora_manager_path)
layout = discovery.layout
with_metadata = 0
with_local_media = 0
planned = 0
trigger_tags = 0
trigger_not_tags = 0
names = []
for sidecar in discovery.sidecars:
metadata = lora_utils.read_lora_metadata(sidecar.metadata_path)
if not metadata:
continue
with_metadata += 1
words, not_tags = lora_utils.trigger_word_tags(metadata)
trigger_tags += len(words)
trigger_not_tags += not_tags
if local_media(sidecar, metadata, layout, media_extensions):
with_local_media += 1
else:
@@ -142,6 +148,8 @@ def preview(
"skipped": discovery.scanned - with_metadata,
"with_local_media": with_local_media,
"planned_downloads": planned,
"trigger_tags": trigger_tags,
"trigger_not_tags": trigger_not_tags,
"fingerprint": fingerprint(discovery),
"names": names,
"layout": layout_summary(layout, Path.home()),
@@ -149,17 +157,22 @@ def preview(
def build_record(metadata: Dict, path: Path, images: List[str]) -> Dict:
"""The prompt a LoRA becomes: its example prompt (else its name), tags, images."""
"""The prompt a LoRA becomes: its example prompt (else its name), tags, images.
Only the trained words that are one short clean phrase become tags
(#618, ``lora_utils.is_tag_phrase``); ``trigger_not_tags`` counts the rest.
"""
model_name = lora_utils.get_model_name_from_metadata(metadata)
text = lora_utils.get_example_prompt_from_metadata(metadata) or model_name
tags = ["lora-manager", f"lora:{model_name}"]
tags.extend(lora_utils.get_trigger_words_from_metadata(metadata))
words, not_tags = lora_utils.trigger_word_tags(metadata)
tags = ["lora-manager", f"lora:{model_name}", *words]
return {
"name": model_name,
"text": text,
"hash": generate_prompt_hash(text),
"tags": list(dict.fromkeys(tags)),
"images": images,
"trigger_not_tags": not_tags,
}
@@ -171,7 +184,11 @@ class StagedImport:
records: List[Dict] = field(default_factory=list)
skipped: List[str] = field(default_factory=list)
stats: Dict[str, int] = field(
default_factory=lambda: {"downloaded": 0, "download_errors": 0}
default_factory=lambda: {
"downloaded": 0,
"download_errors": 0,
"trigger_not_tags": 0,
}
)
@@ -219,6 +236,7 @@ def stage(
images = list(dict.fromkeys([*local, *remote]))
record = build_record(metadata, path, images)
staged.records.append(record)
staged.stats["trigger_not_tags"] += record["trigger_not_tags"]
except Exception as error: # one LoRA never stops the import
name = lora_utils.get_model_name_from_metadata(metadata)
if logger is not None:
+40
View File
@@ -22,11 +22,13 @@ from urllib.parse import urljoin, urlsplit
try:
from ..utils.logging_config import get_logger
from ..utils.validators import validate_tags
except ImportError:
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utils.logging_config import get_logger
from utils.validators import validate_tags
from dataclasses import replace
@@ -387,6 +389,44 @@ def get_trigger_words_from_metadata(metadata: Dict) -> List[str]:
return []
# #618: what a prompt weight looks like, ``(masterpiece:1.2)``: an instruction
# to the sampler, never a label.
_PROMPT_WEIGHT = re.compile(r"\([^()]*:\s*-?\d*\.?\d+\s*\)")
# The ASCII and the fullwidth comma: an entry holding either is a list.
_COMMAS = (",", ",")
def is_tag_phrase(entry: object) -> bool:
"""Whether a trained-words entry is one short clean phrase (#618, Option A).
The existing tag rule (``validate_tags``: not empty, at most 50
characters, no control character), and no comma (ASCII or fullwidth), no
``<``/``>`` (``<lora:name:0.8>`` loads a model) and no prompt weight.
Plain parentheses stay allowed (``hatsune miku (vocaloid)``).
"""
if not isinstance(entry, str):
return False
phrase = entry.strip()
try:
validate_tags([phrase])
except ValueError:
return False
if any(comma in phrase for comma in _COMMAS):
return False
if "<" in phrase or ">" in phrase:
return False
return _PROMPT_WEIGHT.search(phrase) is None
def trigger_word_tags(metadata: Dict) -> Tuple[List[str], int]:
"""``(tags, not_tags)``: the trigger words that are tag phrases, stripped
and in order, and how many were not (#618). The trigger-word lookup
(``get_trigger_words_from_metadata``) still sees every entry."""
words = get_trigger_words_from_metadata(metadata)
tags = [word for word in words if is_tag_phrase(word)]
return tags, len(words) - len(tags)
def get_example_prompt_from_metadata(metadata: Dict) -> Optional[str]:
"""Extract an example prompt from civitai image metadata.
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "promptmanager"
description = "A powerful ComfyUI custom node that extends the standard text encoder with persistent prompt storage, advanced search capabilities, and an automatic image gallery system using SQLite."
version = "3.7.2"
version = "3.8.0"
license = {file = "LICENSE"}
requires-python = ">=3.12"
dependencies = ["watchdog>=2.1.0", "Pillow>=10.1.0"]
+2 -3
View File
@@ -8,9 +8,8 @@
// browser that exits abnormally prints one `pm-browser-exit|` line, and a test
// that fails on a closed or crashed target gets that log attached as
// `browser-stderr`.
// The one-time older-images notice (#527) shows above every workspace page and as
// a modal on the admin page until dismissed, so every context starts with it
// dismissed. A spec about the notice sets `test.use({ olderImagesNotice: true })`.
// The one-time older-images notice (#527) shows above every workspace page until
// dismissed, so every context starts with it dismissed. A spec about the notice sets `test.use({ olderImagesNotice: true })`.
import { test as base, expect } from '../../tools/vendor/node_modules/@playwright/test/index.mjs';
import { attachServerStderr, createServerSupervisor, startBrowserServer } from '../../tools/vendor/start-browser-server.mjs';
import { attachBrowserLogs, createBrowserLogRecorder } from '../../tools/vendor/browser-logs.mjs';
-182
View File
@@ -1,182 +0,0 @@
// #328: the legacy admin and gallery auto-tag batch and review keep working beside System › Auto-tagging. Since #330
// the pages download and unload models only through System (legacy-system-links.spec.mjs); a batch never downloads
// one. The fixture's fake download (`/__test__/tagging/download`) is held so nothing is ever fetched.
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
import { test, expect } from './fixtures.mjs';
async function post(request, url, data) {
await expect(await request.post(url, data === undefined ? {} : { data })).toBeOK();
}
async function downloads(request) {
const response = await request.get('/prompt_manager/jobs');
await expect(response).toBeOK();
return (await response.json()).jobs.filter(job => job.kind === 'model_download');
}
test.beforeEach(async ({ page, request, browserName }) => {
await startCoverage(page, browserName);
// The 3.2.0 update notice would cover the admin page's toolbar.
await page.addInitScript(() => { localStorage.setItem('pm_update_notice_dismissed', '3.2.0'); });
await post(request, '/__test__/jobs/restart');
await post(request, '/__test__/tagging/reset');
await post(request, '/__test__/tagging/models', { unavailable: ['wd14-vit'] });
await post(request, '/__test__/tagging/download', { mode: 'hold' });
});
test.afterEach(async ({ page, request, browserName }) => {
await saveCoverage(page, browserName);
// Releases a download a failed test left held, and puts the raising default back.
await post(request, '/__test__/tagging/reset');
await post(request, '/__test__/jobs/restart');
});
// (wd14-vit is not downloaded in these tests: beforeEach marks it so the download tests can offer it.)
// The gallery's batch reader keyed on `data.status` values the server never sends, so its modal never moved or
// closed (#328 Problem 5). It now reads `type` frames as the admin page does.
async function watchProgress(page) {
await page.evaluate(() => {
window.progressSeen = [];
const node = document.getElementById('autoTagProgressPercent');
// Each change from its own record: frames that land in one task share one
// callback, and the node's text by then is only the last of them.
new MutationObserver(records => {
for (const record of records) {
if (record.type === 'characterData') window.progressSeen.push(record.target.data);
for (const added of record.addedNodes) window.progressSeen.push(added.textContent);
}
}).observe(node, { childList: true, characterData: true, subtree: true });
});
}
async function runGalleryBatch(page) {
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
await watchProgress(page);
const done = page.waitForResponse(response => response.url().includes('/prompt_manager/autotag/start'));
await page.locator('#startAutoTagBtn').click();
await done;
await expect(page.locator('#autoTagProgressModal')).toBeHidden();
// #379: the batch counts images, never prompts.
await expect(page.getByText(/^Auto tagging complete! Tagged \d+ images?\.$/)).toBeVisible();
}
const CLOSE_NOTE = 'Closing this window stops tagging. Tags already added are kept. Prompt Manager\'s Activity page shows the '
+ 'time left.';
async function serverJobs(request) {
const response = await request.get('/prompt_manager/jobs');
await expect(response).toBeOK();
return (await response.json()).jobs;
}
async function runNativeBatch(request) {
const started = await request.post('/prompt_manager/jobs/autotag', { data: { model_type: 'wd14-swinv2', existing: 'skip',
options: { general_threshold: 0.35, character_threshold: 0.85 } } });
expect(started.status()).toBe(202);
const { job } = await started.json();
await expect.poll(async () => (await serverJobs(request)).find(item => item.id === job.id)?.state).toBe('finished');
}
test('gallery batch modal counts progress and closes on complete', async ({ page, request }) => {
await page.goto('/prompt_manager/gallery');
await runGalleryBatch(page);
const seen = await page.evaluate(() => window.progressSeen);
// The phase frames (model 5%, listing 8%) then the per-image frames (from 10%) move the bar.
expect(seen).toContain('8%');
expect(seen.some(value => parseInt(value, 10) >= 10)).toBe(true);
await expect(page.locator('#autoTagCloseNote')).toHaveText(CLOSE_NOTE);
// The batch ran as the autotag job of the legacy page.
expect((await serverJobs(request)).filter(job => job.kind === 'autotag').map(job => [job.title, job.state]))
.toEqual([['Tag output images (legacy page)', 'finished']]);
expect((await downloads(request)).length).toBe(0);
});
test('admin batch copy names images, not prompts (#379)', async ({ page }) => {
await page.goto('/prompt_manager/admin');
await page.locator('#autoTagBtn').click();
await expect(page.locator('input[name="autoTagMode"][value="skip"] + span')).toHaveText('Skip images already auto-tagged');
await expect(page.getByText('"auto-scanned" is not counted as a real tag')).toHaveCount(0);
await expect(page.locator('#autoTagCloseNote')).toHaveText(CLOSE_NOTE);
await expect(page.locator('#retagConfirmModal h3')).toHaveText('Image Already Auto-tagged');
await expect(page.locator('#retagConfirmModal')).toContainText('A tagging model already tagged this image. Generate new tags?');
});
test('admin review opens the first image', async ({ page }) => {
await page.goto('/prompt_manager/admin');
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
await page.locator('#startReviewBtn').click();
// #379: no image is auto-tagged yet (prompt tags no longer count), so the review opens on the first image.
await expect(page.locator('#retagConfirmModal')).toBeHidden();
await expect(page.locator('#autoTagReviewModal')).toBeVisible();
await expect(page.locator('#reviewImageName')).not.toHaveText(/^(image_name\.png|Unknown|)$/);
await expect(page.getByText('Failed to start review mode')).toHaveCount(0);
});
/** The admin review lists every row, videos too: Skip any image that is not one until the confirmation shows. */
async function untilAutoTagged(page, confirm) {
// Each image's skip check answers before its confirmation or its error shows.
const failed = page.locator('#reviewTagsVisible .text-pm-error');
for (let tries = 0; tries < 5; tries++) {
await expect.poll(async () => (await confirm.isVisible()) || (await failed.count()) > 0).toBe(true);
if (await confirm.isVisible()) return;
const answered = page.waitForResponse(item => item.url().endsWith('/prompt_manager/autotag/single'));
await page.locator('#skipReviewBtn').click();
await answered;
}
await expect(confirm).toBeVisible();
}
// #379: the admin review asks before re-tagging an image a model already tagged, and Apply & Next writes that image's
// tags (its bytes, never its prompt).
test('admin review: an auto-tagged image asks first; Re-tag then Apply & Next tags the image', async ({ page, request }) => {
await runNativeBatch(request);
await page.goto('/prompt_manager/admin');
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
await page.locator('#startReviewBtn').click();
const confirm = page.locator('#retagConfirmModal');
await untilAutoTagged(page, confirm);
await expect(confirm.locator('#retagExistingTags span').first()).toHaveText('sandstone');
await page.locator('#retagConfirmBtn').click();
await expect(page.locator('#autoTagReviewModal')).toBeVisible();
await expect(page.locator('#reviewTagsVisible .tag-chip').first()).toContainText('sandstone');
const applied = page.waitForRequest(item => item.url().endsWith('/prompt_manager/autotag/apply'));
const answer = page.waitForResponse(item => item.url().endsWith('/prompt_manager/autotag/apply'));
await page.locator('#applyReviewBtn').click();
const body = (await applied).postDataJSON();
expect(body.prompt_id).toBeUndefined();
expect(body.sha256).toMatch(/^[0-9a-f]{64}$/);
expect((await answer).status()).toBe(200);
});
test('admin review: Skip All Tagged passes every auto-tagged image', async ({ page, request }) => {
await runNativeBatch(request);
await page.goto('/prompt_manager/admin');
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
await page.locator('#startReviewBtn').click();
const confirm = page.locator('#retagConfirmModal');
await untilAutoTagged(page, confirm);
await page.locator('#retagSkipAllBtn').click();
await expect(page.locator('#retagConfirmModal')).toBeHidden();
await expect(page.getByText('Review complete!')).toBeVisible();
});
test('gallery review: Apply & Next tags the image by its path and bytes', async ({ page }) => {
await page.goto('/prompt_manager/gallery');
await page.locator('#autoTagBtn').click();
await page.locator('input[name="autoTagModel"][value="wd14-swinv2"]').check();
const suggested = page.waitForRequest(item => item.url().endsWith('/prompt_manager/autotag/single'));
await page.locator('#startReviewBtn').click();
expect((await suggested).postDataJSON().existing).toBe('merge');
await expect(page.locator('#reviewTagsContainer .tag-chip').first()).toContainText('sandstone');
const applied = page.waitForRequest(item => item.url().endsWith('/prompt_manager/autotag/apply'));
const answer = page.waitForResponse(item => item.url().endsWith('/prompt_manager/autotag/apply'));
await page.locator('#applyReviewBtn').click();
const body = (await applied).postDataJSON();
expect(Object.keys(body).sort()).toEqual(['path', 'root_index', 'sha256', 'tags'].filter(key => key in body).sort());
expect(body.prompt_id).toBeUndefined();
expect((await answer).status()).toBe(200);
});
@@ -1,47 +0,0 @@
// #615: each old page says it will be removed and links to where its job lives now. The page keeps working, and the
// notice takes its own room: nothing is pushed off a page whose layout fills the window.
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
import { test, expect } from './fixtures.mjs';
const PAGES = Object.freeze([
{ path: '/prompt_manager/admin', section: 'library', heading: 'Prompt library' },
{ path: '/prompt_manager/gallery', section: 'images', heading: 'Images' },
{ path: '/prompt_manager/gallery.html', section: 'inspect', heading: 'Inspect a file' },
]);
test.beforeEach(async ({ page, request, browserName }) => {
await startCoverage(page, browserName);
await expect(await request.post('/__test__/reset', {})).toBeOK();
await page.addInitScript(() => {
localStorage.setItem('pm_update_notice_dismissed', '3.2.0');
localStorage.setItem('gallerySettings', JSON.stringify({ checkThumbnailsAtStartup: false }));
});
});
test.afterEach(async ({ page, browserName }) => {
await saveCoverage(page, browserName);
});
for (const { path, section, heading } of PAGES) {
test(`${path} says it will be removed and links to ${section}`, async ({ page }) => {
await page.goto(path);
const notice = page.locator('#legacy-removal-notice');
await expect(notice).toBeVisible();
await expect(notice).toContainText('This page will be removed in a future release.');
await notice.getByRole('link', { name: 'Open the workspace' }).click();
await expect(page).toHaveURL(new RegExp(`/prompt_manager/workspace#/${section}$`));
await expect(page.locator('#workspace-main h1')).toHaveText(heading);
});
}
test('the notice leaves the metadata page filling the window', async ({ page }) => {
await page.goto('/prompt_manager/gallery.html');
await expect(page.locator('#legacy-removal-notice')).toBeVisible();
const { bottom, height, scroll } = await page.locator('#image-area').evaluate(area => ({
bottom: area.getBoundingClientRect().bottom,
height: window.innerHeight,
scroll: document.documentElement.scrollHeight,
}));
expect(bottom).toBeLessThanOrEqual(height);
expect(scroll).toBeLessThanOrEqual(height);
});
-286
View File
@@ -1,286 +0,0 @@
// System S13 (#330): the legacy admin and gallery pages open native System for their System tools. Each replaced
// control is a plain link (`workspace#/system/<id>`, a new tab), and the legacy flows S13 keeps still work.
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
import { test, expect } from './fixtures.mjs';
const PAGES = Object.freeze({ admin: '/prompt_manager/admin', gallery: '/prompt_manager/gallery' });
const LABELS = Object.freeze({
overview: 'Overview',
appearance: 'Appearance',
sources: 'Sources & scans',
integrations: 'Integrations',
tagging: 'Auto-tagging',
maintenance: 'Maintenance',
backups: 'Backup & export',
diagnostics: 'Diagnostics & logs',
});
async function openPageOptions(page) {
await page.locator('#pageOptionsBtn').click();
await expect(page.locator('#settingsModal')).toBeVisible();
}
/** The auto-tag modal with its model rows read from /autotag/models. */
async function openAutoTag(page) {
const read = page.waitForResponse(item => item.url().endsWith('/prompt_manager/autotag/models'));
await page.locator('#autoTagBtn').click();
await read;
await expect(page.locator('#autoTagModal')).toBeVisible();
}
const notDownloaded = (page, request) => post(request, '/__test__/tagging/models', { unavailable: ['gguf'] });
const modelLoaded = (page, request) => post(request, '/__test__/tagging/loaded', { model: 'wd14-vit' });
// One row per System link of the design's §2 map: the page, the control's label, how to find it, the section it opens
// and what a test must arrange before the control shows.
const LINKS = Object.freeze([
{ page: 'admin', label: 'Settings', locate: page => page.locator('#settingsBtn'), section: 'overview' },
{ page: 'admin', label: 'Maintenance', locate: page => page.locator('#maintenanceBtn'), section: 'maintenance' },
{ page: 'admin', label: 'Backup DB', locate: page => page.locator('#backupBtn'), section: 'backups' },
{ page: 'admin', label: 'Restore DB', locate: page => page.locator('#restoreBtn'), section: 'backups' },
{ page: 'gallery', label: 'Settings', locate: page => page.locator('#settingsBtn'), section: 'appearance' },
{ page: 'admin', label: 'Manage in System (model row)', arrange: notDownloaded, reveal: openAutoTag,
locate: page => page.locator('#ggufModelStatus a'), section: 'tagging' },
{ page: 'gallery', label: 'Manage in System (model row)', arrange: notDownloaded, reveal: openAutoTag,
locate: page => page.locator('#ggufModelStatus a'), section: 'tagging' },
{ page: 'gallery', label: 'Manage in System (Unload Model)', arrange: modelLoaded, reveal: openAutoTag,
locate: page => page.locator('#unloadModelBtn'), section: 'tagging' },
{ page: 'gallery', label: 'Page options Maintenance', reveal: openPageOptions,
locate: page => page.locator('#pageOptionsMaintenanceLink'), section: 'maintenance' },
{ page: 'gallery', label: 'Page options Sources & scans', reveal: openPageOptions,
locate: page => page.locator('#pageOptionsSourcesLink'), section: 'sources' },
{ page: 'admin', label: 'Diagnostics', locate: page => page.locator('#diagnosticsBtn'), section: 'diagnostics' },
{ page: 'admin', label: 'View Logs', locate: page => page.locator('#logsBtn'), section: 'diagnostics' },
]);
async function post(request, url, data) {
await expect(await request.post(url, data === undefined ? {} : { data })).toBeOK();
}
test.beforeEach(async ({ page, request, browserName }) => {
await startCoverage(page, browserName);
await post(request, '/__test__/reset');
await post(request, '/__test__/system/reset');
await post(request, '/__test__/tagging/reset');
// The 3.2.0 update notice would cover the admin page's toolbar.
await page.addInitScript(() => { localStorage.setItem('pm_update_notice_dismissed', '3.2.0'); });
page.legacyErrors = [];
page.on('pageerror', error => page.legacyErrors.push(error.message));
});
test.afterEach(async ({ page, request, browserName }) => {
await saveCoverage(page, browserName);
await post(request, '/__test__/tagging/reset');
await post(request, '/__test__/system/reset');
expect(page.legacyErrors).toEqual([]);
});
/** Opens the legacy page with the link showing; returns the link. */
async function openLink(page, request, link) {
if (link.arrange) await link.arrange(page, request);
await page.goto(PAGES[link.page]);
if (link.reveal) await link.reveal(page);
const control = link.locate(page);
await expect(control).toBeVisible();
return control;
}
// Each row opens its section in a new tab and sends no request from the legacy page (the design's `a System link sends
// no request from the legacy page`, checked per row so one slow page never times out the whole table).
for (const link of LINKS) {
test(`legacy ${link.page} ${link.label} opens System ${link.section}`, async ({ page, context, request }) => {
// The gallery's thumbnail startup check (K9) reads its status on a timer of its own; it is off here.
await page.addInitScript(() => {
localStorage.setItem('gallerySettings', JSON.stringify({ checkThumbnailsAtStartup: false }));
});
const control = await openLink(page, request, link);
const legacyUrl = page.url();
await expect(control).toHaveAttribute('href', `workspace#/system/${link.section}`);
await expect(control).toHaveAttribute('target', '_blank');
await expect(control).toHaveAttribute('rel', 'noopener');
// The page's own start-up reads (list, film strips, settings) finish first; then the click must add none.
// Lazy thumbnails may still load whenever the layout changes; they are not the click's.
await page.waitForLoadState('networkidle');
const sent = [];
const record = item => { if (item.resourceType() !== 'image') sent.push(`${item.method()} ${item.url()}`); };
page.on('request', record);
const opened = context.waitForEvent('page');
await control.click();
const system = await opened;
await expect(system).toHaveURL(new RegExp(`/prompt_manager/workspace#/system/${link.section}$`));
page.off('request', record);
expect(sent, 'a System link sends no request from the legacy page').toEqual([]);
// System's page heading is "System"; the open section is the pressed button of its section switcher.
const main = system.locator('#workspace-main');
await expect(main.getByRole('heading', { level: 1, name: 'System', exact: true })).toBeVisible();
await expect(main.getByRole('group', { name: 'System sections', exact: true })
.getByRole('button', { name: LABELS[link.section], exact: true })).toHaveAttribute('aria-pressed', 'true');
expect(page.url()).toBe(legacyUrl);
await system.close();
});
}
test('kept admin flows still work', async ({ page, context }) => {
await page.goto(PAGES.admin);
const texts = page.locator('#resultsList .prompt-text');
await expect(texts.first()).toBeVisible();
// K1: sorting reorders the list.
for (const [value, order] of [['text_asc', 1], ['text_desc', -1]]) {
const listed = page.waitForResponse(item => /\/prompt_manager\/(recent|search)\?/.test(item.url()) && item.url().includes(`sort=${value}`));
await page.locator('#sortBy').selectOption(value);
await listed;
await expect.poll(async () => {
const shown = await texts.allTextContents();
// The server sorts case-insensitively (SQLite NOCASE), not by locale.
const key = text => text.toLowerCase();
const sorted = [...shown].sort((a, b) => order * (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
return shown.length > 1 && shown.join('\n') === sorted.join('\n');
}).toBe(true);
}
// K3: Add Prompt saves a prompt the list then shows.
await page.locator('#addPromptBtn').click();
await page.locator('#addPromptText').fill('Kept flow lighthouse');
const saved = page.waitForResponse(item => item.request().method() === 'POST' && item.url().endsWith('/prompt_manager/save'));
await page.locator('#saveNewPromptBtn').click();
expect((await saved).ok()).toBe(true);
await expect(page.locator('#addPromptModal')).toBeHidden();
await expect(texts.filter({ hasText: 'Kept flow lighthouse' })).toBeVisible();
// K1: a search narrows the list, and a selection enables the bulk buttons.
const all = await texts.allTextContents();
const word = all[0].trim().split(/\s+/)[0];
const searched = page.waitForResponse(item => item.url().includes('/prompt_manager/search?') && item.url().includes('text='));
await page.locator('#searchText').fill(word);
await page.locator('#searchBtn').click();
await searched;
await expect.poll(async () => {
const shown = await texts.allTextContents();
return shown.length > 0 && shown.length < all.length && shown.every(text => text.toLowerCase().includes(word.toLowerCase()));
}).toBe(true);
await expect(page.locator('#bulkDeleteBtn')).toBeDisabled();
await page.locator('#resultsList .prompt-checkbox').first().check();
for (const id of ['#bulkDeleteBtn', '#bulkTagBtn', '#bulkCategoryBtn']) await expect(page.locator(id)).toBeEnabled();
// K4: Stats reads the statistics again; Export downloads the prompts.
const stats = page.waitForResponse(item => item.url().endsWith('/prompt_manager/stats') && item.ok());
await page.locator('#statsBtn').click();
await stats;
await expect(page.getByText('Stats refreshed successfully!')).toBeVisible();
const download = page.waitForEvent('download');
await page.locator('#exportBtn').click();
expect((await download).suggestedFilename()).toMatch(/^prompts-\d{4}-\d{2}-\d{2}\.json$/);
// K5: Scan Images opens its dialog (with the quick backup) without starting a scan.
await page.locator('#scanBtn').click();
await expect(page.locator('#scanModal')).toBeVisible();
await expect(page.locator('#quickBackupBtn')).toBeVisible();
await page.locator('#cancelScan').click();
await expect(page.locator('#scanModal')).toBeHidden();
// K7: Metadata and Gallery open their pages in a new tab.
for (const [id, path] of [['#metadataBtn', '/prompt_manager/gallery.html'], ['#galleryBtn', '/prompt_manager/gallery']]) {
const opened = context.waitForEvent('page');
await page.locator(id).click();
const tab = await opened;
await tab.waitForLoadState('domcontentloaded');
expect(new URL(tab.url()).pathname).toBe(path);
await tab.close();
}
});
test('Page options keeps the page-only settings admin', async ({ page, request }) => {
const before = (await (await request.get('/prompt_manager/settings')).json()).settings;
await page.goto(PAGES.admin);
await expect(page.locator('#resultsList .prompt-text').first()).toBeVisible();
await page.locator('#pageOptionsBtn').click();
const dialog = page.locator('#settingsModal');
await expect(dialog).toBeVisible();
await expect(dialog.locator('h3')).toHaveText('Page options');
// Exactly the page-only setting (G5): the list's Infinite Scrolling default.
expect(await dialog.locator('input, select, textarea').evaluateAll(fields => fields.map(field => field.id)))
.toEqual(['infiniteScrollDefault']);
await expect(page.locator('#infiniteScrollDefault')).not.toBeChecked();
await page.locator('#infiniteScrollDefault').check();
const saved = page.waitForRequest(item => item.method() === 'POST' && item.url().endsWith('/prompt_manager/settings'));
await page.locator('#saveSettings').click();
expect((await saved).postDataJSON()).toEqual({ infinite_scroll: true });
await expect(dialog).toBeHidden();
// The list header follows the saved default at once; nothing else changed.
await expect(page.locator('#infiniteScrollSession')).toBeChecked();
const after = (await (await request.get('/prompt_manager/settings')).json()).settings;
expect(after).toEqual({ ...before, infinite_scroll: true });
await page.reload();
// The dialog shows the saved default once the page has read it (the header follows it first).
await expect(page.locator('#infiniteScrollSession')).toBeChecked();
await page.locator('#pageOptionsBtn').click();
await expect(page.locator('#infiniteScrollDefault')).toBeChecked();
});
test('Page options keeps the page-only settings gallery', async ({ page }) => {
// Native Appearance keys and the startup prompt's own keys are in the shared object before the page opens.
const stored = { imageQuality: 'high', showImageInfo: false, videoMute: false,
autoLoadMetadata: false, workspaceLayout: 'masonry', thumbnailPromptDismissed: 'sig', thumbnailsGenerated: true,
checkThumbnailsAtStartup: false, defaultViewMode: 'list' };
await page.addInitScript(value => {
if (!sessionStorage.getItem('seeded')) {
sessionStorage.setItem('seeded', '1');
localStorage.setItem('gallerySettings', value);
}
}, JSON.stringify(stored));
const listed = page.waitForResponse(item => item.url().includes('/prompt_manager/images/output?'));
await page.goto(PAGES.gallery);
await listed;
// With no Page options control, a stored default view still opens the page in it.
await expect(page.locator('#listViewBtn')).toHaveClass(/bg-pm-accent/);
await openPageOptions(page);
const dialog = page.locator('#settingsModal');
await expect(dialog.locator('h3')).toHaveText('Page options');
// Exactly the page-only settings (G5); the default view is System › Appearance's Default layout.
expect(await dialog.locator('input, select, textarea').evaluateAll(fields => fields.map(field => field.id))).toEqual([
'checkThumbnailsAtStartup', 'lazyLoadingToggle', 'defaultLimitSelect', 'gridColumnsSelect',
'infiniteScrollToggle', 'debugModeToggle', 'apiTimeoutInput']);
await expect(dialog.getByText('Default View Mode')).toHaveCount(0);
await page.locator('#defaultLimitSelect').selectOption('50');
await page.locator('#debugModeToggle').check();
await page.locator('#saveSettingsBtn').click();
await expect(dialog).toBeHidden();
const read = () => page.evaluate(() => JSON.parse(localStorage.getItem('gallerySettings')));
let saved = await read();
expect(saved).toMatchObject({ ...stored, defaultLimit: 50, debugMode: true });
// Reset puts back only the page options' defaults; the Appearance, startup-prompt and default-view keys stay.
await openPageOptions(page);
page.once('dialog', dialog => dialog.accept());
await page.locator('#resetSettingsBtn').click();
await expect(page.getByText('Page options reset to defaults')).toBeVisible();
await expect(page.locator('#defaultLimitSelect')).toHaveValue('100');
saved = await read();
expect(saved).toMatchObject({ defaultViewMode: 'list', imageQuality: 'high', showImageInfo: false, videoMute: false,
autoLoadMetadata: false, workspaceLayout: 'masonry', thumbnailPromptDismissed: 'sig', thumbnailsGenerated: true,
defaultLimit: 100, debugMode: false, checkThumbnailsAtStartup: true, lazyLoading: true, gridColumns: 8,
infiniteScroll: false, apiTimeout: 30 });
});
test('the legacy auto-tag modal stays open after Manage in System', async ({ page, context, request }) => {
for (const legacy of ['admin', 'gallery']) {
await post(request, '/__test__/tagging/models', { unavailable: ['gguf'] });
await page.goto(PAGES[legacy]);
await openAutoTag(page);
const link = page.locator('#ggufModelStatus').getByRole('link', { name: 'Manage in System', exact: true });
await expect(link).toHaveAttribute('title', 'Opens System › Auto-tagging in a new tab');
// A downloaded model keeps its status text.
await expect(page.locator('#wd14VitModelStatus')).toHaveText('\u2713 Downloaded');
const opened = context.waitForEvent('page');
await link.click();
const system = await opened;
await expect(system).toHaveURL(/#\/system\/tagging$/);
await expect(page.locator('#autoTagModal')).toBeVisible();
await system.close();
// Downloaded in System meanwhile: reopening the modal reads the models again (CUJ 4).
await post(request, '/__test__/tagging/models', { unavailable: [] });
await page.goto(PAGES[legacy]);
await openAutoTag(page);
await expect(page.locator('#ggufModelStatus')).toHaveText('\u2713 Downloaded');
}
});
+97
View File
@@ -0,0 +1,97 @@
// #668 (D207): the old admin, gallery and metadata pages are gone. Their URLs, and the old tag bookmarks, lead into
// the workspace, against the real server.
import {startCoverage,saveCoverage} from '../../tools/vendor/browser-coverage.mjs';
import {test,expect} from './fixtures.mjs';
const cards=page=>page.locator('article[data-prompt-id]');
const card=(page,text)=>cards(page).filter({has:page.getByText(text,{exact:true})});
const filtersButton=page=>page.locator('#workspace-main search.toolbar').getByRole('button',{name:/^Filters(?: · \d)?$/});
const caption=page=>page.locator('#workspace-main .section-caption > span').first();
const heading=page=>page.locator('#workspace-main h1').first();
/** The workspace at exactly this hash. */
const at=hash=>url=>url.pathname.endsWith('/prompt_manager/workspace')&&url.search===''&&url.hash===hash;
test.beforeEach(async({page,request,browserName})=>{
await startCoverage(page,browserName);await expect(await request.post('/__test__/reset',{data:{native_library:true}})).toBeOK();
page.oldUrlErrors=[];page.on('pageerror',error=>page.oldUrlErrors.push(error.message));
// A deleted page asset that is still requested would answer 404.
page.missing=[];page.on('response',response=>{if(response.status()===404)page.missing.push(new URL(response.url()).pathname);});
});
test.afterEach(async({page,browserName})=>{
await saveCoverage(page,browserName);expect(page.oldUrlErrors).toEqual([]);expect(page.missing).toEqual([]);
});
for(const [url,hash,title] of [
['/prompt_manager/admin','#/library','Prompt library'],
['/prompt_manager/admin#/tags','#/tags','Tags & categories'],
['/prompt_manager/admin#/tags/','#/tags','Tags & categories'],
['/prompt_manager/admin#/something-else','#/library','Prompt library'],
['/prompt_manager/gallery','#/images','Images'],
['/prompt_manager/gallery.html','#/inspect','Inspect a file'],
['/prompt_manager/web','#/library','Prompt library'],
]) {
test(`${url} opens the workspace's ${title}`,async({page})=>{
await page.goto(url);
await expect(page).toHaveURL(at(hash));
await expect(heading(page)).toHaveText(title);
});
}
test('an old one-tag bookmark opens the Library filtered by that tag',async({page})=>{
await page.goto('/prompt_manager/admin#/tags/cats');
await expect(page).toHaveURL(at('#/library?tag=cats'));
await expect(caption(page)).toHaveText(/^1 positive prompt · /);
await expect(card(page,'Cat portrait')).toHaveCount(1);await expect(cards(page)).toHaveCount(1);
await expect(filtersButton(page)).toHaveText('Filters · 1');
});
test('an old two-tag bookmark matches all of the tags, and any of them with ?mode=or',async({page})=>{
await page.goto('/prompt_manager/admin#/tags/cats,dogs');
await expect(caption(page)).toHaveText(/^0 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters · 1');
await page.goto('about:blank');
await page.goto('/prompt_manager/admin#/tags/cats,dogs?mode=or');
await expect(page).toHaveURL(at('#/library?tag=cats&tag=dogs&tag_mode=any'));
await expect(caption(page)).toHaveText(/^2 positive prompts · /);
await expect(card(page,'Cat portrait')).toHaveCount(1);await expect(card(page,'Dog landscape')).toHaveCount(1);
await expect(filtersButton(page)).toHaveText('Filters · 2');
});
test('an old untagged bookmark asks the Library for the prompts without a tag',async({page})=>{
const listed=page.waitForResponse(item=>{const url=new URL(item.url());return url.pathname==='/prompt_manager/library'&&url.searchParams.get('tag_mode')==='untagged';});
await page.goto('/prompt_manager/admin#/tags/__untagged__');
expect((await (await listed).json()).tag_mode).toBe('untagged');
await expect(page).toHaveURL(at('#/library?tag_mode=untagged'));await expect(filtersButton(page)).toHaveText('Filters · 1');
});
test('the old dashboard URL shows the whole Library even after a tag bookmark in the same tab',async({page})=>{
await page.goto('/prompt_manager/admin#/tags/cats');
await expect(caption(page)).toHaveText(/^1 positive prompt · /);
await page.goto('/prompt_manager/admin');
await expect(page).toHaveURL(at('#/library'));
await expect(caption(page)).toHaveText(/^3 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters');
});
test('Back from the workspace skips the old URL instead of bouncing through it',async({page})=>{
await page.goto('/prompt_manager/workspace#/overview');
await expect(heading(page)).toHaveText('Overview');
for(const [url,title] of [['/prompt_manager/admin#/tags/cats','Prompt library'],['/prompt_manager/gallery','Images']]) {
await page.goto(url);
await expect(heading(page)).toHaveText(title);
await page.goBack();
await expect(page).toHaveURL(at('#/overview'));
await expect(heading(page)).toHaveText('Overview');
}
});
test('the old pages\' scripts and stylesheet are no longer served',async({request})=>{
for(const asset of ['js/admin.js','js/gallery.js','js/tags-page.js','lib/tailwind/styles.css']) {
expect((await request.get(`/prompt_manager/${asset}`)).status(),asset).toBe(404);
}
});
test('the server itself redirects the two old pages that had no hash routes',async({request})=>{
for(const [url,target] of [['/prompt_manager/gallery','workspace#/images'],['/prompt_manager/gallery.html','workspace#/inspect']]) {
const response=await request.get(url,{maxRedirects:0});
expect([response.status(),response.headers().location]).toEqual([302,target]);
}
});
@@ -261,7 +261,8 @@ function measureReview() {
/**
* D107: the server's import plan in the concept's review: "Review LoRA import" with "LoRA reference data" as its `h3`,
* the concept's four rows with the plan's values plus Found and Network, the LoRAs it found (`details`), the hold
* the concept's four rows with the plan's values plus Found, Trigger words (#618, D210) and Network, the LoRAs it
* found (`details`), the hold
* line with the cache sentence in the concept's `p.small`, the D55 backup box, and Cancel / "Start import".
*/
function mapImportConcept(reference, plan) {
@@ -273,6 +274,7 @@ function mapImportConcept(reference, plan) {
heading: { ...reference.heading, text: 'LoRA reference data' },
grid: { ...reference.grid, rows: [['LoraManager', 'environment settings · alongside storage · library default'],
['Scope', plan.scope.label], ['Found', '2 metadata files · 2 LoRAs · 0 with local images'],
['Trigger words', '2 become tags'],
['Protected', 'Nothing is protected'], ['Network', 'Downloads up to 2 example images from CivitAI'],
['Backup', `Create and verify before changes (${plan.backup.destination_label})`],
['Media on disk', 'No files are removed; image links are replaced']] },
@@ -333,9 +335,10 @@ test('LoRA import review comparison detects mutations', async ({ page, request }
const expected = mapImportConcept(concept, plan);
const paths = async () => diffInventory(expected, await page.evaluate(measureReview)).map(item => item.path);
expect(await paths()).toEqual([]);
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[4].textContent = 'Downloads'; });
expect(await paths()).toEqual(['grid.rows.4.0']);
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[4].textContent = 'Network'; });
// Network is the sixth row (after #618's Trigger words).
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[5].textContent = 'Downloads'; });
expect(await paths()).toEqual(['grid.rows.5.0']);
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[5].textContent = 'Network'; });
const undoGrid = await mutate(page, { css: 'dialog#modal dl.meta-grid { column-gap: 3px; }' });
expect(await paths()).toEqual(expect.arrayContaining(['grid.columnGap']));
await undoGrid();
@@ -83,9 +83,29 @@ function mapPairRow(reference) {
};
}
/**
* D210 (#618, beyond the concept): Database adds "Tag cleanup" after "Pair category and tags", shaped like the concept's
* danger row (Unused prompt components') with its own button label, "Find tags".
*/
function mapTagRow(reference) {
return {
...reference,
surfaces: reference.surfaces.map(surface => {
const danger = surface.rows.find(row => row.title === 'Unused prompt components');
const at = surface.rows.findIndex(row => row.title === 'Pair category and tags');
if (!danger || at < 0) return surface;
return { ...surface, tree: [...surface.tree, 'div.operation'], rows: [...surface.rows.slice(0, at + 1),
{ ...danger, title: 'Tag cleanup', description: 'Find tags that are whole comma lists or are used nowhere. ' +
'Review them, then remove only what you tick.',
actions: danger.actions.map(action => ({ ...action, text: 'Find tags' })) },
...surface.rows.slice(at + 1)] };
}),
};
}
/** D102: the Metadata cache row says why its review is unavailable and its button is aria-disabled (D93's dimmed style). */
function mapMaintenanceConcept(reference) {
const mapped = mapPairRow(reference);
const mapped = mapTagRow(mapPairRow(reference));
return {
...mapped,
surfaces: mapped.surfaces.map(surface => ({ ...surface, rows: surface.rows.map(row => row.title !== 'Metadata cache' ? row : {
@@ -229,8 +249,8 @@ test('maintenance comparison detects mutations', async ({ page, request }) => {
const expected = mapMaintenanceConcept(concept);
const production = await productionMaintenance(page, 'dark');
expect(diffInventory(expected, production)).toEqual([]);
// Mapped only for the D192 row, the section differs only on the D102 row.
expect(diffInventory(mapPairRow(concept), production).map(item => item.path).sort()).toEqual([
// Mapped only for the D192 and D210 rows, the section differs only on the D102 row.
expect(diffInventory(mapTagRow(mapPairRow(concept)), production).map(item => item.path).sort()).toEqual([
'surfaces.1.rows.3.actions.0.cursor', 'surfaces.1.rows.3.actions.0.opacity', 'surfaces.1.rows.3.description']);
const measure = () => page.evaluate(measureMaintenance, '#workspace-main');
const paths = async () => diffInventory(expected, await measure()).map(item => item.path);
-280
View File
@@ -1,280 +0,0 @@
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
import { test, expect } from './fixtures.mjs';
test.beforeEach(async ({ request, page, browserName }) => {
await startCoverage(page, browserName);
await expect(await request.post('/__test__/reset')).toBeOK();
page.workflowErrors = [];
page.on('pageerror', error => page.workflowErrors.push(error.message));
page.on('response', response => {
if (response.status() >= 500 && response.url().includes('/prompt_manager/')) {
page.workflowErrors.push(`${response.status()} ${response.url()}`);
}
});
await page.addInitScript(() => { localStorage.setItem('pm_update_notice_dismissed', '3.2.0'); });
});
test.afterEach(async ({ page, browserName }) => {
await saveCoverage(page, browserName);
expect(page.workflowErrors).toEqual([]);
});
// #249 S6b: the legacy admin page says where the library lives (the fixture's database is configured explicitly).
test('the admin page names the library location', async ({ page }) => {
await page.goto('/prompt_manager/admin');
await expect(page.locator('#libraryLocation')).toHaveText('Library: browser.db (set in config.json)');
await expect(page.locator('#totalPrompts')).not.toHaveText('-');
});
test('actual gallery form saves a prompt that the admin page can edit and reload', async ({ page, request }) => {
await page.goto('/prompt_manager/gallery');
await page.locator('#addPromptBtn').click();
await page.locator('#addPromptText').fill('Browser saved landscape');
await page.locator('#addPromptCategory').fill('Browser tests');
await page.locator('#addPromptTagInput').fill('browser-tag');
await page.locator('#addPromptTagInput').press('Enter');
await page.locator('#saveNewPromptBtn').click();
await expect(page.locator('#addPromptModal')).toBeHidden();
await page.goto('/prompt_manager/admin');
const text = page.locator('.prompt-text').filter({ hasText: 'Browser saved landscape' });
await expect(text).toBeVisible();
const id = await text.getAttribute('data-id');
await page.locator(`[data-action="edit"][data-prompt-id="${id}"]`).click();
const editor = page.locator(`.prompt-text[data-id="${id}"]`);
await editor.fill('Browser edited portrait');
// The page shows the edit at once and saves it after: reload only once the save answered (a reload that wins the
// race abandons the PUT, as seen on WebKit in CI).
const savedEdit = page.waitForResponse(item => item.request().method() === 'PUT'
&& item.url().endsWith(`/prompt_manager/prompts/${id}`));
await editor.press('Enter');
await expect(page.locator('.prompt-text').filter({ hasText: 'Browser edited portrait' })).toBeVisible();
expect((await savedEdit).ok()).toBe(true);
await page.reload();
await expect(page.locator('.prompt-text').filter({ hasText: 'Browser edited portrait' })).toBeVisible();
const saved = await request.post('/prompt_manager/save', { data: { text: 'Browser saved landscape' } });
expect((await saved.json()).prompt_id).not.toBe(Number(id));
});
// WebKit fails a fetch that a leaving page starts ("Fetch API cannot load … due to access control checks."), and
// Playwright reports that console error as a page error. A save's follow-up reads must not start once the page hides:
// here the statistics read after an in-place edit is held at the server while the page reloads.
test('an in-place edit whose follow-up reads outlive the page starts no read while it leaves', async ({ page, request }) => {
await page.goto('/prompt_manager/admin');
const text = page.locator('.prompt-text').filter({ hasText: 'Cat portrait' });
const id = await text.getAttribute('data-id');
await expect(await request.post('/__test__/hold', { data: { path: '/prompt_manager/stats' } })).toBeOK();
await page.locator(`[data-action="edit"][data-prompt-id="${id}"]`).click();
const editor = page.locator(`.prompt-text[data-id="${id}"]`);
await editor.fill('Cat portrait at dusk');
await editor.press('Enter');
const held = async () => (await (await request.get('/__test__/hold')).json()).held['/prompt_manager/stats'];
await expect.poll(held).toBe(1);
await page.reload({ waitUntil: 'commit' });
await expect(await request.post('/__test__/release')).toBeOK();
await expect(page.locator('.prompt-text').filter({ hasText: 'Cat portrait at dusk' })).toBeVisible();
});
// A leave that never happens (a stopped navigation, or one answered with a download) must not leave the list dead.
test('a page whose leave was called off reads its list again on the next input', async ({ page }) => {
await page.goto('/prompt_manager/admin');
await expect(page.locator('.prompt-text').first()).toBeVisible();
await page.evaluate(() => window.dispatchEvent(new Event('beforeunload')));
await page.mouse.click(1, 1);
const reread = page.waitForResponse(response => new URL(response.url()).pathname === '/prompt_manager/recent');
await page.locator('#sortBy').selectOption('created_asc');
expect(new URL((await reread).url()).searchParams.get('sort')).toBe('created_asc');
await expect(page.locator('#resultsTitle')).toHaveText('Recent Prompts');
});
// The gallery's startup thumbnail check runs a second after load. When that second ends while the page is leaving,
// the check must start no read: WebKit fails it with "Fetch API cannot load … due to access control checks." and
// Playwright reports a page error (seen in CI on PR #289). The page clock makes the second end after the leave began.
for (const leave of ['beforeunload', 'pagehide']) {
test(`the gallery startup check starts no read after ${leave}`, async ({ page }) => {
await page.clock.install();
const statusReads = [];
page.on('request', req => { if (req.url().includes('/images/thumbnails/status')) statusReads.push(req.url()); });
await page.goto('/prompt_manager/gallery');
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
await page.evaluate(type => window.dispatchEvent(new Event(type)), leave);
await page.clock.runFor(1500);
// A read made after the clock ran is listed, so the listener saw every status read.
await page.evaluate(() => fetch('/prompt_manager/images/thumbnails/status?probe=1'));
expect(statusReads.map(url => new URL(url).search)).toEqual(['?probe=1']);
});
}
// #379: the reviewed tags are that image's own tags; no prompt changes.
test('actual gallery review generates and persists tags for the selected root\'s image', async ({ page, request }) => {
await page.goto('/prompt_manager/gallery');
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
await page.locator('#autoTagBtn').click();
const generated = page.waitForResponse(response => response.url().endsWith('/prompt_manager/autotag/single'));
await page.locator('#startReviewBtn').click();
const generation = await generated;
expect(generation.request().postDataJSON().root_index).toBe(0);
await expect(page.locator('#reviewTagsContainer')).toContainText('sandstone');
const result = page.waitForResponse(response => response.url().endsWith('/prompt_manager/autotag/apply'));
await page.locator('#applyReviewBtn').click();
expect((await (await result).json()).success).toBe(true);
const data = await (await request.get('/prompt_manager/recent?limit=20')).json();
expect(data.results.find(prompt => prompt.text === 'Cat portrait').tags).toEqual(['cats']);
expect(data.results.find(prompt => prompt.text === 'Dog landscape').tags).toEqual(['dogs']);
const tagged = await (await request.get('/prompt_manager/images/output?mode=workspace&tags=sandstone')).json();
expect(tagged.images.map(image => `${image.root_index}:${image.path}`)).toEqual(['0:shared/same.png']);
});
test('actual Tags page reloads the selected filter and opens its image viewer', async ({ page }) => {
await page.goto('/prompt_manager/admin#/tags');
await page.locator('[data-tag-name="cats"]').click();
await expect(page.locator('#tagPromptsGrid')).toContainText('Cat portrait');
const dogs = page.waitForResponse(response => response.url().includes('/tags/dogs/prompts?'));
await page.locator('[data-tag-name="dogs"]').click();
const [shown] = (await (await dogs).json()).prompts[0].images;
await expect(page.locator('#tagPromptsGrid')).toContainText('Dog landscape');
await expect(page.locator('#tagPromptsGrid')).not.toContainText('Cat portrait');
await page.locator('#tagPromptsGrid img').first().click();
await expect(page.locator('.viewer-canvas img')).toBeVisible();
// The viewer's title names the shown image through the page's title callback. ViewerJS renders it only once the
// image is viewed, so closing at "visible" alone left the callback unrun on slower hosts (CI coverage missed it).
await expect(page.locator('.viewer-title')).toHaveText(shown.filename);
await page.locator('.viewer-container').getByRole('button', { name: 'Close', exact: true }).click();
await expect(page.locator('.viewer-container')).toHaveCount(0);
});
test('actual gallery serves colliding filenames and shows the matching prompt', async ({ page }) => {
await page.goto('/prompt_manager/gallery');
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
const images = page.locator('#galleryGrid img[data-original]');
const first = await images.nth(0).getAttribute('data-original');
const second = await images.nth(1).getAttribute('data-original');
expect(first).not.toBe(second);
await page.locator('#galleryGrid .image-item[data-image-index="0"]').click();
await expect(page.locator('#metadata-content')).toContainText('Cat portrait');
await page.keyboard.press('ArrowRight');
await expect(page.locator('#metadata-content')).toContainText('Dog landscape');
await page.keyboard.press('Escape');
await expect(page.locator('#metadata-sidebar')).toHaveCount(0);
});
test('an edit collision is rejected by the backend and the page restores the original text', async ({ page }) => {
await page.goto('/prompt_manager/admin');
const original = page.locator('.prompt-text').filter({ hasText: 'Cat portrait' });
const id = await original.getAttribute('data-id');
await page.locator(`[data-action="edit"][data-prompt-id="${id}"]`).click();
const editor = page.locator(`.prompt-text[data-id="${id}"]`);
await editor.fill('Dog landscape');
const rejected = page.waitForResponse(response => response.request().method() === 'PUT' && response.url().endsWith(`/prompts/${id}`));
await editor.press('Enter');
expect((await rejected).status()).toBe(409);
await expect(editor).toHaveText('Cat portrait');
await page.reload();
await expect(page.locator(`.prompt-text[data-id="${id}"]`)).toHaveText('Cat portrait');
});
test('a delayed real Tags response cannot replace a newer selection', async ({ page }) => {
let release;
const delayed = new Promise(resolve => { release = resolve; });
let received;
const waiting = new Promise(resolve => { received = resolve; });
await page.route('**/prompt_manager/tags/cats/prompts?*', async route => {
const response = await route.fetch();
received();
await delayed;
await route.fulfill({ response });
});
await page.goto('/prompt_manager/admin#/tags');
await page.locator('[data-tag-name="cats"]').click();
await waiting;
await page.locator('[data-tag-name="dogs"]').click();
await expect(page.locator('#tagPromptsGrid')).toContainText('Dog landscape');
const completed = page.waitForResponse(response => response.url().includes('/tags/cats/prompts?'));
release();
await completed;
await expect(page.locator('#tagPromptsGrid')).not.toContainText('Cat portrait');
});
test('gallery infinite scroll appends a real backend page while retaining existing cards', async ({ page, request }) => {
await expect(await request.post('/__test__/reset', { data: { extra_images: 108 } })).toBeOK();
await page.goto('/prompt_manager/gallery');
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(100);
await page.locator('#pageOptionsBtn').click();
await page.locator('#infiniteScrollToggle').check();
await page.locator('#saveSettingsBtn').click();
await expect(page.locator('#settingsModal')).toBeHidden();
const first = page.locator('#galleryGrid .image-item').first();
await first.evaluate(element => { element.dataset.preserved = 'yes'; });
await page.locator('#galleryScroll').evaluate(element => { element.scrollTop = element.scrollHeight; });
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(110);
await expect(first).toHaveAttribute('data-preserved', 'yes');
});
async function promptSnapshot(request) {
const response = await request.get('/prompt_manager/recent?limit=100');
await expect(response).toBeOK();
return (await response.json()).results.map(({ id, text, tags, images }) => ({
id, text, tags: [...tags].sort(),
images: images.map(image => image.image_path).sort(),
})).sort((a, b) => a.id - b.id);
}
function confirmNextDialog(page, accept, message) {
page.once('dialog', async dialog => {
expect(dialog.type()).toBe('confirm');
expect(dialog.message()).toContain(message);
await (accept ? dialog.accept() : dialog.dismiss());
});
}
async function deletePromptButton(page, text) {
const prompt = page.locator('.prompt-text').filter({ hasText: text });
await expect(prompt).toBeVisible();
const id = await prompt.getAttribute('data-id');
return page.locator(`[data-action="delete"][data-prompt-id="${id}"]`);
}
test('prompt deletion requires confirmation and can retry after a network failure', async ({ page, request }) => {
await page.goto('/prompt_manager/admin');
const before = await promptSnapshot(request);
const button = await deletePromptButton(page, 'Cat portrait');
let deletes = 0;
page.on('request', request => { if (request.method() === 'DELETE') deletes++; });
confirmNextDialog(page, false, 'delete this prompt');
await button.click();
expect(deletes).toBe(0);
expect(await promptSnapshot(request)).toEqual(before);
await page.route('**/prompt_manager/delete/*', route => route.abort('failed'), { times: 1 });
confirmNextDialog(page, true, 'delete this prompt');
await button.click();
await expect(page.getByText('Failed to delete prompt', { exact: true })).toBeVisible();
expect(await promptSnapshot(request)).toEqual(before);
confirmNextDialog(page, true, 'delete this prompt');
await button.click();
await expect(page.locator('.prompt-text')).toHaveCount(1);
await page.reload();
await expect(page.locator('.prompt-text')).toHaveCount(1);
expect(await promptSnapshot(request)).toEqual(before.filter(prompt => prompt.text !== 'Cat portrait'));
await page.goto('/prompt_manager/gallery');
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
for (const url of await page.locator('#galleryGrid img[data-original]').evaluateAll(images => images.map(image => image.dataset.original))) {
await expect(await request.get(url)).toBeOK();
}
});
// #320: with previews in one folder, the legacy gallery still shows them, made
// and served from that folder (the fixture's own previews inside the sources
// are never served then).
test('the legacy gallery shows thumbnails kept in one folder', async ({ page, request }) => {
await expect(await request.post('/__test__/thumbnail-location', { data: { mode: 'folder' } })).toBeOK();
const served = page.waitForResponse(response =>
response.url().includes('/prompt_manager/images/serve/thumbnails/') && response.status() === 200);
await page.goto('/prompt_manager/gallery');
await expect(page.locator('#galleryGrid .image-item')).toHaveCount(2);
const response = await served; // made in the folder before it was served
const name = decodeURIComponent(new URL(response.url()).pathname.split('/serve/thumbnails/')[1]);
const files = await (await request.get('/__test__/thumbnail-files')).json();
const stem = name.replace(/\.[^.]+$/, '');
expect(files.folder.some(file => /^[a-z0-9_-]+-[0-9a-f]{8}\//.test(file)
&& file.slice(file.indexOf('/') + 1).replace(/\.[^.]+$/, '') === stem)).toBe(true);
});
@@ -0,0 +1,202 @@
// #668 (D207): `workspace#/library?tag=…&tag_mode=…` is the Prompt library with those Tags and that Tag match, against
// the real server. The filter stays in the address (Reload, Back and Forward keep it) and the address follows the
// shelf's tag filter. Old tag bookmarks are sent to this form (old-urls.spec.mjs).
import {startCoverage,saveCoverage} from '../../tools/vendor/browser-coverage.mjs';
import {test,expect} from './fixtures.mjs';
const workspace='/prompt_manager/workspace';
const cards=page=>page.locator('article[data-prompt-id]');
const card=(page,text)=>cards(page).filter({has:page.getByText(text,{exact:true})});
const toolbar=page=>page.locator('#workspace-main search.toolbar');
const filtersButton=page=>toolbar(page).getByRole('button',{name:/^Filters(?: · \d)?$/});
const refine=page=>page.getByRole('dialog',{name:'Refine this view',exact:true});
const caption=page=>page.locator('#workspace-main .section-caption > span').first();
const toast=page=>page.locator('#workspace-toast');
/** The workspace at exactly this hash. */
const at=hash=>url=>url.pathname.endsWith('/prompt_manager/workspace')&&url.search===''&&url.hash===hash;
const heading=page=>page.locator('#workspace-main h1').first();
const tagsField=page=>refine(page).getByRole('textbox',{name:'Tags',exact:true});
const matchField=page=>refine(page).getByRole('combobox',{name:'Tag match',exact:true});
const apply=page=>refine(page).getByRole('button',{name:'Apply filters',exact:true});
const sidebarLibrary=page=>page.locator('aside.sidebar nav [data-route="library"]');
test.beforeEach(async({page,request,browserName})=>{
await startCoverage(page,browserName);await expect(await request.post('/__test__/reset',{data:{native_library:true}})).toBeOK();
page.libraryErrors=[];page.on('pageerror',error=>page.libraryErrors.push(error.message));
});
test.afterEach(async({page,browserName})=>{await saveCoverage(page,browserName);expect(page.libraryErrors).toEqual([]);});
async function openRefine(page) {
const folders=page.waitForResponse(item=>new URL(item.url()).pathname==='/prompt_manager/library/options'&&new URL(item.url()).searchParams.get('include')==='folders');
await filtersButton(page).click();await expect(refine(page)).toBeVisible();await folders;
}
async function expectCats(page) {
await expect(caption(page)).toHaveText(/^1 positive prompt · /);
await expect(cards(page)).toHaveCount(1);await expect(card(page,'Cat portrait')).toHaveCount(1);
await expect(filtersButton(page)).toHaveText('Filters · 1');
}
test('a Library link opens the shelf filtered by its tags, keeps them in the address and shows them in Refine',async({page})=>{
await page.goto(`${workspace}#/library?tag=cats`);
await expectCats(page);
await expect(page).toHaveURL(at('#/library?tag=cats'));
await expect(heading(page)).toHaveText('Prompt library');
// As for any route, the title takes focus on a navigation inside the workspace, never on the first render.
await expect(heading(page)).not.toBeFocused();
await openRefine(page);
await expect(tagsField(page)).toHaveValue('cats');await expect(matchField(page)).toHaveValue('all');
});
test('Reload keeps the filter of a Library link',async({page})=>{
await page.goto(`${workspace}#/library?tag=cats&tag=dogs&tag_mode=any`);
await expect(caption(page)).toHaveText(/^2 positive prompts · /);
await page.reload();
await expect(page).toHaveURL(at('#/library?tag=cats&tag=dogs&tag_mode=any'));
await expect(caption(page)).toHaveText(/^2 positive prompts · /);
await expect(card(page,'Cat portrait')).toHaveCount(1);await expect(card(page,'Dog landscape')).toHaveCount(1);
await expect(filtersButton(page)).toHaveText('Filters · 2');
});
test('a Library link with two tags matches all of them unless it asks for any, and its address is made canonical',async({page})=>{
await page.goto(`${workspace}#/library?tag=cats&tag=dogs`);
await expect(caption(page)).toHaveText(/^0 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters · 1');
await page.goto('about:blank');
await page.goto(`${workspace}#/library?tag_mode=any&sort=name&tag=cats&tag=dogs&tag=cats`);
await expect(caption(page)).toHaveText(/^2 positive prompts · /);
await expect(filtersButton(page)).toHaveText('Filters · 2');
await expect(page).toHaveURL(at('#/library?tag=cats&tag=dogs&tag_mode=any'));
});
test('opening a prompt and going Back returns to the filtered address and filter, and Forward to the prompt',async({page})=>{
await page.goto(`${workspace}#/library?tag=cats`);
await expectCats(page);
await card(page,'Cat portrait').locator('[data-history]').first().click();
await expect(page).toHaveURL(/\/prompt_manager\/workspace#\/library\/\d+$/);
const promptUrl=page.url();
await page.goBack();
await expect(page).toHaveURL(at('#/library?tag=cats'));await expectCats(page);
await page.goForward();
await expect(page).toHaveURL(promptUrl);
await expect(page.locator('#workspace-main article[data-prompt-id]')).toHaveCount(0);
await page.goBack();
await expect(page).toHaveURL(at('#/library?tag=cats'));await expectCats(page);
// The prompt page's own way back keeps the filter too.
await card(page,'Cat portrait').locator('[data-history]').first().click();
await expect(page).toHaveURL(promptUrl);
await page.locator('#workspace-main').getByRole('button',{name:'← Prompt library',exact:true}).click();
await expect(page).toHaveURL(at('#/library?tag=cats'));await expectCats(page);
});
test('changing the tag filter in Refine updates the address without adding history entries, and clearing it returns to the plain address',async({page})=>{
await page.goto(`${workspace}#/overview`);
await expect(heading(page)).toHaveText('Overview');
await sidebarLibrary(page).click();
await expect(caption(page)).toHaveText(/^3 positive prompts · /);await expect(page).toHaveURL(at('#/library'));
const entries=await page.evaluate(()=>window.history.length);
await openRefine(page);await tagsField(page).fill('cats');await apply(page).click();
await expectCats(page);await expect(page).toHaveURL(at('#/library?tag=cats'));
await openRefine(page);await tagsField(page).fill('dogs, cats');await matchField(page).selectOption('any');await apply(page).click();
await expect(caption(page)).toHaveText(/^2 positive prompts · /);
await expect(page).toHaveURL(at('#/library?tag=dogs&tag=cats&tag_mode=any'));
await openRefine(page);await matchField(page).selectOption('untagged');await apply(page).click();
await expect(page).toHaveURL(at('#/library?tag_mode=untagged'));await expect(filtersButton(page)).toHaveText('Filters · 1');
// Search, category and sort are not in the address.
await page.locator('#workspace-main search.toolbar').getByRole('searchbox').fill('zzz');
await expect(caption(page)).toHaveText(/^0 positive prompts · /);
await expect(page).toHaveURL(at('#/library?tag_mode=untagged'));
await page.locator('#workspace-main search.toolbar').getByRole('searchbox').fill('');
await openRefine(page);await refine(page).getByRole('button',{name:'Clear filters',exact:true}).click();
await expect(caption(page)).toHaveText(/^3 positive prompts · /);await expect(page).toHaveURL(at('#/library'));
expect(await page.evaluate(()=>window.history.length)).toBe(entries);
// One step back leaves the Library: no filter change made an entry.
await page.goBack();
await expect(page).toHaveURL(at('#/overview'));
});
test('the sidebar Library link shows the whole Library after a link filter and after a filter set in Refine',async({page})=>{
await page.goto(`${workspace}#/library?tag=cats`);
await expectCats(page);
await sidebarLibrary(page).click();
await expect(page).toHaveURL(at('#/library'));
await expect(caption(page)).toHaveText(/^3 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters');
await openRefine(page);await tagsField(page).fill('dogs');await apply(page).click();
await expect(page).toHaveURL(at('#/library?tag=dogs'));await expect(caption(page)).toHaveText(/^1 positive prompt · /);
await sidebarLibrary(page).click();
await expect(page).toHaveURL(at('#/library'));
await expect(caption(page)).toHaveText(/^3 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters');
// Leaving for another page and coming back by the sidebar is the whole Library too.
await page.evaluate(()=>{window.location.hash='#/library?tag=cats';});
await expectCats(page);await expect(heading(page)).toBeFocused();
await page.locator('aside.sidebar nav [data-route="tags"]').click();
await expect(heading(page)).toHaveText('Tags & categories');
await sidebarLibrary(page).click();
await expect(page).toHaveURL(at('#/library'));await expect(caption(page)).toHaveText(/^3 positive prompts · /);
});
test('a Library link replaces the filter of a shelf that is already open',async({page})=>{
await page.goto(`${workspace}#/library?tag=cats`);
await expectCats(page);
await page.evaluate(()=>{window.location.hash='#/library?tag=dogs';});
await expect(card(page,'Dog landscape')).toHaveCount(1);await expect(cards(page)).toHaveCount(1);
await expect(filtersButton(page)).toHaveText('Filters · 1');await expect(page).toHaveURL(at('#/library?tag=dogs'));
// Back is the earlier link's filter.
await page.goBack();
await expect(page).toHaveURL(at('#/library?tag=cats'));await expectCats(page);
});
test('Browse on Tags & categories lands on the filtered address',async({page})=>{
await page.goto(`${workspace}#/tags`);
await expect(heading(page)).toHaveText('Tags & categories');
const row=page.locator('#workspace-main tbody tr').filter({has:page.locator('td:first-child').getByText('cats',{exact:true})});
await row.getByRole('button',{name:'Browse',exact:true}).click();
await expect(page).toHaveURL(at('#/library?tag=cats'));await expectCats(page);
await page.reload();
await expect(page).toHaveURL(at('#/library?tag=cats'));await expectCats(page);
});
test('a saved view with a tag filter keeps its own address, and the Library link after it is the whole Library',async({page})=>{
await page.goto(`${workspace}#/library?tag=cats&tag=dogs&tag_mode=any`);
await expect(caption(page)).toHaveText(/^2 positive prompts · /);
await page.locator('#workspace-main search.toolbar').getByRole('button',{name:'Save view',exact:true}).click();
const save=page.getByRole('dialog',{name:'Save this view',exact:true});
await save.getByRole('textbox',{name:'View name',exact:true}).fill('Cats or dogs');
await save.getByRole('button',{name:'Save',exact:true}).click();
const link=page.getByRole('navigation',{name:'Saved views',exact:true}).getByRole('link',{name:'Cats or dogs',exact:true});
await expect(link).toBeVisible();
await sidebarLibrary(page).click();
await expect(page).toHaveURL(at('#/library'));await expect(caption(page)).toHaveText(/^3 positive prompts · /);
await link.click();
await expect(page).toHaveURL(/\/prompt_manager\/workspace#\/saved\/\d+$/);
await expect(caption(page)).toHaveText(/^2 positive prompts · /);await expect(filtersButton(page)).toHaveText('Filters · 2');
const savedUrl=page.url();
// A filter change inside the saved view never rewrites its address.
await openRefine(page);await tagsField(page).fill('cats');await apply(page).click();
await expect(caption(page)).toHaveText(/^1 positive prompt · /);
await expect(page).toHaveURL(savedUrl);
await sidebarLibrary(page).click();
await expect(page).toHaveURL(at('#/library'));await expect(caption(page)).toHaveText(/^3 positive prompts · /);
});
test('a Library link for untagged prompts asks the server for them',async({page})=>{
const listed=page.waitForResponse(item=>{const url=new URL(item.url());return url.pathname==='/prompt_manager/library'&&url.searchParams.get('tag_mode')==='untagged';});
await page.goto(`${workspace}#/library?tag_mode=untagged`);
const body=await (await listed).json();
expect(body.tag_mode).toBe('untagged');
await expect(cards(page)).toHaveCount(body.items.length);
await expect(filtersButton(page)).toHaveText('Filters · 1');await expect(page).toHaveURL(at('#/library?tag_mode=untagged'));
});
test('a Library link that cannot be read opens the whole shelf at the plain address and says so',async({page})=>{
await page.goto(`${workspace}#/library?tag=cats&tag_mode=either`);
await expect(caption(page)).toHaveText(/^3 positive prompts · /);
await expect(filtersButton(page)).toHaveText('Filters');
await expect(toast(page)).toHaveText("This link's tag filter couldn't be read. Showing the whole prompt library.");
await expect(page).toHaveURL(at('#/library'));
});
test('a Library link with an unknown tag shows the empty shelf, not the whole library',async({page})=>{
await page.goto(`${workspace}#/library?tag=no-such-tag`);
await expect(caption(page)).toHaveText(/^0 positive prompts · /);
await expect(page.locator('#workspace-main').getByText('No matching prompts. Try changing the filters.',{exact:true})).toBeVisible();
await expect(filtersButton(page)).toHaveText('Filters · 1');await expect(page).toHaveURL(at('#/library?tag=no-such-tag'));
});
@@ -1,15 +1,13 @@
// The one-time older-images notice in the workspace shell (#527, D166). Its dismissal is the legacy admin page's key,
// so dismissing it in any place dismisses it everywhere.
// The one-time older-images notice in the workspace shell (#527, D166). Its dismissal is the key the old admin page
// used (`pm_update_notice_dismissed`), so a browser that dismissed it there before #668 stays dismissed.
import { test, expect } from './fixtures.mjs';
const WORKSPACE = '/prompt_manager/workspace';
const ADMIN = '/prompt_manager/admin';
const NOTICE_KEY = 'pm_update_notice_dismissed';
const shellNotice = page => page.locator('#older-images-notice > .notice');
const sourcesNotice = page => page.locator('#workspace-main .settings-layout > .notice');
const dialog = page => page.locator('dialog#modal[open]');
const adminModal = page => page.locator('#updateNoticeModal');
const stored = page => page.evaluate(key => localStorage.getItem(key), NOTICE_KEY);
async function openRoute(page, route) {
@@ -105,49 +103,11 @@ test.describe('with the notice not dismissed', () => {
await expect(shellNotice(page)).toHaveCount(0);
await other.close();
});
});
test('the admin modal still works: Later without the checkbox keeps the notice everywhere', async ({ page }) => {
await page.goto(ADMIN);
await expect(adminModal(page)).toBeVisible();
await page.locator('#updateNoticeDismiss').click();
await expect(adminModal(page)).toBeHidden();
expect(await stored(page)).toBeNull();
await openRoute(page, 'library');
await expect(shellNotice(page)).toHaveCount(1);
});
test('dismissing on the admin page dismisses it in the workspace', async ({ page }) => {
await page.goto(ADMIN);
await page.locator('#dismissUpdateNotice').check();
await page.locator('#updateNoticeDismiss').click();
await expect(adminModal(page)).toBeHidden();
await openRoute(page, 'library');
test('specs start with the notice dismissed, on every page', async ({ page }) => {
for (const route of ['library', 'images', 'system/sources']) {
await openRoute(page, route);
await expect(shellNotice(page)).toHaveCount(0);
});
test('dismissing in the workspace dismisses it on the admin page', async ({ page }) => {
await openRoute(page, 'library');
await shellNotice(page).getByRole('button', { name: 'Later', exact: true }).click();
await page.goto(ADMIN);
await page.waitForLoadState('load');
await expect(adminModal(page)).toBeHidden();
});
test('the admin Scan still dismisses it and opens the scan modal', async ({ page }) => {
await page.goto(ADMIN);
await page.locator('#updateNoticeScan').click();
await expect(adminModal(page)).toBeHidden();
expect(await stored(page)).toBe('3.2.0');
});
});
test('specs start with the notice dismissed, on every page', async ({ page, browser, baseURL }) => {
await openRoute(page, 'library');
await expect(shellNotice(page)).toHaveCount(0);
const context = await browser.newContext({ baseURL });
const other = await context.newPage();
await other.goto(ADMIN);
await other.waitForLoadState('load');
await expect(adminModal(other)).toBeHidden();
await context.close();
}
});
@@ -432,15 +432,12 @@ test('a failed settings read leaves the policy disabled with the reason', async
await expect(row.locator('input')).toBeDisabled();
});
test('the legacy Backup and Restore routes keep working and the admin page links to System', async ({ page, request }) => {
test('the legacy Backup and Restore routes keep working', async ({ request }) => {
const bytes = await backupBytes(request);
const restored = await request.post('/prompt_manager/restore', { multipart: { database_file: {
name: 'prompts_backup.db', mimeType: 'application/octet-stream', buffer: bytes } } });
await expect(restored).toBeOK();
expect((await restored.json()).success).toBe(true);
// #330: the admin page's Backup DB and Restore DB open System › Backup & export.
await page.goto('/prompt_manager/admin');
for (const id of ['#backupBtn', '#restoreBtn']) await expect(page.locator(id)).toHaveAttribute('href', 'workspace#/system/backups');
});
/** Start a fake running job (a metadata scan another tab started), which an exclusive restore must wait for. */
@@ -343,6 +343,7 @@ test('Review import shows replacement, blocked items and network effects with th
['LoraManager', 'environment settings · alongside storage · library default'],
['Scope', 'Replace 2 imported prompts with 3 LoRAs'],
['Found', '3 metadata files · 3 LoRAs · 0 with local images'],
['Trigger words', '3 become tags'],
['Protected', 'Nothing is protected'],
['Network', 'Downloads up to 3 example images from CivitAI'],
['Backup', 'Create and verify before changes (browser.db.backup_<date and time>)'],
@@ -387,7 +388,8 @@ test('saved pairs block the import: the review explains it and offers only Close
await enable(page);
await layoutOf(page).getByRole('button', { name: 'Review import', exact: true }).click();
// gridOf reads once; poll until the review has rendered its rows.
await expect.poll(async () => (await gridOf(page))[3]).toEqual(['Protected', '1 imported prompt used by saved pairs']);
await expect.poll(async () => (await gridOf(page)).find(([term]) => term === 'Protected'))
.toEqual(['Protected', '1 imported prompt used by saved pairs']);
await expect(dialog(page).locator('p.small')).toHaveText(
'Delete or change the saved pairs that use these prompts, then review the import again. Nothing was changed.');
expect(await dialog(page).locator('.dialog-actions button').allTextContents()).toEqual(['Close']);
@@ -395,6 +397,18 @@ test('saved pairs block the import: the review explains it and offers only Close
await expect(dialog(page)).toHaveCount(0);
});
test('the import review counts the trained words that are lists or sentences and not made tags (#618)',
async ({ page, request }) => {
await lora(request, { loras: 2, junk: true });
await openIntegrations(page);
await enable(page);
await layoutOf(page).getByRole('button', { name: 'Review import', exact: true }).click();
await expect.poll(async () => (await gridOf(page)).find(([term]) => term === 'Trigger words'))
.toEqual(['Trigger words', '2 become tags · 4 not made tags (lists or sentences)']);
await dialog(page).getByRole('button', { name: 'Cancel', exact: true }).click();
await expect(dialog(page)).toHaveCount(0);
});
test('unusable LoraManager settings: the review says why and offers only Close (#355)', async ({ page, request }) => {
await lora(request, { previous: 1, settings: 'invalid' });
await openIntegrations(page);
@@ -65,8 +65,8 @@ test('the section shows the concept rows; Metadata cache follows Q5 (D102)', asy
]))).toEqual([
['Database', [['Integrity & relationship checks', 'Check', ''], ['Duplicate prompt text', 'Review plan', ''],
['Optimize database', 'Review plan', ''], ['Unused prompt components', 'Review plan', 'danger'],
// D192 (#550): beyond the concept.
['Pair category and tags', 'Review plan', '']]],
// D192 (#550) and D210 (#618): beyond the concept.
['Pair category and tags', 'Review plan', ''], ['Tag cleanup', 'Find tags', 'danger']]],
['Images & cache', [['Missing-file links', 'Review plan', 'danger'], ['Duplicate image files', 'Find duplicates', ''],
['Thumbnail cache', 'Review options', ''], ['Metadata cache', 'Review plan', '']]],
]);
@@ -482,6 +482,104 @@ test('Find duplicates starts a job; its view links Review groups; Keep radios bu
expect((await request.get('/prompt_manager/images/serve/s7-dupes/copy.png?root=0')).status()).toBe(404);
});
test('D210: Tag cleanup finds comma and unused tags, reviews only the ticked rule and deletes only it (#618)',
async ({ page, request }) => {
await expect(await request.post('/__test__/system/tag-cleanup')).toBeOK();
const previews = [];
page.on('request', item => { if (item.url().endsWith(PREVIEW_URL)) previews.push(item.postDataJSON()); });
const before = (await serverJson(request, '/__test__/system/backups')).safety.length;
await openMaintenance(page);
const tagRow = row(page, 'Tag cleanup');
await expect(tagRow.locator('p')).toHaveText('Find tags that are whole comma lists or are used nowhere. Review them, '
+ 'then remove only what you tick.');
await tagRow.getByRole('button', { name: 'Find tags', exact: true }).click();
await expect(page).toHaveURL(/#\/activity\/[0-9a-f]{32}$/);
const findId = page.url().split('/').pop();
const main = page.locator('#workspace-main');
await expect(main.locator('h1')).toHaveText('Find tags to clean up');
const reviewTags = main.getByRole('button', { name: 'Review tags', exact: true });
await expect(reviewTags).toBeVisible();
await expect(main.locator('.stat-row .stat dt')).toHaveText(['Found']);
await expect(main.locator('.stat-row .stat dd')).toHaveText(['4']);
// The found rows are tags (records): plain text, never an open action; no lora: tag is a comma finding.
const results = main.getByRole('region', { name: 'Results', exact: true });
await expect(results.locator('.outcome-files > .file-row')).toHaveText(['s618 a, b · Tags containing a comma',
's618 x,y · Tags containing a comma', 's618-ghost · Tags with no links', 's618-spirit · Tags with no links']);
await expect(results.locator('.outcome-files button')).toHaveCount(0);
await reviewTags.click();
const review = dialog(page);
await expect(review.locator('#modal-title')).toHaveText('Review tag cleanup');
const status = review.locator('#modal-body > p[role="status"]');
await expect(status).toHaveText('0 tags selected');
const start = review.getByRole('button', { name: 'Review cleanup', exact: true });
await expect(start).toBeDisabled();
const comma = review.locator('.tag-cleanup-rule[data-rule="comma"]');
const unused = review.locator('.tag-cleanup-rule[data-rule="unused"]');
await expect(comma.locator(':scope > label')).toHaveText('Tags containing a comma (2)');
await expect(unused.locator(':scope > label')).toHaveText('Tags with no links (2)');
await expect(comma.locator(':scope > p.small')).toHaveText('A whole list saved as one tag, usually from a LoRA\'s '
+ 'trained words. Removes the tag from its prompts, pairs and images and deletes it.');
await expect(review.locator('#modal-body > p.small').last()).toHaveText(/^Nothing is deleted until you review and apply/);
// Nothing is ticked; the tag rows are built when Show tags first opens.
await expect(comma.locator('details input')).toHaveCount(0);
await comma.locator(':scope > label input').check();
await expect(status).toHaveText('2 tags selected');
await expect(start).toBeEnabled();
await comma.locator('details > summary').click();
const tags = comma.locator('details label');
await expect(tags).toHaveText(['s618 a, b · 1 prompt', 's618 x,y · no links']);
await expect(tags.locator('input')).toHaveCount(2);
for (const box of await tags.locator('input').all()) await expect(box).toBeChecked();
await tags.nth(1).locator('input').uncheck();
await expect(status).toHaveText('1 tag selected');
expect(await comma.locator(':scope > label input').evaluate(box => [box.checked, box.indeterminate])).toEqual([false, true]);
await tags.nth(1).locator('input').check();
await expect(status).toHaveText('2 tags selected');
await start.click();
await expect(dialog(page).locator('#modal-title')).toHaveText('Review maintenance plan');
await expect(dialog(page).locator('#modal-body > h3')).toHaveText('Tag cleanup');
expect(previews).toHaveLength(1);
expect(previews[0].operation).toBe('tag_cleanup');
expect(previews[0].options.job_id).toBe(findId);
expect(previews[0].options.select.map(entry => [entry.rule, entry.tag_ids.length])).toEqual([['comma', 2]]);
const grid = await gridOf(page);
expect(grid.slice(0, 2)).toEqual([['Scope', 'Delete 2 tags (removed from 1 prompt, 0 pairs and 0 images)'],
['Protected', 'Nothing is protected']]);
expect(grid[2][1]).toMatch(/^Always created and verified first \(.+\.backup_<date and time>\)$/);
expect(grid[3]).toEqual(['Media on disk', 'No files are removed']);
await dialog(page).getByRole('button', { name: 'Apply reviewed operation', exact: true }).click();
await expect(page).not.toHaveURL(new RegExp(findId));
await expect(page).toHaveURL(/#\/activity\/[0-9a-f]{32}$/);
const job = await ended(request, page.url().split('/').pop());
expect([job.kind, job.title, job.state, job.counters.changed, job.counters.protected])
.toEqual(['maintenance', 'Tag cleanup', 'finished', 2, 0]);
await expect(main.locator('h1')).toHaveText('Tag cleanup');
await results.locator('.outcome-list > button').filter({ hasText: 'Changed' }).click();
await expect(results.locator('.outcome-files > .file-row')).toHaveText([
'Deleted tag “s618 a, b” (Tags containing a comma) · removed from 1 prompt',
'Deleted tag “s618 x,y” (Tags containing a comma)']);
// The safety backup is always taken.
expect((await serverJson(request, '/__test__/system/backups')).safety.length).toBe(before + 1);
// Tags & categories: the other rule's tags and the lora: tag are still there.
const names = (await serverJson(request, '/prompt_manager/vocabulary/tags?limit=200')).tags.map(tag => tag.name);
expect(names).toEqual(expect.arrayContaining(['s618-ghost', 's618-spirit', 's618-clean', 'lora:S618, v2']));
expect(names).not.toContain('s618 a, b');
expect(names).not.toContain('s618 x,y');
// A second search finds only the rest.
await openMaintenance(page);
await row(page, 'Tag cleanup').getByRole('button', { name: 'Find tags', exact: true }).click();
await expect(page).not.toHaveURL(new RegExp(job.id));
await expect(page).toHaveURL(/#\/activity\/[0-9a-f]{32}$/);
const again = await ended(request, page.url().split('/').pop());
expect(again.counters.found).toBe(2);
const body = await serverJson(request, `/prompt_manager/maintenance/tag_cleanup/${again.id}`);
expect(body.rules.map(rule => [rule.id, rule.findings.map(finding => finding.name)]))
.toEqual([['comma', []], ['unused', ['s618-ghost', 's618-spirit']]]);
});
test('the duplicates review pages ten groups at a time and keeps each choice (D101)', async ({ page, request }) => {
await expect(await request.post('/__test__/system/duplicate-files', { data: { groups: 11 } })).toBeOK();
const groupReads = [];
@@ -99,7 +99,7 @@ test('a rename while searching re-reads the same search and sort',async({page})=
test('Untagged prompts Browse opens the Library on exactly the prompts without tags',async({page})=>{
await open(page);
await untagged(page).getByRole('button',{name:'Browse',exact:true}).click();
await expect(page).toHaveURL(/#\/library$/);
await expect(page).toHaveURL(url=>url.hash==='#/library?tag_mode=untagged');
await expect(main(page).getByRole('heading',{level:1})).toBeFocused();
await expect(shelf(page)).toHaveCount(2);
await expect(page.locator('#workspace-main .section-caption > span').first()).toHaveText(/^2 positive prompts · /);
+3 -1
View File
@@ -23,7 +23,9 @@ async function seed(request,data={}) {
const response=await request.post('/__test__/vocabulary/reset',{data});await expect(response).toBeOK();return response.json();
}
async function expectLibrary(page,{tags='',category='',count}) {
await expect(page).toHaveURL(/#\/library$/);
// #668 (D207): a tag Browse lands on the filtered address; a category is not in the address.
const hash=tags?`#/library?${new URLSearchParams({tag:tags})}`:'#/library';
await expect(page).toHaveURL(url=>url.hash===hash);
await expect(main(page).getByRole('heading',{level:1})).toHaveText('Prompt library');
await expect(main(page).getByRole('heading',{level:1})).toBeFocused();
await expect(page.getByRole('searchbox',{name:'Search workspace',exact:true})).toHaveValue('');
+3 -3
View File
@@ -118,9 +118,9 @@ test('all shell destinations deep-link, reload and expose working existing appli
await expect(page.locator('#workspace-main').getByRole('link', { name: 'Open Images', exact: true })).toBeVisible();
await expect(page.locator('a[href*="/prompt_manager/admin"], a[href*="/prompt_manager/gallery"]')).toHaveCount(0);
await expect(page.locator('#workspace-main').getByText('Your existing tools remain available')).toHaveCount(0);
// The legacy pages themselves stay at their URLs.
for (const legacy of ['/prompt_manager/admin', '/prompt_manager/gallery', '/prompt_manager/gallery.html']) {
await expect(await request.get(legacy)).toBeOK();
// The old pages' URLs stay and lead into the workspace (#668; old-urls.spec.mjs follows each one).
for (const old of ['/prompt_manager/admin', '/prompt_manager/gallery', '/prompt_manager/gallery.html']) {
await expect(await request.get(old)).toBeOK();
}
});
@@ -8,7 +8,7 @@ reaches a real LoraManager, ComfyUI install or the network:
the image cache, forgets every LoRA import and injected failure, and opens
the download gate;
- ``POST /__test__/integrations/lora-manager``
``{loras, civitai, preview, previous, settings}`` writes
``{loras, civitai, preview, previous, settings, junk}`` writes
``custom_nodes/ComfyUI-Lora-Manager`` (detected through the
``folder_paths`` stub's base path) and ``loras`` LoRAs under
``models/loras``: each a ``<stem>.safetensors`` model beside its
@@ -18,7 +18,9 @@ reaches a real LoraManager, ComfyUI install or the network:
downloads it only for a LoRA without a local preview); ``previous`` saves
that many earlier ``lora-manager`` imports with tags and image links;
``settings: "invalid"`` makes LoraManager's settings file unreadable JSON
(the server's own isolated settings folder, ``LORA_MANAGER_SETTINGS_DIR``);
(the server's own isolated settings folder, ``LORA_MANAGER_SETTINGS_DIR``); ``junk``
adds a comma list and a ``<lora:…>`` call to each LoRA's trained words, which
the import does not make tags (#618);
- ``POST /__test__/integrations/gate`` ``{hold}`` holds every CivitAI
download until it is released (``{"hold": false}``), so a test sees the job
while it downloads;
@@ -145,6 +147,9 @@ def register_integrations_commands(app, routes, api, root: Path):
for number in range(count):
stem = f"style_{number + 1:02}"
civitai = {"trainedWords": [f"trigger{number + 1}"]}
if data.get("junk") is True:
# #618: a comma list and a model call, never made tags.
civitai["trainedWords"] += ["score_9, score_8_up,", "<lora:x:0.8>"]
if data.get("civitai") is True:
civitai["images"] = [
{
+22
View File
@@ -52,6 +52,10 @@ read. These per-server hooks only change what a System test needs on top:
``{"groups": n}`` adds ``n`` more groups of two copies each, and
``{"trio": false}`` leaves the three ``same.png``/``copy.png`` copies out,
and ``{"long": true}`` adds a group under long names with no spaces;
- ``POST /__test__/system/tag-cleanup`` (#618) saves ``S618 owner`` tagged
``s618 a, b`` (a comma list), ``s618-clean`` and ``lora:S618, v2`` (a LoRA's
identity tag, never a comma finding), and adds the unused tags
``s618 x,y`` (a fullwidth comma), ``s618-ghost`` and ``s618-spirit``;
- ``GET /__test__/system/digest`` (S7) answers the sha256 of the database's
rows (a read-only dump) and of every media file under ``output`` and
``input`` (not the automatic previews in ``thumbnails``), so a test proves
@@ -349,6 +353,24 @@ def register_system_commands(app, routes, api, root: Path):
conn.commit()
return web.json_response({"success": True})
@routes.post("/__test__/system/tag-cleanup")
async def tag_cleanup(request):
def seed():
text = "S618 owner"
api.db.save_prompt(
text,
prompt_hash=hashlib.sha256(text.lower().encode()).hexdigest(),
tags=["s618 a, b", "s618-clean", "lora:S618, v2"],
)
with api.db.model.get_connection() as conn:
conn.executemany(
"INSERT INTO tags(name) VALUES(?)",
[("s618 x\uff0cy",), ("s618-ghost",), ("s618-spirit",)],
)
await api._run_in_executor(seed)
return web.json_response({"success": True})
@routes.post("/__test__/system/pair-metadata")
async def pair_metadata(request):
def seed():
+4 -2
View File
@@ -210,7 +210,7 @@ test(`${label} follows actual ComfyUI light and dark palettes`, async ({ page },
}
});
test(`${label} Web UI button opens the workspace; legacy pages still load`, async ({ page }) => {
test(`${label} Web UI button opens the workspace; the old gallery URL leads to Images`, async ({ page }) => {
await addEditor(page, type);
const popupPromise = page.waitForEvent('popup');
await page.locator('.pm-focused').getByRole('button', { name: 'Web UI ↗', exact: true }).click();
@@ -219,8 +219,10 @@ test(`${label} Web UI button opens the workspace; legacy pages still load`, asyn
await expect(popup).toHaveURL(/\/prompt_manager\/workspace#\/library$/);
await expect(popup.locator('#workspace-main h1')).toHaveText('Prompt library');
await expect(page.locator('.pm-focused').getByRole('status').filter({ hasText: 'Web UI opened.' })).toHaveText('Web UI opened.');
// #668: the old gallery URL leads to the workspace's Images page.
await popup.goto(new URL('/prompt_manager/gallery', page.url()).href);
await expect(popup.locator('#addPromptBtn')).toBeVisible();
await expect(popup).toHaveURL(/\/prompt_manager\/workspace#\/images$/);
await expect(popup.locator('#workspace-main h1')).toHaveText('Images');
await popup.close();
});
+4 -2
View File
@@ -84,7 +84,7 @@ test('all node schemas and extension entrypoints load from the real host', async
});
for (const type of ['PromptManager', 'PromptManagerText']) {
test(`${type} Web UI button opens the workspace; legacy pages still load`, async ({ page }) => {
test(`${type} Web UI button opens the workspace; the old gallery URL leads to Images`, async ({ page }) => {
await page.evaluate(async type => {
const { app } = await import('/scripts/app.js');
const node = LiteGraph.createNode(type);
@@ -97,8 +97,10 @@ for (const type of ['PromptManager', 'PromptManagerText']) {
await popup.waitForLoadState('domcontentloaded');
await expect(popup).toHaveURL(/\/prompt_manager\/workspace#\/library$/);
await expect(popup.locator('#workspace-main h1')).toHaveText('Prompt library');
// #668: the old gallery URL leads to the workspace's Images page.
await popup.goto(new URL('/prompt_manager/gallery', page.url()).href);
await expect(popup.locator('#addPromptBtn')).toBeVisible();
await expect(popup).toHaveURL(/\/prompt_manager\/workspace#\/images$/);
await expect(popup.locator('#workspace-main h1')).toHaveText('Images');
await popup.close();
});
}
+4 -2
View File
@@ -37,12 +37,14 @@ test('workspace serves real library data beside either ComfyUI renderer', async
await expect(workspace.getByText('No matching images · 0 images', { exact: true })).toBeVisible();
await expect(workspace.locator('.gallery-body > .empty')).toHaveText('No matching images. Try another search or category.');
}
// D29: Images no longer links the legacy gallery; #525: nor does Overview. The page stays at its URL.
// D29: Images no longer links the old gallery; #525: nor does Overview. #668: its URL leads to the workspace.
await expect(workspace.locator('#workspace-main a[href="/prompt_manager/gallery"]')).toHaveCount(0);
await workspace.evaluate(() => { location.hash = '/overview'; });
const imagesCard = workspace.locator('#workspace-main').getByRole('link', { name: 'Open Images', exact: true });
await expect(imagesCard).toHaveAttribute('href', '#/images');
expect((await workspace.request.get('/prompt_manager/gallery')).ok()).toBe(true);
const oldGallery = await workspace.request.get('/prompt_manager/gallery');
expect(oldGallery.ok()).toBe(true);
expect(new URL(oldGallery.url()).pathname).toMatch(/\/prompt_manager\/workspace$/);
await workspace.evaluate(() => { location.hash = '/images'; });
await workspace.reload();
await expect(workspace.locator('#workspace-main h1')).toHaveText('Images');
+16
View File
@@ -13,6 +13,22 @@ ffmpeg -f lavfi -i testsrc=size=32x32:rate=4:duration=1 \
Browser tests use the committed file; FFmpeg is not required to run them.
# AVIF metadata fixture
`media/comfyui_avif.avif` (96x96, about 1 KB) is an original synthetic gradient
written by ComfyUI's own AVIF writer, `SaveImageAdvanced` (PyAV with SVT-AV1,
then `inject_avif_metadata`), so it carries the EXIF item ComfyUI writes:
`prompt:{json}` at tag 0x0110 and `workflow:{json}` at 0x010F. It is dedicated
to the public domain under CC0-1.0. `utils/exif_text`, the scan and the monitor
read it; `tests/test_avif_media_type.py` and `tests/test_api_admin.py` cover it.
Reproduce from a ComfyUI checkout with ComfyUI's Python (torch and PyAV with
SVT-AV1), where `comfy_extras` imports:
```sh
python custom_nodes/ComfyUI-PromptManager/tools/make_avif_fixture.py
```
# Local Inspect header fixtures
`local-inspect/tiny.jpg` (48x32) and `local-inspect/tiny.webp` (40x24) are original
+2
View File
@@ -63,6 +63,7 @@
"GET /prompt_manager/lora/status",
"GET /prompt_manager/lora/trigger-words",
"GET /prompt_manager/maintenance/duplicates/{job_id}",
"GET /prompt_manager/maintenance/tag_cleanup/{job_id}",
"GET /prompt_manager/pairs",
"GET /prompt_manager/pairs/export",
"GET /prompt_manager/pairs/{pair_id}",
@@ -134,6 +135,7 @@
"POST /prompt_manager/jobs/image-tags",
"POST /prompt_manager/jobs/model-download",
"POST /prompt_manager/jobs/scan",
"POST /prompt_manager/jobs/tag_cleanup",
"POST /prompt_manager/jobs/thumbnails",
"POST /prompt_manager/jobs/{job_id}/cancel",
"POST /prompt_manager/library",
Binary file not shown.

After

Width:  |  Height:  |  Size: 993 B

-50
View File
@@ -1,50 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
function fixture() {
const panel = { innerHTML: '', isConnected: true };
const requests = new Map();
const context = vm.createContext({ document: { readyState: 'loading', addEventListener() {},
getElementById: id => id === 'metadata-content' ? panel : null },
window: {}, console: { error() {} },
});
const Admin = vm.runInContext(fs.readFileSync(path.join(__dirname, '../../web/js/admin.js'), 'utf8') + '\nPromptAdmin;', context, { filename: path.join(__dirname, '../../web/js/admin.js') });
const manager = Object.create(Admin.prototype);
manager.extractImageMetadata = url => new Promise((resolve, reject) => requests.set(url, { resolve, reject }));
manager.updateMetadataSidebar = metadata => { panel.innerHTML = metadata?.imagePath || 'No metadata'; };
manager.hideModal = () => {};
const load = url => manager.loadMetadataForImage({ getAttribute: () => url });
return { manager, panel, requests, load };
}
test('admin metadata and copy actions stay on the selected image', async () => {
const { manager, panel, requests, load } = fixture();
const old = load('old.png');
const current = load('current.png');
requests.get('current.png').resolve({ imagePath: 'current.png' }); await current;
requests.get('old.png').resolve({ imagePath: 'old.png' }); await old;
assert.equal(panel.innerHTML, 'current.png');
assert.equal(manager.currentMetadata.imagePath, 'current.png');
});
test('navigation clears old action data and late errors cannot replace current metadata', async () => {
const { manager, panel, requests, load } = fixture();
manager.currentMetadata = { imagePath: 'previous.png' };
const old = load('old.png');
assert.equal(manager.currentMetadata, null);
const current = load('current.png');
requests.get('current.png').resolve({ imagePath: 'current.png' }); await current;
requests.get('old.png').reject(new Error('old error')); await old;
assert.equal(panel.innerHTML, 'current.png');
});
for (const close of ['close gallery', 'detach sidebar']) {
test(`${close} prevents pending admin metadata from restoring copy state`, async () => {
const { manager, panel, requests, load } = fixture();
const pending = load('old.png');
if (close === 'close gallery') manager.closeGallery();
else panel.isConnected = false;
requests.get('old.png').resolve({ imagePath: 'old.png' }); await pending;
assert.equal(manager.currentMetadata, null);
assert.notEqual(panel.innerHTML, 'old.png');
});
}
+2 -18
View File
@@ -9,15 +9,11 @@ const path = require("node:path");
const vm = require("node:vm");
const MODULES = {
"html-escape.js": ["HtmlEscape", "escapeHtml", "escapeAttr"],
"data-actions.js": ["DataActions"],
"api-client.js": ["ApiClient"],
"list-state.js": ["ListState"],
"sse-stream.js": ["SseStream"],
"png-metadata.js": ["PngMetadata"],
"view-router.js": ["ViewRouter"],
"prompt-list-sort.js": ["PromptListSort"],
"comfy-metadata.js": ["ComfyMetadata"],
"gallery-settings.js": ["GallerySettings"],
"legacy-links.js": ["LegacyLinks"],
};
function loadInFakeBrowser(file) {
@@ -60,15 +56,3 @@ for (const [file, globals] of Object.entries(MODULES)) {
}
});
}
test("the browser escapeHtml global is the same function as HtmlEscape.escapeHtml", () => {
const window = loadInFakeBrowser("html-escape.js");
assert.equal(window.escapeHtml, window.HtmlEscape.escapeHtml);
assert.equal(window.escapeAttr, window.escapeHtml);
assert.equal(window.escapeHtml(`<a href="x">`), "&lt;a href=&quot;x&quot;&gt;");
});
test("the browser ViewRouter global resolves the tags deep link", () => {
const window = loadInFakeBrowser("view-router.js");
assert.equal(window.ViewRouter.resolveView("#/tags/a"), "tags");
});
+28
View File
@@ -1042,3 +1042,31 @@ test("Split workflow-only metadata recovers serialized fields and connected comp
assert.equal(result.negativePrompt, "avoid blurry watermark");
assert.equal(result.checkpoint, "model.safetensors");
});
// PromptManagerPair roles (moved from pair-metadata.test.js when the old gallery was retired, #668).
function pairGraph(positive = 0, negative = 1) {
return {
1:{class_type:'PromptManagerPair',inputs:{text:'cat',negative_text:'blur',prepend_text:'trigger',append_text:'detail'}},
2:{class_type:'KSampler',inputs:{positive:['1',positive],negative:['1',negative],model:['3',0]}},
3:{class_type:'CheckpointLoaderSimple',inputs:{ckpt_name:'m.safetensors'}},
};
}
test('paired conditioning uses actual output roles and composes only positive', () => {
const metadata = extractGenerationParams({prompt:pairGraph()});
assert.equal(metadata.positivePrompt,'trigger cat detail');
assert.equal(metadata.negativePrompt,'blur');
const swapped = extractGenerationParams({prompt:pairGraph(1,0)});
assert.equal(swapped.positivePrompt,'blur');
assert.equal(swapped.negativePrompt,'trigger cat detail');
});
test('paired strings passed through encoders retain the connected output slot', () => {
const prompt=pairGraph();
prompt[4]={class_type:'CLIPTextEncode',inputs:{text:['1',2]}};
prompt[5]={class_type:'CLIPTextEncode',inputs:{text:['1',3]}};
prompt[2].inputs.positive=['4',0];prompt[2].inputs.negative=['5',0];
const metadata=extractGenerationParams({prompt});
assert.equal(metadata.positivePrompt,'trigger cat detail');
assert.equal(metadata.negativePrompt,'blur');
});
-49
View File
@@ -1,49 +0,0 @@
// Run with: node --test tests/js/
const test = require("node:test");
const assert = require("node:assert/strict");
const { readAction, dispatch } = require("../../web/js/data-actions.js");
test("readAction parses promptId and index as integers", () => {
const parsed = readAction({ action: "open-film", promptId: "42", index: "3" });
assert.equal(parsed.action, "open-film");
assert.equal(parsed.promptId, 42);
assert.equal(parsed.index, 3);
});
test("readAction turns missing or non-numeric ids into null", () => {
assert.equal(readAction({ action: "edit" }).promptId, null);
assert.equal(readAction({ action: "edit", promptId: "abc" }).promptId, null);
assert.equal(readAction({ action: "edit", index: "" }).index, null);
});
test("readAction passes string fields through untouched", () => {
const parsed = readAction({ action: "remove-tag", tag: `a "quoted" tag`, url: "/x?y=1&z=2", copyText: "p" });
assert.equal(parsed.tag, `a "quoted" tag`);
assert.equal(parsed.url, "/x?y=1&z=2");
assert.equal(parsed.copyText, "p");
});
test("readAction tolerates a missing dataset", () => {
assert.equal(readAction(undefined).action, "");
assert.equal(readAction(null).promptId, null);
});
test("dispatch calls the matching handler with the parsed action and extras", () => {
const calls = [];
const handled = dispatch(
{ action: "edit", promptId: "7" },
{ edit: (a, el) => calls.push([a.promptId, el]) },
"element",
);
assert.equal(handled, true);
assert.deepEqual(calls, [[7, "element"]]);
});
test("dispatch returns false and calls nothing for an unknown or empty action", () => {
let called = 0;
const handlers = { edit: () => called++ };
assert.equal(dispatch({ action: "other" }, handlers), false);
assert.equal(dispatch({}, handlers), false);
assert.equal(dispatch({ action: "constructor" }, handlers), false, "no prototype lookups");
assert.equal(called, 0);
});
-76
View File
@@ -1,76 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
function deferred() {
let resolve, reject;
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
}
function fixture() {
const context = vm.createContext({ document: { addEventListener() {}, getElementById() {} },
window: {}, console: { error() {} }, escapeHtml: value => value });
const Manager = vm.runInContext(fs.readFileSync(path.join(__dirname, '../../web/js/gallery.js'), 'utf8') + '\nGalleryManager;', context, { filename: path.join(__dirname, '../../web/js/gallery.js') });
const manager = Object.create(Manager.prototype);
const requests = new Map();
manager.extractImageMetadata = url => {
const pending = deferred();
requests.set(url, pending);
return pending.promise;
};
manager.displayMetadata = (metadata, panel) => {
panel.innerHTML = metadata?.positivePrompt || 'No metadata';
manager.currentMetadata = metadata;
};
manager.stopViewerSlideshow = () => {};
return { manager, requests, panel: { innerHTML: '', isConnected: true } };
}
test('a late response cannot overwrite the selected image or copy state', async () => {
const { manager, requests, panel } = fixture();
const first = manager.loadImageMetadata('old.png', panel);
const second = manager.loadImageMetadata('new.png', panel);
requests.get('new.png').resolve({ positivePrompt: 'new prompt' });
await second;
requests.get('old.png').resolve({ positivePrompt: 'old prompt' });
await first;
assert.equal(panel.innerHTML, 'new prompt');
assert.equal(manager.currentMetadata.positivePrompt, 'new prompt');
});
test('navigation clears old action data while the new request is pending', async () => {
const { manager, requests, panel } = fixture();
manager.currentMetadata = { positivePrompt: 'old prompt' };
const pending = manager.loadImageMetadata('new.png', panel);
assert.equal(manager.currentMetadata, null);
requests.get('new.png').resolve(null);
await pending;
assert.equal(manager.currentMetadata, null);
});
test('a stale error cannot replace newer metadata', async () => {
const { manager, requests, panel } = fixture();
const first = manager.loadImageMetadata('old.png', panel);
const second = manager.loadImageMetadata('new.png', panel);
requests.get('new.png').resolve({ positivePrompt: 'new prompt' });
await second;
requests.get('old.png').reject(new Error('old request failed'));
await first;
assert.equal(panel.innerHTML, 'new prompt');
});
for (const close of ['destroy viewer', 'remove modal']) {
test(`closing via ${close} prevents pending metadata from restoring action data`, async () => {
const { manager, requests, panel } = fixture();
const pending = manager.loadImageMetadata('old.png', panel);
if (close === 'destroy viewer') manager.destroyViewer();
else panel.isConnected = false;
requests.get('old.png').resolve({ positivePrompt: 'closed prompt' });
await pending;
assert.equal(manager.currentMetadata, null);
assert.notEqual(panel.innerHTML, 'closed prompt');
});
}
-209
View File
@@ -1,209 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const { escapeHtml } = require('../../web/js/html-escape.js');
function fixture(count = 2000) {
const elements = new Map();
function element() {
return {
dataset: {}, children: [], listeners: {}, classList: { add() {}, remove() {} },
set innerHTML(html) { this.html = html; this.children = [{ html }]; },
get innerHTML() { return this.html || ''; },
insertAdjacentHTML(position, html) { this.children.push({ html }); },
addEventListener(type, handler) { (this.listeners[type] ||= []).push(handler); },
querySelectorAll() { return []; },
remove() {},
};
}
const document = {
addEventListener() {},
getElementById(id) { if (!elements.has(id)) elements.set(id, element()); return elements.get(id); },
createElement: element,
};
const instances = [];
const timers = new Map();
let timerId = 0;
class Viewer {
constructor(holder, options) {
this.element = holder; this.options = { fullscreen: true, ...options };
this.index = options.initialViewIndex; this.isShown = true;
this.length = (holder.innerHTML.match(/<img /g) || []).length;
instances.push(this);
}
requestFullscreen() { this.fullscreenRequested = true; }
exitFullscreen() { this.fullscreenExited = true; }
show() { this.shown = true; }
view(index) { this.index = index; }
clearEnforceFocus() { this.focusCleared = true; }
destroy() { this.destroyed = true; }
}
const context = vm.createContext({ document, window: {}, Viewer, escapeHtml,
console, setTimeout(callback) { timers.set(++timerId, callback); return timerId; },
clearTimeout(id) { timers.delete(id); },
ApiClient: { resolveUrl: value => value, STALE: Symbol() },
ListState: { nextPageState: (state, next) => ({ ...state, ...next }) },
});
const source = fs.readFileSync(path.join(__dirname, '../../web/js/gallery.js'), 'utf8');
const Manager = vm.runInContext(source + '\nGalleryManager;', context, { filename: path.join(__dirname, '../../web/js/gallery.js') });
const manager = Object.create(Manager.prototype);
Object.assign(manager, { images: Array.from({ length: count }, (_, i) => ({
filename: `${i}.png`, url: `/original/${i}.png`, thumbnail_url: `/thumb/${i}.jpg`,
relative_path: `${i}.png`, size: 100, modified_time: 1,
})), viewMode: 'grid', viewer: null, currentPage: 1, limit: 100, total: count,
getSettings: () => ({ showImageInfo: true }), });
return { manager, document, instances, timers };
}
for (const mode of ['grid', 'list']) {
test(`${mode} append retains existing cards and adds only the new page`, () => {
const { manager, document, timers } = fixture(100);
manager.viewMode = mode;
manager.renderGallery();
const container = document.getElementById(mode === 'grid' ? 'galleryGrid' : 'galleryList');
assert.equal(timers.size, 0);
const first = container.children[0];
manager.images.push({ ...manager.images[0], filename: 'new.png' });
manager.renderGallery({ from: 100 });
assert.equal(container.children[0], first);
assert.equal(container.children.length, 2);
assert.match(container.children[1].html, /new.png/);
assert.doesNotMatch(container.children[1].html, /alt="0.png"/);
assert.match(container.children[1].html, /data-image-index="100"/);
});
}
test('loadImages passes the previous length for append, and zero for replacement', async () => {
const { manager } = fixture(200);
const offsets = [];
Object.assign(manager, { imagesRequest: async () => ({ total: 500, images: [manager.images[0]] }),
renderGallery: options => offsets.push(options.from), updateStats() {},
updatePagination() {}, maybeLoadMore() {}, showLoading() {}, });
await manager.loadImages(3, { append: true });
await manager.loadImages(1);
assert.deepEqual(offsets, [200, 0]);
assert.equal(manager.images.length, 1);
});
test('viewer opening is bounded and selects the clicked original', () => {
const { manager, instances } = fixture();
manager.openViewer(1500);
const viewer = instances[0];
assert.ok(viewer.element.innerHTML.match(/<img /g).length <= 100);
assert.match(viewer.element.innerHTML, /data-original="\/original\/1500.png"/);
const urls = [...viewer.element.innerHTML.matchAll(/data-original="([^"]+)"/g)].map(m => m[1]);
assert.equal(urls[viewer.options.initialViewIndex], '/original/1500.png');
assert.equal(viewer.shown, true);
});
test('previous/next cross window edges and wrap only at gallery edges', () => {
const { manager, instances } = fixture();
manager.openViewer(1500);
const first = manager.viewer;
first.index = 99;
const lastUrl = [...first.element.innerHTML.matchAll(/data-original="\/original\/(\d+).png"/g)].at(-1);
first.next(true);
const next = manager.viewer;
const urls = [...next.element.innerHTML.matchAll(/data-original="\/original\/(\d+).png"/g)];
assert.equal(Number(urls[next.index][1]), Number(lastUrl[1]) + 1);
manager.openViewer(0);
manager.viewer.prev(true);
const wrapped = manager.viewer;
const wrappedUrls = [...wrapped.element.innerHTML.matchAll(/data-original="\/original\/(\d+).png"/g)];
assert.equal(Number(wrappedUrls[wrapped.index][1]), 1999);
assert.ok(instances.length >= 3);
});
test('delegated card clicks bind once, open appended indices, and preserve video dispatch', () => {
const { manager, document } = fixture();
const opened = [];
manager.openViewer = index => opened.push(index);
manager.showVideoModal = (...args) => opened.push(args);
manager.addFallbackClickHandlers();
manager.addFallbackClickHandlers();
const grid = document.getElementById('galleryGrid');
assert.equal(grid.listeners.click.length, 1);
const item = { dataset: { imageIndex: '1500' }, querySelector: () => ({ dataset: {
original: '/original/1500.png', caption: 'caption', isVideo: 'false',
} }) };
const click = () => grid.listeners.click[0]({ target: { closest: () => item }, preventDefault() {}, stopPropagation() {} });
click();
item.querySelector = () => ({ dataset: { original: '/video.mp4', caption: 'video', isVideo: 'true' } });
click();
assert.deepEqual(opened, [1500, ['/video.mp4', 'video', 1500]]);
});
test('navigation inside the window reuses the viewer and honors non-looping edges', () => {
const { manager, instances } = fixture();
manager.openViewer(1500);
const viewer = manager.viewer;
viewer.next(true);
assert.equal(manager.viewer, viewer);
assert.equal(viewer.index, 51);
viewer.prev(true);
assert.equal(viewer.index, 50);
manager.openViewer(0);
const edge = manager.viewer;
edge.prev(false);
assert.equal(manager.viewer, edge);
assert.equal(edge.index, 0);
assert.equal(instances.length, 2);
});
test('append leaves an open viewer intact; a full render destroys it', () => {
const { manager } = fixture();
manager.openViewer(1500);
const viewer = manager.viewer;
manager.renderGallery({ from: 1900 });
assert.equal(manager.viewer, viewer);
manager.renderGallery();
assert.equal(viewer.destroyed, true);
assert.equal(manager.viewer, null);
});
test('each viewed image updates sidebar metadata without waiting for DOM mutations', () => {
const { manager, document } = fixture();
const urls = [];
document.querySelector = () => ({});
const sidebar = document.getElementById('metadata-sidebar');
sidebar.querySelector = () => ({});
manager.loadImageMetadata = url => urls.push(url);
manager.openViewer(1500);
manager.viewer.options.viewed({ detail: { originalImage: { dataset: { original: '/original/1500.png' } } } });
manager.viewer.options.viewed({ detail: { originalImage: { dataset: { original: '/original/1501.png' } } } });
assert.deepEqual(urls, ['/original/1500.png', '/original/1501.png']);
});
test('slideshow advances across windows without preloading every original and stops on hide', () => {
const { manager, timers } = fixture();
manager.openViewer(1500);
let prevented = false;
manager.viewer.options.play({ preventDefault() { prevented = true; } });
assert.equal(prevented, true);
assert.equal(manager.viewer.fullscreenRequested, true);
assert.equal(timers.size, 1);
manager.viewer.index = 99;
const tick = timers.values().next().value;
timers.clear();
tick();
const viewer = manager.viewer;
const urls = [...viewer.element.innerHTML.matchAll(/data-original="([^"]+)"/g)];
assert.equal(urls[viewer.index][1], '/original/1550.png');
assert.equal(timers.size, 1);
viewer.options.hide();
assert.equal(viewer.fullscreenExited, true);
assert.equal(timers.size, 0);
});
test('destroying a viewer removes its focus trap and slideshow timer', () => {
const { manager, timers } = fixture();
manager.openViewer(1500);
const viewer = manager.viewer;
viewer.options.play({ preventDefault() {} });
manager.destroyViewer();
assert.equal(viewer.focusCleared, true);
assert.equal(viewer.destroyed, true);
assert.equal(timers.size, 0);
});
-103
View File
@@ -1,103 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ImageHelpers = require('../../web/js/image-helpers.js');
function deferred() {
let resolve;
const promise = new Promise(yes => { resolve = yes; });
return { promise, resolve };
}
function fixture() {
const elements = new Map();
const requests = [];
const document = { addEventListener() {}, getElementById(id) {
if (!elements.has(id)) elements.set(id, {});
return elements.get(id);
} };
const context = vm.createContext({ document, window: {}, ImageHelpers,
escapeHtml: value => value, console: { error() {} },
ApiClient: { resolveUrl: value => value, fetchUrl: (url, options) => {
const request = deferred();
requests.push({ url, body: JSON.parse(options.body), ...request });
return request.promise;
} },
});
const Manager = vm.runInContext(fs.readFileSync(path.join(__dirname, '../../web/js/gallery.js'), 'utf8') + '\nGalleryManager;', context, { filename: path.join(__dirname, '../../web/js/gallery.js') });
const manager = Object.create(Manager.prototype);
const notifications = [];
Object.assign(manager, { autoTagState: { reviewImages: [
{ id: 'digest', path: 'same.png', root_index: 1, url: '/same.png' },
{ id: 'other', path: 'next.png', root_index: 0, url: '/next.png' },
], reviewIndex: 0, currentTags: [], modelType: 'gguf' },
renderReviewTags() {}, showNotification: (...args) => notifications.push(args), hideModal() {}, loadImages() {},
});
const reply = (index, data) => requests[index].resolve({ json: async () => data });
return { manager, requests, reply, notifications };
}
const SHA = 'a'.repeat(64);
test('gallery review retains root identity and applies the tags to the image by its sha256 (#379)', async () => {
const { manager, requests, reply } = fixture();
const load = manager.loadNextReviewImage();
assert.equal(requests[0].body.root_index, 1);
assert.equal(requests[0].body.existing, 'merge');
reply(0, { success: true, prompt_id: 42, tags: ['smile'], sha256: SHA, image_tags: [] });
await load;
manager.loadNextReviewImage = () => {};
const apply = manager.applyReviewTags();
assert.equal(requests[1].url, '/prompt_manager/autotag/apply');
assert.deepEqual(requests[1].body, ImageHelpers.autotagApplyBody(
{ id: 'digest', path: 'same.png', root_index: 1 }, SHA, ['smile']));
assert.equal('prompt_id' in requests[1].body, false);
reply(1, { success: true });
await apply;
});
test('an unlinked image applies to the image like a linked one', async () => {
const { manager, requests, reply } = fixture();
const load = manager.loadNextReviewImage();
reply(0, { success: true, prompt_id: null, tags: ['smile'], sha256: SHA, image_tags: [] });
await load;
manager.loadNextReviewImage = () => {};
const apply = manager.applyReviewTags();
assert.equal(requests[1].body.sha256, SHA);
assert.deepEqual(requests[1].body.tags, ['smile']);
reply(1, { success: true });
await apply;
});
test('an answer without a captured sha256 never sends an apply', async () => {
const { manager, requests, reply } = fixture();
const load = manager.loadNextReviewImage();
reply(0, { success: true, prompt_id: 42, tags: ['smile'] });
await load;
manager.loadNextReviewImage = () => {};
await manager.applyReviewTags();
assert.equal(requests.filter(r => r.url === '/prompt_manager/autotag/apply').length, 0);
});
test('a failed apply keeps the current image available for retry', async () => {
const { manager, requests, reply } = fixture();
const load = manager.loadNextReviewImage();
reply(0, { success: true, prompt_id: 42, tags: ['smile'], sha256: SHA, image_tags: [] });
await load;
const apply = manager.applyReviewTags();
reply(1, { success: false, error: 'Try again' });
await apply;
assert.equal(manager.autoTagState.reviewIndex, 0);
assert.equal(requests.length, 2);
});
test('late generation responses cannot restore tags from a skipped or closed image', async () => {
const { manager, reply } = fixture();
const first = manager.loadNextReviewImage();
manager.autoTagState.reviewIndex = 1;
const second = manager.loadNextReviewImage();
reply(1, { success: true, prompt_id: 2, tags: ['current'] });
await second;
reply(0, { success: true, prompt_id: 1, tags: ['stale'] });
await first;
assert.deepEqual(Array.from(manager.autoTagState.currentTags), ['current']);
const third = manager.loadNextReviewImage();
manager.cancelReview();
reply(2, { success: true, prompt_id: 2, tags: ['closed'] });
await third;
assert.equal(manager.autoTagState.currentTags.length, 0);
});
-30
View File
@@ -1,30 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const ImageHelpers = require('../../web/js/image-helpers.js');
test('gallery metadata requests retain root identity without including cache parameters in filenames', async () => {
const requests = [];
const context = vm.createContext({ document: { addEventListener() {} }, window: {}, console,
ImageHelpers, ApiClient: { fetchUrl: async url => {
requests.push(url);
return { ok: true, json: async () => ({ success: true, prompt: { text: url } }) };
} },
});
const Manager = vm.runInContext(fs.readFileSync(path.join(__dirname, '../../web/js/gallery.js'), 'utf8') + '\nGalleryManager;', context, { filename: path.join(__dirname, '../../web/js/gallery.js') });
const manager = Object.create(Manager.prototype);
manager.extractImageMetadata = async () => null;
manager.displayMetadata = (metadata, panel) => { panel.prompt = metadata.positivePrompt; };
for (const root of [0, 1]) {
const panel = {};
const expected = `/prompt_manager/images/prompt/sub%2Fsame.png?root=${root}`;
await manager.loadImageMetadata(`/prompt_manager/images/serve/sub/same.png?v=123&root=${root}`, panel);
assert.equal(panel.prompt, expected);
}
assert.deepEqual(requests, [
'/prompt_manager/images/prompt/sub%2Fsame.png?root=0',
'/prompt_manager/images/prompt/sub%2Fsame.png?root=1',
]);
});
-101
View File
@@ -87,104 +87,3 @@ test("the viewer open mode defaults to centered and accepts only its two values"
assert.equal(normalizeGallerySettings({ viewerOpenMode: "fullscreen" }).viewerOpenMode, "fullscreen");
for (const value of ["full", true, 1, null]) assert.equal(normalizeGallerySettings({ viewerOpenMode: value }).viewerOpenMode, "centered");
});
// #330 S13: the legacy gallery's Page options edit only the page-only keys (PAGE_OPTION_KEYS); System › Appearance owns the rest, so a Save
// or a Reset from the legacy page keeps every other stored key.
function legacyGallery(stored, controls, extra = {}) {
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const settings = require("../../web/js/gallery-settings.js");
const storage = new Map([["gallerySettings", JSON.stringify(stored)]]);
const context = vm.createContext({
document: { addEventListener() {}, getElementById: id => controls[id] },
window: {}, console: { debug() {}, warn() {}, error() {} }, GallerySettings: settings,
localStorage: { getItem: key => storage.get(key) ?? null, setItem: (key, value) => storage.set(key, value),
removeItem: key => storage.delete(key) },
...extra,
});
const file = path.join(__dirname, "../../web/js/gallery.js");
const Manager = vm.runInContext(`${fs.readFileSync(file, "utf8")}\nGalleryManager;`, context, { filename: file });
const manager = Object.create(Manager.prototype);
const calls = [];
Object.assign(manager, { showNotification: (message, type) => calls.push([type, message]), hideSettings() {},
applySettings: applied => calls.push(["apply", applied.lazyLoading]) });
return { manager, storage, calls, saved: () => JSON.parse(storage.get("gallerySettings")) };
}
const PAGE_OPTION_CONTROLS = () => ({
checkThumbnailsAtStartup: { checked: false }, lazyLoadingToggle: { checked: false },
defaultLimitSelect: { value: "200" },
gridColumnsSelect: { value: "6" }, infiniteScrollToggle: { checked: true }, debugModeToggle: { checked: true },
apiTimeoutInput: { value: "45" },
});
test("a legacy gallery Save keeps the workspace keys and every other stored key", () => {
const { manager, saved } = legacyGallery({ workspaceLayout: "masonry", workspaceDensity: "compact", someOtherTool: 1,
imageQuality: "high", showImageInfo: false, videoMute: false, thumbnailPromptDismissed: "sig", defaultViewMode: "list",
viewerOpenMode: "fullscreen" },
PAGE_OPTION_CONTROLS());
manager.saveSettings();
const result = saved();
assert.equal(result.workspaceLayout, "masonry");
assert.equal(result.workspaceDensity, "compact");
assert.equal(result.someOtherTool, 1);
assert.equal(result.imageQuality, "high");
assert.equal(result.showImageInfo, false);
assert.equal(result.videoMute, false);
assert.equal(result.thumbnailPromptDismissed, "sig");
assert.equal(result.viewerOpenMode, "fullscreen");
// Page options no longer edit the default view (S13 G5), so a stored one stays.
assert.equal(result.defaultViewMode, "list");
// The page-only keys come from the dialog.
assert.equal(result.lazyLoading, false);
assert.equal(result.debugMode, true);
assert.equal(result.checkThumbnailsAtStartup, false);
assert.equal(result.defaultLimit, 200);
assert.equal(result.gridColumns, 6);
assert.equal(result.infiniteScroll, true);
assert.equal(result.apiTimeout, 45);
});
test("a legacy gallery Reset restores only the page options and keeps every other stored key", () => {
const controls = PAGE_OPTION_CONTROLS();
const { manager, saved, calls } = legacyGallery({ workspaceLayout: "masonry", imageQuality: "high", videoMute: false,
thumbnailPromptDismissed: "sig", thumbnailsGenerated: true, lazyLoading: false, debugMode: true, defaultLimit: 200,
gridColumns: 6, infiniteScroll: true, apiTimeout: 45, checkThumbnailsAtStartup: false, defaultViewMode: "list" }, controls,
{ confirm: message => (calls.push(["confirm", message]), true) });
manager.resetSettings();
const result = saved();
const { DEFAULT_SETTINGS } = require("../../web/js/gallery-settings.js");
for (const key of ["checkThumbnailsAtStartup", "lazyLoading", "defaultLimit", "gridColumns",
"infiniteScroll", "debugMode", "apiTimeout"]) {
assert.equal(result[key], DEFAULT_SETTINGS[key], key);
}
// The default view is not a page option (S13 G5): Reset keeps a stored one.
assert.equal(result.defaultViewMode, "list");
assert.equal(result.workspaceLayout, "masonry");
assert.equal(result.imageQuality, "high");
assert.equal(result.videoMute, false);
assert.equal(result.thumbnailPromptDismissed, "sig");
assert.equal(result.thumbnailsGenerated, true);
// The dialog shows the defaults again and the page applies them.
assert.equal(controls.lazyLoadingToggle.checked, DEFAULT_SETTINGS.lazyLoading);
assert.equal(controls.apiTimeoutInput.value, DEFAULT_SETTINGS.apiTimeout);
assert.deepEqual(calls, [["confirm", "Reset these page options to their defaults?"], ["apply", DEFAULT_SETTINGS.lazyLoading],
["success", "Page options reset to defaults"]]);
});
test("Page options no longer hold the default view; System › Appearance's Default layout is the one control", () => {
const { manager } = legacyGallery({}, {});
assert.deepEqual([...manager.constructor.PAGE_OPTION_KEYS], ["checkThumbnailsAtStartup", "lazyLoading", "defaultLimit",
"gridColumns", "infiniteScroll", "debugMode", "apiTimeout"]);
});
test("a viewer mute or loop click remembers only that key and never reads the Page options dialog", () => {
const { manager, saved, calls } = legacyGallery({ defaultLimit: 200, lazyLoading: false, videoMute: true }, {});
manager.storeSetting("videoMute", false);
const result = saved();
assert.equal(result.videoMute, false);
assert.equal(result.defaultLimit, 200);
assert.equal(result.lazyLoading, false);
assert.deepEqual(calls, []);
});
-235
View File
@@ -1,235 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
function fixture(status, settings = {}) {
const timers = [];
const prompts = [];
const requests = [];
const buttons = {};
const storage = new Map();
const document = {
addEventListener() {},
createElement: () => ({ addEventListener() {} }),
body: { appendChild() {}, removeChild() {} },
getElementById: id => buttons[id] ||= { addEventListener(type, handler) { this[type] = handler; } },
};
const context = vm.createContext({ document, window: {}, console: { debug() {}, warn() {} },
setTimeout: callback => timers.push(callback),
localStorage: { setItem: (key, value) => storage.set(key, value) },
ApiClient: { fetchUrl: async () => ({ json: async () => ({ success: true,
total: 10000, images: Array.from({ length: 50 }, () => ({ thumbnail_url: null })),
}) }) },
});
const Manager = vm.runInContext(fs.readFileSync(path.join(__dirname, '../../web/js/gallery.js'), 'utf8') + '\nGalleryManager;', context, { filename: path.join(__dirname, '../../web/js/gallery.js') });
const manager = Object.create(Manager.prototype);
Object.assign(manager, { getSettings: () => ({ checkThumbnailsAtStartup: true, ...settings }),
api: { get: async url => { requests.push(url); return status; } },
});
const originalPrompt = manager.showThumbnailGenerationPrompt.bind(manager);
manager.showThumbnailGenerationPrompt = (...args) => prompts.push(args);
async function check() {
await manager.checkThumbnailsAtStartup();
await timers.shift()();
}
return { manager, check, prompts, requests, settings, buttons, storage, originalPrompt };
}
test('startup uses exact collection counts instead of extrapolating the newest 50 images', async () => {
const f = fixture({ success: true, total_images: 10000, pending: 50, ready: 9950, collection_id: 'a' });
await f.check();
assert.deepEqual(f.requests, ['/prompt_manager/images/thumbnails/status']);
assert.equal(f.prompts.length, 0);
});
test('startup prompt reports the actual number needing generation', async () => {
const f = fixture({ success: true, total_images: 10000, pending: 1200, collection_id: 'a' });
await f.check();
assert.equal(f.prompts.length, 1);
assert.deepEqual(f.prompts[0].slice(0, 2), [10000, 1200]);
});
test('a complete collection never prompts again', async () => {
const f = fixture({ success: true, total_images: 10000, pending: 0, collection_id: 'a' });
await f.check();
await f.check();
assert.equal(f.prompts.length, 0);
});
test('Not Now persists the collection state and suppresses the unchanged prompt', async () => {
const status = { success: true, total_images: 100, pending: 30, collection_id: 'a' };
const f = fixture(status);
await f.check();
f.originalPrompt(...f.prompts[0]);
f.buttons.thumbnailPromptNo.click();
Object.assign(f.settings, JSON.parse(f.storage.get('gallerySettings')));
f.prompts.length = 0;
await f.check();
assert.equal(f.prompts.length, 0);
status.pending = 40;
await f.check();
assert.equal(f.prompts.length, 1);
});
// WebKit fails a fetch a leaving page starts ("Fetch API cannot load … due to access control checks.") and logs it
// as a page error: the delayed startup check starts no read once the page has begun to leave (as admin.js, #290).
test('the startup check starts no read once the page is leaving', async () => {
const f = fixture({ success: true, total_images: 100, pending: 30, collection_id: 'a' });
f.manager.pageLifetime = new AbortController();
f.manager.pageLifetime.abort();
await f.check();
assert.equal(f.requests.length, 0);
assert.equal(f.prompts.length, 0);
});
test('the startup check passes the page lifetime to its read', async () => {
const f = fixture({ success: true, total_images: 100, pending: 30, collection_id: 'a' });
const signals = [];
f.manager.pageLifetime = new AbortController();
const get = f.manager.api.get;
f.manager.api.get = async (url, options) => { signals.push(options?.signal); return get(url); };
await f.check();
assert.deepEqual(signals, [f.manager.pageLifetime.signal]);
assert.equal(f.prompts.length, 1);
});
test('disabled checks do not request collection status', async () => {
const f = fixture({}, { checkThumbnailsAtStartup: false });
await f.check();
assert.equal(f.requests.length, 0);
assert.equal(f.prompts.length, 0);
});
test('saving gallery settings retains the remembered thumbnail dismissal', () => {
const f = fixture({}, { thumbnailPromptDismissed: 'remembered-state' });
f.manager.showNotification = () => {};
f.manager.hideSettings = () => {};
f.manager.applySettings = () => {};
f.manager.saveSettings();
assert.equal(JSON.parse(f.storage.get('gallerySettings')).thumbnailPromptDismissed, 'remembered-state');
});
// #249 System S5: the stream's work is now an Activity job that outlives the page's connection, so the gallery's
// Cancel asks the server to stop the job. Since #330 the startup dialog is the gallery's only thumbnail stream (System
// › Sources & scans generates the rest). The stream's first frame, `job {id, started}`, names the job; the gallery
// cancels by that id, only a job this stream started, and a Cancel before the id waits for it (review I1).
const JOB = 'b'.repeat(32);
function streamFixture({ postFails = false } = {}) {
const posts = [];
const warnings = [];
const gets = [];
const listeners = {};
const source = { closed: 0, readyState: 1, CLOSED: 2, url: null,
addEventListener(type, handler) { (listeners[type] ||= []).push(handler); },
close() { this.closed += 1; } };
const element = () => ({ classList: { add() {}, remove() {} }, style: {}, textContent: '', handlers: {},
addEventListener(type, handler) { this.handlers[type] = handler; },
removeEventListener(type, handler) { if (this.handlers[type] === handler) delete this.handlers[type]; },
click() { this.handlers.click?.(); } });
const elements = {};
const document = { addEventListener() {}, getElementById: id => elements[id] ||= element(),
createElement: () => element(), body: { appendChild() {}, removeChild() {} } };
const context = vm.createContext({ document, window: {},
console: { debug() {}, warn: (...args) => warnings.push(args), error() {} },
setTimeout() {}, localStorage: { setItem() {} },
SseStream: { connect: (url, options) => { source.url = url; source.options = options; return source; } } });
const file = path.join(__dirname, '../../web/js/gallery.js');
const Manager = vm.runInContext(fs.readFileSync(file, 'utf8') + '\nGalleryManager;', context, { filename: file });
const manager = Object.create(Manager.prototype);
Object.assign(manager, { getSettings: () => ({}),
api: { get: async url => { gets.push(url); return { success: true, jobs: [] }; },
post: async (url, body) => {
posts.push([url, body]);
if (postFails) throw new Error('offline');
return { success: true };
} } });
const emit = (type, data) => (listeners[type] || []).forEach(handler => handler({ data: JSON.stringify(data) }));
// The dialog's Cancel runs the handler and from then on reads as cancelled, as the startup dialog does.
let cancelled = false;
const ui = { addStatusMessage() {}, progressText: element(), progressPercent: element(), progressBar: element(),
progressDetails: element(), progressETA: element(), isCancelled: () => cancelled,
onCancel: handler => { ui.cancel = () => { cancelled = true; handler(); }; } };
const result = manager.generateThumbnailsWithProgressInModal(ui);
const outcome = result.then(value => ({ value }), error => ({ error: error.message }));
const cancel = () => ui.cancel();
const settle = () => new Promise(resolve => setImmediate(resolve));
return { emit, source, posts, gets, warnings, outcome, cancel, settle };
}
const cancelUrl = id => `/prompt_manager/jobs/${id}/cancel`;
const CANCELLED = 'Thumbnail generation cancelled; previews already written are kept';
test('Cancel before the job id arrives cancels that job once it does', async () => {
const f = streamFixture();
f.cancel();
await f.settle();
assert.deepEqual(f.posts, []);
assert.equal(f.source.closed, 0); // kept open until the stream names its job
assert.deepEqual(await f.outcome, { error: CANCELLED });
// The job frame is the stream's first (the dialog closes the stream on any later frame once cancelled).
f.emit('job', { id: JOB, started: true });
await f.settle();
assert.equal(JSON.stringify(f.posts), JSON.stringify([[cancelUrl(JOB), {}]]));
assert.equal(f.source.closed, 1);
f.emit('job', { id: 'c'.repeat(32), started: true }); // a stray second frame changes nothing
await f.settle();
assert.equal(f.posts.length, 1);
assert.deepEqual(f.gets, []); // never looks a job up by kind
});
test('Cancel after the id cancels it at once, and a double Cancel posts once', async () => {
const f = streamFixture();
f.emit('job', { id: JOB, started: true });
f.cancel();
f.cancel();
await f.settle();
assert.equal(JSON.stringify(f.posts), JSON.stringify([[cancelUrl(JOB), {}]]));
assert.equal(f.source.closed, 1);
assert.deepEqual(await f.outcome, { error: CANCELLED });
assert.deepEqual(f.gets, []);
});
test("Cancel leaves another tab's or System's job running and only stops following it", async () => {
const f = streamFixture();
f.emit('job', { id: JOB, started: false });
f.cancel();
await f.settle();
assert.deepEqual(f.posts, []);
assert.deepEqual(f.gets, []);
assert.equal(f.source.closed, 1);
assert.match((await f.outcome).error, /keeps running/);
});
test('a Cancel the stream never names a job for posts nothing and closes when it ends', async () => {
const f = streamFixture();
f.cancel();
f.emit('error', { error: 'Scan for metadata already running' });
await f.settle();
assert.deepEqual(f.posts, []);
assert.equal(f.source.closed, 1);
});
test('a cancel post that fails is reported, not thrown', async () => {
const f = streamFixture({ postFails: true });
f.emit('job', { id: JOB, started: true });
f.cancel();
await f.settle();
assert.equal(f.posts.length, 1);
assert.equal(f.warnings.length, 1);
assert.deepEqual(await f.outcome, { error: CANCELLED });
});
test('the startup dialog cancels its own job by id too', async () => {
const f = streamFixture();
f.cancel();
await f.settle();
assert.deepEqual(f.posts, []);
f.emit('job', { id: JOB, started: true });
await f.settle();
assert.equal(JSON.stringify(f.posts), JSON.stringify([[cancelUrl(JOB), {}]]));
assert.equal(f.source.closed, 1);
assert.match((await f.outcome).error, /cancelled/);
});
-56
View File
@@ -1,56 +0,0 @@
// Run with: node --test tests/js/
const test = require("node:test");
const assert = require("node:assert/strict");
const { escapeHtml, escapeAttr } = require("../../web/js/html-escape.js");
test("escapes the five HTML-significant characters", () => {
assert.equal(escapeHtml(`&<>"'`), "&amp;&lt;&gt;&quot;&#39;");
});
test("a double quote cannot break out of an attribute", () => {
const payload = `" onmouseover="alert(1)`;
const escaped = escapeHtml(payload);
assert.ok(!escaped.includes(`"`), escaped);
assert.equal(escaped, `&quot; onmouseover=&quot;alert(1)`);
assert.equal(`<a data-tag="${escaped}">`, `<a data-tag="&quot; onmouseover=&quot;alert(1)">`);
});
test("a single quote cannot break out of a single-quoted attribute", () => {
const escaped = escapeHtml(`' onclick='alert(1)`);
assert.ok(!escaped.includes(`'`), escaped);
assert.equal(escaped, `&#39; onclick=&#39;alert(1)`);
});
test("a script tag is neutralised in text context", () => {
assert.equal(escapeHtml("<script>x</script>"), "&lt;script&gt;x&lt;/script&gt;");
});
test("unicode and ordinary text pass through unchanged", () => {
assert.equal(escapeHtml("héllo wörld 日本語 🙂"), "héllo wörld 日本語 🙂");
assert.equal(escapeHtml("plain text, no specials"), "plain text, no specials");
});
test("already escaped text is escaped again, never double-decoded", () => {
assert.equal(escapeHtml("&amp;"), "&amp;amp;");
});
test("null and undefined become the empty string", () => {
assert.equal(escapeHtml(null), "");
assert.equal(escapeHtml(undefined), "");
});
test("numbers and booleans are coerced to strings", () => {
assert.equal(escapeHtml(42), "42");
assert.equal(escapeHtml(0), "0");
assert.equal(escapeHtml(1.5), "1.5");
assert.equal(escapeHtml(false), "false");
});
test("objects are coerced through String()", () => {
assert.equal(escapeHtml({ toString: () => "<b>" }), "&lt;b&gt;");
});
test("escapeAttr is the same function as escapeHtml", () => {
assert.equal(escapeAttr, escapeHtml);
assert.equal(escapeAttr(`a"b`), "a&quot;b");
});
-149
View File
@@ -1,149 +0,0 @@
// Run with: node --test tests/js/
const test = require("node:test");
const assert = require("node:assert/strict");
const {
formatImageCaption,
workflowDocumentHtml,
autotagSingleBody,
autotagApplyBody,
autotagCompleteMessage,
fallbackImageSource,
} = require("../../web/js/image-helpers.js");
const WD14 = { modelType: "wd14-vit", generalThreshold: 0.35, characterThreshold: 0.85, prompt: "ignored" };
const CAPTION = { modelType: "blip", generalThreshold: 0.35, characterThreshold: 0.85, prompt: "describe it" };
test("autotagSingleBody sends image_id for a database row", () => {
const body = autotagSingleBody({ id: 42, prompt_id: 7, image_path: "/out/a.png" }, WD14);
assert.equal(body.image_id, 42);
assert.equal("path" in body, false);
});
test("autotagSingleBody sends path for an output-folder entry whose id is a digest", () => {
const body = autotagSingleBody({ id: "3f2a9c1b0d4e5f67", path: "/out/sub/a.png", filename: "a.png" }, WD14);
assert.equal(body.path, "/out/sub/a.png");
assert.equal("image_id" in body, false);
});
test("autotagSingleBody prefers path when a numeric-looking string id has no prompt link", () => {
const body = autotagSingleBody({ id: "1234567890abcdef", path: "/out/b.png" }, WD14);
assert.deepEqual(Object.keys(body).filter((k) => k === "path" || k === "image_id"), ["path"]);
});
test("autotagSingleBody adds wd14 thresholds and no prompt", () => {
const body = autotagSingleBody({ id: 1 }, WD14);
assert.equal(body.model_type, "wd14-vit");
assert.equal(body.general_threshold, 0.35);
assert.equal(body.character_threshold, 0.85);
assert.equal("prompt" in body, false);
});
test("autotagSingleBody adds the prompt for caption models and no thresholds", () => {
const body = autotagSingleBody({ id: 1 }, CAPTION);
assert.equal(body.model_type, "blip");
assert.equal(body.prompt, "describe it");
assert.equal("general_threshold" in body, false);
});
test("autotagSingleBody does not mutate its inputs", () => {
const image = Object.freeze({ id: 1 });
const settings = Object.freeze({ ...WD14 });
assert.doesNotThrow(() => autotagSingleBody(image, settings));
});
const XSS = '"><img src=x onerror=1>';
const formatFileSize = (bytes) => `${bytes} B`;
test("formatImageCaption joins dimensions and size with the separator", () => {
const caption = formatImageCaption({ width: 640, height: 480, file_size: 2048 }, { formatFileSize });
assert.equal(caption, "640×480 | 2048 B");
});
test("formatImageCaption honours a custom separator and omits a missing size", () => {
assert.equal(formatImageCaption({ width: 1, height: 2 }, { formatFileSize, separator: " • " }), "1×2");
});
test("formatImageCaption falls back to Unknown size when a dimension is missing", () => {
assert.equal(formatImageCaption({ width: 640 }, { formatFileSize }), "Unknown size");
assert.equal(formatImageCaption({}, { formatFileSize }), "Unknown size");
assert.equal(formatImageCaption(null, { formatFileSize }), "Unknown size");
});
test("formatImageCaption escapes string dimensions so they cannot break out of an attribute", () => {
const caption = formatImageCaption({ width: XSS, height: 10 }, { formatFileSize });
assert.ok(!caption.includes("<"), caption);
assert.ok(!caption.includes('"'), caption);
assert.ok(caption.includes("&quot;&gt;&lt;img"), caption);
});
test("formatImageCaption ignores a non-numeric file_size instead of formatting it", () => {
const caption = formatImageCaption({ width: 1, height: 1, file_size: XSS }, { formatFileSize });
assert.equal(caption, "1×1");
});
test("formatImageCaption escapes whatever formatFileSize returns", () => {
const caption = formatImageCaption({ width: 1, height: 1, file_size: 5 }, { formatFileSize: () => "<b>" });
assert.equal(caption, "1×1 | &lt;b&gt;");
});
test("workflowDocumentHtml escapes the JSON so it cannot close the pre block", () => {
const html = workflowDocumentHtml({ note: "</pre><script>alert(1)</script>" });
assert.ok(html.includes("&lt;/pre&gt;&lt;script&gt;"), html);
assert.ok(!html.includes("</pre><script>"), html);
assert.ok(html.startsWith("<!DOCTYPE html>"));
assert.ok(html.includes("<title>ComfyUI Workflow Data</title>"));
});
test("workflowDocumentHtml pretty-prints the workflow with two-space indentation", () => {
const html = workflowDocumentHtml({ a: 1 });
assert.ok(html.includes('{\n &quot;a&quot;: 1\n}'), html);
});
test("fallbackImageSource offers the original once when a thumbnail fails", () => {
const dataset = { original: "/serve/a.png", thumbnail: "/serve/thumbnails/a_thumb.png?v=1" };
assert.equal(fallbackImageSource("/serve/thumbnails/a_thumb.png?v=1", dataset), "/serve/a.png");
});
test("fallbackImageSource gives up when the original itself failed or was already tried", () => {
assert.equal(fallbackImageSource("/serve/a.png", { original: "/serve/a.png" }), null);
assert.equal(fallbackImageSource("/serve/t.png", { original: "/serve/a.png", fellBack: "1" }), null);
assert.equal(fallbackImageSource("/serve/t.png", {}), null);
assert.equal(fallbackImageSource("/serve/t.png", undefined), null);
});
const { metadataLookupUrl } = require('../../web/js/image-helpers.js');
test('metadata lookup keeps root identity and strips thumbnail cache query parameters', () => {
assert.equal(metadataLookupUrl('/prompt_manager/images/serve/sub/a.png?root=1&v=123'), '/prompt_manager/images/prompt/sub%2Fa.png?root=1');
assert.equal(metadataLookupUrl('/prompt_manager/images/serve/a.png?root=0'), '/prompt_manager/images/prompt/a.png?root=0');
});
test('metadata lookup preserves encoded filename characters and works behind a proxy', () => {
assert.equal(metadataLookupUrl('https://example.test/ComfyBackendDirect/prompt_manager/images/serve/space%20%23%3F%2520%20caf%C3%A9.png?root=1'), '/prompt_manager/images/prompt/space%20%23%3F%2520%20caf%C3%A9.png?root=1');
assert.equal(metadataLookupUrl('/prompt_manager/images/serve/a.png?v=123'), '/prompt_manager/images/prompt/a.png');
assert.equal(metadataLookupUrl('/elsewhere/a.png'), null);
});
test("autotagSingleBody asks to skip auto-tagged images only when told (#379)", () => {
assert.equal(autotagSingleBody({ id: 1 }, WD14).existing, "merge");
assert.equal(autotagSingleBody({ id: 1 }, { ...WD14, existing: "skip" }).existing, "skip");
assert.equal(autotagSingleBody({ id: 1 }, { ...WD14, existing: "odd" }).existing, "merge");
});
test("autotagApplyBody names the image, its bytes and the tags, never a prompt (#379)", () => {
const sha = "a".repeat(64);
assert.deepEqual(autotagApplyBody({ id: 4, prompt_id: 7 }, sha, ["bird"]), { image_id: 4, sha256: sha, tags: ["bird"] });
assert.deepEqual(autotagApplyBody({ id: "digest", path: "sub/a.png", root_index: 1 }, sha, []),
{ path: "sub/a.png", root_index: 1, sha256: sha, tags: [] });
assert.deepEqual(autotagApplyBody({ id: 2 }, undefined, null), { image_id: 2, sha256: "", tags: [] });
const tags = ["x"];
autotagApplyBody({ id: 1 }, sha, tags).tags.push("y");
assert.deepEqual(tags, ["x"]);
});
test("autotagCompleteMessage counts images (#379)", () => {
assert.equal(autotagCompleteMessage(2), "Auto tagging complete! Tagged 2 images.");
assert.equal(autotagCompleteMessage(1), "Auto tagging complete! Tagged 1 image.");
assert.equal(autotagCompleteMessage(0), "Auto tagging complete! Tagged 0 images.");
assert.equal(autotagCompleteMessage(undefined), "Auto tagging complete! Tagged 0 images.");
});
+95
View File
@@ -0,0 +1,95 @@
// Run with: node --test tests/js/
// #668 (D207): where an old `/prompt_manager/admin#…` bookmark lands in the workspace (web/js/legacy-links.js, loaded
// by web/admin-redirect.html). Every target must be one the workspace router understands.
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const { adminTarget } = require("../../web/js/legacy-links.js");
const state = import("../../web/js/workspace/state.mjs");
test("the dashboard and unknown hashes open the Prompt library", () => {
for (const hash of ["", "#", "#/", "#/prompts", "#tags", "#/tagsx", "#/tagged/a", undefined, null, 7]) {
assert.equal(adminTarget(hash), "workspace#/library", String(hash));
}
});
test("the bare Tags route and an empty tag list open Tags & categories", () => {
for (const hash of ["#/tags", "#/tags/", "#/tags/,", "#/tags/%20", "#/tags/ , ,", "#/tags/?mode=or"]) {
assert.equal(adminTarget(hash), "workspace#/tags", hash);
}
});
test("selected tags open the Library filtered by them, matching all unless the old mode was or", () => {
assert.equal(adminTarget("#/tags/landscape"), "workspace#/library?tag=landscape");
assert.equal(adminTarget("#/tags/landscape,portrait"), "workspace#/library?tag=landscape&tag=portrait");
assert.equal(adminTarget("#/tags/landscape,portrait?mode=or"), "workspace#/library?tag=landscape&tag=portrait&tag_mode=any");
for (const mode of ["and", "OR", "", "any"]) {
assert.equal(adminTarget(`#/tags/a,b?mode=${mode}`), "workspace#/library?tag=a&tag=b", mode);
}
// The old page wrote ?mode=or only for two or more tags and ignored it for one.
assert.equal(adminTarget("#/tags/a?mode=or"), "workspace#/library?tag=a");
assert.equal(adminTarget("#/tags/a,a?mode=or"), "workspace#/library?tag=a");
});
test("tag names are decoded as the old page encoded them and encoded again for the workspace", () => {
// encodeURIComponent per tag, joined with commas (tags-page.js updateUrlHash).
assert.equal(adminTarget("#/tags/red%20fox,a%2Cb,%E2%98%85%26%3D%3F%23"),
`workspace#/library?${new URLSearchParams([["tag", "red fox"], ["tag", "a,b"], ["tag", "★&=?#"]])}`);
// Trimmed before and after decoding; repeats dropped.
assert.equal(adminTarget("#/tags/ a ,%20a,b"), "workspace#/library?tag=a&tag=b");
// A segment that cannot be decoded is used as written (the old page threw on it).
assert.equal(adminTarget("#/tags/100%,b"), "workspace#/library?tag=100%25&tag=b");
// Only the text between the first and the second `?` was the old query.
assert.equal(adminTarget("#/tags/a,b?x=1?mode=or"), "workspace#/library?tag=a&tag=b");
assert.equal(adminTarget("#/tags/a,b?x=1&mode=or"), "workspace#/library?tag=a&tag=b&tag_mode=any");
});
test("the old untagged entry opens the Library's untagged prompts, alone or mixed", () => {
assert.equal(adminTarget("#/tags/__untagged__"), "workspace#/library?tag_mode=untagged");
// The old page asked for untagged prompts whenever the list held the entry, ignoring the other tags.
assert.equal(adminTarget("#/tags/a,__untagged__?mode=or"), "workspace#/library?tag_mode=untagged");
});
test("every target is relative and resolves in the workspace router to the filter it names", async () => {
const { resolveRoute } = await state;
const cases = [
["", "library", undefined],
["#/tags", "tags", undefined],
["#/tags/red%20fox,a%2Cb?mode=or", "library", { tags: ["red fox", "a,b"], tagMode: "any" }],
["#/tags/a", "library", { tags: ["a"], tagMode: "all" }],
["#/tags/__untagged__", "library", { tags: [], tagMode: "untagged" }],
["#/tags/100%", "library", { tags: ["100%"], tagMode: "all" }],
];
for (const [hash, id, browse] of cases) {
const target = adminTarget(hash);
// Relative, so a reverse-proxy mount prefix in front of /prompt_manager/admin survives.
assert.match(target, /^workspace#\//, hash);
const route = resolveRoute(target.slice("workspace".length));
assert.deepEqual([route.id, route.browse, route.browseInvalid], [id, browse, undefined], hash);
}
});
test("the redirect page loads the module, replaces the address and always offers the Library link", () => {
const html = fs.readFileSync(path.join(__dirname, "../../web/admin-redirect.html"), "utf8");
const moduleTag = '<script src="js/legacy-links.js"></script>';
assert.ok(html.includes(moduleTag), "the page loads the mapping module");
// The link is plain markup, visible without scripts and when the script fails: the page has no <noscript> at all.
assert.ok(html.includes('<a href="workspace#/library">'));
assert.equal(html.toLowerCase().includes("<noscript"), false);
// The inline script follows the module tag; on a page where the module failed to load it still leaves for the Library.
const open = html.indexOf("<script>", html.indexOf(moduleTag));
const inline = html.slice(open + "<script>".length, html.indexOf("</script>", open));
assert.ok(open > 0 && inline.includes("location.replace("));
for (const [globals, expected] of [
[{}, "workspace#/library"],
[{ LegacyLinks: { adminTarget() { throw new Error("broken"); } } }, "workspace#/library"],
[{ LegacyLinks: { adminTarget: hash => `workspace#/seen${hash}` } }, "workspace#/seen#/tags/a"],
]) {
const replaced = [];
const window = { ...globals, location: { hash: "#/tags/a", replace: target => replaced.push(target) } };
vm.runInContext(inline, vm.createContext({ window }));
assert.deepEqual(replaced, [expected]);
}
});
@@ -1,6 +1,6 @@
// Run with: node --test tests/js/
// Characterization, not a specification: pins what the legacy viewers
// (web/metadata.html, web/js/gallery.js) show today on the synthetic inspection
// (the old metadata and gallery pages, removed in #668) showed on the synthetic inspection
// parity fixtures, so the #240 workspace work cannot change them by accident.
// Some answers are known to be wrong (f01b shows the preview-only detailer text
// as both roles; f16 shows the last of two conflicting prompt chunks; f19 shows the
@@ -18,8 +18,8 @@ const { extractGenerationParams } = require("../../web/js/comfy-metadata.js");
const FIXTURES = path.join(__dirname, "..", "fixtures", "inspection_parity");
const DETAILER = "Detailer pass: refine the face";
// Copy of the legacy pages' inline glue (NaN cleanup and field order): web/metadata.html
// extractComfyUIData (line 107) and web/js/gallery.js extractComfyUIData (line 1643).
// Copy of the legacy pages' inline glue (NaN cleanup and field order): extractComfyUIData of
// web/metadata.html (line 107) and web/js/gallery.js (line 1643), as of 3.7.2.
// The spec only promises extractGenerationParams is unchanged, so the glue is copied here.
function legacyComfyData(metadata) {
const parse = text => JSON.parse(text.replace(/:\s*NaN\b/g, ": null").replace(/\bNaN\b/g, "null"));
-100
View File
@@ -1,100 +0,0 @@
// The legacy admin and gallery pages show a server refusal's reason (#220, PR #289 review I1 and M8): a job that
// runs in the workspace refuses their record-changing requests, and a corrupt config.json refuses a settings save.
// Each page must name the reason, not report a lost connection, a bare HTTP status or a success.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
function elements() {
const nodes = {};
return {
nodes,
getElementById: id => nodes[id] ||= { id, textContent: '', innerHTML: '', disabled: false, style: {},
value: '', checked: false, addEventListener() {}, querySelectorAll: () => [] },
};
}
function jsonResponse(status, body) {
return { ok: status >= 200 && status < 300, status, statusText: status === 409 ? 'Conflict' : 'OK',
json: async () => body };
}
function load(file, className, fetchUrl, extra = {}, dom = elements()) {
const timers = [];
const notifications = [];
const storage = new Map([['pm_cached', '1'], ['userData', 'keep'], ['pm_workspace_theme', 'light'],
['pm_update_notice_dismissed', '3.3.0']]);
const localStorage = {
get length() { return storage.size; },
key: index => [...storage.keys()][index] ?? null,
getItem: key => storage.get(key) ?? null,
setItem: (key, value) => storage.set(key, String(value)),
removeItem: key => storage.delete(key),
};
const context = vm.createContext({
document: { readyState: 'loading', addEventListener() {}, getElementById: dom.getElementById,
querySelectorAll: () => [] },
window: {}, console: { error() {}, warn() {}, debug() {} },
setTimeout: callback => timers.push(callback),
confirm: () => true,
localStorage,
TextDecoder, TextEncoder, JSON,
ApiClient: { fetchUrl },
...extra,
});
// gallery.html loads cache-ownership.js before gallery.js (#222).
vm.runInContext(fs.readFileSync(path.join(__dirname, '../../web/js/cache-ownership.js'), 'utf8'), context);
const source = fs.readFileSync(path.join(__dirname, `../../web/js/${file}`), 'utf8');
const Page = vm.runInContext(`${source}\n${className};`, context, { filename: path.join(__dirname, `../../web/js/${file}`) });
const page = Object.create(Page.prototype);
page.showNotification = (message, type) => notifications.push([type, message]);
page.showModal = id => notifications.push(['show', id]);
page.hideModal = id => notifications.push(['hide', id]);
return { page, dom, timers, notifications, storage };
}
test('admin settings save shows why config.json refused it', async () => {
const message = 'config.json cannot be read, so nothing was saved. Fix or remove the file, then save again.';
const { page, notifications } = load('admin.js', 'PromptAdmin',
async () => jsonResponse(409, { success: false, persisted: false, code: 'config-unreadable', error: message }));
page.settings = {};
page.setInfiniteScroll = () => assert.fail('nothing changes after a refusal');
await page.saveSettings();
assert.deepEqual(notifications, [['error', `Failed to save settings: ${message}`]]);
});
test('admin settings save keeps its plain message when the reply has no reason', async () => {
const { page, notifications } = load('admin.js', 'PromptAdmin', async () => ({ ok: false, status: 500,
json: async () => { throw new SyntaxError('not json'); } }));
page.settings = {};
await page.saveSettings();
assert.deepEqual(notifications, [['error', 'Failed to save settings']]);
});
// #330 S13-9: the admin page's reduced Page options save sends only the list's scroll default, so a stale legacy form
// can no longer overwrite scan folders or other settings edited in System.
test('admin Page options save posts only infinite_scroll', async () => {
const sent = [];
const { page, dom, notifications } = load('admin.js', 'PromptAdmin', async (url, init) => {
sent.push([url, init.method, JSON.parse(init.body)]);
return jsonResponse(200, { success: true, restart_required: true });
});
page.settings = { infiniteScroll: false };
const scrolled = [];
page.setInfiniteScroll = (on, options) => scrolled.push([on, { ...options }]);
dom.getElementById('infiniteScrollDefault').checked = true;
await page.saveSettings();
assert.deepEqual(sent, [['/prompt_manager/settings', 'POST', { infinite_scroll: true }]]);
assert.deepEqual(scrolled, [[true, { session: false }]]);
assert.equal(page.settings.infiniteScroll, true);
assert.deepEqual(notifications, [['success', 'Page options saved'], ['hide', 'settingsModal']]);
});
-65
View File
@@ -1,65 +0,0 @@
// Run with: node --test tests/js/
const test = require("node:test");
const assert = require("node:assert/strict");
const { nextPageState, shouldSaveEdit, hasMorePages, shouldLoadMore } = require("../../web/js/list-state.js");
test("hasMorePages follows pagination.has_more only while pages keep arriving", () => {
assert.equal(hasMorePages({ pagination: { has_more: true } }, 5000), true);
assert.equal(hasMorePages({ pagination: { has_more: false } }, 5000), false);
assert.equal(hasMorePages({ pagination: { has_more: true } }, 0), false, "an empty page ends the loop");
assert.equal(hasMorePages({}, 10), false, "no pagination block means a single page");
assert.equal(hasMorePages(null, 10), false);
});
const current = { page: 2, limit: 50, total: 120, totalPages: 3 };
test("nextPageState moves to the requested page once the fetch succeeded", () => {
assert.deepEqual(nextPageState(current, { page: 3, total: 120 }), { page: 3, limit: 50, total: 120, totalPages: 3 });
});
test("nextPageState clamps a page beyond the end when the total shrank", () => {
assert.deepEqual(nextPageState(current, { page: 3, total: 60 }), { page: 2, limit: 50, total: 60, totalPages: 2 });
});
test("nextPageState never goes below page 1 and has at least one page", () => {
assert.deepEqual(nextPageState(current, { page: 0, total: 0 }), { page: 1, limit: 50, total: 0, totalPages: 1 });
assert.equal(nextPageState(current, { page: -5, total: 10 }).page, 1);
});
test("nextPageState keeps the current page and total when the response omits them", () => {
assert.deepEqual(nextPageState(current, {}), current);
assert.deepEqual(nextPageState(current, { total: "many", page: "x" }), current);
});
test("nextPageState accepts a new limit and recomputes totalPages", () => {
assert.deepEqual(nextPageState(current, { page: 1, limit: 25, total: 120 }), { page: 1, limit: 25, total: 120, totalPages: 5 });
assert.equal(nextPageState(current, { limit: 0 }).limit, 50, "a zero limit is ignored");
});
test("nextPageState does not mutate its input", () => {
const before = { ...current };
nextPageState(current, { page: 1, total: 5 });
assert.deepEqual(current, before);
});
test("shouldSaveEdit is true only for a non-empty text that changed", () => {
assert.equal(shouldSaveEdit("old", "new"), true);
assert.equal(shouldSaveEdit("same", "same"), false);
assert.equal(shouldSaveEdit("same", " same \n"), false, "whitespace-only changes are not saved");
assert.equal(shouldSaveEdit("old", " "), false, "an emptied prompt is not saved");
assert.equal(shouldSaveEdit("old", null), false);
});
test("shouldLoadMore asks for the next page only near the bottom with pages left", () => {
const base = {
infiniteScroll: true, loading: false, page: 1, limit: 100, total: 1000,
scrollTop: 0, clientHeight: 800, scrollHeight: 4000, threshold: 600,
};
assert.equal(shouldLoadMore(base), false, "far from the bottom");
assert.equal(shouldLoadMore({ ...base, scrollTop: 2700 }), true, "within the threshold");
assert.equal(shouldLoadMore({ ...base, scrollTop: 2700, loading: true }), false, "a load is in flight");
assert.equal(shouldLoadMore({ ...base, scrollTop: 2700, infiniteScroll: false }), false, "setting off");
assert.equal(shouldLoadMore({ ...base, scrollTop: 2700, page: 10 }), false, "last page reached");
assert.equal(shouldLoadMore({ ...base, scrollHeight: 700 }), true, "content shorter than the viewport");
assert.equal(shouldLoadMore({ ...base, total: 0, scrollHeight: 700 }), false, "nothing to load");
});
-61
View File
@@ -1,61 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const ImageHelpers = require('../../web/js/image-helpers.js');
const {extractGenerationParams} = require('../../web/js/comfy-metadata.js');
function graph(positive = 0, negative = 1) {
return {
1:{class_type:'PromptManagerPair',inputs:{text:'cat',negative_text:'blur',prepend_text:'trigger',append_text:'detail'}},
2:{class_type:'KSampler',inputs:{positive:['1',positive],negative:['1',negative],model:['3',0]}},
3:{class_type:'CheckpointLoaderSimple',inputs:{ckpt_name:'m.safetensors'}},
};
}
test('paired conditioning uses actual output roles and composes only positive', () => {
const metadata = extractGenerationParams({prompt:graph()});
assert.equal(metadata.positivePrompt,'trigger cat detail');
assert.equal(metadata.negativePrompt,'blur');
const swapped = extractGenerationParams({prompt:graph(1,0)});
assert.equal(swapped.positivePrompt,'blur');
assert.equal(swapped.negativePrompt,'trigger cat detail');
});
test('paired strings passed through encoders retain the connected output slot', () => {
const prompt=graph();
prompt[4]={class_type:'CLIPTextEncode',inputs:{text:['1',2]}};
prompt[5]={class_type:'CLIPTextEncode',inputs:{text:['1',3]}};
prompt[2].inputs.positive=['4',0];prompt[2].inputs.negative=['5',0];
const metadata=extractGenerationParams({prompt});
assert.equal(metadata.positivePrompt,'trigger cat detail');
assert.equal(metadata.negativePrompt,'blur');
});
test('recorded image pair overrides unrelated PNG fallback, including an empty negative', async () => {
for (const negative of ['blur','']) {
const context=vm.createContext({document:{addEventListener(){}},window:{},console,ImageHelpers,
ApiClient:{fetchUrl:async()=>({ok:true,json:async()=>({success:true,prompt:{text:'raw cat',pair:{negative_text:negative},pair_context:{positive_text:'trigger cat',negative_text:negative}}})})},
});
const Manager=vm.runInContext(fs.readFileSync(path.join(__dirname,'../../web/js/gallery.js'),'utf8')+'\nGalleryManager;',context);
const manager=Object.create(Manager.prototype);
manager.extractImageMetadata=async()=>({positivePrompt:'wrong',negativePrompt:'wrong'});
manager.displayMetadata=data=>{manager.last=data;};
await manager.loadImageMetadata('/prompt_manager/images/serve/example.png',{});
assert.equal(manager.last.positivePrompt,'trigger cat');
assert.equal(manager.last.negativePrompt,negative);
}
});
test('gallery labels graph-inferred text separately from recorded execution text', () => {
const context=vm.createContext({document:{addEventListener(){}},window:{},console,escapeHtml:value=>String(value)});
const Manager=vm.runInContext(fs.readFileSync(path.join(__dirname,'../../web/js/gallery.js'),'utf8')+'\nGalleryManager;',context);
const manager=Object.create(Manager.prototype);
manager.formatPromptText=value=>String(value||'');manager.setupMetadataActions=()=>{};
for (const [source,label] of [['graph-inferred','Recovered from workflow metadata'],['execution','Recorded during execution'],['embedded-parameters','Read from embedded parameters'],['mixed','Execution and workflow metadata']]) {
const panel={};
manager.displayMetadata({positivePrompt:'cat',negativePrompt:'blur',textSource:source},panel);
assert.ok(panel.innerHTML.includes(label),source);
}
});
-66
View File
@@ -1,66 +0,0 @@
// Run with: node --test tests/js/
const test = require("node:test");
const assert = require("node:assert/strict");
const sort = require("../../web/js/prompt-list-sort.js");
test("default sort is recently used and is a listed option", () => {
assert.equal(sort.DEFAULT_SORT, "last_used_desc");
assert.ok(sort.SORT_OPTIONS.some((o) => o.value === sort.DEFAULT_SORT));
});
test("options include Recently used and Most used, each with a label", () => {
const values = sort.SORT_OPTIONS.map((o) => o.value);
assert.ok(values.includes("last_used_desc"));
assert.ok(values.includes("run_count_desc"));
for (const option of sort.SORT_OPTIONS) assert.ok(option.label.trim(), option.value);
assert.equal(new Set(values).size, values.length, "values are unique");
});
test("options cannot be mutated by callers", () => {
assert.throws(() => sort.SORT_OPTIONS.push({ value: "x", label: "x" }));
// Non-strict code fails silently on frozen objects, so check the value survived
const first = sort.SORT_OPTIONS[0].value;
sort.SORT_OPTIONS[0].value = "hacked";
assert.equal(sort.SORT_OPTIONS[0].value, first);
assert.ok(sort.SORT_OPTIONS.every(Object.isFrozen));
});
test("normalizeSort keeps known values and falls back for anything else", () => {
assert.equal(sort.normalizeSort("run_count_desc"), "run_count_desc");
for (const bad of [undefined, null, "", "created_at; DROP TABLE prompts", 42, "LAST_USED_DESC"]) {
assert.equal(sort.normalizeSort(bad), sort.DEFAULT_SORT, String(bad));
}
});
test("buildRecentUrl computes offset from page and always sends a valid sort", () => {
assert.equal(
sort.buildRecentUrl({ page: 3, limit: 25, sort: "rating_desc" }),
"/prompt_manager/recent?limit=25&offset=50&page=3&sort=rating_desc",
);
assert.equal(
sort.buildRecentUrl({ sort: "bogus" }),
"/prompt_manager/recent?limit=50&offset=0&page=1&sort=last_used_desc",
);
});
test("withSort returns a copy with the sort set and leaves the input untouched", () => {
const params = new URLSearchParams({ text: "castle", sort: "text_asc" });
const result = sort.withSort(params, "run_count_desc");
assert.equal(result.get("sort"), "run_count_desc");
assert.equal(result.get("text"), "castle");
assert.equal(params.get("sort"), "text_asc");
assert.equal(sort.withSort(new URLSearchParams(), "nope").get("sort"), sort.DEFAULT_SORT);
});
test("formatRunCount labels zero, one and many runs", () => {
assert.equal(sort.formatRunCount(0), "Never run");
assert.equal(sort.formatRunCount(1), "1 run");
assert.equal(sort.formatRunCount(642), "642 runs");
assert.equal(sort.formatRunCount(1234), "1,234 runs");
});
test("formatRunCount hides the badge for missing or invalid counts", () => {
for (const bad of [undefined, null, -1, 1.5, "3", NaN]) {
assert.equal(sort.formatRunCount(bad), "", String(bad));
}
});
-105
View File
@@ -1,105 +0,0 @@
// Run with: node --test tests/js/
const test = require("node:test");
const assert = require("node:assert/strict");
const {
initialState,
reduceScanEvent,
fromStatus,
dismissAction,
progressLabel,
} = require("../../web/js/scan-progress.js");
test("initialState is idle with zero counts", () => {
assert.deepEqual(initialState(), {
status: "idle", progress: 0, statusText: "", processed: 0, found: 0, added: 0, linked: 0, message: "",
});
});
test("a progress event moves the scan to running and copies the counts", () => {
const before = initialState();
const after = reduceScanEvent(before, {
type: "progress", progress: 42, status: "Processing file 84/200...", processed: 84, found: 12,
});
assert.equal(after.status, "running");
assert.equal(after.progress, 42);
assert.equal(after.statusText, "Processing file 84/200...");
assert.equal(after.processed, 84);
assert.equal(after.found, 12);
assert.equal(before.status, "idle", "reducer must not mutate its input");
});
test("a complete event finishes the scan with the final totals", () => {
const running = reduceScanEvent(initialState(), { type: "progress", progress: 90, status: "x", processed: 9, found: 1 });
const done = reduceScanEvent(running, { type: "complete", processed: 10, found: 3, added: 2, linked: 1 });
assert.equal(done.status, "done");
assert.equal(done.progress, 100);
assert.deepEqual([done.processed, done.found, done.added, done.linked], [10, 3, 2, 1]);
});
test("an error event fails the scan and keeps the server message", () => {
const failed = reduceScanEvent(initialState(), { type: "error", message: "No output directories found." });
assert.equal(failed.status, "failed");
assert.equal(failed.message, "No output directories found.");
});
test("unknown events leave the state untouched", () => {
const state = reduceScanEvent(initialState(), { type: "progress", progress: 5, status: "s", processed: 1, found: 0 });
assert.equal(reduceScanEvent(state, { type: "mystery" }), state);
assert.equal(reduceScanEvent(state, null), state);
});
test("fromStatus rebuilds a running scan from the status endpoint", () => {
const state = fromStatus({
running: true,
last_event: { type: "progress", progress: 30, status: "Processing file 3/10...", processed: 3, found: 1 },
});
assert.equal(state.status, "running");
assert.equal(state.progress, 30);
assert.equal(state.processed, 3);
});
test("fromStatus is idle when nothing is running, even if a last event exists", () => {
assert.equal(fromStatus({ running: false, last_event: { type: "complete", processed: 10 } }).status, "idle");
assert.equal(fromStatus({ running: false, last_event: null }).status, "idle");
assert.equal(fromStatus(null).status, "idle");
});
test("dismissing the modal minimizes a running scan and closes otherwise", () => {
const running = reduceScanEvent(initialState(), { type: "progress", progress: 1, status: "s", processed: 0, found: 0 });
assert.equal(dismissAction(running), "minimize");
assert.equal(dismissAction(initialState()), "close");
assert.equal(dismissAction(reduceScanEvent(running, { type: "complete" })), "close");
});
test("progressLabel summarises a running scan for the minimized pill", () => {
const running = reduceScanEvent(initialState(), { type: "progress", progress: 42, status: "s", processed: 84, found: 12 });
assert.equal(progressLabel(running), "Scanning 42% · 84 files · 12 prompts");
assert.equal(progressLabel(initialState()), "");
});
test('pair totals survive completion and cancellation closes the running state', () => {
const running=reduceScanEvent(initialState(),{type:'progress',progress:30,processed:3});
const done=reduceScanEvent(running,{type:'complete',pairs_added:2,pair_links_added:3,enriched:1,unchanged:4,ambiguous:1,failed:2});
assert.deepEqual([done.pairs_added,done.pair_links_added,done.enriched,done.unchanged,done.ambiguous,done.failed],[2,3,1,4,1,2]);
const cancelled=reduceScanEvent(running,{type:'cancelled',processed:3,pairs_added:1});
assert.equal(cancelled.status,'done');
assert.equal(cancelled.cancelled,true);
assert.equal(cancelled.statusText,'Scan cancelled.');
assert.equal(cancelled.progress,30);
});
test('completion label reports pair enrichment, unresolved work and failures', () => {
const {completionLabel}=require('../../web/js/scan-progress.js');
const state=reduceScanEvent(initialState(),{type:'complete',processed:10,found:8,added:1,linked:2,pairs_added:3,pair_links_added:4,enriched:2,unchanged:1,ambiguous:1,unresolved:2,conflict:1,failed:1});
assert.match(completionLabel(state),/3 new pairs, 4 pair links/);
assert.match(completionLabel(state),/4 need review, 1 failed/);
assert.match(completionLabel({...state,cancelled:true}),/^Scan cancelled!/);
});
test('older servers without pair counts retain a complete readable summary', () => {
const {completionLabel}=require('../../web/js/scan-progress.js');
const state=reduceScanEvent(initialState(),{type:'complete',processed:2,found:1,added:1,linked:0});
assert.match(completionLabel(initialState()),/0 new pairs, 0 pair links; 0 need review, 0 failed/);
assert.match(completionLabel(state),/0 enriched, 0 unchanged/);
assert.equal(fromStatus({running:true,last_event:{type:'unknown'}}).status,'running');
});
-258
View File
@@ -1,258 +0,0 @@
// Run with: node --test tests/js/
const test = require("node:test");
const assert = require("node:assert/strict");
const { parseSseChunk, connect } = require("../../web/js/sse-stream.js");
test("parseSseChunk splits complete events and keeps the unfinished tail", () => {
const { events, rest } = parseSseChunk('data: {"a":1}\n\ndata: {"b":2}\n\ndata: {"c"');
assert.deepEqual(events.map((e) => e.data), ['{"a":1}', '{"b":2}']);
assert.equal(rest, 'data: {"c"');
});
test("parseSseChunk joins multi-line data, reads event names and ignores comments", () => {
const { events, rest } = parseSseChunk(": keep-alive\nevent: progress\ndata: line1\ndata: line2\nid: 7\n\n");
assert.deepEqual(events, [{ event: "progress", data: "line1\nline2" }]);
assert.equal(rest, "");
});
test("parseSseChunk accepts CRLF line endings and a missing space after the colon", () => {
const { events } = parseSseChunk("data:x\r\n\r\ndata: y\r\n\r\n");
assert.deepEqual(events.map((e) => e.data), ["x", "y"]);
});
test("parseSseChunk returns nothing for an empty or whitespace buffer", () => {
assert.deepEqual(parseSseChunk(""), { events: [], rest: "" });
assert.deepEqual(parseSseChunk("\n\n"), { events: [], rest: "" });
});
function streamOf(chunks) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const c of chunks) controller.enqueue(encoder.encode(c));
controller.close();
},
});
}
function until(check, timeoutMs = 500) {
return new Promise((resolve, reject) => {
const started = Date.now();
(function poll() {
if (check()) return resolve();
if (Date.now() - started > timeoutMs) return reject(new Error("timed out"));
setTimeout(poll, 2);
})();
});
}
test("connect POSTs and delivers each event to onmessage, then onclose", async () => {
const seen = [];
let closed = false;
const calls = [];
const fetchImpl = async (url, init) => {
calls.push({ url, init });
return new Response(streamOf(['data: {"n":1}\n\ndata: {"n', '":2}\n\n']), { status: 200 });
};
const source = connect("/prompt_manager/autotag/start?x=1", { method: "POST", fetchImpl });
source.onmessage = (e) => seen.push(JSON.parse(e.data).n);
source.onclose = () => { closed = true; };
await until(() => closed);
assert.deepEqual(seen, [1, 2]);
assert.equal(calls[0].init.method, "POST");
assert.equal(calls[0].url, "/prompt_manager/autotag/start?x=1");
assert.equal(source.readyState, source.CLOSED);
});
test("connect keeps streaming requests under the current proxy mount", async () => {
const previousApiClient = globalThis.ApiClient;
const previousLocation = globalThis.location;
globalThis.ApiClient = require("../../web/js/api-client.js");
globalThis.location = { pathname: "/ComfyBackendDirect/prompt_manager/gallery" };
let requestedUrl;
try {
const source = connect("/prompt_manager/images/generate-thumbnails/progress?quality=80", {
method: "POST",
fetchImpl: async (url) => {
requestedUrl = url;
return new Response(streamOf([]), { status: 200 });
},
});
await until(() => source.readyState === source.CLOSED);
assert.equal(requestedUrl, "/ComfyBackendDirect/prompt_manager/images/generate-thumbnails/progress?quality=80");
} finally {
globalThis.ApiClient = previousApiClient;
globalThis.location = previousLocation;
}
});
test("connect reports a non-2xx response through onerror and never onmessage", async () => {
let error = null;
const fetchImpl = async () => new Response("nope", { status: 405 });
const source = connect("/x", { fetchImpl });
source.onmessage = () => assert.fail("no message expected");
source.onerror = (err) => { error = err; };
await until(() => error !== null);
assert.match(error.message, /405/);
assert.equal(source.readyState, source.CLOSED);
});
test("a non-2xx JSON answer's error sentence reaches onerror as serverMessage", async () => {
let error = null;
const fetchImpl = async () => new Response(
JSON.stringify({ success: false, error: "Auto-tagging is already running" }),
{ status: 409, headers: { "Content-Type": "application/json" } },
);
const source = connect("/x", { fetchImpl });
source.onerror = (err) => { error = err; };
await until(() => error !== null);
assert.match(error.message, /409/);
assert.equal(error.status, 409);
assert.equal(error.serverMessage, "Auto-tagging is already running");
});
test("a non-2xx answer without a JSON error has no serverMessage", async () => {
let error = null;
const fetchImpl = async () => new Response("nope", { status: 500 });
const source = connect("/x", { fetchImpl });
source.onerror = (err) => { error = err; };
await until(() => error !== null);
assert.equal(error.status, 500);
assert.equal(error.serverMessage, undefined);
});
test("connect reports a network failure through onerror", async () => {
let error = null;
const source = connect("/x", { fetchImpl: async () => { throw new TypeError("Failed to fetch"); } });
source.onerror = (err) => { error = err; };
await until(() => error !== null);
assert.equal(error.message, "Failed to fetch");
});
test("close() aborts the request and suppresses later callbacks", async () => {
let aborted = false;
let errors = 0;
const fetchImpl = (url, init) =>
new Promise((resolve, reject) => {
init.signal.addEventListener("abort", () => {
aborted = true;
reject(new DOMException("aborted", "AbortError"));
});
resolve(new Response(new ReadableStream({ start() {} }), { status: 200 }));
});
const source = connect("/x", { fetchImpl });
source.onerror = () => errors++;
await until(() => source.readyState === source.OPEN);
source.close();
assert.equal(aborted, true);
assert.equal(source.readyState, source.CLOSED);
await new Promise((r) => setTimeout(r, 10));
assert.equal(errors, 0);
});
test("connect forwards a request body and an Accept header", async () => {
let init = null;
const fetchImpl = async (_url, i) => { init = i; return new Response(streamOf([]), { status: 200 }); };
const source = connect("/x", { method: "POST", body: '{"a":1}', fetchImpl });
await until(() => source.readyState === source.CLOSED);
assert.equal(init.body, '{"a":1}');
assert.equal(init.headers.Accept, "text/event-stream");
});
test("events arriving with no onmessage handler are dropped without error", async () => {
const fetchImpl = async () => new Response(streamOf(["data: 1\n\n", "data: 2\n\n"]), { status: 200 });
const source = connect("/x", { fetchImpl });
let errors = 0;
source.onerror = () => errors++;
await until(() => source.readyState === source.CLOSED);
assert.equal(errors, 0);
});
test("close() during delivery stops further messages and skips onclose", async () => {
const seen = [];
let closed = false;
const fetchImpl = async () => new Response(streamOf(["data: 1\n\ndata: 2\n\ndata: 3\n\n"]), { status: 200 });
const source = connect("/x", { fetchImpl });
source.onmessage = (e) => { seen.push(e.data); if (e.data === "1") source.close(); };
source.onclose = () => { closed = true; };
await until(() => source.readyState === source.CLOSED);
await new Promise((r) => setTimeout(r, 10));
assert.deepEqual(seen, ["1"]);
assert.equal(closed, false);
});
test("close() before the response arrives discards it silently", async () => {
let resolveFetch;
let errors = 0;
const fetchImpl = () => new Promise((resolve) => { resolveFetch = resolve; });
const source = connect("/x", { fetchImpl });
source.onerror = () => errors++;
source.close();
resolveFetch(new Response(streamOf(["data: late\n\n"]), { status: 200 }));
await new Promise((r) => setTimeout(r, 10));
assert.equal(errors, 0);
assert.equal(source.readyState, source.CLOSED);
});
test("connect defaults to GET and the global fetch", async () => {
const original = globalThis.fetch;
let init = null;
globalThis.fetch = async (_url, i) => { init = i; return new Response(streamOf([]), { status: 200 }); };
try {
const source = connect("/x");
await until(() => source.readyState === source.CLOSED);
assert.equal(init.method, "GET");
} finally {
globalThis.fetch = original;
}
});
test("addEventListener receives named events and unnamed ones go to 'message'", async () => {
const named = [];
const plain = [];
let closed = false;
const fetchImpl = async () =>
new Response(
streamOf(['event: start\ndata: {"total":3}\n\n', 'data: {"n":1}\n\n', 'event: complete\ndata: {"ok":true}\n\n']),
{ status: 200 },
);
const source = connect("/prompt_manager/images/generate-thumbnails/progress", { method: "POST", fetchImpl });
source.addEventListener("start", (e) => named.push(["start", JSON.parse(e.data).total]));
source.addEventListener("complete", (e) => named.push(["complete", JSON.parse(e.data).ok]));
source.addEventListener("message", (e) => plain.push(JSON.parse(e.data).n));
source.onclose = () => { closed = true; };
await until(() => closed);
assert.deepEqual(named, [["start", 3], ["complete", true]]);
assert.deepEqual(plain, [1]);
});
test("removeEventListener stops delivery and onmessage still sees every event", async () => {
const all = [];
const progress = [];
let closed = false;
const fetchImpl = async () =>
new Response(streamOf(["event: progress\ndata: 1\n\n", "event: progress\ndata: 2\n\n"]), { status: 200 });
const source = connect("/x", { fetchImpl });
const listener = (e) => {
progress.push(e.data);
source.removeEventListener("progress", listener);
};
source.addEventListener("progress", listener);
source.onmessage = (e) => all.push(`${e.event}:${e.data}`);
source.onclose = () => { closed = true; };
await until(() => closed);
assert.deepEqual(progress, ["1"]);
assert.deepEqual(all, ["progress:1", "progress:2"]);
});
test("a listener that closes the source stops later events", async () => {
const seen = [];
const fetchImpl = async () =>
new Response(streamOf(["event: error\ndata: boom\n\n", "event: progress\ndata: 2\n\n"]), { status: 200 });
const source = connect("/x", { fetchImpl });
source.addEventListener("error", (e) => { seen.push(e.data); source.close(); });
source.addEventListener("progress", (e) => seen.push(e.data));
await until(() => source.readyState === source.CLOSED);
await new Promise((r) => setTimeout(r, 10));
assert.deepEqual(seen, ["boom"]);
});
-39
View File
@@ -1,39 +0,0 @@
// Run with: node --test tests/js/
const test = require("node:test");
const assert = require("node:assert/strict");
const {
splitTagInput,
applySuggestion,
suggestUrl,
moveSelection,
} = require("../../web/js/tag-autocomplete.js");
test("splitTagInput separates committed tags from the tag being typed", () => {
assert.deepEqual(splitTagInput("asian, portrait, sm"), { committed: ["asian", "portrait"], current: "sm" });
assert.deepEqual(splitTagInput("asian,"), { committed: ["asian"], current: "" });
assert.deepEqual(splitTagInput("asian, "), { committed: ["asian"], current: "" });
assert.deepEqual(splitTagInput("asi"), { committed: [], current: "asi" });
assert.deepEqual(splitTagInput(""), { committed: [], current: "" });
assert.deepEqual(splitTagInput(" asian ,, Asian , dog, "), { committed: ["asian", "dog"], current: "" });
});
test("applySuggestion replaces the partial tag and leaves the cursor ready for the next one", () => {
assert.equal(applySuggestion("asian, sm", "smile"), "asian, smile, ");
assert.equal(applySuggestion("", "asian"), "asian, ");
assert.equal(applySuggestion("asian, ", "portrait"), "asian, portrait, ");
assert.equal(applySuggestion("asian, asi", "asian"), "asian, ");
});
test("suggestUrl encodes the prefix and the committed tags", () => {
assert.equal(suggestUrl("asian, sm"), "/prompt_manager/tags/suggest?q=sm&with=asian&limit=15");
assert.equal(suggestUrl("a&b, c d, x", 5), "/prompt_manager/tags/suggest?q=x&with=a%26b%2Cc+d&limit=5");
assert.equal(suggestUrl(""), "/prompt_manager/tags/suggest?q=&with=&limit=15");
});
test("moveSelection wraps around the list and starts from nothing selected", () => {
assert.equal(moveSelection(-1, 1, 3), 0);
assert.equal(moveSelection(-1, -1, 3), 2);
assert.equal(moveSelection(2, 1, 3), 0);
assert.equal(moveSelection(0, -1, 3), 2);
assert.equal(moveSelection(1, 1, 0), -1);
});
-71
View File
@@ -1,71 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
function fixture() {
const requests = [];
const grid = { replaceChildren() {}, appendChild() {} };
const context = vm.createContext({ window: {}, URLSearchParams, console: { error() {} },
requestAnimationFrame() {}, document: { getElementById: id => id === 'tagPromptsGrid' ? grid : null,
querySelector: () => null, createElement: () => ({ appendChild() {} }) },
});
const Manager = vm.runInContext(fs.readFileSync(path.join(__dirname, '../../web/js/tags-page.js'), 'utf8') + '\nTagsPageManager;', context, { filename: path.join(__dirname, '../../web/js/tags-page.js') });
const manager = Object.create(Manager.prototype);
Object.assign(manager, { selectedTags: ['cats'], filterMode: 'and', promptLimit: 20,
promptOffset: 0, isLoadingPrompts: false, prompts: [], hasMorePrompts: false,
fetchJson(url) { return new Promise((resolve, reject) => requests.push({ url, resolve, reject })); },
renderTagPrompts() {}, appendTagPrompts() {}, updatePromptCountBadge() {}, updateLoadMoreButton() {},
});
const reply = (index, text, more = false) => requests[index].resolve({ success: true,
prompts: [{ text }], pagination: { has_more: more, total: more ? 40 : 1 } });
return { manager, requests, reply };
}
test('changing a filter starts a new request and late results cannot overwrite it', async () => {
const { manager, requests, reply } = fixture();
const old = manager.loadTagPrompts();
manager.selectedTags = ['dogs'];
const current = manager.loadTagPrompts();
assert.equal(requests.length, 2);
assert.match(requests[1].url, /dogs/);
reply(1, 'dog prompt'); await current;
reply(0, 'cat prompt', true); await old;
assert.equal(manager.prompts[0].text, 'dog prompt');
assert.equal(manager.promptTotal, 1);
assert.equal(manager.hasMorePrompts, false);
});
test('clearing selection invalidates pending results', async () => {
const { manager, reply } = fixture();
const old = manager.loadTagPrompts();
manager.selectedTags = [];
manager.clearPrompts();
reply(0, 'cat prompt'); await old;
assert.equal(manager.prompts.length, 0);
assert.equal(manager.promptTotal, 0);
assert.equal(manager.isLoadingPrompts, false);
});
test('a stale pagination response cannot append rows from the previous filter', async () => {
const { manager, requests, reply } = fixture();
Object.assign(manager, { prompts: [{ text: 'cat first page' }], hasMorePrompts: true, promptOffset: 20 });
const old = manager.loadMoreTagPrompts();
manager.selectedTags = ['dogs'];
const current = manager.loadTagPrompts();
assert.equal(requests.length, 2);
reply(1, 'dog prompt'); await current;
reply(0, 'cat second page', true); await old;
assert.equal(manager.prompts.length, 1);
assert.equal(manager.prompts[0].text, 'dog prompt');
assert.equal(manager.promptOffset, 20);
});
test('a stale failure cannot finish the new request or clear its loading state', async () => {
const { manager, requests, reply } = fixture();
const old = manager.loadTagPrompts();
manager.selectedTags = ['dogs'];
const current = manager.loadTagPrompts();
assert.equal(requests.length, 2);
requests[0].reject(new Error('old failure')); await old;
assert.equal(manager.isLoadingPrompts, true);
reply(1, 'dog prompt'); await current;
assert.equal(manager.isLoadingPrompts, false);
assert.equal(manager.prompts[0].text, 'dog prompt');
});
-30
View File
@@ -1,30 +0,0 @@
// Run with: node --test tests/js/
const test = require("node:test");
const assert = require("node:assert/strict");
const { resolveView, VIEWS } = require("../../web/js/view-router.js");
test("the tags deep link and its sub-routes resolve to the tags view", () => {
assert.equal(resolveView("#/tags"), "tags");
assert.equal(resolveView("#/tags/"), "tags");
assert.equal(resolveView("#/tags/landscape,portrait?mode=or"), "tags");
});
test("an empty, bare or unknown hash resolves to the prompts dashboard", () => {
assert.equal(resolveView(""), "prompts");
assert.equal(resolveView("#"), "prompts");
assert.equal(resolveView("#/"), "prompts");
assert.equal(resolveView("#/other"), "prompts");
assert.equal(resolveView("#/tagsX"), "prompts", "prefix must end at a path boundary");
assert.equal(resolveView("#tags"), "prompts");
});
test("non-string input resolves to the prompts dashboard", () => {
assert.equal(resolveView(undefined), "prompts");
assert.equal(resolveView(null), "prompts");
assert.equal(resolveView(42), "prompts");
});
test("every resolved value is a listed view", () => {
assert.ok(Object.isFrozen(VIEWS));
for (const hash of ["#/tags", "", "#/x"]) assert.ok(VIEWS.includes(resolveView(hash)));
});
+20
View File
@@ -248,3 +248,23 @@ test('autotag gets Tagged / Unchanged / Skipped / Errors and Cancel; its legacy
assert.deepEqual([legacy.tiles, legacy.outcomes, [...legacy.openable]], [[], [], []]);
assert.equal(canCancel(held), false);
});
test('a tag search counts the tags found, opens no row and cannot be cancelled (#618)', async () => {
const { kindOf, viewOf, canCancel } = await source;
const { finishToast, startToast, pillParts, outcomeLine } = await store;
const find = job({ kind: 'tag_cleanup', title: 'Find tags to clean up', processed: 0, total: 0, progress: 0,
counters: { found: 0 }, cancellable: false });
const view = kindOf('tag_cleanup');
assert.equal(viewOf(find), view);
assert.deepEqual(view.tiles, [['found', 'Found', '']]);
assert.deepEqual(view.outcomes, [['found', 'Found']]);
assert.deepEqual([...view.openable], []);
assert.equal(view.log, 'Search log');
assert.equal(canCancel(find), false);
assert.equal(pillParts(find).text, 'Finding tags');
assert.equal(startToast(find), 'Tag search started.');
const found = { ...find, state: 'finished', counters: { found: 232 } };
assert.equal(outcomeLine(found), '232 tags found');
assert.equal(finishToast(found), 'Tag search finished · 232 tags found');
assert.equal(finishToast({ ...found, counters: { found: 1 } }), 'Tag search finished · 1 tag found');
});
+12 -7
View File
@@ -293,13 +293,18 @@ test('an empty tag source draws no section', async () => {
try { assert.equal(tagSections(view.f).length, 0); } finally { view.done(); }
});
// LI-4 (D117): "Copy settings summary" after the six facts of the full inspector consolidates the legacy metadata
// page's COPY ALL (web/metadata.html copyAllData). The legacy template is read from that page itself and run on the
// legacy parse, so the summary's text is the legacy page's, line for line, wherever the two agree on the values.
const METADATA_PAGE = fs.readFileSync(new URL('../../web/metadata.html', import.meta.url), 'utf8');
function legacyCopyAll(params) {
const template = METADATA_PAGE.match(/const allData = `([\s\S]*?)`;/)[1];
return new Function('currentWorkflowData', `return \`${template}\`;`)(params);
// LI-4 (D117): "Copy settings summary" after the six facts of the full inspector consolidates the old metadata page's
// COPY ALL. That page is gone (#668); this is its template, copied unchanged from `copyAllData` in web/metadata.html
// as of 3.7.2, and run on the legacy parse, so the summary's text stays the old page's, line for line, wherever the
// two agree on the values.
function legacyCopyAll(currentWorkflowData) {
return `Checkpoint: ${currentWorkflowData.checkpoint || 'Unknown'}
Positive Prompt: ${currentWorkflowData.positivePrompt}
Negative Prompt: ${currentWorkflowData.negativePrompt}
Steps: ${currentWorkflowData.steps || 'Unknown'}
CFG Scale: ${currentWorkflowData.cfgScale || 'Unknown'}
Sampler: ${currentWorkflowData.sampler || 'Unknown'}
Seed: ${currentWorkflowData.seed || 'Unknown'}`;
}
const legacyParams = record => ComfyMetadata.extractGenerationParams({prompt:record.metadata.prompt_graph.status === 'parsed' ? record.metadata.prompt_graph.value : null,
workflow:record.metadata.workflow_graph.status === 'parsed' ? record.metadata.workflow_graph.value : null});
+85
View File
@@ -360,3 +360,88 @@ test('collection links resolve to their id, title Collection, and re-render only
assert.deepEqual(seen,[['collection',3],['collection',4],['saved',undefined],['collection',4]]);
dispose();
});
// #668 (D207): `#/library?tag=…&tag_mode=…` is the shelf with those Tags and that Tag match, and stays the address.
test('a Library link with tags resolves to the shelf with its filter and its canonical hash', async () => {
const { resolveRoute } = await source;
const browse = hash => { const route = resolveRoute(hash); return [route.id, route.browse, route.hash, route.positiveId]; };
assert.deepEqual(browse('#/library?tag=cats&tag=dogs&tag_mode=any'),
['library', { tags: ['cats', 'dogs'], tagMode: 'any' }, '#/library?tag=cats&tag=dogs&tag_mode=any', undefined]);
assert.deepEqual(browse('#/library?tag=cats'), ['library', { tags: ['cats'], tagMode: 'all' }, '#/library?tag=cats', undefined]);
// Canonical: tags in their order, tag_mode left out for All, other keys dropped.
assert.deepEqual(browse('#/library?tag_mode=all&x=1&tag=cats'), ['library', { tags: ['cats'], tagMode: 'all' }, '#/library?tag=cats', undefined]);
assert.deepEqual(browse('#/library?tag_mode=untagged'), ['library', { tags: [], tagMode: 'untagged' }, '#/library?tag_mode=untagged', undefined]);
// One tag per parameter, decoded the standard way, trimmed; empty values and repeats dropped; a comma is part of a name.
assert.deepEqual(resolveRoute('#/library?tag=%20red%20fox+&tag=&tag=a%2Cb&tag=red+fox&tag=%zz').browse,
{ tags: ['red fox', 'a,b', '%zz'], tagMode: 'all' });
// The first tag_mode counts.
assert.deepEqual(browse('#/library?tag_mode=any&tag_mode=all&tag=a&tag=b&sort=name'),
['library', { tags: ['a', 'b'], tagMode: 'any' }, '#/library?tag=a&tag=b&tag_mode=any', undefined]);
});
test('the Library address of a filter is canonical and reads back as the same filter', async () => {
const { libraryLinkHash, libraryLinkFilters, resolveRoute } = await source;
assert.equal(libraryLinkHash({ tags: [], tagMode: 'all' }), '#/library');
assert.equal(libraryLinkHash({}), '#/library');
assert.equal(libraryLinkHash(), '#/library');
// Any of no tags filters nothing.
assert.equal(libraryLinkHash({ tags: [], tagMode: 'any' }), '#/library');
assert.equal(libraryLinkHash({ tags: ['cats'], tagMode: 'all' }), '#/library?tag=cats');
assert.equal(libraryLinkHash({ tags: ['dogs', 'cats'], tagMode: 'any' }), '#/library?tag=dogs&tag=cats&tag_mode=any');
assert.equal(libraryLinkHash({ tags: [], tagMode: 'untagged' }), '#/library?tag_mode=untagged');
// Only tags and the match are in the address.
assert.equal(libraryLinkHash({ tags: ['a'], tagMode: 'all', text: 'fox', category: 'c', folder: 'f', sort: 'name', shelf: 'archived' }), '#/library?tag=a');
for (const filter of [{ tags: ['red fox', 'a,b', '★&=?#', '100%', 'a+b'], tagMode: 'any' }, { tags: ['x'], tagMode: 'all' },
{ tags: ['x'], tagMode: 'any' }, { tags: [], tagMode: 'untagged' }]) {
const hash = libraryLinkHash(filter);
assert.deepEqual(libraryLinkFilters(hash.slice('#/library?'.length)), filter, hash);
assert.deepEqual([resolveRoute(hash).browse, resolveRoute(hash).hash], [filter, hash], hash);
}
});
test('a Library link with nothing to filter is the plain shelf, and an unreadable one says so', async () => {
const { resolveRoute } = await source;
for (const hash of ['#/library?', '#/library?tag=', '#/library?tag_mode=any', '#/library?tag_mode=all', '#/library?other=1']) {
const route = resolveRoute(hash);
assert.deepEqual([route.id, route.browse, route.browseInvalid, route.hash], ['library', undefined, undefined, undefined], hash);
}
for (const hash of ['#/library?tag=a&tag_mode=either', '#/library?tag_mode=', '#/library?tag=a&tag_mode=untagged', '#/library?tag_mode=UNTAGGED']) {
const route = resolveRoute(hash);
assert.deepEqual([route.id, route.browse, route.browseInvalid, route.hash], ['library', undefined, true, undefined], hash);
}
// Only the shelf takes the form: a prompt's own page and other routes do not.
assert.equal(resolveRoute('#/library/7?tag=a').id, 'images');
assert.equal(resolveRoute('#/tags?tag=a').id, 'images');
});
test('the router renders the shelf again when its address filter changes, and keeps the filter in the address', async () => {
const { mountRouter, replaceRouteHash } = await source;
const win = new EventTarget();
win.location = { hash: '#/library' };
const replacements = [];
win.history = { state: null, replaceState(state, unused, hash) { replacements.push(hash); win.location.hash = hash; } };
const seen = [];
const dispose = mountRouter(win, route => seen.push([route.id, route.browse?.tags.join('+'), route.browseInvalid]));
const go = hash => { win.location.hash = hash; win.dispatchEvent(new Event('hashchange')); };
go('#/library?tag=a');
go('#/library?tag=a');
// Another spelling of the same filter is made canonical and is not a new route.
go('#/library?tag_mode=all&tag=a');
go('#/library?tag=a&tag=b');
go('#/library');
go('#/library?tag=a&tag_mode=nope');
go('#/library');
assert.deepEqual(seen, [['library', undefined, undefined], ['library', 'a', undefined], ['library', 'a+b', undefined],
['library', undefined, undefined], ['library', undefined, true]]);
assert.deepEqual(replacements, ['#/library?tag=a', '#/library']);
// The shelf changed its own filter and replaced the address: no render, and the router knows the new address, so
// the plain Library link is a new route afterwards (the filter must not stick).
replaceRouteHash('#/library?tag=z', win);
assert.deepEqual([win.location.hash, replacements.at(-1), seen.length], ['#/library?tag=z', '#/library?tag=z', 5]);
replaceRouteHash('#/library?tag=z', win);
assert.equal(replacements.length, 3, 'the same address is not replaced again');
go('#/library');
assert.deepEqual(seen.at(-1), ['library', undefined, undefined]);
assert.equal(seen.length, 6);
dispose();
});
@@ -137,6 +137,23 @@ test('the import review shows replacement, blocked items and network effects (D1
['Found', '1 metadata file · 1 LoRA · 0 with local images']);
});
test('the import review counts the trained words not made tags, after Found (#618)', async () => {
const { importGrid } = await integrations;
const rowAfterFound = plan => {
const rows = importGrid(plan);
const at = rows.findIndex(([term]) => term === 'Found');
return rows[at + 1];
};
assert.deepEqual(rowAfterFound({ trigger_tags: 1204, trigger_not_tags: 232 }),
['Trigger words', '1,204 become tags · 232 not made tags (lists or sentences)']);
assert.deepEqual(rowAfterFound({ trigger_tags: 3, trigger_not_tags: 0 }), ['Trigger words', '3 become tags']);
assert.deepEqual(rowAfterFound({ trigger_tags: 0, trigger_not_tags: 1 }),
['Trigger words', '0 become tags · 1 not made tags (lists or sentences)']);
// Neither number above 0 (or missing, as from an older server): no row.
assert.deepEqual(rowAfterFound({ trigger_tags: 0, trigger_not_tags: 0 })[0], 'Protected');
assert.deepEqual(rowAfterFound({ trigger_tags: '5', trigger_not_tags: -1 })[0], 'Protected');
});
test('the LoraManager row names what the import read, and an unusable layout closes the review (#355)', async () => {
const { layoutText, closeNote, LAYOUT_UNUSABLE, BLOCKED_NOTE, NOTHING_TO_IMPORT } = await integrations;
assert.equal(layoutText({ source: 'environment', mode: 'alongside', library: 'default', error: null }),
+45 -1
View File
@@ -24,8 +24,42 @@ test('the section lists the concept rows in its order, labels and danger marks',
// D192 (#550, beyond the concept): "Pair category and tags" follows "Unused prompt components" in Database.
const expected = concept.map(([title, ...rest]) => [title.replace('&amp;', '&'), ...rest]);
expected.splice(expected.findIndex(([title]) => title === 'Unused prompt components') + 1, 0, PAIR_ROW);
// D210 (#618, beyond the concept): "Tag cleanup" follows "Pair category and tags".
expected.splice(expected.findIndex(([title]) => title === PAIR_ROW[0]) + 1, 0, TAG_ROW);
assert.deepEqual(production, expected);
assert.equal(production.length, 9);
assert.equal(production.length, 10);
});
const TAG_ROW = Object.freeze(['Tag cleanup', 'Find tags that are whole comma lists or are used nowhere. Review them, then ' +
'remove only what you tick.', 'Find tags', true]);
test('D210: the Tag cleanup row starts the tag search with a danger mark (#618)', async () => {
const { MAINTENANCE_SURFACES, TAG_CLEANUP_KIND } = await maintenance;
const { OPERATION_TITLES } = await review;
const [, database] = MAINTENANCE_SURFACES[0];
const row = database.find(([title]) => title === TAG_ROW[0]);
assert.deepEqual(row, [TAG_ROW[0], TAG_ROW[1], TAG_ROW[2], TAG_CLEANUP_KIND, true]);
assert.equal(TAG_CLEANUP_KIND, 'tag_cleanup');
assert.equal(OPERATION_TITLES.tag_cleanup, 'Tag cleanup');
});
test('startFind opens the started search, toasts a busy start and says when it could not start', async () => {
const { startFind, TAG_FIND_FAILED, FIND_FAILED } = await maintenance;
const scope = { signal: { aborted: false } };
const toasts = [];
const routes = [];
const run = (result, kind = 'tag_cleanup', failed = TAG_FIND_FAILED) => startFind({
store: { start: async started => { assert.equal(started, kind); if (result instanceof Error) throw result; return result; } },
scope, kind, failed, notify: text => toasts.push(text), navigate: route => routes.push(route) });
await run({ job: { id: 'a'.repeat(32) } });
assert.deepEqual(routes, [`#/activity/${'a'.repeat(32)}`]);
await run({ busy: { id: 'b', title: 'Restore database', kind: 'restore' } });
assert.equal(toasts.length, 1);
await run(new Error('offline'));
assert.equal(toasts[1], 'The tag search could not start. Try again.');
await run(new Error('offline'), 'duplicates', FIND_FAILED);
assert.equal(toasts[2], 'The duplicate search could not start. Try again.');
assert.equal(routes.length, 1);
});
const PAIR_ROW = Object.freeze(['Pair category and tags', 'Fill an empty category or tags on prompts older Pair node runs ' +
@@ -173,6 +207,16 @@ test('a failed apply the library overtook offers Review again, back to its revie
assert.equal(reviewAgainOf(failed('maintenance', 'plan-changed', 'not_an_operation')), null);
assert.equal(reviewAgainOf({ ...failed('maintenance', 'plan-changed', 'optimize'), state: 'finished' }), null);
assert.equal(reviewAgainOf(failed('scan', 'plan-changed', 'optimize')), null);
// #618: a Tag cleanup cannot be previewed without its options: search again in Maintenance.
assert.deepEqual(reviewAgainOf(failed('maintenance', 'backup-failed', 'tag_cleanup')), { section: '#/system/maintenance' });
assert.deepEqual(reviewAgainOf(failed('maintenance', undefined, 'tag_cleanup')), { section: '#/system/maintenance' });
});
test('#618: a tag search lists records, not files', async () => {
const { listsRecords } = await jobView;
assert.equal(listsRecords({ kind: 'tag_cleanup', scope: {} }), true);
assert.equal(listsRecords({ kind: 'maintenance', scope: { operation: 'tag_cleanup' } }), true);
assert.equal(listsRecords({ kind: 'duplicates', scope: {} }), false);
});
test('a plan with nothing to do offers no Apply (S7 live test)', async () => {
@@ -0,0 +1,82 @@
// Tag cleanup review (#618, D210): the dialog draws whatever rules the findings route returns; its selection is one
// set of tag ids per rule, nothing ticked at first, and Review cleanup sends exactly the ticked ids per rule.
const test = require('node:test');
const assert = require('node:assert/strict');
const review = import('../../web/js/workspace/tag-cleanup-review.mjs');
const RULES = Object.freeze([
{ id: 'comma', title: 'Tags containing a comma', explanation: 'A whole list saved as one tag.',
action_label: 'Removes the tag and deletes it.', total: 3,
findings: [{ tag_id: 4, name: 'a, b', detail: '3 prompts · 1 pair' }, { tag_id: 9, name: 'c, d', detail: 'no links' },
{ tag_id: 2, name: 'x,y', detail: '1 prompt' }] },
{ id: 'unused', title: 'Tags with no links', explanation: 'No prompt, saved pair or image carries the tag.',
action_label: 'Deletes the tag.', total: 2501, findings: [{ tag_id: 7, name: 'ghost', detail: 'no links' }] },
{ id: 'later', title: 'A later rule', explanation: 'x', action_label: 'y', total: 0, findings: [] },
]);
test('nothing is ticked at first; only rules with findings are drawn', async () => {
const { createSelection, selectedCount, statusText, shownRules } = await review;
const selection = createSelection(RULES);
assert.equal(selectedCount(selection), 0);
assert.equal(statusText(0), '0 tags selected');
assert.equal(statusText(1), '1 tag selected');
assert.equal(statusText(1204), '1,204 tags selected');
assert.deepEqual(shownRules(RULES).map(rule => rule.id), ['comma', 'unused']);
assert.deepEqual(shownRules(null), []);
});
test('a rule tick ticks every listed tag of the rule and clears them; single ticks make it indeterminate', async () => {
const { createSelection, ruleState, toggleRule, toggleTag, selectedCount, isTicked } = await review;
const selection = createSelection(RULES);
assert.equal(ruleState(selection, 'comma'), 'none');
toggleRule(selection, 'comma', true);
assert.equal(ruleState(selection, 'comma'), 'all');
assert.equal(selectedCount(selection), 3);
assert.equal(ruleState(selection, 'unused'), 'none');
toggleTag(selection, 'comma', 9, false);
assert.equal(ruleState(selection, 'comma'), 'some');
assert.equal(isTicked(selection, 'comma', 9), false);
assert.equal(isTicked(selection, 'comma', 4), true);
toggleRule(selection, 'comma', false);
assert.equal(ruleState(selection, 'comma'), 'none');
assert.equal(selectedCount(selection), 0);
toggleTag(selection, 'unused', 7, true);
assert.equal(ruleState(selection, 'unused'), 'all');
// An id the rule did not list is never ticked.
toggleTag(selection, 'unused', 999, true);
assert.equal(selectedCount(selection), 1);
});
test('the select payload names each ticked rule once, in registry order, with its ticked ids', async () => {
const { createSelection, toggleRule, toggleTag, selectPayload } = await review;
const selection = createSelection(RULES);
assert.deepEqual(selectPayload(selection), []);
toggleTag(selection, 'unused', 7, true);
toggleTag(selection, 'comma', 2, true);
toggleTag(selection, 'comma', 4, true);
assert.deepEqual(selectPayload(selection), [{ rule: 'comma', tag_ids: [4, 2] }, { rule: 'unused', tag_ids: [7] }]);
toggleRule(selection, 'comma', false);
assert.deepEqual(selectPayload(selection), [{ rule: 'unused', tag_ids: [7] }]);
});
test('labels: the rule with its total, a finding with its detail, the cap note only when the cap cut the list', async () => {
const { ruleLabel, findingLabel, ruleText, capNote, CAP_NOTE } = await review;
assert.equal(ruleLabel(RULES[1]), 'Tags with no links (2,501)');
assert.equal(findingLabel(RULES[0].findings[0]), 'a, b · 3 prompts · 1 pair');
assert.equal(findingLabel({ name: 'ghost' }), 'ghost');
assert.equal(ruleText(RULES[1]), 'No prompt, saved pair or image carries the tag. Deletes the tag.');
assert.equal(capNote(RULES[0]), null);
assert.equal(capNote(RULES[1]), CAP_NOTE);
assert.equal(CAP_NOTE, 'Only the first 2,000 are listed. Clean these up, then search again.');
});
test('only a finished tag search that found tags offers Review tags', async () => {
const { hasTagFindings } = await review;
const job = (state, found, kind = 'tag_cleanup') => ({ kind, state, counters: { found } });
assert.equal(hasTagFindings(job('finished', 3)), true);
assert.equal(hasTagFindings(job('finished', 0)), false);
assert.equal(hasTagFindings(job('running', 3)), false);
assert.equal(hasTagFindings(job('finished', 3, 'duplicates')), false);
assert.equal(hasTagFindings({ kind: 'tag_cleanup', state: 'finished' }), false);
});
+34
View File
@@ -34,9 +34,12 @@ from aiohttp.test_utils import AioHTTPTestCase # noqa: E402
from database.operations import PromptDatabase # noqa: E402
from py.api import PromptManagerAPI # noqa: E402
from py.config import GalleryConfig, PromptManagerConfig # noqa: E402
from utils import media_formats # noqa: E402
CONFIG_PATH_ENV = "PROMPT_MANAGER_CONFIG_PATH"
EXTRA_ROOTS_ENV = "PROMPT_MANAGER_EXTRA_GALLERY_ROOTS"
AVIF_FIXTURE = Path(__file__).parent / "fixtures" / "media" / "comfyui_avif.avif"
AVIF_READABLE = media_formats.avif_supported()
class AdminAPITestCase(AioHTTPTestCase):
@@ -517,6 +520,37 @@ class TestScansRunOffTheEventLoop(AdminAPITestCase):
self.assertEqual(len(pairs), 1)
self.assertEqual(pairs[0]["negative_text"], "bad")
@unittest.skipUnless(AVIF_READABLE, "Pillow here cannot decode AVIF")
async def test_output_scan_collects_and_links_an_avif(self):
"""#652: SaveImageAdvanced's AVIF links to its prompt like a PNG."""
shutil.copyfile(AVIF_FIXTURE, self.output_dir / "gen.avif")
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.output_dir)]
resp = await self.client.request("POST", "/prompt_manager/scan")
body = await resp.text()
self.assertEqual(resp.status, 200)
self.assertIn('"added": 1', body)
prompts = self.api.db.get_recent_prompts(limit=10)["prompts"]
self.assertEqual({p["text"] for p in prompts}, {"a small avif fixture", "bad"})
pairs = self.api.db.list_prompt_pairs()["pairs"]
self.assertEqual(len(pairs), 1)
self.assertEqual(pairs[0]["negative_text"], "bad")
async def test_output_scan_skips_an_avif_pillow_cannot_read(self):
"""#652: a Pillow without AVIF leaves the file alone, quietly."""
shutil.copyfile(AVIF_FIXTURE, self.output_dir / "gen.avif")
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.output_dir)]
with patch.object(media_formats, "avif_supported", return_value=False):
resp = await self.client.request("POST", "/prompt_manager/scan")
body = await resp.text()
self.assertEqual(resp.status, 200)
self.assertIn('"added": 0', body)
self.assertIn('"found": 0', body)
self.assertEqual(self.api.db.get_recent_prompts(limit=10)["prompts"], [])
async def test_output_scan_without_directories_reports_error(self):
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.outside_dir)]
sys.modules.pop("folder_paths", None)
+64 -15
View File
@@ -396,13 +396,18 @@ class CoreRoutesTestCase(AioHTTPTestCase):
return web_dir
# Pages read from web/: the workspace, the /web redirect page and the page that
# sends an old /admin bookmark on (#668).
UI_PATHS = (
"/prompt_manager/workspace",
"/prompt_manager/web",
"/prompt_manager/gallery.html",
"/prompt_manager/admin",
"/prompt_manager/gallery",
)
# The old gallery and metadata pages (#668, D207): where each URL lands now.
OLD_PAGE_REDIRECTS = {
"/prompt_manager/gallery": "workspace#/images",
"/prompt_manager/gallery.html": "workspace#/inspect",
}
class TestUiRoutes(CoreRoutesTestCase):
@@ -416,10 +421,60 @@ class TestUiRoutes(CoreRoutesTestCase):
async def test_pages_are_cached_after_first_read(self):
await self.client.request("GET", "/prompt_manager/admin")
self.assertTrue(any(p.endswith("admin.html") for p in self.api._html_cache))
self.assertTrue(
any(p.endswith("admin-redirect.html") for p in self.api._html_cache)
)
resp = await self.client.request("GET", "/prompt_manager/admin")
self.assertEqual(resp.status, 200)
async def test_old_admin_url_serves_the_page_that_maps_its_hash(self):
"""The server never sees ``#/tags/a,b``, so the browser maps it."""
resp = await self.client.request(
"GET", "/prompt_manager/admin", allow_redirects=False
)
self.assertEqual(resp.status, 200)
html = await resp.text()
self.assertIn('<script src="js/legacy-links.js"></script>', html)
self.assertIn('href="workspace#/library"', html)
self.assertNotIn("js/admin.js", html)
module = await self.client.request("GET", "/prompt_manager/js/legacy-links.js")
self.assertEqual(module.status, 200)
async def test_old_gallery_urls_redirect_into_the_workspace(self):
for path, target in OLD_PAGE_REDIRECTS.items():
for method in ("GET", "HEAD"):
resp = await self.client.request(method, path, allow_redirects=False)
self.assertEqual(resp.status, 302, path)
# Relative, so the browser keeps a reverse-proxy mount prefix;
# temporary, so no browser stores it for good.
self.assertEqual(resp.headers["Location"], target, path)
self.assertNotIn("Cache-Control", resp.headers, path)
followed = await self.client.request("GET", "/prompt_manager/gallery")
self.assertEqual(followed.status, 200)
self.assertEqual(followed.url.path, "/prompt_manager/workspace")
self.assertIn("js/workspace/index.mjs", await followed.text())
async def test_the_old_pages_and_their_assets_are_gone(self):
for asset in (
"js/admin.js",
"js/gallery.js",
"js/tags-page.js",
"lib/tailwind/styles.css",
):
resp = await self.client.request("GET", f"/prompt_manager/{asset}")
self.assertEqual(resp.status, 404, asset)
web_dir = Path(api_module._get_project_root()) / "web"
self.assertEqual(
sorted(page.name for page in web_dir.glob("*.html")),
["admin-redirect.html", "index.html", "workspace.html"],
)
async def test_old_gallery_urls_redirect_without_reading_a_page(self):
self._fake_root()
for path, target in OLD_PAGE_REDIRECTS.items():
resp = await self.client.request("GET", path, allow_redirects=False)
self.assertEqual((resp.status, resp.headers["Location"]), (302, target))
async def test_missing_pages_are_404(self):
self._fake_root()
for path in UI_PATHS:
@@ -428,13 +483,7 @@ class TestUiRoutes(CoreRoutesTestCase):
async def test_unreadable_pages_are_500(self):
web_dir = self._fake_root()
for name in (
"workspace.html",
"index.html",
"metadata.html",
"admin.html",
"gallery.html",
):
for name in ("workspace.html", "index.html", "admin-redirect.html"):
(web_dir / name).mkdir() # a directory cannot be read as a file
for path in UI_PATHS:
resp = await self.client.request("GET", path)
@@ -485,7 +534,7 @@ class TestUiRoutes(CoreRoutesTestCase):
class TestStaticRoutes(CoreRoutesTestCase):
async def test_js_served_with_mime(self):
resp = await self.client.request("GET", "/prompt_manager/js/admin.js")
resp = await self.client.request("GET", "/prompt_manager/js/api-client.js")
self.assertEqual(resp.status, 200)
self.assertIn("application/javascript", resp.headers["Content-Type"])
@@ -651,7 +700,7 @@ class TestStaticRoutes(CoreRoutesTestCase):
self.assertEqual(resp.status, 404)
async def test_root_of_static_dir_is_not_listed(self):
resp = await self.client.request("GET", "/prompt_manager/lib/tailwind")
resp = await self.client.request("GET", "/prompt_manager/lib/viewerjs")
self.assertEqual(resp.status, 403)
@@ -665,7 +714,7 @@ class TestRevalidatedCaching(CoreRoutesTestCase):
STATIC_PATHS = (
"/prompt_manager/js/workspace/index.mjs",
"/prompt_manager/js/admin.js",
"/prompt_manager/js/api-client.js",
"/prompt_manager/js/inspection-semantics.json",
"/prompt_manager/lib/viewerjs/viewer.min.css",
)
@@ -725,7 +774,7 @@ class TestRevalidatedCaching(CoreRoutesTestCase):
async def test_gzipped_and_plain_bodies_share_a_weak_etag(self):
"""The gzip middleware changes the bytes, so the tag must be weak."""
resp = await self.client.request("GET", "/prompt_manager/js/admin.js")
resp = await self.client.request("GET", "/prompt_manager/js/api-client.js")
self.assertTrue(resp.headers["ETag"].startswith('W/"'))
async def test_errors_carry_no_validator(self):
@@ -759,7 +808,7 @@ class TestRevalidatedCachingBehindMiddlewares(CoreRoutesTestCase):
async def test_gzipped_files_keep_no_cache_and_answer_304(self):
for path in (
"/prompt_manager/js/workspace/index.mjs",
"/prompt_manager/js/admin.js",
"/prompt_manager/js/api-client.js",
"/prompt_manager/lib/viewerjs/viewer.min.css",
"/prompt_manager/workspace",
):
+2 -1
View File
@@ -1109,7 +1109,8 @@ class TestBulkRoutes(RouteCoverageCase):
self.assertEqual(self.api.db.get_prompt_by_id(ids[0])["category"], "Sea")
async def test_bulk_set_category_keeps_the_legacy_admin_request(self):
# web/js/admin.js posts parseInt ids and a trimmed, non-empty category.
# The old admin page (removed in #668) posted parseInt ids and a trimmed,
# non-empty category; the route still takes that request.
ids = [self._save_prompt(f"bulk cat legacy {i}") for i in range(3)]
status, data = await self._set_category(
{"prompt_ids": ids, "category": "Portraits"}
+369
View File
@@ -0,0 +1,369 @@
"""Tag cleanup routes (#618, ``py/api/tag_cleanup.py``).
``POST /prompt_manager/jobs/tag_cleanup`` finds tags to clean up as a ``read``
Activity job; ``GET /prompt_manager/maintenance/tag_cleanup/{job_id}`` answers
every rule with the findings it holds; ``tag_cleanup`` previews the ticked
findings as a reviewed plan whose apply always takes a safety backup first,
whatever the setting, then deletes each target that is unchanged and keeps,
with its reason, each one that changed.
"""
import asyncio
import json
import os
try:
from tests.test_api_maintenance import APPLY, WAIT, ApplyTestCase
except ImportError: # discovered with tests/ as the top-level directory
from test_api_maintenance import APPLY, WAIT, ApplyTestCase
from py.config import PromptManagerConfig # noqa: E402
FIND = "/prompt_manager/jobs/tag_cleanup"
FINDINGS = "/prompt_manager/maintenance/tag_cleanup/"
class TagCleanupTestCase(ApplyTestCase):
def tags(self, *names):
with self.api.db.model.get_connection() as conn:
for name in names:
conn.execute("INSERT INTO tags(name) VALUES(?)", (name,))
def names(self):
with self.api.db.model.get_connection() as conn:
return sorted(r[0] for r in conn.execute("SELECT name FROM tags"))
def seed(self):
"""Two comma tags (one on a prompt), two unused, one clean in use."""
self.save("Owner", tags=["a, b", "clean"])
self.tags("x,y", "ghost", "spirit")
async def find(self):
response = await self.client.request("POST", FIND)
text = await response.text()
self.assertEqual(response.status, 202, text)
job = self.api._jobs.get(json.loads(text)["job"]["id"])
await asyncio.wait_for(asyncio.shield(job.task), WAIT)
return job
async def findings(self, job_id, status=200):
response = await self.client.request("GET", f"{FINDINGS}{job_id}")
text = await response.text()
self.assertEqual(response.status, status, text)
self.assertNotIn(self.tmpdir, text)
if status == 200:
self.assertEqual(response.headers.get("Cache-Control"), "no-store")
return json.loads(text)
async def select(self, job, **by_rule):
"""The preview body selecting every finding of the named rules."""
body = await self.findings(job.id)
rules = {rule["id"]: rule for rule in body["rules"]}
return {
"job_id": job.id,
"select": [
{
"rule": rule,
"tag_ids": [f["tag_id"] for f in rules[rule]["findings"]],
}
for rule in by_rule
],
}
async def plan(self, options, status=200):
return await self.preview("tag_cleanup", status=status, options=options)
class TestFindJob(TagCleanupTestCase):
async def test_find_is_a_read_job_that_records_one_row_per_tag(self):
self.seed()
job = await self.find()
self.assertEqual(
(job.kind, job.title, job.admission, job.cancellable),
("tag_cleanup", "Find tags to clean up", "read", False),
)
self.assertEqual(job.state, "finished", job.log)
self.assertEqual(job.counters, {"found": 4})
self.assertEqual(
[row["detail"] for row in job.outcomes["found"]],
[
"a, b · Tags containing a comma",
"x,y · Tags containing a comma",
"ghost · Tags with no links",
"spirit · Tags with no links",
],
)
self.assertEqual(job.status_line, "Found 4 tags to clean up")
self.assertIn(job.id, self.api._tag_cleanup_finds)
async def test_a_clean_library_finds_nothing(self):
self.save("Owner", tags=["clean"])
job = await self.find()
self.assertEqual(job.counters, {"found": 0})
self.assertEqual(job.status_line, "No tags need cleaning up")
async def test_a_failed_search_says_so_and_holds_nothing(self):
from database import tag_cleanup
original = tag_cleanup.find_tag_cleanup
tag_cleanup.find_tag_cleanup = lambda path: 1 / 0
try:
job = await self.find()
finally:
tag_cleanup.find_tag_cleanup = original
self.assertEqual(job.state, "failed")
self.assertEqual(job.status_line, "The tag search failed.")
body = await self.findings(job.id, status=409)
self.assertEqual(body["code"], "no-groups")
async def test_a_second_find_while_one_runs_is_busy(self):
gate = asyncio.Event()
async def hold(job, db):
await gate.wait()
self.api._run_tag_cleanup_find = hold
response = await self.client.request("POST", FIND)
self.assertEqual(response.status, 202)
first = (await response.json())["job"]["id"]
response = await self.client.request("POST", FIND)
body = await response.json()
self.assertEqual((response.status, body["code"]), (409, "busy"))
reply = await self.findings(first, status=409)
self.assertEqual(reply["code"], "job-running")
gate.set()
await asyncio.wait_for(asyncio.shield(self.api._jobs.get(first).task), WAIT)
async def test_only_the_last_three_finds_are_held(self):
jobs = [await self.find() for _ in range(4)]
self.assertEqual(list(self.api._tag_cleanup_finds), [j.id for j in jobs[1:]])
body = await self.findings(jobs[0].id, status=404)
self.assertEqual(body["code"], "not-found")
class TestFindingsRoute(TagCleanupTestCase):
async def test_findings_list_every_rule_with_its_copy(self):
self.seed()
job = await self.find()
body = await self.findings(job.id)
self.assertTrue(body["success"])
self.assertEqual(body["job"], {"id": job.id, "state": "finished"})
comma, unused = body["rules"]
self.assertEqual(
{k: comma[k] for k in ("id", "title", "total")},
{"id": "comma", "title": "Tags containing a comma", "total": 2},
)
self.assertTrue(comma["explanation"] and comma["action_label"])
self.assertEqual(
[(f["name"], f["detail"]) for f in comma["findings"]],
[("a, b", "1 prompt"), ("x,y", "no links")],
)
self.assertEqual(set(comma["findings"][0]), {"tag_id", "name", "detail"})
self.assertEqual([f["name"] for f in unused["findings"]], ["ghost", "spirit"])
async def test_the_total_says_when_the_cap_cut_the_list(self):
from database import tag_cleanup
self.tags("a", "b", "c")
original = tag_cleanup.MAX_FINDINGS
tag_cleanup.MAX_FINDINGS = 2
try:
job = await self.find()
finally:
tag_cleanup.MAX_FINDINGS = original
unused = (await self.findings(job.id))["rules"][1]
self.assertEqual((unused["total"], len(unused["findings"])), (3, 2))
async def test_unknown_jobs_are_not_found(self):
self.assertEqual((await self.findings("nope", status=404))["code"], "not-found")
other = self.api._jobs.start(
"health", "Health", admission="read", runner=lambda job: asyncio.sleep(0)
)
await other.task
self.assertEqual(
(await self.findings(other.id, status=404))["code"], "not-found"
)
class TestPreview(TagCleanupTestCase):
async def test_the_plan_names_scope_protection_and_a_required_backup(self):
self.seed()
job = await self.find()
PromptManagerConfig.SAFETY_BACKUP = False
plan = await self.plan(await self.select(job, comma=True))
self.assertEqual(plan["operation"], "tag_cleanup")
self.assertEqual(
plan["scope"],
{
"count": 2,
"label": "Delete 2 tags (removed from 1 prompt, 0 pairs and 0 images)",
},
)
self.assertEqual(plan["protected"], {"count": 0, "reasons": []})
self.assertEqual(plan["backup"]["policy"], "required")
self.assertEqual(
plan["backup"]["destination_label"], "prompts.db.backup_<date and time>"
)
self.assertEqual(plan["backup"]["expected_bytes"], self.database_bytes())
self.assertEqual(
plan["media"], {"deletes_files": False, "label": "No files are removed"}
)
self.assertEqual(
[(d["label"], d["detail"]) for d in plan["details"]],
[
("a, b", "Tags containing a comma · 1 prompt"),
("x,y", "Tags containing a comma · no links"),
],
)
self.assertNotIn('"links"', json.dumps(plan)) # the hash stays server-side
async def test_every_bad_shape_is_invalid(self):
self.seed()
job = await self.find()
good = await self.select(job, comma=True)
comma_ids = good["select"][0]["tag_ids"]
cases = [
[],
{},
{"job_id": job.id},
{**good, "extra": 1},
{**good, "job_id": ""},
{**good, "job_id": 3},
{**good, "job_id": "x" * 65},
{**good, "select": []},
{**good, "select": "comma"},
{**good, "select": [good["select"][0]] * 2},
{**good, "select": [{"rule": "reboot", "tag_ids": comma_ids}]},
{**good, "select": [{"rule": "comma"}]},
{**good, "select": [{"rule": "comma", "tag_ids": comma_ids, "x": 1}]},
{**good, "select": [{"rule": "comma", "tag_ids": []}]},
{**good, "select": [{"rule": "comma", "tag_ids": [True]}]},
{**good, "select": [{"rule": "comma", "tag_ids": ["1"]}]},
{**good, "select": [{"rule": "comma", "tag_ids": [0]}]},
{**good, "select": [{"rule": "comma", "tag_ids": comma_ids * 2}]},
# A tag the search listed under the other rule.
{**good, "select": [{"rule": "unused", "tag_ids": comma_ids}]},
{**good, "select": [{"rule": "comma", "tag_ids": [999999]}]},
{**good, "select": [{"rule": "comma", "tag_ids": list(range(1, 2002))}]},
{**good, "select": [{"rule": "comma", "tag_ids": comma_ids}] * 3},
]
for options in cases:
with self.subTest(options=options):
body = await self.plan(options, status=400)
self.assertEqual(body["code"], "invalid-request")
async def test_a_held_find_is_needed(self):
self.seed()
options = {"job_id": "nope", "select": [{"rule": "comma", "tag_ids": [1]}]}
self.assertEqual((await self.plan(options, status=404))["code"], "not-found")
async def test_hundreds_of_ids_are_not_too_large(self):
self.tags(*(f"tag {n:04}" for n in range(500)))
job = await self.find()
plan = await self.plan(await self.select(job, unused=True))
self.assertEqual(plan["scope"]["count"], 500)
async def test_a_finding_changed_since_the_search_is_protected(self):
self.seed()
job = await self.find()
options = await self.select(job, unused=True)
with self.api.db.model.get_connection() as conn:
conn.execute("UPDATE tags SET name='Ghost' WHERE name='ghost'")
plan = await self.plan(options)
self.assertEqual(
plan["protected"],
{"count": 1, "reasons": ["1 tag changed since the search"]},
)
self.assertEqual(plan["scope"]["count"], 1)
class TestApply(TagCleanupTestCase):
async def run_plan(self, options):
plan = await self.plan(options)
body = await self.post(APPLY, {"token": plan["token"]}, 202)
job = self.api._jobs.get(body["job"]["id"])
await asyncio.wait_for(asyncio.shield(job.task), WAIT)
return plan, job
async def test_apply_takes_a_backup_even_with_the_setting_off(self):
self.seed()
find = await self.find()
PromptManagerConfig.SAFETY_BACKUP = False
plan, job = await self.run_plan(await self.select(find, comma=True))
self.assertEqual(
(job.kind, job.title, job.admission, job.cancellable),
("maintenance", "Tag cleanup", "records", False),
)
self.assertEqual(job.state, "finished", job.log)
[backup] = self.backups()
self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, backup)))
self.assertEqual(job.counters, {"changed": 2, "protected": 0, "errors": 0})
self.assertEqual(job.status_line, f"Deleted 2 tags · Safety backup {backup}")
self.assertEqual(
[row["detail"] for row in job.complete["changed"]],
[
"Deleted tag “a, b” (Tags containing a comma) · removed from 1 prompt",
"Deleted tag “x,y” (Tags containing a comma)",
],
)
# Applying one rule leaves the other rule's tags.
self.assertEqual(self.names(), ["clean", "ghost", "spirit"])
self.assertEqual(self.api.db.search_prompts()[0]["tags"], ["clean"])
async def test_changed_targets_are_kept_one_by_one_and_the_rest_apply(self):
self.seed()
find = await self.find()
plan = await self.plan(await self.select(find, unused=True))
with self.api.db.model.get_connection() as conn:
conn.execute("DELETE FROM tags WHERE name='spirit'")
body = await self.post(APPLY, {"token": plan["token"]}, 202)
job = self.api._jobs.get(body["job"]["id"])
await asyncio.wait_for(asyncio.shield(job.task), WAIT)
self.assertEqual(job.state, "finished", job.log)
self.assertEqual(job.counters, {"changed": 1, "protected": 1, "errors": 0})
self.assertEqual(
[row["detail"] for row in job.complete["protected"]],
["Kept tag “spirit”: already deleted"],
)
self.assertEqual(self.names(), ["a, b", "clean", "x,y"])
async def test_findings_protected_at_review_are_in_the_job(self):
self.seed()
find = await self.find()
options = await self.select(find, unused=True)
with self.api.db.model.get_connection() as conn:
conn.execute("UPDATE tags SET name='Ghost' WHERE name='ghost'")
_plan, job = await self.run_plan(options)
self.assertEqual(job.counters["protected"], 1)
self.assertEqual(
[row["detail"] for row in job.complete["protected"]],
["Kept tag “ghost”: changed since the search"],
)
async def test_a_plan_applies_once_and_expires(self):
self.seed()
find = await self.find()
plan, _job = await self.run_plan(await self.select(find, comma=True))
used = await self.post(APPLY, {"token": plan["token"]}, 409)
self.assertEqual(used["code"], "plan-used")
expired = await self.post(APPLY, {"token": "f" * 32}, 410)
self.assertEqual(expired["code"], "plan-expired")
async def test_a_failed_job_offers_the_maintenance_section(self):
self.seed()
find = await self.find()
plan = await self.plan(await self.select(find, comma=True))
self.api.db.apply_maintenance = lambda *args: 1 / 0
body = await self.post(APPLY, {"token": plan["token"]}, 202)
job = self.api._jobs.get(body["job"]["id"])
await asyncio.wait_for(asyncio.shield(job.task), WAIT)
self.assertEqual(job.state, "failed")
self.assertEqual(job.status_line, "Maintenance failed; nothing was changed.")
self.assertEqual(job.scope["operation"], "tag_cleanup")
self.assertIn("a, b", self.names())
class TestOperationEnum(TagCleanupTestCase):
async def test_the_operation_error_names_tag_cleanup(self):
body = await self.preview("reboot", status=400)
self.assertIn("tag_cleanup", body["error"])
+39
View File
@@ -244,6 +244,45 @@ class TestMarker(unittest.TestCase):
self.assertTrue(os.path.exists(lock)) # never taken from its holder
self.assertEqual(pl.read_marker(self.folder)["keys"], {})
def _denying_open(self, refusals):
"""``os.open`` that answers the lock's exclusive create with
PermissionError *refusals* times, as Windows does while the name is
delete-pending (#674); every other open is the real one."""
real_open, calls = os.open, []
def fake(path, flags, *args, **kwargs):
if str(path).endswith(pl.MARKER_LOCK_NAME) and flags & os.O_EXCL:
calls.append(path)
if len(calls) <= refusals:
raise PermissionError(13, "Permission denied", str(path))
return real_open(path, flags, *args, **kwargs)
return fake, calls
def test_a_lock_name_being_deleted_is_waited_out(self):
# #674: on Windows a lock another writer just unlinked can stay
# delete-pending for a moment; creating it then answers "access
# denied", not "exists". The writer waits and tries again.
pl.init_folder(self.folder)
fake, calls = self._denying_open(3)
with patch.object(pl.os, "open", fake):
pl.write_marker(self.folder, lambda m: m["keys"].update({"a-0123abcd": {}}))
self.assertEqual(len(calls), 4)
self.assertIn("a-0123abcd", pl.read_marker(self.folder)["keys"])
self.assertEqual(os.listdir(self.folder), [pl.MARKER_NAME])
def test_a_lock_that_stays_denied_reports_the_permission_error(self):
# A folder this install really cannot write keeps its own error
# (never a misleading "locked" timeout), and nothing is written.
pl.init_folder(self.folder)
fake, calls = self._denying_open(10**6)
with patch.object(pl.os, "open", fake):
with patch.object(pl, "MARKER_LOCK_TIMEOUT", 0.05):
with self.assertRaises(PermissionError):
pl.write_marker(self.folder, lambda m: m["keys"].update({"x": {}}))
self.assertGreater(len(calls), 1)
self.assertEqual(pl.read_marker(self.folder)["keys"], {})
def test_a_folder_without_the_marker_is_missing(self):
self.assertEqual(pl.folder_state(self.folder, "x")[:2], (False, "missing"))
missing = os.path.join(self.folder, "gone")
+217
View File
@@ -0,0 +1,217 @@
"""AVIF is a media type the library collects (#652).
Every file-type list names ``.avif``; only the collection points ask Pillow
(``utils.media_formats.collectable``), so an install whose Pillow cannot
decode AVIF behaves as it did before. The fixture is what ComfyUI's own
``SaveImageAdvanced`` writes (``tools/make_avif_fixture.py``): a still AVIF
whose EXIF item carries the ``prompt`` and ``workflow`` records.
The "Pillow cannot read it" cases patch ``avif_supported`` and run everywhere;
the "Pillow reads it" cases open the fixture and are skipped on a Pillow
built without an AVIF decoder.
"""
import os
import shutil
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
try:
from host_stubs import install_folder_paths_stub
except ImportError: # imported as tests.test_avif_media_type
from tests.host_stubs import install_folder_paths_stub
install_folder_paths_stub()
sys.modules.setdefault("server", MagicMock())
from py.api import images as images_module # noqa: E402
from py.api.autotag_routes import AutotagRoutesMixin # noqa: E402
from py.api.inspection_service import SERVABLE_EXTENSIONS # noqa: E402
from py.api.thumbnail_settings import CONTENT_TYPES # noqa: E402
from utils import media_capture, media_formats # noqa: E402
from utils.image_monitor import ImageGenerationHandler # noqa: E402
FIXTURE = Path(__file__).parent / "fixtures" / "media" / "comfyui_avif.avif"
AVIF_READABLE = media_formats.avif_supported()
class TestMediaFormats(unittest.TestCase):
"""The one runtime answer every collection point asks."""
def test_avif_supported_asks_pillow(self):
with patch("PIL.features.check", return_value=True) as check:
self.assertTrue(media_formats.avif_supported())
check.assert_called_with("avif")
with patch("PIL.features.check", return_value=False):
self.assertFalse(media_formats.avif_supported())
def test_collectable_gates_only_avif(self):
with patch.object(media_formats, "avif_supported", return_value=False):
self.assertFalse(media_formats.collectable(".avif"))
self.assertFalse(media_formats.collectable(".AVIF"))
self.assertTrue(media_formats.collectable(".png"))
self.assertTrue(media_formats.collectable(".webp"))
self.assertTrue(media_formats.collectable(".gif"))
with patch.object(media_formats, "avif_supported", return_value=True):
self.assertTrue(media_formats.collectable(".avif"))
class TestGalleryWalk(unittest.TestCase):
"""The gallery and thumbnail walks list AVIF only where it can be read."""
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.tmpdir, True)
shutil.copyfile(FIXTURE, os.path.join(self.tmpdir, "gen.avif"))
def _walked(self):
return [
Path(entry.path).name
for entry in images_module._walk_media(self.tmpdir, 10)
]
def test_the_walk_lists_avif_when_pillow_reads_it(self):
with patch.object(media_formats, "avif_supported", return_value=True):
self.assertEqual(self._walked(), ["gen.avif"])
def test_the_walk_skips_avif_when_pillow_cannot_read_it(self):
with patch.object(media_formats, "avif_supported", return_value=False):
self.assertEqual(self._walked(), [])
def test_the_settled_entry_agrees_with_the_walk(self):
with patch.object(media_formats, "avif_supported", return_value=False):
self.assertIsNone(images_module._settled_entry(self.tmpdir, "gen.avif"))
with patch.object(media_formats, "avif_supported", return_value=True):
path, _mtime = images_module._settled_entry(self.tmpdir, "gen.avif")
self.assertEqual(Path(path).name, "gen.avif")
class TestMonitorAcceptance(unittest.TestCase):
"""The monitor watches an AVIF output only where Pillow can read it."""
def _monitor(self):
monitor = ImageGenerationHandler.__new__(ImageGenerationHandler)
monitor.supported_extensions = (".png", ".avif")
monitor.watched_roots = ()
return monitor
def test_an_avif_output_is_watched_when_pillow_reads_it(self):
monitor = self._monitor()
output = os.path.join(tempfile.gettempdir(), "output", "gen.avif")
with patch.object(media_formats, "avif_supported", return_value=True):
self.assertTrue(monitor.is_image_file(output))
def test_an_avif_output_is_ignored_when_pillow_cannot_read_it(self):
monitor = self._monitor()
output = os.path.join(tempfile.gettempdir(), "output", "gen.avif")
with patch.object(media_formats, "avif_supported", return_value=False):
self.assertFalse(monitor.is_image_file(output))
class TestAutotagListing(unittest.TestCase):
"""The legacy auto-tag listing follows the same rule."""
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.tmpdir, True)
shutil.copyfile(FIXTURE, os.path.join(self.tmpdir, "gen.avif"))
def test_the_listing_names_avif_when_pillow_reads_it(self):
with patch.object(media_formats, "avif_supported", return_value=True):
found, _truncated = AutotagRoutesMixin._collect_scan_files(
Path(self.tmpdir)
)
self.assertEqual([path.name for path in found], ["gen.avif"])
def test_the_listing_skips_avif_when_pillow_cannot_read_it(self):
with patch.object(media_formats, "avif_supported", return_value=False):
found, _truncated = AutotagRoutesMixin._collect_scan_files(
Path(self.tmpdir)
)
self.assertEqual(found, [])
class TestCaptureGate(unittest.TestCase):
"""The capture store refuses an AVIF the listing would not offer."""
def test_avif_is_capturable_only_when_pillow_reads_it(self):
with patch.object(media_formats, "avif_supported", return_value=False):
with self.assertRaises(media_capture.CaptureDenied):
media_capture._relative_parts("gen.avif")
with patch.object(media_formats, "avif_supported", return_value=True):
_parts, extension = media_capture._relative_parts("gen.avif")
self.assertEqual(extension, ".avif")
class TestServedTypes(unittest.TestCase):
"""AVIF is served and inspected as itself, whatever this Pillow reads."""
def test_avif_is_in_the_servable_set(self):
self.assertIn(".avif", SERVABLE_EXTENSIONS)
self.assertEqual(media_capture.CAPTURE_EXTENSIONS, SERVABLE_EXTENSIONS)
def test_the_content_type_is_named(self):
self.assertEqual(CONTENT_TYPES[".avif"], "image/avif")
@unittest.skipUnless(AVIF_READABLE, "Pillow here cannot decode AVIF")
class TestMonitorLinksAnAvif(unittest.TestCase):
"""The monitor reads the AVIF's own EXIF and links its positive prompt."""
def setUp(self):
from database.operations import PromptDatabase
from tests.background_stops import close_handler
from utils.hashing import generate_prompt_hash
from utils.image_monitor import ImageGenerationHandler
from utils.prompt_tracker import PromptTracker
self.tmpdir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.tmpdir, True)
self.db_path = os.path.join(self.tmpdir, "prompts.db")
self.image = os.path.join(self.tmpdir, "gen.avif")
shutil.copyfile(FIXTURE, self.image)
self.db = PromptDatabase(self.db_path)
self.handler = ImageGenerationHandler(self.db, PromptTracker(self.db))
self.linked = []
self.handler.link_image_to_prompt = (
lambda path, prompt, meta: self.linked.append(prompt["id"])
)
self.positive = self.db.save_prompt(
text="a small avif fixture",
prompt_hash=generate_prompt_hash("a small avif fixture"),
)
self.db.save_prompt(text="bad", prompt_hash=generate_prompt_hash("bad"))
self.addCleanup(self._close, close_handler)
def _close(self, close_handler):
close_handler(self, self.handler) # and the tracker's cleanup thread
self.db.close_all() # Windows cannot unlink an open database file
def test_the_output_links_to_its_positive_prompt(self):
self.handler.process_new_image(self.image)
self.assertEqual(self.linked, [self.positive])
@unittest.skipUnless(AVIF_READABLE, "Pillow here cannot decode AVIF")
class TestTheFixture(unittest.TestCase):
"""The checked-in AVIF is ComfyUI's output shape, and both records read."""
def test_exif_text_answers_both_records(self):
from PIL import Image
from utils.exif_text import exif_text
from utils.png_text import png_text
with Image.open(FIXTURE) as image:
self.assertEqual(png_text(image), {})
text = exif_text(image)
self.assertEqual(sorted(text), ["prompt", "workflow"])
self.assertIn("a small avif fixture", text["prompt"])
self.assertIn("KSampler", text["workflow"])
+1 -1
View File
@@ -19,7 +19,7 @@ except ImportError: # discovered with tests/ as the top-level directory
from test_package_contents import _ignored
ROOT = Path(__file__).resolve().parent.parent
PAGES = ("workspace.html", "admin.html", "gallery.html", "metadata.html", "index.html")
PAGES = ("workspace.html", "admin-redirect.html", "index.html")
ICON_LINK = re.compile(
r'<link rel="(icon|apple-touch-icon)"(?: type="image/png")?'
r' sizes="(\d+)x(\d+)" href="(lib/brand/[a-z0-9-]+\.png)">'
+31 -2
View File
@@ -48,6 +48,7 @@ class TestClassify(unittest.TestCase):
def test_documents_a_test_reads_are_docs(self):
for paths in (
["README.md"],
["CHANGELOG.md"],
["README-legacy.md", "assets/readme/hero.webp"],
["assets/brand/banner.webp", ".github/FUNDING.yml"],
):
@@ -287,15 +288,43 @@ class TestCommandLine(unittest.TestCase):
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.
# No range from pre-commit (a manual run) and a code push both run it.
self.assertEqual(self.run_script(*command).returncode, 0)
self.assertTrue(marker.exists())
marker.unlink()
self.commit({"README.md": "r3\n"})
self.commit({"py/x.py": "x = 1\n"})
refs["PRE_COMMIT_TO_REF"] = self.head()
self.assertEqual(self.run_script(*command, **refs).returncode, 0)
self.assertTrue(marker.exists())
def test_a_docs_push_runs_only_the_tests_that_read_the_docs(self):
# #679: the full suite took minutes for a README edit.
ran = unittest.mock.Mock(return_value=unittest.mock.Mock(returncode=5))
with unittest.mock.patch.dict(os.environ, _isolated_environment(), clear=True):
with (
unittest.mock.patch.object(
change_class, "class_of_range", return_value="docs"
),
unittest.mock.patch.object(change_class.subprocess, "run", ran),
):
code = change_class.main(["--unless-inert", "python", "-m", "full"])
ran.assert_called_once_with(
[
sys.executable,
"-m",
"unittest",
"tests.test_brand_assets",
"tests.test_package_contents",
],
check=False,
)
self.assertEqual(code, 5)
def test_the_docs_tests_named_by_the_hook_exist(self):
for module in change_class.DOCS_TESTS:
path = ROOT / (module.replace(".", "/") + ".py")
self.assertTrue(path.is_file(), module)
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))
+46 -1
View File
@@ -47,7 +47,7 @@ class TestGalleryConfig(unittest.TestCase):
self.assertTrue(config["monitoring"]["enabled"])
self.assertEqual(
config["monitoring"]["extensions"],
[".png", ".jpg", ".jpeg", ".webp", ".gif"],
[".png", ".jpg", ".jpeg", ".webp", ".gif", ".avif"],
)
self.assertEqual(config["tracking"]["prompt_timeout"], 600)
self.assertEqual(config["web_interface"]["images_per_page"], 20)
@@ -116,6 +116,51 @@ class TestGalleryConfig(unittest.TestCase):
self.assertEqual(before, after)
class TestMonitorExtensionMigration(unittest.TestCase):
"""#652: a saved extension list gains .avif and keeps its own entries."""
def setUp(self):
self._orig = list(GalleryConfig.SUPPORTED_EXTENSIONS)
def tearDown(self):
GalleryConfig.SUPPORTED_EXTENSIONS = self._orig
def test_a_list_saved_before_avif_gains_it_last(self):
GalleryConfig.update_config({"monitoring": {"extensions": [".png", ".webp"]}})
self.assertEqual(GalleryConfig.SUPPORTED_EXTENSIONS, [".png", ".webp", ".avif"])
def test_a_list_that_already_names_avif_is_left_alone(self):
GalleryConfig.update_config(
{"monitoring": {"extensions": [".png", ".avif", ".webp"]}}
)
self.assertEqual(GalleryConfig.SUPPORTED_EXTENSIONS, [".png", ".avif", ".webp"])
def test_an_empty_list_keeps_collecting_nothing(self):
GalleryConfig.update_config({"monitoring": {"extensions": []}})
self.assertEqual(GalleryConfig.SUPPORTED_EXTENSIONS, [])
def test_a_value_that_is_not_a_list_keeps_the_current_list(self):
GalleryConfig.SUPPORTED_EXTENSIONS = [".png"]
with self.assertLogs("prompt_manager.config", "WARNING") as logs:
GalleryConfig.update_config({"monitoring": {"extensions": ".png"}})
self.assertEqual(GalleryConfig.SUPPORTED_EXTENSIONS, [".png"])
self.assertIn(
"Ignoring gallery monitoring extensions: expected a list",
"\n".join(logs.output),
)
def test_entries_are_normalised_and_non_strings_dropped(self):
with self.assertLogs("prompt_manager.config", "WARNING") as logs:
GalleryConfig.update_config(
{"monitoring": {"extensions": [".PNG", 3, " .webp "]}}
)
self.assertEqual(GalleryConfig.SUPPORTED_EXTENSIONS, [".png", ".webp", ".avif"])
self.assertIn(
"Ignoring gallery monitoring extension: expected a string",
"\n".join(logs.output),
)
class TestPromptManagerConfig(unittest.TestCase):
"""Test PromptManagerConfig class."""
+3 -2
View File
@@ -244,7 +244,7 @@ class ParsesLikeJavaScript(unittest.TestCase):
)
def test_page_parse_reads_nan_numbers_as_null(self):
# gallery.js and admin.js replace NaN with null before JSON.parse.
# The old pages (removed in #668) replaced NaN with null before JSON.parse.
self.assertEqual(
parse_page_json('{"a": NaN, "b": [NaN], "t": "NaN"}'),
{"a": None, "b": [None], "t": "NaN"},
@@ -258,7 +258,8 @@ class ParsesLikeJavaScript(unittest.TestCase):
@unittest.skipUnless(shutil.which("node"), "Node is not installed")
def test_page_parse_equals_the_legacy_pages_for_nan_numbers(self):
# gallery.js/admin.js: two NaN regexes, then JSON.parse (Infinity throws).
# The old pages (removed in #668): two NaN regexes, then JSON.parse
# (Infinity throws).
texts = [
'{"1": {"is_changed": [NaN]}, "2": {"is_changed": NaN, "v": 1.5}}',
'{"a":NaN,"b":[NaN, 2]}',
+85
View File
@@ -46,6 +46,7 @@ from py import lora_import, lora_utils
from py.api.jobs import RESTORE_JOB_KIND
from py.api.lora_import_routes import LORA_PREVIEW_LEASE
from py.config import IntegrationConfig, PromptManagerConfig
from utils import exit_signal
from utils.hashing import generate_prompt_hash
CATEGORY = "lora-manager"
@@ -536,6 +537,32 @@ class LoraImportRouteTests(LoraImportAPITestCase):
resp, body = await self._post(APPLY, {"token": plan["token"]})
self.assertEqual((resp.status, body["code"]), (409, "plan-used"))
async def test_preview_and_job_say_how_many_entries_were_not_made_tags(self):
# #618: the review and the job log count the trained-words entries
# that were lists or sentences.
_write_metadata(self.loras, "neon", words=["glow", "a, b, c", "<lora:x:1>"])
(self.loras / "neon.png").write_bytes(_png_bytes())
resp, plan = await self._post(PREVIEW)
self.assertEqual(resp.status, 200, plan)
self.assertEqual((plan["trigger_tags"], plan["trigger_not_tags"]), (1, 2))
resp, body = await self._post(APPLY, {"token": plan["token"]})
self.assertEqual(resp.status, 202, body)
job = self.api._jobs.get(body["job"]["id"])
await job.task
self.assertEqual(job.state, "finished", job.log)
line = "2 trained-words entries were not made tags (lists or sentences)"
self.assertTrue(any(entry.endswith(line) for entry in job.log), job.log)
neon = self.api.db.search_prompts(category=CATEGORY)[0]
self.assertEqual(sorted(neon["tags"]), ["glow", "lora-manager", "lora:neon"])
async def test_job_log_is_silent_when_every_entry_is_a_tag(self):
self._two_loras()
_plan, job = await self._apply_reviewed()
await job.task
self.assertEqual(job.state, "finished", job.log)
self.assertFalse(any("not made tags" in line for line in job.log), job.log)
async def test_a_finished_import_clears_the_layout_cache(self):
# #362: the import may link files under a folder LoraManager created
# after the image routes cached its layout.
@@ -1140,6 +1167,34 @@ class LoraImportRefusalTests(LoraImportAPITestCase):
self.assertEqual(job.state, "finished", job.log)
self.assertNotEqual(_snapshot(self.api.db), before)
async def test_an_exit_after_the_commit_point_still_finishes(self):
# #619: ComfyUI exits while the replace runs; the replace is one
# transaction and still commits, so the job truthfully ends
# "finished" with the import written, not "cancelled".
self._two_loras()
before = _snapshot(self.api.db)
replacing, release = threading.Event(), threading.Event()
real_replace = self.api.db.replace_category_prompts
def held_replace(*args, **kwargs):
replacing.set()
release.wait(10)
return real_replace(*args, **kwargs)
loop = asyncio.get_running_loop()
with patch.object(self.api.db, "replace_category_prompts", held_replace):
_plan, job = await self._apply_reviewed()
try:
self.assertTrue(await loop.run_in_executor(None, replacing.wait, 10))
self.assertFalse(job.summary()["cancellable"])
self.addCleanup(exit_signal.reset)
exit_signal.request()
finally:
release.set()
await job.task
self.assertEqual(job.state, "finished", job.log)
self.assertNotEqual(_snapshot(self.api.db), before)
def plan_title():
return lora_import.JOB_TITLE
@@ -1417,10 +1472,40 @@ class LoraImportStageTests(unittest.TestCase):
"hash": generate_prompt_hash("neon street"),
"tags": ["lora-manager", "lora:neon", "glow"],
"images": [os.path.realpath(self.loras / "neon.png")],
"trigger_not_tags": 0,
}
],
)
# #618: only one short clean phrase becomes a tag.
def test_build_record_makes_tags_only_from_short_phrases(self):
metadata = {
"file_name": "neon.safetensors",
"model_name": "neon",
"civitai": {"trainedWords": ["neon", "a, b, c", "<lora:x:1>"]},
}
record = lora_import.build_record(metadata, self.loras / "neon.json", [])
self.assertEqual(record["tags"], ["lora-manager", "lora:neon", "neon"])
self.assertEqual(record["trigger_not_tags"], 2)
def test_stage_counts_entries_not_made_tags(self):
_write_metadata(self.loras, "one", words=["glow", "a, b", "<lora:x:1>"])
_write_metadata(self.loras, "two", words=["long, comma, list"])
_write_metadata(self.loras, "three", words=["fine"])
staged = lora_import.stage(self.discover(), self.tmp, media_extensions=MEDIA)
self.assertEqual(staged.stats["trigger_not_tags"], 3)
tags = {r["name"]: r["tags"] for r in staged.records}
self.assertEqual(tags["one"], ["lora-manager", "lora:one", "glow"])
self.assertEqual(tags["two"], ["lora-manager", "lora:two"])
def test_preview_sums_trigger_tags_and_not_tags(self):
_write_metadata(self.loras, "one", words=["glow", "a, b", "(x:1.2)"])
_write_metadata(self.loras, "two", words=["neon", "street"])
_write_metadata(self.loras, "none")
found = lora_import.preview(str(self.lm), self.tmp / "cache", MEDIA)
self.assertEqual((found["trigger_tags"], found["trigger_not_tags"]), (3, 2))
def test_preview_counts_local_media_and_downloads(self):
_write_metadata(self.loras, "local", images=["https://civitai.com/l.png"])
(self.loras / "local.webp").write_bytes(b"x")
+72
View File
@@ -99,6 +99,64 @@ class TestGetTriggerWords(unittest.TestCase):
self.assertEqual(get_trigger_words_from_metadata(meta), ["valid", "also_valid"])
class TestTriggerWordTags(unittest.TestCase):
"""#618: a trained-words entry becomes a tag only when it is one short
clean phrase (Option A); the trigger-word lookup keeps every entry."""
KEPT = [
"neon glow",
" ohwx woman ",
"score_9",
"hatsune miku (vocaloid)",
"hatsune miku \\(vocaloid\\)",
"a" * 50,
]
SKIPPED = [
"a" * 51,
"score_9, score_8_up, realistic,",
"realistic,",
"赛博朋克,霓虹",
"line one\nline two",
"tab\tword",
"<lora:neon:0.8>",
"(masterpiece:1.2)",
"a girl (smile:0.8) outdoors",
"ratio (16:9)",
]
def test_short_clean_phrases_are_tags(self):
for entry in self.KEPT:
with self.subTest(entry=entry):
self.assertTrue(lora_utils.is_tag_phrase(entry))
def test_lists_sentences_and_prompt_syntax_are_not(self):
for entry in self.SKIPPED:
with self.subTest(entry=entry):
self.assertFalse(lora_utils.is_tag_phrase(entry))
def test_non_entries_are_not_phrases(self):
for entry in ("", " ", None, 12):
with self.subTest(entry=entry):
self.assertFalse(lora_utils.is_tag_phrase(entry))
def test_trigger_word_tags_keeps_order_strips_and_counts(self):
meta = _make_metadata(
trained_words=[*self.KEPT, *self.SKIPPED, "", " ", None, 12]
)
tags, not_tags = lora_utils.trigger_word_tags(meta)
self.assertEqual(tags, [entry.strip() for entry in self.KEPT])
self.assertEqual(not_tags, len(self.SKIPPED))
def test_trigger_word_tags_without_trained_words(self):
self.assertEqual(lora_utils.trigger_word_tags({}), ([], 0))
def test_trigger_words_still_hold_every_entry(self):
meta = _make_metadata(trained_words=["neon", "a, b, c", "<lora:x:1>"])
self.assertEqual(
get_trigger_words_from_metadata(meta), ["neon", "a, b, c", "<lora:x:1>"]
)
class TestGetExamplePrompt(unittest.TestCase):
"""Test get_example_prompt_from_metadata — extracts first usable prompt."""
@@ -1296,6 +1354,20 @@ class TestTriggerWordCache(unittest.TestCase):
self.cache.get_trigger_words("my_lora"), ["trigger1", "trigger2"]
)
def test_lists_and_sentences_stay_trigger_words(self):
"""#618: the phrase rule only decides tags; the lookup keeps all."""
with tempfile.TemporaryDirectory() as tmpdir:
words = ["neon", "a, b, c", "<lora:x:1>"]
meta = {
"file_name": "lists.safetensors",
"civitai": {"trainedWords": words},
}
(Path(tmpdir) / "lists.metadata.json").write_text(json.dumps(meta))
(Path(tmpdir) / "lists.safetensors").write_bytes(b"m")
with patch("py.lora_utils.default_lora_roots", return_value=[tmpdir]):
self.cache.load(tmpdir)
self.assertEqual(self.cache.get_trigger_words("lists"), words)
def test_case_insensitive_lookup(self):
with tempfile.TemporaryDirectory() as tmpdir:
meta = {
+28
View File
@@ -252,6 +252,13 @@ class TestPreviews(MaintenanceDatabaseCase):
with self.assertRaises(ValueError):
self.db.preview_maintenance("reboot", [])
def test_tag_cleanup_is_planned_from_a_find_not_previewed(self):
# #618: it needs a find's findings and a selection; without this
# refusal it would fall through to the unused-components plan.
self.assertIn("tag_cleanup", maintenance.MAINTENANCE_OPERATIONS)
with self.assertRaises(ValueError):
self.db.preview_maintenance("tag_cleanup", [])
def test_same_library_gives_the_same_fingerprint(self):
self.populate()
for operation in OPERATIONS:
@@ -437,6 +444,27 @@ class TestApply(MaintenanceDatabaseCase):
draft.operation, draft.fingerprint, draft.targets, roots
)
def test_tag_cleanup_apply_runs_the_per_target_rechecks(self):
from database import tag_cleanup
with self.db.model.get_connection() as conn:
conn.execute("INSERT INTO tags(name) VALUES('a, b'), ('ghost')")
found = tag_cleanup.find_tag_cleanup(self.db_path)
select = {
r: [f["tag_id"] for f in found["rules"][r]] for r in ("comma", "unused")
}
draft = tag_cleanup.plan_tag_cleanup(self.db_path, found, select)
with self.db.model.get_connection() as conn:
conn.execute("UPDATE tags SET name='Ghost' WHERE name='ghost'")
result = self.db.apply_maintenance(
"tag_cleanup", draft.fingerprint, draft.targets, []
)
self.assertEqual([r["name"] for r in result["rows"]], ["a, b"])
self.assertEqual(
[(k["name"], k["reason"]) for k in result["kept"]],
[("ghost", "renamed since the review")],
)
def test_unused_components_apply_removes_exactly_the_reviewed_prompts(self):
first, second = self.save("One"), self.save("Two")
draft = self.preview("unused_components")
+1 -11
View File
@@ -7,7 +7,6 @@ into the download, or a rule that drops something ComfyUI needs at run time.
import ast
import fnmatch
import re
import sys
import unittest
from pathlib import Path
@@ -32,6 +31,7 @@ KEPT = (
"LICENSE",
"README.md",
"README-legacy.md",
"CHANGELOG.md",
"assets/readme/hero.webp",
)
@@ -88,16 +88,6 @@ class TestPackageContents(unittest.TestCase):
for name in names:
self.assertNotIn(name.split(".")[0], ("tests", "tools"), source)
def test_the_old_pages_name_their_replacement(self):
for page, section in (
("admin", "library"),
("gallery", "images"),
("metadata", "inspect"),
):
html = (ROOT / "web" / f"{page}.html").read_text(encoding="utf-8")
self.assertRegex(html, r'id="legacy-removal-notice"')
self.assertRegex(html, re.escape(f'href="workspace#/{section}"'))
if __name__ == "__main__":
sys.exit(unittest.main())
+1 -10
View File
@@ -1,4 +1,4 @@
"""The UI's sort options must match the server's whitelist exactly."""
"""The node's Recent request must name a sort the server whitelists."""
import os
import re
@@ -10,19 +10,10 @@ sys.path.insert(0, ROOT)
from database.operations import SORT_ORDERS
SORT_MODULE = os.path.join(ROOT, "web", "js", "prompt-list-sort.js")
NODE_EXTENSION = os.path.join(ROOT, "web", "comfy", "prompt_manager.js")
class TestSortContract(unittest.TestCase):
def test_ui_sort_options_match_server_whitelist(self):
with open(SORT_MODULE, encoding="utf-8") as fh:
source = fh.read()
ui_values = set(re.findall(r'value:\s*"([a-z_]+)"', source))
self.assertTrue(ui_values, "no sort options found in prompt-list-sort.js")
self.assertEqual(ui_values, set(SORT_ORDERS))
def test_node_recent_button_requests_recently_used(self):
# The node extension can't import the shared module (ComfyUI load order is
# not guaranteed), so it sends the key directly; it must be a server key.
+432
View File
@@ -0,0 +1,432 @@
"""Tag cleanup rules (#618, ``database/tag_cleanup.py``).
Two rules ship: tags containing a comma (removed from every owner and
deleted; a ``lora:`` tag is never one) and tags with no links (deleted). A
tag belongs to the first rule that finds it. A find reads one snapshot; a
plan re-reads each selected finding and protects the ones that changed; the
apply rechecks every target in the caller's transaction and keeps the ones
that changed, with their reason, while the rest still apply.
"""
import hashlib
import json
import os
import sqlite3
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from database import tag_cleanup
from database.operations import PromptDatabase
from utils.hashing import generate_prompt_hash
try:
from tests.open_handles import assert_closed
except ImportError: # discovered with tests/ as the top-level directory
from open_handles import assert_closed
class TagCleanupCase(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.root = Path(os.path.realpath(self.temp.name))
self.db_path = str(self.root / "prompts.db")
self.db = PromptDatabase(self.db_path)
self.epoch = self.db.get_execution_epoch()
def tearDown(self):
self.db.close_all()
assert_closed(self, self.root)
self.temp.cleanup()
def save(self, text, tags):
return self.db.save_prompt(
text, prompt_hash=generate_prompt_hash(text), tags=tags
)
def add_unused(self, *names):
with self.db.model.get_connection() as conn:
for name in names:
conn.execute("INSERT INTO tags(name) VALUES(?)", (name,))
def image(self, name, tags, digest="a"):
locator = os.path.normcase(str(self.root / name))
self.db.replace_image_tags(
locator=locator,
sha256=hashlib.sha256(digest.encode()).hexdigest(),
size=1,
mtime_ns=1,
expected_epoch=self.db.get_execution_epoch(),
expected_tag_revision=0,
tags=tags,
)
return locator
def image_with(self, name, tag):
"""An image set carrying ``tag``, which the image API refuses when it
holds a comma: the link row is written as older builds could."""
self.image(name, ["placeholder"], digest=name)
with self.db.model.get_connection() as conn:
conn.execute("INSERT OR IGNORE INTO tags(name) VALUES(?)", (tag,))
conn.execute(
"INSERT INTO media_image_tags(byte_id, tag_id, position) "
"SELECT b.id, t.id, 1 FROM media_annotation_bytes b, tags t "
"WHERE t.name=? AND b.sha256=?",
(tag, hashlib.sha256(name.encode()).hexdigest()),
)
def tag_id(self, name):
with self.db.model.get_connection() as conn:
row = conn.execute("SELECT id FROM tags WHERE name=?", (name,)).fetchone()
return row[0] if row else None
def names(self):
with self.db.model.get_connection() as conn:
return sorted(r[0] for r in conn.execute("SELECT name FROM tags"))
def find(self):
return tag_cleanup.find_tag_cleanup(self.db_path)
def found(self, rule):
return [f["name"] for f in self.find()["rules"][rule]]
def plan(self, result, select):
return tag_cleanup.plan_tag_cleanup(self.db_path, result, select)
def apply(self, targets):
with self.db._pair_transaction() as conn:
return tag_cleanup.apply_tag_cleanup(conn, targets)
def select_all(self, result, rule):
return {rule: [f["tag_id"] for f in result["rules"][rule]]}
class TestRegistry(TagCleanupCase):
def test_rules_ship_in_order_with_their_copy(self):
self.assertEqual([r.id for r in tag_cleanup.RULES], ["comma", "unused"])
comma, unused = tag_cleanup.RULES
self.assertEqual(comma.title, "Tags containing a comma")
self.assertEqual(unused.title, "Tags with no links")
for rule in tag_cleanup.RULES:
for text in (rule.explanation, rule.action_label):
self.assertTrue(text and "\n" not in text)
self.assertIs(comma.apply, unused.apply)
class TestFinders(TagCleanupCase):
def test_comma_rule_finds_ascii_and_fullwidth_commas(self):
self.save("a", ["score_9, score_8_up", "clean"])
self.save("b", ["赛博朋克,霓虹", "realistic,"])
self.assertEqual(
self.found("comma"), ["realistic,", "score_9, score_8_up", "赛博朋克,霓虹"]
)
def test_comma_rule_skips_lora_identity_tags(self):
# Maintainer ruling Q1: a lora: tag is never a comma finding.
self.save("a", ["lora:Style, v2", "a, b"])
self.add_unused("lora:Old, model")
found = self.find()
self.assertEqual([f["name"] for f in found["rules"]["comma"]], ["a, b"])
# The unused rule still lists an unused lora: tag.
self.assertEqual(
[f["name"] for f in found["rules"]["unused"]], ["lora:Old, model"]
)
def test_unused_rule_counts_prompt_pair_and_image_links(self):
self.save("a", ["on-prompt"])
self.db.save_prompt_pair("pos", "neg", tags=["on-pair"])
self.image("one.png", ["on-image"])
self.add_unused("nowhere", "Also nowhere")
self.assertEqual(self.found("unused"), ["Also nowhere", "nowhere"])
def test_an_autotag_mark_is_not_a_link(self):
self.image("one.png", [], digest="z")
with self.db.model.get_connection() as conn:
byte = conn.execute("SELECT id FROM media_annotation_bytes").fetchone()[0]
conn.execute("INSERT INTO media_image_autotags(byte_id) VALUES(?)", (byte,))
self.add_unused("lonely")
self.assertEqual(self.found("unused"), ["lonely"])
def test_a_comma_tag_without_links_is_listed_once_under_comma(self):
self.add_unused("a, b", "plain")
found = self.find()
self.assertEqual([f["name"] for f in found["rules"]["comma"]], ["a, b"])
self.assertEqual([f["name"] for f in found["rules"]["unused"]], ["plain"])
self.assertEqual(found["totals"], {"comma": 1, "unused": 1})
def test_findings_carry_counts_saved_views_and_a_links_hash(self):
prompt = self.save("a", ["x, y"])
self.save("b", ["x, y"])
self.db.save_prompt_pair("pos", "neg", tags=["x, y"])
self.image_with("one.png", "x, y")
self.add_unused("ghost")
self.db.create_saved_view(
"images",
"Ghosts",
{
"q": "",
"category": "",
"sort": "newest",
"source": "all",
"folder": "",
"media": "all",
"tags": ["ghost"],
"favorites": False,
"collection": "",
},
)
found = self.find()
[comma] = found["rules"]["comma"]
self.assertEqual(
{k: comma[k] for k in ("rule", "name", "prompts", "pairs", "images")},
{"rule": "comma", "name": "x, y", "prompts": 2, "pairs": 1, "images": 1},
)
self.assertEqual(comma["saved_views"], 0)
self.assertEqual(comma["tag_id"], self.tag_id("x, y"))
self.assertRegex(comma["links"], r"^[0-9a-f]{64}$")
self.assertEqual(
tag_cleanup.finding_detail(comma), "2 prompts · 1 pair · 1 image"
)
[ghost] = found["rules"]["unused"]
self.assertEqual(ghost["saved_views"], 1)
self.assertEqual(ghost["links"], tag_cleanup.NO_LINKS)
self.assertEqual(
tag_cleanup.finding_detail(ghost), "no links · in 1 saved view"
)
self.assertIsNotNone(prompt)
def test_cap_holds_the_first_findings_by_name_and_totals_stay_exact(self):
self.add_unused("b", "A", "c", "d")
with patch.object(tag_cleanup, "MAX_FINDINGS", 2):
found = self.find()
self.assertEqual([f["name"] for f in found["rules"]["unused"]], ["A", "b"])
self.assertEqual(found["totals"]["unused"], 4)
def test_find_writes_nothing_and_closes_its_connection(self):
self.add_unused("a, b")
before = self.names()
with patch.object(sqlite3, "connect", wraps=sqlite3.connect) as connect:
self.find()
self.assertEqual(connect.call_count, 1)
self.assertEqual(self.names(), before)
class TestPlan(TagCleanupCase):
def test_plan_lists_targets_scope_and_details(self):
self.save("a", ["x, y"])
self.save("b", ["x, y", "q, r"])
self.add_unused("ghost")
found = self.find()
draft = self.plan(found, self.select_all(found, "comma"))
self.assertEqual(draft.operation, "tag_cleanup")
self.assertEqual(
[(t["rule"], t["name"]) for t in draft.targets],
[("comma", "q, r"), ("comma", "x, y")],
)
self.assertEqual(
draft.scope,
{
"count": 2,
"label": "Delete 2 tags (removed from 3 prompts, 0 pairs and 0 images)",
},
)
self.assertEqual(draft.protected, {"count": 0, "reasons": []})
self.assertEqual(
draft.media, {"deletes_files": False, "label": "No files are removed"}
)
self.assertEqual(
draft.details[0],
{"label": "q, r", "detail": "Tags containing a comma · 1 prompt"},
)
self.assertTrue(draft.fingerprint.startswith("sha256:"))
def test_one_tag_reads_in_the_singular(self):
self.add_unused("ghost")
found = self.find()
draft = self.plan(found, self.select_all(found, "unused"))
self.assertEqual(
draft.scope["label"],
"Delete 1 tag (removed from 0 prompts, 0 pairs and 0 images)",
)
def test_a_finding_changed_since_the_search_is_protected(self):
first = self.save("a", ["x, y"])
second = self.save("b", ["q, r"])
found = self.find()
# Moved to another prompt: the count stays 1, the links differ.
with self.db.model.get_connection() as conn:
conn.execute(
"UPDATE prompt_tags SET prompt_id=? WHERE prompt_id=? AND tag_id=?",
(second, first, self.tag_id("x, y")),
)
draft = self.plan(found, self.select_all(found, "comma"))
self.assertEqual([t["name"] for t in draft.targets], ["q, r"])
self.assertEqual(
draft.protected,
{"count": 1, "reasons": ["1 tag changed since the search"]},
)
self.assertEqual(
[(h["name"], h["reason"]) for h in tag_cleanup.held_rows(draft)],
[("x, y", "changed since the search")],
)
def test_a_renamed_or_deleted_finding_is_protected(self):
self.add_unused("ghost", "spirit")
found = self.find()
with self.db.model.get_connection() as conn:
conn.execute("UPDATE tags SET name='GHOST' WHERE name='ghost'")
conn.execute("DELETE FROM tags WHERE name='spirit'")
draft = self.plan(found, self.select_all(found, "unused"))
self.assertEqual(draft.targets, [])
self.assertEqual(
draft.protected["reasons"], ["2 tags changed since the search"]
)
class TestApply(TagCleanupCase):
def planned(self, rule):
found = self.find()
return self.plan(found, self.select_all(found, rule)).targets
def test_apply_deletes_the_tag_and_its_three_kinds_of_links(self):
prompt = self.save("a", ["x, y", "keep"])
pair = self.db.save_prompt_pair("pos", "neg", tags=["x, y"])
self.image_with("one.png", "x, y")
with self.db.model.get_connection() as conn:
byte = conn.execute("SELECT id FROM media_annotation_bytes").fetchone()[0]
conn.execute("INSERT INTO media_image_autotags(byte_id) VALUES(?)", (byte,))
revision = conn.execute(
"SELECT image_index_revision FROM media_annotation_metadata"
).fetchone()[0]
targets = self.planned("comma")
result = self.apply(targets)
self.assertEqual(result["changed"], 1)
self.assertEqual([r["name"] for r in result["rows"]], ["x, y"])
self.assertEqual(result["kept"], [])
self.assertIsNone(self.tag_id("x, y"))
with self.db.model.get_connection() as conn:
for table in ("prompt_tags", "prompt_pair_tags", "media_image_tags"):
names = conn.execute(
f"SELECT t.name FROM {table} x JOIN tags t ON t.id=x.tag_id"
).fetchall()
self.assertNotIn(("x, y",), [tuple(n) for n in names], table)
self.assertEqual(
conn.execute(
"SELECT tag_revision FROM media_annotation_bytes"
).fetchone()[0],
2,
)
self.assertEqual(
conn.execute(
"SELECT image_index_revision FROM media_annotation_metadata"
).fetchone()[0],
revision + 1,
)
self.assertEqual(
conn.execute("SELECT COUNT(*) FROM media_image_autotags").fetchone()[0],
1,
)
self.assertIsNotNone(self.db.get_prompt_by_id(prompt))
self.assertIsNotNone(self.db.get_prompt_pair(pair))
self.assertIn("keep", self.names())
def test_saved_views_are_never_rewritten(self):
self.add_unused("ghost")
state = {
"q": "",
"category": "",
"sort": "newest",
"tags": ["ghost"],
"tag_mode": "all",
"folder": "",
}
self.db.create_saved_view("library", "Ghosts", state)
self.apply(self.planned("unused"))
[view] = self.db.list_saved_views()
self.assertEqual(view["state"]["tags"], ["ghost"])
def test_each_recheck_keeps_the_target_with_its_reason(self):
self.add_unused("gone", "renamed", "used")
first = self.save("first", ["moved, tag"])
second = self.save("second", ["anchor"])
self.save("third", ["relinked, tag"])
unused = self.planned("unused")
comma = self.planned("comma")
with self.db.model.get_connection() as conn:
conn.execute("DELETE FROM tags WHERE name='gone'")
conn.execute("UPDATE tags SET name='Renamed' WHERE name='renamed'")
conn.execute(
"INSERT INTO prompt_tags(prompt_id, tag_id) VALUES(?, ?)",
(first, self.tag_id("used")),
)
# Same count, other prompt: its links changed.
conn.execute(
"UPDATE prompt_tags SET prompt_id=? WHERE prompt_id=? AND tag_id=?",
(second, first, self.tag_id("moved, tag")),
)
result = self.apply(unused + comma)
kept = {k["name"]: k["reason"] for k in result["kept"]}
self.assertEqual(
kept,
{
"gone": "already deleted",
"renamed": "renamed since the review",
"used": "it is used now",
"moved, tag": "its links changed since the review",
},
)
# The rest of the plan still applied.
self.assertEqual([r["name"] for r in result["rows"]], ["relinked, tag"])
self.assertEqual(result["changed"], 1)
self.assertIsNone(self.tag_id("relinked, tag"))
def test_the_last_tag_is_kept_while_legacy_json_tags_remain(self):
self.add_unused("only")
with self.db.model.get_connection() as conn:
conn.execute(
"INSERT INTO prompts(text, tags) VALUES('legacy', ?)",
(json.dumps(["old"]),),
)
result = self.apply(self.planned("unused"))
self.assertEqual(
[(k["name"], k["reason"]) for k in result["kept"]],
[("only", "kept so the old tag migration does not run again")],
)
self.assertEqual(self.names(), ["only"])
def test_the_last_tag_goes_when_no_legacy_tags_remain(self):
self.add_unused("only")
result = self.apply(self.planned("unused"))
self.assertEqual(result["changed"], 1)
self.assertEqual(self.names(), [])
def test_an_exception_rolls_everything_back(self):
self.add_unused("a", "b")
targets = self.planned("unused")
calls = []
real = tag_cleanup._delete_target
def fail_second(conn, target):
calls.append(target["name"])
if len(calls) == 2:
raise sqlite3.OperationalError("disk I/O error")
real(conn, target)
with patch.object(tag_cleanup, "_delete_target", fail_second):
with self.assertRaises(sqlite3.OperationalError):
self.apply(targets)
self.assertEqual(self.names(), ["a", "b"])
def test_names_with_quotes_and_percent_signs(self):
name = 'it\'s 100% "real", ok'
self.save("a", [name])
self.add_unused("50%_off")
self.assertEqual(self.found("comma"), [name])
self.assertEqual(self.found("unused"), ["50%_off"])
self.apply(self.planned("comma") + self.planned("unused"))
self.assertEqual(self.names(), [])
if __name__ == "__main__":
unittest.main()
+12
View File
@@ -871,6 +871,18 @@ class TestVocabularyTagCommands(unittest.TestCase):
],
3,
)
with self.db.model.get_connection() as conn:
# The sets that carried it moved revision (a Tag dialog opened
# before sees tag-conflict); so did the image index once.
self.assertEqual(
sorted(
r[0]
for r in conn.execute(
"SELECT tag_revision FROM media_annotation_bytes"
)
),
[2, 2, 2],
)
renamed = self.command(
"rename_vocabulary_tag",
self.tag_id("keep"),

Some files were not shown because too many files have changed in this diff Show More